hexsha stringlengths 40 40 | size int64 8 1.04M | content stringlengths 8 1.04M | avg_line_length float64 2.24 100 | max_line_length int64 4 1k | alphanum_fraction float64 0.25 0.97 |
|---|---|---|---|---|---|
4bfd9642db5338f7ff7aca5d468eae00020e0ba9 | 11,408 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hive.ql.exec;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.ql.CompilationOpContext;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.plan.ExprNodeDesc;
import org.apache.hadoop.hive.ql.plan.MuxDesc;
import org.apache.hadoop.hive.ql.plan.OperatorDesc;
import org.apache.hadoop.hive.ql.plan.api.OperatorType;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* MuxOperator is used in the Reduce side of MapReduce jobs optimized by Correlation Optimizer.
* Correlation Optimizer will remove unnecessary ReduceSinkOperaotrs,
* and MuxOperators are used to replace those ReduceSinkOperaotrs.
* Example: The original operator tree is ...
* JOIN2
* / \
* RS4 RS5
* / \
* GBY1 JOIN1
* | / \
* RS1 RS2 RS3
* If GBY1, JOIN1, and JOIN2 can be executed in the same reducer
* (optimized by Correlation Optimizer).
* The new operator tree will be ...
* JOIN2
* |
* MUX
* / \
* GBY1 JOIN1
* \ /
* DEMUX
* / | \
* / | \
* / | \
* RS1 RS2 RS3
*
* A MuxOperator has two functions.
* First, it will construct key, value and tag structure for
* the input of Join Operators.
* Second, it is a part of operator coordination mechanism which makes sure the operator tree
* in the Reducer can work correctly.
*/
public class MuxOperator extends Operator<MuxDesc> implements Serializable{
private static final long serialVersionUID = 1L;
protected static final Logger LOG = LoggerFactory.getLogger(MuxOperator.class.getName());
/**
* Handler is used to construct the key-value structure.
* This structure is needed by child JoinOperators and GroupByOperators of
* a MuxOperator to function correctly.
*/
protected static class Handler {
private final ObjectInspector outputObjInspector;
private final int tag;
/**
* The evaluators for the key columns. Key columns decide the sort order on
* the reducer side. Key columns are passed to the reducer in the "key".
*/
private final ExprNodeEvaluator[] keyEval;
/**
* The evaluators for the value columns. Value columns are passed to reducer
* in the "value".
*/
private final ExprNodeEvaluator[] valueEval;
private final Object[] outputKey;
private final Object[] outputValue;
private final List<Object> forwardedRow;
public Handler(ObjectInspector inputObjInspector,
List<ExprNodeDesc> keyCols,
List<ExprNodeDesc> valueCols,
List<String> outputKeyColumnNames,
List<String> outputValueColumnNames,
Integer tag) throws HiveException {
keyEval = new ExprNodeEvaluator[keyCols.size()];
int i = 0;
for (ExprNodeDesc e: keyCols) {
keyEval[i++] = ExprNodeEvaluatorFactory.get(e);
}
outputKey = new Object[keyEval.length];
valueEval = new ExprNodeEvaluator[valueCols.size()];
i = 0;
for (ExprNodeDesc e: valueCols) {
valueEval[i++] = ExprNodeEvaluatorFactory.get(e);
}
outputValue = new Object[valueEval.length];
this.tag = tag;
ObjectInspector keyObjectInspector = initEvaluatorsAndReturnStruct(keyEval,
outputKeyColumnNames, inputObjInspector);
ObjectInspector valueObjectInspector = initEvaluatorsAndReturnStruct(valueEval,
outputValueColumnNames, inputObjInspector);
List<ObjectInspector> ois = new ArrayList<ObjectInspector>();
ois.add(keyObjectInspector);
ois.add(valueObjectInspector);
this.outputObjInspector = ObjectInspectorFactory.getStandardStructObjectInspector(
Utilities.reduceFieldNameList, ois);
this.forwardedRow = new ArrayList<Object>(Utilities.reduceFieldNameList.size());
}
public ObjectInspector getOutputObjInspector() {
return outputObjInspector;
}
public int getTag() {
return tag;
}
public Object process(Object row) throws HiveException {
// Evaluate the keys
for (int i = 0; i < keyEval.length; i++) {
outputKey[i] = keyEval[i].evaluate(row);
}
// Evaluate the value
for (int i = 0; i < valueEval.length; i++) {
outputValue[i] = valueEval[i].evaluate(row);
}
forwardedRow.clear();
// JoinOperator assumes the key is backed by an list.
// To be consistent, the value array is also converted
// to a list.
forwardedRow.add(Arrays.asList(outputKey));
forwardedRow.add(Arrays.asList(outputValue));
return forwardedRow;
}
}
private transient ObjectInspector[] outputObjectInspectors;
private transient int numParents;
private transient boolean[] forward;
private transient boolean[] processGroupCalled;
private Handler[] handlers;
// Counters for debugging, we cannot use existing counters (cntr and nextCntr)
// in Operator since we want to individually track the number of rows from different inputs.
private transient long[] cntrs;
private transient long[] nextCntrs;
/** Kryo ctor. */
protected MuxOperator() {
super();
}
public MuxOperator(CompilationOpContext ctx) {
super(ctx);
}
@Override
protected void initializeOp(Configuration hconf) throws HiveException {
super.initializeOp(hconf);
// A MuxOperator should only have a single child
if (childOperatorsArray.length != 1) {
throw new HiveException(
"Expected number of children is 1. Found : " + childOperatorsArray.length);
}
numParents = getNumParent();
forward = new boolean[numParents];
processGroupCalled = new boolean[numParents];
outputObjectInspectors = new ObjectInspector[numParents];
handlers = new Handler[numParents];
cntrs = new long[numParents];
nextCntrs = new long[numParents];
for (int i = 0; i < numParents; i++) {
processGroupCalled[i] = false;
if (conf.getParentToKeyCols().get(i) == null) {
// We do not need to evaluate the input row for this parent.
// So, we can just forward it to the child of this MuxOperator.
handlers[i] = null;
forward[i] = true;
outputObjectInspectors[i] = inputObjInspectors[i];
} else {
handlers[i] = new Handler(
inputObjInspectors[i],
conf.getParentToKeyCols().get(i),
conf.getParentToValueCols().get(i),
conf.getParentToOutputKeyColumnNames().get(i),
conf.getParentToOutputValueColumnNames().get(i),
conf.getParentToTag().get(i));
forward[i] = false;
outputObjectInspectors[i] = handlers[i].getOutputObjInspector();
}
cntrs[i] = 0;
nextCntrs[i] = 1;
}
}
/**
* Calls initialize on each of the children with outputObjetInspector as the
* output row format.
*/
@Override
protected void initializeChildren(Configuration hconf) throws HiveException {
state = State.INIT;
if (LOG.isInfoEnabled()) {
LOG.info("Operator " + id + " " + getName() + " initialized");
}
if (childOperators == null || childOperators.isEmpty()) {
return;
}
if (LOG.isInfoEnabled()) {
LOG.info("Initializing children of " + id + " " + getName());
}
childOperatorsArray[0].initialize(hconf, outputObjectInspectors);
if (reporter != null) {
childOperatorsArray[0].setReporter(reporter);
}
}
@Override
public void process(Object row, int tag) throws HiveException {
if (LOG.isInfoEnabled()) {
cntrs[tag]++;
if (cntrs[tag] == nextCntrs[tag]) {
LOG.info(id + ", tag=" + tag + ", forwarding " + cntrs[tag] + " rows");
nextCntrs[tag] = getNextCntr(cntrs[tag]);
}
}
int childrenDone = 0;
for (int i = 0; i < childOperatorsArray.length; i++) {
Operator<? extends OperatorDesc> child = childOperatorsArray[i];
if (child.getDone()) {
childrenDone++;
} else {
if (forward[tag]) {
// No need to evaluate, just forward it.
child.process(row, tag);
} else {
// Call the corresponding handler to evaluate this row and
// forward the result
child.process(handlers[tag].process(row), handlers[tag].getTag());
}
}
}
// if all children are done, this operator is also done
if (childrenDone == childOperatorsArray.length) {
setDone(true);
}
}
@Override
public void forward(Object row, ObjectInspector rowInspector)
throws HiveException {
// Because we need to revert the tag of a row to its old tag and
// we cannot pass new tag to this method which is used to get
// the old tag from the mapping of newTagToOldTag, we bypass
// this method in MuxOperator and directly call process on children
// in process() method..
}
@Override
public void startGroup() throws HiveException{
for (int i = 0; i < numParents; i++) {
processGroupCalled[i] = false;
}
super.startGroup();
}
@Override
public void endGroup() throws HiveException {
// do nothing
}
@Override
public void processGroup(int tag) throws HiveException {
processGroupCalled[tag] = true;
boolean shouldProceed = true;
for (int i = 0; i < numParents; i++) {
if (!processGroupCalled[i]) {
shouldProceed = false;
break;
}
}
if (shouldProceed) {
Operator<? extends OperatorDesc> child = childOperatorsArray[0];
int childTag = childOperatorsTag[0];
child.flush();
child.endGroup();
child.processGroup(childTag);
}
}
@Override
protected void closeOp(boolean abort) throws HiveException {
if (LOG.isInfoEnabled()) {
for (int i = 0; i < numParents; i++) {
LOG.info(id + ", tag=" + i + ", forwarded " + cntrs[i] + " rows");
}
}
}
/**
* @return the name of the operator
*/
@Override
public String getName() {
return MuxOperator.getOperatorName();
}
static public String getOperatorName() {
return "MUX";
}
@Override
public OperatorType getType() {
return OperatorType.MUX;
}
@Override
public boolean logicalEquals(Operator other) {
return getClass().getName().equals(other.getClass().getName());
}
}
| 32.687679 | 95 | 0.663394 |
664ec573378f0dff15d135b7a9237c3589c227bd | 290 | package wiki.laona.factory.method;
/**
* @author laona
* @description 接口
* @date 2021-12-08 20:26
**/
public interface IRuleConfigParser {
/**
* 转化
*
* @param configText 配置文本
* @return {@link RuleConfig} 配置规则
*/
RuleConfig parse(String configText);
}
| 16.111111 | 40 | 0.610345 |
e2f759c03597cec7bbc9b3443435024450d8524c | 2,126 | package org.greenplum.pxf.automation.components.pxf;
import org.greenplum.pxf.automation.components.common.ShellSystemObject;
import org.greenplum.pxf.automation.domain.PxfProtocolVersion;
import org.greenplum.pxf.automation.utils.json.JsonUtils;
import org.greenplum.pxf.automation.utils.jsystem.report.ReportUtils;
/**
* Component representing a PXF service.
* It can access the REST API through curl commands.
*/
public class Pxf extends ShellSystemObject {
private String port = "5888";
/**
* Default ctor.
*/
public Pxf() {
}
/**
* C'tor with option if to use silent mode of jsystem report.
*
* @param silentReport if true silent else will try to write to jsystem
* report for every report
*/
public Pxf(boolean silentReport) {
super(silentReport);
}
@Override
public void init() throws Exception {
ReportUtils.startLevel(report, getClass(), "init");
super.init();
ReportUtils.stopLevel(report);
}
/**
* Gets port.
*
* @return port
*/
public String getPort() {
return port;
}
/**
* Sets port.
*
* @param port port to set
*/
public void setPort(String port) {
this.port = port;
}
/**
* Runs curl command to get PXF's protocol version
*
* @return protocol version retrieved from PXF API
* @throws Exception if operation failed or output didn't contain version
*/
public String getProtocolVersion() throws Exception {
ReportUtils.startLevel(report, getClass(), "get PXF protocol version");
String result = curl(getHost(), getPort(), "pxf/ProtocolVersion");
ReportUtils.report(report, getClass(), "curl command result: " + result);
PxfProtocolVersion pxfProtocolVersion = JsonUtils.deserialize(result, PxfProtocolVersion.class);
String version = pxfProtocolVersion.getVersion();
ReportUtils.report(report, getClass(), "protocol version: " + version);
ReportUtils.stopLevel(report);
return version;
}
}
| 24.72093 | 104 | 0.645814 |
6732eac0d09ea8b6014c592beddc58eee84cc43d | 532 | import java.awt.Button;
import java.awt.Frame;
public class FlowLayout {
public static void main(String[] args) {
Frame frame = new Frame("Flow Layout");
frame.setVisible(true);
frame.setSize(600, 600);
frame.setLayout(null);
frame.add(new Button("Button 1"));
frame.add(new Button("Button 2"));
frame.add(new Button("Button 3"));
frame.add(new Button("Button 4"));
frame.add(new Button("Button 5"));
frame.add(new Button("Button 6"));
}
}
| 25.333333 | 47 | 0.592105 |
e7ac63aff5fe9f162dbb7af814b3895207785058 | 958 | package com.portfolio.steff.koinexportfolio.Models;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;
import java.io.Serializable;
/**
* Created by steff on 28-Dec-17.
*/
@Entity
public class Portfolio implements Serializable {
@PrimaryKey(autoGenerate = true)
public int id;
public Double ripple;
public Double iota;
public Double bitcoin;
public Double ethereum;
public Portfolio() {
}
public Portfolio(Double ripple, Double iota, Double bitcoin, Double ethereum) {
this.ripple = ripple;
this.iota = iota;
this.bitcoin = bitcoin;
this.ethereum = ethereum;
}
@Override
public String toString() {
return "Portfolio{" +
", ic_ripple=" + ripple +
", ic_iota=" + iota +
", bitcoin=" + bitcoin +
", ic_ethereum=" + ethereum +
'}';
}
}
| 22.27907 | 83 | 0.602296 |
e77c8c9a6c3a680584bd72fffa064e7d4e037910 | 155 | package com.ociweb.gl.api;
/**
* Marker interface for facades that implement listeners
* @author Ray Lo
*
*/
public interface ListenerTransducer {
}
| 14.090909 | 56 | 0.722581 |
2c0aca525d77897309bb984fe28c43fcc16a2f6c | 1,147 | package com.example.kedudemo;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatSeekBar;
import androidx.appcompat.widget.AppCompatSpinner;
import androidx.core.widget.ContentLoadingProgressBar;
import android.os.Bundle;
import android.widget.SeekBar;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AppCompatSeekBar seekBar = findViewById(R.id.seekBar);
final HuxingKedu hxkdView = findViewById(R.id.hxkdView);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
hxkdView.setCurrentAngle((float) (2.7*progress-45));
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
}
| 30.184211 | 92 | 0.692241 |
e2a63e347b854d7421628d7c5709e6d58277d219 | 5,475 | package barqsoft.footballscores;
import android.annotation.TargetApi;
import android.content.Intent;
import android.database.Cursor;
import android.os.Binder;
import android.os.Build;
import android.text.TextUtils;
import android.widget.AdapterView;
import android.widget.RemoteViews;
import android.widget.RemoteViewsService;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class WidgetRemoteViewsService extends RemoteViewsService {
@Override
public RemoteViewsFactory onGetViewFactory(Intent intent) {
return new RemoteViewsFactory() {
private Cursor mData = null;
@Override
public void onCreate() { /* no code */ }
@Override
public void onDataSetChanged() {
if (mData != null) {
mData.close();
}
long identityToken = Binder.clearCallingIdentity();
mData = getContentResolver().query(DatabaseContract.BASE_CONTENT_URI, null, null, null, null);
Binder.restoreCallingIdentity(identityToken);
}
@Override
public void onDestroy() {
if (mData != null) {
mData.close();
mData = null;
}
}
@Override
public int getCount() {
return mData == null ? 0 : mData.getCount();
}
@Override
public RemoteViews getViewAt(int position) {
if (position == AdapterView.INVALID_POSITION || mData == null || !mData.moveToPosition(position)) {
return null;
}
RemoteViews views = new RemoteViews(getPackageName(), R.layout.widget_scores_list_item);
int homeGoals = mData.getInt(ScoresDBHelper.HOME_GOALS_COL_INDEX);
int awayGoals = mData.getInt(ScoresDBHelper.AWAY_GOALS_COL_INDEX);
String scores = Utilies.getScores(awayGoals, homeGoals);
String homeName = mData.getString(ScoresDBHelper.HOME_COL_INDEX);
String awayName = mData.getString(ScoresDBHelper.AWAY_COL_INDEX);
String timeString = mData.getString(ScoresDBHelper.TIME_COL_INDEX);
String dateString = mData.getString(ScoresDBHelper.DATE_COL_INDEX);
String dateTimeString = timeString;
if (!TextUtils.isEmpty(dateString)) {
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(getString(R.string.date_format), Locale.getDefault());
Date date = simpleDateFormat.parse(dateString);
if (date != null) {
String dayName = Utilies.getDayName(date.getTime(), getString(R.string.today), getString(R.string.tomorrow), getString(R.string.yesterday));
dateTimeString = dayName + "\n" + timeString;
}
} catch (ParseException e) {
dateTimeString = dateString + "\n" + timeString;
}
}
views.setTextViewText(R.id.home_name, homeName);
views.setTextViewText(R.id.away_name, awayName);
views.setTextViewText(R.id.data_textview, dateTimeString);
views.setTextViewText(R.id.score_textview, scores);
views.setImageViewResource(R.id.home_crest, Utilies.getTeamCrestByTeamName(homeName));
views.setImageViewResource(R.id.away_crest, Utilies.getTeamCrestByTeamName(awayName));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
String description;
if (homeGoals < 0 || awayGoals < 0) {
description = homeName + " versus " + awayName + ", " + dateTimeString;
} else {
description = homeName + " " + homeGoals + ", " + awayName + " " + awayGoals + ". " + dateTimeString;
}
setRemoteContentDescription(views, description);
views.setContentDescription(R.id.home_crest, getString(R.string.home_crest_description));
views.setContentDescription(R.id.away_crest, getString(R.string.away_crest_description));
}
return views;
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)
private void setRemoteContentDescription(RemoteViews views, String description) {
views.setContentDescription(R.id.widget_list_item, description);
}
@Override
public RemoteViews getLoadingView() {
return new RemoteViews(getPackageName(), R.layout.widget_scores_list_item);
}
@Override
public int getViewTypeCount() {
return 1;
}
@Override
public long getItemId(int position) {
if (mData.moveToPosition(position)) {
return mData.getLong(ScoresDBHelper.MATCH_ID_COL_INDEX);
}
return position;
}
@Override
public boolean hasStableIds() {
return true;
}
};
}
} | 40.858209 | 168 | 0.571142 |
af65514e09b87b985827a3ab8fcd7d0ac610795a | 2,451 | package com.stylefeng.guns.modular.system.model;
import com.baomidou.mybatisplus.enums.IdType;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.activerecord.Model;
import com.baomidou.mybatisplus.annotations.TableName;
import java.io.Serializable;
/**
* <p>
*
* </p>
*
* @author lc
* @since 2018-08-15
*/
@TableName("t_user_info")
public class TUserInfo extends Model<TUserInfo> {
private static final long serialVersionUID = 1L;
/**
* 用户ID
*/
@TableId(value = "uid", type = IdType.AUTO)
private Long uid;
/**
* 用户名
*/
@TableField("user_name")
private String userName;
/**
* 用户的qq (账号)
*/
@TableField("user_qq")
private String userQq;
/**
* 用户的密码
*/
@TableField("user_password")
private String userPassword;
/**
* 用户的积分
*/
private Long integral;
/**
* 推荐用户
*/
@TableField("recommend_user")
private Long recommendUser;
public Long getRecommendUser() {
return recommendUser;
}
public void setRecommendUser(Long recommendUser) {
this.recommendUser = recommendUser;
}
public Long getUid() {
return uid;
}
public void setUid(Long uid) {
this.uid = uid;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserQq() {
return userQq;
}
public void setUserQq(String userQq) {
this.userQq = userQq;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public Long getIntegral() {
return integral;
}
public void setIntegral(Long integral) {
this.integral = integral;
}
@Override
protected Serializable pkVal() {
return this.uid;
}
@Override
public String toString() {
return "TUserInfo{" +
"uid=" + uid +
", userName='" + userName + '\'' +
", userQq='" + userQq + '\'' +
", userPassword='" + userPassword + '\'' +
", integral=" + integral +
", recommendUser=" + recommendUser +
'}';
}
}
| 20.596639 | 58 | 0.579355 |
5584ab69ab0308e2e225260d5b7bfffbb77407b1 | 1,498 | package com.dynatrace.loadrunner.config;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
public class UserConfig {
private final Mode mode;
private final Technology technology;
private final String path;
private final String[] body;
private final String[] header;
private final String lsn;
private UserConfig(Mode mode, Technology technology, String path, String[] body, String[] header, String lsn) {
this.mode = mode;
this.technology = technology;
this.path = path;
this.body = body;
this.header = header;
this.lsn = lsn;
}
public Mode getMode() {
return mode;
}
public Technology getTechnology() {
return technology;
}
public String getPath() {
return path;
}
public String[] getBody() {
return body;
}
public String[] getHeader() {
return header;
}
public String getLsn() {
return lsn;
}
public static UserConfig from(Map<Argument, String> arguments) {
Mode mode = Mode.from(arguments.keySet());
Technology technology = Technology.from(arguments.keySet());
String scriptName = arguments.get(Argument.SCRIPT_NAME);
String path = arguments.get(Argument.PATH);
String[] bodies = split(arguments.get(Argument.BODY));
String[] headers = split(arguments.get(Argument.HEADER));
return new UserConfig(mode, technology, path, bodies, headers, scriptName);
}
static String[] split(String argumentValue) {
if (StringUtils.isBlank(argumentValue)) {
return null;
}
return argumentValue.split("&");
}
}
| 22.029412 | 112 | 0.717623 |
af433ba961679727133fc715ea1b44f8f47c3814 | 279 | package br.sprintdev.model.service;
import br.sprintdev.model.entity.Event;
import java.util.List;
public interface EventService {
void create(Event box);
void update(Event box);
void delete(Long id);
Event findById(Long id);
List<Event> findAll();
}
| 14.684211 | 39 | 0.698925 |
f01cb52dd1fa702f9030cbe4a5e4bfc3eee85cc4 | 7,877 | /*
* Copyright 2018 Red Hat, Inc. and/or its affiliates.
*
* 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.kie.workbench.common.stunner.project.client.session;
import java.util.stream.IntStream;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.workbench.common.stunner.core.client.session.ClientSession;
import org.kie.workbench.common.stunner.core.client.session.command.ManagedClientSessionCommands;
import org.kie.workbench.common.stunner.core.client.session.command.impl.ClearSessionCommand;
import org.kie.workbench.common.stunner.core.client.session.command.impl.CopySelectionSessionCommand;
import org.kie.workbench.common.stunner.core.client.session.command.impl.CutSelectionSessionCommand;
import org.kie.workbench.common.stunner.core.client.session.command.impl.DeleteSelectionSessionCommand;
import org.kie.workbench.common.stunner.core.client.session.command.impl.ExportToBpmnSessionCommand;
import org.kie.workbench.common.stunner.core.client.session.command.impl.ExportToJpgSessionCommand;
import org.kie.workbench.common.stunner.core.client.session.command.impl.ExportToPdfSessionCommand;
import org.kie.workbench.common.stunner.core.client.session.command.impl.ExportToPngSessionCommand;
import org.kie.workbench.common.stunner.core.client.session.command.impl.ExportToSvgSessionCommand;
import org.kie.workbench.common.stunner.core.client.session.command.impl.PasteSelectionSessionCommand;
import org.kie.workbench.common.stunner.core.client.session.command.impl.RedoSessionCommand;
import org.kie.workbench.common.stunner.core.client.session.command.impl.SaveDiagramSessionCommand;
import org.kie.workbench.common.stunner.core.client.session.command.impl.SwitchGridSessionCommand;
import org.kie.workbench.common.stunner.core.client.session.command.impl.UndoSessionCommand;
import org.kie.workbench.common.stunner.core.client.session.command.impl.ValidateSessionCommand;
import org.kie.workbench.common.stunner.core.client.session.command.impl.VisitGraphSessionCommand;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class EditorSessionCommandsTest {
@Mock
protected ManagedClientSessionCommands commands;
@Mock
protected ClientSession session;
protected EditorSessionCommands editorSessionCommands;
@Before
@SuppressWarnings("unchecked")
public void setup() {
this.editorSessionCommands = makeEditorSessionCommands();
when(commands.register(any(Class.class))).thenReturn(commands);
}
protected EditorSessionCommands makeEditorSessionCommands() {
return new EditorSessionCommands(commands);
}
@Test
public void testInit() {
editorSessionCommands.init();
final InOrder inOrder = inOrder(commands);
inOrder.verify(commands).register(VisitGraphSessionCommand.class);
inOrder.verify(commands).register(SwitchGridSessionCommand.class);
inOrder.verify(commands).register(ClearSessionCommand.class);
inOrder.verify(commands).register(DeleteSelectionSessionCommand.class);
inOrder.verify(commands).register(UndoSessionCommand.class);
inOrder.verify(commands).register(RedoSessionCommand.class);
inOrder.verify(commands).register(ValidateSessionCommand.class);
inOrder.verify(commands).register(ExportToPngSessionCommand.class);
inOrder.verify(commands).register(ExportToJpgSessionCommand.class);
inOrder.verify(commands).register(ExportToPdfSessionCommand.class);
inOrder.verify(commands).register(ExportToSvgSessionCommand.class);
inOrder.verify(commands).register(ExportToBpmnSessionCommand.class);
inOrder.verify(commands).register(CopySelectionSessionCommand.class);
inOrder.verify(commands).register(PasteSelectionSessionCommand.class);
inOrder.verify(commands).register(CutSelectionSessionCommand.class);
inOrder.verify(commands).register(SaveDiagramSessionCommand.class);
}
@Test
public void testBind() {
editorSessionCommands.bind(session);
verify(commands).bind(session);
}
@Test
public void testGetCommands() {
assertEquals(commands, editorSessionCommands.getCommands());
}
@Test
public void testGetVisitGraphSessionCommand() {
editorSessionCommands.getVisitGraphSessionCommand();
verify(commands).get(0);
}
@Test
public void testGetSwitchGridSessionCommand() {
editorSessionCommands.getSwitchGridSessionCommand();
verify(commands).get(1);
}
@Test
public void testGetClearSessionCommand() {
editorSessionCommands.getClearSessionCommand();
verify(commands).get(2);
}
@Test
public void testGetDeleteSelectionSessionCommand() {
editorSessionCommands.getDeleteSelectionSessionCommand();
verify(commands).get(3);
}
@Test
public void testGetUndoSessionCommand() {
editorSessionCommands.getUndoSessionCommand();
verify(commands).get(4);
}
@Test
public void testGetRedoSessionCommand() {
editorSessionCommands.getRedoSessionCommand();
verify(commands).get(5);
}
@Test
public void testGetValidateSessionCommand() {
editorSessionCommands.getValidateSessionCommand();
verify(commands).get(6);
}
@Test
public void testGetExportToPngSessionCommand() {
editorSessionCommands.getExportToPngSessionCommand();
verify(commands).get(7);
}
@Test
public void testGetExportToJpgSessionCommand() {
editorSessionCommands.getExportToJpgSessionCommand();
verify(commands).get(8);
}
@Test
public void testGetExportToPdfSessionCommand() {
editorSessionCommands.getExportToPdfSessionCommand();
verify(commands).get(9);
}
@Test
public void testGetExportToSvgSessionCommand() {
editorSessionCommands.getExportToSvgSessionCommand();
verify(commands).get(10);
}
@Test
public void testGetExportToBpmnSessionCommand() {
editorSessionCommands.getExportToBpmnSessionCommand();
verify(commands).get(11);
}
@Test
public void testGetCopySelectionSessionCommand() {
editorSessionCommands.getCopySelectionSessionCommand();
verify(commands).get(12);
}
@Test
public void testGetPasteSelectionSessionCommand() {
editorSessionCommands.getPasteSelectionSessionCommand();
verify(commands).get(13);
}
@Test
public void testGetCutSelectionSessionCommand() {
editorSessionCommands.getCutSelectionSessionCommand();
verify(commands).get(14);
}
@Test
public void testGetSaveDiagramSessionCommand() {
editorSessionCommands.getSaveDiagramSessionCommand();
verify(commands).get(15);
}
@Test
public void testGet() {
IntStream.range(0, 15).forEach(i -> {
editorSessionCommands.get(i);
verify(commands).get(i);
});
}
}
| 34.247826 | 103 | 0.746096 |
d4a45d70a2109c7505c54429d0ced8fdfdf61e54 | 93 | package annotation;
@FunctionalInterface
public interface AD {
public void adAttack();
} | 15.5 | 27 | 0.763441 |
5031d06b70540fa35f8520a46edbf360f24ac1d5 | 1,319 | /*
* Copyright 2017 Sage Bionetworks
*
* 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.sagebase.crf.step.active;
import com.google.common.base.MoreObjects;
/**
* Created by TheMDP on 10/17/17.
*/
public class HeartBeatSample {
public double t;
public float r;
public float g;
public float b;
public float h;
public float s;
public float v;
public int bpm;
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("t", t)
.add("r", r)
.add("g", g)
.add("b", b)
.add("h", h)
.add("s", s)
.add("v", v)
.add("bpm", bpm)
.toString();
}
}
| 26.38 | 78 | 0.585292 |
0434ef299032ca896de2b7a9294d7d9ee1c62b18 | 1,120 | package org.ovirt.engine.core.common.queries;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
//C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes:
@XmlAccessorType(XmlAccessType.NONE)
@XmlType(name = "GetTagByTagNameParametersBase")
public class GetTagByTagNameParametersBase extends VdcQueryParametersBase {
private static final long serialVersionUID = -4620515574262550994L;
public GetTagByTagNameParametersBase(String tagName) {
_tagName = tagName;
}
// C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to
// .NET attributes:
@XmlElement(name = "TagName")
private String _tagName;
public String getTagName() {
return _tagName;
}
@Override
public RegisterableQueryReturnDataType GetReturnedDataTypeByVdcQueryType(VdcQueryType queryType) {
return RegisterableQueryReturnDataType.UNDEFINED;
}
public GetTagByTagNameParametersBase() {
}
}
| 32 | 102 | 0.765179 |
d040f43f6fe269bb5b70405b8ec4c1f18638bfdc | 1,694 | package com.jivesoftware.os.miru.plugin.context;
import com.jivesoftware.os.filer.io.StripingLocksProvider;
import com.jivesoftware.os.miru.api.activity.schema.MiruSchema;
import com.jivesoftware.os.miru.api.base.MiruStreamId;
import com.jivesoftware.os.miru.api.wal.MiruSipCursor;
import com.jivesoftware.os.miru.plugin.cache.MiruPluginCacheProvider;
import com.jivesoftware.os.miru.plugin.index.MiruActivityIndex;
import com.jivesoftware.os.miru.plugin.index.MiruAuthzIndex;
import com.jivesoftware.os.miru.plugin.index.MiruFieldIndexProvider;
import com.jivesoftware.os.miru.plugin.index.MiruInboxIndex;
import com.jivesoftware.os.miru.plugin.index.MiruRemovalIndex;
import com.jivesoftware.os.miru.plugin.index.MiruSipIndex;
import com.jivesoftware.os.miru.plugin.index.MiruTermComposer;
import com.jivesoftware.os.miru.plugin.index.MiruTimeIndex;
import com.jivesoftware.os.miru.plugin.index.MiruUnreadTrackingIndex;
/**
* @author jonathan
*/
public interface MiruRequestContext<BM extends IBM, IBM, S extends MiruSipCursor<S>> {
MiruSchema getSchema();
MiruTermComposer getTermComposer();
MiruTimeIndex getTimeIndex();
MiruActivityIndex getActivityIndex();
MiruFieldIndexProvider<BM, IBM> getFieldIndexProvider();
MiruSipIndex<S> getSipIndex();
MiruPluginCacheProvider<BM, IBM> getCacheProvider();
MiruAuthzIndex<BM, IBM> getAuthzIndex();
MiruRemovalIndex<BM, IBM> getRemovalIndex();
MiruUnreadTrackingIndex<BM, IBM> getUnreadTrackingIndex();
MiruInboxIndex<BM, IBM> getInboxIndex();
StripingLocksProvider<MiruStreamId> getStreamLocks();
boolean isClosed();
boolean hasChunkStores();
boolean hasLabIndex();
}
| 31.962264 | 86 | 0.795159 |
a57124580341a6c925382946f13a6b7349794fa6 | 1,178 | package com.cordys.uiunit.eastwind;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import com.cordys.uiunit.eastwind.runtime.AclForWebServices;
import com.cordys.uiunit.eastwind.runtime.AssignOrgTeamToUser;
import com.cordys.uiunit.eastwind.runtime.CageManagerSalesRepWL;
import com.cordys.uiunit.eastwind.runtime.CageSalesCoordinatorInbox;
import com.cordys.uiunit.eastwind.runtime.CustomerNotification;
import com.cordys.uiunit.eastwind.runtime.KingSalesRepInbox;
import com.cordys.uiunit.eastwind.runtime.LauraPersonalTaskInbox;
import com.cordys.uiunit.eastwind.runtime.PlaceOrder;
import com.cordys.uiunit.eastwind.runtime.ProjectRuntimeOrganizer;
import com.cordys.uiunit.eastwind.runtime.UserManager;
@RunWith(Suite.class)
@SuiteClasses({
ProjectRuntimeOrganizer.class,
AclForWebServices.class,
UserManager.class,
AssignOrgTeamToUser.class,
PlaceOrder.class,
CageSalesCoordinatorInbox.class,
LauraPersonalTaskInbox.class,
CageManagerSalesRepWL.class,
KingSalesRepInbox.class,
CustomerNotification.class
})
public class EastWindRuntimeAfterPublishToOrg {
}
| 32.722222 | 69 | 0.825976 |
7e601c1c0d35a175b830bf992647bb95ccc0ae49 | 926 | import java.util.HashSet;
import java.util.Set;
/*
Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.
This is case sensitive, for example "Aa" is not considered a palindrome here.
Input:
"abccccdd"
Output:
7
Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.
*/
class LongestPalindromeBuild {
public int longestPalindrome(String s) {
int count = 0;
Set<Character> set = new HashSet<>();
for (int i = 0; i < s.length(); i++) {
if(set.contains(s.charAt(i))){
set.remove(s.charAt(i));
count ++;
}else {
set.add(s.charAt(i));
}
}
//odd number
if(set.size() > 0) count = count * 2 + 1;
else count = count * 2;
return count;
}
}
| 23.74359 | 145 | 0.578834 |
e7d11384ee9db73f6d37771d3a5bac0a9c1aae4c | 1,325 | package io.perfmark;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
@State(Scope.Benchmark)
public class EnabledBenchmark {
private final Tag TAG = new Tag("tag", 2);
@Param({"true", "false"})
public boolean enabled;
@Setup
public void setup() {
PerfMark.setEnabled(enabled);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void startStop() {
PerfMark.startTask("hi", TAG);
PerfMark.stopTask("hi", TAG);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public Tag createTag() {
return PerfMark.createTag("tag", 2);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void link() {
Link link = PerfMark.linkOut();
PerfMark.linkIn(link);
}
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public void event() {
PerfMark.event("hi", TAG);
}
}
| 24.090909 | 50 | 0.737358 |
afdf9fa18e55423244d2bf5541d2766b9e948900 | 2,800 | package io.avaje.inject.spi;
import io.avaje.inject.BeanEntry;
import jakarta.inject.Provider;
import java.util.Objects;
/**
* Holds either the bean itself or a provider of the bean.
*/
class DContextEntryBean {
/**
* Create taking into account if it is a Provider or the bean itself.
*
* @param bean The bean itself or provider of the bean
* @param name The optional name for the bean
* @param flag The flag for primary, secondary or normal
*/
static DContextEntryBean of(Object bean, String name, int flag) {
if (bean instanceof Provider) {
return new Prov((Provider<?>)bean, name, flag);
} else {
return new DContextEntryBean(bean, name, flag);
}
}
static DContextEntryBean provider(Provider<?> provider, String name, int flag) {
return new Prov(provider, name, flag);
}
protected final Object source;
private final String name;
private final int flag;
private DContextEntryBean(Object source, String name, int flag) {
this.source = source;
this.name = KeyUtil.lower(name);
this.flag = flag;
}
@Override
public final String toString() {
return "Bean{" +
"source=" + source +
", name='" + name + '\'' +
", flag=" + flag +
'}';
}
final DEntry entry() {
return new DEntry(name, flag, bean());
}
/**
* Return true if qualifierName is null or matched.
*/
final boolean isNameMatch(String qualifierName) {
return qualifierName == null || qualifierName.equals(name);
}
/**
* Return true if qualifierName is matched including null.
*/
final boolean isNameEqual(String qualifierName) {
return Objects.equals(qualifierName, name);
}
/**
* Return the bean if name matches and otherwise null.
*/
Object beanIfNameMatch(String name) {
return isNameMatch(name) ? bean() : null;
}
Object bean() {
return source;
}
Provider<?> provider() {
return this::bean;
}
final boolean isPrimary() {
return flag == BeanEntry.PRIMARY;
}
final boolean isSecondary() {
return flag == BeanEntry.SECONDARY;
}
final boolean isSupplied() {
return flag == BeanEntry.SUPPLIED;
}
final boolean isSupplied(String qualifierName) {
return flag == BeanEntry.SUPPLIED && (qualifierName == null || qualifierName.equals(name));
}
/**
* Provider based entry - provider controls the scope of the provided bean.
*/
static final class Prov extends DContextEntryBean {
private final Provider<?> provider;
private Prov(Provider<?> provider, String name, int flag) {
super(provider, name, flag);
this.provider = provider;
}
@Override
Provider<?> provider() {
return provider;
}
@Override
Object bean() {
return provider.get();
}
}
}
| 22.764228 | 95 | 0.648929 |
a1eb92f58b7a4c8b6216a12d67996d60c8cd3645 | 1,787 | /*_############################################################################
_##
_## SNMP4J 2 - UdpAddress.java
_##
_## Copyright (C) 2003-2016 Frank Fock and Jochen Katz (SNMP4J.org)
_##
_## Licensed under the Apache License, Version 2.0 (the "License");
_## you may not use this file except in compliance with the License.
_## You may obtain a copy of the License at
_##
_## http://www.apache.org/licenses/LICENSE-2.0
_##
_## Unless required by applicable law or agreed to in writing, software
_## distributed under the License is distributed on an "AS IS" BASIS,
_## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
_## See the License for the specific language governing permissions and
_## limitations under the License.
_##
_##########################################################################*/
package org.snmp4j.smi;
import java.net.InetAddress;
/**
* The <code>UdpAddress</code> represents UDP/IP transport addresses.
* @author Frank Fock
* @version 1.8.3
*/
public class UdpAddress extends TransportIpAddress {
static final long serialVersionUID = -4390734262648716203L;
public UdpAddress() {
}
public UdpAddress(InetAddress inetAddress, int port) {
setInetAddress(inetAddress);
setPort(port);
}
public UdpAddress(int port) {
setPort(port);
}
public UdpAddress(String address) {
if (!parseAddress(address)) {
throw new IllegalArgumentException(address);
}
}
public static Address parse(String address) {
UdpAddress a = new UdpAddress();
if (a.parseAddress(address)) {
return a;
}
return null;
}
public boolean equals(Object o) {
return (o instanceof UdpAddress) && super.equals(o);
}
}
| 27.492308 | 79 | 0.620593 |
5d3265e8b76b39ef7651bb625591ac6b2716d918 | 1,807 | /*
* Copyright 2013-2021 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
*
* 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 org.springframework.cloud.sleuth.brave.instrument.redis;
import io.lettuce.core.resource.ClientResources;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Configuration;
import static org.assertj.core.api.BDDAssertions.then;
/**
* @author Chao Chang
*/
@SpringBootTest(classes = BraveRedisAutoConfigurationTests.Config.class,
webEnvironment = SpringBootTest.WebEnvironment.NONE, properties = { "spring.sleuth.redis.enabled=true",
"spring.sleuth.redis.legacy.enabled=true", "spring.sleuth.redis.remote-service-name=redis-foo" })
class BraveRedisAutoConfigurationTests {
@Autowired
ClientResources clientResources;
@Autowired
TraceLettuceClientResourcesBuilderCustomizer customizer;
@Test
void tracing_should_be_set() {
then(this.clientResources.tracing().isEnabled()).isTrue();
then(this.customizer).isNotNull();
}
@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
protected static class Config {
}
}
| 32.267857 | 105 | 0.785833 |
554cecabb96645bd5859470a756becec95447341 | 5,037 | /*
* Copyright © 2015 <code@io7m.com> http://io7m.com
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
* IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package com.io7m.jcage.examples.sandboxed_1;
import com.io7m.jcage.core.JCClassLoaderPolicyType;
import com.io7m.jcage.core.JCClassLoaderPolicyUnrestricted;
import com.io7m.jcage.core.JCClassNameResolverClasspath;
import com.io7m.jcage.core.JCClassNameResolverType;
import com.io7m.jcage.core.JCSandboxType;
import com.io7m.jcage.core.JCSandboxes;
import com.io7m.jcage.core.JCSandboxesType;
import com.io7m.jnull.NullCheck;
import com.io7m.jnull.Nullable;
import java.io.FilePermission;
import java.lang.reflect.Constructor;
import java.security.AccessController;
import java.security.Permissions;
import java.security.PrivilegedAction;
/**
* An example program that starts various sandboxes and demonstrates the
* isolation of the code within.
*/
public final class SandboxerMain
{
private SandboxerMain()
{
}
/**
* Main program.
*
* @param args Command line arguments
*
* @throws Exception On errors
*/
public static void main(
final String[] args)
throws Exception
{
/**
* Retrieve access to the sandbox administration interface. This
* registers a security manager if required, and also performs an
* access check to prevent sandboxed code from trying to get access
* to the interface.
*/
final JCSandboxesType ss = JCSandboxes.get();
/**
* Get access to the system classloader and create a policy that indicates
* that it is allowed to load any classes it wants.
*/
final ClassLoader host_classloader = ClassLoader.getSystemClassLoader();
final JCClassLoaderPolicyType host_classloader_policy =
JCClassLoaderPolicyUnrestricted.get();
/**
* Create a class resolver that can load classes from the classpath
* on behalf of the sandbox.
*/
final JCClassNameResolverType sandbox_class_resolver =
JCClassNameResolverClasspath.get();
/**
* Create a policy that denies the sandbox from loading any classes
* except for the single Sandboxed class.
*/
final String sandboxed_name = Sandboxed.class.getCanonicalName();
final JCClassLoaderPolicyType sandbox_class_policy =
new JCClassLoaderPolicyType()
{
@Override public boolean policyAllowsResource(
final String name)
{
return false;
}
@Override public boolean policyAllowsClass(
final String name)
{
return name.startsWith(sandboxed_name);
}
};
/**
* Create a new sandbox called "example" that has no permissions.
*/
final JCSandboxType s = ss.createSandbox(
"example",
host_classloader,
host_classloader_policy,
sandbox_class_resolver,
sandbox_class_policy,
new Permissions());
/**
* Get access to a sandbox-loaded class. Instantiate it, and execute it.
*/
@SuppressWarnings("unchecked") final Class<Runnable> c =
(Class<Runnable>) s.getSandboxLoadedClass(sandboxed_name);
final Constructor<Runnable> cc =
c.getConstructor(SandboxListenerType.class);
/**
* A function evaluated by sandboxed code that demonstrates how
* sandboxed code can be granted temporary privileges with
* `AccessController.doPrivileged`.
*/
final SandboxListenerType listener = new SandboxListenerType()
{
@Override public void onMessageReceived(
final String m)
{
System.out.println("Listener: received: " + m);
AccessController.doPrivileged(
new PrivilegedAction<Void>()
{
@Override public @Nullable Void run()
{
System.out.println(
"Listener: Attempting to perform privileged operation");
final SecurityManager sm =
NullCheck.notNull(System.getSecurityManager());
sm.checkPermission(new FilePermission("/tmp/z", "write"));
System.out.println("Listener: Performed privileged operation");
return null;
}
});
}
};
final Runnable r = cc.newInstance(listener);
System.out.println("Running sandboxed code...");
r.run();
System.out.println("Finished running sandboxed code.");
}
}
| 30.713415 | 78 | 0.687115 |
9755947beaaa00c37cc749f0804770fcbe31cf87 | 3,825 | package org.aries.service;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
//import nam.model.Service;
import org.aries.Assert;
import org.aries.runtime.BeanContext;
import org.aries.service.model.ServiceMap;
import org.aries.util.ReflectionUtil;
public class ServiceRepositoryImpl implements ServiceRepository {
//private static Log log = LogFactory.getLog(ServiceRepository.class);
//private ApplicationProfile applicationProfile;
private ServiceMap serviceInstances;
private Map<String, Object> serviceDescripters;
private Object mutex = new Object();
public ServiceRepositoryImpl() {
serviceInstances = new ServiceMap();
serviceDescripters = new HashMap<String, Object>();
}
@Override
public Collection<String> getServiceIds() {
synchronized (mutex) {
ArrayList<String> list = new ArrayList<String>(serviceInstances.getServices().keySet());
return list;
}
}
@Override
public Object getServiceDescripter(String serviceId) {
synchronized (mutex) {
return serviceDescripters.get(serviceId);
}
}
@Override
public Collection<Object> getServiceDescripters() {
synchronized (mutex) {
Collection<Object> list = Collections.unmodifiableCollection(serviceDescripters.values());
return list;
}
}
// @Override
// public String getServiceMethod(String serviceId) {
// ServiceDescripter serviceDescripter = getServiceDescripter(serviceId);
// if (serviceDescripter != null && serviceDescripter.getMethodName() != null)
// return serviceDescripter.getMethodName();
// ProcessDescripter processDescripter = serviceDescripter.getProcessDescripters().get(0);
// if (processDescripter != null && processDescripter.getProcessName() != null)
// return processDescripter.getProcessName();
// return ServiceDescripter.DEFAULT_SERVICE_METHOD;
// }
@Override
public Collection<Object> getServiceInstances() {
synchronized (mutex) {
Collection<Object> list = Collections.unmodifiableCollection(serviceInstances.getServices().values());
return list;
}
}
@Override
public Object getServiceInstance(String serviceId) {
synchronized (mutex) {
Object serviceInstance = serviceInstances.getService(serviceId);
if (serviceInstance == null) {
try {
serviceInstance = BeanContext.get(serviceId);
serviceInstances.addService(serviceId, serviceInstance);
} catch (Throwable e) {
//ignore
}
}
Assert.notNull(serviceInstance, "Service not found: "+serviceId);
return serviceInstance;
}
}
@Override
public void addServiceInstance(String serviceId, Object serviceDescripter, Object serviceInstance) {
synchronized (mutex) {
serviceInstances.addService(serviceId, serviceInstance);
serviceDescripters.put(serviceId, serviceDescripter);
}
}
@Override
public void removeServiceInstance(String serviceId) {
synchronized (mutex) {
serviceInstances.removeService(serviceId);
}
}
public void close() {
synchronized (mutex) {
Map<String, Object> services = serviceInstances.getServices();
Iterator<Object> iterator = services.values().iterator();
while (iterator.hasNext()) {
Object service = iterator.next();
close(service);
}
}
}
//TODO move this to shared class
protected void close(Object service) {
try {
String methodName = "close";
Class<?>[] parameterTypes = new Class<?>[] {};
Object[] parameterValues = new Object[] {};
Class<?> resultType = void.class;
Method method = ReflectionUtil.findMethod(service.getClass(), methodName, parameterTypes, resultType);
ReflectionUtil.invokeMethod(service, method, parameterValues);
} catch (Throwable e) {
//ignore
}
}
}
| 27.717391 | 105 | 0.736993 |
0bdfd6baee999bee0134c350feb4aefae131916a | 2,999 | package E03SetsAndMapsAdvanced;
import java.util.Collections;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
public class E11LegendaryFarming {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Map<String, Integer> materials = new TreeMap<>();
materials.put("shards", 0);
materials.put("fragments", 0);
materials.put("motes", 0);
Map<String, Integer> junkMaterials = new TreeMap<>();
boolean legendaryItemObtained = false;
while (!legendaryItemObtained) {
String[] tokens = scanner.nextLine().split("\\s+");
for (int i = 0; i < tokens.length; i += 2) {
int quantity = Integer.parseInt(tokens[i]);
String material = tokens[i + 1].toLowerCase();
switch (material) {
case "shards":
materials.put(material, materials.get(material) + quantity);
if (materials.get("shards") >= 250) {
materials.put("shards", materials.get("shards") - 250);
legendaryItemObtained = true;
System.out.println("Shadowmourne obtained!");
}
break;
case "fragments":
materials.put(material, materials.get(material) + quantity);
if (materials.get("fragments") >= 250) {
materials.put("fragments", materials.get("fragments") - 250);
legendaryItemObtained = true;
System.out.println("Valanyr obtained!");
}
break;
case "motes":
materials.put(material, materials.get(material) + quantity);
if (materials.get("motes") >= 250) {
materials.put("motes", materials.get("motes") - 250);
legendaryItemObtained = true;
System.out.println("Dragonwrath obtained!");
}
break;
default:
junkMaterials.putIfAbsent(material, 0);
junkMaterials.put(material, junkMaterials.get(material) + quantity);
break;
}
if (legendaryItemObtained) {
break;
}
}
}
materials.entrySet().stream().sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
.forEach(entry -> System.out.println(entry.getKey() + ": " + entry.getValue()));
for (var junk : junkMaterials.entrySet()) {
System.out.println(junk.getKey() + ": " + junk.getValue());
}
}
} | 42.239437 | 101 | 0.473158 |
4f2b877363a1bfca8284373e54708c7a8c9b005d | 1,022 |
package mage.cards.s;
import mage.abilities.effects.common.CreateTokenEffect;
import mage.abilities.keyword.SpliceOntoArcaneAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.game.permanent.token.SpiritToken;
import java.util.UUID;
/**
*
* @author LevelX2
*/
public final class SpiritualVisit extends CardImpl {
public SpiritualVisit(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.INSTANT},"{W}");
this.subtype.add(SubType.ARCANE);
// Create a 1/1 colorless Spirit creature token.
this.getSpellAbility().addEffect(new CreateTokenEffect(new SpiritToken()));
// Splice onto Arcane {W}
this.addAbility(new SpliceOntoArcaneAbility("{W}"));
}
public SpiritualVisit(final SpiritualVisit card) {
super(card);
}
@Override
public SpiritualVisit copy() {
return new SpiritualVisit(this);
}
}
| 25.55 | 83 | 0.706458 |
da584e1eb39f1efc2e10e53baecc035d1985de27 | 13,125 | /*
* Copyright 2010-2010 LinkedIn, 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.linkedin.zookeeper.tracker;
import org.slf4j.Logger;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.linkedin.util.annotations.Initializable;
import org.linkedin.util.clock.Clock;
import org.linkedin.util.clock.ClockUtils;
import org.linkedin.util.clock.SystemClock;
import org.linkedin.util.concurrent.ConcurrentUtils;
import org.linkedin.util.io.PathUtils;
import org.linkedin.util.lang.LangUtils;
import org.linkedin.util.lifecycle.Destroyable;
import org.linkedin.zookeeper.client.IZKClient;
import org.linkedin.zookeeper.client.ZKChildren;
import org.linkedin.zookeeper.client.ZKData;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeoutException;
/**
* The purpose of this class is to essentially keep a replica of ZooKeeper data in memory and
* be able to be notified when it changes.
*
* @author ypujante@linkedin.com */
public class ZooKeeperTreeTracker<T> implements Destroyable
{
public static final String MODULE = ZooKeeperTreeTracker.class.getName();
public static final Logger log = org.slf4j.LoggerFactory.getLogger(MODULE);
@Initializable
public Clock clock = SystemClock.INSTANCE;
private final IZKClient _zk;
private final ZKDataReader<T> _zkDataReader;
private final String _root;
private final int _depth;
private final Set<ErrorListener> _errorListeners = new LinkedHashSet<ErrorListener>();
private final Set<NodeEventsListener<T>> _eventsListeners = new LinkedHashSet<NodeEventsListener<T>>();
private volatile Map<String, TrackedNode<T>> _tree = new LinkedHashMap<String, TrackedNode<T>>();
private volatile boolean _destroyed = false;
private long _lastZkTxId;
private final Object _lock = new Object();
private final int _rootDepth;
private final Watcher _treeWacher = new TreeWatcher();
private class TreeWatcher implements Watcher
{
@Override
public void process(WatchedEvent event)
{
if(log.isDebugEnabled())
log.debug(logString(event.getPath(),
"treeWatcher: type=" + event.getType()) + ", state=" + event.getState());
Collection<NodeEvent<T>> events = new ArrayList<NodeEvent<T>>();
try
{
synchronized(_lock)
{
if(!handleEvent(event))
return;
switch(event.getType())
{
case NodeDeleted:
_tree = handleNodeDeleted(event.getPath(), events);
break;
case NodeCreated:
throw new RuntimeException("getting node created event ? when ?");
case NodeChildrenChanged:
_tree = handleNodeChildrenChanged(event.getPath(), events);
break;
case NodeDataChanged:
_tree = handleNodeDataChanged(event.getPath(), events);
break;
case None:
// nothing to do
break;
}
}
raiseEvents(events);
}
catch (Throwable th)
{
log.warn(logString(event.getPath(), "Error in treeWatcher (ignored)"), th);
raiseError(event, th);
}
}
}
public ZooKeeperTreeTracker(IZKClient zk, ZKDataReader<T> zkDataReader, String root)
{
this(zk, zkDataReader, root, Integer.MAX_VALUE);
}
public ZooKeeperTreeTracker(IZKClient zk, ZKDataReader<T> zkDataReader, String root, int depth)
{
_zk = zk;
_zkDataReader = zkDataReader;
_root = root;
_rootDepth = computeAbsoluteDepth(_root);
_depth = depth;
}
public static int computeAbsoluteDepth(String path)
{
if(path == null)
return 0;
int depth = 0;
for(int i = 0; i < path.length(); i++)
{
char c = path.charAt(i);
if(c == '/')
depth++;
}
return depth;
}
public String getRoot()
{
return _root;
}
public IZKClient getZKCient()
{
return _zk;
}
public int getDepth()
{
return _depth;
}
public long getLastZkTxId()
{
synchronized(_lock)
{
return _lastZkTxId;
}
}
/**
* Waits no longer than the timeout provided (or forever if <code>null</code>) for this tracker
* to have seen at least the provided zookeeper transaction id
* @return the last known zkTxId (guaranteed to be >= to zkTxId)
*/
public long waitForZkTxId(long zkTxId, Object timeout)
throws TimeoutException, InterruptedException
{
long endTime = ClockUtils.toEndTime(clock, timeout);
synchronized(_lock)
{
while(_lastZkTxId < zkTxId)
{
ConcurrentUtils.awaitUntil(clock, _lock, endTime);
}
return _lastZkTxId;
}
}
/**
* It is not possible to remove a watcher... so we just set the tracker in destroyed mode which
* will simply ignore all subsequent event.
*/
@Override
public void destroy()
{
synchronized(_lock)
{
_destroyed = true;
}
}
/**
* @return the tree
*/
public Map<String, TrackedNode<T>> getTree()
{
// note that there is no need for synchronization because:
// 1. the attribute is volatile
// 2. the map is never modified (a new one is created / replaced when needed)
return _tree;
}
public void track(NodeEventsListener<T> eventsListener)
throws InterruptedException, KeeperException
{
registerListener(eventsListener);
track();
}
public void track() throws InterruptedException, KeeperException
{
Collection<NodeEvent<T>> events = new ArrayList<NodeEvent<T>>();
synchronized(_lock)
{
_tree = trackNode(_root, new LinkedHashMap<String, TrackedNode<T>>(), events, 0);
}
raiseEvents(events);
}
public void registerListener(NodeEventsListener<T> eventsListener)
{
synchronized(_lock)
{
_eventsListeners.add(eventsListener);
}
}
public void registerErrorListener(ErrorListener errorListener)
{
synchronized(_lock)
{
_errorListeners.add(errorListener);
}
}
/**
* Must be called from a synchronized section
*/
private Map<String, TrackedNode<T>> trackNode(String path,
Map<String, TrackedNode<T>> tree,
Collection<NodeEvent<T>> events,
int depth)
throws InterruptedException, KeeperException
{
if(depth > _depth)
{
if(log.isDebugEnabled())
log.debug(logString(path, "max depth reached ${depth}"));
return tree;
}
TrackedNode<T> oldTrackedNode = tree.get(path);
try
{
ZKData<T> res = _zkDataReader.readData(_zk, path, _treeWacher);
TrackedNode<T> newTrackedNode =
new TrackedNode<T>(path, res.getData(), res.getStat(), depth);
if(oldTrackedNode != null)
{
if(!_zkDataReader.isEqual(oldTrackedNode.getData(), newTrackedNode.getData()))
{
events.add(new NodeEvent<T>(NodeEventType.UPDATED,
newTrackedNode));
}
}
else
{
events.add(new NodeEvent<T>(NodeEventType.ADDED,
newTrackedNode));
}
tree.put(path, newTrackedNode);
if(depth < _depth)
{
ZKChildren children = _zk.getZKChildren(path, _treeWacher);
// the stat may change between the 2 calls
if(!newTrackedNode.getStat().equals(children.getStat()))
newTrackedNode.setStat(children.getStat());
Collections.sort(children.getChildren());
for(String child : children.getChildren())
{
String childPath = PathUtils.addPaths(path, child);
if(!tree.containsKey(childPath))
trackNode(childPath, tree, events, depth + 1);
}
}
_lastZkTxId = Math.max(_lastZkTxId, newTrackedNode.getZkTxId());
_lock.notifyAll();
if(log.isDebugEnabled())
log.debug(logString(path,
"start tracking " + (depth < _depth ? "": "leaf ") +
"node zkTxId=" + newTrackedNode.getZkTxId()));
}
catch (KeeperException.NoNodeException e)
{
// this is a race condition which could happen between the moment the event is received
// and this call
if(log.isDebugEnabled())
log.debug(logString(path, "no such node"));
// it means that the node has disappeared
tree.remove(path);
if(oldTrackedNode != null)
{
events.add(new NodeEvent<T>(NodeEventType.DELETED,
oldTrackedNode));
}
}
return tree;
}
private Map<String, TrackedNode<T>> handleNodeDeleted(String path,
Collection<NodeEvent<T>> events)
throws InterruptedException, KeeperException
{
Map<String, TrackedNode<T>> tree = _tree;
if(_tree.containsKey(path))
{
tree = new LinkedHashMap<String, TrackedNode<T>>(_tree);
TrackedNode<T> trackedNode = tree.remove(path);
events.add(new NodeEvent<T>(NodeEventType.DELETED,
trackedNode));
if(log.isDebugEnabled())
log.debug(logString(path, "stop tracking node"));
// after a delete event, we try to track the node again as a delete/add event could happen
// and be undetected otherwise!
trackNode(path, tree, events, trackedNode.getDepth());
}
return tree;
}
private Map<String, TrackedNode<T>> handleNodeDataChanged(String path,
Collection<NodeEvent<T>> events)
throws InterruptedException, KeeperException
{
return trackNode(path,
new LinkedHashMap<String, TrackedNode<T>>(_tree),
events,
computeDepth(path));
}
private Map<String, TrackedNode<T>> handleNodeChildrenChanged(String path,
Collection<NodeEvent<T>> events)
throws InterruptedException, KeeperException
{
return trackNode(path,
new LinkedHashMap<String, TrackedNode<T>>(_tree),
events,
computeDepth(path));
}
private int computeDepth(String path)
{
return computeAbsoluteDepth(path) - _rootDepth;
}
private void raiseEvents(Collection<NodeEvent<T>> events)
{
if(!events.isEmpty())
{
Set<NodeEventsListener<T>> listeners;
synchronized(_lock)
{
listeners = new LinkedHashSet<NodeEventsListener<T>>(_eventsListeners);
}
for(NodeEventsListener<T> listener : listeners)
{
listener.onEvents(events);
}
}
}
private boolean handleEvent(WatchedEvent event)
{
if(_destroyed)
{
return false;
}
switch(event.getState())
{
case SyncConnected:
return true;
case Disconnected:
return false;
case Expired:
return false;
default:
return false;
}
}
private String logString(String path, String msg)
{
StringBuilder sb = new StringBuilder();
sb.append("[").append(path).append("] ");
sb.append("[").append(LangUtils.shortIdentityString(this)).append("] ");
sb.append("[").append(Thread.currentThread()).append("] ");
sb.append(msg);
return sb.toString();
}
private void raiseError(WatchedEvent event, Throwable th)
{
Set<ErrorListener> listeners;
synchronized(_lock)
{
listeners = new LinkedHashSet<ErrorListener>(_errorListeners);
}
if(!listeners.isEmpty())
{
for(ErrorListener listener : listeners)
{
try
{
if(log.isDebugEnabled())
log.debug(logString(event.getPath(), "Raising error to " +
LangUtils.identityString(listener)),
th);
listener.onError(event, th);
}
catch(Throwable th2)
{
log.warn(logString(event.getPath(), "Error in watcher while executing listener " +
LangUtils.identityString(listener) +
" (ignored)"),
th2);
}
}
}
}
}
| 27.807203 | 105 | 0.6176 |
18f90f94bb1505a7d30dcd30a3d9cd96bc5941e0 | 2,484 | package br.ufg.inf.oop.internshipcandidatefinder.models.entities;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Stream;
public enum UnidadeFederativa {
ACRE("AC", "Acre"), ALAGOAS("AL", "Alagoas"), AMAPA("AP", "Amapa"), AMAZONAS("AM", "Amazonas"),
BAHIA("BA", "Bahia"), CEARA("CE", "Ceará"), DISTRITO_FEDERAL("DF", "Distrito Federal"),
ESPIRITO_SANTO("ES", "Espírito Santo"), GOIAS("GO", "Goiás"), MARANHAO("MA", "Maranhão"),
MATO_GROSSO("MT", "Mato Grosso"), MATO_GROSSO_DO_SUL("MS", "Mato Grosso do Sul"),
MINAS_GERAIS("MG", "Minas Gerais"), PARA("PA", "Ṕará"), PARAIBA("PB", "Paraíba"),
PARANA("PR", "Paraná"), PERNAMBUCO("PE", "Pernambuco"), PIAUI("PI", "Piauí"),
RIO_DE_JANEIRO("RJ", "Rio de Janeiro"), RIO_GRANDE_DO_NORTE("RN", "Rio Grande do Norte"),
RIO_GRANDE_DO_SUL("RS", "Rio Grande do Sul"), RONDONIA("RO", "Rondônia"),
RORAIMA("RR", "Roraima"), SANTA_CATARINA("SC", "Santa Catarina"), SAO_PAULO("SP", "São Paulo"),
SERGIPE("SE", "Sergipe"), TOCANTINS("TO", "Tocantins");
private final String sigla;
private final String nome;
UnidadeFederativa(String sigla, String nome) {
this.sigla = sigla;
this.nome = nome;
}
public String getSigla() {
return sigla;
}
public String getNome() {
return nome;
}
public static UnidadeFederativa fromSigla(String sigla) throws IllegalArgumentException {
for (UnidadeFederativa uf : UnidadeFederativa.values()) {
if (uf.sigla.equalsIgnoreCase(sigla)) {
return uf;
}
}
throw new IllegalArgumentException(String.format("No enum constant %s", sigla));
}
public static UnidadeFederativa fromNome(String nome) {
UnidadeFederativa unidadeFederativa = null;
for (UnidadeFederativa uf : UnidadeFederativa.values()) {
if (uf.nome.equalsIgnoreCase(nome)) {
return uf;
}
}
throw new IllegalArgumentException(String.format("No enum constant %s", nome));
}
public static String valuesToString() {
StringBuilder valuesToString = new StringBuilder();
Arrays.asList(values()).forEach(uf -> valuesToString.append(uf).append("\n"));
return valuesToString.toString();
}
@Override
public String toString() {
return String.format("%s - %s", nome, sigla);
}
}
| 34.985915 | 99 | 0.635266 |
886033a1613eb83ac15ff173e12ea8cda2dfe041 | 1,666 | package jtwirc.common.command.commands.faq;
import jtwirc.common.command.CommandBase;
import jtwirc.types.twitchMessage.TwitchMessage;
import jtwirc.types.users.TwitchUser;
import jtwirc.utils.JSONParser;
import jtwirc.utils.MessageSending;
import org.json.JSONException;
import org.json.JSONObject;
public class CommandCaster extends CommandBase
{
@Override
public void channelCommand(TwitchUser user, TwitchMessage message)
{
super.channelCommand(user, message);
if (user.isMod() || user.isBroadcaster())
{
JSONObject json = null;
try
{
json = new JSONObject(JSONParser.readUrl("https://api.twitch.tv/kraken/channels/" + args[1].toLowerCase()));
}
catch (Exception e)
{
e.printStackTrace();
}
if (json != null)
{
String game = null;
try
{
game = json.get("game").toString();
}
catch (JSONException e)
{
e.printStackTrace();
}
String Status = null;
try
{
Status = json.get("status").toString();
}
catch (JSONException e)
{
e.printStackTrace();
}
System.out.println(Status);
MessageSending.sendNormalMessage("Go give http://twitch.tv/" + args[1] + "a follow, they last played " + Status + " (Playing " + game + ")");
}
}
}
}
| 29.22807 | 157 | 0.5 |
f98eca00b99ee929ebf8096f82552fb9eae282c2 | 871 | package com.data.types;
import java.util.ArrayList;
public class DataRow {
private ArrayList<DataColumn> columns;
public DataRow() {
this.columns = new ArrayList<DataColumn>();
}
public DataRow(ArrayList<DataColumn> columns) {
this.columns = columns;
}
public boolean contains(String name) {
for (DataColumn column : this.columns) {
if (column.getColumnName().equals(name)) {
return true;
}
}
return false;
}
public void addColumn(DataColumn column) {
if (!this.contains(column.getColumnName())) {
this.columns.add(column);
}
}
public DataColumn getColumn(String name) {
for (DataColumn column : this.columns) {
if (column.getColumnName().equals(name)) {
return column;
}
}
return new DataColumn();
}
public ArrayList<DataColumn> getColumns() { return this.columns; }
}
| 21.243902 | 67 | 0.661309 |
cf3e61f16d2f3391409f9dd29f5c8a6bf78a27f4 | 612 | package me.zhengjie.modules.study.repository;
import me.zhengjie.modules.study.domain.UserSysVal;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
public interface UserSysValRepository extends JpaRepository<UserSysVal, Long>, JpaSpecificationExecutor<UserSysVal> {
List<UserSysVal> findByUserId(Long id);
@Query(value = "select val_id from user_sys_val where user_id = ?1", nativeQuery = true)
List<Long> findValIds(Long userId);
} | 36 | 117 | 0.808824 |
c808e474d239a32598bfaa67b825a436608c9120 | 1,892 | package io.stargate.sdk.rest;
import java.util.Optional;
import io.stargate.sdk.doc.ApiDocumentClient;
import io.stargate.sdk.doc.NamespaceClient;
/**
* Operate on Tables in Cassandra.
*
* @author Cedrick LUNVEN (@clunven)
*/
public class TableClient {
/** Astra Client. */
private final ApiRestClient restClient;
/** Namespace. */
private final KeyspaceClient keyspaceClient;
/** Collection name. */
private final String tableName;
/**
* Full constructor.
*/
public TableClient(ApiRestClient restClient, KeyspaceClient keyspaceClient, String tableName) {
this.restClient = restClient;
this.keyspaceClient = keyspaceClient;
this.tableName = tableName;
}
// Get a table
// https://docs.astra.datastax.com/reference#get_api-rest-v2-schemas-keyspaces-keyspace-id-tables-table-id-1
Optional<TableDefinition> find() {
return null;
}
boolean exist() {
return false;
}
// create a table
//https://docs.astra.datastax.com/reference#post_api-rest-v2-schemas-keyspaces-keyspace-id-tables-1
void create(TableCreationRequest tcr) {
}
//replace a table definition
//https://docs.astra.datastax.com/reference#put_api-rest-v2-schemas-keyspaces-keyspace-id-tables-table-id-1
void replaceTableDefinition() {}
//Delete a table
//https://docs.astra.datastax.com/reference#delete_api-rest-v2-schemas-keyspaces-keyspace-id-tables-table-id-1
void delete() {}
// https://docs.astra.datastax.com/reference#get_api-rest-v2-schemas-keyspaces-keyspace-id-tables-table-id-columns-1
void listColumns() {}
//https://docs.astra.datastax.com/reference#post_api-rest-v2-schemas-keyspaces-keyspace-id-tables-table-id-columns-1
void createColum() {}
}
| 27.42029 | 120 | 0.664376 |
42ed3ae9db6290d1f9d8729530a81dd878dc51ca | 1,730 | package com.cqust.pojo;
public class TAddress {
private Integer id;
private String province;
private String detailaddr;
private String zipcode;
private String receiptname;
private String receipphone;
private Integer userid;
private Integer defauladdress;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province == null ? null : province.trim();
}
public String getDetailaddr() {
return detailaddr;
}
public void setDetailaddr(String detailaddr) {
this.detailaddr = detailaddr == null ? null : detailaddr.trim();
}
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode == null ? null : zipcode.trim();
}
public String getReceiptname() {
return receiptname;
}
public void setReceiptname(String receiptname) {
this.receiptname = receiptname == null ? null : receiptname.trim();
}
public String getReceipphone() {
return receipphone;
}
public void setReceipphone(String receipphone) {
this.receipphone = receipphone == null ? null : receipphone.trim();
}
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public Integer getDefauladdress() {
return defauladdress;
}
public void setDefauladdress(Integer defauladdress) {
this.defauladdress = defauladdress;
}
} | 20.843373 | 75 | 0.627746 |
6d5eb9436037978848f18591dc90bc02da510a9a | 4,577 | /*
* 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.commons.dbcp2;
import static org.junit.Assert.fail;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import org.apache.commons.dbcp2.datasources.SharedPoolDataSource;
import org.apache.commons.dbcp2.datasources.PerUserPoolDataSource;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* Tests JNID bind and lookup for DataSource implementations.
* Demonstrates problem indicated in BZ #38073.
*/
public class TestJndi {
/**
* The subcontext where the data source is bound.
*/
protected static final String JNDI_SUBCONTEXT = "jdbc";
/**
* the full jndi path to the data source.
*/
protected static final String JNDI_PATH = JNDI_SUBCONTEXT + "/"
+ "jndiTestDataSource";
/** jndi context to use in tests **/
protected Context context = null;
/**
* Test BasicDatasource bind and lookup
*
* @throws Exception
*/
@Test
public void testBasicDataSourceBind() throws Exception {
final BasicDataSource dataSource = new BasicDataSource();
checkBind(dataSource);
}
/**
* Test SharedPoolDataSource bind and lookup
*
* @throws Exception
*/
@Test
public void testSharedPoolDataSourceBind() throws Exception {
final SharedPoolDataSource dataSource = new SharedPoolDataSource();
checkBind(dataSource);
}
/**
* Test PerUserPoolDataSource bind and lookup
*
* @throws Exception
*/
@Test
public void testPerUserPoolDataSourceBind() throws Exception {
final PerUserPoolDataSource dataSource = new PerUserPoolDataSource();
checkBind(dataSource);
}
@Before
public void setUp() throws Exception {
context = getInitialContext();
context.createSubcontext(JNDI_SUBCONTEXT);
}
@After
public void tearDown() throws Exception {
context.unbind(JNDI_PATH);
context.destroySubcontext(JNDI_SUBCONTEXT);
}
/**
* Binds a DataSource to the jndi and checks that we have successfully
* bound it by looking it up again.
*
* @throws Exception if the bind, lookup or connect fails
*/
protected void checkBind(final DataSource dataSource) throws Exception {
bindDataSource(dataSource);
retrieveDataSource();
}
/**
* Binds a DataSource into jndi.
*
* @throws Exception if creation or binding fails.
*/
protected void bindDataSource(final DataSource dataSource) throws Exception {
context.bind(JNDI_PATH, dataSource);
}
/**
* Retrieves a DataSource from jndi.
*
* @throws Exception if the jndi lookup fails or no DataSource is bound.
*/
protected DataSource retrieveDataSource() throws Exception {
final Context ctx = getInitialContext();
final DataSource dataSource = (DataSource) ctx.lookup(JNDI_PATH);
if (dataSource == null) {
fail("DataSource should not be null");
}
return dataSource;
}
/**
* Retrieves (or creates if it does not exist) an InitialContext.
*
* @return the InitialContext.
* @throws NamingException if the InitialContext cannot be retrieved
* or created.
*/
protected InitialContext getInitialContext() throws NamingException {
final Hashtable<String, String> environment = new Hashtable<>();
environment.put(Context.INITIAL_CONTEXT_FACTORY,
org.apache.naming.java.javaURLContextFactory.class.getName());
final InitialContext ctx = new InitialContext(environment);
return ctx;
}
}
| 30.718121 | 81 | 0.682543 |
36bcfb22453a60dca1b593787ba7bec6e1c929f6 | 1,387 | /* Copyright (c) 2008 Google 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 com.google.gdata.data.docs;
import com.google.gdata.data.BaseFeed;
import com.google.gdata.data.Kind;
/**
* Describes an Metadata feed.
*
*
*/
@Kind.Term(MetadataEntry.KIND)
public class MetadataFeed extends BaseFeed<MetadataFeed, MetadataEntry> {
/**
* Default mutable constructor.
*/
public MetadataFeed() {
super(MetadataEntry.class);
getCategories().add(MetadataEntry.CATEGORY);
}
/**
* Constructs a new instance by doing a shallow copy of data from an existing
* {@link BaseFeed} instance.
*
* @param sourceFeed source feed
*/
public MetadataFeed(BaseFeed<?, ?> sourceFeed) {
super(MetadataEntry.class, sourceFeed);
}
@Override
public String toString() {
return "{MetadataFeed " + super.toString() + "}";
}
}
| 25.218182 | 79 | 0.703677 |
fecd47466899a4c4a2e027a70d2bde43fdd2904d | 9,503 | package edu.fiuba.algo3.modelo.TestsJugador;
import edu.fiuba.algo3.modelo.Kahoot;
import edu.fiuba.algo3.modelo.correcciones.CorrectorClasico;
import edu.fiuba.algo3.modelo.correcciones.CorrectorPenalidad;
import edu.fiuba.algo3.modelo.correcciones.Respuesta;
import edu.fiuba.algo3.modelo.excepciones.NoTieneMultiplicadorException;
import edu.fiuba.algo3.modelo.excepciones.RondaFinalizadaException;
import edu.fiuba.algo3.modelo.jugador.Jugador;
import edu.fiuba.algo3.modelo.preguntas.VerdaderoFalso;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class JugadorTest {
private Kahoot kahoot;
@BeforeEach
public void setUp(){
kahoot = new Kahoot();
kahoot.crearJugadores("Rafael", "Roger");
}
@Test
public void test01ElJugadorSeCreaCorrectamente() {
Jugador jugador = new Jugador("Rafael");
assertEquals("Rafael", jugador.getNombre());
}
@Test
public void test02ElJugadorSeCreaYTienePuntajeCero() {
Jugador jugador = new Jugador("Rafael");
assertEquals(0, jugador.getPuntaje());
}
@Test
public void test03ElJugadorActivaMultiplicadorx2YDevuelveDoblePuntos() throws NoTieneMultiplicadorException {
ArrayList<String> opciones = new ArrayList<String>();
opciones.add("Verdadero");
opciones.add("Falso");
ArrayList<String> respuesta = new ArrayList<String>();
respuesta.add("Verdadero");
CorrectorPenalidad penalidad = new CorrectorPenalidad();
Respuesta respuestaCorrecta = new Respuesta(respuesta);
VerdaderoFalso verdaderoFalso = new VerdaderoFalso("1 + 1 = 2?", respuestaCorrecta, opciones, penalidad);
kahoot.setPreguntaActual(verdaderoFalso);
ArrayList<Respuesta> respuestaJugador = new ArrayList<Respuesta>();
var jugador = kahoot.getJugadorActual();
jugador.respuestaElegida(respuestaCorrecta); //El jugador eligio la respuesta Verdadero
respuestaJugador.add(jugador.getRespuesta());
jugador.activarMultiplicadorx2();
verdaderoFalso.evaluarRespuesta(respuestaJugador);
jugador.actualizarPuntaje();
assertEquals(2, jugador.getPuntaje());
}
@Test
public void test04ElJugadorActivaMultiplicadorx3YDevuelveTriplePuntos() throws NoTieneMultiplicadorException {
ArrayList<String> opciones = new ArrayList<String>();
opciones.add("Verdadero");
opciones.add("Falso");
ArrayList<String> respuesta = new ArrayList<String>();
respuesta.add("Verdadero");
CorrectorPenalidad penalidad = new CorrectorPenalidad();
Respuesta respuestaCorrecta = new Respuesta(respuesta);
VerdaderoFalso verdaderoFalso = new VerdaderoFalso("1 + 1 = 2?", respuestaCorrecta, opciones, penalidad);
kahoot.setPreguntaActual(verdaderoFalso);
ArrayList<Respuesta> respuestaJugador = new ArrayList<Respuesta>();
var jugador = kahoot.getJugadorActual();
jugador.respuestaElegida(respuestaCorrecta); //El jugador eligio la respuesta Verdadero
respuestaJugador.add(jugador.getRespuesta());
jugador.activarMultiplicadorx3();
verdaderoFalso.evaluarRespuesta(respuestaJugador);
jugador.actualizarPuntaje();
assertEquals(3, jugador.getPuntaje());
}
@Test
public void test04ElJugadorActivaMultiplicadorx2YEnLaSiguientePreguntaNoHaceEfecto() throws NoTieneMultiplicadorException {
ArrayList<String> opciones = new ArrayList<String>();
opciones.add("Verdadero");
opciones.add("Falso");
ArrayList<String> respuesta = new ArrayList<String>();
respuesta.add("Verdadero");
CorrectorPenalidad penalidad = new CorrectorPenalidad();
Respuesta respuestaCorrecta = new Respuesta(respuesta);
VerdaderoFalso verdaderoFalso = new VerdaderoFalso("1 + 1 = 2?", respuestaCorrecta, opciones, penalidad);
kahoot.setPreguntaActual(verdaderoFalso);
var jugador = kahoot.getJugadorActual();
jugador.respuestaElegida(respuestaCorrecta); //El jugador eligio la respuesta Verdadero
ArrayList<Respuesta> respuestaJugador = new ArrayList<Respuesta>();
respuestaJugador.add(jugador.getRespuesta());
jugador.activarMultiplicadorx2();
verdaderoFalso.evaluarRespuesta(respuestaJugador);
jugador.actualizarPuntaje();
assertEquals(2, jugador.getPuntaje());
//siguiente pregunta
VerdaderoFalso verdaderoFalso2 = new VerdaderoFalso("1 - 1 = 0?", respuestaCorrecta, opciones, penalidad);
kahoot.setPreguntaActual(verdaderoFalso2);
jugador.respuestaElegida(respuestaCorrecta);
ArrayList<Respuesta> respuestaJugador2 = new ArrayList<Respuesta>();
respuestaJugador2.add(jugador.getRespuesta());
verdaderoFalso.evaluarRespuesta(respuestaJugador);
jugador.actualizarPuntaje();
assertEquals(3, jugador.getPuntaje());
}
@Test
public void test05ElJugadorActivaMultiplicadorx3YEnLaSiguientePreguntaNoHaceEfecto() throws NoTieneMultiplicadorException {
ArrayList<String> opciones = new ArrayList<String>();
opciones.add("Verdadero");
opciones.add("Falso");
ArrayList<String> respuesta = new ArrayList<String>();
respuesta.add("Verdadero");
CorrectorPenalidad penalidad = new CorrectorPenalidad();
Respuesta respuestaCorrecta = new Respuesta(respuesta);
VerdaderoFalso verdaderoFalso = new VerdaderoFalso("1 + 1 = 2?", respuestaCorrecta, opciones, penalidad);
kahoot.setPreguntaActual(verdaderoFalso);
var jugador = kahoot.getJugadorActual();
jugador.respuestaElegida(respuestaCorrecta); //El jugador eligio la respuesta Verdadero
ArrayList<Respuesta> respuestaJugador = new ArrayList<Respuesta>();
respuestaJugador.add(jugador.getRespuesta());
jugador.activarMultiplicadorx3();
verdaderoFalso.evaluarRespuesta(respuestaJugador);
jugador.actualizarPuntaje();
assertEquals(3, jugador.getPuntaje());
//siguiente pregunta
VerdaderoFalso verdaderoFalso2 = new VerdaderoFalso("1 - 1 = 0?", respuestaCorrecta, opciones, penalidad);
kahoot.setPreguntaActual(verdaderoFalso2);
jugador.respuestaElegida(respuestaCorrecta);
ArrayList<Respuesta> respuestaJugador2 = new ArrayList<Respuesta>();
respuestaJugador2.add(jugador.getRespuesta());
verdaderoFalso.evaluarRespuesta(respuestaJugador);
jugador.actualizarPuntaje();
assertEquals(4, jugador.getPuntaje());
}
@Test
public void test06ElJugadorIntentaActivaMultiplicadorx2EnPreguntaSinPenalidadYnoHaceEfecto() throws NoTieneMultiplicadorException, RondaFinalizadaException {
ArrayList<String> opciones = new ArrayList<String>();
opciones.add("Verdadero");
opciones.add("Falso");
ArrayList<String> respuesta = new ArrayList<String>();
respuesta.add("Verdadero");
CorrectorClasico clasico = new CorrectorClasico();
Respuesta respuestaCorrecta = new Respuesta(respuesta);
VerdaderoFalso verdaderoFalso = new VerdaderoFalso("1 + 1 = 2?", respuestaCorrecta, opciones, clasico);
kahoot.setPreguntaActual(verdaderoFalso);
ArrayList<Respuesta> respuestaJugador = new ArrayList<Respuesta>();
kahoot.siguienteJugador();
var jugador = kahoot.getJugadorActual();
jugador.respuestaElegida(respuestaCorrecta); //El jugador eligio la respuesta Verdadero
respuestaJugador.add(jugador.getRespuesta());
jugador.activarMultiplicadorx2();
verdaderoFalso.evaluarRespuesta(respuestaJugador);
jugador.actualizarPuntaje();
assertEquals(1, jugador.getPuntaje());
}
@Test
public void test07ElJugadorActivaMultiplicadorx2IntentaUsarloNuevamenteYLanzaUnaExcepcion() throws NoTieneMultiplicadorException {
ArrayList<String> opciones = new ArrayList<String>();
opciones.add("Verdadero");
opciones.add("Falso");
ArrayList<String> respuesta = new ArrayList<String>();
respuesta.add("Verdadero");
CorrectorPenalidad penalidad = new CorrectorPenalidad();
Respuesta respuestaCorrecta = new Respuesta(respuesta);
VerdaderoFalso verdaderoFalso = new VerdaderoFalso("1 + 1 = 2?", respuestaCorrecta, opciones, penalidad);
kahoot.setPreguntaActual(verdaderoFalso);
ArrayList<Respuesta> respuestaJugador = new ArrayList<Respuesta>();
var jugador = kahoot.getJugadorActual();
jugador.respuestaElegida(respuestaCorrecta); //El jugador eligio la respuesta Verdadero
respuestaJugador.add(jugador.getRespuesta());
jugador.activarMultiplicadorx2();
verdaderoFalso.evaluarRespuesta(respuestaJugador);
jugador.actualizarPuntaje();
assertEquals(2, jugador.getPuntaje());
//siguiente pregunta
VerdaderoFalso verdaderoFalso2 = new VerdaderoFalso("1 + 1 = 2?", respuestaCorrecta, opciones, penalidad);
kahoot.setPreguntaActual(verdaderoFalso2);
boolean excepcion = false;
try {
jugador.activarMultiplicadorx2();
}catch (NoTieneMultiplicadorException e){
excepcion = true;
}
assertEquals(true, excepcion);
}
}
| 40.266949 | 161 | 0.710933 |
35751692d055190ab0e93f664ad8834ba519eb40 | 2,855 | package com.jeebud.module.upms.controller;
import com.jeebud.core.log.OpTypeEnum;
import com.jeebud.core.log.Operation;
import com.jeebud.core.web.RestEntity;
import com.jeebud.module.upms.model.entity.Param;
import com.jeebud.module.upms.model.param.ParamPageQuery;
import com.jeebud.module.upms.service.ParamService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
/**
* <p>Description: </p>
* <p>Copyright (c) www.jeebud.com Inc. All Rights Reserved.</p>
*
* @author Tanxh(itfuyun@gmail.com)
*/
@Controller
@RequestMapping("${jeebud.sys.serverCtx}/sys/param")
public class ParamController {
/**
* 模板前缀
*/
private static final String TPL_PATH = "admin/modules/sys/param";
@Autowired
ParamService paramService;
/**
* 列表页面
*
* @return
*/
@RequiresPermissions("p:sys:param:list")
@GetMapping("/pageList")
public String pageList() {
return TPL_PATH + "/list";
}
/**
* 获取列表
*
* @param query
* @return
*/
@RequiresPermissions("i:sys:param:list")
@GetMapping("/list")
@ResponseBody
public RestEntity<Page<Param>> paramList(ParamPageQuery query) {
Page<Param> paramPage = paramService.page(query);
return RestEntity.ok().data(paramPage);
}
/**
* 新增
*
* @param param
* @return
*/
@Operation(module = "参数模块", opType = OpTypeEnum.CREATE, info = "新增参数")
@RequiresPermissions("i:sys:param:add")
@PostMapping("/add")
@ResponseBody
public RestEntity<String> add(@Validated Param param) {
paramService.insert(param);
return RestEntity.ok();
}
/**
* 修改
*
* @param param
* @return
*/
@Operation(module = "参数模块", opType = OpTypeEnum.UPDATE, info = "修改参数")
@RequiresPermissions("i:sys:param:update")
@PostMapping("/update")
@ResponseBody
public RestEntity<String> update(@Validated Param param) {
paramService.update(param);
return RestEntity.ok();
}
/**
* 删除
*
* @param id
* @return
*/
@Operation(module = "参数模块", opType = OpTypeEnum.DELETE, info = "删除参数")
@RequiresPermissions("i:sys:param:delete")
@PostMapping("/delete")
@ResponseBody
public RestEntity<String> delete(Long id) {
paramService.delete(id);
return RestEntity.ok();
}
}
| 26.435185 | 74 | 0.669352 |
effa315e252488c98e63c5e30e985b4c4d0d1756 | 4,440 | /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
public class Main {
static final String DEX_FILE = System.getenv("DEX_LOCATION") + "/616-cha-unloading-ex.jar";
static final String LIBRARY_SEARCH_PATH = System.getProperty("java.library.path");
static Constructor<? extends ClassLoader> sConstructor;
private static class CHAUnloaderRetType {
private CHAUnloaderRetType(WeakReference<ClassLoader> cl,
AbstractCHATester obj,
long methodPtr) {
this.cl = cl;
this.obj = obj;
this.methodPtr = methodPtr;
}
public WeakReference<ClassLoader> cl;
public AbstractCHATester obj;
public long methodPtr;
}
public static void main(String[] args) throws Exception {
System.loadLibrary(args[0]);
Class<ClassLoader> pathClassLoader = (Class<ClassLoader>) Class.forName("dalvik.system.PathClassLoader");
sConstructor =
pathClassLoader.getDeclaredConstructor(String.class, String.class, ClassLoader.class);
testUnload();
}
private static void testUnload() throws Exception {
// Load a concrete class, then unload it. Get a deleted ArtMethod to test if it'll be inlined.
CHAUnloaderRetType result = doUnloadLoader();
WeakReference<ClassLoader> loader = result.cl;
long methodPtr = result.methodPtr;
// Check that the classloader is indeed unloaded.
if (loader.get() != null) {
throw new Error("Expected class loader to be unloaded");
}
// Reuse the linear alloc used by the unloaded class loader.
reuseArenaOfMethod(methodPtr);
// Try to JIT-compile under dangerous conditions.
ensureJitCompiled(Main.class, "targetMethodForJit");
System.out.println("Done");
}
private static void doUnloading() {
// Do multiple GCs to prevent rare flakiness if some other thread is keeping the
// classloader live.
for (int i = 0; i < 5; ++i) {
Runtime.getRuntime().gc();
}
}
private static CHAUnloaderRetType setupLoader()
throws Exception {
ClassLoader loader = sConstructor.newInstance(
DEX_FILE, LIBRARY_SEARCH_PATH, ClassLoader.getSystemClassLoader());
Class<?> concreteCHATester = loader.loadClass("ConcreteCHATester");
// Preemptively compile methods to prevent delayed JIT tasks from blocking the unloading.
ensureJitCompiled(concreteCHATester, "<init>");
ensureJitCompiled(concreteCHATester, "lonelyMethod");
Object obj = concreteCHATester.newInstance();
Method lonelyMethod = concreteCHATester.getDeclaredMethod("lonelyMethod");
// Get a pointer to a region that shall be not used after the unloading.
long artMethod = getArtMethod(lonelyMethod);
AbstractCHATester ret = null;
return new CHAUnloaderRetType(new WeakReference(loader), ret, artMethod);
}
private static CHAUnloaderRetType targetMethodForJit(int mode)
throws Exception {
CHAUnloaderRetType ret = new CHAUnloaderRetType(null, null, 0);
if (mode == 0) {
ret = setupLoader();
} else if (mode == 1) {
// This branch is not supposed to be executed. It shall trigger "lonelyMethod" inlining
// during jit compilation of "targetMethodForJit".
ret = setupLoader();
AbstractCHATester obj = ret.obj;
obj.lonelyMethod();
}
return ret;
}
private static CHAUnloaderRetType doUnloadLoader()
throws Exception {
CHAUnloaderRetType result = targetMethodForJit(0);
doUnloading();
return result;
}
private static native void ensureJitCompiled(Class<?> itf, String method_name);
private static native long getArtMethod(Object javaMethod);
private static native void reuseArenaOfMethod(long artMethod);
}
| 36.393443 | 109 | 0.713288 |
649f8612d86bf41264dffed3b237d72653c80c0d | 8,629 | /*
* Copyright (c) 2009-2020 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jme3.bullet.collision.shapes;
import com.jme3.export.InputCapsule;
import com.jme3.export.JmeExporter;
import com.jme3.export.JmeImporter;
import com.jme3.export.OutputCapsule;
import com.jme3.math.FastMath;
import com.jme3.math.Vector3f;
import com.jme3.scene.Mesh;
import com.jme3.util.BufferUtils;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A terrain collision shape based on Bullet's btHeightfieldTerrainShape.
* <p>
* This is much more efficient than a regular mesh, but it has a couple
* limitations:
* <ul>
* <li>No rotation or translation.</li>
* <li>The collision bounding box must be centered on (0,0,0) with the height
* above and below the X-Z plane being equal on either side. If not, the whole
* collision box is shifted vertically and objects won't collide properly.</li>
* </ul>
*
* @author Brent Owens
*/
public class HeightfieldCollisionShape extends CollisionShape {
/**
* number of rows in the heightfield (>1)
*/
protected int heightStickWidth;
/**
* number of columns in the heightfield (>1)
*/
protected int heightStickLength;
/**
* array of heightfield samples
*/
protected float[] heightfieldData;
protected float heightScale;
protected float minHeight;
protected float maxHeight;
/**
* index of the height axis (0→X, 1→Y, 2→Z)
*/
protected int upAxis;
protected boolean flipQuadEdges;
/**
* buffer for passing height data to Bullet
* <p>
* A Java reference must persist after createShape() completes, or else the
* buffer might get garbage collected.
*/
protected ByteBuffer bbuf;
// protected FloatBuffer fbuf;
/**
* No-argument constructor needed by SavableClassUtil. Do not invoke
* directly!
*/
protected HeightfieldCollisionShape() {
}
/**
* Instantiate a new shape for the specified height map.
*
* @param heightmap (not null, length≥4, length a perfect square)
*/
public HeightfieldCollisionShape(float[] heightmap) {
createCollisionHeightfield(heightmap, Vector3f.UNIT_XYZ);
}
/**
* Instantiate a new shape for the specified height map and scale vector.
*
* @param heightmap (not null, length≥4, length a perfect square)
* @param scale (not null, no negative component, unaffected, default=1,1,1)
*/
public HeightfieldCollisionShape(float[] heightmap, Vector3f scale) {
createCollisionHeightfield(heightmap, scale);
}
protected void createCollisionHeightfield(float[] heightmap, Vector3f worldScale) {
this.scale = worldScale;
this.heightScale = 1;//don't change away from 1, we use worldScale instead to scale
this.heightfieldData = heightmap;
float min = heightfieldData[0];
float max = heightfieldData[0];
// calculate min and max height
for (int i = 0; i < heightfieldData.length; i++) {
if (heightfieldData[i] < min) {
min = heightfieldData[i];
}
if (heightfieldData[i] > max) {
max = heightfieldData[i];
}
}
// we need to center the terrain collision box at 0,0,0 for BulletPhysics. And to do that we need to set the
// min and max height to be equal on either side of the y axis, otherwise it gets shifted and collision is incorrect.
if (max < 0) {
max = -min;
} else {
if (Math.abs(max) > Math.abs(min)) {
min = -max;
} else {
max = -min;
}
}
this.minHeight = min;
this.maxHeight = max;
this.upAxis = 1;
flipQuadEdges = true;
heightStickWidth = (int) FastMath.sqrt(heightfieldData.length);
heightStickLength = heightStickWidth;
createShape();
}
/**
* Instantiate the configured shape in Bullet.
*/
protected void createShape() {
bbuf = BufferUtils.createByteBuffer(heightfieldData.length * 4);
// fbuf = bbuf.asFloatBuffer();//FloatBuffer.wrap(heightfieldData);
// fbuf.rewind();
// fbuf.put(heightfieldData);
for (int i = 0; i < heightfieldData.length; i++) {
float f = heightfieldData[i];
bbuf.putFloat(f);
}
// fbuf.rewind();
objectId = createShape(heightStickWidth, heightStickLength, bbuf, heightScale, minHeight, maxHeight, upAxis, flipQuadEdges);
Logger.getLogger(this.getClass().getName()).log(Level.FINE, "Created Shape {0}", Long.toHexString(objectId));
setScale(scale);
setMargin(margin);
}
private native long createShape(int heightStickWidth, int heightStickLength, ByteBuffer heightfieldData, float heightScale, float minHeight, float maxHeight, int upAxis, boolean flipQuadEdges);
/**
* Does nothing.
*
* @return null
*/
public Mesh createJmeMesh() {
//TODO return Converter.convert(bulletMesh);
return null;
}
/**
* Serialize this shape, for example when saving to a J3O file.
*
* @param ex exporter (not null)
* @throws IOException from exporter
*/
@Override
public void write(JmeExporter ex) throws IOException {
super.write(ex);
OutputCapsule capsule = ex.getCapsule(this);
capsule.write(heightStickWidth, "heightStickWidth", 0);
capsule.write(heightStickLength, "heightStickLength", 0);
capsule.write(heightScale, "heightScale", 0);
capsule.write(minHeight, "minHeight", 0);
capsule.write(maxHeight, "maxHeight", 0);
capsule.write(upAxis, "upAxis", 1);
capsule.write(heightfieldData, "heightfieldData", new float[0]);
capsule.write(flipQuadEdges, "flipQuadEdges", false);
}
/**
* De-serialize this shape, for example when loading from a J3O file.
*
* @param im importer (not null)
* @throws IOException from importer
*/
@Override
public void read(JmeImporter im) throws IOException {
super.read(im);
InputCapsule capsule = im.getCapsule(this);
heightStickWidth = capsule.readInt("heightStickWidth", 0);
heightStickLength = capsule.readInt("heightStickLength", 0);
heightScale = capsule.readFloat("heightScale", 0);
minHeight = capsule.readFloat("minHeight", 0);
maxHeight = capsule.readFloat("maxHeight", 0);
upAxis = capsule.readInt("upAxis", 1);
heightfieldData = capsule.readFloatArray("heightfieldData", new float[0]);
flipQuadEdges = capsule.readBoolean("flipQuadEdges", false);
createShape();
}
}
| 37.354978 | 198 | 0.646541 |
86cc41cf3232255716faf8b3e0fa648bd21859a1 | 748 | package domain.dinner.food.ingredients;
import javax.persistence.Column;
import javax.persistence.Entity;
import java.util.List;
@Entity
public class Solido extends Ingrediente {
@Column(name="path")
private String path;
public Solido(){
}
@Override
public String getColorString() {
return null;
}
@Override
public void setColorString() {
}
public Solido(String nombre, Double costo, List<Propiedad> propiedades, String path) {
super(nombre,costo,propiedades);
this.path = path;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String color(){
return null;
}
}
| 17.395349 | 90 | 0.629679 |
3f8039f111217bc223f8cbefa0314ebd8f5fd209 | 3,513 | package com.xrtb.tools;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashSet;
import java.util.Map;
import com.aerospike.client.AerospikeClient;
import com.aerospike.redisson.AerospikeHandler;
import com.aerospike.redisson.RedissonClient;
public class AeroListSet {
public static void main(String args[]) throws Exception {
int i = 0;
String aero = "localhost:3000";
String key = null;
String setName = null;
String mapName = null;
String op = null;
String name = null;
String file = null;
boolean range = false;
while (i < args.length) {
switch (args[i]) {
case "-file":
file = args[i + 1];
i += 2;
break;
case "-aero":
aero = args[i + 1];
i += 2;
break;
case "-load-set":
setName = args[i + 1];
op = "load";
i += 2;
break;
case "-range":
range = true;
i ++;
break;
case "-delete-set":
setName = args[i + 1];
op = "delete";
i += 2;
break;
case "-read-set":
op = "read";
setName = args[i + 1];
i += 2;
break;
case "-load-map":
op = "load";
mapName = args[i + 1];
i += 2;
break;
case "-delete-map":
op = "delete";
mapName = args[i + 1];
i += 2;
break;
case "-read-map":
op = "read";
mapName = args[i + 1];
i += 2;
break;
case "-key":
key = args[i + 1];
i += 2;
case "-name":
name = args[i + 1];
i += 2;
break;
default:
System.out.println("Huh? " + args[i]);
System.exit(0);
;
}
;
}
String parts[] = aero.split(":");
int port = 3000;
String host = parts[0];
if (parts.length > 1) {
port = Integer.parseInt(parts[1]);
}
AerospikeHandler client = AerospikeHandler.getInstance(host,port,300);
RedissonClient redisson = new RedissonClient(client);
if (setName != null) {
if (op.equals("load")) {
loadSet(redisson,file, setName, range);
return;
}
if (op.equals("query")) {
Object value = redisson.get("userstore",key);
System.out.println(value);
}
}
if (mapName != null) {
}
System.out.println("Can't figure out what you want to do");
}
public static void loadSet(RedissonClient redisson, String file, String name, boolean range) throws Exception {
BufferedReader br = new BufferedReader(new FileReader(file));
long x = 0, k = 0;
for (String line; (line = br.readLine()) != null;) {
if (range) {
String[] parts = line.split("-");
if (parts.length != 2)
System.out.println(line);
else {
long start = ipToLong(parts[0]);
long end = ipToLong(parts[1]);
for (long i=start;i<=end;i++) {
String ip = longToIp(i);
redisson.set("userstore",name,ip);
x++;
}
}
if (k % 1000 == 0)
System.out.println(k);
k++;
}
}
System.out.println("read " + k + ", total = " + x);
}
public static long ipToLong(String ipAddress) {
String[] ipAddressInArray = ipAddress.split("\\.");
long result = 0;
for (int i = 0; i < ipAddressInArray.length; i++) {
int power = 3 - i;
int ip = Integer.parseInt(ipAddressInArray[i]);
result += ip * Math.pow(256, power);
}
return result;
}
public static String longToIp(long ip) {
StringBuilder result = new StringBuilder(15);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 4; i++) {
result.insert(0, Long.toString(ip & 0xff));
if (i < 3) {
sb.insert(0, '.');
}
ip = ip >> 8;
}
return result.toString();
}
}
| 20.424419 | 112 | 0.571591 |
c33c3ffd0827769468d5dd2016dc7a8315bc6a6e | 3,178 | package com.zubr.bot;
/**
* A counter for keeping track of the number of events that have occurred within a specified time interval, in order to avoid exceeding a rate limit.
* <p>
* {@code FloodTracker} is not thread-safe. If concurrently accessed from multiple threads, external synchronization is required.
*/
public class FloodTracker {
private long[] timestamps;
private int oldest;
private int count;
private long period;
/**
* Creates a counter with the specified event limit and time interval.
* @param capacity the maximum allowed number of events.
* @param period the time period (in nanoseconds) within which {@code capacity} must not bbe exceeded
*/
public FloodTracker(int capacity, long period) {
timestamps = new long[capacity];
this.period = period;
oldest = count = 0;
}
/**
* Checks the number of additional events currently allowed.
* <p>
* Identical to {@code available(System.nanoTime())}.
* @return the number of events that could be added without exceeding the limit.
*/
public int available() {
return available(System.nanoTime());
}
/**
* Checks the number of additional events currently allowed.
* <p>
* Useful to avoid redundant calls to {@code System.nanoTime()} if the caller also needs the timestamp. Not safe for determining
* number of events that will be allowed at a future timepoint: events prior to the interval ending at {@code time} will be forgotten.
* @param time the {@code System.nanoTime()}.
* @return the number of events that could be added without exceeding the limit.
*/
public int available(long time) {
advance(time);
return timestamps.length - count;
}
/**
* Adds an event to this counter, if allowed.
* <p>
* Identical to {@code add(System.nanoTime())}
* @return {@code true} if the event was added, {@code false} if adding the event would have exceeded the limit.
*/
public boolean add() {
return add(System.nanoTime());
}
/**
* Adds an event to this counter, if allowed.
* <p>
* Useful to avoid redundant calls to {@code System.nanoTime()} if the caller also needs the timestamp. May be unsafe to use with
* future timepoints: events prior to the interval ending at {@code time} will be forgotten, and if events are not added in
* chronological order some events may be retained in the count after they should have expired.
* @param time the {@code System.nanoTime()}.
* @return {@code true} if the event was added, {@code false} if adding the event would have exceeded the limit.
*/
public boolean add(long time) {
advance(time);
if(count < timestamps.length) {
count++;
timestamps[(oldest + count) % timestamps.length] = time;
return true;
} else
return false;
}
/**
* Advances internal index to forget old events.
* @param time the current time. Events previously added with timestamps {@code < time - period} are forgotten
*/
private void advance(long time) {
time = time - period;
while(count > 0 && timestamps[oldest] < time) {
oldest = (oldest + 1)%timestamps.length;
count--;
}
}
}
| 35.707865 | 150 | 0.683763 |
afb32856c97a5ba4361b4f6fa8899119cb2581d3 | 1,135 | /*
* Transcode from a Map format to another Collection derived format
* Created because it is not possible to iterate through a Map
*/
package utility;
import datamodel.Tissue;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import datamodel.CompartmentSBML;
import javax.swing.tree.DefaultMutableTreeNode;
/**
*
* @author jplr
*/
public class CollToArrayList {
public ArrayList<Tissue> convertTissue(Map<Integer, Tissue> mapOf) {
Collection<Tissue> deux = mapOf.values();
ArrayList<Tissue> un = new ArrayList<Tissue>(deux);
return un;
}
public ArrayList<Tissue> treeToTissue(Map<Tissue, DefaultMutableTreeNode> mapOf) {
Collection<Tissue> deux = mapOf.keySet() ;
ArrayList<Tissue> un = new ArrayList<Tissue>(deux);
return un;
}
public ArrayList<CompartmentSBML> convertComp(Map<String, CompartmentSBML> mapOf) {
Collection<CompartmentSBML> deux = mapOf.values();
ArrayList<CompartmentSBML> un = new ArrayList<CompartmentSBML>(deux);
return un;
}
}
| 29.868421 | 87 | 0.67489 |
2bd4893b8b7b51c8057967a893937f32c565fb2f | 1,185 | package fr.free.nrw.commons.campaigns;
import com.google.gson.annotations.SerializedName;
/**
* A data class to hold a campaign
*/
public class Campaign {
@SerializedName("title") private String title;
@SerializedName("description") private String description;
@SerializedName("startDate") private String startDate;
@SerializedName("endDate") private String endDate;
@SerializedName("link") private String link;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getStartDate() {
return startDate;
}
public void setStartDate(String startDate) {
this.startDate = startDate;
}
public String getEndDate() {
return endDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
}
| 21.160714 | 62 | 0.643882 |
4f74fffaacaf76b497c5d84d138e6ebb69280525 | 1,003 | package com.ducetech.api.web;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 用于管理 WebContext 对象的生命周期
*/
public class WebContextFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
if (request.getMethod().equalsIgnoreCase("OPTIONS")) {
return;
}
WebContext.init(request, response);
try {
filterChain.doFilter(request, response);
} finally {
WebContext.destroy();
}
}
@Override
public void destroy() {
}
} | 27.108108 | 152 | 0.694915 |
62df39d4949269c38c9d1084407ebd0d1ccb23c1 | 3,739 | package com.mmr2410.firstscoutingapp;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
/**
* Created by Cooper on 2/15/14.
*/
public class Bluetooth extends Thread{
String tag = "FIRST-Scouting";
BluetoothServerSocket bss;
UUID applicationUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
BufferedReader reader;
MainActivity parent;
public Bluetooth(MainActivity parent) {
this.parent = parent;
}
public void recieveFromDevice(){
BluetoothAdapter bt = BluetoothAdapter.getDefaultAdapter();
try {
bss = bt.listenUsingRfcommWithServiceRecord(tag, applicationUUID);
} catch (IOException e) {
Log.e(tag, "ERROR CODE 400: " + e.toString());
}
final MainActivity fparent = parent;
new Thread(new Runnable() {
public void run() {
boolean bool = true;
int i = 0;
while(bool){
BluetoothSocket connection;
try {
connection = bss.accept();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
fparent.handleReceiveFromDevice(reader.readLine());
stream.close();
} catch (IOException e) {
Log.e(tag, "ERROR CODE 401: " + e.toString());
}
if(i>5000){
Log.d(tag,"didn't recieve data, closing thread");
bool = false;
}
i++;
}
}
}).start();
try {
bss.close();
} catch (IOException e) {
Log.e(tag, "ERROR CODE 401: " + e.getMessage());
}
}
public void sendData(String host, String data){
BluetoothAdapter bt = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = bt.getBondedDevices();
BluetoothSocket socket;
for(BluetoothDevice b:pairedDevices){
if(b.getName().equals(host)){
try {
Log.d(tag,"sending to "+host+"...");
socket = b.createRfcommSocketToServiceRecord(applicationUUID);
OutputStream out = socket.getOutputStream();
out.write(data.getBytes());
socket.close();
Log.d(tag,"done.");
} catch (IOException e) {
Log.e(tag, "ERROR CODE 402: " + e.toString());
}
}
}
}
public Set<BluetoothDevice> getPairedDevices(){
BluetoothAdapter bt = BluetoothAdapter.getDefaultAdapter();
return bt.getBondedDevices();
}
public ArrayList<String> getDeviceNames(){
ArrayList<String> btDevices = new ArrayList<String>();
BluetoothAdapter bt = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = bt.getBondedDevices();
for(BluetoothDevice b:pairedDevices){
btDevices.add(b.getName());
}
return btDevices;
}
public String getAddress(){
return BluetoothAdapter.getDefaultAdapter().getAddress();
}
}
| 32.798246 | 83 | 0.565392 |
5efb3986781da50331b503137b06e2d4225e4252 | 145 | package com.hugeinc.db;
import java.sql.SQLException;
public interface BarDataInsertService {
void createDatabase() throws SQLException;
}
| 14.5 | 44 | 0.793103 |
a432151b4bf9e0fe7653ae2ff8e2e253b6267edf | 272 | package com.edudev.dscatalog.api.exceptions;
public final class NotFoundHttpException extends RuntimeException{
public NotFoundHttpException() {
this("Entity not found");
}
public NotFoundHttpException(final String msg) {
super(msg);
}
} | 22.666667 | 66 | 0.705882 |
cbc2cba30a5387894506c74a83bbac74d9da0389 | 2,937 | /**
Copyright 2008-2010 University of Rochester
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 edu.ur.hibernate.metadata.dc;
import org.springframework.context.ApplicationContext;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.testng.annotations.Test;
import edu.ur.hibernate.metadata.helper.test.ContextHolder;
import edu.ur.metadata.dc.DublinCoreTerm;
import edu.ur.metadata.dc.DublinCoreTermDAO;
/**
* @author Nathan Sarr
*
*/
public class DublinCoreTermDAOTest {
/** spring application context manager */
ApplicationContext ctx = ContextHolder.getApplicationContext();
/** dublin core element data access object */
DublinCoreTermDAO dublinCoreTermDAO = (DublinCoreTermDAO)ctx.getBean("dublinCoreTermDAO");
/** platform transaction manager */
PlatformTransactionManager tm = (PlatformTransactionManager)ctx.getBean("transactionManager");
/** transaction definition */
TransactionDefinition td = new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRED);
/**
* Test dublin core term persistence
*/
@Test
public void baseDublinCoreTermDAOTest() throws Exception{
DublinCoreTerm element = new DublinCoreTerm("Dublin Core Element");
element.setDescription("ctDescription");
element.setIsSimpleDublinCoreElement(true);
TransactionStatus ts = tm.getTransaction(td);
dublinCoreTermDAO.makePersistent(element);
tm.commit(ts);
ts = tm.getTransaction(td);
DublinCoreTerm other = dublinCoreTermDAO.getById(element.getId(), false);
assert other.equals(element) : "Dublin Core Terms should be equal mt = " + element + " other = " + other;
DublinCoreTerm dublinCoreElementByName = dublinCoreTermDAO.findByUniqueName(element.getName());
assert dublinCoreElementByName.equals(element) : "Dublin core element should be found " + element;
dublinCoreTermDAO.makeTransient(other);
assert dublinCoreTermDAO.getById(other.getId(), false) == null : "Should no longer be able to find dublin core term";
tm.commit(ts);
}
}
| 39.16 | 127 | 0.728635 |
63020278349b40ebbac4be96d4adfb109357ded3 | 1,911 | /*
* This file is part of ToolBox
* https://github.com/perbone/toolbox/
*
* Copyright 2013-2018 Paulo Perbone
*
* 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.perbone.toolbox.id;
import java.util.Arrays;
/**
* UUID standard implementation.
*
* @author Paulo Perbone <pauloperbone@yahoo.com>
* @since 0.1.0
*/
public final class Uuid
{
/** Raw value */
private final byte id[];
/**
* Creates the object based on the given raw value.
*
* @param id
* the raw value
*/
public Uuid(byte[] id)
{
this.id = id;
}
/**
* Returns the raw value.
*
* @return the raw value
*/
public byte[] value()
{
return id;
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(id);
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;
Uuid other = (Uuid) obj;
if (!Arrays.equals(id, other.id))
return false;
return true;
}
@Override
public String toString()
{
return "Uuid [id=" + Arrays.toString(id) + "]";
}
} | 22.482353 | 75 | 0.586604 |
d6f2535db0081dbb50c6f6fbafcb8c43da82cfa9 | 2,749 | package com.covens.common.core.gen;
import java.util.Random;
import com.covens.common.block.ModBlocks;
import com.covens.common.core.statics.ModConfig;
import net.minecraft.block.Block;
import net.minecraft.block.BlockHorizontal;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.BlockPos.MutableBlockPos;
import net.minecraft.world.World;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.chunk.IChunkProvider;
import net.minecraft.world.gen.IChunkGenerator;
import net.minecraftforge.common.BiomeDictionary;
import net.minecraftforge.fml.common.IWorldGenerator;
public class WorldGenBeehive implements IWorldGenerator {
private static void generateBeehives(World world, Random random, int chunkX, int chunkZ) {
final MutableBlockPos variableBlockPos = new BlockPos.MutableBlockPos();
if (random.nextFloat() < (ModConfig.WORLD_GEN.beehive.beehive_gen_chance / 33.0f)) {
int x = chunkX + random.nextInt(16);
int z = chunkZ + random.nextInt(16);
int y = world.getHeight(x, z) - 1; // if there is a tree, world height will be just above the top leaves of the
// tree.
variableBlockPos.setPos(x, y, z);
if (!isBlockLeaves(world, variableBlockPos)) {
return;
}
int newY = getHeightOfFirstAirBlockBelowLeaves(world, new MutableBlockPos(x, y, z));
if (newY < 0) {
return;
}
variableBlockPos.setY(newY);
world.setBlockState(variableBlockPos, ModBlocks.beehive.getDefaultState().withProperty(BlockHorizontal.FACING, EnumFacing.HORIZONTALS[random.nextInt(4)]), 2);
}
}
private static boolean isBlockLeaves(World world, BlockPos blockPos) {
IBlockState blockState = world.getBlockState(blockPos);
final Block block = blockState.getBlock();
return block.isLeaves(blockState, world, blockPos);
}
private static int getHeightOfFirstAirBlockBelowLeaves(World world, MutableBlockPos pos) {
final IBlockState blockState = world.getBlockState(pos);
final Block block = blockState.getBlock();
if (block.isLeaves(blockState, world, pos)) {
pos.setY(pos.getY() - 1);
return getHeightOfFirstAirBlockBelowLeaves(world, pos);
}
if (world.isAirBlock(pos)) {
return pos.getY();
}
return -1;
}
@Override
public void generate(Random random, int chunkX, int chunkZ, World world, IChunkGenerator chunkGenerator, IChunkProvider chunkProvider) {
final Biome biome = world.getBiomeForCoordsBody(new BlockPos(chunkX, 0, chunkZ));
if (BiomeDictionary.hasType(biome, BiomeDictionary.Type.END) || BiomeDictionary.hasType(biome, BiomeDictionary.Type.NETHER)) {
return;
}
generateBeehives(world, random, (chunkX * 16) + 8, (chunkZ * 16) + 8);
}
}
| 38.180556 | 161 | 0.758821 |
b0904b5baabb52191b6bac712e90b384ce2b8281 | 1,842 | /*
*
* * Copyright 2014 Orient Technologies LTD (info(at)orientechnologies.com)
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
* * For more information: http://www.orientechnologies.com
*
*/
package com.orientechnologies.orient.core.collate;
import com.orientechnologies.orient.core.index.OCompositeKey;
import com.orientechnologies.common.comparator.ODefaultComparator;
/**
* Case insensitive collate.
*
* @author Luca Garulli (l.garulli--at--orientechnologies.com)
*
*/
public class OCaseInsensitiveCollate extends ODefaultComparator implements OCollate {
public static final String NAME = "ci";
public String getName() {
return NAME;
}
public Object transform(final Object obj) {
if (obj instanceof String)
return ((String) obj).toLowerCase();
return obj;
}
@Override
public int hashCode() {
return getName().hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj==null || obj.getClass() != this.getClass())
return false;
final OCaseInsensitiveCollate that = (OCaseInsensitiveCollate) obj;
return getName().equals(that.getName());
}
@Override
public String toString() {
return "{" + getClass().getSimpleName() + " : name = " + getName() + "}";
}
}
| 28.338462 | 85 | 0.680239 |
2c17a658dcef6db688de3dae7334df03dceff6c1 | 7,225 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package st.jigasoft.dbutil.util;
import java.awt.Color;
import java.awt.ComponentOrientation;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FocusTraversalPolicy;
import java.awt.Font;
import java.awt.LayoutManager;
import java.awt.Rectangle;
import java.awt.dnd.DropTarget;
import java.util.Locale;
import javax.swing.JComponent;
import javax.swing.TransferHandler;
import javax.swing.border.Border;
/**
*
* @author Servidor
*/
public class DUStyle
{
public static void applyComponet (JComponent fontStyle, JComponent reciviStyle)
{
reciviStyle.setAlignmentX(fontStyle.getAlignmentX());
reciviStyle.setAlignmentY(fontStyle.getAlignmentY());
reciviStyle.setBackground(fontStyle.getBackground());
reciviStyle.setBorder(fontStyle.getBorder());
reciviStyle.setBounds(fontStyle.getBounds());
reciviStyle.setComponentOrientation(fontStyle.getComponentOrientation());
// component.setComponentPopupMenu(style.getComponentPopupMenu());
//component.setComponentZOrder(style., WIDTH);
reciviStyle.setCursor(fontStyle.getCursor());
reciviStyle.setDebugGraphicsOptions(fontStyle.getDebugGraphicsOptions());
reciviStyle.setDoubleBuffered(fontStyle.isDoubleBuffered());
reciviStyle.setDropTarget(fontStyle.getDropTarget());
reciviStyle.setEnabled(fontStyle.isEnabled());
reciviStyle.setFocusCycleRoot(fontStyle.isFocusCycleRoot());
//component.setFocusTraversalKeys(style.getF, null);
reciviStyle.setFocusTraversalKeysEnabled(fontStyle.getFocusTraversalKeysEnabled());
reciviStyle.setFocusTraversalPolicy(fontStyle.getFocusTraversalPolicy());
reciviStyle.setFocusTraversalPolicyProvider(fontStyle.isFocusTraversalPolicyProvider());
reciviStyle.setFocusable(fontStyle.isFocusable());
reciviStyle.setFont(fontStyle.getFont());
reciviStyle.setForeground(fontStyle.getForeground());
reciviStyle.setLayout(fontStyle.getLayout());
reciviStyle.setLocale(fontStyle.getLocale());
//component.setLocation(style.getLocation());
reciviStyle.setMaximumSize(fontStyle.getMaximumSize());
reciviStyle.setMinimumSize(fontStyle.getMinimumSize());
reciviStyle.setOpaque(fontStyle.isOpaque());
reciviStyle.setPreferredSize(fontStyle.getPreferredSize());
reciviStyle.setRequestFocusEnabled(fontStyle.isRequestFocusEnabled());
reciviStyle.setSize(fontStyle.getSize());
reciviStyle.setToolTipText(fontStyle.getToolTipText());
reciviStyle.setTransferHandler(fontStyle.getTransferHandler());
reciviStyle.setVisible(fontStyle.isVisible());
}
public static void applyComponet (DUStyle dbStyle, JComponent reciviStyle)
{
if(dbStyle.alterAlignmentX) reciviStyle.setAlignmentX(dbStyle.alignmentX);
reciviStyle.setAlignmentY(dbStyle.alignmentY);
reciviStyle.setBackground(dbStyle.background);
reciviStyle.setBorder(dbStyle.border);
reciviStyle.setBounds(dbStyle.bounds);
reciviStyle.setComponentOrientation(dbStyle.componentOrientation);
// component.setComponentPopupMenu(style.getComponentPopupMenu);
//component.setComponentZOrder(style., WIDTH);
reciviStyle.setCursor(dbStyle.cursor);
reciviStyle.setDebugGraphicsOptions(dbStyle.debugGraphicsOptions);
reciviStyle.setDoubleBuffered(dbStyle.doubleBuffered);
reciviStyle.setDropTarget(dbStyle.dropTarget);
reciviStyle.setEnabled(dbStyle.enabled);
reciviStyle.setFocusCycleRoot(dbStyle.focusCycleRoot);
//component.setFocusTraversalKeys(style.getF, null);
reciviStyle.setFocusTraversalKeysEnabled(dbStyle.focusTraversalKeysEnabled);
reciviStyle.setFocusTraversalPolicy(dbStyle.focusTraversalPolicy);
reciviStyle.setFocusTraversalPolicyProvider(dbStyle.focusTraversalPolicyProvider);
reciviStyle.setFocusable(dbStyle.focusable);
reciviStyle.setFont(dbStyle.font);
reciviStyle.setForeground(dbStyle.foreground);
reciviStyle.setLayout(dbStyle.layout);
reciviStyle.setLocale(dbStyle.locale);
//component.setLocation(style.getLocation);
reciviStyle.setMaximumSize(dbStyle.maximumSize);
reciviStyle.setMinimumSize(dbStyle.minimumSize);
reciviStyle.setOpaque(dbStyle.opaque);
reciviStyle.setPreferredSize(dbStyle.preferredSize);
reciviStyle.setRequestFocusEnabled(dbStyle.requestFocusEnabled);
reciviStyle.setSize(dbStyle.size);
reciviStyle.setToolTipText(dbStyle.toolTipText);
reciviStyle.setTransferHandler(dbStyle.transferHandler);
reciviStyle.setVisible(dbStyle.visible);
}
public float alignmentY;
public float alignmentX;
public Color background;
public Border border;
public Rectangle bounds;
public ComponentOrientation componentOrientation;
public Cursor cursor;
public int debugGraphicsOptions;
public boolean doubleBuffered;
public DropTarget dropTarget;
public boolean enabled;
public boolean focusCycleRoot;
public boolean focusTraversalKeysEnabled;
public FocusTraversalPolicy focusTraversalPolicy;
public boolean focusTraversalPolicyProvider;
public boolean focusable;
public Font font;
public Color foreground;
public Locale locale;
public LayoutManager layout;
public Dimension minimumSize;
public Dimension maximumSize;
public boolean opaque;
public Dimension preferredSize;
public boolean requestFocusEnabled;
public Dimension size;
public String toolTipText;
public TransferHandler transferHandler;
public boolean visible;
private boolean alterAlignmentY;
private boolean alterAlignmentX;
private boolean alterBackground;
private boolean alterBorder;
private boolean alterBounds;
private boolean alterComponentOrientation;
private boolean alterCursor;
private boolean alteDebugGraphicsOptions;
private boolean alterDoubleBuffered;
private boolean alterDropTarget;
private boolean alterEnabled;
private boolean alterFocusCycleRoot;
private boolean alterFocusTraversalKeysEnabled;
private boolean alterFocusTraversalPolicy;
private boolean alterFocusTraversalPolicyProvider;
private boolean alterFocusable;
private boolean alterFont;
private boolean alterForeground;
private boolean alterLocale;
private boolean alterLayout;
private boolean alterMinimumSize;
private boolean alterMaximumSize;
private boolean alterOpaque;
private boolean alterPreferredSize;
private boolean alterRequestFocusEnabled;
private boolean alterSize;
private boolean alterToolTipText;
private boolean alterTransferHandler;
private boolean alterVisible;
}
| 44.325153 | 97 | 0.742145 |
9b3cb68fb14fc3bcbdd57227511348955e102e73 | 4,342 | /*
*
* * Copyright 2010-2016 OrientDB LTD (http://orientdb.com)
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
* * For more information: http://orientdb.com
*
*/
package com.orientechnologies.orient.core.command.script;
import com.orientechnologies.orient.core.command.OCommandDistributedReplicateRequest;
import com.orientechnologies.orient.core.command.OCommandRequestText;
import com.orientechnologies.orient.core.command.OCommandRequestTextAbstract;
import com.orientechnologies.orient.core.exception.OSerializationException;
import com.orientechnologies.orient.core.serialization.OMemoryStream;
import com.orientechnologies.orient.core.serialization.OSerializableStream;
import com.orientechnologies.orient.core.serialization.serializer.record.ORecordSerializer;
import javax.script.CompiledScript;
/**
* Script command request implementation. It just stores the request and delegated the execution to the configured OCommandExecutor.
*
*
* @see OCommandExecutorScript
* @author Luca Garulli (l.garulli--(at)--orientdb.com)
*
*/
@SuppressWarnings("serial")
public class OCommandScript extends OCommandRequestTextAbstract {
private String language;
private CompiledScript compiledScript;
private OCommandDistributedReplicateRequest.DISTRIBUTED_EXECUTION_MODE executionMode = OCommandDistributedReplicateRequest.DISTRIBUTED_EXECUTION_MODE.LOCAL;
public OCommandScript() {
useCache = true;
}
public OCommandScript(final String iLanguage, final String iText) {
super(iText);
setLanguage(iLanguage);
useCache = true;
}
public OCommandScript(final String iText) {
this("sql", iText);
}
public boolean isIdempotent() {
return false;
}
public String getLanguage() {
return language;
}
public OCommandScript setLanguage(String language) {
if (language == null || language.isEmpty()) {
throw new IllegalArgumentException("Not a valid script language specified: " + language);
}
this.language = language;
return this;
}
public OCommandRequestText fromStream(byte[] iStream, ORecordSerializer serializer) throws OSerializationException {
final OMemoryStream buffer = new OMemoryStream(iStream);
language = buffer.getAsString();
// FIX TO HANDLE USAGE OF EXECUTION MODE STARTING FROM v2.1.3
final int currPosition = buffer.getPosition();
final String value = buffer.getAsString();
try {
executionMode = OCommandDistributedReplicateRequest.DISTRIBUTED_EXECUTION_MODE.valueOf(value);
} catch (IllegalArgumentException ignore) {
// OLD VERSION: RESET TO THE OLD POSITION
buffer.setPosition(currPosition);
}
fromStream(buffer,serializer);
return this;
}
public byte[] toStream() throws OSerializationException {
final OMemoryStream buffer = new OMemoryStream();
buffer.setUtf8(language);
buffer.setUtf8(executionMode.name());
return toStream(buffer);
}
public CompiledScript getCompiledScript() {
return compiledScript;
}
public void setCompiledScript(CompiledScript script) {
compiledScript = script;
}
@Override
public String toString() {
if (language != null)
return language + "." + text;
return "script." + text;
}
public OCommandDistributedReplicateRequest.DISTRIBUTED_EXECUTION_MODE getExecutionMode() {
return executionMode;
}
public OCommandScript setExecutionMode(OCommandDistributedReplicateRequest.DISTRIBUTED_EXECUTION_MODE executionMode) {
this.executionMode = executionMode;
return this;
}
}
| 34.460317 | 159 | 0.706817 |
a2ce0f52f57e92f6e6b3a9f948f7802b5beb1239 | 1,099 | package net.jarlehansen.proto2javame.business.sourcebuilder.publicmethods;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import net.jarlehansen.proto2javame.testutils.TestConstants;
import net.jarlehansen.proto2javame.testutils.TestObjectFactory;
import org.junit.Before;
import org.junit.Test;
/**
*
* @author hansjar@gmail.com Jarle Hansen
*
*/
public class PublicMethodsBuilderImplTest {
private PublicMethodsBuilder publicMethodsBuilder;
@Before
public void setUp() {
publicMethodsBuilder = new PublicMethodsBuilderImpl();
}
@Test
public void testCreatePublicMethods() {
assertThat(publicMethodsBuilder.createPublicMethods(TestConstants.PROTO_CLASS_NAME, TestObjectFactory
.createTestProtoFileInput()), is(StringBuilder.class));
}
@Test
public void testCreatePublicMethodsAssertSource() {
final StringBuilder builder = publicMethodsBuilder.createPublicMethods(TestConstants.PROTO_CLASS_NAME,
TestObjectFactory.createTestProtoFileInput());
assertTrue(builder.length() > 0);
}
}
| 28.179487 | 104 | 0.808917 |
058a9d67ee6940ceeaed932358426b3f9b0be1a4 | 939 | package com.shadow.blog.service.impl;
import com.shadow.blog.entity.TagDO;
import com.shadow.blog.mapper.TagMapper;
import com.shadow.blog.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author L.R
* @date 2022-4-29 8:37
*/
@Service
public class TagServiceImpl implements TagService {
@Autowired
private TagMapper tagMapper;
@Override
public List<TagDO> listTag() {
return tagMapper.listTag();
}
@Override
public List<TagDO> listTagByIds(String ids) {
return tagMapper.listTagByIds(ids);
}
@Override
public Boolean insertTag(TagDO tagDO) {
return tagMapper.insert(tagDO) == 1;
}
@Override
public Boolean updateTag(TagDO tagDO) {
return tagMapper.updateById(tagDO) == 1;
}
@Override
public Boolean deletaTag(String id) {
return tagMapper.deleteById(id) == 1;
}
}
| 20.866667 | 62 | 0.72737 |
b1deb9495857d090c11aa9ad10b87f16c3e87316 | 7,064 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.farwolf.weex.adapter;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.Base64;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.farwolf.util.FileTool;
import com.farwolf.util.Picture;
import com.farwolf.weex.activity.WeexActivity;
import com.farwolf.weex.util.Weex;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import com.taobao.weex.WXEnvironment;
import com.taobao.weex.adapter.IWXImgLoaderAdapter;
import com.taobao.weex.common.WXImageStrategy;
import com.taobao.weex.dom.WXImageQuality;
import java.util.HashMap;
public class PicassoImageAdapter implements IWXImgLoaderAdapter {
static HashMap<String,Drawable> placeholders=new HashMap<>();
public PicassoImageAdapter() {
}
@Override
public void setImage(final String url, final ImageView view,
final WXImageQuality quality, final WXImageStrategy strategy) {
// WXSDKManager.getInstance().postOnUiThread(new Runnable() {
//
// @Override
// public void run() {
if(view==null||view.getLayoutParams()==null){
return;
}
if (TextUtils.isEmpty(url)) {
view.setImageBitmap(null);
if(strategy==null||strategy.placeHolder==null)
return;
}
String temp = url;
if (view.getLayoutParams().width <= 0 || view.getLayoutParams().height <= 0) {
return;
}
WeexActivity a= (WeexActivity)view.getContext();
temp=Weex.getRelativeUrl(url,a.mWXSDKInstance);
if(temp.startsWith("http"))
{
loadHttp(temp,view,quality,strategy);
}
else
{
loadLocal(temp,view,quality,strategy);
}
// }
// },0);
}
public void loadHttp(final String url,final ImageView view,
WXImageQuality quality, final WXImageStrategy strategy)
{
Drawable pladrawable=null;
if(!TextUtils.isEmpty(strategy.placeHolder)){
if(placeholders.containsKey(strategy.placeHolder))
{
pladrawable=placeholders.get(strategy.placeHolder);
}
else
{
if(strategy.placeHolder!=null)
{
WeexActivity a= (WeexActivity)view.getContext();
String placeholder=Weex.getRelativeUrl(strategy.placeHolder,a.mWXSDKInstance);
// String placeholder=strategy.placeHolder.replace("root:",Weex.baseurl);
placeholder=placeholder.replace(Weex.getBaseUrl(a.mWXSDKInstance),"app/");
Bitmap bm= FileTool.loadAssetImage(placeholder,((Activity)view.getContext()).getApplicationContext());
pladrawable =new BitmapDrawable(bm);
placeholders.put(strategy.placeHolder,pladrawable);
}
}
}
if(url.toLowerCase().contains(".gif"))
{
Glide
.with((Activity)view.getContext())
.load(url)
.asGif()
.placeholder(pladrawable)
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.into(view);
return;
}
Picasso.with(WXEnvironment.getApplication())
.load(url)
.placeholder(pladrawable)
.transform(new BlurTransformation(strategy.blurRadius))
.into(view, new Callback() {
@Override
public void onSuccess() {
if(strategy.getImageListener()!=null){
strategy.getImageListener().onImageFinish(url,view,true,null);
}
}
@Override
public void onError() {
if(strategy.getImageListener()!=null){
strategy.getImageListener().onImageFinish(url,view,false,null);
}
}
});
}
public void loadLocal(String url,final ImageView view,
WXImageQuality quality, final WXImageStrategy strategy)
{
Drawable pladrawable=null;
if(!TextUtils.isEmpty(strategy.placeHolder)){
if(placeholders.containsKey(strategy.placeHolder))
{
pladrawable=placeholders.get(strategy.placeHolder);
}
else
{
if(strategy.placeHolder!=null)
{
// String placeholder=strategy.placeHolder.replace("root:",Weex.baseurl);
WeexActivity a= (WeexActivity)view.getContext();
String placeholder=Weex.getRelativeUrl(strategy.placeHolder,a.mWXSDKInstance);
Bitmap bmx= FileTool.loadAssetImage(placeholder,((Activity)view.getContext()).getApplicationContext());
pladrawable =new BitmapDrawable(bmx);
placeholders.put(strategy.placeHolder,pladrawable);
}
}
}
view.setImageDrawable(pladrawable);
if(url.toLowerCase().contains(".gif"))
{
Glide
.with((Activity)view.getContext())
.load("file:///android_asset/"+url)
.asGif()
.placeholder(pladrawable)
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.into(view);
return;
}
if(url.startsWith("sdcard:"))
{
url=url.replace("sdcard:","");
Bitmap bm= Picture.getBitmap(url);
view.setImageBitmap(bm);
return;
}
url=Weex.getSingleRealUrl(url);
Bitmap bm=null;
if(url.startsWith("base64==="))
{
url=url.replace("base64===","");
bm= base64ToBitmap(url);
}
else
{
bm= FileTool.loadAssetImage(url,view.getContext().getApplicationContext());
}
if(bm!=null)
view.setImageBitmap(bm);
}
public static Bitmap base64ToBitmap(String base64Data) {
byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}
}
| 29.932203 | 121 | 0.618913 |
7ab70ace9569fba5211564ff44d270054f731eee | 1,890 | package com.rapid7.armor.interval;
import java.time.Clock;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZoneOffset;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class IntervalStrategyTest {
@Test
public void testWeekly() {
Instant ld = LocalDate.parse("2021-02-22").atStartOfDay().toInstant(ZoneOffset.UTC);
assertEquals("2021-02-22T00:00:00Z", Interval.WEEKLY.getIntervalStart(ld));
}
@Test
public void testFixed() {
Clock clock = Clock.fixed(Instant.parse("2021-01-01T00:15:00Z"), ZoneId.of("UTC"));
IntervalStrategy intervalStrategy = new IntervalStrategyFixed(12 * 60 * 60 * 1000);
assertEquals(Long.toString(12 * 60), intervalStrategy.getInterval());
assertEquals("2021-01-01T00:00:00Z", intervalStrategy.getIntervalStart(Instant.now(clock)));
}
@Test
public void testSingle() {
IntervalStrategy intervalStrategy = new IntervalStrategySingle();
assertEquals("single", intervalStrategy.getInterval());
assertEquals("1970-01-01T00:00:00Z", intervalStrategy.getIntervalStart(Instant.now()));
}
@Test
public void testMonthly() {
Clock clock = Clock.fixed(Instant.parse("2021-03-24T01:15:05Z"), ZoneId.of("UTC"));
IntervalStrategy intervalStrategy = new IntervalStrategyMonthly();
assertEquals("monthly", intervalStrategy.getInterval());
assertEquals("2021-03-01T00:00:00Z", intervalStrategy.getIntervalStart(Instant.now(clock)));
}
@Test
public void testYearly() {
Clock clock = Clock.fixed(Instant.parse("2021-03-24T01:15:05Z"), ZoneId.of("UTC"));
IntervalStrategy intervalStrategy = new IntervalStrategyYearly();
assertEquals("yearly", intervalStrategy.getInterval());
assertEquals("2021-01-01T00:00:00Z", intervalStrategy.getIntervalStart(Instant.now(clock)));
}
}
| 34.363636 | 96 | 0.737037 |
8cf6a84ada278cacdd1c0ea922ed536db40ccd04 | 1,341 | package data_structure;
import java.util.LinkedList;
import java.util.Queue;
public class Q346MovingAverageFromDataStream {
//TAG: Google
//TAG: data structure
//TAG: sliding window
//Difficulty: Easy
/**
* 346. Moving Average from Data Stream
* Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
For example,
MovingAverage m = new MovingAverage(3);
m.next(1) = 1
m.next(10) = (1 + 10) / 2
m.next(3) = (1 + 10 + 3) / 3
m.next(5) = (10 + 3 + 5) / 3
*/
/**
* Solution:
* Use Queue to represent the sliding window, and avoid sum over flow
*/
class MovingAverage {
/** Initialize your data structure here. */
long sum;
int count, size;
private Queue<Integer> queue;
public MovingAverage(int size) {
this.queue = new LinkedList<>();
sum = 0;
count = 0;
this.size = size;
}
public double next(int val) {
sum += val;
count++;
queue.offer(val);
if (count > size) {
Integer poll = queue.poll();
sum -= poll;
count--;
}
return (double)sum/count;
}
}
}
| 22.728814 | 120 | 0.519761 |
ebc33de16c2fe3531ab8c10fd30d5e73cc76f40f | 3,537 | /*
* Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved.
*/
package com.sap.retail.commercesuite.saparticleb2caddon.populator;
import java.util.ArrayList;
import java.util.List;
import com.sap.retail.commercesuite.saparticleb2caddon.articlecomponent.data.ArticleComponentData;
import com.sap.retail.commercesuite.saparticlemodel.articlecomponent.ArticleComponentService;
import com.sap.retail.commercesuite.saparticlemodel.model.ArticleComponentModel;
import de.hybris.platform.commercefacades.product.converters.populator.AbstractProductPopulator;
import de.hybris.platform.commercefacades.product.data.ProductData;
import de.hybris.platform.core.model.product.ProductModel;
import de.hybris.platform.servicelayer.dto.converter.Converter;
/**
* Populator to enrich product data with article component data.
*
* The populator class retrieves for articles that are structured articles their article components. For each article
* component an article component data object is created that contains the component product, the quantity and the unit
* of measure for the component. The determined product model of the component article is converted by the product
* converter instance to get a full product data object of the component article.
*
* @param <SOURCE>
* the product model
* @param <TARGET>
* the product data
*/
public class ArticleComponentPopulator<SOURCE extends ProductModel, TARGET extends ProductData> extends
AbstractProductPopulator<SOURCE, TARGET>
{
private Converter<ProductModel, ProductData> productConverter;
private ArticleComponentService articleComponentService;
/*
* (non-Javadoc)
*
* @see de.hybris.platform.converters.Populator#populate(java.lang.Object, java.lang.Object)
*/
@Override
public void populate(final SOURCE productModel, final TARGET productData)
{
// Do this only for articles that are structured articles
// i.e. the structured article type must be not empty
if (productModel.getStructuredArticleType() != null && !productModel.getStructuredArticleType().toString().isEmpty())
{
final List<ArticleComponentModel> articleComponentModels = articleComponentService
.getComponentsOfStructuredArticle(productModel);
final List<ArticleComponentData> articleComponents = new ArrayList<ArticleComponentData>();
for (final ArticleComponentModel articleComponentModel : articleComponentModels)
{
final ArticleComponentData articleComponent = new ArticleComponentData();
articleComponent.setComponent(productConverter.convert(articleComponentModel.getComponent()));
articleComponent.setQuantity(articleComponentModel.getQuantity());
articleComponent.setUnit(articleComponentModel.getUnit().getName());
articleComponents.add(articleComponent);
}
productData.setArticleComponents(articleComponents);
}
}
/**
* Sets the article component service to the actual article component service instance.
*
* @param articleComponentService
* the article component service to use
*/
public void setArticleComponentService(final ArticleComponentService articleComponentService)
{
this.articleComponentService = articleComponentService;
}
/**
* Sets the product converter to the actual product converter instance.
*
* @param productConverter
* the product converter instance to use
*/
public void setProductConverter(final Converter<ProductModel, ProductData> productConverter)
{
this.productConverter = productConverter;
}
}
| 38.868132 | 119 | 0.791066 |
3cb9ebddc733b214d2353e8f7216b930be2f7e70 | 5,057 | /*
* Copyright (c) 2014 AsyncHttpClient Project. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package org.asynchttpclient;
import static org.asynchttpclient.util.MiscUtil.getBoolean;
import org.asynchttpclient.util.DefaultHostnameVerifier;
import javax.net.ssl.HostnameVerifier;
public final class AsyncHttpClientConfigDefaults {
private AsyncHttpClientConfigDefaults() {
}
public static final String ASYNC_CLIENT = AsyncHttpClientConfig.class.getName() + ".";
public static int defaultMaxTotalConnections() {
return Integer.getInteger(ASYNC_CLIENT + "maxTotalConnections", -1);
}
public static int defaultMaxConnectionPerHost() {
return Integer.getInteger(ASYNC_CLIENT + "maxConnectionsPerHost", -1);
}
public static int defaultConnectionTimeOutInMs() {
return Integer.getInteger(ASYNC_CLIENT + "connectionTimeoutInMs", 60 * 1000);
}
public static int defaultIdleConnectionInPoolTimeoutInMs() {
return Integer.getInteger(ASYNC_CLIENT + "idleConnectionInPoolTimeoutInMs", 60 * 1000);
}
public static int defaultIdleConnectionTimeoutInMs() {
return Integer.getInteger(ASYNC_CLIENT + "idleConnectionTimeoutInMs", 60 * 1000);
}
public static int defaultRequestTimeoutInMs() {
return Integer.getInteger(ASYNC_CLIENT + "requestTimeoutInMs", 60 * 1000);
}
public static int defaultWebSocketIdleTimeoutInMs() {
return Integer.getInteger(ASYNC_CLIENT + "webSocketTimoutInMS", 15 * 60 * 1000);
}
public static int defaultMaxConnectionLifeTimeInMs() {
return Integer.getInteger(ASYNC_CLIENT + "maxConnectionLifeTimeInMs", -1);
}
public static boolean defaultRedirectEnabled() {
return Boolean.getBoolean(ASYNC_CLIENT + "redirectsEnabled");
}
public static int defaultMaxRedirects() {
return Integer.getInteger(ASYNC_CLIENT + "maxRedirects", 5);
}
public static boolean defaultCompressionEnabled() {
return Boolean.getBoolean(ASYNC_CLIENT + "compressionEnabled");
}
public static String defaultUserAgent() {
return System.getProperty(ASYNC_CLIENT + "userAgent", "NING/1.0");
}
public static int defaultIoThreadMultiplier() {
return Integer.getInteger(ASYNC_CLIENT + "ioThreadMultiplier", 2);
}
public static boolean defaultUseProxySelector() {
return Boolean.getBoolean(ASYNC_CLIENT + "useProxySelector");
}
public static boolean defaultUseProxyProperties() {
return Boolean.getBoolean(ASYNC_CLIENT + "useProxyProperties");
}
public static boolean defaultStrict302Handling() {
return Boolean.getBoolean(ASYNC_CLIENT + "strict302Handling");
}
public static boolean defaultAllowPoolingConnection() {
return getBoolean(ASYNC_CLIENT + "allowPoolingConnection", true);
}
public static boolean defaultUseRelativeURIsWithSSLProxies() {
return getBoolean(ASYNC_CLIENT + "useRelativeURIsWithSSLProxies", true);
}
// unused/broken, left there for compatibility, fixed in Netty 4
public static int defaultRequestCompressionLevel() {
return Integer.getInteger(ASYNC_CLIENT + "requestCompressionLevel", -1);
}
public static int defaultMaxRequestRetry() {
return Integer.getInteger(ASYNC_CLIENT + "maxRequestRetry", 5);
}
public static boolean defaultAllowSslConnectionPool() {
return getBoolean(ASYNC_CLIENT + "allowSslConnectionPool", true);
}
public static boolean defaultUseRawUrl() {
return Boolean.getBoolean(ASYNC_CLIENT + "useRawUrl");
}
public static boolean defaultRemoveQueryParamOnRedirect() {
return getBoolean(ASYNC_CLIENT + "removeQueryParamOnRedirect", true);
}
public static HostnameVerifier defaultHostnameVerifier() {
return new DefaultHostnameVerifier();
}
public static boolean defaultSpdyEnabled() {
return Boolean.getBoolean(ASYNC_CLIENT + "spdyEnabled");
}
public static int defaultSpdyInitialWindowSize() {
return Integer.getInteger(ASYNC_CLIENT + "spdyInitialWindowSize", 10 * 1024 * 1024);
}
public static int defaultSpdyMaxConcurrentStreams() {
return Integer.getInteger(ASYNC_CLIENT + "spdyMaxConcurrentStreams", 100);
}
public static boolean defaultAcceptAnyCertificate() {
return getBoolean(ASYNC_CLIENT + "acceptAnyCertificate", false);
}
}
| 35.865248 | 114 | 0.724738 |
854c2eb864cd46803f1948b83cdbaecadf8f76ff | 1,983 | package com.entity;
/*
* 考勤实体类
*/
public class AttendanceBean {
//考勤id
private int id;
//学生编号
private String code;
//学生姓名
private String name;
//年级名
private String gradeName;
//班级名
private String className;
//科目名
private String subjectName;
//考勤类型
private String type;
//考勤时间
private String time;
//学生id
private int sId;
//科目id
private int subId;
//班级id
private int classId;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGradeName() {
return gradeName;
}
public void setGradeName(String gradeName) {
this.gradeName = gradeName;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getSubjectName() {
return subjectName;
}
public void setSubjectName(String subjectName) {
this.subjectName = subjectName;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public int getsId() {
return sId;
}
public void setsId(int sId) {
this.sId = sId;
}
public int getSubId() {
return subId;
}
public void setSubId(int subId) {
this.subId = subId;
}
public int getClassId() {
return classId;
}
public void setClassId(int classId) {
this.classId = classId;
}
}
| 16.663866 | 52 | 0.560767 |
144e6dd823f7739244d8d546bd6639970515a9f2 | 1,379 | package cn.wz.algorithm.stdlib;
/*************************************************************************
* Compilation: javac HexDump.java
* Execution: java HexDump < file
* Dependencies: BinaryStdIn.java
* Data file: http://introcs.cs.princeton.edu/stdlib/abra.txt
*
* Reads in a binary file and writes out the bytes in hex, 16 per line.
*
* % more abra.txt
* ABRACADABRA!
*
* % java HexDump 16 < abra.txt
* 41 42 52 41 43 41 44 41 42 52 41 21
* 96 bits
*
* % hexdump < abra.txt
*
* % od -t x1 < abra.txt
* 0000000 41 42 52 41 43 41 44 41 42 52 41 21
* 0000014
*
*************************************************************************/
public class HexDump {
public static void main(String[] args) {
int BYTES_PER_LINE = 16;
if (args.length == 1) {
BYTES_PER_LINE = Integer.parseInt(args[0]);
}
int i;
for (i = 0; !BinaryStdIn.isEmpty(); i++) {
if (BYTES_PER_LINE == 0) { BinaryStdIn.readChar(); continue; }
if (i == 0) StdOut.printf("");
else if (i % BYTES_PER_LINE == 0) StdOut.printf("\n", i);
else StdOut.print(" ");
char c = BinaryStdIn.readChar();
StdOut.printf("%02x", c & 0xff);
}
if (BYTES_PER_LINE != 0) StdOut.println();
StdOut.println((i*8) + " bits");
}
}
| 29.340426 | 75 | 0.496012 |
d741da4cea7efe25e6fb5399efc5097d60d74399 | 1,541 | package mh.smartcard.util;
import mh.smartcard.UnexpectedException;
import mh.smartcard.data.Hex;
public final class ByteBuffer {
//private static final Logger logger = LoggerFactory.getLogger(ByteBuffer.class);
private final byte[] value;
private int pos;
public ByteBuffer(byte[] value) {
this.value = value;
this.pos = 0;
}
public ByteBuffer rewind() {
pos = 0;
return this;
}
public ByteBuffer position(int pos) {
if (pos < 0 || value.length < pos) {
String message = String.format("new position is out of range. pos = %d", pos);
//logger.error(message);
throw new UnexpectedException(message);
}
this.pos = pos;
return this;
}
public int position() {
return pos;
}
public int remaining() {
return value.length - pos;
}
public boolean hasRemaining() {
return remaining() != 0;
}
public int get() {
if (hasRemaining()) {
return value[pos++] & 0xFF;
} else {
String message = String.format("position exceeds end of element %s", Hex.toString(value));
//logger.error(message);
throw new UnexpectedException(message);
}
}
public byte[] getByteArray(int length) {
byte[] ret = new byte[length];
for(int i = 0; i < ret.length; i++) {
ret[i] = (byte)get();
}
return ret;
}
public int getShort() {
final int b0 = get();
final int b1 = get();
return (b0 << 8) | b1;
}
public int getInt() {
final int b0 = get();
final int b1 = get();
final int b2 = get();
final int b3 = get();
return (b0 << 24) | (b1 << 16) | (b2 << 8) | b3;
}
} | 23.348485 | 93 | 0.631408 |
dd6f62e7307187f661f6fd3a4c687f5b1cac9004 | 4,594 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.jira;
import com.atlassian.jira.rest.client.domain.BasicIssue;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.jira.mocks.MockJerseyJiraRestClientFactory;
import org.apache.camel.component.jira.mocks.MockJiraRestClient;
import org.apache.camel.component.jira.mocks.MockSearchRestClient;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.impl.JndiRegistry;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class IssueConsumerTest extends CamelTestSupport {
public static final Logger LOG = LoggerFactory.getLogger(IssueConsumerTest.class);
private static final String URL = "https://somerepo.atlassian.net";
private static final String USERNAME = "someguy";
private static final String PASSWORD = "xU3xjhay9yjEaZq";
private static final String JIRA_CREDENTIALS = URL + "&username=" + USERNAME + "&password=" + PASSWORD;
private static final String PROJECT = "camel-jira-component";
protected MockJerseyJiraRestClientFactory factory;
@Override
protected JndiRegistry createRegistry() throws Exception {
JndiRegistry registry = super.createRegistry();
factory = new MockJerseyJiraRestClientFactory();
registry.bind("JerseyJiraRestClientFactory", factory);
return registry;
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
context.addComponent("jira", new JIRAComponent());
from("jira://newIssue?serverUrl=" + JIRA_CREDENTIALS + "&jql=project=" + PROJECT + "&delay=500")
.process(new NewIssueProcessor())
.to("mock:result");
}
};
}
@Test
public void emptyAtStartupTest() throws Exception {
MockEndpoint mockResultEndpoint = getMockEndpoint("mock:result");
mockResultEndpoint.expectedMessageCount(0);
mockResultEndpoint.assertIsSatisfied();
}
@Test
public void singleIssueTest() throws Exception {
MockEndpoint mockResultEndpoint = getMockEndpoint("mock:result");
MockJiraRestClient client = factory.getClient();
MockSearchRestClient restClient = (MockSearchRestClient) client.getSearchClient();
BasicIssue issue1 = restClient.addIssue();
mockResultEndpoint.expectedBodiesReceived(issue1);
mockResultEndpoint.assertIsSatisfied();
}
@Test
public void multipleIssuesTest() throws Exception {
MockEndpoint mockResultEndpoint = getMockEndpoint("mock:result");
MockJiraRestClient client = factory.getClient();
MockSearchRestClient restClient = (MockSearchRestClient) client.getSearchClient();
BasicIssue issue1 = restClient.addIssue();
BasicIssue issue2 = restClient.addIssue();
BasicIssue issue3 = restClient.addIssue();
mockResultEndpoint.expectedBodiesReceived(issue3, issue2, issue1);
mockResultEndpoint.assertIsSatisfied();
}
/**
* Log new issues. Not really needed for this test, but useful for debugging.
*/
public class NewIssueProcessor implements Processor {
@Override
public void process(Exchange exchange) throws Exception {
Message in = exchange.getIn();
BasicIssue issue = in.getBody(BasicIssue.class);
LOG.debug("Got issue with id " + issue.getId() + " key " + issue.getKey());
}
}
}
| 39.603448 | 112 | 0.710057 |
0d303a772f90635f40aad89be4d0c2be7e6f9d19 | 1,193 | /*
* Copyright DataStax, 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 com.datastax.oss.dsbulk.partitioner;
import com.datastax.oss.driver.api.core.metadata.EndPoint;
import com.datastax.oss.driver.api.core.metadata.token.TokenRange;
import edu.umd.cs.findbugs.annotations.NonNull;
import java.math.BigInteger;
import java.util.Set;
public interface BulkTokenRange extends TokenRange {
/** @return The replicas that own this range. */
@NonNull
Set<EndPoint> replicas();
/** @return The range size (i.e. the number of tokens it contains). */
@NonNull
BigInteger size();
/** @return The ring fraction covered by this range. */
double fraction();
}
| 32.243243 | 75 | 0.742666 |
c84ae29d37108d5024adee72303179caeb7dfa7e | 3,005 | /**
* Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.master.marketdatasnapshot.impl;
import java.util.concurrent.ConcurrentHashMap;
import com.opengamma.core.change.ChangeEvent;
import com.opengamma.core.change.ChangeListener;
import com.opengamma.core.marketdatasnapshot.MarketDataSnapshotChangeListener;
import com.opengamma.core.marketdatasnapshot.MarketDataSnapshotSource;
import com.opengamma.core.marketdatasnapshot.StructuredMarketDataSnapshot;
import com.opengamma.id.ObjectId;
import com.opengamma.id.UniqueId;
import com.opengamma.master.AbstractMasterSource;
import com.opengamma.master.marketdatasnapshot.MarketDataSnapshotDocument;
import com.opengamma.master.marketdatasnapshot.MarketDataSnapshotMaster;
import com.opengamma.util.PublicSPI;
import com.opengamma.util.tuple.Pair;
/**
* A {@code MarketDataSnapshotSource} implemented using an underlying {@code MarketDataSnapshotMaster}.
* <p>
* The {@link MarketDataSnapshotSource} interface provides snapshots to the engine via a narrow API.
* This class provides the source on top of a standard {@link MarketDataSnapshotMaster}.
*/
@PublicSPI
public class MasterSnapshotSource extends AbstractMasterSource<StructuredMarketDataSnapshot, MarketDataSnapshotDocument, MarketDataSnapshotMaster> implements MarketDataSnapshotSource {
/**
* The listeners.
*/
private final ConcurrentHashMap<Pair<UniqueId, MarketDataSnapshotChangeListener>, ChangeListener> _registeredListeners =
new ConcurrentHashMap<Pair<UniqueId, MarketDataSnapshotChangeListener>, ChangeListener>();
/**
* Creates an instance with an underlying master which does not override versions.
*
* @param master the master, not null
*/
public MasterSnapshotSource(final MarketDataSnapshotMaster master) {
super(master);
}
//-------------------------------------------------------------------------
@Override
public void addChangeListener(final UniqueId uniqueId, final MarketDataSnapshotChangeListener listener) {
ChangeListener changeListener = new ChangeListener() {
@Override
public void entityChanged(ChangeEvent event) {
ObjectId changedId = event.getObjectId();
if (changedId != null && changedId.getScheme().equals(uniqueId.getScheme()) && changedId.getValue().equals(uniqueId.getValue())) {
//TODO This is over cautious in the case of corrections to non latest versions
listener.objectChanged(uniqueId.getObjectId());
}
}
};
_registeredListeners.put(Pair.of(uniqueId, listener), changeListener);
getMaster().changeManager().addChangeListener(changeListener);
}
@Override
public void removeChangeListener(UniqueId uid, MarketDataSnapshotChangeListener listener) {
ChangeListener changeListener = _registeredListeners.remove(Pair.of(uid, listener));
getMaster().changeManager().removeChangeListener(changeListener);
}
}
| 42.323944 | 184 | 0.764393 |
9caea54a034ac923092f5b829cd103751a2c0c70 | 331 | package fabler.fablededitor.utilities;
import fabler.fablededitor.models.ComponentTag;
public class ComponentMetadataHelper {
public static ComponentTag getNewComponentTag(int index) {
ComponentTag componentTag = new ComponentTag();
componentTag.setComponentIndex(index);
return componentTag;
}
}
| 27.583333 | 62 | 0.758308 |
841598ef944ccf76f6253cbd96a8bffeb4893320 | 3,317 | package io.github.gaomjun.blecommunication.BLECommunication.Message;
import io.github.gaomjun.utils.TypeConversion.HEXString;
/**
* Created by qq on 30/11/2016.
*/
public class SendMessage extends Message {
private byte[] message = new byte[20];
private byte[] header = new byte[]{(byte)0xab, (byte)0xcd};
private byte[] commandBack = new byte[1];
private byte[] trackingFlag = new byte[1];
private byte[] trackingQuailty = new byte[1];
private byte[] xoffset = new byte[4];
private byte[] yoffset = new byte[4];
private byte[] offset = new byte[5];
private byte[] crc = new byte[2];
public void setCommandBack(byte[] commandBack) {
if (commandBack != null) {
this.commandBack = commandBack;
} else {
this.commandBack = new byte[]{(byte) 0x00};
}
}
public void setTrackingFlag(byte[] trackingFlag) {
if (trackingFlag != null) {
this.trackingFlag = trackingFlag;
} else {
this.trackingFlag = new byte[]{(byte) 0x00};
}
}
public void setTrackingQuailty(byte[] trackingQuailty) {
if (trackingQuailty != null) {
this.trackingQuailty = trackingQuailty;
} else {
this.trackingQuailty = new byte[]{(byte) 0x00};
}
}
public void setXoffset(byte[] xoffset) {
if (xoffset != null) {
this.xoffset = xoffset;
} else {
this.xoffset = new byte[]{(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00};;
}
}
public void setYoffset(byte[] yoffset) {
if (yoffset != null) {
this.yoffset = yoffset;
} else {
this.yoffset = new byte[]{(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00};;
}
}
private byte[] crc(byte[] message) {
this.crc = calculateCrc16(message, MESSAGE_LENGTH-2);
return crc;
}
private SendMessage() {
}
private volatile static SendMessage instance = null;
public static SendMessage getInstance() {
if (instance == null) {
synchronized (SendMessage.class) {
if (instance == null) {
instance = new SendMessage();
}
}
}
return instance;
}
public byte[] getMessage() {
byte[] buff = new byte[20];
int index = 0;
System.arraycopy(header, 0, buff, index, header.length); index += header.length;
System.arraycopy(commandBack, 0, buff, index, commandBack.length); index += commandBack.length;
System.arraycopy(trackingFlag, 0, buff, index, trackingFlag.length); index += trackingFlag.length;
System.arraycopy(trackingQuailty, 0, buff, index, trackingQuailty.length); index += trackingQuailty.length;
System.arraycopy(xoffset, 0, buff, index, xoffset.length); index += xoffset.length;
System.arraycopy(yoffset, 0, buff, index, yoffset.length); index += yoffset.length;
System.arraycopy(offset, 0, buff, index, offset.length); index += offset.length;
System.arraycopy(crc(buff), 0, buff, index, crc.length);
message = buff;
return message;
}
public String getMessageHexString() {
return HEXString.bytes2HexString(message);
}
}
| 31.590476 | 115 | 0.593307 |
2218d1623d42572457b46fc215d29e71585d71d6 | 8,991 | /*
* 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.openjpa.persistence.jpql.expressions;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import org.apache.openjpa.persistence.common.apps.*;
import org.apache.openjpa.persistence.common.utils.AbstractTestCase;
public class TestEntityTypeExpression extends AbstractTestCase {
private int userid1, userid2, userid3, userid4, userid5, userid6;
public TestEntityTypeExpression(String name) {
super(name, "jpqlclausescactusapp");
}
public void setUp() {
deleteAll(CompUser.class);
EntityManager em = currentEntityManager();
startTx(em);
Address[] add = new Address[]{
new Address("43 Sansome", "SF", "United-Kingdom", "94104"),
new Address("24 Mink", "ANTIOCH", "USA", "94513"),
new Address("23 Ogbete", "CoalCamp", "NIGERIA", "00000"),
new Address("10 Wilshire", "Worcester", "CANADA", "80080"),
new Address("23 Bellflower", "Ogui", null, "02000"),
new Address("22 Montgomery", "SF", null, "50054") };
CompUser user1 = createUser("Seetha", "MAC", add[0], 36, true);
CompUser user2 = createUser("Shannon", "PC", add[1], 36, false);
CompUser user3 = createUser("Ugo", "PC", add[2], 19, true);
CompUser user4 = createUser("Jacob", "LINUX", add[3], 10, true);
CompUser user5 = createUser("Famzy", "UNIX", add[4], 29, false);
CompUser user6 = createUser("Shade", "UNIX", add[5], 23, false);
em.persist(user1);
userid1 = user1.getUserid();
em.persist(user2);
userid2 = user2.getUserid();
em.persist(user3);
userid3 = user3.getUserid();
em.persist(user4);
userid4 = user4.getUserid();
em.persist(user5);
userid5 = user5.getUserid();
em.persist(user6);
userid6 = user6.getUserid();
endTx(em);
endEm(em);
}
public void testTypeOnNonPolymorphicEntity() {
EntityManager em = currentEntityManager();
String query = "select a from Address a where type(a) = ?1";
List rs = null;
try {
rs = em.createQuery(query).setParameter(1, Address.class).getResultList();
System.out.println("rs size="+rs.size());
} catch(Exception e) {
// as expected
//System.out.println(e.getMessage());
}
}
@SuppressWarnings("unchecked")
public void testTypeExpression() {
EntityManager em = currentEntityManager();
String query = null;
List<CompUser> rs = null;
CompUser user = null;
// test collection-valued input parameters in in-expressions
Collection params = new ArrayList(2);
params.add(FemaleUser.class);
params.add(MaleUser.class);
Collection params2 = new ArrayList(3);
params2.add(36);
params2.add(29);
params2.add(19);
String param3 = "PC";
query = "SELECT e FROM CompUser e where TYPE(e) in ?1 and e.age in ?2" +
" and e.computerName = ?3 ORDER By e.name";
rs = em.createQuery(query).
setParameter(1, params).
setParameter(2, params2).
setParameter(3, param3).getResultList();
user = rs.get(0);
assertEquals("Shannon", user.getName());
query = "SELECT e FROM CompUser e where TYPE(e) in ?1 and e.age in ?2" +
" ORDER By e.name";
rs = em.createQuery(query).
setParameter(1, params).
setParameter(2, params2).getResultList();
user = rs.get(0);
assertEquals("Famzy", user.getName());
query = "SELECT e FROM CompUser e where TYPE(e) in :value " +
"ORDER BY e.age";
rs = em.createQuery(query).
setParameter("value", params).getResultList();
user = rs.get(0);
assertEquals("Jacob", user.getName());
query = "SELECT TYPE(e) FROM MaleUser e where TYPE(e) = MaleUser";
rs = em.createQuery(query).getResultList();
Object type = rs.get(0);
assertEquals(type, MaleUser.class);
query = "SELECT TYPE(e) FROM CompUser e where TYPE(e) = ?1";
rs = em.createQuery(query).
setParameter(1, FemaleUser.class).getResultList();
type = rs.get(0);
assertEquals(type, FemaleUser.class);
query = "SELECT TYPE(e) FROM MaleUser e where TYPE(e) = ?1";
rs = em.createQuery(query).
setParameter(1, MaleUser.class).getResultList();
type = rs.get(0);
assertEquals(type, MaleUser.class);
query = "SELECT e, FemaleUser, a FROM Address a, FemaleUser e " +
" where e.address IS NOT NULL";
List<Object> rs2 = em.createQuery(query).getResultList();
type = ((Object[]) rs2.get(0))[1];
assertEquals(type, FemaleUser.class);
query = "SELECT e FROM CompUser e where TYPE(e) = :type " +
" ORDER BY e.name";
rs = em.createQuery(query).
setParameter("type", FemaleUser.class).getResultList();
assertTrue(rs.size()==3);
user = rs.get(0);
assertEquals("Famzy", user.getName());
user = rs.get(1);
assertEquals("Shade", user.getName());
user = rs.get(2);
assertEquals("Shannon", user.getName());
query = "SELECT e FROM CompUser e where TYPE(e) = ?1 ORDER BY e.name";
rs = em.createQuery(query).
setParameter(1, FemaleUser.class).getResultList();
user = rs.get(0);
assertEquals("Famzy", user.getName());
query = "SELECT e FROM CompUser e where TYPE(e) in (?1)" +
" ORDER BY e.name DESC";
rs = em.createQuery(query).
setParameter(1, MaleUser.class).getResultList();
user = rs.get(0);
assertEquals("Ugo", user.getName());
query = "SELECT e FROM CompUser e where TYPE(e) in (?1, ?2)" +
" ORDER BY e.name DESC";
rs = em.createQuery(query).
setParameter(1, FemaleUser.class).setParameter(2, MaleUser.class).
getResultList();
user = rs.get(0);
assertEquals("Ugo", user.getName());
query = "select sum(e.age) FROM CompUser e GROUP BY e.age" +
" HAVING ABS(e.age) = :param";
Long sum = (Long) em.createQuery(query).
setParameter("param", new Double(36)).getSingleResult();
assertEquals(sum.intValue(), 72);
String[] queries = {
"SELECT e FROM CompUser e where TYPE(e) = MaleUser",
"SELECT e from CompUser e where TYPE(e) in (FemaleUser)",
"SELECT e from CompUser e where TYPE(e) not in (FemaleUser)",
"SELECT e from CompUser e where TYPE(e) in (MaleUser, FemaleUser)",
"SELECT TYPE(e) FROM CompUser e where TYPE(e) = MaleUser",
"SELECT TYPE(e) FROM CompUser e",
"SELECT TYPE(a.user) FROM Address a",
"SELECT MaleUser FROM CompUser e",
"SELECT MaleUser FROM Address a",
"SELECT " +
" CASE TYPE(e) WHEN FemaleUser THEN 'Female' " +
" ELSE 'Male' " +
" END " +
" FROM CompUser e",
};
for (int i = 0; i < queries.length; i++) {
query = queries[i];
List<Object> rs1 = em.createQuery(query).getResultList();
Object obj = rs1.get(0);
obj.toString();
}
endEm(em);
}
public CompUser createUser(String name, String cName, Address add, int age,
boolean isMale) {
CompUser user = null;
if (isMale) {
user = new MaleUser();
user.setName(name);
user.setComputerName(cName);
user.setAddress(add);
user.setAge(age);
} else {
user = new FemaleUser();
user.setName(name);
user.setComputerName(cName);
user.setAddress(add);
user.setAge(age);
}
return user;
}
}
| 37.777311 | 87 | 0.57869 |
2de9f97499f34cf1eeb15824ea2861810d3a34e6 | 5,290 | /**
*/
package de.dc.fx.ui.renderer.model;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.eclipse.emf.common.util.Enumerator;
/**
* <!-- begin-user-doc -->
* A representation of the literals of the enumeration '<em><b>FX Tab Close Policy</b></em>',
* and utility methods for working with them.
* <!-- end-user-doc -->
* @see de.dc.fx.ui.renderer.model.UIPackage#getFXTabClosePolicy()
* @model
* @generated
*/
public enum FXTabClosePolicy implements Enumerator {
/**
* The '<em><b>SELECTED TAB</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #SELECTED_TAB_VALUE
* @generated
* @ordered
*/
SELECTED_TAB(0, "SELECTED_TAB", "SELECTED_TAB"),
/**
* The '<em><b>ALL TABS</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #ALL_TABS_VALUE
* @generated
* @ordered
*/
ALL_TABS(0, "ALL_TABS", "ALL_TABS"),
/**
* The '<em><b>UNAVAILABLE</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #UNAVAILABLE_VALUE
* @generated
* @ordered
*/
UNAVAILABLE(0, "UNAVAILABLE", "UNAVAILABLE");
/**
* The '<em><b>SELECTED TAB</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #SELECTED_TAB
* @model
* @generated
* @ordered
*/
public static final int SELECTED_TAB_VALUE = 0;
/**
* The '<em><b>ALL TABS</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #ALL_TABS
* @model
* @generated
* @ordered
*/
public static final int ALL_TABS_VALUE = 0;
/**
* The '<em><b>UNAVAILABLE</b></em>' literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #UNAVAILABLE
* @model
* @generated
* @ordered
*/
public static final int UNAVAILABLE_VALUE = 0;
/**
* An array of all the '<em><b>FX Tab Close Policy</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static final FXTabClosePolicy[] VALUES_ARRAY = new FXTabClosePolicy[] { SELECTED_TAB, ALL_TABS,
UNAVAILABLE, };
/**
* A public read-only list of all the '<em><b>FX Tab Close Policy</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static final List<FXTabClosePolicy> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY));
/**
* Returns the '<em><b>FX Tab Close Policy</b></em>' literal with the specified literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param literal the literal.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static FXTabClosePolicy get(String literal) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
FXTabClosePolicy result = VALUES_ARRAY[i];
if (result.toString().equals(literal)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>FX Tab Close Policy</b></em>' literal with the specified name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param name the name.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static FXTabClosePolicy getByName(String name) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
FXTabClosePolicy result = VALUES_ARRAY[i];
if (result.getName().equals(name)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>FX Tab Close Policy</b></em>' literal with the specified integer value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the integer value.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static FXTabClosePolicy get(int value) {
switch (value) {
case SELECTED_TAB_VALUE:
return SELECTED_TAB;
}
return null;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final int value;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final String name;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final String literal;
/**
* Only this class can construct instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private FXTabClosePolicy(int value, String name, String literal) {
this.value = value;
this.name = name;
this.literal = literal;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public int getValue() {
return value;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getName() {
return name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getLiteral() {
return literal;
}
/**
* Returns the literal value of the enumerator, which is its string representation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
return literal;
}
} //FXTabClosePolicy
| 23.201754 | 112 | 0.573724 |
122ac8ae803b51fac57afb7cd39426d75c027c07 | 118 | package com.rxjava2.android.samples.ui.Room;
public class Const {
public static final String home = "Movies/";
}
| 19.666667 | 48 | 0.728814 |
51ab59f4234015c1702003e9c4f07a07d7adb018 | 461 | package EstruturaDeDados.Atividade06Exemplo;
public class Fila_exemplo {
public static void main(String[] args) {
Fila<Integer> fila = new Fila<>();
//1
System.out.println(fila.estaVazia()); //true
System.out.println(fila.tamanho()); //0
//2
fila.enfileira(1);
fila.enfileira(2);
fila.enfileira(3);
System.out.println(fila.estaVazia());//false
System.out.println(fila.tamanho());//3
System.out.println(fila.toString());
}
}
| 20.043478 | 46 | 0.67462 |
42b1567c06777a79b2e542b4a58477925dcf563a | 1,549 | package com.study.algafood.api.v1.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.hateoas.RepresentationModel;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.study.algafood.api.v1.CreatorLinks;
import springfox.documentation.annotations.ApiIgnore;
@ApiIgnore
@RestController
@RequestMapping(path = "/v1",produces = MediaType.APPLICATION_JSON_VALUE)
public class RootEntryPointController {
@Autowired
private CreatorLinks linkService;
@GetMapping
public RootEntryPointModel root() {
var rootEntryPointModel = new RootEntryPointModel();
rootEntryPointModel.add(linkService.linkToCozinhas("cozinhas"));
rootEntryPointModel.add(linkService.linkToPedidos("pedidos"));
rootEntryPointModel.add(linkService.linkToRestaurantes("restaurantes"));
//rootEntryPointModel.add(linkService.linkToGrupos("grupos"));
rootEntryPointModel.add(linkService.linkToUsuarios("usuarios"));
//rootEntryPointModel.add(linkService.linkToPermissoes());
//rootEntryPointModel.add(linkService.linkToFormasPagamento("formas-pagamento"));
rootEntryPointModel.add(linkService.linkToEstados("estados"));
rootEntryPointModel.add(linkService.linkToCidades("cidades"));
return rootEntryPointModel;
}
private static class RootEntryPointModel extends RepresentationModel<RootEntryPointModel> {
}
}
| 36.023256 | 92 | 0.823112 |
147a902697fbe14dbba8aac5f00ebeff010790db | 242 | package com.chobocho.command;
import com.chobocho.solitaire.Solitare;
class ConfigFunction implements ComandFunction {
@Override
public boolean run(Solitare game, int from, int to, int count) {
return game.config();
}
}
| 22 | 68 | 0.719008 |
a860df90817261098456252c6cd5856229d5c5a1 | 990 | package com.smhu.overall;
import java.util.List;
public class Overall {
private SystemAmount year;
private List<SystemAmount> term;
private List<SystemAmount> month;
public Overall() {
}
public Overall(SystemAmount year, List<SystemAmount> term, List<SystemAmount> month) {
this.year = year;
this.term = term;
this.month = month;
}
public SystemAmount getYear() {
return year;
}
public void setYear(SystemAmount year) {
this.year = year;
}
public List<SystemAmount> getTerm() {
return term;
}
public void setTerm(List<SystemAmount> term) {
this.term = term;
}
public List<SystemAmount> getMonth() {
return month;
}
public void setMonth(List<SystemAmount> month) {
this.month = month;
}
@Override
public String toString() {
return "Overall{" + "year=" + year + ", term=" + term + ", month=" + month + '}';
}
}
| 19.8 | 90 | 0.590909 |
57f73c7a4522ceecda219f62538701796dae281a | 4,585 | /******************************************************************************
* TUser.java - created by Sakai App Builder -AZ
*
* Copyright (c) 2006 Sakai Project/Sakai Foundation
* Licensed under the Educational Community License version 1.0
*
* A copy of the Educational Community License has been included in this
* distribution and is available at: http://www.opensource.org/licenses/ecl1.php
*
*****************************************************************************/
package org.sakaiproject.blogwow.logic.stubs;
import java.util.Date;
import java.util.Stack;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.time.api.Time;
import org.sakaiproject.user.api.User;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* Test class for the Sakai User object<br/> This has to be here since I cannot create a User object in Sakai for some reason... sure would
* be nice if I could though -AZ
*
* @author Sakai App Builder -AZ
*/
@SuppressWarnings("unchecked")
public class TUser implements User {
private String userId;
private String userEid = "fakeEid";
private String displayName = "Fake DisplayName";
/**
* Construct an empty test user with an id set
*
* @param userId
* a id string
*/
public TUser(String userId) {
this.userId = userId;
}
/**
* Construct an empty test user with an id and eid set
*
* @param userId
* a id string
* @param userEid
* a username string
*/
public TUser(String userId, String userEid) {
this.userId = userId;
this.userEid = userEid;
}
/**
* Construct an empty test user with an id and eid set
*
* @param userId
* a id string
* @param userEid
* a username string
* @param displayName
* a user display name
*/
public TUser(String userId, String userEid, String displayName) {
this.userId = userId;
this.userEid = userEid;
this.displayName = displayName;
}
public boolean checkPassword(String pw) {
// TODO Auto-generated method stub
return false;
}
public User getCreatedBy() {
// TODO Auto-generated method stub
return null;
}
public String getDisplayId() {
// TODO Auto-generated method stub
return null;
}
public String getDisplayName() {
return this.displayName;
}
public String getEid() {
return this.userEid;
}
public String getEmail() {
// TODO Auto-generated method stub
return null;
}
public String getFirstName() {
// TODO Auto-generated method stub
return null;
}
public String getLastName() {
// TODO Auto-generated method stub
return null;
}
public User getModifiedBy() {
// TODO Auto-generated method stub
return null;
}
public String getSortName() {
// TODO Auto-generated method stub
return null;
}
public String getType() {
// TODO Auto-generated method stub
return null;
}
public String getId() {
return userId;
}
public ResourceProperties getProperties() {
// TODO Auto-generated method stub
return null;
}
public String getReference() {
// TODO Auto-generated method stub
return null;
}
public String getReference(String rootProperty) {
// TODO Auto-generated method stub
return null;
}
public String getUrl() {
// TODO Auto-generated method stub
return null;
}
public String getUrl(String rootProperty) {
// TODO Auto-generated method stub
return null;
}
public int compareTo(Object arg0) {
// TODO Auto-generated method stub
return 0;
}
public Time getCreatedTime() {
// TODO Auto-generated method stub
return null;
}
public Time getModifiedTime() {
// TODO Auto-generated method stub
return null;
}
public String getUrlEmbeddableId(){
return this.getDisplayId();
}
@Override
public Element toXml(Document arg0, Stack<Element> arg1) {
// TODO Auto-generated method stub
return null;
}
@Override
public Date getCreatedDate() {
// TODO Auto-generated method stub
return null;
}
@Override
public Date getModifiedDate() {
// TODO Auto-generated method stub
return null;
}
}
| 23.392857 | 139 | 0.593893 |
deae795d6477ac96133a19b35f5fd4ffead8f2cd | 10,341 | // Date: 15.09.2016 15:57:08
// Template version 1.1
// Java generated by Techne
package pokefenn.totemic.client.rendering.model;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.entity.Entity;
import net.minecraft.util.math.MathHelper;
public class ModelBuffalo extends ModelBase
{
private final ModelRenderer head;
private final ModelRenderer body;
private final ModelRenderer back;
private final ModelRenderer udder;
private final ModelRenderer leg1;
private final ModelRenderer leg2;
private final ModelRenderer leg3;
private final ModelRenderer leg4;
private final ModelRenderer hoof1;
private final ModelRenderer hoof2;
private final ModelRenderer hoof3;
private final ModelRenderer hoof4;
private final ModelRenderer tail;
private final ModelRenderer tailhairs;
private final ModelRenderer hornbase1;
private final ModelRenderer hornbase2;
private final ModelRenderer horn1;
private final ModelRenderer horn2;
private final ModelRenderer horn3;
private final ModelRenderer horn4;
private final ModelRenderer horn5;
private final ModelRenderer horn6;
public ModelBuffalo()
{
textureWidth = 64;
textureHeight = 64;
head = new ModelRenderer(this, 0, 45);
head.addBox(-4.5F, -7F, -7F, 9, 7, 9);
head.setRotationPoint(0F, 6F, -7F);
head.setTextureSize(64, 64);
head.mirror = true;
setRotation(head, 1.570796F, 0F, 0F);
body = new ModelRenderer(this, 0, 0);
body.addBox(-6F, -10F, -9F, 12, 10, 13);
body.setRotationPoint(0F, 7F, 2F);
body.setTextureSize(64, 64);
body.mirror = true;
setRotation(body, 1.48353F, 0F, 0F);
back = new ModelRenderer(this, 0, 23);
back.addBox(-5.5F, 0F, -8.5F, 11, 10, 12);
back.setRotationPoint(0F, 7F, 2F);
back.setTextureSize(64, 64);
back.mirror = true;
setRotation(back, 1.48353F, 0F, 0F);
udder = new ModelRenderer(this, 28, 46);
udder.addBox(-3.5F, 4F, -9.5F, 7, 5, 1);
udder.setRotationPoint(0F, 7F, 2F);
udder.setTextureSize(64, 64);
udder.mirror = true;
setRotation(udder, 1.48353F, 0F, 0F);
leg1 = new ModelRenderer(this, 46, 18);
leg1.addBox(-1F, 0F, -3F, 4, 11, 5);
leg1.setRotationPoint(4F, 10F, -5F);
leg1.setTextureSize(64, 64);
leg1.mirror = true;
setRotation(leg1, 0.1396263F, 0F, 0F);
leg1.mirror = false;
leg2 = new ModelRenderer(this, 46, 18);
leg2.addBox(-3F, 0F, -3F, 4, 11, 5);
leg2.setRotationPoint(-4F, 10F, -5F);
leg2.setTextureSize(64, 64);
leg2.mirror = true;
setRotation(leg2, 0.1396263F, 0F, 0F);
leg3 = new ModelRenderer(this, 48, 43);
leg3.addBox(-1F, 0F, -3F, 4, 8, 4);
leg3.setRotationPoint(4F, 10F, 10F);
leg3.setTextureSize(64, 64);
leg3.mirror = true;
setRotation(leg3, 0F, 0F, 0F);
leg3.mirror = false;
leg4 = new ModelRenderer(this, 48, 43);
leg4.addBox(-3F, 0F, -3F, 4, 8, 4);
leg4.setRotationPoint(-4F, 10F, 10F);
leg4.setTextureSize(64, 64);
leg4.mirror = true;
setRotation(leg4, 0F, 0F, 0F);
hoof1 = new ModelRenderer(this, 46, 34);
hoof1.addBox(-0.5F, 8F, 0F, 3, 6, 3);
hoof1.setRotationPoint(4F, 10F, -5F);
hoof1.setTextureSize(64, 64);
hoof1.mirror = true;
setRotation(hoof1, 0F, 0F, 0F);
hoof1.mirror = false;
hoof2 = new ModelRenderer(this, 46, 34);
hoof2.addBox(-2.5F, 8F, 0F, 3, 6, 3);
hoof2.setRotationPoint(-4F, 10F, -5F);
hoof2.setTextureSize(64, 64);
hoof2.mirror = true;
setRotation(hoof2, 0F, 0F, 0F);
hoof3 = new ModelRenderer(this, 48, 55);
hoof3.addBox(-0.5F, 8F, -2F, 3, 6, 3);
hoof3.setRotationPoint(4F, 10F, 10F);
hoof3.setTextureSize(64, 64);
hoof3.mirror = true;
setRotation(hoof3, 0F, 0F, 0F);
hoof3.mirror = false;
hoof4 = new ModelRenderer(this, 48, 55);
hoof4.addBox(-2.5F, 8F, -2F, 3, 6, 3);
hoof4.setRotationPoint(-4F, 10F, 10F);
hoof4.setTextureSize(64, 64);
hoof4.mirror = true;
setRotation(hoof4, 0F, 0F, 0F);
tail = new ModelRenderer(this, 28, 53);
tail.addBox(-1F, 0F, -9.5F, 2, 1, 8);
tail.setRotationPoint(0F, 7F, 12F);
tail.setTextureSize(64, 64);
tail.mirror = true;
setRotation(tail, 1.48353F, 0F, 0F);
tailhairs = new ModelRenderer(this, 35, 62);
tailhairs.addBox(-1F, 0F, -10.5F, 2, 1, 1);
tailhairs.setRotationPoint(0F, 7F, 12F);
tailhairs.setTextureSize(64, 64);
tailhairs.mirror = true;
setRotation(tailhairs, 1.48353F, 0F, 0F);
hornbase1 = new ModelRenderer(this, 52, 0);
hornbase1.addBox(-7.5F, -4F, -1F, 4, 2, 2);
hornbase1.setRotationPoint(0F, 6F, -7F);
hornbase1.setTextureSize(64, 64);
hornbase1.mirror = true;
setRotation(hornbase1, 1.570796F, 0F, 0F);
hornbase2 = new ModelRenderer(this, 52, 0);
hornbase2.addBox(3.5F, -4F, -1F, 4, 2, 2);
hornbase2.setRotationPoint(0F, 6F, -7F);
hornbase2.setTextureSize(64, 64);
hornbase2.mirror = true;
setRotation(hornbase2, 1.570796F, 0F, 0F);
hornbase2.mirror = false;
horn1 = new ModelRenderer(this, 52, 4);
horn1.addBox(6.5F, -4F, 0F, 2, 2, 4);
horn1.setRotationPoint(0F, 6F, -7F);
horn1.setTextureSize(64, 64);
horn1.mirror = true;
setRotation(horn1, 1.570796F, 0F, 0F);
horn1.mirror = false;
horn2 = new ModelRenderer(this, 52, 10);
horn2.addBox(5.5F, -4F, 2F, 2, 2, 3);
horn2.setRotationPoint(0F, 6F, -7F);
horn2.setTextureSize(64, 64);
horn2.mirror = true;
setRotation(horn2, 1.570796F, 0F, 0F);
horn2.mirror = false;
horn3 = new ModelRenderer(this, 52, 15);
horn3.addBox(5.5F, -4F, 5F, 1, 1, 1);
horn3.setRotationPoint(0F, 6F, -7F);
horn3.setTextureSize(64, 64);
horn3.mirror = true;
setRotation(horn3, 1.570796F, 0F, 0F);
horn3.mirror = false;
horn4 = new ModelRenderer(this, 52, 4);
horn4.addBox(-8.5F, -4F, 0F, 2, 2, 4);
horn4.setRotationPoint(0F, 6F, -7F);
horn4.setTextureSize(64, 64);
horn4.mirror = true;
setRotation(horn4, 1.570796F, 0F, 0F);
horn5 = new ModelRenderer(this, 52, 10);
horn5.addBox(-7.5F, -4F, 2F, 2, 2, 3);
horn5.setRotationPoint(0F, 6F, -7F);
horn5.setTextureSize(64, 64);
horn5.mirror = true;
setRotation(horn5, 1.570796F, 0F, 0F);
horn6 = new ModelRenderer(this, 52, 15);
horn6.addBox(-6.5F, -4F, 5F, 1, 1, 1);
horn6.setRotationPoint(0F, 6F, -7F);
horn6.setTextureSize(64, 64);
horn6.mirror = true;
setRotation(horn6, 1.570796F, 0F, 0F);
}
@Override
public void render(Entity entity, float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch, float scale)
{
GlStateManager.pushMatrix();
GlStateManager.translate(0, -0.75F, 0);
GlStateManager.scale(1.5F, 1.5F, 1.5F);
setRotationAngles(limbSwing, limbSwingAmount, ageInTicks, netHeadYaw, headPitch, scale, entity);
if (isChild)
{
GlStateManager.pushMatrix();
GlStateManager.translate(0.0F, 6.0F * scale, 4.0F * scale);
}
head.render(scale);
hornbase1.render(scale);
hornbase2.render(scale);
horn1.render(scale);
horn2.render(scale);
horn3.render(scale);
horn4.render(scale);
horn5.render(scale);
horn6.render(scale);
if (isChild)
{
float childScale = 0.5F;
GlStateManager.popMatrix();
GlStateManager.scale(childScale, childScale, childScale);
GlStateManager.translate(0.0F, 24.0F * scale, 0.0F);
}
tailhairs.render(scale);
hoof1.render(scale);
leg1.render(scale);
leg3.render(scale);
hoof3.render(scale);
leg2.render(scale);
hoof2.render(scale);
leg4.render(scale);
hoof4.render(scale);
back.render(scale);
udder.render(scale);
tail.render(scale);
body.render(scale);
GlStateManager.popMatrix();
}
@Override
public void setRotationAngles(float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch, float scale, Entity entity)
{
super.setRotationAngles(limbSwing, limbSwingAmount, ageInTicks, netHeadYaw, headPitch, scale, entity);
head.rotateAngleX = headPitch / (180F / (float) Math.PI) + ((float) Math.PI / 2F);
hornbase1.rotateAngleX = hornbase2.rotateAngleX = horn1.rotateAngleX = horn2.rotateAngleX = horn3.rotateAngleX
= horn4.rotateAngleX = horn5.rotateAngleX = horn6.rotateAngleX = head.rotateAngleX;
head.rotateAngleY = hornbase1.rotateAngleY = hornbase2.rotateAngleY = horn1.rotateAngleY = horn2.rotateAngleY = horn3.rotateAngleY
= horn4.rotateAngleY = horn5.rotateAngleY = horn6.rotateAngleY = netHeadYaw / (180F / (float) Math.PI);
hoof1.rotateAngleX = MathHelper.cos(limbSwing * 0.6662F) * 1.4F * limbSwingAmount;
leg1.rotateAngleX = hoof1.rotateAngleX + ((float) Math.PI * 8F / 180F);
hoof2.rotateAngleX = MathHelper.cos(limbSwing * 0.6662F + (float) Math.PI) * 1.4F * limbSwingAmount;
leg2.rotateAngleX = hoof2.rotateAngleX + ((float) Math.PI * 8F / 180F);
leg3.rotateAngleX = hoof3.rotateAngleX = MathHelper.cos(limbSwing * 0.6662F + (float) Math.PI) * 1.4F * limbSwingAmount;
leg4.rotateAngleX = hoof4.rotateAngleX = MathHelper.cos(limbSwing * 0.6662F) * 1.4F * limbSwingAmount;
}
private void setRotation(ModelRenderer model, float x, float y, float z)
{
model.rotateAngleX = x;
model.rotateAngleY = y;
model.rotateAngleZ = z;
}
}
| 39.469466 | 154 | 0.611933 |
f182ed912f24b0a26bcace391a7fc222798f1ec9 | 1,299 | package com.indeed.util.core;
import org.junit.Test;
import java.util.Arrays;
import static org.junit.Assert.fail;
import static org.junit.Assert.assertFalse;
public class NetUtilsTest {
@Test
public void testGetRawAddress() {
assertArrayEquals(make(1,1,1,1), NetUtils.getRawAddress("1.1.1.1"));
assertArrayEquals(make(192,168,0,1), NetUtils.getRawAddress("192.168.0.1"));
assertArrayEquals(make(128,127,254,255), NetUtils.getRawAddress("128.127.254.255"));
}
private byte[] make(int a, int b, int c, int d) {
return new byte[] { (byte) a, (byte) b, (byte) c, (byte) d };
}
private void assertArrayEquals(byte[] a, byte[] b) {
if (!Arrays.equals(a, b))
fail("Arrays are not equal, expected: " + Arrays.toString(a) + ", actual: " + Arrays.toString(b));
}
@Test
public void testGetHostname() throws Exception {
assertFalse(NetUtils.determineHostName("unknown").equals("unknown"));
assertFalse(NetUtils.determineHostName("unknown").equals("unknown"));
assertFalse(NetUtils.determineHostName("unknown").equals("unknown"));
}
@Test(expected = NullPointerException.class)
public void testNullException() throws Exception {
NetUtils.determineHostName(null);
}
}
| 33.307692 | 110 | 0.662048 |
cb4a053772cab7e4938700da26bf92ec792439ba | 1,774 | import java.util.Arrays;
import java.util.Scanner;
//най-бързо 0.64
public class Lab_Task_5_MaximumSumOf2x2Submatrix_02 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int[] dimensions = Arrays.stream(scan.nextLine().split(", ")).mapToInt(Integer::parseInt).toArray();
int rows = dimensions[0];
int columns = dimensions[1];
int[][] matrix = new int[rows][];
for (int i = 0; i < rows; i++) {
int[] innerArray = Arrays.stream(scan.nextLine().split(", ")).mapToInt(Integer::parseInt).toArray();
matrix[i] = innerArray;
}
int maxSum = Integer.MIN_VALUE;
int row = -1;
int col = -1;
for (int r = 0; r < matrix.length - 1; r++) {
for (int c = 0; c < matrix[r].length - 1; c++) {
int curr = matrix[r][c];
int belowCurrent = matrix[r + 1][c];
int leftCurr = matrix[r][c + 1];
int belowLeft = matrix[r + 1][c + 1];
int sum = curr + belowCurrent + leftCurr + belowLeft;
if (sum > maxSum) {
maxSum = sum;
row = r;
col = c;
}
}
}
StringBuilder result = new StringBuilder();
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
int asd = row + i;
int dsa = col + j;
int bla = matrix[row + i][col + j];
result.append(matrix[row + i][col + j]).append(" ");
}
result.append(System.lineSeparator());
}
System.out.println(result.toString().trim());
System.out.println(maxSum);
}
}
| 34.115385 | 112 | 0.475197 |
3c928d7c6fbd185610a11ed3ad85583d9678655b | 3,410 | /*
* $Id: LockAction.java,v 1.3 2004/05/06 11:09:59 edankert Exp $
*
* Copyright (C) 2002, Cladonia Ltd. All rights reserved.
*
* This software is the proprietary information of Cladonia Ltd.
* Use is subject to license terms.
*/
package com.cladonia.xngreditor.actions;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.KeyStroke;
import com.cladonia.xml.ExchangerDocument;
import com.cladonia.xml.editor.Editor;
import com.cladonia.xml.editor.XmlEditorPane;
import com.cladonia.xngreditor.ExchangerEditor;
import com.cladonia.xngreditor.XngrImageLoader;
/**
* An action that can be used to Comment the selected text.
*
* @version $Revision: 1.3 $, $Date: 2004/05/06 11:09:59 $
* @author Dogsbay
*/
public class LockAction extends AbstractAction {
private static final boolean DEBUG = false;
private Editor editor = null;
private ExchangerEditor parent = null;
/**
* The constructor for the action that Comments the selected text.
*
* @param editor the XML Editor
*/
public LockAction( ExchangerEditor parent) {
super( "Unlock");
this.parent = parent;
if (DEBUG) System.out.println( "LockAction( "+editor+")");
putValue( MNEMONIC_KEY, new Integer( 'l'));
putValue( ACCELERATOR_KEY, KeyStroke.getKeyStroke( KeyEvent.VK_L, InputEvent.CTRL_MASK, false));
putValue( SMALL_ICON, XngrImageLoader.get().getImage( "com/cladonia/xml/editor/icons/Unlock16.gif"));
putValue( SHORT_DESCRIPTION, "Unlock");
setEnabled( false);
}
/**
* Sets the current view.
*
* @param view the current view.
*/
public void setView( Object view) {
if ( view instanceof Editor) {
editor = (Editor)view;
} else {
editor = null;
}
setDocument( parent.getDocument());
}
public void setDocument( ExchangerDocument doc) {
if ( doc != null && (doc.isXML() || doc.isDTD())) {
setEnabled( editor != null);
} else {
setEnabled( false);
}
}
/**
* Sets wether the action is being used
* for commenting or uncommenting.
*
* @param enabled enable un-commenting.
*/
public void setUnlock( int value) {
if ( value == XmlEditorPane.NOT_LOCKED) {
putValue( NAME, "Lock");
putValue( SHORT_DESCRIPTION, "Allow all changes.");
putValue( SMALL_ICON, XngrImageLoader.get().getImage( "com/cladonia/xml/editor/icons/Unlock16.gif"));
} else if ( value == XmlEditorPane.LOCKED){
putValue( NAME, "Double Lock");
putValue( SHORT_DESCRIPTION, "Allow Attribute and Element content changes.");
putValue( SMALL_ICON, XngrImageLoader.get().getImage( "com/cladonia/xml/editor/icons/Lock16.gif"));
} else if ( value == XmlEditorPane.DOUBLE_LOCKED){
putValue( NAME, "Unlock");
putValue( SHORT_DESCRIPTION, "Allow Element content changes.");
putValue( SMALL_ICON, XngrImageLoader.get().getImage( "com/cladonia/xml/editor/icons/DoubleLock16.gif"));
}
}
/**
* The implementation of the comment action, called
* after a user action.
*
* @param event the action event.
*/
public void actionPerformed( ActionEvent event) {
if (DEBUG) System.out.println( "CommentAction.actionPerformed( "+event+")");
editor.lock();
editor.setFocus();
}
}
| 29.652174 | 109 | 0.678299 |
df8be12b0d031ba7c2f2729951b4252c1b217104 | 2,296 | /*
* Copyright (c) 2008-2016 Haulmont.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.haulmont.cuba.gui.components.autocomplete.impl;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class AliasRemover {
protected Pattern aliasPattern = Pattern.compile("as\\s+\"?([\\w|\\d|_|\\.]+)\"?\\s*");
public HintRequest replaceAliases(HintRequest input) {
HintRequest result = new HintRequest();
result.setQuery(input.getQuery());
result.setPosition(input.getPosition());
result.setExpectedTypes(input.getExpectedTypes());
int indexOfFrom = input.getQuery().indexOf("from");
Matcher matcher = aliasPattern.matcher(input.getQuery());
String resultQuery = result.getQuery();
while (matcher.find()) {
String alias = matcher.group();
int regionStart = matcher.start();
int regionEnd = matcher.end();
if (regionEnd <= indexOfFrom || indexOfFrom == -1) {
if (result.getPosition() > regionEnd) {
result.setPosition(result.getPosition() - alias.length());
resultQuery = matcher.replaceFirst("");
matcher.reset(resultQuery);
} else if (result.getPosition() > regionStart) {
result.setPosition(regionStart - 1);
resultQuery = matcher.replaceFirst("");
matcher.reset(resultQuery);
} else {
resultQuery = matcher.replaceFirst("");
matcher.reset(resultQuery);
}
indexOfFrom = resultQuery.indexOf("from");
}
}
result.setQuery(resultQuery);
return result;
}
} | 37.639344 | 91 | 0.611063 |
bd0be3b453f97b89178a3b7eaf556dafbaf00e89 | 245 | package findajob.hrms.dataAccess.abstracts;
import org.springframework.data.jpa.repository.JpaRepository;
import findajob.hrms.entities.concretes.JobPosition;
public interface JobPositionDao extends JpaRepository<JobPosition, Integer> {
}
| 22.272727 | 77 | 0.836735 |
34bfc5f6c790771f29f7a93ed63756a20758abe6 | 1,049 | package com.google.android.exoplayer2.source.dash;
import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.source.chunk.ChunkSource;
import com.google.android.exoplayer2.source.dash.PlayerEmsgHandler;
import com.google.android.exoplayer2.source.dash.manifest.DashManifest;
import com.google.android.exoplayer2.trackselection.TrackSelection;
import com.google.android.exoplayer2.upstream.LoaderErrorThrower;
import com.google.android.exoplayer2.upstream.TransferListener;
import java.util.List;
public interface DashChunkSource extends ChunkSource {
public interface Factory {
DashChunkSource createDashChunkSource(LoaderErrorThrower loaderErrorThrower, DashManifest dashManifest, int i, int[] iArr, TrackSelection trackSelection, int i2, long j, boolean z, List<Format> list, PlayerEmsgHandler.PlayerTrackEmsgHandler playerTrackEmsgHandler, TransferListener transferListener);
}
void updateManifest(DashManifest dashManifest, int i);
void updateTrackSelection(TrackSelection trackSelection);
}
| 47.681818 | 308 | 0.835081 |
953de0e4bbef8d20c2237479e995519323dc8697 | 599 | package org.citydb.core.plugin.metadata;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
@XmlType(name = "PluginVendorType", propOrder = {})
public class PluginVendor {
@XmlAttribute
private String url;
@XmlValue
private String value;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
| 19.966667 | 51 | 0.657763 |
d6417e65502ba6feaa6c3b044460eee19ebccfbf | 2,925 | package sample.lyl.xyz;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import sample.lyl.xyz.databinding.ActivityMainBinding;
import sample.lyl.xyz.module.adapter.ArchiAdapter;
import sample.lyl.xyz.module.presenter.ArchiPresenter;
import sample.lyl.xyz.module.provider.ArchitectureComponents;
import sample.lyl.xyz.module.viewmodel.ArchiViewModel;
public class MainActivity extends AppCompatActivity {
private ArchiPresenter archiPresenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityMainBinding mainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
setSupportActionBar(mainBinding.toolbar);
ArchiViewModel archiViewModel = new ArchiViewModel();
mainBinding.setArchi(archiViewModel);
archiPresenter = new ArchiPresenter(archiViewModel);
archiPresenter.getArchiList();
mainBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
mainBinding.recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
mainBinding.recyclerView.setAdapter(new ArchiAdapter(new ArchiAdapter.OnUserListener() {
@Override
public void onDelete(ArchitectureComponents architectureComponents) {
archiPresenter.deleteArchi(architectureComponents);
}
}));
mainBinding.refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
archiPresenter.getArchiList();
}
});
mainBinding.fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
archiPresenter.addArchi();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| 35.240964 | 116 | 0.708034 |
beea1de99424a6b6e77a0b7320df39bff1fe298e | 257 | package com.serenitydojo.todomvc.actions;
import net.serenitybdd.core.steps.UIInteractionSteps;
public class Navigate extends UIInteractionSteps {
public void toTheTodoMVCnHomePage() {
openUrl("http://todomvc.com/examples/react/#/");
}
}
| 23.363636 | 56 | 0.747082 |
3588cf63324a17b6ab545170d8afa7067f7ff355 | 2,282 | /*
* Copyright 2012 Netflix, 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 com.netflix.exhibitor.core.entities;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
@SuppressWarnings("UnusedDeclaration")
public class SearchResult
{
private int docId;
private int type;
private String path;
private String date;
private String dataAsString;
private String dataBytes;
public SearchResult()
{
this(0, 0, "", "", "", "");
}
public SearchResult(int docId, int type, String path, String date, String dataAsString, String dataBytes)
{
this.docId = docId;
this.type = type;
this.path = path;
this.date = date;
this.dataAsString = dataAsString;
this.dataBytes = dataBytes;
}
public String getDate()
{
return date;
}
public void setDate(String date)
{
this.date = date;
}
public int getDocId()
{
return docId;
}
public void setDocId(int docId)
{
this.docId = docId;
}
public int getType()
{
return type;
}
public void setType(int type)
{
this.type = type;
}
public String getPath()
{
return path;
}
public void setPath(String path)
{
this.path = path;
}
public String getDataAsString()
{
return dataAsString;
}
public void setDataAsString(String dataAsString)
{
this.dataAsString = dataAsString;
}
public String getDataBytes()
{
return dataBytes;
}
public void setDataBytes(String dataBytes)
{
this.dataBytes = dataBytes;
}
}
| 21.327103 | 109 | 0.608677 |
ab069b607982a60b2434567daed2e19978c9bff0 | 1,417 | /*******************************************************************************
* Caleydo - Visualization for Molecular Biology - http://caleydo.org
* Copyright (c) The Caleydo Team. All rights reserved.
* Licensed under the new BSD license, available at http://caleydo.org/license
******************************************************************************/
package org.caleydo.view.radial;
import org.caleydo.core.event.AEvent;
import org.caleydo.core.view.opengl.keyboard.GLKeyListener;
import org.eclipse.swt.events.KeyEvent;
/**
* Listener for keyboard events for the radial hierarchy.
*
* @author Christian Partl
*/
public class GLRadialHierarchyKeyListener extends GLKeyListener<GLRadialHierarchy> {
GLRadialHierarchy radialHierarchy;
/**
* Constructor.
*
* @param radialHierarchy
* Instance of the radial hierarchy that should handle the
* keyboard events.
*/
public GLRadialHierarchyKeyListener(GLRadialHierarchy radialHierarchy) {
this.radialHierarchy = radialHierarchy;
}
@Override
protected void handleKeyPressedEvent(KeyEvent event) {
if (event.character == 'd') {
radialHierarchy.handleKeyboardAlternativeDiscSelection();
}
}
@Override
public void handleEvent(AEvent event) {
// TODO Auto-generated method stub
}
@Override
protected void handleKeyReleasedEvent(KeyEvent event) {
// TODO Auto-generated method stub
}
}
| 26.735849 | 84 | 0.661962 |
4dd5b06d7ad73e39648ed253725a0f64067d9f29 | 697 | package ru.szhernovoy.security.carstore.service;
import ru.szhernovoy.security.carstore.domain.*;
import java.util.List;
/**
* Created by Admin on 05.02.2017.
*/
public interface CarService {
List<Body> getAllBody();
Body getBodyById(int id);
List<Engine> getAllEngine();
Engine getEngineById(int id);
List<DriveType> getAllDriveType();
DriveType getDriveTypeById(int id);
List<Model> getAllModel();
Model getModelById(int id);
List<Transmission> getAllTransmission();
Transmission getTransmissionById(int id);
List<Car> getAllCar();
Car getCarById(int id);
Car add(Car car);
void delete(Car cart);
Car update(Car car);
}
| 19.361111 | 48 | 0.6901 |
06bb5eaa89c7f0e11dffcdc0e01a4daa2c4108a4 | 548 | package org.libermundi.frostgrave.domain.jpa.base;
import lombok.Getter;
import lombok.Setter;
import org.libermundi.frostgrave.domain.jpa.listeners.CreatedOrUpdatedByListener;
import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;
@Getter
@Setter
@MappedSuperclass
@EntityListeners(CreatedOrUpdatedByListener.class)
public abstract class AuditableEntity extends org.libermundi.frostgrave.domain.jpa.base.StatefulEntity implements CreatedOrUpdatedBy {
private String createdBy;
private String updatedBy;
}
| 28.842105 | 134 | 0.846715 |
4e8daf04748731c3ed50fe226389228cef311fb7 | 2,104 | /**************************************************************
*
* 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.
*
*************************************************************/
/*
* NativeOutputStreamHelper.java
*
* Created on 1. September 2004, 10:39
*/
package com.sun.star.sdbcx.comp.hsqldb;
/**
*
* @author oj93728
*/
public class NativeOutputStreamHelper extends java.io.OutputStream{
private String key;
private String file;
private StorageNativeOutputStream out;
/** Creates a new instance of NativeOutputStreamHelper */
public NativeOutputStreamHelper(String key,String _file) {
file = _file;
this.key = key;
out = new StorageNativeOutputStream(file,key);
}
public void write(byte[] b, int off, int len) throws java.io.IOException{
out.write(key,file,b, off, len);
}
public void write(byte[] b) throws java.io.IOException{
out.write(key,file,b);
}
public void close() throws java.io.IOException{
out.close(key,file);
}
public void write(int b) throws java.io.IOException{
out.write(key,file,b);
}
public void flush() throws java.io.IOException{
out.flush(key,file);
}
public void sync() throws java.io.IOException{
out.sync(key,file);
}
}
| 30.057143 | 78 | 0.635932 |
f3d466a736529143456427c539decd87374c68b4 | 2,118 | package view;
import model.Board;
import model.Player;
import javax.swing.*;
import java.awt.*;
/**
* This is the GUI view for main game panel
*/
public class Game_View extends JFrame {
public Board_View board_view;
public Menu_View menu_view;
public Score_View score_view;
public JPanel main_Panel;
/**
* Constructor for Game_View class
* @param board Game Board
* @param black_Player
* @param white_Player
*/
public Game_View(Board board, Player black_Player, Player white_Player){
/**
* Source: https://www.codejava.net/java-se/swing/jpanel-basic-tutorial-and-examples
*/
super("Chess Game");
setSize(53 * board.Board_Row, 70 * board.Board_Col);
setLayout(new BorderLayout());
this.menu_view = new Menu_View();
add(menu_view, BorderLayout.NORTH);
main_Panel = new JPanel(new BorderLayout());
this.score_view = new Score_View(board, black_Player, white_Player);
main_Panel.add(score_view, BorderLayout.NORTH);
this.board_view = new Board_View(board);
board.board_view = board_view;
main_Panel.add(this.board_view, BorderLayout.CENTER);
add(main_Panel);
setVisible(true);
setLocationRelativeTo(null);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
/**
* Re-initialize Score_View and Board_View
* @param board
* @param black_player
* @param white_player
*/
public void restart(Board board, Player black_player, Player white_player){
this.main_Panel.remove(this.score_view);
this.score_view = new Score_View(board, black_player, white_player);
this.main_Panel.add(score_view, BorderLayout.NORTH);
this.main_Panel.remove(this.board_view);
this.board_view = new Board_View(board);
board.board_view = board_view;
this.main_Panel.add(this.board_view, BorderLayout.CENTER);
this.main_Panel.revalidate();
this.main_Panel.repaint();
}
} | 33.619048 | 93 | 0.647781 |
45f757d70f9f6f5ad000bb259303586cdcb94404 | 1,054 | package no.javazone.cake.redux.comments;
public class TalkRating extends Feedback {
public final Rating rating;
@Override
public FeedbackType feedbackType() {
return FeedbackType.TALK_RATING;
}
@Override
public String getInfo() {
return rating.asText();
}
public static Builder builder() {
return new Builder();
}
public static class Builder extends FeedbackBuilder {
private Rating rating;
public Builder setRating(Rating rating) {
this.rating = rating;
return this;
}
@Override
public Builder setInfo(String info) {
return setRating(Rating.fromText(info));
}
@Override
public TalkRating create() {
return new TalkRating(this);
}
}
private TalkRating(Builder builder) {
super(builder);
if (builder.rating == null) {
throw new NullPointerException("Rating required");
}
this.rating = builder.rating;
}
}
| 21.958333 | 62 | 0.591082 |
61fd41c8ded12d6134cede5ede38d146e750351b | 371 | interface Showable{
void show();
interface Message{
void msg();
}
}
class TestNestedInterface implements Showable.Message{
public void msg(){
System.out.println("Hello nested interface");
}
public static void main(String args[]){
Showable.Message message=new TestNestedInterface();//upcasting here
message.msg();
}
} | 19.526316 | 73 | 0.654987 |
515416eb970e182aafae604878a01c1c6785b3e3 | 1,336 | package com.account.service.configuration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import static springfox.documentation.builders.PathSelectors.regex;
@Slf4j
@Configuration
@EnableSwagger2
class SwaggerConfiguration {
@Bean
public Docket serviceApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.account.service"))
.paths(regex("/*.*"))
.build()
.apiInfo(appMetaData());
}
private ApiInfo appMetaData() {
return new ApiInfoBuilder()
.title("Account Service REST API")
.description("Account Service")
.version("1.0.0")
.license("Any Licence")
.contact(new Contact("Tugce Konuklar",
"https://www.linkedin.com/in/tugce-konuklar/",
"tkonuklar@gmail.com"))
.build();
}
}
| 31.069767 | 71 | 0.752994 |
39fab4f0c023e80f8ebd9723b89973d18462a177 | 674 | package com.github.cyc.wanandroid.http;
/**
* HTTP码
*/
public final class HttpCode {
private HttpCode() {
}
/**
* 成功
*/
public static final int SUCCESS = 0;
/**
* 未知错误
*/
public static final int ERROR_UNKNOWN = 1000;
/**
* HTTP错误
*/
public static final int ERROR_HTTP = 1001;
/**
* 网络错误
*/
public static final int ERROR_NETWORK = 1002;
/**
* 解析错误
*/
public static final int ERROR_PARSE = 1003;
/**
* SSL错误
*/
public static final int ERROR_SSL = 1004;
/**
* 登录失效,需要重新登录
*/
public static final int ERROR_LOGIN_INVALID = -1001;
}
| 14.041667 | 56 | 0.532641 |
f51182f6149251091497232df51f93ea5d213438 | 3,600 | /**
* The MIT License
*
* Copyright (C) 2015 Asterios Raptis
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.astrapi69.test.objects;
import java.io.Serializable;
/**
* The class {@link Company} is a class intended for use in unit tests.
*/
public class Company implements Serializable
{
/**
* The serialVersionUID.
*/
private static final long serialVersionUID = 1L;
/**
* The name.
*/
private String name;
protected Company(CompanyBuilder<?, ?> b)
{
this.name = b.name;
}
public Company(String name)
{
this.name = name;
}
public Company()
{
}
public static CompanyBuilder<?, ?> builder()
{
return new CompanyBuilderImpl();
}
public CompanyBuilder<?, ?> toBuilder()
{
return new CompanyBuilderImpl().$fillValuesFrom(this);
}
public String getName()
{
return this.name;
}
public void setName(String name)
{
this.name = name;
}
public boolean equals(final Object o)
{
if (o == this)
return true;
if (!(o instanceof Company))
return false;
final Company other = (Company)o;
if (!other.canEqual(this))
return false;
final Object this$name = this.getName();
final Object other$name = other.getName();
return this$name == null ? other$name == null : this$name.equals(other$name);
}
protected boolean canEqual(final Object other)
{
return other instanceof Company;
}
public int hashCode()
{
final int PRIME = 59;
int result = 1;
final Object $name = this.getName();
result = result * PRIME + ($name == null ? 43 : $name.hashCode());
return result;
}
public String toString()
{
return "Company(name=" + this.getName() + ")";
}
public static abstract class CompanyBuilder<C extends Company, B extends CompanyBuilder<C, B>>
{
private String name;
private static void $fillValuesFromInstanceIntoBuilder(Company instance,
CompanyBuilder<?, ?> b)
{
b.name(instance.name);
}
public B name(String name)
{
this.name = name;
return self();
}
protected B $fillValuesFrom(C instance)
{
CompanyBuilder.$fillValuesFromInstanceIntoBuilder(instance, this);
return self();
}
protected abstract B self();
public abstract C build();
public String toString()
{
return "Company.CompanyBuilder(name=" + this.name + ")";
}
}
private static final class CompanyBuilderImpl
extends
CompanyBuilder<Company, CompanyBuilderImpl>
{
private CompanyBuilderImpl()
{
}
protected CompanyBuilderImpl self()
{
return this;
}
public Company build()
{
return new Company(this);
}
}
}
| 22.08589 | 95 | 0.698056 |
ee72fafd134b78b13182b20b942e56b3fe365098 | 1,321 | package com.intellij.coverage.listeners;
public abstract class CoverageListener {
private static final Class[] EMPTY_CLASS_ARRAY = new Class[0];
private Object myProjectData;
protected static String sanitize(String className, String methodName) {
return className + "," + sanitize(methodName, className.length());
}
public static String sanitize(String name, int length) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < name.length(); i++) {
final char ch = name.charAt(i);
if (ch > 0 && ch < 255) {
if (Character.isJavaIdentifierPart(ch) || ch == ' ' || ch == '@' || ch == '-') {
result.append(ch);
}
else {
result.append("_");
}
}
}
int methodNameLimit = 250 - length;
if (result.length() >= methodNameLimit) {
String hash = String.valueOf(result.toString().hashCode());
return (methodNameLimit > hash.length() ? result.substring(0, methodNameLimit - hash.length()) : "") + hash;
}
return result.toString();
}
protected Object getData() {
try {
return Class.forName("com.intellij.rt.coverage.data.ProjectData").getMethod("getProjectData", EMPTY_CLASS_ARRAY).invoke(null);
}
catch (Exception e) {
return null; //should not happen
}
}
}
| 28.106383 | 131 | 0.621499 |
f53be4f5d4c26868c10340d409809fc6af948dcd | 567 | package jp.sugarcoffee.processrunner.forge;
import jp.sugarcoffee.processrunner.ProcessRunnerExpectPlatform;
import net.minecraftforge.fml.loading.FMLPaths;
import java.nio.file.Path;
@SuppressWarnings("unused")
public class ProcessRunnerExpectPlatformImpl {
/**
* This is our actual method to {@link ProcessRunnerExpectPlatform#getConfigDirectory()}.
*/
public static Path getConfigDirectory() {
return FMLPaths.CONFIGDIR.get();
}
public static Path getGameDirectory() {
return getConfigDirectory().getParent();
}
}
| 27 | 93 | 0.740741 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.