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 |
|---|---|---|---|---|---|
05440f625a000db069266ea8707379c2ae8597fd | 655 | /**
* Copyright 2019 Smart Society Services B.V.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
package org.opensmartgridplatform.domain.da.measurements;
public enum ReasonType {
PERIODIC(1),
BACKGROUND_SCAN(2),
SPONTANEOUS(3),
INTERROGATED_BY_STATION(4);
private int reasonCode;
private ReasonType(final int reasonCode) {
this.reasonCode = reasonCode;
}
public int getReasonCode() {
return this.reasonCode;
}
}
| 25.192308 | 172 | 0.690076 |
de8c1366c8cc8364f843fe085e166514aa5f6fab | 2,292 | /*
* Portions copyright (c) 1998-1999, James Clark : see copyingjc.txt for
* license details
* Portions copyright (c) 2002, Bill Lindsey : see copying.txt for license
* details
*
* Portions copyright (c) 2009-2011 TIBCO Software 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.genxdm.processor.xpath.v10.expressions;
import org.genxdm.Model;
import org.genxdm.nodes.Traverser;
import org.genxdm.nodes.TraversingInformer;
import org.genxdm.processor.xpath.v10.iterators.FilterNodeIterator;
import org.genxdm.processor.xpath.v10.iterators.FilterTraverser;
import org.genxdm.xpath.v10.BooleanExpr;
import org.genxdm.xpath.v10.TraverserDynamicContext;
import org.genxdm.xpath.v10.ExprContextDynamic;
import org.genxdm.xpath.v10.NodeIterator;
import org.genxdm.xpath.v10.extend.ConvertibleNodeSetExpr;
final class FilterExpr
extends ConvertibleNodeSetExprImpl
{
private final ConvertibleNodeSetExpr expr;
private final BooleanExpr predicate;
FilterExpr(final ConvertibleNodeSetExpr expr, final BooleanExpr predicate)
{
super();
this.expr = expr;
this.predicate = predicate;
}
@Override
public <N> NodeIterator<N> nodeIterator(Model<N> model, final N node, final ExprContextDynamic<N> dynEnv) {
return new FilterNodeIterator<N>(model, expr.nodeIterator(model, node, dynEnv), dynEnv, predicate);
}
public Traverser traverseNodes(TraversingInformer contextNode, TraverserDynamicContext dynEnv) {
return new FilterTraverser(expr.traverseNodes(contextNode, dynEnv), dynEnv, predicate);
}
/*
* OPT: if the expr is of the form position()=n, then SINGLE_LEVEL must be true
*/
public int getOptimizeFlags()
{
return expr.getOptimizeFlags();
}
}
| 35.261538 | 109 | 0.745201 |
e2c14cbd1335257fb0789af97679ff3e1f324623 | 1,344 | /*
* Java
*
* Copyright 2017 IS2T. All rights reserved.
* For demonstration purpose only.
* IS2T PROPRIETARY. Use is subject to license terms.
*/
package com.microej.demo.smarthome.widget.light;
import com.microej.demo.smarthome.data.light.Light;
import com.microej.demo.smarthome.data.light.LightEventListener;
import com.microej.demo.smarthome.widget.CircleWidget;
import ej.style.Style;
/**
* A CircleWidget using a light as a model.
*/
public class LightCircleWidget extends CircleWidget implements LightEventListener {
private final Light light;
/**
* Instantiates a LightCircleWidget.
*
* @param light
* the model.
*/
public LightCircleWidget(final Light light) {
super();
this.light = light;
setEnabled(light.isOn());
}
@Override
protected int getColor(final Style style) {
return this.light.getColor();
}
@Override
public void onColorChange(final int color) {
repaint();
}
@Override
public void onBrightnessChange(final float brightness) {
// Do nothing.
}
@Override
public void onStateChange(final boolean on) {
setEnabled(on);
}
@Override
public void showNotify() {
super.showNotify();
this.light.addListener(this);
setEnabled(this.light.isOn());
}
@Override
public void hideNotify() {
super.hideNotify();
this.light.removeListener(this);
}
}
| 18.666667 | 83 | 0.716518 |
91156b7ed7f374100ef5b4dff36be96e57a1d4a3 | 1,285 | package com.example.applicationrunnercommandlinerunner.runner;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.List;
@Order(1)
@Component
public class TestApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("ApplicationRunner running, args#" + Arrays.asList(args.getSourceArgs()));
List<String> nonOptionArgs = args.getNonOptionArgs();
System.out.println("non option args#" + nonOptionArgs);
List<String> foo = args.getOptionValues("foo");
System.out.println("option args#" + foo);
List<String> foo2 = args.getOptionValues("foo2");
System.out.println("not exist option args#" + foo2);
Thread.sleep(5000);
new Thread(() -> {
try {
Thread.sleep(5000);
System.out.println("ApplicationRunner sub thread, threadId#" + Thread.currentThread().getId());
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
}
| 37.794118 | 111 | 0.675486 |
7b6b50819784887978d416d0ab533045cec6a5ac | 934 | /*
* Copyright (C) 2019 fastjrun, Inc. All Rights Reserved.
*/
package com.fastjrun.client.util;
import java.util.Map;
public abstract class BaseHTTPUtilClient extends BaseUtilClient {
protected String baseUrl;
protected Map<String, String> requestHeaderDefault;
public Map<String, String> getRequestHeaderDefault() {
return requestHeaderDefault;
}
public void setRequestHeaderDefault(Map<String, String> requestHeaderDefault) {
this.requestHeaderDefault = requestHeaderDefault;
}
public String getBaseUrl() {
return baseUrl;
}
public void setBaseUrl(String baseUrl) {
this.baseUrl = baseUrl;
}
public abstract String process(String path, String method, Map<String, String> queryParams,
Map<String, String> headParams, Map<String, String> cookieParams,
String requestBody);
}
| 26.685714 | 100 | 0.667024 |
0a3ea3a687d40685615069872978bbe5c27217e2 | 1,705 | /*
* This file is part of JGAP.
*
* JGAP offers a dual license model containing the LGPL as well as the MPL.
*
* For licensing information please see the file license.txt included with JGAP
* or have a look at the top of class org.jgap.Chromosome which representatively
* includes the JGAP license policy applicable for any file delivered with JGAP.
*/
package org.jgap.distr.grid;
import org.jgap.distr.grid.common.*;
/**
* Context of a message.
*
* @author Klaus Meffert
* @since 3.3.3
*/
public class MessageContext
extends BasicContext {
/** String containing the CVS revision. Read out via reflection!*/
private final static String CVS_REVISION = "$Revision: 1.4 $";
private String m_module;
private String m_context;
private String m_userGrp;
private String m_userID;
private String m_version;
public MessageContext() {
}
public MessageContext(String a_module, String a_context, Object a_contextid) {
m_module = a_module;
m_context = a_context;
setContextId(a_contextid);
}
public String getContext() {
return m_context;
}
public String getModule() {
return m_module;
}
public void setModule(String a_module) {
m_module = a_module;
}
public void setContext(String a_context) {
m_context = a_context;
}
public String getUserID() {
return m_userID;
}
public String getUserGrp() {
return m_userGrp;
}
public void setUserGrp(String a_userGrp) {
m_userGrp = a_userGrp;
}
public void setUserID(String a_userID) {
m_userID = a_userID;
}
public String getVersion() {
return m_version;
}
public void setVersion(String a_version) {
m_version = a_version;
}
}
| 20.297619 | 80 | 0.70088 |
fad5867cd054745c90ecf143754631f7f4f5f39a | 1,694 | package com.huirong.list;
/**
* Created by huirong on 17-5-22.
* 两个队列模拟栈
* 队列为循环队列
*/
public class QueueStack<E> {
private final int NUM;
private Object[] queue1;
private Object[] queue2;
private int front1 = 0, tail1 = 0, front2 = 0, tail2 = 0;
public QueueStack(int num) {
this.NUM = num;
queue1 = new Object[NUM];
queue2 = new Object[NUM];
}
/**
* 如果queue1或者queue2都为空
*/
public boolean empty(){
return front1 == tail1 && front2 == tail2;
}
/**
* 两个队列任意一个队列满都会溢出
*/
public boolean full(){
return (tail1 + 1) % NUM == front1 || (tail2 + 1) % NUM == front2;
}
/**
* 入栈
* 1.如果队列不满,则往队列中添加元素,如果队列满,溢出
*/
public void push(E elem){
if (empty()){
queue1[(tail1++) % NUM] = elem;
}else {
if (full()){
throw new RuntimeException("栈满");
}else {
if (tail1 == front1){
queue2[(tail2++) % NUM] = elem;
}else {
queue1[(tail1++) % NUM] = elem;
}
}
}
}
public E pop(){
if (empty()){
throw new RuntimeException("栈空");
}else {
if (tail1 == front1){
while ((tail2 + 2) % NUM != front2){
queue1[tail1++] = queue2[front2++];
}
return (E)queue2[front2++];
}else {
while ((tail1 + 2) % NUM != front1){
queue2[tail2++] = queue1[front1++];
}
return (E)queue1[front1++];
}
}
}
}
| 23.205479 | 74 | 0.4268 |
6c32385d49776a31e1fd90af23c1fee4dfdec481 | 7,996 | package com.example.ggxiaozhi.common.widget.recycler;
import android.support.annotation.LayoutRes;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import com.example.ggxiaozhi.common.R;
import butterknife.ButterKnife;
import butterknife.Unbinder;
/**
* 工程名 : ITalker
* 包名 : com.example.ggxiaozhi.italker.widget.recycler
* 作者名 : 志先生_
* 日期 : 2017/11/4
* 功能 :RecyclerView适配器封装
*/
public abstract class RecyclerAdapter<Data> extends
RecyclerView.Adapter<RecyclerAdapter.ViewHolder<Data>>
implements View.OnClickListener, View.OnLongClickListener,
AdapterCallBack<Data> {
private final List<Data> mDataList;
private AdapterListener<Data> mListener;
/**
* 三种不同的构造函数
*/
public RecyclerAdapter() {
this(null);
}
public RecyclerAdapter(AdapterListener<Data> adapterListener) {
this(new ArrayList<Data>(), adapterListener);
}
public RecyclerAdapter(List<Data> dataList, AdapterListener<Data> adapterListener) {
this.mDataList = dataList;
this.mListener = adapterListener;
}
/**
* 复写默认的布局返回类型
*
* @param position
* @return 布局类型,其实复写后返回的都是XML布局ID
*/
@Override
public int getItemViewType(int position) {
return getItemViewType(position, mDataList.get(position));
}
/**
* 得到布局的类型
*
* @param position 坐标
* @param data 当前的数据
* @return XML文件的ID
*/
@LayoutRes//@LayoutRes指定返回类型必须是XML布局资源
protected abstract int getItemViewType(int position, Data data);
/**
* 创建一个ViewHolder
*
* @param parent RecyclerView
* @param viewType 界面的类型,约定为XML布局的Id就是viewType
* @return ViewHolder
*/
@Override
public ViewHolder<Data> onCreateViewHolder(ViewGroup parent, int viewType) {
// 得到LayoutInflater用于把XML初始化为View
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
// 把XML id为viewType的文件初始化为一个root View
View root = inflater.inflate(viewType, parent, false);
// 通过子类必须实现的方法,得到一个ViewHolder
ViewHolder<Data> holder = onCreateViewHolder(root, viewType);
//设置View的tag为ViewHolder 进行双向绑定
root.setTag(R.id.tag_recycler_holder, holder);
//设置点击时间
root.setOnClickListener(this);
root.setOnLongClickListener(this);
//进行界面绑定
holder.mUnbinder = ButterKnife.bind(holder, root);
//绑定Callback
holder.mCallBack = this;
return holder;
}
/**
* 得到一个新的ViewHolder
*
* @param root 每个item的布局
* @param viewType 布局的Id
* @return viewholder
*/
protected abstract ViewHolder<Data> onCreateViewHolder(View root, int viewType);
/**
* 绑定数据到一个Holder上
*
* @param holder ViewHolder
* @param position 坐标
*/
@Override
public void onBindViewHolder(ViewHolder<Data> holder, int position) {
//得到绑定的数据
Data data = mDataList.get(position);
//触发Holder的绑定方法
holder.bind(data, position);
}
/**
* 得到当前集合的数据量
*/
@Override
public int getItemCount() {
return mDataList.size();
}
/**
* 得到当前集合
*/
public List<Data> getItems() {
return mDataList;
}
/**
* 插入一条数据并通知插入
*
* @param data
*/
public void add(Data data) {
mDataList.add(data);
//notifyItemInserted(int position);在指定位置插入并更新
notifyItemInserted(mDataList.size() - 1);
}
/**
* 插入多条数据并通知插入
*
* @param datas
*/
public void add(Data... datas) {
if (datas != null && datas.length > 0) {
int startPos = mDataList.size();
//Collections 此类不能实例化,就像一个工具类,服务于Java的Collection框架
Collections.addAll(mDataList, datas);
notifyItemRangeInserted(startPos, datas.length);
}
}
/**
* 插入数据集合并通知插入
*
* @param dataList
*/
public void add(Collection<Data> dataList) {
if (dataList != null && dataList.size() > 0) {
int startPos = mDataList.size();
mDataList.addAll(dataList);
notifyItemRangeInserted(startPos, dataList.size());
}
}
/**
* 清空数据
*/
public void clear() {
mDataList.clear();
notifyDataSetChanged();
}
/**
* 替换一个新的集合,其中包括清空
*
* @param dataList
*/
public void replace(Collection<Data> dataList) {
mDataList.clear();
if (dataList == null || dataList.size() == 0)
return;
mDataList.addAll(dataList);
notifyDataSetChanged();
}
/**
* 更新一条数据 (这个方法是实现AdapterCallBack接口中的方法)
*
* @param data
* @param holder
*/
@Override
public void updata(Data data, ViewHolder<Data> holder) {
//等到当前ViewHolder的坐标
int position = holder.getAdapterPosition();
if (position >= 0) {//判断这个坐标是否有效
//更新
mDataList.remove(position);
mDataList.add(position, data);
//刷新
notifyItemChanged(position);
}
}
@Override
public void onClick(View v) {
@SuppressWarnings("unchecked")
ViewHolder<Data> holder = (ViewHolder<Data>) v.getTag(R.id.tag_recycler_holder);
if (mDataList != null) {
int position = holder.getAdapterPosition();
if (mListener == null)
return;
mListener.onItemClick(holder, mDataList.get(position));
}
}
@Override
public boolean onLongClick(View v) {
@SuppressWarnings("unchecked")
ViewHolder<Data> holder = (ViewHolder<Data>) v.getTag(R.id.tag_recycler_holder);
if (mDataList != null) {
int position = holder.getAdapterPosition();
if (mListener == null)
return false;
mListener.onItemLongClick(holder, mDataList.get(position));
//事件消费返回true不再触发单击事件
return true;
}
return false;
}
/**
* 设置适配器的监听事件
*
* @param adapterListener
*/
public void setAdapterListener(AdapterListener<Data> adapterListener) {
this.mListener = adapterListener;
}
/**
* 点击时间的回调
*
* @param <Data>
*/
public interface AdapterListener<Data> {
//单击事件的回调
void onItemClick(ViewHolder holder, Data data);
//长按事件的回调
void onItemLongClick(ViewHolder holder, Data data);
}
public static class AdapterListenerImpl<Data> implements AdapterListener<Data> {
@Override
public void onItemClick(ViewHolder holder, Data data) {
}
@Override
public void onItemLongClick(ViewHolder holder, Data data) {
}
}
/**
* 自定义的ViewHolder
*
* @param <Data> 数据类型
*/
public static abstract class ViewHolder<Data> extends RecyclerView.ViewHolder {
private AdapterCallBack<Data> mCallBack;
protected Unbinder mUnbinder;
protected Data mData;
public ViewHolder(View itemView) {
super(itemView);
}
/**
* 绑定数据的触发
*
* @param data 绑定的数据
*/
void bind(Data data, int position) {
this.mData = data;
onBind(mData, position);
}
/**
* 绑定数据触发后的回调,必须复写
*
* @param data
*/
public abstract void onBind(Data data, int position);
/**
* holder自己对自己对应的Data进行更新操作
*
* @param data
*/
public void updataData(Data data) {
if (mCallBack != null) {
mCallBack.updata(data, this);
}
}
}
}
| 24.378049 | 88 | 0.588919 |
eb0e6740c29d48b60238de79295cbba900a63b8a | 614 | package net.mabako.steamgifts.data;
import java.io.Serializable;
public class Image implements Serializable {
private String url, title;
public Image(String url, String title) {
this.url = url;
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public String toString() {
return String.format("(%s,%s)", url, title);
}
}
| 18.058824 | 52 | 0.586319 |
6d478171ced5608e1ffe177d45e9f75727a03706 | 459 | package net.minecraft.util;
public enum EnumWorldBlockLayer
{
SOLID("Solid"),
CUTOUT_MIPPED("Mipped Cutout"),
CUTOUT("Cutout"),
TRANSLUCENT("Translucent");
private final String field_180338_e;
private static final String __OBFID = "CL_00002152";
private EnumWorldBlockLayer(String p_i45755_3_)
{
this.field_180338_e = p_i45755_3_;
}
public String toString()
{
return this.field_180338_e;
}
}
| 20.863636 | 56 | 0.67756 |
62db6426fc90e08e3605e6727e0b8e9244e40586 | 5,103 | package apoc.util;
import apoc.export.util.PointSerializer;
import apoc.export.util.TemporalSerializer;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MappingIterator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Option;
import com.jayway.jsonpath.spi.json.JacksonJsonProvider;
import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider;
import org.neo4j.graphdb.spatial.Point;
import org.neo4j.procedure.Name;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.temporal.Temporal;
import java.util.Map;
import java.util.Spliterators;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import static apoc.ApocConfig.apocConfig;
/**
* @author mh
* @since 04.05.16
*/
public class JsonUtil {
public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
public static final Object TOMB = new Object();
private static final Configuration JSON_PATH_CONFIG;
static {
OBJECT_MAPPER.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
OBJECT_MAPPER.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false);
OBJECT_MAPPER.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
OBJECT_MAPPER.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
OBJECT_MAPPER.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
OBJECT_MAPPER.configure(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER, true);
OBJECT_MAPPER.configure(JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS, true);
OBJECT_MAPPER.enable(DeserializationFeature.USE_LONG_FOR_INTS);
SimpleModule module = new SimpleModule("Neo4jApocSerializer");
module.addSerializer(Point.class, new PointSerializer());
module.addSerializer(Temporal.class, new TemporalSerializer());
OBJECT_MAPPER.registerModule(module);
JSON_PATH_CONFIG = Configuration.builder()
.options(Option.DEFAULT_PATH_LEAF_TO_NULL, Option.SUPPRESS_EXCEPTIONS)
.jsonProvider(new JacksonJsonProvider(OBJECT_MAPPER))
.mappingProvider(new JacksonMappingProvider(OBJECT_MAPPER))
.build();
}
static class NonClosingStream extends FilterInputStream {
protected NonClosingStream(InputStream in) {
super(in);
}
@Override
public void close() throws IOException {
}
}
public static Stream<Object> loadJson(String url, Map<String,Object> headers, String payload) {
return loadJson(url,headers,payload,"", true);
}
public static Stream<Object> loadJson(String url, Map<String,Object> headers, String payload, String path, boolean failOnError) {
try {
url = Util.getLoadUrlByConfigFile("json",url, "url").orElse(url);
apocConfig().checkReadAllowed(url);
url = FileUtils.changeFileUrlIfImportDirectoryConstrained(url);
InputStream input = Util.openInputStream(url, headers, payload);
JsonParser parser = OBJECT_MAPPER.getFactory().createParser(input);
MappingIterator<Object> it = OBJECT_MAPPER.readValues(parser, Object.class);
Stream<Object> stream = StreamSupport.stream(Spliterators.spliteratorUnknownSize(it, 0), false);
return (path==null||path.isEmpty()) ? stream : stream.map((value) -> JsonPath.parse(value,JSON_PATH_CONFIG).read(path));
} catch (IOException e) {
String u = Util.cleanUrl(url);
if(!failOnError)
return Stream.of();
else
throw new RuntimeException("Can't read url or key " + u + " as json: "+e.getMessage());
}
}
public static Stream<Object> loadJson(String url) {
return loadJson(url,null,null,"", true);
}
public static <T> T parse(String json, String path, Class<T> type) {
if (json==null || json.isEmpty()) return null;
try {
if (path == null || path.isEmpty()) {
return OBJECT_MAPPER.readValue(json, type);
}
return JsonPath.parse(json,JSON_PATH_CONFIG).read(path, type);
} catch (IOException e) {
throw new RuntimeException("Can't convert " + json + " to "+type.getSimpleName()+" with path "+path, e);
}
}
public static String writeValueAsString(Object json) {
try {
return OBJECT_MAPPER.writeValueAsString(json);
} catch (JsonProcessingException e) {
return null;
}
}
public static byte[] writeValueAsBytes(Object json) {
try {
return OBJECT_MAPPER.writeValueAsBytes(json);
} catch (JsonProcessingException e) {
return null;
}
}
}
| 41.487805 | 133 | 0.692338 |
bdd38cde7b050f979395b589878c5a674a99b065 | 6,052 | /*******************************************************************************
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*******************************************************************************/
package org.jetbrains.kotlin.navigation.netbeans;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.EnumSet;
import java.util.Set;
import javax.swing.text.Document;
import javax.swing.text.StyledDocument;
import kotlin.Pair;
import org.jetbrains.kotlin.utils.ProjectUtils;
import org.jetbrains.kotlin.psi.KtFile;
import org.netbeans.api.editor.mimelookup.MimeRegistration;
import org.netbeans.api.java.source.ElementHandle;
import org.netbeans.api.project.Project;
import org.netbeans.lib.editor.hyperlink.spi.HyperlinkProviderExt;
import org.netbeans.lib.editor.hyperlink.spi.HyperlinkType;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.util.Exceptions;
import org.openide.util.Lookup;
@MimeRegistration(mimeType = "text/x-java", service = HyperlinkProviderExt.class)
public final class JavaHyperlinkProvider implements HyperlinkProviderExt {
private Class clazz = null;
private Object object = null;
public JavaHyperlinkProvider() {
ClassLoader loader = Lookup.getDefault().lookup(ClassLoader.class);
try {
clazz = Class.forName(
"org.netbeans.modules.java.editor.hyperlink.JavaHyperlinkProvider",
true, loader);
Constructor constructor = clazz.getConstructor();
object = constructor.newInstance();
} catch (ReflectiveOperationException ex) {
Exceptions.printStackTrace(ex);
}
}
@Override
public Set<HyperlinkType> getSupportedHyperlinkTypes() {
return EnumSet.of(HyperlinkType.GO_TO_DECLARATION, HyperlinkType.ALT_HYPERLINK);
}
private int[] getIdentifierSpan(Document doc, int offset) {
if (clazz == null || object == null) {
return new int[0];
}
try {
Method method = clazz.getMethod("getHyperlinkSpan", Document.class, int.class, HyperlinkType.class);
return (int[]) method.invoke(object, doc, offset, null);
} catch (ReflectiveOperationException ex) {
Exceptions.printStackTrace(ex);
}
return new int[0];
}
private String tooltipText(Document doc, int offset) {
if (clazz == null || object == null) {
return null;
}
try {
Method method = clazz.getMethod("getTooltipText", Document.class, int.class, HyperlinkType.class);
return (String) method.invoke(object, doc, offset, null);
} catch (ReflectiveOperationException ex) {
Exceptions.printStackTrace(ex);
}
return null;
}
private void clickAction(Document doc, int offset, HyperlinkType type) {
if (clazz == null || object == null) {
return;
}
try {
Method method = clazz.getMethod("performClickAction", Document.class, int.class, HyperlinkType.class);
method.invoke(object, doc, offset, type);
} catch (ReflectiveOperationException ex) {
Exceptions.printStackTrace(ex);
}
}
@Override
public boolean isHyperlinkPoint(Document doc, int offset, HyperlinkType type) {
return getHyperlinkSpan(doc, offset, type) != null;
}
@Override
public int[] getHyperlinkSpan(Document doc, int offset, HyperlinkType type) {
return getIdentifierSpan(doc, offset);
}
@Override
public void performClickAction(Document doc, int offset, HyperlinkType type) {
switch (type) {
case GO_TO_DECLARATION:
ElementHandle element = FromJavaToKotlinNavigationUtilsKt.getElement(doc, offset);
FileObject file = ProjectUtils.getFileObjectForDocument(doc);
Project project = ProjectUtils.getKotlinProjectForFileObject(file);
Pair<KtFile, Integer> pair = FromJavaToKotlinNavigationUtilsKt.findKotlinFileToNavigate(element, project, doc);
if (pair == null) {
clickAction(doc, offset, type);
break;
}
KtFile ktFile = pair.getFirst();
int offsetToOpen = pair.getSecond();
if (ktFile != null) {
String filePath = ktFile.getVirtualFile().getPath();
FileObject fileToOpen = FileUtil.toFileObject(new File(filePath));
try {
StyledDocument docToOpen = ProjectUtils.getDocumentFromFileObject(fileToOpen);
if (docToOpen == null) return;
OpenDeclarationKt.openFileAtOffset(docToOpen, offsetToOpen);
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
} else clickAction(doc, offset, type);
break;
case ALT_HYPERLINK:
clickAction(doc, offset, type);
break;
}
}
@Override
public String getTooltipText(Document doc, int offset, HyperlinkType type) {
return tooltipText(doc, offset);
}
}
| 38.303797 | 127 | 0.61616 |
146da088a41e1731f25ca1be8821eb0c3d27fe2c | 3,593 | /*
* 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 opennlp.tools.ml.perceptron;
import java.util.Map;
import opennlp.tools.ml.model.AbstractModel;
import opennlp.tools.ml.model.Context;
import opennlp.tools.ml.model.EvalParameters;
public class PerceptronModel extends AbstractModel {
public PerceptronModel(Context[] params, String[] predLabels, Map<String, Integer> pmap,
String[] outcomeNames) {
super(params,predLabels,pmap,outcomeNames);
modelType = ModelType.Perceptron;
}
public PerceptronModel(Context[] params, String[] predLabels, String[] outcomeNames) {
super(params,predLabels,outcomeNames);
modelType = ModelType.Perceptron;
}
public double[] eval(String[] context) {
return eval(context,new double[evalParams.getNumOutcomes()]);
}
public double[] eval(String[] context, float[] values) {
return eval(context,values,new double[evalParams.getNumOutcomes()]);
}
public double[] eval(String[] context, double[] probs) {
return eval(context,null,probs);
}
public double[] eval(String[] context, float[] values,double[] outsums) {
int[] scontexts = new int[context.length];
java.util.Arrays.fill(outsums, 0);
for (int i = 0; i < context.length; i++) {
Integer ci = pmap.get(context[i]);
scontexts[i] = ci == null ? -1 : ci;
}
return eval(scontexts,values,outsums,evalParams,true);
}
public static double[] eval(int[] context, double[] prior, EvalParameters model) {
return eval(context,null,prior,model,true);
}
public static double[] eval(int[] context, float[] values, double[] prior, EvalParameters model,
boolean normalize) {
Context[] params = model.getParams();
double[] activeParameters;
int[] activeOutcomes;
double value = 1;
for (int ci = 0; ci < context.length; ci++) {
if (context[ci] >= 0) {
Context predParams = params[context[ci]];
activeOutcomes = predParams.getOutcomes();
activeParameters = predParams.getParameters();
if (values != null) {
value = values[ci];
}
for (int ai = 0; ai < activeOutcomes.length; ai++) {
int oid = activeOutcomes[ai];
prior[oid] += activeParameters[ai] * value;
}
}
}
if (normalize) {
int numOutcomes = model.getNumOutcomes();
double maxPrior = 1;
for (int oid = 0; oid < numOutcomes; oid++) {
if (maxPrior < Math.abs(prior[oid]))
maxPrior = Math.abs(prior[oid]);
}
double normal = 0.0;
for (int oid = 0; oid < numOutcomes; oid++) {
prior[oid] = Math.exp(prior[oid] / maxPrior);
normal += prior[oid];
}
for (int oid = 0; oid < numOutcomes; oid++)
prior[oid] /= normal;
}
return prior;
}
}
| 33.579439 | 98 | 0.652936 |
766c537fcddafddbde93e3beab2e0d8121a9b695 | 9,368 | package bq_standard.tasks;
import betterquesting.api.questing.IQuest;
import betterquesting.api.questing.tasks.ITask;
import betterquesting.api.utils.BigItemStack;
import betterquesting.api.utils.ItemComparison;
import betterquesting.api.utils.JsonHelper;
import betterquesting.api.utils.NBTConverter;
import betterquesting.api2.client.gui.misc.IGuiRect;
import betterquesting.api2.client.gui.panels.IGuiPanel;
import betterquesting.api2.storage.DBEntry;
import betterquesting.api2.utils.ParticipantInfo;
import betterquesting.api2.utils.Tuple2;
import bq_standard.client.gui.tasks.PanelTaskCrafting;
import bq_standard.core.BQ_Standard;
import bq_standard.tasks.factory.FactoryTaskCrafting;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.*;
import net.minecraft.nbt.NBTBase.NBTPrimitive;
import net.minecraft.util.ResourceLocation;
import org.apache.logging.log4j.Level;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.*;
public class TaskCrafting implements ITask
{
private final Set<UUID> completeUsers = new TreeSet<>();
public final List<BigItemStack> requiredItems = new ArrayList<>();
public final TreeMap<UUID, int[]> userProgress = new TreeMap<>();
public boolean partialMatch = true;
public boolean ignoreNBT = true;
public boolean allowAnvil = false;
public boolean allowSmelt = true;
public boolean allowCraft = true;
@Override
public ResourceLocation getFactoryID()
{
return FactoryTaskCrafting.INSTANCE.getRegistryName();
}
@Override
public boolean isComplete(UUID uuid)
{
return completeUsers.contains(uuid);
}
@Override
public void setComplete(UUID uuid)
{
completeUsers.add(uuid);
}
@Override
public String getUnlocalisedName()
{
return "bq_standard.task.crafting";
}
@Override
public void detect(ParticipantInfo pInfo, DBEntry<IQuest> quest)
{
pInfo.ALL_UUIDS.forEach((uuid) -> {
if(isComplete(uuid)) return;
int[] tmp = getUsersProgress(uuid);
for(int i = 0; i < requiredItems.size(); i++)
{
BigItemStack rStack = requiredItems.get(i);
if(tmp[i] < rStack.stackSize) return;
}
setComplete(uuid);
});
pInfo.markDirtyParty(Collections.singletonList(quest.getID()));
}
public void onItemCraft(ParticipantInfo pInfo, DBEntry<IQuest> quest, ItemStack stack)
{
if(!allowCraft) return;
onItemInternal(pInfo, quest, stack);
}
public void onItemSmelt(ParticipantInfo pInfo, DBEntry<IQuest> quest, ItemStack stack)
{
if(!allowSmelt) return;
onItemInternal(pInfo, quest, stack);
}
public void onItemAnvil(ParticipantInfo pInfo, DBEntry<IQuest> quest, ItemStack stack)
{
if(!allowAnvil) return;
onItemInternal(pInfo, quest, stack);
}
private void onItemInternal(ParticipantInfo pInfo, DBEntry<IQuest> quest, ItemStack stack)
{
if(stack == null || stack.stackSize <= 0) return;
final List<Tuple2<UUID, int[]>> progress = getBulkProgress(pInfo.ALL_UUIDS);
boolean changed = false;
for(int i = 0; i < requiredItems.size(); i++)
{
final BigItemStack rStack = requiredItems.get(i);
final int index = i;
if(ItemComparison.StackMatch(rStack.getBaseStack(), stack, !ignoreNBT, partialMatch) || ItemComparison.OreDictionaryMatch(rStack.getOreIngredient(), rStack.GetTagCompound(), stack, !ignoreNBT, partialMatch))
{
progress.forEach((entry) -> {
if(entry.getSecond()[index] >= rStack.stackSize) return;
entry.getSecond()[index] = Math.min(entry.getSecond()[index] + stack.stackSize, rStack.stackSize);
});
changed = true;
}
}
if(changed)
{
setBulkProgress(progress);
detect(pInfo, quest);
}
}
@Override
public NBTTagCompound writeToNBT(NBTTagCompound nbt)
{
nbt.setBoolean("partialMatch", partialMatch);
nbt.setBoolean("ignoreNBT", ignoreNBT);
nbt.setBoolean("allowCraft", allowCraft);
nbt.setBoolean("allowSmelt", allowSmelt);
nbt.setBoolean("allowAnvil", allowAnvil);
NBTTagList itemArray = new NBTTagList();
for(BigItemStack stack : this.requiredItems)
{
itemArray.appendTag(JsonHelper.ItemStackToJson(stack, new NBTTagCompound()));
}
nbt.setTag("requiredItems", itemArray);
return nbt;
}
@Override
public void readFromNBT(NBTTagCompound nbt)
{
partialMatch = nbt.getBoolean("partialMatch");
ignoreNBT = nbt.getBoolean("ignoreNBT");
if(nbt.hasKey("allowCraft")) allowCraft = nbt.getBoolean("allowCraft");
if(nbt.hasKey("allowSmelt")) allowSmelt = nbt.getBoolean("allowSmelt");
if(nbt.hasKey("allowAnvil")) allowAnvil = nbt.getBoolean("allowAnvil");
requiredItems.clear();
NBTTagList iList = nbt.getTagList("requiredItems", 10);
for(int i = 0; i < iList.tagCount(); i++)
{
requiredItems.add(JsonHelper.JsonToItemStack(iList.getCompoundTagAt(i)));
}
}
@Override
public void readProgressFromNBT(NBTTagCompound nbt, boolean merge)
{
if(!merge)
{
completeUsers.clear();
userProgress.clear();
}
NBTTagList cList = nbt.getTagList("completeUsers", 8);
for(int i = 0; i < cList.tagCount(); i++)
{
try
{
completeUsers.add(UUID.fromString(cList.getStringTagAt(i)));
} catch(Exception e)
{
BQ_Standard.logger.log(Level.ERROR, "Unable to load UUID for task", e);
}
}
NBTTagList pList = nbt.getTagList("userProgress", 10);
for(int n = 0; n < pList.tagCount(); n++)
{
NBTTagCompound pTag = pList.getCompoundTagAt(n);
UUID uuid;
try
{
uuid = UUID.fromString(pTag.getString("uuid"));
} catch(Exception e)
{
BQ_Standard.logger.log(Level.ERROR, "Unable to load user progress for task", e);
continue;
}
int[] data = new int[requiredItems.size()];
List<NBTBase> dJson = NBTConverter.getTagList(pTag.getTagList("data", 3));
for(int i = 0; i < data.length && i < dJson.size(); i++)
{
try
{
data[i] = ((NBTPrimitive)dJson.get(i)).func_150287_d();
} catch(Exception e)
{
BQ_Standard.logger.log(Level.ERROR, "Incorrect task progress format", e);
}
}
userProgress.put(uuid, data);
}
}
@Override
public NBTTagCompound writeProgressToNBT(NBTTagCompound nbt, List<UUID> users)
{
NBTTagList jArray = new NBTTagList();
NBTTagList progArray = new NBTTagList();
if(users != null)
{
users.forEach((uuid) -> {
if(completeUsers.contains(uuid)) jArray.appendTag(new NBTTagString(uuid.toString()));
int[] data = userProgress.get(uuid);
if(data != null)
{
NBTTagCompound pJson = new NBTTagCompound();
pJson.setString("uuid", uuid.toString());
NBTTagList pArray = new NBTTagList(); // TODO: Why the heck isn't this just an int array?!
for(int i : data) pArray.appendTag(new NBTTagInt(i));
pJson.setTag("data", pArray);
progArray.appendTag(pJson);
}
});
} else
{
completeUsers.forEach((uuid) -> jArray.appendTag(new NBTTagString(uuid.toString())));
userProgress.forEach((uuid, data) -> {
NBTTagCompound pJson = new NBTTagCompound();
pJson.setString("uuid", uuid.toString());
NBTTagList pArray = new NBTTagList(); // TODO: Why the heck isn't this just an int array?!
for(int i : data) pArray.appendTag(new NBTTagInt(i));
pJson.setTag("data", pArray);
progArray.appendTag(pJson);
});
}
nbt.setTag("completeUsers", jArray);
nbt.setTag("userProgress", progArray);
return nbt;
}
@Override
public void resetUser(@Nullable UUID uuid)
{
if(uuid == null)
{
completeUsers.clear();
userProgress.clear();
} else
{
completeUsers.remove(uuid);
userProgress.remove(uuid);
}
}
@Override
public IGuiPanel getTaskGui(IGuiRect rect, DBEntry<IQuest> context)
{
return new PanelTaskCrafting(rect, this);
}
@Override
@SideOnly(Side.CLIENT)
public GuiScreen getTaskEditor(GuiScreen parent, DBEntry<IQuest> quest)
{
return null;
}
private void setUserProgress(UUID uuid, int[] progress)
{
userProgress.put(uuid, progress);
}
public int[] getUsersProgress(UUID uuid)
{
int[] progress = userProgress.get(uuid);
return progress == null || progress.length != requiredItems.size()? new int[requiredItems.size()] : progress;
}
private List<Tuple2<UUID, int[]>> getBulkProgress(@Nonnull List<UUID> uuids)
{
if(uuids.size() <= 0) return Collections.emptyList();
List<Tuple2<UUID, int[]>> list = new ArrayList<>();
uuids.forEach((key) -> list.add(new Tuple2<>(key, getUsersProgress(key))));
return list;
}
private void setBulkProgress(@Nonnull List<Tuple2<UUID, int[]>> list)
{
list.forEach((entry) -> setUserProgress(entry.getFirst(), entry.getSecond()));
}
}
| 30.122186 | 210 | 0.654996 |
5e343d1be29ed02414e4148ead1a54fb54d74b08 | 621 | import java.util.Scanner;
public class Volume
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("please enter the price for a six-pacak: ");
double packPrice= in.nextDouble();
System.out.print("please enter the volume for each(in ounces):");
double CanVolume = in.nextDouble();
final double CANS_PER_PACK = 6;
double packVolume = CanVolume * CANS_PER_PACK;
double pricePerOunce = packPrice / packVolume;
System.out.printf("price per ounce is: %8.2f", pricePerOunce);
System.out.println();
}
} | 27 | 69 | 0.653784 |
fb2f66624d2e5ca478604a156f8f379f9372f944 | 1,127 | package hci201.tingada;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
public class SplashFirstActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_splash_first);
Thread myThread = new Thread(){
@Override
public void run() {
super.run();
try {
sleep(3000);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
finish();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
myThread.start();
}
}
| 30.459459 | 122 | 0.61402 |
3b45ca43fd192382d8281f67fef50bc7377a1a10 | 472 | public class Test1 {
/**
* Sunny day scenario test.
*/
public static void main()
//@ requires true;
//@ ensures true;
{
Test1[] own1;
Test1[] own2;
Object[] obj1;
Object[] obj2;
int[] int1;
int[] int2;
short[] short1;
short[] short2;
own1 = own2;
obj1 = obj2;
int1 = int2;
short1 = short2;
obj1 = own1;
}
public void test1()
//@ requires true;
//@ ensures true;
{
Test1[] own1;
Object [] obj1;
own1 = obj1; //~
}
}
| 13.111111 | 28 | 0.555085 |
32664a571cb458c69f947c25b50b7eaf6a6dbacf | 954 | /*package com.springbook.view.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.springbook.biz.board.BoardVO;
import com.springbook.biz.board.impl.BoardDAO;
@Controller
public class GetBoardListController {
public GetBoardListController() {
// TODO Auto-generated constructor stub
}
@RequestMapping("/getBoardList.do")
public ModelAndView getBoardList(BoardVO vo , BoardDAO dao ,ModelAndView mnv) {
// TODO Auto-generated method stub
System.out.println("getBoardList.do");
List<BoardVO> boardList = dao.getBoardList(vo);
mnv.addObject("boardList",boardList);
mnv.setViewName("getBoardList.jsp");
return mnv;
}
}
*/ | 22.714286 | 80 | 0.777778 |
76f5749ac8acd1a773729962568d755ae6bdaeb2 | 3,947 | /*
* Copyright 2017-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.opendevstack.provision.model.jira;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
/*
* { "name": "Component 1", "description": "This is a JIRA component", "leadUserName": "fred",
* "assigneeType": "PROJECT_LEAD", "isAssigneeTypeValid": false, "project": "PROJECTKEY",
* "projectId": 10000 }
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({"name", "description", "leadUserName", "assigneeType", "isAssigneeTypeValid",
"project", "projectId"})
@Generated(value = {"JSON-to-Pojo-Generator"})
public class Component {
@JsonProperty("name")
private String name;
@JsonProperty("description")
private String description;
@JsonProperty("leadUserName")
private String leadUserName;
@JsonProperty("assigneeType")
private String assigneeType;
@JsonProperty("isAssigneeTypeValid")
private Boolean isAssigneeTypeValid;
@JsonProperty("project")
private String project;
@JsonProperty("projectId")
private Integer projectId;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
@JsonProperty("name")
public String getName() {
return name;
}
@JsonProperty("name")
public void setName(String name) {
this.name = name;
}
@JsonProperty("description")
public String getDescription() {
return description;
}
@JsonProperty("description")
public void setDescription(String description) {
this.description = description;
}
@JsonProperty("leadUserName")
public String getLeadUserName() {
return leadUserName;
}
@JsonProperty("leadUserName")
public void setLeadUserName(String leadUserName) {
this.leadUserName = leadUserName;
}
@JsonProperty("assigneeType")
public String getAssigneeType() {
return assigneeType;
}
@JsonProperty("assigneeType")
public void setAssigneeType(String assigneeType) {
this.assigneeType = assigneeType;
}
@JsonProperty("isAssigneeTypeValid")
public Boolean getIsAssigneeTypeValid() {
return isAssigneeTypeValid;
}
@JsonProperty("isAssigneeTypeValid")
public void setIsAssigneeTypeValid(Boolean isAssigneeTypeValid) {
this.isAssigneeTypeValid = isAssigneeTypeValid;
}
@JsonProperty("project")
public String getProject() {
return project;
}
@JsonProperty("project")
public void setProject(String project) {
this.project = project;
}
@JsonProperty("projectId")
public Integer getProjectId() {
return projectId;
}
@JsonProperty("projectId")
public void setProjectId(Integer projectId) {
this.projectId = projectId;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
| 29.022059 | 101 | 0.71776 |
99cd1c5eb6e18ae431149e1f25805f39cf38fe9d | 10,464 | package ru.job4j.solid.ocp.worker;
import ru.job4j.solid.ocp.worker.converter.Converter;
import ru.job4j.solid.ocp.worker.converter.ToJSON;
import ru.job4j.solid.ocp.worker.converter.ToTXT;
import ru.job4j.solid.ocp.worker.converter.ToXML;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Pattern;
public class WorkerInfo {
private WorkerStorage workerStorage;
private HashMap<String, Converter> converters;
private HashMap<String, String> filterKeys;
public WorkerInfo(WorkerStorage workerStorage) {
this.workerStorage = workerStorage;
this.converters = new HashMap<>();
this.filterKeys = new HashMap<>();
this.filterKeys.put("0", "without filter");
this.filterKeys.put("1", "name");
this.filterKeys.put("2", "rate");
this.filterKeys.put("3", "experience");
}
public Converter addConverter(String key, Converter converter) {
return this.converters.put(key, converter);
}
public void startShow() throws Exception {
Scanner scanner = new Scanner(System.in);
String converterKey;
do {
this.showConverterKeys();
converterKey = scanner.nextLine();
if (!"exit".equals(converterKey)) {
if (this.converters.containsKey(converterKey)) {
String filterKey;
boolean result;
do {
this.showFilterKeys();
filterKey = scanner.nextLine();
result = this.filterKeys.containsKey(filterKey);
if (!"exit".equals(filterKey)) {
if (result) {
this.converters.get(converterKey).show(this.getFilteredWorkerList(filterKey));
} else {
System.out.println("Введенный ключ некорректен. Используйте ключи из списка.");
}
} else {
converterKey = "exit";
}
} while (!"exit".equals(filterKey) && !result);
} else {
System.out.println("Введенный ключ некорректен. Используйте ключи из списка.");
}
}
} while (!"exit".equals(converterKey));
}
private List<Worker> getFilteredWorkerList(String filterKey) {
List<Worker> result = new ArrayList<>();
int key = Integer.parseInt(filterKey);
if (key == 0) {
result = this.workerStorage.getWorkerList();
} else {
if (key == 1) {
result = this.getFilteredByNameWorkerList();
}
if (key == 2) {
result = this.getFilteredByNumberWorkerList("rate");
}
if (key == 3) {
result = this.getFilteredByNumberWorkerList("experience");
}
}
return result;
}
private List<Worker> getFilteredByNameWorkerList() {
List<Worker> result = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
Pattern pattern;
System.out.println("Введите полное имя работника или маску имени:");
String nameMask = scanner.nextLine();
if (nameMask.contains("*")) {
StringBuilder regexBuilder = new StringBuilder("^");
for (int i = 0; i < nameMask.length(); i++) {
if (nameMask.charAt(i) == '*') {
regexBuilder.append(".*");
} else {
regexBuilder.append(nameMask.charAt(i));
}
}
regexBuilder.append("$");
pattern = Pattern.compile(regexBuilder.toString());
} else {
pattern = Pattern.compile(nameMask);
}
this.workerStorage.getWorkerList().stream()
.filter(worker -> pattern.matcher(worker.getName()).matches())
.forEach(result::add);
return result;
}
private List<Worker> getFilteredByNumberWorkerList(String field) {
List<Worker> result = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
System.out.println(String.format("Введите значение для %s (к примеру, '1.5'):", field));
Double numberFilter = null;
boolean isNumber;
do {
try {
isNumber = true;
numberFilter = Double.valueOf(scanner.nextLine());
} catch (NumberFormatException nfe) {
isNumber = false;
System.out.println("Введенное значение не является числом. Попробуйте снова.");
}
} while (!isNumber);
boolean isComparisonSymbol;
do {
System.out.println("Введи знак условия: ('<', '>', '<=', '>=', '=', '!=')");
String rateFilterString = scanner.nextLine();
Pattern pattern = Pattern.compile("[<>=]|<=|>=|!=");
if (pattern.matcher(rateFilterString).matches()) {
isComparisonSymbol = true;
Double finalNumberFilter = numberFilter;
if (">".equals(rateFilterString)) {
if ("rate".equals(field)) {
this.workerStorage.getWorkerList().stream()
.filter(worker -> worker.getRate() > finalNumberFilter)
.forEach(result::add);
}
if ("experience".equals(field)) {
this.workerStorage.getWorkerList().stream()
.filter(worker -> worker.getExperience() > finalNumberFilter)
.forEach(result::add);
}
}
if ("<".equals(rateFilterString)) {
if ("rate".equals(field)) {
this.workerStorage.getWorkerList().stream()
.filter(worker -> worker.getRate() < finalNumberFilter)
.forEach(result::add);
}
if ("experience".equals(field)) {
this.workerStorage.getWorkerList().stream()
.filter(worker -> worker.getExperience() < finalNumberFilter)
.forEach(result::add);
}
}
if (">=".equals(rateFilterString)) {
if ("rate".equals(field)) {
this.workerStorage.getWorkerList().stream()
.filter(worker -> worker.getRate() >= finalNumberFilter)
.forEach(result::add);
}
if ("experience".equals(field)) {
this.workerStorage.getWorkerList().stream()
.filter(worker -> worker.getExperience() >= finalNumberFilter)
.forEach(result::add);
}
}
if ("<=".equals(rateFilterString)) {
if ("rate".equals(field)) {
this.workerStorage.getWorkerList().stream()
.filter(worker -> worker.getRate() <= finalNumberFilter)
.forEach(result::add);
}
if ("experience".equals(field)) {
this.workerStorage.getWorkerList().stream()
.filter(worker -> worker.getExperience() <= finalNumberFilter)
.forEach(result::add);
}
}
if ("=".equals(rateFilterString)) {
if ("rate".equals(field)) {
this.workerStorage.getWorkerList().stream()
.filter(worker -> worker.getRate() == finalNumberFilter)
.forEach(result::add);
}
if ("experience".equals(field)) {
this.workerStorage.getWorkerList().stream()
.filter(worker -> worker.getExperience() == finalNumberFilter)
.forEach(result::add);
}
}
if ("!=".equals(rateFilterString)) {
if ("rate".equals(field)) {
this.workerStorage.getWorkerList().stream()
.filter(worker -> worker.getRate() != finalNumberFilter)
.forEach(result::add);
}
if ("experience".equals(field)) {
this.workerStorage.getWorkerList().stream()
.filter(worker -> worker.getExperience() != finalNumberFilter)
.forEach(result::add);
}
}
} else {
isComparisonSymbol = false;
System.out.println("Неверный знак условия. Попробуйте еще раз.");
}
} while (!isComparisonSymbol);
return result;
}
private void showFilterKeys() {
System.out.println("Введи ключ фильтра или \"exit\" для выхода:");
this.filterKeys.forEach((key, field) ->
System.out.println("ключ " + key + " - " + field)
);
}
private void showConverterKeys() {
System.out.println("Введи ключ операции или \"exit\" для выхода:");
this.converters.forEach((s, converter) ->
System.out.println("ключ " + s + " для формата " + converter.toString())
);
}
public static void main(String[] args) throws Exception {
WorkerStorage workerStorage = new WorkerStorage();
workerStorage.add(new Worker("worker1", 1.0, 1));
workerStorage.add(new Worker("worker2", 2.0, 2));
workerStorage.add(new Worker("worker2", 2.0, 3));
workerStorage.add(new Worker("worker3", 3.0, 3));
WorkerInfo workerInfo = new WorkerInfo(workerStorage);
workerInfo.addConverter("1", new ToJSON());
workerInfo.addConverter("2", new ToXML());
workerInfo.addConverter("3", new ToTXT());
workerInfo.startShow();
}
}
| 43.782427 | 111 | 0.495413 |
b3f963de5af5da1521136641f377f8655d5070ee | 2,538 | package uk.ac.ox.oucs.oxam.readers;
import java.io.IOException;
import java.io.InputStream;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import uk.ac.ox.oucs.oxam.logic.CategoryService;
import uk.ac.ox.oucs.oxam.logic.ExamPaperService;
import uk.ac.ox.oucs.oxam.logic.LocalPaperFileServiceImpl;
import uk.ac.ox.oucs.oxam.logic.TermService;
import uk.ac.ox.oucs.oxam.readers.Import.ExamPaperRow;
import uk.ac.ox.oucs.oxam.readers.SheetImporter.Format;
// TODO Look at @Parameterized for MySQL/Derby testing.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"/context.xml", "/standalone-beans.xml","/oxam-beans.xml"})
@Transactional
public class FullImportTest {
@Autowired
private ExamPaperService service;
@Autowired
private TermService termService;
@Autowired
private CategoryService categoryService;
private Import import1;
@Before
public void setUp() {
ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
Importer importer = new Importer();
importer.setValidatorFactory(validatorFactory);
importer.setExamPaperService(service);
importer.setCategoryService(categoryService);
importer.setTermService(termService);
importer.setPaperFileService(new LocalPaperFileServiceImpl());
import1 = importer.newImport();
}
@Test
public void testImporter() throws IOException {
InputStream paperInput = getClass().getResourceAsStream("/Papercodes.xlsx");
import1.readPapers(paperInput, Format.XLSX);
InputStream examInput = getClass().getResourceAsStream("/Examcodes.xlsx");
import1.readExams(examInput, Format.XLSX);
InputStream examPaperInput = getClass().getResourceAsStream("/ExamPapersMerged.xlsx");
import1.readExamPapers(examPaperInput, Format.XLSX);
PaperResolver resolver = new ZipPaperResolver(getClass().getResource("/papers.zip").getFile(), "papers", termService, "pdf");
import1.setPaperResolver(resolver);
import1.resolve();
for (ErrorMessages<ExamPaperRow> voilation :import1.getExamPaperRowErrors().values()) {
System.out.println(voilation);
}
System.out.println("Count: "+ import1.getExamPaperRows().size());
}
}
| 32.538462 | 127 | 0.792356 |
ba5844f4ae522881061c1a7a543ea7aafa8a8fa9 | 305 | package com.instrumentalapp;
import org.junit.*;
import java.io.*;
import java.util.Scanner;
public class NoticeTest {
@Test
public void messageValidity() {
Assert.assertTrue(new Notice("hello world", 1, 1).isValid());
Assert.assertFalse(new Notice("hello\nworld", 1, 1).isValid());
}
}
| 19.0625 | 67 | 0.695082 |
6dea4ac1b2edfcfee23e5786e6fb5929d20ca909 | 801 | package net.sf.esfinge.metadata.examples.metadataLocator.simple;
import static org.junit.Assert.*;
import java.lang.annotation.Annotation;
import java.util.List;
import org.junit.Test;
import net.sf.esfinge.metadata.AnnotationFinder;
public class MetadataLocatorTest {
@Test
public void metadataLocatorTestWithAnnotation() {
List<Annotation> annotationList = AnnotationFinder.findAnnotation(ElementWithMetadata.class, AnnotationInElement.class);
assertTrue(annotationList.size()>0);
assertTrue(annotationList.get(0) instanceof AnnotationInElement);
}
@Test
public void metadataLocatorTestWithoutAnnotation() {
List<Annotation> annotationList = AnnotationFinder.findAnnotation(ElementWithoutMetadata.class, AnnotationInElement.class);
assertTrue(annotationList.isEmpty());
}
}
| 27.62069 | 125 | 0.815231 |
fbb8c05df9f9541f237b589c7583e958d250d676 | 1,330 | /*
fazer um programa que leia um valor qualquer
e apresente uma mensagem dizendo em qual dos seguintes intervalos
([0,25], (25,50], (50,75], (75,100])
este valor se encontra.
Se o valor não estiver em nenhum destes intervalos,
deverá ser impressa a mensagem “Fora de intervalo”.
O símbolo ( representa "maior que". Por exemplo:
[0,25] indica valores entre 0 e 25.0000, inclusive eles.
(25,50] indica valores maiores que 25 Ex: 25.00001 até o valor 50.0000000
Exemplo de entrada:
100.00
Exemplo de saída:
Intervalo (75,100]
*/
import java.util.Scanner;
public class Intervalo_1037 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double valor = sc.nextDouble();
String intervalo = "Fora de intervalo";
if (valor >= 0 && valor<= 25){
intervalo = "Intervalo [0,25]";
} else {
if (valor > 25 && valor <= 50){
intervalo = "Intervalo (25,50]";
} else {
if (valor > 50 && valor <= 75){
intervalo = "Intervalo (50,75]";
} else {
if (valor > 75 && valor <= 100){
intervalo = "Intervalo (75,100]";
}
}
}
}
System.out.println(intervalo);
}
}
| 28.913043 | 73 | 0.555639 |
d4b573a46bc1b5ff9a3c9b889d7012eb8f9d0ffb | 597 | import org.hamcrest.core.Is;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.huawei.demo4mt.PojoConsumer;
import com.huawei.demo4mt.TestMgr;
/**
* 一句话功能简述
* 功能详细描述
* @author m00416667
* @version [版本号, ]
* @see [相关类/方法]
* @since [产品/模块版本]
* Package Name:PACKAGE_NAME
*/
public class PojoIT {
@Before
public void setUp(){
TestMgr.errors().clear();
}
@Test
public void pojoTestEntry() throws Exception {
PojoConsumer.main(new String[0]);
Assert.assertThat(TestMgr.errors().isEmpty(), Is.is(true));
}
}
| 18.65625 | 67 | 0.656616 |
623f223ab62f5c71fd77a00ad6317c1cd6176418 | 3,859 | package br.com.zupacademy.ratkovski.proposta.controller;
import br.com.zupacademy.ratkovski.proposta.dto.CarteiraRequestFeingDto;
import br.com.zupacademy.ratkovski.proposta.dto.CarteiraResquestDto;
import br.com.zupacademy.ratkovski.proposta.feing.ApiCartaoFeing;
import br.com.zupacademy.ratkovski.proposta.modelo.Cartao;
import br.com.zupacademy.ratkovski.proposta.modelo.Carteira;
import br.com.zupacademy.ratkovski.proposta.modelo.StatusCartao;
import br.com.zupacademy.ratkovski.proposta.modelo.TipoCarteira;
import br.com.zupacademy.ratkovski.proposta.repository.CartaoRepository;
import br.com.zupacademy.ratkovski.proposta.repository.CarteiraRepository;
import feign.FeignException;
import io.opentracing.Span;
import io.opentracing.Tracer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.util.UriComponentsBuilder;
import javax.validation.Valid;
import java.net.URI;
import java.util.Optional;
@RestController
public class CarteiraController {
@Autowired
private CarteiraRepository carteiraRepository;
@Autowired
private CartaoRepository cartaoRepository;
@Autowired
private ApiCartaoFeing apiCartaoFeing;
@Autowired
private Tracer tracer;
@PostMapping("/cartoes/{uuid}/carteiras")
public ResponseEntity<?> cadcarteira(@PathVariable("uuid") String uuid,
@RequestBody @Valid CarteiraResquestDto request, UriComponentsBuilder builder) {
Span activeSpan = tracer.activeSpan();
String userEmail = activeSpan.getBaggageItem("user.email");
activeSpan.setBaggageItem("user.email", userEmail);
Optional<Cartao> cartaoExist = cartaoRepository.findByUuid(uuid);
if (cartaoExist.isEmpty()) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Este cartão não existe no sistema");
}
Cartao cartao = cartaoExist.get();
/*preciso melhorar isso*/
if (cartaoExist.equals(TipoCarteira.PAYPAL)) {
throw new ResponseStatusException(HttpStatus.UNPROCESSABLE_ENTITY, "Este cartão já esta associado a está carteira");
}
if (cartaoExist.equals(TipoCarteira.SAMSUNG_PAY)) {
throw new ResponseStatusException(HttpStatus.UNPROCESSABLE_ENTITY, "Este cartão já esta associado a está carteira");
}
if (cartaoExist.equals(StatusCartao.BLOQUEADO)) {
throw new ResponseStatusException(HttpStatus.UNPROCESSABLE_ENTITY, "O cartão já está bloqueado");
}
Carteira carteira = request.toModel(cartao);
Optional<Carteira> carteiraExist = carteiraRepository.findByCarteiraAndCartaoId(carteira.getCarteira(), carteira.getCartao().getId());
if (carteiraExist.isPresent()) {
return ResponseEntity.unprocessableEntity().build();
}
CarteiraRequestFeingDto requestFeingDto = new CarteiraRequestFeingDto(cartao.getId(),carteira.getCarteira().toString());
try{
apiCartaoFeing.addcarteira(cartao.getId(), requestFeingDto);
carteiraRepository.save(carteira);
}catch (FeignException ex){
// System.out.println(ex);
return ResponseEntity.unprocessableEntity().build();
}
URI path = builder.path("/cartoes/{uuid}/carteiras/{id}").build(cartao.getUuid(),carteira.getCartao().getId());
return ResponseEntity.created(path).build();
}
}
| 38.979798 | 142 | 0.740347 |
57d77486b26c066b6c82e20c9dfcef57fd90bfcb | 3,632 | package com.keenant.dhub.zwave.transaction;
import com.keenant.dhub.zwave.Controller;
import com.keenant.dhub.zwave.InboundMessage;
import com.keenant.dhub.zwave.UnknownMessage;
import com.keenant.dhub.zwave.frame.Frame;
import com.keenant.dhub.zwave.frame.Status;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.concurrent.TimeUnit;
public abstract class Transaction {
private final Controller controller;
private final Queue<Frame> outbound;
private long queuedTimeNanos;
private long startTimeNanos;
private long completionTimeNanos;
public Transaction(Controller controller) {
this.controller = controller;
this.outbound = new ArrayDeque<>();
}
public abstract void start();
public abstract boolean isComplete();
public abstract InboundMessage handle(UnknownMessage msg);
public abstract void handle(Status status);
public boolean isStarted() {
return startTimeNanos > 0;
}
public Transaction await() {
await(-1);
return this;
}
public Transaction await(int timeout) {
long start = System.currentTimeMillis();
while (!isComplete()) {
long now = System.currentTimeMillis();
if (!controller.isAlive()) {
return this;
}
if (timeout > 0 && now - start > timeout) {
return this;
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
}
return this;
}
public boolean isTimeout() {
long timeout = 5000;
return isStarted() && millisAlive() > timeout;
}
/**
* @return The time in nanoseconds from when the transaction started to when it ended.
* If it is in progress, it is the time up until present time.
* @throws UnsupportedOperationException If the transaction hasn't started.
*/
public long nanosAlive() throws UnsupportedOperationException {
if (!isStarted()) {
throw new UnsupportedOperationException("Transaction has not started yet.");
}
long end = getCompletionTimeNanos();
if (getCompletionTimeNanos() <= 0) {
end = System.nanoTime();
}
return end - startTimeNanos;
}
/**
* @return The time in milliseconds from when the transaction started to when it ended.
* If it is in progress, it is the time up until present time.
* @throws UnsupportedOperationException If the transaction hasn't started.
*/
public long millisAlive() throws UnsupportedOperationException {
long nanos = nanosAlive();
return TimeUnit.MILLISECONDS.convert(nanos, TimeUnit.NANOSECONDS);
}
protected void addToOutboundQueue(Frame frame) {
outbound.add(frame);
}
public Queue<Frame> getOutboundQueue() {
return outbound;
}
public Controller getController() {
return controller;
}
public long getCompletionTimeNanos() {
return completionTimeNanos;
}
public long getStartTimeNanos() {
return startTimeNanos;
}
public long getQueuedTimeNanos() {
return queuedTimeNanos;
}
public void setCompletionTimeNanos(long completionTimeNanos) {
this.completionTimeNanos = completionTimeNanos;
}
public void setStartTimeNanos(long startTimeNanos) {
this.startTimeNanos = startTimeNanos;
}
public void setQueuedTimeNanos(long queuedTimeNanos) {
this.queuedTimeNanos = queuedTimeNanos;
}
}
| 26.510949 | 91 | 0.643447 |
b07bbb87e274ef7f7cfe0b21c68dea196a7b8c70 | 1,129 | package com.hzmct.silentinstall.permission;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
/**
* @author Woong on 2020/5/28
* @website http://woong.cn
*/
public class PermissionActivity extends AppCompatActivity {
private static final String TAG = "PermissionActivity";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Log.i(TAG, "start to generate permission");
requestPermissions(PermissionUtil.permissionArray, 10086);
} else {
Log.i(TAG, "target sdk is low, already has permission");
finish();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
finish();
}
}
| 31.361111 | 121 | 0.703277 |
d60421f1dc32a33a52ddddd2475787fd97bf6a15 | 1,409 | package com.company.superKeyword;
class Animal
{
String color = "white";
Animal()
{//noparameter constructor in Animal class
System.out.println("animal constructor");
}
void print()
{
System.out.println("\ncall animal class method");
System.out.println(color);
System.out.println(this.color);
}
}
class Dog extends Animal
{
String color = "Black";
Dog(String name)
{//parameterized constructor in Dog class
this();//here we have this(). then java compiler doesn't add a super()
//one constructor can not have both super() and this()
//if have super() or this(), it's must be the first argument of the method
System.out.println("dog constructor " + name + '\n');
}
Dog()
{//noparameter constructor in Dog class
//if there is no any super() or this() in constructor ,java compiler automatically add the super()
System.out.println("dog constructor\n");
}
@Override
void print()
{
System.out.println("call dog class method");
System.out.println(color);
System.out.println(this.color);
System.out.println(super.color);//super can be used to refer parent class variable
super.print();//super can be used to call parent class method
}
}
public class TestSuperKeyword
{
public static void main(String[] args)
{
System.out.println("start here..");
Dog dog = new Dog("dog name");
dog.print();
}
}
| 24.293103 | 102 | 0.669269 |
c8da40982da67687a148b59a7d5ef26391205780 | 2,882 | package ecda.test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import coopy.Csv;
import coopy.JavaTableView;
import coopy.Table;
public class FileChecker
{
private static final String FOLDER = "./files/zamg/";
// private static final String FOLDER = "./files/daff/";
public static void main(String[] args) throws IOException
{
File folder = new File(FOLDER);
File[] listOfFiles = folder.listFiles();
ArrayList<ArrayList<String>> totalList = new ArrayList<ArrayList<String>>();
for (int i = 0; i < listOfFiles.length - 1; i++)
{
File file1 = listOfFiles[i];
File file2 = listOfFiles[i + 1];
Table table1 = getTable(FOLDER + file1.getName());
Table table2 = getTable(FOLDER + file2.getName());
Table table3 = getComparison(table1, table2);
// System.out.println(Size of table 1);
storeCSV(table3, "./files/daff/" + file1.getName() + "_" + file2.getName());
ArrayList<String> headers = new ArrayList<String>();
for (int j = 0; j < table3.get_width(); j++)
{
if (table3.getCell(0, 0) == "!")
{
}
headers.add((String) table3.getCell(0, j));
}
totalList.add(headers);
}
for (int i = 0; i < totalList.size(); i++)
{
ArrayList<String> arrayList = totalList.get(i);
if (arrayList.get(0) == "!")
{
for (String string : arrayList)
{
}
// /System.out.println("Change of header in " + listOfFiles[i]);
}
}
}
private static void storeCSV(Table table3, String string) throws IOException
{
Csv csv = new Csv(";", null);
String output = csv.renderTable(table3);
PrintWriter pr = new PrintWriter(new FileWriter(new File(string), false));
// String arr[] = output.split("\\n");
pr.print(output);
pr.close();
}
public static Table getComparison(Table table1, Table table2)
{
coopy.Alignment alignment = coopy.Coopy.compareTables(table1, table2, null).align();
// System.out.println(table1.get_height() + " " + alignment.count());
JavaTableView table_diff = new JavaTableView();
coopy.CompareFlags flags = new coopy.CompareFlags();
flags.show_unchanged = true;
flags.show_unchanged_columns = true;
coopy.TableDiff highlighter = new coopy.TableDiff(alignment, flags);
highlighter.hilite(table_diff);
return table_diff;
}
public static Table getTable(String string) throws IOException
{
// TODO Auto-generated method stub
Csv csv = new Csv(";", null);
BufferedReader reader = new BufferedReader(new FileReader(string));
// read file line by line
String line = null;
String output = "";
while ((line = reader.readLine()) != null)
{
// System.out.println(line);
output = output + line + "\n";
}
// close reader
reader.close();
return csv.makeTable(output);
}
}
| 24.218487 | 86 | 0.671062 |
abe562032d794df5941e6442e897627b4df2056b | 434 | package com.lillicoder.algorithms.search;
import java.util.List;
interface Search {
/**
* Searches the given {@link List} for the given element.
* @param list List to search.
* @param toFind Element to find.
* @param <T> Type of element.
* @return Position of element or {@code -1} if no such element could be found.
*/
<T> int search(List<? extends Comparable<? super T>> list, T toFind);
}
| 25.529412 | 83 | 0.645161 |
ff54f96846fa2f8793a743c587b34c75643c4feb | 3,539 | package org.hf.mls.ar.hadoop;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import java.io.IOException;
/**
* Created by He Fan on 2014/4/9.
*/
public class PreProcessJob extends Configured implements Tool {
public static long runJob(String[] args) throws Exception {
return ToolRunner.run(new Configuration(), new PreProcessJob(), args);
}
@Override
public int run(String[] args) throws Exception {
Configuration conf = new Configuration();
conf.setInt("userIdPosition", Integer.parseInt(args[2]));
conf.setInt("itemIdPosition", Integer.parseInt(args[3]));
conf.setStrings("splitChar", args[4]);
Job job = new Job(conf, "AR_Data pre_" + args[5]);
job.setJarByClass(PreProcessJob.class);
FileInputFormat.setInputPaths(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
job.setMapperClass(DataMapper.class);
job.setReducerClass(DataReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
boolean success = job.waitForCompletion(true);
if (success) {
return 1;
} else {
return 0;
}
}
public static class DataMapper extends Mapper<LongWritable, Text, Text, Text> {
@Override
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
Configuration mapConf = context.getConfiguration();
String splitChar = mapConf.getStrings("splitChar", "-1")[0];
int userIdPosition = mapConf.getInt("userIdPosition", -1);
int itemIdPosition = mapConf.getInt("itemIdPosition", -1);
if (-1 == userIdPosition || -1 == itemIdPosition || "-1".equals(splitChar)) {
System.out.println("[ERROR]UserId/ItemId position or split char lost!");
return;
}
String[] fields = value.toString().split(splitChar);
if (fields.length > 1) {
String userId = fields[userIdPosition];
String itemId = fields[itemIdPosition];
context.write(new Text(userId), new Text(itemId));
}
}
}
public static class DataReducer extends Reducer<Text, Text, Text, Text> {
//fpg default split char is '\t'
public static final String str_split = "\t";
@Override
public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
StringBuilder newKey = new StringBuilder("");
//将同一个user下的item放入一个队列中
for (Text value : values) {
if (!"".equals(value.toString())) {
if (0 != newKey.length()) {
newKey.append(str_split);
}
newKey.append(value.toString());
}
}
context.write(new Text(newKey.toString()), new Text(""));
}
}
}
| 35.39 | 119 | 0.6256 |
297a27901bbe2a2fcbc5c1f0c3fbc67c8b609cb7 | 135 | package com.javaedge.design.pattern.structural.adapter;
/**
* Created by JavaEdge
*/
public interface DC5 {
int outputDC5V();
}
| 15 | 55 | 0.711111 |
9b912eb24c2d5b49bb031f1cdcd0e9c273ac760f | 5,125 | package main;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import tools.FileManager;
import latentTAN.mergeModels;
/**
*
* @author Arturo Lopez Pineda <arl68@pitt.edu>
* Date: June 29, 2015
*/
public class argumentHandler {
public static ArrayList<String> models = new ArrayList<String>();
public static Boolean em = false;
public static String train = "";
public static String target = "class";
public static String type = "independent";
public static String outputFile = "";
//public static String lib = "";
public static void showInfo(){
System.out.println("Expected commands format: -networks model1.xdsl model2.xdsl [-type independent] [model3.xdsl ...] [-train train.arff] [-target class] [-outputFile merged.xdsl]");
System.out.println("-networks file1 file2.\t At least 2 XDSL or NET files that will be merged. Must have a common target variable");
System.out.println("-type [independent|threeway|cascade]\tThe type of merging that is seeked. Default is independent (naïve)");
System.out.println("-train train.arff.\t The training data file that will be used to estimate the parameters of the latent variables with EM. Default: no estimation.");
System.out.println("-target class.\tThe name of the target variable that is in common between all models. Default: class");
System.out.println("-outputFile merged.xdsl\tThe name of the output file. Default: merged.xdsl in the location of the first model");
//System.out.println("-lib libjsmile.jnilib\tThe SMILE library. It should be specific to your Operating System. You can download it from: https://dslpitt.org/genie/");
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
if((args.length < 3)){
System.out.println("Insuficient arguments.");
showInfo();
System.exit(1);
}
//Capture all arguments and check for consistency in their numbers
for(int i = 0; i < args.length; i++){
if(args[i].equalsIgnoreCase("-networks")){
if(i+1 < args.length){
int j= i+1;
while(j < args.length){
if(args[j].startsWith("-")){
break;
}
else{
models.add(args[j]);
}
j++;
}
if(models.size() < 2){
System.out.println("-- Please provide annother argument to (only one network given) -networks");
showInfo();
System.exit(1);
}
}
else{
System.out.println("-- No arguments provided for -networks");
showInfo();
System.exit(1);
}
}
else if(args[i].equalsIgnoreCase("-type")){
if(i+1 < args.length){
if(type.equalsIgnoreCase("independent") || type.equalsIgnoreCase("threeway") || type.equalsIgnoreCase("cascade")){
type = args[i+1];
}
else{
System.out.println("-- The argument provided for -type is not a valid option: choose between: [independent | threeway | cascade]");
showInfo();
System.exit(1);
}
}
else{
System.out.println("-- No argumnet provided for -type");
showInfo();
System.exit(1);
}
}
else if(args[i].equalsIgnoreCase("-train")){
if(i+1 < args.length){
train = args[i+1];
em = true;
}
else{
System.out.println("-- No argument provided for -train");
showInfo();
System.exit(1);
}
}
else if(args[i].equalsIgnoreCase("-target")){
if(i+1 < args.length){
target = args[i+1];
}
else{
System.out.println("-- No argument provided for -target");
showInfo();
System.exit(1);
}
}
else if(args[i].equalsIgnoreCase("-outputFile")){
if(i+1 < args.length){
outputFile = args[i+1];
}
else{
System.out.println("-- No argument provided for -outputFile");
showInfo();
System.exit(1);
}
}
/*else if(args[i].equalsIgnoreCase("-lib")){
if(i+1 < args.length){
lib = args[i+1];
}
else{
System.out.println("-- No argument provided for -lib");
showInfo();
System.exit(1);
}
}*/
}
//System.out.println("outputFile: "+outputFile);
if(outputFile.equals("")){
FileManager fm = new FileManager();
String extension = fm.getExtension(models.get(0));
String path = fm.stripPath(models.get(0));
outputFile = path+"/merged-"+type+extension;
}
//System.out.println("out: "+outputFile);
//Load SMILE library
/* This code didn't work. Instead, I copied the jnilib file to:
* /System/Library/Java/Extensions
*
try {
File jnilib = new File(lib);
System.out.println("path: "+System.getProperty("java.library.path"));
System.out.println("Lib Path: "+jnilib.getAbsolutePath());
System.load(jnilib.getAbsolutePath());
} catch (UnsatisfiedLinkError e) {
System.err.println("Native code library failed to load.\n" + e);
System.exit(1);
}*/
//Runner
mergeModels merge = new mergeModels();
merge.runner(models.toArray(new String[models.size()]), outputFile, type, train, target);
//Finalize
System.out.println("outputFile: "+outputFile);
if(em == false){
System.out.println("EM was not used");
}
System.out.println("----\n");
}
}
| 29.454023 | 184 | 0.641951 |
5c1806b0b72bd67893e48253fda9b7bbd48657bb | 2,663 | package masssh.boilerplate.spring.spa.dao;
import masssh.boilerplate.spring.spa.dao.annotation.DaoTest;
import masssh.boilerplate.spring.spa.enums.VerificationType;
import masssh.boilerplate.spring.spa.model.row.UserRow;
import masssh.boilerplate.spring.spa.model.row.VerificationRow;
import masssh.boilerplate.spring.spa.testutil.factory.UserFactory;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.sql.SQLIntegrityConstraintViolationException;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import static org.assertj.core.api.Assertions.assertThat;
@DaoTest
class VerificationDaoTest {
@Autowired
private VerificationDao verificationDao;
@Autowired
private UserFactory userFactory;
@Test
void crud() throws SQLIntegrityConstraintViolationException {
final Instant now = Instant.now().truncatedTo(ChronoUnit.SECONDS);
final UserRow userRow1 = userFactory.builder().create();
final VerificationRow before = new VerificationRow(0, "verificationHash", userRow1.getUserId(), VerificationType.EMAIL, false, now, now);
verificationDao.create(before);
final long verificationId = before.getVerificationId();
VerificationRow inserted = verificationDao.single(verificationId).orElseThrow(AssertionError::new);
assertThat(inserted.getVerificationId()).isEqualTo(verificationId);
assertThat(inserted.getVerificationHash()).isEqualTo("verificationHash");
assertThat(inserted.getUserId()).isEqualTo(userRow1.getUserId());
assertThat(inserted.getVerificationType()).isEqualTo(VerificationType.EMAIL);
assertThat(inserted.isExpired()).isFalse();
assertThat(inserted.getCreatedAt()).isAfterOrEqualTo(before.getCreatedAt());
assertThat(inserted.getUpdatedAt()).isAfterOrEqualTo(before.getUpdatedAt());
final UserRow userRow2 = userFactory.builder().create();
inserted.setVerificationType(VerificationType.PASSWORD);
inserted.setExpired(true);
verificationDao.update(inserted);
final VerificationRow updated = verificationDao.single(verificationId).orElseThrow(AssertionError::new);
assertThat(updated.getVerificationType()).isEqualTo(VerificationType.PASSWORD);
assertThat(updated.isExpired()).isTrue();
assertThat(updated.getCreatedAt()).isEqualTo(inserted.getCreatedAt());
assertThat(updated.getUpdatedAt()).isAfterOrEqualTo(inserted.getUpdatedAt());
verificationDao.delete(updated.getVerificationId());
assertThat(verificationDao.single(verificationId)).isEmpty();
}
}
| 48.418182 | 145 | 0.764927 |
d06dd27743589c891aff679e7940ec51e7c4ee67 | 24,068 | package com.sanbot.capaBot;
import android.content.Intent;
import android.graphics.RectF;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.alamkanak.weekview.DateTimeInterpreter;
import com.alamkanak.weekview.MonthLoader;
import com.alamkanak.weekview.WeekView;
import com.alamkanak.weekview.WeekViewEvent;
import com.sanbot.opensdk.base.TopBaseActivity;
import com.sanbot.opensdk.beans.FuncConstant;
import com.sanbot.opensdk.function.beans.EmotionsType;
import com.sanbot.opensdk.function.beans.speech.Grammar;
import com.sanbot.opensdk.function.beans.speech.RecognizeTextBean;
import com.sanbot.opensdk.function.unit.SpeechManager;
import com.sanbot.opensdk.function.unit.SystemManager;
import com.sanbot.opensdk.function.unit.interfaces.speech.RecognizeListener;
import com.sanbot.opensdk.function.unit.interfaces.speech.WakenListener;
import net.fortuna.ical4j.model.Calendar;
import net.fortuna.ical4j.model.Component;
import net.fortuna.ical4j.model.Property;
import net.fortuna.ical4j.util.MapTimeZoneCache;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import butterknife.BindView;
import butterknife.ButterKnife;
import static com.sanbot.capaBot.MyUtils.concludeSpeak;
import static com.sanbot.capaBot.MyWeatherActivity.isNetworkAvailable;
public class MyCalendarActivity extends TopBaseActivity implements MyCalendarDownloadAsyncTask.AsyncTaskListener{
private final static String TAG = "IGOR-CAL";
@BindView(R.id.exit)
Button exitButton;
@BindView(R.id.today)
Button todayButton;
@BindView(R.id.weekView)
WeekView mWeekView;
@BindView(R.id.loader_cal)
ProgressBar loader_cal;
@BindView(R.id.text_loader_cal)
TextView text_loader_cal;
private SpeechManager speechManager; //voice, speechRec
private SystemManager systemManager; //emotions
//calendars to show
String[] urlsCalendar = {
"https://ics.teamup.com/feed/ksdxka67t86rufdom3/0.ics",
/* "https://calendar.google.com/calendar/ical/it.portuguese%23holiday%40group.v.calendar.google.com/public/basic.ics"*/
};
private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyyMMdd", Locale.ITALY);
private static final SimpleDateFormat SDFH = new SimpleDateFormat("yyyyMMdd'T'HHmmss", Locale.ITALY);
String lastRecognizedSentence = "";
boolean infiniteWakeup = true;
boolean shortDate = false;
int finishedThreadsCount = 0;
List<WeekViewEvent> events = new ArrayList<WeekViewEvent>();
@Override
protected void onCreate(Bundle savedInstanceState) {
register(MyCalendarActivity.class);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendar);
ButterKnife.bind(this);
//initialize managers
speechManager = (SpeechManager) getUnitManager(FuncConstant.SPEECH_MANAGER);
systemManager = (SystemManager) getUnitManager(FuncConstant.SYSTEM_MANAGER);
//for the iCal4J
System.setProperty("net.fortuna.ical4j.timezone.cache.impl", MapTimeZoneCache.class.getName());
//view
exitButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
goToDialogAndExit(true);
}
});
todayButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mWeekView.goToToday();
}
});
mWeekView.setVisibility(View.GONE);
text_loader_cal.setText("Loading 1/" + urlsCalendar.length );
//robot listeners
initListeners();
//load the task to download the calendars
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
taskLoadUp();
}
}, 100);
//fill with fake events to test
//events = getFakeEvents(2019, 7);
MonthLoader.MonthChangeListener mMonthChangeListener = new MonthLoader.MonthChangeListener() {
@Override
public List<WeekViewEvent> onMonthChange(int newYear, int newMonth) {
Log.i(TAG, "onMonthChange called "+newMonth+" "+newYear);/*
ArrayList<WeekViewEvent> eventsMonth = new ArrayList<WeekViewEvent>();
//put in the list only the events of the month required
for (int i = 0; i < events.size(); i++) {
if (events.get(i).getStartTime().get(java.util.Calendar.MONTH) == newMonth) {
eventsMonth.add(events.get(i));
}
if ((events.get(i).getStartTime().get(java.util.Calendar.MONTH)-1) == newMonth) {
eventsMonth.add(events.get(i));
}
}*/
//todo test
java.util.Calendar today = java.util.Calendar.getInstance();
today.setTime(new Date());
if(today.get(java.util.Calendar.MONTH) != newMonth)
return new ArrayList<>();
return events;
}
};
// The week view has infinite scrolling horizontally. We have to provide the events of a
// month every time the month changes on the week view.
mWeekView.setMonthChangeListener(mMonthChangeListener);
// Show a toast message about the touched event.
mWeekView.setOnEventClickListener(new WeekView.EventClickListener() {
@Override
public void onEventClick(WeekViewEvent event, RectF eventRect) {
Toast.makeText(MyCalendarActivity.this, "Clicked " + event.getName(), Toast.LENGTH_SHORT).show();
speechManager.startSpeak(event.getName()+ " starts at " + getTimeString(event.getStartTime()), MySettings.getSpeakDefaultOption());
}
});
// Set long press listener for events.
mWeekView.setEventLongPressListener(new WeekView.EventLongPressListener() {
@Override
public void onEventLongPress(WeekViewEvent event, RectF eventRect) {
Toast.makeText(MyCalendarActivity.this, "Long pressed event: " + event.getName(), Toast.LENGTH_SHORT).show();
}
});
// Set long press listener for empty view
mWeekView.setEmptyViewLongPressListener(new WeekView.EmptyViewLongPressListener() {
@Override
public void onEmptyViewLongPress(java.util.Calendar time) {
Toast.makeText(MyCalendarActivity.this, "Empty view long-pressed: " + getTimeString(time), Toast.LENGTH_SHORT).show();
speechManager.startSpeak("there is nothing on " + getTimeString(time) , MySettings.getSpeakDefaultOption());
}
});
mWeekView.setEmptyViewClickListener(new WeekView.EmptyViewClickListener() {
@Override
public void onEmptyViewClicked(java.util.Calendar time) {
Toast.makeText(MyCalendarActivity.this, "Empty view clicked: " + getTimeString(time), Toast.LENGTH_SHORT).show();
}
});
mWeekView.setDateTimeInterpreter(new DateTimeInterpreter() {
@Override
public String interpretDate(java.util.Calendar date) {
//week day
SimpleDateFormat weekdayNameFormat = new SimpleDateFormat("EEE", Locale.getDefault());
String weekday = weekdayNameFormat.format(date.getTime());
//format date
SimpleDateFormat format = new SimpleDateFormat(" d/M", Locale.getDefault());
if (shortDate)
weekday = String.valueOf(weekday.charAt(0));
//united strings
return weekday.toUpperCase() + format.format(date.getTime());
}
@Override
public String interpretTime(int hour) {
return hour > 11 ? (hour - 12) + " PM" : (hour == 0 ? "12 AM" : hour + " AM");
}
});
//end onCreate()
}
protected String getTimeString(java.util.Calendar time) {
return String.format("%02d:%02d of %d/%s", time.get(java.util.Calendar.HOUR_OF_DAY), time.get(java.util.Calendar.MINUTE), time.get(java.util.Calendar.DAY_OF_MONTH), time.get(java.util.Calendar.MONTH)+1);
}
private List<WeekViewEvent> getFakeEvents(int newYear, int newMonth) {
// Populate the week view with some events.
List<WeekViewEvent> events = new ArrayList<WeekViewEvent>();
java.util.Calendar startTime = java.util.Calendar.getInstance();
startTime.set(java.util.Calendar.HOUR_OF_DAY, 3);
startTime.set(java.util.Calendar.MINUTE, 0);
startTime.set(java.util.Calendar.MONTH, newMonth-1);
startTime.set(java.util.Calendar.YEAR, newYear);
java.util.Calendar endTime = (java.util.Calendar) startTime.clone();
endTime.add(java.util.Calendar.HOUR, 1);
endTime.set(java.util.Calendar.MONTH, newMonth-1);
WeekViewEvent event = new WeekViewEvent(1, "demo-event 1", startTime, endTime);
event.setColor(getResources().getColor(R.color.colorPrimary, null));
events.add(event);
startTime = java.util.Calendar.getInstance();
startTime.set(java.util.Calendar.HOUR_OF_DAY, 3);
startTime.set(java.util.Calendar.MINUTE, 30);
startTime.set(java.util.Calendar.MONTH, newMonth-1);
startTime.set(java.util.Calendar.YEAR, newYear);
endTime = (java.util.Calendar) startTime.clone();
endTime.set(java.util.Calendar.HOUR_OF_DAY, 4);
endTime.set(java.util.Calendar.MINUTE, 30);
endTime.set(java.util.Calendar.MONTH, newMonth-1);
event = new WeekViewEvent(10, "demo-event 2", startTime, endTime);
events.add(event);
startTime = java.util.Calendar.getInstance();
startTime.set(java.util.Calendar.HOUR_OF_DAY, 4);
startTime.set(java.util.Calendar.MINUTE, 20);
startTime.set(java.util.Calendar.MONTH, newMonth-1);
startTime.set(java.util.Calendar.YEAR, newYear);
endTime = (java.util.Calendar) startTime.clone();
endTime.set(java.util.Calendar.HOUR_OF_DAY, 5);
endTime.set(java.util.Calendar.MINUTE, 0);
event = new WeekViewEvent(10, "demo-event 3", startTime, endTime);
events.add(event);
startTime = java.util.Calendar.getInstance();
startTime.set(java.util.Calendar.HOUR_OF_DAY, 5);
startTime.set(java.util.Calendar.MINUTE, 30);
startTime.set(java.util.Calendar.MONTH, newMonth-1);
startTime.set(java.util.Calendar.YEAR, newYear);
endTime = (java.util.Calendar) startTime.clone();
endTime.add(java.util.Calendar.HOUR_OF_DAY, 2);
endTime.set(java.util.Calendar.MONTH, newMonth-1);
event = new WeekViewEvent(2, "demo-event 4", startTime, endTime);
events.add(event);
startTime = java.util.Calendar.getInstance();
startTime.set(java.util.Calendar.HOUR_OF_DAY, 5);
startTime.set(java.util.Calendar.MINUTE, 0);
startTime.set(java.util.Calendar.MONTH, newMonth-1);
startTime.set(java.util.Calendar.YEAR, newYear);
startTime.add(java.util.Calendar.DATE, 1);
endTime = (java.util.Calendar) startTime.clone();
endTime.add(java.util.Calendar.HOUR_OF_DAY, 3);
endTime.set(java.util.Calendar.MONTH, newMonth - 1);
event = new WeekViewEvent(3, "demo-event 5", startTime, endTime);
events.add(event);
return events;
}
@Override
protected void onMainServiceConnected() {}
void initListeners() {
//Set wakeup, sleep callback
speechManager.setOnSpeechListener(new WakenListener() {
@Override
public void onWakeUpStatus(boolean b) {
}
@Override
public void onWakeUp() {
//Log.i(TAG, "WAKE UP callback");
}
@Override
public void onSleep() {
//Log.i(TAG, "SLEEP callback");
if (infiniteWakeup) {
//recalling wake up to stay awake (not wake-Up-Listening() that resets the Handler)
speechManager.doWakeUp();
}
}
});
//voice listener
speechManager.setOnSpeechListener(new RecognizeListener() {
@Override
public void onRecognizeText(@NonNull RecognizeTextBean recognizeTextBean) {
}
@Override
public boolean onRecognizeResult(@NonNull Grammar grammar) {
lastRecognizedSentence = Objects.requireNonNull(grammar.getText()).toLowerCase();
new Handler().post(new Runnable() {
@Override
public void run() {
if (lastRecognizedSentence.contains("today") ) {
speechManager.startSpeak("These are the events of today", MySettings.getSpeakDefaultOption());
systemManager.showEmotion(EmotionsType.SMILE);
mWeekView.goToToday();
}
if (lastRecognizedSentence.contains("ok") ||lastRecognizedSentence.contains("yes") ||lastRecognizedSentence.contains("i am")||lastRecognizedSentence.contains("we are")
||lastRecognizedSentence.contains("sure") ||lastRecognizedSentence.contains("of course") ||lastRecognizedSentence.contains("thank")) {
if (lastRecognizedSentence.contains("thank")) {
//thanks
speechManager.startSpeak("thank you", MySettings.getSpeakDefaultOption());
concludeSpeak(speechManager);
}
//happy
systemManager.showEmotion(EmotionsType.KISS);
speechManager.startSpeak("I'm happy to hear about it", MySettings.getSpeakDefaultOption());
boolean res = concludeSpeak(speechManager);
//finish
goToDialogAndExit(res);
}
if (lastRecognizedSentence.equals("no") ||lastRecognizedSentence.contains("so and so") ) {
//sad
speechManager.startSpeak("I'm sad to hear this", MySettings.getSpeakDefaultOption());
systemManager.showEmotion(EmotionsType.GOODBYE);
boolean res = concludeSpeak(speechManager);
//finish
goToDialogAndExit(res);
}
if (lastRecognizedSentence.contains("exit") ) {
speechManager.startSpeak("OK", MySettings.getSpeakDefaultOption());
systemManager.showEmotion(EmotionsType.SMILE);
boolean res = concludeSpeak(speechManager);
//finish
goToDialogAndExit(res);
}
}
});
return true;
}
@Override
public void onRecognizeVolume(int i) {
}
@Override
public void onStartRecognize() {
}
@Override
public void onStopRecognize() {
}
@Override
public void onError(int i, int i1) {
}
});
}
public void taskLoadUp() {
if (isNetworkAvailable(getApplicationContext())) {
Log.i(TAG, "network ok");
//for every url
for (String anUrlsCalendar : urlsCalendar) {
//launch a task
MyCalendarDownloadAsyncTask task = new MyCalendarDownloadAsyncTask(this);
task.execute(anUrlsCalendar);
}
} else {
Toast.makeText(this, "No Internet Connection", Toast.LENGTH_LONG).show();
}
}
@Override
public void giveCalendar(Calendar calendar) {
//calendar passed
Log.i(TAG,"calendar number components: " + calendar.getComponents().size());
//for every event
for (Object o : calendar.getComponents()) {
Component component = (Component) o;
Date startDate;
Date endDate;
//grab summary string
String summary = "Not specified";
if (component.getProperties("SUMMARY").size()>0) {
//summary event
summary = component.getProperties("SUMMARY").get(0).getValue();
}
//Log.i(TAG, "-component>>>" + summary);
try {
//if has a start time
if (component.getProperties("DTSTART").size()>0) {
String start_str = null, end_str = null;
//iterator gets start-time String
for (Iterator j = component.getProperties("DTSTART").iterator(); j.hasNext();) {
Property property = (Property) j.next();
start_str = property.getValue();
//Log.i(TAG, "Property DTSTART [" + property.getName() + " <<>> " + property.getValue() + "]");
}
try {
//parsing the string to date with hour
startDate = SDFH.parse(start_str);
//Log.i(TAG, "Property DTSTART parsed with hour: " + startDate);
} catch (ParseException e) {
//parsing the string to date
startDate = SDF.parse(start_str);
//Log.i(TAG, "Property DTSTART parsed only day: " + startDate);
}
java.util.Calendar startCal = java.util.Calendar.getInstance();
startCal.setTime(startDate);
//end time part
java.util.Calendar endCal;
//if it has the end time
if (component.getProperties("DTEND").size()>0) {
//iterator gets end-time String
for (Iterator j = component.getProperties("DTEND").iterator(); j.hasNext();) {
Property property = (Property) j.next();
end_str = property.getValue();
//Log.i(TAG, "Property DTEND [" + property.getName() + " <<>> " + property.getValue() + "]");
}
try {
//parsing the string to date with hour
endDate = SDFH.parse(end_str);
//Log.i(TAG, "Property DTEND parsed with hour: " + endDate);
endCal = java.util.Calendar.getInstance();
endCal.setTime(endDate);
} catch (ParseException e) {
//parsing the string to date
endDate = SDF.parse(end_str);
//Log.i(TAG, "Property DTSTART parsed only day: " + endDate);
endCal = java.util.Calendar.getInstance();
endCal.setTime(endDate);
//if the end day is the same I put the end hour at 24
if (startCal.get(java.util.Calendar.DAY_OF_MONTH) == endCal.get(java.util.Calendar.DAY_OF_MONTH )) {
endCal.set(java.util.Calendar.HOUR_OF_DAY, 24);
}
}
} else {
//Log.i(TAG, "Property DTEND NOT FOUND");
//end time at the end of the same day
endCal = (java.util.Calendar) startCal.clone();
endCal.set(java.util.Calendar.HOUR_OF_DAY, 24);
}
//create event
WeekViewEvent event = new WeekViewEvent(1, summary, startCal, endCal);
//todo put color depending on the events
//event.setColor(getResources().getColor(R.color.colorPrimary, null));
//put the event in the list
events.add(event);
//Log.i(TAG, "added: " + startDate + ">->" + endDate + " Summary: " + summary);
} else{
//no start-time not added
Log.e(TAG, "NOT ADDED (DTSTART not found) component details:" + component.toString());
}
} catch (ParseException e) {
e.printStackTrace();
Log.e(TAG, "PARSE EXCEPTION component details:" + component.toString());
}
}
//finished this thread
finishedThreadsCount++;
Log.i(TAG, "FINISHED THREAD " + finishedThreadsCount);
//notify update to UI
runOnUiThread(new Runnable() {
@Override
public void run() {
//if last thread finished
if (finishedThreadsCount == urlsCalendar.length) {
//update ui
mWeekView.notifyDatasetChanged();
//go to 8 am today
mWeekView.goToToday();
mWeekView.goToHour(8);
//visible
mWeekView.setVisibility(View.VISIBLE);
loader_cal.setVisibility(View.GONE);
text_loader_cal.setVisibility(View.GONE);
//new thread not to lock the UI with the sleep
new Thread(new Runnable() {
public void run() {
speechManager.startSpeak("These are the events of the ISR", MySettings.getSpeakDefaultOption());
concludeSpeak(speechManager);
speechManager.startSpeak("Are you satisfied?", MySettings.getSpeakDefaultOption());
concludeSpeak(speechManager);
speechManager.doWakeUp();
}
}).start();
} else {
//update loading
text_loader_cal.setText("Loading "+ (finishedThreadsCount + 1) +"/" + urlsCalendar.length );
}
}
});
}
private void goToDialogAndExit(boolean result) {
if(result) {
//force sleep
infiniteWakeup = false;
speechManager.doSleep();
//starts dialog activity
Intent myIntent = new Intent(MyCalendarActivity.this, MyDialogActivity.class);
MyCalendarActivity.this.startActivity(myIntent);
//finish
finish();
}
}
}
| 44.080586 | 212 | 0.558293 |
c42bb19a6152ea99bb583042c603879e8a01cf6e | 746 | package xworker.libdgx.functions.scenes.scene2d.utils;
import org.xmeta.ActionContext;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.scenes.scene2d.utils.SpriteDrawable;
public class SpriteDrawableFunctions {
public static Object createSpriteDrawable(ActionContext actionContext){
return new SpriteDrawable();
}
public static Object createSpriteDrawable_sprite(ActionContext actionContext){
Sprite sprite = (Sprite) actionContext.get("sprite");
return new SpriteDrawable(sprite);
}
public static Object createSpriteDrawable_drawable(ActionContext actionContext){
SpriteDrawable drawable = (SpriteDrawable) actionContext.get("drawable");
return new SpriteDrawable(drawable);
}
}
| 32.434783 | 82 | 0.788204 |
935f9c87b8294c24817782fad9760d4dba2880dd | 521 | package com.baiyun.model;
public class Msg {
public static final int SUCCESS = 1;
public static final int ERR = 0;
private int status = ERR;// 0失败,1成功
private String msg;
private Object data;
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
| 14.081081 | 37 | 0.669866 |
4158e02215cbac57ef25e87c8e99a65ef6f71eb6 | 933 | package chapter12.machines;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class TransportDemo2 {
public static void main(String[] arguments) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String str = reader.readLine().trim().toUpperCase();
// Методът valueOf() връща константа от изброимият тип, чиято стойност съответства на низът, предаден на метода като аргумент;
Transport vehicle = Transport.valueOf(str);
System.out.println(vehicle + "\n");
// Методът values() връща масив, съдържащ списък с константите на изброимият тип;
Transport[] vehicles = Transport.values();
for(Transport item : Transport.values()){
System.out.printf("[%d] %s%n", (item.ordinal() + 1), item);
}
reader.close();
}
}
| 35.884615 | 134 | 0.6806 |
71b194d82011a158c91b171593543b8dac64620e | 874 | package sblectric.lightningcraft.util;
import java.util.LinkedList;
import java.util.List;
import net.minecraft.entity.Entity;
import net.minecraft.entity.effect.EntityLightningBolt;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.world.World;
/** Helper methods associated with weather effects */
public class WeatherUtils {
/** gets a list of lightning bolts within a box */
public static List<EntityLightningBolt> getLightningBoltsWithinAABB(World world, AxisAlignedBB box) {
List<EntityLightningBolt> bolts = new LinkedList<EntityLightningBolt>();
for(Entity i : world.weatherEffects) {
if(i instanceof EntityLightningBolt) {
if(i.posX >= box.minX && i.posX <= box.maxX && i.posY >= box.minY && i.posY <= box.maxY && i.posZ >= box.minZ && i.posZ <= box.maxZ)
bolts.add((EntityLightningBolt) i);
}
}
return bolts;
}
}
| 32.37037 | 138 | 0.735698 |
919a89bd6900814cfdcbddea5bdf5baf62b1dc22 | 969 | package com.sms.server.net.rtsp.codec;
import java.nio.charset.CharacterCodingException;
import org.apache.mina.core.buffer.IoBuffer;
import com.sms.server.net.http.message.HTTPMessage;
import com.sms.server.net.http.message.HTTPResponse;
/**
* RTSP Response Encoder
* @author pengliren
*
*/
public class RTSPResponseEncoder extends RTSPMessageEncoder {
public RTSPResponseEncoder() throws CharacterCodingException {
super();
}
@Override
protected void encodeInitialLine(IoBuffer buf, HTTPMessage message) throws Exception {
HTTPResponse response = (HTTPResponse) message;
buf.put(response.getProtocolVersion().toString().getBytes("ASCII"));
buf.put((byte) ' ');
buf.put(String.valueOf(response.getStatus().getCode()).getBytes("ASCII"));
buf.put((byte) ' ');
buf.put(String.valueOf(response.getStatus().getReasonPhrase()).getBytes("ASCII"));
buf.put((byte) '\r');
buf.put((byte) '\n');
}
}
| 27.685714 | 90 | 0.705882 |
b6b1a63e51a52808fcda188128dda20aa85c0205 | 309 | package comlib.adk.util.target;
import comlib.adk.team.tactics.Tactics;
import rescuecore2.worldmodel.EntityID;
public abstract class TargetSelector {
protected Tactics tactics;
public TargetSelector(Tactics t) {
this.tactics = t;
}
public abstract EntityID getTarget(int time);
} | 20.6 | 49 | 0.737864 |
37e242064cbce446bbb11c8e29a4e2e15416d98c | 705 | package com.example.ali.melbournebikeshare.app_manager;
import android.app.Application;
import com.example.ali.melbournebikeshare.network.VolleyManager;
/**
* Created by alireza.sobhani on 18/10/2015.
*/
public class AppManager extends Application {
private static AppManager instance;
private VolleyManager mVolleyManager;
@Override
public void onCreate() {
super.onCreate();
mVolleyManager = new VolleyManager(getApplicationContext());
instance = this;
}
public static synchronized AppManager getInstance() {
return instance;
}
public static VolleyManager getVolleyManager() {
return getInstance().mVolleyManager;
}
}
| 23.5 | 68 | 0.713475 |
5eefa34c45d48945cb5b4d42c6db2bef66fe6592 | 585 | package com.lkats.wishlist.books.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.*;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import javax.validation.constraints.Email;
import java.util.Set;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Document
public class User {
@Id
private String id;
@JsonIgnore
private String password;
@Email
private String email;
private String username;
private boolean active = true;
private Set<String> roles;
}
| 18.870968 | 62 | 0.758974 |
c713ec058161c2fcd18731baa68b94d7e46604bf | 596 | package application;
import java.util.Locale;
import java.util.Scanner;
import util.Calculator2;
public class Main3 {
public static void main(String[] args) {
Locale.setDefault(Locale.US);
Scanner teclado = new Scanner(System.in);
System.out.print("Enter radius: ");
double radius = teclado.nextDouble();
double c = Calculator2.circumference(radius);
double v = Calculator2.volume(radius);
System.out.printf("Circumference: %.2f%n", c);
System.out.printf("Volume: %.2f%n", v);
System.out.printf("PI value: %.2f%n", Calculator2.PI);
teclado.close();
}
}
| 20.551724 | 56 | 0.687919 |
9e14e8f90ab1e0431909a729ba1b79a264089c31 | 8,886 | /*
* Fabric3
* Copyright (c) 2009-2015 Metaform Systems
*
* 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.
*
* Portions originally based on Apache Tuscany 2007
* licensed under the Apache 2.0 license.
*/
package org.fabric3.binding.ws.metro.runtime.core;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.xml.namespace.QName;
import javax.xml.ws.Binding;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.handler.Handler;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import com.sun.xml.ws.api.BindingID;
import com.sun.xml.ws.api.WSBinding;
import com.sun.xml.ws.api.server.Container;
import com.sun.xml.ws.api.server.Invoker;
import com.sun.xml.ws.api.server.SDDocumentSource;
import com.sun.xml.ws.api.server.WSEndpoint;
import com.sun.xml.ws.binding.BindingImpl;
import com.sun.xml.ws.mex.server.MEXEndpoint;
import com.sun.xml.ws.transport.http.servlet.ServletAdapter;
import com.sun.xml.ws.transport.http.servlet.WSServlet;
import com.sun.xml.ws.transport.http.servlet.WSServletDelegate;
/**
* Handles incoming HTTP requests and dispatches them to the Metro stack. Extends the Metro servlet and overrides the <code>getDelegate</code> method.
*/
@SuppressWarnings("NonSerializableFieldInSerializableClass")
public class MetroServlet extends WSServlet {
private static final long serialVersionUID = -2581439830158433922L;
private static final String MEX_SUFFIX = "/mex";
private ExecutorService executorService;
private List<EndpointConfiguration> configurations = new ArrayList<>();
private ServletAdapterFactory servletAdapterFactory = new ServletAdapterFactory();
private volatile F3ServletDelegate delegate;
private F3Container container;
private WSEndpoint<?> mexEndpoint;
/**
* Constructor
*
* @param executorService the executor service for dispatching invocations
*/
public MetroServlet(ExecutorService executorService) {
this.executorService = executorService;
}
public synchronized void init(ServletConfig servletConfig) throws ServletException {
if (delegate != null) {
return;
}
super.init(servletConfig);
ServletContext servletContext = servletConfig.getServletContext();
// Setup the WSIT endpoint that handles WS-MEX requests for registered endpoints. The TCCL must be set for JAXB.
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
ClassLoader seiClassLoader = MEXEndpoint.class.getClassLoader();
try {
Thread.currentThread().setContextClassLoader(seiClassLoader);
container = new F3Container(servletContext);
WSBinding binding = BindingImpl.create(BindingID.SOAP12_HTTP);
mexEndpoint = WSEndpoint.create(MEXEndpoint.class, false, null, null, null, container, binding, null, null, null, true);
} finally {
Thread.currentThread().setContextClassLoader(classLoader);
}
// register services
for (EndpointConfiguration configuration : configurations) {
registerService(configuration);
}
}
public synchronized void registerService(EndpointConfiguration configuration) {
if (delegate == null) {
// servlet has not be initialized, delay service registration
configurations.add(configuration);
return;
}
Class<?> seiClass = configuration.getSeiClass();
ClassLoader classLoader = seiClass.getClassLoader();
ClassLoader old = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(classLoader);
URL wsdlLocation = configuration.getWsdlLocation();
SDDocumentSource primaryWsdl = null;
if (wsdlLocation != null) {
// WSDL may not be defined for a Java-based endpoint, in which case it will be introspected from the SEI class
primaryWsdl = SDDocumentSource.create(wsdlLocation);
}
WSBinding binding = BindingImpl.create(BindingID.SOAP11_HTTP);
Container endpointContainer = container;
List<SDDocumentSource> metadata = null;
URL generatedWsdl = configuration.getGeneratedWsdl();
if (generatedWsdl != null) {
// create a container wrapper used by Metro to resolve the WSIT configuration
endpointContainer = new WsitConfigurationContainer(container, generatedWsdl);
// Compile the list of imported schemas so they can be resolved using ?xsd GET requests. Metro will re-write the WSDL import
// so clients can dereference the imports when they obtain the WSDL.
metadata = new ArrayList<>();
List<URL> schemas = configuration.getGeneratedSchemas();
if (schemas != null) {
for (URL schema : schemas) {
metadata.add(SDDocumentSource.create(schema));
}
}
}
String servicePath = configuration.getServicePath();
Invoker invoker = configuration.getInvoker();
QName serviceName = configuration.getServiceName();
QName portName = configuration.getPortName();
// Fetch the handlers
loadHandlers(binding, configuration);
WSEndpoint<?> wsEndpoint;
try {
wsEndpoint = WSEndpoint.create(seiClass, false, invoker, serviceName, portName, endpointContainer, binding, primaryWsdl, metadata, null, true);
} catch (WebServiceException e) {
if (e.getMessage().contains("Not a primary WSDL")) {
// workaround for WSDLs without service declarations
wsEndpoint = WSEndpoint.create(seiClass, false, invoker, serviceName, portName, endpointContainer, binding, null, metadata, null, true);
} else {
throw e;
}
}
wsEndpoint.setExecutor(executorService);
ServletAdapter adapter = servletAdapterFactory.createAdapter(servicePath, servicePath, wsEndpoint);
delegate.registerServletAdapter(adapter, F3Provider.class.getClassLoader());
String mexPath = servicePath + MEX_SUFFIX;
ServletAdapter mexAdapter = servletAdapterFactory.createAdapter(mexPath, mexPath, mexEndpoint);
delegate.registerServletAdapter(mexAdapter, F3Provider.class.getClassLoader());
} finally {
Thread.currentThread().setContextClassLoader(old);
}
}
/**
* Unregisters a service endpoint.
*
* @param path the endpoint path
*/
public synchronized void unregisterService(String path) {
if (delegate == null) {
// case where the endpoint is undeployed before it has been activated
for (Iterator<EndpointConfiguration> it = configurations.iterator(); it.hasNext(); ) {
EndpointConfiguration configuration = it.next();
if (configuration.getServicePath().equals(path)) {
it.remove();
return;
}
}
return;
}
ServletAdapter adapter = delegate.unregisterServletAdapter(path);
if (adapter != null) {
container.removeEndpoint(adapter);
}
}
/**
* Gets the {@link WSServletDelegate} that we will be forwarding the requests to.
*
* @return Returns a Fabric3 servlet delegate.
*/
protected WSServletDelegate getDelegate(ServletConfig servletConfig) {
if (delegate == null) {
synchronized (this) {
if (delegate == null) {
delegate = new F3ServletDelegate(servletConfig.getServletContext());
}
}
}
return delegate;
}
private void loadHandlers(Binding binding, EndpointConfiguration config) {
List<Handler> handlers = config.getHandlers();
if (handlers == null) {
return;
}
binding.setHandlerChain(handlers);
}
}
| 42.314286 | 159 | 0.661265 |
c1348f287cbbc18ee023e29c5a4bb13afc9f4b75 | 1,142 | /*
* Copyright 2017 dmfs GmbH
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dmfs.httpessentials.executors.authorizing;
import org.dmfs.jems.optional.Optional;
import java.net.URI;
/**
* An authentication scope.
*
* @author Marten Gajda
*/
public interface AuthScope
{
/**
* Returns the {@link URI} of this {@link AuthScope}.
*
* @return A {@link URI}.
*/
URI uri();
/**
* Returns the realm {@link CharSequence} of the {@link AuthScope} if there is any.
*
* @return An {@link Optional} {@link CharSequence}.
*/
Optional<CharSequence> realm();
}
| 24.826087 | 87 | 0.677758 |
455ee8057ad0af2217945e1f7b5e9bdcda235131 | 3,951 | /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.envers.internal.entities.mapper.relation.lazy.initializor;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.hibernate.envers.boot.internal.EnversService;
import org.hibernate.envers.internal.entities.mapper.relation.MiddleComponentData;
import org.hibernate.envers.internal.entities.mapper.relation.query.RelationQueryGenerator;
import org.hibernate.envers.internal.reader.AuditReaderImplementor;
/**
* Initializes a map.
*
* @author Adam Warski (adam at warski dot org)
* @author Chris Cranford
*/
public class ListCollectionInitializor extends AbstractCollectionInitializor<List> {
private final MiddleComponentData elementComponentData;
private final MiddleComponentData indexComponentData;
public ListCollectionInitializor(
EnversService enversService,
AuditReaderImplementor versionsReader,
RelationQueryGenerator queryGenerator,
Object primaryKey,
Number revision,
boolean removed,
MiddleComponentData elementComponentData,
MiddleComponentData indexComponentData) {
super( enversService, versionsReader, queryGenerator, primaryKey, revision, removed );
this.elementComponentData = elementComponentData;
this.indexComponentData = indexComponentData;
}
@Override
@SuppressWarnings({"unchecked"})
protected List initializeCollection(int size) {
// There are two types of List collections that this class may generate
//
// 1. Those which are not-indexed, thus the entries in the list are equal to the size argument passed.
// 2. Those which are indexed, thus the entries in the list are based on the highest result-set index value.
// In this use case, the supplied size value is irrelevant other than to minimize allocations.
//
// So what we're going to do is to build an ArrayList based on the supplied size as the best of the two
// worlds. When adding elements to the collection, we cannot make any assumption that the slot for which
// we are inserting is valid, so we must continually expand the list as needed for (2); however we can
// avoid unnecessary memory allocations by using the size parameter as an optimization for both (1) and (2).
final List list = new ArrayList( size );
for ( int i = 0; i < size; i++ ) {
list.add( i, null );
}
return list;
}
@Override
@SuppressWarnings({"unchecked"})
protected void addToCollection(List collection, Object collectionRow) {
// collectionRow will be the actual object if retrieved from audit relation or middle table
// otherwise it will be a List
Object elementData = collectionRow;
Object indexData = collectionRow;
if ( java.util.List.class.isInstance( collectionRow ) ) {
final java.util.List row = java.util.List.class.cast( collectionRow );
elementData = row.get( elementComponentData.getComponentIndex() );
indexData = row.get( indexComponentData.getComponentIndex() );
}
final Object element;
if ( Map.class.isInstance( elementData ) ) {
element = elementComponentData.getComponentMapper().mapToObjectFromFullMap(
entityInstantiator,
(Map<String, Object>) elementData,
null,
revision
);
}
else {
element = elementData;
}
final Object indexObj = indexComponentData.getComponentMapper().mapToObjectFromFullMap(
entityInstantiator,
(Map<String, Object>) indexData,
element,
revision
);
final int index = ( (Number) indexObj ).intValue();
// This is copied from PersistentList#readFrom
// For the indexed list use case to make sure the slot that we're going to set actually exists.
for ( int i = collection.size(); i <= index; ++i ) {
collection.add( i, null );
}
collection.set( index, element );
}
}
| 36.925234 | 111 | 0.748165 |
829b8bf9d6b15ef37c6322d634e3f6d8b2ee51da | 681 | package cn.kiyohara.cocplayercharactermanager;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
public class AboutActivity extends AppCompatActivity {
ImageView cancelIv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
cancelIv = findViewById(R.id.about_actionBar_iv_cancel);
cancelIv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
} | 28.375 | 64 | 0.69163 |
6b32a7a158d9f77b684be955ac33dc53785df450 | 289 | public class Challenge {
public static void main(String[] args) {
// 1. 1~100 을 순회한다
// 2. 루프 내에서 난수 값을 할당 받는다.
// 3. 현재 i값이 난수의 배수인지 판정한다.
// 4. 배수라면 출력하고 sum에 합산
// 아니라면 i에 가장 가까운 i보다 큰 난수 배수값을 찾아서 출력하고 합산한다.
// 또한 현재 i값값
}
}
| 26.272727 | 57 | 0.50519 |
9fbb2156bce491bb858eb67ccf15330277c17b82 | 1,392 |
import java.util.Scanner;
public class matrix_symmetric
{
int A[][],B[][],n,i,j;
void input()
{
Scanner sc=new Scanner(System.in);
System.out.println("enter no. of rows and columns");
n=sc.nextInt();
A=new int[n][n];
B=new int[n][n];
System.out.println("enter elements"+(n*n));
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
A[i][j]=sc.nextInt();
}
}
void display()
{
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
System.out.print(A[i][j]);
System.out.println();
}
}
void transpose()
{
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
B[i][j]=A[j][i];
}
}
//printing B
System.out.println("transpose");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
System.out.print(B[i][j]);
System.out.println();
}
}
void symmetric()
{
boolean flag=true;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(A[i][j]!=B[i][j])
flag=false;
}
}
if(flag==true)
System.out.println("Symmetric matrix");
else
System.out.println("not symmetric");
}
public static void main(String args[])
{
matrix_symmetric obj=new matrix_symmetric();
obj.input();
obj.display();
obj.transpose();
obj.symmetric();
}
} | 19.605634 | 57 | 0.45977 |
7b371f162d67c15d473b2fd74c01cfee10b48855 | 4,627 | /*
* Copyright 2020-2021 Richard Linsdale (richard at theretiredprogrammer.uk).
*
* 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 uk.theretiredprogrammer.sketch.display.entity.course;
import uk.theretiredprogrammer.sketch.core.entity.Angle;
import uk.theretiredprogrammer.sketch.core.entity.Location;
import uk.theretiredprogrammer.sketch.display.entity.boats.Boat;
import uk.theretiredprogrammer.sketch.display.entity.flows.WaterFlow;
import uk.theretiredprogrammer.sketch.display.entity.flows.WindFlow;
import uk.theretiredprogrammer.sketch.display.entity.base.SketchModel;
import uk.theretiredprogrammer.sketch.display.entity.course.Decision.Importance;
import static uk.theretiredprogrammer.sketch.display.entity.course.Decision.Importance.INSIGNIFICANT;
import static uk.theretiredprogrammer.sketch.display.entity.course.Decision.Importance.MAJOR;
public class Params {
public final Boat boat;
public final SketchModel model;
public final WindFlow windflow;
public final WaterFlow waterflow;
//
public Decision decision;
public CurrentLeg leg;
public Angle winddirection;
public Angle starboardCloseHauled;
public Angle portCloseHauled;
public Angle starboardReaching;
public Angle portReaching;
public Angle heading;
public Location location;
public double angletowind;
public Angle meanwinddirection;
public boolean reachesdownwind;
public double downwindrelative;
public double upwindrelative;
public boolean isPort;
public Location marklocation;
public Angle markmeanwinddirection;
public Angle angletomark;
public Params(SketchModel model, Boat boat) {
this.model = model;
windflow = model.getWindFlow();
waterflow = model.getWaterFlow();
this.boat = boat;
refresh();
}
public final void refresh() {
leg = boat.getCurrentLeg();
decision = leg.decision;
//
angletomark = leg.getAngleofLeg();
marklocation = leg.getMarkLocation();
//
winddirection = windflow.getFlow(boat.getLocation()).getAngle();
meanwinddirection = windflow.getMeanFlowAngle();
markmeanwinddirection = marklocation == null ? null : windflow.getMeanFlowAngle(marklocation);
//
heading = boat.getDirection();
location = boat.getLocation();
downwindrelative = boat.metrics.downwindrelative.get();
upwindrelative = boat.metrics.upwindrelative.get();
reachesdownwind = boat.isReachdownwind();
isPort = boat.isPort(winddirection);
starboardCloseHauled = boat.getStarboardCloseHauledCourse(winddirection);
portCloseHauled = boat.getPortCloseHauledCourse(winddirection);
starboardReaching = boat.getStarboardReachingCourse(winddirection);
portReaching = boat.getPortReachingCourse(winddirection);
angletowind = heading.degreesDiff(winddirection).get();
}
public final Angle angleToSailToMark() {
return angleToSailToMark(isPort);
}
public final Angle angleToSailToMark(boolean port) {
return leg.getAngletoSail(location, port);
}
public final boolean setSAILON() {
decision.setSAILON(heading);
return true;
}
public final boolean setTURN(Angle degrees, boolean turndirection, Importance importance, String reason) {
Angle change = degrees.degreesDiff(heading).fold();
if (change.lt(0.1)) {
decision.setSAILON(heading);
} else if (change.lt(1) && importance != MAJOR) {
decision.setTURN(degrees, turndirection, INSIGNIFICANT, reason);
} else {
decision.setTURN(degrees, turndirection, importance, reason);
}
return true;
}
public final boolean setMARKROUNDING(Angle degrees, boolean turndirection, Importance importance, String reason) {
decision.setMARKROUNDING(degrees, turndirection, importance, reason);
return true;
}
public final boolean setSTOP() {
decision.setSTOP(heading);
return true;
}
}
| 37.92623 | 118 | 0.712989 |
2e1e53002bfe0c221827b46d9416e948d9d9e542 | 165 | package com.yofish.yyconfig.client.pattern;
/**
* @Author: xiongchengwei
* @version:
* @Description: 类的主要职责说明
* @Date: 2020/8/19 下午2:02
*/
public class Ss {
}
| 15 | 43 | 0.672727 |
8857a0b2bf978a7c4b20b897c3746eb9e40e9396 | 9,170 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.hw1_131044084_mehmed_mustafa;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
*
* @author mmustafa
*/
public class CourseTest extends TestCase {
public CourseTest(String testName) {
super(testName);
}
public static Test suite() {
TestSuite suite = new TestSuite(CourseTest.class);
return suite;
}
@Override
protected void setUp() throws Exception {
super.setUp();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
/**
* Test of setCourseCode method, of class Course.
*/
public void testSetCourseCode() {
System.out.println("setCourseCode");
String courseCode = "";
Course instance = new Course();
instance.setCourseCode(courseCode);
}
/**
* Test of getCourseCode method, of class Course.
*/
public void testGetCourseCode() {
System.out.println("getCourseCode");
Course instance = new Course();
String expResult = "NoName";
String result = instance.getCourseCode();
assertEquals(expResult, result);
}
/**
* Test of setCourseTeacher method, of class Course.
*/
public void testSetCourseTeacher() {
System.out.println("setCourseTeacher");
Teacher instructor = null;
Course instance = new Course();
instance.setCourseTeacher(instructor);
}
/**
* Test of getCourseTeacher method, of class Course.
*/
public void testGetCourseTeacher() {
System.out.println("getCourseTeacher");
Course instance = new Course();
Teacher expResult = new Teacher();
Teacher result = instance.getCourseTeacher();
assertEquals(expResult, result);
}
/**
* Test of checkStudentExistence method, of class Course.
*/
public void testCheckStudentExistence() {
System.out.println("checkStudentExistence");
Student aStudent = new Student("Mehmed", "Mustafa");
Course instance = new Course();
int expResult = -1;
int result = instance.checkStudentExistence(aStudent);
assertEquals(expResult, result);
}
/**
* Test of checkTutorExistence method, of class Course.
*/
public void testCheckTutorExistence() {
System.out.println("checkTutorExistence");
Tutor aTutor = new Tutor("Ekber", "Aizezi");
Course instance = new Course();
int expResult = -1;
int result = instance.checkTutorExistence(aTutor);
assertEquals(expResult, result);
}
/**
* Test of checkDocumentExistence method, of class Course.
*/
public void testCheckDocumentExistence() {
System.out.println("checkDocumentExistence");
String docName = "ClassLectures";
String aType = "pdf";
Course instance = new Course();
int expResult = -1;
int result = instance.checkDocumentExistence(docName, aType);
assertEquals(expResult, result);
}
/**
* Test of checkAssignmentExistence method, of class Course.
*/
public void testCheckAssignmentExistence() {
System.out.println("checkAssignmentExistence");
String assigName = null;
Course instance = new Course();
int expResult = -1;
int result = instance.checkAssignmentExistence(assigName);
assertEquals(expResult, result);
}
/**
* Test of addStudent method, of class Course.
*/
public void testAddStudent() {
System.out.println("addStudent");
Student aStudent = null;
Course instance = new Course();
boolean expResult = false;
boolean result = instance.addStudent(aStudent);
assertEquals(expResult, result);
}
/**
* Test of addTutor method, of class Course.
*/
public void testAddTutor() {
System.out.println("addTutor");
Tutor aTutor = null;
Course instance = new Course();
boolean expResult = false;
boolean result = instance.addTutor(aTutor);
assertEquals(expResult, result);
}
/**
* Test of addDocument method, of class Course.
*/
public void testAddDocument() {
System.out.println("addDocument");
Document aDocument = null;
Course instance = new Course();
boolean expResult = false;
boolean result = instance.addDocument(aDocument);
assertEquals(expResult, result);
}
/**
* Test of addAssignment method, of class Course.
*/
public void testAddAssignment() {
System.out.println("addAssignment");
Assignment anAssignment = null;
Course instance = new Course();
boolean expResult = false;
boolean result = instance.addAssignment(anAssignment);
assertEquals(expResult, result);
}
/**
* Test of removeStudent method, of class Course.
*/
public void testRemoveStudent() {
System.out.println("removeStudent");
String firstName = "";
String lastName = "";
Course instance = new Course();
boolean expResult = false;
boolean result = instance.removeStudent(firstName, lastName);
assertEquals(expResult, result);
}
/**
* Test of removeTutor method, of class Course.
*/
public void testRemoveTutor() {
System.out.println("removeTutor");
String firstName = "";
String lastName = "";
Course instance = new Course();
boolean expResult = false;
boolean result = instance.removeTutor(firstName, lastName);
assertEquals(expResult, result);
}
/**
* Test of removeDocument method, of class Course.
*/
public void testRemoveDocument() {
System.out.println("removeDocument");
String fileName = "";
String aType = "";
Course instance = new Course();
boolean expResult = false;
boolean result = instance.removeDocument(fileName, aType);
assertEquals(expResult, result);
}
/**
* Test of removeAssignment method, of class Course.
*/
public void testRemoveAssignment() {
System.out.println("removeAssignment");
String assigName = "";
Course instance = new Course();
boolean expResult = false;
boolean result = instance.removeAssignment(assigName);
assertEquals(expResult, result);
}
/**
* Test of findAssignment method, of class Course.
*/
public void testFindAssignment() {
System.out.println("findAssignment");
String assigName = "";
Course instance = new Course();
Assignment expResult = null;
Assignment result = instance.findAssignment(assigName);
assertEquals(expResult, result);
}
/**
* Test of printTheCourseStudents method, of class Course.
*/
public void testPrintTheCourseStudents() {
System.out.println("printTheCourseStudents");
Course instance = new Course();
instance.printTheCourseStudents();
}
/**
* Test of printTheCourseTutors method, of class Course.
*/
public void testPrintTheCourseTutors() {
System.out.println("printTheCourseTutors");
Course instance = new Course();
instance.printTheCourseTutors();
}
/**
* Test of printTheCourseDocuments method, of class Course.
*/
public void testPrintTheCourseDocuments() {
System.out.println("printTheCourseDocuments");
Course instance = new Course();
instance.printTheCourseDocuments();
}
/**
* Test of printTheCourseAssignments method, of class Course.
*/
public void testPrintTheCourseAssignments() {
System.out.println("printTheCourseAssignments");
Course instance = new Course();
instance.printTheCourseAssignments();
}
/**
* Test of equals method, of class Course.
*/
public void testEquals() {
System.out.println("equals");
Object obj = null;
Course instance = new Course();
boolean expResult = false;
boolean result = instance.equals(obj);
assertEquals(expResult, result);
}
/**
* Test of hashCode method, of class Course.
*/
public void testHashCode() {
System.out.println("hashCode");
Course instance = new Course();
int expResult = 7;
int result = instance.hashCode();
assertEquals(expResult, result);
}
/**
* Test of toString method, of class Course.
*/
public void testToString() {
System.out.println("toString");
Course instance = new Course();
String expResult = "NoName, Course teacher: NoFirstName NoLastName";
String result = instance.toString();
assertEquals(expResult, result);
}
}
| 29.580645 | 79 | 0.618975 |
14207691a970fbc904c2f63a961d1fdaae696d71 | 1,848 | package com.GestionStock.dto;
import com.GestionStock.model.LigneCommandeFournisseur;
import lombok.Builder;
import lombok.Data;
import java.math.BigDecimal;
@Data
@Builder
public class LigneCommandeFournisseurDto {
private Integer id;
private BigDecimal quantite;
private BigDecimal prixUnitaire;
private ArticleDto article;
private Integer idEntreprise;
private CommandeFournisseurDto commandeFournisseur;
public static LigneCommandeFournisseurDto fromEntity(LigneCommandeFournisseur ligneCommandeFournisseur){
if(ligneCommandeFournisseur.equals(null)){
return null;
}
return LigneCommandeFournisseurDto.builder()
.id(ligneCommandeFournisseur.getId())
.article(ArticleDto.fromEntity(ligneCommandeFournisseur.getArticle()))
.quantite(ligneCommandeFournisseur.getPrixUnitaire())
.idEntreprise(ligneCommandeFournisseur.getIdEntreprise())
.build();
}
public static LigneCommandeFournisseur toEntity(LigneCommandeFournisseurDto ligneCommandeFournisseurDto){
if(ligneCommandeFournisseurDto.equals(null)){
return null;
}
LigneCommandeFournisseur ligneCommandeFournisseur = new LigneCommandeFournisseur();
ligneCommandeFournisseur.setId(ligneCommandeFournisseurDto.getId());
ligneCommandeFournisseur.setArticle(ArticleDto.toEntity(ligneCommandeFournisseurDto.getArticle()));
ligneCommandeFournisseur.setPrixUnitaire(ligneCommandeFournisseurDto.getPrixUnitaire());
ligneCommandeFournisseur.setQuantite(ligneCommandeFournisseurDto.getQuantite());
ligneCommandeFournisseur.setIdEntreprise(ligneCommandeFournisseurDto.getIdEntreprise());
return ligneCommandeFournisseur;
}
}
| 33.6 | 111 | 0.739177 |
2e855b753b11be56c26c55c46f085a3e4b370b65 | 271 | package com.linkedbook.dto.deal.createDeal;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Builder
public class CreateDealOutput {
private int dealId;
} | 19.357143 | 43 | 0.826568 |
d94499cb7427fcceb5f63a09a515ce4fabb44f39 | 1,841 | package com.alibaba.alink.common.mapper;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.java.tuple.Tuple4;
import org.apache.flink.ml.api.misc.param.Params;
import org.apache.flink.table.api.TableSchema;
import com.alibaba.alink.params.mapper.MISOMapperParams;
/**
* Mapper with Multi-Input columns and Single Output column(MISO).
*/
public abstract class MISOMapper extends Mapper {
private static final long serialVersionUID = 7808362775563479371L;
/**
* Constructor.
*
* @param dataSchema input table schema.
* @param params input parameters.
*/
public MISOMapper(TableSchema dataSchema, Params params) {
super(dataSchema, params);
}
/**
* Determine the return type of the {@link MISOMapper#map(Object[])}
*
* @return the output column type.
*/
protected abstract TypeInformation<?> initOutputColType();
/**
* Map input objects to single object.
*
* @param input input objects.
* @return output object.
*/
protected abstract Object map(Object[] input) throws Exception;
@Override
protected void map(SlicedSelectedSample selection, SlicedResult result) throws Exception {
Object[] input = new Object[selection.length()];
for (int i = 0; i < selection.length(); i++) {
input[i] = selection.get(i);
}
result.set(0, map(input));
}
@Override
protected Tuple4 <String[], String[], TypeInformation <?>[], String[]> prepareIoSchema(
TableSchema dataSchema, Params params) {
String[] keepColNames = null;
if (params.contains(MISOMapperParams.RESERVED_COLS)) {
keepColNames = params.get(MISOMapperParams.RESERVED_COLS);
}
return Tuple4.of(
params.get(MISOMapperParams.SELECTED_COLS),
new String[] {params.get(MISOMapperParams.OUTPUT_COL)},
new TypeInformation<?>[] {initOutputColType()},
keepColNames
);
}
}
| 27.477612 | 91 | 0.724606 |
2a21800d6f874cd340cf67980a899e321093fd70 | 585 | package com.glovoapp.diagrams;
import java.util.Set;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
public interface Component<Id extends Identifier<Id>> extends Identifiable<Id> {
String getName();
Set<Component<Id>> getNestedComponents();
@Getter
@EqualsAndHashCode
@RequiredArgsConstructor
final class SimpleComponent<Id extends Identifier<Id>> implements Component<Id> {
private final Id id;
private final String name;
private final Set<Component<Id>> nestedComponents;
}
}
| 22.5 | 85 | 0.735043 |
3f828c82b84511769aadf3dd8ab0b25096e4998e | 287 | package com.scottlogic.deg.generator.generation;
import com.scottlogic.deg.generator.outputs.GeneratedObject;
public interface DataGeneratorMonitor {
void generationStarting(GenerationConfig generationConfig);
void rowEmitted(GeneratedObject row);
void endGeneration();
}
| 26.090909 | 63 | 0.811847 |
4cb47f4c5ece60912976b50a4a9b16ad6b646c36 | 1,500 | package qunar.tc.qconfig.client.impl;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import java.util.AbstractMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
/**
* @author lepdou 2017-06-30
*/
class ConfigRepository {
private static final ConfigRepository INSTANCE = new ConfigRepository();
/**
* (groupName,fileName) -> (fileVersion, fileData)
*/
private ConcurrentMap<Meta, Map.Entry<Long, String>> repository;
public static ConfigRepository getInstance() {
return INSTANCE;
}
private ConfigRepository() {
repository = Maps.newConcurrentMap();
}
void saveOrUpdate(Meta meta, long version, String fileData) {
if (meta == null) {
return;
}
String group = meta.getGroupName();
String fileName = meta.getFileName();
if (Strings.isNullOrEmpty(group) || Strings.isNullOrEmpty(fileName)) {
return;
}
repository.put(meta, new AbstractMap.SimpleImmutableEntry(version, fileData));
}
Map<Meta, Map.Entry<Long, String>> getAllConfigs() {
return repository;
}
String getData(Meta meta) {
Map.Entry<Long, String> entry = repository.get(meta);
if (entry == null) return "";
return entry.getValue();
}
Set<Meta> allMetas() {
return repository.keySet();
}
}
| 25 | 87 | 0.615333 |
1433d33eb53737e56c48b8a610992dbffe0fe841 | 1,510 | // Copyright 2016 theaigames.com (developers@theaigames.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 the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
package com.theaigames.game;
import java.util.List;
import com.theaigames.uttt.move.ProcessorMove;
/**
* GameHandler interface
*
* DO NOT EDIT THIS FILE
*
* This interface handles all the game logic.
*
* @author Jim van Eeden <jim@starapple.nl>
*/
// handles actual game specific logic
public interface GameHandler {
public void playRound(); // play one round of the game
public int getRoundNumber(); // return the current round number
public int getWinner(); // return the winner of the game, -1 if no winner yet
public boolean isGameOver(); // returns true if the game is over
public List<ProcessorMove> getMoves();
public void updateCurrentSampleValues();
}
| 35.952381 | 79 | 0.706623 |
538558d4f34768659ee70643151da4aa78f283f4 | 4,295 | package org.tat.fni.api.domain;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.TableGenerator;
import javax.persistence.Version;
import org.tat.fni.api.common.IDInterceptor;
import org.tat.fni.api.common.KeyFactor;
import org.tat.fni.api.common.TableName;
import org.tat.fni.api.common.UserRecorder;
@Entity
@Table(name = TableName.INSUREDPERSONKEYFACTORVALUE)
@TableGenerator(name = "INSUREDPERSONKEYFACTORVALUE_GEN", table = "ID_GEN", pkColumnName = "GEN_NAME", valueColumnName = "GEN_VAL", pkColumnValue = "INSUREDPERSONKEYFACTORVALUE_GEN", allocationSize = 10)
@NamedQueries(value = { @NamedQuery(name = "InsuredPersonKeyFactorValue.findAll", query = "SELECT v FROM InsuredPersonKeyFactorValue v "),
@NamedQuery(name = "InsuredPersonKeyFactorValue.findById", query = "SELECT v FROM InsuredPersonKeyFactorValue v WHERE v.id = :id") })
@EntityListeners(IDInterceptor.class)
public class InsuredPersonKeyFactorValue {
@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "INSUREDPERSONKEYFACTORVALUE_GEN")
private String id;
private String value;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "KEYFACTORID", referencedColumnName = "ID")
private KeyFactor keyFactor;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "LIFEPROPOSALINSUREDPERSONID", referencedColumnName = "ID")
private ProposalInsuredPerson proposalInsuredPerson;
@Embedded
private UserRecorder recorder;
@Version
private int version;
public InsuredPersonKeyFactorValue() {
}
public InsuredPersonKeyFactorValue(KeyFactor keyFactor) {
this.keyFactor = keyFactor;
}
public InsuredPersonKeyFactorValue(String value, KeyFactor keyFactor) {
this.value = value;
this.keyFactor = keyFactor;
}
// public InsuredPersonKeyFactorValue(PolicyInsuredPersonKeyFactorValue pinsuredPersonKeyFactorValue) {
// this.keyFactor = pinsuredPersonKeyFactorValue.getKeyFactor();
// this.value = pinsuredPersonKeyFactorValue.getValue();
// }
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public UserRecorder getRecorder() {
return recorder;
}
public void setRecorder(UserRecorder recorder) {
this.recorder = recorder;
}
public String getValue() {
return this.value;
}
public void setValue(String value) {
this.value = value;
}
public KeyFactor getKeyFactor() {
return this.keyFactor;
}
public void setKeyFactor(KeyFactor keyFactor) {
this.keyFactor = keyFactor;
}
public ProposalInsuredPerson getProposalInsuredPerson() {
return proposalInsuredPerson;
}
public void setProposalInsuredPerson(ProposalInsuredPerson proposalInsuredPerson) {
this.proposalInsuredPerson = proposalInsuredPerson;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((recorder == null) ? 0 : recorder.hashCode());
result = prime * result + ((value == null) ? 0 : value.hashCode());
result = prime * result + version;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
InsuredPersonKeyFactorValue other = (InsuredPersonKeyFactorValue) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (recorder == null) {
if (other.recorder != null)
return false;
} else if (!recorder.equals(other.recorder))
return false;
if (value == null) {
if (other.value != null)
return false;
} else if (!value.equals(other.value))
return false;
if (version != other.version)
return false;
return true;
}
}
| 27.88961 | 203 | 0.747846 |
48e9fcc42b1e85b078c8440a095ec2ccfa03422c | 1,776 | package com.simple.csv.model;
/**
* Created by Illia Vinnichenko on 25.08.2016.
*/
public class TopProduct {
private Long matchingId;
private Double totalPrice;
private Double avgPrice;
private String currency;
private Long ignoredProductsCount;
public Long getMatchingId() {
return matchingId;
}
public void setMatchingId(Long matchingId) {
this.matchingId = matchingId;
}
public Double getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(Double totalPrice) {
this.totalPrice = totalPrice;
}
public Double getAvgPrice() {
return avgPrice;
}
public void setAvgPrice(Double avgPrice) {
this.avgPrice = avgPrice;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public Long getIgnoredProductsCount() {
return ignoredProductsCount;
}
public void setIgnoredProductsCount(Long ignoredProductsCount) {
this.ignoredProductsCount = ignoredProductsCount;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TopProduct that = (TopProduct) o;
return !(matchingId != null ? !matchingId.equals(that.matchingId) : that.matchingId != null);
}
@Override
public int hashCode() {
return matchingId != null ? matchingId.hashCode() : 0;
}
@Override
public String toString() {
return matchingId +
"," + totalPrice +
"," + avgPrice +
"," + currency +
"," + ignoredProductsCount;
}
}
| 22.481013 | 101 | 0.606982 |
d14b1ba00084c63eb55fe306394e07d5517156bf | 1,846 | package com.ndr.app.stock.screener.listener;
import com.ndr.app.stock.screener.list.CriteriaModelList;
import com.ndr.app.stock.screener.statusbar.StatusBar;
import com.ndr.app.stock.screener.text.NoteTextPane;
import com.ndr.model.stock.screener.CriteriaModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class CriteriaModelNoteListSelectionListener implements ListSelectionListener {
private CriteriaModelList<CriteriaModel> criteriaModelList;
private NoteTextPane noteTextPane;
private StatusBar statusBar;
public CriteriaModelNoteListSelectionListener(CriteriaModelList<CriteriaModel> criteriaModelList,
NoteTextPane noteTextPane) {
this.criteriaModelList = criteriaModelList;
this.noteTextPane = noteTextPane;
}
public CriteriaModelNoteListSelectionListener(CriteriaModelList<CriteriaModel> criteriaModelList,
NoteTextPane noteTextPane,
StatusBar statusBar) {
this.criteriaModelList = criteriaModelList;
this.noteTextPane = noteTextPane;
this.statusBar = statusBar;
}
@Override
public void valueChanged(ListSelectionEvent event) {
if (!event.getValueIsAdjusting()) {
if (criteriaModelList.isNotEmpty()) {
CriteriaModel selectedCriteriaModel = criteriaModelList.getSelectedEntity();
if (selectedCriteriaModel != null) {
noteTextPane.setText(selectedCriteriaModel.getNote());
if (statusBar != null) {
statusBar.setCriteriaModelStatus(selectedCriteriaModel.getName());
}
}
}
}
}
} | 41.954545 | 101 | 0.658722 |
ae56c88b7689cacf72f9769222b632b6687ad0d7 | 1,895 | package com.upserve.uppend;
import com.upserve.uppend.util.SafeDeleting;
import org.junit.*;
import org.junit.rules.ExpectedException;
import java.io.IOException;
import java.nio.file.*;
import static org.junit.Assert.assertEquals;
public class AppendOnlyStorePartitionSizeTest {
private final Path path = Paths.get("build/test/file-append-only-partition-size");
private AppendOnlyStore newStore() {
return TestHelper.getDefaultAppendStoreTestBuilder().withDir(path.resolve("store-path")).withPartitionCount(2).build(false);
}
private AppendOnlyStore store;
@Rule
public ExpectedException thrown = ExpectedException.none();
@Before
public void initialize() throws IOException {
SafeDeleting.removeDirectory(path);
store = newStore();
}
@After
public void cleanUp() {
try {
store.close();
} catch (Exception e) {
throw new AssertionError("Should not raise: {}", e);
}
}
@Test
public void testWithPartitionSize() {
assertEquals(0, store.scan().count());
assertEquals(0, store.keys().count());
assertEquals(0, store.keyCount());
assertEquals(0, store.read("foo", "bar").count());
store.append("foo", "foobar", "bytes".getBytes());
store.append("foo", "foobat", "bytes".getBytes());
store.append("goo", "goobar", "bytes".getBytes());
store.append("goo", "goobat", "bytes".getBytes());
store.append("shoe", "shoebar", "bytes".getBytes());
store.append("shoe", "shoebat", "bytes".getBytes());
assertEquals(6, store.scan().count());
assertEquals(0, store.keyCount());
assertEquals(1, store.read("foo", "foobar").count());
assertEquals(1, store.read("goo", "goobat").count());
store.flush();
assertEquals(6, store.keyCount());
}
}
| 31.065574 | 132 | 0.631135 |
769b187306eef32da591414b3a1f4f3f83d8599a | 3,944 | /*
* Copyright 2019 Hopper
*
* 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 zookeeper;
import org.apache.log4j.Logger;
import org.apache.zookeeper.*;
import java.io.IOException;
import java.util.Random;
public final class ZooServerConnection implements org.apache.zookeeper.Watcher {
public final String SERVER_ID = Integer.toHexString(new Random().nextInt());
protected final static Logger LOG = Logger.getLogger(ZooServerConnection.class);
protected final String hostServer;
protected final int port;
private ZooKeeper zk;
private volatile boolean connected = false;
private volatile boolean expired = false;
private static ZooServerConnection instance = null;
public static ZooServerConnection getInstance() {
if(instance== null) {
instance= new ZooServerConnection();
}
return instance;
}
public static ZooServerConnection getInstance(String hostServer, int port) {
if(instance == null) {
instance = new ZooServerConnection(hostServer, port);
}
return instance;
}
private ZooServerConnection(String hostServer, int port){
this.hostServer = hostServer;
this.port = port;
startZK();
}
private ZooServerConnection(){
this.hostServer = "localhost";
this.port = 2181;
startZK();
}
//TODO manage multiple connection trys
public void startZK(){
int tryConnectionCount = 0;
try {
tryConnectionCount++;
this.zk = new ZooKeeper(this.hostServer + ":" + this.port, 15000, this);
} catch (IOException e) {
LOG.error(e);
}
}
public void stopZK() throws InterruptedException {
LOG.info( "Closing" );
try{
zk.close();
} catch (InterruptedException e) {
LOG.warn("ZooKeeper interrupted while closing");
}
}
/**
* Checks if this client is connected.
*
* @return boolean
*/
public boolean isConnected() {
return connected;
}
/**
* Checks if ZooKeeper session is expired.
*
* @return
*/
public boolean isExpired() {
return expired;
}
@Override
/**
* Deals with session events like connecting
* and disconnecting.
*
* @param e new event generated
*/
public void process(WatchedEvent event) {
LOG.info(event.toString() + ", " + hostServer + port);
if(event.getType() == Event.EventType.None){
switch (event.getState()) {
case SyncConnected:
/*
* Registered with ZooKeeper
*/
connected = true;
break;
case Disconnected:
connected = false;
break;
case Expired:
expired = true;
connected = false;
LOG.error("Session expired");
break;
default:
LOG.error("session state not found");
break;
}
}
}
public ZooKeeper getZookeeperConnection(){
return this.zk;
}
}
| 25.445161 | 84 | 0.563387 |
28ec3df7f94e4d319ae5359db8ff4bafa8de518d | 1,761 | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*/
package com.microsoft.intellij;
import com.microsoft.azure.toolkit.intellij.link.mysql.PasswordSaveType;
import com.microsoft.azure.toolkit.intellij.link.po.BaseResourcePO;
import com.microsoft.intellij.secure.IdeaSecureStore;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import java.util.HashMap;
import java.util.Map;
public abstract class AzureSecurityServiceStorage<T extends BaseResourcePO> extends AzureServiceStorage<T> {
private final Map<CredentialAttributes, String> memoryCache = new HashMap<>();
public void savePassword(T service, PasswordSaveType passwordSave, String username, String password) {
if (PasswordSaveType.FOEVER.equals(passwordSave)) {
IdeaSecureStore.getInstance().savePassword(service.getId(), username, password);
} else if (PasswordSaveType.UNTIL_RESTART.equals(passwordSave)) {
memoryCache.put(new CredentialAttributes(service.getId(), username), password);
}
}
public String loadPassword(T service, PasswordSaveType passwordSave, String username) {
if (PasswordSaveType.FOEVER.equals(passwordSave)) {
return IdeaSecureStore.getInstance().loadPassword(service.getId(), username);
} else if (PasswordSaveType.UNTIL_RESTART.equals(passwordSave)) {
return memoryCache.get(new CredentialAttributes(service.getId(), username));
}
return null;
}
@AllArgsConstructor
@EqualsAndHashCode
private static class CredentialAttributes {
private String serviceId;
private String username;
}
}
| 38.282609 | 108 | 0.741624 |
af93052e3771a757ea82ae3ca9f9b02f2bc1d87b | 286 | package com.example.advertise.advertisement.repository;
import com.example.advertise.advertisement.entity.Ad;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
public interface AdRepository extends CrudRepository<Ad,Long> {
List<Ad> findAll();
}
| 23.833333 | 63 | 0.811189 |
10013d158619fcd8e6993bd4281289aba9e81225 | 1,328 | package com.xj.scud.client;
import com.xj.scud.core.MessageManager;
import com.xj.scud.core.NetworkProtocol;
import com.xj.scud.core.RpcResult;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Author: xiajun
* Date: 2017/01/08 12:00
*/
public class ClientInvoker implements Invoker {
private final static Logger LOGGER = LoggerFactory.getLogger(ClientInvoker.class);
@Override
public void invoke(final Channel ch, final NetworkProtocol protocol, final int packageId) {
ChannelFuture channelFuture = ch.writeAndFlush(protocol);
if (LOGGER.isDebugEnabled()) {
final long startTime = System.currentTimeMillis();
channelFuture.addListeners((ChannelFutureListener) future -> {
if (!future.isSuccess()) {
RpcResult result = new RpcResult();
result.setException(future.cause());
MessageManager.release(packageId, result);
}
LOGGER.debug("Scud send msg packageId={} cost {}ms, channel={}, exception= {}", protocol.getSequence(), (System.currentTimeMillis() - startTime), ch.toString(), future.cause());
});
}
}
}
| 37.942857 | 193 | 0.666416 |
80a211513ddc3cc9a4d277f01969d83b19f02831 | 3,592 | package br.com.zup.academy.tania.proposta.Carteira;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;
import br.com.zup.academy.tania.proposta.Bloqueio.BloqueioCartao;
import br.com.zup.academy.tania.proposta.Bloqueio.BloqueioCartaoRepository;
import br.com.zup.academy.tania.proposta.Cartao.Cartao;
import br.com.zup.academy.tania.proposta.Cartao.CartaoRepository;
import br.com.zup.academy.tania.proposta.NovaProposta.CartaoClient;
import feign.FeignException;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import javax.validation.Valid;
@RestController
@RequestMapping("/api/cartoes")
public class NovaCarteiraController {
private CarteiraRepository carteiraRepository;
private CartaoRepository cartaoRepository;
private BloqueioCartaoRepository bloqueioCartaoRepository;
private CartaoClient cartaoClient;
private final Logger logger = LoggerFactory.getLogger(Carteira.class);
@Autowired
public NovaCarteiraController(
CarteiraRepository carteiraRepository,
CartaoRepository cartaoRepository,
BloqueioCartaoRepository bloqueioCartaoRepository,
CartaoClient cartaoClient) {
this.carteiraRepository = carteiraRepository;
this.cartaoRepository = cartaoRepository;
this.bloqueioCartaoRepository = bloqueioCartaoRepository;
this.cartaoClient = cartaoClient;
}
@PostMapping("/{id}/carteiras")
public ResponseEntity<?> carteira(@PathVariable Long id, @RequestBody @Valid CarteiraRequest carteiraRequest,
UriComponentsBuilder uriBuilder) {
Optional<Cartao> cartao = cartaoRepository.findById(id);
Optional<BloqueioCartao> cartoesBloqueados = bloqueioCartaoRepository.findById(id);
if (cartao.isPresent()) {
if (cartoesBloqueados.isPresent()) {
return ResponseEntity.unprocessableEntity().body("Esse cartão está bloqueado!");
}
try {
Optional<Carteira> carteiraExistente = carteiraRepository
.findByEnumCarteiraAndCartao(carteiraRequest.getCarteira(), cartao.get());
if (carteiraExistente.isPresent()) {
return ResponseEntity.unprocessableEntity()
.body("Esse cartão já está vinculado a carteira " + carteiraRequest.getCarteira() + " !");
}
cartaoClient.carteira(cartao.get().getNumero(), new NovaCarteiraRequest(carteiraRequest));
Carteira carteira = carteiraRequest.toModel(cartao.get());
cartao.get().adicionaCarteiraDigital(carteira);
carteiraRepository.save(carteira);
URI location = uriBuilder.path("/cartoes/{id}/carteiras/{id}")
.build(cartao.get().getId(),
carteira.getId());
logger.info("Carteira={} digital criada com sucesso para o email={}!", carteira.getEnumCarteira(),
cartao.get().getNumero());
return ResponseEntity.created(location).build();
} catch (FeignException.UnprocessableEntity ex) {
Map<String, Object> badRequest = new HashMap<>();
badRequest.put("Algum processo interno foi violado", badRequest);
return ResponseEntity.unprocessableEntity().body(badRequest);
}
}
return ResponseEntity.notFound().build();
}
} | 37.416667 | 111 | 0.77422 |
0125f0e3780cc2521ed6d9545be5d54fb326810a | 1,071 | package com.jxq.tools;
import com.alibaba.fastjson.JSONObject;
import com.jxq.douban.domain.MovieResponseVO;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
/**
* @Auther: jx
* @Date: 2018/7/17 17:29
* @Description:
*/
public class RespVoConverterFactory extends Converter.Factory {
public static RespVoConverterFactory create() {
return new RespVoConverterFactory();
}
private RespVoConverterFactory() {
}
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
return new RespVoConverter();
}
public class RespVoConverter implements Converter<ResponseBody, MovieResponseVO> {
@Override
public MovieResponseVO convert(ResponseBody value) throws IOException {
String temp = value.string();
return JSONObject.parseObject(temp, MovieResponseVO.class);
}
}
}
| 26.121951 | 117 | 0.722689 |
69e6ea4a0e7fc0ed82e4f20562dc72c34eb52b70 | 1,910 | package seedu.address.model.person;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.Objects;
//@@author Ang-YC
/**
* Represents a Person's interview date in the address book.
* Guarantees: immutable
*/
public class InterviewDate {
public static final String MESSAGE_INTERVIEW_DATE_XML_ERROR =
"Interview date must be in epoch format, failed to parse from XML";
public static final ZoneOffset LOCAL_ZONE_OFFSET = ZoneId.systemDefault().getRules().getOffset(LocalDateTime.now());
public final LocalDateTime dateTime;
public final String value;
/**
* Constructs a {@code InterviewDate}.
*/
public InterviewDate() {
this((LocalDateTime) null);
}
/**
* Constructs a {@code InterviewDate}.
* @param timestamp A epoch timestamp
*/
public InterviewDate(Long timestamp) {
this(LocalDateTime.ofEpochSecond(timestamp, 0, ZoneOffset.UTC));
}
/**
* Constructs a {@code InterviewDate}.
* @param dateTime of the person
*/
public InterviewDate(LocalDateTime dateTime) {
this.dateTime = dateTime;
if (dateTime != null) {
this.value = String.valueOf(dateTime.toEpochSecond(ZoneOffset.UTC));
} else {
this.value = null;
}
}
public LocalDateTime getDateTime() {
return dateTime;
}
@Override
public String toString() {
return value;
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if (!(other instanceof InterviewDate)) {
return false;
}
InterviewDate i = (InterviewDate) other;
return Objects.equals(getDateTime(), i.getDateTime());
}
@Override
public int hashCode() {
return getDateTime().hashCode();
}
}
| 24.805195 | 120 | 0.626178 |
21c8446bcd9302d50233293ba9909ae349c958c8 | 382 | import java.util.*;
class Test{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
String a = sc.next();
String b = sc.next();
String c = a+a;
if(a.length()==b.length() && c.contains(b)){
System.out.println("true");
}
else{
System.out.println("false");
}
}
}
| 23.875 | 52 | 0.486911 |
7b242a8ed003320232dec17ff7b576c4031dd5d7 | 5,518 | /**
* This class is generated by jOOQ
*/
package org.jooq.test.db2.generatedclasses.tables.records;
/**
* This class is generated by jOOQ.
*/
@java.lang.SuppressWarnings("all")
public class VAuthorRecord extends org.jooq.impl.TableRecordImpl<org.jooq.test.db2.generatedclasses.tables.records.VAuthorRecord> implements org.jooq.Record6<java.lang.Integer, java.lang.String, java.lang.String, java.sql.Date, java.lang.Integer, java.lang.String> {
private static final long serialVersionUID = 1059284710;
/**
* Setter for <code>LUKAS.V_AUTHOR.ID</code>.
*/
public void setId(java.lang.Integer value) {
setValue(org.jooq.test.db2.generatedclasses.tables.VAuthor.ID, value);
}
/**
* Getter for <code>LUKAS.V_AUTHOR.ID</code>.
*/
public java.lang.Integer getId() {
return getValue(org.jooq.test.db2.generatedclasses.tables.VAuthor.ID);
}
/**
* Setter for <code>LUKAS.V_AUTHOR.FIRST_NAME</code>.
*/
public void setFirstName(java.lang.String value) {
setValue(org.jooq.test.db2.generatedclasses.tables.VAuthor.FIRST_NAME, value);
}
/**
* Getter for <code>LUKAS.V_AUTHOR.FIRST_NAME</code>.
*/
public java.lang.String getFirstName() {
return getValue(org.jooq.test.db2.generatedclasses.tables.VAuthor.FIRST_NAME);
}
/**
* Setter for <code>LUKAS.V_AUTHOR.LAST_NAME</code>.
*/
public void setLastName(java.lang.String value) {
setValue(org.jooq.test.db2.generatedclasses.tables.VAuthor.LAST_NAME, value);
}
/**
* Getter for <code>LUKAS.V_AUTHOR.LAST_NAME</code>.
*/
public java.lang.String getLastName() {
return getValue(org.jooq.test.db2.generatedclasses.tables.VAuthor.LAST_NAME);
}
/**
* Setter for <code>LUKAS.V_AUTHOR.DATE_OF_BIRTH</code>.
*/
public void setDateOfBirth(java.sql.Date value) {
setValue(org.jooq.test.db2.generatedclasses.tables.VAuthor.DATE_OF_BIRTH, value);
}
/**
* Getter for <code>LUKAS.V_AUTHOR.DATE_OF_BIRTH</code>.
*/
public java.sql.Date getDateOfBirth() {
return getValue(org.jooq.test.db2.generatedclasses.tables.VAuthor.DATE_OF_BIRTH);
}
/**
* Setter for <code>LUKAS.V_AUTHOR.YEAR_OF_BIRTH</code>.
*/
public void setYearOfBirth(java.lang.Integer value) {
setValue(org.jooq.test.db2.generatedclasses.tables.VAuthor.YEAR_OF_BIRTH, value);
}
/**
* Getter for <code>LUKAS.V_AUTHOR.YEAR_OF_BIRTH</code>.
*/
public java.lang.Integer getYearOfBirth() {
return getValue(org.jooq.test.db2.generatedclasses.tables.VAuthor.YEAR_OF_BIRTH);
}
/**
* Setter for <code>LUKAS.V_AUTHOR.ADDRESS</code>.
*/
public void setAddress(java.lang.String value) {
setValue(org.jooq.test.db2.generatedclasses.tables.VAuthor.ADDRESS, value);
}
/**
* Getter for <code>LUKAS.V_AUTHOR.ADDRESS</code>.
*/
public java.lang.String getAddress() {
return getValue(org.jooq.test.db2.generatedclasses.tables.VAuthor.ADDRESS);
}
// -------------------------------------------------------------------------
// Record6 type implementation
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Row6<java.lang.Integer, java.lang.String, java.lang.String, java.sql.Date, java.lang.Integer, java.lang.String> fieldsRow() {
return org.jooq.impl.DSL.row(field1(), field2(), field3(), field4(), field5(), field6());
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Row6<java.lang.Integer, java.lang.String, java.lang.String, java.sql.Date, java.lang.Integer, java.lang.String> valuesRow() {
return org.jooq.impl.DSL.row(value1(), value2(), value3(), value4(), value5(), value6());
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Field<java.lang.Integer> field1() {
return org.jooq.test.db2.generatedclasses.tables.VAuthor.ID;
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Field<java.lang.String> field2() {
return org.jooq.test.db2.generatedclasses.tables.VAuthor.FIRST_NAME;
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Field<java.lang.String> field3() {
return org.jooq.test.db2.generatedclasses.tables.VAuthor.LAST_NAME;
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Field<java.sql.Date> field4() {
return org.jooq.test.db2.generatedclasses.tables.VAuthor.DATE_OF_BIRTH;
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Field<java.lang.Integer> field5() {
return org.jooq.test.db2.generatedclasses.tables.VAuthor.YEAR_OF_BIRTH;
}
/**
* {@inheritDoc}
*/
@Override
public org.jooq.Field<java.lang.String> field6() {
return org.jooq.test.db2.generatedclasses.tables.VAuthor.ADDRESS;
}
/**
* {@inheritDoc}
*/
@Override
public java.lang.Integer value1() {
return getId();
}
/**
* {@inheritDoc}
*/
@Override
public java.lang.String value2() {
return getFirstName();
}
/**
* {@inheritDoc}
*/
@Override
public java.lang.String value3() {
return getLastName();
}
/**
* {@inheritDoc}
*/
@Override
public java.sql.Date value4() {
return getDateOfBirth();
}
/**
* {@inheritDoc}
*/
@Override
public java.lang.Integer value5() {
return getYearOfBirth();
}
/**
* {@inheritDoc}
*/
@Override
public java.lang.String value6() {
return getAddress();
}
// -------------------------------------------------------------------------
// Constructors
// -------------------------------------------------------------------------
/**
* Create a detached VAuthorRecord
*/
public VAuthorRecord() {
super(org.jooq.test.db2.generatedclasses.tables.VAuthor.V_AUTHOR);
}
}
| 24.524444 | 266 | 0.658753 |
3824c6ddfbb37a24501f8178195fa375055e246c | 1,264 | /*******************************************************************************
* Copyright (c) 2008, 2010 SAP AG.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* SAP AG - initial API and implementation
*******************************************************************************/
package org.eclipse.mat.util;
/**
* Helpers for building HTML reports.
*/
public final class HTMLUtils {
/**
* Escape input text so that characters are not misinterpreted by HTML parsers.
*
* @param text
* @return the escaped text
*/
public static String escapeText(String text) {
final StringBuilder result = new StringBuilder(text.length() * 120 / 100);
for (int ii = 0; ii < text.length(); ii++) {
char ch = text.charAt(ii);
if (ch == '<')
result.append("<");
else if (ch == '>')
result.append(">");
else if (ch == '&')
result.append("&");
else if (ch == '\u00bb')
result.append("»");
else
result.append(ch);
}
return result.toString();
}
private HTMLUtils() {
}
}
| 26.893617 | 81 | 0.563291 |
13f8460530afb9460efd0e986d0f09c041e6c264 | 1,610 | package org.opencds.cqf.cql.elm.execution;
import org.opencds.cqf.cql.execution.Context;
import org.opencds.cqf.cql.runtime.Value;
/*
IndexOf(argument List<T>, element T) Integer
The IndexOf operator returns the 0-based index of the given element in the given source list.
The operator uses the notion of equivalence to determine the index. The search is linear,
and returns the index of the first element that is equivalent to the element being searched for.
If the list is empty, or no element is found, the result is -1.
If the list argument is null, the result is null.
*/
/**
* Created by Bryn on 5/25/2016.
*/
public class IndexOfEvaluator extends org.cqframework.cql.elm.execution.IndexOf {
public static Object indexOf(Object source, Object elementToFind) {
if (source == null) {
return null;
}
int index = -1;
boolean nullSwitch = false;
for (Object element : (Iterable)source) {
index++;
Boolean equiv = EquivalentEvaluator.equivalent(element, elementToFind);
if (equiv == null) {
nullSwitch = true;
}
else if (equiv) {
return index;
}
}
if (nullSwitch) {
return null;
}
return -1;
}
@Override
public Object evaluate(Context context) {
Object source = getSource().evaluate(context);
Object elementToFind = getElement().evaluate(context);
return context.logTrace(this.getClass(), indexOf(source, elementToFind), source, elementToFind);
}
}
| 28.245614 | 104 | 0.637888 |
adb6fa0976debc7b10a620e2d3fbb879342e86a9 | 876 | package com.alibaba.p3c.pmd.lang.java.rule.extend;
import net.sourceforge.pmd.testframework.SimpleAggregatorTst;
public class AliCodeExtendRuleTest extends SimpleAggregatorTst {
private static final String RULESET = "java-ali-extend";
@Override
public void setUp() {
//addRule(RULESET, "MethodParamsNumRule");
//addRule(RULESET, "NoMapParamTypeRule");
//addRule(RULESET, "AvoidTryErrorLogLevelRule");
//addRule(RULESET, "AvoidCatchInfoLogLevelRule");
//addRule(RULESET, "AvoidCommonErrorLogLevelRule");
//addRule(RULESET, "AvoidSystemdoOutRule");
//addRule(RULESET, "AvoidEdoGetMessageRule");
//addRule(RULESET, "RequestMappingRule");
//addRule(RULESET, "LogBlockRule");
addRule(RULESET, "AvoidTestNetworkSegmentRule");
}
}
| 33.692308 | 65 | 0.657534 |
fcf2bade6365e95d64be68c9444ace1b5d8a7e38 | 3,574 | package com.etzwallet.presenter.activities.settings;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.etzwallet.R;
import com.etzwallet.presenter.activities.util.BRActivity;
import com.etzwallet.presenter.customviews.BRDialogView;
import com.etzwallet.tools.animation.BRAnimator;
import com.etzwallet.tools.animation.BRDialog;
import com.etzwallet.tools.manager.BRSharedPrefs;
import com.etzwallet.tools.threads.executor.BRExecutor;
import com.etzwallet.wallet.WalletsMaster;
public class SyncBlockchainActivity extends BRActivity {
private static final String TAG = SyncBlockchainActivity.class.getName();
private Button mRescanButton;
@Override
protected void onSaveInstanceState(Bundle outState) {
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sync_blockchain);
// ImageButton faq = findViewById(R.id.faq_button);
//
// faq.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// if (!BRAnimator.isClickAllowed()) {
// return;
// }
// BaseWalletManager wm = WalletsMaster.getInstance(SyncBlockchainActivity.this).getCurrentWallet(SyncBlockchainActivity.this);
// BRAnimator.showSupportFragment(SyncBlockchainActivity.this, BRConstants.FAQ_RESCAN, wm);
// }
// });
mRescanButton = findViewById(R.id.button_scan);
mRescanButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!BRAnimator.isClickAllowed()) {
return;
}
BRDialog.showCustomDialog(SyncBlockchainActivity.this, getString(R.string.ReScan_alertTitle),
getString(R.string.ReScan_footer), getString(R.string.ReScan_alertAction), getString(R.string.Button_cancel),
new BRDialogView.BROnClickListener() {
@Override
public void onClick(BRDialogView brDialogView) {
brDialogView.dismissWithAnimation();
rescanClicked();
}
}, new BRDialogView.BROnClickListener() {
@Override
public void onClick(BRDialogView brDialogView) {
brDialogView.dismissWithAnimation();
}
}, null, 0);
}
});
}
private void rescanClicked() {
BRExecutor.getInstance().forLightWeightBackgroundTasks().execute(new Runnable() {
@Override
public void run() {
Activity thisApp = SyncBlockchainActivity.this;
BRSharedPrefs.putStartHeight(thisApp, BRSharedPrefs.getCurrentWalletIso(thisApp), 0);
BRSharedPrefs.putAllowSpend(thisApp, BRSharedPrefs.getCurrentWalletIso(thisApp), false);
WalletsMaster.getInstance(thisApp).getCurrentWallet(thisApp).rescan(thisApp);
BRAnimator.startBreadActivity(thisApp, false);
}
});
}
@Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(R.anim.enter_from_left, R.anim.exit_to_right);
}
}
| 38.847826 | 142 | 0.620313 |
f68f0355cdd6c65d7d6f71e220199a70e7498d77 | 2,161 | /*
* 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.glaf.flowable.util;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.flowable.common.engine.impl.db.DbSqlSession;
import io.netty.util.concurrent.FastThreadLocal;
public abstract class ThreadHolder {
static FastThreadLocal<SqlSession> sqlSessionThreadLocal = new FastThreadLocal<SqlSession>();
static FastThreadLocal<DbSqlSession> dbSqlSessionThreadLocal = new FastThreadLocal<DbSqlSession>();
static FastThreadLocal<List<String>> taskIdsThreadLocal = new FastThreadLocal<List<String>>();
public static void clear() {
sqlSessionThreadLocal.remove();
dbSqlSessionThreadLocal.remove();
taskIdsThreadLocal.remove();
}
public static DbSqlSession getDbSqlSession() {
return dbSqlSessionThreadLocal.get();
}
public static SqlSession getSqlSession() {
return sqlSessionThreadLocal.get();
}
public static List<String> getTaskIds() {
return taskIdsThreadLocal.get();
}
public static void removeTaskIds() {
taskIdsThreadLocal.remove();
}
public static void setDbSqlSession(DbSqlSession dbSqlSession) {
dbSqlSessionThreadLocal.set(dbSqlSession);
}
public static void setSqlSession(SqlSession sqlSession) {
sqlSessionThreadLocal.set(sqlSession);
}
public static void setTaskIds(List<String> taskIds) {
taskIdsThreadLocal.set(taskIds);
}
private ThreadHolder() {
}
} | 29.202703 | 100 | 0.771402 |
159e73198558a1983e7130432bbf7514f212560c | 2,284 | package no.uib.inf112.desktop;
import com.badlogic.gdx.Application;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Graphics;
import com.badlogic.gdx.backends.headless.HeadlessApplication;
import com.badlogic.gdx.graphics.GL20;
import no.uib.inf112.core.GameGraphics;
import no.uib.inf112.core.player.IPlayer;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
public class TestGraphics {
// This is our "test" application
private static Application application;
public static final String TEST_MAP_FOLDER = "testmaps";
// Before running any tests, initialize the application with the headless backend
@BeforeClass
public static void init() {
GameGraphics.HEADLESS = true;
application = new HeadlessApplication(mock(ApplicationListener.class));
Gdx.app.setLogLevel(Application.LOG_DEBUG);
// Use Mockito to mock the OpenGL methods since we are running headlessly
Gdx.gl20 = mock(GL20.class);
Gdx.gl = Gdx.gl20;
//run postRunnable at once
Gdx.app = mock(Application.class);
doAnswer(invocation -> {
invocation.getArgumentAt(0, Runnable.class).run();
return null;
}).when(Gdx.app).postRunnable(any(Runnable.class));
Gdx.graphics = mock(Graphics.class);
when(Gdx.graphics.getWidth()).thenReturn(1);
when(Gdx.graphics.getHeight()).thenReturn(1);
}
// After we are done, clean up the application
@AfterClass
public static void cleanUp() {
// Exit the application first
application.exit();
application = null;
}
public void registerFlagVisits(int n, IPlayer player) {
for (int i = 0; i < n; i++) {
player.registerFlagVisit();
}
}
protected IPlayer resetPlayer(IPlayer player) {
GameGraphics.getRoboRally().getCurrentMap().removeEntity(player);
GameGraphics.getRoboRally().getPlayerHandler().removeMainPlayer();
player = GameGraphics.getRoboRally().getPlayerHandler().mainPlayer();
GameGraphics.getRoboRally().getCurrentMap().addEntity(player);
return player;
}
}
| 33.101449 | 85 | 0.687828 |
c0881885e1f67b0dc9414fe0a7300cd6779705c5 | 1,510 | package monCollector.worker;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import monCollector.net.NetMap;
import yuk.Thread.TimerWork;
import yuk.dic.ModelDic;
import yuk.model.MonitorData;
import yuk.model.single.TransactionData;
import yuk.util.CommonLogger;
import yuk.util.NormalUtil;
public class AggreActionThread extends TimerWork{
//key = name::group
private Map<String, TransactionData> cache = new ConcurrentHashMap<String, TransactionData>();
public AggreActionThread() {
super();
}
@Override
public void work() throws Exception {
try {
MonitorData<TransactionData> object = new MonitorData<TransactionData>(ModelDic.SERVER, ModelDic.TYPE_TRANS,null);
for(TransactionData data : cache.values()){
object.dataList.add(data);
}
cache.clear();
ActionNullChecker.putData(cache);
if(object.dataList.size() > 0)
NetMap.send(object);
} catch (Exception e) {
CommonLogger.getLogger().error(getClass(), "can't aggregate transaction", e);
}
}
@Override
public void preWork() throws Exception {
}
public void aggre(Collection<TransactionData> dataSet) throws Exception {
for(TransactionData data : dataSet){
String key = NormalUtil.makeKey("::", data.name,data.command);
if(cache.containsKey(key)){
TransactionData old = cache.get(key);
old.modelAdd(data, true);
}
else{
cache.put(key, data);
}
}
}
}
| 25.59322 | 119 | 0.696689 |
ce7fe079d2e4acfcab41a2dc5a1cf465d28b293e | 9,125 | import javax.crypto.SecretKey;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.ParseException;
public class RsaOverAes {
private final static String helpArgumentText = "RSAoverAES Version 1.0.2\n\n" +
"This Programm Outputs a 128 Bit AES-KEY in GCM Mode with No Padding,\nwhich is then " +
"Encrypted via the RSA Pbulic Key Algorithm.\n" +
"Optionally you can specify a file which is encrypted with the 128 Bit AES Key\nthat " +
"will then be saved encrypted via RSA.\n\n" +
"CommandLine Arguments:\n" +
"\n" +
" -encrypt Set Mode to Generate RSA encrypted AES File and encrypt File\n" +
" -fileToEncrypt Specify a File to be Encrypted via AES/GCM/NoPadding - 128Bit\n" +
" -pubKey Specify a RSA-Public Key to encrypt the AES KeyFile with (mandatory with -encrypt)\n" +
"\n" +
" -decrypt Set Mode to decrypt the AESKey File using RSA Private Key and decrypt File\n" +
" -fileToDecrypt Specify a File to Decrypt\n" +
" -aesKey Specify the RSA/OAEP/SHA512withMGF1 Encrypted AES-Key File to decrypt (mandatory with -decrypt)\n" +
" -privKey Specify the RSA Private key for decrypting the AES-Key File (mandatory with -decrypt)\n" +
"\n" +
"* Use these Commands to create the RSA Private-PKCS8 + PublicKey in openssl\n" +
"\n" +
" * openssl genrsa -out privatekey.pem 4096\n" +
" * openssl rsa -in privatekey.pem -out publickey.pem -pubout\n" +
" * openssl pkcs8 -in privatekey.pem -topk8 -nocrypt -out privatekey-pkcs8.pem\n" +
" * rm privatekey.pem\n" +
"\n"
+"For more Information see: https://github.com/eXspir3/RSAoverAES";
private final static String greeting =
"\n\n===================================================\n" +
"RSAoverAES Version 1.0.2 - Author: Philipp Ensinger\n" +
"===================================================\n";
private final static boolean keepFile = true;
private final static boolean deleteFile = false;
public static void main(String[] args) throws IOException, GeneralSecurityException {
EncryptionHandler rsaOverAesHandler = new EncryptionHandler();
Path pubKey;
Path fileToEncrypt;
Path privKey;
Path fileToDecrypt;
Path aesKey;
CommandLine commandLine;
System.out.println(greeting);
Option option_help = Option.builder("help").required(false).desc("Show HelpPage").build();
Option option_encrypt = Option.builder("encrypt").required(false).desc("Set Mode to Generate RSA encrypted AES File and encrypt File").build();
Option option_decrypt = Option.builder("decrypt").required(false).desc("Set Mode to decrypt the AESKey File using RSA Private Key and decrypt File").build();
Option option_pubKey = Option.builder("pubKey").required(false).desc("Set RSA PublicKey").hasArg().build();
Option option_privKey = Option.builder("privKey").required(false).desc("Set RSA privateKey").hasArg().build();
Option option_aesKey = Option.builder("aesKey").required(false).desc("Set Encrypted AES-Key File to decrypt").hasArg().build();
Option option_fileToEncrypt = Option.builder("fileToEncrypt").required(false).desc("Specify a File to Encrypt").hasArg().build();
Option option_fileToDecrypt = Option.builder("fileToDecrypt").required(false).desc("Specify a File to Decrypt").hasArg().build();
Options options = new Options();
CommandLineParser parser = new DefaultParser();
options.addOption(option_pubKey);
options.addOption(option_privKey);
options.addOption(option_aesKey);
options.addOption(option_fileToEncrypt);
options.addOption(option_fileToDecrypt);
options.addOption(option_help);
options.addOption(option_encrypt);
options.addOption(option_decrypt);
try {
commandLine = parser.parse(options, args);
if (commandLine.hasOption("help")) {
System.out.println(helpArgumentText);
System.exit(0);
}
if (commandLine.hasOption("encrypt")) {
if (commandLine.hasOption("pubKey") && commandLine.hasOption("fileToEncrypt")) {
pubKey = Paths.get(commandLine.getOptionValue("pubKey"));
System.out.println("Generating RSA-Encrypted AES-KeyFile");
System.out.println("Using RSA PublicKey to encrypt AES-KeyFile: " + pubKey.toString());
/*
* Generate and save the AES Key RSA encrypted to File.
*/
SecretKey AESKey = rsaOverAesHandler.generateAESandEncryptRSA(pubKey, deleteFile, getCurrentTimeStamp());
/*
* Encrypt the provided File using AESKey
*/
fileToEncrypt = Paths.get(commandLine.getOptionValue("fileToEncrypt"));
System.out.println("Encrypting File: " + fileToEncrypt.toString() + " with AES-128 GCM / NOPadding");
rsaOverAesHandler.encryptFile(fileToEncrypt, AESKey);
} else if (commandLine.hasOption("pubKey")) {
pubKey = Paths.get(commandLine.getOptionValue("pubKey"));
System.out.println("Generating RSA-Encrypted AES-KeyFile");
System.out.println("Using RSA PublicKey to encrypt AES-KeyFile: " + pubKey.toString());
/*
* Generate and save the AES Key RSA encrypted to File.
*/
rsaOverAesHandler.generateAESandEncryptRSA(pubKey, deleteFile, getCurrentTimeStamp());
System.out.println("Only generated RSA Encrypted AES-Key-File as no -fileToEncrypt was specified");
} else {
throw new ParseException("At least -pubKey has to be specified when using -encrypt\nBe sure to pay Attention to case-sensitivity!");
}
}
if (commandLine.hasOption("decrypt")) {
if (commandLine.hasOption("privKey") && commandLine.hasOption("aesKey") && commandLine.hasOption("fileToDecrypt")) {
privKey = Paths.get(commandLine.getOptionValue("privKey"));
aesKey = Paths.get(commandLine.getOptionValue("aesKey"));
System.out.println("Decrypting RSA Encrypted AES-Key-File: " + aesKey.toString());
System.out.println("Using RSA PrivateKey to decrypt AES-KeyFile: " + privKey.toString());
/*
* Decrypt AES-Key and save to File unencrypted
*/
SecretKey AESKey = rsaOverAesHandler.decryptAESKeyAndLoad(aesKey, privKey, keepFile, deleteFile);
/*
* Decrypt the provided File using AESKey
*/
fileToDecrypt = Paths.get(commandLine.getOptionValue("fileToDecrypt"));
rsaOverAesHandler.decryptFile(fileToDecrypt, AESKey);
} else if (commandLine.hasOption("privKey") && commandLine.hasOption("aesKey")) {
privKey = Paths.get(commandLine.getOptionValue("privKey"));
aesKey = Paths.get(commandLine.getOptionValue("aesKey"));
System.out.println("Decrypting RSA Encrypted AES-Key-File: " + aesKey.toString());
System.out.println("Using RSA PrivateKey to decrypt AES-KeyFile: " + privKey.toString());
/*
* Decrypt and save the decrypted AES Key to File.
*/
rsaOverAesHandler.decryptAESKeyAndLoad(aesKey, privKey, keepFile, keepFile);
System.out.println("Only decrypted RSA Encrypted AES-Key-File as no -fileToDecrypt was specified");
} else {
throw new ParseException("At least -privKey and -aesKey has to be specified when using -decrypt\nBe sure to pay Attention to case-sensitivity!");
}
}
} catch (ParseException exception) {
System.out.print("Parse error: ");
System.out.println(exception.getMessage());
System.exit(-1);
}
}
private static String getCurrentTimeStamp() {
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
Date now = new Date();
return sdfDate.format(now);
}
}
| 53.362573 | 165 | 0.604932 |
fb9d45b72e592c9267276495874cf3283cdadad9 | 1,112 | package org.kevin.codec;
import org.kevin.enums.Command;
public class QueryEncoder extends CommandEncoder {
private final String term;
private int limit;
private int offset;
public QueryEncoder(String collection, String bucket, String term, int limit, int offset){
super(collection, bucket);
this.term = term;
this.limit = limit;
this.offset = offset;
}
@Override
public void wrapperCommand(StringBuffer sb) {
//command
sb.append(this.getCommand());
sb.append(" ");
//query term
sb.append(this.getCollection().trim());
sb.append(" ");
sb.append(this.getBucket().trim());
sb.append(" ");
sb.append(escape(term.trim()));
sb.append(" ");
//limit
if(limit > -1){
sb.append("LIMIT(").append(limit).append(")").append(" ");
}
//offset
if(offset > -1){
sb.append("OFFSET(").append(offset).append(")");
}
}
@Override
public String getCommand() {
return Command.QUERY.name();
}
}
| 25.272727 | 94 | 0.556655 |
1843469322636a1384fb0e994b161cae2c05d8e6 | 168 | package de.vogella.plugin.adapter;
import org.eclipse.ui.views.contentoutline.ContentOutlinePage;
public class TodoOutlinePage extends ContentOutlinePage {
}
| 21 | 63 | 0.803571 |
0672a24ae09c415d18f1fcfacaf9527b47ffacc2 | 5,657 | package fr.insa.h4401.gfaim;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.github.aakira.expandablelayout.Utils;
import com.github.clans.fab.FloatingActionMenu;
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;
import com.wdullaer.materialdatetimepicker.time.RadialPickerLayout;
import com.wdullaer.materialdatetimepicker.time.TimePickerDialog;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link AlarmsFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link AlarmsFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class AlarmsFragment extends Fragment implements TimePickerDialog.OnTimeSetListener {
private OnFragmentInteractionListener mListener;
static final List<ItemModel> data = new ArrayList<>();
static RecyclerView recyclerView;
public AlarmsFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @return A new instance of fragment AlarmsFragment.
*/
// TODO: Rename and change types and number of parameters
public static AlarmsFragment newInstance() {
AlarmsFragment fragment = new AlarmsFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_alarms, container, false);
final FloatingActionMenu fab = (FloatingActionMenu) v.findViewById(R.id.alarm_add_button);
final TimePickerDialog.OnTimeSetListener that = this;
fab.setOnMenuButtonClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Calendar now = Calendar.getInstance();
TimePickerDialog dpd = TimePickerDialog.newInstance(that,
now.get(Calendar.HOUR_OF_DAY),
now.get(Calendar.MINUTE),
true);
dpd.show(getActivity().getFragmentManager(), "TimePickerDialog");
}
});
recyclerView = (RecyclerView) v.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
if(data.isEmpty()){
data.add(new ItemModel(
"11:55",
Utils.createInterpolator(Utils.FAST_OUT_SLOW_IN_INTERPOLATOR),
false));
data.add(new ItemModel(
"12:55",
Utils.createInterpolator(Utils.FAST_OUT_SLOW_IN_INTERPOLATOR),
false));
}
recyclerView.setAdapter(new RecyclerViewRecyclerAdapter(data));
return v;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
// if (context instanceof OnFragmentInteractionListener) {
// mListener = (OnFragmentInteractionListener) context;
// } else {
// throw new RuntimeException(context.toString()
// + " must implement OnFragmentInteractionListener");
// }
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute, int second) {
String hour;
String min;
if (hourOfDay < 10)
hour = "0" + hourOfDay;
else hour = "" + hourOfDay;
if (minute < 10)
min = "0" + minute;
else min = "" + minute;
data.add(new ItemModel(
hour + ":" + min,
Utils.createInterpolator(Utils.FAST_OUT_SLOW_IN_INTERPOLATOR),
true));
recyclerView.setAdapter(new RecyclerViewRecyclerAdapter(data));
}
public static void remove(ItemModel item) {
data.remove(item);
recyclerView.setAdapter(new RecyclerViewRecyclerAdapter(data));
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
| 33.473373 | 98 | 0.655825 |
3c0ac703cedcedf20484ab3bda177a09597d033e | 6,216 | package cz.kb.openbanking.adaa.client.api.model;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* Contains basic information about current page with elements.
*
* @param <T> type of elements on the page
* @author <a href="mailto:aleh_kuchynski@kb.cz">Aleh Kuchynski</a>
* @since 1.0
*/
public class PageSlice<T> {
/**
* List of elements.
*/
private List<T> content;
/**
* Total number of pages.
*/
private int totalPages;
/**
* Current page number.
*/
private int pageNumber;
/**
* PageSlice size.
*/
private int pageSize;
/**
* Number of elements on the current page.
*/
private int numberOfElements;
/**
* Is the first page.
*/
private boolean first;
/**
* Is the last page.
*/
private boolean last;
/**
* Is the current page empty.
*/
private boolean empty;
/**
* New instance.
*
* @param content list of elements
* @param totalPages total number of pages
* @param pageNumber number of page
* @param pageSize page size
* @param numberOfElements number of elements on the current page
* @param first is the first page
* @param last is the last page
* @param empty is the current page empty
*/
@JsonCreator
public PageSlice(@JsonProperty("content") Collection<T> content, @JsonProperty("totalPages") int totalPages,
@JsonProperty("pageNumber") int pageNumber, @JsonProperty("pageSize") int pageSize,
@JsonProperty("numberOfElements") int numberOfElements, @JsonProperty("first") boolean first,
@JsonProperty("last") boolean last, @JsonProperty("empty") boolean empty)
{
if (content == null) {
throw new IllegalArgumentException("content must not be null");
}
if (totalPages < 0) {
throw new IllegalArgumentException("totalPages must be greater or equal to zero");
}
if (pageNumber < 0) {
throw new IllegalArgumentException("pageNumber must be greater or equal to zero");
}
if (pageSize <= 0) {
throw new IllegalArgumentException("pageSize must be greater to zero");
}
if (numberOfElements < 0) {
throw new IllegalArgumentException("numberOfElements must be greater or equal to zero");
}
this.content = new ArrayList<>(content);
this.totalPages = totalPages;
this.pageNumber = pageNumber;
this.pageSize = pageSize;
this.numberOfElements = numberOfElements;
this.first = first;
this.last = last;
this.empty = empty;
}
/**
* Gets page content.
*
* @return page content
*/
public List<T> getContent() {
return Collections.unmodifiableList(content);
}
/**
* Gets number of total pages.
*
* @return number of total pages
*/
public int getTotalPages() {
return totalPages;
}
/**
* Gets number of the current page.
*
* @return number of the current page
*/
public int getPageNumber() {
return pageNumber;
}
/**
* Gets page size.
*
* @return page size
*/
public int getPageSize() {
return pageSize;
}
/**
* Gets number of all elements.
*
* @return number of all elements
*/
public int getNumberOfElements() {
return numberOfElements;
}
/**
* Gets if the last page is the first one.
*
* @return if the last page is the first one
*/
public boolean isFirst() {
return first;
}
/**
* Gets if the last page is the last one.
*
* @return if the last page is the last one
*/
public boolean isLast() {
return last;
}
/**
* Gets if the last page is empty.
*
* @return if the last page is empty
*/
public boolean isEmpty() {
return empty;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof PageSlice)) {
return false;
}
final PageSlice<?> pageSlice = (PageSlice<?>) o;
return new EqualsBuilder()
.append(getTotalPages(), pageSlice.getTotalPages())
.append(getPageNumber(), pageSlice.getPageNumber())
.append(getPageSize(), pageSlice.getPageSize())
.append(getNumberOfElements(), pageSlice.getNumberOfElements())
.append(isFirst(), pageSlice.isFirst())
.append(isLast(), pageSlice.isLast())
.append(isEmpty(), pageSlice.isEmpty())
.append(getContent(), pageSlice.getContent())
.isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder(17, 37)
.append(getContent())
.append(getTotalPages())
.append(getPageNumber())
.append(getPageSize())
.append(getNumberOfElements())
.append(isFirst())
.append(isLast())
.append(isEmpty())
.toHashCode();
}
@Override
public String toString() {
return new ToStringBuilder(this)
.append("content", content)
.append("totalPages", totalPages)
.append("pageNumber", pageNumber)
.append("pageSize", pageSize)
.append("numberOfElements", numberOfElements)
.append("first", first)
.append("last", last)
.append("empty", empty)
.toString();
}
}
| 26.909091 | 114 | 0.563546 |
5a7d7e1e31694fe2e951758c25d2ce580716aa38 | 1,416 | package l.c.x;
import com.mojang.authlib.Agent;
import com.mojang.authlib.exceptions.AuthenticationException;
import com.mojang.authlib.yggdrasil.YggdrasilAuthenticationService;
import com.mojang.authlib.yggdrasil.YggdrasilUserAuthentication;
import java.net.Proxy;
import net.minecraft.util.Session;
public class e {
public static final int fur;
public static final boolean fik;
public static Session d(String var0, String var1) {
if (var0 != null && var0.length() > 0 && var1 != null && var1.length() > 0) {
YggdrasilAuthenticationService var2 = new YggdrasilAuthenticationService(Proxy.NO_PROXY, "");
YggdrasilUserAuthentication var3 = (YggdrasilUserAuthentication)var2.createUserAuthentication(Agent.MINECRAFT);
var3.setUsername(var0);
var3.setPassword(var1);
Session var10000;
try {
var3.logIn();
var10000 = new Session(var3.getSelectedProfile().getName(), var3.getSelectedProfile().getId().toString(), var3.getAuthenticatedToken(), "LEGACY");
} catch (AuthenticationException var8) {
var8.printStackTrace();
System.out.println("Failed login: " + var0 + ":" + var1);
return null;
}
return var10000;
} else {
return null;
}
}
public static Session ft(String var0) {
return new Session(var0, "", "", "LEGACY");
}
}
| 34.536585 | 158 | 0.663136 |
07e8fa97e59c3bcafcdfa6654e7265b5ad518ad4 | 1,064 | package pers.brian.mall.modules.sms.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import pers.brian.mall.modules.sms.model.SmsHomeAdvertise;
import pers.brian.mall.modules.sms.mapper.SmsHomeAdvertiseMapper;
import pers.brian.mall.modules.sms.service.SmsHomeAdvertiseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* <p>
* 首页轮播广告表 服务实现类
* </p>
*
* @author BrianHu
* @since 2021-12-01
*/
@Service
public class SmsHomeAdvertiseServiceImpl extends ServiceImpl<SmsHomeAdvertiseMapper, SmsHomeAdvertise> implements SmsHomeAdvertiseService {
@Override
public List<SmsHomeAdvertise> getHomeBanners() {
QueryWrapper<SmsHomeAdvertise> queryWrapper = new QueryWrapper<>();
queryWrapper.lambda()
.eq(SmsHomeAdvertise::getType, 0)
.eq(SmsHomeAdvertise::getStatus, 1)
.orderByAsc(SmsHomeAdvertise::getSort);
return this.list(queryWrapper);
}
}
| 32.242424 | 139 | 0.744361 |
1277f990675d95c3a362daaede6e38659a28de23 | 8,425 | /*
* MIT License
*
* Copyright (c) 2016 Kungliga Tekniska högskolan
*
* 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 se.kth.infosys.smx.alma.internal;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.support.ExchangeHelper;
import org.apache.commons.beanutils.PropertyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import se.kth.infosys.alma.AlmaUserService;
import se.kth.infosys.smx.alma.model.User;
import se.kth.infosys.smx.alma.model.UserIdentifier;
import se.kth.infosys.smx.alma.model.UserIdentifiers;
import se.kth.infosys.smx.alma.model.WebServiceResult;
import javax.ws.rs.BadRequestException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.HashSet;
/**
* Wrapper class translating exchanges to AlmaUserService requests.
*/
public class UserServiceWrapper {
private final Logger log = LoggerFactory.getLogger(getClass());
private final AlmaUserService userService;
private final HashSet<String> NO_UPDATE_PROPERTIES = new HashSet<>(Collections.singletonList("externalId"));
/**
* Constructor
* @param host the Alma service environment.
* @param apiKey the API key to use.
* @throws Exception on errors.
*/
public UserServiceWrapper(final String host, final String apiKey) throws Exception {
userService = new AlmaUserService(host, apiKey);
}
/**
* Get result from AlmaUserService.updateUser() and store in exchange.
* @param exchange the Camel exchange.
* @throws Exception on errors.
*/
public void updateUser(final Exchange exchange) throws Exception {
final Message in = exchange.getIn();
in.setHeader(AlmaMessage.Header.Status, AlmaMessage.Status.Failed);
User user = exchange.getIn().getMandatoryBody(User.class);
User currentUser = getUserByUser(user);
copyPropertiesFromTo(currentUser, user);
log.debug("Updating user with id {} in ALMA", currentUser.getPrimaryId());
in.setBody(userService.updateUser(user, currentUser.getPrimaryId()));
in.setHeader(AlmaMessage.Header.Status, AlmaMessage.Status.Ok);
}
private void copyPropertiesFromTo(User from, User to) throws Exception {
for (PropertyDescriptor property : PropertyUtils.getPropertyDescriptors(User.class)) {
if (NO_UPDATE_PROPERTIES.contains(property.getName())) {
log.debug("Copying property {}", property.getName());
Method read = property.getReadMethod();
Method write = property.getWriteMethod();
if (read.invoke(from) != null) {
write.invoke(to, read.invoke(from));
}
}
}
}
/**
* Update user if exists, otherwise create it.
* @param exchange the Camel exchange.
* @throws Exception on errors.
*/
public void createOrUpdateUser(final Exchange exchange) throws Exception {
try {
updateUser(exchange);
} catch (BadRequestException e) {
if (e.getResponse().getStatus() != 400) {
log.error("Failed to update user", e);
throw e;
}
WebServiceResult res = e.getResponse().readEntity(WebServiceResult.class);
if (! AlmaUserService.USER_NOT_FOUND.equals(res.getErrorList().getError().get(0).getErrorCode())) {
log.error("Failed to update user", e);
throw e;
}
e.getResponse().close();
log.debug("Could not update non-existing user in Alma, creating instead.");
createUser(exchange);
}
}
/**
* Get result from AlmaUserService.createUser() and store in exchange.
* @param exchange the Camel exchange.
* @throws Exception on errors.
*/
public void createUser(final Exchange exchange) throws Exception {
final Message in = exchange.getIn();
in.setHeader(AlmaMessage.Header.Status, AlmaMessage.Status.Failed);
User user = in.getMandatoryBody(User.class);
try {
log.debug("Creating user with id {} in ALMA", user.getPrimaryId());
in.setBody(userService.createUser(user));
in.setHeader(AlmaMessage.Header.Status, AlmaMessage.Status.Ok);
} catch (BadRequestException e) {
if (e.getResponse().getStatus() != 400) {
log.error("Failed to create user", e);
} else {
WebServiceResult res = e.getResponse().readEntity(WebServiceResult.class);
String code = res.getErrorList().getError().get(0).getErrorCode();
String message = res.getErrorList().getError().get(0).getErrorMessage();
log.error("Code: " + code + ", message: " + message, e);
e.getResponse().close();
}
throw e;
}
}
/**
* Get result from AlmaUserService.getUser() and store in exchange.
* @param exchange the Camel exchange.
* @throws Exception on errors.
*/
public void getUser(final Exchange exchange) throws Exception {
final Message in = exchange.getIn();
in.setHeader(AlmaMessage.Header.Status, AlmaMessage.Status.Failed);
if (in.getHeader(AlmaMessage.Header.UserId) != null) {
in.setBody(getUserById(in.getHeader(AlmaMessage.Header.UserId, String.class)));
} else {
in.setBody(getUserByUser(in.getMandatoryBody(User.class)));
}
in.setHeader(AlmaMessage.Header.Status, AlmaMessage.Status.Ok);
}
private User getUserByUser(User user) {
UserIdentifiers identifiers = user.getUserIdentifiers();
for (UserIdentifier identifier : identifiers.getUserIdentifier()) {
try {
log.debug("Finding user by identifer: {}: {}",
identifier.getIdType().getValue(),
identifier.getValue());
return userService.getUser(identifier.getValue());
} catch (Exception e) {
log.debug("Failed to get User {}. Caught exception {}.", user, e);
}
}
return userService.getUser(user.getPrimaryId());
}
private User getUserById(String userId) {
log.debug("Getting user with id {} from ALMA", userId);
return userService.getUser(userId);
}
/**
* Run AlmaUserService.deleteUser(), produces no output.
* @param exchange the Camel exchange.
* @throws Exception on errors.
*/
public void deleteUser(final Exchange exchange) throws Exception {
final Message in = exchange.getIn();
in.setHeader(AlmaMessage.Header.Status, AlmaMessage.Status.Failed);
String userId = ExchangeHelper.getMandatoryHeader(exchange, AlmaMessage.Header.UserId, String.class);
log.debug("Getting user with id {} from ALMA", userId);
if (userService.deleteUser(userId)) {
log.debug("User with id {} deleted from Alma.", userId);
in.setHeader(AlmaMessage.Header.Status, AlmaMessage.Status.Ok);
} else {
log.debug("User with id {} NOT deleted from Alma, maybe not found.", userId);
in.setHeader(AlmaMessage.Header.Status, AlmaMessage.Status.Failed);
}
}
}
| 41.707921 | 112 | 0.654243 |
6cf76b5932a01fde3e90c2e9870594ed16dc661c | 2,836 | /*
* This file is part of the Solid TX project.
*
* Copyright (c) 2015. sha1(OWNER) = df334a7237f10846a0ca302bd323e35ee1463931
* --> See LICENSE.txt for more information.
*
* @author BinaryBabel OSS (http://code.binbab.org)
*/
package org.binarybabel.solidtx.core.network;
import org.binarybabel.solidtx.core.storage.StorageIndex;
import java.util.concurrent.ConcurrentLinkedQueue;
/**
* Links network Gateway to a set of DataRequests in order
* to request/fetch the next Payload.
*
* @see Gateway
* @see DataRequest
* @see PayloadRequest
* @see Payload
*/
public class PayloadBus {
protected Gateway gateway;
protected int channel;
protected ConcurrentLinkedQueue<DataRequest> dataRequests; // non-blocking, fifo
protected PayloadRequest pendingPayloadRequest;
/**
* Create new PayloadBus for a specific gateway,
* on a channel id used to align it with other
* stack services.
*
* @param gateway the network gateway
* @param channel the channel id
*/
public PayloadBus(Gateway gateway, int channel) {
this.gateway = gateway;
this.channel = channel;
this.dataRequests = new ConcurrentLinkedQueue<DataRequest>();
}
public Gateway getGateway() {
return gateway;
}
public int getChannel() {
return channel;
}
/**
* Add data request for the next payload.
*
* @param request the request to add
*/
public void addDataRequest(DataRequest request) {
dataRequests.add(request);
}
/**
* Get the next payload responding to all new data requests,
* as well as requesting updates to existing stored entities.
*
* If the last payload was not received successfully then the
* previous payload will be requested again and existing data
* requests will remain on the bus.
*
* WARNING: This network operation occurs synchronously on the
* gateway and will block the thread.
*
* @param storageIndex the index the storage container on this channel
* @return the payload
* @throws NetworkException on network error
*/
public Payload getNextPayload(StorageIndex storageIndex) throws NetworkException {
if (pendingPayloadRequest == null) {
// Request queue will be emptied into new request.
pendingPayloadRequest = new PayloadRequest(dataRequests, storageIndex);
}
Payload p;
try {
p = getGateway().getPayload(pendingPayloadRequest);
} catch (NetworkException e) {
pendingPayloadRequest.attempts++;
pendingPayloadRequest.lastError = e;
throw e;
}
pendingPayloadRequest.respondWithPayload(p);
pendingPayloadRequest = null;
return p;
}
}
| 28.646465 | 86 | 0.661495 |
6c03c99d0f6e27f2b5a795b0024efaf6564651d2 | 4,315 | /*
* Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
@test
@bug 6852592
@summary invalidate() must stop when it encounters a validate root
@author anthony.petrov@sun.com
@run main/othervm -Djava.awt.smartInvalidate=true InvalidateMustRespectValidateRoots
*/
import javax.swing.*;
import java.awt.event.*;
public class InvalidateMustRespectValidateRoots {
private static volatile JRootPane rootPane;
public static void main(String args[]) throws Exception {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
// The JRootPane is a validate root. We'll check if
// invalidate() stops on the root pane, or goes further
// up to the frame.
JFrame frame = new JFrame();
final JButton button = new JButton();
frame.add(button);
// To enable running the test manually: use the Ctrl-Shift-F1
// to print the component hierarchy to the console
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
if (button.isValid()) {
button.invalidate();
} else {
button.revalidate();
}
}
});
rootPane = frame.getRootPane();
// Now the component hierarchy looks like:
// frame
// --> rootPane
// --> layered pane
// --> content pane
// --> button
// Make all components valid first via showing the frame
// We have to make the frame visible. Otherwise revalidate() is
// useless (see RepaintManager.addInvalidComponent()).
frame.pack(); // To enable running this test manually
frame.setVisible(true);
if (!frame.isValid()) {
throw new RuntimeException(
"setVisible(true) failed to validate the frame");
}
// Now invalidate the button
button.invalidate();
// Check if the 'valid' status is what we expect it to be
if (rootPane.isValid()) {
throw new RuntimeException(
"invalidate() failed to invalidate the root pane");
}
if (!frame.isValid()) {
throw new RuntimeException(
"invalidate() invalidated the frame");
}
// Now validate the hierarchy again
button.revalidate();
// Now let the validation happen on the EDT
}
});
Thread.sleep(1000);
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
// Check if the root pane finally became valid
if (!rootPane.isValid()) {
throw new RuntimeException(
"revalidate() failed to validate the hierarchy");
}
}
});
}
}
| 37.521739 | 86 | 0.554809 |
9b57526a7cd2862bb7c935702629a3d0ea5dd889 | 323 | package com.cometchat.pro.androiduikit.constants;
public class AppConfig {
public class AppDetails {
public static final String APP_ID = "202691892d6697c9";
public static final String AUTH_KEY = "eac1d5120eaf7f5eb1fae02d94f53912c7af1514";
public static final String REGION = "eu";
}
}
| 21.533333 | 89 | 0.71517 |
d8fa2d77dd7f00af4ce5944c04cecbdd7d0f2e1b | 1,843 | package net.Nephty.rgbee.data.features;
import net.Nephty.rgbee.Rgbee;
import net.Nephty.rgbee.setup.ModBlocks;
import net.minecraft.block.Block;
import net.minecraft.util.registry.Registry;
import net.minecraft.util.registry.WorldGenRegistries;
import net.minecraft.world.gen.GenerationStage;
import net.minecraft.world.gen.blockplacer.SimpleBlockPlacer;
import net.minecraft.world.gen.blockstateprovider.WeightedBlockStateProvider;
import net.minecraft.world.gen.feature.*;
import net.minecraftforge.event.world.BiomeLoadingEvent;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.registries.DeferredRegister;
import net.minecraftforge.registries.ForgeRegistries;
public class EnchantedFlowerGeneration {
public static final BlockClusterFeatureConfig ENCHANTED_DEFAULT_FLOWER_CONFIG = (new BlockClusterFeatureConfig.Builder((new WeightedBlockStateProvider()).add(ModBlocks.ENCHANTED_FLOWER.get().defaultBlockState(), 2), SimpleBlockPlacer.INSTANCE)).tries(64).build();
public static final ConfiguredFeature<?, ?> ENCHANTED_FLOWER_DEFAULT = register("enchanted_flower_default", Feature.FLOWER.configured(ENCHANTED_DEFAULT_FLOWER_CONFIG).decorated(Features.Placements.ADD_32).decorated(Features.Placements.HEIGHTMAP_SQUARE).count(2));
private static <FC extends IFeatureConfig> ConfiguredFeature<FC, ?> register(String p_243968_0_, ConfiguredFeature<FC, ?> p_243968_1_) {
return Registry.register(WorldGenRegistries.CONFIGURED_FEATURE, p_243968_0_, p_243968_1_);
}
public static void addFlowers(final BiomeLoadingEvent event) {
addFlower(event);
}
private static void addFlower(final BiomeLoadingEvent event) {
event.getGeneration().addFeature(GenerationStage.Decoration.TOP_LAYER_MODIFICATION, ENCHANTED_FLOWER_DEFAULT);
}
}
| 54.205882 | 268 | 0.805751 |
6a326eaf1c226f6ac1358a3841313603815c4050 | 4,082 | package br.ufrpe.wanderlustapp.hopitais.persistencia;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.List;
import br.ufrpe.wanderlustapp.cidade.persistencia.CidadeDAO;
import br.ufrpe.wanderlustapp.hopitais.dominio.Hospitais;
import br.ufrpe.wanderlustapp.infra.persistencia.AbstractDAO;
import br.ufrpe.wanderlustapp.infra.persistencia.DBHelper;
import br.ufrpe.wanderlustapp.pontoTuristico.dominio.PontoTuristico;
public class HospitaisDAO extends AbstractDAO {
private SQLiteDatabase db;
private DBHelper helper;
private Context context;
public HospitaisDAO(Context context) {
this.context = context;
helper = new DBHelper(context);
}
private ContentValues getContentValues(Hospitais hospital) {
ContentValues values = new ContentValues();
values.put(DBHelper.CAMPO_FK_CIDADE_HOSPITAL, hospital.getCidade().getId());
values.put(DBHelper.CAMPO_NOME_HOSPITAL, hospital.getNome());
values.put(DBHelper.CAMPO_DESCRICAO_HOSPITAL, hospital.getDescricao());
return values;
}
private Cursor getCursor(List<Hospitais> hospitais, String sql) {
Cursor cursor = db.rawQuery(sql, new String[]{});
while (cursor.moveToNext()){
hospitais.add(createHospitais(cursor));
}
return cursor;
}
private void setsHospitais(Cursor cursor, Hospitais hospitais, CidadeDAO cidadeDAO) {
int columnIndex = cursor.getColumnIndex(DBHelper.CAMPO_ID_HOSPITAIL);
hospitais.setId(Integer.parseInt(cursor.getString(columnIndex)));
columnIndex = cursor.getColumnIndex(DBHelper.CAMPO_NOME_HOSPITAL);
hospitais.setNome(cursor.getString(columnIndex));
columnIndex = cursor.getColumnIndex(DBHelper.CAMPO_DESCRICAO_HOSPITAL);
hospitais.setDescricao(cursor.getString(columnIndex));
columnIndex = cursor.getColumnIndex(DBHelper.CAMPO_FK_CIDADE_HOSPITAL);
hospitais.setCidade(cidadeDAO.getCidade(cursor.getInt(columnIndex)));
}
public Hospitais getPontoTuristicoById(long id) {
Hospitais hospital = null;
db = helper.getReadableDatabase();
String sql = "SELECT * FROM " + DBHelper.TABELA_HOSPITAIS + " WHERE " + DBHelper.CAMPO_ID_HOSPITAIL + " LIKE ?;";
Cursor cursor = db.rawQuery(sql, new String[]{Long.toString(id)});
hospital = getHospital(hospital, cursor);
super.close(cursor, db);
return hospital;
}
private Hospitais getHospital(Hospitais hospital, Cursor cursor) {
if (cursor.moveToFirst()) {
hospital = createHospitais(cursor);
}
return hospital;
}
public Hospitais getPHospitalByNome(String nome) {
Hospitais hospital= null;
db = helper.getReadableDatabase();
String sql = "SELECT * FROM " + DBHelper.TABELA_HOSPITAIS + " WHERE " + DBHelper.CAMPO_NOME_HOSPITAL + " LIKE ?;";
Cursor cursor = db.rawQuery(sql, new String[]{nome});
hospital = getHospital(hospital, cursor);
super.close(cursor, db);
return hospital;
}
public List<Hospitais> getListHospitais(){
List<Hospitais> hospitais = new ArrayList<Hospitais>();
db = helper.getReadableDatabase();
String sql = "SELECT * FROM " + DBHelper.TABELA_HOSPITAIS;
Cursor cursor = getCursor(hospitais, sql);
cursor.close();
db.close();
return hospitais;
}
private Hospitais createHospitais(Cursor cursor) {
Hospitais hospital = new Hospitais();
CidadeDAO cidadeDAO = new CidadeDAO(context);
setsHospitais(cursor, hospital, cidadeDAO);
return hospital;
}
public long cadastrar(Hospitais hospital){
db = helper.getWritableDatabase();
ContentValues values = getContentValues(hospital);
long id = db.insert(DBHelper.TABELA_HOSPITAIS,null,values);
super.close(db);
return id;
}
}
| 37.449541 | 122 | 0.693533 |
30e60e0dc006ed3ca8498946832349488e1054d4 | 3,543 | package com.wxnacy.common.http;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Map;
public class HttpUtils {
public static void main(String[] args) {
try {
String url = "http://wxnacy.com/images/mp.jpg";
HttpResponse<InputStream> response = get(url);
File file = new File("/Users/wxnacy/Downloads/index.jpg");
FileUtils.writeByteArrayToFile(file, IOUtils.toByteArray(response.body()));
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static String toString(HttpResponse<InputStream> response) throws IOException {
return IOUtils.toString(response.body(), StandardCharsets.UTF_8);
}
public static void download(String url, String filePath) throws IOException, InterruptedException {
HttpResponse<InputStream> response = get(url);
File file = new File(filePath);
FileUtils.writeByteArrayToFile(file, IOUtils.toByteArray(response.body()));
}
public static void download(String url, String filePath, Map<String, String> headers) throws IOException, InterruptedException {
HttpResponse<InputStream> response = get(url, null, headers, null);
File file = new File(filePath);
FileUtils.writeByteArrayToFile(file, IOUtils.toByteArray(response.body()));
}
public static HttpResponse<InputStream> get(String url) throws IOException, InterruptedException {
return get(url, null, null, null);
}
public static HttpResponse<InputStream> get(String url, Map<String, String> params, Map<String, String> headers, Long timeout) throws IOException, InterruptedException {
return request(HttpMethod.GET, url, params, headers, timeout);
}
private static HttpResponse<InputStream> request(HttpMethod method, String url, Map<String, String> params, Map<String, String> headers, Long timeout) throws IOException, InterruptedException {
HttpClient.Builder clientBuilder = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.followRedirects(HttpClient.Redirect.NORMAL);
HttpRequest.Builder builder = HttpRequest.newBuilder()
.uri(URI.create(url));
if (timeout != null) {
clientBuilder = clientBuilder.connectTimeout(Duration.ofSeconds(timeout));
builder = builder.timeout(Duration.ofSeconds(timeout));
}
if (method == HttpMethod.GET) {
builder = builder.GET();
} else if (method == HttpMethod.POST) {
builder = builder.POST(null);
}
if ( headers != null) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
builder.setHeader(key, value);
}
}
HttpClient client = clientBuilder.build();
HttpRequest request = builder.build();
HttpResponse.BodyHandler<InputStream> inputStreamBodyHandler = HttpResponse.BodyHandlers.ofInputStream();
return client.send(request, inputStreamBodyHandler);
}
}
| 40.261364 | 197 | 0.671183 |
997b73859aeb5dab53f8c392254e8277fb4cad54 | 903 | import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.Logger;
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//logger.info("Get login request done");
super.doGet(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String login = req.getParameter("login");
String password = req.getParameter("password");
System.out.println(login + "\n" + password);
Logger.getLogger("main").info("First log");
resp.setStatus(HttpServletResponse.SC_ACCEPTED);
}
}
| 36.12 | 114 | 0.735327 |
f776cae7bc2fae043fc297f91faf9f2044dfa5fc | 9,107 | package de.dennisguse.opentracks.content.provider;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteConstraintException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.VisibleForTesting;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.HashMap;
import java.util.Map;
import de.dennisguse.opentracks.content.data.MarkerColumns;
import de.dennisguse.opentracks.content.data.TrackPointsColumns;
import de.dennisguse.opentracks.content.data.TracksColumns;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
@RunWith(AndroidJUnit4.class)
public class CustomSQLiteOpenHelperTest {
private static final String TRACKS_CREATE_TABLE_V23 = "CREATE TABLE tracks (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, description TEXT, category TEXT, starttime INTEGER, stoptime INTEGER, numpoints INTEGER, totaldistance FLOAT, totaltime INTEGER, movingtime INTEGER, avgspeed FLOAT, avgmovingspeed FLOAT, maxspeed FLOAT, minelevation FLOAT, maxelevation FLOAT, elevationgain FLOAT, mingrade FLOAT, maxgrade FLOAT, icon TEXT)";
private static final String TRACKPOINTS_CREATE_TABLE_V23 = "CREATE TABLE trackpoints (_id INTEGER PRIMARY KEY AUTOINCREMENT, trackid INTEGER, longitude INTEGER, latitude INTEGER, time INTEGER, elevation FLOAT, accuracy FLOAT, speed FLOAT, bearing FLOAT, sensor_heartrate FLOAT, sensor_cadence FLOAT, sensor_power FLOAT)";
private static final String WAYPOINTS_CREATE_TABLE_V23 = "CREATE TABLE waypoints (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, description TEXT, category TEXT, icon TEXT, trackid INTEGER, type INTEGER, length FLOAT, duration INTEGER, starttime INTEGER, startid INTEGER, stopid INTEGER, longitude INTEGER, latitude INTEGER, time INTEGER, elevation FLOAT, accuracy FLOAT, speed FLOAT, bearing FLOAT, totaldistance FLOAT, totaltime INTEGER, movingtime INTEGER, avgspeed FLOAT, avgmovingspeed FLOAT, maxspeed FLOAT, minelevation FLOAT, maxelevation FLOAT, elevationgain FLOAT, mingrade FLOAT, maxgrade FLOAT, photoUrl TEXT)";
private static final String DATABASE_NAME = "test.db";
private final Context context = ApplicationProvider.getApplicationContext();
/**
* Get the SQL create statements for all tables (ordered by name).
*
* @return Map(TableName, SQL)
*/
@VisibleForTesting
public static Map<String, String> getTableSQL(SQLiteDatabase db) {
HashMap<String, String> tableSQL = new HashMap<>();
try (Cursor cursor = db.query("sqlite_master", new String[]{"name", "SQL"}, "name IN ('" + TracksColumns.TABLE_NAME + "', '" + TrackPointsColumns.TABLE_NAME + "', '" + MarkerColumns.TABLE_NAME + "')", null, null, null, "name")) {
if (cursor != null) {
while (cursor.moveToNext()) {
tableSQL.put(cursor.getString(0), cursor.getString(1));
}
}
}
return tableSQL;
}
/**
* Get the SQL create statements for all indices (ordered by name).
*
* @return Map(tableName, SQL)
*/
@VisibleForTesting
public static Map<String, String> getIndexSQL(SQLiteDatabase db) {
HashMap<String, String> indexSQL = new HashMap<>();
try (Cursor cursor = db.rawQuery("SELECT tbl_name, SQL FROM sqlite_master WHERE type = 'index'", null)) {
if (cursor != null) {
while (cursor.moveToNext()) {
indexSQL.put(cursor.getString(0), cursor.getString(1));
}
}
}
return indexSQL;
}
/**
* Returns true if a SQL create statement is in the schema.
*
* @param sqlCreate the table name
*/
private static boolean hasSqlCreate(SQLiteDatabase db, String sqlCreate) {
try (Cursor cursor = db.rawQuery("SELECT SQL FROM sqlite_master", null)) {
if (cursor != null) {
while (cursor.moveToNext()) {
String sql = cursor.getString(0);
if (sqlCreate.equals(sql)) {
return true;
}
}
}
}
return false;
}
@Before
@After
public void setUp() {
context.deleteDatabase(DATABASE_NAME);
}
@Test
public void onCreate() {
try (SQLiteDatabase db = new CustomSQLiteOpenHelper(context, DATABASE_NAME).getWritableDatabase()) {
assertTrue(hasSqlCreate(db, TracksColumns.CREATE_TABLE));
assertTrue(hasSqlCreate(db, TrackPointsColumns.CREATE_TABLE));
assertTrue(hasSqlCreate(db, TrackPointsColumns.CREATE_TABLE_INDEX));
assertTrue(hasSqlCreate(db, MarkerColumns.CREATE_TABLE));
assertTrue(hasSqlCreate(db, MarkerColumns.CREATE_TABLE_INDEX));
} catch (Exception e) {
fail();
}
}
@Test
public void onUpgrade_FromVersion23() {
createVersion23();
// Open database with SQL upgrade
Map<String, String> tableByUpgrade;
Map<String, String> indicesByUpgrade;
try (SQLiteDatabase dbUpgraded = new CustomSQLiteOpenHelper(context, DATABASE_NAME).getReadableDatabase()) {
tableByUpgrade = getTableSQL(dbUpgraded);
indicesByUpgrade = getIndexSQL(dbUpgraded);
}
context.deleteDatabase(DATABASE_NAME);
// Open database via creation script
Map<String, String> tablesByCreate;
Map<String, String> indicesByCreate;
try (SQLiteDatabase dbCreated = new CustomSQLiteOpenHelper(context, DATABASE_NAME).getReadableDatabase()) {
tablesByCreate = getTableSQL(dbCreated);
indicesByCreate = getIndexSQL(dbCreated);
}
// then - verify table structure
assertEquals(3, tableByUpgrade.size());
assertEquals(tableByUpgrade.size(), tablesByCreate.size());
assertEquals(tablesByCreate.get(TracksColumns.TABLE_NAME), tableByUpgrade.get(TracksColumns.TABLE_NAME));
assertEquals(tablesByCreate.get(TrackPointsColumns.TABLE_NAME), tableByUpgrade.get(TrackPointsColumns.TABLE_NAME));
assertEquals(tablesByCreate.get(MarkerColumns.TABLE_NAME), tableByUpgrade.get(MarkerColumns.TABLE_NAME));
// then - verify custom indices
assertEquals(3, indicesByCreate.size());
assertEquals(indicesByUpgrade.get(TracksColumns.TABLE_NAME), indicesByCreate.get(TracksColumns.TABLE_NAME));
assertEquals(indicesByUpgrade.get(TrackPointsColumns.TABLE_NAME), indicesByCreate.get(TrackPointsColumns.TABLE_NAME));
assertEquals(indicesByUpgrade.get(MarkerColumns.TABLE_NAME), indicesByCreate.get(MarkerColumns.TABLE_NAME));
}
@Test
public void onDowngrade_ToVersion23() {
// Create most recent database schema
new CustomSQLiteOpenHelper(context, DATABASE_NAME).getReadableDatabase().close();
// Downgrade schema to version 23 (base version)
Map<String, String> tablesByDowngrade;
Map<String, String> indicesByDowngrade;
try (SQLiteDatabase db = new CustomSQLiteOpenHelper(context, DATABASE_NAME, 23).getReadableDatabase()) {
tablesByDowngrade = getTableSQL(db);
indicesByDowngrade = getIndexSQL(db);
}
// then - verify table structure
assertEquals(TRACKS_CREATE_TABLE_V23, tablesByDowngrade.get("tracks"));
assertEquals(TRACKPOINTS_CREATE_TABLE_V23, tablesByDowngrade.get("trackpoints"));
assertEquals(WAYPOINTS_CREATE_TABLE_V23, tablesByDowngrade.get("waypoints"));
// then - verify custom indices
assertEquals(0, indicesByDowngrade.size());
}
@Test
public void track_uuid_unique() {
try (SQLiteDatabase db = new CustomSQLiteOpenHelper(context, DATABASE_NAME).getWritableDatabase()) {
db.execSQL("INSERT INTO tracks (uuid) VALUES (0x00)");
db.execSQL("INSERT INTO tracks (uuid) VALUES (0x00)");
fail("unique constraint not enforced");
} catch (SQLiteConstraintException e) {
assertTrue(e.getMessage().contains("UNIQUE constraint failed: tracks.uuid"));
}
}
private void createVersion23() {
// Manually create database schema with version 23 (base version)
SQLiteDatabase dbBase = new SQLiteOpenHelper(context, DATABASE_NAME, null, 23) {
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}.getWritableDatabase();
dbBase.execSQL(TRACKS_CREATE_TABLE_V23);
dbBase.execSQL(TRACKPOINTS_CREATE_TABLE_V23);
dbBase.execSQL(WAYPOINTS_CREATE_TABLE_V23);
dbBase.close();
}
} | 44.862069 | 630 | 0.688811 |
938a705ab9e16b6af1299bfa8bd06c6bdfa10eed | 1,529 | /*-
* ========================LICENSE_START=================================
* ids-container-manager
* %%
* Copyright (C) 2019 Fraunhofer AISEC
* %%
* 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.
* =========================LICENSE_END==================================
*/
package de.fhg.aisec.ids.comm.unixsocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TrustmeUnixSocketResponseHandler {
private Logger LOG = LoggerFactory.getLogger(TrustmeUnixSocketResponseHandler.class);
private byte[] rsp = null;
public synchronized boolean handleResponse(byte[] rsp) {
this.rsp = rsp.clone();
this.notify();
return true;
}
public synchronized byte[] waitForResponse() {
while (this.rsp == null) {
try {
this.wait();
} catch (InterruptedException e) {
LOG.error(e.getMessage(), e);
}
}
byte[] result = rsp;
LOG.debug("received response byte length: {}", result.length);
this.rsp = null;
return result;
}
}
| 31.204082 | 87 | 0.639634 |
263dbb08961242c593834313104b74a22bdd9d71 | 2,928 | package org.bian.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.bian.dto.BQRegulatoryTermsEvaluateInputModelCustomerAgreementInstanceRecord;
import org.bian.dto.BQRegulatoryTermsEvaluateInputModelRegulatoryTermsInstanceRecord;
import javax.validation.Valid;
/**
* BQRegulatoryTermsEvaluateInputModel
*/
public class BQRegulatoryTermsEvaluateInputModel {
private BQRegulatoryTermsEvaluateInputModelCustomerAgreementInstanceRecord customerAgreementInstanceRecord = null;
private String customerAgreementInstanceReference = null;
private String regulatoryTermsInstanceReference = null;
private BQRegulatoryTermsEvaluateInputModelRegulatoryTermsInstanceRecord regulatoryTermsInstanceRecord = null;
/**
* Get customerAgreementInstanceRecord
* @return customerAgreementInstanceRecord
**/
public BQRegulatoryTermsEvaluateInputModelCustomerAgreementInstanceRecord getCustomerAgreementInstanceRecord() {
return customerAgreementInstanceRecord;
}
public void setCustomerAgreementInstanceRecord(BQRegulatoryTermsEvaluateInputModelCustomerAgreementInstanceRecord customerAgreementInstanceRecord) {
this.customerAgreementInstanceRecord = customerAgreementInstanceRecord;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::ISO20022andUNCEFACT::Identifier general-info: Reference to the parent Customer Agreement instance
* @return customerAgreementInstanceReference
**/
public String getCustomerAgreementInstanceReference() {
return customerAgreementInstanceReference;
}
public void setCustomerAgreementInstanceReference(String customerAgreementInstanceReference) {
this.customerAgreementInstanceReference = customerAgreementInstanceReference;
}
/**
* `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::ISO20022andUNCEFACT::Identifier general-info: Reference to the Regulatory Terms instance
* @return regulatoryTermsInstanceReference
**/
public String getRegulatoryTermsInstanceReference() {
return regulatoryTermsInstanceReference;
}
public void setRegulatoryTermsInstanceReference(String regulatoryTermsInstanceReference) {
this.regulatoryTermsInstanceReference = regulatoryTermsInstanceReference;
}
/**
* Get regulatoryTermsInstanceRecord
* @return regulatoryTermsInstanceRecord
**/
public BQRegulatoryTermsEvaluateInputModelRegulatoryTermsInstanceRecord getRegulatoryTermsInstanceRecord() {
return regulatoryTermsInstanceRecord;
}
public void setRegulatoryTermsInstanceRecord(BQRegulatoryTermsEvaluateInputModelRegulatoryTermsInstanceRecord regulatoryTermsInstanceRecord) {
this.regulatoryTermsInstanceRecord = regulatoryTermsInstanceRecord;
}
}
| 35.277108 | 191 | 0.83709 |
f4e7df1ac80bb7738f210631c573160bd044ea45 | 236 | package ch.uzh.ifi.hase.soprafs22.rest.dto;
public class UserIdDTO {
private long userId;
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
}
| 15.733333 | 43 | 0.627119 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.