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
|
---|---|---|---|---|---|
7337ada576a589629635ed2851b938556d1eec09
| 948 |
package pathsala.serverless.student;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import pathsala.student.StudentParams;
import pathsala.student.StudentVisitor;
@Getter
@Setter
@DynamoDBTable(tableName = "PSStudent")
@ToString
public class StudentData implements StudentParams, StudentVisitor {
@DynamoDBHashKey
private String studentId;
@DynamoDBAttribute
private String firstName;
@DynamoDBAttribute
private String middleName;
@DynamoDBAttribute
private String lastName;
@DynamoDBAttribute
private String addressLine;
@DynamoDBAttribute
private String city;
@DynamoDBAttribute
private String state;
@DynamoDBAttribute
private String zipCode;
}
| 27.882353 | 72 | 0.798523 |
90780c4ea74cf567483796246ae9145f59d758f5
| 619 |
package org.apereo.cas.configuration.model.support.pac4j;
/**
* This is {@link Pac4jGenericClientProperties}.
*
* @author Misagh Moayyed
* @since 5.2.0
*/
public class Pac4jGenericClientProperties {
/**
* The client id.
*/
private String id;
/**
* The client secret.
*/
private String secret;
public String getId() {
return this.id;
}
public void setId(final String id) {
this.id = id;
}
public String getSecret() {
return this.secret;
}
public void setSecret(final String secret) {
this.secret = secret;
}
}
| 17.685714 | 57 | 0.592892 |
7739cbe49b47b367841d6dfe911bf273bfcb7a90
| 1,491 |
/*
* Copyright 2021 LINE Corporation
*
* LINE Corporation 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:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.linecorp.armeria.internal.common.thrift;
import org.apache.thrift.TConfiguration;
import org.apache.thrift.transport.TTransportException;
import com.linecorp.armeria.common.annotation.Nullable;
import io.netty.buffer.ByteBuf;
public final class TByteBufTransport extends AbstractTByteBufTransport {
public TByteBufTransport(ByteBuf buf) {
super(buf);
}
@Nullable
@Override
public TConfiguration getConfiguration() {
return null;
}
@Override
public void updateKnownMessageSize(long size) throws TTransportException {
// This method is not called by the 'TProtocol's provided by Armeria
}
@Override
public void checkReadBytesAvailable(long numBytes) throws TTransportException {
// The size of readable bytes is already checked by the underlying ByteBuf.
}
}
| 31.723404 | 83 | 0.743125 |
acecca3cf863d5bf1e5f7d9c89f3ccac851b0584
| 2,737 |
package com.funtl.my.shop.web.admin.abstracts;
import com.funtl.my.shop.commons.dto.BaseResult;
import com.funtl.my.shop.commons.dto.PageInfo;
import com.funtl.my.shop.commons.persistence.BaseEntity;
import com.funtl.my.shop.commons.persistence.BaseService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.servlet.http.HttpServletRequest;
/**
* @ClassName AbstractBaseController
* @Description TODO
* @Author kdnight
* @Date 2019/6/4 10:47
* @Version 1.0
**/
public abstract class AbstractBaseController<T extends BaseEntity, S extends BaseService<T>> {
/**
* 注入业务逻辑层
*/
@Autowired
protected S service;
/**
* 跳转列表页
*
* @return
*/
public abstract String list();
/**
* 跳转到表单页
* @return
*/
public abstract String form();
/**
* 保存信息
* @param entity
* @param redirectAttributes
* @param model
* @return
*/
public abstract String save(T entity, RedirectAttributes redirectAttributes, Model model);
/**
* 删除
* @param ids
* @return
*/
@ResponseBody
@RequestMapping(value = "delete", method = RequestMethod.POST)
public BaseResult delete(String ids){
BaseResult baseResult=null;
if (StringUtils.isNotBlank(ids)) {
String[] idArray = ids.split(",");
service.deleteMulti(idArray);
baseResult = BaseResult.success("删除成功");
} else {
baseResult = BaseResult.fail("删除失败");
}
return baseResult;
}
/**
* 分页查询
* @param request
* @param entity
* @return
*/
@ResponseBody
@RequestMapping(value = "page",method = RequestMethod.GET)
public PageInfo<T> page(HttpServletRequest request, T entity){
String strDraw = request.getParameter("draw");
String strStart = request.getParameter("start");
String strLength = request.getParameter("length");
int draw = strDraw == null ? 0 : Integer.parseInt(strDraw);
int start = strStart == null ? 0 : Integer.parseInt(strStart);
int length = strLength == null ? 10 : Integer.parseInt(strLength);
//封装datatable需要的结果
PageInfo<T> pageInfo = service.page(draw, start, length,entity);
return pageInfo;
}
/**
* 跳转详情页
* @return
*/
public abstract String detail();
}
| 27.37 | 94 | 0.651443 |
3e0dc2912ac2d339862b51ca11071fbd5464aeea
| 2,023 |
/*
* Copyright 2013-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example.springdata.mongodb.aggregation;
import java.util.List;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.repository.Aggregation;
import org.springframework.data.repository.CrudRepository;
/**
* A repository interface assembling CRUD functionality as well as the API to invoke the methods implemented manually.
*
* @author Thomas Darimont
* @author Oliver Gierke
* @author Divya Srivastava
*/
public interface OrderRepository extends CrudRepository<Order, String>, OrderRepositoryCustom {
@Aggregation("{ $group : { _id : $customerId, total : { $sum : 1 } } }")
List<OrdersPerCustomer> totalOrdersPerCustomer(Sort sort);
@Aggregation(pipeline = { "{ $match : { customerId : ?0 } }", "{ $count : total }" })
Long totalOrdersForCustomer(String customerId);
@Aggregation(pipeline = { "{ $match : { id : ?0 } }", "{ $unwind : { path : '$items' } }",
"{ $project : { id : 1 , customerId : 1 , items : 1 , lineTotal : { $multiply: [ '$items.price' , '$items.quantity' ] } } }",
"{ $group : { '_id' : '$_id' , 'netAmount' : { $sum : '$lineTotal' } , 'items' : { $addToSet : '$items' } } }",
"{ $project : { 'orderId' : '$_id' , 'items' : 1 , 'netAmount' : 1 , 'taxAmount' : { $multiply: [ '$netAmount' , 0.19 ] } , 'totalAmount' : { $multiply: [ '$netAmount' , 1.19 ] } } }" })
Invoice aggregateInvoiceForOrder(String orderId);
}
| 43.978261 | 189 | 0.681167 |
615afec555a55c2e333d4e4f068f4d5be3b20931
| 6,945 |
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.autofill.keyboard_accessory;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.support.v7.content.res.AppCompatResources;
import android.support.v7.widget.RecyclerView;
import android.text.method.PasswordTransformationMethod;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.chromium.base.ApiCompatibilityUtils;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.autofill.keyboard_accessory.AccessorySheetTabModel.AccessorySheetDataPiece;
import org.chromium.chrome.browser.autofill.keyboard_accessory.AccessorySheetTabViewBinder.ElementViewHolder;
import org.chromium.chrome.browser.autofill.keyboard_accessory.KeyboardAccessoryData.FooterCommand;
import org.chromium.ui.modelutil.ListModel;
/**
* This stateless class provides methods to bind the items in a {@link ListModel <Item>}
* to the {@link RecyclerView} used as view of the Password accessory sheet component.
*/
class PasswordAccessorySheetViewBinder {
static ElementViewHolder create(ViewGroup parent, @AccessorySheetDataPiece.Type int viewType) {
switch (viewType) {
case AccessorySheetDataPiece.Type.TITLE:
return new PasswordsTitleViewHolder(parent);
case AccessorySheetDataPiece.Type.PASSWORD_INFO:
return new PasswordsInfoViewHolder(parent);
case AccessorySheetDataPiece.Type.FOOTER_COMMAND:
return new FooterCommandViewHolder(parent);
}
assert false : "Unhandled type of data piece: " + viewType;
return null;
}
/**
* Holds a the TextView with the title of the sheet and a divider for the accessory bar.
*/
static class PasswordsTitleViewHolder extends ElementViewHolder<String, LinearLayout> {
PasswordsTitleViewHolder(ViewGroup parent) {
super(parent, R.layout.password_accessory_sheet_label);
}
@Override
protected void bind(String displayText, LinearLayout view) {
TextView titleView = view.findViewById(R.id.tab_title);
titleView.setText(displayText);
titleView.setContentDescription(displayText);
}
}
/**
* Holds a TextView that represents a bottom command and is separated to the top by a divider.
*/
static class FooterCommandViewHolder extends ElementViewHolder<FooterCommand, LinearLayout> {
FooterCommandViewHolder(ViewGroup parent) {
super(parent, R.layout.password_accessory_sheet_legacy_option);
}
@Override
protected void bind(FooterCommand footerCommand, LinearLayout layout) {
TextView view = layout.findViewById(R.id.footer_text);
view.setText(footerCommand.getDisplayText());
view.setContentDescription(footerCommand.getDisplayText());
view.setOnClickListener(v -> footerCommand.execute());
view.setClickable(true);
}
}
/**
* Holds a layout for a username and a password with a small icon.
*/
static class PasswordsInfoViewHolder
extends ElementViewHolder<KeyboardAccessoryData.UserInfo, LinearLayout> {
private final int mPadding;
private final int mIconSize;
PasswordsInfoViewHolder(ViewGroup parent) {
super(parent, R.layout.keyboard_accessory_sheet_tab_legacy_password_info);
mPadding = itemView.getContext().getResources().getDimensionPixelSize(
R.dimen.keyboard_accessory_suggestion_padding);
mIconSize = itemView.getContext().getResources().getDimensionPixelSize(
R.dimen.keyboard_accessory_suggestion_icon_size);
}
@Override
protected void bind(KeyboardAccessoryData.UserInfo info, LinearLayout layout) {
TextView username = layout.findViewById(R.id.suggestion_text);
TextView password = layout.findViewById(R.id.password_text);
bindTextView(username, info.getFields().get(0));
bindTextView(password, info.getFields().get(1));
// Set the default icon for username, then try to get a better one.
setIconForBitmap(username, null);
if (info.getFaviconProvider() != null) {
info.getFaviconProvider().fetchFavicon(
mIconSize, icon -> setIconForBitmap(username, icon));
}
username.setPadding(mPadding, 0, mPadding, 0);
// Passwords have no icon, so increase the offset.
password.setPadding(2 * mPadding + mIconSize, 0, mPadding, 0);
}
private void bindTextView(TextView text, KeyboardAccessoryData.UserInfo.Field field) {
text.setTransformationMethod(
field.isObfuscated() ? new PasswordTransformationMethod() : null);
text.setText(field.getDisplayText());
text.setContentDescription(field.getA11yDescription());
text.setOnClickListener(!field.isSelectable() ? null : src -> field.triggerSelection());
text.setClickable(true); // Ensures that "disabled" is announced.
text.setEnabled(field.isSelectable());
text.setBackground(getBackgroundDrawable(field.isSelectable()));
}
private @Nullable Drawable getBackgroundDrawable(boolean selectable) {
if (!selectable) return null;
TypedArray a = itemView.getContext().obtainStyledAttributes(
new int[] {R.attr.selectableItemBackground});
Drawable suggestionBackground = a.getDrawable(0);
a.recycle();
return suggestionBackground;
}
private void setIconForBitmap(TextView text, @Nullable Bitmap favicon) {
Drawable icon;
if (favicon == null) {
icon = AppCompatResources.getDrawable(
itemView.getContext(), R.drawable.ic_globe_36dp);
} else {
icon = new BitmapDrawable(itemView.getContext().getResources(), favicon);
}
if (icon != null) { // AppCompatResources.getDrawable is @Nullable.
icon.setBounds(0, 0, mIconSize, mIconSize);
}
text.setCompoundDrawablePadding(mPadding);
ApiCompatibilityUtils.setCompoundDrawablesRelative(text, icon, null, null, null);
}
}
public static void initializeView(RecyclerView view, AccessorySheetTabModel model) {
view.setAdapter(PasswordAccessorySheetCoordinator.createAdapter(model));
}
}
| 45.690789 | 110 | 0.683225 |
7f5edade2b5f8f9ffd8cdf9ed9ea475d0a085914
| 1,333 |
package com.ahdms.user.client;
import com.ahdms.user.client.vo.CompanyInfoRmiRspVo;
import com.ahdms.user.client.vo.PayInfoRspVo;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.validation.constraints.NotNull;
import java.util.List;
/**
* @author qinxiang
* @date 2020-07-16 20:00
*/
@FeignClient(value = "${client.omp.user.center.group:omp-user-center}", contextId = "user")
@RequestMapping("/rmi/user/company")
public interface CompanyClientService {
/**
* 获取用户下 的服务商或供应商信息
* @param userId
* @return
*/
@GetMapping("info")
CompanyInfoRmiRspVo getCompanyInfo(@Validated @NotNull @RequestParam("userId")Long userId);
/**
* 获取用户下 所有启用的代理商或依赖方
* @param userId
* @return
*/
@GetMapping("infos")
List<CompanyInfoRmiRspVo> getCompanyInfos(@Validated @NotNull @RequestParam("userId")Long userId);
/**
* 根据商家业务主键查询支付账号信息
* @param companyId
* @return
*/
@GetMapping("getPayInfos")
PayInfoRspVo getPayInfos(@Validated @NotNull @RequestParam("companyId") Long companyId);
}
| 28.978261 | 102 | 0.726932 |
fd69cb6eb18435a3d451f2cd5e27536ca28db63d
| 632 |
package model.math.transformation;
/**
* The Identity Matrix
* @author Abdullah Emad
* @version 1.0
* @see Matrix
*/
public class Identity extends Matrix {
/**
* Creates the identity Matrix
*/
public Identity() {
super(initArray());
}
private static double[][] initArray(){
double[][] mat = new double[4][4];
for(int i = 0; i < mat.length; i++){
for(int j = 0; j < mat[i].length; j++){
mat[i][j] = 0;
}
}
mat[0][0] = 1;
mat[1][1] = 1;
mat[2][2] = 1;
mat[3][3] = 1;
return mat;
}
}
| 19.151515 | 51 | 0.463608 |
52e0352837d487495f8d532588e9b0ad2113bc1f
| 623 |
public class OO7 {
public static void main(String[] args) {
// manipular horários
Horario h1 = new Horario();
System.out.println(h1.horas); // 0
System.out.println(h1.minutos); // 0
System.out.println(h1.segundos); // 0
System.out.println(h1.horas == 0); // 0
System.out.println(h1.minutos == 0); // 0
System.out.println(h1.segundos == 0); // 0
h1.horas = 18;
System.out.println(h1.horas); // 18
System.out.println(h1.horas == 18); // 18
Horario h2 = adicionaHoras(h1, 12);
System.out.println(h1.horas == 18); // 18
System.out.println(h2.horas == 18); // 6
}
}
| 29.666667 | 46 | 0.605136 |
630d67d273b1d51b1b02c11bec5b939373f27785
| 924 |
package victor.keys.logger.utils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import lombok.SneakyThrows;
public class DetermineActiveIDE {
public enum IDE {
ECLIPSE, IDEA
}
public static void main(String[] args) {
System.out.println(DetermineActiveIDE.getActiveIDE());
}
public static IDE getActiveIDE() {
if (lookForProcess("eclipse.exe")) {
return IDE.ECLIPSE;
}
if (lookForProcess("idea")) {
return IDE.IDEA;
}
return null;
}
@SneakyThrows
private static boolean lookForProcess(String processName) {
String line;
String pidInfo ="";
Process p =Runtime.getRuntime().exec(System.getenv("windir") +"\\system32\\"+"tasklist.exe");
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
pidInfo+=line;
}
input.close();
return pidInfo.contains(processName);
}
}
| 20.086957 | 95 | 0.703463 |
659fa74a3e8b8b48d284091f4680f602de231d50
| 208 |
/**
*
*/
package grapheus.event;
/**
* @author black
*
*/
public interface DataSourceControlListener {
void onDatasourceDisabled(String dsLinkId);
void onDatasourceEnabled(String dsLinkId);
}
| 13.866667 | 47 | 0.701923 |
75f3f8f9f1aa87de4a601f1bfdf3ee6625e0eeb0
| 2,459 |
/*
* Copyright (c) 2012-2013, Poplar Yfyang 杨友峰 (poplar1123@gmail.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.
*/
package com.asura.framework.dao.mybatis.paginator.support;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.transaction.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.asura.framework.dao.mybatis.paginator.dialect.Dialect;
/**
*
* @author poplar.yfyang
* @author miemiedev
*/
public class SQLHelp {
private static Logger logger = LoggerFactory.getLogger(SQLHelp.class);
/**
* 查询总纪录数
*
* @param mappedStatement mapped
* @param parameterObject 参数
* @param boundSql boundSql
* @param dialect database dialect
* @return 总记录数
* @throws java.sql.SQLException sql查询错误
*/
public static int getCount(
final MappedStatement mappedStatement, final Transaction transaction, final Object parameterObject,
final BoundSql boundSql, Dialect dialect) throws SQLException {
final String count_sql = dialect.getCountSQL();
logger.debug("Total count SQL [{}] ", count_sql);
logger.debug("Total count Parameters: {} ", parameterObject);
Connection connection = transaction.getConnection();
PreparedStatement countStmt = connection.prepareStatement(count_sql);
DefaultParameterHandler handler = new DefaultParameterHandler(mappedStatement,parameterObject,boundSql);
handler.setParameters(countStmt);
ResultSet rs = countStmt.executeQuery();
int count = 0;
if (rs.next()) {
count = rs.getInt(1);
}
logger.debug("Total count: {}", count);
return count;
}
}
| 33.684932 | 130 | 0.693371 |
378935ed5a3abf91d4126c2abe742f1bd65673f5
| 1,014 |
package org.usfirst.frc.team4950.robot.autoplay;
public class Reading {
private double leftPow;
private double rightPow;
private double gyro;
private int leftEnc;
private int rightEnc;
private boolean gearMech;
private boolean shooter;
public Reading(double lp, double rp, double g, int le, int re, boolean gm, boolean s) {
leftPow = lp;
rightPow = rp;
gyro = g;
leftEnc = le;
rightEnc = re;
gearMech = gm;
shooter = s;
}
public Reading() {
this(0, 0, 0, 0, 0, false, false);
}
public double getLeftPow() { return leftPow; }
public double getRightPow() { return rightPow; }
public double getGyro() { return gyro; }
public int getLeftEnc() { return leftEnc; }
public int getRightEnc() { return rightEnc; }
public boolean getGearMech() { return gearMech; }
public boolean getShooter() { return shooter; }
@Override
public String toString() {
return leftPow + " " + rightPow + " " + gyro + " " + leftEnc + " " + rightEnc + " " + gearMech + " " + shooter;
}
}
| 26 | 113 | 0.66568 |
775fff35e83ec64466ec36c9b58bfb48ac597ce0
| 1,134 |
/*
* Copyright (c) 2015 - 11 - 1 9 : 42 :5
* @author wupeiji It will be
* @Email wpjlovehome@gmail.com
*/
package com.wpj.wx.service;
import com.wpj.wx.common.Page;
import com.wpj.wx.damain.TbListmain;
import java.util.List;
import java.util.Map;
/**
* Created by WPJ587 on 2015/11/1.
*/
public interface ListMainService extends IService<TbListmain> {
/**
* Find content message by id map.
*
* @param id the id
* @return the map
*/
Map<String,Object> findContentMessageById(int id);
/**
* 根据条件分页查询
*
* @param listmain the listmain
* @param page the page
* @param rows the rows
* @return list
*/
List<TbListmain> selectByListmain(TbListmain listmain, int page, int rows);
/**
* Find list main by page list.
*
* @param page the page
* @return the list
*/
List<TbListmain> findListMainByPage(Page page);
/**
* 获取总数
* @return
*/
int findCountNo();
/**
* 根据listmain的id获取listmain文章具体内容
* @param id
* @return
*/
TbListmain getListMainById(int id);
}
| 19.551724 | 79 | 0.590829 |
73b12fc6925b84afb00fa78b8e38ba2e8444d368
| 6,965 |
package dao;
import com.avaje.ebean.Ebean;
import dao.impl.CategoryDaoImpl;
import dao.impl.ResourceDaoImpl;
import models.Category;
import utilities.Dependencies;
import models.Resource;
import models.ResourceType;
import org.junit.Before;
import org.junit.Test;
import testutils.BaseTest;
import java.util.List;
import static dao.ResourceDao.ResourceSearchCriteria;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class ResourceDaoSearchTest extends BaseTest {
Category category1, category2, childCategory1, childCategory2, parentCategory;
Resource book1, book2, book3;
Resource article1, article2, article3;
Resource video1, video2, video3;
Resource site1, site2, site3;
Resource highRate1, highRate2, highRate3;
dao.ResourceDao resourceDao;
@Before
public void setUp() {
resourceDao = new ResourceDaoImpl();
dao.CategoryDao categoryDao = new CategoryDaoImpl();
Dependencies.setResourceDao(resourceDao);
Dependencies.setCategoryDao(categoryDao);
parentCategory = newCategory("parentCateogry");
categoryDao.create(parentCategory);
childCategory1 = newCategory("childCategory1");
childCategory1.parent = parentCategory;
categoryDao.create(childCategory1);
childCategory2 = newCategory("childCategory2");
childCategory2.parent = parentCategory;
categoryDao.create(childCategory2);
parentCategory = Ebean.find(Category.class, parentCategory.id);
category1 = newCategory("category1");
category2 = newCategory("category2");
categoryDao.create(category1);
categoryDao.create(category2);
book1 = newResource("book1 name_query", ResourceType.BOOK, parentCategory);
book2 = newResource("book2", ResourceType.BOOK, category1);
book3 = newResource("book3", ResourceType.BOOK, category1, category2);
article1 = newResource("article1", ResourceType.ARTICLE, childCategory1);
article2 = newResource("article2 name_query", ResourceType.ARTICLE, category1, childCategory1, parentCategory);
article3 = newResource("article3", ResourceType.ARTICLE, category1, category2);
video1 = newResource("video1", ResourceType.VIDEO);
video2 = newResource("video2", ResourceType.VIDEO, category1);
video3 = newResource("video3 name_query", ResourceType.VIDEO, category1, category2, childCategory2);
site1 = newResource("site1 name_query", ResourceType.WEBSITE, childCategory1);
site2 = newResource("site2", ResourceType.WEBSITE, category1, childCategory2);
site3 = newResource("site3", ResourceType.WEBSITE, category1, category2);
book2.description = "felan felan desc_query felan felan";
article1.description = "felan felan desc_query felan felan";
video1.description = "felan felan desc_query felan felan";
site3.description = "felan felan desc_query felan felan";
book1 = resourceDao.create(book1);
book2 = resourceDao.create(book2);
book3 = highRate1 = resourceDao.create(book3);
article1 = resourceDao.create(article1);
article2 = highRate2 = resourceDao.create(article2);
article3 = resourceDao.create(article3);
video1 = highRate3 = resourceDao.create(video1);
video2 = resourceDao.create(video2);
video3 = resourceDao.create(video3);
site1 = resourceDao.create(site1);
site2 = resourceDao.create(site2);
site3 = resourceDao.create(site3);
highRate1.rating = 5.0;
highRate2.rating = 4.5;
highRate3.rating = 3.0;
resourceDao.update(highRate1);
resourceDao.update(highRate2);
resourceDao.update(highRate3);
}
@Test
public void testRetrieveResources() {
ResourceDao.ResourceSearchCriteria criteria = new ResourceDao.ResourceSearchCriteria(null, null, ResourceType.BOOK);
assertSearch(criteria, book1, book2, book3);
criteria = new ResourceDao.ResourceSearchCriteria(null, category1, ResourceType.ARTICLE);
assertSearch(criteria, article2, article3);
criteria = new ResourceDao.ResourceSearchCriteria(null, category1, ResourceType.VIDEO, ResourceType.WEBSITE);
assertSearch(criteria, video2, site2, video3, site3);
criteria = new ResourceDao.ResourceSearchCriteria(null, category2);
assertSearch(criteria, book3, article3, video3, site3);
criteria = new ResourceDao.ResourceSearchCriteria("name_query", category1);
assertSearch(criteria, article2, video3);
criteria = new ResourceDao.ResourceSearchCriteria("desc_query", null, ResourceType.ARTICLE, ResourceType.WEBSITE);
assertSearch(criteria, article1, site3);
}
@Test
public void testPages() {
ResourceSearchCriteria criteria = new ResourceSearchCriteria(null, null);
criteria.setPageNumber(0);
criteria.setPageSize(5);
List<Resource> firstPage = resourceDao.findByCriteria(criteria);
criteria.setPageNumber(1);
List<Resource> secondPage = resourceDao.findByCriteria(criteria);
assertEquals("Search should return #'pageNumber' results", 5, firstPage.size());
assertEquals("Search should return #'pageNumber' results", 5, secondPage.size());
for (Resource resource : firstPage) {
assertFalse("Different search pages should contain different results", secondPage.contains(resource));
}
}
@Test
public void testParentCategory() {
ResourceDao.ResourceSearchCriteria criteria = new ResourceDao.ResourceSearchCriteria(null, parentCategory);
assertSearch("Searching with parent category should return results for child categories as well",
criteria, book1, article1, article2, video3, site1, site2);
}
@Test
public void testSortByRate() {
ResourceSearchCriteria criteria = new ResourceSearchCriteria(null, null);
criteria.setSortBy(ResourceSearchCriteria.SORT_BY_RATE);
List<Resource> results = resourceDao.findByCriteria(criteria);
assertEquals(highRate1, results.get(0));
assertEquals(highRate2, results.get(1));
assertEquals(highRate3, results.get(2));
}
private void assertSearch(String message, ResourceDao.ResourceSearchCriteria criteria, Resource... resources) {
List<Resource> resourceList = resourceDao.findByCriteria(criteria);
assertEquals(message, resources.length, resourceList.size());
for (Resource resource : resources) {
assertTrue(message, resourceList.contains(resource));
resourceList.remove(resource);
}
}
private void assertSearch(ResourceDao.ResourceSearchCriteria criteria, Resource... resources) {
assertSearch(null, criteria, resources);
}
}
| 41.957831 | 124 | 0.707968 |
1f30ab0888eea44eeaaee61988a0d33de50e6eb3
| 1,637 |
package com.junyu.IMBudget.model;
/**
* Created by Junyu on 10/17/2016.
*/
public class Friend {
public Boolean online;
public String userId;
public String chatId;
public String name;
public String lastMsg;
public String lastMsgTime;
public String imgUrl = "";
public Friend() {
}
public Friend(String name, Boolean online) {
this.name = name;
this.online = online;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Boolean getOnline() {
return online;
}
public void setOnline(Boolean online) {
this.online = online;
}
public String getChatId() {
return chatId;
}
public void setChatId(String id) {
this.chatId = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getLastMsg() {
return lastMsg;
}
public void setLastMsg(String lastMsg) {
this.lastMsg = lastMsg;
}
public String getLastMsgTime() {
return lastMsgTime;
}
public void setLastMsgTime(String lastMsgTime) {
this.lastMsgTime = lastMsgTime;
}
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
@Override
public String toString() {
return "Friend UserId is " + userId + " Friend Name " +
name + " status " + online + " img is " + imgUrl;
}
}
| 17.602151 | 65 | 0.576665 |
22cf01c476424f07bad1fd0973dcb172d09052e6
| 4,261 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to you under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jmeter.protocol.jdbc.sampler;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.jmeter.config.ConfigTestElement;
import org.apache.jmeter.engine.util.ConfigMergabilityIndicator;
import org.apache.jmeter.gui.TestElementMetadata;
import org.apache.jmeter.protocol.jdbc.AbstractJDBCTestElement;
import org.apache.jmeter.protocol.jdbc.config.DataSourceElement;
import org.apache.jmeter.samplers.Entry;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.samplers.Sampler;
import org.apache.jmeter.testbeans.TestBean;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jorphan.util.JOrphanUtils;
/**
* A sampler which understands JDBC database requests.
*
*/
@TestElementMetadata(labelResource = "displayName")
public class JDBCSampler extends AbstractJDBCTestElement implements Sampler, TestBean, ConfigMergabilityIndicator {
private static final Set<String> APPLIABLE_CONFIG_CLASSES = new HashSet<>(
Arrays.asList("org.apache.jmeter.config.gui.SimpleConfigGui"));
private static final long serialVersionUID = 234L;
/**
* Creates a JDBCSampler.
*/
public JDBCSampler() {
}
@Override
public SampleResult sample(Entry e) {
SampleResult res = new SampleResult();
res.setSampleLabel(getName());
res.setSamplerData(toString());
res.setDataType(SampleResult.TEXT);
res.setContentType("text/plain"); // $NON-NLS-1$
res.setDataEncoding(ENCODING);
// Assume we will be successful
res.setSuccessful(true);
res.setResponseMessageOK();
res.setResponseCodeOK();
res.sampleStart();
Connection conn = null;
try {
if(JOrphanUtils.isBlank(getDataSource())) {
throw new IllegalArgumentException("Variable Name must not be null in "+getName());
}
try {
conn = DataSourceElement.getConnection(getDataSource());
} finally {
res.connectEnd();
}
res.setResponseHeaders(DataSourceElement.getConnectionInfo(getDataSource()));
res.setResponseData(execute(conn, res));
} catch (SQLException ex) {
final String errCode = Integer.toString(ex.getErrorCode());
res.setResponseMessage(ex.toString());
res.setResponseCode(ex.getSQLState()+ " " +errCode);
res.setResponseData(ex.getMessage().getBytes());
res.setSuccessful(false);
} catch (Exception ex) {
res.setResponseMessage(ex.toString());
res.setResponseCode("000");
res.setResponseData(ObjectUtils.defaultIfNull(ex.getMessage(), "NO MESSAGE").getBytes());
res.setSuccessful(false);
} finally {
close(conn);
}
// TODO: process warnings? Set Code and Message to success?
res.sampleEnd();
return res;
}
/**
* @see org.apache.jmeter.samplers.AbstractSampler#applies(org.apache.jmeter.config.ConfigTestElement)
*/
@Override
public boolean applies(ConfigTestElement configElement) {
String guiClass = configElement.getProperty(TestElement.GUI_CLASS).getStringValue();
return APPLIABLE_CONFIG_CLASSES.contains(guiClass);
}
}
| 37.052174 | 115 | 0.693264 |
6f642ff162a41986cd0210e432f74528dc2f1f89
| 200 |
package com.teammental.medto;
import java.io.Serializable;
/**
* See {@link AbstractIdDto}.
*/
@Deprecated
public abstract class BaseIdDto<IdT extends Serializable> extends AbstractIdDto<IdT> {
}
| 18.181818 | 86 | 0.76 |
c468b0e4b1c57aa02d480fdaa6887c7ceb126eb2
| 3,164 |
package iyegoroff.imagefilterkit.nativeplatform;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import com.facebook.cache.common.CacheKey;
import com.facebook.common.references.CloseableReference;
import com.facebook.imagepipeline.bitmaps.PlatformBitmapFactory;
import com.facebook.imagepipeline.image.CloseableImage;
import org.json.JSONObject;
import java.util.Locale;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import iyegoroff.imagefilterkit.InputConverter;
import iyegoroff.imagefilterkit.utility.CompositionPostProcessor;
public class PorterDuffXfermodePostProcessor extends CompositionPostProcessor {
private final @Nonnull PorterDuff.Mode mMode;
public PorterDuffXfermodePostProcessor(
int width,
int height,
@Nullable JSONObject config,
@Nonnull CloseableReference<CloseableImage> src,
@Nonnull CacheKey srcCacheKey
) {
super(width, height, config, src, srcCacheKey);
InputConverter converter = new InputConverter(width, height);
mMode = converter.convertPorterDuffMode(config, "mode", PorterDuff.Mode.ADD);
}
@Override
public String getName() {
return "PorterDuffXfermodePostProcessor";
}
@Override
protected CloseableReference<Bitmap> processComposition(
Bitmap dstImage,
Bitmap srcImage,
PlatformBitmapFactory bitmapFactory
) {
final CloseableReference<Bitmap> outRef = bitmapFactory.createBitmap(
canvasExtent(dstImage.getWidth(), srcImage.getWidth(), mWidth),
canvasExtent(dstImage.getHeight(), srcImage.getHeight(), mHeight)
);
try {
final Canvas canvas = new Canvas(outRef.get());
final int flags = Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG | Paint.FILTER_BITMAP_FLAG;
final Paint paint = new Paint(flags);
if (mSwapImages) {
drawSrc(canvas, srcImage, paint);
} else {
drawDst(canvas, dstImage, paint);
}
paint.setXfermode(new PorterDuffXfermode(mMode));
if (mSwapImages) {
drawDst(canvas, dstImage, paint);
} else {
drawSrc(canvas, srcImage, paint);
}
return CloseableReference.cloneOrNull(outRef);
} finally {
CloseableReference.closeSafely(outRef);
}
}
private void drawDst(@Nonnull Canvas canvas, @Nonnull Bitmap dst, @Nonnull Paint paint) {
canvas.drawBitmap(
dst,
bitmapTransform(
canvas.getWidth(),
canvas.getHeight(),
dst.getWidth(),
dst.getHeight(),
mDstTransform
),
paint
);
}
private void drawSrc(@Nonnull Canvas canvas, @Nonnull Bitmap src, @Nonnull Paint paint) {
canvas.drawBitmap(
src,
bitmapTransform(
canvas.getWidth(),
canvas.getHeight(),
src.getWidth(),
src.getHeight(),
mSrcTransform
),
paint
);
}
@Nonnull
@Override
public CacheKey generateCacheKey() {
return compositionCacheKey(String.format(
Locale.ROOT,
"porter_duff_xfermode_%s",
mMode.toString())
);
}
}
| 25.723577 | 93 | 0.70196 |
752709d5de5a1c4307a2b916ae1c43ee4806e0bf
| 1,278 |
package com.github.sormuras.bach.workflow;
import com.github.sormuras.bach.Bach;
import com.github.sormuras.bach.Command;
import com.github.sormuras.bach.Project;
import com.github.sormuras.bach.ToolCall;
import com.github.sormuras.bach.ToolRun;
import com.github.sormuras.bach.project.ProjectSpace;
import java.lang.module.ModuleFinder;
import java.nio.file.Path;
import java.util.ArrayList;
public class LaunchModuleWorkflow extends AbstractSpaceWorkflow {
private final Command<?> command;
public LaunchModuleWorkflow(Bach bach, Project project, ProjectSpace space, Command<?> command) {
super(bach, project, space);
this.command = command;
}
protected ModuleFinder computeRuntimeModuleFinder() {
var paths = new ArrayList<Path>();
paths.add(computeOutputDirectoryForModules(space));
paths.addAll(computeModulePathsOption().values());
return ModuleFinder.of(paths.toArray(Path[]::new));
}
protected ToolCall computeToolCall() {
var finder = computeRuntimeModuleFinder();
return ToolCall.module(finder, command);
}
protected void visitToolRun(ToolRun run) {
bach.printer().print(run);
}
@Override
public void run() {
var call = computeToolCall();
var run = bach.run(call);
visitToolRun(run);
}
}
| 28.4 | 99 | 0.746479 |
119f960cba3c69514db6d0e1798a923cc5c1703a
| 268 |
package com.boot.edu.healthcare.service;
import com.boot.edu.healthcare.domain.Doctor;
import java.util.List;
/**
* @author Sergey Zhernovoy
* create on 03.01.2018.
*/
public interface DoctorService {
List<Doctor> find(String location, String speciality);
}
| 19.142857 | 58 | 0.742537 |
e45bfb8443fe01c29d6a16d0de270f56ece20746
| 19,534 |
package com.kickstarter.dropwizard.metrics.influxdb.transformer;
import com.codahale.metrics.Counter;
import com.codahale.metrics.ExponentiallyDecayingReservoir;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.Meter;
import com.codahale.metrics.Timer;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.kickstarter.dropwizard.metrics.influxdb.InfluxDbMeasurement;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class DropwizardTransformerTest {
@Test
public void testConvertDuration_Milliseconds() {
final DropwizardTransformer transformer = transformerWithUnits(TimeUnit.SECONDS, TimeUnit.MILLISECONDS);
assertEquals("Should convert duration to milliseconds precisely", 2.0E-5, transformer.convertDuration(20), 0.0);
}
@Test
public void testConvertDuration_Seconds() {
final DropwizardTransformer transformer = transformerWithUnits(TimeUnit.SECONDS, TimeUnit.SECONDS);
assertEquals("Should convert duration to seconds precisely", 2.0E-8, transformer.convertDuration(20), 0.0);
}
@Test
public void testConvertRate_Seconds() {
final DropwizardTransformer transformer = transformerWithUnits(TimeUnit.SECONDS, TimeUnit.MILLISECONDS);
assertEquals("Should convert rate to seconds precisely", 20.0, transformer.convertRate(20), 0.0);
}
@Test
public void testConvertRate_Minutes() {
final DropwizardTransformer transformer = transformerWithUnits(TimeUnit.MINUTES, TimeUnit.MILLISECONDS);
assertEquals("Should convert rate to minutes precisely", 1200.0, transformer.convertRate(20), 0.0);
}
@Test
public void testFromTimer() {
final Set<String> fieldKeys = ImmutableSet.of(
"count",
"min",
"max",
"mean",
"std-dev",
"50-percentile",
"75-percentile",
"95-percentile",
"99-percentile",
"999-percentile",
"one-minute",
"five-minute",
"fifteen-minute",
"mean-minute",
"run-count"
);
final DropwizardMeasurementParser parser = mock(DropwizardMeasurementParser.class);
final DropwizardTransformer transformer = transformerWithParser(parser, true);
when(parser.parse("some.metric.name")).thenReturn(
DropwizardMeasurement.create("Measurement", MEASUREMENT_TAGS, Optional.empty())
);
final Timer timer = new Timer();
timer.update(50, TimeUnit.MILLISECONDS);
timer.update(70, TimeUnit.MILLISECONDS);
timer.update(100, TimeUnit.MILLISECONDS);
final InfluxDbMeasurement measurement = transformer.fromTimer("some.metric.name", timer, 90210L);
assertEquals("should parse name from full metric key", "Measurement", measurement.name());
assertEquals("should add global and measurement tags", ALL_TAGS, measurement.tags());
assertEquals("should timestamp measurement", 90210L, measurement.timestamp());
assertEquals("should add all timer fields", fieldKeys, measurement.fields().keySet());
}
@Test
public void testFromMeter() {
final Set<String> fieldKeys = ImmutableSet.of(
"count",
"one-minute",
"five-minute",
"fifteen-minute",
"mean-minute"
);
final DropwizardMeasurementParser parser = mock(DropwizardMeasurementParser.class);
final DropwizardTransformer transformer = transformerWithParser(parser, true);
when(parser.parse("some.metric.name")).thenReturn(
DropwizardMeasurement.create("Measurement", MEASUREMENT_TAGS, Optional.empty())
);
final Meter meter = new Meter();
meter.mark(50L);
meter.mark(64L);
meter.mark(80L);
final InfluxDbMeasurement measurement = transformer.fromMeter("some.metric.name", meter, 90210L);
assertEquals("should parse name from full metric key", "Measurement", measurement.name());
assertEquals("should add global and measurement tags", ALL_TAGS, measurement.tags());
assertEquals("should timestamp measurement", 90210L, measurement.timestamp());
assertEquals("should add all meter fields", fieldKeys, measurement.fields().keySet());
}
@Test
public void testFromHistogram() {
final Set<String> fieldKeys = ImmutableSet.of(
"count",
"min",
"max",
"mean",
"std-dev",
"50-percentile",
"75-percentile",
"95-percentile",
"99-percentile",
"999-percentile",
"run-count"
);
final DropwizardMeasurementParser parser = mock(DropwizardMeasurementParser.class);
final DropwizardTransformer transformer = transformerWithParser(parser, true);
when(parser.parse("some.metric.name")).thenReturn(
DropwizardMeasurement.create("Measurement", MEASUREMENT_TAGS, Optional.empty())
);
final Histogram histogram = new Histogram(new ExponentiallyDecayingReservoir());
histogram.update(15L);
histogram.update(70L);
histogram.update(100L);
final InfluxDbMeasurement measurement = transformer.fromHistogram("some.metric.name", histogram, 90210L);
assertEquals("should parse name from full metric key", "Measurement", measurement.name());
assertEquals("should add global and measurement tags", ALL_TAGS, measurement.tags());
assertEquals("should timestamp measurement", 90210L, measurement.timestamp());
assertEquals("should add all histogram fields", fieldKeys, measurement.fields().keySet());
}
@Test
public void testFromCounters_Ungrouped() {
final DropwizardMeasurementParser parser = mock(DropwizardMeasurementParser.class);
final DropwizardTransformer transformer = transformerWithParser(parser, false);
final List<Counter> counters = ImmutableList.of(new Counter(), new Counter());
counters.get(0).inc(15L);
counters.get(1).inc(6L);
final Map<String, Counter> cMap = ImmutableMap.of(
"some.stuff.queued", counters.get(0),
"some.stuff.processed", counters.get(1)
);
when(parser.parse("some.stuff.queued")).thenReturn(
DropwizardMeasurement.create("some.stuff.queued", MEASUREMENT_TAGS, Optional.empty())
);
when(parser.parse("some.stuff.processed")).thenReturn(
DropwizardMeasurement.create("some.stuff.processed", MEASUREMENT_TAGS, Optional.empty())
);
final List<InfluxDbMeasurement> expected = ImmutableList.of(
InfluxDbMeasurement.create("some.stuff.queued", ALL_TAGS, ImmutableMap.of("count", "15i"), 90210L),
InfluxDbMeasurement.create("some.stuff.processed", ALL_TAGS, ImmutableMap.of("count", "6i"), 90210L)
);
final List<InfluxDbMeasurement> measurements = transformer.fromCounters(cMap, 90210L);
assertEquals("should not group counter measurements", expected, measurements);
}
@Test
public void testFromCounters_Grouped() {
final DropwizardMeasurementParser parser = mock(DropwizardMeasurementParser.class);
final DropwizardTransformer transformer = transformerWithParser(parser, true);
final List<Counter> counters = ImmutableList.of(new Counter(), new Counter());
counters.get(0).inc(15L);
counters.get(1).inc(6L);
final Map<String, Counter> cMap = ImmutableMap.of(
"some.stuff.queued", counters.get(0),
"some.stuff.processed", counters.get(1)
);
when(parser.parse("some.stuff")).thenReturn(
DropwizardMeasurement.create("some.stuff", MEASUREMENT_TAGS, Optional.empty())
);
final List<InfluxDbMeasurement> expected = ImmutableList.of(
InfluxDbMeasurement.create("some.stuff", ALL_TAGS, ImmutableMap.of("queued", "15i", "processed", "6i"), 90210L)
);
final List<InfluxDbMeasurement> measurements = transformer.fromCounters(cMap, 90210L);
assertEquals("should group counters by tags and prefix", expected, measurements);
}
@Test
public void testFromGauges_Ungrouped() {
final DropwizardMeasurementParser parser = mock(DropwizardMeasurementParser.class);
final DropwizardTransformer transformer = transformerWithParser(parser, false);
final Map<String, Gauge> gauges = ImmutableMap.of(
"some.stuff.queued", () -> 12,
"some.stuff.processed", () -> 15
);
when(parser.parse("some.stuff.queued")).thenReturn(
DropwizardMeasurement.create("some.stuff.queued", MEASUREMENT_TAGS, Optional.empty())
);
when(parser.parse("some.stuff.processed")).thenReturn(
DropwizardMeasurement.create("some.stuff.processed", MEASUREMENT_TAGS, Optional.empty())
);
final List<InfluxDbMeasurement> expected = ImmutableList.of(
InfluxDbMeasurement.create("some.stuff.queued", ALL_TAGS, ImmutableMap.of("value", "12i"), 90210L),
InfluxDbMeasurement.create("some.stuff.processed", ALL_TAGS, ImmutableMap.of("value", "15i"), 90210L)
);
final List<InfluxDbMeasurement> measurements = transformer.fromGauges(gauges, 90210L);
assertEquals("should not group gauge measurements", expected, measurements);
}
@Test
public void testFromGauges_Grouped() {
final DropwizardMeasurementParser parser = mock(DropwizardMeasurementParser.class);
final DropwizardTransformer transformer = transformerWithParser(parser, true);
final Map<String, Gauge> gauges = ImmutableMap.of(
"some.stuff.queued", () -> 12,
"some.stuff.processed", () -> 15
);
when(parser.parse("some.stuff")).thenReturn(
DropwizardMeasurement.create("some.stuff", MEASUREMENT_TAGS, Optional.empty())
);
final List<InfluxDbMeasurement> expected = ImmutableList.of(
InfluxDbMeasurement.create("some.stuff", ALL_TAGS, ImmutableMap.of("queued", "12i", "processed", "15i"), 90210L)
);
final List<InfluxDbMeasurement> measurements = transformer.fromGauges(gauges, 90210L);
assertEquals("should group gauges by tags and prefix", expected, measurements);
}
@Test
public void testFromKeyValue() {
final DropwizardMeasurementParser parser = mock(DropwizardMeasurementParser.class);
final DropwizardTransformer transformer = transformerWithParser(parser, false);
when(parser.parse("some.stuff.queued")).thenReturn(
DropwizardMeasurement.create("some.stuff.queued", MEASUREMENT_TAGS, Optional.empty())
);
final InfluxDbMeasurement measurement = transformer.fromKeyValue("some.stuff.queued", "some_key", 12L, 90210L);
assertEquals("should map values directly to measurement",
InfluxDbMeasurement.create("some.stuff.queued", ALL_TAGS, ImmutableMap.of("some_key", "12i"), 90210L),
measurement);
}
@Test
public void testGroupValues_Inline() {
final DropwizardMeasurementParser parser = mock(DropwizardMeasurementParser.class);
final DropwizardTransformer transformer = transformerWithParser(parser, true);
final Map<String, Gauge> gauges = ImmutableMap.of(
"Measurement queued", () -> 12,
"Measurement processed", () -> 15
);
when(parser.parse("Measurement queued")).thenReturn(
DropwizardMeasurement.create("Measurement", MEASUREMENT_TAGS, Optional.of("queued"))
);
when(parser.parse("Measurement processed")).thenReturn(
DropwizardMeasurement.create("Measurement", MEASUREMENT_TAGS, Optional.of("processed"))
);
final Map<GroupKey, Map<String, Object>> expected = ImmutableMap.of(
GroupKey.create("Measurement", MEASUREMENT_TAGS), ImmutableMap.of("queued", 12, "processed", 15)
);
final Map<GroupKey, Map<String, Object>> groups = transformer.groupValues(gauges, "unused_default_key", Gauge::getValue);
assertEquals("should group values with inlined keys", expected, groups);
}
@Test
public void testGroupValues_CountingGauges() {
final DropwizardMeasurementParser parser = mock(DropwizardMeasurementParser.class);
final DropwizardTransformer transformer = transformerWithParser(parser, true);
final Map<String, Gauge> gauges = ImmutableMap.of(
"some.stuff.queued.count", () -> 12,
"some.stuff.processed.count", () -> 15
);
when(parser.parse("some.stuff")).thenReturn(
DropwizardMeasurement.create("some.stuff", MEASUREMENT_TAGS, Optional.empty())
);
final Map<GroupKey, Map<String, Object>> expected = ImmutableMap.of(
GroupKey.create("some.stuff", MEASUREMENT_TAGS), ImmutableMap.of("queued.count", 12, "processed.count", 15)
);
final Map<GroupKey, Map<String, Object>> groups = transformer.groupValues(gauges, "unused_default_key", Gauge::getValue);
assertEquals("should ignore .count postfix when parsing groups", expected, groups);
}
@Test
public void testGroupValues_NoDotIndex() {
final DropwizardMeasurementParser parser = mock(DropwizardMeasurementParser.class);
final DropwizardTransformer transformer = transformerWithParser(parser, true);
final Map<String, Gauge> gauges = ImmutableMap.of(
"some_stuff_queued", () -> 12,
"some_stuff_processed", () -> 15
);
when(parser.parse("some_stuff_queued")).thenReturn(
DropwizardMeasurement.create("some.stuff.queued", MEASUREMENT_TAGS, Optional.empty())
);
when(parser.parse("some_stuff_processed")).thenReturn(
DropwizardMeasurement.create("some.stuff.processed", MEASUREMENT_TAGS, Optional.empty())
);
final Map<GroupKey, Map<String, Object>> expected = ImmutableMap.of(
GroupKey.create("some.stuff.queued", MEASUREMENT_TAGS), ImmutableMap.of("default_key", 12),
GroupKey.create("some.stuff.processed", MEASUREMENT_TAGS), ImmutableMap.of("default_key", 15)
);
final Map<GroupKey, Map<String, Object>> groups = transformer.groupValues(gauges, "default_key", Gauge::getValue);
assertEquals("should use fully parsed key and default value", expected, groups);
}
@Test
public void testGroupValues_WithDotIndex() {
final DropwizardMeasurementParser parser = mock(DropwizardMeasurementParser.class);
final DropwizardTransformer transformer = transformerWithParser(parser, true);
final Map<String, Gauge> gauges = ImmutableMap.of(
"some.stuff.queued", () -> 12,
"some.stuff.processed", () -> 15
);
when(parser.parse("some.stuff")).thenReturn(
DropwizardMeasurement.create("some.stuff", MEASUREMENT_TAGS, Optional.empty())
);
final Map<GroupKey, Map<String, Object>> expected = ImmutableMap.of(
GroupKey.create("some.stuff", MEASUREMENT_TAGS), ImmutableMap.of("queued", 12, "processed", 15)
);
final Map<GroupKey, Map<String, Object>> groups = transformer.groupValues(gauges, "unused_default_key", Gauge::getValue);
assertEquals("should group values by field postfix", expected, groups);
}
@Test
public void testGroupValues_WithSeparateTags() {
final DropwizardMeasurementParser parser = mock(DropwizardMeasurementParser.class);
final DropwizardTransformer transformer = transformerWithParser(parser, true);
final Map<String, Gauge> gauges = ImmutableMap.of(
"some.jumping.stuff.queued", () -> 12,
"some.leaning.stuff.processed", () -> 15
);
final ImmutableMap<String, String> jumpingTag = ImmutableMap.of("action", "jumping");
final ImmutableMap<String, String> leaningTag = ImmutableMap.of("action", "leaning");
when(parser.parse("some.jumping.stuff")).thenReturn(
DropwizardMeasurement.create("some.stuff", jumpingTag, Optional.empty())
);
when(parser.parse("some.leaning.stuff")).thenReturn(
DropwizardMeasurement.create("some.stuff", leaningTag, Optional.empty())
);
final Map<GroupKey, Map<String, Object>> expected = ImmutableMap.of(
GroupKey.create("some.stuff", jumpingTag), ImmutableMap.of("queued", 12),
GroupKey.create("some.stuff", leaningTag), ImmutableMap.of("processed", 15)
);
final Map<GroupKey, Map<String, Object>> groups = transformer.groupValues(gauges, "unused_default_key", Gauge::getValue);
assertEquals("should separate measurements by tag", expected, groups);
}
@Test
public void testFromValueGroup() {
final DropwizardMeasurementParser parser = mock(DropwizardMeasurementParser.class);
final DropwizardTransformer transformer = transformerWithParser(parser, true);
final Map<String, Object> objFields = ImmutableMap.of(
"some", true,
"fields", 5
);
final Map<String, String> strFields = ImmutableMap.of(
"some", "true",
"fields", "5i"
);
assertEquals("should convert value group to influx measurement with global tags and stringy fields",
Optional.of(InfluxDbMeasurement.create("Measurement", ALL_TAGS, strFields, 90210L)),
transformer.fromValueGroup(GroupKey.create("Measurement", MEASUREMENT_TAGS), objFields, 90210L));
}
@Test
public void testFromValueGroup_InvalidField() {
final DropwizardMeasurementParser parser = mock(DropwizardMeasurementParser.class);
final DropwizardTransformer transformer = transformerWithParser(parser, true);
final GroupKey key = GroupKey.create("Measurement", MEASUREMENT_TAGS);
final Map<String, Object> objFields = ImmutableMap.of(
"some", true,
"bad", Arrays.asList(1, 2, 3),
"fields", 5,
"NOW", ImmutableMap.of("ha", "ha")
);
final Map<String, String> strFields = ImmutableMap.of(
"some", "true",
"bad", "[1, 2, 3]",
"fields", "5i"
);
assertEquals("should silently drop invalid values",
Optional.of(InfluxDbMeasurement.create("Measurement", ALL_TAGS, strFields, 90210L)),
transformer.fromValueGroup(key, objFields, 90210L));
}
@Test
public void testFromValueGroup_InvalidMeasurement() {
final DropwizardMeasurementParser parser = mock(DropwizardMeasurementParser.class);
final DropwizardTransformer transformer = transformerWithParser(parser, true);
final GroupKey key = GroupKey.create("Measurement", MEASUREMENT_TAGS);
final Map<String, Object> objFields = ImmutableMap.of(
"all", Float.NaN,
"bad", ImmutableMap.of("oh", "no"),
"fields", Float.NaN
);
assertEquals("should silently drop invalid measurements",
Optional.empty(),
transformer.fromValueGroup(key, objFields, 90210L));
}
// ===================================================================================================================
// Test helpers
private static final ImmutableMap<String, String> BASE_TAGS = ImmutableMap.of(
"some", "simple",
"global", "tags"
);
private static final ImmutableMap<String, String> MEASUREMENT_TAGS = ImmutableMap.of(
"more", "specific",
"measurement", "tags"
);
private static final ImmutableMap<String, String> ALL_TAGS = new ImmutableMap.Builder<String, String>()
.putAll(BASE_TAGS)
.putAll(MEASUREMENT_TAGS)
.build();
private static DropwizardTransformer transformerWithParser(final DropwizardMeasurementParser parser, final boolean group) {
return new DropwizardTransformer(
BASE_TAGS,
parser,
group,
group,
// Dropwizard Defaults
TimeUnit.SECONDS,
TimeUnit.MILLISECONDS
);
}
private static DropwizardTransformer transformerWithUnits(final TimeUnit rateUnits, final TimeUnit durationUnits) {
return new DropwizardTransformer(
ImmutableMap.of(),
DropwizardMeasurementParser.withTemplates(ImmutableMap.of()),
true,
true,
rateUnits,
durationUnits
);
}
}
| 38.604743 | 125 | 0.714395 |
22b089c1069928169e72f227e0e2267394d71c6b
| 660 |
package de.centerdevice.classcleaner;
import org.eclipse.ui.plugin.AbstractUIPlugin;
public class ClassCleanerPlugin extends AbstractUIPlugin {
public static final String ANALYZER_METHOD_CLUSTER = "ANALYZER_METHOD_CLUSTER";
public static final String ANALYZER_FOREIGN_METHOD = "ANALYZER_FOREIGN_METHOD";
public static final String ANALYZER_UNUSED_METHOD = "ANALYZER_UNUSED_METHOD";
public static final String DEFAULT_REFERENCE_SCOPE = "DEFAULT_REFERENCE_SCOPE";
private static ClassCleanerPlugin plugin = null;
public static ClassCleanerPlugin getDefault() {
if (plugin == null) {
plugin = new ClassCleanerPlugin();
}
return plugin;
}
}
| 28.695652 | 80 | 0.804545 |
d562dc2d782125f0217d91de064520d3f45ba0fc
| 18,208 |
package org.alfresco.rest.servlet;
import io.restassured.RestAssured;
import org.alfresco.rest.RestTest;
import org.alfresco.rest.core.RestRequest;
import org.alfresco.rest.core.RestResponse;
import org.alfresco.utility.model.FileModel;
import org.alfresco.utility.model.FileType;
import org.alfresco.utility.model.FolderModel;
import org.alfresco.utility.model.SiteModel;
import org.alfresco.utility.model.TestGroup;
import org.alfresco.utility.model.UserModel;
import org.alfresco.utility.report.Bug;
import org.alfresco.utility.testrail.ExecutionType;
import org.alfresco.utility.testrail.annotation.TestRail;
import org.apache.commons.codec.binary.Base64;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
public class DownloadContentServletTests extends RestTest
{
private static final String CONTENT_DISPOSITION = "Content-Disposition";
private static final String FILENAME_HEADER = "filename=\"%s\"";
private static final String ATTACHMENT = "attachment";
private static final String FILE_CONTENT = "The content of the file.";
private static String downloadContentServletAttach = "alfresco/d/a/workspace/SpacesStore/";
private static String downloadContentServletDirect = "alfresco/d/d/workspace/SpacesStore/";
private UserModel testUser;
private FileModel testContentFile;
private String authHeaderEncoded;
@BeforeClass(alwaysRun = true)
public void dataPreparation() throws Exception
{
testUser = dataUser.createRandomTestUser();
SiteModel testSite = dataSite.usingUser(testUser).createPublicRandomSite();
FolderModel testFolder = dataContent.usingUser(testUser).usingSite(testSite).createFolder();
testContentFile = dataContent.usingUser(testUser).usingResource(testFolder)
.createContent(new FileModel("hotOuside", FileType.TEXT_PLAIN, FILE_CONTENT));
String authHeader = String.format("%s:%s", testUser.getUsername(), testUser.getPassword());
authHeaderEncoded = new String(Base64.encodeBase64(authHeader.getBytes()));
RestAssured.basePath = "";
restClient.configureRequestSpec().setBasePath(RestAssured.basePath);
}
@TestRail(section = { TestGroup.REST_API },
executionType = ExecutionType.REGRESSION,
description = "Verify DownloadContentServlet retrieve content using short descriptor and attach short descriptor.")
@Test(groups = { TestGroup.REST_API, TestGroup.FULL, TestGroup.ENTERPRISE})
@Bug(id ="MNT-21602", status=Bug.Status.FIXED)
public void verifyDCSShortAttachShort()
{
authenticateTestUser();
RestRequest request = RestRequest.simpleRequest(
HttpMethod.GET, downloadContentServletAttach + testContentFile.getNodeRef() + "/" + testContentFile.getName());
RestResponse response = restClient.process(request);
restClient.assertStatusCodeIs(HttpStatus.OK);
assertEquals(FILE_CONTENT, response.getResponse().body().asString());
restClient.assertHeaderValueContains(CONTENT_DISPOSITION, ATTACHMENT);
restClient.assertHeaderValueContains(CONTENT_DISPOSITION, String.format(FILENAME_HEADER, testContentFile.getName()));
}
@TestRail(section = { TestGroup.REST_API },
executionType = ExecutionType.REGRESSION,
description = "Verify DownloadContentServlet retrieve content using short descriptor and attach long descriptor.")
@Test(groups = { TestGroup.REST_API, TestGroup.FULL, TestGroup.ENTERPRISE})
@Bug(id ="MNT-21602", status=Bug.Status.FIXED)
public void verifyDCSShortAttachLong()
{
authenticateTestUser();
String downloadContentServletAttachLong = "alfresco/d/attach/workspace/SpacesStore/";
RestRequest request = RestRequest.simpleRequest(HttpMethod.GET,
downloadContentServletAttachLong + testContentFile.getNodeRef() + "/" + testContentFile.getName());
RestResponse response = restClient.process(request);
restClient.assertStatusCodeIs(HttpStatus.OK);
assertEquals(FILE_CONTENT, response.getResponse().body().asString());
restClient.assertHeaderValueContains(CONTENT_DISPOSITION, ATTACHMENT);
restClient.assertHeaderValueContains(CONTENT_DISPOSITION, String.format(FILENAME_HEADER, testContentFile.getName()));
}
@TestRail(section = { TestGroup.REST_API },
executionType = ExecutionType.REGRESSION,
description = "Verify DownloadContentServlet retrieve content using short descriptor and direct short descriptor.")
@Test(groups = { TestGroup.REST_API, TestGroup.FULL, TestGroup.ENTERPRISE})
@Bug(id ="MNT-21602", status=Bug.Status.FIXED)
public void verifyDCSShortDirectShort()
{
authenticateTestUser();
RestRequest request = RestRequest.simpleRequest(HttpMethod.GET,
downloadContentServletDirect + testContentFile.getNodeRef() + "/" + testContentFile.getName());
RestResponse response = restClient.process(request);
restClient.assertStatusCodeIs(HttpStatus.OK);
assertEquals(FILE_CONTENT, response.getResponse().body().asString());
restClient.assertHeaderValueContains(CONTENT_DISPOSITION, ATTACHMENT);
restClient.assertHeaderValueContains(CONTENT_DISPOSITION, String.format(FILENAME_HEADER, testContentFile.getName()));
}
@TestRail(section = { TestGroup.REST_API },
executionType = ExecutionType.REGRESSION,
description = "Verify DownloadContentServlet retrieve content using short descriptor and direct long descriptor.")
@Test(groups = { TestGroup.REST_API, TestGroup.FULL, TestGroup.ENTERPRISE})
@Bug(id ="MNT-21602", status=Bug.Status.FIXED)
public void verifyDCSShortDirectLong()
{
authenticateTestUser();
String downloadContentServletDirectLong = "alfresco/d/direct/workspace/SpacesStore/";
RestRequest request = RestRequest.simpleRequest(HttpMethod.GET,
downloadContentServletDirectLong + testContentFile.getNodeRef() + "/" + testContentFile.getName());
RestResponse response = restClient.process(request);
restClient.assertStatusCodeIs(HttpStatus.OK);
assertEquals(FILE_CONTENT, response.getResponse().body().asString());
restClient.assertHeaderValueContains(CONTENT_DISPOSITION, ATTACHMENT);
restClient.assertHeaderValueContains(CONTENT_DISPOSITION, String.format(FILENAME_HEADER, testContentFile.getName()));
}
@TestRail(section = { TestGroup.REST_API },
executionType = ExecutionType.REGRESSION,
description = "Verify DownloadContentServlet retrieve content using long descriptor and attach short descriptor.")
@Test(groups = { TestGroup.REST_API, TestGroup.FULL, TestGroup.ENTERPRISE})
@Bug(id ="MNT-21602", status=Bug.Status.FIXED)
public void verifyDCSLongAttachShort()
{
authenticateTestUser();
String downloadContentLongServletAttach = "alfresco/download/a/workspace/SpacesStore/";
RestRequest request = RestRequest.simpleRequest(HttpMethod.GET,
downloadContentLongServletAttach + testContentFile.getNodeRef() + "/" + testContentFile.getName());
RestResponse response = restClient.process(request);
restClient.assertStatusCodeIs(HttpStatus.OK);
assertEquals(FILE_CONTENT, response.getResponse().body().asString());
restClient.assertHeaderValueContains(CONTENT_DISPOSITION, ATTACHMENT);
restClient.assertHeaderValueContains(CONTENT_DISPOSITION, String.format(FILENAME_HEADER, testContentFile.getName()));
}
@TestRail(section = { TestGroup.REST_API },
executionType = ExecutionType.REGRESSION,
description = "Verify DownloadContentServlet retrieve content using long descriptor and attach long descriptor.")
@Test(groups = { TestGroup.REST_API, TestGroup.FULL, TestGroup.ENTERPRISE})
@Bug(id ="MNT-21602", status=Bug.Status.FIXED)
public void verifyDCSLongAttachLong()
{
authenticateTestUser();
String downloadContentLongServletAttachLong = "alfresco/download/attach/workspace/SpacesStore/";
RestRequest request = RestRequest.simpleRequest(HttpMethod.GET,
downloadContentLongServletAttachLong + testContentFile.getNodeRef() + "/" + testContentFile.getName());
RestResponse response = restClient.process(request);
restClient.assertStatusCodeIs(HttpStatus.OK);
assertEquals(FILE_CONTENT, response.getResponse().body().asString());
restClient.assertHeaderValueContains(CONTENT_DISPOSITION, ATTACHMENT);
restClient.assertHeaderValueContains(CONTENT_DISPOSITION, String.format(FILENAME_HEADER, testContentFile.getName()));
}
@TestRail(section = { TestGroup.REST_API },
executionType = ExecutionType.REGRESSION,
description = "Verify DownloadContentServlet retrieve content using long descriptor and direct short descriptor.")
@Test(groups = { TestGroup.REST_API, TestGroup.FULL, TestGroup.ENTERPRISE})
@Bug(id ="MNT-21602", status=Bug.Status.FIXED)
public void verifyDCSLongDirectShort()
{
authenticateTestUser();
String downloadContentLongServletDirect = "alfresco/download/d/workspace/SpacesStore/";
RestRequest request = RestRequest.simpleRequest(HttpMethod.GET,
downloadContentLongServletDirect + testContentFile.getNodeRef() + "/" + testContentFile.getName());
RestResponse response = restClient.process(request);
restClient.assertStatusCodeIs(HttpStatus.OK);
assertEquals(FILE_CONTENT, response.getResponse().body().asString());
restClient.assertHeaderValueContains(CONTENT_DISPOSITION, ATTACHMENT);
restClient.assertHeaderValueContains(CONTENT_DISPOSITION, String.format(FILENAME_HEADER, testContentFile.getName()));
}
@TestRail(section = { TestGroup.REST_API },
executionType = ExecutionType.REGRESSION,
description = "Verify DownloadContentServlet retrieve content using long descriptor and direct long descriptor.")
@Test(groups = { TestGroup.REST_API, TestGroup.FULL, TestGroup.ENTERPRISE})
@Bug(id ="MNT-21602", status=Bug.Status.FIXED)
public void verifyDCSLongDirectLong()
{
authenticateTestUser();
String downloadContentLongServletDirectLong = "alfresco/download/direct/workspace/SpacesStore/";
RestRequest request = RestRequest.simpleRequest(HttpMethod.GET,
downloadContentLongServletDirectLong + testContentFile.getNodeRef() + "/" + testContentFile.getName());
RestResponse response = restClient.process(request);
restClient.assertStatusCodeIs(HttpStatus.OK);
assertEquals(FILE_CONTENT, response.getResponse().body().asString());
restClient.assertHeaderValueContains(CONTENT_DISPOSITION, ATTACHMENT);
restClient.assertHeaderValueContains(CONTENT_DISPOSITION, String.format(FILENAME_HEADER, testContentFile.getName()));
}
@TestRail(section = { TestGroup.REST_API },
executionType = ExecutionType.REGRESSION,
description = "Verify DownloadContentServlet retrieve content using short descriptor and attach short uppercase descriptor.")
@Test(groups = { TestGroup.REST_API, TestGroup.FULL, TestGroup.ENTERPRISE})
@Bug(id ="MNT-21602", status=Bug.Status.FIXED)
public void verifyDCSShortAttachUppercaseShort()
{
authenticateTestUser();
String downloadContentAttachUppercase = "alfresco/d/A/workspace/SpacesStore/";
RestRequest request = RestRequest.simpleRequest(HttpMethod.GET,
downloadContentAttachUppercase + testContentFile.getNodeRef() + "/" + testContentFile.getName());
RestResponse response = restClient.process(request);
restClient.assertStatusCodeIs(HttpStatus.OK);
assertEquals(FILE_CONTENT, response.getResponse().body().asString());
restClient.assertHeaderValueContains(CONTENT_DISPOSITION, ATTACHMENT);
restClient.assertHeaderValueContains(CONTENT_DISPOSITION, String.format(FILENAME_HEADER, testContentFile.getName()));
}
@TestRail(section = { TestGroup.REST_API },
executionType = ExecutionType.REGRESSION,
description = "Verify DownloadContentServlet retrieve content using short descriptor and direct short uppercase descriptor.")
@Test(groups = { TestGroup.REST_API, TestGroup.FULL, TestGroup.ENTERPRISE})
@Bug(id ="MNT-21602", status=Bug.Status.FIXED)
public void verifyDCSShortDirectUppercaseShort()
{
authenticateTestUser();
String downloadContentDirectUppercase = "alfresco/d/D/workspace/SpacesStore/";
RestRequest request = RestRequest.simpleRequest(HttpMethod.GET,
downloadContentDirectUppercase + testContentFile.getNodeRef() + "/" + testContentFile.getName());
RestResponse response = restClient.process(request);
restClient.assertStatusCodeIs(HttpStatus.OK);
assertEquals(FILE_CONTENT, response.getResponse().body().asString());
restClient.assertHeaderValueContains(CONTENT_DISPOSITION, ATTACHMENT);
restClient.assertHeaderValueContains(CONTENT_DISPOSITION, String.format(FILENAME_HEADER, testContentFile.getName()));
}
@TestRail(section = { TestGroup.REST_API },
executionType = ExecutionType.REGRESSION,
description = "Verify DownloadContentServlet retrieve content using attach without specifying {storeType}.")
@Test(groups = { TestGroup.REST_API, TestGroup.FULL, TestGroup.ENTERPRISE})
@Bug(id ="MNT-21602", status=Bug.Status.FIXED)
public void verifyDCSAttachWithoutStoreType()
{
authenticateTestUser();
String downloadContentLessPathAttach = "alfresco/d/a/SpacesStore/";
RestRequest request = RestRequest.simpleRequest(HttpMethod.GET,
downloadContentLessPathAttach + testContentFile.getNodeRef() + "/" + testContentFile.getName());
restClient.process(request);
restClient.assertStatusCodeIs(HttpStatus.INTERNAL_SERVER_ERROR);
}
@TestRail(section = { TestGroup.REST_API },
executionType = ExecutionType.REGRESSION,
description = "Verify DownloadContentServlet retrieve content using direct without specifying {storeType}.")
@Test(groups = { TestGroup.REST_API, TestGroup.FULL, TestGroup.ENTERPRISE})
@Bug(id ="MNT-21602", status=Bug.Status.FIXED)
public void verifyDCSDirectWithoutStoreType()
{
authenticateTestUser();
String downloadContentLessPathDirect = "alfresco/d/d/SpacesStore/";
RestRequest request = RestRequest.simpleRequest(HttpMethod.GET,
downloadContentLessPathDirect + testContentFile.getNodeRef() + "/" + testContentFile.getName());
restClient.process(request);
restClient.assertStatusCodeIs(HttpStatus.INTERNAL_SERVER_ERROR);
}
@TestRail(section = { TestGroup.REST_API },
executionType = ExecutionType.REGRESSION,
description = "Verify DownloadContentServlet retrieve content using direct without specifying {storeType}.")
@Test(groups = { TestGroup.REST_API, TestGroup.FULL, TestGroup.ENTERPRISE})
@Bug(id ="MNT-21602", status=Bug.Status.FIXED)
public void verifyDCSDirectWithInvalidStoreType()
{
authenticateTestUser();
String downloadContentLessPathDirect = "alfresco/download/d/badWorkspace/SpacesStore/";
RestRequest request = RestRequest.simpleRequest(HttpMethod.GET,
downloadContentLessPathDirect + testContentFile.getNodeRef() + "/" + testContentFile.getName());
restClient.process(request);
restClient.assertStatusCodeIs(HttpStatus.INTERNAL_SERVER_ERROR);
}
@TestRail(section = { TestGroup.REST_API },
executionType = ExecutionType.REGRESSION,
description = "Verify DownloadContentServlet retrieve content using direct without specifying {storeType}.")
@Test(groups = { TestGroup.REST_API, TestGroup.FULL, TestGroup.ENTERPRISE})
@Bug(id ="MNT-21602", status=Bug.Status.FIXED)
public void verifyDCSDirectWithInvalidStoreId()
{
authenticateTestUser();
String downloadContentLessPathDirect = "alfresco/download/d/workspace/badSpacesStore/";
RestRequest request = RestRequest.simpleRequest(HttpMethod.GET,
downloadContentLessPathDirect + testContentFile.getNodeRef() + "/" + testContentFile.getName());
restClient.process(request);
restClient.assertStatusCodeIs(HttpStatus.INTERNAL_SERVER_ERROR);
}
@TestRail(section = { TestGroup.REST_API },
executionType = ExecutionType.REGRESSION,
description = "Verify DownloadContentServlet retrieve content using attach without authentication.")
@Test(groups = { TestGroup.REST_API, TestGroup.FULL, TestGroup.ENTERPRISE})
@Bug(id ="MNT-21602", status=Bug.Status.FIXED)
public void verifyDCSAttachWithoutAuthentication()
{
RestRequest request = RestRequest.simpleRequest(HttpMethod.GET,
downloadContentServletAttach + testContentFile.getNodeRef() + "/" + testContentFile.getName());
restClient.process(request);
restClient.assertStatusCodeIs(HttpStatus.UNAUTHORIZED);
}
@TestRail(section = { TestGroup.REST_API },
executionType = ExecutionType.REGRESSION,
description = "Verify DownloadContentServlet retrieve content using direct without authentication.")
@Test(groups = { TestGroup.REST_API, TestGroup.FULL, TestGroup.ENTERPRISE})
@Bug(id ="MNT-21602", status=Bug.Status.FIXED)
public void verifyDCSDirectWithoutAuthentication()
{
RestRequest request = RestRequest.simpleRequest(HttpMethod.GET,
downloadContentServletDirect + testContentFile.getNodeRef() + "/" + testContentFile.getName());
restClient.process(request);
restClient.assertStatusCodeIs(HttpStatus.UNAUTHORIZED);
}
private void authenticateTestUser()
{
restClient.configureRequestSpec()
.addHeader("Authorization", String.format("Basic %s", authHeaderEncoded))
.build();
}
}
| 56.024615 | 133 | 0.738631 |
1fa24708f078e5ba2833fa68895ad5cc10b3aff2
| 895 |
package in.hocg.boot.vars.autoconfiguration.jdbc;
import lombok.experimental.UtilityClass;
/**
* Created by hocgin on 2021/6/13
* email: hocgin@gmail.com
*
* @author hocgin
*/
@UtilityClass
public class TableVarsConfig {
public static final String TABLE_NAME = "boot_vars_config";
public static final String FIELD_ID = "id";
public static final String FIELD_VAR_KEY = "var_key";
public static final String FIELD_VAR_VALUE = "var_value";
public static final String FIELD_TITLE = "title";
public static final String FIELD_REMARK = "remark";
public static final String FIELD_ENABLED = "enabled";
public static final String FIELD_CREATED_AT = "created_at";
public static final String FIELD_CREATOR = "creator";
public static final String FIELD_LAST_UPDATED_AT = "last_updated_at";
public static final String FIELD_LAST_UPDATER = "last_updater";
}
| 34.423077 | 73 | 0.748603 |
72662fcee71e52b3ad08a2e247887f8efcd87401
| 1,232 |
package com.xymiao.cms.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xymiao.cms.util.ResponseBodyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component("customAuthenticationEntryPoint")
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
private Logger logger = LoggerFactory.getLogger(CustomAuthenticationSuccessHandler.class);
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
logger.info("没有登录, 请登录");
response.setStatus(200);
response.setContentType("application/json;charset=UTF-8");
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(response.getWriter(), ResponseBodyUtils.createByErrorCodeMessage(401,"没有登录, 请登录!"));
}
}
| 41.066667 | 160 | 0.810065 |
79d0f41c2b5c6364df969fc5e627112300d15381
| 184 |
public class Main {
public static void main(String[] args) {
Generator fractalGen = new Generator();
new Gui(fractalGen);
new Drawing(fractalGen);
}
}
| 20.444444 | 47 | 0.608696 |
9a53fdd4696364291694e9324e09d0c03f3bc484
| 619 |
package com.tasfe.framework.crud.api.dialect;
public class MySql5Dialect extends Dialect {
public String getLimitString(String querySqlString, int offset, int limit) {
return querySqlString + " limit " + offset + " ," + limit;
}
@Override
public String getCountString(String querySqlString) {
int limitIndex = querySqlString.lastIndexOf("limit");
if(limitIndex != -1){
querySqlString = querySqlString.substring(0, limitIndex != -1 ? limitIndex : querySqlString.length() - 1);
}
return "SELECT COUNT(*) FROM (" + querySqlString + ") tem";
}
public boolean supportsLimit() {
return true;
}
}
| 24.76 | 109 | 0.709208 |
fc360e10a498bc61024f0861b2b13e480a4da5fc
| 226 |
package br.com.alura.estoque.retrofit.callback;
interface MensagensCallback {
String MENSAGEM_ERRO_RESPOSTA_NAO_SUCEDIDA = "Resposta não sucedida";
String MENSAGEM_ERRO_FALHA_COMUNICACAO = "Fala de comunicação: ";
}
| 28.25 | 73 | 0.79646 |
f5892ad0afd991a3d35e239b06482ef77c314182
| 2,935 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.svn.actions;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.vcs.*;
import com.intellij.openapi.vfs.ReadonlyStatusHandler;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.idea.svn.SvnBundle;
import org.jetbrains.idea.svn.SvnVcs;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static com.intellij.util.containers.ContainerUtil.*;
public class ResolveAction extends BasicAction {
@NotNull
@Override
protected String getActionName() {
return SvnBundle.message("action.name.resolve.conflict");
}
@Override
protected boolean isEnabled(@NotNull SvnVcs vcs, @NotNull VirtualFile file) {
FileStatus status = FileStatusManager.getInstance(vcs.getProject()).getStatus(file);
return file.isDirectory() || FileStatus.MERGED_WITH_CONFLICTS.equals(status) || FileStatus.MERGED_WITH_BOTH_CONFLICTS.equals(status);
}
@Override
protected void perform(@NotNull SvnVcs vcs, @NotNull VirtualFile file, @NotNull DataContext context) throws VcsException {
batchPerform(vcs, ar(file), context);
}
@Override
protected void batchPerform(@NotNull SvnVcs vcs, @NotNull VirtualFile[] files, @NotNull DataContext context) {
boolean hasDirs = exists(files, VirtualFile::isDirectory);
List<VirtualFile> fileList = newArrayList();
if (!hasDirs) {
Collections.addAll(fileList, files);
}
else {
ProgressManager.getInstance().runProcessWithProgressSynchronously(() -> {
for (VirtualFile file : files) {
if (file.isDirectory()) {
ProjectLevelVcsManager.getInstance(vcs.getProject()).iterateVcsRoot(file, filePath -> {
ProgressManager.checkCanceled();
VirtualFile fileOrDir = filePath.getVirtualFile();
if (fileOrDir != null && !fileOrDir.isDirectory() && isEnabled(vcs, fileOrDir) && !fileList.contains(fileOrDir)) {
fileList.add(fileOrDir);
}
return true;
});
}
else {
if (!fileList.contains(file)) {
fileList.add(file);
}
}
}
}, SvnBundle.message("progress.searching.for.files.with.conflicts"), true, vcs.getProject());
}
ReadonlyStatusHandler.OperationStatus status = ReadonlyStatusHandler.getInstance(vcs.getProject()).ensureFilesWritable(fileList);
fileList.removeAll(Arrays.asList(status.getReadonlyFiles()));
AbstractVcsHelper.getInstance(vcs.getProject()).showMergeDialog(fileList, new SvnMergeProvider(vcs.getProject()));
}
@Override
protected boolean isBatchAction() {
return true;
}
}
| 37.628205 | 140 | 0.708688 |
79c510cacfe11f9c5b597fcf843068da29518255
| 8,905 |
import java.util.HashMap;
import java.util.HashSet;
import java.util.Random;
import java.util.Queue;
import java.util.LinkedList;
public class Lesson14_2 {
/**
* @Description: 图的结点
*/
public static Random rand = new Random();
/**
* 和之前一样,在讲座中可以省略
*
* @param user_nodes-用户的结点;user_id-给定的用户ID,我们要为这个用户查找好友
* @return void
* @Description: 通过广度优先搜索,查找好友
*/
public static void bfs(Node[] user_nodes, int user_id) {
if (user_id > user_nodes.length) return; // 防止数组越界的异常
Queue<Integer> queue = new LinkedList<Integer>(); // 用于广度优先搜索的队列
queue.offer(user_id); // 放入初始结点
HashSet<Integer> visited = new HashSet<>(); // 存放已经被访问过的结点,防止回路
visited.add(user_id);
while (!queue.isEmpty()) {
int current_user_id = queue.poll(); // 拿出队列头部的第一个结点
if (user_nodes[current_user_id] == null) continue;
// 遍历刚刚拿出的这个结点的所有直接连接结点,并加入队列尾部
for (int friend_id : user_nodes[current_user_id].friends) {
if (user_nodes[friend_id] == null) continue;
if (visited.contains(friend_id)) continue;
queue.offer(friend_id);
visited.add(friend_id); // 记录已经访问过的结点
user_nodes[friend_id].degree = user_nodes[current_user_id].degree + 1;
// 好友度数是当前结点的好友度数再加1
System.out.println(String.format("\t%d度好友:%d", user_nodes[friend_id].degree, friend_id));
}
}
}
/**
* @param user_nodes-用户的结点;user_id_a-用户a的ID;user_id_b-用户b的ID
* @return void
* @Description: 通过广度优先搜索,查找特定的好友
*/
public static void bfs(Node[] user_nodes, int user_id_a, int user_id_b) {
if (user_id_a > user_nodes.length) return; // 防止数组越界的异常
if (user_id_a == user_id_b) {
System.out.println(String.format("%d和%d两者是%d度好友", user_id_a, user_id_b, 0));
return;
}
Queue<Integer> queue = new LinkedList<Integer>(); // 用于广度优先搜索的队列
queue.offer(user_id_a); // 放入初始结点
HashSet<Integer> visited = new HashSet<>(); // 存放已经被访问过的结点,防止回路
visited.add(user_id_a);
boolean founded = false;
while (!queue.isEmpty()) {
int current_user_id = queue.poll(); // 拿出队列头部的第一个结点
if (user_nodes[current_user_id] == null) continue;
// 遍历刚刚拿出的这个结点的所有直接连接结点,并加入队列尾部
for (int friend_id : user_nodes[current_user_id].friends) {
if (user_nodes[friend_id] == null) continue;
if (visited.contains(friend_id)) continue;
queue.offer(friend_id);
visited.add(friend_id); // 记录已经访问过的结点
user_nodes[friend_id].degree = user_nodes[current_user_id].degree + 1; // 好友度数是当前结点的好友度数再加1
// 发现特定的好友,输出,然后跳出循环并返回
if (friend_id == user_id_b) {
System.out.println(String.format("%d和%d两者是%d度好友", user_id_a, user_id_b, user_nodes[friend_id].degree));
founded = true;
break;
}
}
// 已经发现特定的好友,跳出循环并返回
if (founded) break;
}
}
/**
* @param user_nodes-用户的结点;user_id_a-用户a的ID;user_id_b-用户b的ID
* @return void
* @Description: 通过双向广度优先搜索,查找两人之间最短通路的长度
*/
public static int bi_bfs(Node[] user_nodes, int user_id_a, int user_id_b) {
if (user_id_a > user_nodes.length || user_id_b > user_nodes.length) return -1; // 防止数组越界的异常
if (user_id_a == user_id_b) return 0; // 两个用户是同一人,直接返回0
Queue<Integer> queue_a = new LinkedList<Integer>(); // 队列a,用于从用户a出发的广度优先搜索
Queue<Integer> queue_b = new LinkedList<Integer>(); // 队列b,用于从用户b出发的广度优先搜索
queue_a.offer(user_id_a); // 放入初始结点
HashSet<Integer> visited_a = new HashSet<>(); // 存放已经被访问过的结点,防止回路
visited_a.add(user_id_a);
queue_b.offer(user_id_b); // 放入初始结点
HashSet<Integer> visited_b = new HashSet<>(); // 存放已经被访问过的结点,防止回路
visited_b.add(user_id_b);
int degree_a = 0, degree_b = 0, max_degree = 20; // max_degree的设置,防止两者之间不存在通路的情况
while ((degree_a + degree_b) < max_degree) {
degree_a++;
getNextDegreeFriend(user_id_a, user_nodes, queue_a, visited_a, degree_a);
// 沿着a出发的方向,继续广度优先搜索degree + 1的好友
if (hasOverlap(visited_a, visited_b)) return (degree_a + degree_b);
// 判断到目前为止,被发现的a的好友,和被发现的b的好友,两个集合是否存在交集
degree_b++;
getNextDegreeFriend(user_id_b, user_nodes, queue_b, visited_b, degree_b);
// 沿着b出发的方向,继续广度优先搜索degree + 1的好友
if (hasOverlap(visited_a, visited_b)) return (degree_a + degree_b);
// 判断到目前为止,被发现的a的好友,和被发现的b的好友,两个集合是否存在交集
}
return -1; // 广度优先搜索超过max_degree之后,仍然没有发现a和b的重叠,认为没有通路
}
// 广度优先搜索和user_id相距度数为degree的所有好友
public static void getNextDegreeFriend(int user_id, Node[] user_nodes, Queue<Integer> queue, HashSet<Integer> visited, int degree) {
while (!queue.isEmpty()) {
if (user_nodes[queue.peek()].degrees.get(user_id) >= degree) break;
// 首先看看,下一个从队列头部取出来的用户,他/她和出发点相距的度数是否超过了参数degree。如果超过了就跳出
int current_user_id = queue.poll(); // 拿出队列头部的第一个结点
if (user_nodes[current_user_id] == null) continue;
for (int friend_id : user_nodes[current_user_id].friends) {
if (user_nodes[friend_id] == null) continue;
if (visited.contains(friend_id)) continue;
queue.offer(friend_id);
visited.add(friend_id);
user_nodes[friend_id].degrees.put(user_id, user_nodes[current_user_id].degrees.get(user_id) + 1);
// 好友度数是当前结点的好友度数再加1
}
}
}
// 判断两个好友集合是否有交集
public static boolean hasOverlap(HashSet<Integer> friends_from_a, HashSet<Integer> friends_from_b) {
for (Integer f_a : friends_from_a) {
if (friends_from_b.contains(f_a))
return true;
}
return false;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
// System.out.println(String.format("lastModifiedTime>=%d", System.currentTimeMillis() - (6*30*24*3600*1000L)));
// System.out.println(String.format("lastModifiedTime>=%d", System.currentTimeMillis()));
// System.exit(0);
Lesson14_2 l14_1 = new Lesson14_2();
Node[] user_nodes = l14_1.generateGraph(50000, 320000); //生成较大数量的结点和边,用于测试两种方法的性能差异
long start = 0, end = 0;
int a_id = 0, b_id = 1;
start = System.currentTimeMillis();
Lesson14_2.bfs(user_nodes, a_id, b_id);
end = System.currentTimeMillis();
System.out.println(String.format("耗时%d毫秒", end - start));
System.out.println();
start = System.currentTimeMillis();
System.out.println(String.format("%d和%d两者是%d度好友", a_id, b_id, Lesson14_2.bi_bfs(user_nodes, a_id, b_id)));
end = System.currentTimeMillis();
System.out.println(String.format("耗时%d毫秒", end - start));
}
/**
* 和之前一样,在讲座中可以省略
*
* @param user_num-用户的数量,也就是结点的数量;relation_num-好友关系的数量,也就是边的数量
* @return Node[]-图的所有结点
* @Description: 生成图的结点和边
*/
public Node[] generateGraph(int user_num, int relation_num) {
Node[] user_nodes = new Node[user_num];
// 生成所有表示用户的结点
for (int i = 0; i < user_num; i++) {
user_nodes[i] = new Node(i);
}
// 生成所有表示好友关系的边
for (int i = 0; i < relation_num; i++) {
int friend_a_id = rand.nextInt(user_num);
int friend_b_id = rand.nextInt(user_num);
if (friend_a_id == friend_b_id) continue; // 自己不能是自己的好友。如果生成的两个好友id相同,跳过
Node friend_a = user_nodes[friend_a_id];
Node friend_b = user_nodes[friend_b_id];
// 这里为了简化起见,暂时不考虑重复的好友id。如果有重复,跳过
if (!friend_a.friends.contains(friend_b_id)) {
friend_a.friends.add(friend_b_id);
}
if (!friend_b.friends.contains(friend_a_id)) {
friend_b.friends.add(friend_a_id);
}
}
return user_nodes;
}
public class Node {
public int user_id; // 结点的名称,这里使用用户id
public HashSet<Integer> friends = null;
// 使用哈希映射存放相连的朋友结点。哈希便于确认和某个用户是否相连。
public int degree; // 用于存放和给定的用户结点,是几度好友
public HashMap<Integer, Integer> degrees; // 存放从不同用户出发,当前用户结点是第几度
// 初始化结点
public Node(int id) {
user_id = id;
friends = new HashSet<>();
degree = 0;
degrees = new HashMap<>();
degrees.put(id, 0);
}
}
}
| 34.25 | 136 | 0.586749 |
3eb8cf109611d7e38921fbc05d5c884ea7d7726b
| 10,281 |
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher3.tapl;
import android.graphics.Rect;
import androidx.annotation.NonNull;
import androidx.test.uiautomator.BySelector;
import androidx.test.uiautomator.Direction;
import androidx.test.uiautomator.UiObject2;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
/**
* Common overview panel for both Launcher and fallback recents
*/
public class BaseOverview extends LauncherInstrumentation.VisibleContainer {
private static final int FLINGS_FOR_DISMISS_LIMIT = 40;
BaseOverview(LauncherInstrumentation launcher) {
super(launcher);
verifyActiveContainer();
verifyActionsViewVisibility();
}
@Override
protected LauncherInstrumentation.ContainerType getContainerType() {
return LauncherInstrumentation.ContainerType.FALLBACK_OVERVIEW;
}
/**
* Flings forward (left) and waits the fling's end.
*/
public void flingForward() {
try (LauncherInstrumentation.Closable e = mLauncher.eventsCheck()) {
flingForwardImpl();
}
}
private void flingForwardImpl() {
try (LauncherInstrumentation.Closable c =
mLauncher.addContextLayer("want to fling forward in overview")) {
LauncherInstrumentation.log("Overview.flingForward before fling");
final UiObject2 overview = verifyActiveContainer();
final int leftMargin =
mLauncher.getTargetInsets().left + mLauncher.getEdgeSensitivityWidth();
mLauncher.scroll(overview, Direction.LEFT, new Rect(leftMargin + 1, 0, 0, 0), 20,
false);
try (LauncherInstrumentation.Closable c2 =
mLauncher.addContextLayer("flung forwards")) {
verifyActiveContainer();
verifyActionsViewVisibility();
}
}
}
/**
* Dismissed all tasks by scrolling to Clear-all button and pressing it.
*/
public void dismissAllTasks() {
try (LauncherInstrumentation.Closable e = mLauncher.eventsCheck();
LauncherInstrumentation.Closable c = mLauncher.addContextLayer(
"dismissing all tasks")) {
final BySelector clearAllSelector = mLauncher.getOverviewObjectSelector("clear_all");
for (int i = 0;
i < FLINGS_FOR_DISMISS_LIMIT
&& !verifyActiveContainer().hasObject(clearAllSelector);
++i) {
flingForwardImpl();
}
mLauncher.clickLauncherObject(
mLauncher.waitForObjectInContainer(verifyActiveContainer(), clearAllSelector));
mLauncher.waitUntilLauncherObjectGone(clearAllSelector);
}
}
/**
* Flings backward (right) and waits the fling's end.
*/
public void flingBackward() {
try (LauncherInstrumentation.Closable e = mLauncher.eventsCheck();
LauncherInstrumentation.Closable c =
mLauncher.addContextLayer("want to fling backward in overview")) {
LauncherInstrumentation.log("Overview.flingBackward before fling");
final UiObject2 overview = verifyActiveContainer();
final int rightMargin =
mLauncher.getTargetInsets().right + mLauncher.getEdgeSensitivityWidth();
mLauncher.scroll(
overview, Direction.RIGHT, new Rect(0, 0, rightMargin + 1, 0), 20, false);
try (LauncherInstrumentation.Closable c2 =
mLauncher.addContextLayer("flung backwards")) {
verifyActiveContainer();
verifyActionsViewVisibility();
}
}
}
/**
* Scrolls the current task via flinging forward until it is off screen.
*
* If only one task is present, it is only partially scrolled off screen and will still be
* the current task.
*/
public void scrollCurrentTaskOffScreen() {
try (LauncherInstrumentation.Closable e = mLauncher.eventsCheck();
LauncherInstrumentation.Closable c = mLauncher.addContextLayer(
"want to scroll current task off screen in overview")) {
verifyActiveContainer();
OverviewTask task = getCurrentTask();
mLauncher.assertNotNull("current task is null", task);
mLauncher.scrollLeftByDistance(verifyActiveContainer(), task.getVisibleWidth());
try (LauncherInstrumentation.Closable c2 =
mLauncher.addContextLayer("scrolled task off screen")) {
verifyActiveContainer();
verifyActionsViewVisibility();
if (getTaskCount() > 1) {
if (mLauncher.isTablet()) {
mLauncher.assertTrue("current task is not grid height",
getCurrentTask().getVisibleHeight() == mLauncher
.getGridTaskRectForTablet().height());
}
mLauncher.assertTrue("Current task not scrolled off screen",
!getCurrentTask().equals(task));
}
}
}
}
/**
* Gets the current task in the carousel, or fails if the carousel is empty.
*
* @return the task in the middle of the visible tasks list.
*/
@NonNull
public OverviewTask getCurrentTask() {
final List<UiObject2> taskViews = getTasks();
mLauncher.assertNotEquals("Unable to find a task", 0, taskViews.size());
// taskViews contains up to 3 task views: the 'main' (having the widest visible part) one
// in the center, and parts of its right and left siblings. Find the main task view by
// its width.
final UiObject2 widestTask = Collections.max(taskViews,
(t1, t2) -> Integer.compare(mLauncher.getVisibleBounds(t1).width(),
mLauncher.getVisibleBounds(t2).width()));
return new OverviewTask(mLauncher, widestTask, this);
}
/**
* Returns a list of all tasks fully visible in the tablet grid overview.
*/
@NonNull
public List<OverviewTask> getCurrentTasksForTablet() {
final List<UiObject2> taskViews = getTasks();
mLauncher.assertNotEquals("Unable to find a task", 0, taskViews.size());
final int gridTaskWidth = mLauncher.getGridTaskRectForTablet().width();
return taskViews.stream().filter(t -> t.getVisibleBounds().width() == gridTaskWidth).map(
t -> new OverviewTask(mLauncher, t, this)).collect(Collectors.toList());
}
@NonNull
private List<UiObject2> getTasks() {
try (LauncherInstrumentation.Closable c = mLauncher.addContextLayer(
"want to get overview tasks")) {
verifyActiveContainer();
return mLauncher.getDevice().findObjects(
mLauncher.getOverviewObjectSelector("snapshot"));
}
}
int getTaskCount() {
return getTasks().size();
}
/**
* Returns whether Overview has tasks.
*/
public boolean hasTasks() {
return getTasks().size() > 0;
}
/**
* Gets Overview Actions.
*
* @return The Overview Actions
*/
@NonNull
public OverviewActions getOverviewActions() {
try (LauncherInstrumentation.Closable c = mLauncher.addContextLayer(
"want to get overview actions")) {
verifyActiveContainer();
UiObject2 overviewActions = mLauncher.waitForOverviewObject("action_buttons");
return new OverviewActions(overviewActions, mLauncher);
}
}
/**
* Returns if clear all button is visible.
*/
public boolean isClearAllVisible() {
return mLauncher.hasLauncherObject(mLauncher.getOverviewObjectSelector("clear_all"));
}
private void verifyActionsViewVisibility() {
if (!hasTasks()) {
return;
}
try (LauncherInstrumentation.Closable c = mLauncher.addContextLayer(
"want to assert overview actions view visibility")) {
if (mLauncher.isTablet() && !isOverviewSnappedToFocusedTaskForTablet()) {
mLauncher.waitUntilOverviewObjectGone("action_buttons");
} else {
mLauncher.waitForOverviewObject("action_buttons");
}
}
}
/**
* Returns if focused task is currently snapped task in tablet grid overview.
*/
private boolean isOverviewSnappedToFocusedTaskForTablet() {
UiObject2 focusedTask = getFocusedTaskForTablet();
if (focusedTask == null) {
return false;
}
return Math.abs(
focusedTask.getVisibleBounds().exactCenterX() - mLauncher.getExactScreenCenterX())
< 1;
}
/**
* Returns Overview focused task if it exists.
*
* @throws IllegalStateException if not run on a tablet device.
*/
UiObject2 getFocusedTaskForTablet() {
if (!mLauncher.isTablet()) {
throw new IllegalStateException("Must be run on tablet device.");
}
final List<UiObject2> taskViews = getTasks();
if (taskViews.size() == 0) {
return null;
}
int focusedTaskHeight = mLauncher.getFocusedTaskHeightForTablet();
for (UiObject2 task : taskViews) {
if (task.getVisibleBounds().height() == focusedTaskHeight) {
return task;
}
}
return null;
}
}
| 37.385455 | 99 | 0.617352 |
af7af856942a36f81c904f807bec2e3c4609b81f
| 325 |
package be.stijnhooft.portal.social.dtos;
public enum ImageLabel {
ORIGINAL("original"),
COLOR_THUMBNAIL("thumbnail"),
SEPIA_THUMBNAIL("sepia");
private final String value;
ImageLabel(String value) {
this.value = value;
}
public String getValue() {
return this.value;
}
}
| 17.105263 | 41 | 0.64 |
4e3ce3b409d358c33057b862085322d889d15e66
| 3,395 |
/**
* Copyright (c) 2007 Regents of the University of California.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. The name of the University may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
package io.grpc.examples.p4p.p4p.crypto;
import java.math.BigInteger;
import io.grpc.examples.p4p.p4p.util.P4PParameters;
/**
*
* This is an abstract 3-round (a.k.a $\Sigma$) proof consisting of 3 rounds:
* <p>
* Prover -> Verifier: commitment
* Verifier -> Prover: challenge
* Prover -> Verifier: response
* <p>
* The proof is made non-interactive by hashing the commitment.
*
* @author ET 08/29/2005
*/
public abstract class Proof extends P4PParameters {
protected BigInteger[] commitment = null;
/**
* This is the first message in a 3-round proof. The prover ``commits''
* to her data using some kind of commitment scheme. This is essentially
* a sequence of big numbers. Could be computed by one of the
* Commitment classes.
*/
protected BigInteger[] challenge = null;
/**
* The second message in the $\Sigma$ proof. Conceptually this is a
* random number selected by the verifier. In a non-interactive mode,
* it is produced by the prover by hashing the commitment.
*/
protected BigInteger[] response = null;
/**
* The third message in the proof.
*/
public Proof() {}
public Proof(BigInteger[] commitment, BigInteger[] challenge,
BigInteger[] response) {
this.commitment = commitment;
this.challenge = challenge;
this.response = response;
}
public BigInteger[] getCommitment() { return commitment; }
public BigInteger[] getChallenge() { return challenge; }
public BigInteger[] getResponse() { return response; }
/**
* Construct the proof. This should be overriden by subclasses.
*/
public abstract void construct();
/**
* Verify the proof. To be overriden by subclasses.
*/
// public abstract boolean verify();
}
| 34.292929 | 80 | 0.699264 |
3a1a7ca727738830bbc9214fca05fa7051574ffe
| 22,831 |
package com.webcheckers.model;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.SplittableRandom;
/**
* A representation of a single Game, with two players and a Board.
*/
public class Game {
//
// Attributes
//
private Player redPlayer;
private Player whitePlayer;
private Player winner;
private Player loser;
private Color activeColor;
private BoardView redBoard;
private BoardView whiteBoard;
private int redCaptured = 0;
private int whiteCaptured = 0;
private String id;
private boolean turn = false;
private boolean canDeleteGame = false;
private final int NUM_ROWS_COLS = 7;
private List<Move> moves = new ArrayList<Move>();
private List<Move> tempMoves = new ArrayList<>();
public enum ViewMode { PLAY, SPECTATOR, REPLAY }
/**
* Create a Game with the red and white players, where the active color is
* red and the winner is null.
* @param redPlayer
* Player {@link Player} representing the red Player
* @param whitePlayer
* Player {@link Player} representing the white Player
*/
public Game(Player redPlayer, Player whitePlayer, String id){
Objects.requireNonNull(redPlayer, "redPlayer must not be null");
Objects.requireNonNull(whitePlayer, "whitePlayer must not be null");
this.redPlayer = redPlayer;
this.whitePlayer = whitePlayer;
this.activeColor = Color.RED;
this.winner = null;
this.redBoard = new BoardView(redPlayer);
this.whiteBoard = new BoardView(whitePlayer);
this.id = id;
}
/**
* Gets the Red Player from the Game
* @return
* redPlayer, the Player {@link Player} assigned to RED for this game
*/
public Player getRedPlayer() {
return redPlayer;
}
/**
* Gets the white Player from the Game
* @return
* whitePlayer, the Player {@link Player} assigned to WHITE for this game
*/
public Player getWhitePlayer() {
return whitePlayer;
}
public String getId(){return id; }
public void changeTurn(){
if (turn == true){
turn = false;
}
else {
turn = true;
}
}
public boolean changedTurn(){
return turn;
}
public Color getPlayerColor(String username){
if(username.equals(redPlayer.getName())){
return Color.RED;
}
else if( username.equals(whitePlayer.getName())){
return Color.WHITE;
}
else{
return null;
}
}
/**
* Sets the white player to a new player created from the provided username
* @param username
* A string representation of the new player's username
*/
public void setWhitePlayer(String username){
this.whitePlayer = new Player(username);
}
/**
* Sets the red player to a new player created from the provided username
* @param username
* A string representation of the new player's username
*/
public void setRedPlayer(String username){
this.redPlayer = new Player(username);
}
/**
* Queries whether the provided player has a game - If they are either
* the red or the white player
* @param player
* Player {@link Player} to check if they are in a game
* @return
* True if the provided player is the red or white player.
* False otherwise
*/
public boolean hasGame(Player player){
return this.redPlayer.equals(player) | this.whitePlayer.equals(player);
}
public boolean hasGame2(String id){
return this.getId().equals(id);
}
/**
* Checks for overall move ability, helps look for win by stagnation
* @return
* whether this player can make any valid moves
*/
private boolean hasMove() {
return (hasSimpleMove() || hasJumpMove());
}
/**
* Check to see if current player has any moves available
* @return
*/
public boolean hasSimpleMove(){
if( whiteCaptured == 12 || redCaptured == 12){
return false;
}
BoardView board;
if( activeColor == Color.WHITE){
board = whiteBoard;
}
else{ board = redBoard;}
// iterate over rows and spaces
for(Row r : board){
for(Space s : r){
// if space has piece, see if there's a valid move in any direction
if( s.getPiece() != null){
if( s.getPiece().getColor() == activeColor){
ArrayList<Position> positions = new ArrayList<>();
// if piece belongs to player, check if it is movable
Position current = new Position(r.getIndex(), s.getCellIdx());
Position simpleLF = new Position(current.getRow()+1, current.getCell()-1);
if( simpleLF.isOnBoard()) positions.add(simpleLF);
Position simpleRF = new Position(current.getRow()+1, current.getCell()+1);
if( simpleRF.isOnBoard()) positions.add(simpleRF);
Position kingLF = new Position(current.getRow()-1, current.getCell()-1);
if( kingLF.isOnBoard()) positions.add(kingLF);
Position kingRF = new Position(current.getRow()-1, current.getCell()+1);
if( kingRF.isOnBoard()) positions.add(kingRF);
for(Position p : positions){
Move move = new Move(current, p);
if( activeColor == Color.WHITE) {
if (move.isValid(whiteBoard)) return true;
}
else{
if( move.isValid(redBoard)) return true;
}
}
}
}
}
}
// default to false if no valid move is found
return false;
}
public boolean hasJumpMove(){
if( whiteCaptured == 12 || redCaptured == 12){
return false;
}
BoardView board;
if( activeColor == Color.WHITE){
board = whiteBoard;
}
else{ board = redBoard;}
// iterate over rows and spaces
for(Row r : board){
for(Space s : r){
// if space has piece, see if there's a valid move in any direction
if( s.getPiece() != null){
if( s.getPiece().getColor() == activeColor){
ArrayList<Position> positions = new ArrayList<>();
// if piece belongs to player, check if it is movable
Position current = new Position(r.getIndex(), s.getCellIdx());
Position jumpLF = new Position(current.getRow()+2, current.getCell()-2);
if( jumpLF.isOnBoard()) positions.add(jumpLF);
Position jumpRF = new Position(current.getRow()+2, current.getCell()+2);
if( jumpRF.isOnBoard()) positions.add(jumpRF);
Position kingJumpLF = new Position(current.getRow()-2, current.getCell()-2);
if( kingJumpLF.isOnBoard()) positions.add(kingJumpLF);
Position kingJumpRF = new Position(current.getRow()-2, current.getCell()+2);
if( kingJumpRF.isOnBoard()) positions.add(kingJumpRF);
for(Position p : positions){
Move move = new Move(current, p);
if( activeColor == Color.WHITE) {
if (move.isValid(whiteBoard)) return true;
}
else{
if( move.isValid(redBoard)) return true;
}
}
}
}
}
}
// default to false if no valid move is found
return false;
}
/**
* checks whether player can perform another jump in from their current position
* @param p position of player currently
* @return true if another jump can be made
*/
public boolean hasNextJump(Position p){
ArrayList<Position> positions = new ArrayList<>();
// if piece belongs to player, check if it is movable
Position jumpLF = new Position(p.getRow()+2, p.getCell()-2);
if( jumpLF.isOnBoard()) positions.add(jumpLF);
Position jumpRF = new Position(p.getRow()+2, p.getCell()+2);
if( jumpRF.isOnBoard()) positions.add(jumpRF);
Position kingJumpLF = new Position(p.getRow()-2, p.getCell()-2);
if( kingJumpLF.isOnBoard()) positions.add(kingJumpLF);
Position kingJumpRF = new Position(p.getRow()-2, p.getCell()+2);
if( kingJumpRF.isOnBoard()) positions.add(kingJumpRF);
for(Position ps : positions){
Move move = new Move(p, ps);
if( activeColor == Color.WHITE) {
if (move.isValid(whiteBoard)) return true;
}
else{
if( move.isValid(redBoard)) return true;
}
}
return false;
}
/**
* Gets the Board for this Game if current player is red
* @return
* Board {@link BoardView} representation for this Game
*/
public BoardView getRedBoard(){
return this.redBoard;
}
/**
* Gets the Board for this Game if current player is white
* @return
* Board {@link BoardView} representation for this Game
*/
public BoardView getWhiteBoard(){
return this.whiteBoard;
}
/**
* Gets the active color for this game - which player is legally allowed to move
* @return
* The activeColor, either RED or WHITE
*/
public Color getActiveColor(){
return this.activeColor;
}
/**
* Checks if the provided player is currently active - if their color and the activeColor match
* @param player
* Player to check if they are active or not
* @return
* True if the player is red and activeColor is red, or vice versa for white
* False otherwise
*/
public boolean isActive(Player player){
boolean isRedPlayer = player.equals(this.redPlayer) && this.activeColor.equals(Color.RED);
boolean isWhitePlayer = player.equals(this.whitePlayer) && this.activeColor.equals(Color.WHITE);
return isRedPlayer || isWhitePlayer;
}
/**
* Sets the activeColor to the opposite color
*/
public void toggleActiveColor(){
if(this.activeColor == Color.RED){
this.activeColor = Color.WHITE;
}
else{
this.activeColor = Color.RED;
}
}
/**
* Toggles whether a finished game can be deleted
* Gets called when each player is redirected to home
*/
public void toggleCanDeleteGame() {
this.canDeleteGame = !this.canDeleteGame;
}
/**
* Return whether the game is safe to be deleted
*/
public boolean safeToDelete() { return this.canDeleteGame; }
/**
* Sets the winner and loser of the game to either the Red or White player
* @param player
* The winning player
*/
public void setWinner(Player player){
if(this.redPlayer.equals(player)) {
this.winner = this.redPlayer;
this.loser = this.whitePlayer;
} else {
this.winner = this.whitePlayer;
this.loser = this.redPlayer;
}
player.addWin();
this.redPlayer.leaveGame();
this.whitePlayer.leaveGame();
}
/**
* Checks whether a winner has been declared yet
* @return
* True if winner is not null
* False otherwise
*/
public boolean hasWinner(){
return this.winner != null;
}
/**
* Gets the Game's winner
* @return
* The winner of the Game, either the Red or White player
*/
public Player getWinner() {
return this.winner;
}
/**
* Gets the list of moves made so far in the game
* @return
* The current list of moves
*/
public List<Move> getMoves() { return this.moves; }
/**
* Gets the list of moves made so far in the turn
* @return
* The current list of moves in the turn
*/
public List<Move> getTempMoves() {
List<Move> lightingMoves = new ArrayList<>(tempMoves);
return lightingMoves;
}
public void resetTempMoves(){
while(!tempMoves.isEmpty()){
tempMoves.remove(0);
}
}
/**
* Completes removal of white captured piece and adds to captured count
* @param target
* location of piece being captured
*/
public void whiteCaptured(Position target) {
whiteCaptured++;
// Remove from red board
Row targetRow = this.redBoard.getRow(target.getRow());
Space targetSpace = targetRow.getSpace(target.getCell());
targetSpace.removePiece();
// Remove from white board
targetRow = this.whiteBoard.getRow(NUM_ROWS_COLS - target.getRow());
targetSpace = targetRow.getSpace(NUM_ROWS_COLS - target.getCell());
targetSpace.removePiece();
}
/**
* Completes removal of red captured piece and adds to captured count
* @param target
* location of piece being captured
*/
public void redCaptured(Position target) {
redCaptured++;
// Remove from white board
Row targetRow = this.whiteBoard.getRow(target.getRow());
Space targetSpace = targetRow.getSpace(target.getCell());
targetSpace.removePiece();
// Remove from red board
targetRow = this.redBoard.getRow(NUM_ROWS_COLS - target.getRow());
targetSpace = targetRow.getSpace(NUM_ROWS_COLS - target.getCell());
targetSpace.removePiece();
}
/**
* Updates both boards for a red player's turn, adds move to list of moves,
* makes pieces into kings as necessary
* @param m
* the Move submitted
*/
public Message updateBoardRedTurn(Move m) {
// if first move of turn, check if jump is possible & force if so
if( tempMoves.isEmpty()) {
if( hasJumpMove() && !m.isJump()){
return new Message(Message.Type.error, "You have a jump possible.");
}
// Add move to the ongoing list of moves
moves.add(m);
tempMoves.add(m);
}
// if previous move is jump check if curr move is jump
else if( tempMoves.get(0).isJump()) {
if( m.isJump()){
// Add move to the ongoing list of moves
moves.add(m);
tempMoves.add(m);
}
else {
return new Message(Message.Type.error, "One simple move per turn....CHEATER");
}
}
// else the first move was a simple move and you can't keep going
else{
return new Message(Message.Type.error, "One simple move per turn....CHEATER");
}
// RED BOARD
// Removes red piece from given start space
Row startRow = this.redBoard.getRow(m.getStart().getRow());
Space startSpace = startRow.getSpace(m.getStart().getCell());
Piece piece = startSpace.removePiece();
// Adds red piece to given end space
Row endRow = this.redBoard.getRow(m.getEnd().getRow());
Space endSpace = endRow.getSpace(m.getEnd().getCell());
endSpace.putPiece(piece);
// Checks for new king piece
if(piece.getType().equals(Piece.Type.SINGLE) && endRow.getIndex() == 0) {
endSpace.putPiece(piece.makeKing());
}
// WHITE BOARD
// Overwrites all variables used for red board
// Removes red piece from given start space
startRow = this.whiteBoard.getRow(NUM_ROWS_COLS - m.getStart().getRow());
startSpace = startRow.getSpace(NUM_ROWS_COLS - m.getStart().getCell());
piece = startSpace.removePiece();
// Adds red piece to given end space
endRow = this.whiteBoard.getRow(NUM_ROWS_COLS - m.getEnd().getRow());
endSpace = endRow.getSpace(NUM_ROWS_COLS - m.getEnd().getCell());
endSpace.putPiece(piece);
// Checks for new king piece
if(piece.getType().equals(Piece.Type.SINGLE) && endRow.getIndex() == NUM_ROWS_COLS) {
endSpace.putPiece(piece.makeKing());
}
return new Message(Message.Type.info, "Well played");
}
/**
* Updates both boards for a white player's turn, removes move from list of moves,
* makes pieces into kings as necessary
* @param m
* the Move submitted
*/
public Message updateBoardWhiteTurn(Move m) {
// if first move of turn, add
if( tempMoves.isEmpty()) {
if( hasJumpMove() && !m.isJump()){
return new Message(Message.Type.error, "You have a jump possible.");
}
// Add move to the ongoing list of moves
moves.add(m);
tempMoves.add(m);
}
// if previous move is jump check if curr move is jump
else if( tempMoves.get(0).isJump()) {
if( m.isJump()){
// Add move to the ongoing list of moves
moves.add(m);
tempMoves.add(m);
}
else {
return new Message(Message.Type.error, "One simple move per turn....CHEATER");
}
}
// else the first move was a simple move and you can't keep going
else{
return new Message(Message.Type.error, "One simple move per turn....CHEATER");
}
// WHITE BOARD
// Removes white piece from given start space
Row startRow = this.whiteBoard.getRow(m.getStart().getRow());
Space startSpace = startRow.getSpace(m.getStart().getCell());
Piece piece = startSpace.removePiece();
// Adds white piece to given end space
Row endRow = this.whiteBoard.getRow(m.getEnd().getRow());
Space endSpace = endRow.getSpace(m.getEnd().getCell());
endSpace.putPiece(piece);
// Checks for new king piece
if(piece.getType().equals(Piece.Type.SINGLE) && endRow.getIndex() == 0) {
endSpace.putPiece(piece.makeKing());
}
// RED BOARD
// Overwrites all variables used for white board
// Removes white piece from given start space
startRow = this.redBoard.getRow(NUM_ROWS_COLS - m.getStart().getRow());
startSpace = startRow.getSpace(NUM_ROWS_COLS - m.getStart().getCell());
piece = startSpace.removePiece();
// Adds white piece to given end space
endRow = this.redBoard.getRow(NUM_ROWS_COLS - m.getEnd().getRow());
endSpace = endRow.getSpace(NUM_ROWS_COLS - m.getEnd().getCell());
endSpace.putPiece(piece);
// Checks for new king piece
if(piece.getType().equals(Piece.Type.SINGLE) && endRow.getIndex() == NUM_ROWS_COLS) {
endSpace.putPiece(piece.makeKing());
}
return new Message(Message.Type.info, "Well played.");
}
/**
* Backs up the previously made move by the red player
*/
public void backupRedTurn() {
// Removes previously made move from move list
Move move = tempMoves.remove(tempMoves.size() - 1);
// RED BOARD
// Removes red piece from given ending space
Row finalRow = this.redBoard.getRow(move.getEnd().getRow());
Space finalSpace = finalRow.getSpace(move.getEnd().getCell());
Piece piece = finalSpace.removePiece();
// Adds red piece to original space
Row originalRow = this.redBoard.getRow(move.getStart().getRow());
Space originalSpace = originalRow.getSpace(move.getStart().getCell());
originalSpace.putPiece(piece);
// WHITE BOARD
// Overwrites all variables used for red board
// Removes red piece from given start space
finalRow = this.whiteBoard.getRow(NUM_ROWS_COLS - move.getEnd().getRow());
finalSpace = finalRow.getSpace(NUM_ROWS_COLS - move.getEnd().getCell());
piece = finalSpace.removePiece();
// Adds red piece to given end space
originalRow = this.whiteBoard.getRow(NUM_ROWS_COLS - move.getStart().getRow());
originalSpace = originalRow.getSpace(NUM_ROWS_COLS - move.getStart().getCell());
originalSpace.putPiece(piece);
}
/**
* Backs up the previously made move by the white player
*/
public void backupWhiteTurn() {
// Removes previously made move from move list
Move move = tempMoves.remove(tempMoves.size() - 1);
// WHITE BOARD
// Removes white piece from given ending space
Row finalRow = this.whiteBoard.getRow(move.getEnd().getRow());
Space finalSpace = finalRow.getSpace(move.getEnd().getCell());
Piece piece = finalSpace.removePiece();
// Adds white piece to original space
Row originalRow = this.whiteBoard.getRow(move.getStart().getRow());
Space originalSpace = originalRow.getSpace(move.getStart().getCell());
originalSpace.putPiece(piece);
// RED BOARD
// Overwrites all variables used for white board
// Removes white piece from given start space
finalRow = this.redBoard.getRow(NUM_ROWS_COLS - move.getEnd().getRow());
finalSpace = finalRow.getSpace(NUM_ROWS_COLS - move.getEnd().getCell());
piece = finalSpace.removePiece();
// Adds white piece to given end space
originalRow = this.redBoard.getRow(NUM_ROWS_COLS - move.getStart().getRow());
originalSpace = originalRow.getSpace(NUM_ROWS_COLS - move.getStart().getCell());
originalSpace.putPiece(piece);
}
/**
* Checks if either player has captured all of opponent's pieces or has run out of moves
*/
public void checkForWin() {
//TODO use this if hasMove works
// if(whiteCaptured == 12 || !hasMove()) setWinner(this.redPlayer);
// else if(redCaptured == 12 || !hasMove()) setWinner(this.whitePlayer);
if(whiteCaptured == 12 ) setWinner(this.redPlayer);
else if(redCaptured == 12 ) setWinner(this.whitePlayer);
}
}
| 32.992775 | 104 | 0.576891 |
3fb53d633760ae6939c32ef8d596a9039e4ac19c
| 5,161 |
/*
* Copyright 2009-2015 University of Hildesheim, Software Systems Engineering
*
* 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 de.uni_hildesheim.sse.qmApp.dialogs;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.swt.widgets.Shell;
import de.uni_hildesheim.sse.qmApp.model.ModelAccess;
import net.ssehub.easy.varModel.confModel.Configuration;
import net.ssehub.easy.varModel.confModel.IDecisionVariable;
import net.ssehub.easy.varModel.model.datatypes.IDatatype;
/**
* A variable selector dialog based on a given configuration.
*
* @author Holger Eichelberger
*/
public class ConfigurationVariableSelectorDialog extends AbstractVariableSelectorDialog {
/**
* Selects variables for display.
*
* @author Holger Eichelberger
*/
public interface IVariableSelector {
/**
* Whether the given <code>variable</code> is enabled for display.
*
* @param variable the variable
* @return <code>true</code> if the <code>variable</code> is enabled, <code>false</code> else
*/
public boolean enabled(IDecisionVariable variable);
}
/**
* A type-based variable selector, i.e., types and their sub-types are enabled.
*
* @author Holger Eichelberger
*/
public static class TypeBasedVariableSelector implements IVariableSelector {
private IDatatype[] types;
/**
* Creates a type-based variable selector.
*
* @param types the types which enable the selection
*/
public TypeBasedVariableSelector(IDatatype[] types) {
this.types = types;
}
/**
* Creates a type-based variable selector.
*
* @param types the types which enable the selection
*/
public TypeBasedVariableSelector(Collection<IDatatype> types) {
this.types = new IDatatype[types.size()];
types.toArray(this.types);
}
@Override
public boolean enabled(IDecisionVariable variable) {
boolean enabled = false;
IDatatype varType = variable.getDeclaration().getType();
for (int t = 0; !enabled && t < types.length; t++) {
enabled = types[t].isAssignableFrom(varType);
}
return enabled;
}
}
private Configuration config;
private IVariableSelector selector;
/**
* Creates a single-selection variable selector dialog.
*
* @param shell the parent shell
* @param title the title
* @param config the configuration to select from
* @param selector a generic variable selector
*/
public ConfigurationVariableSelectorDialog(Shell shell, String title, Configuration config,
IVariableSelector selector) {
this(shell, title, config, selector, false);
}
/**
* Creates a variable selector dialog.
*
* @param shell the parent shell
* @param title the title
* @param config the configuration to select from
* @param selector a generic variable selector
* @param multi whether multiple selections are allowed
*/
public ConfigurationVariableSelectorDialog(Shell shell, String title, Configuration config,
IVariableSelector selector, boolean multi) {
super(shell, title, multi);
this.config = config;
this.selector = selector;
}
@Override
protected String getDialogSettingsName() {
return "FilteredConfigurationVariableSelectorDialogSettings";
}
@Override
protected void fillContentProvider(AbstractContentProvider contentProvider, ItemsFilter itemsFilter,
IProgressMonitor progressMonitor) throws CoreException {
progressMonitor.beginTask("Filling elements", config.getDecisionCount());
TreeMap<String, IDecisionVariable> tmp = new TreeMap<String, IDecisionVariable>();
Iterator<IDecisionVariable> iter = config.iterator();
while (iter.hasNext()) {
IDecisionVariable var = iter.next();
if (null == selector || selector.enabled(var)) {
tmp.put(ModelAccess.getDisplayName(var), var);
}
progressMonitor.worked(1);
}
for (Map.Entry<String, IDecisionVariable> entry : tmp.entrySet()) {
contentProvider.add(entry.getValue(), itemsFilter);
}
progressMonitor.done();
}
}
| 33.953947 | 104 | 0.660918 |
2c02028f1cdb654938be0edc5ac99b9788ec430f
| 652 |
package net;
import net.minecraft.block.properties.IProperty;
import net.minecraft.client.renderer.block.statemap.StateMap;
import net.minecraft.client.renderer.block.statemap.StateMap$Builder;
public class agQ {
public static StateMap$Builder a(StateMap$Builder var0, IProperty var1) {
return var0.withName(var1);
}
public static StateMap a(StateMap$Builder var0) {
return var0.build();
}
public static StateMap$Builder a(StateMap$Builder var0, String var1) {
return var0.withSuffix(var1);
}
public static StateMap$Builder a(StateMap$Builder var0, IProperty[] var1) {
return var0.ignore(var1);
}
}
| 27.166667 | 78 | 0.731595 |
fd9261370e646ccfc3b4aba77bfd4377bb09f7d7
| 1,011 |
package io.shockah.dunlin.commands;
public class CommandParseException extends Exception {
private static final long serialVersionUID = -1260914648331453444L;
public final boolean onlyMessage;
public CommandParseException() {
this(false);
}
public CommandParseException(String message) {
this(message, false);
}
public CommandParseException(Throwable cause) {
this(cause, false);
}
public CommandParseException(String message, Throwable cause) {
this(message, cause, false);
}
public CommandParseException(boolean onlyMessage) {
super();
this.onlyMessage = onlyMessage;
}
public CommandParseException(String message, boolean onlyMessage) {
super(message);
this.onlyMessage = onlyMessage;
}
public CommandParseException(Throwable cause, boolean onlyMessage) {
super(cause);
this.onlyMessage = onlyMessage;
}
public CommandParseException(String message, Throwable cause, boolean onlyMessage) {
super(message, cause);
this.onlyMessage = onlyMessage;
}
}
| 23.511628 | 85 | 0.760633 |
f32cdd24dab92f26cdfd96a647b7e482f9016d08
| 985 |
package com.qypt.just_syn_asis_version1_0.utils;
public class UrlUtils {
//address
public static final String DOWNDATA="http://115.28.146.253:8080/HttpSnySisService/servlet/DownSynServlet";
public static final String UPDATA=" http://115.28.146.253:8080/HttpSnySisService/servlet/SynServlet";
public static final String REGISTER="http://115.28.146.253:8080/HttpSnySisService/servlet/RegisterServlet";
public static final String LOGIN="http://115.28.146.253:8080/HttpSnySisService/servlet/LoginServlet";
public static final String SDPATH="";
public static final String FEEDBACK="http://115.28.146.253:8080/HttpSnySisService/servlet/FeedbackServlet";
public static final String CONTACTMENORY="http://115.28.146.253:8080/HttpSnySisService/servlet/ContactMemoryServlet";
public static final String POINTFILEDOWN="http://115.28.146.253:8080/HttpSnySisService/servlet/DownPointServlet";
public static final String TULINGROBOT="http://www.tuling123.com/openapi/api"; //tuling
}
| 61.5625 | 118 | 0.804061 |
104e0718d6ee8afce816e7aae211ff163188c7af
| 1,157 |
/*
* (C) Copyright IBM Corp. 2020
*
* SPDX-License-Identifier: Apache-2.0
*/
package com.ibm.fhir.bucket.cos;
/**
* Constants related to our COS connection
*/
public class COSConstants {
// the IBM COS API key or S3 access key.
public static final String COS_API_KEY = "cos.api.key";
// the IBM COS service instance id or S3 secret key.
public static final String COS_SRVINSTID = "cos.srvinstid";
// the IBM COS or S3 End point URL.
public static final String COS_ENDPOINT_URL = "cos.endpoint.url";
// the IBM COS or S3 location.
public static final String COS_LOCATION = "cos.location";
// the IBM COS or S3 bucket name to import from.
public static final String COS_BUCKET_NAME = "cos.bucket.name";
// if use IBM credential(Y/N), default(Y).
public static final String COS_CREDENTIAL_IBM = "cos.credential.ibm";
public static final String COS_REQUEST_TIMEOUT = "cos.request.timeout";
public static final String COS_SOCKET_TIMEOUT = "cos.socket.timeout";
// The max keys to return per list objects request
public static final String COS_MAX_KEYS = "cos.max.keys";
}
| 28.925 | 75 | 0.696629 |
2ce29fe9b8ca7cdfaf3ba7e1e5bbc6579a937d73
| 2,469 |
package org.domain.code.widget;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import org.domain.code.App;
import java.util.ArrayList;
import java.util.List;
public class Spinner extends View {
/*
*控件:下拉列表框
*@天才工作
*/
private final List<String> item = new ArrayList<String>();
private ArrayAdapter<String> adapter;
private Event event;
public Spinner() {
try {
if (App.action() != null) {
VIEW = new android.widget.Spinner(App.action());
adapter = new ArrayAdapter<String>(App.action(), android.R.layout.simple_list_item_1, item);
view().setAdapter(adapter);
view().setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, android.view.View view, int i, long l) {
eventSelected(i);
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
} catch (Exception exception) {
App.Log.send(exception);
}
}
public void add(Object text) {
try {
if (text != null) {
item.add(text.toString());
adapter.notifyDataSetChanged();
}
} catch (Exception exception) {
App.Log.send(exception);
}
}
public void delete(Object index) {
try {
if (index != null) {
}
} catch (Exception exception) {
App.Log.send(exception);
}
}
public int get() {
int result = 0;
return result;
}
public void clear() {
}
public int size() {
int result = -1;
try {
result = item.size();
} catch (Exception exception) {
App.Log.send(exception);
}
return result;
}
public void event(Event Event) {
if (Event != null) {
event = Event;
}
}
public android.widget.Spinner view() {
return (android.widget.Spinner) VIEW;
}
private void eventSelected(int index) {
if (event != null) {
event.selected(index);
}
}
public interface Event {
void selected(int index);//选中
}
}
| 22.044643 | 115 | 0.511543 |
c383e96c1c982207ca31121659c7bc1f8bb3fa4e
| 2,668 |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.zonky.test.db.postgres.util;
import org.apache.commons.lang3.StringUtils;
import static org.apache.commons.lang3.StringUtils.lowerCase;
public class ArchUtils {
private ArchUtils() {}
public static String normalize(String archName) {
if (StringUtils.isBlank(archName)) {
throw new IllegalStateException("No architecture detected");
}
String arch = lowerCase(archName).replaceAll("[^a-z0-9]+", "");
if (arch.matches("^(x8664|amd64|ia32e|em64t|x64)$")) {
return "x86_64";
}
if (arch.matches("^(x8632|x86|i[3-6]86|ia32|x32)$")) {
return "x86_32";
}
if (arch.matches("^(ia64w?|itanium64)$")) {
return "itanium_64";
}
if ("ia64n".equals(arch)) {
return "itanium_32";
}
if (arch.matches("^(sparcv9|sparc64)$")) {
return "sparc_64";
}
if (arch.matches("^(sparc|sparc32)$")) {
return "sparc_32";
}
if (arch.matches("^(aarch64|armv8|arm64).*$")) {
return "arm_64";
}
if (arch.matches("^(arm|arm32).*$")) {
return "arm_32";
}
if (arch.matches("^(mips|mips32)$")) {
return "mips_32";
}
if (arch.matches("^(mipsel|mips32el)$")) {
return "mipsel_32";
}
if ("mips64".equals(arch)) {
return "mips_64";
}
if ("mips64el".equals(arch)) {
return "mipsel_64";
}
if (arch.matches("^(ppc|ppc32)$")) {
return "ppc_32";
}
if (arch.matches("^(ppcle|ppc32le)$")) {
return "ppcle_32";
}
if ("ppc64".equals(arch)) {
return "ppc_64";
}
if ("ppc64le".equals(arch)) {
return "ppcle_64";
}
if ("s390".equals(arch)) {
return "s390_32";
}
if ("s390x".equals(arch)) {
return "s390_64";
}
throw new IllegalStateException("Unsupported architecture: " + archName);
}
}
| 29.977528 | 81 | 0.546102 |
bbc9abae8878d61777ec504e1410365a3525cee6
| 9,153 |
package com.sample.data;
import java.util.ArrayList;
import java.util.List;
import com.sample.model.Record;
import com.sample.model.RecordTypeField;
import com.sample.model.RecordTypeFieldValue;
public class RecordTypeFieldValueDAO {
private static List<RecordTypeFieldValue> list = new ArrayList<RecordTypeFieldValue>();
public RecordTypeFieldValueDAO() {
if (list.size() == 0) {
list.add(new RecordTypeFieldValue(40, new RecordTypeField(1), new Record(29), "Intel Core i3 3.60 GHz"));
list.add(new RecordTypeFieldValue(41, new RecordTypeField(2), new Record(29), "8GB"));
list.add(new RecordTypeFieldValue(42, new RecordTypeField(3), new Record(29), "2x4gb"));
list.add(new RecordTypeFieldValue(43, new RecordTypeField(4), new Record(29), "ddr3"));
list.add(new RecordTypeFieldValue(44, new RecordTypeField(5), new Record(29), "1TB"));
list.add(new RecordTypeFieldValue(45, new RecordTypeField(6), new Record(29), "256GB"));
list.add(new RecordTypeFieldValue(46, new RecordTypeField(7), new Record(29), "none"));
list.add(new RecordTypeFieldValue(47, new RecordTypeField(8), new Record(29), "n/a"));
list.add(new RecordTypeFieldValue(48, new RecordTypeField(9), new Record(29), "n/a"));
list.add(new RecordTypeFieldValue(49, new RecordTypeField(10), new Record(29), "VGA, HDMI"));
list.add(new RecordTypeFieldValue(50, new RecordTypeField(11), new Record(29), "Win 7 Pro"));
list.add(new RecordTypeFieldValue(51, new RecordTypeField(12), new Record(29), "n/a"));
list.add(new RecordTypeFieldValue(52, new RecordTypeField(13), new Record(29), ""));
list.add(new RecordTypeFieldValue(53, new RecordTypeField(1), new Record(30), "Intel Core i3 3.60 GHz"));
list.add(new RecordTypeFieldValue(54, new RecordTypeField(2), new Record(30), "8GB"));
list.add(new RecordTypeFieldValue(55, new RecordTypeField(3), new Record(30), "2x4gb"));
list.add(new RecordTypeFieldValue(56, new RecordTypeField(4), new Record(30), "ddr3"));
list.add(new RecordTypeFieldValue(57, new RecordTypeField(5), new Record(30), "1TB"));
list.add(new RecordTypeFieldValue(58, new RecordTypeField(6), new Record(30), "256GB"));
list.add(new RecordTypeFieldValue(59, new RecordTypeField(7), new Record(30), "none"));
list.add(new RecordTypeFieldValue(60, new RecordTypeField(8), new Record(30), "n/a"));
list.add(new RecordTypeFieldValue(61, new RecordTypeField(9), new Record(30), "n/a"));
list.add(new RecordTypeFieldValue(62, new RecordTypeField(10), new Record(30), "VGA, HDMI"));
list.add(new RecordTypeFieldValue(63, new RecordTypeField(11), new Record(30), "Win 7 Pro"));
list.add(new RecordTypeFieldValue(64, new RecordTypeField(12), new Record(30), "n/a"));
list.add(new RecordTypeFieldValue(65, new RecordTypeField(13), new Record(30), ""));
list.add(new RecordTypeFieldValue(66, new RecordTypeField(1), new Record(31), "Intel Core i3 3.60 GHz"));
list.add(new RecordTypeFieldValue(67, new RecordTypeField(2), new Record(31), "8GB"));
list.add(new RecordTypeFieldValue(68, new RecordTypeField(3), new Record(31), "2x4gb"));
list.add(new RecordTypeFieldValue(69, new RecordTypeField(4), new Record(31), "ddr3"));
list.add(new RecordTypeFieldValue(70, new RecordTypeField(5), new Record(31), "1TB"));
list.add(new RecordTypeFieldValue(71, new RecordTypeField(6), new Record(31), "256GB"));
list.add(new RecordTypeFieldValue(72, new RecordTypeField(7), new Record(31), "none"));
list.add(new RecordTypeFieldValue(73, new RecordTypeField(8), new Record(31), "n/a"));
list.add(new RecordTypeFieldValue(74, new RecordTypeField(9), new Record(31), "n/a"));
list.add(new RecordTypeFieldValue(75, new RecordTypeField(10), new Record(31), "VGA, HDMI"));
list.add(new RecordTypeFieldValue(76, new RecordTypeField(11), new Record(31), "Win 7 Pro"));
list.add(new RecordTypeFieldValue(77, new RecordTypeField(12), new Record(31), "n/a"));
list.add(new RecordTypeFieldValue(78, new RecordTypeField(13), new Record(31), ""));
list.add(new RecordTypeFieldValue(79, new RecordTypeField(25), new Record(32), "13x15"));
list.add(new RecordTypeFieldValue(80, new RecordTypeField(26), new Record(32), ""));
list.add(new RecordTypeFieldValue(81, new RecordTypeField(27), new Record(32), ""));
list.add(new RecordTypeFieldValue(82, new RecordTypeField(28), new Record(32), "HDMI"));
list.add(new RecordTypeFieldValue(83, new RecordTypeField(29), new Record(32), ""));
list.add(new RecordTypeFieldValue(84, new RecordTypeField(25), new Record(40), "13x15"));
list.add(new RecordTypeFieldValue(85, new RecordTypeField(26), new Record(40), "VGA"));
list.add(new RecordTypeFieldValue(86, new RecordTypeField(27), new Record(40), ""));
list.add(new RecordTypeFieldValue(87, new RecordTypeField(28), new Record(40), "HDMI"));
list.add(new RecordTypeFieldValue(88, new RecordTypeField(29), new Record(40), ""));
list.add(new RecordTypeFieldValue(89, new RecordTypeField(25), new Record(42), "13x15"));
list.add(new RecordTypeFieldValue(90, new RecordTypeField(26), new Record(42), "VGA"));
list.add(new RecordTypeFieldValue(91, new RecordTypeField(27), new Record(42), ""));
list.add(new RecordTypeFieldValue(92, new RecordTypeField(28), new Record(42), "HDMI"));
list.add(new RecordTypeFieldValue(93, new RecordTypeField(29), new Record(42), ""));
list.add(new RecordTypeFieldValue(94, new RecordTypeField(25), new Record(43), "13x15"));
list.add(new RecordTypeFieldValue(95, new RecordTypeField(26), new Record(43), "VGA"));
list.add(new RecordTypeFieldValue(96, new RecordTypeField(27), new Record(43), ""));
list.add(new RecordTypeFieldValue(97, new RecordTypeField(28), new Record(43), "HDMI"));
list.add(new RecordTypeFieldValue(98, new RecordTypeField(29), new Record(43), ""));
list.add(new RecordTypeFieldValue(99, new RecordTypeField(34), new Record(46), "SW"));
list.add(new RecordTypeFieldValue(100, new RecordTypeField(35), new Record(46), "64:D9:89:33:0C:80"));
list.add(new RecordTypeFieldValue(101, new RecordTypeField(36), new Record(46), "-"));
list.add(new RecordTypeFieldValue(102, new RecordTypeField(37), new Record(46), "-"));
list.add(new RecordTypeFieldValue(103, new RecordTypeField(38), new Record(46), "-"));
list.add(new RecordTypeFieldValue(104, new RecordTypeField(39), new Record(46), "-"));
list.add(new RecordTypeFieldValue(105, new RecordTypeField(40), new Record(46), "-"));
list.add(new RecordTypeFieldValue(106, new RecordTypeField(41), new Record(46), "-"));
list.add(new RecordTypeFieldValue(107, new RecordTypeField(34), new Record(47), "SW"));
list.add(new RecordTypeFieldValue(108, new RecordTypeField(35), new Record(47), "64:D9:89:33:0C:80"));
list.add(new RecordTypeFieldValue(109, new RecordTypeField(36), new Record(47), "-"));
list.add(new RecordTypeFieldValue(110, new RecordTypeField(37), new Record(47), "-"));
list.add(new RecordTypeFieldValue(111, new RecordTypeField(38), new Record(47), "-"));
list.add(new RecordTypeFieldValue(112, new RecordTypeField(39), new Record(47), "-"));
list.add(new RecordTypeFieldValue(113, new RecordTypeField(40), new Record(47), "-"));
list.add(new RecordTypeFieldValue(114, new RecordTypeField(41), new Record(47), "-"));
list.add(new RecordTypeFieldValue(115, new RecordTypeField(48), new Record(52), "Ref"));
list.add(new RecordTypeFieldValue(116, new RecordTypeField(52), new Record(52), "Refrigerator"));
list.add(new RecordTypeFieldValue(117, new RecordTypeField(48), new Record(53), "Ref"));
list.add(new RecordTypeFieldValue(118, new RecordTypeField(52), new Record(53), "Refrigerator"));
list.add(new RecordTypeFieldValue(119, new RecordTypeField(51), new Record(54), "Brown chairs"));
list.add(new RecordTypeFieldValue(120, new RecordTypeField(51), new Record(55), "Brown chairs"));
list.add(new RecordTypeFieldValue(121, new RecordTypeField(51), new Record(56), "Brown chairs"));
}
}
public List<RecordTypeFieldValue> getDetailsOfRecord(Record record) {
List<RecordTypeFieldValue> results = new ArrayList<RecordTypeFieldValue>();
for (RecordTypeFieldValue value : list) {
if (value.getRecord().getId() == record.getId()) {
value.setRecord(record);
results.add(value);
}
}
return results;
}
}
| 81 | 117 | 0.658145 |
938a2a56bb6617d3a821195e73daa7d884f14749
| 3,826 |
package com.homw.tool.application;
import java.io.File;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import com.homw.common.util.Platform;
/**
* @description 应用工厂
* @author Hom
* @version 1.0
* @since 2019-05-20
*/
public class ApplicationFactory {
private static Map<String, String> appMap = new HashMap<>();
private static Application active;
private ApplicationFactory() {}
/**
* 创建应用
*
* @param appKey
* @return
* @throws Exception
*/
public static Application create(String appKey) throws Exception {
String className = appMap.get(appKey);
if (className == null) {
throw new IllegalArgumentException("application [" + appKey + "] not found.");
}
try {
Class<?> clazz = Class.forName(className);
if (Application.class.isAssignableFrom(clazz)) {
active = (Application) clazz.newInstance();
return active;
} else {
throw new IllegalArgumentException("application [" + appKey + "] not supported.");
}
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("class [" + className + "] not found.", e);
}
}
/**
* 初始化注册应用
* @param packageName
* @throws Exception
*/
public static void init(String packageName) throws Exception {
String path = packageName.replaceAll("\\.", "/");
Enumeration<URL> resources = Thread.currentThread().getContextClassLoader().getResources(path);
while (resources.hasMoreElements()) {
URL resource = resources.nextElement();
String protocol = resource.getProtocol();
if ("file".equals(protocol)) {
File dir = new File(resource.getFile());
for (File file : dir.listFiles()) {
if (file.isDirectory()) {
init(packageName + "." + file.getName());
} else if (file.getName().endsWith(".class")) {
String className = packageName + "." + file.getName().replace(".class", "");
Class<?> clazz = Class.forName(className);
com.homw.tool.annotation.Application appAnnotaion = clazz.getAnnotation(
com.homw.tool.annotation.Application.class);
if (appAnnotaion != null) {
appMap.put(appAnnotaion.value(), className);
}
}
}
} else if ("jar".equals(protocol)) {
String jarpath = resource.getPath();
if (Platform.isWindow()) {
jarpath = jarpath.replace("file:/", "");
} else {
jarpath = jarpath.replace("file:", "");
}
jarpath = jarpath.substring(0, jarpath.indexOf("!"));
// fix FileNotFoundException
// example: jarPath contains '%e4%91%e8', encode from Chinese or space
jarpath = URLDecoder.decode(jarpath, "UTF-8");
JarFile jarFile = new JarFile(jarpath);
try {
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
String entryName = entry.getName();
if (entryName.startsWith(path) && entryName.endsWith(".class")) {
String className = entryName.replace('/', '.');
className = className.substring(0, className.length() - 6);
Class<?> clazz = Class.forName(className);
com.homw.tool.annotation.Application appAnnotaion = clazz
.getAnnotation(com.homw.tool.annotation.Application.class);
if (appAnnotaion != null) {
appMap.put(appAnnotaion.value(), className);
}
}
}
} finally {
jarFile.close();
}
}
}
}
public static Map<String, String> getAppMap() {
return Collections.unmodifiableMap(appMap);
}
public static Application getActive() {
return active;
}
}
| 30.608 | 98 | 0.634605 |
bd59b26fafebe9bc129810ce683194be147fbc1b
| 3,627 |
package com.udacity.vehicles.service;
import com.udacity.vehicles.client.maps.MapsClient;
import com.udacity.vehicles.client.prices.PriceClient;
import com.udacity.vehicles.domain.Location;
import com.udacity.vehicles.domain.car.Car;
import com.udacity.vehicles.domain.car.CarRepository;
import java.util.List;
import java.util.stream.Collectors;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
/**
* Implements the car service create, read, update or delete
* information about vehicles, as well as gather related
* location and price data when desired.
*/
@Service
public class CarService {
private final CarRepository repository;
private final MapsClient mapsClient;
private final PriceClient priceClient;
@Autowired
public CarService(
CarRepository repository,
@Qualifier("maps") WebClient mapsWebClient,
@Qualifier("pricing") WebClient priceWebClient,
ModelMapper modelMapper
) {
this.repository = repository;
this.mapsClient = new MapsClient(mapsWebClient, modelMapper);
this.priceClient = new PriceClient(priceWebClient);
}
/**
* Gathers a list of all vehicles
* @return a list of all vehicles in the CarRepository
*/
public List<Car> list() {
return repository.findAll().stream()
.peek(this::fetchPriceAndAddress)
.collect(Collectors.toList());
}
/**
* Gets car information by ID (or throws exception if non-existent)
* @param id the ID number of the car to gather information on
* @return the requested car's information, including location and price
*/
public Car findById(Long id) {
Car car = repository.findById(id).orElseThrow(CarNotFoundException::new);
fetchPriceAndAddress(car);
return car;
}
/**
* Either creates or updates a vehicle, based on prior existence of car
* @param car A car object, which can be either new or existing
* @return the new/updated car is stored in the repository
*/
public Car save(Car car) {
if (car.getId() != null) {
return repository.findById(car.getId())
.map(carToBeUpdated -> {
carToBeUpdated.setDetails(car.getDetails());
carToBeUpdated.setLocation(car.getLocation());
carToBeUpdated = repository.save(carToBeUpdated);
fetchPriceAndAddress(carToBeUpdated);
return carToBeUpdated;
}).orElseThrow(CarNotFoundException::new);
}
repository.save(car);
fetchPriceAndAddress(car);
return car;
}
/**
* Deletes a given car by ID
* @param id the ID number of the car to delete
*/
public void delete(Long id) {
Car car = repository.findById(id).orElseThrow(CarNotFoundException::new);
repository.delete(car);
repository.save(car);
}
/**
* Fetches and sets Car object in-place price and address by calling other separate services
* @param car @Car object
*/
public void fetchPriceAndAddress(Car car) {
String price = priceClient.getPrice(car.getId());
car.setPrice(price);
Location address = mapsClient.getAddress(car.getLocation());
car.setLocation(address);
}
}
| 32.972727 | 96 | 0.658947 |
da0ac1a46a3ad279a4f3c3a68247f8cc5b7d944a
| 15,574 |
/**
* This software was developed and / or modified by Raytheon Company,
* pursuant to Contract DG133W-05-CQ-1067 with the US Government.
*
* U.S. EXPORT CONTROLLED TECHNICAL DATA
* This software product contains export-restricted data whose
* export/transfer/disclosure is restricted by U.S. law. Dissemination
* to non-U.S. persons whether in the United States or abroad requires
* an export license or other authorization.
*
* Contractor Name: Raytheon Company
* Contractor Address: 6825 Pine Street, Suite 340
* Mail Stop B8
* Omaha, NE 68106
* 402.291.0100
*
* See the AWIPS II Master Rights File ("Master Rights File.pdf") for
* further licensing information.
**/
package com.raytheon.uf.common.mpe.gribit2.grib;
import java.io.IOException;
import java.io.OutputStream;
import com.mchange.lang.ByteUtils;
/**
* Utility to handle common conversions of xmrg to grib properties.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Jul 27, 2016 4619 bkowal Initial creation
* Aug 10, 2016 4619 bkowal Added pack methods and handling of negative values.
* Aug 18, 2016 4619 bkowal Updated to support binary data section packing.
*
* </pre>
*
* @author bkowal
*/
public final class XmrgGribPropertyUtils {
private static final int DIVISOR_5 = 65536;
public static final int DIVISOR_6 = 256;
public static final int SIZE_BYTES_LEN = 3;
public static final int CONST_128 = 128;
public static final int CONST_255 = 255;
private static final int CONST_CONVERT_NEGATIVE = 8388608;
private static final int CONST_REVERT_NEGATIVE = 8388607;
private static final int[] BIT_ONES = { 1, 3, 7, 15, 31, 63, 127, CONST_255 };
private static final int BITS_PER_BYTE = 8;
protected XmrgGribPropertyUtils() {
}
/**
* Converts the specified byte array to unsigned bytes utilizing
* {@link ByteUtils}.
*
* @param bytes
* the specified byte array
* @return the unsigned byte array that was produced
*/
public static short[] getUnsignedBytes(final byte[] bytes) {
if (bytes == null) {
throw new IllegalArgumentException(
"Required argument 'bytes' cannot be NULL.");
}
short[] unsignedBytes = new short[bytes.length];
for (int i = 0; i < bytes.length; i++) {
unsignedBytes[i] = ByteUtils.toUnsigned(bytes[i]);
}
return unsignedBytes;
}
/**
* Converts the specified byte array to a size value. Gribit stored many
* larger numeric values across three (3) array elements. The specified byte
* array is expected to have a length of {@link #SIZE_BYTES_LEN}.
*
* @param sizeBytes
* the specified byte array
* @return the size value that was calculated
*/
public static int convertToSize(final short[] sizeBytes) {
if (sizeBytes.length != SIZE_BYTES_LEN) {
throw new IllegalArgumentException(
"Expected argument 'sizeBytes' to have a length of "
+ SIZE_BYTES_LEN + ".");
}
return (sizeBytes[0] * DIVISOR_5) + (sizeBytes[1] * DIVISOR_6)
+ sizeBytes[2];
}
/**
* Unpack bits. Extract arbitrary size values from the specified packed bit
* string, right justifying each value in the unpacked array. Based on:
* /rary.ohd.pproc.gribit/TEXT/gbytes_char.f
*
* @param destination
* the output array to write the unpacked result to
* @param toUnpack
* the specified packed bit string
* @param skip
* initial number of bits to skip
* @param count
* number of bits to take
*/
public static void unpackBytes(int[] destination, final short[] toUnpack,
final int skip, final int count) {
unpackBytes(destination, toUnpack, skip, count, 0, 1);
}
/**
* Unpack bits. Extract arbitrary size values from the specified packed bit
* string, right justifying each value in the unpacked array. Based on:
* /rary.ohd.pproc.gribit/TEXT/gbytes_char.f
*
* @param destination
* the output array to write the unpacked result to
* @param toUnpack
* the specified packed bit string
* @param skip
* additional number of bits to skip on each iteration
* @param count
* number of bits to take
* @param adjustNegative
* boolean flag specifying whether possible negative
* transformations should be applied to unpacked values that are
* determined to be negative.
*/
public static void unpackBytes(int[] destination, final short[] toUnpack,
final int skip, final int count, final boolean adjustNegative) {
unpackBytes(destination, toUnpack, skip, count, 0, 1, adjustNegative);
}
/**
* Unpack bits. Extract arbitrary size values from the specified packed bit
* string, right justifying each value in the unpacked array. Based on:
* /rary.ohd.pproc.gribit/TEXT/gbytes_char.f
*
* @param destination
* the output array to write the unpacked result to
* @param toUnpack
* the specified packed bit string
* @param skip
* additional number of bits to skip on each iteration
* @param count
* number of bits to take
* @param additional
* additional number of bits to skip on each iteration
* @param iterations
* number of iterations
*/
public static void unpackBytes(int[] destination, final short[] toUnpack,
final int skip, final int count, final int additional,
final int iterations) {
unpackBytes(destination, toUnpack, skip, count, additional, iterations,
false);
}
/**
* Unpack bits. Extract arbitrary size values from the specified packed bit
* string, right justifying each value in the unpacked array. Based on:
* /rary.ohd.pproc.gribit/TEXT/gbytes_char.f
*
* @param destination
* the output array to write the unpacked result to
* @param toUnpack
* the specified packed bit string
* @param skip
* additional number of bits to skip on each iteration
* @param count
* number of bits to take
* @param additional
* additional number of bits to skip on each iteration
* @param iterations
* number of iterations
* @param adjustNegative
* boolean flag specifying whether possible negative
* transformations should be applied to unpacked values that are
* determined to be negative.
*/
public static void unpackBytes(int[] destination, final short[] toUnpack,
final int skip, final int count, final int additional,
final int iterations, final boolean adjustNegative) {
int nbit = skip;
for (int i = 0; i < iterations; i++) {
int bitCount = count;
int index = (nbit / 8);
int ibit = nbit % 8;
nbit = nbit + count + skip;
/*
* first byte.
*/
int tbit = Math.min(bitCount, 8 - ibit);
int itmp = toUnpack[index] & BIT_ONES[7 - ibit];
if (tbit != (8 - ibit)) {
final int shift = tbit - 8 + ibit;
if (shift < 0) {
itmp = (itmp >>> Math.abs(shift));
} else {
itmp = (itmp << shift);
}
}
++index;
bitCount = bitCount - tbit;
while (bitCount >= 8) {
itmp = (itmp << 8) | toUnpack[index];
bitCount -= 8;
++index;
}
// last byte
if (bitCount > 0) {
// bit count is between 1 and 7 inclusive.
/*
* 1 is subtracted from the bit count when accessing the
* BIT_ONES array because Fortran arrays start at index 1
* whereas Java arrays currently start at index 0.
*/
itmp = (itmp << bitCount)
| ((toUnpack[index] >>> (8 - bitCount)) & BIT_ONES[bitCount - 1]);
}
if (adjustNegative && (itmp & CONST_CONVERT_NEGATIVE) != 0) {
itmp = -(itmp & CONST_REVERT_NEGATIVE);
}
destination[i] = itmp;
}
}
/**
* Pack bits. Put arbitrary size values from the specified unpacked bit
* string into a packed bit string, taking the low order bits from each
* value in the unpacked array.
*
* @param destination
* the output array to write the packed result to
* @param toPack
* the specified unpacked bit string
* @param skip
* additional number of bits to skip on each iteration
* @param count
* number of bits to take
*/
public static void packBytes(short[] destination, final int[] toPack,
final int skip, final int count) {
packBytes(destination, toPack, skip, count, false);
}
/**
* Pack bits. Put arbitrary size values from the specified unpacked bit
* string into a packed bit string, taking the low order bits from each
* value in the unpacked array.
*
* @param destination
* the output array to write the packed result to
* @param toPack
* the specified unpacked bit string
* @param skip
* additional number of bits to skip on each iteration
* @param count
* number of bits to take
* @param adjustNegative
* boolean flag specifying whether negative values should be
* detected and adjusted prior to packing
*/
public static void packBytes(short[] destination, final int[] toPack,
final int skip, final int count, final boolean adjustNegative) {
packBytes(destination, toPack, skip, count, 0, 1, adjustNegative);
}
/**
* Pack bits. Put arbitrary size values from the specified unpacked bit
* string into a packed bit string, taking the low order bits from each
* value in the unpacked array.
*
* @param destination
* the output array to write the packed result to
* @param toPack
* the specified unpacked bit string
* @param skip
* additional number of bits to skip on each iteration
* @param count
* number of bits to take
* @param additional
* additional number of bits to skip on each iteration
* @param iterations
* number of iterations
*/
public static void packBytes(short[] destination, final int[] toPack,
final int skip, final int count, final int additional,
final int iterations) {
packBytes(destination, toPack, skip, count, additional, iterations,
false);
}
/**
* Pack bits. Put arbitrary size values from the specified unpacked bit
* string into a packed bit string, taking the low order bits from each
* value in the unpacked array.
*
* @param destination
* the output array to write the packed result to
* @param toPack
* the specified unpacked bit string
* @param skip
* additional number of bits to skip on each iteration
* @param count
* number of bits to take
* @param additional
* additional number of bits to skip on each iteration
* @param iterations
* number of iterations
* @param adjustNegative
* boolean flag specifying whether negative values should be
* detected and adjusted prior to packing
*/
public static void packBytes(short[] destination, final int[] toPack,
final int skip, final int count, final int additional,
final int iterations, final boolean adjustNegative) {
int nbit = skip + count - 1;
for (int i = 0; i < iterations; i++) {
int itmp = toPack[i];
if (adjustNegative && itmp < 0) {
itmp = Math.abs(itmp) | CONST_CONVERT_NEGATIVE;
}
int bitCount = count;
int index = (nbit / 8);
int ibit = nbit % 8;
nbit = nbit + count + skip;
/*
* make byte aligned
*/
if (ibit != 7) {
int tbit = Math.min(bitCount, ibit + 1);
final int shift = 7 - ibit;
int itmp2;
int imask;
if (shift < 0) {
imask = (BIT_ONES[tbit - 1] >>> Math.abs(shift));
itmp2 = (itmp >>> Math.abs(shift)) & imask;
} else {
imask = (BIT_ONES[tbit - 1] << shift);
itmp2 = (itmp << shift) & imask;
}
int itmp3 = destination[index] & (CONST_255 - imask);
destination[index] = (short) (itmp2 | itmp3);
bitCount -= tbit;
final int opTbit = -tbit;
if (opTbit < 0) {
itmp = itmp >>> Math.abs(opTbit);
} else {
itmp = itmp << opTbit;
}
--index;
}
/*
* now byte aligned
*/
while (bitCount >= 8) {
destination[index] = (short) (itmp & CONST_255);
itmp = itmp >>> 8;
bitCount -= 8;
--index;
}
if (bitCount > 0) {
int itmp2 = itmp & BIT_ONES[bitCount - 1];
int itmp3 = destination[index]
& (CONST_255 - BIT_ONES[bitCount - 1]);
destination[index] = (short) (itmp2 | itmp3);
}
}
}
/**
* Calculates the bit offset excluding the size bytes. An additional 1 is
* subtracted because the first index in a Fortran array is 1 whereas in
* Java the first index in an array is 0.
*
* @param startIndex
* the index of the first byte
* @return the calculated bit offset
*/
public static int calculateBitOffset(final int startIndex) {
return (startIndex - SIZE_BYTES_LEN - 1) * BITS_PER_BYTE;
}
/**
* Writes an array of shorts as bytes to the specified {@link OutputStream}.
* In Fortran, characters are only one byte compared to the two byte
* characters in Java.
*
* @param os
* the specified {@link OutputStream}
* @param toWrite
* the array of shorts to write to the buffer as bytes
*/
public static void writeShortArrayAsBytes(final OutputStream os,
final short[] toWrite) throws IOException {
for (short value : toWrite) {
os.write(value);
}
}
}
| 36.731132 | 90 | 0.559843 |
a7e7a8d555717cae60706e65a1306a51190c7ede
| 2,464 |
/*
* Copyright (C) 2011 the original author or authors.
* See the notice.md file distributed with this work for additional
* information regarding copyright ownership.
*
* 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.iq80.leveldb.impl;
import org.iq80.leveldb.util.Slice;
import org.testng.annotations.Test;
import java.io.File;
import java.io.FileInputStream;
import java.nio.channels.FileChannel;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.fail;
public class TestMMapLogWriter
{
@Test
public void testLogRecordBounds()
throws Exception
{
File file = File.createTempFile("test", ".log");
try {
int recordSize = LogConstants.BLOCK_SIZE - LogConstants.HEADER_SIZE;
Slice record = new Slice(recordSize);
LogWriter writer = new MMapLogWriter(file, 10);
writer.addRecord(record, false);
writer.close();
LogMonitor logMonitor = new AssertNoCorruptionLogMonitor();
FileChannel channel = new FileInputStream(file).getChannel();
LogReader logReader = new LogReader(channel, logMonitor, true, 0);
int count = 0;
for (Slice slice = logReader.readRecord(); slice != null; slice = logReader.readRecord()) {
assertEquals(slice.length(), recordSize);
count++;
}
assertEquals(count, 1);
}
finally {
file.delete();
}
}
private static class AssertNoCorruptionLogMonitor
implements LogMonitor
{
@Override
public void corruption(long bytes, String reason)
{
fail("corruption at " + bytes + " reason: " + reason);
}
@Override
public void corruption(long bytes, Throwable reason)
{
fail("corruption at " + bytes + " reason: " + reason);
}
}
}
| 31.189873 | 103 | 0.642451 |
3b16c632a2a2faf2e11132090214845520c2ac49
| 1,775 |
package practice.java.numericexamples;
public class SwapWithoutThirdVariable {
public static void main(String[] args) {
// swap(10,20);
// greatestOfNumber(20,30,30);
// arrayTwoGreatestNumber();
// reverseNumber(45780);
// palindrome(12321);
armstrongNumber(371);
}
private static void armstrongNumber(int n) {
int temp =n;
int a=0;int arm=0;
while(n!=0) {
a=n%10;
arm =arm+(a*a*a);
n=n/10;
}
System.out.println(" n is : " + temp + " arm is " +arm);
if(temp == arm) {
System.out.println("Given no is armstrong no");
}else {
System.out.println("Given no is not armstong no");
}
}
private static void palindrome(int i) {
if(i == reverseNumber(i)) {
System.out.println("Number is palindrome");
}else
{
System.out.println("Number is not palindrome");
}
}
private static int reverseNumber(int i) {
int r=0;
while(i!=0) {
r=(i%10)+10*r;
i=i/10;
}
System.out.println(r);
return r;
}
private static void arrayTwoGreatestNumber() {
int[] arr = {40,5,20,3,6,9};int temp=0;
for (int i=0;i<arr.length;i++) {
for(int j=i+1;j<arr.length;j++) {
if(arr[i]<arr[j]) {
temp = arr[j];
arr[j]=arr[i];
arr[i]=temp;
}
}
}
System.out.println("Largest 2 numbers in Array are " + arr[0] +" and " + arr[1]);
}
private static void greatestOfNumber(int i, int j, int k) {
if(i>j & i>k) {
System.out.println(i + "i is greatest number");
}
else if(j>k) {
System.out.println(j + " j is greatest number");
}
else {
System.out.println(k + " k is greatest number");
}
}
private static void swap(int a, int b) {
System.out.println(" a =" + a + " b =" + b);
a = a + b;
b = a - b;
a = a - b;
System.out.println(" a =" + a + " b =" + b);
}
}
| 21.130952 | 83 | 0.581408 |
da4b7d8b02d3233e9a5875b7092954b8daf4801c
| 2,648 |
package jeyts.uflapplication.Adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;
import jeyts.uflapplication.R;
import jeyts.uflapplication.Model.MyDataModel;
import java.util.List;
public class StandArrayAdapter extends ArrayAdapter<MyDataModel> {
List<MyDataModel> modelList;
Context context;
private LayoutInflater mInflater;
// Constructors
public StandArrayAdapter(Context context, List<MyDataModel> objects) {
super(context, 0, objects);
this.context = context;
this.mInflater = LayoutInflater.from(context);
modelList = objects;
}
@Override
public MyDataModel getItem(int position) {
return modelList.get(position);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder vh;
if (convertView == null) {
View view = mInflater.inflate(R.layout.layout2_row_view, parent, false);
vh = ViewHolder.create((RelativeLayout) view);
view.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
MyDataModel item = getItem(position);
vh.textViewTeamStand.setText(item.getTeamStand());
vh.textViewStandScore.setText(item.getStandScore());
return vh.rootView;
}
/**
* ViewHolder class for layout.<br />
* <br />
* Auto-created on 2016-01-05 00:50:26 by Android Layout Finder
* (http://www.buzzingandroid.com/tools/android-layout-finder)
*/
private static class ViewHolder {
public final RelativeLayout rootView;
public final TextView textViewTeamStand;
public final TextView textViewStandScore;
private ViewHolder(RelativeLayout rootView, TextView textViewTeamStand, TextView textViewStandScore) {
this.rootView = rootView;
this.textViewTeamStand = textViewTeamStand;
this.textViewStandScore = textViewStandScore;
}
public static ViewHolder create(RelativeLayout rootView) {
TextView textViewTeamStand = (TextView) rootView.findViewById(R.id.textViewStandings);
TextView textViewStandScore = (TextView) rootView.findViewById(R.id.textViewScore);
// TextView textViewCompletions = (TextView) rootView.findViewById(R.id.textViewCompletions);
return new ViewHolder(rootView, textViewTeamStand, textViewStandScore);
}
}
}
| 30.790698 | 110 | 0.687689 |
0bba13804e50825244252616bcac020f8b41dc52
| 270 |
package com.github.valentinkarnaukhov.stubgeneratorv3.processor;
import com.github.valentinkarnaukhov.stubgenerator.model.TagTemplate;
import java.util.List;
/**
* @author Valentin Karnaukhov
*/
public interface SpecProcessor {
List<TagTemplate> process();
}
| 18 | 69 | 0.785185 |
ecf29a314c68309e9556174d52ce6298cffbcf9c
| 2,065 |
package com.akjava.lib.common.functions;
import com.akjava.lib.common.utils.FileNames;
import com.google.common.base.Function;
public class FileNamesFunctions {
/**
* TODO
* @author aki
*
*filter extension
*file only
*
*path to parentfolders for zip?
*/
public class PathToDirectoryNameFunction implements Function<String,String>{
private boolean isHandleNoExtensionFileAsDir;
private FileNames fileNames;
public PathToDirectoryNameFunction(char fileSeparator,boolean isHandleNoExtensionFileAsDir){
fileNames=FileNames.as(fileSeparator);
this.isHandleNoExtensionFileAsDir=isHandleNoExtensionFileAsDir;
}
@Override
public String apply(String input) {
return fileNames.getDirectoryPath(input,isHandleNoExtensionFileAsDir);
}
}
/**
* not replace when no extension like ends with file separator or has no extension
* @author aki
*
*/
public class ChangeExtensionFunction implements Function<String,String>{
private String extension;
private FileNames fileNames;
public ChangeExtensionFunction(char fileSeparator,String extension){
fileNames=FileNames.as(fileSeparator);
this.extension=extension;
}
@Override
public String apply(String input) {
return fileNames.getChangedExtensionName(input,extension);
}
}
/**
* replace no extension files too,but not replace a file must be folder(ends with fileSeparator)
* @author aki
*
*/
public class ChangeOrAddExtensionFunction implements Function<String,String>{
private String extension;
private FileNames fileNames;
public ChangeOrAddExtensionFunction(char fileSeparator,String extension){
fileNames=FileNames.as(fileSeparator);
this.extension=extension;
}
@Override
public String apply(String input) {
if(fileNames.isEndsWithFileSeparator(input)){
return input;
}
if(fileNames.hasExtension(input)){
return fileNames.getChangedExtensionName(input,extension);
}else{
return input+"."+extension;
}
}
}
}
| 27.171053 | 98 | 0.731719 |
5232cc915b1920f61eda5ed587a43537d111aa08
| 218 |
package study.daydayup.wolf.business.account.api.service.auth;
/**
* study.daydayup.wolf.business.account.api.service.auth
*
* @author Wingle
* @since 2019/9/27 5:18 PM
**/
public interface WechatAuthService {
}
| 19.818182 | 62 | 0.733945 |
4c101bb4fdbcbeea5187b0f4b2c4cbb7bee7fc1d
| 474 |
package hu.pazsitz.tools.java.util.stream;
public class NoEqualsForObject {
private String attr1;
private String attr2;
public NoEqualsForObject(String attr1, String attr2) {
this.attr1 = attr1;
this.attr2 = attr2;
}
public String getAttr1() {
return attr1;
}
public String getAttr2() {
return attr2;
}
@Override
public String toString() {
return "{" + attr1 + ":" + attr2 + "}";
}
}
| 18.96 | 58 | 0.586498 |
a71e0352e236c83870c579b1ed57bc69e40a63c7
| 304 |
package mil.nga.crs.common;
/**
* Unit Type
*
* @author osbornb
*/
public enum UnitType {
/**
* Angle
*/
ANGLEUNIT,
/**
* Length
*/
LENGTHUNIT,
/**
* Parametric
*/
PARAMETRICUNIT,
/**
* Scale
*/
SCALEUNIT,
/**
* Time
*/
TIMEUNIT,
/**
* Generic
*/
UNIT;
}
| 7.414634 | 27 | 0.5 |
456cd5194e51793b12db57dad45083597eef2c60
| 13,253 |
package com.baidu.location.b;
import android.annotation.SuppressLint;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.os.Build.VERSION;
import android.os.SystemClock;
import android.text.TextUtils;
import com.baidu.location.d.j;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class g
{
public List<ScanResult> a = null;
private long b = 0L;
private long c = 0L;
private boolean d = false;
private boolean e;
public g(List<ScanResult> paramList, long paramLong)
{
this.b = paramLong;
this.a = paramList;
this.c = System.currentTimeMillis();
i();
}
private boolean a(String paramString)
{
if (TextUtils.isEmpty(paramString)) {
return false;
}
return Pattern.compile("wpa|wep", 2).matcher(paramString).find();
}
private void i()
{
if (a() < 1) {
return;
}
int j = this.a.size() - 1;
int i = 1;
label23:
int k;
if ((j >= 1) && (i != 0))
{
k = 0;
i = 0;
label36:
if (k < j)
{
if (((ScanResult)this.a.get(k)).level >= ((ScanResult)this.a.get(k + 1)).level) {
break label147;
}
ScanResult localScanResult = (ScanResult)this.a.get(k + 1);
this.a.set(k + 1, this.a.get(k));
this.a.set(k, localScanResult);
i = 1;
}
}
label147:
for (;;)
{
k += 1;
break label36;
j -= 1;
break label23;
break;
}
}
public int a()
{
if (this.a == null) {
return 0;
}
return this.a.size();
}
public String a(int paramInt)
{
return a(paramInt, false);
}
@SuppressLint({"NewApi"})
public String a(int paramInt, boolean paramBoolean)
{
if (a() < 1) {
return null;
}
int j = 0;
Object localObject3;
int n;
long l2;
long l3;
int i;
int k;
long l4;
label161:
int i2;
label178:
int m;
label209:
int i4;
label258:
int i1;
for (;;)
{
try
{
localObject7 = new Random();
localStringBuffer = new StringBuffer(512);
localObject6 = new ArrayList();
localObject3 = h.a().i();
if ((localObject3 == null) || (((WifiInfo)localObject3).getBSSID() == null)) {
break label1255;
}
Object localObject1 = ((WifiInfo)localObject3).getBSSID().replace(":", "");
n = ((WifiInfo)localObject3).getRssi();
localObject3 = h.a().k();
if (n >= 0) {
break label1240;
}
n = -n;
Object localObject4 = localObject3;
localObject3 = localObject1;
localObject1 = localObject4;
l2 = 0L;
l3 = 0L;
i = 0;
k = Build.VERSION.SDK_INT;
if (k < 17) {
break label1233;
}
}
catch (Error localError1)
{
StringBuffer localStringBuffer;
return null;
if ((paramInt != 1) || (((Random)localObject7).nextInt(20) != 1) || (((ScanResult)this.a.get(i4)).SSID == null) || (((ScanResult)this.a.get(i4)).SSID.length() >= 30)) {
break label1221;
}
localStringBuffer.append(((ScanResult)this.a.get(i4)).SSID);
paramInt = 2;
continue;
continue;
localStringBuffer.append(((ScanResult)this.a.get(i4)).SSID);
i1 = k;
break label1284;
if (j != 0) {
continue;
}
localStringBuffer.append("&wf_n=" + i);
if ((localObject3 == null) || (n == -1)) {
continue;
}
localStringBuffer.append("&wf_rs=" + n);
if ((l2 <= 10L) || (((List)localObject6).size() <= 0) || (((Long)((List)localObject6).get(0)).longValue() <= 0L)) {
continue;
}
localObject3 = new StringBuffer(128);
((StringBuffer)localObject3).append("&wf_ut=");
paramInt = 1;
localObject5 = (Long)((List)localObject6).get(0);
Object localObject6 = ((List)localObject6).iterator();
if (!((Iterator)localObject6).hasNext()) {
continue;
}
Object localObject7 = (Long)((Iterator)localObject6).next();
if (paramInt == 0) {
continue;
}
((StringBuffer)localObject3).append(((Long)localObject7).longValue());
paramInt = 0;
((StringBuffer)localObject3).append("|");
continue;
long l1 = ((Long)localObject7).longValue() - ((Long)localObject5).longValue();
if (l1 == 0L) {
break label1302;
}
((StringBuffer)localObject3).append("" + l1);
break label1302;
localStringBuffer.append(((StringBuffer)localObject3).toString());
localStringBuffer.append("&wf_st=");
localStringBuffer.append(this.b);
localStringBuffer.append("&wf_et=");
localStringBuffer.append(this.c);
localStringBuffer.append("&wf_vt=");
localStringBuffer.append(h.a);
if (i <= 0) {
continue;
}
this.d = true;
localStringBuffer.append("&wf_en=");
if (!this.e) {
continue;
}
paramInt = 1;
localStringBuffer.append(paramInt);
if (localError1 == null) {
continue;
}
localStringBuffer.append("&wf_gw=");
localStringBuffer.append(localError1);
str1 = localStringBuffer.toString();
return str1;
paramInt = 0;
continue;
return null;
}
catch (Exception localException1)
{
label647:
return null;
}
try
{
l1 = SystemClock.elapsedRealtimeNanos() / 1000L;
l2 = l1;
if (l1 <= 0L) {
break label1233;
}
i = 1;
l4 = l1;
if (i == 0) {
break label1227;
}
if ((i != 0) && (paramBoolean))
{
i = 1;
i2 = i;
k = 0;
i = 0;
int i3 = this.a.size();
m = 1;
if (i3 <= paramInt) {
break label1224;
}
i3 = paramInt;
break label1267;
if (i4 >= i3) {
continue;
}
m = ((ScanResult)this.a.get(i4)).level;
if (m != 0) {
continue;
}
m = j;
j = k;
l1 = l2;
k = paramInt;
paramInt = m;
i4 += 1;
m = j;
j = paramInt;
paramInt = k;
k = m;
l2 = l1;
continue;
}
}
catch (Error localError2)
{
l1 = 0L;
continue;
i = 0;
continue;
l1 = l2;
if (i2 == 0) {}
}
try
{
l3 = (l4 - ((ScanResult)this.a.get(i4)).timestamp) / 1000000L;
((List)localObject6).add(Long.valueOf(l3));
l1 = l2;
if (l3 > l2) {
l1 = l3;
}
if (j != 0)
{
j = 0;
localStringBuffer.append("&wf=");
String str2 = ((ScanResult)this.a.get(i4)).BSSID;
i1 = i;
m = k;
if (str2 == null) {
break label1284;
}
str2 = str2.replace(":", "");
localStringBuffer.append(str2);
i1 = ((ScanResult)this.a.get(i4)).level;
m = i1;
if (i1 < 0) {
m = -i1;
}
localStringBuffer.append(String.format(Locale.CHINA, ";%d;", new Object[] { Integer.valueOf(m) }));
m = k + 1;
int i5 = 0;
i1 = i5;
k = i;
if (localObject3 != null)
{
i1 = i5;
k = i;
if (((String)localObject3).equals(str2))
{
this.e = a(((ScanResult)this.a.get(i4)).capabilities);
i1 = 1;
k = m;
}
}
if (i1 != 0) {
continue;
}
if (paramInt != 0) {
continue;
}
}
}
catch (Exception localException2)
{
try
{
if ((((Random)localObject7).nextInt(10) != 2) || (((ScanResult)this.a.get(i4)).SSID == null) || (((ScanResult)this.a.get(i4)).SSID.length() >= 30)) {
break label1221;
}
localStringBuffer.append(((ScanResult)this.a.get(i4)).SSID);
paramInt = 1;
i = k;
k = paramInt;
paramInt = j;
j = m;
}
catch (Exception localException3)
{
i = j;
j = m;
m = paramInt;
paramInt = i;
i = k;
k = m;
}
localException2 = localException2;
l3 = 0L;
continue;
localStringBuffer.append("|");
}
}
label1221:
label1224:
label1227:
label1233:
label1240:
label1255:
label1267:
label1284:
label1302:
for (;;)
{
String str1;
break label647;
break label1267;
i2 = i;
break label178;
l4 = l2;
break label161;
Object localObject5 = localException1;
Object localObject2 = localObject3;
localObject3 = localObject5;
break;
n = -1;
localObject2 = null;
localObject3 = null;
break;
i4 = 0;
paramInt = j;
j = m;
l2 = l3;
break label209;
i = j;
j = m;
k = paramInt;
paramInt = i;
i = i1;
break label258;
}
}
public boolean a(g paramg)
{
if ((this.a != null) && (paramg != null) && (paramg.a != null))
{
int i;
int j;
if (this.a.size() < paramg.a.size())
{
i = this.a.size();
j = 0;
}
for (;;)
{
if (j >= i) {
break label116;
}
if (!((ScanResult)this.a.get(j)).BSSID.equals(((ScanResult)paramg.a.get(j)).BSSID))
{
return false;
i = paramg.a.size();
break;
}
j += 1;
}
label116:
return true;
}
return false;
}
public String b()
{
try
{
String str = a(j.L, true);
return str;
}
catch (Exception localException) {}
return null;
}
public String b(int paramInt)
{
int i = 0;
if ((paramInt == 0) || (a() < 1)) {
return null;
}
StringBuffer localStringBuffer = new StringBuffer(256);
int j = this.a.size();
if (j > j.L) {
j = j.L;
}
for (;;)
{
int m = 1;
int k = 0;
if (k < j)
{
if (((m & paramInt) == 0) || (((ScanResult)this.a.get(k)).BSSID == null)) {
break label199;
}
if (i == 0)
{
localStringBuffer.append("&ssid=");
label101:
localStringBuffer.append(((ScanResult)this.a.get(k)).BSSID.replace(":", ""));
localStringBuffer.append(";");
localStringBuffer.append(((ScanResult)this.a.get(k)).SSID);
i += 1;
}
}
label199:
for (;;)
{
m <<= 1;
k += 1;
break;
localStringBuffer.append("|");
break label101;
return localStringBuffer.toString();
}
}
}
public boolean b(g paramg)
{
if ((this.a != null) && (paramg != null) && (paramg.a != null))
{
int i;
int j;
if (this.a.size() < paramg.a.size())
{
i = this.a.size();
j = 0;
}
for (;;)
{
if (j >= i) {
break label167;
}
String str1 = ((ScanResult)this.a.get(j)).BSSID;
int k = ((ScanResult)this.a.get(j)).level;
String str2 = ((ScanResult)paramg.a.get(j)).BSSID;
int m = ((ScanResult)paramg.a.get(j)).level;
if ((!str1.equals(str2)) || (k != m))
{
return false;
i = paramg.a.size();
break;
}
j += 1;
}
label167:
return true;
}
return false;
}
public String c()
{
try
{
String str = a(15);
return str;
}
catch (Exception localException) {}
return null;
}
public boolean c(g paramg)
{
return h.a(paramg, this, j.O);
}
public int d()
{
int k = 0;
int i = 0;
for (;;)
{
int j = k;
if (i < a())
{
j = -((ScanResult)this.a.get(i)).level;
if (j <= 0) {}
}
else
{
return j;
}
i += 1;
}
}
public boolean e()
{
return this.d;
}
public boolean f()
{
return (System.currentTimeMillis() - this.c > 0L) && (System.currentTimeMillis() - this.c < 5000L);
}
public boolean g()
{
return (System.currentTimeMillis() - this.c > 0L) && (System.currentTimeMillis() - this.c < 5000L);
}
public boolean h()
{
return (System.currentTimeMillis() - this.c > 0L) && (System.currentTimeMillis() - this.b < 5000L);
}
}
/* Location: /Users/gaoht/Downloads/zirom/classes-dex2jar.jar!/com/baidu/location/b/g.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/
| 23.08885 | 176 | 0.474006 |
642da8d46c23c1224a38ef563bdfcec49319bd0f
| 745 |
package de.suzufa.screwbox.playground.debo.tiles;
import java.util.Optional;
import de.suzufa.screwbox.tiled.Converter;
import de.suzufa.screwbox.tiled.Tile;
public abstract class BaseTileConverter implements Converter<Tile> {
private final String typeName;
protected BaseTileConverter(final String typeName) {
this.typeName = typeName;
}
@Override
public boolean accepts(final Tile tile) {
final Optional<String> type = tile.layer().properties().get("type");
if (type.isPresent()) {
return typeName.equals(type.get());
}
final Optional<String> tileType = tile.properties().get("type");
return tileType.isPresent() && typeName.equals(tileType.get());
}
}
| 28.653846 | 76 | 0.683221 |
4d06cc13a3021b82084894fb2be5dc90ae31f997
| 2,568 |
package com.rapleaf.jack.queries;
public class AggregatedColumn<T> extends Column<T> {
private enum Function {
COUNT, AVG, SUM, MAX, MIN
}
private final Function function;
private final String sqlKeyword;
private final String alias;
private AggregatedColumn(Column column, Function function, String sqlKeyword, String alias) {
super(column.table, column.field, column.type);
this.function = function;
this.sqlKeyword = sqlKeyword;
this.alias = alias;
}
private AggregatedColumn(Column column, Function function) {
this(column, function, createSqlKeyword(column, function), createAlias(column, function));
}
public static <T> AggregatedColumn<Integer> COUNT(Column<T> column) {
return new AggregatedColumn<>(column.as(Integer.class), Function.COUNT);
}
public static <T extends Number> AggregatedColumn<Number> AVG(Column<T> column) {
return new AggregatedColumn<>(column, Function.AVG);
}
public static <T extends Number> AggregatedColumn<T> SUM(Column<T> column) {
return new AggregatedColumn<>(column, Function.SUM);
}
public static <T extends Number> AggregatedColumn<T> MAX(Column<T> column) {
return new AggregatedColumn<>(column, Function.MAX);
}
public static <T extends Number> AggregatedColumn<T> MIN(Column<T> column) {
return new AggregatedColumn<>(column, Function.MIN);
}
@Override
AggregatedColumn<T> forTable(String tableAlias) {
return new AggregatedColumn<>(super.forTable(tableAlias), function, alias, alias);
}
/**
* @return SQL keyword for select clause. For aggregated column,
* it is in the form of "column AS alias".
*/
@Override
String getSelectKeyword() {
return sqlKeyword + " AS " + alias;
}
/**
* @return column alias for select clause. For aggregated column,
* it is just the alias.
*/
@Override
String getSelectAlias() {
return alias;
}
@Override
public String getSqlKeyword() {
return sqlKeyword;
}
/**
* @return the sql expression that applies the function on the column.
* E.g. MAX(users.id)
*/
private static String createSqlKeyword(Column column, Function function) {
return String.format("%s(%s)", function.toString(), column.getSqlKeyword());
}
/**
* @return an alias that concatenate function and column name with underscore.
* E.g. MAX(users.id) => users_id_max
*/
private static String createAlias(Column column, Function function) {
return column.getSqlKeyword().replaceAll("\\.", "_") + "_" + function.name().toLowerCase();
}
}
| 29.181818 | 95 | 0.698598 |
9a46aa14bdfa01dce6634abe8e2ad97f8f03dbcd
| 2,180 |
package eu.inmite.android.gridwichterle.core;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.util.TypedValue;
/**
* Created with IntelliJ IDEA.
* User: Michal Matl (michal.matl@inmite.eu)
* Date: 7/20/13
* Time: 11:00 PM
*/
public class Utils {
public static int getStatusBarHeight(Context context) {
int result = 0;
int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = context.getResources().getDimensionPixelSize(resourceId);
}
return result;
}
public static int getPxFromDpi(Context context, int px) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) px, context.getResources().getDisplayMetrics());
}
/**
* Opens external browser, e.g. Chrome.
*/
public static void openBrowser(Context context, String url) {
context.startActivity(createOpenBrowserIntent(url));
}
/**
* Creates intent for opening browser.
*/
public static Intent createOpenBrowserIntent(String url) {
if (!url.startsWith("http")) {
url = "http://" + url;
}
return new Intent(Intent.ACTION_VIEW, Uri.parse(url));
}
/**
* Opens e-mail client, e.g. Gmail.
*/
public static void sendEmail(Context context, String recipient) {
sendEmail(context, new String[]{recipient}, null, null, null);
}
/**
* Opens e-mail client e.g. Gmail.
*/
public static void sendEmail(Context context, String[] recipients, String subject, String text, Uri stream) {
context.startActivity(createSendEmailIntent(recipients, subject, text, stream));
}
/**
* Creates intent for sending e-mail.
*/
public static Intent createSendEmailIntent(String[] recipients, String subject, String text, Uri stream) {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
if (recipients != null) {
i.putExtra(Intent.EXTRA_EMAIL, recipients);
}
i.putExtra(Intent.EXTRA_SUBJECT, subject);
if (!TextUtils.isEmpty(text)) {
i.putExtra(Intent.EXTRA_TEXT, text);
}
if (stream != null) {
i.putExtra(Intent.EXTRA_STREAM, stream);
}
return i;
}
}
| 26.91358 | 126 | 0.711009 |
ee5c282f95e64e8a5ac250261ca5725044b6ec01
| 2,142 |
package net.kyrptonaught.lemclienthelper.mixin.SmallInv;
import net.kyrptonaught.lemclienthelper.SmallInv.SmallInvInit;
import net.kyrptonaught.lemclienthelper.SmallInv.SmallInvPlayerInv;
import net.kyrptonaught.lemclienthelper.SmallInv.SmallInvScreen;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.screen.ingame.HandledScreen;
import net.minecraft.client.network.ClientPlayerEntity;
import org.jetbrains.annotations.Nullable;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.Slice;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(MinecraftClient.class)
public class MinecraftClientMixin {
@Shadow
@Nullable
public ClientPlayerEntity player;
@Redirect(method = "handleInputEvents",
at = @At(value = "INVOKE", target = "Lnet/minecraft/client/MinecraftClient;setScreen(Lnet/minecraft/client/gui/screen/Screen;)V"),
slice = @Slice(
from = @At(value = "INVOKE", target = "Lnet/minecraft/client/tutorial/TutorialManager;onInventoryOpened()V"),
to = @At(value = "INVOKE", target = "Lnet/minecraft/client/network/ClientPlayNetworkHandler;getAdvancementHandler()Lnet/minecraft/client/network/ClientAdvancementManager;")))
public void openSmallInv(MinecraftClient instance, Screen screen) {
instance.setScreen(SmallInvInit.isSmallInv(player) ? new SmallInvScreen(player) : screen);
}
@Inject(method = "setScreen", at = @At(value = "FIELD", target = "Lnet/minecraft/client/MinecraftClient;currentScreen:Lnet/minecraft/client/gui/screen/Screen;", ordinal = 2))
public void attemptOpenSmallInv(Screen screen, CallbackInfo ci) {
if (screen instanceof HandledScreen<?> handledScreen) {
((SmallInvPlayerInv) handledScreen).setIsSmall(SmallInvInit.isSmallInv(player));
}
}
}
| 52.243902 | 194 | 0.766106 |
aa8847b9388946c7a0d14250fd350122e982bea4
| 6,054 |
package com.xpl.qvod;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends AppCompatActivity {
private ProgressBar pb;
private SurfaceView sv;
private SeekBar seekBar1;
private SharedPreferences sp;
private MediaPlayer mediaPlayer;
private Timer timer;
private TimerTask task;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initView();
initData();
initEvent();
}
private void initEvent() {
seekBar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.seekTo(seekBar.getProgress());
}
}
});
sv.getHolder().addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
System.out.println("SurfaceView被创建了");
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource("http://vfx.mtime.cn/Video/2016/07/19/mp4/160719095812990469.mp4");
// 播放视频必须设置播放的容器,通过sv得到他的holder
mediaPlayer.setDisplay(sv.getHolder());
mediaPlayer.prepareAsync();// 异步的准备,开启子线程
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
//在播放过程中到达媒体源的末尾时调用
@Override
public void onCompletion(MediaPlayer mp) { //mp 到达文件末尾的MediaPlayer
SharedPreferences.Editor editor = sp.edit();
editor.putInt("position", 0);
editor.commit();
}
});
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
/**
*在媒体文件准备好播放时调用。
*
* @param mp 准备好播放的MediaPlayer
*/
@Override
public void onPrepared(MediaPlayer mp) {
pb.setVisibility(View.INVISIBLE);
mediaPlayer.start();
int position = sp.getInt("position", 0);
mediaPlayer.seekTo(position);
timer = new Timer();
task = new TimerTask() {
@Override
public void run() {
int max = mediaPlayer.getDuration();
int progress = mediaPlayer.getCurrentPosition();
seekBar1.setMax(max);
seekBar1.setProgress(progress);
}
};
timer.schedule(task, 0, 500);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
System.out.println("SurfaceView被销毁了");
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
int position = mediaPlayer.getCurrentPosition();
SharedPreferences.Editor editor = sp.edit();
editor.putInt("position", position); //记忆播放位置
editor.commit();
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
timer.cancel();
task.cancel();
timer = null;
task = null;
}
}
});
}
private void initData() {
sp = getSharedPreferences("config", MODE_PRIVATE);
}
private void initView() {
setContentView(R.layout.activity_main);
seekBar1 = (SeekBar) findViewById(R.id.seekBar1);
pb = (ProgressBar) findViewById(R.id.pb);
sv = (SurfaceView) findViewById(R.id.sv);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
System.out.println("----------------------------");
seekBar1.setVisibility(View.VISIBLE);
new Thread(){
@Override
public void run() {
// 3秒隐藏进度条
SystemClock.sleep(3000);
runOnUiThread(new Runnable() {
@Override
public void run() {
seekBar1.setVisibility(View.INVISIBLE);
}
});
}
}.start();
}
return super.onTouchEvent(event);
}
}
| 36.46988 | 113 | 0.498513 |
3398da6f5f18e5512ebf6a74e0d545046f0052f3
| 6,570 |
package gov.nasa.arc.irg.astrobee.wifisetup;
import android.net.wifi.WifiConfiguration;
import android.util.Log;
import org.json.*;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public class ConfigLoader {
private static final String TAG = "SetupService";
public static List<WifiConfiguration> loadConfigs(final File f) throws IOException {
if (!f.exists()) {
throw new FileNotFoundException("No such file");
}
CharBuffer cb = CharBuffer.allocate((int) f.length());
InputStreamReader isr = new InputStreamReader(
new BufferedInputStream(
new FileInputStream(f)), StandardCharsets.UTF_8);
isr.read(cb);
isr.close();
if (!f.delete())
Log.w(TAG, "Unable to delete file");
cb.rewind();
return loadConfigs(cb.toString());
}
public static List<WifiConfiguration> loadConfigs(final String s) {
final List<WifiConfiguration> list = new LinkedList<>();
final JSONTokener t = new JSONTokener(s);
try {
while (t.more()) {
Object v = t.nextValue();
if (v instanceof JSONObject) {
list.add(loadConfig((JSONObject) v));
} else if (v instanceof JSONArray) {
final JSONArray a = (JSONArray) v;
for (int i = 0; i < a.length(); i++) {
final JSONObject o = a.getJSONObject(i);
list.add(loadConfig(o));
}
}
}
} catch (JSONException e) {
// Ignore "End of Input" exceptions
if (t.more())
throw new RuntimeException("Malformed JSON given", e);
}
return list;
}
private static final String CCMP = "CCMP";
private static final String TKIP = "TKIP";
private static final String WPA = "WPA";
private static final String RSN = "RSN";
private static final String WPA2 = "WPA2";
private static final String DHCP = "DHCP";
public static WifiConfiguration loadConfig(final JSONObject o) {
final WifiConfiguration config = new WifiConfiguration();
try {
config.SSID = o.getString("ssid");
config.hiddenSSID = o.optBoolean("hidden", false);
config.preSharedKey = o.optString("psk", null);
Object netObj = o.opt("network");
if (netObj == null ||
(netObj instanceof String && ((String) netObj).equalsIgnoreCase(DHCP))) {
ProxyIpConfiguration ipConfig = new ProxyIpConfiguration();
ipConfig.setIpAssignment(ProxyIpConfiguration.IpAssignment.DHCP);
ProxyWifiConfiguration proxyConfig = new ProxyWifiConfiguration(config);
proxyConfig.setIpConfiguration(ipConfig);
} else if (netObj instanceof JSONObject) {
ProxyIpConfiguration ipConfig = parseNetwork((JSONObject) netObj);
ProxyWifiConfiguration proxyConfig = new ProxyWifiConfiguration(config);
proxyConfig.setIpConfiguration(ipConfig);
} else {
throw new RuntimeException("Invalid network config specified");
}
Object protocolObj = o.opt("protocol");
if (protocolObj instanceof String) {
parseProtocols(config.allowedProtocols,
Collections.singletonList((String) protocolObj));
} else if (protocolObj instanceof JSONArray) {
final JSONArray a = (JSONArray) protocolObj;
final ArrayList<String> strings = new ArrayList<>(a.length());
for (int i = 0; i < a.length(); i++) {
strings.add(a.getString(i));
}
parseProtocols(config.allowedProtocols, strings);
}
} catch (JSONException e) {
throw new RuntimeException("Invalid WiFi config", e);
} catch (ReflectiveOperationException e) {
throw new RuntimeException("Unable to setup a proper config", e);
}
return config;
}
private static void parseProtocols(final BitSet protocols, final List<String> strings) {
final String[] protocolStrings = WifiConfiguration.Protocol.strings;
for (final String s : strings) {
for (int i = 0; i < protocolStrings.length; i++) {
if (protocolStrings[i].equalsIgnoreCase(s)) {
protocols.set(i, true);
}
}
}
}
private static ProxyIpConfiguration parseNetwork(final JSONObject o)
throws JSONException, ReflectiveOperationException
{
final ProxyStaticIpConfiguration sip = new ProxyStaticIpConfiguration();
try {
int prefix = o.getInt("prefix");
if (prefix < 0 || prefix > 32)
throw new RuntimeException("Invalid prefix");
sip.setIpAddress(InetAddress.getByName(o.getString("ip")), o.getInt("prefix"));
sip.setGateway(InetAddress.getByName(o.optString("gateway", "0.0.0.0")));
final Object dns = o.opt("dns");
if (dns instanceof String) {
sip.setDnsServers(Arrays.asList(InetAddress.getByName((String) dns)));
} else if (dns instanceof JSONArray) {
final JSONArray servers = (JSONArray) dns;
ArrayList<InetAddress> addrs = new ArrayList<>(servers.length());
for (int i = 0; i < servers.length(); i++) {
addrs.add(InetAddress.getByName(servers.getString(i)));
}
sip.setDnsServers(addrs);
}
} catch (UnknownHostException e) {
throw new RuntimeException("Invalid ip, gateway or dns server", e);
}
final ProxyIpConfiguration config = new ProxyIpConfiguration();
config.setIpAssignment(ProxyIpConfiguration.IpAssignment.STATIC);
config.setStaticIpConfiguration(sip);
return config;
}
}
| 37.758621 | 93 | 0.596347 |
011411d7318b9411d17681d6ba17c2d390283a62
| 551 |
package com.template.def.desktop;
import com.template.def.core.GameAdapter;
import com.tokelon.toktales.core.engine.EngineException;
import com.tokelon.toktales.core.game.IGameAdapter;
import com.tokelon.toktales.desktop.application.TokTalesApplication;
public class Application extends TokTalesApplication {
@Override
public Class<? extends IGameAdapter> makeDefaultGameAdapter() {
return GameAdapter.class;
}
public static void main(String[] args) throws EngineException {
new Application().run(args);
}
}
| 25.045455 | 68 | 0.760436 |
8aaa474f34920262f7bd82157753b8ef043614fa
| 2,252 |
package com.chendu.jq.core.equity.calculator.analytical;
import com.chendu.jq.core.JqTrade;
import com.chendu.jq.core.common.jqEnum.OptionDirection;
import com.chendu.jq.core.equity.DigitalOption;
import com.chendu.jq.core.equity.calculator.OptionCalculator;
import com.chendu.jq.core.market.JqMarket;
import java.time.LocalDate;
public class EuropeanDigitalCalculator extends OptionCalculator {
@Override
public Double calcPv(JqTrade trade, JqMarket jqMarket) {
DigitalOption digitalOption = (DigitalOption) trade;
LocalDate exerciseDate = digitalOption.getExerciseDate();
LocalDate maturityDate = digitalOption.getMaturityDate();
Double exerciseTime = digitalOption.getDayCount().yearFraction(jqMarket.getMktDate(), exerciseDate);
Double maturityTime = digitalOption.getDayCount().yearFraction(jqMarket.getMktDate(), maturityDate);
Double dfAtExercise = jqMarket.jqCurve(digitalOption.getDomCurrency()).getDf(exerciseTime);
Double dividendDfAtExercise = jqMarket.getDividendCurveMap().get(digitalOption.getUnderlyingTicker()).getDf(exerciseTime);
Double dfAtMaturity = jqMarket.jqCurve(digitalOption.getDomCurrency()).getDf(maturityTime);
Double dfExercise2Maturity = dfAtMaturity / dfAtExercise;
Double vol = jqMarket.tickerVol(digitalOption.getUnderlyingTicker());
Double s0 = jqMarket.tickerPrice(digitalOption.getUnderlyingTicker());
Double f = s0 * dividendDfAtExercise / dfAtExercise;
Double notional = digitalOption.getNotional();
Double strike = digitalOption.getStrike();
Double d1 = (Math.log(f / strike) + vol * vol / 2.0 * exerciseTime) / (vol * Math.sqrt(exerciseTime));
Double d2 = d1 - vol * Math.sqrt(exerciseTime);
Double nd1 = normal.cumulativeProbability(d1);
Double nd2 = normal.cumulativeProbability(d2);
OptionDirection optionDirection = digitalOption.getOptionDirection();
return optionDirection == OptionDirection.Call
? notional * dfExercise2Maturity * dfAtExercise * (nd2 * digitalOption.getDigitalPayoff())
: notional * dfExercise2Maturity * dfAtExercise * (1 - nd2) * digitalOption.getDigitalPayoff();
}
}
| 47.914894 | 130 | 0.734458 |
fc3679e39959f000950b5c444528b58a6324ccb2
| 462 |
/*
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/**
* Abstraction we use in order to allocate memory for bitmaps in different OS versions. It also
* contains implementation of the Releaser which is responsible to close the specific
* CloseableReference when not used anymore.
*/
package com.facebook.imagepipeline.bitmaps;
| 33 | 95 | 0.757576 |
deb6abfc6697c4c15362b0c643cdbaca0438d170
| 1,265 |
package io.mercury.common.concurrent.disruptor.dynamic.strategy;
import io.mercury.common.concurrent.disruptor.dynamic.DynamicDisruptor;
import io.mercury.common.concurrent.disruptor.dynamic.sentinel.SentinelEvent;
/**
* @Author : Rookiex
* @Date : Created in 2019/11/12 13:33
* @Describe :
* @version: 1.0
*/
public class IntegralStrategy implements RegulateStrategy {
@Override
public void regulate(DynamicDisruptor dynamicDisruptor, SentinelEvent sentinelEvent) {
RegulateStrategy.updateThreadCount(dynamicDisruptor, getNeedUpdateCount(sentinelEvent));
}
@Override
public int getNeedUpdateCount(SentinelEvent sentinelEvent) {
int updateCount = 0;
int totalDifference = sentinelEvent.getTotalDifference();
int recentConsumeCount = sentinelEvent.getRecentConsumeCount();
int runThreadCount = sentinelEvent.getRunThreadCount();
int totalThreadCount = sentinelEvent.getTotalThreadCount();
if (totalThreadCount == runThreadCount) {
if (totalDifference > recentConsumeCount) {
// 保留两位小数
int needAddThread = (totalDifference * 100 / recentConsumeCount * runThreadCount) / 100
- runThreadCount;
updateCount += needAddThread;
} else if (totalDifference > 0) {
updateCount += 1;
}
}
return updateCount;
}
}
| 31.625 | 91 | 0.765217 |
54d027824e9a34cf588df1bbebbe839f4711ad85
| 1,341 |
/*
* Copyright 2020 Wuyi Chen.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ftgo.kitchenservice.api.model;
import org.apache.commons.lang.builder.ToStringBuilder;
import java.util.List;
/**
* The ticket detailed information.
*
* @author Wuyi Chen
* @date 05/14/2019
* @version 1.0
* @since 1.0
*/
public class TicketDetails {
private List<TicketLineItem> lineItems;
public TicketDetails() {}
public TicketDetails(List<TicketLineItem> lineItems) {
this.lineItems = lineItems;
}
public List<TicketLineItem> getLineItems() { return lineItems; }
public void setLineItems(List<TicketLineItem> lineItems) { this.lineItems = lineItems; }
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
| 28.531915 | 105 | 0.706189 |
2cbd2724ebf6ecbc9eb62977d1bee2e654f6189f
| 2,330 |
package com.sx.frontend.protocal376_1.internal.fieldType;
import com.sx.frontend.protocal376_1.exception.InvalidConfigException;
import com.sx.frontend.protocal376_1.internal.ConfigParse.FieldTypeParam;
import java.nio.ByteBuffer;
/**
* Created by PETER on 2015/3/12.
*/
public class BcdUnsignedByBit implements IFieldType {
/**
* 默认一个字节
*/
private static final int BITS_PER_UNIT=8;
/**
* 剩余的位数
*/
private int _avail=BITS_PER_UNIT;
/**
* 缓存
*/
private byte buffer;
private static final int[] bmask=new int[]{
0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f,0xff
};
@Override
public byte[] encode(Object value, FieldTypeParam fieldTypeParam) throws Exception {
int length=fieldTypeParam.getLength();
if(length==0){
length=BITS_PER_UNIT;
}
if(length>_avail){
throw new InvalidConfigException(111,"配置文件错误,BcdUnsignedByBit长度超过8");
}
buffer=(byte)(buffer+(intToBcd(Integer.parseInt(value.toString()))<<(BITS_PER_UNIT-_avail)));
if(length<_avail){
_avail=_avail-length;
return new byte[0];
}else{
_avail=BITS_PER_UNIT;
byte result=buffer;
buffer=0;
return new byte[]{result};
}
}
@Override
public Integer decode(ByteBuffer byteBuffer, FieldTypeParam fieldTypeParam) throws Exception {
int length=fieldTypeParam.getLength();
if(length==0){
length=BITS_PER_UNIT;
}
if(length>_avail){
throw new InvalidConfigException(1111,"BcdUnsignedByBit,Unsigned8长度超过8");
}
if(_avail==BITS_PER_UNIT){
buffer=byteBuffer.get();
}
int result=buffer&bmask[length];
result=bcdToInt(result);
if(length<_avail){
buffer>>=length;
_avail-=length;
}else{
buffer=0;
_avail=BITS_PER_UNIT;
}
return result;
}
private int bcdToInt(int bcdValue){
return (0x0f & bcdValue)+(0x0f & bcdValue>>4)*10;
}
private int intToBcd(int intValue){
return (intValue/10)*16 + intValue%10;
}
@Override
public void reset() {
buffer=0;
_avail=BITS_PER_UNIT;
}
}
| 26.781609 | 101 | 0.596137 |
59e3c468419faa532acef019a67ac31eb5dc79f7
| 2,069 |
package edu.virginia.vcgr.genii.client.invoke.handlers;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import javax.xml.namespace.QName;
import org.apache.axis.message.MessageElement;
import org.oasis_open.docs.wsrf.rp_2.GetMultipleResourcePropertiesResponse;
import org.oasis_open.docs.wsrf.rp_2.GetResourcePropertyDocumentResponse;
import org.oasis_open.docs.wsrf.rp_2.GetResourcePropertyResponse;
import edu.virginia.vcgr.genii.client.comm.axis.Elementals;
public class CachedAttributeData
{
private HashMap<QName, Collection<MessageElement>> _attrs = new HashMap<QName, Collection<MessageElement>>();
private MessageElement[] _all;
private boolean _isFull;
private CachedAttributeData(MessageElement[] elements, boolean isFull)
{
_isFull = isFull;
_all = elements;
if (elements != null) {
for (MessageElement element : elements) {
QName attrName = element.getQName();
Collection<MessageElement> col = _attrs.get(attrName);
if (col == null)
_attrs.put(attrName, col = new ArrayList<MessageElement>());
col.add(element);
}
}
}
public CachedAttributeData(GetResourcePropertyResponse resp)
{
this(resp.get_any(), false);
}
public CachedAttributeData(GetMultipleResourcePropertiesResponse resp)
{
this(resp.get_any(), false);
}
public CachedAttributeData(GetResourcePropertyDocumentResponse resp)
{
this(resp.get_any(), true);
}
public void flush(QName[] attributes)
{
for (QName name : attributes) {
_attrs.remove(name);
}
_isFull = false;
}
public CachedAttributeData(MessageElement uberDoc)
{
this(Elementals.getOurChildren(uberDoc));
}
public CachedAttributeData(Collection<MessageElement> attrs)
{
this(attrs.toArray(new MessageElement[0]), false);
}
public CachedAttributeData(MessageElement[] any)
{
this(any, false);
}
public boolean isFull()
{
return _isFull;
}
public MessageElement[] getAll()
{
return _all;
}
public Collection<MessageElement> getAttributes(QName attrName)
{
return _attrs.get(attrName);
}
}
| 22.988889 | 110 | 0.754471 |
0f714795c0aaf9bf3e035a6a7aa6c6284c504355
| 1,007 |
// @@author chrischenhui
package seedu.address.logic.parser.open;
import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import seedu.address.logic.commands.cardcommands.ListCommand;
import seedu.address.logic.parser.Parser;
import seedu.address.logic.parser.exceptions.ParseException;
/**
* Parses input arguments and creates a new ClearCommand object.
*/
public class ListCommandParser implements Parser<ListCommand> {
/**
* Parses the given {@code String} of arguments in the context of the ListCommand
* and returns a ListCommand object for execution.
*
* @throws ParseException if the user input does not conform the expected format
*/
public ListCommand parse(String args) throws ParseException {
if (!args.isEmpty()) {
throw new ParseException(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, ListCommand.MESSAGE_USAGE));
} else {
return new ListCommand();
}
}
}
| 32.483871 | 94 | 0.714002 |
1697d78b82159f34b38d7ffe54750b7ab7d2c396
| 743 |
package org.egov.pt.web.contracts;
import java.util.List;
import org.egov.common.contract.response.ResponseInfo;
import org.egov.pt.models.Assessment;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
/**
* The response of create or update of assessment. Contains the ResponseHeader and created/updated assessment
*/
@ToString
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class AssessmentResponse {
@JsonProperty("ResponseInfo")
private ResponseInfo responseInfo;
@JsonProperty("Assessments")
private List<Assessment> assessments;
}
| 20.638889 | 109 | 0.803499 |
a0971664face912f72af2df304be9edc567d28f8
| 14,424 |
package org.pzdcdoc;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.FileWriterWithEncoding;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.asciidoctor.Asciidoctor;
import org.asciidoctor.Asciidoctor.Factory;
import org.asciidoctor.Attributes;
import org.asciidoctor.Options;
import org.asciidoctor.SafeMode;
import org.asciidoctor.extension.JavaExtensionRegistry;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;
import org.pzdcdoc.processor.DrawIO;
import org.pzdcdoc.processor.JavaDocLink;
import org.pzdcdoc.processor.snippet.Snippet;
/**
* The main runnable class, converting AsciiDoc sources to HTML.
*
* @author Shamil Vakhitov
*/
public class Generator {
private static final Logger log = LogManager.getLogger();
private static final String DIR_RES = "_res";
private static final String EXT_ADOC = ".adoc";
private static final String EXT_ADOCF = ".adocf";
private static final String EXT_HTML = ".html";
public static final String ATTR_GENERATOR = "generator";
public static final String ATTR_TARGET = "target";
public static final String ATTR_SOURCE = "source";
private final Asciidoctor asciidoctor = Factory.create();
private static final String[] SCRIPTS = { "jquery-3.3.1.js", "pzdcdoc.js",
// https://lunrjs.com/guides/language_support.html
"lunr-2.3.6.js", "lunr.stemmer.support.js", "lunr.multi.js", "lunr.ru.js", "lunr.de.js"
};
private static final String[] SCRIPTS_INJECT = ArrayUtils.add(SCRIPTS, Search.SCRIPT);
private static final String ASCIIDOCTOR_DEFAULT_CSS = "asciidoctor.css";
private static final String PZDCDOC_CSS = "pzdcdoc.css";
private static final String FONT_CSS = "font.css";
private static final String[] STYLESHEETS = { ASCIIDOCTOR_DEFAULT_CSS, PZDCDOC_CSS, FONT_CSS, "coderay-asciidoctor.css" };
private static final String[] STYLESHEETS_INJECT = { PZDCDOC_CSS, FONT_CSS };
@Option(required = true, name = "-i", aliases = { "--in" }, usage = "Source directory path")
private File sourceDir;
@Option(required = true, name = "-o", aliases = { "--out" }, usage = "Target directory path")
private File targetDir;
/** Cached ToC from index.adoc for injecting everywhere. */
private Element toc;
/** Search supporting object. */
private final Search search = new Search();
/** Processing errors counter. */
private int errors;
private Generator() throws Exception {
// https://github.com/asciidoctor/asciidoctorj/blob/v2.1.0/docs/integrator-guide.adoc
JavaExtensionRegistry javaExtensionRegistry = asciidoctor.javaExtensionRegistry();
javaExtensionRegistry.inlineMacro(new JavaDocLink());
javaExtensionRegistry.inlineMacro(new DrawIO());
javaExtensionRegistry.block(new Snippet());
//javaExtensionRegistry.treeprocessor(new Treeprocessor());
asciidoctor.requireLibrary("asciidoctor-diagram");
}
/**
* Increments error's counter.
*/
public void error() {
errors++;
}
private int process() throws Exception {
if (!sourceDir.isDirectory())
throw new IllegalArgumentException("Incorrect source directory: " + sourceDir);
process(sourceDir, targetDir, -1, new HashMap<>());
copyScriptsAndStyles();
deleteTmpFiles();
if (errors > 0)
log.error("PROC ERRORS => " + errors);
return errors;
}
private int check() throws Exception {
int errors = new Links().checkDir(targetDir);
if (errors > 0)
log.error("CHECK ERRORS => " + errors);
return errors;
}
private void process(File source, File target, int depth, Map<String, Object> attributes) throws Exception {
final String sourceName = source.getName();
// hidden resources, names started by .
if (sourceName.startsWith(".")) {
log.debug("Skipping hidden: {}", source);
return;
}
// include - skipping
if (sourceName.endsWith(EXT_ADOCF)) {
log.debug("Skipping include: {}", source);
return;
}
if (source.isDirectory()) {
File[] files = source.listFiles();
// index.adoc in the root folder must be processed first to be included in all files after
Arrays.sort(files, (f1, f2) -> {
if (containsIndex(f1.getName()))
return -1;
if (containsIndex(f2.getName()))
return 1;
return 0;
});
attributes = loadAttributes(source, attributes);
for (File file : files)
process(file, new File(target.getPath() + "/" + file.getName()), depth + 1, attributes);
} else {
if (sourceName.endsWith(EXT_ADOC)) {
log.info("Processing: " + source);
Path targetPath = Paths.get(target.getPath().replace(EXT_ADOC, EXT_HTML));
var attrs = Attributes.builder()
.backend("html5")
.stylesDir(StringUtils.repeat("../", depth) + DIR_RES)
.styleSheetName(ASCIIDOCTOR_DEFAULT_CSS)
.linkCss(true)
.sourceHighlighter("coderay")
.icons(Attributes.FONT_ICONS)
.tableOfContents(true)
.setAnchors(true)
.linkAttrs(true)
.build();
attrs.setAttribute("last-update-label", "Powered by <a target='_blank' href='https://pzdcdoc.org'>PzdcDoc</a> at: ");
attrs.setAttribute(ATTR_SOURCE, source);
attrs.setAttribute(ATTR_TARGET, targetPath);
attrs.setAttribute(ATTR_GENERATOR, this);
attrs.setAttributes(attributes);
var options = Options.builder()
.toFile(false)
.headerFooter(true)
.safe(SafeMode.UNSAFE)
.attributes(attrs)
.build();
String html = asciidoctor.convertFile(source, options);
html = correctHtmlAndCopyResources(source.toPath(), html, targetPath, depth, new SourceLink(attributes));
FileUtils.forceMkdirParent(target);
try (var writer = new FileWriterWithEncoding(targetPath.toFile(), StandardCharsets.UTF_8)) {
writer.write(html);
}
return;
}
}
}
private Map<String, Object> loadAttributes(File source, Map<String, Object> attributes) throws DocumentException {
Path configuration = source.toPath().resolve("pzdcdoc.xml");
if (configuration.toFile().exists()) {
log.info("Processing configuration: {}", configuration);
org.dom4j.Document document = new SAXReader().read(configuration.toFile());
attributes = new HashMap<>(attributes);
for (Node attr : document.selectNodes("//attributes/*"))
attributes.put(attr.getName(), attr.getText());
log.info("Read {} attributes", attributes.size());
}
return attributes;
}
private void copyScriptsAndStyles() throws IOException {
log.info("Copying scripts and styles.");
File rootRes = new File(targetDir + "/" + DIR_RES);
if (!rootRes.exists()) rootRes.mkdirs();
for (String script : SCRIPTS)
IOUtils.copy(getClass().getClassLoader().getResourceAsStream("scripts/" + script),
new FileOutputStream(rootRes.getAbsolutePath() + "/" + script));
search.writeScript(rootRes);
for (String style : STYLESHEETS)
IOUtils.copy(getClass().getClassLoader().getResourceAsStream("stylesheets/" + style),
new FileOutputStream(rootRes.getAbsolutePath() + "/" + style));
}
private void deleteTmpFiles() throws IOException {
log.info("Deleting temporary directories.");
Files
.walk(sourceDir.toPath())
.filter(f -> f.toFile().isDirectory() && f.getFileName().startsWith(".asciidoctor"))
.forEach(f -> {
try {
log.info(f);
FileUtils.deleteDirectory(f.toFile());
} catch (Exception e) {
log.error(e.getMessage(), e);
}
});
}
private boolean containsIndex(String name) {
return name.contains("index");
}
private String correctHtmlAndCopyResources(Path source, String html, Path target, int depth, SourceLink linkToSource) throws Exception {
log.debug("correctHtml targetPath: {}, deep: {}", target, depth);
if (toc == null) {
// the index file must be placed on the top the root directory
if (containsIndex(target.toString())) {
toc = Jsoup.parse(html, StandardCharsets.UTF_8.name());
toc = toc.select("body").tagName("div").get(0);
// add search field
search.injectField(toc.select("#header"));
}
return html;
}
Document jsoup = Jsoup.parse(html);
Element head = jsoup.selectFirst("head");
// add content to search index
if (search != null) {
final String relativePath = targetDir.toPath().relativize(target).toString();
search.addArticle(new Search.Article(relativePath, head.select("title").text(), jsoup.text()));
}
copyResources(jsoup, source, target);
injectScriptsAndStyles(depth, head);
correctToC(jsoup, target, depth);
linkToSource.inject(jsoup, sourceDir.toPath().relativize(source).toString());
return jsoup.toString();
}
private void injectScriptsAndStyles(int depth, Element head) {
var pathPrefix = StringUtils.repeat("../", depth) + DIR_RES + "/";
for (String script : SCRIPTS_INJECT)
head.append("<script src='" + pathPrefix + script + "'/>");
for (String css : STYLESHEETS_INJECT)
head.append("<link rel='stylesheet' href='" + pathPrefix + css + "'>");
}
private void correctToC(Document jsoup, Path target, int depth) {
// find of the top ToC
Element pageToC = jsoup.selectFirst("#toc.toc");
if (pageToC != null) {
Element ul = pageToC.selectFirst(".sectlevel1").clone();
// remove doesn't work properly
pageToC.html("");
pageToC = ul;
}
// inject left ToC
jsoup.selectFirst("body").addClass("toc2");
jsoup.select("#toc").before("<div id=\"toc\" class=\"toc2\">" + toc.toString() + "</div>");
for (Element a : jsoup.select("#toc.toc2 a")) {
Link link = new Link(a);
if (link.isExternalReference())
continue;
String href = link.get();
if (target.endsWith(href)) {
a.addClass("current");
if (pageToC != null)
a.after(pageToC);
}
link.set(StringUtils.repeat("../", depth) + href);
a.attr("title", a.text());
}
// add link to root on title
Element title = jsoup.selectFirst("#toc #header h1");
if (title != null) {
title.html("<a href='" + StringUtils.repeat("../", depth) + "index.html'>" + title.text() + "</a>");
}
}
private void copyResources(Document jsoup, Path source, Path target) throws IOException {
for (Link link : Links.getLinks(jsoup)) {
String href = link.get();
href = StringUtils.substringBefore(href, "#");
if (href.endsWith(EXT_HTML))
continue;
File resSrc = source.getParent().resolve(href).toFile();
if (!resSrc.exists() || resSrc.isDirectory()) {
log.debug("Skipping: {}", resSrc);
continue;
}
// Ditaa generated images
if (href.startsWith("diag")) {
File resTarget = target.getParent().resolve(href).toFile();
log.info("Moving {} to {}", resSrc, resTarget);
// without the deletion moving after fails in case of existing file
FileUtils.deleteQuietly(resTarget);
FileUtils.moveFile(resSrc, resTarget);
} else {
String relativePath = DIR_RES + "/" + Paths.get(href).getFileName();
link.set(relativePath);
File resTarget = target.getParent().resolve(relativePath).toFile();
log.info("Copying {} to {}", resSrc, resTarget);
FileUtils.forceMkdirParent(resTarget);
if (resTarget.exists() && resTarget.lastModified() == resSrc.lastModified())
log.info("Not changed.");
else
FileUtils.copyFile(resSrc, resTarget);
}
}
}
public static void main(String[] args) throws Exception {
var gen = new Generator();
var parser = new CmdLineParser(gen);
try {
parser.parseArgument(args);
} catch (CmdLineException e) {
System.err.println(e.getMessage());
parser.printUsage(System.err);
System.exit(1);
}
int errors = gen.process();
errors += gen.check();
log.info("DONE!");
if (errors > 0) {
log.error("ERRORS => " + errors);
System.exit(errors);
}
}
}
| 37.079692 | 140 | 0.59096 |
4b7ae45d846f514d2c7463da8b9eb47f1ee41ff1
| 1,621 |
/*
* 11/07/2004
*
* AbstractTokenMaker.java - An abstract implementation of TokenMaker.
*
* This library is distributed under a modified BSD license. See the included
* LICENSE file for details.
*/
package org.fife.ui.rsyntaxtextarea;
/**
* An abstract implementation of the
* {@link org.fife.ui.rsyntaxtextarea.TokenMaker} interface. It should
* be overridden for every language for which you want to provide
* syntax highlighting.<p>
*
* @see Token
*
* @author Robert Futrell
* @version 0.2
*/
public abstract class AbstractTokenMaker extends TokenMakerBase {
/**
* Hash table of words to highlight and what token type they are.
* The keys are the words to highlight, and their values are the
* token types, for example, <code>Token.RESERVED_WORD</code> or
* <code>Token.FUNCTION</code>.
*/
protected TokenMap wordsToHighlight;
/**
* Constructor.
*/
public AbstractTokenMaker() {
wordsToHighlight = getWordsToHighlight();
}
/**
* Returns the words to highlight for this programming language.
*
* @return A <code>TokenMap</code> containing the words to highlight for
* this programming language.
*/
public abstract TokenMap getWordsToHighlight();
/**
* Removes the token last added from the linked list of tokens. The
* programmer should never have to call this directly; it can be called
* by subclasses of <code>TokenMaker</code> if necessary.
*/
public void removeLastToken() {
if (previousToken==null) {
firstToken = currentToken = null;
}
else {
currentToken = previousToken;
currentToken.setNextToken(null);
}
}
}
| 23.838235 | 78 | 0.708822 |
18b09fecb1ac1ae78082b6586e99ae223964a38f
| 159 |
package evaluator.ast;
public enum Operators {
ADD1, SUB1, ISZERO, // ASTOp1
PLUS, MINUS, MULTIPLY, EXPONENTIATE // ASTOp2
}
| 19.875 | 53 | 0.584906 |
62fbb960b0d70a8db6b277f94b8f22a711b1f0ab
| 4,838 |
/*
* Copyright 2017 Apereo
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tle.core.item.operations;
import com.dytech.devlib.PropBagEx;
import com.google.common.collect.Sets;
import com.tle.annotation.NonNullByDefault;
import com.tle.annotation.Nullable;
import com.tle.beans.entity.Schema;
import com.tle.beans.entity.itemdef.ItemDefinition;
import com.tle.beans.item.Item;
import com.tle.beans.item.ItemId;
import com.tle.beans.item.ItemKey;
import com.tle.beans.item.ItemPack;
import com.tle.beans.item.ItemStatus;
import com.tle.beans.item.attachments.Attachments;
import com.tle.beans.item.attachments.UnmodifiableAttachments;
import com.tle.common.Check;
import com.tle.common.filesystem.handle.StagingFile;
import com.tle.common.usermanagement.user.CurrentUser;
import com.tle.core.collection.service.ItemDefinitionService;
import com.tle.core.events.ApplicationEvent;
import com.tle.core.item.service.ItemFileService;
import com.tle.core.item.service.ItemService;
import com.tle.core.services.FileSystemService;
import java.util.Collection;
import java.util.Date;
import java.util.Set;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
/** @author Aaron */
@NonNullByDefault
public abstract class AbstractWorkflowOperation implements WorkflowOperation {
@Inject protected ItemDefinitionService itemdefService;
@Inject protected ItemService itemService;
@Inject protected FileSystemService fileSystemService;
@Inject protected ItemFileService itemFileService;
protected ItemOperationParams params;
private boolean injected;
@Override
public void setParams(ItemOperationParams params) {
this.params = params;
}
@Nullable
@Override
public Item getItem() {
final ItemPack<Item> pack = params.getItemPack();
if (pack != null) {
return pack.getItem();
}
return null;
}
@Nullable
@Override
public ItemPack<Item> getItemPack() {
return params.getItemPack();
}
@Override
public boolean isReadOnly() {
return true;
}
@Override
public boolean failedToAutowire() {
return !injected;
}
@Override
public boolean isDeleteLike() {
return false;
}
protected String getUuid() {
return getItem().getUuid();
}
protected int getVersion() {
return getItem().getVersion();
}
protected ItemStatus getItemStatus() {
return getItem().getStatus();
}
protected ItemDefinition getCollection() {
return getItem().getItemDefinition();
}
protected Schema getSchema() {
return getCollection().getSchema();
}
protected String getItemOwnerId() {
return getItem().getOwner();
}
protected Collection<String> getAllOwnerIds() {
Set<String> owners = Sets.newHashSet();
owners.add(getItemOwnerId());
owners.addAll(getItem().getCollaborators());
return owners;
}
public Attachments getAttachments() {
return new UnmodifiableAttachments(getItem());
}
protected boolean isOwner(String userid) {
return getItem().getOwner().equals(userid);
}
protected void setOwner(String userid) {
getItem().setOwner(userid);
}
protected String getUserId() {
return CurrentUser.getUserID();
}
protected ItemKey getItemKey() {
return params.getItemKey();
}
protected void setStopImmediately(boolean stop) {
params.setStopImmediately(stop);
}
@Nullable
protected StagingFile getStaging() {
ItemPack<Item> itemPack = getItemPack();
if (itemPack != null) {
String s = itemPack.getStagingID();
if (!Check.isEmpty(s)) {
return new StagingFile(s);
}
}
return null;
}
protected Date getDateModified() {
Item item = getItem();
if (item == null || item.getDateModified() == null) {
return params.getDateNow();
}
return item.getDateModified();
}
protected void setVersion(int version) {
getItem().setVersion(version);
}
protected void addAfterCommitEvent(ApplicationEvent<?> event) {
params.getAfterCommitEvents().add(event);
}
protected ItemId getItemId() {
return getItem().getItemId();
}
protected PropBagEx getItemXml() {
return getItemPack().getXml();
}
protected ItemOperationParams getParams() {
return params;
}
@PostConstruct
protected void injected() {
this.injected = true;
}
}
| 24.938144 | 78 | 0.721786 |
ff00db758110335894eec89fd80ae13f2a878db5
| 9,574 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2017 Fabian Mastenbroek, Christian Slothouber,
* Laetitia Molkenboer, Nikki Bouman, Nils de Beukelaar
*
* 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 nl.tudelft.fa.frontend.javafx.controller.lobby;
import akka.actor.AbstractActor;
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import akka.japi.pf.ReceiveBuilder;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import nl.tudelft.fa.client.lobby.Lobby;
import nl.tudelft.fa.client.lobby.LobbyStatus;
import nl.tudelft.fa.client.lobby.message.*;
import nl.tudelft.fa.client.team.Team;
import nl.tudelft.fa.frontend.javafx.Main;
import nl.tudelft.fa.frontend.javafx.controller.AbstractController;
import nl.tudelft.fa.frontend.javafx.service.ClientService;
import nl.tudelft.fa.frontend.javafx.service.TeamService;
import scala.PartialFunction;
import scala.concurrent.duration.FiniteDuration;
import scala.runtime.BoxedUnit;
import java.net.URL;
import java.time.Duration;
import java.util.ResourceBundle;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
/**
* A controller for the home lobby view.
*
* @author Fabian Mastenbroek
* @author Christian Slothouber
* @author Laetitia Molkenboer
*/
public class LobbyHomeController extends AbstractController {
/**
* The reference to the location of the view of this controller.
*/
public static final URL VIEW = Main.class.getResource("view/lobby/home.fxml");
/**
* The injected client service.
*/
@Inject
private ClientService client;
/**
* The injected team service.
*/
@Inject
private TeamService teamService;
/**
* The chat list view.
*/
@FXML
private ListView<ChatEvent> chat;
/**
* The text field containing the chat message.
*/
@FXML
private TextField input;
/**
* The label that contains the remaining time.
*/
@FXML
private Label remaining;
/**
* This method is called when the screen is loaded.
*/
@Override
public void initialize(URL location, ResourceBundle resources) {
super.initialize(location, resources);
// Create a handler for the server events
ActorRef ref = client.system().actorOf(Props.create(LobbyHomeActor.class,
LobbyHomeActor::new).withDispatcher("javafx-dispatcher"));
// Tell the session about the handler
client.session().tell(ref, ref);
// Ask for the current lobby information
client.session().tell(RequestInformation.INSTANCE, ref);
// Welcome the user
sentMessage(ref, "Welcome in this lobby!");
// Cell factory of the chat list
chat.setCellFactory(view -> new ListCell<ChatEvent>() {
@Override
protected void updateItem(ChatEvent event, boolean empty) {
if (empty) {
setGraphic(null);
} else {
setGraphic(toNode(event));
}
}
});
}
/**
* Handle the given chat event.
*
* @param event The chat event to handle.
*/
@FXML
private void chat(KeyEvent event) {
String message = input.getText();
if (event.getCode().equals(KeyCode.ENTER) && !message.isEmpty()) {
client.session().tell(new Chat(teamService.teamProperty().get(), message),
ActorRef.noSender());
input.clear();
root.requestFocus();
}
}
/**
* Convert the given {@link ChatEvent} to a node.
*
* @param event The event to convert.
* @return The node that has been created.
*/
private Node toNode(ChatEvent event) {
Text user = new Text();
user.getStyleClass().add("user");
user.setText(String.format("%s: ", event.getTeam().getName()));
Text message = new Text();
message.getStyleClass().add("message");
message.setText(event.getMessage());
TextFlow flow = new TextFlow();
flow.getChildren().addAll(user, message);
return flow;
}
/**
* Sent a message from the lobby.
*
* @param ref The reference to the actor we sent the messages to.
* @param message The message to sent.
*/
private void sentMessage(ActorRef ref, String message) {
// Sent a message from the lobby
ref.tell(new ChatEvent(new Team(null, "Lobby", 0, null, null),
message), ActorRef.noSender());
}
/**
* Set the time remaining of the view.
*
* @param status The status of the lobby.
* @param duration The remaining duration.
*/
private void setRemaining(LobbyStatus status, Duration duration) {
String text = duration.toString()
.substring(2)
.replaceAll("(\\d[HMS])(?!$)", "$1 ")
.toLowerCase();
String message = text;
switch (status) {
case INTERMISSION:
message = String.format("Game preparation in %s", text);
break;
case PREPARATION:
message = String.format("Game starting in %s", text);
break;
default:
break;
}
remaining.setText(message.toUpperCase());
}
/**
* The actor that handles the logic for the lobby home screen.
*
* @author Fabian Mastenbroek
*/
public class LobbyHomeActor extends AbstractActor {
/**
* The {@link LoggingAdapter} of this class.
*/
private final LoggingAdapter log = Logging.getLogger(context().system(), this);
/**
* The time remaining.
*/
private Duration remaining;
/**
* The status of the lobby.
*/
private LobbyStatus status = LobbyStatus.INTERMISSION;
/**
* This method is invoked on the start of this actor.
*/
@Override
public void preStart() {
// initialize the countdown
context().system().scheduler().schedule(FiniteDuration.Zero(),
FiniteDuration.create(1, TimeUnit.SECONDS), self(), "tick",
context().dispatcher(), self());
}
/**
* This method defines the initial actor behavior, it must return a partial function with
* the actor logic.
*
* @return The initial actor behavior as a partial function.
*/
@Override
public PartialFunction<Object, BoxedUnit> receive() {
return ReceiveBuilder
.match(ChatEvent.class, msg -> {
chat.getItems().add(msg);
chat.scrollTo(chat.getItems().size() - 1);
})
.match(Lobby.class, msg -> {
if (remaining == null) {
remaining = msg.getStatus().equals(LobbyStatus.INTERMISSION)
? msg.getConfiguration().getIntermission()
: msg.getConfiguration().getPreparation();
}
})
.match(TimeRemaining.class, msg -> {
remaining = msg.getRemaining();
if (!remaining.isNegative()) {
setRemaining(status, remaining);
}
})
.matchEquals("tick", msg -> {
if (remaining == null) {
return;
}
remaining = remaining.minusSeconds(1);
if (!remaining.isNegative()) {
setRemaining(status, remaining);
}
})
.match(LobbyStatusChanged.class, msg -> status = msg.getStatus())
.match(TeamJoined.class, msg -> sentMessage(self(),
String.format("%s has joined the lobby", msg.getTeam().getName())))
.match(TeamLeft.class, msg -> sentMessage(self(),
String.format("%s has left the lobby", msg.getTeam().getName())))
.build();
}
}
}
| 32.900344 | 97 | 0.600689 |
f64d5cc3478afc7bc232f82fe15aad3123c0eb0c
| 5,108 |
/*
* Copyright 2011-Present 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.cp.elements.beans.event;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.beans.PropertyChangeEvent;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.junit.Test;
/**
* The ChangeTrackerTest class is a test suite of test cases testing the contract and functionality of the
* ChangeTracker class.
*
* @author John J. Blum
* @see org.cp.elements.beans.event.ChangeTracker
* @see org.junit.Assert
* @see org.junit.Test
* @since 1.0.0
*/
public class ChangeTrackerTest {
private static final Object SOURCE = new Object();
protected final PropertyChangeEvent createPropertyChangeEvent(final String propertyName,
final Object oldValue,
final Object newValue)
{
return new PropertyChangeEvent(SOURCE, propertyName, oldValue, newValue);
}
@Test
public void testPropertyChange() {
final ChangeTracker tracker = new ChangeTracker();
assertNotNull(tracker);
assertFalse(tracker.isModified());
tracker.propertyChange(createPropertyChangeEvent("myProperty", null, "test"));
assertTrue(tracker.isModified());
assertTrue(tracker.isModified("myProperty"));
assertFalse(tracker.isModified("yourProperty"));
tracker.propertyChange(createPropertyChangeEvent("myProperty", "test", "testing"));
assertTrue(tracker.isModified());
assertTrue(tracker.isModified("myProperty"));
assertFalse(tracker.isModified("yourProperty"));
tracker.propertyChange(createPropertyChangeEvent("myProperty", "testing", "tested"));
assertTrue(tracker.isModified());
assertTrue(tracker.isModified("myProperty"));
assertFalse(tracker.isModified("yourProperty"));
tracker.propertyChange(createPropertyChangeEvent("myProperty", "tested", null));
assertFalse(tracker.isModified());
assertFalse(tracker.isModified("myProperty"));
assertFalse(tracker.isModified("yourProperty"));
tracker.propertyChange(createPropertyChangeEvent("yourProperty", null, null));
assertFalse(tracker.isModified());
assertFalse(tracker.isModified("myProperty"));
assertFalse(tracker.isModified("yourProperty"));
}
@Test
public void testIterator() {
final ChangeTracker tracker = new ChangeTracker();
assertNotNull(tracker);
assertFalse(tracker.isModified());
tracker.propertyChange(createPropertyChangeEvent("propertyOne", null, "test"));
tracker.propertyChange(createPropertyChangeEvent("propertyTwo", null, null));
tracker.propertyChange(createPropertyChangeEvent("propertyThree", "null", null));
tracker.propertyChange(createPropertyChangeEvent("propertyFour", "null", "null"));
tracker.propertyChange(createPropertyChangeEvent("propertyFive", "null", "nil"));
assertTrue(tracker.isModified());
assertTrue(tracker.isModified("propertyOne"));
assertFalse(tracker.isModified("propertyTwo"));
assertTrue(tracker.isModified("propertyThree"));
assertFalse(tracker.isModified("propertyFour"));
assertTrue(tracker.isModified("propertyFive"));
final Set<String> actualProperties = new HashSet<String>(3);
for (final String property : tracker) {
actualProperties.add(property);
}
assertFalse(actualProperties.isEmpty());
assertEquals(3, actualProperties.size());
assertTrue(actualProperties.contains("propertyOne"));
assertFalse(actualProperties.contains("propertyTwo"));
assertTrue(actualProperties.contains("propertyThree"));
assertFalse(actualProperties.contains("propertyFour"));
assertTrue(actualProperties.contains("propertyFive"));
}
@Test(expected = UnsupportedOperationException.class)
public void testIteratorUnmodifiable() {
final ChangeTracker tracker = new ChangeTracker();
assertNotNull(tracker);
assertFalse(tracker.isModified());
tracker.propertyChange(createPropertyChangeEvent("propertyOne", null, "test"));
tracker.propertyChange(createPropertyChangeEvent("propertyTwo", null, null));
assertTrue(tracker.isModified());
assertTrue(tracker.isModified("propertyOne"));
assertFalse(tracker.isModified("propertyTwo"));
final Iterator<String> it = tracker.iterator();
assertNotNull(it);
assertTrue(it.hasNext());
it.remove();
}
}
| 34.513514 | 106 | 0.727291 |
d22a4271370ccde4223092068cb8e689786e75f1
| 25,490 |
/*
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* The Apereo Foundation licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.unitime.timetable.webutil;
import java.awt.Image;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.TreeSet;
import org.unitime.commons.web.WebTable;
import org.unitime.localization.impl.Localization;
import org.unitime.localization.messages.CourseMessages;
import org.unitime.timetable.defaults.CommonValues;
import org.unitime.timetable.defaults.UserProperty;
import org.unitime.timetable.model.BuildingPref;
import org.unitime.timetable.model.ClassInstructor;
import org.unitime.timetable.model.Class_;
import org.unitime.timetable.model.DepartmentalInstructor;
import org.unitime.timetable.model.DistributionPref;
import org.unitime.timetable.model.Exam;
import org.unitime.timetable.model.ExamType;
import org.unitime.timetable.model.InstructorAttribute;
import org.unitime.timetable.model.InstructorAttributeType;
import org.unitime.timetable.model.InstructorCoursePref;
import org.unitime.timetable.model.PreferenceLevel;
import org.unitime.timetable.model.RoomFeaturePref;
import org.unitime.timetable.model.RoomGroupPref;
import org.unitime.timetable.model.RoomPref;
import org.unitime.timetable.model.TimePref;
import org.unitime.timetable.model.comparators.ClassComparator;
import org.unitime.timetable.model.comparators.ClassInstructorComparator;
import org.unitime.timetable.security.SessionContext;
import org.unitime.timetable.security.rights.Right;
import org.unitime.timetable.util.Constants;
import org.unitime.timetable.util.Formats;
/**
* @author Heston Fernandes, Tomas Muller, Zuzana Mullerova
*/
public class InstructorListBuilder {
protected final static CourseMessages MSG = Localization.create(CourseMessages.class);
public String htmlTableForInstructor(SessionContext context, String deptId, int order, String backId) throws Exception {
boolean timeVertical = RequiredTimeTable.getTimeGridVertical(context.getUser());
boolean gridAsText = RequiredTimeTable.getTimeGridAsText(context.getUser());
String timeGridSize = RequiredTimeTable.getTimeGridSize(context.getUser());
// Loop through Instructor class
List list = null;
if (deptId.equals(Constants.ALL_OPTION_VALUE))
list = DepartmentalInstructor.findInstructorsForSession(context.getUser().getCurrentAcademicSessionId());
else
list = DepartmentalInstructor.findInstructorsForDepartment(Long.valueOf(deptId));
if (list==null || list.size() == 0) {
return null;
} else {
boolean hasCoursePrefs = false;
boolean hasTeachPref = false;
boolean hasMaxLoad = false;
boolean hasUnavailableDates = false;
TreeSet<InstructorAttributeType> attributeTypes = new TreeSet<InstructorAttributeType>(new Comparator<InstructorAttributeType>() {
@Override
public int compare(InstructorAttributeType o1, InstructorAttributeType o2) {
return o1.getReference().compareTo(o2.getReference());
}
});
for (Iterator i = list.iterator(); i.hasNext();) {
DepartmentalInstructor di = (DepartmentalInstructor)i.next();
if (!di.getPreferences(InstructorCoursePref.class).isEmpty()) hasCoursePrefs = true;
if (di.getMaxLoad() != null && di.getMaxLoad() > 0f) hasMaxLoad = true;
if (di.hasUnavailabilities()) hasUnavailableDates = true;
if (di.getTeachingPreference() != null && !PreferenceLevel.sProhibited.equals(di.getTeachingPreference().getPrefProlog())) hasTeachPref = true;
for (InstructorAttribute at: di.getAttributes())
if (at.getType() != null)
attributeTypes.add(at.getType());
}
String[] fixedHeaders1 = new String[] {
MSG.columnExternalId(),
MSG.columnInstructorName(),
MSG.columnInstructorPosition(),
MSG.columnInstructorNote(),
MSG.columnPreferences()+"<BR>"+MSG.columnTimePref(),
"<BR>"+MSG.columnRoomPref(),
"<BR>"+MSG.columnDistributionPref()};
String[] fixedHeaders2 = new String[] {
MSG.columnInstructorClassAssignments(),
MSG.columnInstructorExamAssignments(),
MSG.columnInstructorIgnoreTooFar()};
String[] headers = new String[fixedHeaders1.length + (hasCoursePrefs ? 1 : 0) + (hasTeachPref ? 1 : 0) + (hasMaxLoad ? 1 : 0) + (hasUnavailableDates ? 1 : 0) + attributeTypes.size() + fixedHeaders2.length];
String[] aligns = new String[headers.length];
boolean[] asc = new boolean[headers.length];
int idx = 0;
for (String h: fixedHeaders1) {
headers[idx] = h;
aligns[idx] = "left";
asc[idx] = true;
idx++;
}
if (hasCoursePrefs) {
headers[idx] = "<BR>" + MSG.columnCoursePref();
aligns[idx] = "left";
asc[idx] = true;
idx++;
}
if (hasTeachPref) {
headers[idx] = MSG.columnTeachingPreference();
aligns[idx] = "left";
asc[idx] = true;
idx++;
}
if (hasUnavailableDates) {
headers[idx] = MSG.columnUnavailableDates();
aligns[idx] = "left";
asc[idx] = true;
idx++;
}
if (hasMaxLoad) {
headers[idx] = MSG.columnMaxTeachingLoad();
aligns[idx] = "left";
asc[idx] = true;
idx++;
}
for (InstructorAttributeType at: attributeTypes) {
headers[idx] = at.getReference();
aligns[idx] = "left";
asc[idx] = true;
idx++;
}
for (String h: fixedHeaders2) {
headers[idx] = h;
aligns[idx] = "left";
asc[idx] = true;
idx++;
}
// Create new table
WebTable webTable = new WebTable(headers.length, "", "instructorList.do?order=%%&deptId=" + deptId, headers, aligns, asc);
webTable.setRowStyle("white-space:nowrap;");
webTable.enableHR("#9CB0CE");
String instructorNameFormat = UserProperty.NameFormat.get(context.getUser());
String instructorSortOrder = UserProperty.SortNames.get(context.getUser());
for (Iterator iter = list.iterator(); iter.hasNext();) {
DepartmentalInstructor di = (DepartmentalInstructor) iter.next();
String[] line = new String[headers.length];
Comparable[] cmp = new Comparable[headers.length];
idx = 0;
// puid
if (di.getExternalUniqueId()!=null && di.getExternalUniqueId().trim().length()>0) {
line[idx] = di.getExternalUniqueId();
cmp[idx] = di.getExternalUniqueId();
} else {
line[idx] = "<center><img src='images/error.png' border='0' alt='" + MSG.altNotAvailableExternalId() + "' title='"+MSG.titleInstructorExternalIdNotSupplied()+"'></center>";
cmp[idx] = "";
}
idx++;
// instructor name
line[idx] = Constants.toInitialCase(di.getName(instructorNameFormat), "-".toCharArray());
if (CommonValues.SortAsDisplayed.eq(instructorSortOrder))
cmp[idx] = line[idx].toLowerCase();
else
cmp[idx] = di.nameLastNameFirst().toLowerCase();
idx ++;
// position
if (di.getPositionType() != null) {
line[idx] = di.getPositionType().getLabel();
cmp[idx] = di.getPositionType().getSortOrder();
} else {
line[idx] = MSG.instructorPositionNotSpecified();
cmp[idx] = Integer.MAX_VALUE;
}
idx ++;
// note
if (di.getNote() != null) {
line[idx] = di.getNote();
cmp[idx] = di.getNote();
} else {
line[idx] = "";
cmp[idx] = "";
}
idx++;
// time preference
StringBuffer timePref = new StringBuffer();
if (di.getTimePreferences() != null) {
try {
for (Iterator i = di.getTimePreferences().iterator(); i.hasNext();) {
TimePref tp = (TimePref) i.next();
RequiredTimeTable rtt = tp.getRequiredTimeTable();
if (gridAsText) {
timePref.append("<span onmouseover=\"showGwtInstructorAvailabilityHint(this, '" + di.getUniqueId() + "');\" onmouseout=\"hideGwtInstructorAvailabilityHint();\">" +
rtt.getModel().toString().replaceAll(", ","<br>") + "</span>");
} else {
rtt.getModel().setDefaultSelection(timeGridSize);
timePref.append("<img border='0' onmouseover=\"showGwtInstructorAvailabilityHint(this, '" + di.getUniqueId() + "');\" onmouseout=\"hideGwtInstructorAvailabilityHint();\" " +
"src='pattern?v=" + (timeVertical ? 1 : 0) + "&s=" + rtt.getModel().getDefaultSelection() + "&p=" + rtt.getModel().getPreferences() + "' title='"+rtt.getModel().toString()+"' > ");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
line[idx] = timePref.toString();
idx ++;
// room preferences
line[idx] = "";
String x = di.getEffectivePrefHtmlForPrefType(RoomPref.class);
if (x != null && !x.trim().isEmpty()) {
line[idx] += x;
}
x = di.getEffectivePrefHtmlForPrefType(BuildingPref.class);
if (x != null && !x.trim().isEmpty()) {
if (!line[idx].isEmpty()) line[idx] += "<br>";
line[idx] += x;
}
x = di.getEffectivePrefHtmlForPrefType(RoomFeaturePref.class);
if (x != null && !x.trim().isEmpty()) {
if (!line[idx].isEmpty()) line[idx] += "<br>";
line[idx] += x;
}
x = di.getEffectivePrefHtmlForPrefType(RoomGroupPref.class);
if (x != null && !x.trim().isEmpty()) {
if (!line[idx].isEmpty()) line[idx] += "<br>";
line[idx] += x;
}
idx ++;
// distribution preferences
line[idx] = di.getEffectivePrefHtmlForPrefType(DistributionPref.class);
idx ++;
// course preferences
if (hasCoursePrefs) {
line[idx] = di.getEffectivePrefHtmlForPrefType(InstructorCoursePref.class);
idx ++;
}
// teaching preferences
if (hasTeachPref) {
PreferenceLevel pref = di.getTeachingPreference();
if (pref == null) pref = PreferenceLevel.getPreferenceLevel(PreferenceLevel.sProhibited);
line[idx] = "<span style='font-weight:bold; color:" + PreferenceLevel.prolog2color(pref.getPrefProlog()) + ";' title='" + pref.getPrefName() + "'>" + pref.getPrefName() + "</span>";
cmp[idx] = pref.getPrefId();
idx ++;
}
if (hasUnavailableDates) {
line[idx] = (di.hasUnavailabilities() ? di.getUnavailableDaysText("<br>") : "");
cmp[idx] = line[idx];
idx++;
}
// max load
if (hasMaxLoad) {
if (di.getMaxLoad() == null) {
line[idx] = "";
cmp[idx] = 0f;
} else {
line[idx] = Formats.getNumberFormat("0.##").format(di.getMaxLoad());
cmp[idx] = di.getMaxLoad();
}
idx ++;
}
for (InstructorAttributeType at: attributeTypes) {
line[idx] = "";
for (InstructorAttribute a: di.getAttributes(at)) {
if (!line[idx].isEmpty()) { line[idx] += "<br>"; }
line[idx] += "<span title='" + a.getName() + "'>" + a.getCode() + "</span>";
}
cmp[idx] = line[idx];
idx ++;
}
TreeSet classes = new TreeSet(new ClassInstructorComparator(new ClassComparator(ClassComparator.COMPARE_BY_LABEL)));
classes.addAll(di.getClasses());
line[idx] = "";
for (Iterator i=classes.iterator();i.hasNext();) {
ClassInstructor ci = (ClassInstructor)i.next();
Class_ c = ci.getClassInstructing();
String className = c.getClassLabel();
String title = className;
if (c.isCancelled())
title = MSG.classNoteCancelled(c.getClassLabel());
title += " ("+ci.getPercentShare()+"%"+(ci.isLead().booleanValue()?", " + MSG.titleCheckConflicts() :"")+")";
if (!c.isDisplayInstructor().booleanValue()){
title += " - " + MSG.titleDoNotDisplayInstructor();
}
if (c.isCancelled()) {
line[idx] += "<span style='color: gray; text-decoration: line-through;" + (ci.isLead() ? "font-weight:bold;" : "") + (c.isDisplayInstructor() ? "" : "font-style:italic;") + "' title='"+title+"'>";
} else if (ci.isLead().booleanValue()){
line[idx] += "<span style='font-weight:bold;"+(c.isDisplayInstructor().booleanValue()?"":"font-style:italic;")+"' title='"+title+"'>";
} else {
line[idx] += "<span title='"+title+"'>";
}
line[idx] += className;
line[idx] += "</span>";
if (i.hasNext()) line[idx] += "<br>";
}
idx ++;
TreeSet exams = new TreeSet(di.getExams());
line[idx] = "";
for (Iterator i=exams.iterator();i.hasNext();) {
Exam exam = (Exam)i.next();
if (!context.hasPermission(exam, Right.ExaminationView)) continue;
String examName = exam.getLabel();
if (exam.getExamType().getType()==ExamType.sExamTypeMidterm) {
line[idx] += "<span title='"+examName+" "+MSG.titleMidtermExamination()+"'>"+examName+"</span>";
} else {
line[idx] += "<span style='font-weight:bold;' title='"+examName+" "+MSG.titleFinalExamination()+"'>"+examName+"</span>";
}
if (i.hasNext()) line[idx] += "<br>";
}
idx ++;
if (di.isIgnoreToFar()==null?false:di.isIgnoreToFar().booleanValue()) {
line[idx] = "<img border='0' title='" + MSG.titleIgnoreTooFarDistances() + "' alt='true' align='absmiddle' src='images/accept.png'>";
cmp[idx] = true;
} else {
line[idx] = "";
cmp[idx] = false;
}
idx ++;
boolean back = di.getUniqueId().toString().equals(backId);
if (back) line[0] = "<A name=\"back\"></A>" + line[0];
// Add to web table
webTable.addLine("onClick=\"document.location='instructorDetail.do?instructorId=" + di.getUniqueId() + "&deptId=" + deptId + "';\"", line, cmp);
}
String tblData = webTable.printTable(order);
return tblData;
}
}
public PdfWebTable pdfTableForInstructor(SessionContext context, String deptId, boolean canHaveImages) throws Exception {
boolean timeVertical = RequiredTimeTable.getTimeGridVertical(context.getUser());
boolean gridAsText = RequiredTimeTable.getTimeGridAsText(context.getUser());
String timeGridSize = RequiredTimeTable.getTimeGridSize(context.getUser());
// Loop through Instructor class
List list = null;
if (deptId.equals(Constants.ALL_OPTION_VALUE))
list = DepartmentalInstructor.findInstructorsForSession(context.getUser().getCurrentAcademicSessionId());
else
list = DepartmentalInstructor.findInstructorsForDepartment(Long.valueOf(deptId));
if (list==null || list.size() == 0)
return null;
boolean hasCoursePrefs = false;
boolean hasTeachPref = false;
boolean hasMaxLoad = false;
boolean hasUnavailableDates = false;
TreeSet<InstructorAttributeType> attributeTypes = new TreeSet<InstructorAttributeType>(new Comparator<InstructorAttributeType>() {
@Override
public int compare(InstructorAttributeType o1, InstructorAttributeType o2) {
return o1.getReference().compareTo(o2.getReference());
}
});
for (Iterator i = list.iterator(); i.hasNext();) {
DepartmentalInstructor di = (DepartmentalInstructor)i.next();
if (!di.getPreferences(InstructorCoursePref.class).isEmpty()) hasCoursePrefs = true;
if (di.getMaxLoad() != null && di.getMaxLoad() > 0f) hasMaxLoad = true;
if (di.hasUnavailabilities()) hasUnavailableDates = true;
if (di.getTeachingPreference() != null && !PreferenceLevel.sProhibited.equals(di.getTeachingPreference().getPrefProlog())) hasTeachPref = true;
for (InstructorAttribute at: di.getAttributes())
if (at.getType() != null)
attributeTypes.add(at.getType());
}
String[] fixedHeaders1 = new String[] {
MSG.columnExternalId(),
MSG.columnInstructorName(),
MSG.columnInstructorPosition(),
MSG.columnInstructorNote(),
MSG.columnPreferences()+"\n"+MSG.columnTimePref(),
"\n"+MSG.columnRoomPref(),
"\n"+MSG.columnDistributionPref()};
String[] fixedHeaders2 = new String[] {
MSG.columnInstructorClassAssignmentsPDF(),
MSG.columnInstructorExamAssignmentsPDF(),
MSG.columnInstructorIgnoreTooFarPDF()};
String[] headers = new String[fixedHeaders1.length + (hasCoursePrefs ? 1 : 0) + (hasTeachPref ? 1 : 0) + (hasMaxLoad ? 1 : 0) + (hasUnavailableDates ? 1 : 0) + attributeTypes.size() + fixedHeaders2.length];
String[] aligns = new String[headers.length];
boolean[] asc = new boolean[headers.length];
int idx = 0;
for (String h: fixedHeaders1) {
headers[idx] = h;
aligns[idx] = "left";
asc[idx] = true;
idx++;
}
if (hasCoursePrefs) {
headers[idx] = "\n" + MSG.columnCoursePref();
aligns[idx] = "left";
asc[idx] = true;
idx++;
}
if (hasTeachPref) {
headers[idx] = MSG.columnTeachingPreferencePDF();
aligns[idx] = "left";
asc[idx] = true;
idx++;
}
if (hasUnavailableDates) {
headers[idx] = MSG.columnUnavailableDatesPDF();
aligns[idx] = "left";
asc[idx] = true;
idx++;
}
if (hasMaxLoad) {
headers[idx] = MSG.columnMaxTeachingLoadPDF();
aligns[idx] = "left";
asc[idx] = true;
idx++;
}
for (InstructorAttributeType at: attributeTypes) {
headers[idx] = at.getReference();
aligns[idx] = "left";
asc[idx] = true;
idx++;
}
for (String h: fixedHeaders2) {
headers[idx] = h;
aligns[idx] = "left";
asc[idx] = true;
idx++;
}
// Create new table
PdfWebTable webTable = new PdfWebTable(headers.length, MSG.sectionTitleInstructorList(), null, headers, aligns, asc);
String instructorNameFormat = UserProperty.NameFormat.get(context.getUser());
String instructorSortOrder = UserProperty.SortNames.get(context.getUser());
for (Iterator iter = list.iterator(); iter.hasNext();) {
DepartmentalInstructor di = (DepartmentalInstructor) iter.next();
String[] line = new String[headers.length];
Comparable[] cmp = new Comparable[headers.length];
idx = 0;
// puid
if (di.getExternalUniqueId()!=null && di.getExternalUniqueId().trim().length()>0) {
line[idx] = di.getExternalUniqueId();
cmp[idx] = di.getExternalUniqueId();
} else {
line[idx] = "@@ITALIC "+MSG.instructorExternalIdNotSpecified();
cmp[idx] = "";
}
idx++;
// instructor name
line[idx] = Constants.toInitialCase(di.getName(instructorNameFormat), "-".toCharArray());
if (CommonValues.SortAsDisplayed.eq(instructorSortOrder))
cmp[idx] = line[idx].toLowerCase();
else
cmp[idx] = di.nameLastNameFirst().toLowerCase();
idx ++;
// position
if (di.getPositionType() != null) {
line[idx] = di.getPositionType().getLabel();
cmp[idx] = di.getPositionType().getSortOrder();
} else {
line[idx] = "@@ITALIC " + MSG.instructorPositionNotSpecified();
cmp[idx] = Integer.MAX_VALUE;
}
idx ++;
// note
if (di.getNote() != null) {
line[idx] = di.getNote();
cmp[idx] = di.getNote();
} else {
line[idx] = "";
cmp[idx] = "";
}
idx++;
// time preference
StringBuffer timePref = new StringBuffer();
if (di.getTimePreferences() != null) {
for (Iterator i = di.getTimePreferences().iterator(); i.hasNext();) {
TimePref tp = (TimePref) i.next();
RequiredTimeTable rtt = tp.getRequiredTimeTable();
if (gridAsText || !canHaveImages) {
timePref.append(rtt.getModel().toString().replaceAll(", ","\n"));
} else {
rtt.getModel().setDefaultSelection(timeGridSize);
Image image = rtt.createBufferedImage(timeVertical);
if (image != null) {
webTable.addImage(tp.getUniqueId().toString(), image);
timePref.append("@@IMAGE "+tp.getUniqueId().toString()+" ");
} else
timePref.append(rtt.getModel().toString().replaceAll(", ","\n"));
if (i.hasNext()) timePref.append("\n");
}
}
}
line[idx] = timePref.toString();
idx ++;
// room preferences
line[idx] = "";
for (Iterator i=di.effectivePreferences(RoomPref.class).iterator();i.hasNext();) {
RoomPref rp = (RoomPref)i.next();
if (!line[idx].isEmpty()) line[idx] += "\n";
line[idx] += "@@COLOR " + PreferenceLevel.prolog2color(rp.getPrefLevel().getPrefProlog()) + " " + rp.getPrefLevel().getAbbreviation()+" "+rp.getRoom().getLabel();
}
for (Iterator i=di.effectivePreferences(BuildingPref.class).iterator();i.hasNext();) {
BuildingPref bp = (BuildingPref)i.next();
if (!line[idx].isEmpty()) line[idx] += "\n";
line[idx] += "@@COLOR " + PreferenceLevel.prolog2color(bp.getPrefLevel().getPrefProlog()) + " " + bp.getPrefLevel().getAbbreviation()+" "+bp.getBuilding().getAbbreviation();
}
for (Iterator i=di.effectivePreferences(RoomFeaturePref.class).iterator();i.hasNext();) {
RoomFeaturePref rfp = (RoomFeaturePref)i.next();
if (!line[idx].isEmpty()) line[idx] += "\n";
line[idx] += "@@COLOR " + PreferenceLevel.prolog2color(rfp.getPrefLevel().getPrefProlog()) + " " + rfp.getPrefLevel().getAbbreviation()+" "+rfp.getRoomFeature().getLabel();
}
for (Iterator i=di.effectivePreferences(RoomGroupPref.class).iterator();i.hasNext();) {
RoomGroupPref rgp = (RoomGroupPref)i.next();
if (!line[idx].isEmpty()) line[idx] += "\n";
line[idx] += "@@COLOR " + PreferenceLevel.prolog2color(rgp.getPrefLevel().getPrefProlog()) + " " + rgp.getPrefLevel().getAbbreviation()+" "+rgp.getRoomGroup().getName();
}
idx ++;
// distribution preferences
line[idx] = "";
for (Iterator i=di.effectivePreferences(DistributionPref.class).iterator();i.hasNext();) {
DistributionPref dp = (DistributionPref)i.next();
if (!line[idx].isEmpty()) line[idx] += "\n";
line[idx] += "@@COLOR " + PreferenceLevel.prolog2color(dp.getPrefLevel().getPrefProlog()) + " " + dp.getPrefLevel().getAbbreviation()+" "+dp.getDistributionType().getAbbreviation();
}
idx ++;
// course preferences
if (hasCoursePrefs) {
line[idx] = "";
for (Iterator i=di.effectivePreferences(InstructorCoursePref.class).iterator();i.hasNext();) {
InstructorCoursePref dp = (InstructorCoursePref)i.next();
if (!line[idx].isEmpty()) line[idx] += "\n";
line[idx] += "@@COLOR " + PreferenceLevel.prolog2color(dp.getPrefLevel().getPrefProlog()) + " " + dp.getPrefLevel().getAbbreviation()+" "+dp.getCourse().getCourseName();
}
idx ++;
}
// teaching preferences
if (hasTeachPref) {
PreferenceLevel pref = di.getTeachingPreference();
if (pref == null) pref = PreferenceLevel.getPreferenceLevel(PreferenceLevel.sProhibited);
line[idx] = "@@COLOR " + PreferenceLevel.prolog2color(pref.getPrefProlog()) + " " + pref.getPrefName();
cmp[idx] = pref.getPrefId();
idx ++;
}
if (hasUnavailableDates) {
line[idx] = (di.hasUnavailabilities() ? di.getUnavailableDaysText("\n") : "");
cmp[idx] = line[idx];
idx++;
}
// max load
if (hasMaxLoad) {
if (di.getMaxLoad() == null) {
line[idx] = "";
cmp[idx] = 0f;
} else {
line[idx] = Formats.getNumberFormat("0.##").format(di.getMaxLoad());
cmp[idx] = di.getMaxLoad();
}
idx ++;
}
for (InstructorAttributeType at: attributeTypes) {
line[idx] = "";
for (InstructorAttribute a: di.getAttributes(at)) {
if (!line[idx].isEmpty()) { line[idx] += "\n"; }
line[idx] += a.getCode();
}
cmp[idx] = line[idx];
idx ++;
}
TreeSet classes = new TreeSet(new ClassInstructorComparator(new ClassComparator(ClassComparator.COMPARE_BY_LABEL)));
classes.addAll(di.getClasses());
line[idx] = "";
for (Iterator i=classes.iterator();i.hasNext();) {
ClassInstructor ci = (ClassInstructor)i.next();
Class_ c = ci.getClassInstructing();
String className = c.getClassLabel();
if (ci.isLead().booleanValue())
line[idx] += "@@BOLD ";
if (!c.isDisplayInstructor().booleanValue())
line[idx] += "@@ITALIC ";
line[idx] += className;
if (!c.isDisplayInstructor().booleanValue())
line[idx] += "@@END_ITALIC ";
if (ci.isLead().booleanValue())
line[idx] += "@@END_BOLD ";
if (i.hasNext()) line[idx] += "\n";
}
idx ++;
TreeSet exams = new TreeSet(di.getExams());
line[idx] = "";
for (Iterator i=exams.iterator();i.hasNext();) {
Exam exam = (Exam)i.next();
if (!context.hasPermission(exam, Right.ExaminationView)) continue;
String examName = exam.getLabel();
if (exam.getExamType().getType()==ExamType.sExamTypeMidterm) {
line[idx] += examName;
} else {
line[idx] += "@@BOLD " + examName + "@@END_BOLD ";
}
if (i.hasNext()) line[idx] += "\n";
}
idx ++;
if (di.isIgnoreToFar()==null?false:di.isIgnoreToFar().booleanValue()) {
line[idx] = "@@ITALIC " + MSG.yes();
cmp[idx] = true;
} else {
line[idx] = "@@ITALIC " + MSG.no();
cmp[idx] = false;
}
idx ++;
// Add to web table
webTable.addLine(null, line, cmp);
}
return webTable;
}
}
| 37.875186 | 209 | 0.638564 |
9bb8410ced9881075d84d2a1f2bc12aeed4aedfe
| 6,432 |
package com.planet_ink.coffee_mud.Abilities.Spells;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2000-2010 Bo Zimmerman
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.
*/
@SuppressWarnings("unchecked")
public class Spell_PhantomHound extends Spell
{
public String ID() { return "Spell_PhantomHound"; }
public String name(){return "Phantom Hound";}
protected int canAffectCode(){return CAN_MOBS;}
protected int canTargetCode(){return 0;}
public int abstractQuality(){ return Ability.QUALITY_MALICIOUS;}
public int enchantQuality(){return Ability.QUALITY_INDIFFERENT;}
protected MOB victim=null;
protected int pointsLeft=0;
public int classificationCode(){return Ability.ACODE_SPELL|Ability.DOMAIN_ILLUSION;}
public boolean tick(Tickable ticking, int tickID)
{
if(tickID==Tickable.TICKID_MOB)
{
if(((affected==null)
||(unInvoked)
||(!(affected instanceof MOB)))
&&(canBeUninvoked()))
unInvoke();
else
{
MOB beast=(MOB)affected;
int a=0;
while(a<beast.numEffects())
{
Ability A=beast.fetchEffect(a);
if(A!=null)
{
int n=beast.numEffects();
if(A.ID().equals(ID()))
a++;
else
{
A.unInvoke();
if(beast.numEffects()==n)
a++;
}
}
else
a++;
}
if((!beast.isInCombat())||(beast.getVictim()!=victim))
{
if(beast.amDead()) beast.setLocation(null);
beast.destroy();
}
else
{
pointsLeft-=(victim.charStats().getStat(CharStats.STAT_INTELLIGENCE));
pointsLeft-=victim.envStats().level();
int pointsLost=beast.baseState().getHitPoints()-beast.curState().getHitPoints();
if(pointsLost>0)
pointsLeft-=pointsLost/4;
if(pointsLeft<0)
{
if(beast.amDead()) beast.setLocation(null);
beast.destroy();
}
}
}
}
return super.tick(ticking,tickID);
}
public void executeMsg(Environmental myHost, CMMsg msg)
{
super.executeMsg(myHost,msg);
if((affected!=null)
&&(affected instanceof MOB)
&&(msg.amISource((MOB)affected)||msg.amISource(((MOB)affected).amFollowing()))
&&(msg.sourceMinor()==CMMsg.TYP_QUIT))
{
unInvoke();
if(msg.source().playerStats()!=null) msg.source().playerStats().setLastUpdated(0);
}
}
public void unInvoke()
{
MOB mob=(MOB)affected;
super.unInvoke();
if((canBeUninvoked())&&(mob!=null))
{
if(mob.amDead()) mob.setLocation(null);
mob.destroy();
}
}
public boolean okMessage(Environmental myHost, CMMsg msg)
{
if((affected!=null)
&&(affected instanceof MOB)
&&(msg.amISource((MOB)affected))
&&(msg.targetMinor()==CMMsg.TYP_DAMAGE))
msg.setValue(0);
return super.okMessage(myHost,msg);
}
public boolean invoke(MOB mob, Vector commands, Environmental givenTarget, boolean auto, int asLevel)
{
if(!mob.isInCombat())
{
mob.tell("You must be in combat to cast this spell!");
return false;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
CMMsg msg=CMClass.getMsg(mob,null,this,verbalCastCode(mob,null,auto),auto?"":"^S<S-NAME> invoke(s) a ferocious phantom assistant.^?");
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
MOB beast=CMClass.getMOB("GenMOB");
beast.setName("the phantom hound");
beast.setDisplayText("the phantom hound is here");
beast.setStartRoom(null);
beast.setDescription("This is the most ferocious beast you have ever seen.");
beast.baseEnvStats().setAttackAdjustment(mob.envStats().attackAdjustment()+100);
beast.baseEnvStats().setArmor(mob.baseEnvStats().armor()-20);
beast.baseEnvStats().setDamage(75);
beast.baseEnvStats().setLevel(mob.envStats().level()+(2*getXLEVELLevel(mob)));
beast.baseEnvStats().setSensesMask(EnvStats.CAN_SEE_DARK|EnvStats.CAN_SEE_HIDDEN|EnvStats.CAN_SEE_INVISIBLE|EnvStats.CAN_SEE_SNEAKERS);
beast.baseCharStats().setMyRace(CMClass.getRace("Dog"));
beast.baseCharStats().getMyRace().startRacing(beast,false);
for(int i : CharStats.CODES.SAVING_THROWS())
beast.baseCharStats().setStat(i,200);
beast.addNonUninvokableEffect(CMClass.getAbility("Prop_ModExperience"));
beast.baseEnvStats().setAbility(100);
beast.baseState().setMana(100);
beast.baseState().setMovement(1000);
beast.recoverEnvStats();
beast.recoverCharStats();
beast.recoverMaxState();
beast.resetToMaxState();
beast.text();
beast.bringToLife(mob.location(),true);
CMLib.beanCounter().clearZeroMoney(beast,null);
beast.location().showOthers(beast,null,CMMsg.MSG_OK_ACTION,"<S-NAME> appears!");
beast.setStartRoom(null);
victim=mob.getVictim();
if(victim!=null)
{
victim.setVictim(beast);
beast.setVictim(victim);
}
pointsLeft=130;
beneficialAffect(mob,beast,asLevel,0);
}
}
else
beneficialVisualFizzle(mob,null,"<S-NAME> attempt(s) to invoke a spell, but fizzle(s) the spell.");
// return whether it worked
return success;
}
}
| 32.321608 | 140 | 0.680193 |
08d1f2de9f3e5a9ccec0c4b4a6b25c5409736497
| 7,414 |
/*
* Copyright (C) 2012 Andrew Neal Licensed under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
* or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.andrew.apollo.ui.fragments;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import com.andrew.apollo.Config;
import com.andrew.apollo.R;
import com.andrew.apollo.adapters.GenreAdapter;
import com.andrew.apollo.loaders.GenreLoader;
import com.andrew.apollo.menu.FragmentMenuItems;
import com.andrew.apollo.model.Genre;
import com.andrew.apollo.recycler.RecycleHolder;
import com.andrew.apollo.ui.activities.ProfileActivity;
import com.andrew.apollo.utils.MusicUtils;
/**
* This class is used to display all of the genres on a user's device.
*
* @author Andrew Neal (andrewdneal@gmail.com)
*/
public class GenreFragment extends Fragment implements LoaderCallbacks<List<Genre>>,
OnItemClickListener {
/**
* Used to keep context menu items from bleeding into other fragments
*/
private static final int GROUP_ID = 5;
/**
* LoaderCallbacks identifier
*/
private static final int LOADER = 0;
/**
* Fragment UI
*/
private ViewGroup mRootView;
/**
* The adapter for the list
*/
private GenreAdapter mAdapter;
/**
* The list view
*/
private ListView mListView;
/**
* Genre song list
*/
private long[] mGenreList;
/**
* Represents a genre
*/
private Genre mGenre;
/**
* Empty constructor as per the {@link Fragment} documentation
*/
public GenreFragment() {
}
/**
* {@inheritDoc}
*/
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create the adpater
mAdapter = new GenreAdapter(getActivity(), R.layout.list_item_simple);
}
/**
* {@inheritDoc}
*/
@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
final Bundle savedInstanceState) {
// The View for the fragment's UI
mRootView = (ViewGroup)inflater.inflate(R.layout.list_base, null);
// Initialize the list
mListView = (ListView)mRootView.findViewById(R.id.list_base);
// Set the data behind the list
mListView.setAdapter(mAdapter);
// Release any references to the recycled Views
mListView.setRecyclerListener(new RecycleHolder());
// Listen for ContextMenus to be created
mListView.setOnCreateContextMenuListener(this);
// Show the albums and songs from the selected genre
mListView.setOnItemClickListener(this);
return mRootView;
}
/**
* {@inheritDoc}
*/
@Override
public void onActivityCreated(final Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Enable the options menu
setHasOptionsMenu(true);
// Start the loader
getLoaderManager().initLoader(LOADER, null, this);
}
/**
* {@inheritDoc}
*/
@Override
public void onCreateContextMenu(final ContextMenu menu, final View v,
final ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
// Get the position of the selected item
final AdapterContextMenuInfo info = (AdapterContextMenuInfo)menuInfo;
// Create a new genre
mGenre = mAdapter.getItem(info.position);
// Create a list of the genre's songs
mGenreList = MusicUtils.getSongListForGenre(getActivity(), mGenre.mGenreId);
// Play the genre
menu.add(GROUP_ID, FragmentMenuItems.PLAY_SELECTION, Menu.NONE,
R.string.context_menu_play_selection);
// Add the genre to the queue
menu.add(GROUP_ID, FragmentMenuItems.ADD_TO_QUEUE, Menu.NONE, R.string.add_to_queue);
}
/**
* {@inheritDoc}
*/
@Override
public boolean onContextItemSelected(final android.view.MenuItem item) {
if (item.getGroupId() == GROUP_ID) {
switch (item.getItemId()) {
case FragmentMenuItems.PLAY_SELECTION:
MusicUtils.playAll(getActivity(), mGenreList, 0, false);
return true;
case FragmentMenuItems.ADD_TO_QUEUE:
MusicUtils.addToQueue(getActivity(), mGenreList);
return true;
default:
break;
}
}
return super.onContextItemSelected(item);
}
/**
* {@inheritDoc}
*/
@Override
public void onItemClick(final AdapterView<?> parent, final View view, final int position,
final long id) {
mGenre = mAdapter.getItem(position);
// Create a new bundle to transfer the artist info
final Bundle bundle = new Bundle();
bundle.putLong(Config.ID, mGenre.mGenreId);
bundle.putString(Config.MIME_TYPE, MediaStore.Audio.Genres.CONTENT_TYPE);
bundle.putString(Config.NAME, mGenre.mGenreName);
// Create the intent to launch the profile activity
final Intent intent = new Intent(getActivity(), ProfileActivity.class);
intent.putExtras(bundle);
startActivity(intent);
}
/**
* {@inheritDoc}
*/
@Override
public Loader<List<Genre>> onCreateLoader(final int id, final Bundle args) {
return new GenreLoader(getActivity());
}
/**
* {@inheritDoc}
*/
@Override
public void onLoadFinished(final Loader<List<Genre>> loader, final List<Genre> data) {
// Check for any errors
if (data.isEmpty()) {
// Set the empty text
final TextView empty = (TextView)mRootView.findViewById(R.id.empty);
empty.setText(getString(R.string.empty_music));
mListView.setEmptyView(empty);
return;
}
// Start fresh
mAdapter.unload();
// Add the data to the adpater
for (final Genre genre : data) {
mAdapter.add(genre);
}
// Build the cache
mAdapter.buildCache();
}
/**
* {@inheritDoc}
*/
@Override
public void onLoaderReset(final Loader<List<Genre>> loader) {
// Clear the data in the adapter
mAdapter.unload();
}
}
| 31.151261 | 93 | 0.654168 |
973fd3d98bbae93e9a0651c5259c9d04d3648c76
| 626 |
package com.sixt.service.framework.kafka;
import org.apache.kafka.clients.consumer.ConsumerRecord;
public class EagerMessageQueue implements MessageQueue {
private MessageExecutor messageExecutor;
public EagerMessageQueue(MessageExecutor messageExecutor, long retryDelayMillis) {
this.messageExecutor = messageExecutor;
}
@Override
public void add(ConsumerRecord<String, String> record) {
messageExecutor.execute(record);
}
@Override
public void consumed(KafkaTopicInfo topicInfo) {
}
@Override
public void processingEnded(KafkaTopicInfo topicInfo) {
}
}
| 24.076923 | 86 | 0.741214 |
1341f4728aee60883df666799a4da7ca491c92bd
| 2,993 |
package no.rmz.midibridge;
import com.fasterxml.jackson.annotation.JsonProperty;
/*
Command Meaning # parameters param 1 param 2
0x80 Note-off 2 key velocity
0x90 Note-on 2 key veolcity
0xA0 Aftertouch 2 key touch
0xB0 Continuous controller 2 controller controller value
0xC0 Patch change 2 instrument #
0xD0 Channel Pressure 1 pressure
0xE0 Pitch bend 2 lsb (7 bits) msb (7 bits)
" 14 bits of bend value"
0xF0 (non-musical commands)
*/
public final class FbMidiEventBean {
private String cmd;
private int chan;
private int note;
private int velocity;
private int controller;
private int pressure;
private int touch;
private int instrument;
private int bendValue;
private int patch;
public FbMidiEventBean() {
}
public void setPatch(int patch) {
this.patch = patch;
}
public void setInstrument(int instrument) {
this.instrument = instrument;
}
@JsonProperty
public int getBendValue() {
return bendValue;
}
public void setBendValue(int bendValue) {
this.bendValue = bendValue;
}
@JsonProperty
public int getController() {
return controller;
}
public void setController(int controller) {
this.controller = controller;
}
@JsonProperty
public int getPressure() {
return pressure;
}
public void setPressure(int pressure) {
this.pressure = pressure;
}
@JsonProperty
public int getTouch() {
return touch;
}
@JsonProperty
public void setTouch(int touch) {
this.touch = touch;
}
@JsonProperty
public int getInstrumentNumber() {
return instrument;
}
public void setInstrumentNumber(int instrumentNumber) {
this.instrument = instrumentNumber;
}
public void setCmd(String cmd) {
this.cmd = cmd;
}
public void setChan(int chan) {
this.chan = chan;
}
public void setNote(int note) {
this.note = note;
}
@JsonProperty
public String getCmd() {
return cmd;
}
@JsonProperty
public int getChan() {
return chan;
}
@JsonProperty
public int getNote() {
return note;
}
@JsonProperty
public int getVelocity() {
return velocity;
}
public void setVelocity(int velocity) {
this.velocity = velocity;
}
@Override
public String toString() {
return "FbMidiEventBean{" + "cmd=" + cmd + ", chan=" + chan + ", note=" + note + ", velocity=" + velocity + '}';
}
public int getInstrument() {
return instrument;
}
@JsonProperty
public int getPatch() {
return patch;
}
}
| 21.688406 | 120 | 0.564651 |
be4a2dcc1240b2c4a78865c7dd8903a66597efef
| 2,420 |
package org.im97mori.ble.advertising;
import static org.im97mori.ble.constants.DataType.APPEARANCE_DATA_TYPE;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import org.im97mori.ble.BLEUtils;
import org.im97mori.ble.constants.AppearanceValues;
import androidx.annotation.NonNull;
/**
* <p>
* Appearance
* <p>
* https://www.bluetooth.com/specifications/assigned-numbers/generic-access-profile/
* </p>
*/
public class Appearance extends AbstractAdvertisingData {
/**
* Appearance
*/
private final int mAppearance;
/**
* Constructor for Appearance
*
* @param data byte array from <a href=
* "https://developer.android.com/reference/android/bluetooth/le/ScanRecord#getBytes()">ScanRecord#getBytes()</a>
* @param offset data offset
* @param length 1st octet of Advertising Data
*/
public Appearance(@NonNull byte[] data, int offset, int length) {
super(length);
mAppearance = BLEUtils.createUInt16(data, offset + 2);
}
/**
* {@inheritDoc}
*/
@Override
public int getDataType() {
return APPEARANCE_DATA_TYPE;
}
/**
* @return Appearance
*/
public int getAppearance() {
return mAppearance;
}
/**
* @return Appearance Category(bits 15 to 6)
*/
public int getAppearanceCategory() {
return (mAppearance >> 6) & 0b00000011_11111111;
}
/**
* @return Appearance Category
*/
public int getAppearanceCategoryWithOffset() {
return mAppearance & 0b11111111_11000000;
}
/**
* @return Appearance Category Name
* @see AppearanceValues#APPEARANCE_CATEGORY_MAPPING
*/
public String getAppearanceCategoryName() {
return AppearanceValues.APPEARANCE_CATEGORY_MAPPING.get(getAppearanceCategoryWithOffset());
}
/**
* @return Appearance Sub Category(bits 5 to 0)
*/
public int getAppearanceSubCategory() {
return mAppearance & 0b00111111;
}
/**
* @return Appearance Sub Category Name
* @see AppearanceValues#APPEARANCE_SUB_CATEGORY_MAPPING
*/
public String getAppearanceSubCategoryName() {
return AppearanceValues.APPEARANCE_SUB_CATEGORY_MAPPING.get(mAppearance);
}
/**
* {@inheritDoc}
*/
@NonNull
@Override
public byte[] getBytes() {
byte[] data = new byte[1 + getLength()];
ByteBuffer byteBuffer = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN);
byteBuffer.put((byte) getLength());
byteBuffer.put((byte) getDataType());
byteBuffer.putShort((short) mAppearance);
return data;
}
}
| 22.407407 | 128 | 0.718182 |
68ba7ca8436838d8332e68b74f01389c6f6b2c6b
| 1,839 |
package com.stackroute.recommendationservice.repository;
import com.stackroute.recommendationservice.domain.QuestionNode;
import com.stackroute.recommendationservice.domain.UserNode;
import org.springframework.data.neo4j.annotation.Query;
import org.springframework.data.neo4j.repository.Neo4jRepository;
import org.springframework.data.repository.query.Param;
import java.util.List;
public interface UserRepository extends Neo4jRepository<UserNode, String> {
@Query("Match(u:UserNode),(c:children),(p:parents),(q:QuestionNode) WHERE u.email={UserName} AND (q)-[:question_of_topic]->(c) AND (u)-[:follows]->(c) or (q)-[:question_of_topic]->(p) and (u)-[:follows]->(p) And NOT (q)<-[:answer_of ]-() Return q")
List<QuestionNode> findAllUnansweredQuestionsForRegisteredUser(@Param("UserName") String username);
@Query("match (u:UserNode),(c:children),(p:parents),(q:QuestionNode) where (q)-[:question_of_topic]->(c) and (u)-[:follows]->(c) or (q)-[:question_of_topic]->(p) and (u)-[:follows]->(p) and q.question={question} return u")
List<UserNode> findAllUsersRelatedToTopic(@Param("question") String question);
@Query("match (q:QuestionNode),(u:UserNode),(c:children),(p:parents) where u.email={username} and (u)-[:follows]->(c) and (q)-[:question_of_topic]->(c) or (u)-[:follows]->(p) and (q)-[:question_of_topic]->(p) return q")
List<QuestionNode> getAllTrendingQuestionsForRegisteredUser(@Param("username") String username);
@Query("Match (u:UserNode),(q:QuestionNode),(a:AnswerNode),(c:children),(p:parents) where u.email={username} and (u)-[:follows]->(c) or (u)-[:follows]->(p) and (q)-[:question_of_topic]->(c) or (q)-[:question_of_topic]->(p) and (a)-[:answer_of]->(q) and a.accepted=true return q")
List<QuestionNode> getAllAcceptedAnswersForDomain(@Param("username") String username);
}
| 73.56 | 284 | 0.725394 |
06a36eaa0d3a2ba5d73c355a87c1f93c43cab861
| 7,660 |
/**
* Licensed to JumpMind Inc under one or more contributor
* license agreements. See the NOTICE file distributed
* with this work for additional information regarding
* copyright ownership. JumpMind Inc licenses this file
* to you under the GNU General Public License, version 3.0 (GPLv3)
* (the "License"); you may not use this file except in compliance
* with the License.
*
* You should have received a copy of the GNU General Public License,
* version 3.0 (GPLv3) along with this library; if not, see
* <http://www.gnu.org/licenses/>.
*
* 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.jumpmind.symmetric.job;
import org.apache.commons.lang.StringUtils;
import org.jumpmind.symmetric.ISymmetricEngine;
import org.jumpmind.symmetric.SymmetricException;
import org.jumpmind.symmetric.model.JobDefinition;
import org.jumpmind.symmetric.service.impl.AbstractService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
/*
* @see IJobManager
*/
public class JobManager extends AbstractService implements IJobManager {
static final Logger log = LoggerFactory.getLogger(JobManager.class);
private List<IJob> jobs;
private ThreadPoolTaskScheduler taskScheduler;
private ISymmetricEngine engine;
private JobCreator jobCreator = new JobCreator();
private boolean started = false;
public JobManager(ISymmetricEngine engine) {
super(engine.getParameterService(), engine.getSymmetricDialect());
this.engine = engine;
this.taskScheduler = new ThreadPoolTaskScheduler();
setSqlMap(new JobManagerSqlMap(engine.getSymmetricDialect().getPlatform(), createSqlReplacementTokens()));
this.taskScheduler.setThreadNamePrefix(String.format("%s-job-", engine.getParameterService().getEngineName()));
this.taskScheduler.setPoolSize(20);
this.taskScheduler.initialize();
}
@Override
protected Map<String, String> createSqlReplacementTokens() {
Map<String, String> replacementTokens = createSqlReplacementTokens(this.tablePrefix, symmetricDialect.getPlatform()
.getDatabaseInfo().getDelimiterToken(), symmetricDialect.getPlatform());
replacementTokens.putAll(symmetricDialect.getSqlReplacementTokens());
return replacementTokens;
}
@Override
public void init() {
this.stopJobs();
List<JobDefinition> jobDefitions = loadJobs(engine);
BuiltInJobs builtInJobs = new BuiltInJobs();
jobDefitions = builtInJobs.syncBuiltInJobs(jobDefitions, engine, taskScheduler); // TODO save built in jobs
this.jobs = new ArrayList<IJob>();
for (JobDefinition jobDefinition : jobDefitions) {
IJob job = jobCreator.createJob(jobDefinition, engine, taskScheduler);
if (job != null) {
jobs.add(job);
}
}
}
protected List<JobDefinition> loadJobs(ISymmetricEngine engine) {
return sqlTemplate.query(getSql("loadCustomJobs"), new JobMapper());
}
@Override
public boolean isStarted() {
return started;
}
@Override
public IJob getJob(String name) {
for (IJob job : jobs) {
if (job.getName().equals(name)) {
return job;
}
}
return null;
}
/*
* Start the jobs if they are configured to be started
*/
@Override
public synchronized void startJobs() {
for (IJob job : jobs) {
if (isAutoStartConfigured(job) && isJobApplicableToNodeGroup(job)) {
job.start();
} else {
log.info("Job {} not configured for auto start", job.getName());
}
}
started = true;
}
@Override
public boolean isJobApplicableToNodeGroup(IJob job) {
String nodeGroupId = job.getJobDefinition().getNodeGroupId();
if (StringUtils.isEmpty(nodeGroupId) || nodeGroupId.equals("ALL")) {
return true;
}
return engine.getParameterService().getNodeGroupId().equals(nodeGroupId);
}
protected boolean isAutoStartConfigured(IJob job) {
String autoStartValue = null;
if (job.getDeprecatedStartParameter() != null) {
autoStartValue = engine.getParameterService().getString(job.getDeprecatedStartParameter());
}
if (StringUtils.isEmpty(autoStartValue)) {
autoStartValue = engine.getParameterService().getString(job.getJobDefinition().getStartParameter());
if (StringUtils.isEmpty(autoStartValue)) {
autoStartValue = String.valueOf(job.getJobDefinition().isDefaultAutomaticStartup());
}
}
return "1".equals(autoStartValue) || Boolean.parseBoolean(autoStartValue);
}
@Override
public synchronized void stopJobs() {
if (jobs != null) {
for (IJob job : jobs) {
job.stop();
}
Thread.interrupted();
started = false;
}
}
@Override
public synchronized void destroy() {
stopJobs();
if (taskScheduler != null) {
taskScheduler.shutdown();
}
}
@Override
public List<IJob> getJobs() {
List<IJob> sortedJobs = sortJobs(jobs);
return sortedJobs;
}
protected List<IJob> sortJobs(List<IJob> jobs) {
List<IJob> jobsSorted = new ArrayList<>();
if (jobs != null) {
jobsSorted.addAll(jobs);
Collections.sort(jobsSorted, new Comparator<IJob>() {
@Override
public int compare(IJob job1, IJob job2) {
Integer job1Started = job1.isStarted() ? 1 : 0;
Integer job2Started = job2.isStarted() ? 1 : 0;
if (job1Started == job2Started) {
return -job1.getJobDefinition().getJobType().compareTo(job2.getJobDefinition().getJobType());
} else {
return -job1Started.compareTo(job2Started);
}
}
});
}
return jobsSorted;
}
@Override
public void restartJobs() {
this.init();
this.startJobs();
}
@Override
public void saveJob(JobDefinition job) {
Object[] args = { job.getDescription(), job.getJobType().toString(),
job.getJobExpression(), job.isDefaultAutomaticStartup() ? 1 : 0, job.getDefaultSchedule(),
job.getNodeGroupId(), job.getCreateBy(), job.getLastUpdateBy(), job.getJobName() };
if (sqlTemplate.update(getSql("updateJobSql"), args) <= 0) {
sqlTemplate.update(getSql("insertJobSql"), args);
}
restartJobs();
}
@Override
public void removeJob(String name) {
Object[] args = { name };
if (sqlTemplate.update(getSql("deleteJobSql"), args) == 1) {
} else {
throw new SymmetricException("Failed to remove job " + name + ". Note that BUILT_IN jobs cannot be removed.");
}
restartJobs();
}
}
| 34.504505 | 123 | 0.615405 |
976a15c73da7c5c63b7a56e349324f24a3df6c89
| 1,203 |
package com.mooveit.fakeit.utils;
import java.util.Locale;
public class Constants {
public enum FakeitLocale {
CA("ca"),
DE("de"),
EN("en"),
ES("es"),
FA("fa"),
FI("fi-FI"),
FR("fr"),
HE("he"),
ID("id"),
IT("it"),
JA("ja"),
KO("ko"),
NB("nb-NO"),
NL("nl"),
PL("pl"),
PT("pt"),
RU("ru"),
SK("sk"),
SV("sv"),
TR("tr"),
UK("uk"),
VI("vi"),
ZH("zh-CN");
private Locale locale;
FakeitLocale(String locale) {
switch (locale) {
case ("fi-FI"):
this.locale = new Locale("fi", "FI");
break;
case ("zh-CN"):
this.locale = new Locale("zh", "CN");
break;
case ("nb-NO"):
this.locale = new Locale("nb", "NO");
break;
default:
this.locale = new Locale(locale);
break;
}
}
public Locale locale() {
return locale;
}
}
}
| 21.105263 | 57 | 0.347465 |
76de6a4180272fde0de3f3aa474f895802f21aa2
| 1,783 |
package densan.s.game.sound;
import java.net.URL;
import javafx.scene.media.AudioClip;
/*
* Created on 2005/08/15
*
*/
/**
* 効果音ファイルを再生するクラス<br>
* ユーザーはSoundManagerクラスの方を使う
* @author mori
*
*/
public class SEEngine {
// 登録できるWAVEファイルの最大数
public static final int MAX_CLIPS = 256;
// WAVEファイルデータ
private static SEClip[] dataClips = new SEClip[MAX_CLIPS];
// 登録されたWAVEファイル数
private static int counter = 0;
/**
* 効果音ファイルをロード
*
* @param url
* 効果音ファイルのURL
* @return 登録した番号 登録できなかった場合は−1
*/
public static int load(URL url){
//すでに登録されてるか調べて登録されてるなら登録番号を返す
for (int i=0; i < getLoadCount(); i++) {
if (dataClips[i].getFile().equals( url.getPath())) {
return i;
}
}
if (counter == MAX_CLIPS) {
System.err.println("エラー: これ以上登録できません");
return -1;
}
// 空のクリップを作成
AudioClip clip = new AudioClip(url.toExternalForm());
// クリップを登録
dataClips[counter] = new SEClip(clip, url);
counter++;
//登録した番号を返す
return counter-1;
}
/**
* 効果音ファイルをロード
*
* @param filename
* 効果音ファイル名
* @return 登録した番号 登録できなかった場合は−1
*/
public static int load(String filename){
//URL url = WaveEngine.class.getClassLoader().getResource(filename);
URL url = ClassLoader.getSystemResource(filename);
return load(url);
}
/**
* 再生開始
*
* @param no
* 再生する効果音の番号
*/
public static void play(int no) {
if (dataClips[no] == null) {
return;
}
dataClips[no].play();
}
/**
* 停止
*
* @param no
* 停止する効果音の番号
*/
public static void stop(int no) {
if (dataClips[no] == null) {
return;
}
// 名前に対応するクリップを取得
dataClips[no].stop();
}
/**
* いくつロードされたかを返す
* @return ロードされたファイルの数
*/
public static int getLoadCount() {
return counter;
}
}
| 16.357798 | 70 | 0.615255 |
4b9f9af4abaeb89df10753d62e9d27588103acfa
| 4,048 |
package com.wrapper.spotify.methods;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.SettableFuture;
import com.wrapper.spotify.Api;
import com.wrapper.spotify.TestUtil;
import com.wrapper.spotify.models.SpotifyEntityType;
import com.wrapper.spotify.models.Track;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static junit.framework.Assert.assertEquals;
import static junit.framework.TestCase.assertNotNull;
import static junit.framework.TestCase.assertTrue;
import static junit.framework.TestCase.fail;
@RunWith(MockitoJUnitRunner.class)
public class TopTracksRequestTest {
@Test
public void shouldGetTracksResult_async() throws Exception {
final Api api = Api.DEFAULT_API;
final TopTracksRequest request = api.getTopTracksForArtist("43ZHCT0cAZBISjO8DG9PnE", "GB")
.httpManager(TestUtil.MockedHttpManager.returningJson("tracks-for-artist.json"))
.build();
final CountDownLatch asyncCompleted = new CountDownLatch(1);
final SettableFuture<List<Track>> tracksFuture = request.getAsync();
Futures.addCallback(tracksFuture, new FutureCallback<List<Track>>() {
@Override
public void onSuccess(List<Track> tracks) {
assertTrue(tracks.size() > 0);
Track firstTrack = tracks.get(0);
assertNotNull(firstTrack.getAlbum());
assertNotNull(firstTrack.getArtists());
assertNotNull(firstTrack.getAvailableMarkets());
assertTrue(firstTrack.getDiscNumber() > 0);
assertTrue(firstTrack.getDuration() > 0);
assertNotNull(firstTrack.isExplicit());
assertNotNull(firstTrack.getExternalIds());
String id = firstTrack.getId();
assertNotNull(firstTrack.getId());
assertEquals("https://open.spotify.com/track/" + id, firstTrack.getExternalUrls().get("spotify"));
assertEquals("https://api.spotify.com/v1/tracks/" + id, firstTrack.getHref());
assertTrue(firstTrack.getPopularity() >= 0 && firstTrack.getPopularity() <= 100);
assertNotNull(firstTrack.getPreviewUrl());
assertTrue(firstTrack.getTrackNumber() >= 0);
assertEquals(SpotifyEntityType.TRACK, firstTrack.getType());
assertEquals("spotify:track:" + id, firstTrack.getUri());
asyncCompleted.countDown();
}
@Override
public void onFailure(Throwable throwable) {
fail("Failed to resolve future");
}
});
asyncCompleted.await(1, TimeUnit.SECONDS);
}
@Test
public void shouldGetTracksResult_sync() throws Exception {
final Api api = Api.DEFAULT_API;
final TopTracksRequest request = api.getTopTracksForArtist("43ZHCT0cAZBISjO8DG9PnE", "GB")
.httpManager(TestUtil.MockedHttpManager.returningJson("tracks-for-artist.json"))
.build();
final List<Track> tracks = request.get();
assertTrue(tracks.size() > 0);
Track firstTrack = tracks.get(0);
assertNotNull(firstTrack.getAlbum());
assertNotNull(firstTrack.getArtists());
assertNotNull(firstTrack.getAvailableMarkets());
assertTrue(firstTrack.getDiscNumber() > 0);
assertTrue(firstTrack.getDuration() > 0);
assertNotNull(firstTrack.isExplicit());
assertNotNull(firstTrack.getExternalIds());
String id = firstTrack.getId();
assertNotNull(firstTrack.getId());
assertEquals("https://open.spotify.com/track/" + id, firstTrack.getExternalUrls().get("spotify"));
assertEquals("https://api.spotify.com/v1/tracks/" + id, firstTrack.getHref());
assertTrue(firstTrack.getPopularity() >= 0 && firstTrack.getPopularity() <= 100);
assertNotNull(firstTrack.getPreviewUrl());
assertTrue(firstTrack.getTrackNumber() >= 0);
assertEquals(SpotifyEntityType.TRACK, firstTrack.getType());
assertEquals("spotify:track:" + id, firstTrack.getUri());
}
}
| 36.468468 | 106 | 0.722085 |
2b0b071cff40c6d2252edc54e4f5056bd659d371
| 2,729 |
package de.ellpeck.naturesaura.chunk.effect;
import de.ellpeck.naturesaura.ModConfig;
import de.ellpeck.naturesaura.NaturesAura;
import de.ellpeck.naturesaura.api.aura.chunk.IAuraChunk;
import de.ellpeck.naturesaura.api.aura.chunk.IDrainSpotEffect;
import de.ellpeck.naturesaura.api.aura.type.IAuraType;
import net.minecraft.entity.IAngerable;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk;
import java.util.List;
public class AngerEffect implements IDrainSpotEffect {
public static final ResourceLocation NAME = new ResourceLocation(NaturesAura.MOD_ID, "anger");
private AxisAlignedBB bb;
private boolean calcValues(World world, BlockPos pos, Integer spot) {
if (spot >= 0)
return false;
int aura = IAuraChunk.getAuraInArea(world, pos, 50);
if (aura > 0)
return false;
int dist = Math.min(Math.abs(aura) / 50000, 75);
if (dist < 10)
return false;
this.bb = new AxisAlignedBB(pos).grow(dist);
return true;
}
@Override
public ActiveType isActiveHere(PlayerEntity player, Chunk chunk, IAuraChunk auraChunk, BlockPos pos, Integer spot) {
if (!this.calcValues(player.world, pos, spot))
return ActiveType.INACTIVE;
if (!this.bb.contains(player.getPositionVec()))
return ActiveType.INACTIVE;
return ActiveType.ACTIVE;
}
@Override
public ItemStack getDisplayIcon() {
return new ItemStack(Items.FIRE_CHARGE);
}
@Override
public void update(World world, Chunk chunk, IAuraChunk auraChunk, BlockPos pos, Integer spot) {
if (world.getGameTime() % 100 != 0)
return;
if (!this.calcValues(world, pos, spot))
return;
List<LivingEntity> entities = world.getEntitiesWithinAABB(LivingEntity.class, this.bb);
for (LivingEntity entity : entities) {
if (!(entity instanceof IAngerable))
continue;
PlayerEntity player = world.getClosestPlayer(entity, 25);
if (player == null)
continue;
((IAngerable) entity).setAttackTarget(player);
}
}
@Override
public boolean appliesHere(Chunk chunk, IAuraChunk auraChunk, IAuraType type) {
return ModConfig.instance.angerEffect.get();
}
@Override
public ResourceLocation getName() {
return NAME;
}
}
| 33.691358 | 120 | 0.679736 |
7260fde5ef5b309d776e661c713532d9ca13cabb
| 2,697 |
/*
* Copyright 2014-2015 Open Networking Laboratory
*
* 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.onosproject.mfwd.cli;
import org.apache.karaf.shell.commands.Argument;
import org.apache.karaf.shell.commands.Command;
import org.onosproject.cli.AbstractShellCommand;
import org.onosproject.mfwd.impl.McastConnectPoint;
import org.onosproject.mfwd.impl.McastRouteBase;
import org.onosproject.mfwd.impl.McastRouteTable;
/**
* Installs a source, multicast group flow.
*/
@Command(scope = "onos", name = "mcast-join",
description = "Installs a source, multicast group flow")
public class McastJoinCommand extends AbstractShellCommand {
@Argument(index = 0, name = "sAddr",
description = "IP Address of the multicast source. '*' can be used for any source (*, G) entry",
required = true, multiValued = false)
String sAddr = null;
@Argument(index = 1, name = "gAddr",
description = "IP Address of the multicast group",
required = true, multiValued = false)
String gAddr = null;
@Argument(index = 2, name = "ingressPort",
description = "Ingress port and Egress ports",
required = false, multiValued = false)
String ingressPort = null;
@Argument(index = 3, name = "ports",
description = "Ingress port and Egress ports",
required = false, multiValued = true)
String[] ports = null;
@Override
protected void execute() {
McastRouteTable mrib = McastRouteTable.getInstance();
McastRouteBase mr = mrib.addRoute(sAddr, gAddr);
// Port format "of:0000000000000023/4"
if (ingressPort != null) {
String inCP = ingressPort;
log.debug("Ingress port provided: " + inCP);
mr.addIngressPoint(inCP);
}
for (int i = 0; i < ports.length; i++) {
String egCP = ports[i];
log.debug("Egress port provided: " + egCP);
mr.addEgressPoint(egCP, McastConnectPoint.JoinSource.STATIC);
}
print("Added the mcast route");
}
}
| 36.945205 | 111 | 0.640341 |
af4707e92fb956b984b445b600242b6777c7d4e0
| 2,883 |
package com.qht.blog2.BaseAdapter.BaseSlideRecycleView.holder;
import android.animation.ValueAnimator;
import android.view.View;
import com.chad.library.adapter.base.BaseViewHolder;
import com.qht.blog2.BaseAdapter.BaseSlideRecycleView.ISlide;
import com.qht.blog2.BaseAdapter.BaseSlideRecycleView.helper.SlideAnimationHelper;
/**
* Created by zhan on 2017/2/6.
*/
public abstract class SlideViewHolder extends BaseViewHolder implements ISlide {
private static final int DURATION_OPEN = 300;
private static final int DURATION_CLOSE = 150;
private static final int NORMAL_OFFSET = 50;
private SlideAnimationHelper mSlideAnimationHelper;
private OpenUpdateListener mOpenUpdateListener;
private CloseUpdateListener mCloseUpdateListener;
protected int mOffset;
public SlideViewHolder(View itemView) {
super(itemView);
mOffset = SlideAnimationHelper.getOffset(itemView.getContext(), NORMAL_OFFSET);
mSlideAnimationHelper = new SlideAnimationHelper();
}
public void setOffset(int offset) {
mOffset = SlideAnimationHelper.getOffset(itemView.getContext(), offset);
}
public int getOffset() {
return mOffset;
}
//keep change state
public void onBindSlide(View targetView) {
switch (mSlideAnimationHelper.getState()) {
case SlideAnimationHelper.STATE_CLOSE:
targetView.scrollTo(0, 0);
onBindSlideClose(SlideAnimationHelper.STATE_CLOSE);
break;
case SlideAnimationHelper.STATE_OPEN:
targetView.scrollTo(-mOffset, 0);
doAnimationSetOpen(SlideAnimationHelper.STATE_OPEN);
break;
}
}
@Override public void slideOpen() {
if (mOpenUpdateListener == null) {
mOpenUpdateListener = new OpenUpdateListener();
}
mSlideAnimationHelper.openAnimation(DURATION_OPEN, mOpenUpdateListener);
}
@Override public void slideClose() {
if (mCloseUpdateListener == null) {
mCloseUpdateListener = new CloseUpdateListener();
}
mSlideAnimationHelper.closeAnimation(DURATION_CLOSE, mCloseUpdateListener);
}
public abstract void doAnimationSet(int offset, float fraction);
public abstract void onBindSlideClose(int state);
public abstract void doAnimationSetOpen(int state);
private class OpenUpdateListener implements ValueAnimator.AnimatorUpdateListener {
@Override public void onAnimationUpdate(ValueAnimator animation) {
float fraction = animation.getAnimatedFraction();
int endX = (int) (-mOffset * fraction);
doAnimationSet(endX, fraction);
}
}
private class CloseUpdateListener implements ValueAnimator.AnimatorUpdateListener {
@Override public void onAnimationUpdate(ValueAnimator animation) {
float fraction = animation.getAnimatedFraction();
fraction = 1.0f - fraction;
int endX = (int) (-mOffset * fraction);
doAnimationSet(endX, fraction);
}
}
}
| 29.121212 | 85 | 0.747832 |
a5a5bdf7a9e4f37afde27d14f90ea1874a814b07
| 2,441 |
package com.tyrfing.games.id18.test.edit.network;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.net.UnknownHostException;
import org.junit.Test;
import com.tyrfing.games.id18.edit.battle.action.EndTurnAction;
import com.tyrfing.games.id18.edit.network.ActionSerializer;
import com.tyrfing.games.id18.edit.network.NetworkActionProvider;
import com.tyrfing.games.id18.model.network.NetworkActionMessage;
import com.tyrfing.games.id18.model.unit.Faction;
import com.tyrfing.games.tyrlib3.edit.action.IAction;
import com.tyrfing.games.tyrlib3.edit.action.IActionRequester;
import com.tyrfing.games.tyrlib3.model.networking.Connection;
import com.tyrfing.games.tyrlib3.model.networking.INetworkListener;
import com.tyrfing.games.tyrlib3.model.networking.Network;
public class NetworkActionProviderTest {
public static final int SLEEP_TIME = 500;
private class TestActionRequester implements IActionRequester {
protected IAction requestedAction;
@Override
public void onProvideRequest(IAction action) {
this.requestedAction = action;
}
}
@Test
public void testRequestAction() throws UnknownHostException, IOException, InterruptedException {
final int PORT = 666;
Faction faction = new Faction();
Network hostNetwork = new Network();
Network clientNetwork = new Network();
hostNetwork.host(PORT);
INetworkListener clientListener = new INetworkListener() {
@Override
public void onReceivedData(Connection c, Object o) {
c.send(NetworkActionMessage.IConstantMessages.END_TURN_ACTION);
}
@Override
public void onNewConnection(Connection c) {
}
@Override
public void onConnectionLost(Connection c) {
}
};
clientNetwork.addListener(clientListener);
clientNetwork.connectTo(hostNetwork.getServer().getServerName(), PORT);
Thread.sleep(SLEEP_TIME);
Connection connection = hostNetwork.getConnection(0);
NetworkActionProvider networkActionProvider = new NetworkActionProvider(new ActionSerializer(null), faction, connection);
TestActionRequester requester = new TestActionRequester();
networkActionProvider.requestAction(requester);
Thread.sleep(SLEEP_TIME);
assertTrue("Received requested action", requester.requestedAction instanceof EndTurnAction);
hostNetwork.close();
clientNetwork.close();
}
}
| 30.135802 | 124 | 0.757067 |
41984d5c6fc8f6898a0a222c9c42ed96d63da0ed
| 179 |
package org.corfudb.runtime.exceptions;
/**
* Represents an exception which failed deserialization.
*/
public class DeserializationFailedException extends RuntimeException {
}
| 22.375 | 70 | 0.810056 |
574eb8afd5b283b5d4a34aad68b710f42a477a13
| 2,225 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.drill.exec.oauth;
public interface Tokens {
/**
* Key of {@link this} tokens table.
*/
String getKey();
/**
* Gets the current access token.
*
* @return The current access token
*/
String getAccessToken();
/**
* Sets the access token.
*
* @param accessToken Sets the access token.
*/
void setAccessToken(String accessToken);
String getRefreshToken();
void setRefreshToken(String refreshToken);
/**
* Returns value from tokens table that corresponds to provided plugin.
*
* @param token token of the value to obtain
* @return value from token table that corresponds to provided plugin
*/
String get(String token);
/**
* Associates provided token with provided plugin in token table.
*
* @param token Token of the value to associate with
* @param value Value that will be associated with provided alias
* @param replace Whether existing value for the same token should be replaced
* @return {@code true} if provided token was associated with
* the provided value in tokens table
*/
boolean put(String token, String value, boolean replace);
/**
* Removes value for specified token from tokens table.
* @param token token of the value to remove
* @return {@code true} if the value associated with
* provided token was removed from the tokens table.
*/
boolean remove(String token);
}
| 31.338028 | 80 | 0.713258 |
83d0489ea1be99eaec9d8f2dd63bb845b570ace9
| 2,406 |
/*
* The MIT License
*
* Copyright (c) 2012 The Broad Institute
*
* 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 picard.illumina.parser;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
/**
* For "non-cycle" files (files that have multiple cycles per file). Maps a Tile -> File
* @author jburke@broadinstitute.org
*/
class IlluminaFileMap extends TreeMap<Integer, File> {
/** Return a file map that includes only the tiles listed */
public IlluminaFileMap keep(final List<Integer> tilesToKeep) {
final IlluminaFileMap fileMap = new IlluminaFileMap();
for(final Integer tile : tilesToKeep) {
final File file = this.get(tile);
if(file != null) {
fileMap.put(tile, file);
}
}
return fileMap;
}
/**
* Return the List of Files in order starting at the given tile and containing all files with tile numbers greater than startingTile that
* are within this map
* @param startingTile The first File in the returned list will correspond to this tile
* @return A List of files for all tiles >= startingTile that are contained in this FileMap
*/
public List<File> getFilesStartingAt(final int startingTile) {
return new ArrayList<File>(this.tailMap(startingTile).values());
}
}
| 40.779661 | 141 | 0.714464 |
b8085684d69b8e61e688a0f53d287af09351b6c7
| 940 |
package de.peeeq.wurstscript.types;
import de.peeeq.wurstscript.ast.TypeParamDef;
import de.peeeq.wurstscript.parser.WPos;
import fj.Ord;
import fj.Ordering;
/**
*
*/
public class TypeParamOrd {
private static final Ord<TypeParamDef> instance = Ord.ord((TypeParamDef x, TypeParamDef y) -> {
int c1 = x.getName().compareTo(y.getName());
if (c1 < 0) {
return Ordering.LT;
} else if (c1 > 0) {
return Ordering.GT;
}
return compareSource(x.getSource(), y.getSource());
});
public static Ord<TypeParamDef> instance() {
return instance;
}
private static Ordering compareSource(WPos x, WPos y) {
int c1 = x.getFile().compareTo(y.getFile());
if (c1 < 0) {
return Ordering.LT;
} else if (c1 > 0) {
return Ordering.GT;
}
return Ordering.fromInt(y.getLeftPos() - x.getLeftPos());
}
}
| 25.405405 | 99 | 0.588298 |
7103aa3df987371988dfb4bd07e9527e368f5f8c
| 1,758 |
package br.com.projectteste.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import br.com.projectteste.entity.Medicamento;
import br.com.projectteste.entity.Paciente;
@Repository
@Transactional
public class MedicamentoDao {
public void createMedicamento(Medicamento medicamento){
entityManager.persist(medicamento);
return;
}
public void delete(Medicamento medicamento) {
if (entityManager.contains(medicamento))
entityManager.remove(medicamento);
else
entityManager.remove(entityManager.merge(medicamento));
return;
}
public void update(Medicamento medicamento) {
if(!entityManager.contains(medicamento)){
Medicamento med = entityManager.find(medicamento.getClass(), medicamento.getId());
med.setNomeMedicamento(medicamento.getNomeMedicamento());
medicamento = med;
}
entityManager.merge(medicamento);
return;
}
public Paciente getByNomeMedicamento(String nomeMedicamento){
return (Paciente) entityManager.createQuery(
"from Medicamento where nome_medicamento = :nomeMedicamento")
.setParameter("nomeMedicamento", nomeMedicamento)
.getSingleResult();
}
public Medicamento getById(long id) {
return entityManager.find(Medicamento.class, id);
}
@SuppressWarnings("unchecked")
public List <Medicamento> getAll() {
return entityManager.createQuery("from Medicamento").getResultList();
}
@PersistenceContext
private EntityManager entityManager;
}
| 25.852941 | 90 | 0.71843 |
351169a4c0912a4a35d8d3484b142b2fd1fd3a43
| 16,836 |
/**
*
*/
package trobbie.bootrestsimple.controller;
import java.util.Optional;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentMatchers;
import org.mockito.Mockito;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import com.fasterxml.jackson.databind.ObjectMapper;
import trobbie.bootrestsimple.dao.TestDatabase;
import trobbie.bootrestsimple.model.Resource;
import trobbie.bootrestsimple.service.DefaultResourceService;
import trobbie.bootrestsimple.service.ResourceService;
/**
* Test DefaultResourceController implementation of the ResourceController interface.
* An example resource model is needed to run the tests.
*
* Test method syntax: MethodName_StateUnderTest_ExpectedBehavior
*
* @author Trevor Robbie
*
*/
public abstract class DefaultResourceControllerTest<T extends Resource<ID>, ID> {
@Autowired
private MockMvc mockMvc;
@MockBean
private DefaultResourceService<T, ID> resourceService;
@Autowired
private TestDatabase<T, ID> testDatabase;
private static String asJsonString(final Object obj) {
try {
return new ObjectMapper().writeValueAsString(obj);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Before
public void resetData() {
this.testDatabase.resetData();
}
@Test
public void getResources_RequestedOnEmptyData_Return200AndEmptyList() throws Exception {
Mockito.when(resourceService.getResources())
.thenReturn(this.testDatabase.getEmptyResources());
RequestBuilder requestBuilder = MockMvcRequestBuilders
.get(DefaultResourceController.RELATIVE_PATH)
.accept(MediaType.APPLICATION_JSON)
.characterEncoding("UTF-8");
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
String expected = "[]";
Assert.assertEquals(HttpStatus.OK.value(), result.getResponse().getStatus());
JSONAssert.assertEquals(expected, result.getResponse().getContentAsString(), false);
}
@Test
public void getResources_RequestedOnNonEmptyData_Return200WithList() throws Exception {
Mockito.when(resourceService.getResources())
.thenReturn(this.testDatabase.getResources());
RequestBuilder requestBuilder = MockMvcRequestBuilders
.get(DefaultResourceController.RELATIVE_PATH)
.accept(MediaType.APPLICATION_JSON)
.characterEncoding("UTF-8");
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
String expected = "[{id:1,name:MockResource1},{id:2,name:MockResource2}]";
Assert.assertEquals(HttpStatus.OK.value(), result.getResponse().getStatus());
JSONAssert.assertEquals(expected, result.getResponse().getContentAsString(), false);
}
@Test
public void getResource_IdFound_ReturnResource() throws Exception {
Mockito.when(resourceService.getResource(Mockito.any()))
.thenReturn(Optional.of(this.testDatabase.getResource(1)));
RequestBuilder requestBuilder = MockMvcRequestBuilders
.get(DefaultResourceController.RELATIVE_PATH + "/" + this.testDatabase.getResource(1).getId())
.accept(MediaType.APPLICATION_JSON)
.characterEncoding("UTF-8");
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
String expected = asJsonString(this.testDatabase.getResource(1));
Assert.assertEquals(HttpStatus.OK.value(), result.getResponse().getStatus());
JSONAssert.assertEquals(expected, result.getResponse().getContentAsString(), false);
}
@Test
public void getResource_IdUnknown_Return404NotFound() throws Exception {
Long unknownId = 99999L;
Mockito.when(resourceService.getResource(Mockito.any()))
.thenReturn(Optional.empty());
RequestBuilder requestBuilder = MockMvcRequestBuilders
.get(DefaultResourceController.RELATIVE_PATH + "/" + unknownId)
.accept(MediaType.APPLICATION_JSON)
.characterEncoding("UTF-8");
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
Assert.assertEquals(HttpStatus.NOT_FOUND.value(), result.getResponse().getStatus());
}
@Test
public void getResource_InvalidPathId_Return400BadRequest() throws Exception {
Mockito.when(resourceService.getResource(Mockito.any()))
.thenReturn(null);
RequestBuilder requestBuilder = MockMvcRequestBuilders
.get(DefaultResourceController.RELATIVE_PATH + "/invalid_typed_id") // change this if String id is actually ok
.accept(MediaType.APPLICATION_JSON)
.characterEncoding("UTF-8");
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
Assert.assertEquals(HttpStatus.BAD_REQUEST.value(), result.getResponse().getStatus());
}
@Test
public void getResource_HeadRequest_ActiveAndNoBody() throws Exception {
Mockito.when(resourceService.getResource(Mockito.any()))
.thenReturn(Optional.of(this.testDatabase.getResource(1)));
RequestBuilder requestBuilder = MockMvcRequestBuilders
.head(DefaultResourceController.RELATIVE_PATH + "/" + this.testDatabase.getResource(1).getId())
.accept(MediaType.APPLICATION_JSON)
.characterEncoding("UTF-8");
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
// Spring 4.3+ has implicit support for HEAD. There is no need to test their implementation.
// Here we are testing if it is active for our API.
Assert.assertEquals(HttpStatus.OK.value(), result.getResponse().getStatus());
Assert.assertEquals("Should not return message-body in response", 0, result.getResponse().getContentAsString().length());
}
@Test
public void replaceResource_ExistingResource_ReturnSameResource() throws Exception {
Resource<ID> mockResource2 = this.testDatabase.changeResource(2);
ResourceService.ReplaceResourceResult<T> mockServiceresult = new ResourceService.ReplaceResourceResult<T>(
this.testDatabase.getResource(2), false, null);
Mockito.when(resourceService.replaceResource(ArgumentMatchers.anyString(), ArgumentMatchers.any()))
.thenReturn(Optional.of(mockServiceresult));
RequestBuilder requestBuilder = MockMvcRequestBuilders
.put(DefaultResourceController.RELATIVE_PATH + "/" + this.testDatabase.getResource(2).getId())
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.characterEncoding("UTF-8")
.content(asJsonString(mockResource2));
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
String expected = asJsonString(mockResource2);
Assert.assertEquals(HttpStatus.OK.value(), result.getResponse().getStatus());
JSONAssert.assertEquals(expected, result.getResponse().getContentAsString(), false);
}
@Test
public void replaceResource_RequestNewResource_Return201Created() throws Exception {
ResourceService.ReplaceResourceResult<T> mockServiceresult = new ResourceService.ReplaceResourceResult<T>(
this.testDatabase.getResource(2), true, null);
Mockito.when(resourceService.replaceResource(ArgumentMatchers.anyString(), ArgumentMatchers.any()))
.thenReturn(Optional.of(mockServiceresult));
RequestBuilder requestBuilder = MockMvcRequestBuilders
.put(DefaultResourceController.RELATIVE_PATH + "/" + this.testDatabase.getResource(2).getId())
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.characterEncoding("UTF-8")
.content(asJsonString(this.testDatabase.getResource(2)));
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
Assert.assertEquals(HttpStatus.CREATED.value(), result.getResponse().getStatus());
}
@Test
public void replaceResource_IdMismatch_ReturnSuccess() throws Exception {
ResourceService.ReplaceResourceResult<T> mockServiceresult = new ResourceService.ReplaceResourceResult<T>(
this.testDatabase.getResource(2), false, null);
Mockito.when(resourceService.replaceResource(ArgumentMatchers.anyString(), ArgumentMatchers.any()))
.thenReturn(Optional.of(mockServiceresult));
RequestBuilder requestBuilder = MockMvcRequestBuilders
.put(DefaultResourceController.RELATIVE_PATH + "/" + this.testDatabase.getResource(1).getId())
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.characterEncoding("UTF-8")
.content(asJsonString(this.testDatabase.getResource(2)));
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
Assert.assertEquals(HttpStatus.OK.value(), result.getResponse().getStatus());
}
@Test
public void replaceResource_InvalidPathId_Return400BadRequest() throws Exception {
ResourceService.ReplaceResourceResult<T> mockServiceresult = new ResourceService.ReplaceResourceResult<T>(
null, false, "Id type is invalid.");
Mockito.when(resourceService.replaceResource(Mockito.anyString(), Mockito.any()))
.thenReturn(Optional.of(mockServiceresult));
RequestBuilder requestBuilder = MockMvcRequestBuilders
.put(DefaultResourceController.RELATIVE_PATH + "/invalid_typed_id") // change this if String id is actually ok
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.characterEncoding("UTF-8")
.content(asJsonString(this.testDatabase.getResource(2)));
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
Assert.assertEquals(HttpStatus.BAD_REQUEST.value(), result.getResponse().getStatus());
}
@Test
public void replaceResource_RequestWithEmptyBody_Return400BadRequest() throws Exception {
// should not call service layer at all
Mockito.when(resourceService.replaceResource(ArgumentMatchers.anyString(), ArgumentMatchers.any()))
.thenThrow(new RuntimeException());
RequestBuilder requestBuilder = MockMvcRequestBuilders
.put(DefaultResourceController.RELATIVE_PATH + "/" + this.testDatabase.getResource(2).getId())
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.characterEncoding("UTF-8")
.content("");
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
Assert.assertEquals(HttpStatus.BAD_REQUEST.value(), result.getResponse().getStatus());
}
@Test
public void replaceResource_RequestWithInvalidBody_Return400BadRequest() throws Exception {
// should not call service layer at all
Mockito.when(resourceService.replaceResource(ArgumentMatchers.anyString(), ArgumentMatchers.any()))
.thenThrow(new RuntimeException());
RequestBuilder requestBuilder = MockMvcRequestBuilders
.put(DefaultResourceController.RELATIVE_PATH + "/" + this.testDatabase.getResource(2).getId())
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.characterEncoding("UTF-8")
.content("[_id='invalidentity'");
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
Assert.assertEquals(HttpStatus.BAD_REQUEST.value(), result.getResponse().getStatus());
}
@Test
public void replaceResource_UnknownServerError_Return500InternalServerError() throws Exception {
Mockito.when(resourceService.replaceResource(ArgumentMatchers.anyString(), ArgumentMatchers.any()))
.thenReturn(Optional.empty());
RequestBuilder requestBuilder = MockMvcRequestBuilders
.put(DefaultResourceController.RELATIVE_PATH + "/" + this.testDatabase.getResource(2).getId())
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.characterEncoding("UTF-8")
.content(asJsonString(this.testDatabase.getResource(2)));
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR.value(), result.getResponse().getStatus());
}
@Test
public void insertResource_RequestNewResource_Return201Created() throws Exception {
Integer new_index = this.testDatabase.saveResource(this.testDatabase.newUnsavedResource());
Mockito.when(resourceService.insertResource(ArgumentMatchers.any()))
.thenReturn(Optional.of(this.testDatabase.getResource(new_index)));
// temporarily assign id=null to get the JSON body for the request
Resource<ID> new_resource = this.testDatabase.getResource(new_index);
ID new_id = new_resource.getId();
new_resource.setId(null);
String jsonResourceWithNullId = asJsonString(new_resource);
new_resource.setId(new_id); // reassigned
RequestBuilder requestBuilder = MockMvcRequestBuilders
.post(DefaultResourceController.RELATIVE_PATH)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.characterEncoding("UTF-8")
.content(jsonResourceWithNullId);
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
Assert.assertEquals(HttpStatus.CREATED.value(), result.getResponse().getStatus());
Resource<ID> resource_result = testDatabase.asResource(result.getResponse().getContentAsString());
Assert.assertEquals("Id expected to be assigned", resource_result.getId(), new_resource.getId());
}
@Test
public void insertResource_RequestResourceIdAssigned_Return400BadRequest() throws Exception {
Mockito.when(resourceService.insertResource(ArgumentMatchers.any()))
.thenThrow(new RuntimeException());
RequestBuilder requestBuilder = MockMvcRequestBuilders
.post(DefaultResourceController.RELATIVE_PATH)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.characterEncoding("UTF-8")
.content(asJsonString(this.testDatabase.getResource(1)));
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
Assert.assertEquals("Expected 400 response when resource id already specified", HttpStatus.BAD_REQUEST.value(), result.getResponse().getStatus());
}
@Test
public void insertResource_RequestUsingUnsupportedMediaType_Return415() throws Exception {
Mockito.when(resourceService.insertResource(ArgumentMatchers.any()))
.thenThrow(new RuntimeException());
RequestBuilder requestBuilder = MockMvcRequestBuilders
.post(DefaultResourceController.RELATIVE_PATH)
.contentType(MediaType.APPLICATION_XML)
.accept(MediaType.APPLICATION_JSON)
.characterEncoding("UTF-8")
.content("<unsupported></unsupported>");
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
Assert.assertEquals("Expected 415 response when sending XML in request body", HttpStatus.UNSUPPORTED_MEDIA_TYPE.value(), result.getResponse().getStatus());
}
@Test
public void insertResource_UnknownServerError_Return500InternalServerError() throws Exception {
Mockito.when(resourceService.insertResource(ArgumentMatchers.any()))
.thenReturn(Optional.empty());
RequestBuilder requestBuilder = MockMvcRequestBuilders
.post(DefaultResourceController.RELATIVE_PATH)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.characterEncoding("UTF-8")
.content(asJsonString(this.testDatabase.newUnsavedResource()));
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
Assert.assertEquals(HttpStatus.INTERNAL_SERVER_ERROR.value(), result.getResponse().getStatus());
}
@Test
public void deleteResource_ExistingResource_Return204() throws Exception {
Mockito.when(resourceService.getResource(this.testDatabase.getResource(1).getId().toString()))
.thenReturn(Optional.of(this.testDatabase.getResource(1)));
Mockito.when(resourceService.deleteResource(this.testDatabase.getResource(1).getId().toString()))
.thenReturn(Boolean.TRUE);
RequestBuilder requestBuilder = MockMvcRequestBuilders
.delete(DefaultResourceController.RELATIVE_PATH + "/" + this.testDatabase.getResource(1).getId())
.contentType(MediaType.APPLICATION_JSON)
.characterEncoding("UTF-8");
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
Assert.assertEquals("Expected 204 No Content when deleting existing resource",
HttpStatus.NO_CONTENT.value(), result.getResponse().getStatus());
}
@Test
public void deleteResource_NonExistingResource_Return404() throws Exception {
Resource<ID> res = this.testDatabase.newUnsavedResource();
res.setId(this.testDatabase.getIdNeverExist());
Mockito.when(resourceService.getResource(res.getId().toString()))
.thenReturn(Optional.empty());
Mockito.when(resourceService.deleteResource(ArgumentMatchers.any()))
.thenThrow(new RuntimeException());
RequestBuilder requestBuilder = MockMvcRequestBuilders
.delete(DefaultResourceController.RELATIVE_PATH + "/" + res.getId())
.contentType(MediaType.APPLICATION_JSON)
.characterEncoding("UTF-8");
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
Assert.assertEquals("Expected 404 Not Found when deleting non-existing resource",
HttpStatus.NOT_FOUND.value(), result.getResponse().getStatus());
}
}
| 38.438356 | 157 | 0.785697 |
bb1fb4fe5951c5e0f222fbe91dc92f0d3e864436
| 563 |
__________________________________________________________________________________________________
sample 0 ms submission
class Solution {
public boolean divisorGame(int N) {
return (N%2==0);
}
}
__________________________________________________________________________________________________
sample 31560 kb submission
class Solution {
public boolean divisorGame(int N) {
if ((N & 1) == 0) return true;
return false;
}
}
__________________________________________________________________________________________________
| 33.117647 | 98 | 0.804618 |
8d234e3c9a9dccec1f51624a4a9eacdfdfbcc778
| 7,193 |
package org.estatio.module.capex.dom.payment;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Comparator;
import javax.inject.Inject;
import javax.jdo.annotations.Column;
import javax.jdo.annotations.DatastoreIdentity;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.NotPersistent;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Queries;
import javax.jdo.annotations.Query;
import javax.jdo.annotations.Unique;
import javax.jdo.annotations.Uniques;
import javax.jdo.annotations.Version;
import javax.jdo.annotations.VersionStrategy;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.apache.isis.applib.annotation.Action;
import org.apache.isis.applib.annotation.ActionLayout;
import org.apache.isis.applib.annotation.Contributed;
import org.apache.isis.applib.annotation.DomainObject;
import org.apache.isis.applib.annotation.Programmatic;
import org.apache.isis.applib.annotation.PropertyLayout;
import org.apache.isis.applib.annotation.SemanticsOf;
import org.apache.isis.applib.annotation.Where;
import org.apache.isis.schema.utils.jaxbadapters.PersistentEntityAdapter;
import org.isisaddons.module.security.dom.tenancy.ApplicationTenancy;
import org.estatio.module.base.dom.UdoDomainObject2;
import org.estatio.module.capex.dom.invoice.IncomingInvoice;
import org.estatio.module.capex.dom.invoice.IncomingInvoiceRepository;
import org.estatio.module.capex.dom.invoice.approval.IncomingInvoiceApprovalState;
import org.estatio.module.currency.dom.Currency;
import org.estatio.module.financial.dom.BankAccount;
import org.estatio.module.party.dom.Party;
import lombok.Getter;
import lombok.Setter;
@PersistenceCapable(
identityType = IdentityType.DATASTORE,
schema = "dbo",
table = "PaymentLine"
)
@DatastoreIdentity(
strategy = IdGeneratorStrategy.IDENTITY,
column = "id")
@Version(
strategy = VersionStrategy.VERSION_NUMBER,
column = "version")
@Queries({
@Query(
name = "findByInvoice", language = "JDOQL",
value = "SELECT "
+ "FROM org.estatio.module.capex.dom.payment.PaymentLine "
+ "WHERE invoice == :invoice "),
@Query(
name = "findByInvoiceAndBatchApprovalState", language = "JDOQL",
value = "SELECT "
+ "FROM org.estatio.module.capex.dom.payment.PaymentLine "
+ "WHERE invoice == :invoice "
+ " && batch.approvalState == :approvalState "),
@Query(
name = "findByInvoiceAndBatchApprovalState", language = "JDOQL",
value = "SELECT "
+ "FROM org.estatio.module.capex.dom.payment.PaymentLine "
+ "WHERE invoice == :invoice "
+ " && batch.approvalState == :approvalState "),
@Query(
name = "findFromRequestedExecutionDate", language = "JDOQL",
value = "SELECT "
+ "FROM org.estatio.module.capex.dom.payment.PaymentLine "
+ "WHERE batch.requestedExecutionDate >= :fromRequestedExecutionDate ")
})
@Uniques({
@Unique(
name = "PaymentLine_batch_sequence", members = {"batch", "sequence"}
)
})
@DomainObject(
objectType = "payment.PaymentLine"
)
@XmlJavaTypeAdapter(PersistentEntityAdapter.class)
public class PaymentLine extends UdoDomainObject2<PaymentLine> {
public PaymentLine() {
super("batch, sequence, invoice");
}
public PaymentLine(
final PaymentBatch batch,
final int sequence,
final IncomingInvoice invoice,
final BigDecimal transferAmount,
final String remittanceInformation){
this();
this.batch = batch;
this.sequence = sequence;
this.invoice = invoice;
this.creditorBankAccount = invoice.getBankAccount();
this.remittanceInformation = remittanceInformation;
this.amount = transferAmount;
}
public String title() {
return String.format("%s: %s for %s",
getCreditorBankAccount().getIban(),
new DecimalFormat("0.00").format(getAmount()),
getInvoice().getInvoiceNumber());
}
@Column(allowsNull = "false", name = "batchId")
@Getter @Setter
@PropertyLayout(hidden = Where.REFERENCES_PARENT)
private PaymentBatch batch;
/**
* Document > PmtInf > CdtTrfTxInf > PmtId > EndToEndId
*
* appends to the PaymentBatch's PmtInfId somehow
*/
@Getter @Setter
private int sequence;
/**
* Document > PmtInf > CdtTrfTxInf > CdtrAcct > Id > IBAN
* Document > PmtInf > CdtTrfTxInf > CdtrAgt > FinInstnId > BIC
*/
@Column(allowsNull = "false", name = "creditorBankAccountId")
@Getter @Setter
@PropertyLayout(hidden = Where.REFERENCES_PARENT)
private BankAccount creditorBankAccount;
@NotPersistent
public Currency getCurrency() {
return getInvoice().getCurrency();
}
/**
* Document > PmtInf > CdtTrfTxInf > Amt > InstdAmt
*/
@Column(allowsNull = "false", scale = 2)
@Getter @Setter
private BigDecimal amount;
/**
* Document > PmtInf > CdtTrfTxInf > Cdtr > Nm
* Document > PmtInf > CdtTrfTxInf > Cdtr > PstlAdr > Ctry
*/
@PropertyLayout(hidden = Where.REFERENCES_PARENT)
public Party getCreditor() {
return getCreditorBankAccount().getOwner();
}
/**
* Document > PmtInf > CdtTrfTxInf > RmtInf > Ustrd
*
* some combination of:
* invoice number, invoice date, invoice total amount, invoice payment amount, and invoice discount amount.
*/
@Column(allowsNull = "true", length = 255)
@Getter @Setter
private String remittanceInformation;
/**
* Used to default the {@link #getAmount()} (though this can be adjusted by the user if they wish).
*/
@Column(allowsNull = "false", name = "invoiceId")
@Getter @Setter
@PropertyLayout(hidden = Where.REFERENCES_PARENT)
private IncomingInvoice invoice;
@Override
@PropertyLayout(hidden = Where.ALL_TABLES)
public ApplicationTenancy getApplicationTenancy() {
return invoice.getApplicationTenancy();
}
@Action(semantics = SemanticsOf.SAFE)
@ActionLayout(contributed = Contributed.AS_ASSOCIATION)
public boolean getUpstreamCreditNoteFound(){
return incomingInvoiceRepository.findCreditNotesInStateOf(getCreditorBankAccount(), IncomingInvoiceApprovalState.upstreamStates());
}
@Programmatic
public void remove() {
remove(this);
}
public static class CreditorBankAccountComparator implements Comparator<PaymentLine> {
@Override
public int compare(PaymentLine l1, PaymentLine l2) {
return l1.getCreditorBankAccount().compareTo(l2.getCreditorBankAccount());
}
}
@Inject
IncomingInvoiceRepository incomingInvoiceRepository;
}
| 34.581731 | 139 | 0.669123 |
88a5be02cbb05794487a726c8b18553864054263
| 2,494 |
/*
* Copyright (c) 2013-2018, Bingo.Chen (finesoft@gmail.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.
*/
package org.corant.modules.jpa.shared.cdi;
import static org.corant.context.Beans.resolveApply;
import javax.enterprise.inject.spi.InjectionPoint;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceUnit;
import org.corant.context.CDIs;
import org.corant.context.ResourceReferences;
import org.corant.modules.jpa.shared.ExtendedEntityManager;
import org.corant.modules.jpa.shared.JPAProvider;
import org.corant.modules.jpa.shared.PersistenceService;
import org.jboss.weld.injection.spi.JpaInjectionServices;
import org.jboss.weld.injection.spi.ResourceReferenceFactory;
/**
* corant-modules-jpa-shared
*
* The JPAInjectionServices implementation
*
* @see JPAProvider
* @author bingo 下午4:18:45
*
*/
public class JPAInjectionServices implements JpaInjectionServices {
@Override
public void cleanup() {
// Noop
}
@Override
public ResourceReferenceFactory<EntityManager> registerPersistenceContextInjectionPoint(
InjectionPoint injectionPoint) {
final PersistenceContext pc = CDIs.getAnnotation(injectionPoint, PersistenceContext.class);
return ResourceReferences
.refac(() -> resolveApply(PersistenceService.class, b -> b.getEntityManager(pc)), t -> {
if (t instanceof ExtendedEntityManager) {
((ExtendedEntityManager) t).destroy();
}
}); // FIXME close?
}
@Override
public ResourceReferenceFactory<EntityManagerFactory> registerPersistenceUnitInjectionPoint(
InjectionPoint injectionPoint) {
PersistenceUnit pu = CDIs.getAnnotation(injectionPoint, PersistenceUnit.class);
return ResourceReferences.refac(
() -> resolveApply(PersistenceService.class, b -> b.getEntityManagerFactory(pu)),
EntityManagerFactory::close);// FIXME close?
}
}
| 36.676471 | 100 | 0.763432 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.