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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9245f44f4a7bd9c9457a288da4e936406321ec62
| 945 |
java
|
Java
|
app/src/main/java/br/inatel/hackathon/vigintillionlocalizer/model/Beacon.java
|
vitordepaula/VigintillionLocalizer
|
775bcdfdbf8fac864e212ab1d33b5cbbbac7d011
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/br/inatel/hackathon/vigintillionlocalizer/model/Beacon.java
|
vitordepaula/VigintillionLocalizer
|
775bcdfdbf8fac864e212ab1d33b5cbbbac7d011
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/br/inatel/hackathon/vigintillionlocalizer/model/Beacon.java
|
vitordepaula/VigintillionLocalizer
|
775bcdfdbf8fac864e212ab1d33b5cbbbac7d011
|
[
"Apache-2.0"
] | null | null | null | 19.6875 | 56 | 0.609524 | 1,003,581 |
package br.inatel.hackathon.vigintillionlocalizer.model;
import com.google.android.gms.maps.model.LatLng;
/**
* Created by lucas on 27/08/2016.
*/
public class Beacon {
private String id; // MAC address
private int rssi;
private long timestamp; // unix time (epoch)
private LatLng location;
public String getId() {
return id;
}
public Beacon setId(String id) {
this.id = id;
return this;
}
public int getRssi() { return rssi; }
public Beacon setRssi(int rssi) {
this.rssi = rssi;
return this;
}
public long getTimestamp() {
return timestamp;
}
public Beacon setTimestamp(long timestamp) {
this.timestamp = timestamp;
return this;
}
public LatLng getLocation() {
return location;
}
public Beacon setLocation(LatLng location) {
this.location = location;
return this;
}
}
|
9245f581ccd10607b8d5c6cdfecaabdd3b819fdf
| 1,309 |
java
|
Java
|
src/main/java/com/optimaize/langdetect/ngram/StandardNgramFilter.java
|
mafagafogigante/language-detector
|
57cdf47d4c1d7145658773aa3afce0534f4e39f0
|
[
"Apache-2.0"
] | 1 |
2019-04-25T13:43:17.000Z
|
2019-04-25T13:43:17.000Z
|
src/main/java/com/optimaize/langdetect/ngram/StandardNgramFilter.java
|
mafagafogigante/language-detector
|
57cdf47d4c1d7145658773aa3afce0534f4e39f0
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/optimaize/langdetect/ngram/StandardNgramFilter.java
|
mafagafogigante/language-detector
|
57cdf47d4c1d7145658773aa3afce0534f4e39f0
|
[
"Apache-2.0"
] | 2 |
2019-02-23T10:49:26.000Z
|
2020-03-24T16:17:29.000Z
| 27.270833 | 102 | 0.495798 | 1,003,582 |
package com.optimaize.langdetect.ngram;
/**
* Filters what is generally not desired.
*
* @author Fabian Kessler
*/
public class StandardNgramFilter implements NgramFilter {
private static final StandardNgramFilter INSTANCE = new StandardNgramFilter();
public static NgramFilter getInstance() {
return INSTANCE;
}
private StandardNgramFilter() {
}
@Override
public boolean use(String ngram) {
switch (ngram.length()) {
case 1:
if (ngram.charAt(0)==' ') {
return false;
}
return true;
case 2:
return true;
case 3:
if (ngram.charAt(1)==' ') {
//middle char is a space
return false;
}
return true;
case 4:
if (ngram.charAt(1)==' ' || ngram.charAt(2)==' ') {
//one of the middle chars is a space
return false;
}
return true;
default:
//would need the same check: no space in the middle, border is fine.
throw new UnsupportedOperationException("Unsupported n-gram length: "+ngram.length());
}
}
}
|
9245f592ae2202cbebb2d9af8d384d5f892c5bf9
| 2,233 |
java
|
Java
|
GATEWAY_API/src/main/java/com/viettel/bccsgw/utils/ProcessorMX.java
|
olivier741/services
|
c73d139240f8490d58c4847cb4bf37a83b6c91f7
|
[
"Apache-2.0"
] | null | null | null |
GATEWAY_API/src/main/java/com/viettel/bccsgw/utils/ProcessorMX.java
|
olivier741/services
|
c73d139240f8490d58c4847cb4bf37a83b6c91f7
|
[
"Apache-2.0"
] | 42 |
2020-04-23T20:32:08.000Z
|
2021-12-14T21:39:01.000Z
|
GATEWAY_API/src/main/java/com/viettel/bccsgw/utils/ProcessorMX.java
|
olivier741/services
|
c73d139240f8490d58c4847cb4bf37a83b6c91f7
|
[
"Apache-2.0"
] | 1 |
2020-08-26T03:03:07.000Z
|
2020-08-26T03:03:07.000Z
| 21.679612 | 162 | 0.680699 | 1,003,583 |
package com.viettel.bccsgw.utils;
import java.util.Vector;
import javax.management.MBeanException;
import javax.management.MBeanOperationInfo;
import javax.management.MBeanParameterInfo;
import javax.management.ReflectionException;
import javax.management.RuntimeOperationsException;
import org.apache.log4j.Logger;
public abstract class ProcessorMX
extends AgentMX
{
protected Logger logger;
protected String name;
public abstract void start();
public abstract void stop();
public abstract void restart();
public ProcessorMX()
{
this("Noname");
}
public ProcessorMX(String name)
{
this.name = name;
this.logger = Logger.getLogger(name);
this.dClassName = getClass().getName();
buildDynamicMBeanInfo();
}
public Object invoke(String operationName, Object[] params, String[] signature)
throws MBeanException, ReflectionException
{
if (operationName == null) {
throw new RuntimeOperationsException(new IllegalArgumentException("Operation name cannot be null"), "Cannot invoke a null operation in " + this.dClassName);
}
if (operationName.equals("start"))
{
start();
return null;
}
if (operationName.equals("stop"))
{
stop();
return null;
}
if (operationName.equals("restart"))
{
restart();
return null;
}
return super.invoke(operationName, params, signature);
}
protected MBeanOperationInfo[] buildOperations()
{
Vector<MBeanOperationInfo> v = new Vector();
MBeanParameterInfo[] params = new MBeanParameterInfo[0];
v.add(new MBeanOperationInfo("start", "start processor", params, "void", 1));
v.add(new MBeanOperationInfo("stop", "stop processor", params, "void", 1));
v.add(new MBeanOperationInfo("restart", "stop processor", params, "void", 1));
v.add(new MBeanOperationInfo("getInfor", "get configuration information and runtime state of this processor", params, "java.lang.String", 1));
return (MBeanOperationInfo[])v.toArray(new MBeanOperationInfo[v.size()]);
}
public String getName()
{
return this.name;
}
public void setName(String name)
{
this.name = name;
}
}
|
9245f85f41523ccc14670aca425c66de44c4189d
| 737 |
java
|
Java
|
backend/src/main/java/ma/hiddenfounders/codingchallenge/common/util/InstantAttributeConverter.java
|
mouadelmerchi/facebook-photos-exporting
|
a20be715379ccf33d9d1957af65bb0d64e398604
|
[
"MIT"
] | null | null | null |
backend/src/main/java/ma/hiddenfounders/codingchallenge/common/util/InstantAttributeConverter.java
|
mouadelmerchi/facebook-photos-exporting
|
a20be715379ccf33d9d1957af65bb0d64e398604
|
[
"MIT"
] | 7 |
2020-07-15T23:28:16.000Z
|
2022-03-02T02:09:14.000Z
|
backend/src/main/java/ma/hiddenfounders/codingchallenge/common/util/InstantAttributeConverter.java
|
mouadelmerchi/facebook-photos-exporting
|
a20be715379ccf33d9d1957af65bb0d64e398604
|
[
"MIT"
] | null | null | null | 33.5 | 108 | 0.789688 | 1,003,584 |
package ma.hiddenfounders.codingchallenge.common.util;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
@Converter
public class InstantAttributeConverter implements AttributeConverter<Instant, Timestamp> {
@Override
public Timestamp convertToDatabaseColumn(Instant instant) {
return (instant == null ? null : Timestamp.valueOf(LocalDateTime.ofInstant(instant, ZoneOffset.UTC)));
}
@Override
public Instant convertToEntityAttribute(Timestamp sqlTimestamp) {
return (sqlTimestamp == null ? null : sqlTimestamp.toLocalDateTime().toInstant(ZoneOffset.UTC));
}
}
|
9245f88dae236e94d3d46f002069db5d765c4745
| 4,872 |
java
|
Java
|
src/android/bookinventory/app/src/main/java/com/jxd/android/bookinventtory/widgets/ProgressWidget.java
|
jxdong1013/bookinventory
|
2866540a73c810e02c6e38eb192a28c65a278cb8
|
[
"Apache-2.0"
] | null | null | null |
src/android/bookinventory/app/src/main/java/com/jxd/android/bookinventtory/widgets/ProgressWidget.java
|
jxdong1013/bookinventory
|
2866540a73c810e02c6e38eb192a28c65a278cb8
|
[
"Apache-2.0"
] | null | null | null |
src/android/bookinventory/app/src/main/java/com/jxd/android/bookinventtory/widgets/ProgressWidget.java
|
jxdong1013/bookinventory
|
2866540a73c810e02c6e38eb192a28c65a278cb8
|
[
"Apache-2.0"
] | null | null | null | 28.828402 | 94 | 0.650657 | 1,003,585 |
package com.jxd.android.bookinventtory.widgets;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.jxd.android.bookinventtory.R;
/**
* 进度组件
*/
public class ProgressWidget extends LinearLayout {
TextView tvMessage;
public ProgressWidget(Context context) {
super(context);
init(null, 0);
}
public ProgressWidget(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs, 0);
}
public ProgressWidget(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs, defStyle);
}
private void init(AttributeSet attrs, int defStyle) {
LayoutInflater layoutInflater = LayoutInflater.from(this.getContext() );
layoutInflater.inflate(R.layout.layout_progress , this , true);
tvMessage = findViewById(R.id.progressText);
}
public void setProgressMessage(String message){
tvMessage.setText(message);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// TODO: consider storing these as member variables to reduce
// allocations per draw cycle.
int paddingLeft = getPaddingLeft();
int paddingTop = getPaddingTop();
int paddingRight = getPaddingRight();
int paddingBottom = getPaddingBottom();
int contentWidth = getWidth() - paddingLeft - paddingRight;
int contentHeight = getHeight() - paddingTop - paddingBottom;
// Draw the text.
// canvas.drawText(mExampleString,
// paddingLeft + (contentWidth - mTextWidth) / 2,
// paddingTop + (contentHeight + mTextHeight) / 2,
// mTextPaint);
// Draw the example drawable on top of the text.
// if (mExampleDrawable != null) {
// mExampleDrawable.setBounds(paddingLeft, paddingTop,
// paddingLeft + contentWidth, paddingTop + contentHeight);
// mExampleDrawable.draw(canvas);
// }
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
//return true;
return super.onInterceptTouchEvent(ev);
}
/**
* Gets the example string attribute value.
*
* @return The example string attribute value.
*/
// public String getExampleString() {
// return mExampleString;
// }
/**
* Sets the view's example string attribute value. In the example view, this string
* is the text to draw.
*
* @param exampleString The example string attribute value to use.
*/
// public void setExampleString(String exampleString) {
// mExampleString = exampleString;
// invalidateTextPaintAndMeasurements();
// }
/**
* Gets the example color attribute value.
*
* @return The example color attribute value.
*/
// public int getExampleColor() {
// return mExampleColor;
// }
/**
* Sets the view's example color attribute value. In the example view, this color
* is the font color.
*
* @param exampleColor The example color attribute value to use.
*/
// public void setExampleColor(int exampleColor) {
// mExampleColor = exampleColor;
// invalidateTextPaintAndMeasurements();
// }
/**
* Gets the example dimension attribute value.
*
* @return The example dimension attribute value.
*/
// public float getExampleDimension() {
// return mExampleDimension;
// }
/**
* Sets the view's example dimension attribute value. In the example view, this dimension
* is the font size.
*
* @param exampleDimension The example dimension attribute value to use.
*/
// public void setExampleDimension(float exampleDimension) {
// mExampleDimension = exampleDimension;
// invalidateTextPaintAndMeasurements();
// }
/**
* Gets the example drawable attribute value.
*
* @return The example drawable attribute value.
*/
// public Drawable getExampleDrawable() {
// return mExampleDrawable;
// }
/**
* Sets the view's example drawable attribute value. In the example view, this drawable is
* drawn above the text.
*
* @param exampleDrawable The example drawable attribute value to use.
*/
// public void setExampleDrawable(Drawable exampleDrawable) {
// mExampleDrawable = exampleDrawable;
// }
}
|
9245f8940cbaa67ec25510140879f578e4c8f3dc
| 615 |
java
|
Java
|
src/test/java/org/globsframework/metamodel/DummyObjectWithRequiredFields.java
|
mathieu-chauvet/globs
|
b33def49e28d73a099083c0bd21d74ce9bddf5ce
|
[
"Apache-2.0"
] | null | null | null |
src/test/java/org/globsframework/metamodel/DummyObjectWithRequiredFields.java
|
mathieu-chauvet/globs
|
b33def49e28d73a099083c0bd21d74ce9bddf5ce
|
[
"Apache-2.0"
] | null | null | null |
src/test/java/org/globsframework/metamodel/DummyObjectWithRequiredFields.java
|
mathieu-chauvet/globs
|
b33def49e28d73a099083c0bd21d74ce9bddf5ce
|
[
"Apache-2.0"
] | null | null | null | 24.6 | 61 | 0.817886 | 1,003,586 |
package org.globsframework.metamodel;
import org.globsframework.metamodel.annotations.Key;
import org.globsframework.metamodel.annotations.Required;
import org.globsframework.metamodel.fields.IntegerField;
import org.globsframework.metamodel.fields.StringField;
import org.globsframework.metamodel.utils.GlobTypeLoader;
public class DummyObjectWithRequiredFields {
public static GlobType TYPE;
@Key
public static IntegerField ID;
@Required
public static IntegerField VALUE;
@Required
public static StringField NAME;
static {
GlobTypeLoader.init(DummyObjectWithRequiredFields.class);
}
}
|
9245f89fc0dd98031201283a5743557e49fc1770
| 899 |
java
|
Java
|
src/api/com/skycloud/api/domain/base/ActionOperationMessage.java
|
xiwc/jkb
|
834f19247b88a867eede277e3267089d72040e65
|
[
"Apache-2.0"
] | null | null | null |
src/api/com/skycloud/api/domain/base/ActionOperationMessage.java
|
xiwc/jkb
|
834f19247b88a867eede277e3267089d72040e65
|
[
"Apache-2.0"
] | null | null | null |
src/api/com/skycloud/api/domain/base/ActionOperationMessage.java
|
xiwc/jkb
|
834f19247b88a867eede277e3267089d72040e65
|
[
"Apache-2.0"
] | null | null | null | 23.051282 | 50 | 0.757508 | 1,003,587 |
package com.skycloud.api.domain.base;
public class ActionOperationMessage{
private String operationid;
private Integer default_msg;
private String mediatypeid;
private String message;
private String subject;
public void setOperationid(String operationid) {
this.operationid = operationid;
}
public String getOperationid() {
return operationid;
}
public void setDefault_msg(Integer default_msg) {
this.default_msg = default_msg;
}
public Integer getDefault_msg() {
return default_msg;
}
public void setMediatypeid(String mediatypeid) {
this.mediatypeid = mediatypeid;
}
public String getMediatypeid() {
return mediatypeid;
}
public void setMessage(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getSubject() {
return subject;
}
}
|
9245f900917cac506f6ad9ae3e76c41fadb776f3
| 437 |
java
|
Java
|
app/src/main/java/com/example/administrator/zhailuprojecttest001/retrofit2/Data2GetCode.java
|
18668197127/ZhailuProjectTest001
|
ab9bd1400a1dd802c4a6451d2351d9c89c57ffec
|
[
"MIT"
] | null | null | null |
app/src/main/java/com/example/administrator/zhailuprojecttest001/retrofit2/Data2GetCode.java
|
18668197127/ZhailuProjectTest001
|
ab9bd1400a1dd802c4a6451d2351d9c89c57ffec
|
[
"MIT"
] | null | null | null |
app/src/main/java/com/example/administrator/zhailuprojecttest001/retrofit2/Data2GetCode.java
|
18668197127/ZhailuProjectTest001
|
ab9bd1400a1dd802c4a6451d2351d9c89c57ffec
|
[
"MIT"
] | null | null | null | 21.85 | 74 | 0.755149 | 1,003,588 |
package com.example.administrator.zhailuprojecttest001.retrofit2;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;
//retrofit2的一个接口
public interface Data2GetCode {
//test1
@FormUrlEncoded
@POST("getcode")
Call<ResponseBody> postData(@Field("telephone") String telephone);
}
|
9245f97f7cb166f4097fa7ca66aa862e12620d94
| 1,325 |
java
|
Java
|
src/main/java/com/letv/core/bean/channel/ChannelHomeBean.java
|
tiwer/letv
|
1eeb7079be8bad4ffb61fdb06ff8d49760f9e120
|
[
"Apache-2.0"
] | 39 |
2017-08-07T09:03:54.000Z
|
2021-09-29T09:31:39.000Z
|
src/main/java/com/letv/core/bean/channel/ChannelHomeBean.java
|
JackChan1999/letv
|
1eeb7079be8bad4ffb61fdb06ff8d49760f9e120
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/letv/core/bean/channel/ChannelHomeBean.java
|
JackChan1999/letv
|
1eeb7079be8bad4ffb61fdb06ff8d49760f9e120
|
[
"Apache-2.0"
] | 39 |
2017-05-08T13:11:39.000Z
|
2021-12-26T12:42:14.000Z
| 33.974359 | 62 | 0.720755 | 1,003,589 |
package com.letv.core.bean.channel;
import com.alibaba.fastjson.annotation.JSONField;
import com.letv.core.bean.HomeBlock;
import com.letv.core.bean.HomeMetaData;
import com.letv.core.bean.LetvBaseBean;
import com.letv.core.bean.LiveRemenListBean.LiveRemenBaseBean;
import com.letv.core.utils.BaseTypeUtils;
import java.util.ArrayList;
import java.util.List;
public class ChannelHomeBean implements LetvBaseBean {
public static boolean sHasLetvShop = false;
private static final long serialVersionUID = 1;
public ArrayList<HomeBlock> block;
@JSONField(name = "bootings")
public List<Booting> bootings = new ArrayList();
public ArrayList<HomeMetaData> focus;
public boolean isShowLiveBlock;
public boolean isShowTextMark;
public ChannelWorldCupInfoList mChannelWorldCupInfoList;
public List<LiveRemenBaseBean> mLiveSportsList;
public ArrayList<ChannelNavigation> navigation;
public ArrayList<String> searchWords;
public int tabIndex = -1;
public void clear() {
if (!BaseTypeUtils.isListEmpty(this.block)) {
this.block.clear();
}
if (!BaseTypeUtils.isListEmpty(this.focus)) {
this.focus.clear();
}
if (!BaseTypeUtils.isListEmpty(this.navigation)) {
this.navigation.clear();
}
}
}
|
9245f9a09fa37c0b5c276822f6b870232b0f7a18
| 3,606 |
java
|
Java
|
azure-toolkit-libs/azure-toolkit-appservice-lib/src/main/java/com/microsoft/azure/toolkit/lib/appservice/AzureFunction.java
|
AkashNeil/azure-maven-plugins
|
0e00984a82d1c5474f2111dbee76e7bee234dca9
|
[
"MIT"
] | 95 |
2019-05-22T03:33:20.000Z
|
2022-03-10T08:27:04.000Z
|
azure-toolkit-libs/azure-toolkit-appservice-lib/src/main/java/com/microsoft/azure/toolkit/lib/appservice/AzureFunction.java
|
AkashNeil/azure-maven-plugins
|
0e00984a82d1c5474f2111dbee76e7bee234dca9
|
[
"MIT"
] | 621 |
2019-05-07T19:12:37.000Z
|
2022-03-30T07:14:08.000Z
|
azure-toolkit-libs/azure-toolkit-appservice-lib/src/main/java/com/microsoft/azure/toolkit/lib/appservice/AzureFunction.java
|
AkashNeil/azure-maven-plugins
|
0e00984a82d1c5474f2111dbee76e7bee234dca9
|
[
"MIT"
] | 91 |
2019-05-23T06:05:55.000Z
|
2022-03-28T05:16:47.000Z
| 46.831169 | 156 | 0.733777 | 1,003,590 |
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*/
package com.microsoft.azure.toolkit.lib.appservice;
import com.azure.resourcemanager.appservice.AppServiceManager;
import com.microsoft.azure.toolkit.lib.AbstractAzureResourceModule;
import com.microsoft.azure.toolkit.lib.appservice.service.IFunctionApp;
import com.microsoft.azure.toolkit.lib.appservice.service.impl.FunctionApp;
import com.microsoft.azure.toolkit.lib.common.cache.CacheEvict;
import com.microsoft.azure.toolkit.lib.common.cache.CacheManager;
import com.microsoft.azure.toolkit.lib.common.cache.Cacheable;
import com.microsoft.azure.toolkit.lib.common.event.AzureOperationEvent;
import com.microsoft.azure.toolkit.lib.common.model.Subscription;
import com.microsoft.azure.toolkit.lib.common.operation.AzureOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nonnull;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
@Slf4j
public class AzureFunction extends AbstractAzureResourceModule<IFunctionApp> implements AzureOperationEvent.Source<AzureFunction> {
public AzureFunction() { // for SPI
super(AzureFunction::new);
}
private AzureFunction(@Nonnull final List<Subscription> subscriptions) {
super(AzureFunction::new, subscriptions);
}
@Override
@Cacheable(cacheName = "appservice/{}/functionapps", key = "$sid", condition = "!(force&&force[0])")
@AzureOperation(name = "functionapp.list.subscription", params = "sid", type = AzureOperation.Type.SERVICE)
public List<IFunctionApp> list(@NotNull String sid, boolean... force) {
final AppServiceManager azureResourceManager = getAppServiceManager(sid);
return azureResourceManager
.functionApps().list().stream().parallel()
.filter(functionAppBasic -> StringUtils.containsIgnoreCase(functionAppBasic.innerModel().kind(), "functionapp")) // Filter out function apps
.map(functionAppBasic -> new FunctionApp(functionAppBasic, azureResourceManager))
.collect(Collectors.toList());
}
@NotNull
@Override
@Cacheable(cacheName = "appservice/{}/rg/{}/functionapp/{}", key = "$sid/$rg/$name")
@AzureOperation(name = "functionapp.get.name|rg|sid", params = {"name", "rg"}, type = AzureOperation.Type.SERVICE)
public IFunctionApp get(@NotNull String sid, @NotNull String rg, @NotNull String name) {
return new FunctionApp(sid, rg, name, getAppServiceManager(sid));
}
// todo: share codes within app service module
@Cacheable(cacheName = "appservice/{}/manager", key = "$subscriptionId")
@AzureOperation(name = "appservice.get_client.subscription", params = "subscriptionId", type = AzureOperation.Type.SERVICE)
AppServiceManager getAppServiceManager(String subscriptionId) {
return getResourceManager(subscriptionId, AppServiceManager::configure, AppServiceManager.Configurable::authenticate);
}
@AzureOperation(name = "common|service.refresh", params = "this.name()", type = AzureOperation.Type.SERVICE)
public void refresh() {
try {
CacheManager.evictCache("appservice/{}/functionapps", CacheEvict.ALL);
} catch (ExecutionException e) {
log.warn("failed to evict cache", e);
}
}
@Override
public String name() {
return "Azure Function";
}
}
|
9245f9adcf7d7b3f1ad2f29e38c2df8a371480b0
| 2,245 |
java
|
Java
|
pcgen/code/src/java/pcgen/core/SubClass.java
|
odraccir/pcgen-deprecated
|
ab07cb4250e5d0419fd805197fb040a2ea425cc8
|
[
"OML"
] | 1 |
2020-01-12T22:28:29.000Z
|
2020-01-12T22:28:29.000Z
|
pcgen/code/src/java/pcgen/core/SubClass.java
|
odraccir/pcgen-deprecated
|
ab07cb4250e5d0419fd805197fb040a2ea425cc8
|
[
"OML"
] | null | null | null |
pcgen/code/src/java/pcgen/core/SubClass.java
|
odraccir/pcgen-deprecated
|
ab07cb4250e5d0419fd805197fb040a2ea425cc8
|
[
"OML"
] | null | null | null | 25.166667 | 86 | 0.718764 | 1,003,591 |
/*
* SubClass.java
* Copyright 2002 (C) Bryan McRoberts <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Created on November 19, 2002, 10:29 PM
*
* $Id$
*/
package pcgen.core;
import pcgen.cdom.base.CategorizedCDOMObject;
import pcgen.cdom.base.Category;
import pcgen.cdom.enumeration.IntegerKey;
import pcgen.cdom.enumeration.ObjectKey;
/**
* <code>SubClass</code>.
*
* @author Bryan McRoberts <[email protected]>
* @version $Revision$
*/
public final class SubClass extends PCClass implements CategorizedCDOMObject<SubClass>
{
/**
* Get the choice
* @return choice
*/
public String getChoice()
{
SpellProhibitor sp = get(ObjectKey.CHOICE);
if (sp == null)
{
return "";
}
return sp.getValueList().get(0);
}
/**
* Returns the prohibitCost. If the prohibited cost has not already
* been set, then the sub-classes cost will be returned. This preserves
* the previous behaviour where the prohibited cost and cost were the same.
*
* @return int The prohibit cost for the sub-class.
*/
public int getProhibitCost()
{
Integer prohib = get(IntegerKey.PROHIBIT_COST);
if (prohib != null)
{
return prohib;
}
return getSafe(IntegerKey.COST);
}
@Override
public Category<SubClass> getCDOMCategory()
{
return get(ObjectKey.SUBCLASS_CATEGORY);
}
@Override
public void setCDOMCategory(Category<SubClass> cat)
{
put(ObjectKey.SUBCLASS_CATEGORY, cat);
}
@Override
public String getFullKey()
{
return getCDOMCategory() + "." + super.getFullKey();
}
}
|
9245f9e87b8a14117d34b3b12e728a8202d2d513
| 613 |
java
|
Java
|
src/main/java/indi/pings/android/util/listener/impl/StringCallBackListener.java
|
pingszi/-JavaCommons
|
9f919d0cfe4f475f66d0b9ef3a2d4e7bf7c2b1c0
|
[
"Apache-2.0"
] | 1 |
2019-05-21T09:07:30.000Z
|
2019-05-21T09:07:30.000Z
|
src/main/java/indi/pings/android/util/listener/impl/StringCallBackListener.java
|
pingszi/JavaCommons
|
9f919d0cfe4f475f66d0b9ef3a2d4e7bf7c2b1c0
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/indi/pings/android/util/listener/impl/StringCallBackListener.java
|
pingszi/JavaCommons
|
9f919d0cfe4f475f66d0b9ef3a2d4e7bf7c2b1c0
|
[
"Apache-2.0"
] | null | null | null | 24.52 | 97 | 0.804241 | 1,003,592 |
package indi.pings.android.util.listener.impl;
import indi.pings.android.util.common.Constant;
import indi.pings.android.util.listener.HttpCallbackListener;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
public abstract class StringCallBackListener implements HttpCallbackListener<String, Exception> {
@Override
public String parseResponse(HttpResponse response) throws Exception{
return EntityUtils.toString(response.getEntity(), Constant.ENCODING);
}
@Override
public abstract void onFinish(String response);
@Override
public void onError(Exception e) {
}
}
|
9245fadf9dd9f76f9c473ec9cf816df2f8a85318
| 2,340 |
java
|
Java
|
app/src/main/java/com/hippo/easyrecyclerview/MarginItemDecoration.java
|
tonylu00/EhViewer
|
32a07e9033c98b7b683895d3b2676b0dbc30c7c6
|
[
"Apache-2.0"
] | 253 |
2020-11-29T06:02:49.000Z
|
2022-03-30T08:14:11.000Z
|
app/src/main/java/com/hippo/easyrecyclerview/MarginItemDecoration.java
|
NuclearVGA/EhViewer-CN
|
9d10b9b51f4e709f31f9e64abc84fd208cd0b1c1
|
[
"Apache-2.0"
] | 14 |
2020-11-30T04:31:04.000Z
|
2020-12-05T10:28:21.000Z
|
app/src/main/java/com/hippo/easyrecyclerview/MarginItemDecoration.java
|
NuclearVGA/EhViewer-CN
|
9d10b9b51f4e709f31f9e64abc84fd208cd0b1c1
|
[
"Apache-2.0"
] | 16 |
2020-11-29T10:12:55.000Z
|
2021-11-23T12:26:58.000Z
| 36.5625 | 82 | 0.697863 | 1,003,593 |
/*
* Copyright (C) 2015 Hippo Seven
*
* 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.hippo.easyrecyclerview;
import android.graphics.Rect;
import android.view.View;
import androidx.recyclerview.widget.RecyclerView;
public class MarginItemDecoration extends RecyclerView.ItemDecoration {
private int mMargin;
private int mPaddingLeft;
private int mPaddingTop;
private int mPaddingRight;
private int mPaddingBottom;
public MarginItemDecoration(int margin, int paddingLeft, int paddingTop,
int paddingRight, int paddingBottom) {
setMargin(margin, paddingLeft, paddingTop, paddingRight, paddingBottom);
}
@Override
public void getItemOffsets(Rect outRect, View view,
RecyclerView parent, RecyclerView.State state) {
outRect.set(mMargin, mMargin, mMargin, mMargin);
}
/**
* @param margin gap between two item
* @param paddingLeft gap between RecyclerView left and left item left
* @param paddingTop gap between RecyclerView top and top item top
* @param paddingRight gap between RecyclerView right and right item right
* @param paddingBottom gap between RecyclerView bottom and bottom item bottom
*/
public void setMargin(int margin, int paddingLeft, int paddingTop,
int paddingRight, int paddingBottom) {
int halfMargin = margin / 2;
mMargin = halfMargin;
mPaddingLeft = paddingLeft - halfMargin;
mPaddingTop = paddingTop - halfMargin;
mPaddingRight = paddingRight - halfMargin;
mPaddingBottom = paddingBottom - halfMargin;
}
public void applyPaddings(View view) {
view.setPadding(mPaddingLeft, mPaddingTop, mPaddingRight, mPaddingBottom);
}
}
|
9245fc148e295d759598cabade2b415288121ca2
| 23,213 |
java
|
Java
|
presto-main/src/main/java/com/facebook/presto/operator/Driver.java
|
alexingcool/presto
|
091cbeaef7e14835660712acd75158d7a05bd779
|
[
"Apache-2.0"
] | 456 |
2015-04-23T09:24:25.000Z
|
2022-01-11T08:49:25.000Z
|
presto-main/src/main/java/com/facebook/presto/operator/Driver.java
|
alexingcool/presto
|
091cbeaef7e14835660712acd75158d7a05bd779
|
[
"Apache-2.0"
] | 10 |
2015-08-02T15:37:23.000Z
|
2020-11-18T07:33:46.000Z
|
presto-main/src/main/java/com/facebook/presto/operator/Driver.java
|
ricdong/presto
|
29b76b405b26656d326da8381bbd3f313451df3f
|
[
"Apache-2.0"
] | 123 |
2015-04-30T04:04:40.000Z
|
2021-04-08T09:57:34.000Z
| 37.022329 | 136 | 0.576401 | 1,003,594 |
/*
* 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.facebook.presto.operator;
import com.facebook.presto.ScheduledSplit;
import com.facebook.presto.TaskSource;
import com.facebook.presto.metadata.Split;
import com.facebook.presto.spi.Page;
import com.facebook.presto.spi.UpdatablePageSource;
import com.facebook.presto.sql.planner.plan.PlanNodeId;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.SettableFuture;
import io.airlift.log.Logger;
import io.airlift.units.Duration;
import javax.annotation.concurrent.GuardedBy;
import java.io.Closeable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Supplier;
import static com.facebook.presto.operator.Operator.NOT_BLOCKED;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
//
// NOTE: As a general strategy the methods should "stage" a change and only
// process the actual change before lock release (DriverLockResult.close()).
// The assures that only one thread will be working with the operators at a
// time and state changer threads are not blocked.
//
public class Driver
implements Closeable
{
private static final Logger log = Logger.get(Driver.class);
private final DriverContext driverContext;
private final List<Operator> operators;
private final Map<PlanNodeId, SourceOperator> sourceOperators;
private final Optional<DeleteOperator> deleteOperator;
private final ConcurrentMap<PlanNodeId, TaskSource> newSources = new ConcurrentHashMap<>();
private final AtomicReference<State> state = new AtomicReference<>(State.ALIVE);
private final ReentrantLock exclusiveLock = new ReentrantLock();
@GuardedBy("this")
private Thread lockHolder;
@GuardedBy("exclusiveLock")
private final Map<PlanNodeId, TaskSource> currentSources = new ConcurrentHashMap<>();
private enum State
{
ALIVE, NEED_DESTRUCTION, DESTROYED
}
public Driver(DriverContext driverContext, Operator firstOperator, Operator... otherOperators)
{
this(checkNotNull(driverContext, "driverContext is null"),
ImmutableList.<Operator>builder()
.add(checkNotNull(firstOperator, "firstOperator is null"))
.add(checkNotNull(otherOperators, "otherOperators is null"))
.build());
}
public Driver(DriverContext driverContext, List<Operator> operators)
{
this.driverContext = checkNotNull(driverContext, "driverContext is null");
this.operators = ImmutableList.copyOf(checkNotNull(operators, "operators is null"));
checkArgument(!operators.isEmpty(), "There must be at least one operator");
ImmutableMap.Builder<PlanNodeId, SourceOperator> sourceOperators = ImmutableMap.builder();
Optional<DeleteOperator> deleteOperator = Optional.empty();
for (Operator operator : operators) {
if (operator instanceof SourceOperator) {
SourceOperator sourceOperator = (SourceOperator) operator;
sourceOperators.put(sourceOperator.getSourceId(), sourceOperator);
}
else if (operator instanceof DeleteOperator) {
checkArgument(!deleteOperator.isPresent(), "There must be at most one DeleteOperator");
deleteOperator = Optional.of((DeleteOperator) operator);
}
}
this.sourceOperators = sourceOperators.build();
this.deleteOperator = deleteOperator;
}
public DriverContext getDriverContext()
{
return driverContext;
}
public Set<PlanNodeId> getSourceIds()
{
return sourceOperators.keySet();
}
@Override
public void close()
{
// mark the service for destruction
if (!state.compareAndSet(State.ALIVE, State.NEED_DESTRUCTION)) {
return;
}
// if we can get the lock, attempt a clean shutdown; otherwise someone else will shutdown
try (DriverLockResult lockResult = tryLockAndProcessPendingStateChanges(0, TimeUnit.MILLISECONDS)) {
// if we did not get the lock, interrupt the lock holder
if (!lockResult.wasAcquired()) {
// there is a benign race condition here were the lock holder
// can be change between attempting to get lock and grabbing
// the synchronized lock here, but in either case we want to
// interrupt the lock holder thread
synchronized (this) {
if (lockHolder != null) {
lockHolder.interrupt();
}
}
}
// clean shutdown is automatically triggered during lock release
}
}
public boolean isFinished()
{
checkLockNotHeld("Can not check finished status while holding the driver lock");
// if we can get the lock, attempt a clean shutdown; otherwise someone else will shutdown
try (DriverLockResult lockResult = tryLockAndProcessPendingStateChanges(0, TimeUnit.MILLISECONDS)) {
if (lockResult.wasAcquired()) {
return isFinishedInternal();
}
else {
// did not get the lock, so we can't check operators, or destroy
return state.get() != State.ALIVE || driverContext.isDone();
}
}
}
private boolean isFinishedInternal()
{
checkLockHeld("Lock must be held to call isFinishedInternal");
boolean finished = state.get() != State.ALIVE || driverContext.isDone() || operators.get(operators.size() - 1).isFinished();
if (finished) {
state.compareAndSet(State.ALIVE, State.NEED_DESTRUCTION);
}
return finished;
}
public void updateSource(TaskSource source)
{
checkLockNotHeld("Can not update sources while holding the driver lock");
// does this driver have an operator for the specified source?
if (!sourceOperators.containsKey(source.getPlanNodeId())) {
return;
}
// stage the new updates
while (true) {
// attempt to update directly to the new source
TaskSource currentNewSource = newSources.putIfAbsent(source.getPlanNodeId(), source);
// if update succeeded, just break
if (currentNewSource == null) {
break;
}
// merge source into the current new source
TaskSource newSource = currentNewSource.update(source);
// if this is not a new source, just return
if (newSource == currentNewSource) {
break;
}
// attempt to replace the currentNewSource with the new source
if (newSources.replace(source.getPlanNodeId(), currentNewSource, newSource)) {
break;
}
// someone else updated while we were processing
}
// attempt to get the lock and process the updates we staged above
// updates will be processed in close if and only if we got the lock
tryLockAndProcessPendingStateChanges(0, TimeUnit.MILLISECONDS).close();
}
private void processNewSources()
{
checkLockHeld("Lock must be held to call processNewSources");
// only update if the driver is still alive
if (state.get() != State.ALIVE) {
return;
}
// copy the pending sources
// it is ok to "miss" a source added during the copy as it will be
// handled on the next call to this method
Map<PlanNodeId, TaskSource> sources = new HashMap<>(newSources);
for (Entry<PlanNodeId, TaskSource> entry : sources.entrySet()) {
// Remove the entries we are going to process from the newSources map.
// It is ok if someone already updated the entry; we will catch it on
// the next iteration.
newSources.remove(entry.getKey(), entry.getValue());
processNewSource(entry.getValue());
}
}
private void processNewSource(TaskSource source)
{
checkLockHeld("Lock must be held to call processNewSources");
// create new source
Set<ScheduledSplit> newSplits;
TaskSource currentSource = currentSources.get(source.getPlanNodeId());
if (currentSource == null) {
newSplits = source.getSplits();
currentSources.put(source.getPlanNodeId(), source);
}
else {
// merge the current source and the specified source
TaskSource newSource = currentSource.update(source);
// if this is not a new source, just return
if (newSource == currentSource) {
return;
}
// find the new splits to add
newSplits = Sets.difference(newSource.getSplits(), currentSource.getSplits());
currentSources.put(source.getPlanNodeId(), newSource);
}
// add new splits
for (ScheduledSplit newSplit : newSplits) {
Split split = newSplit.getSplit();
SourceOperator sourceOperator = sourceOperators.get(source.getPlanNodeId());
if (sourceOperator != null) {
Supplier<Optional<UpdatablePageSource>> pageSource = sourceOperator.addSplit(split);
if (deleteOperator.isPresent()) {
deleteOperator.get().setPageSource(pageSource);
}
}
}
// set no more splits
if (source.isNoMoreSplits()) {
sourceOperators.get(source.getPlanNodeId()).noMoreSplits();
}
}
public ListenableFuture<?> processFor(Duration duration)
{
checkLockNotHeld("Can not process for a duration while holding the driver lock");
checkNotNull(duration, "duration is null");
long maxRuntime = duration.roundTo(TimeUnit.NANOSECONDS);
try (DriverLockResult lockResult = tryLockAndProcessPendingStateChanges(100, TimeUnit.MILLISECONDS)) {
if (lockResult.wasAcquired()) {
driverContext.startProcessTimer();
try {
long start = System.nanoTime();
do {
ListenableFuture<?> future = processInternal();
if (!future.isDone()) {
return future;
}
}
while (System.nanoTime() - start < maxRuntime && !isFinishedInternal());
}
finally {
driverContext.recordProcessed();
}
}
}
return NOT_BLOCKED;
}
public ListenableFuture<?> process()
{
checkLockNotHeld("Can not process while holding the driver lock");
try (DriverLockResult lockResult = tryLockAndProcessPendingStateChanges(100, TimeUnit.MILLISECONDS)) {
if (!lockResult.wasAcquired()) {
// this is unlikely to happen unless the driver is being
// destroyed and in that case the caller should notice notice
// this state change by calling isFinished
return NOT_BLOCKED;
}
return processInternal();
}
}
private ListenableFuture<?> processInternal()
{
checkLockHeld("Lock must be held to call processInternal");
try {
if (!newSources.isEmpty()) {
processNewSources();
}
// special handling for drivers with a single operator
if (operators.size() == 1) {
if (driverContext.isDone()) {
return NOT_BLOCKED;
}
// check if operator is blocked
Operator current = operators.get(0);
ListenableFuture<?> blocked = isBlocked(current);
if (!blocked.isDone()) {
current.getOperatorContext().recordBlocked(blocked);
return blocked;
}
// there is only one operator so just finish it
current.getOperatorContext().startIntervalTimer();
current.finish();
current.getOperatorContext().recordFinish();
return NOT_BLOCKED;
}
boolean movedPage = false;
for (int i = 0; i < operators.size() - 1 && !driverContext.isDone(); i++) {
Operator current = operators.get(i);
Operator next = operators.get(i + 1);
// skip blocked operators
if (!isBlocked(current).isDone()) {
continue;
}
if (!isBlocked(next).isDone()) {
continue;
}
// if the current operator is not finished and next operator needs input...
if (!current.isFinished() && next.needsInput()) {
// get an output page from current operator
current.getOperatorContext().startIntervalTimer();
Page page = current.getOutput();
current.getOperatorContext().recordGetOutput(page);
// if we got an output page, add it to the next operator
if (page != null) {
next.getOperatorContext().startIntervalTimer();
next.addInput(page);
next.getOperatorContext().recordAddInput(page);
movedPage = true;
}
}
// if current operator is finished...
if (current.isFinished()) {
// let next operator know there will be no more data
next.getOperatorContext().startIntervalTimer();
next.finish();
next.getOperatorContext().recordFinish();
}
}
// if we did not move any pages, check if we are blocked
if (!movedPage) {
List<Operator> blockedOperators = new ArrayList<>();
List<ListenableFuture<?>> blockedFutures = new ArrayList<>();
for (Operator operator : operators) {
ListenableFuture<?> blocked = isBlocked(operator);
if (!blocked.isDone()) {
blockedOperators.add(operator);
blockedFutures.add(blocked);
}
}
if (!blockedFutures.isEmpty()) {
// unblock when the first future is complete
ListenableFuture<?> blocked = firstFinishedFuture(blockedFutures);
// driver records serial blocked time
driverContext.recordBlocked(blocked);
// each blocked operator is responsible for blocking the execution
// until one of the operators can continue
for (Operator operator : blockedOperators) {
operator.getOperatorContext().recordBlocked(blocked);
}
return blocked;
}
}
return NOT_BLOCKED;
}
catch (Throwable t) {
driverContext.failed(t);
throw t;
}
}
private void destroyIfNecessary()
{
checkLockHeld("Lock must be held to call destroyIfNecessary");
if (!state.compareAndSet(State.NEED_DESTRUCTION, State.DESTROYED)) {
return;
}
// record the current interrupted status (and clear the flag); we'll reset it later
boolean wasInterrupted = Thread.interrupted();
// if we get an error while closing a driver, record it and we will throw it at the end
Throwable inFlightException = null;
try {
for (Operator operator : operators) {
try {
operator.close();
}
catch (InterruptedException t) {
// don't record the stack
wasInterrupted = true;
}
catch (Throwable t) {
inFlightException = addSuppressedException(
inFlightException,
t,
"Error closing operator %s for task %s",
operator.getOperatorContext().getOperatorId(),
driverContext.getTaskId());
}
try {
operator.getOperatorContext().setMemoryReservation(0);
}
catch (Throwable t) {
inFlightException = addSuppressedException(
inFlightException,
t,
"Error freeing memory for operator %s for task %s",
operator.getOperatorContext().getOperatorId(),
driverContext.getTaskId());
}
}
driverContext.finished();
}
catch (Throwable t) {
// this shouldn't happen but be safe
inFlightException = addSuppressedException(
inFlightException,
t,
"Error destroying driver for task %s",
driverContext.getTaskId());
}
finally {
// reset the interrupted flag
if (wasInterrupted) {
Thread.currentThread().interrupt();
}
}
if (inFlightException != null) {
// this will always be an Error or Runtime
throw Throwables.propagate(inFlightException);
}
}
private static ListenableFuture<?> isBlocked(Operator operator)
{
ListenableFuture<?> blocked = operator.isBlocked();
if (blocked.isDone()) {
blocked = operator.getOperatorContext().isWaitingForMemory();
}
return blocked;
}
private static Throwable addSuppressedException(Throwable inFlightException, Throwable newException, String message, Object... args)
{
if (newException instanceof Error) {
if (inFlightException == null) {
inFlightException = newException;
}
else {
// Self-suppression not permitted
if (inFlightException != newException) {
inFlightException.addSuppressed(newException);
}
}
}
else {
// log normal exceptions instead of rethrowing them
log.error(newException, message, args);
}
return inFlightException;
}
private DriverLockResult tryLockAndProcessPendingStateChanges(int timeout, TimeUnit unit)
{
checkLockNotHeld("Can not acquire the driver lock while already holding the driver lock");
return new DriverLockResult(timeout, unit);
}
private synchronized void checkLockNotHeld(String message)
{
checkState(Thread.currentThread() != lockHolder, message);
}
private synchronized void checkLockHeld(String message)
{
checkState(Thread.currentThread() == lockHolder, message);
}
private static ListenableFuture<?> firstFinishedFuture(List<ListenableFuture<?>> futures)
{
SettableFuture<?> result = SettableFuture.create();
ExecutorService executor = MoreExecutors.newDirectExecutorService();
for (ListenableFuture<?> future : futures) {
future.addListener(() -> result.set(null), executor);
}
return result;
}
private class DriverLockResult
implements AutoCloseable
{
private final boolean acquired;
private DriverLockResult(int timeout, TimeUnit unit)
{
acquired = tryAcquire(timeout, unit);
}
private boolean tryAcquire(int timeout, TimeUnit unit)
{
boolean acquired = false;
try {
acquired = exclusiveLock.tryLock(timeout, unit);
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
if (acquired) {
synchronized (Driver.this) {
lockHolder = Thread.currentThread();
}
}
return acquired;
}
public boolean wasAcquired()
{
return acquired;
}
@Override
public void close()
{
if (!acquired) {
return;
}
boolean done = false;
while (!done) {
done = true;
// before releasing the lock, process any new sources and/or destroy the driver
try {
try {
processNewSources();
}
finally {
destroyIfNecessary();
}
}
finally {
synchronized (Driver.this) {
lockHolder = null;
}
exclusiveLock.unlock();
// if new sources were added after we processed them, go around and try again
// in case someone else failed to acquire the lock and as a result won't update them
if (!newSources.isEmpty() && state.get() == State.ALIVE && tryAcquire(0, TimeUnit.MILLISECONDS)) {
done = false;
}
}
}
}
}
}
|
9245fcb03707435624683677e2a4db4522c9fde4
| 713 |
java
|
Java
|
src/main/com/cairn/rmi/task/ExactMassTask.java
|
jones-gareth/OraRdkitCart
|
c0f08e3d69257f10ba77983f625ded9d9aff3d35
|
[
"Apache-2.0"
] | 3 |
2019-09-02T09:29:23.000Z
|
2021-08-02T11:10:35.000Z
|
src/main/com/cairn/rmi/task/ExactMassTask.java
|
jones-gareth/OraRdkitCart
|
c0f08e3d69257f10ba77983f625ded9d9aff3d35
|
[
"Apache-2.0"
] | null | null | null |
src/main/com/cairn/rmi/task/ExactMassTask.java
|
jones-gareth/OraRdkitCart
|
c0f08e3d69257f10ba77983f625ded9d9aff3d35
|
[
"Apache-2.0"
] | 1 |
2021-08-02T11:10:36.000Z
|
2021-08-02T11:10:36.000Z
| 23.766667 | 83 | 0.681627 | 1,003,595 |
package com.cairn.rmi.task;
import com.cairn.common.RDKitOps;
import org.RDKit.RDKFuncs;
import org.apache.log4j.Logger;
/**
*
* @author Gareth Jones
*/
public class ExactMassTask extends AbstractTask {
private static final long serialVersionUID = 1000L;
private static final Logger logger = Logger.getLogger(MolecularWeightTask.class
.getName());
@Override
public Object submitTask() {
String smiles = (String) settings;
logger.debug("processing smiles " + smiles);
var molOpt = RDKitOps.smilesToMol(smiles);
var exactMass = molOpt.map(RDKFuncs::calcExactMW).orElse(Double.NaN);
results = exactMass;
return exactMass;
}
}
|
9245fcb067e9f6683ea216e720985aebd984b06d
| 2,826 |
java
|
Java
|
src/main/java/org/CyfrSheets/models/EventTime.java
|
ZekeSturm/schedule-sheets
|
926b654ebd65e3c51a4bf2641cd2ae0aa9907afa
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/org/CyfrSheets/models/EventTime.java
|
ZekeSturm/schedule-sheets
|
926b654ebd65e3c51a4bf2641cd2ae0aa9907afa
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/org/CyfrSheets/models/EventTime.java
|
ZekeSturm/schedule-sheets
|
926b654ebd65e3c51a4bf2641cd2ae0aa9907afa
|
[
"Apache-2.0"
] | null | null | null | 32.113636 | 119 | 0.686837 | 1,003,596 |
package org.CyfrSheets.models;
import org.CyfrSheets.models.exceptions.EventTypeMismatchException;
import java.util.Calendar;
import static org.CyfrSheets.models.EventType.*;
public class EventTime {
private TimeType tType;
private EventType parentType;
private boolean staticEvent;
private boolean startOnly;
private Calendar startTime;
private Calendar endTime;
// Implement Planning Event participant/time pairs in hashmaps here... at some point.
public EventTime(EventType parentType, Calendar startTime, Calendar endTime)
throws EventTypeMismatchException {
this.parentType = parentType;
if (parentType == SDP || parentType == MDP) {
if (startOnly) throw new EventTypeMismatchException("Planning Event Must Have End Time");
planningInit(startTime, endTime);
} else {
if (startOnly) staticInit(startTime);
else staticInit(startTime, endTime);
}
}
public EventTime(Calendar startTime) throws EventTypeMismatchException
{ this(SOS,startTime,null); }
public EventTime() { }
public Calendar getStartTime() { return startTime; }
public Calendar getEndTime() throws EventTypeMismatchException {
if (startOnly) throw new EventTypeMismatchException("Events tagged with startOnly do not have an end time");
return endTime;
}
public EventType fetchType() { return parentType; }
// When adding below getters/setters, add checks for "is this a planning event or not". Throw
// EventTypeMismatchException for attempting to access from static event
// Getter methods for participant/time pairs go here. May make these a further subclass but it would be an in-class
// subclass and would still export standard hashmap key/value pairs at the public level
// Setter methods for participant/time pairs go here. See above. Required for planning events.
private void staticInit(Calendar startTime, Calendar endTime) {
this.endTime = endTime;
staticInit(startTime);
}
private void staticInit(Calendar startTime) {
this.startTime = startTime;
staticEvent = true;
}
private void planningInit(Calendar startTime, Calendar endTime) {
staticEvent = false;
// Initialize participant/timeblock storage here
}
}
enum TimeType { TWELVE, TWENTYFOUR }
/**
Legacy typefinder code - may be useful to export elsewhere
private EventType findParentType(Calendar startTime, Calendar endTime) {
if (endTime == null) return SOS;
if (startTime.get(DATE) == endTime.get(DATE)) {
if (staticEvent) return SDS;
else return SDP;
} else {
if (staticEvent) return MDS;
else return MDP;
}
}
*/
|
9245fd8301fafeb76db746137ddb05d9c65423ab
| 1,983 |
java
|
Java
|
B2G/gecko/mobile/android/base/Telemetry.java
|
wilebeast/FireFox-OS
|
43067f28711d78c429a1d6d58c77130f6899135f
|
[
"Apache-2.0"
] | 3 |
2015-08-31T15:24:31.000Z
|
2020-04-24T20:31:29.000Z
|
B2G/gecko/mobile/android/base/Telemetry.java
|
wilebeast/FireFox-OS
|
43067f28711d78c429a1d6d58c77130f6899135f
|
[
"Apache-2.0"
] | null | null | null |
B2G/gecko/mobile/android/base/Telemetry.java
|
wilebeast/FireFox-OS
|
43067f28711d78c429a1d6d58c77130f6899135f
|
[
"Apache-2.0"
] | 3 |
2015-07-29T07:17:15.000Z
|
2020-11-04T06:55:37.000Z
| 30.507692 | 86 | 0.566314 | 1,003,597 |
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*-
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.gecko;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.SystemClock;
import android.util.Log;
public class Telemetry {
private static final String LOGTAG = "Telemetry";
// Define new histograms in:
// toolkit/components/telemetry/Histograms.json
public static void HistogramAdd(String name,
int value) {
try {
JSONObject jsonData = new JSONObject();
jsonData.put("name", name);
jsonData.put("value", value);
GeckoEvent event =
GeckoEvent.createBroadcastEvent("Telemetry:Add", jsonData.toString());
GeckoAppShell.sendEventToGecko(event);
Log.v(LOGTAG, "Sending telemetry: " + jsonData.toString());
} catch (JSONException e) {
Log.e(LOGTAG, "JSON exception: ", e);
}
}
public static class Timer {
private long mStartTime;
private String mName;
private boolean mHasFinished;
public Timer(String name) {
mName = name;
mStartTime = SystemClock.uptimeMillis();
mHasFinished = false;
}
public void stop() {
// Only the first stop counts.
if (mHasFinished) {
return;
} else {
mHasFinished = true;
}
long elapsed = SystemClock.uptimeMillis() - mStartTime;
if (elapsed < Integer.MAX_VALUE) {
HistogramAdd(mName, (int)(elapsed));
} else {
Log.e(LOGTAG, "Duration of " + elapsed + " ms is too long.");
}
}
}
}
|
9245fe9acb2909491e60ad102d5ed54813812188
| 11,322 |
java
|
Java
|
java/drda/org/apache/derby/impl/drda/SQLTypes.java
|
kyowill/derby-10.0.2.1
|
b30dddf5248b603291bdf509ba6b10efe6999609
|
[
"Apache-2.0"
] | null | null | null |
java/drda/org/apache/derby/impl/drda/SQLTypes.java
|
kyowill/derby-10.0.2.1
|
b30dddf5248b603291bdf509ba6b10efe6999609
|
[
"Apache-2.0"
] | null | null | null |
java/drda/org/apache/derby/impl/drda/SQLTypes.java
|
kyowill/derby-10.0.2.1
|
b30dddf5248b603291bdf509ba6b10efe6999609
|
[
"Apache-2.0"
] | null | null | null | 41.472527 | 166 | 0.686451 | 1,003,598 |
/*
Derby - Class org.apache.derby.impl.drda.SQLTypes
Copyright 2002, 2004 The Apache Software Foundation or its licensors, as applicable.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.apache.derby.impl.drda;
import java.sql.Types;
import java.sql.SQLException;
import org.apache.derby.iapi.reference.JDBC30Translation;
public class SQLTypes {
//----------------------------------------------------------------------------
protected final static int DB2_SQLTYPE_DATE = 384; // DATE
protected final static int DB2_SQLTYPE_NDATE = 385;
protected final static int DB2_SQLTYPE_TIME = 388; // TIME
protected final static int DB2_SQLTYPE_NTIME = 389;
protected final static int DB2_SQLTYPE_TIMESTAMP = 392; // TIMESTAMP
protected final static int DB2_SQLTYPE_NTIMESTAMP = 393;
protected final static int DB2_SQLTYPE_DATALINK = 396; // DATALINK
protected final static int DB2_SQLTYPE_NDATALINK = 397;
protected final static int DB2_SQLTYPE_BLOB = 404; // BLOB
protected final static int DB2_SQLTYPE_NBLOB = 405;
protected final static int DB2_SQLTYPE_CLOB = 408; // CLOB
protected final static int DB2_SQLTYPE_NCLOB = 409;
protected final static int DB2_SQLTYPE_DBCLOB = 412; // DBCLOB
protected final static int DB2_SQLTYPE_NDBCLOB = 413;
protected final static int DB2_SQLTYPE_VARCHAR = 448; // VARCHAR(i) - varying length string
protected final static int DB2_SQLTYPE_NVARCHAR = 449;
protected final static int DB2_SQLTYPE_CHAR = 452; // CHAR(i) - fixed length
protected final static int DB2_SQLTYPE_NCHAR = 453;
protected final static int DB2_SQLTYPE_LONG = 456; // LONG VARCHAR - varying length string
protected final static int DB2_SQLTYPE_NLONG = 457;
protected final static int DB2_SQLTYPE_CSTR = 460; // SBCS - null terminated
protected final static int DB2_SQLTYPE_NCSTR = 461;
protected final static int DB2_SQLTYPE_VARGRAPH = 464; // VARGRAPHIC(i) - varying length
// graphic string (2 byte length)
protected final static int DB2_SQLTYPE_NVARGRAPH = 465;
protected final static int DB2_SQLTYPE_GRAPHIC = 468; // GRAPHIC(i) - fixed length graphic string */
protected final static int DB2_SQLTYPE_NGRAPHIC = 469;
protected final static int DB2_SQLTYPE_LONGRAPH = 472; // LONG VARGRAPHIC(i) - varying length graphic string */
protected final static int DB2_SQLTYPE_NLONGRAPH = 473;
protected final static int DB2_SQLTYPE_LSTR = 476; // varying length string for Pascal (1-byte length) */
protected final static int DB2_SQLTYPE_NLSTR = 477;
protected final static int DB2_SQLTYPE_FLOAT = 480; // FLOAT - 4 or 8 byte floating point
protected final static int DB2_SQLTYPE_NFLOAT = 481;
protected final static int DB2_SQLTYPE_DECIMAL = 484; // DECIMAL (m,n)
protected final static int DB2_SQLTYPE_NDECIMAL = 485;
protected final static int DB2_SQLTYPE_ZONED = 488; // Zoned Decimal -> DECIMAL(m,n)
protected final static int DB2_SQLTYPE_NZONED = 489;
protected final static int DB2_SQLTYPE_BIGINT = 492; // BIGINT - 8-byte signed integer
protected final static int DB2_SQLTYPE_NBIGINT = 493;
protected final static int DB2_SQLTYPE_INTEGER = 496; // INTEGER
protected final static int DB2_SQLTYPE_NINTEGER = 497;
protected final static int DB2_SQLTYPE_SMALL = 500; // SMALLINT - 2-byte signed integer */
protected final static int DB2_SQLTYPE_NSMALL = 501;
protected final static int DB2_SQLTYPE_NUMERIC = 504; // NUMERIC -> DECIMAL (m,n)
protected final static int DB2_SQLTYPE_NNUMERIC = 505;
protected final static int DB2_SQLTYPE_ROWID = 904; // ROWID
protected final static int DB2_SQLTYPE_NROWID = 905;
protected final static int DB2_SQLTYPE_BLOB_LOCATOR = 960; // BLOB locator
protected final static int DB2_SQLTYPE_NBLOB_LOCATOR = 961;
protected final static int DB2_SQLTYPE_CLOB_LOCATOR = 964; // CLOB locator
protected final static int DB2_SQLTYPE_NCLOB_LOCATOR = 965;
protected final static int DB2_SQLTYPE_DBCLOB_LOCATOR = 968; // DBCLOB locator
protected final static int DB2_SQLTYPE_NDBCLOB_LOCATOR = 969;
// define final statics for the fdoca type codes here!!!
// hide the default constructor
private SQLTypes() {}
/**
* Map DB2 SQL Type to JDBC Type
*
* @param sqlType SQL Type to convert
* @param length storage length of type
* @param ccsid ccsid of type
*
* @return Corresponding JDBC Type
*/
static protected int mapDB2SqlTypeToJdbcType (int sqlType, long length, int ccsid)
{
switch (getNonNullableSqlType (sqlType)) { // mask the isNullable bit
case DB2_SQLTYPE_SMALL:
return java.sql.Types.SMALLINT;
case DB2_SQLTYPE_INTEGER:
return java.sql.Types.INTEGER;
case DB2_SQLTYPE_BIGINT:
return java.sql.Types.BIGINT;
case DB2_SQLTYPE_FLOAT:
if (length == 16) // can map to either NUMERIC or DECIMAL!!! @sxg
return java.sql.Types.DECIMAL;
else if (length == 8) // can map to either DOUBLE or FLOAT!!! @sxg
return java.sql.Types.DOUBLE;
else if (length == 4)
return java.sql.Types.REAL;
else
return 0;
//throw new BugCheckException ("Encountered unexpected float length");
case DB2_SQLTYPE_DECIMAL: // can map to either NUMERIC or DECIMAL!!! @sxg
case DB2_SQLTYPE_ZONED: // can map to either NUMERIC or DECIMAL!!! @sxg
case DB2_SQLTYPE_NUMERIC: // can map to either NUMERIC or DECIMAL!!! @sxg
return java.sql.Types.DECIMAL;
case DB2_SQLTYPE_CHAR: // mixed and single byte
if (ccsid == 0xffff || ccsid == 0) // we think UW returns 0, and 390 returns 0xffff, doublecheck !!!
return java.sql.Types.BINARY;
else
return java.sql.Types.CHAR;
case DB2_SQLTYPE_CSTR: // SBCS null terminated
case DB2_SQLTYPE_GRAPHIC: // fixed character DBCS
return java.sql.Types.CHAR;
// use ccsid to distinguish between BINARY and CHAR, VARBINARY and VARCHAR, LONG... !!! -j/p/s
case DB2_SQLTYPE_VARGRAPH: // variable character DBCS
case DB2_SQLTYPE_VARCHAR: // variable character SBCS/Mixed
if (ccsid == 0xffff || ccsid == 0) // we think UW returns 0, and 390 returns 0xffff, doublecheck !!!
return java.sql.Types.VARBINARY;
else
return java.sql.Types.VARCHAR;
case DB2_SQLTYPE_LSTR: // pascal string SBCS/Mixed
return java.sql.Types.VARCHAR;
case DB2_SQLTYPE_LONGRAPH: // long varchar DBCS
case DB2_SQLTYPE_LONG: // long varchar SBCS/Mixed
if (ccsid == 0xffff || ccsid == 0) // we think UW returns 0, and 390 returns 0xffff, doublecheck !!!
return java.sql.Types.LONGVARBINARY;
else
return java.sql.Types.LONGVARCHAR;
case DB2_SQLTYPE_DATE:
return java.sql.Types.DATE;
case DB2_SQLTYPE_TIME:
return java.sql.Types.TIME;
case DB2_SQLTYPE_TIMESTAMP:
return java.sql.Types.TIMESTAMP;
case DB2_SQLTYPE_CLOB: // large object character SBCS/Mixed
case DB2_SQLTYPE_DBCLOB: // large object character DBCS
return java.sql.Types.CLOB;
case DB2_SQLTYPE_BLOB: // large object bytes
case DB2_SQLTYPE_BLOB_LOCATOR:
case DB2_SQLTYPE_CLOB_LOCATOR:
case DB2_SQLTYPE_DBCLOB_LOCATOR:
return java.sql.Types.BLOB;
default:
//throw new BugCheckException ("Encountered unexpected type code");
return 0;
}
}
/**
* Map jdbc type to the DB2 DRDA SQL Types expected by jcc.
*@param jdbctype - jdbc Type to convert
*@param nullable - whether the type is nullable
**/
/** Map JDBC Type to DB2 SqlType
* @param jdbctype JDBC Type from java.sql.Types
* @param nullable true if this is a nullable type
* @param outlen output parameter with type length
*
* @return Corresponding DB2 SQL Type (See DRDA Manual FD:OCA Meta
* Data Summary, page 245)
*
* @exception SQLException thrown for unrecognized SQLType
*/
static protected int mapJdbcTypeToDB2SqlType (int jdbctype, boolean nullable,
int[] outlen)
throws SQLException
{
int nullAddVal =0;
if (nullable)
nullAddVal =1;
// Call FdocaConstants just to get the length
FdocaConstants.mapJdbcTypeToDrdaType(jdbctype,nullable,outlen);
switch(jdbctype)
{
case JDBC30Translation.BOOLEAN:
case java.sql.Types.BIT:
case java.sql.Types.TINYINT:
case java.sql.Types.SMALLINT:
return DB2_SQLTYPE_SMALL + nullAddVal;
case java.sql.Types.INTEGER:
return DB2_SQLTYPE_INTEGER + nullAddVal;
case java.sql.Types.BIGINT:
return DB2_SQLTYPE_BIGINT + nullAddVal;
case java.sql.Types.DOUBLE:
case java.sql.Types.REAL:
return DB2_SQLTYPE_FLOAT + nullAddVal;
case java.sql.Types.DECIMAL:
case java.sql.Types.NUMERIC:
return DB2_SQLTYPE_DECIMAL + nullAddVal;
case java.sql.Types.DATE:
return DB2_SQLTYPE_DATE + nullAddVal;
case java.sql.Types.TIME:
return DB2_SQLTYPE_TIME + nullAddVal;
case java.sql.Types.TIMESTAMP:
return DB2_SQLTYPE_TIMESTAMP + nullAddVal;
case java.sql.Types.CHAR:
return DB2_SQLTYPE_CHAR + nullAddVal; // null terminated SBCS/Mixed
case java.sql.Types.BINARY:
return DB2_SQLTYPE_CHAR + nullAddVal;
case java.sql.Types.VARCHAR:
case java.sql.Types.VARBINARY:
return DB2_SQLTYPE_VARCHAR + nullAddVal;
case java.sql.Types.LONGVARBINARY:
return DB2_SQLTYPE_LONG + nullAddVal;
case java.sql.Types.JAVA_OBJECT:
return DB2_SQLTYPE_LONG + nullAddVal;
case java.sql.Types.BLOB:
return DB2_SQLTYPE_BLOB + nullAddVal;
case java.sql.Types.CLOB:
return DB2_SQLTYPE_CLOB + nullAddVal;
case java.sql.Types.LONGVARCHAR:
return DB2_SQLTYPE_LONG + nullAddVal;
case java.sql.Types.ARRAY:
case java.sql.Types.DISTINCT:
case java.sql.Types.NULL:
case java.sql.Types.OTHER:
case java.sql.Types.REF:
case java.sql.Types.STRUCT:
throw new SQLException("Jdbc type" + jdbctype + "not Supported yet");
default:
throw new SQLException ("unrecognized sql type: " + jdbctype);
//throw new BugCheckException ("Encountered unexpected type code");
}
}
/**
* Translate DB2 SQL Type to the non-nullable type.
* @param sqlType DB2 SQL Type
*
* @return The Non-Nullable DB2 SQL Type.
*/
protected static int getNonNullableSqlType (int sqlType)
{
return sqlType & ~1;
}
}
|
9245feceb39f27bf6ce7537378d4d83ae19b4543
| 882 |
java
|
Java
|
src/main/java/com/learn/leetcode/offer/offer50.java
|
LJLintermittent/leetcode
|
f0ac05bb38117de4e3c02f1dcb3559d693027b86
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/learn/leetcode/offer/offer50.java
|
LJLintermittent/leetcode
|
f0ac05bb38117de4e3c02f1dcb3559d693027b86
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/learn/leetcode/offer/offer50.java
|
LJLintermittent/leetcode
|
f0ac05bb38117de4e3c02f1dcb3559d693027b86
|
[
"Apache-2.0"
] | null | null | null | 21.047619 | 54 | 0.521493 | 1,003,599 |
package com.learn.leetcode.offer;
import java.util.HashMap;
import java.util.Map;
/**
* Description:
* date: 2021/8/27 10:59
* Package: com.learn.leetcode.offer
*
* @author 李佳乐
* @email [email protected]
*/
@SuppressWarnings("all")
public class offer50 {
public static void main(String[] args) {
String s = "acaadcad";
char ans = firstUniqChar(s);
System.out.println(ans);
}
/**
* 第一个只出现一次的字符
*/
public static char firstUniqChar(String s) {
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
map.put(c, map.getOrDefault(c, 0) + 1);
}
for (int i = 0; i < s.length(); i++) {
if (map.get(s.charAt(i)) == 1) {
return s.charAt(i);
}
}
return ' ';
}
}
|
9245fedd7f48d7a8bcd24d849fdfe5223995c1d3
| 2,822 |
java
|
Java
|
Databases Frameworks - Hibernate & Spring Data/Exercises - Spring Data Advanced Quering/BookShop-System/src/main/java/bookshopsystem/repositories/BookRepository.java
|
Valentin9003/Java
|
9d263063685ba60ab75dc9efd25554b715a7980a
|
[
"Apache-2.0"
] | 1 |
2018-10-28T13:48:48.000Z
|
2018-10-28T13:48:48.000Z
|
Databases Frameworks - Hibernate & Spring Data/Exercises - Spring Data Advanced Quering/BookShop-System/src/main/java/bookshopsystem/repositories/BookRepository.java
|
Valentin9003/Java
|
9d263063685ba60ab75dc9efd25554b715a7980a
|
[
"Apache-2.0"
] | null | null | null |
Databases Frameworks - Hibernate & Spring Data/Exercises - Spring Data Advanced Quering/BookShop-System/src/main/java/bookshopsystem/repositories/BookRepository.java
|
Valentin9003/Java
|
9d263063685ba60ab75dc9efd25554b715a7980a
|
[
"Apache-2.0"
] | null | null | null | 41.5 | 124 | 0.755847 | 1,003,600 |
package bookshopsystem.repositories;
import bookshopsystem.dto.AuthorDto;
import bookshopsystem.dto.BookDto;
import bookshopsystem.dto.ReducedBook;
import bookshopsystem.enums.AgeRestriction;
import bookshopsystem.enums.EditionType;
import bookshopsystem.models.entity.Author;
import bookshopsystem.models.entity.Book;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.query.Procedure;
import org.springframework.data.repository.query.Param;
import java.util.Date;
import java.util.List;
public interface BookRepository extends JpaRepository<Book, Integer> {
List<Book> findAllByReleaseDateAfter(Date releaseDate);
List<Book> findAllByAuthor(Author author);
List<Book> findAllByAuthorAndReleaseDateBefore(Author author, Date date);
List<Book> findAllByAuthorOrderByReleaseDateDescTitleAsc(Author author);
@Query(value = "SELECT b.title FROM Book b WHERE b.ageRestriction = :restriction")
List<String> allBooksByRestriction(@Param("restriction") AgeRestriction restriction);
@Query(value = "SELECT b.title FROM Book b WHERE b.copies < 5000 AND b.editionType = :edition")
List<String> allGoldenEditionBooksWithLessThan5000Copies(@Param("edition") EditionType editionType);
@Query("SELECT new bookshopsystem.dto.BookDto(b.title, b.price) FROM Book b WHERE b.price < 5 OR b.price > 40")
List<BookDto> allBooksByPrice();
@Query(value = "SELECT b.title FROM Book b WHERE b.releaseDate <> :date")
List<String> notReleasedBooksOnGivenYear(@Param("date") Date date);
@Query("SELECT new bookshopsystem.dto.BookDto(b.title, b.price, b.editionType) FROM Book b WHERE b.releaseDate < :date")
List<BookDto> booksReleasedBeforeDate(@Param("date") Date date);
List<Book> findAllByTitleContains(String str);
@Query("SELECT b FROM Book b WHERE b.author.lastName LIKE :str")
List<Book> bookTitleSearchByAuthorLastNameStartingWith(@Param("str") String str);
@Query("SELECT count(b.title) FROM Book b WHERE length(b.title) > :number")
int countBookByTitleGreaterThan(@Param("number") Integer number);
@Query("SELECT " +
"new bookshopsystem.dto.AuthorDto(b.author.firstName, b.author.lastName, sum(b.copies))" +
"FROM Book b " +
"GROUP BY b.author.firstName, b.author.lastName")
List<AuthorDto> totalBookCopiesByAuthors();
ReducedBook findBookByTitle(String title);
@Modifying
@Query("UPDATE Book b SET b.copies = b.copies + :newCopies WHERE b.releaseDate > :date")
int increaseBookCopies(@Param("date") Date date, @Param("newCopies") int newCopies);
@Modifying
int removeBooksByCopiesLessThan(int number);
}
|
9246003a4d7e3246899e67554e8b4998584cafc4
| 185 |
java
|
Java
|
examples/tdd-example/src/main/java/com/github/hyeyoom/module/NotPositiveNumberException.java
|
neouldevs/book-study
|
839137f1eeb45a83b2adc86fab5f043f5660d8ef
|
[
"MIT"
] | 2 |
2019-11-16T08:46:22.000Z
|
2019-11-17T07:17:23.000Z
|
examples/tdd-example/src/main/java/com/github/hyeyoom/module/NotPositiveNumberException.java
|
neouldevs/book-study
|
839137f1eeb45a83b2adc86fab5f043f5660d8ef
|
[
"MIT"
] | null | null | null |
examples/tdd-example/src/main/java/com/github/hyeyoom/module/NotPositiveNumberException.java
|
neouldevs/book-study
|
839137f1eeb45a83b2adc86fab5f043f5660d8ef
|
[
"MIT"
] | 1 |
2019-11-26T17:53:11.000Z
|
2019-11-26T17:53:11.000Z
| 20.555556 | 59 | 0.751351 | 1,003,601 |
package com.github.hyeyoom.module;
public class NotPositiveNumberException extends Exception {
public NotPositiveNumberException(String message) {
super(message);
}
}
|
92460146252afb5b386c7cfb85a1f0682227a269
| 1,770 |
java
|
Java
|
ucmh/src/main/java/es/fdi/ucm/ucmh/controller/UserController.java
|
manuel-freire/UCMH
|
dd22b7a55fe1432a03b9fcdb974b29780cf937d3
|
[
"MIT"
] | null | null | null |
ucmh/src/main/java/es/fdi/ucm/ucmh/controller/UserController.java
|
manuel-freire/UCMH
|
dd22b7a55fe1432a03b9fcdb974b29780cf937d3
|
[
"MIT"
] | null | null | null |
ucmh/src/main/java/es/fdi/ucm/ucmh/controller/UserController.java
|
manuel-freire/UCMH
|
dd22b7a55fe1432a03b9fcdb974b29780cf937d3
|
[
"MIT"
] | null | null | null | 23.918919 | 103 | 0.723729 | 1,003,602 |
package es.fdi.ucm.ucmh.controller;
import javax.persistence.EntityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import es.fdi.ucm.ucmh.model.User;
@Controller
public class UserController {
@Autowired
EntityManager jpaEntityManager;
@GetMapping(value = "/user/{userID}/{userPage}")
public String getUser(@PathVariable Long userID, @PathVariable String userPage, Model model) {
User person = jpaEntityManager.find(User.class, userID);
if (person == null) {
return "404";
}
model.addAttribute("user", person);
String pageToReturn = null;
switch (userPage) {
case "ajustes":
pageToReturn = "ajustesPaciente";
break;
case "pagina-principal":
pageToReturn = "misCitas";
break;
case "estadisticas":
pageToReturn = "estadisticasPaciente";
break;
default:
break;
}
return pageToReturn;
}
@GetMapping(value = "/user/{userID}/psychologist/{userPage}")
public String getPsycologist(@PathVariable Long userID, @PathVariable String userPage, Model model) {
User u = jpaEntityManager.find(User.class, userID);
if (u == null)
return "404";
if (u.getPsychologist() != null) //tiene un psicologo asignado
model.addAttribute("user", u.getPsychologist());
String pageToReturn = null;
switch (userPage) {
case "ajustes":
pageToReturn = "ajustesPaciente";
break;
case "pagina-principal":
pageToReturn = "misCitas";
break;
case "estadisticas":
pageToReturn = "estadisticasPaciente";
break;
default:
break;
}
return pageToReturn;
}
}
|
924601565f26d7e44c0726302bc8c5327f89caeb
| 20,755 |
java
|
Java
|
PatternMiner/libraries/spmf/src/main/java/algorithms/frequentpatterns/HUIM_BPSO/AlgoHUIM_BPSO.java
|
landongw/disease-pattern-miner
|
e62d7ec76b09330cf95c8dbe9993e41e77cc6cc6
|
[
"MIT"
] | 10 |
2018-12-26T13:12:53.000Z
|
2021-10-09T15:34:31.000Z
|
PatternMiner/libraries/spmf/src/main/java/algorithms/frequentpatterns/HUIM_BPSO/AlgoHUIM_BPSO.java
|
vitaliy-ostapchuk93/disease-pattern-miner
|
e62d7ec76b09330cf95c8dbe9993e41e77cc6cc6
|
[
"MIT"
] | 2 |
2021-08-02T17:25:47.000Z
|
2021-08-02T17:25:53.000Z
|
PatternMiner/libraries/spmf/src/main/java/algorithms/frequentpatterns/HUIM_BPSO/AlgoHUIM_BPSO.java
|
landongw/disease-pattern-miner
|
e62d7ec76b09330cf95c8dbe9993e41e77cc6cc6
|
[
"MIT"
] | 6 |
2019-04-26T13:58:36.000Z
|
2020-12-31T06:35:22.000Z
| 36.412281 | 93 | 0.504601 | 1,003,603 |
package algorithms.frequentpatterns.HUIM_BPSO;
import java.io.*;
import java.util.*;
/**
* * * * This is an implementation of the high utility itemset mining algorithm
* based on Binary Particle Swarm Optimization Algorithm.
* <p>
* Copyright (c) 2016 Jerry Chun-Wei Lin, Lu Yang, Philippe Fournier-Viger
* <p>
* This file is part of the SPMF DATA MINING SOFTWARE *
* (http://www.philippe-fournier-viger.com/spmf).
* <p>
* <p>
* SPMF is free software: you can redistribute it and/or modify it under the *
* terms of the GNU General Public License as published by the Free Software *
* Foundation, either version 3 of the License, or (at your option) any later *
* version. *
* <p>
* SPMF 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.
* *
* <p>
* You should have received a copy of the GNU General Public License along with
* * SPMF. If not, see .
*
* @author Jerry Chun-Wei Lin, Lu Yang, Philippe Fournier-Viger
*/
public class AlgoHUIM_BPSO {
final int pop_size = 20;// the size of populations
final int iterations = 10000;// the iterations of algorithms
final int c1 = 2, c2 = 2;// the parameter used in BPSO algorithm
final double w = 0.9;// the parameter used in BPSO algorithm
// variable for statistics
double maxMemory = 0; // the maximum memory usage
long startTimestamp = 0; // the time the algorithm started
long endTimestamp = 0; // the time the algorithm terminated
Map<Integer, Integer> mapItemToTWU;
Map<Integer, Integer> mapItemToTWU0;//�����Ƴ���ЩTWUС��minUtil��item
List<Integer> twuPattern;// the items which has twu value more than minUtil
BufferedWriter writer = null; // writer to write the output file
Particle gBest;// the gBest particle in populations
List<Particle> pBest = new ArrayList<Particle>();// each pBest particle in
// populations,
List<Particle> population = new ArrayList<Particle>();// populations
List<HUI> huiSets = new ArrayList<HUI>();// the set of HUIs
List<List<Double>> V = new ArrayList<List<Double>>();// the velocity of each
// particle
List<Double> percentage = new ArrayList<Double>();// the portation of twu
// Create a list to store database
List<List<Pair>> database = new ArrayList<List<Pair>>();
/**
* Default constructor
*/
public AlgoHUIM_BPSO() {
}
/**
* Run the algorithm
*
* @param input the input file path
* @param output the output file path
* @param minUtility the minimum utility threshold
* @throws IOException exception if error while writing the file
*/
public void runAlgorithm(String input, String output, int minUtility)
throws IOException {
// reset maximum
maxMemory = 0;
startTimestamp = System.currentTimeMillis();
writer = new BufferedWriter(new FileWriter(output));
// We create a map to store the TWU of each item
mapItemToTWU = new HashMap<Integer, Integer>();
mapItemToTWU0 = new HashMap<Integer, Integer>();
// We scan the database a first time to calculate the TWU of each item.
BufferedReader myInput = null;
String thisLine;
try {
// prepare the object for reading the file
myInput = new BufferedReader(new InputStreamReader(
new FileInputStream(new File(input))));
// for each line (transaction) until the end of file
while ((thisLine = myInput.readLine()) != null) {
// if the line is a comment, is empty or is a
// kind of metadata
if (thisLine.isEmpty() == true || thisLine.charAt(0) == '#'
|| thisLine.charAt(0) == '%'
|| thisLine.charAt(0) == '@') {
continue;
}
// split the transaction according to the : separator
String split[] = thisLine.split(":");
// the first part is the list of items
String items[] = split[0].split(" ");
// the second part is the transaction utility
int transactionUtility = Integer.parseInt(split[1]);
// for each item, we add the transaction utility to its TWU
for (int i = 0; i < items.length; i++) {
// convert item to integer
Integer item = Integer.parseInt(items[i]);
// get the current TWU of that item
Integer twu = mapItemToTWU.get(item);
Integer twu0 = mapItemToTWU0.get(item);
// add the utility of the item in the current transaction to
// its twu
twu = (twu == null) ? transactionUtility : twu
+ transactionUtility;
twu0 = (twu0 == null) ? transactionUtility : twu0
+ transactionUtility;
mapItemToTWU.put(item, twu);
mapItemToTWU0.put(item, twu0);
}
}
} catch (Exception e) {
// catches exception if error while reading the input file
e.printStackTrace();
} finally {
if (myInput != null) {
myInput.close();
}
}
//���������д�����Դ�����еģ�Ȼ�������д��������Ǵ����
//���뱾����twuPattern����HTWU-1item�����²�����û�дﵽ���Ŀ��
/*twuPattern = new ArrayList<Integer>(mapItemToTWU.keySet());
Collections.sort(twuPattern);*/
// SECOND DATABASE PASS TO CONSTRUCT THE DATABASE
// OF 1-ITEMSETS HAVING TWU >= minutil (promising items)
try {
// prepare object for reading the file
myInput = new BufferedReader(new InputStreamReader(
new FileInputStream(new File(input))));
// variable to count the number of transaction
// for each line (transaction) until the end of file
while ((thisLine = myInput.readLine()) != null) {
// if the line is a comment, is empty or is a
// kind of metadata
if (thisLine.isEmpty() == true || thisLine.charAt(0) == '#'
|| thisLine.charAt(0) == '%'
|| thisLine.charAt(0) == '@') {
continue;
}
// split the line according to the separator
String split[] = thisLine.split(":");
// get the list of items
String items[] = split[0].split(" ");
// get the list of utility values corresponding to each item
// for that transaction
String utilityValues[] = split[2].split(" ");
// Create a list to store items and its utility
List<Pair> revisedTransaction = new ArrayList<Pair>();
// Create a list to store items
List<Integer> pattern = new ArrayList<Integer>();
// for each item
for (int i = 0; i < items.length; i++) {
// / convert values to integers
Pair pair = new Pair();
pair.item = Integer.parseInt(items[i]);
pair.utility = Integer.parseInt(utilityValues[i]);
// if the item has enough utility
if (mapItemToTWU.get(pair.item) >= minUtility) {
// add it
revisedTransaction.add(pair);
pattern.add(pair.item);
} else {
mapItemToTWU0.remove(pair.item);
}
}
// Copy the transaction into database but
// without items with TWU < minutility
database.add(revisedTransaction);
}
} catch (Exception e) {
// to catch error while reading the input file
e.printStackTrace();
} finally {
if (myInput != null) {
myInput.close();
}
}
twuPattern = new ArrayList<Integer>(mapItemToTWU0.keySet());//����������ݴ�list���б���
Collections.sort(twuPattern);//���ֵ�����
// System.out.println("twuPattern:"+twuPattern.size());
// System.out.println(twuPattern);
for (int i = 0; i < pop_size; ++i) {
//List<Particle> pBest = new ArrayList<Particle>();
pBest.add(new Particle(twuPattern.size()));
}
gBest = new Particle(twuPattern.size());
// check the memory usage
checkMemory();
// Mine the database recursively
if (twuPattern.size() > 0) {
// initial population
generatePop(minUtility);
for (int i = 0; i < iterations; i++) {
// System.out.println("gBest:"+gBest.fitness);
// System.out.println(gBest.X);
// update population and HUIset
update(minUtility);
// System.out.println(i + "-update end. HUIs No. is "
// + huiSets.size());
}
}
writeOut();
// check the memory usage again and close the file.
checkMemory();
// close output file
writer.close();
// record end time
endTimestamp = System.currentTimeMillis();
}
// value of each
// 1-HTWUIs in sum of
// twu value
/**
* This is the method to initial population
*
* @param minUtility minimum utility threshold
*/
private void generatePop(int minUtility)//
{
int i, j, k, temp;
// initial percentage according to the twu value of 1-HTWUIs
percentage = roulettePercent();
// System.out.println(percentage);
for (i = 0; i < pop_size; i++) {
// initial particles
Particle tempParticle = new Particle(twuPattern.size());
j = 0;
// k is the count of 1 in particle
k = (int) (Math.random() * twuPattern.size());
while (j < k) {
// roulette select the position of 1 in population
temp = rouletteSelect(percentage);
if (tempParticle.X.get(temp) == 0) {
j++;
tempParticle.X.set(temp, 1);
}
}
// calculate the fitness of each particle
tempParticle.fitness = fitCalculate(tempParticle.X, k);
// insert particle into population
population.add(i, tempParticle);
// initial pBest
//pBest.add(i, population.get(i));
pBest.get(i).copyParticle(tempParticle);
// update huiSets
if (population.get(i).fitness >= minUtility) {
insert(population.get(i));
}
// update gBest
if (i == 0) {
//gBest = pBest.get(i);
gBest.copyParticle(pBest.get(i));
} else {
if (pBest.get(i).fitness > gBest.fitness) {
gBest.copyParticle(pBest.get(i));
}
}
// update velocity
List<Double> tempV = new ArrayList<Double>();
for (j = 0; j < twuPattern.size(); j++) {
tempV.add(j, Math.random());
}
V.add(i, tempV);
}
}
/**
* Methos to update particle, velocity, pBest and gBest
*
* @param minUtility
*/
private void update(int minUtility) {
int i, j, k;
double r1, r2, temp1, temp2;
for (i = 0; i < pop_size; i++) {
k = 0;// record the count of 1 in particle
r1 = Math.random();
r2 = Math.random();
// update velocity
for (j = 0; j < twuPattern.size(); j++) {
double temp = V.get(i).get(j) + r1
* (pBest.get(i).X.get(j) - population.get(i).X.get(j))
+ r2 * (gBest.X.get(j) - population.get(i).X.get(j));
V.get(i).set(j, temp);
if (V.get(i).get(j) < -2.0)
V.get(i).set(j, -2.0);
else if (V.get(i).get(j) > 2.0)
V.get(i).set(j, 2.0);
}
// update particle
for (j = 0; j < twuPattern.size(); j++) {
temp1 = Math.random();
temp2 = 1 / (1.0 + Math.exp(-V.get(i).get(j)));
//System.out.println("temp1:"+temp1+" "+"temp2:"+temp2);
if (temp1 < temp2) {
population.get(i).X.set(j, 1);
k++;
} else {
population.get(i).X.set(j, 0);
}
}
// calculate fitness
population.get(i).fitness = fitCalculate(population.get(i).X, k);
// update pBest & gBest
if (population.get(i).fitness > pBest.get(i).fitness) {
//pBest.set(i, population.get(i));
pBest.get(i).copyParticle(population.get(i));
if (pBest.get(i).fitness > gBest.fitness) {
gBest.copyParticle(pBest.get(i));
}
}
// update huiSets
if (population.get(i).fitness >= minUtility) {
insert(population.get(i));
}
//System.out.println(population.get(i).X);
//System.out.println("fitness:"+population.get(i).fitness);
}
}
/**
* Method to inseret tempParticle to huiSets
*
* @param tempParticle the particle to be inserted
*/
private void insert(Particle tempParticle) {
int i;
StringBuilder temp = new StringBuilder();
for (i = 0; i < twuPattern.size(); i++) {
if (tempParticle.X.get(i) == 1) {
temp.append(twuPattern.get(i));
temp.append(' ');
}
}
// huiSets is null
if (huiSets.size() == 0) {
huiSets.add(new HUI(temp.toString(), tempParticle.fitness));
} else {
// huiSets is not null, judge whether exist an itemset in huiSets
// same with tempParticle
for (i = 0; i < huiSets.size(); i++) {
if (temp.toString().equals(huiSets.get(i).itemset)) {
break;
}
}
// if not exist same itemset in huiSets with tempParticle,insert it
// into huiSets
if (i == huiSets.size())
huiSets.add(new HUI(temp.toString(), tempParticle.fitness));
}
}
/**
* Method to initial percentage
*
* @return percentage
*/
private List<Double> roulettePercent() {
int i, sum = 0, tempSum = 0;
double tempPercent;
// calculate the sum of twu value of each 1-HTWUIs
for (i = 0; i < twuPattern.size(); i++) {
sum = sum + mapItemToTWU.get(twuPattern.get(i));
}
// calculate the portation of twu value of each item in sum
for (i = 0; i < twuPattern.size(); i++) {
tempSum = tempSum + mapItemToTWU.get(twuPattern.get(i));
tempPercent = tempSum / (sum + 0.0);
percentage.add(tempPercent);
}
return percentage;
}
/**
* Method to ensure the posotion of 1 in particle use roulette selection
*
* @param percentage the portation of twu value of each 1-HTWUIs in sum of twu
* value
* @return the position of 1
*/
private int rouletteSelect(List<Double> percentage) {
int i, temp = 0;
double randNum;
randNum = Math.random();
for (i = 0; i < percentage.size(); i++) {
if (i == 0) {
if ((randNum >= 0) && (randNum <= percentage.get(0))) {
temp = 0;
break;
}
} else if ((randNum > percentage.get(i - 1))
&& (randNum <= percentage.get(i))) {
temp = i;
break;
}
}
return temp;
}
/**
* Method to calculate the fitness of each particle
*
* @param tempParticle
* @param k the number of 1 in particle
* @return fitness
*/
private int fitCalculate(List<Integer> tempParticle, int k) {
if (k == 0)
return 0;
int i, j, p, q, temp;
int sum, fitness = 0;
for (p = 0; p < database.size(); p++) {// p scan the transactions in
// database
i = 0;
j = 0;
q = 0;
temp = 0;
sum = 0;
// j scan the 1 in particle, q scan each transaction, i scan each
// particle
while (j < k && q < database.get(p).size()
&& i < tempParticle.size()) {
if (tempParticle.get(i) == 1) {
if (database.get(p).get(q).item < twuPattern.get(i))
q++;
else if (database.get(p).get(q).item == twuPattern.get(i)) {
sum = sum + database.get(p).get(q).utility;
j++;
q++;
temp++;
i++;
} else if (database.get(p).get(q).item > twuPattern.get(i)) {
j++;
i++;
}
} else
i++;
}
if (temp == k) {
fitness = fitness + sum;
}
}
return fitness;
}
/**
* Method to write a high utility itemset to the output file.
*
* @throws IOException
*/
private void writeOut() throws IOException {
// Create a string buffer
StringBuilder buffer = new StringBuilder();
// append the prefix
for (int i = 0; i < huiSets.size(); i++) {
buffer.append(huiSets.get(i).itemset);
// append the utility value
buffer.append("#UTIL: ");
buffer.append(huiSets.get(i).fitness);
buffer.append(System.lineSeparator());
}
// write to file
writer.write(buffer.toString());
writer.newLine();
}
/**
* Method to check the memory usage and keep the maximum memory usage.
*/
private void checkMemory() {
// get the current memory usage
double currentMemory = (Runtime.getRuntime().totalMemory() - Runtime
.getRuntime().freeMemory()) / 1024d / 1024d;
// if higher than the maximum until now
if (currentMemory > maxMemory) {
// replace the maximum with the current memory usage
maxMemory = currentMemory;
}
}
/**
* Print statistics about the latest execution to System.out.
*/
public void printStats() {
System.out
.println("============= HUIM-BPSO ALGORITHM v.2.11 - STATS =============");
System.out.println(" Total time ~ " + (endTimestamp - startTimestamp)
+ " ms");
System.out.println(" Memory ~ " + maxMemory + " MB");
System.out.println(" High-utility itemsets count : " + huiSets.size());
System.out
.println("===================================================");
}
// this class represent an item and its utility in a transaction
class Pair {
int item = 0;
int utility = 0;
}
// this class represent the particles
class Particle {
List<Integer> X;// the particle
int fitness;// fitness value of particle
public Particle() {
X = new ArrayList<Integer>();
}
public Particle(int length) {
X = new ArrayList<Integer>();
for (int i = 0; i < length; i++) {
X.add(i, 0);
}
}
//��֮������
public void copyParticle(Particle particle1) {
for (int i = 0; i < particle1.X.size(); ++i) {
this.X.set(i, particle1.X.get(i).intValue());
}
this.fitness = particle1.fitness;
}
}
class HUI {
String itemset;
int fitness;
public HUI(String itemset, int fitness) {
super();
this.itemset = itemset;
this.fitness = fitness;
}
}
}
|
924602455bc8657f90fd53c52255dc05f93c1463
| 181 |
java
|
Java
|
gradle01/springboot-mybatis-02/src/main/java/org/tain/kang/UserMapper.java
|
grtlinux/KieaTomcat
|
1b8e05c86197437f26bb28bb9e4410a18082ae26
|
[
"Apache-2.0"
] | null | null | null |
gradle01/springboot-mybatis-02/src/main/java/org/tain/kang/UserMapper.java
|
grtlinux/KieaTomcat
|
1b8e05c86197437f26bb28bb9e4410a18082ae26
|
[
"Apache-2.0"
] | null | null | null |
gradle01/springboot-mybatis-02/src/main/java/org/tain/kang/UserMapper.java
|
grtlinux/KieaTomcat
|
1b8e05c86197437f26bb28bb9e4410a18082ae26
|
[
"Apache-2.0"
] | null | null | null | 18.1 | 69 | 0.729282 | 1,003,604 |
package org.tain.kang;
import java.util.List;
import java.util.Map;
public interface UserMapper {
public List<Map<String, Object>> selectUserList() throws Exception;
}
|
924602f6d92be660b5b225006e3c66e01bc122cb
| 2,451 |
java
|
Java
|
gemp-swccg-cards/src/main/java/com/gempukku/swccgo/cards/set14/dark/Card14_086.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/set14/dark/Card14_086.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/set14/dark/Card14_086.java
|
stevetotheizz0/gemp-swccg-public
|
05529086de91ecb03807fda820d98ec8a1465246
|
[
"MIT"
] | 21 |
2020-08-29T16:19:44.000Z
|
2022-03-29T01:37:39.000Z
| 48.058824 | 260 | 0.760914 | 1,003,605 |
package com.gempukku.swccgo.cards.set14.dark;
import com.gempukku.swccgo.cards.AbstractRepublic;
import com.gempukku.swccgo.cards.conditions.AtCondition;
import com.gempukku.swccgo.cards.conditions.WithCondition;
import com.gempukku.swccgo.cards.evaluators.PresentInBattleEvaluator;
import com.gempukku.swccgo.common.*;
import com.gempukku.swccgo.filters.Filters;
import com.gempukku.swccgo.game.PhysicalCard;
import com.gempukku.swccgo.game.SwccgGame;
import com.gempukku.swccgo.logic.conditions.Condition;
import com.gempukku.swccgo.logic.modifiers.AttritionModifier;
import com.gempukku.swccgo.logic.modifiers.DefenseValueModifier;
import com.gempukku.swccgo.logic.modifiers.Modifier;
import com.gempukku.swccgo.logic.modifiers.PowerModifier;
import java.util.LinkedList;
import java.util.List;
/**
* Set: Theed Palace
* Type: Character
* Subtype: Republic
* Title: Rune Haako, Legal Counsel
*/
public class Card14_086 extends AbstractRepublic {
public Card14_086() {
super(Side.DARK, 2, 3, 2, 3, 4, "Rune Haako, Legal Counsel", Uniqueness.UNIQUE);
setLore("The Trade Federation's only Neimoidian leader to have ever encountered a Jedi Knight. Assumed Daultay Dofine's responsibilities after Dofine questioned their Sith Lord's plans.");
setGameText("While at Theed Palace Throne Room, your attrition against opponent in battles at same and related Naboo sites is +X, where X = number of battle druids present at that site. While with a battle droid, Haako is power and defense value +2.");
addPersona(Persona.HAAKO);
addIcons(Icon.THEED_PALACE, Icon.EPISODE_I);
addKeywords(Keyword.LEADER);
setSpecies(Species.NEIMOIDIAN);
}
@Override
protected List<Modifier> getGameTextWhileActiveInPlayModifiers(SwccgGame game, final PhysicalCard self) {
Condition withBattleDroid = new WithCondition(self, Filters.battle_droid);
List<Modifier> modifiers = new LinkedList<Modifier>();
modifiers.add(new AttritionModifier(self, Filters.and(Filters.Naboo_site, Filters.sameOrRelatedSite(self)),
new AtCondition(self, Filters.Theed_Palace_Throne_Room), new PresentInBattleEvaluator(self, Filters.battle_droid),
game.getOpponent(self.getOwner())));
modifiers.add(new PowerModifier(self, withBattleDroid, 2));
modifiers.add(new DefenseValueModifier(self, withBattleDroid, 2));
return modifiers;
}
}
|
9246033c1506362bdde424c5cd858907a00cc153
| 7,158 |
java
|
Java
|
src/main/java/com/roamtech/uc/jainsip/UCSystemMsgClient.java
|
caibinglong1987/ucserver
|
68075a9e275bf26c17bf7a39305196803d572918
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/roamtech/uc/jainsip/UCSystemMsgClient.java
|
caibinglong1987/ucserver
|
68075a9e275bf26c17bf7a39305196803d572918
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/roamtech/uc/jainsip/UCSystemMsgClient.java
|
caibinglong1987/ucserver
|
68075a9e275bf26c17bf7a39305196803d572918
|
[
"Apache-2.0"
] | null | null | null | 35.107843 | 300 | 0.617844 | 1,003,606 |
package com.roamtech.uc.jainsip;
import com.roamtech.uc.client.rxevent.PurchaseDataTrafficEvent;
import com.roamtech.uc.jainsip.rxevent.KickOutEvent;
import com.roamtech.uc.jainsip.rxevent.SendMessageEvent;
import com.roamtech.uc.model.MsgPublish;
import com.roamtech.uc.repository.MsgPublishRepository;
import com.roamtech.uc.util.RxBus;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import rx.Observable;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import javax.sip.*;
import java.text.ParseException;
import java.util.List;
import java.util.TooManyListenersException;
import java.util.concurrent.TimeUnit;
/**
* Created by admin03 on 2016/8/27.
*/
@Component("ucSystemMsgClient")
public class UCSystemMsgClient implements MessageProcessor, InitializingBean {
private static final Logger LOG = LoggerFactory
.getLogger(UCSystemMsgClient.class);
private SipLayer sipLayer;
private String username;
private String displayName="络漫科技";
private String sipIp;
private Integer port;
private String proxy;
private String welcome="欢迎你使用漫话,我们将竭诚为你服务。我们作为全球互联网+移动通信领域的创新公司,致力于打造一张全新的全球互联网-移动通信网络。同时依托络漫全球通信云平台、络漫专利智能通讯硬件,为你带来全新的全球免费漫游通讯体验及综合性的全方位出境服务。如果在使用过程中有任何问题或建议,记得给我们反馈哦。";
private String publicproxy;
@Autowired
MsgPublishRepository msgRepo;
public void processMessage(String sender, String message) {
LOG.info("From " +
sender + ": " + message);
}
public void processError(String errorMessage) {
LOG.warn("ERROR: " +
errorMessage);
}
public void processInfo(String infoMessage) {
LOG.info(
infoMessage);
}
private String buildSipUri(String username,String domain,String userid) {
return "sip:" + username + "@" + domain + ";to=" + username + ";userid=" + userid;
}
@Override
public void afterPropertiesSet() throws Exception {
sipLayer = new SipLayer(username, sipIp, port);
sipLayer.setMessageProcessor(this);
LOG.info(displayName);
LOG.info(welcome);
Observable<SendMessageEvent> smeSubject = RxBus.getInstance().register(SendMessageEvent.class);
smeSubject.observeOn(Schedulers.io()).delay(3, TimeUnit.SECONDS).subscribe(new Action1<SendMessageEvent>() {
@Override
public void call(SendMessageEvent sme) {
try {
List<MsgPublish> msgs = msgRepo.findByType(sme.getType());
for(MsgPublish msg:msgs) {
String from = StringUtils.isBlank(sme.getFrom()) ? msg.getCaller() : sme.getFrom();
String callername = StringUtils.isBlank(sme.getDisplayname()) ? msg.getCallerName():sme.getDisplayname();
String message = StringUtils.isNotBlank(sme.getMessage()) ? sme.getMessage() : msg.getMessage();
getSipLayer().sendMessage(callername,
buildSipUri(from,publicproxy,sme.getUserid()),
buildSipUri(sme.getTo(),proxy,sme.getUserid()),
message);
}
} catch (ParseException e) {
LOG.warn("ParseException",e);
} catch (InvalidArgumentException e) {
LOG.warn("InvalidArgumentException",e);
} catch (SipException e) {
LOG.warn("SipException",e);
}
}
});
Observable<KickOutEvent> koeSubject = RxBus.getInstance().register(KickOutEvent.class);
koeSubject.observeOn(Schedulers.io()).subscribe(new Action1<KickOutEvent>() {
@Override
public void call(KickOutEvent koe) {
try {
getSipLayer().sendMessage(koe.getDisplayname(),
buildSipUri(koe.getFrom(),publicproxy,koe.getUserid()),
buildSipUri(koe.getTo(),proxy,koe.getUserid()),
koe.getMessage());
} catch (ParseException e) {
LOG.warn("ParseException",e);
} catch (InvalidArgumentException e) {
LOG.warn("InvalidArgumentException",e);
} catch (SipException e) {
LOG.warn("SipException",e);
}
}
});
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getSipIp() {
return sipIp;
}
public void setSipIp(String sipIp) {
this.sipIp = sipIp;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public void setSipLayer(SipLayer sipLayer) {
this.sipLayer = sipLayer;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public SipLayer getSipLayer() {
return sipLayer;
}
public String getProxy() {
return proxy;
}
public void setProxy(String proxy) {
this.proxy = proxy;
}
public String getWelcome() {
return welcome;
}
public void setWelcome(String welcome) {
this.welcome = welcome;
}
public String getPublicproxy() {
return publicproxy;
}
public void setPublicproxy(String publicproxy) {
this.publicproxy = publicproxy;
}
/*
public UCSystemMsgClient(String username, String ip, Integer port) {
try {
sipLayer = new SipLayer(username, ip, port);
} catch (PeerUnavailableException e) {
e.printStackTrace();
} catch (TransportNotSupportedException e) {
e.printStackTrace();
} catch (InvalidArgumentException e) {
e.printStackTrace();
} catch (ObjectInUseException e) {
e.printStackTrace();
} catch (TooManyListenersException e) {
e.printStackTrace();
}
sipLayer.setMessageProcessor(this);
}
public static void main(String[] args) {
UCSystemMsgClient client = new UCSystemMsgClient("roamtech", "192.168.0.4", 5060);
try {
client.sipLayer.sendMessage("络漫科技","sip:[email protected];to=roamtech;userid=1","sip:[email protected];to=roamtech;userid=1","欢迎你使用漫话,我们将竭诚为你服务。我们作为全球互联网+移动通信领域的创新公司,致力于打造一张全新的全球互联网-移动通信网络。同时依托络漫全球通信云平台、络漫专利智能通讯硬件,为你带来全新的全球免费漫游通讯体验及综合性的全方位出境服务。如果在使用过程中有任何问题或建议,记得给我们反馈哦。");
} catch (ParseException e) {
e.printStackTrace();
} catch (InvalidArgumentException e) {
e.printStackTrace();
} catch (SipException e) {
e.printStackTrace();
}
}
*/
}
|
92460461462331564bbc818dd8079245840373d8
| 6,951 |
java
|
Java
|
2048/src/Console2048.java
|
jonlee48/2048
|
488bf8fc6c82732f890db974a628f5c1263c5086
|
[
"MIT"
] | 1 |
2019-06-27T02:38:32.000Z
|
2019-06-27T02:38:32.000Z
|
2048/src/Console2048.java
|
jonlee48/2048
|
488bf8fc6c82732f890db974a628f5c1263c5086
|
[
"MIT"
] | null | null | null |
2048/src/Console2048.java
|
jonlee48/2048
|
488bf8fc6c82732f890db974a628f5c1263c5086
|
[
"MIT"
] | null | null | null | 24.475352 | 102 | 0.489858 | 1,003,607 |
//This version of 2048 runs in terminal
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Console2048 {
private int[][] board, boardCopy, testBoard;
ArrayList<Integer> empty = new ArrayList<Integer>();
private int score;
private final int SIZE;
public Console2048(int s) {
SIZE = s;
board = new int[SIZE][SIZE];
boardCopy = new int[SIZE][SIZE];
testBoard = new int[SIZE][SIZE];
}
public boolean addNum() // returns false if no room, else returns true
{
// first generate 2 or 4
int rand, row, col;
if (Math.random() < 0.9)
rand = 2;
else
rand = 4;
// create a list of all empty spaces
// clear it first
empty.clear();
for (int r = 0; r < SIZE; r++) {
for (int c = 0; c < SIZE; c++) {
if (board[r][c] == 0) {
empty.add(r);
empty.add(c);
}
}
}
if (empty.size() == 0)
return false;
// select random coordinates
int index = 2 * (int) (Math.random() * ((empty.size() - 2) / 2) + 0.5);
row = empty.get(index);
col = empty.get(index + 1);
board[row][col] = rand;
// for debugging -->
// System.out.println(row + ", " + col);
// System.out.println(Arrays.toString(empty.toArray()));
return true;
}
public void right(int[][] someBoard) {
for (int r = 0; r < SIZE; r++) {
int cap = SIZE; // place less than c
for (int c = SIZE - 2; c >= 0; c--) {
while (someBoard[r][c] != 0 && c != SIZE - 1 && c < cap
&& (someBoard[r][c + 1] == someBoard[r][c] || someBoard[r][c + 1] == 0)) // its not 0 and not in
// the last column
// and (its the same
// as the one to the
// right or equal to
// 0)
{
if (someBoard[r][c + 1] == 0) {
someBoard[r][c + 1] = someBoard[r][c];
someBoard[r][c] = 0;
c++;
} else if (someBoard[r][c] == someBoard[r][c + 1]) {
someBoard[r][c + 1] = someBoard[r][c] * 2;
score += someBoard[r][c + 1];
someBoard[r][c] = 0;
cap = c;
}
}
}
}
}
public void left(int[][] someBoard) {
for (int r = 0; r < SIZE; r++) {
int cap = -1;
for (int c = 1; c < SIZE; c++) {
while (someBoard[r][c] != 0 && c != 0 && c > cap
&& (someBoard[r][c - 1] == someBoard[r][c] || someBoard[r][c - 1] == 0)) // its not 0 and not in
// the last column
// and (its the same
// as the one to the
// right or equal to
// 0)
{
if (someBoard[r][c - 1] == 0) {
someBoard[r][c - 1] = someBoard[r][c];
someBoard[r][c] = 0;
c--;
} else if (someBoard[r][c] == someBoard[r][c - 1]) {
someBoard[r][c - 1] = someBoard[r][c] * 2;
score += someBoard[r][c - 1];
someBoard[r][c] = 0;
cap = c;
}
}
}
}
}
public void up(int[][] someBoard) {
for (int c = 0; c < SIZE; c++) {
int cap = -1;
for (int r = 1; r < SIZE; r++) {
while (someBoard[r][c] != 0 && r != 0 && r > cap
&& (someBoard[r - 1][c] == someBoard[r][c] || someBoard[r - 1][c] == 0)) // its not 0 and not in
// the last column
// and (its the same
// as the one to the
// right or equal to
// 0)
{
if (someBoard[r - 1][c] == 0) {
someBoard[r - 1][c] = someBoard[r][c];
someBoard[r][c] = 0;
r--;
} else if (someBoard[r][c] == someBoard[r - 1][c]) {
someBoard[r - 1][c] = someBoard[r][c] * 2;
score += someBoard[r - 1][c];
someBoard[r][c] = 0;
cap = r;
}
}
}
}
}
public void down(int[][] someBoard) {
for (int c = 0; c < SIZE; c++) {
int cap = SIZE; // place less than c
for (int r = SIZE - 2; r >= 0; r--) {
while (someBoard[r][c] != 0 && r != SIZE - 1 && r < cap
&& (someBoard[r + 1][c] == someBoard[r][c] || someBoard[r + 1][c] == 0)) // its not 0 and not in
// the last column
// and (its the same
// as the one to the
// right or equal to
// 0)
{
if (someBoard[r + 1][c] == 0) {
someBoard[r + 1][c] = someBoard[r][c];
someBoard[r][c] = 0;
r++;
} else if (someBoard[r][c] == someBoard[r + 1][c]) {
someBoard[r + 1][c] = someBoard[r][c] * 2;
score += someBoard[r + 1][c];
someBoard[r][c] = 0;
cap = r;
}
}
}
}
}
public void updateCopy() {
for (int r = 0; r < SIZE; r++) {
for (int c = 0; c < SIZE; c++) {
boardCopy[r][c] = board[r][c];
}
}
}
public boolean stateChange(int[][] someBoard, int[][] thisBoard) // returns true if changed
{
for (int r = 0; r < SIZE; r++) {
for (int c = 0; c < SIZE; c++) {
if (someBoard[r][c] != thisBoard[r][c])
return true;
}
}
return false;
}
public boolean gameOver() {
for (int r = 0; r < SIZE; r++) {
for (int c = 0; c < SIZE; c++) {
testBoard[r][c] = board[r][c];
}
}
int s = score;
// checks if any possible moves
right(testBoard);
if (stateChange(testBoard, board)) {
score = s;
return false;
}
left(testBoard);
if (stateChange(testBoard, board)) {
score = s;
return false;
}
up(testBoard);
if (stateChange(testBoard, board)) {
score = s;
return false;
}
down(testBoard);
if (stateChange(testBoard, board)) {
score = s;
return false;
}
score = s;
return true;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Swipe using 'WASD' keys");
System.out.println("Enter 'Q' to quit");
System.out.print("Enter board size: ");
int size = input.nextInt();
Console2048 game = new Console2048(size); // ENTER SIZE HERE
// add 2 seeds
game.addNum();
game.addNum();
while (true) {
game.updateCopy(); // creates identical board
for (int j = 0; j < game.SIZE; j++) {
System.out.println(Arrays.toString(game.board[j]));
}
String wasd = input.nextLine();
System.out.println("");
switch (wasd) {
case "w": {
game.up(game.board);
break;
}
case "a": {
game.left(game.board);
break;
}
case "s": {
game.down(game.board);
break;
}
case "d": {
game.right(game.board);
break;
}
}
if (wasd.equals("q"))
break;
// System.out.println(game.stateChange());
if (game.stateChange(game.boardCopy, game.board)) // if state changes, add num
{
game.addNum();
}
if (game.gameOver()) {
for (int j = 0; j < game.SIZE; j++) {
System.out.println(Arrays.toString(game.board[j]));
}
System.out.println("***Game Over***");
break;
}
System.out.println("Score: " + game.score);
}
input.close();
}
}
|
924605011649ac5eb5a17fe73cee414854f7e3e2
| 2,209 |
java
|
Java
|
src/core/plugin/monkey/win/device/BuilderDlg.java
|
OneLiteCore/MonkeyMaster
|
645e15a07dc147d8ac4a8ad4b180981aeee58997
|
[
"Apache-2.0"
] | 1 |
2022-02-09T01:21:30.000Z
|
2022-02-09T01:21:30.000Z
|
src/core/plugin/monkey/win/device/BuilderDlg.java
|
OneLiteCore/MonkeyMaster
|
645e15a07dc147d8ac4a8ad4b180981aeee58997
|
[
"Apache-2.0"
] | null | null | null |
src/core/plugin/monkey/win/device/BuilderDlg.java
|
OneLiteCore/MonkeyMaster
|
645e15a07dc147d8ac4a8ad4b180981aeee58997
|
[
"Apache-2.0"
] | null | null | null | 25.390805 | 89 | 0.637392 | 1,003,608 |
package core.plugin.monkey.win.device;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.awt.event.ActionEvent;
import java.util.Arrays;
import java.util.List;
import javax.swing.Action;
import javax.swing.JComponent;
import javax.swing.JPanel;
import core.plugin.monkey.core.Monkey;
import core.plugin.monkey.util.Callback;
import core.plugin.monkey.util.SimpleCallback;
import core.plugin.monkey.win.base.BaseDlg;
/**
* @author DrkCore
* @since 2017-01-28
*/
public class BuilderDlg extends BaseDlg {
public interface ConfigPanel {
void adapt(Monkey.Builder config);
void apply(Monkey.Builder config);
}
private JPanel contentPanel;
private GeneralPanel generalPanel;
private DebugPanel debugPanel;
private EventPanel eventPanel;
private List<ConfigPanel> panels;
private final Monkey.Builder config;
public BuilderDlg() {
this(null);
}
public BuilderDlg(@Nullable Monkey.Builder config) {
super("Config Monkey Runner");
this.config = config != null ? config.clone() : new Monkey.Builder();
panels = Arrays.asList(generalPanel, debugPanel, eventPanel);
panels.forEach(configPanel -> configPanel.adapt(BuilderDlg.this.config));
}
private Callback<Monkey.Builder> callback;
public BuilderDlg setCallback(Callback<Monkey.Builder> callback) {
this.callback = callback;
return this;
}
@NotNull
@Override
protected Action[] createActions() {
return new Action[]{new DialogWrapperAction("Run") {
@SuppressWarnings("unchecked")
@Override
protected void doAction(ActionEvent actionEvent) {
dispose();
panels.forEach(configPanel -> configPanel.apply(BuilderDlg.this.config));
SimpleCallback.call(config, callback);
}
}, getCancelAction()};
}
@Nullable
@Override
protected JComponent createCenterPanel() {
return contentPanel;
}
}
|
92460531ce6fe0f22b1c3040895217bedafc53c9
| 890 |
java
|
Java
|
src/main/java/org/dimdev/vanillafix/dynamicresources/modsupport/mixins/client/MixinMagicStitchingSprite.java
|
democat3457/VanillaFix
|
51790666e0390204cd93e3543d75535564af51cf
|
[
"MIT"
] | 198 |
2018-04-26T05:46:54.000Z
|
2022-02-06T14:08:55.000Z
|
src/main/java/org/dimdev/vanillafix/dynamicresources/modsupport/mixins/client/MixinMagicStitchingSprite.java
|
democat3457/VanillaFix
|
51790666e0390204cd93e3543d75535564af51cf
|
[
"MIT"
] | 325 |
2018-04-26T16:41:28.000Z
|
2022-03-21T08:18:59.000Z
|
src/main/java/org/dimdev/vanillafix/dynamicresources/modsupport/mixins/client/MixinMagicStitchingSprite.java
|
democat3457/VanillaFix
|
51790666e0390204cd93e3543d75535564af51cf
|
[
"MIT"
] | 64 |
2018-05-06T05:52:40.000Z
|
2022-03-26T17:11:57.000Z
| 35.6 | 91 | 0.797753 | 1,003,609 |
package org.dimdev.vanillafix.dynamicresources.modsupport.mixins.client;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Pseudo;
import org.spongepowered.asm.mixin.Shadow;
import team.chisel.client.TextureStitcher;
@Pseudo
@Mixin(TextureStitcher.MagicStitchingSprite.class)
@SuppressWarnings("deprecation")
public abstract class MixinMagicStitchingSprite extends TextureAtlasSprite {
@Shadow abstract void postStitch();
@Shadow private TextureAtlasSprite parent;
@Overwrite(remap = false)
public MixinMagicStitchingSprite(String spriteName) {
super(spriteName);
parent = Minecraft.getMinecraft().getTextureMapBlocks().getAtlasSprite(spriteName);
postStitch();
}
}
|
9246058010f15de4f69a9187c45a407c0f2dc5ad
| 1,804 |
java
|
Java
|
base/src/com/google/idea/blaze/base/run/filter/StandardFileResolver.java
|
ricebin/intellij
|
33f15b87476cea7b2e006f51027526d97ceffc89
|
[
"Apache-2.0"
] | 675 |
2016-07-11T15:24:50.000Z
|
2022-03-21T20:35:53.000Z
|
base/src/com/google/idea/blaze/base/run/filter/StandardFileResolver.java
|
ricebin/intellij
|
33f15b87476cea7b2e006f51027526d97ceffc89
|
[
"Apache-2.0"
] | 1,327 |
2016-07-11T20:30:17.000Z
|
2022-03-30T18:57:25.000Z
|
base/src/com/google/idea/blaze/base/run/filter/StandardFileResolver.java
|
ricebin/intellij
|
33f15b87476cea7b2e006f51027526d97ceffc89
|
[
"Apache-2.0"
] | 262 |
2016-07-11T17:51:01.000Z
|
2022-03-21T09:05:19.000Z
| 32.8 | 98 | 0.73337 | 1,003,610 |
/*
* Copyright 2016 The Bazel Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.idea.blaze.base.run.filter;
import com.google.idea.blaze.base.model.BlazeProjectData;
import com.google.idea.blaze.base.sync.data.BlazeProjectDataManager;
import com.intellij.openapi.project.Project;
import java.io.File;
import java.io.IOException;
import javax.annotation.Nullable;
/** Parses absolute and workspace-relative paths. */
public class StandardFileResolver implements FileResolver {
@Nullable
@Override
public File resolve(Project project, String fileString) {
File file = new File(fileString);
if (file.isAbsolute()) {
return new File(getCanonicalPathSafe(file));
}
BlazeProjectData projectData =
BlazeProjectDataManager.getInstance(project).getBlazeProjectData();
if (projectData == null) {
return null;
}
return projectData.getWorkspacePathResolver().resolveToFile(fileString);
}
/**
* Swallows {@link IOException}s, falling back to returning the absolute, possibly non-canonical
* path.
*/
private static String getCanonicalPathSafe(File file) {
try {
return file.getCanonicalPath();
} catch (IOException e) {
return file.getAbsolutePath();
}
}
}
|
92460606ce310fcc7556824b91ebbd94cc0ac687
| 533 |
java
|
Java
|
hi/src/com/mvc/service/SysMenuService.java
|
gaoyibing111/gao
|
9e9a15ef9f4e94fa5ced3faf42b9d74fd1de592f
|
[
"Apache-2.0"
] | null | null | null |
hi/src/com/mvc/service/SysMenuService.java
|
gaoyibing111/gao
|
9e9a15ef9f4e94fa5ced3faf42b9d74fd1de592f
|
[
"Apache-2.0"
] | null | null | null |
hi/src/com/mvc/service/SysMenuService.java
|
gaoyibing111/gao
|
9e9a15ef9f4e94fa5ced3faf42b9d74fd1de592f
|
[
"Apache-2.0"
] | null | null | null | 22.208333 | 62 | 0.757974 | 1,003,611 |
package com.mvc.service;
import java.util.List;
import org.springframework.stereotype.Service;
import com.mvc.domain.PageBean;
import com.mvc.domain.SysMenu;
@Service(value="sysMenuService")
public interface SysMenuService {
/*List<SysMenu> findAllPage(PageBean page,SysMenu sysMenu);*/
List<SysMenu> findAll();
/* public Long getTotal(PageBean page);*/
List<SysMenu> findByChildId(List<String> menuId);
void save(SysMenu menu);
/* List<SysMenu> findAllChi();*/
void update(SysMenu menu);
void delete(String menuId);
}
|
9246060982ae8a9fc5b542b10232de3fe0affdab
| 250 |
java
|
Java
|
openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/Revision.java
|
infosiftr/sdc
|
a1f23ec5e7cd191b76271b5f33c237bad38c61c6
|
[
"Apache-2.0"
] | null | null | null |
openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/Revision.java
|
infosiftr/sdc
|
a1f23ec5e7cd191b76271b5f33c237bad38c61c6
|
[
"Apache-2.0"
] | null | null | null |
openecomp-be/lib/openecomp-sdc-versioning-lib/openecomp-sdc-versioning-api/src/main/java/org/openecomp/sdc/versioning/dao/types/Revision.java
|
infosiftr/sdc
|
a1f23ec5e7cd191b76271b5f33c237bad38c61c6
|
[
"Apache-2.0"
] | null | null | null | 16.666667 | 47 | 0.768 | 1,003,612 |
package org.openecomp.sdc.versioning.dao.types;
import lombok.Getter;
import lombok.Setter;
import java.util.Date;
@Getter
@Setter
public class Revision {
private String id;
private String message;
private Date time;
private String user;
}
|
9246062d4e4ae71009ef3d6426de45b768017de4
| 2,006 |
java
|
Java
|
examples/net/andreinc/mockneat/github/GenerateMonths.java
|
lazycodeninja/mockneat
|
2d1ec8dbb484784501f504d34bb6b38d92e1aeff
|
[
"Apache-2.0"
] | null | null | null |
examples/net/andreinc/mockneat/github/GenerateMonths.java
|
lazycodeninja/mockneat
|
2d1ec8dbb484784501f504d34bb6b38d92e1aeff
|
[
"Apache-2.0"
] | null | null | null |
examples/net/andreinc/mockneat/github/GenerateMonths.java
|
lazycodeninja/mockneat
|
2d1ec8dbb484784501f504d34bb6b38d92e1aeff
|
[
"Apache-2.0"
] | null | null | null | 39.333333 | 125 | 0.715354 | 1,003,613 |
package net.andreinc.mockneat.github;
/**
* Copyright 2017, Andrei N. Ciobanu
Permission is hereby granted, free of charge, to any user 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. PARAM NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER PARAM AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, FREE_TEXT OF OR PARAM CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS PARAM THE SOFTWARE.
*/
import net.andreinc.mockneat.MockNeat;
import java.time.Month;
import java.time.format.TextStyle;
import java.util.Locale;
import static java.time.Month.AUGUST;
import static java.time.Month.JULY;
import static java.time.Month.JUNE;
public class GenerateMonths {
public static void main(String[] args) {
MockNeat mock = MockNeat.threadLocal();
Month m = mock.months().val();
System.out.println(m);
Month summer = mock.months().rangeClosed(JUNE, AUGUST).val();
System.out.println(summer);
Month beforeSummer = mock.months().before(JUNE).val();
System.out.println(beforeSummer);
String month = mock.months()
.before(JULY)
.display(TextStyle.FULL, Locale.CANADA)
.val();
System.out.println(month);
}
}
|
9246073d36b90790622f43f2eba1607638aae0ac
| 821 |
java
|
Java
|
src/main/java/xyz/morecraft/dev/scp/security/util/Security.java
|
EmhyrVarEmreis/SimpleCurrencyPredicator
|
df51be52492eb6bdf9d6fd3ad38bd14c9993b50b
|
[
"MIT"
] | null | null | null |
src/main/java/xyz/morecraft/dev/scp/security/util/Security.java
|
EmhyrVarEmreis/SimpleCurrencyPredicator
|
df51be52492eb6bdf9d6fd3ad38bd14c9993b50b
|
[
"MIT"
] | null | null | null |
src/main/java/xyz/morecraft/dev/scp/security/util/Security.java
|
EmhyrVarEmreis/SimpleCurrencyPredicator
|
df51be52492eb6bdf9d6fd3ad38bd14c9993b50b
|
[
"MIT"
] | null | null | null | 27.366667 | 71 | 0.706456 | 1,003,614 |
package xyz.morecraft.dev.scp.security.util;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import xyz.morecraft.dev.scp.dao.User;
import xyz.morecraft.dev.scp.security.UserDetailsWrapper;
import java.util.Optional;
/**
* Provides security util.
*/
public class Security {
private Security() {
}
public static User currentUser() {
return Optional.ofNullable(SecurityContextHolder.getContext())
.map(SecurityContext::getAuthentication)
.map(Authentication::getPrincipal)
.map(UserDetailsWrapper.class::cast)
.map(UserDetailsWrapper::getUser)
.orElse(null);
}
}
|
92460821a4b2617a7c7282668f15a0543b873be2
| 4,229 |
java
|
Java
|
src/IR_project1/Main.java
|
alexPlessias/IR-TF-IDF
|
8d3f851b5a16d06f1a3bd2567285fc8c2a705f2b
|
[
"MIT"
] | null | null | null |
src/IR_project1/Main.java
|
alexPlessias/IR-TF-IDF
|
8d3f851b5a16d06f1a3bd2567285fc8c2a705f2b
|
[
"MIT"
] | null | null | null |
src/IR_project1/Main.java
|
alexPlessias/IR-TF-IDF
|
8d3f851b5a16d06f1a3bd2567285fc8c2a705f2b
|
[
"MIT"
] | null | null | null | 39.523364 | 182 | 0.634192 | 1,003,615 |
/**
* @author Πλέσσιας Αλέξανδρος (ΑΜ.:2025201100068).
*/
package IR_project1;
import Files.Question1And4_1;
import Files.Question2And4_2;
import Files.Question3And4_3;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.util.TreeMap;
/**
* Main get input from user create dictionary, all users dictionaries,
* calculate idfs and execute all the questions of exercise.
* Also in comments exist helpful functions.
*/
public class Main {
public static void main(String[] args) {
String folderName = "papers";
HashMap<String, TreeMap<String, ArrayList<Float>>> allMembersDictionary;
// All DEP memebers dictionaries in one HashMap.
AllMembersDictionaries AllMembersDictionariesObject = new AllMembersDictionaries(folderName);
allMembersDictionary = AllMembersDictionariesObject.getAllDEPmembesrDictionary(); // Initialize.
Dictionary dictionaryObject = new Dictionary(allMembersDictionary);
TreeMap<String, ArrayList<String>> dictionary = dictionaryObject.getDictionary(); // Inverted index. terms->{DEPmember name,DEPmember name, ... ,DEPmember name } .
//dictionaryObject.printDictionary();
TreeMap<String, Float> allTermsIDF = dictionaryObject.getAllTermsIDF(); // Create idfs array for futere use.
//dictionaryObject.printIDFs();
//Create VSMs for each DEP memeber.
CreateVSMs AllMembersVSMs = new CreateVSMs(allMembersDictionary, dictionary);
allMembersDictionary = AllMembersVSMs.getVSMs(); // Overwrite.
//AllMembersVSMs.printVSMs();
//Calculate all tf and tf-idf.
CalcUsefullMetrics AllMembersUsefullMetricsObject = new CalcUsefullMetrics(allMembersDictionary, allTermsIDF);
allMembersDictionary = AllMembersUsefullMetricsObject.getUsefullMetrics(); //Overwrite aqain.
// Create Results directory..
File resultsFile = new File("Results");
resultsFile.mkdirs();
// Get input from user.
String userQuery = "";
int N;
int M;
try (Scanner scan = new Scanner(System.in)) {
System.out.println("Please, give a query:");
while (scan.hasNextLine()) {
String temp = scan.nextLine();
userQuery = userQuery + temp;
if (!scan.equals("\\n")) {
break;
}
}
System.out.println("Please, give N value:");
N = scan.nextInt(); // The fist N-impotant elements.
System.out.println("Please give M value (from 1-25):");
M = scan.nextInt(); // The first M-impotant colleagues for each member.
scan.close();
}
System.out.println();
// Question 1 & Question 4_1.
Question1And4_1 question1And4_1 = new Question1And4_1(N, resultsFile, allMembersDictionary);
question1And4_1.doQuenstion1();
question1And4_1.doQuenstion4_1();
// Question 2 & Question 4_2.
Question2And4_2 question2And4_2 = new Question2And4_2(resultsFile, userQuery, dictionary, allTermsIDF, allMembersDictionary);
question2And4_2.doQuenstion2();
question2And4_2.doQuenstion4_2();
// Question 3 & Question 4_3.
Question3And4_3 question3And4_3 = new Question3And4_3(M, resultsFile, allMembersDictionary);
System.out.println("Now wait for ~18 seconds(it depends on the system) for Quenstion3... ");
question3And4_3.doQuestion3();
//question3And4_3.saveArrayOfQuestion3();
System.out.println("Now wait for another ~20 seconds(it depends on the system) for Quenstion4_3... ");
question3And4_3.doQuestion4_3();
//question3And4_3.saveArrayOfQuestion4_3();
System.out.println();
System.out.println("See the results in Project's folder Results.");
System.out.println("Goodbye!!! Have a nice day.");
System.exit(0);
// Write the Report .
}
}
|
9246087ecac3e0d3e214af3fa42b7617554a39de
| 1,146 |
java
|
Java
|
UnofficialProjects/TelerikAcademySchedule/app/src/main/java/lab/chabingba/telerikacademyschedule/LogoActivity.java
|
TsvetanMilanov/AndroidApplications
|
7c4b33491920aec05ba25685d8cbf17dace38f1a
|
[
"MIT"
] | null | null | null |
UnofficialProjects/TelerikAcademySchedule/app/src/main/java/lab/chabingba/telerikacademyschedule/LogoActivity.java
|
TsvetanMilanov/AndroidApplications
|
7c4b33491920aec05ba25685d8cbf17dace38f1a
|
[
"MIT"
] | 1 |
2015-05-20T22:46:32.000Z
|
2015-05-20T22:46:32.000Z
|
UnofficialProjects/TelerikAcademySchedule/app/src/main/java/lab/chabingba/telerikacademyschedule/LogoActivity.java
|
TsvetanMilanov/AndroidApplications
|
7c4b33491920aec05ba25685d8cbf17dace38f1a
|
[
"MIT"
] | null | null | null | 27.285714 | 89 | 0.568935 | 1,003,616 |
package lab.chabingba.telerikacademyschedule;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;
public class LogoActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.logo_layout);
ImageView imageView = (ImageView) findViewById(R.id.imageLogo);
imageView.setImageResource(R.drawable.logo_edited);
Thread logoThread = new Thread() {
public void run() {
try {
// TODO: return to 1000/1500.
sleep(0);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Intent startMain = new Intent(LogoActivity.this, MainActivity.class);
startActivity(startMain);
finish();
}
}
};
logoThread.start();
}
@Override
protected void onPause() {
super.onPause();
finish();
}
}
|
924608c08bb22aa07a08c7b51b63ae8ea85e8059
| 479 |
java
|
Java
|
Milkomeda/src/main/java/com/github/yizzuide/milkomeda/wormhole/WormholeHolder.java
|
chingov/Milkomeda
|
3249df53b101d4fac3c93e325435a8a0564e31ee
|
[
"MIT"
] | 2 |
2019-12-19T11:28:45.000Z
|
2019-12-19T11:28:50.000Z
|
Milkomeda/src/main/java/com/github/yizzuide/milkomeda/wormhole/WormholeHolder.java
|
monkSweeping/Milkomeda
|
1c04539e0901d8c87eb5d133e0a27d536a8adcc5
|
[
"MIT"
] | null | null | null |
Milkomeda/src/main/java/com/github/yizzuide/milkomeda/wormhole/WormholeHolder.java
|
monkSweeping/Milkomeda
|
1c04539e0901d8c87eb5d133e0a27d536a8adcc5
|
[
"MIT"
] | 1 |
2020-09-21T06:08:38.000Z
|
2020-09-21T06:08:38.000Z
| 18.423077 | 56 | 0.661795 | 1,003,617 |
package com.github.yizzuide.milkomeda.wormhole;
/**
* WormholeHolder
*
* @author yizzuide
* @since 3.3.0
* Create at 2020/05/05 14:52
*/
public class WormholeHolder {
private static WormholeEventBus eventBus;
static void setEventBus(WormholeEventBus eventBus) {
WormholeHolder.eventBus = eventBus;
}
/**
* 获取领域事件总线
* @return WormholeEventBus
*/
public static WormholeEventBus getEventBus() {
return eventBus;
}
}
|
924608fb13dd1977c8f54cdf8aa8dddec6f5e250
| 3,452 |
java
|
Java
|
server/node/src/main/java/org/kaaproject/kaa/server/admin/client/mvp/activity/LogSchemasActivity.java
|
MiddlewareICS/kaa
|
65c02e847d6019e4afb20fbfb03c3416e0972908
|
[
"ECL-2.0",
"Apache-2.0"
] | 2 |
2019-08-27T10:45:57.000Z
|
2019-08-30T06:21:04.000Z
|
server/node/src/main/java/org/kaaproject/kaa/server/admin/client/mvp/activity/LogSchemasActivity.java
|
MiddlewareICS/kaa
|
65c02e847d6019e4afb20fbfb03c3416e0972908
|
[
"ECL-2.0",
"Apache-2.0"
] | 8 |
2020-01-31T18:26:22.000Z
|
2022-01-21T23:34:19.000Z
|
server/node/src/main/java/org/kaaproject/kaa/server/admin/client/mvp/activity/LogSchemasActivity.java
|
MiddlewareICS/kaa
|
65c02e847d6019e4afb20fbfb03c3416e0972908
|
[
"ECL-2.0",
"Apache-2.0"
] | 1 |
2019-11-24T07:01:26.000Z
|
2019-11-24T07:01:26.000Z
| 36.723404 | 99 | 0.756083 | 1,003,618 |
/*
* Copyright 2014-2016 CyberVision, 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.
*/
package org.kaaproject.kaa.server.admin.client.mvp.activity;
import com.google.gwt.place.shared.Place;
import com.google.gwt.user.client.rpc.AsyncCallback;
import org.kaaproject.avro.ui.gwt.client.widget.grid.AbstractGrid;
import org.kaaproject.avro.ui.gwt.client.widget.grid.event.RowActionEvent;
import org.kaaproject.kaa.common.dto.admin.RecordKey.RecordFiles;
import org.kaaproject.kaa.common.dto.logs.LogSchemaDto;
import org.kaaproject.kaa.server.admin.client.KaaAdmin;
import org.kaaproject.kaa.server.admin.client.mvp.ClientFactory;
import org.kaaproject.kaa.server.admin.client.mvp.activity.grid.AbstractDataProvider;
import org.kaaproject.kaa.server.admin.client.mvp.data.LogSchemasDataProvider;
import org.kaaproject.kaa.server.admin.client.mvp.place.LogSchemaPlace;
import org.kaaproject.kaa.server.admin.client.mvp.place.LogSchemasPlace;
import org.kaaproject.kaa.server.admin.client.mvp.view.BaseListView;
import org.kaaproject.kaa.server.admin.client.mvp.view.grid.KaaRowAction;
import org.kaaproject.kaa.server.admin.client.servlet.ServletHelper;
import org.kaaproject.kaa.server.admin.client.util.Utils;
public class LogSchemasActivity
extends AbstractBaseCtlSchemasActivity<LogSchemaDto, LogSchemasPlace> {
private String applicationId;
public LogSchemasActivity(LogSchemasPlace place, ClientFactory clientFactory) {
super(place, LogSchemaDto.class, clientFactory);
this.applicationId = place.getApplicationId();
}
@Override
protected BaseListView<LogSchemaDto> getView() {
return clientFactory.getLogSchemasView();
}
@Override
protected AbstractDataProvider<LogSchemaDto, String> getDataProvider(
AbstractGrid<LogSchemaDto, String> dataGrid) {
return new LogSchemasDataProvider(dataGrid, listView, applicationId);
}
@Override
protected Place newEntityPlace() {
return new LogSchemaPlace(applicationId, "");
}
@Override
protected Place existingEntityPlace(String id) {
return new LogSchemaPlace(applicationId, id);
}
@Override
protected void deleteEntity(String id, AsyncCallback<Void> callback) {
callback.onSuccess((Void) null);
}
@Override
protected void onCustomRowAction(RowActionEvent<String> event) {
super.onCustomRowAction(event);
Integer schemaVersion = Integer.valueOf(event.getClickedId());
if (event.getAction() == KaaRowAction.DOWNLOAD_LOG_SCHEMA_LIBRARY) {
KaaAdmin.getDataSource().getRecordData(applicationId, schemaVersion, RecordFiles.LOG_LIBRARY,
new AsyncCallback<String>() {
@Override
public void onFailure(Throwable caught) {
Utils.handleException(caught, listView);
}
@Override
public void onSuccess(String key) {
ServletHelper.downloadRecordLibrary(key);
}
});
}
}
}
|
92460a0522eac314d9e247ff325219168bfe265c
| 391 |
java
|
Java
|
src/main/java/org/happydev/core/model/event/Participant.java
|
AnnieOmsk/it-conference
|
93511455626e7ee37f2eb8d29d23a879a8bc5f1f
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/org/happydev/core/model/event/Participant.java
|
AnnieOmsk/it-conference
|
93511455626e7ee37f2eb8d29d23a879a8bc5f1f
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/org/happydev/core/model/event/Participant.java
|
AnnieOmsk/it-conference
|
93511455626e7ee37f2eb8d29d23a879a8bc5f1f
|
[
"Apache-2.0"
] | null | null | null | 23 | 49 | 0.769821 | 1,003,619 |
package org.happydev.core.model.event;
import org.happydev.core.model.AbstractEntity;
import org.happydev.core.model.Picture;
import org.happydev.core.model.social.User;
/**
* A participant of the concrete Event
*/
public class Participant extends AbstractEntity {
private User user;
private HallEvent hallEvent;
private String selfDescription;
private Picture photo;
}
|
92460a9d8ec858fe5915a74f09048248801daa2b
| 655 |
java
|
Java
|
src/LuoGu/P1030.java
|
kid1999/Algorithmic-training
|
7bb246ecfa6907c7f4b9a1fb2774ad75ce110673
|
[
"MIT"
] | 2 |
2019-09-16T03:56:16.000Z
|
2019-10-12T03:30:37.000Z
|
src/LuoGu/P1030.java
|
kid1999/Algorithmic-training
|
7bb246ecfa6907c7f4b9a1fb2774ad75ce110673
|
[
"MIT"
] | null | null | null |
src/LuoGu/P1030.java
|
kid1999/Algorithmic-training
|
7bb246ecfa6907c7f4b9a1fb2774ad75ce110673
|
[
"MIT"
] | null | null | null | 27.291667 | 80 | 0.603053 | 1,003,620 |
package LuoGu;
import java.util.Scanner;
public class P1030 {
static String mid;
static String last;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
mid = sc.next();
last = sc.next();
dfs(0,mid.length()-1,0,last.length()-1);
}
public static void dfs(int l1,int r1,int l2,int r2){
if(l1>r1) return;
System.out.print(last.charAt(r2)); // 先序遍历 直接输出节点
int index = l1;
while (mid.charAt(index) != last.charAt(r2)) index++; //找到中序的切分点 分为左子树和右子数
int count = index-l1; //
dfs(l1,index-1,l2,l2+count-1); // 左子树
dfs(index+1,r1,l2+count,r2-1); // 右子树
}
}
|
92460b47a93bbc41ba52ee0bff0372a5d02705c4
| 1,179 |
java
|
Java
|
src/main/java/au/gov/nehta/model/clinical/etp/prescriptionrequest/PrescriberInstructionDetail.java
|
AuDigitalHealth/clinical-document-library-java
|
217483c9a2dc18aa7aa262bb22a7175888550839
|
[
"Apache-2.0"
] | 5 |
2019-08-13T13:58:36.000Z
|
2021-12-07T07:45:57.000Z
|
src/main/java/au/gov/nehta/model/clinical/etp/prescriptionrequest/PrescriberInstructionDetail.java
|
AuDigitalHealth/clinical-document-library-java
|
217483c9a2dc18aa7aa262bb22a7175888550839
|
[
"Apache-2.0"
] | 1 |
2020-04-27T02:22:19.000Z
|
2020-04-27T02:22:19.000Z
|
src/main/java/au/gov/nehta/model/clinical/etp/prescriptionrequest/PrescriberInstructionDetail.java
|
AuDigitalHealth/clinical-document-library-java
|
217483c9a2dc18aa7aa262bb22a7175888550839
|
[
"Apache-2.0"
] | 4 |
2019-10-24T03:48:01.000Z
|
2022-03-14T13:21:08.000Z
| 36.84375 | 104 | 0.806616 | 1,003,621 |
/*
* Copyright 2011 NEHTA
*
* Licensed under the NEHTA Open Source (Apache) License; you may not use this
* file except in compliance with the License. A copy of the License is in the
* 'license.txt' file, which should be provided with this work.
*
* 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 au.gov.nehta.model.clinical.etp.prescriptionrequest;
import java.time.ZonedDateTime;
import au.gov.nehta.model.clinical.etp.common.participation.PrescriberInstructionRecipientParticipation;
public interface PrescriberInstructionDetail {
PrescriberInstructionRecipientParticipation getPrescriberInstructionRecipient();
ZonedDateTime getDateTimePrescriberInstructionReceived();
String getPrescriberInstruction();
PrescriberInstructionSource getPrescriberInstructionSource();
PrescriberInstructionCommunicationMedium getPrescriberInstructionCommunicationMedium();
}
|
92460b8b71e6c7c84ad58c7779919fa6dd335282
| 9,657 |
java
|
Java
|
RealVirtualIntegration/RealVirtualSensorSimulator/src/com/cyberlightning/realvirtualsensorsimulator/views/SettingsViewFragment.java
|
Cyberlightning/Cyber-WeX
|
11dc560b7a30eb31c1dfa18196f6a0760648f9a7
|
[
"Apache-2.0"
] | 2 |
2015-11-04T10:21:48.000Z
|
2016-03-07T15:14:35.000Z
|
RealVirtualIntegration/RealVirtualSensorSimulator/src/com/cyberlightning/realvirtualsensorsimulator/views/SettingsViewFragment.java
|
Cyberlightning/Cyber-WeX
|
11dc560b7a30eb31c1dfa18196f6a0760648f9a7
|
[
"Apache-2.0"
] | null | null | null |
RealVirtualIntegration/RealVirtualSensorSimulator/src/com/cyberlightning/realvirtualsensorsimulator/views/SettingsViewFragment.java
|
Cyberlightning/Cyber-WeX
|
11dc560b7a30eb31c1dfa18196f6a0760648f9a7
|
[
"Apache-2.0"
] | null | null | null | 40.746835 | 144 | 0.751476 | 1,003,622 |
package com.cyberlightning.realvirtualsensorsimulator.views;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import com.cyberlightning.realvirtualsensorsimulator.ClientSocket;
import com.cyberlightning.realvirtualsensorsimulator.MainActivity;
import com.cyberlightning.realvirtualsensorsimulator.SensorListener;
import com.cyberlightning.realvirtualsensorsimulator.staticresources.JsonParser;
import com.example.realvirtualsensorsimulator.R;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
public class SettingsViewFragment extends Fragment implements OnClickListener {
private Button saveButton;
private Button exitButton;
private Button resetButton;
private CheckBox gpsCheckBox;
private EditText addressTextField;
private EditText intervalTextField;
private EditText portTextField;
private EditText locationTextField;
private LinearLayout sensorListLeft;
private LinearLayout sensorListRight;
private LinearLayout settingsFragmentView;
private Set<String> defaultValues;
private String address;
private String location;
private int port;
private long interval;
public static final String PREFS_NAME = "RealVirtualInteraction";
public static final String SHARED_SENSORS = "Sensors";
public static final String SHARED_ADDRESS = "ServerAddress";
public static final String SHARED_PORT = "ServerPort";
public static final String SHARED_INTERVAL = "EventInterval";
public static final String SHARED_LOCATION = "ContextualLocation";
public static final String SHARED_GPS = "GpsLocation";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (((MainActivity)getActivity()).isLandScape)this.settingsFragmentView = (LinearLayout) inflater.inflate(R.layout.settings_landscape , null);
else this.settingsFragmentView = (LinearLayout) inflater.inflate(R.layout.settings , null);
this.sensorListLeft = (LinearLayout) this.settingsFragmentView.findViewById(R.id.settings_sensorlist_left);
this.sensorListRight = (LinearLayout) this.settingsFragmentView.findViewById(R.id.settings_sensorlist_right);
this.addressTextField = (EditText) this.settingsFragmentView.findViewById(R.id.settings_address);
this.portTextField = (EditText) this.settingsFragmentView.findViewById(R.id.settings_port);
this.intervalTextField = (EditText) this.settingsFragmentView.findViewById(R.id.settings_interval);
this.resetButton = (Button) this.settingsFragmentView.findViewById(R.id.settings_button_reset);
this.resetButton.setOnClickListener(this);
this.exitButton = (Button) this.settingsFragmentView.findViewById(R.id.settings_button_exit);
this.exitButton.setOnClickListener(this);
this.saveButton = (Button) this.settingsFragmentView.findViewById(R.id.settings_button_save);
this.saveButton.setOnClickListener(this);
this.gpsCheckBox = (CheckBox) this.settingsFragmentView.findViewById(R.id.settings_gps_location);
this.gpsCheckBox.setOnClickListener(this);
this.locationTextField = (EditText) this.settingsFragmentView.findViewById(R.id.settings_contextual_locations);
setHasOptionsMenu(true);
this.loadSettings();
return this.settingsFragmentView;
}
private void loadSettings() {
SharedPreferences settings = getActivity().getSharedPreferences(PREFS_NAME, 0);
List<Sensor> availableSensors = ((SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE)).getSensorList(Sensor.TYPE_ALL);
this.defaultValues = new HashSet<String>(availableSensors.size());
for (Sensor sensor: availableSensors) {
this.defaultValues.add(Integer.toString(sensor.getType()));
}
boolean isLeft = true;
Set<String> sensors = settings.getStringSet(SHARED_SENSORS, this.defaultValues);
for (String sensor : this.defaultValues) {
int id = Integer.parseInt(sensor);
CheckBox cb = new CheckBox(getActivity());
cb.setTextColor(Color.BLACK);
cb.setTextSize(11);
cb.setText(JsonParser.resolveSensorTypeById(id));
cb.setId(id);
if (sensors.contains(JsonParser.resolveSensorTypeById(id)))cb.setChecked(true);
if (isLeft) {
this.sensorListLeft.addView(cb);
isLeft = false;
} else {
this.sensorListRight.addView(cb);
isLeft = true;
}
}
this.address= settings.getString(SHARED_ADDRESS, ClientSocket.SERVER_DEFAULT_ADDRESS);
this.addressTextField.setText(this.address);
this.port = settings.getInt(SHARED_PORT, ClientSocket.SERVER_DEFAULT_PORT);
this.portTextField.setText(Integer.toString(this.port));
this.interval = settings.getLong(SHARED_INTERVAL, SensorListener.SENSOR_EVENT_INTERVAL);
this.intervalTextField.setText(Long.toString(this.interval));
this.location = settings.getString(SHARED_LOCATION, "");
if (this.location.length() > 0) this.locationTextField.setText(this.location);
if (!getActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_LOCATION_GPS)){
this.gpsCheckBox.setEnabled(false);
} else {
this.gpsCheckBox.setChecked(settings.getBoolean(SHARED_GPS, false));
}
}
@Override
public void onCreateOptionsMenu(Menu menu,MenuInflater inflater) {
((MenuItem)menu.findItem(R.id.menu_main)).setVisible(true);
((MenuItem)menu.findItem(R.id.menu_settings)).setVisible(false);
((MenuItem)menu.findItem(R.id.menu_settings)).setEnabled(false);
//getActivity().invalidateOptionsMenu(); //cause stack overflow in Samsung galaxy 4.1.2
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
this.saveState(false);
if(((MainActivity)getActivity()).isLandScape)((MainActivity)getActivity()).onSettingsItemClicked(false);
} else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
this.saveState(false);
if(!((MainActivity)getActivity()).isLandScape)((MainActivity)getActivity()).onSettingsItemClicked(true);
}
}
private void saveState(Boolean _showToast) {
Set<String> sensors = new HashSet<String>(this.defaultValues.size());
for (int i = 0; i < this.sensorListLeft.getChildCount(); i ++) {
if (this.sensorListLeft.getChildAt(i) instanceof CheckBox) {
if (((CheckBox)this.sensorListLeft.getChildAt(i)).isChecked()) {
sensors.add(JsonParser.resolveSensorTypeById(this.sensorListLeft.getChildAt(i).getId()));
}
}
}
for (int i = 0; i < this.sensorListRight.getChildCount(); i ++) {
if (this.sensorListRight.getChildAt(i) instanceof CheckBox) {
if (((CheckBox)this.sensorListRight.getChildAt(i)).isChecked()) {
sensors.add(JsonParser.resolveSensorTypeById(this.sensorListRight.getChildAt(i).getId()));
}
}
}
SharedPreferences settings = getActivity().getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putStringSet(SHARED_SENSORS, sensors);
editor.commit();
if (!this.addressTextField.getText().toString().contentEquals(this.address)) {
editor.putString(SHARED_ADDRESS, this.addressTextField.getText().toString());
editor.commit();
} if (Integer.parseInt(this.portTextField.getText().toString()) != this.port) {
editor.putInt(SHARED_PORT, Integer.parseInt(this.portTextField.getText().toString()));
editor.commit();
} if (Long.parseLong(this.intervalTextField.getText().toString()) != this.interval) {
editor.putLong(SHARED_INTERVAL, Long.parseLong(this.intervalTextField.getText().toString()));
editor.commit();
} if (!this.locationTextField.getText().toString().contentEquals(this.location)) {
editor.putString(SHARED_LOCATION, this.locationTextField.getText().toString());
editor.commit();
}if (this.gpsCheckBox.isEnabled()) {
editor.putBoolean(SHARED_GPS, this.gpsCheckBox.isChecked());
editor.commit();
}
if (_showToast) ((MainActivity)getActivity()).showToast("Settings saved!");
}
public void onBackPressed() {
this.saveState(true);
}
private void toggleGPS(Boolean _turnOn) {
Intent intent=new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", _turnOn);
getActivity().sendBroadcast(intent);
}
@Override
public void onClick(View _view) {
switch (_view.getId()) {
case R.id.settings_button_exit: getActivity().onBackPressed();
break;
case R.id.settings_button_reset:
this.sensorListLeft.removeAllViews();
this.sensorListRight.removeAllViews();
this.loadSettings();
break;
case R.id.settings_button_save: this.saveState(true);
break;
case R.id.settings_gps_location: if (this.gpsCheckBox.isEnabled()) this.toggleGPS(this.gpsCheckBox.isChecked());
}
}
}
|
92460bb5e5f6a2193093b8ebdef57cd23761abc6
| 2,630 |
java
|
Java
|
app/src/main/java/com/example/android/newsfeedapp/Activities/FavouritesActivity.java
|
baiden/News-Feed-App
|
99dc3a4d066b1a81090f31315be1e6392599bef9
|
[
"Unlicense"
] | 7 |
2018-10-09T07:52:38.000Z
|
2021-12-02T14:24:35.000Z
|
app/src/main/java/com/example/android/newsfeedapp/Activities/FavouritesActivity.java
|
okornoe/News-Feed-App
|
99dc3a4d066b1a81090f31315be1e6392599bef9
|
[
"Unlicense"
] | 1 |
2019-08-06T05:55:42.000Z
|
2019-08-06T05:55:42.000Z
|
app/src/main/java/com/example/android/newsfeedapp/Activities/FavouritesActivity.java
|
okornoe/News-Feed-App
|
99dc3a4d066b1a81090f31315be1e6392599bef9
|
[
"Unlicense"
] | 3 |
2018-11-15T06:29:24.000Z
|
2020-03-30T06:23:52.000Z
| 40.461538 | 139 | 0.656274 | 1,003,623 |
package com.example.android.newsfeedapp.Activities;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.FragmentActivity;
import android.view.MenuItem;
import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;
import com.example.android.newsfeedapp.Helpers.BottomNavigationViewHelper;
import com.example.android.newsfeedapp.R;
import butterknife.BindView;
import butterknife.ButterKnife;
public class FavouritesActivity extends FragmentActivity {
@BindView(R.id.bottomNavigationView) BottomNavigationView bottomNavMenu; //Bottom Navigation View Menu
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favourites);
ButterKnife.bind(this);
BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavigationView);
BottomNavigationViewHelper.disableShiftMode(bottomNavigationView); //Disables the default transaction in the bottom navigation view
//Sets onClick listeners on the buttons on the bottom navigation view
bottomNavMenu.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
Intent homeIntent = new Intent(FavouritesActivity.this, MainActivity.class);
startActivity(homeIntent);
break;
case R.id.headline:
Intent headlineIntent = new Intent(FavouritesActivity.this, HeadlinesActivity.class);
startActivity(headlineIntent);
break;
case R.id.favourites:
YoYo.with(Techniques.Tada)
.duration(700)
.playOn(findViewById(R.id.favourites));
break;
case R.id.trending:
Intent newsstandIntent = new Intent(FavouritesActivity.this, TrendingNewsActivity.class);
startActivity(newsstandIntent);
break;
}
return false;
}
});
}
}
|
92460c5de95df472e136dc5a0c63df18c00b4413
| 91,400 |
java
|
Java
|
src/main/java/com/thaiopensource/relaxng/parse/compact/CompactSyntax.java
|
junlapong/trang
|
00ddd1e062dcecf5dbde9001d164c6f2afb4184b
|
[
"BSD-3-Clause"
] | 7 |
2015-02-25T04:26:50.000Z
|
2017-09-25T18:36:38.000Z
|
src/main/java/com/thaiopensource/relaxng/parse/compact/CompactSyntax.java
|
junlapong/trang
|
00ddd1e062dcecf5dbde9001d164c6f2afb4184b
|
[
"BSD-3-Clause"
] | 6 |
2016-02-06T13:46:55.000Z
|
2022-01-27T16:18:48.000Z
|
src/main/java/com/thaiopensource/relaxng/parse/compact/CompactSyntax.java
|
junlapong/trang
|
00ddd1e062dcecf5dbde9001d164c6f2afb4184b
|
[
"BSD-3-Clause"
] | 5 |
2016-03-24T06:29:24.000Z
|
2019-05-08T05:35:46.000Z
| 27.781155 | 558 | 0.611182 | 1,003,624 |
/* Generated By:JavaCC: Do not edit this line. CompactSyntax.java */
package com.thaiopensource.relaxng.parse.compact;
import com.thaiopensource.relaxng.parse.Annotations;
import com.thaiopensource.relaxng.parse.BuildException;
import com.thaiopensource.relaxng.parse.CommentList;
import com.thaiopensource.relaxng.parse.Context;
import com.thaiopensource.relaxng.parse.DataPatternBuilder;
import com.thaiopensource.relaxng.parse.Div;
import com.thaiopensource.relaxng.parse.ElementAnnotationBuilder;
import com.thaiopensource.relaxng.parse.Grammar;
import com.thaiopensource.relaxng.parse.GrammarSection;
import com.thaiopensource.relaxng.parse.IllegalSchemaException;
import com.thaiopensource.relaxng.parse.Include;
import com.thaiopensource.relaxng.parse.IncludedGrammar;
import com.thaiopensource.relaxng.parse.SchemaBuilder;
import com.thaiopensource.relaxng.parse.Scope;
import com.thaiopensource.util.Ref;
import com.thaiopensource.xml.util.WellKnownNamespaces;
import com.thaiopensource.util.Localizer;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.LocatorImpl;
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;
import java.io.Reader;
public class CompactSyntax<Pattern, NameClass, Location, ElementAnnotation,
CommentListImpl extends CommentList<Location>,
AnnotationsImpl extends Annotations<Location, ElementAnnotation, CommentListImpl>>
implements Context, CompactSyntaxConstants {
private static final int IN_ELEMENT = 0;
private static final int IN_ATTRIBUTE = 1;
private static final int IN_ANY_NAME = 2;
private static final int IN_NS_NAME = 4;
private String defaultNamespace = SchemaBuilder.INHERIT_NS;
private String compatibilityPrefix = null;
private SchemaBuilder<Pattern, NameClass, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> sb;
private String sourceUri;
private ErrorHandler eh;
private final Map<String, String> namespaceMap = new HashMap<String, String>();
private final Map<String, String> datatypesMap = new HashMap<String, String>();
private boolean hadError = false;
private static final Localizer localizer = new Localizer(CompactSyntax.class);
private final Set<String> attributeNames = new HashSet<String>();
private boolean annotationsIncludeElements = false;
final class LocatedString {
private final String str;
private final Token tok;
LocatedString(String str, Token tok) {
this.str = str;
this.tok = tok;
}
String getString() {
return str;
}
Location getLocation() {
return makeLocation(tok);
}
Token getToken() {
return tok;
}
}
public CompactSyntax(Reader r, String sourceUri, SchemaBuilder<Pattern, NameClass, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> sb, ErrorHandler eh) {
this(r);
this.sourceUri = sourceUri;
this.sb = sb;
this.eh = eh;
// this causes the root pattern to have non-null annotations
// which is useful because it gives a context to trang
this.topLevelComments = sb.makeCommentList();
}
Pattern parse(Scope<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> scope) throws IllegalSchemaException {
try {
Pattern p = Input(scope);
if (!hadError)
return p;
}
catch (ParseException e) {
error("syntax_error", e.currentToken.next);
}
catch (EscapeSyntaxException e) {
reportEscapeSyntaxException(e);
}
throw new IllegalSchemaException();
}
Pattern parseInclude(IncludedGrammar<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> g) throws IllegalSchemaException {
try {
Pattern p = IncludedGrammar(g);
if (!hadError)
return p;
}
catch (ParseException e) {
error("syntax_error", e.currentToken.next);
}
catch (EscapeSyntaxException e) {
reportEscapeSyntaxException(e);
}
throw new IllegalSchemaException();
}
private void checkNsName(int context, LocatedString ns) {
if ((context & IN_NS_NAME) != 0)
error("ns_name_except_contains_ns_name", ns.getToken());
}
private void checkAnyName(int context, Token t) {
if ((context & IN_NS_NAME) != 0)
error("ns_name_except_contains_any_name", t);
if ((context & IN_ANY_NAME) != 0)
error("any_name_except_contains_any_name", t);
}
private void error(String key, Token tok) {
doError(localizer.message(key), tok);
}
private void error(String key, String arg, Token tok) {
doError(localizer.message(key, arg), tok);
}
private void error(String key, String arg1, String arg2, Token tok) {
doError(localizer.message(key, arg1, arg2), tok);
}
private void doError(String message, Token tok) {
hadError = true;
if (eh != null) {
LocatorImpl loc = new LocatorImpl();
loc.setLineNumber(tok.beginLine);
loc.setColumnNumber(tok.beginColumn);
loc.setSystemId(sourceUri);
try {
eh.error(new SAXParseException(message, loc));
}
catch (SAXException se) {
throw new BuildException(se);
}
}
}
private void reportEscapeSyntaxException(EscapeSyntaxException e) {
if (eh != null) {
LocatorImpl loc = new LocatorImpl();
loc.setLineNumber(e.getLineNumber());
loc.setColumnNumber(e.getColumnNumber());
loc.setSystemId(sourceUri);
try {
eh.error(new SAXParseException(localizer.message(e.getKey()), loc));
}
catch (SAXException se) {
throw new BuildException(se);
}
}
}
private static String unquote(String s) {
if (s.length() >= 6 && s.charAt(0) == s.charAt(1)) {
s = s.replace('\u0000', '\n');
return s.substring(3, s.length() - 3);
}
else
return s.substring(1, s.length() - 1);
}
Location makeLocation(Token t) {
return sb.makeLocation(sourceUri, t.beginLine, t.beginColumn);
}
String getCompatibilityPrefix() {
if (compatibilityPrefix == null) {
compatibilityPrefix = "a";
while (namespaceMap.get(compatibilityPrefix) != null)
compatibilityPrefix = compatibilityPrefix + "a";
}
return compatibilityPrefix;
}
public String resolveNamespacePrefix(String prefix) {
String result = namespaceMap.get(prefix);
if (result == null || result.length() == 0)
return null;
return result;
}
public Set<String> prefixes() {
return namespaceMap.keySet();
}
public String getBaseUri() {
return sourceUri;
}
public boolean isUnparsedEntity(String entityName) {
return false;
}
public boolean isNotation(String notationName) {
return false;
}
public Context copy() {
return this;
}
private Context getContext() {
return this;
}
private CommentListImpl getComments() {
return getComments(getTopLevelComments());
}
private CommentListImpl topLevelComments;
private CommentListImpl getTopLevelComments() {
CommentListImpl tem = topLevelComments;
topLevelComments = null;
return tem;
}
private void noteTopLevelComments() {
topLevelComments = getComments(topLevelComments);
}
private void topLevelComments(GrammarSection<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> section) {
section.topLevelComment(getComments(null));
}
private Token lastCommentSourceToken = null;
private CommentListImpl getComments(CommentListImpl comments) {
Token nextToken = getToken(1);
if (lastCommentSourceToken != nextToken) {
if (lastCommentSourceToken == null)
lastCommentSourceToken = token;
do {
lastCommentSourceToken = lastCommentSourceToken.next;
Token t = lastCommentSourceToken.specialToken;
if (t != null) {
while (t.specialToken != null)
t = t.specialToken;
if (comments == null)
comments = sb.makeCommentList();
for (; t != null; t = t.next) {
String s = mungeComment(t.image);
Location loc = makeLocation(t);
if (t.next != null
&& t.next.kind == CompactSyntaxConstants.SINGLE_LINE_COMMENT_CONTINUE) {
StringBuffer buf = new StringBuffer(s);
do {
t = t.next;
buf.append('\n');
buf.append(mungeComment(t.image));
} while (t.next != null
&& t.next.kind == CompactSyntaxConstants.SINGLE_LINE_COMMENT_CONTINUE);
s = buf.toString();
}
comments.addComment(s, loc);
}
}
} while (lastCommentSourceToken != nextToken);
}
return comments;
}
private Pattern afterPatternComments(Pattern p) {
CommentListImpl comments = getComments(null);
if (comments == null)
return p;
return sb.commentAfterPattern(p, comments);
}
private NameClass afterNameClassComments(NameClass nc) {
CommentListImpl comments = getComments(null);
if (comments == null)
return nc;
return sb.commentAfterNameClass(nc, comments);
}
private static String mungeComment(String image) {
int i = image.indexOf('#') + 1;
while (i < image.length() && image.charAt(i) == '#')
i++;
if (i < image.length() && image.charAt(i) == ' ')
i++;
return image.substring(i);
}
private AnnotationsImpl getCommentsAsAnnotations() {
CommentListImpl comments = getComments();
if (comments == null)
return null;
return sb.makeAnnotations(comments, getContext());
}
private AnnotationsImpl addCommentsToChildAnnotations(AnnotationsImpl a) {
CommentListImpl comments = getComments();
if (comments == null)
return a;
if (a == null)
a = sb.makeAnnotations(null, getContext());
a.addComment(comments);
return a;
}
private AnnotationsImpl addCommentsToLeadingAnnotations(AnnotationsImpl a) {
CommentListImpl comments = getComments();
if (comments == null)
return a;
if (a == null)
return sb.makeAnnotations(comments, getContext());
a.addLeadingComment(comments);
return a;
}
private AnnotationsImpl getTopLevelCommentsAsAnnotations() {
CommentListImpl comments = getTopLevelComments();
if (comments == null)
return null;
return sb.makeAnnotations(comments, getContext());
}
private void clearAttributeList() {
attributeNames.clear();
}
private void addAttribute(Annotations<Location, ElementAnnotation, CommentListImpl> a, String ns, String localName, String prefix, String value, Token tok) {
String key = ns + "#" + localName;
if (attributeNames.contains(key))
error("duplicate_attribute", ns, localName, tok);
else {
attributeNames.add(key);
a.addAttribute(ns, localName, prefix, value, makeLocation(tok));
}
}
private void checkExcept(Token[] except) {
if (except[0] != null)
error("except_missing_parentheses", except[0]);
}
private String lookupPrefix(String prefix, Token t) {
String ns = namespaceMap.get(prefix);
if (ns == null) {
error("undeclared_prefix", prefix, t);
return "#error";
}
return ns;
}
private String lookupDatatype(String prefix, Token t) {
String ns = datatypesMap.get(prefix);
if (ns == null) {
error("undeclared_prefix", prefix, t);
return ""; // XXX
}
return ns;
}
final public Pattern Input(Scope<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> scope) throws ParseException {
Pattern p;
Preamble();
if (jj_2_1(2147483647)) {
p = TopLevelGrammar(scope);
} else {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 1:
case 10:
case 17:
case 18:
case 19:
case 26:
case 27:
case 28:
case 31:
case 32:
case 33:
case 34:
case 35:
case 36:
case DOCUMENTATION:
case DOCUMENTATION_AFTER_SINGLE_LINE_COMMENT:
case IDENTIFIER:
case ESCAPED_IDENTIFIER:
case PREFIXED_NAME:
case LITERAL:
p = Expr(true, scope, null, null);
p = afterPatternComments(p);
jj_consume_token(0);
break;
default:
jj_la1[0] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
}
{if (true) return p;}
throw new Error("Missing return statement in function");
}
final public void TopLevelLookahead() throws ParseException {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case PREFIXED_NAME:
jj_consume_token(PREFIXED_NAME);
jj_consume_token(1);
break;
case IDENTIFIER:
case ESCAPED_IDENTIFIER:
Identifier();
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 1:
jj_consume_token(1);
break;
case 2:
jj_consume_token(2);
break;
case 3:
jj_consume_token(3);
break;
case 4:
jj_consume_token(4);
break;
default:
jj_la1[1] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
break;
case 5:
case 6:
case 7:
LookaheadGrammarKeyword();
break;
case 1:
LookaheadBody();
LookaheadAfterAnnotations();
break;
case DOCUMENTATION:
case DOCUMENTATION_AFTER_SINGLE_LINE_COMMENT:
LookaheadDocumentation();
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 1:
LookaheadBody();
break;
default:
jj_la1[2] = jj_gen;
;
}
LookaheadAfterAnnotations();
break;
default:
jj_la1[3] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
}
final public void LookaheadAfterAnnotations() throws ParseException {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case IDENTIFIER:
case ESCAPED_IDENTIFIER:
Identifier();
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 2:
jj_consume_token(2);
break;
case 3:
jj_consume_token(3);
break;
case 4:
jj_consume_token(4);
break;
default:
jj_la1[4] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
break;
case 5:
case 6:
case 7:
LookaheadGrammarKeyword();
break;
default:
jj_la1[5] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
}
final public void LookaheadGrammarKeyword() throws ParseException {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 5:
jj_consume_token(5);
break;
case 6:
jj_consume_token(6);
break;
case 7:
jj_consume_token(7);
break;
default:
jj_la1[6] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
}
final public void LookaheadDocumentation() throws ParseException {
label_1:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case DOCUMENTATION:
jj_consume_token(DOCUMENTATION);
break;
case DOCUMENTATION_AFTER_SINGLE_LINE_COMMENT:
jj_consume_token(DOCUMENTATION_AFTER_SINGLE_LINE_COMMENT);
break;
default:
jj_la1[7] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
label_2:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case DOCUMENTATION_CONTINUE:
;
break;
default:
jj_la1[8] = jj_gen;
break label_2;
}
jj_consume_token(DOCUMENTATION_CONTINUE);
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case DOCUMENTATION:
case DOCUMENTATION_AFTER_SINGLE_LINE_COMMENT:
;
break;
default:
jj_la1[9] = jj_gen;
break label_1;
}
}
}
final public void LookaheadBody() throws ParseException {
jj_consume_token(1);
label_3:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 1:
case 2:
case 5:
case 6:
case 7:
case 8:
case 10:
case 13:
case 14:
case 15:
case 16:
case 17:
case 18:
case 19:
case 26:
case 27:
case 31:
case 32:
case 33:
case 34:
case 35:
case 36:
case IDENTIFIER:
case ESCAPED_IDENTIFIER:
case PREFIXED_NAME:
case LITERAL:
;
break;
default:
jj_la1[10] = jj_gen;
break label_3;
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case PREFIXED_NAME:
jj_consume_token(PREFIXED_NAME);
break;
case 5:
case 6:
case 7:
case 10:
case 13:
case 14:
case 15:
case 16:
case 17:
case 18:
case 19:
case 26:
case 27:
case 31:
case 32:
case 33:
case 34:
case 35:
case 36:
case IDENTIFIER:
case ESCAPED_IDENTIFIER:
UnprefixedName();
break;
case 2:
jj_consume_token(2);
break;
case LITERAL:
jj_consume_token(LITERAL);
break;
case 8:
jj_consume_token(8);
break;
case 1:
LookaheadBody();
break;
default:
jj_la1[11] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
}
jj_consume_token(9);
}
final public Pattern IncludedGrammar(IncludedGrammar<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> g) throws ParseException {
AnnotationsImpl a;
Pattern p;
Preamble();
if (jj_2_2(2147483647)) {
a = GrammarBody(g, g, getTopLevelCommentsAsAnnotations());
} else {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 1:
case 10:
case DOCUMENTATION:
case DOCUMENTATION_AFTER_SINGLE_LINE_COMMENT:
a = AnnotationsImpl();
jj_consume_token(10);
jj_consume_token(11);
a = GrammarBody(g, g, a);
topLevelComments(g);
jj_consume_token(12);
break;
default:
jj_la1[12] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
}
p = afterPatternComments(g.endIncludedGrammar(sb.makeLocation(sourceUri, 1, 1), a));
jj_consume_token(0);
{if (true) return p;}
throw new Error("Missing return statement in function");
}
final public Pattern TopLevelGrammar(Scope<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> scope) throws ParseException {
AnnotationsImpl a = getTopLevelCommentsAsAnnotations();
Grammar<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> g;
Pattern p;
g = sb.makeGrammar(scope);
a = GrammarBody(g, g, a);
p = afterPatternComments(g.endGrammar(sb.makeLocation(sourceUri, 1, 1), a));
jj_consume_token(0);
{if (true) return p;}
throw new Error("Missing return statement in function");
}
final public void Preamble() throws ParseException {
label_4:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 13:
case 14:
case 16:
;
break;
default:
jj_la1[13] = jj_gen;
break label_4;
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 13:
case 14:
NamespaceDecl();
break;
case 16:
DatatypesDecl();
break;
default:
jj_la1[14] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
}
namespaceMap.put("xml", WellKnownNamespaces.XML);
if (datatypesMap.get("xsd") == null)
datatypesMap.put("xsd", WellKnownNamespaces.XML_SCHEMA_DATATYPES);
}
final public void NamespaceDecl() throws ParseException {
LocatedString prefix = null;
boolean isDefault = false;
String namespaceName;
noteTopLevelComments();
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 13:
jj_consume_token(13);
prefix = UnprefixedName();
break;
case 14:
jj_consume_token(14);
isDefault = true;
jj_consume_token(13);
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 5:
case 6:
case 7:
case 10:
case 13:
case 14:
case 15:
case 16:
case 17:
case 18:
case 19:
case 26:
case 27:
case 31:
case 32:
case 33:
case 34:
case 35:
case 36:
case IDENTIFIER:
case ESCAPED_IDENTIFIER:
prefix = UnprefixedName();
break;
default:
jj_la1[15] = jj_gen;
;
}
break;
default:
jj_la1[16] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
jj_consume_token(2);
namespaceName = NamespaceName();
if (isDefault)
defaultNamespace = namespaceName;
if (prefix != null) {
if (prefix.getString().equals("xmlns"))
error("xmlns_prefix", prefix.getToken());
else if (prefix.getString().equals("xml")) {
if (!namespaceName.equals(WellKnownNamespaces.XML))
error("xml_prefix_bad_uri", prefix.getToken());
}
else if (namespaceName.equals(WellKnownNamespaces.XML))
error("xml_uri_bad_prefix", prefix.getToken());
else {
if (namespaceName.equals(WellKnownNamespaces.RELAX_NG_COMPATIBILITY_ANNOTATIONS))
compatibilityPrefix = prefix.getString();
namespaceMap.put(prefix.getString(), namespaceName);
}
}
}
final public String NamespaceName() throws ParseException {
String r;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case LITERAL:
r = Literal();
break;
case 15:
jj_consume_token(15);
r = SchemaBuilder.INHERIT_NS;
break;
default:
jj_la1[17] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
{if (true) return r;}
throw new Error("Missing return statement in function");
}
final public void DatatypesDecl() throws ParseException {
LocatedString prefix;
String uri;
noteTopLevelComments();
jj_consume_token(16);
prefix = UnprefixedName();
jj_consume_token(2);
uri = Literal();
datatypesMap.put(prefix.getString(), uri);
}
final public Pattern AnnotatedPrimaryExpr(boolean topLevel, Scope<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> scope, Token[] except) throws ParseException {
AnnotationsImpl a;
Pattern p;
ElementAnnotation e;
Token t;
a = AnnotationsImpl();
p = PrimaryExpr(topLevel, scope, a, except);
label_5:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case FANNOTATE:
;
break;
default:
jj_la1[18] = jj_gen;
break label_5;
}
t = jj_consume_token(FANNOTATE);
e = AnnotationElement(false);
if (topLevel)
error("top_level_follow_annotation", t);
else
p = sb.annotateAfterPattern(p, e);
}
{if (true) return p;}
throw new Error("Missing return statement in function");
}
final public Pattern PrimaryExpr(boolean topLevel, Scope<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> scope, AnnotationsImpl a, Token[] except) throws ParseException {
Pattern p;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 26:
p = ElementExpr(scope, a);
break;
case 27:
p = AttributeExpr(scope, a);
break;
case 10:
p = GrammarExpr(scope, a);
break;
case 33:
p = ExternalRefExpr(scope, a);
break;
case 31:
p = ListExpr(scope, a);
break;
case 32:
p = MixedExpr(scope, a);
break;
case 28:
p = ParenExpr(topLevel, scope, a);
break;
case IDENTIFIER:
case ESCAPED_IDENTIFIER:
p = IdentifierExpr(scope, a);
break;
case 34:
p = ParentExpr(scope, a);
break;
case 35:
case 36:
case PREFIXED_NAME:
p = DataExpr(topLevel, scope, a, except);
break;
case LITERAL:
p = ValueExpr(topLevel, a);
break;
case 18:
p = TextExpr(a);
break;
case 17:
p = EmptyExpr(a);
break;
case 19:
p = NotAllowedExpr(a);
break;
default:
jj_la1[19] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
{if (true) return p;}
throw new Error("Missing return statement in function");
}
final public Pattern EmptyExpr(AnnotationsImpl a) throws ParseException {
Token t;
t = jj_consume_token(17);
{if (true) return sb.makeEmpty(makeLocation(t), a);}
throw new Error("Missing return statement in function");
}
final public Pattern TextExpr(AnnotationsImpl a) throws ParseException {
Token t;
t = jj_consume_token(18);
{if (true) return sb.makeText(makeLocation(t), a);}
throw new Error("Missing return statement in function");
}
final public Pattern NotAllowedExpr(AnnotationsImpl a) throws ParseException {
Token t;
t = jj_consume_token(19);
{if (true) return sb.makeNotAllowed(makeLocation(t), a);}
throw new Error("Missing return statement in function");
}
final public Pattern Expr(boolean topLevel, Scope<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> scope, Token t, AnnotationsImpl a) throws ParseException {
Pattern p;
List<Pattern> patterns = new ArrayList<Pattern>();
boolean[] hadOccur = new boolean[1];
Token[] except = new Token[1];
p = UnaryExpr(topLevel, scope, hadOccur, except);
patterns.add(p);
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 20:
case 21:
case 22:
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 20:
checkExcept(except);
label_6:
while (true) {
t = jj_consume_token(20);
p = UnaryExpr(topLevel, scope, null, except);
patterns.add(p); checkExcept(except);
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 20:
;
break;
default:
jj_la1[20] = jj_gen;
break label_6;
}
}
p = sb.makeChoice(patterns, makeLocation(t), a);
break;
case 21:
label_7:
while (true) {
t = jj_consume_token(21);
p = UnaryExpr(topLevel, scope, null, except);
patterns.add(p); checkExcept(except);
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 21:
;
break;
default:
jj_la1[21] = jj_gen;
break label_7;
}
}
p = sb.makeInterleave(patterns, makeLocation(t), a);
break;
case 22:
label_8:
while (true) {
t = jj_consume_token(22);
p = UnaryExpr(topLevel, scope, null, except);
patterns.add(p); checkExcept(except);
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 22:
;
break;
default:
jj_la1[22] = jj_gen;
break label_8;
}
}
p = sb.makeGroup(patterns, makeLocation(t), a);
break;
default:
jj_la1[23] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
break;
default:
jj_la1[24] = jj_gen;
;
}
if (patterns.size() == 1 && a != null) {
if (hadOccur[0])
p = sb.annotatePattern(p, a);
else
p = sb.makeGroup(patterns, makeLocation(t), a);
}
{if (true) return p;}
throw new Error("Missing return statement in function");
}
final public Pattern UnaryExpr(boolean topLevel, Scope<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> scope, boolean[] hadOccur, Token[] except) throws ParseException {
Pattern p;
Token t;
ElementAnnotation e;
p = AnnotatedPrimaryExpr(topLevel, scope, except);
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 23:
case 24:
case 25:
if (hadOccur != null) hadOccur[0] = true;
p = afterPatternComments(p);
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 23:
t = jj_consume_token(23);
checkExcept(except); p = sb.makeOneOrMore(p, makeLocation(t), null);
break;
case 24:
t = jj_consume_token(24);
checkExcept(except); p = sb.makeOptional(p, makeLocation(t), null);
break;
case 25:
t = jj_consume_token(25);
checkExcept(except); p = sb.makeZeroOrMore(p, makeLocation(t), null);
break;
default:
jj_la1[25] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
label_9:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case FANNOTATE:
;
break;
default:
jj_la1[26] = jj_gen;
break label_9;
}
t = jj_consume_token(FANNOTATE);
e = AnnotationElement(false);
if (topLevel)
error("top_level_follow_annotation", t);
else
p = sb.annotateAfterPattern(p, e);
}
break;
default:
jj_la1[27] = jj_gen;
;
}
{if (true) return p;}
throw new Error("Missing return statement in function");
}
final public Pattern ElementExpr(Scope<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> scope, AnnotationsImpl a) throws ParseException {
Token t;
NameClass nc;
Pattern p;
t = jj_consume_token(26);
nc = NameClass(IN_ELEMENT, null);
jj_consume_token(11);
p = Expr(false, scope, null, null);
p = afterPatternComments(p);
jj_consume_token(12);
{if (true) return sb.makeElement(nc, p, makeLocation(t), a);}
throw new Error("Missing return statement in function");
}
final public Pattern AttributeExpr(Scope<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> scope, AnnotationsImpl a) throws ParseException {
Token t;
NameClass nc;
Pattern p;
t = jj_consume_token(27);
nc = NameClass(IN_ATTRIBUTE, null);
jj_consume_token(11);
p = Expr(false, scope, null, null);
p = afterPatternComments(p);
jj_consume_token(12);
{if (true) return sb.makeAttribute(nc, p, makeLocation(t), a);}
throw new Error("Missing return statement in function");
}
final public NameClass NameClass(int context, Ref<AnnotationsImpl> ra) throws ParseException {
AnnotationsImpl a;
NameClass nc;
a = AnnotationsImpl();
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 5:
case 6:
case 7:
case 10:
case 13:
case 14:
case 15:
case 16:
case 17:
case 18:
case 19:
case 26:
case 27:
case 28:
case 31:
case 32:
case 33:
case 34:
case 35:
case 36:
case IDENTIFIER:
case ESCAPED_IDENTIFIER:
case PREFIXED_NAME:
nc = PrimaryNameClass(context, a);
nc = AnnotateAfter(nc);
nc = NameClassAlternatives(context, nc, ra);
break;
case 25:
nc = AnyNameExceptClass(context, a, ra);
break;
case PREFIX_STAR:
nc = NsNameExceptClass(context, a, ra);
break;
default:
jj_la1[28] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
{if (true) return nc;}
throw new Error("Missing return statement in function");
}
final public NameClass AnnotateAfter(NameClass nc) throws ParseException {
ElementAnnotation e;
label_10:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case FANNOTATE:
;
break;
default:
jj_la1[29] = jj_gen;
break label_10;
}
jj_consume_token(FANNOTATE);
e = AnnotationElement(false);
nc = sb.annotateAfterNameClass(nc, e);
}
{if (true) return nc;}
throw new Error("Missing return statement in function");
}
final public NameClass NameClassAlternatives(int context, NameClass nc, Ref<AnnotationsImpl> ra) throws ParseException {
Token t;
List<NameClass> nameClasses;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 20:
nameClasses = new ArrayList<NameClass>();
nameClasses.add(nc);
label_11:
while (true) {
t = jj_consume_token(20);
nc = BasicNameClass(context);
nc = AnnotateAfter(nc);
nameClasses.add(nc);
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 20:
;
break;
default:
jj_la1[30] = jj_gen;
break label_11;
}
}
AnnotationsImpl a;
if (ra == null)
a = null;
else {
a = ra.get();
ra.clear();
}
nc = sb.makeNameClassChoice(nameClasses, makeLocation(t), a);
break;
default:
jj_la1[31] = jj_gen;
;
}
{if (true) return nc;}
throw new Error("Missing return statement in function");
}
final public NameClass BasicNameClass(int context) throws ParseException {
AnnotationsImpl a;
NameClass nc;
a = AnnotationsImpl();
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 5:
case 6:
case 7:
case 10:
case 13:
case 14:
case 15:
case 16:
case 17:
case 18:
case 19:
case 26:
case 27:
case 28:
case 31:
case 32:
case 33:
case 34:
case 35:
case 36:
case IDENTIFIER:
case ESCAPED_IDENTIFIER:
case PREFIXED_NAME:
nc = PrimaryNameClass(context, a);
break;
case 25:
case PREFIX_STAR:
nc = OpenNameClass(context, a);
break;
default:
jj_la1[32] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
{if (true) return nc;}
throw new Error("Missing return statement in function");
}
final public NameClass PrimaryNameClass(int context, AnnotationsImpl a) throws ParseException {
NameClass nc;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 5:
case 6:
case 7:
case 10:
case 13:
case 14:
case 15:
case 16:
case 17:
case 18:
case 19:
case 26:
case 27:
case 31:
case 32:
case 33:
case 34:
case 35:
case 36:
case IDENTIFIER:
case ESCAPED_IDENTIFIER:
nc = UnprefixedNameClass(context, a);
break;
case PREFIXED_NAME:
nc = PrefixedNameClass(a);
break;
case 28:
nc = ParenNameClass(context, a);
break;
default:
jj_la1[33] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
{if (true) return nc;}
throw new Error("Missing return statement in function");
}
final public NameClass OpenNameClass(int context, AnnotationsImpl a) throws ParseException {
Token t;
LocatedString ns;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case PREFIX_STAR:
ns = NsName();
checkNsName(context, ns); {if (true) return sb.makeNsName(ns.getString(), ns.getLocation(), a);}
break;
case 25:
t = jj_consume_token(25);
checkAnyName(context, t); {if (true) return sb.makeAnyName(makeLocation(t), a);}
break;
default:
jj_la1[34] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
throw new Error("Missing return statement in function");
}
final public NameClass UnprefixedNameClass(int context, AnnotationsImpl a) throws ParseException {
LocatedString name;
name = UnprefixedName();
String ns;
if ((context & (IN_ATTRIBUTE|IN_ELEMENT)) == IN_ATTRIBUTE)
ns = "";
else
ns = defaultNamespace;
{if (true) return sb.makeName(ns, name.getString(), null, name.getLocation(), a);}
throw new Error("Missing return statement in function");
}
final public NameClass PrefixedNameClass(AnnotationsImpl a) throws ParseException {
Token t;
t = jj_consume_token(PREFIXED_NAME);
String qn = t.image;
int colon = qn.indexOf(':');
String prefix = qn.substring(0, colon);
{if (true) return sb.makeName(lookupPrefix(prefix, t), qn.substring(colon + 1), prefix, makeLocation(t), a);}
throw new Error("Missing return statement in function");
}
final public NameClass NsNameExceptClass(int context, AnnotationsImpl a, Ref<AnnotationsImpl> ra) throws ParseException {
LocatedString ns;
NameClass nc;
ns = NsName();
checkNsName(context, ns);
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 30:
nc = ExceptNameClass(context | IN_NS_NAME);
nc = sb.makeNsName(ns.getString(), nc, ns.getLocation(), a);
nc = AnnotateAfter(nc);
break;
default:
jj_la1[35] = jj_gen;
nc = sb.makeNsName(ns.getString(), ns.getLocation(), a);
nc = AnnotateAfter(nc);
nc = NameClassAlternatives(context, nc, ra);
}
{if (true) return nc;}
throw new Error("Missing return statement in function");
}
final public LocatedString NsName() throws ParseException {
Token t;
t = jj_consume_token(PREFIX_STAR);
String qn = t.image;
String prefix = qn.substring(0, qn.length() - 2);
{if (true) return new LocatedString(lookupPrefix(prefix, t), t);}
throw new Error("Missing return statement in function");
}
final public NameClass AnyNameExceptClass(int context, AnnotationsImpl a, Ref<AnnotationsImpl> ra) throws ParseException {
Token t;
NameClass nc;
t = jj_consume_token(25);
checkAnyName(context, t);
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 30:
nc = ExceptNameClass(context | IN_ANY_NAME);
nc = sb.makeAnyName(nc, makeLocation(t), a);
nc = AnnotateAfter(nc);
break;
default:
jj_la1[36] = jj_gen;
nc = sb.makeAnyName(makeLocation(t), a);
nc = AnnotateAfter(nc);
nc = NameClassAlternatives(context, nc, ra);
}
{if (true) return nc;}
throw new Error("Missing return statement in function");
}
final public NameClass ParenNameClass(int context, AnnotationsImpl a) throws ParseException {
Token t;
NameClass nc;
Ref<AnnotationsImpl> ra = new Ref<AnnotationsImpl>(a);
t = jj_consume_token(28);
nc = NameClass(context, ra);
nc = afterNameClassComments(nc);
jj_consume_token(29);
if (ra.get() != null)
nc = sb.makeNameClassChoice(Collections.singletonList(nc), makeLocation(t), ra.get());
{if (true) return nc;}
throw new Error("Missing return statement in function");
}
final public NameClass ExceptNameClass(int context) throws ParseException {
NameClass nc;
jj_consume_token(30);
nc = BasicNameClass(context);
{if (true) return nc;}
throw new Error("Missing return statement in function");
}
final public Pattern ListExpr(Scope<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> scope, AnnotationsImpl a) throws ParseException {
Token t;
Pattern p;
t = jj_consume_token(31);
jj_consume_token(11);
p = Expr(false, scope, null, null);
p = afterPatternComments(p);
jj_consume_token(12);
{if (true) return sb.makeList(p, makeLocation(t), a);}
throw new Error("Missing return statement in function");
}
final public Pattern MixedExpr(Scope<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> scope, AnnotationsImpl a) throws ParseException {
Token t;
Pattern p;
t = jj_consume_token(32);
jj_consume_token(11);
p = Expr(false, scope, null, null);
p = afterPatternComments(p);
jj_consume_token(12);
{if (true) return sb.makeMixed(p, makeLocation(t), a);}
throw new Error("Missing return statement in function");
}
final public Pattern GrammarExpr(Scope<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> scope, AnnotationsImpl a) throws ParseException {
Token t;
Grammar<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> g;
t = jj_consume_token(10);
g = sb.makeGrammar(scope);
jj_consume_token(11);
a = GrammarBody(g, g, a);
topLevelComments(g);
jj_consume_token(12);
{if (true) return g.endGrammar(makeLocation(t), a);}
throw new Error("Missing return statement in function");
}
final public Pattern ParenExpr(boolean topLevel, Scope<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> scope, AnnotationsImpl a) throws ParseException {
Token t;
Pattern p;
t = jj_consume_token(28);
p = Expr(topLevel, scope, t, a);
p = afterPatternComments(p);
jj_consume_token(29);
{if (true) return p;}
throw new Error("Missing return statement in function");
}
final public AnnotationsImpl GrammarBody(GrammarSection<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> section, Scope<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> scope, AnnotationsImpl a) throws ParseException {
ElementAnnotation e;
label_12:
while (true) {
if (jj_2_3(2)) {
;
} else {
break label_12;
}
e = AnnotationElementNotKeyword();
if (a == null) a = sb.makeAnnotations(null, getContext()); a.addElement(e);
}
label_13:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 1:
case 5:
case 6:
case 7:
case DOCUMENTATION:
case DOCUMENTATION_AFTER_SINGLE_LINE_COMMENT:
case IDENTIFIER:
case ESCAPED_IDENTIFIER:
;
break;
default:
jj_la1[37] = jj_gen;
break label_13;
}
GrammarComponent(section, scope);
}
{if (true) return a;}
throw new Error("Missing return statement in function");
}
final public void GrammarComponent(GrammarSection<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> section, Scope<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> scope) throws ParseException {
ElementAnnotation e;
AnnotationsImpl a;
a = AnnotationsImpl();
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 5:
case IDENTIFIER:
case ESCAPED_IDENTIFIER:
Definition(section, scope, a);
break;
case 7:
Include(section, scope, a);
break;
case 6:
Div(section, scope, a);
break;
default:
jj_la1[38] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
label_14:
while (true) {
if (jj_2_4(2)) {
;
} else {
break label_14;
}
e = AnnotationElementNotKeyword();
section.topLevelAnnotation(e);
}
}
final public void Definition(GrammarSection<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> section, Scope<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> scope, AnnotationsImpl a) throws ParseException {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case IDENTIFIER:
case ESCAPED_IDENTIFIER:
Define(section, scope, a);
break;
case 5:
Start(section, scope, a);
break;
default:
jj_la1[39] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
}
final public void Start(GrammarSection<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> section, Scope<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> scope, AnnotationsImpl a) throws ParseException {
Token t;
GrammarSection.Combine combine;
Pattern p;
t = jj_consume_token(5);
combine = AssignOp();
p = Expr(false, scope, null, null);
section.define(GrammarSection.START, combine, p, makeLocation(t), a);
}
final public void Define(GrammarSection<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> section, Scope<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> scope, AnnotationsImpl a) throws ParseException {
LocatedString name;
GrammarSection.Combine combine;
Pattern p;
name = Identifier();
combine = AssignOp();
p = Expr(false, scope, null, null);
section.define(name.getString(), combine, p, name.getLocation(), a);
}
final public GrammarSection.Combine AssignOp() throws ParseException {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 2:
jj_consume_token(2);
{if (true) return null;}
break;
case 4:
jj_consume_token(4);
{if (true) return GrammarSection.COMBINE_CHOICE;}
break;
case 3:
jj_consume_token(3);
{if (true) return GrammarSection.COMBINE_INTERLEAVE;}
break;
default:
jj_la1[40] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
throw new Error("Missing return statement in function");
}
final public void Include(GrammarSection<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> section, Scope<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> scope, AnnotationsImpl a) throws ParseException {
Token t;
String href;
String ns;
Include include = section.makeInclude();
t = jj_consume_token(7);
href = Literal();
ns = Inherit();
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 11:
jj_consume_token(11);
a = IncludeBody(include, scope, a);
topLevelComments(include);
jj_consume_token(12);
break;
default:
jj_la1[41] = jj_gen;
;
}
try {
include.endInclude(href, sourceUri, ns, makeLocation(t), a);
}
catch (IllegalSchemaException e) { }
}
final public AnnotationsImpl IncludeBody(GrammarSection<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> section, Scope<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> scope, AnnotationsImpl a) throws ParseException {
ElementAnnotation e;
label_15:
while (true) {
if (jj_2_5(2)) {
;
} else {
break label_15;
}
e = AnnotationElementNotKeyword();
if (a == null) a = sb.makeAnnotations(null, getContext()); a.addElement(e);
}
label_16:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 1:
case 5:
case 6:
case DOCUMENTATION:
case DOCUMENTATION_AFTER_SINGLE_LINE_COMMENT:
case IDENTIFIER:
case ESCAPED_IDENTIFIER:
;
break;
default:
jj_la1[42] = jj_gen;
break label_16;
}
IncludeComponent(section, scope);
}
{if (true) return a;}
throw new Error("Missing return statement in function");
}
final public void IncludeComponent(GrammarSection<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> section, Scope<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> scope) throws ParseException {
ElementAnnotation e;
AnnotationsImpl a;
a = AnnotationsImpl();
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 5:
case IDENTIFIER:
case ESCAPED_IDENTIFIER:
Definition(section, scope, a);
break;
case 6:
IncludeDiv(section, scope, a);
break;
default:
jj_la1[43] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
label_17:
while (true) {
if (jj_2_6(2)) {
;
} else {
break label_17;
}
e = AnnotationElementNotKeyword();
section.topLevelAnnotation(e);
}
}
final public void Div(GrammarSection<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> section, Scope<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> scope, AnnotationsImpl a) throws ParseException {
Token t;
Div<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> div = section.makeDiv();
t = jj_consume_token(6);
jj_consume_token(11);
a = GrammarBody(div, scope, a);
topLevelComments(div);
jj_consume_token(12);
div.endDiv(makeLocation(t), a);
}
final public void IncludeDiv(GrammarSection<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> section, Scope<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> scope, AnnotationsImpl a) throws ParseException {
Token t;
Div<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> div = section.makeDiv();
t = jj_consume_token(6);
jj_consume_token(11);
a = IncludeBody(div, scope, a);
topLevelComments(div);
jj_consume_token(12);
div.endDiv(makeLocation(t), a);
}
final public Pattern ExternalRefExpr(Scope<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> scope, AnnotationsImpl a) throws ParseException {
Token t;
String href;
String ns;
t = jj_consume_token(33);
href = Literal();
ns = Inherit();
try {
{if (true) return sb.makeExternalRef(href, sourceUri, ns, scope, makeLocation(t), a);}
}
catch (IllegalSchemaException e) {
{if (true) return sb.makeErrorPattern();}
}
throw new Error("Missing return statement in function");
}
final public String Inherit() throws ParseException {
String ns = null;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 15:
jj_consume_token(15);
jj_consume_token(2);
ns = Prefix();
break;
default:
jj_la1[44] = jj_gen;
;
}
if (ns == null)
ns = defaultNamespace;
{if (true) return ns;}
throw new Error("Missing return statement in function");
}
final public Pattern ParentExpr(Scope<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> scope, AnnotationsImpl a) throws ParseException {
LocatedString name;
jj_consume_token(34);
a = addCommentsToChildAnnotations(a);
name = Identifier();
{if (true) return scope.makeParentRef(name.getString(), name.getLocation(), a);}
throw new Error("Missing return statement in function");
}
final public Pattern IdentifierExpr(Scope<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> scope, AnnotationsImpl a) throws ParseException {
LocatedString name;
name = Identifier();
{if (true) return scope.makeRef(name.getString(), name.getLocation(), a);}
throw new Error("Missing return statement in function");
}
final public Pattern ValueExpr(boolean topLevel, AnnotationsImpl a) throws ParseException {
LocatedString s;
s = LocatedLiteral();
if (topLevel && annotationsIncludeElements) {
error("top_level_follow_annotation", s.getToken());
a = null;
}
{if (true) return sb.makeValue("", "token", s.getString(), getContext(), defaultNamespace, s.getLocation(), a);}
throw new Error("Missing return statement in function");
}
final public Pattern DataExpr(boolean topLevel, Scope<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> scope, AnnotationsImpl a, Token[] except) throws ParseException {
Token datatypeToken;
Location loc;
String datatype;
String datatypeUri = null;
String s = null;
Pattern e = null;
DataPatternBuilder<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> dpb;
datatypeToken = DatatypeName();
datatype = datatypeToken.image;
loc = makeLocation(datatypeToken);
int colon = datatype.indexOf(':');
if (colon < 0)
datatypeUri = "";
else {
String prefix = datatype.substring(0, colon);
datatypeUri = lookupDatatype(prefix, datatypeToken);
datatype = datatype.substring(colon + 1);
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case LITERAL:
s = Literal();
if (topLevel && annotationsIncludeElements) {
error("top_level_follow_annotation", datatypeToken);
a = null;
}
{if (true) return sb.makeValue(datatypeUri, datatype, s, getContext(), defaultNamespace, loc, a);}
break;
default:
jj_la1[48] = jj_gen;
dpb = sb.makeDataPatternBuilder(datatypeUri, datatype, loc);
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 11:
Params(dpb);
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 30:
e = Except(scope, except);
break;
default:
jj_la1[45] = jj_gen;
;
}
break;
default:
jj_la1[47] = jj_gen;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 30:
e = Except(scope, except);
break;
default:
jj_la1[46] = jj_gen;
;
}
}
{if (true) return e == null ? dpb.makePattern(loc, a) : dpb.makePattern(e, loc, a);}
}
throw new Error("Missing return statement in function");
}
final public Token DatatypeName() throws ParseException {
Token t;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 35:
t = jj_consume_token(35);
break;
case 36:
t = jj_consume_token(36);
break;
case PREFIXED_NAME:
t = jj_consume_token(PREFIXED_NAME);
break;
default:
jj_la1[49] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
{if (true) return t;}
throw new Error("Missing return statement in function");
}
final public LocatedString Identifier() throws ParseException {
LocatedString s;
Token t;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case IDENTIFIER:
t = jj_consume_token(IDENTIFIER);
s = new LocatedString(t.image, t);
break;
case ESCAPED_IDENTIFIER:
t = jj_consume_token(ESCAPED_IDENTIFIER);
s = new LocatedString(t.image.substring(1), t);
break;
default:
jj_la1[50] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
{if (true) return s;}
throw new Error("Missing return statement in function");
}
final public String Prefix() throws ParseException {
Token t;
String prefix;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case IDENTIFIER:
t = jj_consume_token(IDENTIFIER);
prefix = t.image;
break;
case ESCAPED_IDENTIFIER:
t = jj_consume_token(ESCAPED_IDENTIFIER);
prefix = t.image.substring(1);
break;
case 5:
case 6:
case 7:
case 10:
case 13:
case 14:
case 15:
case 16:
case 17:
case 18:
case 19:
case 26:
case 27:
case 31:
case 32:
case 33:
case 34:
case 35:
case 36:
t = Keyword();
prefix = t.image;
break;
default:
jj_la1[51] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
{if (true) return lookupPrefix(prefix, t);}
throw new Error("Missing return statement in function");
}
final public LocatedString UnprefixedName() throws ParseException {
LocatedString s;
Token t;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case IDENTIFIER:
case ESCAPED_IDENTIFIER:
s = Identifier();
break;
case 5:
case 6:
case 7:
case 10:
case 13:
case 14:
case 15:
case 16:
case 17:
case 18:
case 19:
case 26:
case 27:
case 31:
case 32:
case 33:
case 34:
case 35:
case 36:
t = Keyword();
s = new LocatedString(t.image, t);
break;
default:
jj_la1[52] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
{if (true) return s;}
throw new Error("Missing return statement in function");
}
final public void Params(DataPatternBuilder<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> dpb) throws ParseException {
jj_consume_token(11);
label_18:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 1:
case 5:
case 6:
case 7:
case 10:
case 13:
case 14:
case 15:
case 16:
case 17:
case 18:
case 19:
case 26:
case 27:
case 31:
case 32:
case 33:
case 34:
case 35:
case 36:
case DOCUMENTATION:
case DOCUMENTATION_AFTER_SINGLE_LINE_COMMENT:
case IDENTIFIER:
case ESCAPED_IDENTIFIER:
;
break;
default:
jj_la1[53] = jj_gen;
break label_18;
}
Param(dpb);
}
jj_consume_token(12);
}
final public void Param(DataPatternBuilder<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> dpb) throws ParseException {
LocatedString name;
AnnotationsImpl a;
String value;
a = AnnotationsImpl();
name = UnprefixedName();
jj_consume_token(2);
a = addCommentsToLeadingAnnotations(a);
value = Literal();
dpb.addParam(name.getString(), value, getContext(), defaultNamespace, name.getLocation(), a);
}
final public Pattern Except(Scope<Pattern, Location, ElementAnnotation, CommentListImpl, AnnotationsImpl> scope, Token[] except) throws ParseException {
AnnotationsImpl a;
Pattern p;
Token t;
Token[] innerExcept = new Token[1];
t = jj_consume_token(30);
a = AnnotationsImpl();
p = PrimaryExpr(false, scope, a, innerExcept);
checkExcept(innerExcept);
except[0] = t;
{if (true) return p;}
throw new Error("Missing return statement in function");
}
final public ElementAnnotation Documentation() throws ParseException {
CommentListImpl comments = getComments();
ElementAnnotationBuilder<Location, ElementAnnotation, CommentListImpl> eab;
Token t;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case DOCUMENTATION:
t = jj_consume_token(DOCUMENTATION);
break;
case DOCUMENTATION_AFTER_SINGLE_LINE_COMMENT:
t = jj_consume_token(DOCUMENTATION_AFTER_SINGLE_LINE_COMMENT);
break;
default:
jj_la1[54] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
eab = sb.makeElementAnnotationBuilder(WellKnownNamespaces.RELAX_NG_COMPATIBILITY_ANNOTATIONS,
"documentation",
getCompatibilityPrefix(),
makeLocation(t),
comments,
getContext());
eab.addText(mungeComment(t.image), makeLocation(t), null);
label_19:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case DOCUMENTATION_CONTINUE:
;
break;
default:
jj_la1[55] = jj_gen;
break label_19;
}
t = jj_consume_token(DOCUMENTATION_CONTINUE);
eab.addText("\n" + mungeComment(t.image), makeLocation(t), null);
}
{if (true) return eab.makeElementAnnotation();}
throw new Error("Missing return statement in function");
}
final public AnnotationsImpl AnnotationsImpl() throws ParseException {
CommentListImpl comments = getComments();
AnnotationsImpl a = null;
ElementAnnotation e;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case DOCUMENTATION:
case DOCUMENTATION_AFTER_SINGLE_LINE_COMMENT:
a = sb.makeAnnotations(comments, getContext());
label_20:
while (true) {
e = Documentation();
a.addElement(e);
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case DOCUMENTATION:
case DOCUMENTATION_AFTER_SINGLE_LINE_COMMENT:
;
break;
default:
jj_la1[56] = jj_gen;
break label_20;
}
}
comments = getComments();
if (comments != null)
a.addLeadingComment(comments);
break;
default:
jj_la1[57] = jj_gen;
;
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 1:
jj_consume_token(1);
if (a == null) a = sb.makeAnnotations(comments, getContext()); clearAttributeList(); annotationsIncludeElements = false;
label_21:
while (true) {
if (jj_2_7(2)) {
;
} else {
break label_21;
}
PrefixedAnnotationAttribute(a, false);
}
label_22:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 5:
case 6:
case 7:
case 10:
case 13:
case 14:
case 15:
case 16:
case 17:
case 18:
case 19:
case 26:
case 27:
case 31:
case 32:
case 33:
case 34:
case 35:
case 36:
case IDENTIFIER:
case ESCAPED_IDENTIFIER:
case PREFIXED_NAME:
;
break;
default:
jj_la1[58] = jj_gen;
break label_22;
}
e = AnnotationElement(false);
a.addElement(e); annotationsIncludeElements = true;
}
a.addComment(getComments());
jj_consume_token(9);
break;
default:
jj_la1[59] = jj_gen;
;
}
if (a == null && comments != null)
a = sb.makeAnnotations(comments, getContext());
{if (true) return a;}
throw new Error("Missing return statement in function");
}
final public void AnnotationAttribute(Annotations<Location, ElementAnnotation, CommentListImpl> a) throws ParseException {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case PREFIXED_NAME:
PrefixedAnnotationAttribute(a, true);
break;
case 5:
case 6:
case 7:
case 10:
case 13:
case 14:
case 15:
case 16:
case 17:
case 18:
case 19:
case 26:
case 27:
case 31:
case 32:
case 33:
case 34:
case 35:
case 36:
case IDENTIFIER:
case ESCAPED_IDENTIFIER:
UnprefixedAnnotationAttribute(a);
break;
default:
jj_la1[60] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
}
final public void PrefixedAnnotationAttribute(Annotations<Location, ElementAnnotation, CommentListImpl> a, boolean nested) throws ParseException {
Token t;
String value;
t = jj_consume_token(PREFIXED_NAME);
jj_consume_token(2);
value = Literal();
String qn = t.image;
int colon = qn.indexOf(':');
String prefix = qn.substring(0, colon);
String ns = lookupPrefix(prefix, t);
if (ns == SchemaBuilder.INHERIT_NS)
error("inherited_annotation_namespace", t);
else if (ns.length() == 0 && !nested)
error("unqualified_annotation_attribute", t);
else if (ns.equals(WellKnownNamespaces.RELAX_NG) && !nested)
error("relax_ng_namespace", t);
/*else if (ns.length() == 0
&& qn.length() - colon - 1 == 5
&& qn.regionMatches(colon + 1, "xmlns", 0, 5))
error("xmlns_annotation_attribute", t);*/
else if (ns.equals(WellKnownNamespaces.XMLNS))
error("xmlns_annotation_attribute_uri", t);
else {
if (ns.length() == 0)
prefix = null;
addAttribute(a, ns, qn.substring(colon + 1), prefix, value, t);
}
}
final public void UnprefixedAnnotationAttribute(Annotations<Location, ElementAnnotation, CommentListImpl> a) throws ParseException {
LocatedString name;
String value;
name = UnprefixedName();
jj_consume_token(2);
value = Literal();
if (name.getString().equals("xmlns"))
error("xmlns_annotation_attribute", name.getToken());
else
addAttribute(a, "", name.getString(), null, value, name.getToken());
}
final public ElementAnnotation AnnotationElement(boolean nested) throws ParseException {
ElementAnnotation a;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case PREFIXED_NAME:
a = PrefixedAnnotationElement(nested);
break;
case 5:
case 6:
case 7:
case 10:
case 13:
case 14:
case 15:
case 16:
case 17:
case 18:
case 19:
case 26:
case 27:
case 31:
case 32:
case 33:
case 34:
case 35:
case 36:
case IDENTIFIER:
case ESCAPED_IDENTIFIER:
a = UnprefixedAnnotationElement();
break;
default:
jj_la1[61] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
{if (true) return a;}
throw new Error("Missing return statement in function");
}
final public ElementAnnotation AnnotationElementNotKeyword() throws ParseException {
ElementAnnotation a;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case PREFIXED_NAME:
a = PrefixedAnnotationElement(false);
break;
case IDENTIFIER:
case ESCAPED_IDENTIFIER:
a = IdentifierAnnotationElement();
break;
default:
jj_la1[62] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
{if (true) return a;}
throw new Error("Missing return statement in function");
}
final public ElementAnnotation PrefixedAnnotationElement(boolean nested) throws ParseException {
CommentListImpl comments = getComments();
Token t;
ElementAnnotationBuilder<Location, ElementAnnotation, CommentListImpl> eab;
t = jj_consume_token(PREFIXED_NAME);
String qn = t.image;
int colon = qn.indexOf(':');
String prefix = qn.substring(0, colon);
String ns = lookupPrefix(prefix, t);
if (ns == SchemaBuilder.INHERIT_NS) {
error("inherited_annotation_namespace", t);
ns = "";
}
else if (!nested && ns.equals(WellKnownNamespaces.RELAX_NG)) {
error("relax_ng_namespace", t);
ns = "";
}
else {
if (ns.length() == 0)
prefix = null;
}
eab = sb.makeElementAnnotationBuilder(ns, qn.substring(colon + 1), prefix,
makeLocation(t), comments, getContext());
AnnotationElementContent(eab);
{if (true) return eab.makeElementAnnotation();}
throw new Error("Missing return statement in function");
}
final public ElementAnnotation UnprefixedAnnotationElement() throws ParseException {
CommentListImpl comments = getComments();
LocatedString name;
ElementAnnotationBuilder<Location, ElementAnnotation, CommentListImpl> eab;
name = UnprefixedName();
eab = sb.makeElementAnnotationBuilder("", name.getString(), null,
name.getLocation(), comments, getContext());
AnnotationElementContent(eab);
{if (true) return eab.makeElementAnnotation();}
throw new Error("Missing return statement in function");
}
final public ElementAnnotation IdentifierAnnotationElement() throws ParseException {
CommentListImpl comments = getComments();
LocatedString name;
ElementAnnotationBuilder<Location, ElementAnnotation, CommentListImpl> eab;
name = Identifier();
eab = sb.makeElementAnnotationBuilder("", name.getString(), null,
name.getLocation(), comments, getContext());
AnnotationElementContent(eab);
{if (true) return eab.makeElementAnnotation();}
throw new Error("Missing return statement in function");
}
final public void AnnotationElementContent(ElementAnnotationBuilder<Location, ElementAnnotation, CommentListImpl> eab) throws ParseException {
ElementAnnotation e;
jj_consume_token(1);
clearAttributeList();
label_23:
while (true) {
if (jj_2_8(2)) {
;
} else {
break label_23;
}
AnnotationAttribute(eab);
}
label_24:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 5:
case 6:
case 7:
case 10:
case 13:
case 14:
case 15:
case 16:
case 17:
case 18:
case 19:
case 26:
case 27:
case 31:
case 32:
case 33:
case 34:
case 35:
case 36:
case IDENTIFIER:
case ESCAPED_IDENTIFIER:
case PREFIXED_NAME:
case LITERAL:
;
break;
default:
jj_la1[63] = jj_gen;
break label_24;
}
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case LITERAL:
AnnotationElementLiteral(eab);
label_25:
while (true) {
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 8:
;
break;
default:
jj_la1[64] = jj_gen;
break label_25;
}
jj_consume_token(8);
AnnotationElementLiteral(eab);
}
break;
case 5:
case 6:
case 7:
case 10:
case 13:
case 14:
case 15:
case 16:
case 17:
case 18:
case 19:
case 26:
case 27:
case 31:
case 32:
case 33:
case 34:
case 35:
case 36:
case IDENTIFIER:
case ESCAPED_IDENTIFIER:
case PREFIXED_NAME:
e = AnnotationElement(true);
eab.addElement(e);
break;
default:
jj_la1[65] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
}
eab.addComment(getComments());
jj_consume_token(9);
}
final public void AnnotationElementLiteral(ElementAnnotationBuilder<Location, ElementAnnotation, CommentListImpl> eab) throws ParseException {
Token t;
CommentListImpl comments = getComments();
t = jj_consume_token(LITERAL);
eab.addText(unquote(t.image), makeLocation(t), comments);
}
final public String Literal() throws ParseException {
Token t;
String s;
StringBuffer buf;
t = jj_consume_token(LITERAL);
s = unquote(t.image);
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 8:
buf = new StringBuffer(s);
label_26:
while (true) {
jj_consume_token(8);
t = jj_consume_token(LITERAL);
buf.append(unquote(t.image));
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 8:
;
break;
default:
jj_la1[66] = jj_gen;
break label_26;
}
}
s = buf.toString();
break;
default:
jj_la1[67] = jj_gen;
;
}
{if (true) return s;}
throw new Error("Missing return statement in function");
}
final public LocatedString LocatedLiteral() throws ParseException {
Token t;
Token t2;
String s;
StringBuffer buf;
t = jj_consume_token(LITERAL);
s = unquote(t.image);
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 8:
buf = new StringBuffer(s);
label_27:
while (true) {
jj_consume_token(8);
t2 = jj_consume_token(LITERAL);
buf.append(unquote(t2.image));
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 8:
;
break;
default:
jj_la1[68] = jj_gen;
break label_27;
}
}
s = buf.toString();
break;
default:
jj_la1[69] = jj_gen;
;
}
{if (true) return new LocatedString(s, t);}
throw new Error("Missing return statement in function");
}
final public Token Keyword() throws ParseException {
Token t;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case 26:
t = jj_consume_token(26);
break;
case 27:
t = jj_consume_token(27);
break;
case 13:
t = jj_consume_token(13);
break;
case 31:
t = jj_consume_token(31);
break;
case 32:
t = jj_consume_token(32);
break;
case 10:
t = jj_consume_token(10);
break;
case 17:
t = jj_consume_token(17);
break;
case 18:
t = jj_consume_token(18);
break;
case 34:
t = jj_consume_token(34);
break;
case 33:
t = jj_consume_token(33);
break;
case 19:
t = jj_consume_token(19);
break;
case 5:
t = jj_consume_token(5);
break;
case 7:
t = jj_consume_token(7);
break;
case 14:
t = jj_consume_token(14);
break;
case 15:
t = jj_consume_token(15);
break;
case 35:
t = jj_consume_token(35);
break;
case 36:
t = jj_consume_token(36);
break;
case 16:
t = jj_consume_token(16);
break;
case 6:
t = jj_consume_token(6);
break;
default:
jj_la1[70] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
{if (true) return t;}
throw new Error("Missing return statement in function");
}
private boolean jj_2_1(int xla) {
jj_la = xla; jj_lastpos = jj_scanpos = token;
try { return !jj_3_1(); }
catch(LookaheadSuccess ls) { return true; }
finally { jj_save(0, xla); }
}
private boolean jj_2_2(int xla) {
jj_la = xla; jj_lastpos = jj_scanpos = token;
try { return !jj_3_2(); }
catch(LookaheadSuccess ls) { return true; }
finally { jj_save(1, xla); }
}
private boolean jj_2_3(int xla) {
jj_la = xla; jj_lastpos = jj_scanpos = token;
try { return !jj_3_3(); }
catch(LookaheadSuccess ls) { return true; }
finally { jj_save(2, xla); }
}
private boolean jj_2_4(int xla) {
jj_la = xla; jj_lastpos = jj_scanpos = token;
try { return !jj_3_4(); }
catch(LookaheadSuccess ls) { return true; }
finally { jj_save(3, xla); }
}
private boolean jj_2_5(int xla) {
jj_la = xla; jj_lastpos = jj_scanpos = token;
try { return !jj_3_5(); }
catch(LookaheadSuccess ls) { return true; }
finally { jj_save(4, xla); }
}
private boolean jj_2_6(int xla) {
jj_la = xla; jj_lastpos = jj_scanpos = token;
try { return !jj_3_6(); }
catch(LookaheadSuccess ls) { return true; }
finally { jj_save(5, xla); }
}
private boolean jj_2_7(int xla) {
jj_la = xla; jj_lastpos = jj_scanpos = token;
try { return !jj_3_7(); }
catch(LookaheadSuccess ls) { return true; }
finally { jj_save(6, xla); }
}
private boolean jj_2_8(int xla) {
jj_la = xla; jj_lastpos = jj_scanpos = token;
try { return !jj_3_8(); }
catch(LookaheadSuccess ls) { return true; }
finally { jj_save(7, xla); }
}
private boolean jj_3R_49() {
if (jj_3R_57()) return true;
if (jj_scan_token(2)) return true;
return false;
}
private boolean jj_3R_40() {
if (jj_3R_49()) return true;
return false;
}
private boolean jj_3R_48() {
if (jj_3R_41()) return true;
if (jj_3R_56()) return true;
return false;
}
private boolean jj_3_3() {
if (jj_3R_29()) return true;
return false;
}
private boolean jj_3_6() {
if (jj_3R_29()) return true;
return false;
}
private boolean jj_3_2() {
if (jj_3R_28()) return true;
return false;
}
private boolean jj_3R_58() {
if (jj_3R_57()) return true;
return false;
}
private boolean jj_3_5() {
if (jj_3R_29()) return true;
return false;
}
private boolean jj_3R_62() {
Token xsp;
xsp = jj_scanpos;
if (jj_scan_token(26)) {
jj_scanpos = xsp;
if (jj_scan_token(27)) {
jj_scanpos = xsp;
if (jj_scan_token(13)) {
jj_scanpos = xsp;
if (jj_scan_token(31)) {
jj_scanpos = xsp;
if (jj_scan_token(32)) {
jj_scanpos = xsp;
if (jj_scan_token(10)) {
jj_scanpos = xsp;
if (jj_scan_token(17)) {
jj_scanpos = xsp;
if (jj_scan_token(18)) {
jj_scanpos = xsp;
if (jj_scan_token(34)) {
jj_scanpos = xsp;
if (jj_scan_token(33)) {
jj_scanpos = xsp;
if (jj_scan_token(19)) {
jj_scanpos = xsp;
if (jj_scan_token(5)) {
jj_scanpos = xsp;
if (jj_scan_token(7)) {
jj_scanpos = xsp;
if (jj_scan_token(14)) {
jj_scanpos = xsp;
if (jj_scan_token(15)) {
jj_scanpos = xsp;
if (jj_scan_token(35)) {
jj_scanpos = xsp;
if (jj_scan_token(36)) {
jj_scanpos = xsp;
if (jj_scan_token(16)) {
jj_scanpos = xsp;
if (jj_scan_token(6)) return true;
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
return false;
}
private boolean jj_3R_61() {
if (jj_3R_62()) return true;
return false;
}
private boolean jj_3R_30() {
if (jj_scan_token(PREFIXED_NAME)) return true;
if (jj_scan_token(2)) return true;
return false;
}
private boolean jj_3R_60() {
if (jj_3R_41()) return true;
return false;
}
private boolean jj_3R_57() {
Token xsp;
xsp = jj_scanpos;
if (jj_3R_60()) {
jj_scanpos = xsp;
if (jj_3R_61()) return true;
}
return false;
}
private boolean jj_3R_46() {
if (jj_3R_43()) return true;
return false;
}
private boolean jj_3R_52() {
Token xsp;
xsp = jj_scanpos;
if (jj_scan_token(57)) {
jj_scanpos = xsp;
if (jj_3R_58()) {
jj_scanpos = xsp;
if (jj_scan_token(2)) {
jj_scanpos = xsp;
if (jj_scan_token(58)) {
jj_scanpos = xsp;
if (jj_scan_token(8)) {
jj_scanpos = xsp;
if (jj_3R_59()) return true;
}
}
}
}
}
return false;
}
private boolean jj_3R_43() {
if (jj_scan_token(1)) return true;
Token xsp;
while (true) {
xsp = jj_scanpos;
if (jj_3R_52()) { jj_scanpos = xsp; break; }
}
if (jj_scan_token(9)) return true;
return false;
}
private boolean jj_3R_31() {
Token xsp;
xsp = jj_scanpos;
if (jj_3R_39()) {
jj_scanpos = xsp;
if (jj_3R_40()) return true;
}
return false;
}
private boolean jj_3R_39() {
if (jj_3R_30()) return true;
return false;
}
private boolean jj_3R_55() {
Token xsp;
xsp = jj_scanpos;
if (jj_scan_token(40)) {
jj_scanpos = xsp;
if (jj_scan_token(43)) return true;
}
while (true) {
xsp = jj_scanpos;
if (jj_scan_token(41)) { jj_scanpos = xsp; break; }
}
return false;
}
private boolean jj_3R_45() {
Token xsp;
if (jj_3R_55()) return true;
while (true) {
xsp = jj_scanpos;
if (jj_3R_55()) { jj_scanpos = xsp; break; }
}
return false;
}
private boolean jj_3_7() {
if (jj_3R_30()) return true;
return false;
}
private boolean jj_3R_42() {
Token xsp;
xsp = jj_scanpos;
if (jj_scan_token(5)) {
jj_scanpos = xsp;
if (jj_scan_token(6)) {
jj_scanpos = xsp;
if (jj_scan_token(7)) return true;
}
}
return false;
}
private boolean jj_3R_54() {
if (jj_3R_42()) return true;
return false;
}
private boolean jj_3R_51() {
if (jj_scan_token(ESCAPED_IDENTIFIER)) return true;
return false;
}
private boolean jj_3R_50() {
if (jj_scan_token(IDENTIFIER)) return true;
return false;
}
private boolean jj_3R_44() {
Token xsp;
xsp = jj_scanpos;
if (jj_3R_53()) {
jj_scanpos = xsp;
if (jj_3R_54()) return true;
}
return false;
}
private boolean jj_3R_53() {
if (jj_3R_41()) return true;
Token xsp;
xsp = jj_scanpos;
if (jj_scan_token(2)) {
jj_scanpos = xsp;
if (jj_scan_token(3)) {
jj_scanpos = xsp;
if (jj_scan_token(4)) return true;
}
}
return false;
}
private boolean jj_3R_41() {
Token xsp;
xsp = jj_scanpos;
if (jj_3R_50()) {
jj_scanpos = xsp;
if (jj_3R_51()) return true;
}
return false;
}
private boolean jj_3R_47() {
if (jj_scan_token(PREFIXED_NAME)) return true;
if (jj_3R_56()) return true;
return false;
}
private boolean jj_3R_36() {
if (jj_3R_45()) return true;
Token xsp;
xsp = jj_scanpos;
if (jj_3R_46()) jj_scanpos = xsp;
if (jj_3R_44()) return true;
return false;
}
private boolean jj_3R_35() {
if (jj_3R_43()) return true;
if (jj_3R_44()) return true;
return false;
}
private boolean jj_3R_34() {
if (jj_3R_42()) return true;
return false;
}
private boolean jj_3R_33() {
if (jj_3R_41()) return true;
Token xsp;
xsp = jj_scanpos;
if (jj_scan_token(1)) {
jj_scanpos = xsp;
if (jj_scan_token(2)) {
jj_scanpos = xsp;
if (jj_scan_token(3)) {
jj_scanpos = xsp;
if (jj_scan_token(4)) return true;
}
}
}
return false;
}
private boolean jj_3_1() {
if (jj_3R_28()) return true;
return false;
}
private boolean jj_3R_32() {
if (jj_scan_token(PREFIXED_NAME)) return true;
if (jj_scan_token(1)) return true;
return false;
}
private boolean jj_3R_28() {
Token xsp;
xsp = jj_scanpos;
if (jj_3R_32()) {
jj_scanpos = xsp;
if (jj_3R_33()) {
jj_scanpos = xsp;
if (jj_3R_34()) {
jj_scanpos = xsp;
if (jj_3R_35()) {
jj_scanpos = xsp;
if (jj_3R_36()) return true;
}
}
}
}
return false;
}
private boolean jj_3R_38() {
if (jj_3R_48()) return true;
return false;
}
private boolean jj_3R_59() {
if (jj_3R_43()) return true;
return false;
}
private boolean jj_3R_37() {
if (jj_3R_47()) return true;
return false;
}
private boolean jj_3R_29() {
Token xsp;
xsp = jj_scanpos;
if (jj_3R_37()) {
jj_scanpos = xsp;
if (jj_3R_38()) return true;
}
return false;
}
private boolean jj_3_8() {
if (jj_3R_31()) return true;
return false;
}
private boolean jj_3_4() {
if (jj_3R_29()) return true;
return false;
}
private boolean jj_3R_56() {
if (jj_scan_token(1)) return true;
return false;
}
/** Generated Token Manager. */
public CompactSyntaxTokenManager token_source;
JavaCharStream jj_input_stream;
/** Current token. */
public Token token;
/** Next token. */
public Token jj_nt;
private int jj_ntk;
private Token jj_scanpos, jj_lastpos;
private int jj_la;
private int jj_gen;
final private int[] jj_la1 = new int[71];
static private int[] jj_la1_0;
static private int[] jj_la1_1;
static {
jj_la1_init_0();
jj_la1_init_1();
}
private static void jj_la1_init_0() {
jj_la1_0 = new int[] {0x9c0e0402,0x1e,0x2,0xe2,0x1c,0xe0,0xe0,0x0,0x0,0x0,0x8c0fe5e6,0x8c0fe5e6,0x402,0x16000,0x16000,0x8c0fe4e0,0x6000,0x8000,0x0,0x9c0e0400,0x100000,0x200000,0x400000,0x700000,0x700000,0x3800000,0x0,0x3800000,0x9e0fe4e0,0x0,0x100000,0x100000,0x9e0fe4e0,0x9c0fe4e0,0x2000000,0x40000000,0x40000000,0xe2,0xe0,0x20,0x1c,0x800,0x62,0x60,0x8000,0x40000000,0x40000000,0x800,0x0,0x0,0x0,0x8c0fe4e0,0x8c0fe4e0,0x8c0fe4e2,0x0,0x0,0x0,0x0,0x8c0fe4e0,0x2,0x8c0fe4e0,0x8c0fe4e0,0x0,0x8c0fe4e0,0x100,0x8c0fe4e0,0x100,0x100,0x100,0x100,0x8c0fe4e0,};
}
private static void jj_la1_init_1() {
jj_la1_1 = new int[] {0x6c0091f,0x0,0x0,0x2c00900,0x0,0xc00000,0x0,0x900,0x200,0x900,0x6c0001f,0x6c0001f,0x900,0x0,0x0,0xc0001f,0x0,0x4000000,0x8000000,0x6c0001f,0x0,0x0,0x0,0x0,0x0,0x0,0x8000000,0x0,0x3c0001f,0x8000000,0x0,0x0,0x3c0001f,0x2c0001f,0x1000000,0x0,0x0,0xc00900,0xc00000,0xc00000,0x0,0x0,0xc00900,0xc00000,0x0,0x0,0x0,0x0,0x4000000,0x2000018,0xc00000,0xc0001f,0xc0001f,0xc0091f,0x900,0x200,0x900,0x900,0x2c0001f,0x0,0x2c0001f,0x2c0001f,0x2c00000,0x6c0001f,0x0,0x6c0001f,0x0,0x0,0x0,0x0,0x1f,};
}
final private JJCalls[] jj_2_rtns = new JJCalls[8];
private boolean jj_rescan = false;
private int jj_gc = 0;
/** Constructor with InputStream. */
public CompactSyntax(java.io.InputStream stream) {
this(stream, null);
}
/** Constructor with InputStream and supplied encoding */
public CompactSyntax(java.io.InputStream stream, String encoding) {
try { jj_input_stream = new JavaCharStream(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
token_source = new CompactSyntaxTokenManager(jj_input_stream);
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 71; i++) jj_la1[i] = -1;
for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
}
/** Reinitialise. */
public void ReInit(java.io.InputStream stream) {
ReInit(stream, null);
}
/** Reinitialise. */
public void ReInit(java.io.InputStream stream, String encoding) {
try { jj_input_stream.ReInit(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
token_source.ReInit(jj_input_stream);
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 71; i++) jj_la1[i] = -1;
for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
}
/** Constructor. */
public CompactSyntax(java.io.Reader stream) {
jj_input_stream = new JavaCharStream(stream, 1, 1);
token_source = new CompactSyntaxTokenManager(jj_input_stream);
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 71; i++) jj_la1[i] = -1;
for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
}
/** Reinitialise. */
public void ReInit(java.io.Reader stream) {
jj_input_stream.ReInit(stream, 1, 1);
token_source.ReInit(jj_input_stream);
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 71; i++) jj_la1[i] = -1;
for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
}
/** Constructor with generated Token Manager. */
public CompactSyntax(CompactSyntaxTokenManager tm) {
token_source = tm;
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 71; i++) jj_la1[i] = -1;
for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
}
/** Reinitialise. */
public void ReInit(CompactSyntaxTokenManager tm) {
token_source = tm;
token = new Token();
jj_ntk = -1;
jj_gen = 0;
for (int i = 0; i < 71; i++) jj_la1[i] = -1;
for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
}
private Token jj_consume_token(int kind) throws ParseException {
Token oldToken;
if ((oldToken = token).next != null) token = token.next;
else token = token.next = token_source.getNextToken();
jj_ntk = -1;
if (token.kind == kind) {
jj_gen++;
if (++jj_gc > 100) {
jj_gc = 0;
for (int i = 0; i < jj_2_rtns.length; i++) {
JJCalls c = jj_2_rtns[i];
while (c != null) {
if (c.gen < jj_gen) c.first = null;
c = c.next;
}
}
}
return token;
}
token = oldToken;
jj_kind = kind;
throw generateParseException();
}
static private final class LookaheadSuccess extends java.lang.Error { }
final private LookaheadSuccess jj_ls = new LookaheadSuccess();
private boolean jj_scan_token(int kind) {
if (jj_scanpos == jj_lastpos) {
jj_la--;
if (jj_scanpos.next == null) {
jj_lastpos = jj_scanpos = jj_scanpos.next = token_source.getNextToken();
} else {
jj_lastpos = jj_scanpos = jj_scanpos.next;
}
} else {
jj_scanpos = jj_scanpos.next;
}
if (jj_rescan) {
int i = 0; Token tok = token;
while (tok != null && tok != jj_scanpos) { i++; tok = tok.next; }
if (tok != null) jj_add_error_token(kind, i);
}
if (jj_scanpos.kind != kind) return true;
if (jj_la == 0 && jj_scanpos == jj_lastpos) throw jj_ls;
return false;
}
/** Get the next Token. */
final public Token getNextToken() {
if (token.next != null) token = token.next;
else token = token.next = token_source.getNextToken();
jj_ntk = -1;
jj_gen++;
return token;
}
/** Get the specific Token. */
final public Token getToken(int index) {
Token t = token;
for (int i = 0; i < index; i++) {
if (t.next != null) t = t.next;
else t = t.next = token_source.getNextToken();
}
return t;
}
private int jj_ntk() {
if ((jj_nt=token.next) == null)
return (jj_ntk = (token.next=token_source.getNextToken()).kind);
else
return (jj_ntk = jj_nt.kind);
}
private java.util.List jj_expentries = new java.util.ArrayList();
private int[] jj_expentry;
private int jj_kind = -1;
private int[] jj_lasttokens = new int[100];
private int jj_endpos;
private void jj_add_error_token(int kind, int pos) {
if (pos >= 100) return;
if (pos == jj_endpos + 1) {
jj_lasttokens[jj_endpos++] = kind;
} else if (jj_endpos != 0) {
jj_expentry = new int[jj_endpos];
for (int i = 0; i < jj_endpos; i++) {
jj_expentry[i] = jj_lasttokens[i];
}
jj_entries_loop: for (java.util.Iterator it = jj_expentries.iterator(); it.hasNext();) {
int[] oldentry = (int[])(it.next());
if (oldentry.length == jj_expentry.length) {
for (int i = 0; i < jj_expentry.length; i++) {
if (oldentry[i] != jj_expentry[i]) {
continue jj_entries_loop;
}
}
jj_expentries.add(jj_expentry);
break jj_entries_loop;
}
}
if (pos != 0) jj_lasttokens[(jj_endpos = pos) - 1] = kind;
}
}
/** Generate ParseException. */
public ParseException generateParseException() {
jj_expentries.clear();
boolean[] la1tokens = new boolean[61];
if (jj_kind >= 0) {
la1tokens[jj_kind] = true;
jj_kind = -1;
}
for (int i = 0; i < 71; i++) {
if (jj_la1[i] == jj_gen) {
for (int j = 0; j < 32; j++) {
if ((jj_la1_0[i] & (1<<j)) != 0) {
la1tokens[j] = true;
}
if ((jj_la1_1[i] & (1<<j)) != 0) {
la1tokens[32+j] = true;
}
}
}
}
for (int i = 0; i < 61; i++) {
if (la1tokens[i]) {
jj_expentry = new int[1];
jj_expentry[0] = i;
jj_expentries.add(jj_expentry);
}
}
jj_endpos = 0;
jj_rescan_token();
jj_add_error_token(0, 0);
int[][] exptokseq = new int[jj_expentries.size()][];
for (int i = 0; i < jj_expentries.size(); i++) {
exptokseq[i] = (int[])jj_expentries.get(i);
}
return new ParseException(token, exptokseq, tokenImage);
}
/** Enable tracing. */
final public void enable_tracing() {
}
/** Disable tracing. */
final public void disable_tracing() {
}
private void jj_rescan_token() {
jj_rescan = true;
for (int i = 0; i < 8; i++) {
try {
JJCalls p = jj_2_rtns[i];
do {
if (p.gen > jj_gen) {
jj_la = p.arg; jj_lastpos = jj_scanpos = p.first;
switch (i) {
case 0: jj_3_1(); break;
case 1: jj_3_2(); break;
case 2: jj_3_3(); break;
case 3: jj_3_4(); break;
case 4: jj_3_5(); break;
case 5: jj_3_6(); break;
case 6: jj_3_7(); break;
case 7: jj_3_8(); break;
}
}
p = p.next;
} while (p != null);
} catch(LookaheadSuccess ls) { }
}
jj_rescan = false;
}
private void jj_save(int index, int xla) {
JJCalls p = jj_2_rtns[index];
while (p.gen > jj_gen) {
if (p.next == null) { p = p.next = new JJCalls(); break; }
p = p.next;
}
p.gen = jj_gen + xla - jj_la; p.first = token; p.arg = xla;
}
static final class JJCalls {
int gen;
Token first;
int arg;
JJCalls next;
}
}
|
92460d3c52d14bde9fe437dc3a3513e3a291d92b
| 633 |
java
|
Java
|
azure-functions-gradle-plugin/src/main/java/lenala/azure/gradle/functions/bindings/StorageBaseBinding.java
|
feilfeilundfeil/azure-gradle-plugins
|
83b774733aad4057baa6f4e3c5008a6791ce6576
|
[
"MIT"
] | null | null | null |
azure-functions-gradle-plugin/src/main/java/lenala/azure/gradle/functions/bindings/StorageBaseBinding.java
|
feilfeilundfeil/azure-gradle-plugins
|
83b774733aad4057baa6f4e3c5008a6791ce6576
|
[
"MIT"
] | null | null | null |
azure-functions-gradle-plugin/src/main/java/lenala/azure/gradle/functions/bindings/StorageBaseBinding.java
|
feilfeilundfeil/azure-gradle-plugins
|
83b774733aad4057baa6f4e3c5008a6791ce6576
|
[
"MIT"
] | null | null | null | 27.521739 | 95 | 0.739336 | 1,003,625 |
package lenala.azure.gradle.functions.bindings;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonInclude;
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public abstract class StorageBaseBinding extends BaseBinding {
private String connection = "";
protected StorageBaseBinding(String name, String type, String direction, String dataType) {
super(name, type, direction, dataType);
}
@JsonGetter
public String getConnection() {
return connection;
}
public void setConnection(String connection) {
this.connection = connection;
}
}
|
92460d824b80acba8f1a4219ff1b3bf0ee16d0ab
| 7,706 |
java
|
Java
|
src/main/java/org/jhotdraw/app/action/AbstractSaveUnsavedChangesAction.java
|
openTCS/opentcs-thirdparty-jhotdraw
|
bf28f69cd55cf3cc12107f7cc696f2bd9137706e
|
[
"MIT"
] | 1 |
2022-03-24T14:13:56.000Z
|
2022-03-24T14:13:56.000Z
|
src/main/java/org/jhotdraw/app/action/AbstractSaveUnsavedChangesAction.java
|
openTCS/opentcs-thirdparty-jhotdraw
|
bf28f69cd55cf3cc12107f7cc696f2bd9137706e
|
[
"MIT"
] | null | null | null |
src/main/java/org/jhotdraw/app/action/AbstractSaveUnsavedChangesAction.java
|
openTCS/opentcs-thirdparty-jhotdraw
|
bf28f69cd55cf3cc12107f7cc696f2bd9137706e
|
[
"MIT"
] | null | null | null | 41.430108 | 158 | 0.565274 | 1,003,626 |
/*
* @(#)AbstractSaveUnsavedChangesAction.java
*
* Copyright (c) 1996-2010 by the original authors of JHotDraw and all its
* contributors. All rights reserved.
*
* You may not use, copy or modify this file, except in compliance with the
* license agreement you entered into with the copyright holders. For details
* see accompanying license terms.
*/
package org.jhotdraw.app.action;
import edu.umd.cs.findbugs.annotations.Nullable;
import org.jhotdraw.gui.filechooser.ExtensionFileFilter;
import org.jhotdraw.gui.*;
import org.jhotdraw.gui.event.*;
import org.jhotdraw.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.URI;
import org.jhotdraw.app.Application;
import org.jhotdraw.app.View;
import org.jhotdraw.gui.URIChooser;
import org.jhotdraw.gui.JFileURIChooser;
import org.jhotdraw.net.URIUtil;
/**
* This abstract class can be extended to implement an {@code Action} that asks
* to save unsaved changes of a {@link org.jhotdraw.app.View} before a destructive
* action is performed.
* <p>
* If the view has no unsaved changes, method {@code doIt} is invoked immediately.
* If unsaved changes are present, a dialog is shown asking whether the user
* wants to discard the changes, cancel or save the changes before doing it.
* If the user chooses to discard the changes, {@code doIt} is invoked immediately.
* If the user chooses to cancel, the action is aborted.
* If the user chooses to save the changes, the view is saved, and {@code doIt}
* is only invoked after the view was successfully saved.
*
* @author Werner Randelshofer
* @version $Id: AbstractSaveUnsavedChangesAction.java 717 2010-11-21 12:30:57Z rawcoder $
*/
public abstract class AbstractSaveUnsavedChangesAction extends AbstractViewAction {
@Nullable
private Component oldFocusOwner;
/** Creates a new instance. */
public AbstractSaveUnsavedChangesAction(Application app, @Nullable View view) {
super(app, view);
}
@Override
public void actionPerformed(ActionEvent evt) {
final View v = getActiveView();
if (v == null) {
return;
}
if (v.isEnabled()) {
final ResourceBundleUtil labels = ResourceBundleUtil.getBundle("org.jhotdraw.app.Labels");
Window wAncestor = SwingUtilities.getWindowAncestor(v.getComponent());
oldFocusOwner = (wAncestor == null) ? null : wAncestor.getFocusOwner();
v.setEnabled(false);
if (v.hasUnsavedChanges()) {
URI unsavedURI = v.getURI();
JOptionPane pane = new JOptionPane(
"<html>" + UIManager.getString("OptionPane.css") +//
"<b>" + labels.getFormatted("file.saveBefore.doYouWantToSave.message",//
(unsavedURI == null) ? labels.getString("unnamedFile") : URIUtil.getName(unsavedURI)) + "</b><p>" +//
labels.getString("file.saveBefore.doYouWantToSave.details"),
JOptionPane.WARNING_MESSAGE);
Object[] options = { //
labels.getString("file.saveBefore.saveOption.text"),//
labels.getString("file.saveBefore.cancelOption.text"), //
labels.getString("file.saveBefore.dontSaveOption.text")//
};
pane.setOptions(options);
pane.setInitialValue(options[0]);
pane.putClientProperty("Quaqua.OptionPane.destructiveOption", 2);
JSheet.showSheet(pane, v.getComponent(), new SheetListener() {
@Override
public void optionSelected(SheetEvent evt) {
Object value = evt.getValue();
if (value == null || value.equals(labels.getString("file.saveBefore.cancelOption.text"))) {
v.setEnabled(true);
} else if (value.equals(labels.getString("file.saveBefore.dontSaveOption.text"))) {
doIt(v);
v.setEnabled(true);
} else if (value.equals(labels.getString("file.saveBefore.saveOption.text"))) {
saveView(v);
}
}
});
} else {
doIt(v);
v.setEnabled(true);
if (oldFocusOwner != null) {
oldFocusOwner.requestFocus();
}
}
}
}
protected URIChooser getChooser(View view) {
URIChooser chsr = (URIChooser) (view.getComponent()).getClientProperty("saveChooser");
if (chsr == null) {
chsr = getApplication().getModel().createSaveChooser(getApplication(), view);
view.getComponent().putClientProperty("saveChooser", chsr);
}
return chsr;
}
protected void saveView(final View v) {
if (v.getURI() == null) {
URIChooser chooser = getChooser(v);
//int option = fileChooser.showSaveDialog(this);
JSheet.showSaveSheet(chooser, v.getComponent(), new SheetListener() {
@Override
public void optionSelected(final SheetEvent evt) {
if (evt.getOption() == JFileChooser.APPROVE_OPTION) {
final URI uri;
if ((evt.getChooser() instanceof JFileURIChooser) && evt.getFileChooser().getFileFilter() instanceof ExtensionFileFilter) {
uri = ((ExtensionFileFilter) evt.getFileChooser().getFileFilter()).makeAcceptable(evt.getFileChooser().getSelectedFile()).toURI();
} else {
uri = evt.getChooser().getSelectedURI();
}
saveViewToURI(v, uri, evt.getChooser());
} else {
v.setEnabled(true);
if (oldFocusOwner != null) {
oldFocusOwner.requestFocus();
}
}
}
});
} else {
saveViewToURI(v, v.getURI(), null);
}
}
protected void saveViewToURI(final View v, final URI uri, @Nullable final URIChooser chooser) {
v.execute(new Worker() {
@Override
protected Object construct() throws IOException {
v.write(uri, chooser);
return null;
}
@Override
protected void done(Object value) {
v.setURI(uri);
v.markChangesAsSaved();
doIt(v);
}
@Override
protected void failed(Throwable value) {
String message = (value.getMessage() != null) ? value.getMessage() : value.toString();
ResourceBundleUtil labels = ResourceBundleUtil.getBundle("org.jhotdraw.app.Labels");
JSheet.showMessageSheet(getActiveView().getComponent(),
"<html>" + UIManager.getString("OptionPane.css")
+ "<b>" + labels.getFormatted("file.save.couldntSave.message", URIUtil.getName(uri)) + "</b><p>"
+ ((message == null) ? "" : message),
JOptionPane.ERROR_MESSAGE);
}
@Override
protected void finished() {
v.setEnabled(true);
if (oldFocusOwner != null) {
oldFocusOwner.requestFocus();
}
}
});
}
protected abstract void doIt(View p);
}
|
92460de90caa18e5901b1bf915ecffecb8ab104f
| 963 |
java
|
Java
|
currency-conversion-service/src/main/java/com/practice/microservices/currencyconversionservice/controllers/CurrencyConversionController.java
|
acanozturk/microservices-practice
|
3d05d9aed1ba5dd7e20e2fb9d18828ec51d93be8
|
[
"Apache-2.0"
] | null | null | null |
currency-conversion-service/src/main/java/com/practice/microservices/currencyconversionservice/controllers/CurrencyConversionController.java
|
acanozturk/microservices-practice
|
3d05d9aed1ba5dd7e20e2fb9d18828ec51d93be8
|
[
"Apache-2.0"
] | null | null | null |
currency-conversion-service/src/main/java/com/practice/microservices/currencyconversionservice/controllers/CurrencyConversionController.java
|
acanozturk/microservices-practice
|
3d05d9aed1ba5dd7e20e2fb9d18828ec51d93be8
|
[
"Apache-2.0"
] | null | null | null | 41.869565 | 111 | 0.830737 | 1,003,627 |
package com.practice.microservices.currencyconversionservice.controllers;
import com.practice.microservices.currencyconversionservice.models.CurrencyConversion;
import com.practice.microservices.currencyconversionservice.services.interfaces.CurrencyConversionService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
@AllArgsConstructor
public class CurrencyConversionController {
private final CurrencyConversionService currencyConversionService;
@GetMapping("/currency-conversion/from/{from}/to/{to}/amount/{amount}")
public CurrencyConversion getConversionRate(@PathVariable final String from, @PathVariable final String to,
@PathVariable final Double amount) {
return currencyConversionService.convertCurrencies(from, to, amount);
}
}
|
92460e46b80ed9226f35177337c2d4f81920fb82
| 666 |
java
|
Java
|
python/python-psi-impl/src/com/jetbrains/python/psi/stubs/PySuperClassIndex.java
|
dunno99/intellij-community
|
aa656a5d874b947271b896b2105e4370827b9149
|
[
"Apache-2.0"
] | 2 |
2019-04-28T07:48:50.000Z
|
2020-12-11T14:18:08.000Z
|
python/python-psi-impl/src/com/jetbrains/python/psi/stubs/PySuperClassIndex.java
|
dunno99/intellij-community
|
aa656a5d874b947271b896b2105e4370827b9149
|
[
"Apache-2.0"
] | 173 |
2018-07-05T13:59:39.000Z
|
2018-08-09T01:12:03.000Z
|
python/python-psi-impl/src/com/jetbrains/python/psi/stubs/PySuperClassIndex.java
|
dunno99/intellij-community
|
aa656a5d874b947271b896b2105e4370827b9149
|
[
"Apache-2.0"
] | 2 |
2020-03-15T08:57:37.000Z
|
2020-04-07T04:48:14.000Z
| 31.714286 | 140 | 0.776276 | 1,003,628 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.psi.stubs;
import com.intellij.psi.stubs.StringStubIndexExtension;
import com.intellij.psi.stubs.StubIndexKey;
import com.jetbrains.python.psi.PyClass;
import org.jetbrains.annotations.NotNull;
/**
* @author yole
*/
public class PySuperClassIndex extends StringStubIndexExtension<PyClass> {
public static final StubIndexKey<String, PyClass> KEY = StubIndexKey.createIndexKey("Py.class.super");
@Override
@NotNull
public StubIndexKey<String, PyClass> getKey() {
return KEY;
}
}
|
92460e79715bf59532021ba013b05179f2e7c630
| 1,657 |
java
|
Java
|
src/main/java/bd/io/AdMetricWritable.java
|
Higmin/bigdata-zookeeper
|
a984defa885155ac86e4cd3d161c65e55ab26b6c
|
[
"Apache-2.0"
] | 2 |
2019-08-06T03:32:12.000Z
|
2019-08-20T12:38:52.000Z
|
src/main/java/bd/io/AdMetricWritable.java
|
Higmin/bigdata
|
a984defa885155ac86e4cd3d161c65e55ab26b6c
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/bd/io/AdMetricWritable.java
|
Higmin/bigdata
|
a984defa885155ac86e4cd3d161c65e55ab26b6c
|
[
"Apache-2.0"
] | null | null | null | 21.24359 | 68 | 0.617984 | 1,003,629 |
package bd.io;
import org.apache.hadoop.io.Writable;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
public class AdMetricWritable implements Writable {
private long pv;
private long click;
private float clickRate;
//反序列化时,需要调用无参的构造方法,如果定义了有参的构造方法,一定要定义一个无参的构造方法
public AdMetricWritable() {
}
public AdMetricWritable(long pv, long click, float clickRate) {
this.pv = pv;
this.click = click;
this.clickRate = clickRate;
}
/**
*用于序列化
* @param dataOutput
* @throws IOException
*/
@Override
public void write(DataOutput dataOutput) throws IOException {
dataOutput.writeLong(this.pv);
dataOutput.writeLong(this.click);
dataOutput.writeFloat(this.clickRate);
}
/**
* 用于反序列化(反序列化的顺序要和序列化的顺序一致)
* @param dataInput
* @throws IOException
*/
@Override
public void readFields(DataInput dataInput) throws IOException {
this.pv = dataInput.readLong();
this.click = dataInput.readLong();
this.clickRate = dataInput.readFloat();
}
@Override
public String toString() {
return this.pv + "\t" + this.click + "\t" +this.clickRate;
}
public long getPv() {
return pv;
}
public void setPv(long pv) {
this.pv = pv;
}
public long getClick() {
return click;
}
public void setClick(long click) {
this.click = click;
}
public float getClickRate() {
return clickRate;
}
public void setClickRate(float clickRate) {
this.clickRate = clickRate;
}
}
|
92460f110cb297380e9dafdd605bb1af4ce2ac2d
| 257 |
java
|
Java
|
src/main/java/avatar/game/quest/Reward.java
|
Jimmeh94/Avatar
|
728769b84086b61750f494cb01d83adac17cd70c
|
[
"MIT"
] | null | null | null |
src/main/java/avatar/game/quest/Reward.java
|
Jimmeh94/Avatar
|
728769b84086b61750f494cb01d83adac17cd70c
|
[
"MIT"
] | null | null | null |
src/main/java/avatar/game/quest/Reward.java
|
Jimmeh94/Avatar
|
728769b84086b61750f494cb01d83adac17cd70c
|
[
"MIT"
] | null | null | null | 15.117647 | 57 | 0.700389 | 1,003,630 |
package avatar.game.quest;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.text.Text;
public interface Reward {
/*
* Quest rewards
*/
Text getDescription();
void giveAward(Player player);
}
|
92460f940d72086e23db679cfe96eb03579c1576
| 2,567 |
java
|
Java
|
dismemberSpring2/entrance/src/main/java/com/koala/springComponents/springContext/context/support/AbstractXmlApplicationContext.java
|
1129269131/dismemberSpring
|
adb0b25af53794d377087a436c1b521f3636706f
|
[
"Apache-2.0"
] | null | null | null |
dismemberSpring2/entrance/src/main/java/com/koala/springComponents/springContext/context/support/AbstractXmlApplicationContext.java
|
1129269131/dismemberSpring
|
adb0b25af53794d377087a436c1b521f3636706f
|
[
"Apache-2.0"
] | null | null | null |
dismemberSpring2/entrance/src/main/java/com/koala/springComponents/springContext/context/support/AbstractXmlApplicationContext.java
|
1129269131/dismemberSpring
|
adb0b25af53794d377087a436c1b521f3636706f
|
[
"Apache-2.0"
] | null | null | null | 37.202899 | 115 | 0.75263 | 1,003,631 |
package com.koala.springComponents.springContext.context.support;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.ResourceEntityResolver;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.lang.Nullable;
import java.io.IOException;
/**
* Create by koala on 2021-08-26
*/
public abstract class AbstractXmlApplicationContext extends AbstractRefreshableConfigApplicationContext {
private boolean validating = true;
public AbstractXmlApplicationContext() {
}
public AbstractXmlApplicationContext(@Nullable ApplicationContext parent) {
super(parent);
}
public void setValidating(boolean validating) {
this.validating = validating;
}
@Override
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
// Create a new XmlBeanDefinitionReader for the given BeanFactory. day07:准备读取xml内容的读取器
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
// Configure the bean definition reader with this context's
// resource loading environment.
beanDefinitionReader.setEnvironment(this.getEnvironment());
beanDefinitionReader.setResourceLoader(this); //day07:持有ioc容器的环境类
beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
// Allow a subclass to provide custom initialization of the reader,
// then proceed with actually loading the bean definitions.
initBeanDefinitionReader(beanDefinitionReader);
loadBeanDefinitions(beanDefinitionReader);
}
protected void initBeanDefinitionReader(XmlBeanDefinitionReader reader) {
reader.setValidating(this.validating);
}
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
Resource[] configResources = getConfigResources();
if (configResources != null) {
reader.loadBeanDefinitions(configResources);
}
String[] configLocations = getConfigLocations(); //day07:可以一次传入很多配置文件
if (configLocations != null) {
reader.loadBeanDefinitions(configLocations); //day07:读取文件
}
}
@Nullable
protected Resource[] getConfigResources() {
return null;
}
}
|
9246103aef724a020caceca9097253c6c2b855b5
| 2,497 |
java
|
Java
|
ethereum/core/src/test/java/org/hyperledger/besu/ethereum/mainnet/ProtocolScheduleTest.java
|
diega/besu
|
1b172ae64c878ae057da149985dae831026fc8f2
|
[
"Apache-2.0"
] | 702 |
2019-09-05T12:44:20.000Z
|
2022-03-31T11:13:15.000Z
|
ethereum/core/src/test/java/org/hyperledger/besu/ethereum/mainnet/ProtocolScheduleTest.java
|
diega/besu
|
1b172ae64c878ae057da149985dae831026fc8f2
|
[
"Apache-2.0"
] | 2,114 |
2019-09-16T02:31:28.000Z
|
2022-03-31T18:07:06.000Z
|
ethereum/core/src/test/java/org/hyperledger/besu/ethereum/mainnet/ProtocolScheduleTest.java
|
diega/besu
|
1b172ae64c878ae057da149985dae831026fc8f2
|
[
"Apache-2.0"
] | 472 |
2019-09-16T01:44:28.000Z
|
2022-03-30T08:27:15.000Z
| 36.720588 | 118 | 0.761314 | 1,003,632 |
/*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.ethereum.mainnet;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import java.math.BigInteger;
import java.util.Optional;
import org.assertj.core.api.Assertions;
import org.junit.Test;
public class ProtocolScheduleTest {
private static final Optional<BigInteger> CHAIN_ID = Optional.of(BigInteger.ONE);
@SuppressWarnings("unchecked")
@Test
public void getByBlockNumber() {
final ProtocolSpec spec1 = mock(ProtocolSpec.class);
final ProtocolSpec spec2 = mock(ProtocolSpec.class);
final ProtocolSpec spec3 = mock(ProtocolSpec.class);
final ProtocolSpec spec4 = mock(ProtocolSpec.class);
final MutableProtocolSchedule schedule = new MutableProtocolSchedule(CHAIN_ID);
schedule.putMilestone(20, spec3);
schedule.putMilestone(0, spec1);
schedule.putMilestone(30, spec4);
schedule.putMilestone(10, spec2);
assertThat(schedule.getByBlockNumber(0)).isEqualTo(spec1);
assertThat(schedule.getByBlockNumber(15)).isEqualTo(spec2);
assertThat(schedule.getByBlockNumber(35)).isEqualTo(spec4);
assertThat(schedule.getByBlockNumber(105)).isEqualTo(spec4);
}
@Test
public void emptySchedule() {
Assertions.assertThatThrownBy(() -> new MutableProtocolSchedule(CHAIN_ID).getByBlockNumber(0))
.hasMessage("At least 1 milestone must be provided to the protocol schedule");
}
@SuppressWarnings("unchecked")
@Test
public void conflictingSchedules() {
final ProtocolSpec spec1 = mock(ProtocolSpec.class);
final ProtocolSpec spec2 = mock(ProtocolSpec.class);
final MutableProtocolSchedule protocolSchedule = new MutableProtocolSchedule(CHAIN_ID);
protocolSchedule.putMilestone(0, spec1);
protocolSchedule.putMilestone(0, spec2);
assertThat(protocolSchedule.getByBlockNumber(0)).isSameAs(spec2);
}
}
|
9246115cc662908f84923e7b423d13389c6a73e2
| 1,249 |
java
|
Java
|
src/main/test/edu/fiuba/algo3/modelo/PuntajeSorterTest.java
|
TBroderick99/Algo-3-TP2
|
9641100db148e730bc6075f6bad4e9e6daa0d078
|
[
"MIT"
] | null | null | null |
src/main/test/edu/fiuba/algo3/modelo/PuntajeSorterTest.java
|
TBroderick99/Algo-3-TP2
|
9641100db148e730bc6075f6bad4e9e6daa0d078
|
[
"MIT"
] | null | null | null |
src/main/test/edu/fiuba/algo3/modelo/PuntajeSorterTest.java
|
TBroderick99/Algo-3-TP2
|
9641100db148e730bc6075f6bad4e9e6daa0d078
|
[
"MIT"
] | null | null | null | 33.756757 | 79 | 0.68695 | 1,003,633 |
package edu.fiuba.algo3.modelo;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class PuntajeSorterTest {
@Test
public void test01SiJugador1TieneMasPuntajeQueJugador2DevuelveMenorA0() {
PuntajeSorter ordenador = new PuntajeSorter();
Jugador jugador1 = new Jugador();
jugador1.setPuntaje(2);
Jugador jugador2 = new Jugador();
jugador2.setPuntaje(1);
assertEquals(ordenador.compare(jugador1, jugador2), -1);
}
@Test
public void test02SiJugador1TieneIgualPuntajeQueJugador2Devuelve0() {
PuntajeSorter ordenador = new PuntajeSorter();
Jugador jugador1 = new Jugador();
jugador1.setPuntaje(1);
Jugador jugador2 = new Jugador();
jugador2.setPuntaje(1);
assertEquals(ordenador.compare(jugador1, jugador2), 0);
}
@Test
public void test03SiJugador1TieneMenosPuntajeQueJugador2DevuelveMayorA0() {
PuntajeSorter ordenador = new PuntajeSorter();
Jugador jugador1 = new Jugador();
jugador1.setPuntaje(1);
Jugador jugador2 = new Jugador();
jugador2.setPuntaje(2);
assertEquals(ordenador.compare(jugador1, jugador2), 1);
}
}
|
9246124c4b504413afe0a831b4747c2a6c4c0127
| 12,041 |
java
|
Java
|
renfeid-core/src/main/java/net/renfei/repositories/model/SysSettingExample.java
|
renfei/renfeid
|
a9813049143df7622e3a35becd98a92987a1540d
|
[
"Apache-2.0"
] | 5 |
2021-11-12T08:05:26.000Z
|
2022-03-02T02:12:50.000Z
|
renfeid-core/src/main/java/net/renfei/repositories/model/SysSettingExample.java
|
moutainhigh/renfeid
|
627fb36ae88b89e76486c79e97e14f560d09f823
|
[
"Apache-2.0"
] | 24 |
2021-11-12T14:11:22.000Z
|
2022-03-31T11:23:28.000Z
|
renfeid-core/src/main/java/net/renfei/repositories/model/SysSettingExample.java
|
moutainhigh/renfeid
|
627fb36ae88b89e76486c79e97e14f560d09f823
|
[
"Apache-2.0"
] | 7 |
2021-11-12T14:08:38.000Z
|
2022-03-17T08:43:52.000Z
| 30.177945 | 102 | 0.5757 | 1,003,634 |
package net.renfei.repositories.model;
import java.util.ArrayList;
import java.util.List;
public class SysSettingExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public SysSettingExample() {
oredCriteria = new ArrayList<>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andIdIsNull() {
addCriterion("`id` is null");
return (Criteria) this;
}
public Criteria andIdIsNotNull() {
addCriterion("`id` is not null");
return (Criteria) this;
}
public Criteria andIdEqualTo(Long value) {
addCriterion("`id` =", value, "id");
return (Criteria) this;
}
public Criteria andIdNotEqualTo(Long value) {
addCriterion("`id` <>", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThan(Long value) {
addCriterion("`id` >", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThanOrEqualTo(Long value) {
addCriterion("`id` >=", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThan(Long value) {
addCriterion("`id` <", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThanOrEqualTo(Long value) {
addCriterion("`id` <=", value, "id");
return (Criteria) this;
}
public Criteria andIdIn(List<Long> values) {
addCriterion("`id` in", values, "id");
return (Criteria) this;
}
public Criteria andIdNotIn(List<Long> values) {
addCriterion("`id` not in", values, "id");
return (Criteria) this;
}
public Criteria andIdBetween(Long value1, Long value2) {
addCriterion("`id` between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andIdNotBetween(Long value1, Long value2) {
addCriterion("`id` not between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andSettingKeyIsNull() {
addCriterion("`setting_key` is null");
return (Criteria) this;
}
public Criteria andSettingKeyIsNotNull() {
addCriterion("`setting_key` is not null");
return (Criteria) this;
}
public Criteria andSettingKeyEqualTo(String value) {
addCriterion("`setting_key` =", value, "settingKey");
return (Criteria) this;
}
public Criteria andSettingKeyNotEqualTo(String value) {
addCriterion("`setting_key` <>", value, "settingKey");
return (Criteria) this;
}
public Criteria andSettingKeyGreaterThan(String value) {
addCriterion("`setting_key` >", value, "settingKey");
return (Criteria) this;
}
public Criteria andSettingKeyGreaterThanOrEqualTo(String value) {
addCriterion("`setting_key` >=", value, "settingKey");
return (Criteria) this;
}
public Criteria andSettingKeyLessThan(String value) {
addCriterion("`setting_key` <", value, "settingKey");
return (Criteria) this;
}
public Criteria andSettingKeyLessThanOrEqualTo(String value) {
addCriterion("`setting_key` <=", value, "settingKey");
return (Criteria) this;
}
public Criteria andSettingKeyLike(String value) {
addCriterion("`setting_key` like", value, "settingKey");
return (Criteria) this;
}
public Criteria andSettingKeyNotLike(String value) {
addCriterion("`setting_key` not like", value, "settingKey");
return (Criteria) this;
}
public Criteria andSettingKeyIn(List<String> values) {
addCriterion("`setting_key` in", values, "settingKey");
return (Criteria) this;
}
public Criteria andSettingKeyNotIn(List<String> values) {
addCriterion("`setting_key` not in", values, "settingKey");
return (Criteria) this;
}
public Criteria andSettingKeyBetween(String value1, String value2) {
addCriterion("`setting_key` between", value1, value2, "settingKey");
return (Criteria) this;
}
public Criteria andSettingKeyNotBetween(String value1, String value2) {
addCriterion("`setting_key` not between", value1, value2, "settingKey");
return (Criteria) this;
}
public Criteria andSettingValueIsNull() {
addCriterion("`setting_value` is null");
return (Criteria) this;
}
public Criteria andSettingValueIsNotNull() {
addCriterion("`setting_value` is not null");
return (Criteria) this;
}
public Criteria andSettingValueEqualTo(String value) {
addCriterion("`setting_value` =", value, "settingValue");
return (Criteria) this;
}
public Criteria andSettingValueNotEqualTo(String value) {
addCriterion("`setting_value` <>", value, "settingValue");
return (Criteria) this;
}
public Criteria andSettingValueGreaterThan(String value) {
addCriterion("`setting_value` >", value, "settingValue");
return (Criteria) this;
}
public Criteria andSettingValueGreaterThanOrEqualTo(String value) {
addCriterion("`setting_value` >=", value, "settingValue");
return (Criteria) this;
}
public Criteria andSettingValueLessThan(String value) {
addCriterion("`setting_value` <", value, "settingValue");
return (Criteria) this;
}
public Criteria andSettingValueLessThanOrEqualTo(String value) {
addCriterion("`setting_value` <=", value, "settingValue");
return (Criteria) this;
}
public Criteria andSettingValueLike(String value) {
addCriterion("`setting_value` like", value, "settingValue");
return (Criteria) this;
}
public Criteria andSettingValueNotLike(String value) {
addCriterion("`setting_value` not like", value, "settingValue");
return (Criteria) this;
}
public Criteria andSettingValueIn(List<String> values) {
addCriterion("`setting_value` in", values, "settingValue");
return (Criteria) this;
}
public Criteria andSettingValueNotIn(List<String> values) {
addCriterion("`setting_value` not in", values, "settingValue");
return (Criteria) this;
}
public Criteria andSettingValueBetween(String value1, String value2) {
addCriterion("`setting_value` between", value1, value2, "settingValue");
return (Criteria) this;
}
public Criteria andSettingValueNotBetween(String value1, String value2) {
addCriterion("`setting_value` not between", value1, value2, "settingValue");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
}
|
924612dd74b7c1e4baaf4021556b39429cdce57b
| 3,927 |
java
|
Java
|
engine/src/main/java/org/camunda/bpm/engine/impl/bpmn/behavior/ThrowSignalEventActivityBehavior.java
|
matthiasblaesing/camunda-bpm-platform
|
1b2d4b9087d07788bc75736d0470ac1ee5ba1cca
|
[
"Apache-2.0"
] | 1 |
2019-04-23T11:35:12.000Z
|
2019-04-23T11:35:12.000Z
|
engine/src/main/java/org/camunda/bpm/engine/impl/bpmn/behavior/ThrowSignalEventActivityBehavior.java
|
matthiasblaesing/camunda-bpm-platform
|
1b2d4b9087d07788bc75736d0470ac1ee5ba1cca
|
[
"Apache-2.0"
] | null | null | null |
engine/src/main/java/org/camunda/bpm/engine/impl/bpmn/behavior/ThrowSignalEventActivityBehavior.java
|
matthiasblaesing/camunda-bpm-platform
|
1b2d4b9087d07788bc75736d0470ac1ee5ba1cca
|
[
"Apache-2.0"
] | null | null | null | 43.142857 | 114 | 0.801579 | 1,003,635 |
/*
* Copyright © 2013-2018 camunda services GmbH and various authors ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.camunda.bpm.engine.impl.bpmn.behavior;
import org.camunda.bpm.engine.impl.ProcessEngineLogger;
import org.camunda.bpm.engine.impl.bpmn.parser.EventSubscriptionDeclaration;
import org.camunda.bpm.engine.impl.context.Context;
import org.camunda.bpm.engine.impl.persistence.entity.EventSubscriptionEntity;
import org.camunda.bpm.engine.impl.persistence.entity.EventSubscriptionManager;
import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity;
import org.camunda.bpm.engine.impl.pvm.delegate.ActivityExecution;
import org.camunda.bpm.engine.variable.VariableMap;
import java.util.List;
/**
* Defines activity behavior for signal end event and intermediate throw signal event.
*
* @author Daniel Meyer
*/
public class ThrowSignalEventActivityBehavior extends AbstractBpmnActivityBehavior {
protected final static BpmnBehaviorLogger LOG = ProcessEngineLogger.BPMN_BEHAVIOR_LOGGER;
protected final EventSubscriptionDeclaration signalDefinition;
public ThrowSignalEventActivityBehavior(EventSubscriptionDeclaration signalDefinition) {
this.signalDefinition = signalDefinition;
}
@Override
public void execute(ActivityExecution execution) throws Exception {
String businessKey = signalDefinition.getEventPayload().getBusinessKey(execution);
VariableMap variableMap = signalDefinition.getEventPayload().getInputVariables(execution);
String eventName = signalDefinition.resolveExpressionOfEventName(execution);
// trigger all event subscriptions for the signal (start and intermediate)
List<EventSubscriptionEntity> signalEventSubscriptions =
findSignalEventSubscriptions(eventName, execution.getTenantId());
for (EventSubscriptionEntity signalEventSubscription : signalEventSubscriptions) {
if (isActiveEventSubscription(signalEventSubscription)) {
signalEventSubscription.eventReceived(variableMap, null, businessKey, signalDefinition.isAsync());
}
}
leave(execution);
}
protected List<EventSubscriptionEntity> findSignalEventSubscriptions(String signalName, String tenantId) {
EventSubscriptionManager eventSubscriptionManager = Context.getCommandContext().getEventSubscriptionManager();
if (tenantId != null) {
return eventSubscriptionManager
.findSignalEventSubscriptionsByEventNameAndTenantIdIncludeWithoutTenantId(signalName, tenantId);
} else {
// find event subscriptions without tenant id
return eventSubscriptionManager.findSignalEventSubscriptionsByEventNameAndTenantId(signalName, null);
}
}
protected boolean isActiveEventSubscription(EventSubscriptionEntity signalEventSubscriptionEntity) {
return isStartEventSubscription(signalEventSubscriptionEntity)
|| isActiveIntermediateEventSubscription(signalEventSubscriptionEntity);
}
protected boolean isStartEventSubscription(EventSubscriptionEntity signalEventSubscriptionEntity) {
return signalEventSubscriptionEntity.getExecutionId() == null;
}
protected boolean isActiveIntermediateEventSubscription(EventSubscriptionEntity signalEventSubscriptionEntity) {
ExecutionEntity execution = signalEventSubscriptionEntity.getExecution();
return execution != null && !execution.isEnded() && !execution.isCanceled();
}
}
|
924612e4163dd41dd10b201cc37356eb99d01cd9
| 988 |
java
|
Java
|
uncommitted/GCC-OpenMP4.5/syntaxtree/ArrayInitializer.java
|
anonymousoopsla21/homeostasis
|
e56c5c2f8392027ad5a49a45d7ac49a139c33674
|
[
"MIT"
] | 1 |
2021-06-14T13:48:37.000Z
|
2021-06-14T13:48:37.000Z
|
uncommitted/GCC-OpenMP4.5/syntaxtree/ArrayInitializer.java
|
anonymousoopsla21/homeostasis
|
e56c5c2f8392027ad5a49a45d7ac49a139c33674
|
[
"MIT"
] | null | null | null |
uncommitted/GCC-OpenMP4.5/syntaxtree/ArrayInitializer.java
|
anonymousoopsla21/homeostasis
|
e56c5c2f8392027ad5a49a45d7ac49a139c33674
|
[
"MIT"
] | null | null | null | 20.583333 | 93 | 0.591093 | 1,003,636 |
//
// Generated by JTB 1.3.2
//
package syntaxtree;
/**
* Grammar production:
* f0 -> "{"
* f1 -> InitializerList()
* f2 -> ( "," )?
* f3 -> "}"
*/
public class ArrayInitializer implements Node {
public NodeToken f0;
public InitializerList f1;
public NodeOptional f2;
public NodeToken f3;
public ArrayInitializer(NodeToken n0, InitializerList n1, NodeOptional n2, NodeToken n3) {
f0 = n0;
f1 = n1;
f2 = n2;
f3 = n3;
}
public ArrayInitializer(InitializerList n0, NodeOptional n1) {
f0 = new NodeToken("{");
f1 = n0;
f2 = n1;
f3 = new NodeToken("}");
}
public void accept(visitor.Visitor v) {
v.visit(this);
}
public <R,A> R accept(visitor.GJVisitor<R,A> v, A argu) {
return v.visit(this,argu);
}
public <R> R accept(visitor.GJNoArguVisitor<R> v) {
return v.visit(this);
}
public <A> void accept(visitor.GJVoidVisitor<A> v, A argu) {
v.visit(this,argu);
}
}
|
9246138cdfce7f08fdeb3cd1cf7b5db7ab1093ac
| 2,268 |
java
|
Java
|
modules/sst-security/src/main/java/org/simpliccity/sst/security/service/SpringSecurityServiceSecurityHandler.java
|
simpliccity/sst
|
43b57e793a4df8c71b7b05a901e882e209cfe19b
|
[
"Apache-2.0"
] | null | null | null |
modules/sst-security/src/main/java/org/simpliccity/sst/security/service/SpringSecurityServiceSecurityHandler.java
|
simpliccity/sst
|
43b57e793a4df8c71b7b05a901e882e209cfe19b
|
[
"Apache-2.0"
] | null | null | null |
modules/sst-security/src/main/java/org/simpliccity/sst/security/service/SpringSecurityServiceSecurityHandler.java
|
simpliccity/sst
|
43b57e793a4df8c71b7b05a901e882e209cfe19b
|
[
"Apache-2.0"
] | null | null | null | 32.869565 | 115 | 0.770723 | 1,003,637 |
/*
* Copyright 2014 Information Control Corporation
*
* 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.simpliccity.sst.security.service;
import java.security.Principal;
import java.util.Collection;
import org.simpliccity.sst.security.role.RoleUtils;
import org.simpliccity.sst.service.security.ServiceSecurityHandler;
import org.simpliccity.sst.service.security.ServiceSemanticContext;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
/**
* An implementation of {@link org.simpliccity.sst.service.security.ServiceSecurityHandler} based on Spring
* Security. This allows the {@link org.simpliccity.sst.ws.endpoint.security.EndpointAccessValidatorInterceptor}
* to be used in a runtime environment that relies on Spring Security for authentication and authorization.
*
* @author Kevin Fox
* @since 1.0.0
*
*/
public class SpringSecurityServiceSecurityHandler implements ServiceSecurityHandler
{
@Override
public Principal getPrincipal(ServiceSemanticContext<?> semanticContext)
{
return SecurityContextHolder.getContext().getAuthentication();
}
@SuppressWarnings("unchecked")
@Override
public boolean inApplicableRole(ServiceSemanticContext<?> semanticContext, String[] roles)
{
Principal user = getPrincipal(semanticContext);
boolean result = false;
if (user instanceof Authentication)
{
Collection<GrantedAuthority> assigned = (Collection<GrantedAuthority>) ((Authentication) user).getAuthorities();
for (String role : roles)
{
result = RoleUtils.hasAuthority(assigned, role);
if (result)
{
break;
}
}
}
return result;
}
}
|
9246140713cd9dde61b0d3b2b0b872c9a3d473c0
| 15,361 |
java
|
Java
|
bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/explorer/dynamodb/TablePropertiesDialog.java
|
mmusti1234/aws-toolkit-eclipse
|
85417f68e1eb6d90d46e145229e390cf55a4a554
|
[
"Apache-2.0"
] | 202 |
2015-01-23T09:41:51.000Z
|
2022-03-22T02:27:20.000Z
|
bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/explorer/dynamodb/TablePropertiesDialog.java
|
mmusti1234/aws-toolkit-eclipse
|
85417f68e1eb6d90d46e145229e390cf55a4a554
|
[
"Apache-2.0"
] | 209 |
2015-03-18T15:34:48.000Z
|
2022-03-02T22:23:55.000Z
|
bundles/com.amazonaws.eclipse.dynamodb/src/com/amazonaws/eclipse/explorer/dynamodb/TablePropertiesDialog.java
|
mmusti1234/aws-toolkit-eclipse
|
85417f68e1eb6d90d46e145229e390cf55a4a554
|
[
"Apache-2.0"
] | 166 |
2015-01-02T20:12:00.000Z
|
2022-03-20T22:35:53.000Z
| 41.182306 | 137 | 0.629712 | 1,003,638 |
/*
* Copyright 2012 Amazon Technologies, 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://aws.amazon.com/apache2.0
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and
* limitations under the License.
*/
package com.amazonaws.eclipse.explorer.dynamodb;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.jface.layout.TableColumnLayout;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ColumnPixelData;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import com.amazonaws.eclipse.core.AwsToolkitCore;
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition;
import com.amazonaws.services.dynamodbv2.model.DescribeTableRequest;
import com.amazonaws.services.dynamodbv2.model.KeySchemaElement;
import com.amazonaws.services.dynamodbv2.model.KeyType;
import com.amazonaws.services.dynamodbv2.model.LocalSecondaryIndexDescription;
import com.amazonaws.services.dynamodbv2.model.ProjectionType;
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput;
import com.amazonaws.services.dynamodbv2.model.TableDescription;
import com.amazonaws.services.dynamodbv2.model.UpdateTableRequest;
/**
* Dialog to show the table properties.
*/
public class TablePropertiesDialog extends MessageDialog {
private final String tableName;
private final TableDescription tableDescription;
private Text writeCapacityText;
private Text readCapacityText;
private Long readCapacity;
private Long writeCapacity;
protected TablePropertiesDialog(String tableName) {
super(Display.getCurrent().getActiveShell(), "Table properties for " + tableName, AwsToolkitCore.getDefault().getImageRegistry()
.get(AwsToolkitCore.IMAGE_AWS_ICON), null,
MessageDialog.NONE, new String[] { "Update", "Cancel" }, 1);
this.tableName = tableName;
tableDescription = AwsToolkitCore.getClientFactory().getDynamoDBV2Client()
.describeTable(new DescribeTableRequest().withTableName(tableName)).getTable();
readCapacity = tableDescription.getProvisionedThroughput().getReadCapacityUnits();
writeCapacity = tableDescription.getProvisionedThroughput().getWriteCapacityUnits();
setShellStyle(getShellStyle() | SWT.RESIZE);
}
public UpdateTableRequest getUpdateRequest() {
return new UpdateTableRequest().withTableName(tableName).withProvisionedThroughput(
new ProvisionedThroughput().withReadCapacityUnits(readCapacity).withWriteCapacityUnits(writeCapacity));
}
@Override
protected Control createCustomArea(Composite parent) {
Composite comp = new Composite(parent, SWT.NONE);
GridDataFactory.fillDefaults().grab(true, true).applyTo(comp);
GridLayoutFactory.fillDefaults().numColumns(2).applyTo(comp);
newLabel(comp).setText("Created on:");
newReadOnlyTextField(comp).setText(tableDescription.getCreationDateTime().toString());
newLabel(comp).setText("Status:");
newReadOnlyTextField(comp).setText(tableDescription.getTableStatus());
newLabel(comp).setText("Item count:");
newReadOnlyTextField(comp).setText(tableDescription.getItemCount().toString());
newLabel(comp).setText("Size (bytes):");
newReadOnlyTextField(comp).setText(tableDescription.getTableSizeBytes().toString());
newLabel(comp).setText("Hash key attribute:");
newReadOnlyTextField(comp).setText(getHashKeyName());
newLabel(comp).setText("Hash key type:");
newReadOnlyTextField(comp).setText(getAttributeType(getHashKeyName()));
if ( getRangeKeyName() != null ) {
new Label(comp, SWT.READ_ONLY).setText("Range key attribute:");
newReadOnlyTextField(comp).setText(getRangeKeyName());
new Label(comp, SWT.READ_ONLY).setText("Range key type:");
newReadOnlyTextField(comp).setText(getAttributeType(getRangeKeyName()));
}
new Label(comp, SWT.READ_ONLY).setText("Read capacity units:");
readCapacityText = newTextField(comp);
readCapacityText.setText(readCapacity.toString());
readCapacityText.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
try {
readCapacity = Long.parseLong(readCapacityText.getText());
} catch ( NumberFormatException e1 ) {
readCapacity = null;
}
validate();
}
});
new Label(comp, SWT.READ_ONLY).setText("Write capacity units:");
writeCapacityText = newTextField(comp);
writeCapacityText.setText(writeCapacity.toString());
writeCapacityText.addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
try {
writeCapacity = Long.parseLong(writeCapacityText.getText());
} catch ( NumberFormatException e1 ) {
writeCapacity = null;
}
validate();
}
});
if ( tableDescription.getProvisionedThroughput().getLastIncreaseDateTime() != null ) {
new Label(comp, SWT.READ_ONLY).setText("Provisioned throughput last increased:");
newReadOnlyTextField(comp).setText(
tableDescription.getProvisionedThroughput().getLastIncreaseDateTime().toString());
}
if ( tableDescription.getProvisionedThroughput().getLastDecreaseDateTime() != null ) {
new Label(comp, SWT.READ_ONLY).setText("Provisioned throughput last decreased:");
newReadOnlyTextField(comp).setText(
tableDescription.getProvisionedThroughput().getLastDecreaseDateTime().toString());
}
// Local secondary index
Group group = new Group(comp, SWT.NONE);
group.setText("Local Secondary Index");
group.setLayout(new GridLayout(1, false));
GridDataFactory.fillDefaults().grab(true, true).span(2, SWT.DEFAULT).applyTo(group);
IndexTable table = new IndexTable(group);
GridDataFactory.fillDefaults().grab(true, true).applyTo(table);
table.refresh();
return comp;
}
@Override
protected void createButtonsForButtonBar(Composite parent) {
super.createButtonsForButtonBar(parent);
validate();
}
private Text newTextField(Composite comp) {
Text text = new Text(comp, SWT.BORDER);
GridDataFactory.fillDefaults().grab(true, false).applyTo(text);
return text;
}
private Text newReadOnlyTextField(Composite comp) {
Text text = new Text(comp, SWT.READ_ONLY);
text.setBackground(comp.getBackground());
GridDataFactory.fillDefaults().grab(true, false).applyTo(text);
return text;
}
private Label newLabel(Composite comp) {
Label label = new Label(comp, SWT.NONE);
GridDataFactory.fillDefaults().grab(true, false).applyTo(label);
return label;
}
private void validate() {
if ( readCapacity == null || readCapacity < 5 ) {
setErrorMessage("Please enter a read capacity of 5 or more.");
return;
}
if ( writeCapacity == null || writeCapacity < 5 ) {
setErrorMessage("Please enter a write capacity of 5 or more.");
return;
}
setErrorMessage(null);
}
private void setErrorMessage(String message) {
getButton(0).setEnabled(message == null);
}
private String getHashKeyName() {
for (KeySchemaElement element : tableDescription.getKeySchema()) {
if (element.getKeyType().equals(KeyType.HASH.toString())) {
return element.getAttributeName();
}
}
return null;
}
private String getRangeKeyName() {
for (KeySchemaElement element : tableDescription.getKeySchema()) {
if (element.getKeyType().equals(KeyType.RANGE.toString())) {
return element.getAttributeName();
}
}
return null;
}
private String getAttributeType(String attributeName) {
for (AttributeDefinition definition : tableDescription.getAttributeDefinitions()) {
if (definition.getAttributeName().equals(attributeName)) {
return definition.getAttributeType();
}
}
return null;
}
// The table to show the local secondary index info
private class IndexTable extends Composite {
private TableViewer viewer;
private IndexTableContentProvider contentProvider;
private IndexTableLabelProvider labelProvider;
IndexTable(Composite parent) {
super(parent, SWT.NONE);
TableColumnLayout tableColumnLayout = new TableColumnLayout();
this.setLayout(tableColumnLayout);
contentProvider = new IndexTableContentProvider();
labelProvider = new IndexTableLabelProvider();
viewer = new TableViewer(this, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
viewer.getTable().setLinesVisible(true);
viewer.getTable().setHeaderVisible(true);
viewer.setLabelProvider(labelProvider);
viewer.setContentProvider(contentProvider);
createColumns(tableColumnLayout, viewer.getTable());
}
// Enforce call getElement method in contentProvider
public void refresh() {
viewer.setInput(new Object());
}
protected final class IndexTableContentProvider extends ArrayContentProvider {
@Override
public void dispose() {
}
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
@Override
public Object[] getElements(Object inputElement) {
if (tableDescription == null || tableDescription.getLocalSecondaryIndexes() == null) {
return new LocalSecondaryIndexDescription[0];
}
return tableDescription.getLocalSecondaryIndexes().toArray();
}
}
protected final class IndexTableLabelProvider implements ITableLabelProvider {
@Override
public void addListener(ILabelProviderListener listener) {
}
@Override
public void removeListener(ILabelProviderListener listener) {
}
@Override
public void dispose() {
}
@Override
public boolean isLabelProperty(Object element, String property) {
return false;
}
@Override
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
@Override
public String getColumnText(Object element, int columnIndex) {
if (element instanceof LocalSecondaryIndexDescription == false)
return "";
LocalSecondaryIndexDescription index = (LocalSecondaryIndexDescription) element;
switch (columnIndex) {
case 0:
return index.getIndexName();
case 1:
String returnString = "";
returnString += index.getKeySchema().get(1).getAttributeName() + " (";
returnString += getAttributeType(index.getKeySchema().get(1).getAttributeName()) + ")";
return returnString;
case 2:
return index.getIndexSizeBytes().toString();
case 3:
return index.getItemCount().toString();
case 4:
return getProjectionAttributes(index);
}
return element.toString();
}
}
// Generate a String has the detail info about projection in this LSI
private String getProjectionAttributes(LocalSecondaryIndexDescription index) {
String returnString = "";
if (index.getProjection().getProjectionType().equals(ProjectionType.ALL.toString())) {
return index.getProjection().getProjectionType();
} else if (index.getProjection().getProjectionType().equals(ProjectionType.INCLUDE.toString())) {
for (String attribute : index.getProjection().getNonKeyAttributes()) {
returnString += attribute + ", ";
}
returnString = returnString.substring(0, returnString.length() - 2);
return returnString;
} else {
returnString += getHashKeyName() + ", ";
if (getRangeKeyName() != null) {
returnString += getRangeKeyName() + ", ";
}
returnString += index.getKeySchema().get(1).getAttributeName();
return returnString;
}
}
private void createColumns(TableColumnLayout columnLayout, Table table) {
createColumn(table, columnLayout, "Index Name");
createColumn(table, columnLayout, "Attribute To Index");
createColumn(table, columnLayout, "Index Size (Bytes)");
createColumn(table, columnLayout, "Item Count");
createColumn(table, columnLayout, "Projected Attributes");
}
private TableColumn createColumn(Table table, TableColumnLayout columnLayout, String text) {
TableColumn column = new TableColumn(table, SWT.NONE);
column.setText(text);
column.setMoveable(true);
columnLayout.setColumnData(column, new ColumnPixelData(150));
return column;
}
}
}
|
92461448c9e0816ffa383e8ea97088828b7aa21a
| 85 |
java
|
Java
|
src/main/java/com/regitiny/catiny/config/package-info.java
|
ndtung01061999/catiny
|
a4f43f4539b12653c48f87619bab17ab08ccdc5c
|
[
"Unlicense"
] | null | null | null |
src/main/java/com/regitiny/catiny/config/package-info.java
|
ndtung01061999/catiny
|
a4f43f4539b12653c48f87619bab17ab08ccdc5c
|
[
"Unlicense"
] | null | null | null |
src/main/java/com/regitiny/catiny/config/package-info.java
|
ndtung01061999/catiny
|
a4f43f4539b12653c48f87619bab17ab08ccdc5c
|
[
"Unlicense"
] | null | null | null | 17 | 40 | 0.741176 | 1,003,639 |
/**
* Spring Framework configuration files.
*/
package com.regitiny.catiny.config;
|
92461489a8e012faa495e136e4a76cc262c39eee
| 1,651 |
java
|
Java
|
eventmesh-schema-registry/eventmesh-schema-registry-server/src/main/java/org/apache/eventmesh/schema/registry/server/repository/SubjectRepository.java
|
horoc/incubator-eventmesh
|
02deb6224df1620c5a302947ec41dda6230cc7aa
|
[
"Apache-2.0"
] | null | null | null |
eventmesh-schema-registry/eventmesh-schema-registry-server/src/main/java/org/apache/eventmesh/schema/registry/server/repository/SubjectRepository.java
|
horoc/incubator-eventmesh
|
02deb6224df1620c5a302947ec41dda6230cc7aa
|
[
"Apache-2.0"
] | null | null | null |
eventmesh-schema-registry/eventmesh-schema-registry-server/src/main/java/org/apache/eventmesh/schema/registry/server/repository/SubjectRepository.java
|
horoc/incubator-eventmesh
|
02deb6224df1620c5a302947ec41dda6230cc7aa
|
[
"Apache-2.0"
] | null | null | null | 41.275 | 94 | 0.778316 | 1,003,640 |
/*
* 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.eventmesh.schema.registry.server.repository;
import org.apache.eventmesh.schema.registry.server.domain.Subject;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface SubjectRepository extends JpaRepository<Subject,String> {
@Query(value = "select SUBJECT from SUBJECT", nativeQuery = true)
List<String> getAllSubject();
@Query(value = "select VERSION from SCHEMA v where v.SUBJECT=:subject",nativeQuery = true)
List<Integer> getAllVersionsBySubject(@Param("subject") String subject);
Subject deleteSubjectBySubject(String subject);
Subject getSubjectBySubject(String subject);
}
|
9246154d5d598eb7fd36385a982ef13e10ec597a
| 10,151 |
java
|
Java
|
snowballrun/src/main/java/com/google/android/apps/santatracker/doodles/snowballrun/RunnerActor.java
|
Hritiknitish/santa-tracker-android
|
be2966e9ceee49950cb1cde12b333e7659ffd286
|
[
"Apache-2.0"
] | 2,269 |
2015-03-27T05:56:54.000Z
|
2022-03-30T17:35:01.000Z
|
snowballrun/src/main/java/com/google/android/apps/santatracker/doodles/snowballrun/RunnerActor.java
|
willpyshan13/santa-tracker-android
|
bac925e399877e268e9faff0c3131befcc70f2e8
|
[
"Apache-2.0"
] | 60 |
2019-09-24T14:35:41.000Z
|
2021-07-29T10:47:52.000Z
|
snowballrun/src/main/java/com/google/android/apps/santatracker/doodles/snowballrun/RunnerActor.java
|
willpyshan13/santa-tracker-android
|
bac925e399877e268e9faff0c3131befcc70f2e8
|
[
"Apache-2.0"
] | 456 |
2015-03-27T07:55:55.000Z
|
2022-03-16T06:57:15.000Z
| 35.246528 | 107 | 0.608216 | 1,003,641 |
/*
* Copyright 2019. Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.santatracker.doodles.snowballrun;
import android.content.res.Resources;
import android.graphics.Canvas;
import com.google.android.apps.santatracker.doodles.shared.actor.Actor;
import com.google.android.apps.santatracker.doodles.shared.animation.AnimatedSprite;
import com.google.android.apps.santatracker.doodles.shared.animation.AnimatedSprite.AnimatedSpriteListener;
/** A fruit that runs down the screen. */
public class RunnerActor extends Actor {
private static final int RUNNING_Z_INDEX = 10;
private static final int DEAD_Z_INDEX = 3;
protected int lane;
protected RunnerType type;
protected RunnerState state;
protected float radius;
protected AnimatedSprite currentSprite;
protected AnimatedSprite runningSprite;
protected AnimatedSprite crouchSprite;
protected AnimatedSprite enteringSprite;
protected AnimatedSprite runningLeftSprite;
protected AnimatedSprite runningRightSprite;
protected AnimatedSprite standingSprite;
protected AnimatedSprite deadSprite;
protected AnimatedSprite dyingSprite;
RunnerActor(Resources resources, RunnerType type, int lane) {
this.lane = lane;
this.type = type;
runningSprite = AnimatedSprite.fromFrames(resources, type.runRes);
crouchSprite = AnimatedSprite.fromFrames(resources, type.crouchRes);
enteringSprite = AnimatedSprite.fromFrames(resources, type.enteringRes);
runningLeftSprite = AnimatedSprite.fromFrames(resources, type.runLeftRes);
runningRightSprite = AnimatedSprite.fromFrames(resources, type.runLeftRes);
standingSprite = AnimatedSprite.fromFrames(resources, type.standRes);
deadSprite = AnimatedSprite.fromFrames(resources, type.deadRes);
dyingSprite = AnimatedSprite.fromFrames(resources, type.dyingRes);
enteringSprite.setLoop(false);
enteringSprite.setFPS(
(int) ((enteringSprite.getNumFrames() + 1) / PursuitModel.RUNNER_ENTER_DURATION));
setSpriteAnchorUpright(runningSprite);
setSpriteAnchorWithYOffset(crouchSprite, 0);
setSpriteAnchorUpright(enteringSprite);
setSpriteAnchorUpright(runningLeftSprite);
setSpriteAnchorUpright(runningRightSprite);
setSpriteAnchorUpright(standingSprite);
setSpriteAnchorCenter(deadSprite);
switch (type) {
case PLAYER:
setSpriteAnchorWithYOffset(dyingSprite, 0);
break;
case REINDEER:
setSpriteAnchorWithYOffset(dyingSprite, 0);
break;
case ELF:
setSpriteAnchorWithYOffset(dyingSprite, 0);
break;
case SNOWMAN:
setSpriteAnchorWithYOffset(dyingSprite, 0);
break;
}
currentSprite = runningSprite;
state = RunnerState.RUNNING;
zIndex = RUNNING_Z_INDEX;
}
protected static void setSpriteAnchorCenter(AnimatedSprite sprite) {
setSpriteAnchorWithYOffset(sprite, sprite.frameHeight * 0.5f);
}
protected static void setSpriteAnchorUpright(AnimatedSprite sprite) {
setSpriteAnchorWithYOffset(sprite, 0);
}
protected static void setSpriteAnchorWithYOffset(AnimatedSprite sprite, float yOffset) {
sprite.setAnchor(sprite.frameWidth * 0.5f, sprite.frameHeight - yOffset);
}
@Override
public void update(float deltaMs) {
super.update(deltaMs);
if (state == RunnerState.RUNNING) {
currentSprite.setFPS(3 + (int) (5 * velocity.y / PursuitModel.BASE_SPEED));
}
currentSprite.update(deltaMs);
}
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
if (currentSprite == null) {
return;
}
float runnerScale = scale * 1.50f;
currentSprite.setScale(runnerScale, runnerScale);
currentSprite.setPosition(position.x, position.y);
if (currentSprite == runningRightSprite) {
currentSprite.setScale(-runnerScale, runnerScale);
}
currentSprite.draw(canvas);
}
public int getLane() {
return lane;
}
public void setLane(int lane) {
this.lane = lane;
}
public float getRadius() {
return radius;
}
public void setRadius(float radius) {
this.radius = radius;
}
public RunnerState getRunnerState() {
return state;
}
// yOffset is in percentage not game units, or pixels
// yOffset of 0.5f centers the sprite vertically
// yOffset of 0 draws the sprite starting from its y position
public void setRunnerState(RunnerState state) {
if (this.state == state) {
return;
}
this.state = state;
switch (state) {
case RUNNING:
currentSprite = runningSprite;
break;
case CROUCH:
currentSprite = crouchSprite;
break;
case ENTERING:
currentSprite = enteringSprite;
break;
case RUNNING_LEFT:
currentSprite = runningLeftSprite;
break;
case RUNNING_RIGHT:
currentSprite = runningRightSprite;
break;
case STANDING:
currentSprite = standingSprite;
break;
case DYING:
currentSprite = dyingSprite;
dyingSprite.setLoop(false);
dyingSprite.setFrameIndex(0);
dyingSprite.clearListeners();
int frame = 3;
switch (type) {
case SNOWMAN:
frame = 2;
break;
case ELF:
frame = 2;
break;
}
final int finalFrame = frame;
dyingSprite.addListener(
new AnimatedSpriteListener() {
@Override
public void onFrame(int index) {
super.onFrame(index);
if (index == finalFrame) {
setRunnerState(RunnerState.DEAD);
}
}
});
break;
case DEAD:
currentSprite = deadSprite;
break;
}
if (state == RunnerState.DEAD) {
zIndex = DEAD_Z_INDEX;
} else {
zIndex = RUNNING_Z_INDEX;
}
}
/** Currently there are four different kinds of fruits. */
public enum RunnerType {
PLAYER(
SnowballRunSprites.snowballrun_running_normal,
R.drawable.snowballrun_running_starting_runner,
SnowballRunSprites.snowballrun_running_sidestep,
SnowballRunSprites.snowballrun_running_appearing,
R.drawable.snowballrun_standing_elf,
SnowballRunSprites.snowballrun_elf_squish,
R.drawable.snowballrun_elf_squished_05),
SNOWMAN(
SnowballRunSprites.snowballrun_running_snowman_opponent,
R.drawable.snowballrun_running_starting_snowman,
SnowballRunSprites.empty_frame,
SnowballRunSprites.empty_frame,
R.drawable.snowballrun_standing_snowman,
SnowballRunSprites.running_snowman_squish,
R.drawable.snowballrun_snowman_squished_09),
ELF(
SnowballRunSprites.snowballrun_running_elf_opponent,
R.drawable.snowballrun_running_starting_elfopponent,
SnowballRunSprites.empty_frame,
SnowballRunSprites.empty_frame,
R.drawable.snowballrun_standing_elfopponent,
SnowballRunSprites.running_elfopponent_squish,
R.drawable.snowballrun_elfopponent_squished_09),
REINDEER(
SnowballRunSprites.snowballrun_running_reindeer_opponent,
R.drawable.snowballrun_running_starting_reindeer,
SnowballRunSprites.empty_frame,
SnowballRunSprites.empty_frame,
R.drawable.snowballrun_standing_reindeer,
SnowballRunSprites.snowballrun_reindeer_squish,
R.drawable.snowballrun_reindeer_squished_05);
public int[] runRes, crouchRes, runLeftRes, enteringRes, standRes, dyingRes, deadRes;
RunnerType(
int[] runRes,
int crouchRes,
int[] runLeftRes,
int[] enteringRes,
int standRes,
int[] dyingRes,
int deadRes) {
this.runRes = runRes;
this.crouchRes = new int[] {crouchRes};
this.runLeftRes = runLeftRes;
this.enteringRes = enteringRes;
this.standRes = new int[] {standRes};
this.dyingRes = dyingRes;
this.deadRes = new int[] {deadRes};
}
}
// TODO: Because the running left animation is no longer used for the opponents'
// entrance, consider moving RUNNING_LEFT and RUNNING_RIGHT to PlayerActor.
enum RunnerState {
RUNNING,
CROUCH,
ENTERING,
RUNNING_LEFT,
RUNNING_RIGHT,
STANDING,
DYING,
DEAD,
}
}
|
924616fc423ec6537007c288ae2cc7d0d46a172d
| 42,009 |
java
|
Java
|
ExtractedJars/Health_com.huawei.health/javafiles/android/support/v4/media/session/MediaControllerCompat$MediaControllerImplBase.java
|
Andreas237/AndroidPolicyAutomation
|
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
|
[
"MIT"
] | 3 |
2019-05-01T09:22:08.000Z
|
2019-07-06T22:21:59.000Z
|
ExtractedJars/Health_com.huawei.health/javafiles/android/support/v4/media/session/MediaControllerCompat$MediaControllerImplBase.java
|
Andreas237/AndroidPolicyAutomation
|
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
|
[
"MIT"
] | null | null | null |
ExtractedJars/Health_com.huawei.health/javafiles/android/support/v4/media/session/MediaControllerCompat$MediaControllerImplBase.java
|
Andreas237/AndroidPolicyAutomation
|
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
|
[
"MIT"
] | 1 |
2020-11-26T12:22:02.000Z
|
2020-11-26T12:22:02.000Z
| 43.174717 | 280 | 0.594944 | 1,003,642 |
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package android.support.v4.media.session;
import android.app.PendingIntent;
import android.os.*;
import android.support.v4.media.MediaDescriptionCompat;
import android.support.v4.media.MediaMetadataCompat;
import android.util.Log;
import android.view.KeyEvent;
import java.util.List;
// Referenced classes of package android.support.v4.media.session:
// MediaControllerCompat, IMediaSession, ParcelableVolumeInfo, IMediaControllerCallback,
// PlaybackStateCompat
static class MediaControllerCompat$MediaControllerImplBase
implements MediaControllerCompat.MediaControllerImpl
{
public void addQueueItem(MediaDescriptionCompat mediadescriptioncompat)
{
try
{
if((4L & mBinder.getFlags()) == 0L)
//* 0 0:ldc2w #44 <Long 4L>
//* 1 3:aload_0
//* 2 4:getfield #38 <Field IMediaSession mBinder>
//* 3 7:invokeinterface #51 <Method long IMediaSession.getFlags()>
//* 4 12:land
//* 5 13:lconst_0
//* 6 14:lcmp
//* 7 15:ifne 28
{
throw new UnsupportedOperationException("This session doesn't support queue management operations");
// 8 18:new #53 <Class UnsupportedOperationException>
// 9 21:dup
// 10 22:ldc1 #55 <String "This session doesn't support queue management operations">
// 11 24:invokespecial #58 <Method void UnsupportedOperationException(String)>
// 12 27:athrow
} else
{
mBinder.addQueueItem(mediadescriptioncompat);
// 13 28:aload_0
// 14 29:getfield #38 <Field IMediaSession mBinder>
// 15 32:aload_1
// 16 33:invokeinterface #60 <Method void IMediaSession.addQueueItem(MediaDescriptionCompat)>
return;
// 17 38:return
}
}
// Misplaced declaration of an exception variable
catch(MediaDescriptionCompat mediadescriptioncompat)
//* 18 39:astore_1
{
Log.e("MediaControllerCompat", (new StringBuilder()).append("Dead object in addQueueItem. ").append(((Object) (mediadescriptioncompat))).toString());
// 19 40:ldc1 #62 <String "MediaControllerCompat">
// 20 42:new #64 <Class StringBuilder>
// 21 45:dup
// 22 46:invokespecial #65 <Method void StringBuilder()>
// 23 49:ldc1 #67 <String "Dead object in addQueueItem. ">
// 24 51:invokevirtual #71 <Method StringBuilder StringBuilder.append(String)>
// 25 54:aload_1
// 26 55:invokevirtual #74 <Method StringBuilder StringBuilder.append(Object)>
// 27 58:invokevirtual #78 <Method String StringBuilder.toString()>
// 28 61:invokestatic #84 <Method int Log.e(String, String)>
// 29 64:pop
}
// 30 65:return
}
public void addQueueItem(MediaDescriptionCompat mediadescriptioncompat, int i)
{
try
{
if((4L & mBinder.getFlags()) == 0L)
//* 0 0:ldc2w #44 <Long 4L>
//* 1 3:aload_0
//* 2 4:getfield #38 <Field IMediaSession mBinder>
//* 3 7:invokeinterface #51 <Method long IMediaSession.getFlags()>
//* 4 12:land
//* 5 13:lconst_0
//* 6 14:lcmp
//* 7 15:ifne 28
{
throw new UnsupportedOperationException("This session doesn't support queue management operations");
// 8 18:new #53 <Class UnsupportedOperationException>
// 9 21:dup
// 10 22:ldc1 #55 <String "This session doesn't support queue management operations">
// 11 24:invokespecial #58 <Method void UnsupportedOperationException(String)>
// 12 27:athrow
} else
{
mBinder.addQueueItemAt(mediadescriptioncompat, i);
// 13 28:aload_0
// 14 29:getfield #38 <Field IMediaSession mBinder>
// 15 32:aload_1
// 16 33:iload_2
// 17 34:invokeinterface #88 <Method void IMediaSession.addQueueItemAt(MediaDescriptionCompat, int)>
return;
// 18 39:return
}
}
// Misplaced declaration of an exception variable
catch(MediaDescriptionCompat mediadescriptioncompat)
//* 19 40:astore_1
{
Log.e("MediaControllerCompat", (new StringBuilder()).append("Dead object in addQueueItemAt. ").append(((Object) (mediadescriptioncompat))).toString());
// 20 41:ldc1 #62 <String "MediaControllerCompat">
// 21 43:new #64 <Class StringBuilder>
// 22 46:dup
// 23 47:invokespecial #65 <Method void StringBuilder()>
// 24 50:ldc1 #90 <String "Dead object in addQueueItemAt. ">
// 25 52:invokevirtual #71 <Method StringBuilder StringBuilder.append(String)>
// 26 55:aload_1
// 27 56:invokevirtual #74 <Method StringBuilder StringBuilder.append(Object)>
// 28 59:invokevirtual #78 <Method String StringBuilder.toString()>
// 29 62:invokestatic #84 <Method int Log.e(String, String)>
// 30 65:pop
}
// 31 66:return
}
public void adjustVolume(int i, int j)
{
try
{
mBinder.adjustVolume(i, j, ((String) (null)));
// 0 0:aload_0
// 1 1:getfield #38 <Field IMediaSession mBinder>
// 2 4:iload_1
// 3 5:iload_2
// 4 6:aconst_null
// 5 7:invokeinterface #95 <Method void IMediaSession.adjustVolume(int, int, String)>
return;
// 6 12:return
}
catch(RemoteException remoteexception)
//* 7 13:astore_3
{
Log.e("MediaControllerCompat", (new StringBuilder()).append("Dead object in adjustVolume. ").append(((Object) (remoteexception))).toString());
// 8 14:ldc1 #62 <String "MediaControllerCompat">
// 9 16:new #64 <Class StringBuilder>
// 10 19:dup
// 11 20:invokespecial #65 <Method void StringBuilder()>
// 12 23:ldc1 #97 <String "Dead object in adjustVolume. ">
// 13 25:invokevirtual #71 <Method StringBuilder StringBuilder.append(String)>
// 14 28:aload_3
// 15 29:invokevirtual #74 <Method StringBuilder StringBuilder.append(Object)>
// 16 32:invokevirtual #78 <Method String StringBuilder.toString()>
// 17 35:invokestatic #84 <Method int Log.e(String, String)>
// 18 38:pop
}
// 19 39:return
}
public boolean dispatchMediaButtonEvent(KeyEvent keyevent)
{
if(keyevent == null)
//* 0 0:aload_1
//* 1 1:ifnonnull 14
throw new IllegalArgumentException("event may not be null.");
// 2 4:new #101 <Class IllegalArgumentException>
// 3 7:dup
// 4 8:ldc1 #103 <String "event may not be null.">
// 5 10:invokespecial #104 <Method void IllegalArgumentException(String)>
// 6 13:athrow
try
{
mBinder.sendMediaButton(keyevent);
// 7 14:aload_0
// 8 15:getfield #38 <Field IMediaSession mBinder>
// 9 18:aload_1
// 10 19:invokeinterface #107 <Method boolean IMediaSession.sendMediaButton(KeyEvent)>
// 11 24:pop
}
//* 12 25:goto 54
// Misplaced declaration of an exception variable
catch(KeyEvent keyevent)
//* 13 28:astore_1
{
Log.e("MediaControllerCompat", (new StringBuilder()).append("Dead object in dispatchMediaButtonEvent. ").append(((Object) (keyevent))).toString());
// 14 29:ldc1 #62 <String "MediaControllerCompat">
// 15 31:new #64 <Class StringBuilder>
// 16 34:dup
// 17 35:invokespecial #65 <Method void StringBuilder()>
// 18 38:ldc1 #109 <String "Dead object in dispatchMediaButtonEvent. ">
// 19 40:invokevirtual #71 <Method StringBuilder StringBuilder.append(String)>
// 20 43:aload_1
// 21 44:invokevirtual #74 <Method StringBuilder StringBuilder.append(Object)>
// 22 47:invokevirtual #78 <Method String StringBuilder.toString()>
// 23 50:invokestatic #84 <Method int Log.e(String, String)>
// 24 53:pop
}
return false;
// 25 54:iconst_0
// 26 55:ireturn
}
public Bundle getExtras()
{
Bundle bundle;
try
{
bundle = mBinder.getExtras();
// 0 0:aload_0
// 1 1:getfield #38 <Field IMediaSession mBinder>
// 2 4:invokeinterface #113 <Method Bundle IMediaSession.getExtras()>
// 3 9:astore_1
}
//* 4 10:aload_1
//* 5 11:areturn
catch(RemoteException remoteexception)
//* 6 12:astore_1
{
Log.e("MediaControllerCompat", (new StringBuilder()).append("Dead object in getExtras. ").append(((Object) (remoteexception))).toString());
// 7 13:ldc1 #62 <String "MediaControllerCompat">
// 8 15:new #64 <Class StringBuilder>
// 9 18:dup
// 10 19:invokespecial #65 <Method void StringBuilder()>
// 11 22:ldc1 #115 <String "Dead object in getExtras. ">
// 12 24:invokevirtual #71 <Method StringBuilder StringBuilder.append(String)>
// 13 27:aload_1
// 14 28:invokevirtual #74 <Method StringBuilder StringBuilder.append(Object)>
// 15 31:invokevirtual #78 <Method String StringBuilder.toString()>
// 16 34:invokestatic #84 <Method int Log.e(String, String)>
// 17 37:pop
return null;
// 18 38:aconst_null
// 19 39:areturn
}
return bundle;
}
public long getFlags()
{
long l;
try
{
l = mBinder.getFlags();
// 0 0:aload_0
// 1 1:getfield #38 <Field IMediaSession mBinder>
// 2 4:invokeinterface #51 <Method long IMediaSession.getFlags()>
// 3 9:lstore_1
}
//* 4 10:lload_1
//* 5 11:lreturn
catch(RemoteException remoteexception)
//* 6 12:astore_3
{
Log.e("MediaControllerCompat", (new StringBuilder()).append("Dead object in getFlags. ").append(((Object) (remoteexception))).toString());
// 7 13:ldc1 #62 <String "MediaControllerCompat">
// 8 15:new #64 <Class StringBuilder>
// 9 18:dup
// 10 19:invokespecial #65 <Method void StringBuilder()>
// 11 22:ldc1 #117 <String "Dead object in getFlags. ">
// 12 24:invokevirtual #71 <Method StringBuilder StringBuilder.append(String)>
// 13 27:aload_3
// 14 28:invokevirtual #74 <Method StringBuilder StringBuilder.append(Object)>
// 15 31:invokevirtual #78 <Method String StringBuilder.toString()>
// 16 34:invokestatic #84 <Method int Log.e(String, String)>
// 17 37:pop
return 0L;
// 18 38:lconst_0
// 19 39:lreturn
}
return l;
}
public Object getMediaController()
{
return ((Object) (null));
// 0 0:aconst_null
// 1 1:areturn
}
public MediaMetadataCompat getMetadata()
{
MediaMetadataCompat mediametadatacompat;
try
{
mediametadatacompat = mBinder.getMetadata();
// 0 0:aload_0
// 1 1:getfield #38 <Field IMediaSession mBinder>
// 2 4:invokeinterface #122 <Method MediaMetadataCompat IMediaSession.getMetadata()>
// 3 9:astore_1
}
//* 4 10:aload_1
//* 5 11:areturn
catch(RemoteException remoteexception)
//* 6 12:astore_1
{
Log.e("MediaControllerCompat", (new StringBuilder()).append("Dead object in getMetadata. ").append(((Object) (remoteexception))).toString());
// 7 13:ldc1 #62 <String "MediaControllerCompat">
// 8 15:new #64 <Class StringBuilder>
// 9 18:dup
// 10 19:invokespecial #65 <Method void StringBuilder()>
// 11 22:ldc1 #124 <String "Dead object in getMetadata. ">
// 12 24:invokevirtual #71 <Method StringBuilder StringBuilder.append(String)>
// 13 27:aload_1
// 14 28:invokevirtual #74 <Method StringBuilder StringBuilder.append(Object)>
// 15 31:invokevirtual #78 <Method String StringBuilder.toString()>
// 16 34:invokestatic #84 <Method int Log.e(String, String)>
// 17 37:pop
return null;
// 18 38:aconst_null
// 19 39:areturn
}
return mediametadatacompat;
}
public String getPackageName()
{
String s;
try
{
s = mBinder.getPackageName();
// 0 0:aload_0
// 1 1:getfield #38 <Field IMediaSession mBinder>
// 2 4:invokeinterface #127 <Method String IMediaSession.getPackageName()>
// 3 9:astore_1
}
//* 4 10:aload_1
//* 5 11:areturn
catch(RemoteException remoteexception)
//* 6 12:astore_1
{
Log.e("MediaControllerCompat", (new StringBuilder()).append("Dead object in getPackageName. ").append(((Object) (remoteexception))).toString());
// 7 13:ldc1 #62 <String "MediaControllerCompat">
// 8 15:new #64 <Class StringBuilder>
// 9 18:dup
// 10 19:invokespecial #65 <Method void StringBuilder()>
// 11 22:ldc1 #129 <String "Dead object in getPackageName. ">
// 12 24:invokevirtual #71 <Method StringBuilder StringBuilder.append(String)>
// 13 27:aload_1
// 14 28:invokevirtual #74 <Method StringBuilder StringBuilder.append(Object)>
// 15 31:invokevirtual #78 <Method String StringBuilder.toString()>
// 16 34:invokestatic #84 <Method int Log.e(String, String)>
// 17 37:pop
return null;
// 18 38:aconst_null
// 19 39:areturn
}
return s;
}
public MediaControllerCompat.PlaybackInfo getPlaybackInfo()
{
Object obj;
try
{
obj = ((Object) (mBinder.getVolumeAttributes()));
// 0 0:aload_0
// 1 1:getfield #38 <Field IMediaSession mBinder>
// 2 4:invokeinterface #135 <Method ParcelableVolumeInfo IMediaSession.getVolumeAttributes()>
// 3 9:astore_1
obj = ((Object) (new MediaControllerCompat.PlaybackInfo(((ParcelableVolumeInfo) (obj)).volumeType, ((ParcelableVolumeInfo) (obj)).audioStream, ((ParcelableVolumeInfo) (obj)).controlType, ((ParcelableVolumeInfo) (obj)).maxVolume, ((ParcelableVolumeInfo) (obj)).currentVolume)));
// 4 10:new #137 <Class MediaControllerCompat$PlaybackInfo>
// 5 13:dup
// 6 14:aload_1
// 7 15:getfield #143 <Field int ParcelableVolumeInfo.volumeType>
// 8 18:aload_1
// 9 19:getfield #146 <Field int ParcelableVolumeInfo.audioStream>
// 10 22:aload_1
// 11 23:getfield #149 <Field int ParcelableVolumeInfo.controlType>
// 12 26:aload_1
// 13 27:getfield #152 <Field int ParcelableVolumeInfo.maxVolume>
// 14 30:aload_1
// 15 31:getfield #155 <Field int ParcelableVolumeInfo.currentVolume>
// 16 34:invokespecial #158 <Method void MediaControllerCompat$PlaybackInfo(int, int, int, int, int)>
// 17 37:astore_1
}
//* 18 38:aload_1
//* 19 39:areturn
catch(RemoteException remoteexception)
//* 20 40:astore_1
{
Log.e("MediaControllerCompat", (new StringBuilder()).append("Dead object in getPlaybackInfo. ").append(((Object) (remoteexception))).toString());
// 21 41:ldc1 #62 <String "MediaControllerCompat">
// 22 43:new #64 <Class StringBuilder>
// 23 46:dup
// 24 47:invokespecial #65 <Method void StringBuilder()>
// 25 50:ldc1 #160 <String "Dead object in getPlaybackInfo. ">
// 26 52:invokevirtual #71 <Method StringBuilder StringBuilder.append(String)>
// 27 55:aload_1
// 28 56:invokevirtual #74 <Method StringBuilder StringBuilder.append(Object)>
// 29 59:invokevirtual #78 <Method String StringBuilder.toString()>
// 30 62:invokestatic #84 <Method int Log.e(String, String)>
// 31 65:pop
return null;
// 32 66:aconst_null
// 33 67:areturn
}
return ((MediaControllerCompat.PlaybackInfo) (obj));
}
public PlaybackStateCompat getPlaybackState()
{
PlaybackStateCompat playbackstatecompat;
try
{
playbackstatecompat = mBinder.getPlaybackState();
// 0 0:aload_0
// 1 1:getfield #38 <Field IMediaSession mBinder>
// 2 4:invokeinterface #164 <Method PlaybackStateCompat IMediaSession.getPlaybackState()>
// 3 9:astore_1
}
//* 4 10:aload_1
//* 5 11:areturn
catch(RemoteException remoteexception)
//* 6 12:astore_1
{
Log.e("MediaControllerCompat", (new StringBuilder()).append("Dead object in getPlaybackState. ").append(((Object) (remoteexception))).toString());
// 7 13:ldc1 #62 <String "MediaControllerCompat">
// 8 15:new #64 <Class StringBuilder>
// 9 18:dup
// 10 19:invokespecial #65 <Method void StringBuilder()>
// 11 22:ldc1 #166 <String "Dead object in getPlaybackState. ">
// 12 24:invokevirtual #71 <Method StringBuilder StringBuilder.append(String)>
// 13 27:aload_1
// 14 28:invokevirtual #74 <Method StringBuilder StringBuilder.append(Object)>
// 15 31:invokevirtual #78 <Method String StringBuilder.toString()>
// 16 34:invokestatic #84 <Method int Log.e(String, String)>
// 17 37:pop
return null;
// 18 38:aconst_null
// 19 39:areturn
}
return playbackstatecompat;
}
public List getQueue()
{
List list;
try
{
list = mBinder.getQueue();
// 0 0:aload_0
// 1 1:getfield #38 <Field IMediaSession mBinder>
// 2 4:invokeinterface #170 <Method List IMediaSession.getQueue()>
// 3 9:astore_1
}
//* 4 10:aload_1
//* 5 11:areturn
catch(RemoteException remoteexception)
//* 6 12:astore_1
{
Log.e("MediaControllerCompat", (new StringBuilder()).append("Dead object in getQueue. ").append(((Object) (remoteexception))).toString());
// 7 13:ldc1 #62 <String "MediaControllerCompat">
// 8 15:new #64 <Class StringBuilder>
// 9 18:dup
// 10 19:invokespecial #65 <Method void StringBuilder()>
// 11 22:ldc1 #172 <String "Dead object in getQueue. ">
// 12 24:invokevirtual #71 <Method StringBuilder StringBuilder.append(String)>
// 13 27:aload_1
// 14 28:invokevirtual #74 <Method StringBuilder StringBuilder.append(Object)>
// 15 31:invokevirtual #78 <Method String StringBuilder.toString()>
// 16 34:invokestatic #84 <Method int Log.e(String, String)>
// 17 37:pop
return null;
// 18 38:aconst_null
// 19 39:areturn
}
return list;
}
public CharSequence getQueueTitle()
{
CharSequence charsequence;
try
{
charsequence = mBinder.getQueueTitle();
// 0 0:aload_0
// 1 1:getfield #38 <Field IMediaSession mBinder>
// 2 4:invokeinterface #178 <Method CharSequence IMediaSession.getQueueTitle()>
// 3 9:astore_1
}
//* 4 10:aload_1
//* 5 11:areturn
catch(RemoteException remoteexception)
//* 6 12:astore_1
{
Log.e("MediaControllerCompat", (new StringBuilder()).append("Dead object in getQueueTitle. ").append(((Object) (remoteexception))).toString());
// 7 13:ldc1 #62 <String "MediaControllerCompat">
// 8 15:new #64 <Class StringBuilder>
// 9 18:dup
// 10 19:invokespecial #65 <Method void StringBuilder()>
// 11 22:ldc1 #180 <String "Dead object in getQueueTitle. ">
// 12 24:invokevirtual #71 <Method StringBuilder StringBuilder.append(String)>
// 13 27:aload_1
// 14 28:invokevirtual #74 <Method StringBuilder StringBuilder.append(Object)>
// 15 31:invokevirtual #78 <Method String StringBuilder.toString()>
// 16 34:invokestatic #84 <Method int Log.e(String, String)>
// 17 37:pop
return null;
// 18 38:aconst_null
// 19 39:areturn
}
return charsequence;
}
public int getRatingType()
{
int i;
try
{
i = mBinder.getRatingType();
// 0 0:aload_0
// 1 1:getfield #38 <Field IMediaSession mBinder>
// 2 4:invokeinterface #184 <Method int IMediaSession.getRatingType()>
// 3 9:istore_1
}
//* 4 10:iload_1
//* 5 11:ireturn
catch(RemoteException remoteexception)
//* 6 12:astore_2
{
Log.e("MediaControllerCompat", (new StringBuilder()).append("Dead object in getRatingType. ").append(((Object) (remoteexception))).toString());
// 7 13:ldc1 #62 <String "MediaControllerCompat">
// 8 15:new #64 <Class StringBuilder>
// 9 18:dup
// 10 19:invokespecial #65 <Method void StringBuilder()>
// 11 22:ldc1 #186 <String "Dead object in getRatingType. ">
// 12 24:invokevirtual #71 <Method StringBuilder StringBuilder.append(String)>
// 13 27:aload_2
// 14 28:invokevirtual #74 <Method StringBuilder StringBuilder.append(Object)>
// 15 31:invokevirtual #78 <Method String StringBuilder.toString()>
// 16 34:invokestatic #84 <Method int Log.e(String, String)>
// 17 37:pop
return 0;
// 18 38:iconst_0
// 19 39:ireturn
}
return i;
}
public int getRepeatMode()
{
int i;
try
{
i = mBinder.getRepeatMode();
// 0 0:aload_0
// 1 1:getfield #38 <Field IMediaSession mBinder>
// 2 4:invokeinterface #189 <Method int IMediaSession.getRepeatMode()>
// 3 9:istore_1
}
//* 4 10:iload_1
//* 5 11:ireturn
catch(RemoteException remoteexception)
//* 6 12:astore_2
{
Log.e("MediaControllerCompat", (new StringBuilder()).append("Dead object in getRepeatMode. ").append(((Object) (remoteexception))).toString());
// 7 13:ldc1 #62 <String "MediaControllerCompat">
// 8 15:new #64 <Class StringBuilder>
// 9 18:dup
// 10 19:invokespecial #65 <Method void StringBuilder()>
// 11 22:ldc1 #191 <String "Dead object in getRepeatMode. ">
// 12 24:invokevirtual #71 <Method StringBuilder StringBuilder.append(String)>
// 13 27:aload_2
// 14 28:invokevirtual #74 <Method StringBuilder StringBuilder.append(Object)>
// 15 31:invokevirtual #78 <Method String StringBuilder.toString()>
// 16 34:invokestatic #84 <Method int Log.e(String, String)>
// 17 37:pop
return 0;
// 18 38:iconst_0
// 19 39:ireturn
}
return i;
}
public PendingIntent getSessionActivity()
{
PendingIntent pendingintent;
try
{
pendingintent = mBinder.getLaunchPendingIntent();
// 0 0:aload_0
// 1 1:getfield #38 <Field IMediaSession mBinder>
// 2 4:invokeinterface #196 <Method PendingIntent IMediaSession.getLaunchPendingIntent()>
// 3 9:astore_1
}
//* 4 10:aload_1
//* 5 11:areturn
catch(RemoteException remoteexception)
//* 6 12:astore_1
{
Log.e("MediaControllerCompat", (new StringBuilder()).append("Dead object in getSessionActivity. ").append(((Object) (remoteexception))).toString());
// 7 13:ldc1 #62 <String "MediaControllerCompat">
// 8 15:new #64 <Class StringBuilder>
// 9 18:dup
// 10 19:invokespecial #65 <Method void StringBuilder()>
// 11 22:ldc1 #198 <String "Dead object in getSessionActivity. ">
// 12 24:invokevirtual #71 <Method StringBuilder StringBuilder.append(String)>
// 13 27:aload_1
// 14 28:invokevirtual #74 <Method StringBuilder StringBuilder.append(Object)>
// 15 31:invokevirtual #78 <Method String StringBuilder.toString()>
// 16 34:invokestatic #84 <Method int Log.e(String, String)>
// 17 37:pop
return null;
// 18 38:aconst_null
// 19 39:areturn
}
return pendingintent;
}
public MediaControllerCompat.TransportControls getTransportControls()
{
if(mTransportControls == null)
//* 0 0:aload_0
//* 1 1:getfield #202 <Field MediaControllerCompat$TransportControls mTransportControls>
//* 2 4:ifnonnull 22
mTransportControls = ((MediaControllerCompat.TransportControls) (new MediaControllerCompat.TransportControlsBase(mBinder)));
// 3 7:aload_0
// 4 8:new #204 <Class MediaControllerCompat$TransportControlsBase>
// 5 11:dup
// 6 12:aload_0
// 7 13:getfield #38 <Field IMediaSession mBinder>
// 8 16:invokespecial #207 <Method void MediaControllerCompat$TransportControlsBase(IMediaSession)>
// 9 19:putfield #202 <Field MediaControllerCompat$TransportControls mTransportControls>
return mTransportControls;
// 10 22:aload_0
// 11 23:getfield #202 <Field MediaControllerCompat$TransportControls mTransportControls>
// 12 26:areturn
}
public boolean isShuffleModeEnabled()
{
boolean flag;
try
{
flag = mBinder.isShuffleModeEnabled();
// 0 0:aload_0
// 1 1:getfield #38 <Field IMediaSession mBinder>
// 2 4:invokeinterface #211 <Method boolean IMediaSession.isShuffleModeEnabled()>
// 3 9:istore_1
}
//* 4 10:iload_1
//* 5 11:ireturn
catch(RemoteException remoteexception)
//* 6 12:astore_2
{
Log.e("MediaControllerCompat", (new StringBuilder()).append("Dead object in isShuffleModeEnabled. ").append(((Object) (remoteexception))).toString());
// 7 13:ldc1 #62 <String "MediaControllerCompat">
// 8 15:new #64 <Class StringBuilder>
// 9 18:dup
// 10 19:invokespecial #65 <Method void StringBuilder()>
// 11 22:ldc1 #213 <String "Dead object in isShuffleModeEnabled. ">
// 12 24:invokevirtual #71 <Method StringBuilder StringBuilder.append(String)>
// 13 27:aload_2
// 14 28:invokevirtual #74 <Method StringBuilder StringBuilder.append(Object)>
// 15 31:invokevirtual #78 <Method String StringBuilder.toString()>
// 16 34:invokestatic #84 <Method int Log.e(String, String)>
// 17 37:pop
return false;
// 18 38:iconst_0
// 19 39:ireturn
}
return flag;
}
public void registerCallback(MediaControllerCompat.Callback callback, Handler handler)
{
if(callback == null)
//* 0 0:aload_1
//* 1 1:ifnonnull 14
throw new IllegalArgumentException("callback may not be null.");
// 2 4:new #101 <Class IllegalArgumentException>
// 3 7:dup
// 4 8:ldc1 #217 <String "callback may not be null.">
// 5 10:invokespecial #104 <Method void IllegalArgumentException(String)>
// 6 13:athrow
try
{
mBinder.asBinder().linkToDeath(((android.os.IBinder.DeathRecipient) (callback)), 0);
// 7 14:aload_0
// 8 15:getfield #38 <Field IMediaSession mBinder>
// 9 18:invokeinterface #221 <Method IBinder IMediaSession.asBinder()>
// 10 23:aload_1
// 11 24:iconst_0
// 12 25:invokeinterface #225 <Method void IBinder.linkToDeath(android.os.IBinder$DeathRecipient, int)>
mBinder.registerCallbackListener((IMediaControllerCallback)MediaControllerCompat.Callback.access$200(callback));
// 13 30:aload_0
// 14 31:getfield #38 <Field IMediaSession mBinder>
// 15 34:aload_1
// 16 35:invokestatic #231 <Method Object MediaControllerCompat$Callback.access$200(MediaControllerCompat$Callback)>
// 17 38:checkcast #233 <Class IMediaControllerCallback>
// 18 41:invokeinterface #237 <Method void IMediaSession.registerCallbackListener(IMediaControllerCallback)>
MediaControllerCompat.Callback.access$300(callback, handler);
// 19 46:aload_1
// 20 47:aload_2
// 21 48:invokestatic #240 <Method void MediaControllerCompat$Callback.access$300(MediaControllerCompat$Callback, Handler)>
callback.mRegistered = true;
// 22 51:aload_1
// 23 52:iconst_1
// 24 53:putfield #244 <Field boolean MediaControllerCompat$Callback.mRegistered>
return;
// 25 56:return
}
// Misplaced declaration of an exception variable
catch(Handler handler)
//* 26 57:astore_2
{
Log.e("MediaControllerCompat", (new StringBuilder()).append("Dead object in registerCallback. ").append(((Object) (handler))).toString());
// 27 58:ldc1 #62 <String "MediaControllerCompat">
// 28 60:new #64 <Class StringBuilder>
// 29 63:dup
// 30 64:invokespecial #65 <Method void StringBuilder()>
// 31 67:ldc1 #246 <String "Dead object in registerCallback. ">
// 32 69:invokevirtual #71 <Method StringBuilder StringBuilder.append(String)>
// 33 72:aload_2
// 34 73:invokevirtual #74 <Method StringBuilder StringBuilder.append(Object)>
// 35 76:invokevirtual #78 <Method String StringBuilder.toString()>
// 36 79:invokestatic #84 <Method int Log.e(String, String)>
// 37 82:pop
}
callback.onSessionDestroyed();
// 38 83:aload_1
// 39 84:invokevirtual #249 <Method void MediaControllerCompat$Callback.onSessionDestroyed()>
// 40 87:return
}
public void removeQueueItem(MediaDescriptionCompat mediadescriptioncompat)
{
try
{
if((4L & mBinder.getFlags()) == 0L)
//* 0 0:ldc2w #44 <Long 4L>
//* 1 3:aload_0
//* 2 4:getfield #38 <Field IMediaSession mBinder>
//* 3 7:invokeinterface #51 <Method long IMediaSession.getFlags()>
//* 4 12:land
//* 5 13:lconst_0
//* 6 14:lcmp
//* 7 15:ifne 28
{
throw new UnsupportedOperationException("This session doesn't support queue management operations");
// 8 18:new #53 <Class UnsupportedOperationException>
// 9 21:dup
// 10 22:ldc1 #55 <String "This session doesn't support queue management operations">
// 11 24:invokespecial #58 <Method void UnsupportedOperationException(String)>
// 12 27:athrow
} else
{
mBinder.removeQueueItem(mediadescriptioncompat);
// 13 28:aload_0
// 14 29:getfield #38 <Field IMediaSession mBinder>
// 15 32:aload_1
// 16 33:invokeinterface #252 <Method void IMediaSession.removeQueueItem(MediaDescriptionCompat)>
return;
// 17 38:return
}
}
// Misplaced declaration of an exception variable
catch(MediaDescriptionCompat mediadescriptioncompat)
//* 18 39:astore_1
{
Log.e("MediaControllerCompat", (new StringBuilder()).append("Dead object in removeQueueItem. ").append(((Object) (mediadescriptioncompat))).toString());
// 19 40:ldc1 #62 <String "MediaControllerCompat">
// 20 42:new #64 <Class StringBuilder>
// 21 45:dup
// 22 46:invokespecial #65 <Method void StringBuilder()>
// 23 49:ldc1 #254 <String "Dead object in removeQueueItem. ">
// 24 51:invokevirtual #71 <Method StringBuilder StringBuilder.append(String)>
// 25 54:aload_1
// 26 55:invokevirtual #74 <Method StringBuilder StringBuilder.append(Object)>
// 27 58:invokevirtual #78 <Method String StringBuilder.toString()>
// 28 61:invokestatic #84 <Method int Log.e(String, String)>
// 29 64:pop
}
// 30 65:return
}
public void removeQueueItemAt(int i)
{
try
{
if((4L & mBinder.getFlags()) == 0L)
//* 0 0:ldc2w #44 <Long 4L>
//* 1 3:aload_0
//* 2 4:getfield #38 <Field IMediaSession mBinder>
//* 3 7:invokeinterface #51 <Method long IMediaSession.getFlags()>
//* 4 12:land
//* 5 13:lconst_0
//* 6 14:lcmp
//* 7 15:ifne 28
{
throw new UnsupportedOperationException("This session doesn't support queue management operations");
// 8 18:new #53 <Class UnsupportedOperationException>
// 9 21:dup
// 10 22:ldc1 #55 <String "This session doesn't support queue management operations">
// 11 24:invokespecial #58 <Method void UnsupportedOperationException(String)>
// 12 27:athrow
} else
{
mBinder.removeQueueItemAt(i);
// 13 28:aload_0
// 14 29:getfield #38 <Field IMediaSession mBinder>
// 15 32:iload_1
// 16 33:invokeinterface #258 <Method void IMediaSession.removeQueueItemAt(int)>
return;
// 17 38:return
}
}
catch(RemoteException remoteexception)
//* 18 39:astore_2
{
Log.e("MediaControllerCompat", (new StringBuilder()).append("Dead object in removeQueueItemAt. ").append(((Object) (remoteexception))).toString());
// 19 40:ldc1 #62 <String "MediaControllerCompat">
// 20 42:new #64 <Class StringBuilder>
// 21 45:dup
// 22 46:invokespecial #65 <Method void StringBuilder()>
// 23 49:ldc2 #260 <String "Dead object in removeQueueItemAt. ">
// 24 52:invokevirtual #71 <Method StringBuilder StringBuilder.append(String)>
// 25 55:aload_2
// 26 56:invokevirtual #74 <Method StringBuilder StringBuilder.append(Object)>
// 27 59:invokevirtual #78 <Method String StringBuilder.toString()>
// 28 62:invokestatic #84 <Method int Log.e(String, String)>
// 29 65:pop
}
// 30 66:return
}
public void sendCommand(String s, Bundle bundle, ResultReceiver resultreceiver)
{
try
{
mBinder.sendCommand(s, bundle, new MediaSessionCompat.ResultReceiverWrapper(resultreceiver));
// 0 0:aload_0
// 1 1:getfield #38 <Field IMediaSession mBinder>
// 2 4:aload_1
// 3 5:aload_2
// 4 6:new #264 <Class MediaSessionCompat$ResultReceiverWrapper>
// 5 9:dup
// 6 10:aload_3
// 7 11:invokespecial #267 <Method void MediaSessionCompat$ResultReceiverWrapper(ResultReceiver)>
// 8 14:invokeinterface #270 <Method void IMediaSession.sendCommand(String, Bundle, MediaSessionCompat$ResultReceiverWrapper)>
return;
// 9 19:return
}
// Misplaced declaration of an exception variable
catch(String s)
//* 10 20:astore_1
{
Log.e("MediaControllerCompat", (new StringBuilder()).append("Dead object in sendCommand. ").append(((Object) (s))).toString());
// 11 21:ldc1 #62 <String "MediaControllerCompat">
// 12 23:new #64 <Class StringBuilder>
// 13 26:dup
// 14 27:invokespecial #65 <Method void StringBuilder()>
// 15 30:ldc2 #272 <String "Dead object in sendCommand. ">
// 16 33:invokevirtual #71 <Method StringBuilder StringBuilder.append(String)>
// 17 36:aload_1
// 18 37:invokevirtual #74 <Method StringBuilder StringBuilder.append(Object)>
// 19 40:invokevirtual #78 <Method String StringBuilder.toString()>
// 20 43:invokestatic #84 <Method int Log.e(String, String)>
// 21 46:pop
}
// 22 47:return
}
public void setVolumeTo(int i, int j)
{
try
{
mBinder.setVolumeTo(i, j, ((String) (null)));
// 0 0:aload_0
// 1 1:getfield #38 <Field IMediaSession mBinder>
// 2 4:iload_1
// 3 5:iload_2
// 4 6:aconst_null
// 5 7:invokeinterface #275 <Method void IMediaSession.setVolumeTo(int, int, String)>
return;
// 6 12:return
}
catch(RemoteException remoteexception)
//* 7 13:astore_3
{
Log.e("MediaControllerCompat", (new StringBuilder()).append("Dead object in setVolumeTo. ").append(((Object) (remoteexception))).toString());
// 8 14:ldc1 #62 <String "MediaControllerCompat">
// 9 16:new #64 <Class StringBuilder>
// 10 19:dup
// 11 20:invokespecial #65 <Method void StringBuilder()>
// 12 23:ldc2 #277 <String "Dead object in setVolumeTo. ">
// 13 26:invokevirtual #71 <Method StringBuilder StringBuilder.append(String)>
// 14 29:aload_3
// 15 30:invokevirtual #74 <Method StringBuilder StringBuilder.append(Object)>
// 16 33:invokevirtual #78 <Method String StringBuilder.toString()>
// 17 36:invokestatic #84 <Method int Log.e(String, String)>
// 18 39:pop
}
// 19 40:return
}
public void unregisterCallback(MediaControllerCompat.Callback callback)
{
if(callback == null)
//* 0 0:aload_1
//* 1 1:ifnonnull 14
throw new IllegalArgumentException("callback may not be null.");
// 2 4:new #101 <Class IllegalArgumentException>
// 3 7:dup
// 4 8:ldc1 #217 <String "callback may not be null.">
// 5 10:invokespecial #104 <Method void IllegalArgumentException(String)>
// 6 13:athrow
try
{
mBinder.unregisterCallbackListener((IMediaControllerCallback)MediaControllerCompat.Callback.access$200(callback));
// 7 14:aload_0
// 8 15:getfield #38 <Field IMediaSession mBinder>
// 9 18:aload_1
// 10 19:invokestatic #231 <Method Object MediaControllerCompat$Callback.access$200(MediaControllerCompat$Callback)>
// 11 22:checkcast #233 <Class IMediaControllerCallback>
// 12 25:invokeinterface #282 <Method void IMediaSession.unregisterCallbackListener(IMediaControllerCallback)>
mBinder.asBinder().unlinkToDeath(((android.os.IBinder.DeathRecipient) (callback)), 0);
// 13 30:aload_0
// 14 31:getfield #38 <Field IMediaSession mBinder>
// 15 34:invokeinterface #221 <Method IBinder IMediaSession.asBinder()>
// 16 39:aload_1
// 17 40:iconst_0
// 18 41:invokeinterface #286 <Method boolean IBinder.unlinkToDeath(android.os.IBinder$DeathRecipient, int)>
// 19 46:pop
callback.mRegistered = false;
// 20 47:aload_1
// 21 48:iconst_0
// 22 49:putfield #244 <Field boolean MediaControllerCompat$Callback.mRegistered>
return;
// 23 52:return
}
// Misplaced declaration of an exception variable
catch(MediaControllerCompat.Callback callback)
//* 24 53:astore_1
{
Log.e("MediaControllerCompat", (new StringBuilder()).append("Dead object in unregisterCallback. ").append(((Object) (callback))).toString());
// 25 54:ldc1 #62 <String "MediaControllerCompat">
// 26 56:new #64 <Class StringBuilder>
// 27 59:dup
// 28 60:invokespecial #65 <Method void StringBuilder()>
// 29 63:ldc2 #288 <String "Dead object in unregisterCallback. ">
// 30 66:invokevirtual #71 <Method StringBuilder StringBuilder.append(String)>
// 31 69:aload_1
// 32 70:invokevirtual #74 <Method StringBuilder StringBuilder.append(Object)>
// 33 73:invokevirtual #78 <Method String StringBuilder.toString()>
// 34 76:invokestatic #84 <Method int Log.e(String, String)>
// 35 79:pop
}
// 36 80:return
}
private IMediaSession mBinder;
private MediaSessionCompat.Token mToken;
private MediaControllerCompat.TransportControls mTransportControls;
public MediaControllerCompat$MediaControllerImplBase(MediaSessionCompat.Token token)
{
// 0 0:aload_0
// 1 1:invokespecial #20 <Method void Object()>
mToken = token;
// 2 4:aload_0
// 3 5:aload_1
// 4 6:putfield #22 <Field MediaSessionCompat$Token mToken>
mBinder = IMediaSession.Stub.asInterface((IBinder)token.getToken());
// 5 9:aload_0
// 6 10:aload_1
// 7 11:invokevirtual #28 <Method Object MediaSessionCompat$Token.getToken()>
// 8 14:checkcast #30 <Class IBinder>
// 9 17:invokestatic #36 <Method IMediaSession IMediaSession$Stub.asInterface(IBinder)>
// 10 20:putfield #38 <Field IMediaSession mBinder>
// 11 23:return
}
}
|
9246184333198e58e8ca2dd40f30a458047ac60f
| 121 |
java
|
Java
|
raw_dataset/67254107@[email protected]
|
zthang/code2vec_treelstm
|
0c5f98d280b506317738ba603b719cac6036896f
|
[
"MIT"
] | 1 |
2020-04-24T03:35:40.000Z
|
2020-04-24T03:35:40.000Z
|
raw_dataset/67131481@[email protected]
|
ruanyuan115/code2vec_treelstm
|
0c5f98d280b506317738ba603b719cac6036896f
|
[
"MIT"
] | 2 |
2020-04-23T21:14:28.000Z
|
2021-01-21T01:07:18.000Z
|
raw_dataset/71520099@[email protected]
|
zthang/code2vec_treelstm
|
0c5f98d280b506317738ba603b719cac6036896f
|
[
"MIT"
] | null | null | null | 15.125 | 27 | 0.355372 | 1,003,643 |
private int common(int v) {
int c = 0;
while (v != 1) {
v = (v >>> 1);
++c;
}
return c;
}
|
9246194034024de3dd3d5979398849160a6ae5d9
| 1,068 |
java
|
Java
|
src/main/java/net/foulest/kitpvp/cmds/CombatLogCmd.java
|
Foulest/kitpvp
|
fbf3ab9b2a081653ed1cce996cc6ff72f10fc10a
|
[
"MIT"
] | null | null | null |
src/main/java/net/foulest/kitpvp/cmds/CombatLogCmd.java
|
Foulest/kitpvp
|
fbf3ab9b2a081653ed1cce996cc6ff72f10fc10a
|
[
"MIT"
] | null | null | null |
src/main/java/net/foulest/kitpvp/cmds/CombatLogCmd.java
|
Foulest/kitpvp
|
fbf3ab9b2a081653ed1cce996cc6ff72f10fc10a
|
[
"MIT"
] | null | null | null | 32.363636 | 109 | 0.653558 | 1,003,644 |
package net.foulest.kitpvp.cmds;
import net.foulest.kitpvp.listeners.CombatLog;
import net.foulest.kitpvp.util.MessageUtil;
import net.foulest.kitpvp.util.command.Command;
import net.foulest.kitpvp.util.command.CommandArgs;
import org.bukkit.entity.Player;
/**
* @author Foulest
* @project KitPvP
* <p>
* Command for displaying your current combat tag timer.
*/
public class CombatLogCmd {
@Command(name = "combatlog", aliases = {"combattag", "ct", "combat", "combattime"},
description = "Displays your current combat tag timer.", usage = "/combatlog", inGameOnly = true)
public void onCommand(CommandArgs args) {
Player player = args.getPlayer();
if (CombatLog.isInCombat(player)) {
int timeLeft = CombatLog.getRemainingTime(player);
MessageUtil.messagePlayer(player, "&cYou are in combat for " + timeLeft + " more "
+ (timeLeft == 1 ? "second" : "seconds") + ".");
} else {
MessageUtil.messagePlayer(player, "&aYou are not in combat.");
}
}
}
|
924619b0bca3f17672b2a0801bba4026e0560430
| 2,359 |
java
|
Java
|
src/main/java/www/swing/hack029/ShortcutFileView.java
|
anondroid5/SwingHack
|
c8f693a2f18e54ec49b4127a3df593264d695fd2
|
[
"Apache-2.0"
] | 1 |
2015-08-07T13:34:55.000Z
|
2015-08-07T13:34:55.000Z
|
src/main/java/www/swing/hack029/ShortcutFileView.java
|
anondroid5/SwingHack
|
c8f693a2f18e54ec49b4127a3df593264d695fd2
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/www/swing/hack029/ShortcutFileView.java
|
anondroid5/SwingHack
|
c8f693a2f18e54ec49b4127a3df593264d695fd2
|
[
"Apache-2.0"
] | null | null | null | 32.763889 | 77 | 0.564646 | 1,003,645 |
package www.swing.hack029;
import java.io.File;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.UIManager;
import javax.swing.filechooser.FileView;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.FileChooserUI;
public class ShortcutFileView extends FileView {
public boolean isDirLink(File f) {
try {
if(f.getName().toLowerCase().endsWith(".lnk")) {
LnkParser parser = new LnkParser(f);
if(parser.isDirectory()) {
return true;
}
}
} catch (Exception ex) {
System.out.println("exception: " + ex.getMessage());
ex.printStackTrace();
}
return false;
}
public Boolean isTraversable(File f) {
if(isDirLink(f)) {
return new Boolean(true);
}
return null;
}
public Icon getIcon(File f) {
if(isDirLink(f)) {
/* all of this nonsense is to get to the
default file view */
System.out.println("get icon for: " + f);
JFileChooser chooser = new JFileChooser();
ComponentUI ui = UIManager.getUI(chooser);
System.out.println("got : " + ui);
FileChooserUI fcui = (FileChooserUI)ui;
fcui.installUI(chooser);
FileView def = fcui.getFileView(chooser);
// get the standard icon for a folder
File tmp = new File("C:\\windows");
Icon folder = def.getIcon(tmp);
int w = folder.getIconWidth();
int h = folder.getIconHeight();
// create a buffered image the same size as the icon
Image img = new BufferedImage(w,h,BufferedImage.TYPE_4BYTE_ABGR);
Graphics g = img.getGraphics();
// draw the normal icon
folder.paintIcon(chooser,g,0,0);
// draw the shortcut image on top of the icon
Image shortcut = new ImageIcon("images/shortcut.png").getImage();
g.drawImage(shortcut,0,0,null);
g.dispose();
return new ImageIcon(img);
}
return super.getIcon(f);
}
}
|
92461b215f3de77b3b9dbd00cb48aa0cbe7ceaca
| 2,078 |
java
|
Java
|
src/main/java/me/SuperRonanCraft/BetterRTP/player/PlayerInfo.java
|
jyhsu2000/BetterRTP
|
9c27e30c108f6c2f6c8e1df3c2ad72816e0c516f
|
[
"MIT"
] | 55 |
2017-10-08T02:35:58.000Z
|
2022-03-23T22:11:42.000Z
|
src/main/java/me/SuperRonanCraft/BetterRTP/player/PlayerInfo.java
|
jyhsu2000/BetterRTP
|
9c27e30c108f6c2f6c8e1df3c2ad72816e0c516f
|
[
"MIT"
] | 84 |
2017-10-08T03:31:25.000Z
|
2022-03-28T13:12:52.000Z
|
src/main/java/me/SuperRonanCraft/BetterRTP/player/PlayerInfo.java
|
jyhsu2000/BetterRTP
|
9c27e30c108f6c2f6c8e1df3c2ad72816e0c516f
|
[
"MIT"
] | 71 |
2017-10-08T02:40:11.000Z
|
2022-03-29T16:29:53.000Z
| 28.465753 | 86 | 0.666506 | 1,003,646 |
package me.SuperRonanCraft.BetterRTP.player;
import lombok.Getter;
import lombok.Setter;
import me.SuperRonanCraft.BetterRTP.references.invs.RTP_INV_SETTINGS;
import me.SuperRonanCraft.BetterRTP.references.rtpinfo.CooldownData;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
public class PlayerInfo {
private final HashMap<Player, Inventory> invs = new HashMap<>();
private final HashMap<Player, RTP_INV_SETTINGS> invType = new HashMap<>();
private final HashMap<Player, World> invWorld = new HashMap<>();
private final HashMap<Player, RTP_INV_SETTINGS> invNextInv = new HashMap<>();
private final HashMap<Player, CooldownData> cooldown = new HashMap<>();
private final HashMap<Player, Boolean> rtping = new HashMap<>();
private final HashMap<Player, List<Location>> previousLocations = new HashMap<>();
//private final HashMap<Player, RTP_TYPE> rtpType = new HashMap<>();
private void setInv(Player p, Inventory inv) {
invs.put(p, inv);
}
private void setInvType(Player p, RTP_INV_SETTINGS type) {
invType.put(p, type);
}
private void setInvWorld(Player p, World type) {
invWorld.put(p, type);
}
private void setNextInv(Player p, RTP_INV_SETTINGS type) {
invNextInv.put(p, type);
}
//--Logic--
private Boolean playerExists(Player p) {
return invs.containsKey(p);
}
private void unloadAll() {
invs.clear();
invType.clear();
invWorld.clear();
invNextInv.clear();
cooldown.clear();
rtping.clear();
previousLocations.clear();
}
private void unload(Player p) {
clearInvs(p);
cooldown.remove(p);
rtping.remove(p);
previousLocations.remove(p);
}
public void clearInvs(Player p) {
invs.remove(p);
invType.remove(p);
invWorld.remove(p);
invNextInv.remove(p);
}
}
|
92461c55edadd0727f9d30e5a6c48dcde8ad05c2
| 6,080 |
java
|
Java
|
expressows/com/sgitmanagement/expressoext/filter/BasicAuthentificationFilter.java
|
stessygallant/expresso
|
d703829a8d3365694f4b2fb207a936bf82d503b7
|
[
"MIT"
] | null | null | null |
expressows/com/sgitmanagement/expressoext/filter/BasicAuthentificationFilter.java
|
stessygallant/expresso
|
d703829a8d3365694f4b2fb207a936bf82d503b7
|
[
"MIT"
] | null | null | null |
expressows/com/sgitmanagement/expressoext/filter/BasicAuthentificationFilter.java
|
stessygallant/expresso
|
d703829a8d3365694f4b2fb207a936bf82d503b7
|
[
"MIT"
] | null | null | null | 34.157303 | 133 | 0.725164 | 1,003,647 |
package com.sgitmanagement.expressoext.filter;
import java.io.IOException;
import java.security.Principal;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sgitmanagement.expresso.base.PersistenceManager;
import com.sgitmanagement.expresso.dto.Query;
import com.sgitmanagement.expresso.util.Util;
import com.sgitmanagement.expressoext.security.User;
import com.sgitmanagement.expressoext.security.UserService;
public class BasicAuthentificationFilter implements Filter {
final private static Logger logger = LoggerFactory.getLogger(BasicAuthentificationFilter.class);
private static final String WWW_AUTHENTICATE_HEADER = "WWW-Authenticate";
private static final String AUTHORIZATION_HEADER = "Authorization";
private static final String BASIC_PREFIX = "Basic ";
private static final String LOGIN_TOKEN = "X-Login-Token";
@Override
public void init(FilterConfig config) throws ServletException {
logger.info("BasicAuthentificationFilter init");
}
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
// do not create a session if not
HttpSession session = request.getSession(false);
// if there is no valid session, authenticate the user again
if (session != null) {
// logger.debug("Session is active [" + session.getId() + "] for user [" +
// request.getUserPrincipal().getName()
// + "]");
chain.doFilter(request, response);
} else {
String authUser = null;
// get username and password from the Authorization header
String authHeader = request.getHeader(AUTHORIZATION_HEADER);
String loginToken = request.getHeader(LOGIN_TOKEN);
if (loginToken == null && (authHeader == null || !authHeader.startsWith(BASIC_PREFIX))) {
// this will prompt the basic auth dialog on the browser
// setBasicAuthRequired(response);
setBasicAuthFailed(response);
} else {
try {
String userPassBase64;
if (loginToken != null) {
userPassBase64 = loginToken;
} else {
userPassBase64 = authHeader.substring(BASIC_PREFIX.length());
}
String userPassDecoded = new String(Base64.decodeBase64(userPassBase64));
// Finally userPassDecoded must contain readable "username:password"
if (!userPassDecoded.contains(":")) {
setBasicAuthRequired(response);
} else {
authUser = userPassDecoded.substring(0, userPassDecoded.indexOf(':'));
String authPass = userPassDecoded.substring(userPassDecoded.indexOf(':') + 1);
PersistenceManager persistenceManager = PersistenceManager.getInstance();
EntityManager em = persistenceManager.getEntityManager(false);
try {
UserService userService = UserService.newServiceStatic(UserService.class, User.class);
User user = userService.get(new Query.Filter("userName", authUser));
// verify password
String hashedPassword = Util.hashPassword(authPass);
if (user.getPassword() != null && user.getPassword().equals(hashedPassword)) {
logger.info("Authenticated [" + authUser + "] from IP [" + Util.getIpAddress(request) + "]");
// we must create a session (to store the authorization)
session = request.getSession(true);
} else {
logger.warn("Authentication failed for [" + authUser + "] from IP [" + Util.getIpAddress(request) + "]");
// if there is no local password, there is no risk
if (user.isLocalAccount() && user.getPassword() != null && !user.isGenericAccount()) {
// logger.info("Found the user [" + authUser + "]:" + user.getNbrFailedAttempts());
persistenceManager.startTransaction(em);
user.setNbrFailedAttempts(user.getNbrFailedAttempts() + 1);
}
setBasicAuthFailed(response);
}
} catch (NoResultException ex1) {
// not a valid username
setBasicAuthFailed(response);
} finally {
// close the connection
persistenceManager.commitAndClose(em);
}
}
} catch (Exception e) {
setBasicAuthFailed(response);
}
if (session != null) {
chain.doFilter(new ExpressoHttpServletRequestWrapper(authUser, request), response);
}
}
}
}
/**
* This method will trigger a challenge to the browser. By default, the browser will display a dialog to enter username and password
*
* @param response
*/
private void setBasicAuthRequired(HttpServletResponse response) {
response.setHeader(WWW_AUTHENTICATE_HEADER, "Basic realm=\"Local\"");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
/**
* This method will send an authorization failed to the browser (no Basic Auth window displayed)
*
* @param response
*/
private void setBasicAuthFailed(HttpServletResponse response) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
/**
*
*
*/
public class ExpressoHttpServletRequestWrapper extends HttpServletRequestWrapper {
private String userName;
public ExpressoHttpServletRequestWrapper(String userName, HttpServletRequest request) {
super(request);
this.userName = userName;
}
@Override
public boolean isUserInRole(String role) {
return false;
}
@Override
public Principal getUserPrincipal() {
return new Principal() {
@Override
public String getName() {
return userName;
}
};
}
}
}
|
92461c9f69d8afbeaa641ab5c45ad45463ab8443
| 781 |
java
|
Java
|
src/main/java/com/example/thymeleaf/common/UserDetailsServiceImpl.java
|
Git-hxz/thymeleaf-role
|
27dc28b5c1e7448b7a392f81475fe3b9eb8046cc
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/example/thymeleaf/common/UserDetailsServiceImpl.java
|
Git-hxz/thymeleaf-role
|
27dc28b5c1e7448b7a392f81475fe3b9eb8046cc
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/example/thymeleaf/common/UserDetailsServiceImpl.java
|
Git-hxz/thymeleaf-role
|
27dc28b5c1e7448b7a392f81475fe3b9eb8046cc
|
[
"Apache-2.0"
] | null | null | null | 28.925926 | 100 | 0.805378 | 1,003,648 |
package com.example.thymeleaf.common;
import com.example.thymeleaf.model.User;
import com.example.thymeleaf.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
/**
* user details service implementation
*
* @author linux_china
*/
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserRepository userRepository;
public CurrentUserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findOne(Long.parseLong(username));
return new CurrentUserDetails(user);
}
}
|
92461cdddd0b70b81c58c43b2a52e15aa6a3b586
| 438 |
java
|
Java
|
Java/TRABALHO_JAVA/Capitulo_04/Ex05/Encontra.java
|
1ricardo66/Programming_Exercises
|
5b7895bb93399713c0f6c5b22ac4708332e0b385
|
[
"Apache-2.0"
] | null | null | null |
Java/TRABALHO_JAVA/Capitulo_04/Ex05/Encontra.java
|
1ricardo66/Programming_Exercises
|
5b7895bb93399713c0f6c5b22ac4708332e0b385
|
[
"Apache-2.0"
] | null | null | null |
Java/TRABALHO_JAVA/Capitulo_04/Ex05/Encontra.java
|
1ricardo66/Programming_Exercises
|
5b7895bb93399713c0f6c5b22ac4708332e0b385
|
[
"Apache-2.0"
] | null | null | null | 31.285714 | 123 | 0.625571 | 1,003,649 |
public class Encontra{
void retorna(String palavra, String frase){
String retorno[] = new String[60];
int contador=0;
retorno = frase.split(" ");
for (int i = 0 ; i < retorno.length; i++){
if (retorno[i].toUpperCase().equals(palavra.toUpperCase())){
contador++;
}
}
System.out.println("Frase fornecida: "+frase+"\nPalavra fornecida: "+palavra+"\nQuantidade de ocorrencias: "+contador);
}
}
|
92461d04feb442bf9e2a726a7d3bd573e4e666cc
| 1,516 |
java
|
Java
|
plugins/org.apache.karaf.eik.core/src/main/java/org/apache/karaf/eik/core/shell/KarafRemoteShellConnection.java
|
BlackBeltTechnology/karaf-eik
|
02880b5a30dbca4741b8ca20df66b5f00e1ada3d
|
[
"Apache-2.0"
] | 4 |
2015-04-30T11:50:34.000Z
|
2021-11-10T13:32:43.000Z
|
plugins/org.apache.karaf.eik.core/src/main/java/org/apache/karaf/eik/core/shell/KarafRemoteShellConnection.java
|
BlackBeltTechnology/karaf-eik
|
02880b5a30dbca4741b8ca20df66b5f00e1ada3d
|
[
"Apache-2.0"
] | 2 |
2016-03-11T01:09:23.000Z
|
2019-06-07T12:38:34.000Z
|
plugins/org.apache.karaf.eik.core/src/main/java/org/apache/karaf/eik/core/shell/KarafRemoteShellConnection.java
|
BlackBeltTechnology/karaf-eik
|
02880b5a30dbca4741b8ca20df66b5f00e1ada3d
|
[
"Apache-2.0"
] | 25 |
2015-03-04T14:10:55.000Z
|
2021-11-10T13:32:33.000Z
| 33.688889 | 80 | 0.721636 | 1,003,650 |
/*
* 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.karaf.eik.core.shell;
import java.io.IOException;
public interface KarafRemoteShellConnection {
/**
* Connects to the remote shell of a Karaf instance.
* This method will block until the connection has been established.
*/
public void connect() throws IOException;
/**
* Disconnects from the remote shell of a Karaf instance.
* This method will block until the connection has been severed
*/
public void disconnect() throws IOException;
/**
* Determines whether or not there is a connection to the Karaf remote shell
*
* @return true if a connection exists, false otherwise
*/
public boolean isConnected();
}
|
92461eae21ca8f2d5fc966998dabbcfd1af7df07
| 2,662 |
java
|
Java
|
eventmobi/src/test/java/com/hyperaware/conference/android/marshal/gson/TestSpeakersGsonSectionResponseParser.java
|
CodingDoug/white-label-event-app
|
2e0693c22730350309f8c9b3154957b838a7fb60
|
[
"Apache-2.0"
] | 28 |
2016-02-29T12:54:05.000Z
|
2021-03-25T12:21:13.000Z
|
eventmobi/src/test/java/com/hyperaware/conference/android/marshal/gson/TestSpeakersGsonSectionResponseParser.java
|
SpokoSachs/andevcon-event-app
|
833a7b64e45d880a1f4cd02ba90d2eac5a395e2f
|
[
"Apache-2.0"
] | null | null | null |
eventmobi/src/test/java/com/hyperaware/conference/android/marshal/gson/TestSpeakersGsonSectionResponseParser.java
|
SpokoSachs/andevcon-event-app
|
833a7b64e45d880a1f4cd02ba90d2eac5a395e2f
|
[
"Apache-2.0"
] | 8 |
2015-11-27T17:44:23.000Z
|
2020-01-19T23:27:45.000Z
| 36.465753 | 84 | 0.71713 | 1,003,651 |
/*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hyperaware.conference.android.marshal.gson;
import com.hyperaware.conference.eventmobi.model.EmSection;
import com.hyperaware.conference.eventmobi.model.EmSectionResponse;
import com.hyperaware.conference.eventmobi.model.EmSpeakerItem;
import com.hyperaware.conference.eventmobi.model.EmSpeakersSectionResponse;
import com.hyperaware.conference.eventmobi.parser.gson.GsonSectionResponseParser;
import org.junit.Test;
import java.io.InputStream;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class TestSpeakersGsonSectionResponseParser {
@Test
public void test() throws Exception {
GsonSectionResponseParser<EmSpeakerItem, EmSpeakersSectionResponse> parser =
new GsonSectionResponseParser<>(EmSpeakersSectionResponse.class);
InputStream is = getClass().getResourceAsStream("/section_speakers.json");
EmSectionResponse<EmSpeakerItem> response = parser.parse(is);
is.close();
assertNotNull(response);
assertEquals("success", response.getStatus());
EmSection<EmSpeakerItem> section = response.getSection();
assertNotNull(section);
assertEquals("122371", section.getId());
assertEquals("9849", section.getEventId());
assertEquals("Speakers", section.getName());
assertEquals("speakers", section.getType());
List<EmSpeakerItem> items = section.getItems();
assertNotNull(items);
assertEquals(2, items.size());
EmSpeakerItem item0 = items.get(0);
assertNotNull(item0);
assertEquals("2753081", item0.getId());
assertEquals("Me", item0.getName());
assertEquals("Google", item0.getCompanyName());
assertEquals("me50.jpg", item0.getImage50());
assertEquals("me100.jpg", item0.getImage100());
assertEquals("Something about me", item0.getAbout());
assertEquals(0, item0.getPosition());
// Lazy
assertNotNull(items.get(1));
}
}
|
92461ed571a90f88a8b8923945d061bbb7d111f3
| 370 |
java
|
Java
|
mhcdemo/src/main/java/com/mhc/design_pattern/singleon/Singleton2.java
|
DNCBA/demo
|
6d3bac77982a5dc75951641b101040b0fd52c330
|
[
"Apache-2.0"
] | 13 |
2018-11-13T09:36:01.000Z
|
2021-07-02T02:16:51.000Z
|
mhcdemo/src/main/java/com/mhc/design_pattern/singleon/Singleton2.java
|
DNCBA/demo
|
6d3bac77982a5dc75951641b101040b0fd52c330
|
[
"Apache-2.0"
] | 12 |
2020-03-04T22:18:47.000Z
|
2021-08-09T20:45:05.000Z
|
mhcdemo/src/main/java/com/mhc/design_pattern/singleon/Singleton2.java
|
DNCBA/demo
|
6d3bac77982a5dc75951641b101040b0fd52c330
|
[
"Apache-2.0"
] | 4 |
2018-11-20T07:04:49.000Z
|
2020-02-03T12:58:57.000Z
| 14 | 50 | 0.671958 | 1,003,652 |
package com.mhc.design_pattern.singleon;
/**
* @author :menghui.cao, [email protected]
* @date :2019.txt-11-25 13:40
* 饱汉模式
* 静态代码块模式
*/
public class Singleton2 {
private Singleton2() {
}
private static volatile Singleton2 instance;
static {
instance = new Singleton2();
}
public static Singleton2 getInstance() {
return instance;
}
}
|
92461ff523de614e0df69afdde5a13352d5970e8
| 1,509 |
java
|
Java
|
cdm/java/mil/tatrc/physiology/utilities/FileNameFilter.java
|
isuhao/engine1
|
4b928612290150c2a3e0455e38e52d13d90a7340
|
[
"Apache-2.0"
] | 2 |
2019-03-15T04:20:11.000Z
|
2019-05-02T18:39:45.000Z
|
cdm/java/mil/tatrc/physiology/utilities/FileNameFilter.java
|
sinmx/engine1
|
4b928612290150c2a3e0455e38e52d13d90a7340
|
[
"Apache-2.0"
] | null | null | null |
cdm/java/mil/tatrc/physiology/utilities/FileNameFilter.java
|
sinmx/engine1
|
4b928612290150c2a3e0455e38e52d13d90a7340
|
[
"Apache-2.0"
] | 1 |
2018-09-22T04:10:37.000Z
|
2018-09-22T04:10:37.000Z
| 22.191176 | 86 | 0.648111 | 1,003,653 |
/* Distributed under the Apache License, Version 2.0.
See accompanying NOTICE file for details.*/
package mil.tatrc.physiology.utilities;
import java.io.File;
import java.io.FilenameFilter;
import java.util.*;
/**
* Filters out names that do not equal given "filename" and are not files(directories)
* Filters out names that have .zip if ExcludeZip is true
* @author khaith
*
*/
public class FileNameFilter implements FilenameFilter
{
String filename;
Set<String> ignoredExtensions=new HashSet<String>();
public FileNameFilter(String filename)
{
this.filename = filename;
}
public FileNameFilter(String filename, String[] excludeExtensions)
{
int dot=-1;
this.filename = filename;
for(String ext : excludeExtensions)
{
dot=ext.indexOf(".");
if(dot==-1)
this.ignoredExtensions.add(ext);
else
this.ignoredExtensions.add(ext.substring(dot+1));
}
}
public boolean accept(File dir, String name)
{
int indexOfDelim;
String prefix,suffix;
indexOfDelim = name.lastIndexOf(".");
if(indexOfDelim>-1)
prefix=name.substring(0, indexOfDelim);
else
prefix=name;
if(!prefix.equals(this.filename))
return false;
if(!this.ignoredExtensions.isEmpty())
{
suffix=name.substring(indexOfDelim+1);
for(String ext : this.ignoredExtensions)
{
if(suffix.equals(ext))
{
return false;
}
}
}
return true;
}
}
|
924620685e2d25d74c854598f877de872996ba81
| 11,668 |
java
|
Java
|
src/main/java/classes/Main.java
|
mastermeli-juanifilardo/practico1
|
60e3c25f088f186c14d052f403bdad382e9bb02e
|
[
"MIT"
] | null | null | null |
src/main/java/classes/Main.java
|
mastermeli-juanifilardo/practico1
|
60e3c25f088f186c14d052f403bdad382e9bb02e
|
[
"MIT"
] | null | null | null |
src/main/java/classes/Main.java
|
mastermeli-juanifilardo/practico1
|
60e3c25f088f186c14d052f403bdad382e9bb02e
|
[
"MIT"
] | null | null | null | 41.671429 | 150 | 0.549966 | 1,003,654 |
package classes;
import com.google.gson.Gson;
import interfaces.*;
import services.*;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import static spark.Spark.*;
public class Main {
public static void main(String[] args) {
final IUsuarioService usuarioService = new UsuarioServiceMap();
final IProyectoService proyectoService = new ProyectoServiceMap();
final IIncidenteService incidenteService = new IncidenteServiceMap();
loadUsuarios(usuarioService);
loadIncidentes(incidenteService, usuarioService);
loadProyectos(proyectoService, usuarioService, incidenteService);
// USUARIO
post("/usuario", ((request, response) -> {
response.type("application/json");
Usuario usuario = new Gson().fromJson(request.body(), Usuario.class);
usuarioService.addUsuario(usuario);
return new Gson().toJson(new StandardResponse(ResponseStatus.SUCCESS));
}));
get("/usuario", (request, response) -> {
response.type("application/json");
return new Gson().toJson(new StandardResponse(
ResponseStatus.SUCCESS,
new Gson().toJsonTree(usuarioService.getUsuarios())
));
});
get("/usuario/:id", (request, response) -> {
response.type("application/json");
Integer id = Integer.parseInt(request.params(":id"));
return new Gson().toJson(new StandardResponse(
ResponseStatus.SUCCESS,
new Gson().toJsonTree(usuarioService.getUsuario(id))
));
});
put("/usuario", (request, response) -> {
response.type("application/json");
Usuario usuario = new Gson().fromJson(request.body(), Usuario.class);
Usuario usuarioEditado = usuarioService.editUsuario(usuario);
if (usuarioEditado != null) {
return new Gson().toJson(new StandardResponse(
ResponseStatus.SUCCESS,
new Gson().toJsonTree(usuarioEditado)
));
} else {
return new Gson().toJson(new StandardResponse(
ResponseStatus.ERROR,
"Error al editar el usuario."
));
}
});
delete("/usuario/:id", (request, response) -> {
response.type("application/json");
Integer id = Integer.parseInt(request.params(":id"));
if (has_proyectos(id, proyectoService) || has_incidentes(id, incidenteService)) {
return new Gson().toJson(new StandardResponse(
ResponseStatus.ERROR, "No pudo borrarse el usuario porque posee proyectos o incidentes asociados."
));
} else {
usuarioService.deleteUsuario(id);
return new Gson().toJson(new StandardResponse(
ResponseStatus.SUCCESS, "Usuario borrado."
));
}
});
options("usuario/:id", (request, response) -> {
Integer id = Integer.parseInt(request.params(":id"));
return new Gson().toJson(new StandardResponse(
ResponseStatus.SUCCESS,
(usuarioService.usuarioExists(id) ? "El usuario existe" : "El usuario no existe")
));
});
// PROYECTO
post("/proyecto", ((request, response) -> {
response.type("application/json");
Proyecto proyecto = new Gson().fromJson(request.body(), Proyecto.class);
proyectoService.addProyecto(proyecto);
return new Gson().toJson(new StandardResponse(ResponseStatus.SUCCESS));
}));
get("/proyecto", (request, response) -> {
response.type("application/json");
return new Gson().toJson(new StandardResponse(
ResponseStatus.SUCCESS,
new Gson().toJsonTree(proyectoService.getProyectos())
));
});
get("/proyecto/:id", (request, response) -> {
response.type("application/json");
Integer id = Integer.parseInt(request.params(":id"));
return new Gson().toJson(new StandardResponse(
ResponseStatus.SUCCESS,
new Gson().toJsonTree(proyectoService.getProyecto(id))
));
});
put("/proyecto", (request, response) -> {
response.type("application/json");
Proyecto proyecto = new Gson().fromJson(request.body(), Proyecto.class);
Proyecto proyectoEditado = proyectoService.editProyecto(proyecto);
if (proyectoEditado != null) {
return new Gson().toJson(new StandardResponse(
ResponseStatus.SUCCESS,
new Gson().toJsonTree(proyectoEditado)
));
} else {
return new Gson().toJson(new StandardResponse(
ResponseStatus.ERROR,
"Error al editar el proyecto."
));
}
});
delete("/proyecto/:id", (request, response) -> {
response.type("application/json");
Integer id = Integer.parseInt(request.params(":id"));
if (proyectoService.getProyecto(id).hasIncidentes()) {
return new Gson().toJson(new StandardResponse(
ResponseStatus.ERROR, "No pudo borrarse el proyecto porque posee incidentes asociados."
));
} else {
proyectoService.deleteProyecto(id);
return new Gson().toJson(new StandardResponse(
ResponseStatus.SUCCESS, "Proyecto borrado."
));
}
});
options("proyecto/:id", (request, response) -> {
Integer id = Integer.parseInt(request.params(":id"));
return new Gson().toJson(new StandardResponse(
ResponseStatus.SUCCESS,
(proyectoService.proyectoExists(id) ? "El proyecto existe" : "El proyecto no existe")
));
});
// INCIDENTE
/*
todos los incidentes asignados a un usuario, todos
incidentes creados por un usuario, todos los incidentes asociados a
un proyecto, todos los incidentes abiertos (que estarían pendientes)
y, finalmente, todos los incidentes resueltos (los que estarían
cerrados).
*/
post("/incidente", ((request, response) -> {
response.type("application/json");
Incidente incidente = new Gson().fromJson(request.body(), Incidente.class);
incidenteService.addIncidente(incidente);
return new Gson().toJson(new StandardResponse(ResponseStatus.SUCCESS));
}));
get("/incidente", (request, response) -> {
response.type("application/json");
if (request.queryParams("userId") != null) {
Integer userId = Integer.parseInt(request.queryParams("userId"));
return new Gson().toJson(new StandardResponse(
ResponseStatus.SUCCESS,
new Gson().toJsonTree(
incidenteService.getIncidentes()
.stream()
.filter(s -> s.getResponsable().getId() == userId)
.toArray()
)
));
} else if (request.queryParams("proyectoId") != null) {
Integer proyectoId = Integer.parseInt(request.queryParams("proyectoId"));
try {
return new Gson().toJson(new StandardResponse(
ResponseStatus.SUCCESS,
new Gson().toJsonTree(proyectoService.getProyecto(proyectoId).getIncidentes())
));
} catch (Exception e) {
return new Gson().toJson(new StandardResponse(
ResponseStatus.ERROR, "No existe el proyecto con id " + proyectoId
));
}
} else if (request.queryParams("estado") != null) {
String estado = request.queryParams("estado");
if (estado.equalsIgnoreCase(Estado.ASIGNADO.toString()) || estado.equalsIgnoreCase(Estado.RESUELTO.toString())) {
return new Gson().toJson(new StandardResponse(
ResponseStatus.SUCCESS,
new Gson().toJsonTree(
incidenteService.getIncidentes()
.stream()
.filter(s -> s.getEstado().toString().equalsIgnoreCase(estado))
.toArray()
)
));
} else {
return new Gson().toJson(new StandardResponse(
ResponseStatus.ERROR, "No existe el estado " + estado
));
}
} else {
return new Gson().toJson(new StandardResponse(
ResponseStatus.SUCCESS,
new Gson().toJsonTree(incidenteService.getIncidentes())
));
}
});
}
private static boolean has_incidentes(Integer idUsuario, IIncidenteService incidenteServiceMap) {
for (Incidente i : incidenteServiceMap.getIncidentes()){
if (i.getReportador().getId() == idUsuario || i.getResponsable().getId() == idUsuario) {
return true;
}
}
return false;
}
private static boolean has_proyectos(Integer idUsuario, IProyectoService iProyectoServiceMap) {
for (Proyecto p : iProyectoServiceMap.getProyectos()) {
if (p.getPropietario().getId() == idUsuario) {
return true;
}
}
return false;
}
private static void loadIncidentes(IIncidenteService incidenteServiceMap, IUsuarioService usuarioServiceMap) {
incidenteServiceMap.addIncidente(new Incidente(
1, Clasificacion.CRITICO, Estado.ASIGNADO, "Bug crítico",
usuarioServiceMap.getUsuario(3), usuarioServiceMap.getUsuario(1))
);
incidenteServiceMap.addIncidente(new Incidente(
2, Clasificacion.MENOR, Estado.RESUELTO, "Error cosmético",
usuarioServiceMap.getUsuario(3), usuarioServiceMap.getUsuario(2))
);
}
private static void loadProyectos(IProyectoService proyectoServiceMap, IUsuarioService usuarioServiceMap, IIncidenteService incidenteServiceMap) {
Proyecto p1 = new Proyecto(1, "Shipping", usuarioServiceMap.getUsuario(1));
p1.addIncidente(incidenteServiceMap.getIncidente(1));
proyectoServiceMap.addProyecto(p1);
Proyecto p2 = new Proyecto(2, "Core", usuarioServiceMap.getUsuario(2));
p2.addIncidente(incidenteServiceMap.getIncidente(2));
proyectoServiceMap.addProyecto(p2);
}
private static void loadUsuarios(IUsuarioService usuarioServiceMap) {
usuarioServiceMap.addUsuario(new Usuario(1, "Juan", "Filardo"));
usuarioServiceMap.addUsuario(new Usuario(2, "Federico", "Silva"));
usuarioServiceMap.addUsuario(new Usuario(3, "Matías", "Brond"));
}
}
|
924620e321a4330870358a0398ba1d0607f4db43
| 1,227 |
java
|
Java
|
core/src/escape/room/game/event/ERScreenInputHandler.java
|
gotchamana/EscapeRommGame
|
74986e63ebb6a45ace57eb630bacdad86b8d4e4c
|
[
"CC0-1.0"
] | 3 |
2019-05-31T02:12:05.000Z
|
2019-11-05T11:35:13.000Z
|
core/src/escape/room/game/event/ERScreenInputHandler.java
|
gotchamana/EscapeRommGame
|
74986e63ebb6a45ace57eb630bacdad86b8d4e4c
|
[
"CC0-1.0"
] | 1 |
2019-05-24T10:28:02.000Z
|
2019-05-24T10:28:02.000Z
|
core/src/escape/room/game/event/ERScreenInputHandler.java
|
gotchamana/EscapeRoomGame
|
74986e63ebb6a45ace57eb630bacdad86b8d4e4c
|
[
"CC0-1.0"
] | null | null | null | 27.266667 | 89 | 0.748166 | 1,003,655 |
package escape.room.game.event;
import com.badlogic.gdx.*;
import escape.room.game.gameobject.TouchableSprite;
import escape.room.game.screen.ERScreen;
public class ERScreenInputHandler extends InputAdapter {
private ERScreen screen;
public ERScreenInputHandler(ERScreen screen) {
this.screen = screen;
}
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
TouchableSprite[] touchableSprites = screen.getCurrentMap().getTouchableSprites();
for (TouchableSprite touchableSprite : touchableSprites) {
if (touchableSprite.getBoundingRectangle().contains(screenX, screenY)) {
if (touchableSprite.onTouchDown(new TouchEvent(screenX, screenY, pointer, button))) {
return true;
}
}
}
return false;
}
@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
TouchableSprite[] touchableSprites = screen.getCurrentMap().getTouchableSprites();
for (TouchableSprite touchableSprite : touchableSprites) {
if (touchableSprite.getBoundingRectangle().contains(screenX, screenY)) {
if (touchableSprite.onTouchUp(new TouchEvent(screenX, screenY, pointer, button))) {
return true;
}
}
}
return false;
}
}
|
924621d2f9a424b5c62afa49b8761c93207915cc
| 3,332 |
java
|
Java
|
core/src/main/java/org/apache/calcite/util/Compatible.java
|
sugarcrm-dmoore/calcite
|
812e3e98eae518cf85cd1b6b7f055fb96784a423
|
[
"Apache-2.0"
] | 2,984 |
2015-10-29T03:04:33.000Z
|
2022-03-31T09:56:30.000Z
|
core/src/main/java/org/apache/calcite/util/Compatible.java
|
sugarcrm-dmoore/calcite
|
812e3e98eae518cf85cd1b6b7f055fb96784a423
|
[
"Apache-2.0"
] | 1,374 |
2015-10-28T03:21:38.000Z
|
2022-03-30T06:23:43.000Z
|
core/src/main/java/org/apache/calcite/util/Compatible.java
|
sugarcrm-dmoore/calcite
|
812e3e98eae518cf85cd1b6b7f055fb96784a423
|
[
"Apache-2.0"
] | 1,736 |
2015-10-27T20:18:37.000Z
|
2022-03-31T06:37:04.000Z
| 39.666667 | 80 | 0.670468 | 1,003,656 |
/*
* 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.calcite.util;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import static java.util.Objects.requireNonNull;
/** Compatibility layer.
*
* <p>Allows to use advanced functionality if the latest JDK or Guava version
* is present.
*/
public interface Compatible {
Compatible INSTANCE = new Factory().create();
/** Same as {@code MethodHandles#privateLookupIn()}.
* (On JDK 8, only {@link MethodHandles#lookup()} is available. */
<T> MethodHandles.Lookup lookupPrivate(Class<T> clazz);
/** Creates the implementation of Compatible suitable for the
* current environment. */
class Factory {
Compatible create() {
return (Compatible) Proxy.newProxyInstance(
Compatible.class.getClassLoader(),
new Class<?>[] {Compatible.class}, (proxy, method, args) -> {
if (method.getName().equals("lookupPrivate")) {
// Use MethodHandles.privateLookupIn if it is available (JDK 9
// and above)
@SuppressWarnings("rawtypes")
final Class<?> clazz = (Class) requireNonNull(args[0], "args[0]");
try {
final Method privateLookupMethod =
MethodHandles.class.getMethod("privateLookupIn",
Class.class, MethodHandles.Lookup.class);
final MethodHandles.Lookup lookup = MethodHandles.lookup();
return privateLookupMethod.invoke(null, clazz, lookup);
} catch (NoSuchMethodException e) {
return privateLookupJdk8(clazz);
}
}
return null;
});
}
/** Emulates MethodHandles.privateLookupIn on JDK 8;
* in later JDK versions, throws. */
@SuppressWarnings("deprecation")
static <T> MethodHandles.Lookup privateLookupJdk8(Class<T> clazz) {
try {
final Constructor<MethodHandles.Lookup> constructor =
MethodHandles.Lookup.class.getDeclaredConstructor(Class.class,
int.class);
if (!constructor.isAccessible()) {
constructor.setAccessible(true);
}
return constructor.newInstance(clazz, MethodHandles.Lookup.PRIVATE);
} catch (InstantiationException | IllegalAccessException
| InvocationTargetException | NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
}
}
|
9246223681a0684deb0fd02a10ae35f0e08b4715
| 258 |
java
|
Java
|
mercadolivre/src/main/java/br/com/zupacademy/mercadolivre/dto/requests/impl/RetornoGatewayPagamento.java
|
lucas-gdsouza/orange-talents-07-template-ecommerce
|
321c0db79214b8e45ea71f395480c37a7473d22b
|
[
"Apache-2.0"
] | null | null | null |
mercadolivre/src/main/java/br/com/zupacademy/mercadolivre/dto/requests/impl/RetornoGatewayPagamento.java
|
lucas-gdsouza/orange-talents-07-template-ecommerce
|
321c0db79214b8e45ea71f395480c37a7473d22b
|
[
"Apache-2.0"
] | null | null | null |
mercadolivre/src/main/java/br/com/zupacademy/mercadolivre/dto/requests/impl/RetornoGatewayPagamento.java
|
lucas-gdsouza/orange-talents-07-template-ecommerce
|
321c0db79214b8e45ea71f395480c37a7473d22b
|
[
"Apache-2.0"
] | null | null | null | 28.666667 | 57 | 0.829457 | 1,003,657 |
package br.com.zupacademy.mercadolivre.dto.requests.impl;
import br.com.zupacademy.mercadolivre.domains.Compra;
import br.com.zupacademy.mercadolivre.domains.Transacao;
public interface RetornoGatewayPagamento {
Transacao toTransacao(Compra compra);
}
|
924622a3da1012aba1944e1af6ed4c8b4dc6833a
| 7,438 |
java
|
Java
|
Editor/src/main/java/fr/poulpogaz/isekai/editor/ui/theme/ThemePanel.java
|
PoulpoGaz/Isekai
|
86076c349f5b8090e4c75d5d2f89cabd7c07d8d0
|
[
"MIT"
] | null | null | null |
Editor/src/main/java/fr/poulpogaz/isekai/editor/ui/theme/ThemePanel.java
|
PoulpoGaz/Isekai
|
86076c349f5b8090e4c75d5d2f89cabd7c07d8d0
|
[
"MIT"
] | 12 |
2021-05-17T17:13:23.000Z
|
2022-02-06T19:47:56.000Z
|
Editor/src/main/java/fr/poulpogaz/isekai/editor/ui/theme/ThemePanel.java
|
PoulpoGaz/Isekai
|
86076c349f5b8090e4c75d5d2f89cabd7c07d8d0
|
[
"MIT"
] | null | null | null | 30.11336 | 137 | 0.624496 | 1,003,658 |
package fr.poulpogaz.isekai.editor.ui.theme;
import com.formdev.flatlaf.FlatClientProperties;
import com.formdev.flatlaf.ui.FlatBorder;
import fr.poulpogaz.isekai.editor.IsekaiEditor;
import fr.poulpogaz.isekai.editor.Prefs;
import fr.poulpogaz.isekai.editor.ui.Dialogs;
import fr.poulpogaz.isekai.editor.ui.Icons;
import fr.poulpogaz.isekai.editor.ui.WrapBorder;
import fr.poulpogaz.isekai.editor.ui.layout.HCOrientation;
import fr.poulpogaz.isekai.editor.ui.layout.HorizontalConstraint;
import fr.poulpogaz.isekai.editor.ui.layout.HorizontalLayout;
import fr.poulpogaz.isekai.editor.utils.Utils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class ThemePanel extends JPanel {
private static final Logger LOGGER = LogManager.getLogger(ThemePanel.class);
public static void showDialog() {
IsekaiEditor parent = IsekaiEditor.getInstance();
JDialog dialog = new JDialog(parent, "Themes", true);
dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
dialog.setContentPane(new ThemePanel());
dialog.pack();
dialog.setLocationRelativeTo(parent);
dialog.setVisible(true);
}
private final List<Theme> themesList;
private JPanel top;
private JComboBox<String> filter;
private JButton github;
private JList<Theme> themes;
private JScrollPane pane;
private boolean isAdjusting = false;
public ThemePanel() {
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
setLayout(new BorderLayout());
ThemeManager.loadThemes();
themesList = createThemesList();
initComponents();
}
protected List<Theme> createThemesList() {
Comparator<Theme> comparator = (a, b) -> a.name().compareToIgnoreCase(b.name());
ArrayList<Theme> toAdd = new ArrayList<>(ThemeManager.getCoreThemes());
toAdd.sort(comparator);
ArrayList<Theme> themes = new ArrayList<>(toAdd);
toAdd.clear();
toAdd.addAll(ThemeManager.getThemes());
toAdd.sort(comparator);
themes.addAll(toAdd);
return themes;
}
protected void initComponents() {
// center
themes = new JList<>(new DefaultListModel<>());
themes.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
themes.setCellRenderer(new CellRenderer());
addThemesToList();
selectTheme();
themes.addListSelectionListener(this::changeLaf);
pane = new JScrollPane();
pane.setViewportView(themes);
pane.setBorder(new WrapBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5), pane.getBorder()));
// top
github = new JButton(Icons.get("icons/github.svg"));
github.putClientProperty(FlatClientProperties.BUTTON_TYPE, FlatClientProperties.BUTTON_TYPE_TOOLBAR_BUTTON);
github.addActionListener(this::browse);
setGithubIconSelected();
filter = new JComboBox<>();
filter.addItem("All");
filter.addItem("Light");
filter.addItem("Dark");
filter.addActionListener((e) -> addThemesToList());
top = new JPanel();
top.setLayout(new HorizontalLayout());
HorizontalConstraint constraint = new HorizontalConstraint();
constraint.endComponent = true;
top.add(new JLabel("Themes:"), constraint);
constraint.endComponent = false;
constraint.orientation = HCOrientation.RIGHT;
top.add(filter, constraint);
top.add(github, constraint);
// add components to panel
add(top, BorderLayout.NORTH);
add(pane, BorderLayout.CENTER);
}
@Override
public void addNotify() {
super.addNotify();
themes.ensureIndexIsVisible(themes.getSelectedIndex());
}
protected void addThemesToList() {
isAdjusting = true;
Theme oldSelected = themes.getSelectedValue();
DefaultListModel<Theme> model = (DefaultListModel<Theme>) themes.getModel();
model.removeAllElements();
String filter = this.filter == null ? "All" : (String) this.filter.getSelectedItem();
if (filter == null) {
return;
}
if (filter.equals("Light")) {
for (Theme theme : themesList) {
if (!theme.dark()) {
model.addElement(theme);
}
}
} else if (filter.equals("Dark")) {
for (Theme theme : themesList) {
if (theme.dark()) {
model.addElement(theme);
}
}
} else {
model.addAll(themesList);
}
if (oldSelected != null) {
if (model.contains(oldSelected)) {
themes.setSelectedValue(oldSelected, true); // don't change theme
} else {
isAdjusting = false;
themes.setSelectedValue(model.get(0), true); // change theme
}
}
isAdjusting = false;
}
protected void changeLaf(ListSelectionEvent event) {
if (event.getValueIsAdjusting() || isAdjusting) {
return;
}
setGithubIconSelected();
EventQueue.invokeLater(() -> {
Theme theme = themes.getSelectedValue();
ThemeManager.setTheme(theme, true, this, true);
});
}
protected void selectTheme() {
String themeName = Prefs.getTheme();
if (themeName == null) {
return;
}
ListModel<Theme> model = themes.getModel();
for (int i = 0; i < model.getSize(); i++) {
Theme theme = model.getElementAt(i);
if (theme.name().equals(themeName)) {
boolean old = this.isAdjusting;
isAdjusting = true;
themes.setSelectedValue(theme, true);
isAdjusting = old;
break;
}
}
}
protected void setGithubIconSelected() {
Theme theme = themes.getSelectedValue();
github.setEnabled(theme.isIntellijTheme());
}
protected void browse(ActionEvent evt) {
IntelliJIDEATheme theme = (IntelliJIDEATheme) themes.getSelectedValue();
if (!Utils.browse(theme.sourceCodeUrl())) {
Dialogs.showError(this, "Failed to open your browser");
}
}
private static class CellRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
Theme theme = (Theme) value;
setText(theme.name());
String tooltip = "Name: %s\nDark: %s".formatted(theme.name(), theme.dark());
if (theme instanceof IntelliJIDEATheme iTheme) {
tooltip += "\nLicense: %s\nSource code: %s".formatted(iTheme.license(), iTheme.sourceCodeUrl());
}
setToolTipText(tooltip);
return this;
}
}
}
|
924622e7df10e189b69efded1db8f917673ef978
| 1,206 |
java
|
Java
|
src/main/java/sample/mybatis/controller/DishController.java
|
developer1981/DevTestNG
|
e8df8cd8ff8fe7cd8201c3eaa5d404326597ae4a
|
[
"MIT"
] | null | null | null |
src/main/java/sample/mybatis/controller/DishController.java
|
developer1981/DevTestNG
|
e8df8cd8ff8fe7cd8201c3eaa5d404326597ae4a
|
[
"MIT"
] | null | null | null |
src/main/java/sample/mybatis/controller/DishController.java
|
developer1981/DevTestNG
|
e8df8cd8ff8fe7cd8201c3eaa5d404326597ae4a
|
[
"MIT"
] | null | null | null | 28.046512 | 75 | 0.801824 | 1,003,659 |
package sample.mybatis.controller;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import sample.mybatis.common.Config;
import sample.mybatis.common.Response;
import sample.mybatis.domain.Dish;
import sample.mybatis.mapper.DishMapper;
@RestController
@RequestMapping("/api/dish")
public class DishController {
@Autowired
DishMapper dishMapper;
@RequestMapping(value="/queryDishByVendorId", method = RequestMethod.GET)
public Response queryDishByVendorId(@RequestParam("vid") String vid){
Response resp = new Response();
List<Dish> dishes = dishMapper.selectByVendorId(Integer.parseInt(vid));
resp.setMessage("OK!");
resp.setRespData(dishes);
resp.setStatusCode(Config.SUCCESS_CODE);
return resp;
}
}
|
924623bbcc404b2b549d7265dea20099a01e226f
| 6,041 |
java
|
Java
|
llap-server/src/java/org/apache/hadoop/hive/llap/security/LlapServerSecurityInfo.java
|
sho25/hive
|
7a6a045c2a487bd200aeaded38497c843ec6a83c
|
[
"Apache-2.0"
] | null | null | null |
llap-server/src/java/org/apache/hadoop/hive/llap/security/LlapServerSecurityInfo.java
|
sho25/hive
|
7a6a045c2a487bd200aeaded38497c843ec6a83c
|
[
"Apache-2.0"
] | 3 |
2020-05-15T22:28:40.000Z
|
2022-01-27T16:24:32.000Z
|
llap-server/src/java/org/apache/hadoop/hive/llap/security/LlapServerSecurityInfo.java
|
sho25/hive
|
7a6a045c2a487bd200aeaded38497c843ec6a83c
|
[
"Apache-2.0"
] | null | null | null | 14.016241 | 569 | 0.802185 | 1,003,660 |
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * 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. */
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|llap
operator|.
name|security
package|;
end_package
begin_import
import|import
name|java
operator|.
name|lang
operator|.
name|annotation
operator|.
name|Annotation
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|conf
operator|.
name|Configuration
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|conf
operator|.
name|HiveConf
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|llap
operator|.
name|protocol
operator|.
name|LlapManagementProtocolPB
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|llap
operator|.
name|protocol
operator|.
name|LlapProtocolBlockingPB
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|security
operator|.
name|KerberosInfo
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|security
operator|.
name|SecurityInfo
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|security
operator|.
name|token
operator|.
name|TokenIdentifier
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|security
operator|.
name|token
operator|.
name|TokenInfo
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|security
operator|.
name|token
operator|.
name|TokenSelector
import|;
end_import
begin_import
import|import
name|org
operator|.
name|slf4j
operator|.
name|Logger
import|;
end_import
begin_import
import|import
name|org
operator|.
name|slf4j
operator|.
name|LoggerFactory
import|;
end_import
begin_class
specifier|public
class|class
name|LlapServerSecurityInfo
extends|extends
name|SecurityInfo
block|{
specifier|private
specifier|static
specifier|final
name|Logger
name|LOG
init|=
name|LoggerFactory
operator|.
name|getLogger
argument_list|(
name|LlapServerSecurityInfo
operator|.
name|class
argument_list|)
decl_stmt|;
annotation|@
name|Override
specifier|public
name|KerberosInfo
name|getKerberosInfo
parameter_list|(
name|Class
argument_list|<
name|?
argument_list|>
name|protocol
parameter_list|,
name|Configuration
name|conf
parameter_list|)
block|{
if|if
condition|(
name|LOG
operator|.
name|isDebugEnabled
argument_list|()
condition|)
block|{
name|LOG
operator|.
name|debug
argument_list|(
literal|"Trying to get KerberosInfo for "
operator|+
name|protocol
argument_list|)
expr_stmt|;
block|}
if|if
condition|(
operator|!
name|LlapProtocolBlockingPB
operator|.
name|class
operator|.
name|isAssignableFrom
argument_list|(
name|protocol
argument_list|)
operator|&&
operator|!
name|LlapManagementProtocolPB
operator|.
name|class
operator|.
name|isAssignableFrom
argument_list|(
name|protocol
argument_list|)
condition|)
return|return
literal|null
return|;
return|return
operator|new
name|KerberosInfo
argument_list|()
block|{
annotation|@
name|Override
specifier|public
name|Class
argument_list|<
name|?
extends|extends
name|Annotation
argument_list|>
name|annotationType
parameter_list|()
block|{
return|return
literal|null
return|;
block|}
annotation|@
name|Override
specifier|public
name|String
name|serverPrincipal
parameter_list|()
block|{
return|return
name|HiveConf
operator|.
name|ConfVars
operator|.
name|LLAP_KERBEROS_PRINCIPAL
operator|.
name|varname
return|;
block|}
annotation|@
name|Override
specifier|public
name|String
name|clientPrincipal
parameter_list|()
block|{
return|return
literal|null
return|;
block|}
block|}
return|;
block|}
annotation|@
name|Override
specifier|public
name|TokenInfo
name|getTokenInfo
parameter_list|(
name|Class
argument_list|<
name|?
argument_list|>
name|protocol
parameter_list|,
name|Configuration
name|conf
parameter_list|)
block|{
if|if
condition|(
name|LOG
operator|.
name|isDebugEnabled
argument_list|()
condition|)
block|{
name|LOG
operator|.
name|debug
argument_list|(
literal|"Trying to get TokenInfo for "
operator|+
name|protocol
argument_list|)
expr_stmt|;
block|}
comment|// Tokens cannot be used for the management protocol (for now).
if|if
condition|(
operator|!
name|LlapProtocolBlockingPB
operator|.
name|class
operator|.
name|isAssignableFrom
argument_list|(
name|protocol
argument_list|)
condition|)
return|return
literal|null
return|;
return|return
operator|new
name|TokenInfo
argument_list|()
block|{
annotation|@
name|Override
specifier|public
name|Class
argument_list|<
name|?
extends|extends
name|Annotation
argument_list|>
name|annotationType
parameter_list|()
block|{
return|return
literal|null
return|;
block|}
annotation|@
name|Override
specifier|public
name|Class
argument_list|<
name|?
extends|extends
name|TokenSelector
argument_list|<
name|?
extends|extends
name|TokenIdentifier
argument_list|>
argument_list|>
name|value
parameter_list|()
block|{
return|return
name|LlapTokenSelector
operator|.
name|class
return|;
block|}
block|}
return|;
block|}
block|}
end_class
end_unit
|
924624055c26af08cf1ae6e3922c23c2c4e01c37
| 753 |
java
|
Java
|
src/main/java/com/requirementsphase/RequirementsPhaseApplication.java
|
Eklas-machettete/com.requirementsphase-main
|
9394eb50994f7b9193622e1851914301dcf7251b
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/requirementsphase/RequirementsPhaseApplication.java
|
Eklas-machettete/com.requirementsphase-main
|
9394eb50994f7b9193622e1851914301dcf7251b
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/requirementsphase/RequirementsPhaseApplication.java
|
Eklas-machettete/com.requirementsphase-main
|
9394eb50994f7b9193622e1851914301dcf7251b
|
[
"Apache-2.0"
] | null | null | null | 26.892857 | 79 | 0.833997 | 1,003,661 |
package com.requirementsphase;
import javax.annotation.PostConstruct;
import org.camunda.bpm.engine.ManagementService;
import org.camunda.bpm.spring.boot.starter.annotation.EnableProcessApplication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@EnableProcessApplication
public class RequirementsPhaseApplication {
@Autowired
private ManagementService managementService;
public static void main(String... args) {
SpringApplication.run(RequirementsPhaseApplication.class, args);
}
@PostConstruct
public void startProcess() {
managementService.toggleTelemetry(false);
}
}
|
92462467640bb557100428a210ef584e068ce3f8
| 37,450 |
java
|
Java
|
src/test/java8/net/finmath/montecarlo/interestrate/LIBORMarketModelValuationTest.java
|
xiayingfeng/finmath-lib
|
49b71c512775b786f54d33dc828c2e0d1e701883
|
[
"Apache-2.0"
] | 373 |
2015-01-01T11:27:51.000Z
|
2022-03-29T21:51:49.000Z
|
src/test/java8/net/finmath/montecarlo/interestrate/LIBORMarketModelValuationTest.java
|
xiayingfeng/finmath-lib
|
49b71c512775b786f54d33dc828c2e0d1e701883
|
[
"Apache-2.0"
] | 67 |
2015-01-21T08:52:23.000Z
|
2021-09-22T20:13:11.000Z
|
src/test/java8/net/finmath/montecarlo/interestrate/LIBORMarketModelValuationTest.java
|
xiayingfeng/finmath-lib
|
49b71c512775b786f54d33dc828c2e0d1e701883
|
[
"Apache-2.0"
] | 184 |
2015-01-05T17:30:18.000Z
|
2022-03-28T10:55:29.000Z
| 45.790954 | 295 | 0.763809 | 1,003,662 |
/*
* (c) Copyright Christian P. Fries, Germany. Contact: [email protected].
*
* Created on 10.02.2004
*/
package net.finmath.montecarlo.interestrate;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import net.finmath.exception.CalculationException;
import net.finmath.functions.AnalyticFormulas;
import net.finmath.marketdata.model.curves.DiscountCurve;
import net.finmath.marketdata.model.curves.DiscountCurveFromForwardCurve;
import net.finmath.marketdata.model.curves.ForwardCurve;
import net.finmath.marketdata.model.curves.ForwardCurveInterpolation;
import net.finmath.modelling.products.Swaption.ValueUnit;
import net.finmath.montecarlo.BrownianMotion;
import net.finmath.montecarlo.RandomVariableFactory;
import net.finmath.montecarlo.RandomVariableFromArrayFactory;
import net.finmath.montecarlo.automaticdifferentiation.backward.RandomVariableDifferentiableAADFactory;
import net.finmath.montecarlo.automaticdifferentiation.forward.RandomVariableDifferentiableADFactory;
import net.finmath.montecarlo.interestrate.models.LIBORMarketModelFromCovarianceModel;
import net.finmath.montecarlo.interestrate.models.covariance.AbstractLIBORCovarianceModelParametric;
import net.finmath.montecarlo.interestrate.models.covariance.LIBORCorrelationModelExponentialDecay;
import net.finmath.montecarlo.interestrate.models.covariance.LIBORCovarianceModelCalibrateable;
import net.finmath.montecarlo.interestrate.models.covariance.LIBORCovarianceModelExponentialForm5Param;
import net.finmath.montecarlo.interestrate.models.covariance.LIBORCovarianceModelFromVolatilityAndCorrelation;
import net.finmath.montecarlo.interestrate.models.covariance.LIBORVolatilityModel;
import net.finmath.montecarlo.interestrate.models.covariance.LIBORVolatilityModelFourParameterExponentialForm;
import net.finmath.montecarlo.interestrate.products.AbstractLIBORMonteCarloProduct;
import net.finmath.montecarlo.interestrate.products.Bond;
import net.finmath.montecarlo.interestrate.products.DigitalCaplet;
import net.finmath.montecarlo.interestrate.products.SimpleSwap;
import net.finmath.montecarlo.interestrate.products.Swaption;
import net.finmath.montecarlo.interestrate.products.SwaptionAnalyticApproximation;
import net.finmath.montecarlo.interestrate.products.SwaptionSimple;
import net.finmath.montecarlo.process.EulerSchemeFromProcessModel;
import net.finmath.stochastic.RandomVariable;
import net.finmath.time.TimeDiscretization;
import net.finmath.time.TimeDiscretizationFromArray;
/**
* This class tests the LIBOR market model and products.
*
* @author Christian Fries
*/
@RunWith(Parameterized.class)
public class LIBORMarketModelValuationTest {
@Parameters(name="{0}")
public static Collection<Object[]> generateData()
{
return Arrays.asList(new Object[][] {
{ new RandomVariableFromArrayFactory(true /* isUseDoublePrecisionFloatingPointImplementation */) },
{ new RandomVariableFromArrayFactory(false /* isUseDoublePrecisionFloatingPointImplementation */) },
{ new RandomVariableDifferentiableAADFactory() },
{ new RandomVariableDifferentiableADFactory() },
});
}
private final int numberOfPaths = 20000;
private final int numberOfFactors = 6;
private final LIBORModelMonteCarloSimulationModel liborMarketModel;
private static DecimalFormat formatterMaturity = new DecimalFormat("00.00", new DecimalFormatSymbols(Locale.ENGLISH));
private static DecimalFormat formatterValue = new DecimalFormat(" ##0.000%;-##0.000%", new DecimalFormatSymbols(Locale.ENGLISH));
private static DecimalFormat formatterMoneyness = new DecimalFormat(" 000.0%;-000.0%", new DecimalFormatSymbols(Locale.ENGLISH));
private static DecimalFormat formatterDeviation = new DecimalFormat(" 0.00000E00;-0.00000E00", new DecimalFormatSymbols(Locale.ENGLISH));
public LIBORMarketModelValuationTest(final RandomVariableFactory randomVariableFactory) throws CalculationException {
// Create a libor market model
liborMarketModel = createLIBORMarketModel(randomVariableFactory, numberOfPaths, numberOfFactors, 0.1 /* Correlation */);
}
public static LIBORModelMonteCarloSimulationModel createLIBORMarketModel(
final RandomVariableFactory randomVariableFactory, final int numberOfPaths, final int numberOfFactors, final double correlationDecayParam) throws CalculationException {
/*
* Create the forward rate tenor structure and the initial values
*/
final double liborPeriodLength = 0.5;
final double liborRateTimeHorzion = 20.0;
final TimeDiscretization liborPeriodDiscretization = new TimeDiscretizationFromArray(0.0, (int) (liborRateTimeHorzion / liborPeriodLength), liborPeriodLength);
// Create the forward curve (initial value of the LIBOR market model)
final ForwardCurve forwardCurveInterpolation = ForwardCurveInterpolation.createForwardCurveFromForwards(
"forwardCurve" /* name of the curve */,
new double[] {0.5 , 1.0 , 2.0 , 5.0 , 40.0} /* fixings of the forward */,
new double[] {0.05, 0.05, 0.05, 0.05, 0.05} /* forwards */,
liborPeriodLength /* tenor / period length */
);
/*
* Create a simulation time discretization
*/
final double lastTime = 20.0;
final double dt = 0.5;
final TimeDiscretization timeDiscretization = new TimeDiscretizationFromArray(0.0, (int) (lastTime / dt), dt);
/*
* Create a volatility structure v[i][j] = sigma_j(t_i)
*/
final double a = 0.2, b = 0.0, c = 0.25, d = 0.3;
final LIBORVolatilityModel volatilityModel = new LIBORVolatilityModelFourParameterExponentialForm(timeDiscretization, liborPeriodDiscretization, a, b, c, d, false);
/*
* Create a correlation model rho_{i,j} = exp(-a * abs(T_i-T_j))
*/
final LIBORCorrelationModelExponentialDecay correlationModel = new LIBORCorrelationModelExponentialDecay(
timeDiscretization, liborPeriodDiscretization, numberOfFactors,
correlationDecayParam);
/*
* Combine volatility model and correlation model to a covariance model
*/
final LIBORCovarianceModelCalibrateable covarianceModel = new LIBORCovarianceModelFromVolatilityAndCorrelation(
timeDiscretization, liborPeriodDiscretization, volatilityModel, correlationModel);
// BlendedLocalVolatlityModel (future extension)
// AbstractLIBORCovarianceModel covarianceModel2 = new BlendedLocalVolatlityModel(covarianceModel, 0.00, false);
// Set model properties
final Map<String, String> properties = new HashMap<>();
// Choose the simulation measure
properties.put("measure", LIBORMarketModelFromCovarianceModel.Measure.SPOT.name());
// Choose log normal model
properties.put("stateSpace", LIBORMarketModelFromCovarianceModel.StateSpace.LOGNORMAL.name());
// Empty array of calibration items - hence, model will use given covariance
final CalibrationProduct[] calibrationItems = new CalibrationProduct[0];
/*
* Create corresponding LIBOR Market Model
*/
final LIBORMarketModel liborMarketModel = LIBORMarketModelFromCovarianceModel.of(liborPeriodDiscretization, null /* analyticModel */, forwardCurveInterpolation, new DiscountCurveFromForwardCurve(forwardCurveInterpolation), randomVariableFactory, covarianceModel, calibrationItems, properties);
final BrownianMotion brownianMotion = new net.finmath.montecarlo.BrownianMotionFromMersenneRandomNumbers(timeDiscretization, numberOfFactors, numberOfPaths, 3141 /* seed */);
final EulerSchemeFromProcessModel process = new EulerSchemeFromProcessModel(liborMarketModel, brownianMotion, EulerSchemeFromProcessModel.Scheme.PREDICTOR_CORRECTOR);
return new LIBORMonteCarloSimulationFromLIBORModel(process);
}
@Test
public void testBond() throws CalculationException {
/*
* Value a bond
*/
final DiscountCurve discountCurve = liborMarketModel.getModel().getDiscountCurve();
System.out.println("Bond prices:\n");
System.out.println("Maturity Simulation Analytic Deviation");
double maxAbsDeviation = 0.0;
for (double maturity = 0.0; maturity <= 20.0; maturity += 0.125) {
System.out.print(formatterMaturity.format(maturity) + " ");
// Create a bond
final Bond bond = new Bond(maturity);
// Bond price with Monte Carlo
final double priceOfBond = bond.getValue(liborMarketModel);
System.out.print(formatterValue.format(priceOfBond) + " ");
// Bond price analytic
final double priceOfBondAnalytic = discountCurve.getDiscountFactor(maturity);
System.out.print(formatterValue.format(priceOfBondAnalytic) + " ");
// Relative deviation
final double deviation = (priceOfBond - priceOfBondAnalytic);
System.out.println(formatterDeviation.format(deviation));
maxAbsDeviation = Math.max(maxAbsDeviation, Math.abs(deviation));
}
System.out.println("Maximum abs deviation: " + formatterDeviation.format(maxAbsDeviation));
System.out.println("__________________________________________________________________________________________\n");
// jUnit assertion: condition under which we consider this test successful
Assert.assertTrue(maxAbsDeviation < 8E-03);
}
@Test
public void testFRA() throws CalculationException {
/*
* Value a fra
*/
System.out.println("Par-FRA prices:\n");
System.out.println("FRA \t\t Value");
double maxAbsDeviation = 0.0;
for (double startDate = 0.0; startDate <= 20.0-0.5; startDate += 0.125) {
final int numberOfPeriods = 1;
// Create a swap
final double[] fixingDates = new double[numberOfPeriods];
final double[] paymentDates = new double[numberOfPeriods];
final double[] swapTenor = new double[numberOfPeriods + 1];
final double swapPeriodLength = 0.5;
for (int periodStartIndex = 0; periodStartIndex < numberOfPeriods; periodStartIndex++) {
fixingDates[periodStartIndex] = startDate + periodStartIndex * swapPeriodLength;
paymentDates[periodStartIndex] = startDate + (periodStartIndex + 1) * swapPeriodLength;
swapTenor[periodStartIndex] = startDate + periodStartIndex * swapPeriodLength;
}
swapTenor[numberOfPeriods] = startDate + numberOfPeriods * swapPeriodLength;
System.out.print("(" + formatterMaturity.format(swapTenor[0]) + "," + formatterMaturity.format(swapTenor[numberOfPeriods]) + ")" + "\t");
// Par swap rate
final double swaprate = getParSwaprate(liborMarketModel, swapTenor);
// Set swap rates for each period
final double[] swaprates = new double[numberOfPeriods];
for (int periodStartIndex = 0; periodStartIndex < numberOfPeriods; periodStartIndex++) {
swaprates[periodStartIndex] = swaprate;
}
// Create a swap
final SimpleSwap swap = new SimpleSwap(fixingDates, paymentDates, swaprates);
// Value the swap
final double value = swap.getValue(liborMarketModel);
System.out.print(formatterValue.format(value) + "\n");
maxAbsDeviation = Math.max(maxAbsDeviation, Math.abs(value));
}
System.out.println("Maximum abs deviation: " + formatterDeviation.format(maxAbsDeviation));
System.out.println("__________________________________________________________________________________________\n");
/*
* jUnit assertion: condition under which we consider this test successful
* The swap should be at par (close to zero)
*/
Assert.assertTrue(maxAbsDeviation < 2E-3);
}
@Test
public void testSwap() throws CalculationException {
/*
* Value a swap
*/
System.out.println("Par-Swap prices:\n");
System.out.println("Swap \t\t\t Value");
double maxAbsDeviation = 0.0;
for (double startDate = 0.0; startDate < 15.0; startDate += 0.5) {
final int numberOfPeriods = 10;
// Create a swap
final double[] fixingDates = new double[numberOfPeriods];
final double[] paymentDates = new double[numberOfPeriods];
final double[] swapTenor = new double[numberOfPeriods + 1];
final double swapPeriodLength = 0.5;
for (int periodStartIndex = 0; periodStartIndex < numberOfPeriods; periodStartIndex++) {
fixingDates[periodStartIndex] = startDate + periodStartIndex * swapPeriodLength;
paymentDates[periodStartIndex] = startDate + (periodStartIndex + 1) * swapPeriodLength;
swapTenor[periodStartIndex] = startDate + periodStartIndex * swapPeriodLength;
}
swapTenor[numberOfPeriods] = startDate + numberOfPeriods * swapPeriodLength;
System.out.print("(" + formatterMaturity.format(swapTenor[0]) + "," + formatterMaturity.format(swapTenor[numberOfPeriods]) + "," + swapPeriodLength + ")" + "\t");
// Par swap rate
final double swaprate = getParSwaprate(liborMarketModel, swapTenor);
// Set swap rates for each period
final double[] swaprates = new double[numberOfPeriods];
for (int periodStartIndex = 0; periodStartIndex < numberOfPeriods; periodStartIndex++) {
swaprates[periodStartIndex] = swaprate;
}
// Create a swap
final SimpleSwap swap = new SimpleSwap(fixingDates, paymentDates, swaprates);
// Value the swap
final double value = swap.getValue(liborMarketModel);
System.out.print(formatterValue.format(value) + "\n");
maxAbsDeviation = Math.max(maxAbsDeviation, Math.abs(value));
}
System.out.println("Maximum abs deviation: " + formatterDeviation.format(maxAbsDeviation));
System.out.println("__________________________________________________________________________________________\n");
/*
* jUnit assertion: condition under which we consider this test successful
* The swap should be at par (close to zero)
*/
Assert.assertTrue(maxAbsDeviation < 2E-3);
}
@Test
public void testDigitalCaplet() throws CalculationException {
/*
* Value a digital caplet
*/
System.out.println("Digital caplet prices:\n");
System.out.println("Maturity Simulation Analytic Deviation");
double maxAbsDeviation = 0.0;
for (double optionMaturity = 1.0; optionMaturity <= 19.5; optionMaturity += 0.5) {
final double periodStart = optionMaturity;
final double periodEnd = optionMaturity+0.5;
final double strike = 0.02;
// Create a digital caplet
final DigitalCaplet digitalCaplet = new DigitalCaplet(optionMaturity, periodStart, periodEnd, strike);
// Value with Monte Carlo
final double valueSimulation = digitalCaplet.getValue(liborMarketModel);
System.out.print(formatterValue.format(valueSimulation) + " ");
// Value analytic
final double forward = getParSwaprate(liborMarketModel, new double[] { periodStart , periodEnd});
final double periodLength = periodEnd-periodStart;
final double discountFactor = getSwapAnnuity(liborMarketModel, new double[] { periodStart , periodEnd}) / periodLength;
final int optionMaturityIndex = liborMarketModel.getTimeIndex(optionMaturity);
final int liborIndex = liborMarketModel.getLiborPeriodIndex(periodStart);
final double volatility = Math.sqrt(((LIBORMarketModel)liborMarketModel.getModel()).getIntegratedLIBORCovariance(liborMarketModel.getTimeDiscretization())[optionMaturityIndex][liborIndex][liborIndex]/optionMaturity);
final double valueAnalytic = net.finmath.functions.AnalyticFormulas.blackModelDigitalCapletValue(forward, volatility, periodLength, discountFactor, optionMaturity, strike);
System.out.print(formatterValue.format(valueAnalytic) + " ");
// Absolute deviation
final double deviation = (valueSimulation - valueAnalytic);
System.out.println(formatterDeviation.format(deviation) + " ");
maxAbsDeviation = Math.max(maxAbsDeviation, Math.abs(deviation));
}
System.out.println("Maximum abs deviation: " + formatterDeviation.format(maxAbsDeviation));
System.out.println("__________________________________________________________________________________________\n");
/*
* jUnit assertion: condition under which we consider this test successful
*/
Assert.assertTrue(Math.abs(maxAbsDeviation) < 5E-2);
}
@Test
public void testSwaption() throws CalculationException {
/*
* Value a swaption
*/
System.out.println("Swaption prices:\n");
System.out.println("Maturity Simulation Analytic Deviation");
double maxAbsDeviation = 0.0;
for (double maturity = 1.0; maturity <= 17.5; maturity += 0.5) {
final double exerciseDate = maturity;
System.out.print(formatterMaturity.format(exerciseDate) + " ");
final int numberOfPeriods = 5;
// Create a swaption
final double[] fixingDates = new double[numberOfPeriods];
final double[] paymentDates = new double[numberOfPeriods];
final double[] swapTenor = new double[numberOfPeriods + 1];
final double swapPeriodLength = 0.5;
for (int periodStartIndex = 0; periodStartIndex < numberOfPeriods; periodStartIndex++) {
fixingDates[periodStartIndex] = exerciseDate + periodStartIndex * swapPeriodLength;
paymentDates[periodStartIndex] = exerciseDate + (periodStartIndex + 1) * swapPeriodLength;
swapTenor[periodStartIndex] = exerciseDate + periodStartIndex * swapPeriodLength;
}
swapTenor[numberOfPeriods] = exerciseDate + numberOfPeriods * swapPeriodLength;
// Swaptions swap rate
final double swaprate = getParSwaprate(liborMarketModel, swapTenor);
// Set swap rates for each period
final double[] swaprates = new double[numberOfPeriods];
for (int periodStartIndex = 0; periodStartIndex < numberOfPeriods; periodStartIndex++) {
swaprates[periodStartIndex] = swaprate;
}
// Value with Monte Carlo
final Swaption swaptionMonteCarlo = new Swaption(exerciseDate, fixingDates, paymentDates, swaprates);
final double valueSimulation = swaptionMonteCarlo.getValue(liborMarketModel);
System.out.print(formatterValue.format(valueSimulation) + " ");
// Value analytic
final SwaptionAnalyticApproximation swaptionAnalyitc = new SwaptionAnalyticApproximation(swaprate, swapTenor, SwaptionAnalyticApproximation.ValueUnit.VALUE);
final double valueAnalytic = swaptionAnalyitc.getValue(liborMarketModel);
System.out.print(formatterValue.format(valueAnalytic) + " ");
// Absolute deviation
final double deviation = (valueSimulation - valueAnalytic);
System.out.println(formatterDeviation.format(deviation) + " ");
maxAbsDeviation = Math.max(maxAbsDeviation, Math.abs(deviation));
}
System.out.println("Maximum abs deviation: " + formatterDeviation.format(maxAbsDeviation));
System.out.println("__________________________________________________________________________________________\n");
/*
* jUnit assertion: condition under which we consider this test successful
*/
Assert.assertTrue(Math.abs(maxAbsDeviation) < 8E-3);
}
@Test
public void testCaplet() throws CalculationException {
/*
* Value a caplet
*/
System.out.println("Caplet prices:\n");
System.out.println("Maturity Simulation Analytic Deviation");
double maxAbsDeviation = 0.0;
for (double maturity = 1.0; maturity <= 19.5; maturity += 0.5) {
final double exerciseDate = maturity;
System.out.print(formatterMaturity.format(exerciseDate) + " ");
final int numberOfPeriods = 1;
// Create a swaption
final double[] fixingDates = new double[numberOfPeriods];
final double[] paymentDates = new double[numberOfPeriods];
final double[] swapTenor = new double[numberOfPeriods + 1];
final double swapPeriodLength = 0.5;
for (int periodStartIndex = 0; periodStartIndex < numberOfPeriods; periodStartIndex++) {
fixingDates[periodStartIndex] = exerciseDate + periodStartIndex * swapPeriodLength;
paymentDates[periodStartIndex] = exerciseDate + (periodStartIndex + 1) * swapPeriodLength;
swapTenor[periodStartIndex] = exerciseDate + periodStartIndex * swapPeriodLength;
}
swapTenor[numberOfPeriods] = exerciseDate + numberOfPeriods * swapPeriodLength;
// Swaptions swap rate
final double swaprate = getParSwaprate(liborMarketModel, swapTenor);
// Set swap rates for each period
final double[] swaprates = new double[numberOfPeriods];
for (int periodStartIndex = 0; periodStartIndex < numberOfPeriods; periodStartIndex++) {
swaprates[periodStartIndex] = swaprate;
}
// Value with Monte Carlo
final Swaption swaptionMonteCarlo = new Swaption(exerciseDate, fixingDates, paymentDates, swaprates);
final double valueSimulation = swaptionMonteCarlo.getValue(liborMarketModel);
System.out.print(formatterValue.format(valueSimulation) + " ");
// Value analytic
final SwaptionAnalyticApproximation swaptionAnalytic = new SwaptionAnalyticApproximation(swaprate, swapTenor, SwaptionAnalyticApproximation.ValueUnit.VALUE);
final double valueAnalytic = swaptionAnalytic.getValue(liborMarketModel);
System.out.print(formatterValue.format(valueAnalytic) + " ");
// Absolute deviation
final double deviation = (valueSimulation - valueAnalytic);
System.out.println(formatterDeviation.format(deviation) + " ");
maxAbsDeviation = Math.max(maxAbsDeviation, Math.abs(deviation));
}
System.out.println("Maximum abs deviation: " + formatterDeviation.format(maxAbsDeviation));
System.out.println("__________________________________________________________________________________________\n");
/*
* jUnit assertion: condition under which we consider this test successful
*/
Assert.assertTrue(Math.abs(maxAbsDeviation) < 8E-3);
}
@Test
public void testCapletSmile() throws CalculationException {
/*
* Value a caplet
*/
System.out.println("Caplet prices:\n");
System.out.println(" Valuation Implied Bachelier Volatility ");
System.out.println("Moneyness Simulation Analytic Deviation Simulation Analytic Deviation");
final double maturity = 5.0;
final int numberOfPeriods = 1;
final double swapPeriodLength = 0.5;
double maxAbsDeviation = 0.0;
for (double moneyness = 0.5; moneyness < 2.0; moneyness += 0.1) {
final double exerciseDate = maturity;
// Create a caplet
final double[] fixingDates = new double[numberOfPeriods];
final double[] paymentDates = new double[numberOfPeriods];
final double[] swapTenor = new double[numberOfPeriods + 1];
for (int periodStartIndex = 0; periodStartIndex < numberOfPeriods; periodStartIndex++) {
fixingDates[periodStartIndex] = exerciseDate + periodStartIndex * swapPeriodLength;
paymentDates[periodStartIndex] = exerciseDate + (periodStartIndex + 1) * swapPeriodLength;
swapTenor[periodStartIndex] = exerciseDate + periodStartIndex * swapPeriodLength;
}
swapTenor[numberOfPeriods] = exerciseDate + numberOfPeriods * swapPeriodLength;
// Swaptions swap rate
final double swaprate = moneyness * getParSwaprate(liborMarketModel, swapTenor);
// Set swap rates for each period
final double[] swaprates = new double[numberOfPeriods];
for (int periodStartIndex = 0; periodStartIndex < numberOfPeriods; periodStartIndex++) {
swaprates[periodStartIndex] = swaprate;
}
final Swaption swaptionMonteCarlo = new Swaption(exerciseDate, fixingDates, paymentDates, swaprates);
System.out.print(formatterMoneyness.format(moneyness) + " ");
// Value with Monte Carlo
final double valueSimulation = swaptionMonteCarlo.getValue(liborMarketModel);
final double impliedVolSimulation = AnalyticFormulas.bachelierOptionImpliedVolatility(getParSwaprate(liborMarketModel, swapTenor), exerciseDate, swaprate, getSwapAnnuity(liborMarketModel, swapTenor), valueSimulation);
// Value analytic
final SwaptionAnalyticApproximation swaptionAnalytic = new SwaptionAnalyticApproximation(swaprate, swapTenor, SwaptionAnalyticApproximation.ValueUnit.VALUE);
final double valueAnalytic = swaptionAnalytic.getValue(liborMarketModel);
final double impliedVolAnalytic = AnalyticFormulas.bachelierOptionImpliedVolatility(getParSwaprate(liborMarketModel, swapTenor), exerciseDate, swaprate, getSwapAnnuity(liborMarketModel, swapTenor), valueAnalytic);
// Absolute deviation
final double deviationValue = (valueSimulation - valueAnalytic);
final double deviationVol = (impliedVolSimulation - impliedVolAnalytic);
System.out.print(formatterValue.format(valueSimulation) + " ");
System.out.print(formatterValue.format(valueAnalytic) + " ");
System.out.print(formatterDeviation.format(deviationValue) + " ");
System.out.print(formatterValue.format(impliedVolSimulation) + " ");
System.out.print(formatterValue.format(impliedVolAnalytic) + " ");
System.out.println(formatterDeviation.format(deviationVol) + " ");
maxAbsDeviation = Math.max(maxAbsDeviation, Math.abs(deviationVol));
}
System.out.println("Maximum abs deviation: " + formatterDeviation.format(maxAbsDeviation));
System.out.println("__________________________________________________________________________________________\n");
/*
* jUnit assertion: condition under which we consider this test successful
*/
Assert.assertTrue(Math.abs(maxAbsDeviation) < 5E-4);
}
@Test
public void testSwaptionSmile() throws CalculationException {
/*
* Value swaptions
*/
System.out.println("Swaption prices:\n");
System.out.println("Moneyness Simulation Analytic Deviation");
final double maturity = 5.0;
final int numberOfPeriods = 10;
final double swapPeriodLength = 0.5;
double maxAbsDeviation = 0.0;
for (double moneyness = 0.5; moneyness < 2.0; moneyness += 0.1) {
final double exerciseDate = maturity;
// Create a swaption
final double[] fixingDates = new double[numberOfPeriods];
final double[] paymentDates = new double[numberOfPeriods];
final double[] swapTenor = new double[numberOfPeriods + 1];
for (int periodStartIndex = 0; periodStartIndex < numberOfPeriods; periodStartIndex++) {
fixingDates[periodStartIndex] = exerciseDate + periodStartIndex * swapPeriodLength;
paymentDates[periodStartIndex] = exerciseDate + (periodStartIndex + 1) * swapPeriodLength;
swapTenor[periodStartIndex] = exerciseDate + periodStartIndex * swapPeriodLength;
}
swapTenor[numberOfPeriods] = exerciseDate + numberOfPeriods * swapPeriodLength;
// Swaptions swap rate
final double swaprate = moneyness * getParSwaprate(liborMarketModel, swapTenor);
// Set swap rates for each period
final double[] swaprates = new double[numberOfPeriods];
for (int periodStartIndex = 0; periodStartIndex < numberOfPeriods; periodStartIndex++) {
swaprates[periodStartIndex] = swaprate;
}
final Swaption swaptionMonteCarlo = new Swaption(exerciseDate, fixingDates, paymentDates, swaprates);
final SwaptionAnalyticApproximation swaptionAnalyitc = new SwaptionAnalyticApproximation(
swaprate, swapTenor,
SwaptionAnalyticApproximation.ValueUnit.VALUE);
System.out.print(formatterValue.format(moneyness) + " ");
// Value with Monte Carlo
final double valueSimulation = swaptionMonteCarlo.getValue(liborMarketModel);
final double impliedVolSimulation = AnalyticFormulas.blackScholesOptionImpliedVolatility(getParSwaprate(liborMarketModel, swapTenor), exerciseDate, swaprate, getSwapAnnuity(liborMarketModel, swapTenor), valueSimulation);
System.out.print(formatterValue.format(impliedVolSimulation) + " ");
// Value analytic
final double valueAnalytic = swaptionAnalyitc.getValue(liborMarketModel);
final double impliedVolAnalytic = AnalyticFormulas.blackScholesOptionImpliedVolatility(getParSwaprate(liborMarketModel, swapTenor), exerciseDate, swaprate, getSwapAnnuity(liborMarketModel, swapTenor), valueAnalytic);
System.out.print(formatterValue.format(impliedVolAnalytic) + " ");
// Absolute deviation
final double deviation = (impliedVolSimulation - impliedVolAnalytic);
System.out.println(formatterDeviation.format(deviation) + " ");
maxAbsDeviation = Math.max(maxAbsDeviation, Math.abs(deviation));
}
System.out.println("Maximum abs deviation: " + formatterDeviation.format(maxAbsDeviation));
System.out.println("__________________________________________________________________________________________\n");
/*
* jUnit assertion: condition under which we consider this test successful
*/
Assert.assertTrue(Math.abs(maxAbsDeviation) < 1E-1);
}
@Test
public void testLIBORInArrearsConvexity() throws CalculationException {
/*
* Value payment of a forward rate at a later toime
*/
System.out.println("Forward value:\n");
System.out.println("Maturity \tRate");
final double fixing = 5.0;
for(double payment = 5.0; payment < 20; payment += 0.5) {
final double periodStart = fixing;
final double periodEnd = fixing + 0.5;
final RandomVariable libor = liborMarketModel.getForwardRate(fixing, periodStart, periodEnd);
final RandomVariable numeraireAtPayment = liborMarketModel.getNumeraire(payment);
final RandomVariable numeraireAtEvaluation = liborMarketModel.getNumeraire(0);
final double value = libor.div(numeraireAtPayment).mult(numeraireAtEvaluation).getAverage();
final double zeroCouponBondCorrespondingToPaymentTime = numeraireAtEvaluation.div(numeraireAtPayment).getAverage();
final double rate = value / zeroCouponBondCorrespondingToPaymentTime;
final RandomVariable numeraireAtPeriodEnd = liborMarketModel.getNumeraire(periodEnd);
final double zeroCouponBondCorrespondingToPeriodEnd = numeraireAtEvaluation.div(numeraireAtPeriodEnd).getAverage();
final double forward = libor.div(numeraireAtPeriodEnd).mult(numeraireAtEvaluation).getAverage() / zeroCouponBondCorrespondingToPeriodEnd;
System.out.println(payment + " \t" + formatterValue.format(rate));
if(payment < periodEnd) {
Assert.assertTrue("LIBOR payment convexity adjustment: rate > forward", rate > forward);
}
if(payment > periodEnd) {
Assert.assertTrue("LIBOR payment convexity adjustment: rate < forward", rate < forward);
}
}
System.out.println("__________________________________________________________________________________________\n");
/*
* jUnit assertion: condition under which we consider this test successful
*/
}
@Test
public void testSwaptionCalibration() throws CalculationException {
/*
* Calibration test
*/
System.out.println("Calibration to Swaptions (on lognormal volatilities):");
/*
* Create a set of calibration products.
*/
final ArrayList<CalibrationProduct> calibrationProducts = new ArrayList<>();
for (int exerciseIndex = 4; exerciseIndex <= liborMarketModel.getNumberOfLibors() - 5; exerciseIndex+=4) {
final double exerciseDate = liborMarketModel.getLiborPeriod(exerciseIndex);
for (int numberOfPeriods = 1; numberOfPeriods < liborMarketModel.getNumberOfLibors() - exerciseIndex - 5; numberOfPeriods+=4) {
// Create a swaption
final double[] fixingDates = new double[numberOfPeriods];
final double[] paymentDates = new double[numberOfPeriods];
final double[] swapTenor = new double[numberOfPeriods + 1];
final double swapPeriodLength = 0.5;
for (int periodStartIndex = 0; periodStartIndex < numberOfPeriods; periodStartIndex++) {
fixingDates[periodStartIndex] = exerciseDate + periodStartIndex * swapPeriodLength;
paymentDates[periodStartIndex] = exerciseDate + (periodStartIndex + 1) * swapPeriodLength;
swapTenor[periodStartIndex] = exerciseDate + periodStartIndex * swapPeriodLength;
}
swapTenor[numberOfPeriods] = exerciseDate + numberOfPeriods * swapPeriodLength;
// Swaptions swap rate
final double swaprate = getParSwaprate(liborMarketModel,swapTenor);
// Set swap rates for each period
final double[] swaprates = new double[numberOfPeriods];
Arrays.fill(swaprates, swaprate);
// This is just some swaption volatility used for testing, true market data should go here.
final double targetValueVolatilty = 0.20 + 0.20 * Math.exp(-exerciseDate / 10.0) + 0.20 * Math.exp(-(exerciseDate+numberOfPeriods) / 10.0);
// Buid our calibration product
// XXX1: Change the calibration product here
final boolean isUseAnalyticCalibration = true;
if(isUseAnalyticCalibration) {
// Use an analytic approximation to the swaption - much faster
final SwaptionAnalyticApproximation swaptionAnalytic = new SwaptionAnalyticApproximation(swaprate, swapTenor, SwaptionAnalyticApproximation.ValueUnit.VOLATILITYLOGNORMAL);
calibrationProducts.add(new CalibrationProduct(swaptionAnalytic, targetValueVolatilty, 1.0));
}
else {
// You may also use full Monte-Carlo calibration - more accurate. Also possible for displaced diffusion.
final SwaptionSimple swaptionMonteCarlo = new SwaptionSimple(swaprate, swapTenor, ValueUnit.VOLATILITYLOGNORMAL);
calibrationProducts.add(new CalibrationProduct(swaptionMonteCarlo, targetValueVolatilty, 1.0));
// Alternative: Calibration to prices
//Swaption swaptionMonteCarlo = new Swaption(exerciseDate, fixingDates, paymentDates, swaprates);
//double targetValuePrice = AnalyticFormulas.blackModelSwaptionValue(swaprate, targetValueVolatilty, fixingDates[0], swaprate, getSwapAnnuity(liborMarketModel,swapTenor));
//calibrationItems.add(new CalibrationProduct(swaptionMonteCarlo, targetValuePrice, 1.0));
}
}
}
System.out.println();
/*
* Take discretization and forward curve from liborMarketModel
*/
final TimeDiscretization timeDiscretization = liborMarketModel.getTimeDiscretization();
final ForwardCurve forwardCurve = liborMarketModel.getModel().getForwardRateCurve();
/*
* Create a LIBOR Market Model
*/
// XXX2 Change covariance model here
final AbstractLIBORCovarianceModelParametric covarianceModelParametric = new LIBORCovarianceModelExponentialForm5Param(timeDiscretization, liborMarketModel.getLiborPeriodDiscretization(), liborMarketModel.getNumberOfFactors());
// Set model properties
final Map<String, Object> properties = new HashMap<>();
// Set calibration properties
final Map<String, Object> calibrationParameters = new HashMap<>();
calibrationParameters.put("accuracy", Double.valueOf(1E-6));
calibrationParameters.put("numberOfPaths", Integer.valueOf(20000));
properties.put("calibrationParameters", calibrationParameters);
final LIBORMarketModelFromCovarianceModel liborMarketModelCalibrated = new LIBORMarketModelFromCovarianceModel(
liborMarketModel.getLiborPeriodDiscretization(),
forwardCurve, null, covarianceModelParametric, calibrationProducts.toArray(new CalibrationProduct[0]), properties);
/*
* Test our calibration
*/
final EulerSchemeFromProcessModel process = new EulerSchemeFromProcessModel(
liborMarketModelCalibrated,
new net.finmath.montecarlo.BrownianMotionLazyInit(timeDiscretization,
numberOfFactors, numberOfPaths, 3141 /* seed */));
final double[] param = ((AbstractLIBORCovarianceModelParametric) liborMarketModelCalibrated.getCovarianceModel()).getParameterAsDouble();
for (final double p : param) {
System.out.println(p);
}
final net.finmath.montecarlo.interestrate.LIBORMonteCarloSimulationFromLIBORModel simulationCalibrated = new net.finmath.montecarlo.interestrate.LIBORMonteCarloSimulationFromLIBORModel(
liborMarketModelCalibrated, process);
double deviationSum = 0.0;
double deviationSquaredSum = 0.0;
for (int i = 0; i < calibrationProducts.size(); i++) {
final AbstractLIBORMonteCarloProduct calibrationProduct = calibrationProducts.get(i).getProduct();
final double valueModel = calibrationProduct.getValue(simulationCalibrated);
final double valueTarget = calibrationProducts.get(i).getTargetValue().getAverage();
deviationSum += (valueModel-valueTarget);
deviationSquaredSum += Math.pow(valueModel-valueTarget,2);
System.out.println("Model: " + formatterValue.format(valueModel) + "\t Target: " + formatterValue.format(valueTarget) + "\t Deviation: " + formatterDeviation.format(valueModel-valueTarget));
}
final double diviationRMS = Math.sqrt(deviationSquaredSum/calibrationProducts.size());
System.out.println("Mean Deviation...............:" + formatterValue.format(deviationSum/calibrationProducts.size()));
System.out.println("Root Mean Squared Deviation..:" + formatterValue.format(diviationRMS));
System.out.println("__________________________________________________________________________________________\n");
Assert.assertEquals("RMS Deviation", 0.0, diviationRMS, 0.025);
}
private static double getParSwaprate(final LIBORModelMonteCarloSimulationModel liborMarketModel, final double[] swapTenor) {
return net.finmath.marketdata.products.Swap.getForwardSwapRate(new TimeDiscretizationFromArray(swapTenor), new TimeDiscretizationFromArray(swapTenor), liborMarketModel.getModel().getForwardRateCurve(), liborMarketModel.getModel().getDiscountCurve());
}
private static double getSwapAnnuity(final LIBORModelMonteCarloSimulationModel liborMarketModel, final double[] swapTenor) {
return net.finmath.marketdata.products.SwapAnnuity.getSwapAnnuity(new TimeDiscretizationFromArray(swapTenor), liborMarketModel.getModel().getDiscountCurve());
}
}
|
9246246bd257fad3169356266270c1ca1a4b0c98
| 3,984 |
java
|
Java
|
subprojects/jtrim-property/src/test/java/org/jtrim2/property/ListVerifierTest.java
|
kelemen/JTrim
|
6a877a500241de66f465ac8a893d64d47e67e73b
|
[
"Apache-2.0"
] | 7 |
2016-09-25T03:36:44.000Z
|
2022-01-09T17:05:41.000Z
|
subprojects/jtrim-property/src/test/java/org/jtrim2/property/ListVerifierTest.java
|
kelemen/JTrim
|
6a877a500241de66f465ac8a893d64d47e67e73b
|
[
"Apache-2.0"
] | null | null | null |
subprojects/jtrim-property/src/test/java/org/jtrim2/property/ListVerifierTest.java
|
kelemen/JTrim
|
6a877a500241de66f465ac8a893d64d47e67e73b
|
[
"Apache-2.0"
] | 1 |
2019-01-12T06:14:22.000Z
|
2019-01-12T06:14:22.000Z
| 36.888889 | 96 | 0.670683 | 1,003,663 |
package org.jtrim2.property;
import java.util.Arrays;
import java.util.List;
import org.jtrim2.collections.ArraysEx;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.invocation.InvocationOnMock;
import static org.junit.Assert.*;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
public class ListVerifierTest {
private static final String VERIFIED_SUFFIX = ".VERIFIED";
@SuppressWarnings("unchecked")
private static <T> PropertyVerifier<T> mockVerifier() {
return mock(PropertyVerifier.class);
}
private static PropertyVerifier<String> stubbedVerifier() {
PropertyVerifier<String> verifier = mockVerifier();
stub(verifier.storeValue(any(String.class))).toAnswer((InvocationOnMock invocation) -> {
Object arg = invocation.getArguments()[0];
return arg + VERIFIED_SUFFIX;
});
return verifier;
}
private void testNotNullElements(int elementCount, boolean allowNull) {
PropertyVerifier<String> elementVerifier = stubbedVerifier();
ListVerifier<String> verifier = new ListVerifier<>(elementVerifier, allowNull);
String[] input = new String[elementCount];
String[] output = new String[elementCount];
for (int i = 0; i < elementCount; i++) {
input[i] = "ListVerifierTest-32746835" + "." + i;
output[i] = input[i] + VERIFIED_SUFFIX;
}
verifyZeroInteractions(elementVerifier);
List<String> verified = verifier.storeValue(ArraysEx.viewAsList(input));
ArgumentCaptor<String> argCaptor = ArgumentCaptor.forClass(String.class);
verify(elementVerifier, times(elementCount)).storeValue(argCaptor.capture());
assertEquals(Arrays.asList(input), argCaptor.getAllValues());
assertEquals(Arrays.asList(output), verified);
}
private void testNullElements(int elementCount, boolean allowNull) {
PropertyVerifier<String> elementVerifier = stubbedVerifier();
ListVerifier<String> verifier = new ListVerifier<>(elementVerifier, allowNull);
String[] input = new String[elementCount];
String[] output = new String[elementCount];
for (int i = 0; i < elementCount; i++) {
input[i] = null;
output[i] = input[i] + VERIFIED_SUFFIX;
}
verifyZeroInteractions(elementVerifier);
List<String> verified = verifier.storeValue(ArraysEx.viewAsList(input));
ArgumentCaptor<String> argCaptor = ArgumentCaptor.forClass(String.class);
verify(elementVerifier, times(elementCount)).storeValue(argCaptor.capture());
assertEquals(Arrays.asList(input), argCaptor.getAllValues());
assertEquals(Arrays.asList(output), verified);
}
@Test
public void testNotNullElements() {
for (boolean allowNull: Arrays.asList(false, true)) {
for (int elementCount = 0; elementCount < 5; elementCount++) {
testNotNullElements(elementCount, allowNull);
}
}
}
@Test
public void testNullElements() {
for (boolean allowNull: Arrays.asList(false, true)) {
for (int elementCount = 0; elementCount < 5; elementCount++) {
testNullElements(elementCount, allowNull);
}
}
}
@Test
public void testNullList() {
PropertyVerifier<String> elementVerifier = stubbedVerifier();
ListVerifier<String> verifier = new ListVerifier<>(elementVerifier, true);
List<String> verified = verifier.storeValue(null);
assertNull(verified);
verifyZeroInteractions(elementVerifier);
}
@Test(expected = NullPointerException.class)
public void testNullListNotAllowsNullList() {
PropertyVerifier<String> elementVerifier = stubbedVerifier();
ListVerifier<String> verifier = new ListVerifier<>(elementVerifier, false);
verifier.storeValue(null);
}
}
|
9246246e4f131c3536a46779abc186f436780ef1
| 268 |
java
|
Java
|
spi/src/main/java/io/machinecode/chainlink/spi/configuration/factory/JobLoaderFactory.java
|
machinecode-io/chainlink
|
31d5c367bd94ce83f3d0fa7a22b38c680651eb5a
|
[
"Apache-2.0"
] | null | null | null |
spi/src/main/java/io/machinecode/chainlink/spi/configuration/factory/JobLoaderFactory.java
|
machinecode-io/chainlink
|
31d5c367bd94ce83f3d0fa7a22b38c680651eb5a
|
[
"Apache-2.0"
] | null | null | null |
spi/src/main/java/io/machinecode/chainlink/spi/configuration/factory/JobLoaderFactory.java
|
machinecode-io/chainlink
|
31d5c367bd94ce83f3d0fa7a22b38c680651eb5a
|
[
"Apache-2.0"
] | null | null | null | 23 | 71 | 0.76087 | 1,003,664 |
package io.machinecode.chainlink.spi.configuration.factory;
import io.machinecode.chainlink.spi.loader.JobLoader;
/**
* @author <a href="mailto:[email protected]">Brent Douglas</a>
* @since 1.0
*/
public interface JobLoaderFactory extends Factory<JobLoader> {
}
|
924624f680998af335df4c2bcbf78d444ce131fb
| 977 |
java
|
Java
|
fp4g-java-gdx/src/fp4g/generator/gdx/functions/GetTexture.java
|
egyware/fp4g
|
60ebb5bde0c52ea60b62bcf3e87aa5e799d7f49b
|
[
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null |
fp4g-java-gdx/src/fp4g/generator/gdx/functions/GetTexture.java
|
egyware/fp4g
|
60ebb5bde0c52ea60b62bcf3e87aa5e799d7f49b
|
[
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null |
fp4g-java-gdx/src/fp4g/generator/gdx/functions/GetTexture.java
|
egyware/fp4g
|
60ebb5bde0c52ea60b62bcf3e87aa5e799d7f49b
|
[
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | 34.892857 | 179 | 0.799386 | 1,003,665 |
package fp4g.generator.gdx.functions;
import fp4g.core.Expresion;
import fp4g.data.Container;
import fp4g.data.ExprList;
import fp4g.data.IDefine;
import fp4g.data.expresion.DirectCode;
import fp4g.data.expresion.FunctionCall;
import fp4g.exceptions.CannotEvalException;
import fp4g.generator.gdx.GdxFunction;
import fp4g.generator.gdx.JavaGenerator;
import fp4g.generator.gdx.models.JavaMetaSourceModel;
public class GetTexture extends GdxFunction
{
public GetTexture()
{
super("getTexture");
}
@Override
public Expresion generate(JavaGenerator generator, JavaMetaSourceModel model, FunctionCall call, IDefine current, Container container, ExprList list) throws CannotEvalException {
String resourceName = generator.expresion(model,container,list.get(0));
model.addRequireSource("com.badlogic.gdx.graphics.Texture");
DirectCode expr = new DirectCode(String.format("(Texture)container.gameManager.assets.get(%s)",resourceName));
return expr;
}
}
|
924625b08591b2fba124bd3c7d308f2b16e2a995
| 3,037 |
java
|
Java
|
src/main/java/io/appium/java_client/ErrorCodesMobile.java
|
dr29bart/java-client
|
c7d01e749b891dad5958aa87580033d1ad3df65d
|
[
"Apache-2.0"
] | 1,007 |
2015-01-07T02:18:32.000Z
|
2022-03-22T16:57:21.000Z
|
src/main/java/io/appium/java_client/ErrorCodesMobile.java
|
dr29bart/java-client
|
c7d01e749b891dad5958aa87580033d1ad3df65d
|
[
"Apache-2.0"
] | 1,272 |
2015-01-05T19:48:52.000Z
|
2022-03-31T14:01:10.000Z
|
src/main/java/io/appium/java_client/ErrorCodesMobile.java
|
dr29bart/java-client
|
c7d01e749b891dad5958aa87580033d1ad3df65d
|
[
"Apache-2.0"
] | 834 |
2015-01-12T04:05:20.000Z
|
2022-03-27T01:39:47.000Z
| 34.511364 | 99 | 0.685545 | 1,003,666 |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.appium.java_client;
import com.google.common.collect.ImmutableMap;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.remote.ErrorCodes;
import java.util.Map;
/**
* Defines common error codes for the mobile JSON wire protocol.
*
* @author [email protected] (Jonah Stiennon)
*/
public class ErrorCodesMobile extends ErrorCodes {
public static final int NO_SUCH_CONTEXT = 35;
private static Map<Integer, String> statusToState =
ImmutableMap.<Integer, String>builder().put(NO_SUCH_CONTEXT, "No such context found")
.build();
/**
* Returns the exception type that corresponds to the given {@code statusCode}. All unrecognized
* status codes will be mapped to {@link WebDriverException WebDriverException.class}.
*
* @param statusCode The status code to convert.
* @return The exception type that corresponds to the provided status
*/
public Class<? extends WebDriverException> getExceptionType(int statusCode) {
switch (statusCode) {
case NO_SUCH_CONTEXT:
return NoSuchContextException.class;
default:
return super.getExceptionType(statusCode);
}
}
/**
* Returns the exception type that corresponds to the given {@code message}or {@code null} if
* there are no matching mobile exceptions.
*
* @param message message An error message returned by Appium server
* @return The exception type that corresponds to the provided error message or {@code null} if
* there are no matching mobile exceptions.
*/
public Class<? extends WebDriverException> getExceptionType(String message) {
for (Map.Entry<Integer, String> entry : statusToState.entrySet()) {
if (message.contains(entry.getValue())) {
return getExceptionType(entry.getKey());
}
}
return null;
}
/**
* Converts a thrown error into the corresponding status code.
*
* @param thrown The thrown error.
* @return The corresponding status code for the given thrown error.
*/
public int toStatusCode(Throwable thrown) {
if (thrown instanceof NoSuchContextException) {
return NO_SUCH_CONTEXT;
} else {
return super.toStatusCode(thrown);
}
}
}
|
924625f6432375cd3864fead73cebc271c71feb7
| 5,053 |
java
|
Java
|
oauth2/src/main/java/io/micronaut/security/oauth2/openid/endpoints/token/DefaultAuthorizationCodeGrantRequestGenerator.java
|
sascha-frinken/micronaut-oauth2
|
e8c1c729b389d062639bfbc3136391dd0863b16c
|
[
"Apache-2.0"
] | null | null | null |
oauth2/src/main/java/io/micronaut/security/oauth2/openid/endpoints/token/DefaultAuthorizationCodeGrantRequestGenerator.java
|
sascha-frinken/micronaut-oauth2
|
e8c1c729b389d062639bfbc3136391dd0863b16c
|
[
"Apache-2.0"
] | null | null | null |
oauth2/src/main/java/io/micronaut/security/oauth2/openid/endpoints/token/DefaultAuthorizationCodeGrantRequestGenerator.java
|
sascha-frinken/micronaut-oauth2
|
e8c1c729b389d062639bfbc3136391dd0863b16c
|
[
"Apache-2.0"
] | null | null | null | 45.936364 | 211 | 0.762715 | 1,003,667 |
/*
* Copyright 2017-2019 original authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.micronaut.security.oauth2.openid.endpoints.token;
import io.micronaut.context.annotation.Requires;
import io.micronaut.http.HttpHeaders;
import io.micronaut.http.HttpRequest;
import io.micronaut.http.MediaType;
import io.micronaut.http.MutableHttpRequest;
import io.micronaut.security.oauth2.configuration.OauthConfiguration;
import io.micronaut.security.oauth2.grants.AuthorizationCodeGrant;
import io.micronaut.security.oauth2.openid.configuration.OpenIdProviderMetadata;
import io.micronaut.security.oauth2.openid.endpoints.DefaultRedirectUrlProvider;
import javax.annotation.Nonnull;
import javax.inject.Singleton;
import java.util.Objects;
/**
* Default implementation of {@link AuthorizationCodeGrantRequestGenerator}.
*
* @since 1.0.0
* @author Sergio del Amo
*/
@Requires(beans = {OpenIdProviderMetadata.class, TokenEndpointConfiguration.class, OauthConfiguration.class})
@Requires(condition = TokenEndpointNotNullCondition.class)
@Requires(condition = TokenEndpointGrantTypeAuthorizationCodeCondition.class)
@Singleton
public class DefaultAuthorizationCodeGrantRequestGenerator implements AuthorizationCodeGrantRequestGenerator {
@Nonnull
private final OauthConfiguration oauthConfiguration;
@Nonnull
private final OpenIdProviderMetadata openIdProviderMetadata;
@Nonnull
private final TokenEndpointConfiguration tokenEndpointConfiguration;
@Nonnull
private final DefaultRedirectUrlProvider defaultRedirectUrlProvider;
/**
*
* @param oauthConfiguration OAuth 2.0 Configuration
* @param openIdProviderMetadata OpenID provider metadata.
* @param tokenEndpointConfiguration Token Endpoint configuration
* @param defaultRedirectUrlProvider The Default Redirect Url Provider.
*/
public DefaultAuthorizationCodeGrantRequestGenerator(@Nonnull OauthConfiguration oauthConfiguration,
@Nonnull OpenIdProviderMetadata openIdProviderMetadata,
@Nonnull TokenEndpointConfiguration tokenEndpointConfiguration,
@Nonnull DefaultRedirectUrlProvider defaultRedirectUrlProvider) {
this.oauthConfiguration = oauthConfiguration;
this.openIdProviderMetadata = openIdProviderMetadata;
this.tokenEndpointConfiguration = tokenEndpointConfiguration;
this.defaultRedirectUrlProvider = defaultRedirectUrlProvider;
}
@Nonnull
@Override
public HttpRequest generateRequest(@Nonnull String code) {
AuthorizationCodeGrant authorizationCodeGrant = isntantiateAuthorizationCodeGrant(code);
Object body = tokenEndpointConfiguration.getContentType().equals(MediaType.APPLICATION_FORM_URLENCODED_TYPE) ? authorizationCodeGrant.toMap() : authorizationCodeGrant;
MutableHttpRequest req = HttpRequest.POST(Objects.requireNonNull(openIdProviderMetadata.getTokenEndpoint()), body).header(HttpHeaders.CONTENT_TYPE, tokenEndpointConfiguration.getContentType().getName());
return secureRequest(req);
}
/**
*
* @param request Token endpoint Request
* @return a HTTP Request to the Token Endpoint with Authorization Code Grant payload.
*/
protected MutableHttpRequest secureRequest(@Nonnull MutableHttpRequest request) {
if (tokenEndpointConfiguration.getAuthMethod() != null && tokenEndpointConfiguration.getAuthMethod().equals(TokenEndpointAuthMethod.CLIENT_SECRET_BASIC.getAuthMethod())) {
return request.basicAuth(oauthConfiguration.getClientId(), oauthConfiguration.getClientSecret());
}
return request;
}
/**
* @param code The code received with the authentication response.
* @return A Authorization Code Grant
*/
protected AuthorizationCodeGrant isntantiateAuthorizationCodeGrant(@Nonnull String code) {
AuthorizationCodeGrant authorizationCodeGrant = new AuthorizationCodeGrant();
authorizationCodeGrant.setCode(code);
authorizationCodeGrant.setClientId(oauthConfiguration.getClientId());
authorizationCodeGrant.setClientSecret(oauthConfiguration.getClientSecret());
authorizationCodeGrant.setRedirectUri(tokenEndpointConfiguration.getRedirectUri() != null ? tokenEndpointConfiguration.getRedirectUri() : defaultRedirectUrlProvider.getRedirectUri());
return authorizationCodeGrant;
}
}
|
9246265ae64b5333d4420d7715341ce13ab1bd7b
| 3,538 |
java
|
Java
|
src/main/java/mekanism/client/gui/GuiChemicalTank.java
|
Ridanisaurus/Mekanism
|
9e2d28418e21dcfa19842820fc587b96618311d7
|
[
"MIT"
] | 534 |
2019-04-19T23:49:31.000Z
|
2022-03-29T12:37:06.000Z
|
src/main/java/mekanism/client/gui/GuiChemicalTank.java
|
Ridanisaurus/Mekanism
|
9e2d28418e21dcfa19842820fc587b96618311d7
|
[
"MIT"
] | 2,015 |
2019-04-19T05:59:28.000Z
|
2022-03-29T00:54:46.000Z
|
src/main/java/mekanism/client/gui/GuiChemicalTank.java
|
Ridanisaurus/Mekanism
|
9e2d28418e21dcfa19842820fc587b96618311d7
|
[
"MIT"
] | 309 |
2019-04-19T20:32:55.000Z
|
2022-03-31T02:16:26.000Z
| 50.542857 | 185 | 0.698417 | 1,003,668 |
package mekanism.client.gui;
import com.mojang.blaze3d.matrix.MatrixStack;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nonnull;
import mekanism.api.chemical.IChemicalTank;
import mekanism.api.chemical.merged.MergedChemicalTank.Current;
import mekanism.api.text.ILangEntry;
import mekanism.client.gui.element.GuiInnerScreen;
import mekanism.client.gui.element.bar.GuiMergedChemicalBar;
import mekanism.client.gui.element.button.GuiGasMode;
import mekanism.common.MekanismLang;
import mekanism.common.inventory.container.tile.MekanismTileContainer;
import mekanism.common.tier.ChemicalTankTier;
import mekanism.common.tile.TileEntityChemicalTank;
import mekanism.common.util.text.TextUtils;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.util.text.ITextComponent;
public class GuiChemicalTank extends GuiConfigurableTile<TileEntityChemicalTank, MekanismTileContainer<TileEntityChemicalTank>> {
public GuiChemicalTank(MekanismTileContainer<TileEntityChemicalTank> container, PlayerInventory inv, ITextComponent title) {
super(container, inv, title);
dynamicSlots = true;
}
@Override
protected void addGuiElements() {
super.addGuiElements();
addButton(new GuiMergedChemicalBar<>(this, tile, tile.getChemicalTank(), 42, 16, 116, 10, true));
addButton(new GuiInnerScreen(this, 42, 37, 118, 28, () -> {
List<ITextComponent> ret = new ArrayList<>();
Current current = tile.getChemicalTank().getCurrent();
if (current == Current.EMPTY) {
ret.add(MekanismLang.CHEMICAL.translate(MekanismLang.NONE));
ret.add(MekanismLang.GENERIC_FRACTION.translate(0, tile.getTier() == ChemicalTankTier.CREATIVE ? MekanismLang.INFINITE : TextUtils.format(tile.getTier().getStorage())));
} else if (current == Current.GAS) {
addStored(ret, tile.getChemicalTank().getGasTank(), MekanismLang.GAS);
} else if (current == Current.INFUSION) {
addStored(ret, tile.getChemicalTank().getInfusionTank(), MekanismLang.INFUSE_TYPE);
} else if (current == Current.PIGMENT) {
addStored(ret, tile.getChemicalTank().getPigmentTank(), MekanismLang.PIGMENT);
} else if (current == Current.SLURRY) {
addStored(ret, tile.getChemicalTank().getSlurryTank(), MekanismLang.SLURRY);
} else {
throw new IllegalStateException("Unknown current type");
}
return ret;
}));
addButton(new GuiGasMode(this, 159, 72, true, () -> tile.dumping, tile.getBlockPos(), 0));
}
private void addStored(List<ITextComponent> ret, IChemicalTank<?, ?> tank, ILangEntry langKey) {
ret.add(langKey.translate(tank.getStack()));
if (!tank.isEmpty() && tile.getTier() == ChemicalTankTier.CREATIVE) {
ret.add(MekanismLang.INFINITE.translate());
} else {
ret.add(MekanismLang.GENERIC_FRACTION.translate(TextUtils.format(tank.getStored()),
tile.getTier() == ChemicalTankTier.CREATIVE ? MekanismLang.INFINITE : TextUtils.format(tank.getCapacity())));
}
}
@Override
protected void drawForegroundText(@Nonnull MatrixStack matrix, int mouseX, int mouseY) {
renderTitleText(matrix);
drawString(matrix, inventory.getDisplayName(), inventoryLabelX, inventoryLabelY, titleTextColor());
super.drawForegroundText(matrix, mouseX, mouseY);
}
}
|
9246267aef36a01ba7e3bd63a396ba371dafeddf
| 4,894 |
java
|
Java
|
server/regtest/src/test/java/org/hyperledger/account/ColoredAccountOperationsInBlocksTest.java
|
esgott/hlp-candidate
|
6e529c1fac511595a9009bd793d148ade1c300a6
|
[
"Apache-2.0"
] | null | null | null |
server/regtest/src/test/java/org/hyperledger/account/ColoredAccountOperationsInBlocksTest.java
|
esgott/hlp-candidate
|
6e529c1fac511595a9009bd793d148ade1c300a6
|
[
"Apache-2.0"
] | null | null | null |
server/regtest/src/test/java/org/hyperledger/account/ColoredAccountOperationsInBlocksTest.java
|
esgott/hlp-candidate
|
6e529c1fac511595a9009bd793d148ade1c300a6
|
[
"Apache-2.0"
] | 1 |
2020-05-23T20:19:15.000Z
|
2020-05-23T20:19:15.000Z
| 42.929825 | 131 | 0.728647 | 1,003,669 |
/**
* 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.hyperledger.account;
import com.typesafe.config.ConfigFactory;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.hyperledger.account.color.ColorIssuer;
import org.hyperledger.account.color.ColoredAccount;
import org.hyperledger.account.color.ColoredBaseAccount;
import org.hyperledger.api.BCSAPI;
import org.hyperledger.common.PrivateKey;
import org.hyperledger.common.Transaction;
import org.hyperledger.common.color.Color;
import org.hyperledger.test.RegtestRule;
import org.hyperledger.test.TestServer;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import java.security.Security;
import static org.hyperledger.account.ActionWaiter.*;
import static org.junit.Assert.assertEquals;
public class ColoredAccountOperationsInBlocksTest {
@BeforeClass
public static void init() {
Security.addProvider(new BouncyCastleProvider());
}
@ClassRule
public static RegtestRule regtestRule = new RegtestRule(ConfigFactory.parseResources("test-config.json"));
@Test
public void test() throws Exception {
BCSAPI bcsapi = regtestRule.getBCSAPI();
TestServer testServer = regtestRule.getTestServer();
ConfirmationManager confirmationManager = new ConfirmationManager();
confirmationManager.init(bcsapi, 101);
PrivateKey issuerKey = PrivateKey.createNew();
PrivateKey receiverKey = PrivateKey.createNew();
BaseAccount issuerAccount = new BaseAccount(new KeyListChain(issuerKey));
ColoredAccount coloredAccount = new ColoredBaseAccount(new KeyListChain(receiverKey));
ColorIssuer colorIssuer = new ColorIssuer(issuerKey);
// listeners
bcsapi.registerTransactionListener(issuerAccount);
confirmationManager.addConfirmationListener(issuerAccount);
bcsapi.registerTransactionListener(coloredAccount);
confirmationManager.addConfirmationListener(coloredAccount);
bcsapi.registerTransactionListener(colorIssuer);
confirmationManager.addConfirmationListener(colorIssuer);
// fund issuer address
UIAddress issuerAddress = new UIAddress(UIAddress.Network.TEST, colorIssuer.getFundingAddress());
ActionWaiter.execute(() -> testServer.sendTo(issuerAddress.toString(), 1000000000), expected(colorIssuer, 2));
// check balance
long b = issuerAccount.getCoins().getTotalSatoshis(); // 1000000000
assertEquals(1000000000, b);
long b2 = issuerAccount.getConfirmedCoins().getTotalSatoshis(); // 1000000000
assertEquals(1000000000, b2);
Color color = colorIssuer.getColor();
// issue 100 units carried by 50000 satoshis
Transaction issuing = colorIssuer.issueTokens(
receiverKey.getAddress(),
100, 50000,
BaseTransactionFactory.MINIMUM_FEE);
ActionWaiter.execute(() -> bcsapi.sendTransaction(issuing), expectedOneOnEach(colorIssuer, coloredAccount, issuerAccount));
ActionWaiter.execute(() -> testServer.mineOneBlock(), expectedOne(coloredAccount));
// receiver account received transaction with colored coin
b = coloredAccount.getConfirmedCoins().getTotalSatoshis(); //50000
assertEquals(50000, b);
b2 = coloredAccount.getConfirmedCoins().getColoredCoins().getCoins().size(); // 1
assertEquals(1, b2);
long b3 = coloredAccount.getConfirmedCoins().getColoredCoins().getCoins(color).getTotalQuantity();
assertEquals(100, b3);
PrivateKey nextOwner = PrivateKey.createNew();
Transaction transfer = coloredAccount.createTransactionFactory()
.proposeColored(nextOwner.getAddress(),
color, 50)
.sign(coloredAccount.getChain());
ActionWaiter.execute(() -> bcsapi.sendTransaction(transfer), expectedOne(coloredAccount));
ColoredAccount nextOwnerAccount = new ColoredBaseAccount(new KeyListChain(nextOwner));
ActionWaiter.execute(() -> testServer.mineOneBlock(), expectedOne(coloredAccount));
ActionWaiter.execute(() -> nextOwnerAccount.sync(bcsapi), expectedOne(nextOwnerAccount));
assertEquals(50, nextOwnerAccount.getConfirmedCoins().getColoredCoins().getCoins(color).getTotalQuantity());
}
}
|
92462799e8e0e3ac13cf5c256212246eecfbabe2
| 620 |
java
|
Java
|
pousse-cafe-core/src/test/java/poussecafe/entity/SimpleEntity.java
|
pousse-cafe/pousse-cafe
|
9dfc2d0b7c2e9a733d26f8179fb3954357f33d44
|
[
"Apache-2.0"
] | 6 |
2017-05-10T15:02:57.000Z
|
2020-08-07T14:38:02.000Z
|
pousse-cafe-core/src/test/java/poussecafe/entity/SimpleEntity.java
|
pousse-cafe/pousse-cafe
|
9dfc2d0b7c2e9a733d26f8179fb3954357f33d44
|
[
"Apache-2.0"
] | 217 |
2018-01-31T07:52:30.000Z
|
2021-03-23T20:48:43.000Z
|
pousse-cafe-core/src/test/java/poussecafe/entity/SimpleEntity.java
|
pousse-cafe/pousse-cafe
|
9dfc2d0b7c2e9a733d26f8179fb3954357f33d44
|
[
"Apache-2.0"
] | 4 |
2019-05-23T05:49:50.000Z
|
2020-04-08T07:47:15.000Z
| 25.833333 | 97 | 0.716129 | 1,003,670 |
package poussecafe.entity;
import poussecafe.domain.Entity;
import poussecafe.domain.EntityAttributes;
import poussecafe.util.StringId;
public class SimpleEntity extends Entity<StringId, SimpleEntity.Attributes> {
@Override
public boolean equals(Object obj) {
SimpleEntity other = (SimpleEntity) obj;
return attributes().identifier().value().equals(other.attributes().identifier().value());
}
@Override
public int hashCode() {
return attributes().identifier().value().hashCode();
}
public static interface Attributes extends EntityAttributes<StringId> {
}
}
|
92462a70ce3290956ec672d3f5619824dd226a4c
| 1,797 |
java
|
Java
|
Salailija/src/main/java/labra/tira/salailija/Utils/Quicksort.java
|
vapsolon/Salailija
|
9d6f96d52363c99a1b7225353d57aae28fe9b002
|
[
"MIT"
] | null | null | null |
Salailija/src/main/java/labra/tira/salailija/Utils/Quicksort.java
|
vapsolon/Salailija
|
9d6f96d52363c99a1b7225353d57aae28fe9b002
|
[
"MIT"
] | 2 |
2020-02-14T18:20:55.000Z
|
2020-02-28T21:24:40.000Z
|
Salailija/src/main/java/labra/tira/salailija/Utils/Quicksort.java
|
vapsolon/Salailija
|
9d6f96d52363c99a1b7225353d57aae28fe9b002
|
[
"MIT"
] | null | null | null | 32.089286 | 80 | 0.631608 | 1,003,671 |
package labra.tira.salailija.Utils;
/**
* Jo aiemmin toteutettu Quicksort, tällä kertaa paljon klassisemmassa muodossa.
* <br>
* Tehtävänä on järjestää frekvenssianalyysin tuottamia merkkien
* esiintymismäärälistoja esiintymismäärän perusteella.
* @author vapsolon
*/
public class Quicksort {
private FrequencyPair[] frequencies;
/**
* Aloitusfunktio ja näistä ainoa ulkopuolelta kutsuttava. <br>
* Ottaa vastaan valmiin frekvenssiparilistan ja siirtää sen
* järjestettäväksi. Kun järjestys on valmis palauttaa tuloksen.
* @param fp Järjestettävä FrequencyPair-lista
* @param length Listan aito pituus, ei siis sisällä listan olemassa olevia
* mutta täyttämättömiä kenttiä
* @return Parametrina annettu lista mutta järjestettynä
*/
public FrequencyPair[] start(FrequencyPair[] fp, int length){
this.frequencies = fp;
sort(0, length-1);
return this.frequencies;
}
private void sort(int start, int end){
if(start < end){
int middle = split(start, end);
sort(start, middle-1);
sort(middle+1, end);
}
}
private int split(int start, int end){
int middle = start;
for(int i=start+1;i<=end;i++){
FrequencyPair current = this.frequencies[i];
FrequencyPair first = this.frequencies[start];
if(current.getCount() > first.getCount()){
middle++;
this.frequencies[i] = this.frequencies[middle];
this.frequencies[middle] = current;
}
}
FrequencyPair temp = this.frequencies[start];
this.frequencies[start] = this.frequencies[middle];
this.frequencies[middle] = temp;
return middle;
}
}
|
92462ad0a7eb2e042d4d6b324e6d4b3617cd766c
| 2,219 |
java
|
Java
|
mymarkapp/src/main/java/com/mymark/app/data/reference/Country.java
|
jsicree/mymark-monolith
|
4d89c6de7cd45480ea053c6f58065266a5444a9d
|
[
"MIT"
] | null | null | null |
mymarkapp/src/main/java/com/mymark/app/data/reference/Country.java
|
jsicree/mymark-monolith
|
4d89c6de7cd45480ea053c6f58065266a5444a9d
|
[
"MIT"
] | 2 |
2018-02-10T19:28:11.000Z
|
2018-06-20T17:49:48.000Z
|
mymarkapp/src/main/java/com/mymark/app/data/reference/Country.java
|
jsicree/mymark-monolith
|
4d89c6de7cd45480ea053c6f58065266a5444a9d
|
[
"MIT"
] | null | null | null | 19.637168 | 67 | 0.657503 | 1,003,672 |
package com.mymark.app.data.reference;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import com.mymark.app.data.enums.Language;
@Entity(name="COUNTRY")
public class Country {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name="NAME")
private String name;
@Column(name="CODE")
private String code;
public Country() {
super();
// TODO Auto-generated constructor stub
}
public Country(String name, String code) {
super();
this.name = name;
this.code = code;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Country [id=");
builder.append(id);
builder.append(", name=");
builder.append(name);
builder.append(", code=");
builder.append(code);
builder.append("]");
return builder.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((code == null) ? 0 : code.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Country other = (Country) obj;
if (code == null) {
if (other.code != null)
return false;
} else if (!code.equals(other.code))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
|
92462b432775aace5e04163b19a01afd04a23fd0
| 5,496 |
java
|
Java
|
sdk/java/src/org/opencv/face/MACE.java
|
avamartynenko/OpenCV-android-sdk
|
b667b9e7bdd8f689c14e3166e018ff36dbdfc516
|
[
"Apache-2.0"
] | 7 |
2020-08-25T05:05:53.000Z
|
2022-03-10T09:14:51.000Z
|
sdk/java/src/org/opencv/face/MACE.java
|
avamartynenko/OpenCV-android-sdk
|
b667b9e7bdd8f689c14e3166e018ff36dbdfc516
|
[
"Apache-2.0"
] | 2 |
2020-10-26T03:08:24.000Z
|
2020-12-11T15:51:57.000Z
|
sdk/java/src/org/opencv/face/MACE.java
|
avamartynenko/OpenCV-android-sdk
|
b667b9e7bdd8f689c14e3166e018ff36dbdfc516
|
[
"Apache-2.0"
] | 1 |
2021-11-16T23:18:11.000Z
|
2021-11-16T23:18:11.000Z
| 29.079365 | 117 | 0.62682 | 1,003,673 |
//
// This file is auto-generated. Please don't modify it!
//
package org.opencv.face;
import java.util.ArrayList;
import java.util.List;
import org.opencv.core.Algorithm;
import org.opencv.core.Mat;
import org.opencv.face.MACE;
import org.opencv.utils.Converters;
// C++: class MACE
/**
* Minimum Average Correlation Energy Filter
* useful for authentication with (cancellable) biometrical features.
* (does not need many positives to train (10-50), and no negatives at all, also robust to noise/salting)
*
* see also: CITE: Savvides04
*
* this implementation is largely based on: https://code.google.com/archive/p/pam-face-authentication (GSOC 2009)
*
* use it like:
* <code>
*
* Ptr<face::MACE> mace = face::MACE::create(64);
*
* vector<Mat> pos_images = ...
* mace->train(pos_images);
*
* Mat query = ...
* bool same = mace->same(query);
*
* </code>
*
* you can also use two-factor authentication, with an additional passphrase:
*
* <code>
* String owners_passphrase = "ilikehotdogs";
* Ptr<face::MACE> mace = face::MACE::create(64);
* mace->salt(owners_passphrase);
* vector<Mat> pos_images = ...
* mace->train(pos_images);
*
* // now, users have to give a valid passphrase, along with the image:
* Mat query = ...
* cout << "enter passphrase: ";
* string pass;
* getline(cin, pass);
* mace->salt(pass);
* bool same = mace->same(query);
* </code>
*
* save/load your model:
* <code>
* Ptr<face::MACE> mace = face::MACE::create(64);
* mace->train(pos_images);
* mace->save("my_mace.xml");
*
* // later:
* Ptr<MACE> reloaded = MACE::load("my_mace.xml");
* reloaded->same(some_image);
* </code>
*/
public class MACE extends Algorithm {
protected MACE(long addr) { super(addr); }
// internal usage only
public static MACE __fromPtr__(long addr) { return new MACE(addr); }
//
// C++: static Ptr_MACE cv::face::MACE::create(int IMGSIZE = 64)
//
/**
* constructor
* @param IMGSIZE images will get resized to this (should be an even number)
* @return automatically generated
*/
public static MACE create(int IMGSIZE) {
return MACE.__fromPtr__(create_0(IMGSIZE));
}
/**
* constructor
* @return automatically generated
*/
public static MACE create() {
return MACE.__fromPtr__(create_1());
}
//
// C++: static Ptr_MACE cv::face::MACE::load(String filename, String objname = String())
//
/**
* constructor
* @param filename build a new MACE instance from a pre-serialized FileStorage
* @param objname (optional) top-level node in the FileStorage
* @return automatically generated
*/
public static MACE load(String filename, String objname) {
return MACE.__fromPtr__(load_0(filename, objname));
}
/**
* constructor
* @param filename build a new MACE instance from a pre-serialized FileStorage
* @return automatically generated
*/
public static MACE load(String filename) {
return MACE.__fromPtr__(load_1(filename));
}
//
// C++: bool cv::face::MACE::same(Mat query)
//
/**
* correlate query img and threshold to min class value
* @param query a Mat with query image
* @return automatically generated
*/
public boolean same(Mat query) {
return same_0(nativeObj, query.nativeObj);
}
//
// C++: void cv::face::MACE::salt(String passphrase)
//
/**
* optionally encrypt images with random convolution
* @param passphrase a crc64 random seed will get generated from this
*/
public void salt(String passphrase) {
salt_0(nativeObj, passphrase);
}
//
// C++: void cv::face::MACE::train(vector_Mat images)
//
/**
* train it on positive features
* compute the mace filter: {@code h = D(-1) * X * (X(+) * D(-1) * X)(-1) * C}
* also calculate a minimal threshold for this class, the smallest self-similarity from the train images
* @param images a vector<Mat> with the train images
*/
public void train(List<Mat> images) {
Mat images_mat = Converters.vector_Mat_to_Mat(images);
train_0(nativeObj, images_mat.nativeObj);
}
@Override
protected void finalize() throws Throwable {
delete(nativeObj);
}
// C++: static Ptr_MACE cv::face::MACE::create(int IMGSIZE = 64)
private static native long create_0(int IMGSIZE);
private static native long create_1();
// C++: static Ptr_MACE cv::face::MACE::load(String filename, String objname = String())
private static native long load_0(String filename, String objname);
private static native long load_1(String filename);
// C++: bool cv::face::MACE::same(Mat query)
private static native boolean same_0(long nativeObj, long query_nativeObj);
// C++: void cv::face::MACE::salt(String passphrase)
private static native void salt_0(long nativeObj, String passphrase);
// C++: void cv::face::MACE::train(vector_Mat images)
private static native void train_0(long nativeObj, long images_mat_nativeObj);
// native support for java finalize()
private static native void delete(long nativeObj);
}
|
92462bf748cfa32ead4f3d55899030d13f7b7d6d
| 1,483 |
java
|
Java
|
rhino-core/src/main/java/io/ryos/rhino/sdk/annotations/SessionFeeder.java
|
ryos-io/Rhino
|
f6f69ac201a79e66f801b42a39789bcf3d8d9d9d
|
[
"Apache-2.0"
] | 14 |
2019-07-14T22:45:50.000Z
|
2021-05-29T13:12:23.000Z
|
rhino-core/src/main/java/io/ryos/rhino/sdk/annotations/SessionFeeder.java
|
ryos-io/Rhino
|
f6f69ac201a79e66f801b42a39789bcf3d8d9d9d
|
[
"Apache-2.0"
] | 110 |
2019-07-10T12:19:02.000Z
|
2021-12-18T18:12:51.000Z
|
rhino-core/src/main/java/io/ryos/rhino/sdk/annotations/SessionFeeder.java
|
bagdemir/rhino
|
bb731dccb9384ee79f38722f55cea81fdc79a13b
|
[
"Apache-2.0"
] | 1 |
2019-05-10T09:27:16.000Z
|
2019-05-10T09:27:16.000Z
| 35.309524 | 99 | 0.774781 | 1,003,674 |
/*
Copyright 2018 Ryos.io.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package io.ryos.rhino.sdk.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Session feeder annotation marks the injection point where the current user define is to be
* injected. A user define starts with simulation execution, and ends as soon as the simulation
* ends. The user sessions are useful e.g if you need a context shared between scenario executions.
* Test developers might choose to initialize resources in prepare() method, e.g upload a
* resource beforehand and store the reference of the resource in the define so as to access it
* in scenario methods.
*
* @author Erhan Bagdemir
* @since 1.1.0
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Documented
public @interface SessionFeeder {
}
|
92462c4e968ba2ee8f304a5f359656df009477b4
| 640 |
java
|
Java
|
app/src/main/java/br/com/tassioauad/spotifystreamer/presenter/TrackPresenter.java
|
tassioauad/SpotifyStreamer
|
08075228a5122a802bcb05b5b0958d4cae85fefb
|
[
"Apache-2.0"
] | 9 |
2015-06-27T22:06:26.000Z
|
2021-04-08T00:50:24.000Z
|
app/src/main/java/br/com/tassioauad/spotifystreamer/presenter/TrackPresenter.java
|
tassioauad/SpotifyStreamer
|
08075228a5122a802bcb05b5b0958d4cae85fefb
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/br/com/tassioauad/spotifystreamer/presenter/TrackPresenter.java
|
tassioauad/SpotifyStreamer
|
08075228a5122a802bcb05b5b0958d4cae85fefb
|
[
"Apache-2.0"
] | 2 |
2015-09-26T18:28:55.000Z
|
2021-04-07T11:10:53.000Z
| 25.6 | 80 | 0.679688 | 1,003,675 |
package br.com.tassioauad.spotifystreamer.presenter;
import java.util.ArrayList;
import java.util.Arrays;
import br.com.tassioauad.spotifystreamer.model.entity.Track;
import br.com.tassioauad.spotifystreamer.view.TrackView;
public class TrackPresenter {
private TrackView view;
public TrackPresenter(TrackView view) {
this.view = view;
}
public void init(ArrayList<Track> trackList, int actualPosition) {
if(trackList == null || trackList.size() == 0 || actualPosition == -1) {
view.warnNoTracks();
} else {
view.showPlayer(trackList, actualPosition);
}
}
}
|
92462da6ae84496dfec6bdded3fe8c86a1880aef
| 1,116 |
java
|
Java
|
src/main/java/com/github/johanbrorson/example/ConfigurationHelper.java
|
JohanBrorson/cucumber-webdriver-example
|
6c4e2aff8124809d91226ee8a79ed5db1f7b46c2
|
[
"MIT"
] | null | null | null |
src/main/java/com/github/johanbrorson/example/ConfigurationHelper.java
|
JohanBrorson/cucumber-webdriver-example
|
6c4e2aff8124809d91226ee8a79ed5db1f7b46c2
|
[
"MIT"
] | 1 |
2021-12-18T18:38:49.000Z
|
2021-12-18T18:38:49.000Z
|
src/main/java/com/github/johanbrorson/example/ConfigurationHelper.java
|
JohanBrorson/cucumber-webdriver-example
|
6c4e2aff8124809d91226ee8a79ed5db1f7b46c2
|
[
"MIT"
] | null | null | null | 32.823529 | 90 | 0.74552 | 1,003,676 |
package com.github.johanbrorson.example;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class ConfigurationHelper {
private static final Logger LOG = LogManager.getLogger(ConfigurationHelper.class);
public static String getBrowserType() {
String browserTypeKey = ConfigurationKeys.BROWSER_TYPE.getKey();
String browserTypeDefault = (String) ConfigurationKeys.BROWSER_TYPE.getDefaultValue();
return getStringProperty(browserTypeKey, browserTypeDefault);
}
public static String getBaseUrl() {
String baseUrlKey = ConfigurationKeys.SITE_URL_BASE.getKey();
String baseUrlDefault = (String) ConfigurationKeys.SITE_URL_BASE.getDefaultValue();
return getStringProperty(baseUrlKey, baseUrlDefault);
}
private static String getStringProperty(String key, String defaultValue) {
String value;
try {
value = Configuration.getInstance().getString(key, defaultValue);
} catch (Exception e) {
e.printStackTrace();
value = defaultValue;
}
LOG.debug("Key: {}, Value: {}", key, value);
return value;
}
}
|
92462e8cf8df2643b2382eb8470ebbfa48ac9aa0
| 2,006 |
java
|
Java
|
src/main/java/model/SystemDetailImpl.java
|
gabrigiunchi/AlarmSARL
|
778909db157df292b74457b4a8478d3ac784a21b
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/model/SystemDetailImpl.java
|
gabrigiunchi/AlarmSARL
|
778909db157df292b74457b4a8478d3ac784a21b
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/model/SystemDetailImpl.java
|
gabrigiunchi/AlarmSARL
|
778909db157df292b74457b4a8478d3ac784a21b
|
[
"Apache-2.0"
] | null | null | null | 17.443478 | 73 | 0.660518 | 1,003,677 |
package model;
import static model.SystemDetail.SystemState.unknown;
import java.util.UUID;
/**
*
* @author Gabriele Giunchi
*
* Implementazione di {@link SystemDetail}
*
*/
public class SystemDetailImpl implements SystemDetail {
// Stato di default in cui si trova il sistema alla sua creazione
private static final SystemState INITIAL_STATE = unknown;
private final UUID agentId;
private String id;
private String name;
private SystemState state;
public SystemDetailImpl(final UUID agentId) {
this.name = "";
this.agentId = agentId;
this.id = "";
this.state = INITIAL_STATE;
}
@Override
public void setState(final SystemState state) {
this.state = state;
}
@Override
public void setName(final String name) {
this.name = name;
}
@Override
public void setId(final String id) {
this.id = id;
}
@Override
public String getName() {
return this.name;
}
@Override
public String getId() {
return this.id;
}
@Override
public UUID getAgentId() {
return this.agentId;
}
@Override
public SystemState getState() {
return this.state;
}
@Override
public String toString() {
final StringBuilder stringBuilder = new StringBuilder(this.id);
if (!this.name.isEmpty()) {
stringBuilder.append('(')
.append(name)
.append(')');
}
stringBuilder.append(" : ")
.append(state);
return stringBuilder.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((agentId == null) ? 0 : agentId.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final SystemDetailImpl other = (SystemDetailImpl) obj;
if (agentId == null) {
if (other.agentId != null) {
return false;
}
} else if (!agentId.equals(other.agentId)) {
return false;
}
return true;
}
}
|
92462ecead6b3bd8b913ad024cd9b5e091996c8c
| 1,810 |
java
|
Java
|
src/main/java/ilusr/textadventurecreator/menus/DebugMenuItem.java
|
JeffreyRiggle/textadventurecreator
|
72e5bb2d3530a222d756b21800d300e711752b73
|
[
"MIT"
] | null | null | null |
src/main/java/ilusr/textadventurecreator/menus/DebugMenuItem.java
|
JeffreyRiggle/textadventurecreator
|
72e5bb2d3530a222d756b21800d300e711752b73
|
[
"MIT"
] | 8 |
2017-08-15T09:12:36.000Z
|
2021-10-01T10:02:39.000Z
|
src/main/java/ilusr/textadventurecreator/menus/DebugMenuItem.java
|
JeffreyRiggle/textadventurecreator
|
72e5bb2d3530a222d756b21800d300e711752b73
|
[
"MIT"
] | null | null | null | 31.206897 | 116 | 0.762431 | 1,003,678 |
package ilusr.textadventurecreator.menus;
import ilusr.logrunner.LogRunner;
import ilusr.textadventurecreator.debug.IDebugService;
import ilusr.textadventurecreator.language.DisplayStrings;
import ilusr.textadventurecreator.language.ILanguageService;
import ilusr.textadventurecreator.shell.TextAdventureProvider;
import ilusr.textadventurecreator.views.assets.AssetLoader;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
/**
*
* @author Jeff Riggle
*
*/
public class DebugMenuItem extends GameAwareMenuItem {
private final TextAdventureProvider provider;
private final IDebugService service;
private final ILanguageService languageService;
/**
*
* @param provider A @see TextAdventureProvider to provide the current text adventure.
* @param service A @see DebugService to debug the text adventure with.
* @param languageService A @see LanguageService to provide display strings.
*/
public DebugMenuItem(TextAdventureProvider provider,
IDebugService service,
ILanguageService languageService) {
super(provider, languageService.getValue(DisplayStrings.DEBUG));
this.provider = provider;
this.service = service;
this.languageService = languageService;
initialize();
}
private void initialize() {
super.setOnAction((e) -> {
LogRunner.logger().info("Run -> Debug Pressed.");
service.debugGame(provider.getTextAdventureProject().getTextAdventure());
});
languageService.addListener(() -> {
super.textProperty().set(languageService.getValue(DisplayStrings.DEBUG));
});
try {
Image debugIco = new Image(AssetLoader.getResourceURL("DebugManyIcon.png").toExternalForm(), 16, 16, true, true);
super.setGraphic(new ImageView(debugIco));
} catch (Exception e) {
LogRunner.logger().severe(e);
}
}
}
|
92462ed477add0aa2db7295c697efd13d6049066
| 4,778 |
java
|
Java
|
src/main/java/io/renren/common/utils/HttpHelper.java
|
xukaka/leifeng
|
693fbbc56ebc2b1ccfaebf9088e18a80477fb145
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/io/renren/common/utils/HttpHelper.java
|
xukaka/leifeng
|
693fbbc56ebc2b1ccfaebf9088e18a80477fb145
|
[
"Apache-2.0"
] | 2 |
2021-04-22T16:48:14.000Z
|
2021-09-20T20:47:21.000Z
|
src/main/java/io/renren/common/utils/HttpHelper.java
|
xukaka/leifeng
|
693fbbc56ebc2b1ccfaebf9088e18a80477fb145
|
[
"Apache-2.0"
] | 1 |
2019-04-27T02:23:35.000Z
|
2019-04-27T02:23:35.000Z
| 32.283784 | 134 | 0.681666 | 1,003,679 |
/**
* 版权所有:深圳云之家网络科技有限公司
* Copyright 2018 yunzhijia.com Inc.
* All right reserved.
*====================================================
* 文件名称: BaseController.java
* 修订记录:
* No 日期 作者(操作:具体内容)
* 1. May 20, 2018 wangzy,yz(创建:创建文件)
*====================================================
* 类描述:http 请求帮助类
*/
package io.renren.common.utils;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;
import java.util.*;
public final class HttpHelper {
private final static String UTF8 = "UTF-8";
public static String post(Map<String, String> params, String url) throws Exception {
return post(params, url, 0);
}
public static String post(Map<String, String> params, String url, int timeOutInMillis) throws Exception {
return post(null, params, url, timeOutInMillis);
}
public static String post(Map<String, String> headers, Map<String, String> params, String url) throws Exception {
return post(headers, params, url, 0);
}
public static String post(Map<String, String> headers, Map<String, String> params, String url,
int timeOutInMillis) throws Exception {
HttpPost post = null;
try {
post = getHttpPost(headers, params, url, timeOutInMillis);
return HttpClientHelper.getHttpClient().execute(post, UTF8);
} finally {
if(post != null) post.abort();
}
}
private static HttpPost getHttpPost(Map<String, String> headers, Map<String, String> params,
String url, int timeOutInMillis) throws Exception {
HttpPost post = new HttpPost(url);
if(headers != null) {
Set<String> set = headers.keySet();
Iterator<String> it = set.iterator();
while(it.hasNext()) {
String key = it.next();
post.addHeader(key, headers.get(key));
}
}
if(params != null) {
List<NameValuePair> uvp = new LinkedList<NameValuePair>();
Set<String> set = params.keySet();
Iterator<String> it = set.iterator();
while(it.hasNext()) {
String key = it.next();
uvp.add(new BasicNameValuePair(key, params.get(key)));
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(uvp, UTF8);
post.setEntity(entity);
}
if(timeOutInMillis > 0) {
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeOutInMillis).setConnectTimeout(timeOutInMillis).build();
post.setConfig(requestConfig);
}
return post;
}
public static String post(Map<String, String> headers, String jsonObject, String url, int timeOutInMillis) throws Exception {
HttpPost post = null;
try {
post = new HttpPost(url);
if(headers != null) {
Set<String> set = headers.keySet();
Iterator<String> it = set.iterator();
while (it.hasNext()) {
String key = it.next();
post.addHeader(key, headers.get(key));
}
}
if(null == jsonObject || jsonObject.isEmpty()) throw new Exception("json参数为空!");
StringEntity entity = new StringEntity(jsonObject, UTF8);
if(timeOutInMillis > 0) {
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeOutInMillis).setConnectTimeout(timeOutInMillis).build();
post.setConfig(requestConfig);
}
post.setEntity(entity);
return HttpClientHelper.getHttpClient().execute(post, UTF8);
} finally {
if(post != null) post.abort();
}
}
public static String get( String url) throws Exception {
return get( url, 0);
}
public static String get( String url, int timeOutInMillis) throws Exception {
return get(null, url, timeOutInMillis);
}
public static String get(Map<String, String> headers, String url) throws Exception {
return get(headers, url, 0);
}
public static String get(Map<String, String> headers,String url,
int timeOutInMillis) throws Exception {
HttpGet get = null;
try {
get = getHttpGet(headers, url, timeOutInMillis);
return HttpClientHelper.getHttpClient().execute(get, UTF8);
} finally {
if(get != null) get.abort();
}
}
private static HttpGet getHttpGet(Map<String, String> headers,
String url, int timeOutInMillis) throws Exception {
HttpGet get = new HttpGet(url);
if(headers != null) {
Set<String> set = headers.keySet();
Iterator<String> it = set.iterator();
while(it.hasNext()) {
String key = it.next();
get.addHeader(key, headers.get(key));
}
}
if(timeOutInMillis > 0) {
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeOutInMillis).setConnectTimeout(timeOutInMillis).build();
get.setConfig(requestConfig);
}
return get;
}
}
|
92462f036eb15cb21976db57fdacbe1657da86d3
| 3,208 |
java
|
Java
|
fency-core/src/main/java/io/fency/RabbitMqBeanPostProcessor.java
|
ask4gilles/fency
|
9c8bb89a7d4b5360e81e32c5742752ad5e00da73
|
[
"Apache-2.0"
] | 14 |
2019-04-21T05:28:27.000Z
|
2021-01-02T15:11:58.000Z
|
fency-core/src/main/java/io/fency/RabbitMqBeanPostProcessor.java
|
ask4gilles/fency
|
9c8bb89a7d4b5360e81e32c5742752ad5e00da73
|
[
"Apache-2.0"
] | 2 |
2019-02-20T13:25:56.000Z
|
2019-02-22T09:39:27.000Z
|
fency-core/src/main/java/io/fency/RabbitMqBeanPostProcessor.java
|
ask4gilles/fency
|
9c8bb89a7d4b5360e81e32c5742752ad5e00da73
|
[
"Apache-2.0"
] | 8 |
2019-04-25T00:54:34.000Z
|
2020-11-26T03:01:44.000Z
| 38.190476 | 100 | 0.787095 | 1,003,680 |
/*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.fency;
import java.lang.reflect.Field;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.util.ReflectionUtils;
import lombok.RequiredArgsConstructor;
import org.aopalliance.aop.Advice;
/**
* Instrument amqp containers with a {@link MessageInterceptor}.
*
* @author Gilles Robert
*/
@RequiredArgsConstructor
class RabbitMqBeanPostProcessor implements BeanPostProcessor {
private final MessageInterceptor messageInterceptor;
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
if (bean instanceof SimpleRabbitListenerContainerFactory) {
SimpleRabbitListenerContainerFactory factory = (SimpleRabbitListenerContainerFactory) bean;
registerIdempotentInterceptor(factory);
} else if (bean instanceof AbstractMessageListenerContainer) {
AbstractMessageListenerContainer container = (AbstractMessageListenerContainer) bean;
registerIdempotentInterceptor(container);
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
private void registerIdempotentInterceptor(SimpleRabbitListenerContainerFactory factory) {
Advice[] chain = factory.getAdviceChain();
Advice[] adviceChainWithTracing = getAdviceChainOrAddInterceptorToChain(chain);
factory.setAdviceChain(adviceChainWithTracing);
}
private void registerIdempotentInterceptor(AbstractMessageListenerContainer container) {
Field adviceChainField =
ReflectionUtils.findField(AbstractMessageListenerContainer.class, "adviceChain");
ReflectionUtils.makeAccessible(adviceChainField);
Advice[] chain = (Advice[]) ReflectionUtils.getField(adviceChainField, container);
Advice[] newAdviceChain = getAdviceChainOrAddInterceptorToChain(chain);
container.setAdviceChain(newAdviceChain);
}
private Advice[] getAdviceChainOrAddInterceptorToChain(Advice... existingAdviceChain) {
if (existingAdviceChain == null) {
return new Advice[] {messageInterceptor};
}
Advice[] newChain = new Advice[existingAdviceChain.length + 1];
System.arraycopy(existingAdviceChain, 0, newChain, 0, existingAdviceChain.length);
newChain[existingAdviceChain.length] = messageInterceptor;
return newChain;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.