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
|
|---|---|---|---|---|---|
19922a1fb8d342074bb42dc922ff06482d55092d
| 1,188
|
package com.quarkdata.yunpan.api.model.vo;
import com.quarkdata.quark.share.model.vo.DepartmentSearchVO;
import com.quarkdata.quark.share.model.vo.GroupSearchVO;
import com.quarkdata.quark.share.model.vo.UserSearchVO;
import java.io.Serializable;
import java.util.List;
public class MemberInfoVO implements Serializable{
List<UserSearchVO> users;
List<GroupSearchVO> groups;
List<DepartmentSearchVO> departments;
public MemberInfoVO(List<UserSearchVO> users, List<GroupSearchVO> groups, List<DepartmentSearchVO> departments){
this.users = users;
this.groups = groups;
this.departments = departments;
}
public List<UserSearchVO> getUsers() {
return users;
}
public void setUsers(List<UserSearchVO> users) {
this.users = users;
}
public List<GroupSearchVO> getGroups() {
return groups;
}
public void setGroups(List<GroupSearchVO> groups) {
this.groups = groups;
}
public List<DepartmentSearchVO> getDepartments() {
return departments;
}
public void setDepartments(List<DepartmentSearchVO> departments) {
this.departments = departments;
}
}
| 26.4
| 116
| 0.703704
|
1ab7eefdbda98f9e31d4001b081fb712ae73d334
| 13,614
|
package org.corfudb.infrastructure;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import org.corfudb.protocols.wireprotocol.CorfuMsgType;
import org.corfudb.protocols.wireprotocol.CorfuPayloadMsg;
import org.corfudb.protocols.wireprotocol.SequencerMetrics;
import org.corfudb.protocols.wireprotocol.SequencerRecoveryMsg;
import org.corfudb.runtime.view.stream.StreamAddressSpace;
import org.corfudb.protocols.wireprotocol.Token;
import org.corfudb.protocols.wireprotocol.TokenRequest;
import org.corfudb.protocols.wireprotocol.TokenResponse;
import org.corfudb.protocols.wireprotocol.TokenType;
import org.corfudb.runtime.view.Address;
import org.junit.Before;
import org.junit.Test;
import org.roaringbitmap.longlong.Roaring64NavigableMap;
/**
* Created by mwei on 12/13/15.
*/
public class SequencerServerTest extends AbstractServerTest {
public SequencerServerTest() {
super();
}
SequencerServer server;
@Override
public AbstractServer getDefaultServer() {
ServerContext serverContext = new ServerContextBuilder().setSingle(true).build();
serverContext.installSingleNodeLayoutIfAbsent();
serverContext.setServerRouter(router);
router.setServerContext(serverContext);
serverContext.setServerEpoch(serverContext.getCurrentLayout().getEpoch(), router);
server = new SequencerServer(serverContext);
return server;
}
@Override
public void resetTest() {
super.resetTest();
}
@Before
public void bootstrapSequencer() {
server.setSequencerEpoch(0L);
}
/**
* Verifies that the SEQUENCER_METRICS_REQUEST is responded by the SEQUENCER_METRICS_RESPONSE
*/
@Test
public void sequencerMetricsRequest() {
CompletableFuture<SequencerMetrics> cFuture = sendRequest(CorfuMsgType.SEQUENCER_METRICS_REQUEST.msg());
SequencerMetrics seqMetrics = cFuture.join();
assertThat(seqMetrics.getSequencerStatus())
.isEqualTo(SequencerMetrics.SequencerStatus.READY);
}
@Test
public void tokensAreIncreasing() {
long lastTokenValue = -1;
for (int i = 0; i < PARAMETERS.NUM_ITERATIONS_LOW; i++) {
CompletableFuture<TokenResponse> future = sendRequest(new CorfuPayloadMsg<>(CorfuMsgType.TOKEN_REQ,
new TokenRequest(1L, Collections.emptyList())));
Token thisToken = future.join().getToken();
assertThat(thisToken.getSequence())
.isGreaterThan(lastTokenValue);
lastTokenValue = thisToken.getSequence();
}
}
@Test
public void checkTokenPositionWorks() {
for (int i = 0; i < PARAMETERS.NUM_ITERATIONS_LOW; i++) {
CompletableFuture<TokenResponse> future1 = sendRequest(new CorfuPayloadMsg<>(CorfuMsgType.TOKEN_REQ,
new TokenRequest(1L, Collections.emptyList())));
CompletableFuture<TokenResponse> future2 = sendRequest(new CorfuPayloadMsg<>(CorfuMsgType.TOKEN_REQ,
new TokenRequest(0L, Collections.emptyList())));
Token thisToken = future1.join().getToken();
Token checkToken = future2.join().getToken();
assertThat(thisToken)
.isEqualTo(checkToken);
}
}
@Test
public void perStreamCheckTokenPositionWorks() {
UUID streamA = UUID.nameUUIDFromBytes("streamA".getBytes());
UUID streamB = UUID.nameUUIDFromBytes("streamB".getBytes());
for (int i = 0; i < PARAMETERS.NUM_ITERATIONS_LOW; i++) {
CompletableFuture<TokenResponse> future = sendRequest(new CorfuPayloadMsg<>(CorfuMsgType.TOKEN_REQ,
new TokenRequest(1L, Collections.singletonList(streamA))));
Token thisTokenA = future.join().getToken();
future = sendRequest(new CorfuPayloadMsg<>(CorfuMsgType.TOKEN_REQ,
new TokenRequest(0L, Collections.singletonList(streamA))));
long checkTokenA = future.join().getStreamTail(streamA);
assertThat(thisTokenA.getSequence())
.isEqualTo(checkTokenA);
future = sendRequest(new CorfuPayloadMsg<>(CorfuMsgType.TOKEN_REQ,
new TokenRequest(1L, Collections.singletonList(streamB))));
Token thisTokenB = future.join().getToken();
future = sendRequest(new CorfuPayloadMsg<>(CorfuMsgType.TOKEN_REQ,
new TokenRequest(0L, Collections.singletonList(streamB))));
long checkTokenB = future.join().getStreamTail(streamB);
assertThat(thisTokenB.getSequence())
.isEqualTo(checkTokenB);
future = sendRequest(new CorfuPayloadMsg<>(CorfuMsgType.TOKEN_REQ,
new TokenRequest(0L, Collections.singletonList(streamA))));
long checkTokenA2 = future.join().getStreamTail(streamA);
assertThat(checkTokenA2)
.isEqualTo(checkTokenA);
assertThat(thisTokenB.getSequence())
.isGreaterThan(checkTokenA);
}
}
@Test
public void checkBackpointersWork() {
UUID streamA = UUID.nameUUIDFromBytes("streamA".getBytes());
UUID streamB = UUID.nameUUIDFromBytes("streamB".getBytes());
for (int i = 0; i < PARAMETERS.NUM_ITERATIONS_LOW; i++) {
CompletableFuture<TokenResponse> future = sendRequest(new CorfuPayloadMsg<>(CorfuMsgType.TOKEN_REQ,
new TokenRequest(1L, Collections.singletonList(streamA))));
Token thisTokenA = future.join().getToken();
future = sendRequest(new CorfuPayloadMsg<>(CorfuMsgType.TOKEN_REQ,
new TokenRequest(1L, Collections.singletonList(streamA))));
long checkTokenAValue = future.join().getBackpointerMap().get(streamA);
assertThat(thisTokenA.getSequence())
.isEqualTo(checkTokenAValue);
future = sendRequest(new CorfuPayloadMsg<>(CorfuMsgType.TOKEN_REQ,
new TokenRequest(1L, Collections.singletonList(streamB))));
Token thisTokenB = future.join().getToken();
future = sendRequest(new CorfuPayloadMsg<>(CorfuMsgType.TOKEN_REQ,
new TokenRequest(1L, Collections.singletonList(streamB))));
long checkTokenBValue = future.join().getBackpointerMap().get(streamB);
assertThat(thisTokenB.getSequence())
.isEqualTo(checkTokenBValue);
final long MULTI_TOKEN = 5L;
future = sendRequest(new CorfuPayloadMsg<>(CorfuMsgType.TOKEN_REQ,
new TokenRequest(MULTI_TOKEN, Collections.singletonList(streamA))));
thisTokenA = future.join().getToken();
future = sendRequest(new CorfuPayloadMsg<>(CorfuMsgType.TOKEN_REQ,
new TokenRequest(1L, Collections.singletonList(streamA))));
checkTokenAValue = future.join().getBackpointerMap().get(streamA);
assertThat(thisTokenA.getSequence() + MULTI_TOKEN - 1)
.isEqualTo(checkTokenAValue);
// check the requesting multiple tokens does not break the back-pointer for the multi-entry
future = sendRequest(new CorfuPayloadMsg<>(CorfuMsgType.TOKEN_REQ,
new TokenRequest(1L, Collections.singletonList(streamA))));
thisTokenA = future.join().getToken();
future = sendRequest(new CorfuPayloadMsg<>(CorfuMsgType.TOKEN_REQ,
new TokenRequest(MULTI_TOKEN, Collections.singletonList(streamA))));
checkTokenAValue = future.join().getBackpointerMap().get(streamA);
assertThat(thisTokenA.getSequence()).isEqualTo(checkTokenAValue);
}
}
@Test
public void SequencerWillResetTails() throws Exception {
UUID streamA = UUID.nameUUIDFromBytes("streamA".getBytes());
UUID streamB = UUID.nameUUIDFromBytes("streamB".getBytes());
UUID streamC = UUID.nameUUIDFromBytes("streamC".getBytes());
CompletableFuture<TokenResponse> future = sendRequest(new CorfuPayloadMsg<>(CorfuMsgType.TOKEN_REQ,
new TokenRequest(1L, Collections.singletonList(streamA))));
long tailA = future.join().getToken().getSequence();
future = sendRequest(new CorfuPayloadMsg<>(CorfuMsgType.TOKEN_REQ,
new TokenRequest(1L, Collections.singletonList(streamB))));
long tailB = future.join().getToken().getSequence();
future = sendRequest(new CorfuPayloadMsg<>(CorfuMsgType.TOKEN_REQ,
new TokenRequest(1L, Collections.singletonList(streamC))));
future = sendRequest(new CorfuPayloadMsg<>(CorfuMsgType.TOKEN_REQ,
new TokenRequest(1L, Collections.singletonList(streamC))));
long tailC = future.join().getToken().getSequence();
future = sendRequest(new CorfuPayloadMsg<>(CorfuMsgType.TOKEN_REQ,
new TokenRequest(0L, Collections.emptyList())));
long globalTail = future.join().getToken().getSequence();
// Construct new tails
Map<UUID, StreamAddressSpace> tailMap = new HashMap<>();
long newTailA = tailA + 2;
long newTailB = tailB + 1;
// This one should not be updated
long newTailC = tailC - 1;
tailMap.put(streamA, new StreamAddressSpace(Address.NON_ADDRESS, Roaring64NavigableMap.bitmapOf(newTailA)));
tailMap.put(streamB, new StreamAddressSpace(Address.NON_ADDRESS, Roaring64NavigableMap.bitmapOf(newTailB)));
tailMap.put(streamC, new StreamAddressSpace(Address.NON_ADDRESS, Roaring64NavigableMap.bitmapOf(newTailC)));
// Modifying the sequencerEpoch to simulate sequencer reset.
server.setSequencerEpoch(-1L);
future = sendRequest(new CorfuPayloadMsg<>(CorfuMsgType.BOOTSTRAP_SEQUENCER,
new SequencerRecoveryMsg(globalTail + 2, tailMap, 0L, false)));
future.join();
future = sendRequest(new CorfuPayloadMsg<>(CorfuMsgType.TOKEN_REQ,
new TokenRequest(0L, Collections.singletonList(streamA))));
assertThat(future.join().getStreamTail(streamA)).isEqualTo(newTailA);
future = sendRequest(new CorfuPayloadMsg<>(CorfuMsgType.TOKEN_REQ,
new TokenRequest(0L, Collections.singletonList(streamB))));
assertThat(future.join().getStreamTail(streamB)).isEqualTo(newTailB);
// We should have the same value than before
future = sendRequest(new CorfuPayloadMsg<>(CorfuMsgType.TOKEN_REQ,
new TokenRequest(0L, Collections.singletonList(streamC))));
assertThat(future.join().getStreamTail(streamC)).isEqualTo(newTailC);
}
/**
* Scenario to verify that we do not regress the token count when the layout switches primary
* sequencers.
* We assert that the failover sequencer should always receive a full bootstrap message rather
* than an empty bootstrap message (without streamTailsMap)
*/
@Test
public void failoverSeqDoesNotRegressTokenValue() {
UUID streamA = UUID.nameUUIDFromBytes("streamA".getBytes());
// Request tokens.
final long num = 10;
// 0 - 9
CompletableFuture<TokenResponse> future = null;
for (int i = 0; i < num; i++) {
future = sendRequest(new CorfuPayloadMsg<>(CorfuMsgType.TOKEN_REQ,
new TokenRequest(1L, Collections.singletonList(streamA))));
}
future.join();
assertThat(server.getGlobalLogTail()).isEqualTo(num);
// Sequencer accepts a delta bootstrap message only if the new epoch is consecutive.
long newEpoch = server.getServerContext().getServerEpoch() + 1;
server.getServerContext().setServerEpoch(newEpoch, server.getServerContext().getServerRouter());
CompletableFuture<Boolean> future1 = sendRequestWithEpoch(CorfuMsgType.BOOTSTRAP_SEQUENCER.payloadMsg(new SequencerRecoveryMsg(
Address.NON_EXIST, Collections.emptyMap(), newEpoch, true)), newEpoch);
assertThat(future1.join()).isEqualTo(true);
// Sequencer accepts only a full bootstrap message if the epoch is not consecutive.
newEpoch = server.getServerContext().getServerEpoch() + 2;
server.getServerContext().setServerEpoch(newEpoch, server.getServerContext().getServerRouter());
future1 = sendRequestWithEpoch(CorfuMsgType.BOOTSTRAP_SEQUENCER.payloadMsg(new SequencerRecoveryMsg(
Address.NON_EXIST, Collections.emptyMap(), newEpoch, true)), newEpoch);
assertThat(future1.join()).isEqualTo(false);
future1 = sendRequestWithEpoch(CorfuMsgType.BOOTSTRAP_SEQUENCER.payloadMsg(new SequencerRecoveryMsg(
num, Collections.singletonMap(streamA, new StreamAddressSpace(Address.NON_ADDRESS,
Roaring64NavigableMap.bitmapOf(num))), newEpoch, false)), newEpoch);
assertThat(future1.join()).isEqualTo(true);
future = sendRequestWithEpoch(CorfuMsgType.TOKEN_REQ.payloadMsg(new TokenRequest(0L, Collections.emptyList())), newEpoch);
assertThat(future.join())
.isEqualTo(new TokenResponse(TokenType.NORMAL, TokenResponse.NO_CONFLICT_KEY,
TokenResponse.NO_CONFLICT_STREAM, new Token(newEpoch, num - 1),
Collections.emptyMap(), Collections.emptyMap()));
}
}
| 45.38
| 135
| 0.672984
|
4841264bd7bc0e18145a1f4a1d668917b4473e3a
| 419
|
package org.xm.xmnlp.dic;
public class DictPair<K> {
public K key;
public Double freq = 0.0;
public String nature = "";
public DictPair(K key, double freq, String nature) {
this.key = key;
this.freq = freq;
this.nature = nature;
}
@Override
public String toString() {
return "Candidate [key=" + key + ", freq=" + freq + ", nature=" + nature+ "]";
}
}
| 20.95
| 86
| 0.556086
|
6a9a76a0a91369871bb53c3e181349824efc99aa
| 2,493
|
/*
* Developed by Softeq Development Corporation
* http://www.softeq.com
*/
package com.softeq.accelerator.flyway.mapper;
import com.softeq.accelerator.flyway.dto.AssessmentDto;
import com.softeq.accelerator.flyway.dto.CreateUserDto;
import com.softeq.accelerator.flyway.dto.UserDto;
import com.softeq.accelerator.flyway.entity.Assessment;
import com.softeq.accelerator.flyway.entity.User;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Named;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
/**
* Maps user related objects
* <p/>
* Created on 4/6/2020.
* <p/>
*
* @author slapitsky
*/
@Mapper(componentModel = "spring")
public abstract class UserMapper {
@Mapping(target = "id", source = "dto.id")
@Mapping(target = "email", source = "dto.email")
@Mapping(target = "firstName", source = "dto.firstName")
@Mapping(target = "lastName", source = "dto.lastName")
public abstract User toEntity(UserDto dto);
@Mapping(target = "email", source = "dto.email")
@Mapping(target = "firstName", source = "dto.firstName")
@Mapping(target = "lastName", source = "dto.lastName")
public abstract User toEntity(CreateUserDto dto);
@Mapping(target = "id", source = "user.id")
@Mapping(target = "email", source = "user.email")
@Mapping(target = "firstName", source = "user.firstName")
@Mapping(target = "lastName", source = "user.lastName")
@Mapping(target = "assessments", expression = "java( toAssessmentDtoList(user.getAssessments()) )")
public abstract UserDto toDto(User user);
@Mapping(target = "id", source = "shortUser.id")
@Mapping(target = "email", source = "shortUser.email")
@Mapping(target = "firstName", source = "shortUser.firstName")
@Mapping(target = "lastName", source = "shortUser.lastName")
@Named("shortUser")
public abstract UserDto toShortDto(User shortUser);
@Mapping(target = "targetUser", expression = "java(null)")
@Mapping(target = "feedbacks", expression = "java(null)")
@Mapping(target = "assessmentDate", source = "assessment.assessmentDate")
public abstract AssessmentDto toAssessmentDto(Assessment assessment);
public List<AssessmentDto> toAssessmentDtoList(List<Assessment> assessments) {
if (assessments == null) {
return Collections.emptyList();
}
return assessments.stream().map(this::toAssessmentDto).collect(Collectors.toList());
}
}
| 36.130435
| 103
| 0.69996
|
d3c793b0b6d7d0f533892dc9aa6ac85bcc5da096
| 312
|
package de.karthaus.heatingControl3.producer;
import io.micronaut.configuration.rabbitmq.annotation.Binding;
import io.micronaut.configuration.rabbitmq.annotation.RabbitClient;
@RabbitClient("hc-lcd-display")
public interface LcdStatusMessageProducer {
@Binding("hc-lcd-display")
void send(byte[] data);
}
| 24
| 67
| 0.810897
|
d4be7219364d920089e75bd655cbae35f4c9e4d1
| 2,023
|
package com.intita.ws;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.endpoint.WebSocketTraceEndpoint;
import org.springframework.boot.actuate.trace.InMemoryTraceRepository;
import org.springframework.boot.actuate.trace.TraceRepository;
import org.springframework.boot.actuate.trace.WebSocketTraceChannelInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Description;
import org.springframework.messaging.support.ExecutorSubscribableChannel;
import org.springframework.stereotype.Component;
@Component("cool")
public class WebSocketTraceChannelInterceptorAutoConfiguration {
@Value("${management.websocket.trace-inbound:true}")
private boolean enableTraceInboundChannel;
@Value("${management.websocket.trace-outbound:false}")
private boolean enableTraceOutboundChannel;
@Autowired
private ExecutorSubscribableChannel clientInboundChannel;
@Autowired
private ExecutorSubscribableChannel clientOutboundChannel;
@Autowired
WebSocketTraceChannelInterceptor interseptor;
private TraceRepository traceRepository = new InMemoryTraceRepository();
@Bean
@Description("Spring Actuator endpoint to expose WebSocket traces")
public WebSocketTraceEndpoint websocketTraceEndpoint() {
return new WebSocketTraceEndpoint(traceRepository);
}
@Bean
public WebSocketTraceChannelInterceptor webSocketTraceChannelInterceptor() {
interseptor.setTraceRepository(traceRepository);
return interseptor;
}
public WebSocketTraceChannelInterceptorAutoConfiguration()
{
addTraceInterceptor();
}
@PostConstruct
private void addTraceInterceptor() {
if(enableTraceInboundChannel) {
clientInboundChannel.addInterceptor(webSocketTraceChannelInterceptor());
}
if(enableTraceOutboundChannel) {
clientOutboundChannel.addInterceptor(webSocketTraceChannelInterceptor());
}
}
}
| 31.609375
| 79
| 0.836382
|
5779f35581bfcfbb04e4d71a73845bc05075d5e1
| 3,485
|
/**
*
*/
package jp.mydns.sys1yagi.android.greendaosample.history;
import java.text.SimpleDateFormat;
import jp.mydns.sys1yagi.android.greendaosample.DaoSession;
import jp.mydns.sys1yagi.android.greendaosample.R;
import jp.mydns.sys1yagi.android.greendaosample.Todo;
import jp.mydns.sys1yagi.android.greendaosample.TodoDao;
import jp.mydns.sys1yagi.android.greendaosample.todo.TodoDaoOpenHelper;
import jp.mydns.sys1yagi.android.greendaosample.todo.TodoLoader;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
class HistoryCursorAdapter extends CursorAdapter implements
LoaderManager.LoaderCallbacks<Cursor> {
private static class ViewHolder {
TextView todo;
TextView addDate;
TextView endDate;
}
private LayoutInflater mInflator;
private Fragment mFragment;
private DaoSession mDaoSession;
private SimpleDateFormat mFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm");
public HistoryCursorAdapter(Fragment fragment, DaoSession daoSession) {
super(fragment.getActivity(), null, false);
mDaoSession = daoSession;
mInflator = (LayoutInflater) fragment.getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
mFragment = fragment;
}
@Override
public void bindView(View paramView, Context paramContext,
Cursor paramCursor) {
Todo todo = mDaoSession.getTodoDao().readEntity(paramCursor, 0);
if (todo != null) {
ViewHolder holder = (ViewHolder) paramView.getTag();
holder.todo.setText(todo.getTodo());
holder.addDate.setText("開始:" + mFormat.format(todo.getAddDate()));
if (todo.getEndDate() != null) {
holder.endDate.setText("終了:"
+ mFormat.format(todo.getEndDate()));
}
}
}
@Override
public View newView(Context paramContext, Cursor paramCursor,
ViewGroup paramViewGroup) {
View view = mInflator.inflate(R.layout.history_item, null);
ViewHolder holder = new ViewHolder();
holder.todo = (TextView) view.findViewById(R.id.todo);
holder.addDate = (TextView) view.findViewById(R.id.add_date);
holder.endDate = (TextView) view.findViewById(R.id.end_date);
view.setTag(holder);
return view;
}
@Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
String addDateColumn = TodoDao.Properties.EndDate.columnName;
String orderBy = addDateColumn + " DESC";
return new TodoLoader(mFragment.getActivity(),
mDaoSession.getDatabase(), TodoDao.TABLENAME, mDaoSession
.getTodoDao().getAllColumns(),
TodoDao.Properties.Status.columnName + "=?",
new String[] { Integer
.toString(TodoDaoOpenHelper.STATUS_ARCHIVE) }, orderBy);
}
@Override
public void onLoaderReset(Loader<Cursor> arg0) {
this.swapCursor(null);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
this.swapCursor(cursor);
}
}
| 36.302083
| 80
| 0.682353
|
d6e16cb82a8a4030b2021cf2f5be008ee52d3da3
| 1,116
|
package com.atguigu.gmall.wms.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
/**
* @author Only when I saw the eyes from mirror, I realized that's me.
*/
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/**
* Override this method to configure the {@link HttpSecurity}. Typically subclasses
* should not invoke this method by calling super as it may override their
* configuration. The default configuration is:
*
* <pre>
* http.authorizeRequests().anyRequest().authenticated().and().formLogin().and().httpBasic();
* </pre>
*
* @param http the {@link HttpSecurity} to modify
* @throws Exception if an error occurs
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/**").permitAll();
//跨站请求伪造(英语:Cross-site request forgery) 总是忘记
http.csrf().disable();
}
}
| 32.823529
| 101
| 0.741935
|
ec6d37a6e09a0c7af29e53412b24648850072a65
| 247
|
// "Replace 'if else' with '?:'" "INFORMATION"
class Test {
String foo(String currentBranch) {
<caret>if (currentBranch.isEmpty()) {
return currentBranch;
}
else {
return currentBranch.substring(0); // comment
}
}
}
| 22.454545
| 51
| 0.611336
|
44e3edabd74b4f83c447eff7101e6408c882638f
| 776
|
package com.fulton_shaw.idea.plugin.lang.properties.view;
import com.intellij.lang.Language;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.FileViewProvider;
import com.intellij.psi.FileViewProviderFactory;
import com.intellij.psi.PsiManager;
import org.jetbrains.annotations.NotNull;
/**
* @author xiaohuadong (put comment here)
* @date 2019/04/17
*/
public class PropertiesInJavaFileViewProviderFactory implements FileViewProviderFactory {
@NotNull
@Override
public FileViewProvider createFileViewProvider(@NotNull VirtualFile file, Language language, @NotNull PsiManager manager, boolean eventSystemEnabled) {
return new PropertiesInJavaFileViewProvider(manager,file,eventSystemEnabled,language);
}
}
| 36.952381
| 156
| 0.787371
|
f2024e21f0b7c34e61c476b5d6b31b2ac6e4ea95
| 5,249
|
package aleksander73.doom.weapon_system;
import java.util.ArrayList;
import java.util.List;
import aleksander73.doom.animation.SpriteAnimation;
import aleksander73.doom.enemies.Enemy;
import aleksander73.doom.hud.StatusBar;
import aleksander73.doom.player.Player;
import aleksander73.math.linear_algebra.Vector2d;
import aleksander73.math.linear_algebra.Vector3d;
import aleksander73.vector.adt.StateMachine;
import aleksander73.vector.animation.ValueAnimation;
import aleksander73.vector.core.GameEngine;
import aleksander73.vector.core.GameObject;
import aleksander73.vector.core.Transform;
import aleksander73.vector.gui.GUIElement;
import aleksander73.vector.rendering.materials.Colour;
import aleksander73.vector.rendering.materials.Texture;
import aleksander73.vector.rendering.mesh.Mesh;
import aleksander73.vector.rendering.renderers.Renderer;
public abstract class Weapon extends GUIElement {
private int ammo;
private final int damage;
private final Vector2d hidePosition;
private final Texture mainTexture;
private final ValueAnimation<Vector2d> equipAnimation;
private final ValueAnimation<Vector2d> hideAnimation;
private final SpriteAnimation shootAnimation;
private final String shootSound;
private static final String emptySound = "weapon_empty.wav";
private final StateMachine behaviourStateMachine;
public Weapon(String name, final Vector2d equippedPosition, Vector2d dimensions, float h, Colour colour, Texture mainTexture, int ammo, int damage, final float equipTime, final float hideTime, SpriteAnimation shootAnimation, String shootSound) {
super(name, equippedPosition, dimensions, colour, mainTexture);
this.ammo = ammo;
this.damage = damage;
this.mainTexture = mainTexture;
this.shootSound = shootSound;
hidePosition = equippedPosition.add(new Vector2d(0.0f, -h)).toVector2d();
equipAnimation = new ValueAnimation<>(equipTime, false, t -> hidePosition.lerp(equippedPosition, t / equipTime).toVector2d());
hideAnimation = new ValueAnimation<>(hideTime, false, t -> equippedPosition.lerp(hidePosition, t / hideTime).toVector2d());
this.shootAnimation = shootAnimation;
this.addComponents(equipAnimation, hideAnimation, shootAnimation);
this.setActive(false);
this.getComponent(Renderer.class).setActive(false);
behaviourStateMachine = this.buildBehaviourStateMachine();
}
protected abstract StateMachine buildBehaviourStateMachine();
@Override
public void update() {
if(this.isPlayerAlive()) {
behaviourStateMachine.update();
}
}
public void shoot() {
ammo--;
GameEngine.getResourceSystem().playSound(shootSound, false);
((StatusBar)this.getScene().find("StatusBar")).updateAmmo(ammo);
List<Enemy> enemies = new ArrayList<>();
for(GameObject gameObject : this.getScene().getGameObjects()) {
if(gameObject instanceof Enemy) {
Enemy enemy = (Enemy)gameObject;
if(enemy.isAlive()) {
enemies.add(enemy);
}
}
}
Transform playerTransform = this.getScene().find("Player").getComponent(Transform.class);
Vector3d playerPosition = playerTransform.getPosition();
Vector3d playerForward = playerTransform.getForward();
for(Enemy enemy : enemies) {
Vector3d enemyPosition = enemy.getComponent(Transform.class).getPosition();
Vector3d r = enemyPosition.sub(playerPosition).toVector3d();
Vector3d r_xz = new Vector3d(r.getX(), 0.0f, r.getZ());
float alpha = playerForward.angle(r_xz);
float enemyWidth = enemy.getComponent(Mesh.class).dimensions().getX();
float tan = ((0.5f * enemyWidth) / r_xz.magnitude());
float maxAlpha = (float)Math.toDegrees(Math.atan(tan));
if(alpha <= maxAlpha) {
AttackInfo attackInfo = new AttackInfo(this, playerPosition);
enemy.applyDamage(attackInfo);
}
}
}
private boolean isPlayerAlive() {
Player player = (Player)this.getScene().find("Player");
return player.isAlive();
}
public boolean canShoot() {
return ammo > 0;
}
public void addAmmo(int ammo) {
this.ammo += ammo;
}
public void reset() {
behaviourStateMachine.reset();
}
// --------------------------------------------------
public int getAmmo() {
return ammo;
}
public int getDamage() {
return damage;
}
public Vector2d getHidePosition() {
return hidePosition;
}
public ValueAnimation<Vector2d> getEquipAnimation() {
return equipAnimation;
}
public ValueAnimation<Vector2d> getHideAnimation() {
return hideAnimation;
}
public SpriteAnimation getShootAnimation() {
return shootAnimation;
}
public StateMachine getBehaviourStateMachine() {
return behaviourStateMachine;
}
public Texture getMainTexture() {
return mainTexture;
}
public String getEmptySound() {
return emptySound;
}
}
| 35.228188
| 249
| 0.675557
|
4368a079a7312a23a987519d4cb1786dfcb13811
| 5,669
|
/*
* Copyright 2020-2021 Alexengrig Dev.
*
* 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 dev.alexengrig.metter.processor;
import dev.alexengrig.metter.element.descriptor.TypeDescriptor;
import dev.alexengrig.metter.util.Exceptions;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.tools.Diagnostic;
import java.lang.annotation.Annotation;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Base processor.
*
* @param <A> type of annotation
* @param <E> type of element
* @author Grig Alex
* @version 0.2.0
* @see javax.annotation.processing.AbstractProcessor
* @since 0.1.0
*/
public abstract class BaseProcessor<A extends Annotation, E extends Element> extends AbstractProcessor {
/**
* {@link Class#getName()} for {@link Object}.
*
* @since 0.2.0
*/
protected static final String JAVA_LANG_OBJECT_CLASS_NAME = Object.class.getName();
/**
* Annotation class.
*
* @since 0.1.0
*/
protected final Class<? extends A> annotationClass;
/**
* Constructs with an annotation class.
*
* @param annotationClass annotation class
* @since 0.1.0
*/
public BaseProcessor(Class<? extends A> annotationClass) {
this.annotationClass = annotationClass;
}
/**
* {@inheritDoc}
*
* @see #process(Element)
* @since 0.1.0
*/
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
if (roundEnv.processingOver()) {
return false;
}
for (Element annotatedElement : roundEnv.getElementsAnnotatedWith(annotationClass)) {
@SuppressWarnings("unchecked")
E element = (E) annotatedElement;
process(element);
}
return true;
}
/**
* Processes a annotated element.
*
* @param annotatedElement annotated element
* @since 0.1.0
*/
protected abstract void process(E annotatedElement);
/**
* Prints a note message.
*
* @param message message text
* @since 0.1.0
*/
protected void note(String message) {
processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, message);
}
/**
* Prints an error message.
*
* @param message message text
* @param throwable exception
* @since 0.1.0
*/
protected void error(String message, Throwable throwable) {
String stackTrace = Exceptions.getStackTrace(throwable);
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, message + System.lineSeparator() + stackTrace);
}
/**
* Returns all super type descriptors for a type descriptor.
*
* @param typeDescriptor type descriptor
* @return all super type descriptors for {@code typeDescriptor}
* @since 0.2.0
*/
protected Set<TypeDescriptor> getAllSuperTypes(TypeDescriptor typeDescriptor) {
Set<TypeDescriptor> target = new HashSet<>();
Queue<TypeElement> queue = new LinkedList<>();
queue.add(typeDescriptor.getElement());
while (!queue.isEmpty()) {
TypeElement type = queue.remove();
Set<TypeElement> superTypes = processingEnv.getTypeUtils().directSupertypes(type.asType())
.stream()
.filter(typeMirror -> typeMirror.getKind() == TypeKind.DECLARED)
.map(DeclaredType.class::cast)
.map(DeclaredType::asElement)
.filter(element -> element.getKind() == ElementKind.CLASS)
.filter(element -> !JAVA_LANG_OBJECT_CLASS_NAME.equals(element.toString()))
.map(TypeElement.class::cast)
.collect(Collectors.toSet());
if (!superTypes.isEmpty()) {
target.addAll(superTypes.stream().map(TypeDescriptor::new).collect(Collectors.toSet()));
queue.addAll(superTypes);
}
}
return target;
}
/**
* Returns an empty set.
*
* @return empty set
* @since 0.1.0
*/
@Override
public Set<String> getSupportedOptions() {
return Collections.emptySet();
}
/**
* Returns 1.8 version.
*
* @return 1.8 version
* @since 0.1.0
*/
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.RELEASE_8;
}
/**
* Returns a set with an annotation class name.
*
* @return set with an annotation class name.
* @since 0.1.0
*/
@Override
public Set<String> getSupportedAnnotationTypes() {
return Collections.singleton(annotationClass.getName());
}
}
| 30.478495
| 119
| 0.643147
|
6395f5931a324691167c43738a524066fd49e435
| 5,900
|
/*
* Copyright (c) 2017 org.hrodberaht
*
* 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.hrodberaht.injection.core.internal.annotation;
import org.hrodberaht.injection.core.internal.exception.InjectRuntimeException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Simple Java Utils - Container
*
* @author Robert Alexandersson
* 2010-maj-29 00:58:46
* @version 1.0
* @since 1.0
*/
public class ReflectionUtils {
private ReflectionUtils() {
}
public static List<Method> findMethods(Class clazz) {
final Method[] declaredMethods = clazz.getDeclaredMethods();
final List<Method> methods = new ArrayList<Method>();
methods.addAll(Arrays.asList(declaredMethods));
if (clazz.getSuperclass() != null && !clazz.getSuperclass().equals(Object.class)) {
methods.addAll(findMethods(clazz.getSuperclass()));
}
return methods;
}
public static List<Member> findMembers(Class clazz) {
final List<Member> members = new ArrayList<Member>();
final Field[] declaredFields = clazz.getDeclaredFields();
members.addAll(Arrays.asList(declaredFields));
final Method[] declaredMethods = clazz.getDeclaredMethods();
members.addAll(Arrays.asList(declaredMethods));
if (clazz.getSuperclass() != null && !clazz.getSuperclass().equals(Object.class)) {
members.addAll(0, findMembers(clazz.getSuperclass()));
}
return members;
}
public static boolean isOverridden(Method method, List<Method> candidates) {
for (final Method candidate : candidates) {
if (isOverridden(method, candidate)) {
return true;
}
}
return false;
}
public static boolean isOverridden(Method method, Method candidate) {
if (!hasOverridableAccessModifiers(method, candidate)) {
return false;
}
if (!isSubClassOf(candidate.getDeclaringClass(), method.getDeclaringClass())) {
return false;
}
if (!hasTheSameName(method, candidate)) {
return false;
}
if (!hasTheSameParameters(method, candidate)) {
return false;
}
return true;
}
public static boolean isInTheSamePackage(Method method, Method candidate) {
final Package methodPackage = method.getDeclaringClass().getPackage();
final Package candidatePackage = candidate.getDeclaringClass().getPackage();
return methodPackage.equals(candidatePackage);
}
public static boolean hasOverridableAccessModifiers(Method method, Method candidate) {
if (isFinal(method) || isPrivate(method) || isStatic(method)
|| isPrivate(candidate) || isStatic(candidate)) {
return false;
}
if (isDefault(method)) {
return isInTheSamePackage(method, candidate);
}
return true;
}
public static boolean isPrivate(Member member) {
return Modifier.isPrivate(member.getModifiers());
}
public static boolean isProtected(Member member) {
return Modifier.isProtected(member.getModifiers());
}
public static boolean isPublic(Member member) {
return Modifier.isPublic(member.getModifiers());
}
public static boolean isDefault(Member member) {
return !isPublic(member) && !isProtected(member) && !isPrivate(member);
}
public static boolean isStatic(Member member) {
return Modifier.isStatic(member.getModifiers());
}
public static boolean isFinal(Member member) {
return Modifier.isFinal(member.getModifiers());
}
public static boolean isSubClassOf(Class<?> subclass, Class<?> superclass) {
if (subclass.getSuperclass() != null) {
if (subclass.getSuperclass().equals(superclass)) {
return true;
}
return isSubClassOf(subclass.getSuperclass(), superclass);
}
return false;
}
public static boolean hasTheSameName(Method method, Method candidate) {
return method.getName().equals(candidate.getName());
}
public static boolean hasTheSameParameters(Method method, Method candidate) {
Class<?>[] methodParameters = method.getParameterTypes();
Class<?>[] candidateParameters = candidate.getParameterTypes();
if (methodParameters.length != candidateParameters.length) {
return false;
}
for (int i = 0; i < methodParameters.length; i++) {
Class<?> methodParameter = methodParameters[i];
Class<?> candidateParameter = candidateParameters[i];
if (!methodParameter.equals(candidateParameter)) {
return false;
}
}
return true;
}
public static void invoke(Method method, Object object) {
try {
method.invoke(object);
} catch (IllegalAccessException e) {
throw new InjectRuntimeException(e);
} catch (InvocationTargetException e) {
throw new InjectRuntimeException(e);
}
}
}
| 29.949239
| 91
| 0.649322
|
75d0c8717b04e5eb65f44868b4376d24cf2d0087
| 2,169
|
package core.services.interfaces;
import core.domain.Customer;
import core.exceptions.APIException;
import java.util.List;
/**
* Interface for the Customer Service.
* This service acts as a layer between the view controllers and the database
* repository.
*/
public interface CustomerServiceInterface {
/**
* Method which returns the details of a single Customer based on its
* database ID.
*
* @param customerId the ID of the Customer we want to retrieve
* @return Customer the Customer with the ID specified
* @throws core.exceptions.APIException
*/
public Customer requestCustomerDetails(String customerId) throws APIException;
/**
* Method to retrieve all Customers stored in MongoDB
*
* @return List<Customer> a list of all Customers stored in MongoDB
*/
public List<Customer> requestAllCustomers();
/**
* Method to save a new Customer to MongoDB
*
* @param customer the Customer we want to save to MongoDB
* @return Customer the newly saved Customer
* @throws core.exceptions.APIException
*/
public Customer requestNewCustomer(Customer customer) throws APIException;
/**
* Method to update a Customer saved in MongoDB
*
* @param customer the Customer we want to update
* @return Customer the newly updated Customer
* @throws core.exceptions.APIException
*/
public Customer requestUpdateCustomer(Customer customer) throws APIException;
/**
* Method to retrieve the Customer ID of the Customer linked to an API User
*
* @param apiUserId the API User ID that we want to search for
* @return String the Customer ID that possesses the API User ID we specify
* @throws core.exceptions.APIException
*/
public String requestCustomerId(String apiUserId) throws APIException;
/**
* Method which removes a Customer from MongoDB.
*
* @param customerId - The ID of the Customer we want to remove..
* @throws core.exceptions.APIException
*/
public void requestRemoveCustomer(String customerId) throws APIException;
}
| 32.863636
| 82
| 0.691563
|
8edf20b5b93dd03fe758e3ea5ae7f23853c762a4
| 469
|
package com.smarttoni.models.wrappers;
import java.util.List;
public class MealWrapper {
String mealId;
public List<RecipeWrapper> recipes;
public String getMealId() {
return mealId;
}
public void setMealId(String mealId) {
this.mealId = mealId;
}
public List<RecipeWrapper> getRecipes() {
return recipes;
}
public void setRecipes(List<RecipeWrapper> recipes) {
this.recipes = recipes;
}
}
| 18.038462
| 57
| 0.646055
|
a6cf22ee766faf720304c764b52607d49e49e037
| 4,426
|
package glredbook10;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.media.opengl.GL;
import javax.media.opengl.GL2;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLCapabilities;
import javax.media.opengl.GLEventListener;
import javax.media.opengl.awt.GLJPanel;
import javax.swing.JFrame;
import com.jogamp.opengl.util.FPSAnimator;
/**
* This is a simple double buffered program. Pressing the left mouse button
* rotates the rectangle. Pressing the middle mouse button stops the rotation.
*
* @author Kiet Le (Java port) Ported to JOGL 2.x by Claudio Eduardo Goes
*/
public class doublebuf//
extends GLSkeleton<GLJPanel>
implements GLEventListener, KeyListener, MouseListener {
private float spin = 0f, spinDelta = 0f;
@Override
protected GLJPanel createDrawable() {
GLCapabilities caps = new GLCapabilities(null);
//
GLJPanel panel = new GLJPanel(caps);
panel.setDoubleBuffered(true);
panel.addGLEventListener(this);
panel.addKeyListener(this);
panel.addMouseListener(this);
return panel;
}
public static void main(String[] args) {
doublebuf demo = new doublebuf();
FPSAnimator animator = new FPSAnimator(demo.drawable, 60);
demo.setAnimator(animator);
//
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("doublebuf");
frame.setSize(512, 256);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(demo.drawable);
frame.setVisible(true);
demo.drawable.requestFocusInWindow();
animator.start();
}
public void init(GLAutoDrawable drawable) {
GL2 gl = drawable.getGL().getGL2();
//
gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
gl.glShadeModel(GL2.GL_FLAT);
}
public synchronized void display(GLAutoDrawable drawable) {
GL2 gl = drawable.getGL().getGL2();
//
gl.glClear(GL.GL_COLOR_BUFFER_BIT);
gl.glPushMatrix();
gl.glRotatef(spin, 0.0f, 0.0f, 1.0f);
gl.glColor3f(1.0f, 1.0f, 1.0f);
gl.glRectf(-25.0f, -25.0f, 25.0f, 25.0f);
gl.glPopMatrix();
gl.glFlush();
spinDisplay();
}
public void reshape(GLAutoDrawable drawable, int x, int y, int w, int h) {
GL2 gl = drawable.getGL().getGL2();
gl.glViewport(0, 0, w, h);
gl.glMatrixMode(GL2.GL_PROJECTION);
gl.glLoadIdentity();
float aspect = 0;
if (w <= h) {
aspect = (float) h / (float) w;
gl.glOrtho(-50.0, 50.0, -50.0 * aspect, 50.0 * aspect, //
-1.0, 1.0);
} else {
aspect = (float) w / (float) h;
gl.glOrtho(-50.0 * aspect, 50.0 * aspect, -50.0, 50.0, //
-1.0, 1.0);
}
gl.glMatrixMode(GL2.GL_MODELVIEW);
gl.glLoadIdentity();
}
public void displayChanged(GLAutoDrawable drawable, boolean modeChanged,
boolean deviceChanged) {
}
private void spinDisplay() {
spin = spin + spinDelta;
if (spin > 360f)
spin = spin - 360;
}
public void keyTyped(KeyEvent key) {
}
public void keyPressed(KeyEvent key) {
switch (key.getKeyCode()) {
case KeyEvent.VK_ESCAPE:
super.runExit();
default:
break;
}
}
public void keyReleased(KeyEvent key) {
}
public void mouseClicked(MouseEvent key) {
}
public void mousePressed(MouseEvent mouse) {
switch (mouse.getButton()) {
case MouseEvent.BUTTON1:
spinDelta = 2f;
break;
case MouseEvent.BUTTON2:
case MouseEvent.BUTTON3:
spinDelta = 0f;
break;
}//
super.refresh();
}
public void mouseReleased(MouseEvent mouse) {
}
public void mouseEntered(MouseEvent mouse) {
}
public void mouseExited(MouseEvent mouse) {
}
public void dispose(GLAutoDrawable arg0) {
}
}//
| 28.012658
| 79
| 0.582693
|
e84470c711ccda12f39190ca913d161c5ab64615
| 251
|
package com.atguigu.designPattern03.day21strategy.demo.improve;
/**
* Create by koala on 2021-06-09
*/
public class BadFlyBehavior implements FlyBehavior {
@Override
public void fly() {
System.out.println(" 飞翔技术一般 ~~~");
}
}
| 16.733333
| 63
| 0.669323
|
89198d5c71184a58bf7f4235917b51c2e70b4e74
| 1,923
|
/**
* Copyright (C), 2015-2020
* FileName: BasePage
* Author: 呵呵哒
* Date: 2020/11/16 14:42
* Description:
*/
package org.springblade.common.tool;
import java.util.ArrayList;
import java.util.List;
/**
* @创建人 hyp
* @创建时间 2020/11/16
* @描述
*/
public class BasePage<T> {
private int _$9 = 1;
private int _$8 = 100;
private int _$7;
private int _$6;
private List<T> _$5 = new ArrayList();
private String _$4;
private String _$3;
private String _$2;
private int _$1;
public String getListColumnNames() {
return this._$3;
}
public void setListColumnNames(String var1) {
this._$3 = var1;
}
public String getListId() {
return this._$4;
}
public void setListId(String var1) {
this._$4 = var1;
}
public BasePage() {
}
public int getPage() {
if (this._$9 < 1) {
this._$9 = 1;
} else if (this._$9 >= this.getTotalPage()) {
this._$9 = this.getTotalPage();
}
return this._$9;
}
public void setPage(int var1) {
this._$9 = var1;
}
public int getPageSize() {
return this._$8;
}
public void setPageSize(int var1) {
this._$8 = var1;
}
public int getTotal() {
return this._$7;
}
public void setTotal(int var1) {
this._$7 = var1;
}
public int getTotalPage() {
if (this.getTotal() != 0) {
if (this.getPageSize() > 0) {
return this.getTotal() % this.getPageSize() == 0 ? this.getTotal() / this.getPageSize() : this.getTotal() / this.getPageSize() + 1;
} else {
return 1;
}
} else {
return 1;
}
}
public List<T> getRows() {
return this._$5;
}
public void setRows(List<T> var1) {
this._$5 = var1;
}
public String getOrderColumn() {
return this._$2;
}
public void setOrderColumn(String var1) {
if (ValidatorTool.validateRegex(var1, "\\w+")) {
this._$2 = var1;
} else {
this._$2 = null;
}
}
public int getOrder() {
return this._$1;
}
public void setOrder(int var1) {
this._$1 = var1;
}
}
| 16.159664
| 135
| 0.613105
|
36bd4b96a92570f73564ea1d23a99bedb0825818
| 789
|
package org.rdfhdt.hdt.gremlin.iterators;
import java.util.Iterator;
import org.rdfhdt.hdt.iterator.utils.IteratorConcat;
public class NumberIterator implements Iterator<Integer> {
int pos;
int max;
public NumberIterator(int pos, int max) {
super();
this.pos = pos;
this.max = max;
}
@Override
public boolean hasNext() {
return pos<=max;
}
@Override
public Integer next() {
return pos++;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
public static void main(String[] args) {
NumberIterator it1 = new NumberIterator(1, 10);
NumberIterator it2 = new NumberIterator(17, 20);
Iterator<Integer> it = IteratorConcat.concat(it1, it2);
while(it.hasNext()) {
int a = it.next();
System.out.println(a);
}
}
}
| 17.931818
| 58
| 0.690748
|
a95ad43a79c4c2df8957778ae1fa3f2ea703c3bc
| 1,750
|
/*
* 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.samza.table;
/**
* Custom exception which can be thrown by implementations of {@link org.apache.samza.table.remote.TableWriteFunction}
* when {@link AsyncReadWriteUpdateTable#updateAsync(Object, Object)} fails due an existing record not being
* present for the given key. {@link org.apache.samza.operators.MessageStream#sendTo(Table,
* org.apache.samza.operators.UpdateOptions)} will attempt to call {@link AsyncReadWriteUpdateTable#putAsync(Object, Object,
* Object...)} instead to insert a new record if a default is provided.
*/
public class RecordNotFoundException extends RuntimeException {
private static final long serialVersionUID = 1L;
public RecordNotFoundException() {
super();
}
public RecordNotFoundException(String s, Throwable t) {
super(s, t);
}
public RecordNotFoundException(String s) {
super(s);
}
public RecordNotFoundException(Throwable t) {
super(t);
}
}
| 36.458333
| 124
| 0.750857
|
a6d02d1f123db875984c9ec09fb60cebf6b33827
| 1,484
|
package org.vitrivr.cineast.core.decode.shotboundary;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;
import org.vitrivr.cineast.core.data.entities.MediaSegmentDescriptor;
public final class ShotBoundaryDecoder {
private ShotBoundaryDecoder(){}
public static List<MediaSegmentDescriptor> decode(File boundaryFile, String videoId) throws NullPointerException, SecurityException, FileNotFoundException{
if(boundaryFile == null){
throw new NullPointerException("boundaryFile was null in ShotBoundaryDecoder.decode()");
}
if(videoId == null){
throw new NullPointerException("videoId was null in ShotBoundaryDecoder.decode()");
}
if(!boundaryFile.exists() || !boundaryFile.isFile()){
throw new FileNotFoundException("'" + boundaryFile.getAbsolutePath() + "' was not found in ShotBoundaryDecoder.decode()");
}
if(!boundaryFile.canRead()){
throw new SecurityException("'" + boundaryFile.getAbsolutePath() + "' cannot be read in ShotBoundaryDecoder.decode()");
}
String extension = "";
int i = boundaryFile.getName().lastIndexOf('.');
if (i > 0) {
extension = boundaryFile.getName().substring(i+1);
}
switch(extension){
case "msb":
case "sb":{
return TrecvidMasterShotReferenceDecoder.decode(boundaryFile, videoId);
}
default:
throw new IllegalArgumentException("'" + extension + "' is not a recognized file extension in ShotBoundaryDecoder.decode()");
}
}
}
| 28.538462
| 156
| 0.726415
|
2649310b5e8dfb1a6755ae5147af3a971ae90ed5
| 1,089
|
package Utility;
/**
* Author : Sivasankaramalan
*/
import org.apache.log4j.Logger;
import Driver.desiredCapabilities;
public class Log extends desiredCapabilities{
//Initialize Log4j instance
private static Logger Log = Logger.getLogger(Log.class.getName());
//We can use it when starting tests
public static void startLog (String testClassName){
Log.info("Test is Starting...");
}
//We can use it when ending tests
public static void endLog (String testClassName){
Log.info("Test is Ending...");
}
//Info Level Logs
public static void info (String message) {
Log.info(message);
}
//Warn Level Logs
public static void warn (String message) {
Log.warn(message);
}
//Error Level Logs
public static void error (String message) {
Log.error(message);
}
//Fatal Level Logs
public static void fatal (String message) {
Log.fatal(message);
}
//Debug Level Logs
public static void debug (String message) {
Log.debug(message);
}
}
| 22.22449
| 70
| 0.636364
|
7131d2085aa05b1360614c0afb01d734115ecb4d
| 5,342
|
package cg.morfismo;
import java.awt.*;
import java.awt.geom.*;
import java.util.Timer;
import java.util.TimerTask;
import java.awt.image.BufferedImage;
public class MorphingCandS extends TimerTask {
//The window in which the transformation is shown.
private BufferedImageDrawer buffid;
//The two images to be transformed into each other will be scaled to
//this size.
private int width;
private int height;
//The number of steps (frames) for the transformation.
private int steps;
//The first triangulated image.
private TriangulatedImage t1;
//The second triangulated image.
private TriangulatedImage t2;
//This is used for generating/storing the intermediate images.
private BufferedImage mix;
//A variable which is increased stepwise from 0 to 1. It is needed
//for the computation of the convex combinations.
private double alpha;
//The change of alpha in each step: deltAlpha = 1.0/steps
private double deltaAlpha;
public MorphingCandS(){
}
public MorphingCandS(BufferedImageDrawer bid) {
buffid = bid;
width = 100;
height = 150;
steps = 100;
deltaAlpha = 1.0 / steps;
alpha = 0;
//This object is used for loading the two images.
Image loadedImage;
//Generating the first triangulated image:
t1 = new TriangulatedImage();
//Define the size.
t1.bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//Generate the Graphics2D object.
Graphics2D g2dt1 = t1.bi.createGraphics();
//Load the image and draw it on the corresponding BufferedImage.
loadedImage = new javax.swing.ImageIcon("src/cg/imagens/novo.jpg").getImage();
g2dt1.drawImage(loadedImage, 0, 0, null);
//Definition of the points for the triangulation.
t1.tPoints = new Point2D[9];
t1.tPoints[0] = new Point2D.Double(0, 0);
t1.tPoints[1] = new Point2D.Double(0, 110);
t1.tPoints[2] = new Point2D.Double(0, 150);
t1.tPoints[3] = new Point2D.Double(50, 150);
t1.tPoints[4] = new Point2D.Double(100, 150);
t1.tPoints[5] = new Point2D.Double(100, 110);
t1.tPoints[6] = new Point2D.Double(100, 0);
t1.tPoints[7] = new Point2D.Double(50, 0);
t1.tPoints[8] = new Point2D.Double(50, 110);
//Definition of the triangles.
t1.triangles = new int[8][3];
for (int i = 0; i < 7; i++) {
t1.triangles[i][0] = i;
t1.triangles[i][1] = i + 1;
t1.triangles[i][2] = 8;
}
t1.triangles[7][0] = 7;
t1.triangles[7][1] = 0;
t1.triangles[7][2] = 8;
//The same for the second image.
t2 = new TriangulatedImage();
t2.bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2dt2 = t2.bi.createGraphics();
loadedImage = new javax.swing.ImageIcon("src/cg/imagens/velho.jpg").getImage();
g2dt2.drawImage(loadedImage, 0, 0, null);
t2.tPoints = new Point2D[9];
t2.tPoints[0] = new Point2D.Double(0, 0);
t2.tPoints[1] = new Point2D.Double(0, 40);
t2.tPoints[2] = new Point2D.Double(0, 150);
t2.tPoints[3] = new Point2D.Double(55, 150);
t2.tPoints[4] = new Point2D.Double(100, 150);
t2.tPoints[5] = new Point2D.Double(100, 40);
t2.tPoints[6] = new Point2D.Double(100, 0);
t2.tPoints[7] = new Point2D.Double(55, 0);
t2.tPoints[8] = new Point2D.Double(55, 40);
//The indexing for the triangles must be the same as in the
//the first image.
t2.triangles = t1.triangles;
}
//This method is called in regular intervals. This method computes
//the updated image/frame and calls the repaint method to draw the
//updated image on the window.
public void run() {
//Since this method is called arbitrarily often, interpolation must only
//be carred out while alpha is between 0 and 1.
if (alpha >= 0 && alpha <= 1) {
//Generate the interpolated image.
mix = t1.mixWith(t2, alpha);
//Draw the interpolated image on the BufferedImage.
buffid.g2dbi.drawImage(mix, 50, 50, null);
//Call the method for updating the window.
buffid.repaint();
}
//Increment alpha.
alpha = alpha + deltaAlpha;
}
public void execute(){
//Width of the window.
int width = 200;
//Height of the window.
int height = 250;
//Specifies (in milliseconds) when the frame should be updated.
int delay = 50;
//The BufferedImage to be drawn in the window.
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//The window in which everything is drawn.
BufferedImageDrawer bid = new BufferedImageDrawer(bi, width, height);
bid.setTitle("Transforming shape and colour");
bid.setLocationRelativeTo(null);
//The TimerTask in which the repeated computations for drawing take place.
MorphingCandS mcs = new MorphingCandS(bid);
Timer t = new Timer();
t.scheduleAtFixedRate(mcs, 0, delay);
}
}
| 31.423529
| 88
| 0.614938
|
ed126837bde248c33b5dec3952224182fdc5f4dd
| 8,414
|
package engine.linear.material;
import engine.core.sourceelements.RawModel;
import engine.core.sourceelements.SourceElement;
import engine.render.overlaysystem.OverlayRenderer;
import org.lwjgl.opengl.Display;
import org.lwjgl.util.vector.Matrix4f;
import org.lwjgl.util.vector.Vector2f;
import org.lwjgl.util.vector.Vector3f;
/**
* Created by Luecx on 05.03.2017.
*/
public abstract class GuiElement extends Material implements SourceElement{
public static final int DISPLAY_MODE_PIXEL_SPACE = 1;
public static final int DISPLAY_MODE_CLIP_SPACE = 2;
public static final int ANIMATION_NO_ANIMATION = 0;
public static final int ANIMATION_NO_UPDATE= 1;
public static final int ANIMATION_PROGRESS_TO_B= 2;
public static final int ANIMATION_PROGRESS_TO_A= 3;
private int displayMode;
private boolean visible = true;
private Vector2f location = new Vector2f(0,0);
private Vector2f scale = new Vector2f(0.5f,1);
private float rotation;
private boolean trigonometricInterpolation;
private int animationStatus = 0;
private float animationFrac = 0f;
private float animationTime = 1f;
private Vector2f animationAnchorA = new Vector2f();
private Vector2f animationAnchorB = new Vector2f();
protected Vector3f blendColor = new Vector3f();
protected float blendFactor = 0;
private boolean blackWhite = false;
private boolean ignoreAlpha = false;
private boolean matrixDeprecated = true;
private Matrix4f transformationMatrix;
public GuiElement(int colorMap) {
super(colorMap);
}
public GuiElement(String colorMap) {
super(colorMap);
}
public GuiElement(int colorMap, int displayMode) {
super(colorMap);
this.displayMode = displayMode;
}
public boolean isVisible() {
return visible;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
public GuiElement(String colorMap, int displayMode) {
super(colorMap);
this.displayMode = displayMode;
}
public void setAnimation(Vector2f pointA, Vector2f pointB, float animationTime){
if(this.displayMode == DISPLAY_MODE_PIXEL_SPACE){
pointA = pixelToClipLocation(pointA);
pointB = pixelToClipLocation(pointB);
}
animationStatus = 1;
this.animationTime = animationTime;
this.animationAnchorA = pointA;
this.animationAnchorB = pointB;
}
public void setAnimationFrac(float animationFrac) {
if(animationStatus == ANIMATION_NO_ANIMATION) return;
this.animationFrac = animationFrac;
}
public void updateAnimation(float progressedTime){
if(animationStatus == ANIMATION_NO_ANIMATION) return;
if(animationStatus == ANIMATION_NO_UPDATE) {}
else if(animationStatus == ANIMATION_PROGRESS_TO_B){
animationFrac += progressedTime / animationTime;
} else if(animationStatus == ANIMATION_PROGRESS_TO_A){
animationFrac -= progressedTime / animationTime;
}
if(animationFrac > 1) {animationFrac = 1; this.animationStatus = ANIMATION_NO_UPDATE;}
if(animationFrac < 0) {animationFrac = 0; this.animationStatus = ANIMATION_NO_UPDATE;}
this.location = trigonometricInterpolation ? trigonometricInterpolation(animationAnchorA, animationAnchorB, animationFrac):
linearInterpolation(animationAnchorA, animationAnchorB, animationFrac);
this.matrixDeprecated = true;
}
public int getDisplayMode() {
return displayMode;
}
public void setDisplayMode(int displayMode) {
if(displayMode != DISPLAY_MODE_CLIP_SPACE && displayMode != DISPLAY_MODE_PIXEL_SPACE) return;
this.displayMode = displayMode;
this.matrixDeprecated = true;
}
public Vector2f getLocation() {
this.matrixDeprecated = true;
return location;
}
public void setLocation(Vector2f location) {
if(this.displayMode == DISPLAY_MODE_PIXEL_SPACE) location = pixelToClipLocation(location);
this.location = location;
this.matrixDeprecated = true;
}
public Vector2f getScale() {
this.matrixDeprecated = true;
return scale;
}
public void setScale(Vector2f scale) {
if(this.displayMode == DISPLAY_MODE_PIXEL_SPACE) scale = pixelToClipScale(scale);
this.scale = scale;
this.matrixDeprecated = true;
}
public float getRotation() {
return rotation;
}
public void setRotation(float rotation) {
this.rotation = rotation;
this.matrixDeprecated = true;
}
public boolean isBlackWhite() {
return blackWhite;
}
public void setBlackWhite(boolean blackWhite) {
this.blackWhite = blackWhite;
}
public boolean isIgnoreAlpha() {
return ignoreAlpha;
}
public void setIgnoreAlpha(boolean ignoreAlpha) {
this.ignoreAlpha = ignoreAlpha;
}
public void enableTrigonometricInterpolation(){
this.trigonometricInterpolation = true;
}
public void disableTrigonometricInterpolation() {
this.trigonometricInterpolation = false;
}
public boolean isTrigonometricInterpolation() {
return trigonometricInterpolation;
}
public int getAnimationStatus() {
return animationStatus;
}
public void setAnimationStatus(int animationStatus) {
if(animationStatus != ANIMATION_NO_ANIMATION &&animationStatus != ANIMATION_NO_UPDATE &&
animationStatus != ANIMATION_PROGRESS_TO_B &&animationStatus != ANIMATION_PROGRESS_TO_A)return;
this.animationStatus = animationStatus;
}
public float getAnimationTime() {
return animationTime;
}
public void setAnimationTime(float animationTime) {
this.animationTime = animationTime;
}
public Vector2f getAnimationAnchorA() {
return animationAnchorA;
}
public void setAnimationAnchorA(Vector2f animationAnchorA) {
this.animationAnchorA = animationAnchorA;
}
public Vector2f getAnimationAnchorB() {
return animationAnchorB;
}
public void setAnimationAnchorB(Vector2f animationAnchorB) {
this.animationAnchorB = animationAnchorB;
}
public float getAnimationFrac() {
return animationFrac;
}
public boolean isMatrixDeprecated() {
return matrixDeprecated;
}
public Vector3f getBlendColor() {
return blendColor;
}
public void setBlendColor(Vector3f blendColor) {
this.blendColor = blendColor;
}
public float getBlendFactor() {
return blendFactor;
}
public void setBlendFactor(float blendFactor) {
this.blendFactor = blendFactor;
}
public static Vector2f pixelToClipLocation(Vector2f in){
return new Vector2f((2 * in.x) / (float)Display.getDisplayMode().getWidth() - 1, (2 *in.y) /(float) Display.getDisplayMode().getHeight() - 1);
}
public static Vector2f pixelToClipScale(Vector2f in){
return new Vector2f(in.x / (float)Display.getDisplayMode().getWidth(), in.y /(float) Display.getDisplayMode().getHeight());
}
public static Vector2f linearInterpolation(Vector2f a, Vector2f b, float frac){
return Vector2f.add(a, (Vector2f)Vector2f.sub(b, a, null).scale(frac), null);
}
public static Vector2f trigonometricInterpolation(Vector2f a, Vector2f b, float frac){
double c = (float)((Math.cos((frac * Math.PI)-Math.PI) * 0.5 + 0.5));
return new Vector2f((float)(c * (b.x-a.x) + a.x),
(float)(c * (b.y-a.y) + a.y));
}
@Override
public RawModel getRawModel() {
return OverlayRenderer.quad;
}
public Matrix4f getTransformationMatrix() {
if(this.matrixDeprecated == true){
transformationMatrix = new Matrix4f();
transformationMatrix.setIdentity();
Matrix4f.translate(this.location, transformationMatrix, transformationMatrix);
Matrix4f.scale(new Vector3f(this.scale.x, this.scale.y, 1f), transformationMatrix, transformationMatrix);
Matrix4f.rotate((float)Math.toRadians(this.rotation), new Vector3f(0,0,1),transformationMatrix, transformationMatrix);
}
return this.transformationMatrix;
}
public abstract void update();
}
| 31.395522
| 150
| 0.68184
|
9bfb532de137d860e1c5bf07352cc0a93579da31
| 988
|
package edu.pdx.cs410J.lang;
/**
* This class demonstrates throwing exceptions. It reads two
* <code>double</code>s from the command line and divides the second
* by the first. If the second is zero, an
* <code>IllegalArgumentException</code> is thrown.
*/
public class DivTwo {
/**
* Reads two <code>double</code>s from the command line and divides
* the first by the second.
*/
public static void main(String[] args) {
double d1 = 0.0;
double d2 = 0.0;
if (args.length < 2) {
System.err.println("Not enough arguments");
System.exit(1);
}
try {
d1 = Double.parseDouble(args[0]);
d2 = Double.parseDouble(args[1]);
} catch (NumberFormatException ex) {
System.err.println("Not a double: " + ex);
System.exit(1);
}
if (d2 == 0.0) {
String m = "Denominator can't be zero!";
throw new IllegalArgumentException(m);
}
System.out.println(d1 + " / " + d2 + " = " + (d1/d2));
}
}
| 23.52381
| 69
| 0.604251
|
5fd22d6abb48689a52a50d8417f319827f2ae49b
| 193
|
package com.trampcr.developerrepository.plugin;
public class Title {
public String getTitle() {
// return "It's a original app";
return "It's forth hotfix version";
}
}
| 21.444444
| 47
| 0.65285
|
8f6be9ec8615c84c32046ffe200d91c5e9e771a6
| 10,042
|
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2018-2019 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package frc.robot;
import edu.wpi.first.wpilibj.GenericHID;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.XboxController;
import edu.wpi.first.wpilibj.shuffleboard.Shuffleboard;
import com.kauailabs.navx.frc.AHRS;
import edu.wpi.first.cscore.MjpegServer;
import edu.wpi.first.math.geometry.Pose2d;
import edu.wpi.first.math.trajectory.Trajectory;
import edu.wpi.first.wpilibj2.command.Command;
import edu.wpi.first.wpilibj2.command.InstantCommand;
import edu.wpi.first.wpilibj2.command.ParallelCommandGroup;
import edu.wpi.first.wpilibj2.command.button.JoystickButton;
import frc.robot.commands.*;
import frc.robot.subsystems.*;
import frc.robot.subsystems.DriveTrain.Cockpit;
import frc.robot.subsystems.FeedbackPanel.PanelMode;
import org.photonvision.PhotonCamera;
import org.photonvision.targeting.PhotonPipelineResult;
import edu.wpi.first.math.controller.PIDController;
import edu.wpi.first.wpilibj.DriverStation.Alliance;
import edu.wpi.first.wpilibj.DriverStation;
/**
* This class is where the bulk of the robot should be declared. Since
* Command-based is a "declarative" paradigm, very little robot logic should
* actually be handled in the {@link Robot} periodic methods (other than the
* scheduler calls). Instead, the structure of the robot (including subsystems,
* commands, and button mappings) should be declared here.
*/
public class RobotContainer {
// -------------------- Joysticks and Buttons -------------------- \\
// Joysticks
final Joystick stick1 = new Joystick(Constants.stickport1); // Creates a joystick on port 1
// Xbox Controller
final XboxController xbox = new XboxController(Constants.xboxport);
// The robot's subsystems and commands are defined here...
// -------------------- Subsystems -------------------- \\
// Inputs
private final AHRS m_ahrs = new AHRS();
private final USBCamera usbCamera = new USBCamera();
// Outputs
public final DriveTrain m_driveTrain = new DriveTrain(m_ahrs, stick1, xbox);
private final Climber m_climber = new Climber();
private final Intake intake = new Intake();
private final Chambers ballDetection = new Chambers(3);
private final Indicators lights = new Indicators(3);
private final PhotonVision vision = new PhotonVision(stick1, m_driveTrain, lights);
private final FeedbackPanel m_feedbackPanel = new FeedbackPanel(3);
private final Shooter shooter = new Shooter(xbox);
// Diagnostics
private final Battery m_battery = new Battery(m_ahrs, m_driveTrain, xbox);
private final Field field = new Field(m_ahrs);
// -------------------- Autonomous Commands -------------------- \\
// insert autonomous commands here
// -------------------- Telop Commands -------------------- \\
// insert teleop commands here
// -------------------- Global Toggles -------------------- \\
/** Whether or not autonomous/smart systems are disabled. */
private static boolean manualMode = false;
private static boolean boostMode = false;
private static boolean slowMode = false;
public static boolean manualModeOp = false;
/**
* The container for the robot. Contains subsystems, OI devices, and commands.
*/
public RobotContainer() {
// Configure the button bindings
configureButtonBindings();
// Switch Shuffleboard to the driver dashboard
Shuffleboard.getTab("Config");
Shuffleboard.selectTab("Config");
}
/**
* Use this method to define your button->command mappings. Buttons can be
* created by instantiating a {@link GenericHID} or one of its subclasses
* ({@link edu.wpi.first.wpilibj.Joystick} or {@link XboxController}), and then
* passing it to a {@link edu.wpi.first.wpilibj2.command.button.JoystickButton}.
*/
private void configureButtonBindings() {
// Button for driving at full speed
new JoystickButton(stick1, 5).whenPressed(() -> {
boostMode = true;
}).whenReleased(() -> {
boostMode = false;
});
// Button for driving slowly
new JoystickButton(stick1, 2).whenPressed(() -> {
slowMode = true;
}).whenReleased(() -> {
slowMode = false;
});
// Disable rotation (not yet in this branch)
// Zero navX rotation
new JoystickButton(stick1, 4).whenPressed(() -> m_driveTrain.reset());
// Velocity retention (not yet in this branch)
// Button for disabling autonomous/smart functions
new JoystickButton(stick1, 6).whenPressed(() -> {
manualMode = true;
}).whenReleased(() -> {
manualMode = false;
});
new JoystickButton(stick1, 9).whenPressed(() -> {
}).whenReleased(() -> {
vision.invertCams();
});
new JoystickButton(stick1, Constants.VISION_DRIVE_BUTTON).whenPressed(() -> {
vision.drive();
});
// Climber control (RB for full power and LB for low power)
new JoystickButton(xbox, 6).whenPressed(() -> m_climber.setClimberSpeed(1.0))
.whenReleased(() -> m_climber.setClimberSpeed(0));
new JoystickButton(xbox, 5).whenPressed(() -> m_climber.setClimberSpeed(0.3))
.whenReleased(() -> m_climber.setClimberSpeed(0));
// Lower intake up (A button)
new JoystickButton(xbox, 1).whenPressed(() -> intake.setIntakeMotorSpeed(0, -Constants.intakeSpeed))
.whenReleased(() -> intake.setIntakeMotorSpeed(0, 0));
// Upper intake up and also shooter (X button)
new JoystickButton(xbox, 3).whenPressed(
new ParallelCommandGroup(
new InstantCommand(() -> {
intake.setIntakeMotorSpeed(1, -Constants.intakeSpeed);
}),
new InstantCommand(() -> {
// Normal Shooter Operation
// shooter.setShooterSpeed(0.7);
// Change shooter with xbox triggers
shooter.setShooterSpeed(Shooter.shooterSpeedWithTriggerChange);
})))
.whenReleased(
new ParallelCommandGroup(
new InstantCommand(() -> {
intake.setIntakeMotorSpeed(1, 0);
}),
new InstantCommand(() -> {
shooter.setShooterSpeed(0);
})));
// Lower intake down (B button)
new JoystickButton(xbox, 2).whenPressed(() -> intake.setIntakeMotorSpeed(0,
Constants.intakeSpeed))
.whenReleased(() -> intake.setIntakeMotorSpeed(0, 0));
// Button for disabling automatic operation
new JoystickButton(xbox, 7).whenPressed(() -> {
manualModeOp = true;
}).whenReleased(() -> {
manualModeOp = false;
});
// Toggle driving in intake-oriented mode
new JoystickButton(stick1, 7).whenPressed(() -> m_driveTrain.setIntakeCockpitMode(Cockpit.LEFT))
.whenReleased(() -> {
if (m_driveTrain.getIntakeCockpitMode() == Cockpit.LEFT)
m_driveTrain.setIntakeCockpitMode(Cockpit.NONE);
});
new JoystickButton(stick1, 8).whenPressed(() -> m_driveTrain.setIntakeCockpitMode(Cockpit.RIGHT))
.whenReleased(() -> {
if (m_driveTrain.getIntakeCockpitMode() == Cockpit.RIGHT)
m_driveTrain.setIntakeCockpitMode(Cockpit.NONE);
});
// Toggle driving in robot-oriented mode
new JoystickButton(stick1, 11).whenPressed(() -> m_driveTrain.setIntakeCockpitMode(Cockpit.FRONT))
.whenReleased(() -> {
if (m_driveTrain.getIntakeCockpitMode() == Cockpit.FRONT)
m_driveTrain.setIntakeCockpitMode(Cockpit.NONE);
});
// Death Blossom (rotate 180)
new JoystickButton(stick1, 12).whenPressed(() -> m_driveTrain.deathBlossom(180));
}
/** Returns whether or not the robot is driving at full speed. */
public static boolean getBoostMode() {
return boostMode;
}
/** Returns whether or not the robot is driving in slow mode. */
public static boolean getSlowMode() {
return slowMode;
}
/** Returns whether or not autonomous/smart systems are disabled. */
public static boolean getManualMode() {
return manualMode;
}
/** Returns whether or not automatic operation is distabled. */
public static boolean getManualModeOp() {
return manualModeOp;
}
/**
* Use this to pass the enable command to the main {@link Robot} class.
* This command is run immediately when the robot is enabled (not simply turned
* on), regardless of whether the robot is in teleop or autonomous.
*
* @return the command to run when the robot is enabled
*/
public Command getEnableCommand() {
return new InstantCommand(() -> m_driveTrain.reset(true));
}
/**
* Use this to pass the autonomous command to the main {@link Robot} class.
*
* @return the command to run in autonomous
*/
public Command getAutonomousCommand() {
// Creates a new Autonomous Command for the robot
System.out.println("Getting autonomous command");
m_feedbackPanel.setDisplayMode(PanelMode.Boot);
return new Autonomous(m_driveTrain, intake, shooter, m_ahrs, xbox, m_feedbackPanel);
}
public Command getTelopCommand() {
vision.setPipelineFromAlliance();
m_feedbackPanel.setDisplayMode(PanelMode.Status);
Shuffleboard.selectTab("Driver Dashboard");
return new SingleJoystickDrive(m_driveTrain, stick1);
}
public Command getTestCommand() {
return new SingleJoystickDrive(m_driveTrain, stick1);
}
}
| 38.475096
| 105
| 0.64051
|
96b0a9b0f624b32c0f741a60cd81ad0f3d6ceef0
| 11,254
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package indiesvsgamersbropals;
import bropals.lib.simplegame.animation.Animation;
import bropals.lib.simplegame.animation.Track;
import bropals.lib.simplegame.entity.BaseEntity;
import bropals.lib.simplegame.entity.GameWorld;
import bropals.lib.simplegame.entity.block.TexturedBlock;
import bropals.lib.simplegame.io.AssetManager;
import bropals.lib.simplegame.state.GameState;
import indiesvsgamersbropals.entity.HazardBlock;
import indiesvsgamersbropals.entity.SwordEntity;
import indiesvsgamersbropals.entity.SwordEntityFactory;
import indiesvsgamersbropals.entity.enem.GuardEntity;
import indiesvsgamersbropals.entity.enem.KnightDownEntity;
import indiesvsgamersbropals.entity.enem.WhiteGhostEntity;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.InputStream;
/**
* Takes a file and builds it into a world
* @author Kevin
*/
public class WorldBuilder {
/**
* The world file to read data from
*/
private File file;
private int worldWidth; // how many scenes wide the world is
private int worldHeight; // how many scenes high the world is
private int spawnSceneX, spawnSceneY, spawnPosX, spawnPosY, goalSceneX, goalSceneY;
private BufferedImage lastBackgroundImage;
private SwordEntity goalEnemy;
public WorldBuilder(File worldFile) {
file = worldFile;
worldHeight = 0;
worldWidth = 0;
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String input = "";
while ((input = reader.readLine()) != null) {
if (input.length() == 0) {
continue;
}
if (input.startsWith("ROW")) {
String[] tokens = input.split(" ");
worldWidth = Integer.parseInt(tokens[1]);
} else if (input.startsWith("COL")) {
String[] tokens = input.split(" ");
worldHeight = Integer.parseInt(tokens[1]);
} else if (input.startsWith("PLAYER_SPAWN")){
String[] tokens = input.split(" ");
spawnSceneX = Integer.parseInt(tokens[1]);
spawnSceneY = Integer.parseInt(tokens[2]);
spawnPosX = Integer.parseInt(tokens[3]);
spawnPosY = Integer.parseInt(tokens[4]);
}
}
reader.close();
} catch(FileNotFoundException fnfe) {
System.err.println("Could not find the file " + file);
} catch(Exception e) {
System.err.println(e);
}
}
public boolean sceneInBounds(int posX, int posY) {
return posX >= 0 && posX < worldWidth && posY >= 0 && posY < worldHeight;
}
/**
* Get the scene at the given position.
* @param stateToBuildFor The game state to load the scene for
* @param posX The x position of the scene.
* @param posY LThe y position of the scene
* @return The scene, or null if there was an error with loading it
*/
public GameWorld<BaseEntity> buildWorld(GameState stateToBuildFor, int posX, int posY) {
System.out.println("world width: " + worldWidth);
System.out.println("world height: " + worldHeight);
System.out.println("Scene position: " + posX + ", " + posY);
if (!sceneInBounds(posX, posY)) {
System.err.println("The scene location is outside of the given bounds");
return null;
}
GameWorld<BaseEntity> world = new GameWorld<>(stateToBuildFor);
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String input = "";
int line = 0;
boolean onScene = false;
while ((input = reader.readLine()) != null) {
line++;
if (input.length() == 0) {
continue;
}
// System.out.println("Reading line: " + input);
if (onScene) {
if (input.startsWith("SCENE")) {
// if you were already on a scene, then finish it
return world;
} else if (input.startsWith("BLOCK") || input.startsWith("HAZARD")) {
String[] tokens = input.split(" ");
int x = Integer.parseInt(tokens[1]);
int y = Integer.parseInt(tokens[2]);
int width = Integer.parseInt(tokens[3]);
int height = Integer.parseInt(tokens[4]);
TexturedBlock block;
if (input.startsWith("HAZARD")) {
block = new HazardBlock(world, x, y, width, height);
} else {
block = new TexturedBlock(world, x, y, width, height);
}
world.addEntity(block);
block.setParent(world);
block.setAnchored(true);
if (tokens[5].equals("I")) {
block.setImage(stateToBuildFor.getAssetManager().getImage(tokens[6]));
} else if (tokens[5].equals("A")) {
Animation anim = new Animation();
anim.addTrack(new Track(
stateToBuildFor.getAssetManager().getImage(tokens[6]),
Integer.parseInt(tokens[7]),
Integer.parseInt(tokens[8]),
Integer.parseInt(tokens[9])));
anim.setTrack(0);
block.setAnimation(anim);
} else {
System.err.println("Parsing error");
throw new Exception("Parsing error with the line line '" + line + "'");
}
} else if (input.startsWith("BACKGROUND")) {
String[] tokens = input.split(" ");
lastBackgroundImage = stateToBuildFor.getAssetManager().getImage(tokens[1]);
}
} else {
// find the scene you're looking for
if (input.equals("SCENE " + posX + " " + posY)) {
onScene = true;
System.out.println("Found the scene. input: '" + input + "'");
}
}
}
reader.close();
return world;
} catch(FileNotFoundException fnfe) {
System.err.println("Could not find the file " + file);
} catch(Exception e) {
System.err.println(e);
e.printStackTrace();
}
return null;
}
public void spawnEnemiesForQuest(File questFile, EnemyManager manager,
AssetManager assetManager, SwordEntity player) {
try {
BufferedReader reader = new BufferedReader(new FileReader(questFile));
SwordEntityFactory factory = new SwordEntityFactory(assetManager);
// delete any previous scene goal
goalSceneX = -1;
goalSceneY = -1;
String input = "";
while ((input = reader.readLine()) != null) {
if (input.length() == 0) {
continue;
}
// System.out.println("reading: " + input);
if (input.startsWith("SPAWN") || input.startsWith("SPAWN_GOAL")) {
String[] tokens = input.split(" ");
String enemyType = tokens[1];
int sceneY = Integer.parseInt(tokens[2]);
int sceneX = Integer.parseInt(tokens[3]);
int x = Integer.parseInt(tokens[4]);
int y = Integer.parseInt(tokens[5]);
System.out.println("position: " + x + ", " + y);
// use the factory to make a new enemy
// add it to the enemy manager
SwordEntity entity = null;
if (enemyType.equals("GUARD")) {
entity = factory.makeGuardEnemy(x, y);
System.out.println("added a guard to the scene");
} else if (enemyType.equals("KNIGHT_D")) {
entity = factory.makeKnightDownEnemy(x, y);
System.out.println("added a knight facing down to the scene");
} else if (enemyType.equals("KNIGHT_U")) {
entity = factory.makeKnightUpEnemy(x, y);
System.out.println("added a knight facing up to the scene");
} else if (enemyType.equals("ROGUE")) {
entity = factory.makeRogueEnemy(x, y);
System.out.println("added a rogue to the scene");
} else if (enemyType.equals("WHITE_GHOST")) {
entity = factory.makeWhiteGhostBoss(x, y);
System.out.println("added a white ghost to the scene");
}
if (entity != null) {
// give the enemy the reference to the player
// and save them to the enemy manager
entity.givePlayer(player);
manager.saveEnemy(sceneX, sceneY, entity);
}
// set up the goal if this enemy was the goal
if (entity != null && input.startsWith("SPAWN_GOAL")) {
goalSceneX = sceneX;
goalSceneY = sceneY;
goalEnemy = entity;
}
}
}
reader.close();
} catch(FileNotFoundException fnfe) {
System.err.println("Could not find the file " + questFile);
} catch(Exception e) {
System.err.println(e);
e.printStackTrace();
}
}
public int getSpawnSceneX() {
return spawnSceneX;
}
public int getSpawnSceneY() {
return spawnSceneY;
}
public int getSpawnPosY() {
return spawnPosY;
}
public int getSpawnPosX() {
return spawnPosX;
}
public int getGoalSceneX() {
return goalSceneX;
}
public int getGoalSceneY() {
return goalSceneY;
}
public SwordEntity getGoalEnemy() {
return goalEnemy;
}
public BufferedImage getLastBackgroundImage() {
return lastBackgroundImage;
}
}
| 40.049822
| 100
| 0.508264
|
7db90f755c7d85a22248808cd48f52a1caefb558
| 3,399
|
package com.learn.controller;
import com.learn.pojo.UserInfo;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.List;
/**
* <p>
* AutoDeliverController
* </p>
*
* @author Yuhaoran
* @since 2021/12/8
*/
@RestController
@RequestMapping("/autoDeliver")
public class AutoDeliverController {
@Autowired
private RestTemplate restTemplate;
@Autowired
private DiscoveryClient discoveryClient;
@HystrixCommand(
threadPoolKey = "findOpenStatusByUid",
threadPoolProperties = {
@HystrixProperty(name="coreSize",value = "2"),// 线程数
@HystrixProperty(name="maxQueueSize",value="20") // 等待队列长度
},
commandProperties = {
//@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "2000"),
//配置一个8s内请求次数达到2个失败率达到50%就跳闸的熔断器,跳闸后的活动窗口设置为3s
// @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds",value = "8000"),
// @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "2"),
// @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "50"),
// @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "3000")
},
fallbackMethod = "myFallBack"
)
@GetMapping("/findOpenStatusByUid")
public Integer findOpenStatusByUid(@RequestParam("uid") Integer uid){
String url = "http://user/user/findUserById?id="+uid;
System.out.println("############URL##########:"+url);
UserInfo forObject = restTemplate.getForObject(url, UserInfo.class);
return forObject.getOpen();
}
@HystrixCommand(
// 线程池标识,要保持唯一,不唯一的话就共用了
threadPoolKey = "findOpenStatusByUid1",
// 线程池细节属性配置
threadPoolProperties = {
@HystrixProperty(name="coreSize",value = "2"),// 线程数
@HystrixProperty(name="maxQueueSize",value="20") // 等待队列长度
},
commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "2000")
},
fallbackMethod = "myFallBack"
)
@GetMapping("/findOpenStatusByUid1")
public Integer findOpenStatusByUid1(@RequestParam("uid") Integer uid){
String url = "http://user/user/findUserById?id="+uid;
System.out.println("############URL##########:"+url);
UserInfo forObject = restTemplate.getForObject(url, UserInfo.class);
return forObject.getOpen();
}
//回退方法,返回默认值
public Integer myFallBack(Integer uid){
return -1;//默认数据\兜底数据
}
}
| 39.523256
| 113
| 0.65637
|
d6fae4fcadfc61a1d0d277b2de36035bbc8d6912
| 1,932
|
package me.jessyan.mvparms.photomark.mvp.model.entity;
import java.io.Serializable;
/**
* Created by zhiPeng.S on 2017/5/9.
*/
public class PList implements Serializable{
/**
* pid : 1
* pno : p-123456
* pname : postertest
* type : 1
* originalsrc : left_img.png
* thumbnailsrc : 1
* width : 674
* height : 1198
*/
private int pid;
private String pno;
private String pname;
private int type;
private String originalsrc;
private String thumbnailsrc;
private String backgroundsrc;
private String width;
private String height;
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public String getPno() {
return pno;
}
public void setPno(String pno) {
this.pno = pno;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getOriginalsrc() {
return originalsrc;
}
public void setOriginalsrc(String originalsrc) {
this.originalsrc = originalsrc;
}
public String getThumbnailsrc() {
return thumbnailsrc;
}
public void setThumbnailsrc(String thumbnailsrc) {
this.thumbnailsrc = thumbnailsrc;
}
public String getBackgroundsrc() {
return backgroundsrc;
}
public void setBackgroundsrc(String backgroundsrc) {
this.backgroundsrc = backgroundsrc;
}
public String getWidth() {
return width;
}
public void setWidth(String width) {
this.width = width;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
}
| 18.576923
| 56
| 0.59472
|
84f33e81afd036f04d0016e442ef4d39b6c80e3b
| 3,525
|
package com.zhengzhou.hadoop.multiple_In_out;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import java.io.IOException;
public class Multipleoutput {
static String input = "hdfs://127.0.0.1:9000/mr/input";
static String output = "hdfs://127.0.0.1:9000/mr/output";
/**
* @param args
* @throws IOException
* @throws InterruptedException
* @throws ClassNotFoundException
*/
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
// TODO Auto-generated method stub
Job job = new Job();
job.setJarByClass(Multipleoutput.class);
job.setMapperClass(Map.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(Text.class);
job.setReducerClass(Reduce.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
job.setInputFormatClass(TextInputFormat.class);
job.setOutputFormatClass(TextOutputFormat.class);
MultipleOutputs.addNamedOutput(job, "china", TextOutputFormat.class, Text.class, Text.class);
MultipleOutputs.addNamedOutput(job, "usa", TextOutputFormat.class, Text.class, Text.class);
MultipleOutputs.addNamedOutput(job, "cpeople", TextOutputFormat.class, Text.class, Text.class);
FileInputFormat.addInputPath(job, new Path(input));
FileOutputFormat.setOutputPath(job, new Path(output));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
public static class Map extends Mapper<LongWritable, Text, Text, Text> {
private static Text k = new Text();
private static Text v = new Text();
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String[] list = value.toString().split(",");
k.set(list[0]);
v.set(list[1]);
context.write(k, v);
}
}
public static class Reduce extends Reducer<Text, Text, Text, Text> {
private MultipleOutputs mos;
public void setup(Context context) {
mos = new MultipleOutputs(context);
}
public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
String k = key.toString();
for (Text t : values) {
if ("中国".equals(k)) {
System.out.println(t.toString());
mos.write("china", new Text("中国"), t);
} else if ("美国".equals(k)) {
System.out.println(t.toString());
mos.write("usa", new Text("美国"), t);
} else if ("中国人".equals(k)) {
System.out.println(t.toString());
mos.write("cpeople", new Text("中国人"), t);
}
}
}
public void cleanup(Context context) throws IOException, InterruptedException {
mos.close();
}
}
}
| 37.105263
| 119
| 0.643404
|
4f6956778733011d3c07b51c0000f692a84be2e0
| 872
|
package mariculture.api.fishery;
import mariculture.api.fishery.fish.FishSpecies;
import net.minecraft.inventory.IInventory;
import cpw.mods.fml.common.eventhandler.Cancelable;
import cpw.mods.fml.common.eventhandler.Event;
@Cancelable
public class FishTickEvent extends Event {
/** This event is called everytime, a fish ticks; Output slots are 7-12
* This is called before a fish ticks, you can cancel the event to stop,
* them from producing eggs/products etc. **/
//The Male Slot is 5, The Female Slot Number is 6, if you wish to affect them
public final boolean isMale;
public final FishSpecies species;
public final IInventory inventory;
public FishTickEvent(IInventory inventory, FishSpecies species, boolean isMale) {
this.inventory = inventory;
this.species = species;
this.isMale = false;
}
}
| 36.333333
| 85
| 0.732798
|
99dfa322c38fc6f7626640a04a17ed06b8a77e78
| 7,757
|
// Template Source: BaseEntityRequest.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.requests;
import com.microsoft.graph.http.IRequestBuilder;
import com.microsoft.graph.core.ClientException;
import com.microsoft.graph.models.DeviceManagementConfigurationPolicyPolicySetItem;
import java.util.Arrays;
import java.util.EnumSet;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;
import com.microsoft.graph.core.IBaseClient;
import com.microsoft.graph.http.BaseRequest;
import com.microsoft.graph.http.HttpMethod;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the Device Management Configuration Policy Policy Set Item Request.
*/
public class DeviceManagementConfigurationPolicyPolicySetItemRequest extends BaseRequest<DeviceManagementConfigurationPolicyPolicySetItem> {
/**
* The request for the DeviceManagementConfigurationPolicyPolicySetItem
*
* @param requestUrl the request URL
* @param client the service client
* @param requestOptions the options for this request
*/
public DeviceManagementConfigurationPolicyPolicySetItemRequest(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) {
super(requestUrl, client, requestOptions, DeviceManagementConfigurationPolicyPolicySetItem.class);
}
/**
* Gets the DeviceManagementConfigurationPolicyPolicySetItem from the service
*
* @return a future with the result
*/
@Nonnull
public java.util.concurrent.CompletableFuture<DeviceManagementConfigurationPolicyPolicySetItem> getAsync() {
return sendAsync(HttpMethod.GET, null);
}
/**
* Gets the DeviceManagementConfigurationPolicyPolicySetItem from the service
*
* @return the DeviceManagementConfigurationPolicyPolicySetItem from the request
* @throws ClientException this exception occurs if the request was unable to complete for any reason
*/
@Nullable
public DeviceManagementConfigurationPolicyPolicySetItem get() throws ClientException {
return send(HttpMethod.GET, null);
}
/**
* Delete this item from the service
*
* @return a future with the deletion result
*/
@Nonnull
public java.util.concurrent.CompletableFuture<DeviceManagementConfigurationPolicyPolicySetItem> deleteAsync() {
return sendAsync(HttpMethod.DELETE, null);
}
/**
* Delete this item from the service
* @return the resulting response if the service returns anything on deletion
*
* @throws ClientException if there was an exception during the delete operation
*/
@Nullable
public DeviceManagementConfigurationPolicyPolicySetItem delete() throws ClientException {
return send(HttpMethod.DELETE, null);
}
/**
* Patches this DeviceManagementConfigurationPolicyPolicySetItem with a source
*
* @param sourceDeviceManagementConfigurationPolicyPolicySetItem the source object with updates
* @return a future with the result
*/
@Nonnull
public java.util.concurrent.CompletableFuture<DeviceManagementConfigurationPolicyPolicySetItem> patchAsync(@Nonnull final DeviceManagementConfigurationPolicyPolicySetItem sourceDeviceManagementConfigurationPolicyPolicySetItem) {
return sendAsync(HttpMethod.PATCH, sourceDeviceManagementConfigurationPolicyPolicySetItem);
}
/**
* Patches this DeviceManagementConfigurationPolicyPolicySetItem with a source
*
* @param sourceDeviceManagementConfigurationPolicyPolicySetItem the source object with updates
* @return the updated DeviceManagementConfigurationPolicyPolicySetItem
* @throws ClientException this exception occurs if the request was unable to complete for any reason
*/
@Nullable
public DeviceManagementConfigurationPolicyPolicySetItem patch(@Nonnull final DeviceManagementConfigurationPolicyPolicySetItem sourceDeviceManagementConfigurationPolicyPolicySetItem) throws ClientException {
return send(HttpMethod.PATCH, sourceDeviceManagementConfigurationPolicyPolicySetItem);
}
/**
* Creates a DeviceManagementConfigurationPolicyPolicySetItem with a new object
*
* @param newDeviceManagementConfigurationPolicyPolicySetItem the new object to create
* @return a future with the result
*/
@Nonnull
public java.util.concurrent.CompletableFuture<DeviceManagementConfigurationPolicyPolicySetItem> postAsync(@Nonnull final DeviceManagementConfigurationPolicyPolicySetItem newDeviceManagementConfigurationPolicyPolicySetItem) {
return sendAsync(HttpMethod.POST, newDeviceManagementConfigurationPolicyPolicySetItem);
}
/**
* Creates a DeviceManagementConfigurationPolicyPolicySetItem with a new object
*
* @param newDeviceManagementConfigurationPolicyPolicySetItem the new object to create
* @return the created DeviceManagementConfigurationPolicyPolicySetItem
* @throws ClientException this exception occurs if the request was unable to complete for any reason
*/
@Nullable
public DeviceManagementConfigurationPolicyPolicySetItem post(@Nonnull final DeviceManagementConfigurationPolicyPolicySetItem newDeviceManagementConfigurationPolicyPolicySetItem) throws ClientException {
return send(HttpMethod.POST, newDeviceManagementConfigurationPolicyPolicySetItem);
}
/**
* Creates a DeviceManagementConfigurationPolicyPolicySetItem with a new object
*
* @param newDeviceManagementConfigurationPolicyPolicySetItem the object to create/update
* @return a future with the result
*/
@Nonnull
public java.util.concurrent.CompletableFuture<DeviceManagementConfigurationPolicyPolicySetItem> putAsync(@Nonnull final DeviceManagementConfigurationPolicyPolicySetItem newDeviceManagementConfigurationPolicyPolicySetItem) {
return sendAsync(HttpMethod.PUT, newDeviceManagementConfigurationPolicyPolicySetItem);
}
/**
* Creates a DeviceManagementConfigurationPolicyPolicySetItem with a new object
*
* @param newDeviceManagementConfigurationPolicyPolicySetItem the object to create/update
* @return the created DeviceManagementConfigurationPolicyPolicySetItem
* @throws ClientException this exception occurs if the request was unable to complete for any reason
*/
@Nullable
public DeviceManagementConfigurationPolicyPolicySetItem put(@Nonnull final DeviceManagementConfigurationPolicyPolicySetItem newDeviceManagementConfigurationPolicyPolicySetItem) throws ClientException {
return send(HttpMethod.PUT, newDeviceManagementConfigurationPolicyPolicySetItem);
}
/**
* Sets the select clause for the request
*
* @param value the select clause
* @return the updated request
*/
@Nonnull
public DeviceManagementConfigurationPolicyPolicySetItemRequest select(@Nonnull final String value) {
addSelectOption(value);
return this;
}
/**
* Sets the expand clause for the request
*
* @param value the expand clause
* @return the updated request
*/
@Nonnull
public DeviceManagementConfigurationPolicyPolicySetItemRequest expand(@Nonnull final String value) {
addExpandOption(value);
return this;
}
}
| 44.58046
| 233
| 0.75622
|
02df66eb307f6f41eb25537cc1a844b84ae2ad31
| 1,495
|
/*******************************************************************************
*
* Copyright FUJITSU LIMITED 2020
*
* Creation Date: 27.02.2020
*
*******************************************************************************/
package org.oscm.logging;
public enum AppenderConfiguration {
SYSTEM_LOG_APPENDER("SystemLogAppender", "system.log", "system-%i.log"),
ACCESS_LOG_APPENDER("AccessLogAppender", "access.log", "access-%i.log"),
AUDIT_LOG_APPENDER("AuditLogAppender", "audit.log", "audit-%i.log"),
PROXY_LOG_APPENDER("ProxyLogAppender", "reverseproxy.log", "reverseproxy-%i.log");
AppenderConfiguration(String name, String fileName, String filePattern) {
this.name = name;
this.fileName = fileName;
this.filePattern = filePattern;
}
private String name;
private String fileName;
private String filePattern;
private static final String MAX_BACKUP_INDEX = "5";
private static final String MAX_FILE_SIZE = "10MB";
private static final String PATTERN_LAYOUT =
"%d{MM/dd/yyyy_HH:mm:ss.SSS} FSP_INTS-BSS: %p: ThreadID %t: %c{1}: %m%n";
public String getFileName() {
return fileName;
}
public String getFilePattern() {
return filePattern;
}
public String getName() {
return name;
}
public static String getMaxBackupIndex() {
return MAX_BACKUP_INDEX;
}
public static String getMaxFileSize() {
return MAX_FILE_SIZE;
}
public static String getPatternLayout() {
return PATTERN_LAYOUT;
}
}
| 26.696429
| 84
| 0.6301
|
2a4c3c4bcbb6717db1a3dbd50c579dede047c2b0
| 1,159
|
package org.openexi.proc.common;
import java.io.IOException;
public final class BinaryDataSource {
private byte[] m_byteArray;
private int m_startIndex;
private int m_length;
private long m_n_remainingBytes;
private IBinaryValueScanner m_scanner;
public final byte[] getByteArray() {
return m_byteArray;
}
public final int getStartIndex() {
return m_startIndex;
}
public final int getLength() {
return m_length;
}
public final long getRemainingBytesCount() {
return m_n_remainingBytes;
}
/**
* @y.exclude
*/
public void setValues(byte[] byteArray, int startIndex, int length, IBinaryValueScanner scanner, long n_remainingBytes) {
m_byteArray = byteArray;
m_startIndex = startIndex;
m_length = length;
m_n_remainingBytes = n_remainingBytes;
m_scanner = scanner;
}
public boolean hasNext() {
return m_n_remainingBytes > 0;
}
public int next() throws IOException {
if (m_n_remainingBytes > 0) {
m_scanner.scan(m_n_remainingBytes, this);
return m_length;
}
return -1;
}
}
| 21.072727
| 124
| 0.656601
|
1e82de05c2132a3f0ce1978b0db511b7fbff945a
| 11,018
|
package org.bf2.admin.kafka.admin;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.PartitionInfo;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.errors.InvalidPartitionsException;
import org.apache.kafka.common.errors.TimeoutException;
import org.apache.kafka.common.errors.UnknownTopicOrPartitionException;
import org.apache.kafka.common.header.Header;
import org.apache.kafka.common.header.Headers;
import org.bf2.admin.kafka.admin.handlers.AdminClientFactory;
import org.bf2.admin.kafka.admin.model.Types;
import org.jboss.logging.Logger;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
@RequestScoped
public class RecordOperations {
private static final Logger log = Logger.getLogger(RecordOperations.class);
public static final String BINARY_DATA_MESSAGE = "Binary or non-UTF-8 encoded data cannot be displayed";
static final int REPLACEMENT_CHARACTER = '\uFFFD';
@Inject
AdminClientFactory clientFactory;
public Types.PagedResponse<Types.Record> consumeRecords(String topicName,
Integer partition,
Integer offset,
String timestamp,
Integer limit,
List<String> include,
Integer maxValueLength) {
try (Consumer<byte[], byte[]> consumer = clientFactory.createConsumer(limit)) {
List<PartitionInfo> partitions = consumer.partitionsFor(topicName);
if (partitions.isEmpty()) {
throw noSuchTopic(topicName);
}
List<TopicPartition> assignments = partitions.stream()
.filter(p -> partition == null || partition.equals(p.partition()))
.map(p -> new TopicPartition(p.topic(), p.partition()))
.collect(Collectors.toList());
if (assignments.isEmpty()) {
throw noSuchTopicPartition(topicName, partition);
}
consumer.assign(assignments);
if (timestamp != null) {
Long tsMillis = stringToTimestamp(timestamp);
Map<TopicPartition, Long> timestampsToSearch =
assignments.stream().collect(Collectors.toMap(Function.identity(), p -> tsMillis));
consumer.offsetsForTimes(timestampsToSearch)
.forEach((p, tsOffset) -> {
if (tsOffset != null) {
consumer.seek(p, tsOffset.offset());
} else {
/*
* No offset for the time-stamp (future date?), seek to
* end and return nothing for this partition.
*/
consumer.seekToEnd(List.of(p));
}
});
} else {
Map<TopicPartition, Long> endOffsets = consumer.endOffsets(assignments);
assignments.forEach(p -> {
long partitionEnd = endOffsets.get(p);
if (offset == null) {
// Fetch the latest records
consumer.seek(p, Math.max(partitionEnd - limit, 0));
} else if (offset <= partitionEnd) {
consumer.seek(p, offset);
} else {
/*
* Requested offset is beyond the end of the partition,
* seek to end and return nothing for this partition.
*/
consumer.seek(p, endOffsets.get(p));
}
});
}
var records = consumer.poll(Duration.ofSeconds(2));
List<Types.Record> items = StreamSupport.stream(records.spliterator(), false)
.map(rec -> {
Types.Record item = new Types.Record();
setProperty(Types.Record.PROP_PARTITION, include, rec::partition, item::setPartition);
setProperty(Types.Record.PROP_OFFSET, include, rec::offset, item::setOffset);
setProperty(Types.Record.PROP_TIMESTAMP, include, () -> timestampToString(rec.timestamp()), item::setTimestamp);
setProperty(Types.Record.PROP_TIMESTAMP_TYPE, include, rec.timestampType()::name, item::setTimestampType);
setProperty(Types.Record.PROP_KEY, include, rec::key, k -> item.setKey(bytesToString(k, maxValueLength)));
setProperty(Types.Record.PROP_VALUE, include, rec::value, v -> item.setValue(bytesToString(v, maxValueLength)));
setProperty(Types.Record.PROP_HEADERS, include, () -> headersToMap(rec.headers(), maxValueLength), item::setHeaders);
return item;
})
.collect(Collectors.toList());
return Types.PagedResponse.forItems(items).result();
}
}
public CompletionStage<Types.Record> produceRecord(String topicName, Types.Record input) {
CompletableFuture<Types.Record> promise = new CompletableFuture<>();
Producer<String, String> producer = clientFactory.createProducer();
try {
List<PartitionInfo> partitions = producer.partitionsFor(topicName);
if (partitions.isEmpty()) {
promise.completeExceptionally(noSuchTopic(topicName));
} else if (input.getPartition() != null && partitions.stream().noneMatch(p -> input.getPartition().equals(p.partition()))) {
promise.completeExceptionally(noSuchTopicPartition(topicName, input.getPartition()));
} else {
send(topicName, input, producer, promise);
}
} catch (TimeoutException e) {
promise.completeExceptionally(noSuchTopic(topicName));
}
return promise.whenComplete((result, exception) -> {
try {
producer.close(Duration.ZERO);
} catch (Exception e) {
log.warnf("Exception closing Kafka Producer", e);
}
});
}
void send(String topicName, Types.Record input, Producer<String, String> producer, CompletableFuture<Types.Record> promise) {
String key = input.getKey();
List<Header> headers = input.getHeaders() != null ? input.getHeaders()
.entrySet()
.stream()
.map(h -> new Header() {
@Override
public String key() {
return h.getKey();
}
@Override
public byte[] value() {
return h.getValue() != null ? h.getValue().getBytes() : null;
}
})
.collect(Collectors.toList()) : Collections.emptyList();
ProducerRecord<String, String> request = new ProducerRecord<>(topicName, input.getPartition(), stringToTimestamp(input.getTimestamp()), key, input.getValue(), headers);
producer.send(request, (meta, exception) -> {
if (exception != null) {
promise.completeExceptionally(exception);
} else {
Types.Record result = new Types.Record();
result.setPartition(meta.partition());
if (meta.hasOffset()) {
result.setOffset(meta.offset());
}
if (meta.hasTimestamp()) {
result.setTimestamp(timestampToString(meta.timestamp()));
}
result.setKey(input.getKey());
result.setValue(input.getValue());
result.setHeaders(input.getHeaders());
promise.complete(result);
}
});
}
<T> void setProperty(String fieldName, List<String> include, Supplier<T> source, java.util.function.Consumer<T> target) {
if (include.isEmpty() || include.contains(fieldName)) {
target.accept(source.get());
}
}
String bytesToString(byte[] bytes, Integer maxValueLength) {
if (bytes == null) {
return null;
}
if (bytes.length == 0) {
return "";
}
int bufferSize = maxValueLength != null ? Math.min(maxValueLength, bytes.length) : bytes.length;
StringBuilder buffer = new StringBuilder(bufferSize);
try (Reader reader = new InputStreamReader(new ByteArrayInputStream(bytes), StandardCharsets.UTF_8)) {
int input;
while ((input = reader.read()) > -1) {
if (input == REPLACEMENT_CHARACTER || !Character.isDefined(input)) {
return BINARY_DATA_MESSAGE;
}
buffer.append((char) input);
if (maxValueLength != null && buffer.length() == maxValueLength) {
break;
}
}
return buffer.toString();
} catch (IOException e) {
return BINARY_DATA_MESSAGE;
}
}
Map<String, String> headersToMap(Headers headers, Integer maxValueLength) {
Map<String, String> headerMap = new LinkedHashMap<>();
headers.iterator().forEachRemaining(h -> headerMap.put(h.key(), bytesToString(h.value(), maxValueLength)));
return headerMap;
}
String timestampToString(long timestamp) {
return Instant.ofEpochMilli(timestamp).atZone(ZoneOffset.UTC).toString();
}
Long stringToTimestamp(String value) {
if (value == null) {
return null;
}
return ZonedDateTime.parse(value).toInstant().toEpochMilli();
}
static UnknownTopicOrPartitionException noSuchTopic(String topicName) {
return new UnknownTopicOrPartitionException("No such topic: " + topicName);
}
static InvalidPartitionsException noSuchTopicPartition(String topicName, int partition) {
return new InvalidPartitionsException(String.format("No such partition for topic %s: %d", topicName, partition));
}
}
| 41.265918
| 176
| 0.581503
|
d43abcf62def8ff44f315164abda4a8da3305cd8
| 1,859
|
package com.paragon464.gameserver.io.database.table.definition.shop;
import com.paragon464.gameserver.io.database.pool.impl.ConnectionPool;
import com.paragon464.gameserver.model.item.ShopItem;
import com.paragon464.gameserver.model.shop.Shop;
import com.paragon464.gameserver.model.shop.ShopManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public final class ShopTable {
private static final Logger LOGGER = LoggerFactory.getLogger(ShopTable.class);
public static void load() {
try (Connection connection = ConnectionPool.getPool().getConnection();
PreparedStatement statement = connection.prepareStatement("SELECT * FROM paragon_definition_shop")) {
final ResultSet result = statement.executeQuery();
while (result.next()) {
final int id = result.getInt("id");
final String name = result.getString("name");
final String currency = result.getString("currency");
final boolean generalStore = result.getBoolean("general_store");
final boolean buysBack = result.getBoolean("buys_back");
final Shop shop = new Shop();
shop.setId(id);
shop.setName(name);
shop.setCurrency(currency);
shop.setGeneralShop(generalStore);
shop.setBuysBack(buysBack);
shop.setStock(new ShopItem[40]);
ShopManager.shop_definitions.add(shop);
}
} catch (SQLException e) {
while (e != null) {
LOGGER.error("An error occurred whilst loading the shop table!", e);
e = e.getNextException();
}
}
}
}
| 39.553191
| 114
| 0.640129
|
6d8b670b076cf089557788e15c3ff75214e6e0ad
| 1,532
|
/*
* The MIT License (MIT) Copyright (c) 2020-2021 artipie.com
* https://github.com/artipie/http/blob/master/LICENSE.txt
*/
package com.artipie.http.rs;
import com.artipie.http.Connection;
import com.artipie.http.Headers;
import com.artipie.http.Response;
import io.reactivex.Flowable;
import java.nio.ByteBuffer;
import java.util.concurrent.CompletionStage;
/**
* Standard responses.
* @since 0.8
*/
public enum StandardRs implements Response {
/**
* Empty response.
*/
EMPTY(con -> con.accept(RsStatus.OK, Headers.EMPTY, Flowable.empty())),
/**
* OK 200 response.
*/
OK(EMPTY),
/**
* Success response without content.
*/
NO_CONTENT(new RsWithStatus(RsStatus.NO_CONTENT)),
/**
* Not found response.
*/
NOT_FOUND(new RsWithStatus(RsStatus.NOT_FOUND)),
/**
* Not found with json.
*/
JSON_NOT_FOUND(
new RsWithBody(
new RsWithHeaders(
new RsWithStatus(RsStatus.NOT_FOUND),
new Headers.From("Content-Type", "application/json")
),
ByteBuffer.wrap("{\"error\" : \"not found\"}".getBytes())
)
);
/**
* Origin response.
*/
private final Response origin;
/**
* Ctor.
* @param origin Origin response
*/
StandardRs(final Response origin) {
this.origin = origin;
}
@Override
public CompletionStage<Void> send(final Connection connection) {
return this.origin.send(connection);
}
}
| 23.212121
| 75
| 0.608355
|
012472e5616fe5d98e643c9606ef99421cb21501
| 5,766
|
/*
* Copyright (c) 2015 Nokia Solutions and Networks. All rights reserved.
*/
package com.nsn.ood.cls.rest.filter.certificates.util;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.powermock.api.easymock.PowerMock.replayAll;
import static org.powermock.api.easymock.PowerMock.verifyAll;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
/**
* @author wro50095
*
*/
public class CertificatePathValidatorTest {
private CertificatePathValidator bean;
@Before
public void setUp() throws Exception {
final List<X509Certificate> trustedCertificates = new ArrayList<>();
trustedCertificates.add(loadRootCACertificate());
trustedCertificates.add(loadServerCACertificate());
trustedCertificates.add(loadInstallationCACertificate());
this.bean = new CertificatePathValidator(trustedCertificates);
}
@Test
public void testNoCertificates() throws Exception {
replayAll();
assertFalse(this.bean.checkCertificates(Collections.<X509Certificate> emptyList()));
verifyAll();
}
@Test
public void testClientCertificateFromServerAndRootCa() throws Exception {
final List<X509Certificate> certificates = new ArrayList<>();
certificates.add(loadValidClientCertificateSignedByServer());
certificates.add(loadServerCACertificate());
certificates.add(loadInstallationCACertificate());
certificates.add(loadRootCACertificate());
replayAll();
assertTrue(this.bean.checkCertificates(certificates));
verifyAll();
}
@Test
public void testClientCertificateFromServerAndServerCa() throws Exception {
final List<X509Certificate> certificates = new ArrayList<>();
certificates.add(loadValidClientCertificateSignedByServer());
certificates.add(loadServerCACertificate());
replayAll();
assertTrue(this.bean.checkCertificates(certificates));
verifyAll();
}
@Test
public void testGenericClientCertificateAndRootCaMutlipleTimes() throws Exception {
final List<X509Certificate> certificates = new ArrayList<>();
certificates.add(loadValidClientCertificateSignedByRoot());
certificates.add(loadRootCACertificate());
replayAll();
assertTrue(this.bean.checkCertificates(certificates));
assertTrue(this.bean.checkCertificates(certificates));
verifyAll();
}
@Test
public void testGenericClientCertificateAndRootCa() throws Exception {
final List<X509Certificate> certificates = new ArrayList<>();
certificates.add(loadValidClientCertificateSignedByRoot());
certificates.add(loadRootCACertificate());
replayAll();
assertTrue(this.bean.checkCertificates(certificates));
verifyAll();
}
@Test
public void testClientCertificateSignedByAnotherCLS() throws Exception {
final List<X509Certificate> certificates = new ArrayList<>();
certificates.add(loadNotValidClientCertificate());
certificates.add(loadAnotherCLServerCACertificate());
certificates.add(loadAnotherCLSServerCertificate());
certificates.add(loadRootCACertificate());
replayAll();
assertFalse(this.bean.checkCertificates(certificates));
verifyAll();
}
private X509Certificate loadAnotherCLSServerCertificate() throws CertificateException, FileNotFoundException,
IOException {
return loadCertificateFromResource("/certs/notValid/CLS_Server.crt");
}
private X509Certificate loadAnotherCLServerCACertificate() throws CertificateException, FileNotFoundException,
IOException {
return loadCertificateFromResource("/certs/notValid/CLS_Server_CA.crt");
}
private X509Certificate loadNotValidClientCertificate() throws CertificateException, FileNotFoundException,
IOException {
return loadCertificateFromResource("/certs/notValid/CLS_Client.crt");
}
private X509Certificate loadValidClientCertificateSignedByServer() throws CertificateException,
FileNotFoundException, IOException {
return loadCertificateFromResource("/certs/valid/CLS_Client.crt");
}
private X509Certificate loadValidClientCertificateSignedByRoot() throws CertificateException,
FileNotFoundException, IOException {
return loadCertificateFromResource("/certs/valid/CLS_Client_Root.crt");
}
private X509Certificate loadRootCACertificate() throws FileNotFoundException, IOException, CertificateException {
return loadCertificateFromResource("/certs/valid/CLS_Root_CA.crt");
}
private X509Certificate loadInstallationCACertificate() throws FileNotFoundException, IOException,
CertificateException {
return loadCertificateFromResource("/certs/valid/CLS_Installation_CA.crt");
}
private X509Certificate loadServerCACertificate() throws FileNotFoundException, IOException, CertificateException {
return loadCertificateFromResource("/certs/valid/CLS_Server_CA.crt");
}
@SuppressWarnings("unused")
private X509Certificate loadCertificate(final String path) throws CertificateException, FileNotFoundException,
IOException {
try (final InputStream is = new FileInputStream(path)) {
return loadCertificate(is);
}
}
private X509Certificate loadCertificateFromResource(final String path) throws CertificateException,
FileNotFoundException, IOException {
try (final InputStream is = this.getClass().getResourceAsStream(path)) {
return loadCertificate(is);
}
}
private X509Certificate loadCertificate(final InputStream is) throws CertificateException {
final CertificateFactory fact = CertificateFactory.getInstance("X.509");
return (X509Certificate) fact.generateCertificate(is);
}
}
| 33.917647
| 116
| 0.805931
|
d6ebc85494e4adad9ae2d2d78530d344b7ed82e3
| 105
|
package ferrari;
public interface Car {
String getDriverName();
void brake();
void gas();
}
| 13.125
| 27
| 0.638095
|
8ab96a54cf764be6352f927d829458b44e1346cb
| 1,415
|
//给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。
//
//
//
// 示例:
//
// 输入:"Let's take LeetCode contest"
//输出:"s'teL ekat edoCteeL tsetnoc"
//
//
//
//
// 提示:
//
//
// 在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。
//
// Related Topics 字符串
// 👍 271 👎 0
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class _557_ReverseWordsInAStringIii {
public static void main(String[] args) {
Solution solution = new _557_ReverseWordsInAStringIii().new Solution();
System.out.println(solution);
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public String reverseWords(String s) {
List<String> reversed = Arrays.stream(s.split(" ")).map(str -> {
StringBuilder sb = new StringBuilder();
for (int i = str.length() - 1; i >= 0; i--) {
sb.append(str.charAt(i));
}
return sb.toString();
}).collect(Collectors.toList());
StringBuilder sb = new StringBuilder();
for (int i = 0; i < reversed.size(); i++) {
sb.append(reversed.get(i));
if (i < reversed.size() - 1) {
sb.append(' ');
}
}
return sb.toString();
}
}
//leetcode submit region end(Prohibit modification and deletion)
}
| 26.203704
| 79
| 0.554064
|
301b88fc504027d101344c879a027453ae8b63b0
| 376
|
package com.clj.fastble.callback;
import com.clj.fastble.exception.BleException;
public abstract class BleIndicateCallback extends BleBaseCallback{
public abstract void onIndicateSuccess(String strMac);
public abstract void onIndicateFailure(String strMac, BleException exception);
public abstract void onCharacteristicChanged(String strMac, byte[] data);
}
| 26.857143
| 82
| 0.808511
|
e3946192261297fa4277b18ccb09e0baf0f7832a
| 7,853
|
//
// ========================================================================
// Copyright (c) 1995-2017 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.server.session;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.junit.Test;
/**
* AbstractLastAccessTimeTest
*
* This test checks that a session can migrate from node A to node B, kept in use in node B
* past the time at which it would have expired due to inactivity on node A but is NOT
* scavenged by node A. In other words, it tests that a session that migrates from one node
* to another is not timed out on the original node.
*/
public abstract class AbstractLastAccessTimeTest
{
public abstract AbstractTestServer createServer(int port, int max, int scavenge);
@Test
public void testLastAccessTime() throws Exception
{
String contextPath = "";
String servletMapping = "/server";
int maxInactivePeriod = 8; //session will timeout after 8 seconds
int scavengePeriod = 2; //scavenging occurs every 2 seconds
AbstractTestServer server1 = createServer(0, maxInactivePeriod, scavengePeriod);
TestServlet servlet1 = new TestServlet();
ServletHolder holder1 = new ServletHolder(servlet1);
ServletContextHandler context = server1.addContext(contextPath);
TestSessionListener listener1 = new TestSessionListener();
context.addEventListener(listener1);
context.addServlet(holder1, servletMapping);
try
{
server1.start();
int port1=server1.getPort();
AbstractTestServer server2 = createServer(0, maxInactivePeriod, scavengePeriod);
server2.addContext(contextPath).addServlet(TestServlet.class, servletMapping);
try
{
server2.start();
int port2=server2.getPort();
HttpClient client = new HttpClient();
client.start();
try
{
// Perform one request to server1 to create a session
ContentResponse response1 = client.GET("http://localhost:" + port1 + contextPath + servletMapping + "?action=init");
assertEquals(HttpServletResponse.SC_OK, response1.getStatus());
assertEquals("test", response1.getContentAsString());
String sessionCookie = response1.getHeaders().getStringField("Set-Cookie");
assertTrue( sessionCookie != null );
// Mangle the cookie, replacing Path with $Path, etc.
sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");
// Perform some request to server2 using the session cookie from the previous request
// This should migrate the session from server1 to server2, and leave server1's
// session in a very stale state, while server2 has a very fresh session.
// We want to test that optimizations done to the saving of the shared lastAccessTime
// do not break the correct working
int requestInterval = 500;
for (int i = 0; i < maxInactivePeriod * (1000 / requestInterval); ++i)
{
Request request = client.newRequest("http://localhost:" + port2 + contextPath + servletMapping);
request.header("Cookie", sessionCookie);
ContentResponse response2 = request.send();
assertEquals(HttpServletResponse.SC_OK , response2.getStatus());
assertEquals("test", response2.getContentAsString());
String setCookie = response2.getHeaders().getStringField("Set-Cookie");
if (setCookie!=null)
sessionCookie = setCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");
Thread.sleep(requestInterval);
}
// At this point, session1 should be eligible for expiration.
// Let's wait for the scavenger to run, waiting 2.5 times the scavenger period
Thread.sleep(scavengePeriod * 2500L);
//check that the session was not scavenged over on server1 by ensuring that the SessionListener destroy method wasn't called
assertFalse(listener1.destroyed);
}
finally
{
client.stop();
}
}
finally
{
server2.stop();
}
}
finally
{
server1.stop();
}
}
public static class TestSessionListener implements HttpSessionListener
{
public boolean destroyed = false;
public boolean created = false;
@Override
public void sessionDestroyed(HttpSessionEvent se)
{
destroyed = true;
}
@Override
public void sessionCreated(HttpSessionEvent se)
{
created = true;
}
}
public static class TestServlet extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse httpServletResponse) throws ServletException, IOException
{
String action = request.getParameter("action");
if ("init".equals(action))
{
HttpSession session = request.getSession(true);
session.setAttribute("test", "test");
sendResult(session, httpServletResponse.getWriter());
}
else
{
HttpSession session = request.getSession(false);
// if we node hopped we should get the session and test should already be present
sendResult(session, httpServletResponse.getWriter());
if (session!=null)
{
session.setAttribute("test", "test");
}
}
}
private void sendResult(HttpSession session, PrintWriter writer)
{
if (session != null)
{
writer.print(session.getAttribute("test"));
}
else
{
writer.print("null");
}
}
}
}
| 39.069652
| 144
| 0.582707
|
52f0ca664533678f18a7e09b36d3a832f3e8c7b5
| 1,711
|
package run.mojo.actor;
import java.lang.reflect.Method;
import run.mojo.MojoError;
import run.mojo.MojoError.Code;
import run.mojo.message.MessageCodec;
/**
*
*/
public class AskDescriptor {
public final MessageCodec messageCodec;
public final MessageCodec responseCodec;
public final Method method;
public final run.mojo.Ask ask;
ActorDescriptor actor;
int id;
int messageId;
int responseId;
ActorRuntime runtime;
ActorService[] services;
private AskDescriptor(
MessageCodec messageCodec,
MessageCodec responseCodec,
Method method) {
this.messageCodec = messageCodec;
this.responseCodec = responseCodec;
this.method = method;
this.ask = method.getDeclaredAnnotation(run.mojo.Ask.class);
}
public static AskDescriptor create(
MessageCodec messageCodec,
MessageCodec responseCodec,
Class<? extends MetalActor> actorClass,
String methodName) {
try {
Method m = actorClass.getDeclaredMethod(methodName, messageCodec.messageClass());
return new AskDescriptor(messageCodec, responseCodec, m);
} catch (Throwable e) {
throw new MojoError(e, Code.BAD_INPUT);
}
}
boolean isMatch(AskDescriptor other) {
return this.messageCodec.messageClass().equals(other.messageCodec.messageClass())
&& this.responseCodec.messageClass().equals(other.responseCodec.messageClass())
&& this.method.equals(other.method);
}
boolean copyFrom(AskDescriptor first) {
if (!isMatch(first)) {
return false;
}
id = first.id;
messageId = first.messageId;
responseId = first.responseId;
runtime = first.runtime;
services = first.services;
return true;
}
}
| 26.323077
| 87
| 0.708358
|
844f0d45edea747fce93d61e0cbaec37f3d95cec
| 1,077
|
/*L
* Copyright Northrop Grumman Information Technology.
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/nci-term-browser/LICENSE.txt for details.
*/
package gov.nih.nci.evs.browser.test.utils;
import java.util.*;
import gov.nih.nci.evs.browser.properties.*;
public class PropertyTest {
public static void main(String[] args) throws Exception {
args = SetupEnv.getInstance().parse(args);
NCItBrowserProperties.getInstance();
String value =
NCItBrowserProperties.getStandardFtpReportUrl();
System.out.println("getStandardFtpReportUrl: " + value);
Vector<StandardFtpReportInfo> list =
NCItBrowserProperties.getStandardFtpReportInfoList();
Iterator<StandardFtpReportInfo> iterator = list.iterator();
System.out.println("getStandardFtpReportInfoList:");
while (iterator.hasNext()) {
StandardFtpReportInfo info = iterator.next();
System.out.println(" * " + info);
}
}
}
| 33.65625
| 72
| 0.661096
|
0c5d10be543d4267264bae64baff861fa3ae59ef
| 4,114
|
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import java.io.*;
import org.apache.hadoop.mapreduce.Mapper;
import java.security.NoSuchAlgorithmException;
import javax.xml.bind.DatatypeConverter;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.*;
public class TotalFailMapper extends Mapper<LongWritable, Text, WTRKey,
RequestReplyMatch> {
private MessageDigest messageDigest;
@Override
public void setup(Context ctxt) throws IOException, InterruptedException{
// You probably need to do the same setup here you did
// with the QFD writer
super.setup(ctxt);
try{
messageDigest = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("SHA-1 algorithm not available");
}
messageDigest.update(HashUtils.SALT.getBytes(StandardCharsets.UTF_8));
}
@Override
public void map(LongWritable lineNo, Text line, Context ctxt)
throws IOException, InterruptedException {
// The value in the input for the key/value pair is a Tor IP.
// You need to then query that IP's source QFD to get
// all cookies from that IP,
// query the cookie QFDs to get all associated requests
// which are by those cookies, and store them in a torusers QFD
System.out.println("tor user");
System.out.println(line);
MessageDigest md = HashUtils.cloneMessageDigest(messageDigest);
md.update(line.toString().getBytes(StandardCharsets.UTF_8));
byte[] hash = md.digest();
byte[] hashBytes = Arrays.copyOf(hash, HashUtils.NUM_HASH_BYTES);
String hashString = DatatypeConverter.printHexBinary(hashBytes);
WTRKey key = new WTRKey("srcIP", hashString);
System.out.println("key is ");
System.out.println(key);
System.out.println("hashCode ");
System.out.println(key.hashCode());
System.out.println("hashBytes ");
System.out.println(key.getHashBytes());
QueryFocusedDataSet e = null;
try
{
FileInputStream fileIn = new FileInputStream("qfds/srcIP/srcIP_" + key.getHashBytes());
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (QueryFocusedDataSet) in.readObject();
in.close();
fileIn.close();
} catch(IOException i)
{
i.printStackTrace();
return;
} catch(ClassNotFoundException c)
{
System.out.println("qfds not found");
c.printStackTrace();
return;
}
System.out.println("qfds");
System.out.println(e.getName());
System.out.println(e.getMatches());
System.out.println("cookies are ");
HashSet<WebTrafficRecord> replies = new HashSet<>();
for (RequestReplyMatch i : e.getMatches()){
replies.add(new WebTrafficRecord(i.getRequest()));
WebTrafficRecord cookie = i.getRequest();
md = HashUtils.cloneMessageDigest(messageDigest);
md.update(cookie.getCookie().getBytes(StandardCharsets.UTF_8));
hash = md.digest();
hashBytes = Arrays.copyOf(hash, HashUtils.NUM_HASH_BYTES);
hashString = DatatypeConverter.printHexBinary(hashBytes);
WTRKey key1 = new WTRKey("cookie", hashString);
QueryFocusedDataSet j = null;
try
{
FileInputStream fileIn = new FileInputStream("qfds/cookie/cookie_" + key1.getHashBytes());
ObjectInputStream in = new ObjectInputStream(fileIn);
j = (QueryFocusedDataSet) in.readObject();
in.close();
fileIn.close();
} catch(IOException k)
{
k.printStackTrace();
return;
} catch(ClassNotFoundException l)
{
System.out.println("qfds not found");
l.printStackTrace();
return;
}
for (RequestReplyMatch m : j.getMatches()){
System.out.println("create toruser");
md = HashUtils.cloneMessageDigest(messageDigest);
md.update(m.getReply().getUserName().getBytes(StandardCharsets.UTF_8));
hash = md.digest();
hashBytes = Arrays.copyOf(hash, HashUtils.NUM_HASH_BYTES);
hashString = DatatypeConverter.printHexBinary(hashBytes);
WTRKey k = new WTRKey("torusers", hashString);
ctxt.write(k, m);
}
}
System.out.println(replies);
}
}
| 35.465517
| 94
| 0.701021
|
fe09cc4c19e99a90ea1f79db0e47649102c86336
| 2,702
|
package com.example.customview.telescope;
import android.os.Bundle;
import android.widget.SeekBar;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.example.customview.MyUtils;
import com.example.customview.R;
/**
* @author: LiuSaiSai
* @date: 2020/08/18 19:48
* @description: 望远镜效果
*/
public class TelescopeActivity extends AppCompatActivity {
private TextView tv_telescope_factor, tv_telescope_radius;
private SeekBar sb_telescope_factor, sb_telescope_radius;
private MyTelescopeView telescope_view;
public int telescope_factor = 3;
public int telescope_radius = 320;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_telescope);
initView();
}
private void initView() {
MyUtils.hideWindows(this);
tv_telescope_factor = findViewById(R.id.tv_telescope_factor);
tv_telescope_radius = findViewById(R.id.tv_telescope_radius);
telescope_view = findViewById(R.id.telescope_view);
sb_telescope_factor = findViewById(R.id.sb_telescope_factor);
sb_telescope_radius = findViewById(R.id.sb_telescope_radius);
sb_telescope_factor.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
telescope_factor = progress;
tv_telescope_factor.setText(String.valueOf(progress));
sb_telescope_factor.setProgress(progress);
telescope_view.setParameter(telescope_radius, telescope_factor,true);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
sb_telescope_radius.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
telescope_radius = progress;
tv_telescope_radius.setText(String.valueOf(progress));
sb_telescope_radius.setProgress(progress);
telescope_view.setParameter(telescope_radius, telescope_factor,false);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
}
| 32.166667
| 94
| 0.676906
|
cb8f558072673474fab6cb73b1c5344f6ba45057
| 493
|
package net.socialhub.twitter.web.entity.response;
import com.google.gson.annotations.SerializedName;
/**
* TODO:
* "responseObjects": {
* "feedbackActions": {}
* }
*/
public class Timeline {
@SerializedName("id")
private String id;
@SerializedName("instructions")
private Instruction[] instructions;
// region
public String getId() {
return id;
}
public Instruction[] getInstructions() {
return instructions;
}
// endregion
}
| 17.607143
| 50
| 0.643002
|
1f38f82c11dd36de4c28c07536410005302eeff7
| 86
|
package com.google.android.gms.internal;
public interface zzbeh {
void zzmF();
}
| 14.333333
| 40
| 0.72093
|
418eb2b00a33ef6c547e19cf22ea22e9ca453981
| 95
|
package agh.cs.oop.project1;
public class InvalidFormatException extends RuntimeException {
}
| 19
| 62
| 0.831579
|
72fbbb70c778a6f78c2345afa6fcfe6794a191cc
| 6,154
|
package us.ihmc.avatar.multiContact;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.awt.Color;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import us.ihmc.avatar.drcRobot.DRCRobotModel;
import us.ihmc.avatar.initialSetup.DRCRobotInitialSetup;
import us.ihmc.avatar.networkProcessor.kinematicsToolboxModule.HumanoidKinematicsToolboxControllerTest;
import us.ihmc.commons.ContinuousIntegrationTools;
import us.ihmc.commons.thread.ThreadTools;
import us.ihmc.euclid.transform.RigidBodyTransform;
import us.ihmc.graphicsDescription.appearance.YoAppearanceRGBColor;
import us.ihmc.mecano.multiBodySystem.interfaces.OneDoFJointBasics;
import us.ihmc.robotModels.FullHumanoidRobotModel;
import us.ihmc.sensorProcessing.simulatedSensors.DRCPerfectSensorReaderFactory;
import us.ihmc.sensorProcessing.simulatedSensors.SensorDataContext;
import us.ihmc.simulationConstructionSetTools.util.HumanoidFloatingRootJointRobot;
import us.ihmc.simulationconstructionset.Robot;
import us.ihmc.simulationconstructionset.SimulationConstructionSet;
public abstract class HumanoidRobotTransformOptimizerTest
{
public abstract DRCRobotModel createNewRobotModel();
private DRCRobotModel robotModelA;
private DRCRobotModel robotModelB;
private DRCRobotModel robotModelBCorrected;
private static final YoAppearanceRGBColor robotBApperance = new YoAppearanceRGBColor(Color.decode("#9e8329"), 0.25); // Some darkish orangish
private static final YoAppearanceRGBColor robotBCorrectedApperance = new YoAppearanceRGBColor(Color.decode("#35824a"), 0.75); // Some darkish green
@BeforeEach
public void setup()
{
robotModelA = createNewRobotModel();
robotModelB = createNewRobotModel();
robotModelBCorrected = createNewRobotModel();
robotModelA.getRobotDescription().setName("RobotA");
robotModelB.getRobotDescription().setName("RobotB");
robotModelBCorrected.getRobotDescription().setName("RobotBCorrected");
HumanoidKinematicsToolboxControllerTest.recursivelyModifyGraphics(robotModelB.getRobotDescription().getChildrenJoints().get(0), robotBApperance);
HumanoidKinematicsToolboxControllerTest.recursivelyModifyGraphics(robotModelBCorrected.getRobotDescription().getChildrenJoints().get(0),
robotBCorrectedApperance);
}
@AfterEach
public void tearDown()
{
robotModelA = null;
robotModelB = null;
robotModelBCorrected = null;
}
public void visualizeRobots(Robot... robots)
{
if (ContinuousIntegrationTools.isRunningOnContinuousIntegrationServer())
return;
SimulationConstructionSet scs = new SimulationConstructionSet(robots);
scs.startOnAThread();
ThreadTools.sleepForever();
}
public void runTest(DRCRobotInitialSetup<HumanoidFloatingRootJointRobot> initialSetupA, DRCRobotInitialSetup<HumanoidFloatingRootJointRobot> initialSetupB,
double epsilon)
{
HumanoidFloatingRootJointRobot scsRobotA = robotModelA.createHumanoidFloatingRootJointRobot(false);
HumanoidFloatingRootJointRobot scsRobotB = robotModelB.createHumanoidFloatingRootJointRobot(false);
HumanoidFloatingRootJointRobot scsRobotBCorrected = robotModelBCorrected.createHumanoidFloatingRootJointRobot(false);
FullHumanoidRobotModel idRobotA = robotModelA.createFullRobotModel();
FullHumanoidRobotModel idRobotB = robotModelB.createFullRobotModel();
FullHumanoidRobotModel idRobotBCorrected = robotModelBCorrected.createFullRobotModel();
initialSetupA.initializeRobot(scsRobotA, robotModelA.getJointMap());
initialSetupB.initializeRobot(scsRobotB, robotModelB.getJointMap());
initialSetupB.initializeRobot(scsRobotBCorrected, robotModelBCorrected.getJointMap());
copyRobotState(scsRobotA, idRobotA);
copyRobotState(scsRobotB, idRobotB);
copyRobotState(scsRobotBCorrected, idRobotBCorrected);
RobotTransformOptimizer robotTransformOptimizer = new RobotTransformOptimizer(idRobotA.getElevator(), idRobotB.getElevator());
robotTransformOptimizer.addDefaultRigidBodyLinearErrorCalculators((bodyA, bodyB) -> !bodyA.isRootBody());
robotTransformOptimizer.setInitializeWithHeaviestBody(true);
robotTransformOptimizer.compute();
RigidBodyTransform transform = new RigidBodyTransform();
scsRobotBCorrected.getRootJoint().getTransformToWorld(transform);
transform.preMultiply(robotTransformOptimizer.getTransformFromBToA());
scsRobotBCorrected.getRootJoint().setRotationAndTranslation(transform);
scsRobotBCorrected.update();
idRobotBCorrected.getRootJoint().getJointPose().set(transform);
idRobotBCorrected.updateFrames();
visualizeRobots(scsRobotA, scsRobotB, scsRobotBCorrected);
OneDoFJointBasics[] jointsA = idRobotA.getOneDoFJoints();
OneDoFJointBasics[] jointsBCorrected = idRobotBCorrected.getOneDoFJoints();
double errorMagnitude = 0.0;
for (int i = 0; i < jointsA.length; i++)
{
OneDoFJointBasics jointA = jointsA[i];
OneDoFJointBasics jointBCorrected = jointsBCorrected[i];
errorMagnitude += jointA.getFrameAfterJoint().getTransformToDesiredFrame(jointBCorrected.getFrameAfterJoint()).getTranslation().length();
}
errorMagnitude /= jointsA.length;
assertTrue(errorMagnitude < epsilon, "Error magnitude is larger than expected: " + errorMagnitude);
}
private static void copyRobotState(HumanoidFloatingRootJointRobot source, FullHumanoidRobotModel destination)
{
DRCPerfectSensorReaderFactory drcPerfectSensorReaderFactory = new DRCPerfectSensorReaderFactory(source, 0);
drcPerfectSensorReaderFactory.build(destination.getRootJoint(), null, null, null, null);
SensorDataContext sensorDataContext = new SensorDataContext();
long timestamp = drcPerfectSensorReaderFactory.getSensorReader().read(sensorDataContext);
drcPerfectSensorReaderFactory.getSensorReader().compute(timestamp, sensorDataContext);
destination.updateFrames();
}
}
| 47.338462
| 158
| 0.784205
|
9e4cbed8be436ee7253a430a268690a69c436f26
| 28,609
|
package common.output;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Hashtable;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultCellEditor;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableModel;
import org.trianacode.gui.panels.ParameterPanel;
public class CondorPanel extends ParameterPanel {
// Define GUI components here, e.g.
//
// private JTextField namelabel = new JTextField();
private JTextField schedd_name;
private JCheckBox verbose;
private JCheckBox remote;
private JCheckBox nopermchk;
private JTable command;
private JTextArea output_submit;
private JTextArea qoutput;
private JTextArea st_output;
private MyCellEditorInfo cellEditorInfo;
public CondorPanel() {
// cell editor
cellEditorInfo = new MyCellEditorInfo();
cellEditorInfo.addSimple("universe",
new DefaultCellEditor(new JComboBox(new String[]{
"", "vanilla", "standard", "pvm", "scheduler", "globus", "mpi", "java"
})));
cellEditorInfo.addChooser("executable");
// "requirements",
cellEditorInfo.addChooser("input");
cellEditorInfo.addChooser("output");
cellEditorInfo.addChooser("error");
cellEditorInfo.addChooser("initialdir");
cellEditorInfo.addSimple("should_transfer_files",
new DefaultCellEditor(new JComboBox(new String[]{
"", "yes", "no", "if_needed"})));
cellEditorInfo.addSimple("when_to_transfer_output",
new DefaultCellEditor(new JComboBox(new String[]{
"", "on_exit", "on_exit_or_evict"})));
cellEditorInfo.addList("transfer_input_files");
cellEditorInfo.addList("transfer_output_files");
// "rank",
// "on_exit_remove",
// "on_exit_hold",
// "periodic_remove",
// "periodic_hold",
// "periodic_release",
// "priority",
cellEditorInfo.addSimple("notification",
new DefaultCellEditor(new JComboBox(new String[]{
"", "always", "complete", "error", "never"})));
// "notify_user",
cellEditorInfo.addSimple("copy_to_spool",
new DefaultCellEditor(new JComboBox(new String[]{"", "true", "false"})));
cellEditorInfo.addSimple("getenv",
new DefaultCellEditor(new JComboBox(new String[]{"", "true", "false"})));
cellEditorInfo.addSimple("hold",
new DefaultCellEditor(new JComboBox(new String[]{"", "true", "false"})));
//?? "environment",
cellEditorInfo.addChooser("log");
cellEditorInfo.addSimple("log_xml",
new DefaultCellEditor(new JComboBox(new String[]{"", "true", "false"})));
cellEditorInfo.addList("jar_files");
// "image_size",
// "machine_count",
// "coresize",
cellEditorInfo.addSimple("nice_user",
new DefaultCellEditor(new JComboBox(new String[]{"", "true", "false"})));
// "kill_sig",
cellEditorInfo.addList("compress_files");
cellEditorInfo.addList("fetch_files");
cellEditorInfo.addList("append_files");
cellEditorInfo.addList("local_files");
//?? "file_remaps",
//?? "buffer_files",
// "buffer_size",
// "buffer_block_size",
cellEditorInfo.addChooser("rendezvousdir");
cellEditorInfo.addChooser("x509directory");
cellEditorInfo.addChooser("x509userproxy");
// "globusscheduler",
// "globusrsl",
// "globus_resubmit",
// "globus_rematch",
// "leave_in_queue",
// "match_list_length",
cellEditorInfo.addSimple("transfer_output",
new DefaultCellEditor(new JComboBox(new String[]{"", "true", "false"})));
cellEditorInfo.addSimple("transfer_input",
new DefaultCellEditor(new JComboBox(new String[]{"", "true", "false"})));
cellEditorInfo.addSimple("transfer_error",
new DefaultCellEditor(new JComboBox(new String[]{"", "true", "false"})));
cellEditorInfo.addSimple("transfer_executable",
new DefaultCellEditor(new JComboBox(new String[]{"", "true", "false"})));
cellEditorInfo.addSimple("stream_output",
new DefaultCellEditor(new JComboBox(new String[]{"", "true", "false"})));
cellEditorInfo.addSimple("stream_error",
new DefaultCellEditor(new JComboBox(new String[]{"", "true", "false"})));
//?? "+",
cellEditorInfo.addSpinner("QUEUE");
cellEditorInfo.addSimple("allow_startup_script",
new DefaultCellEditor(new JComboBox(new String[]{"", "true", "false"})));
}
/**
* This method is called before the panel is displayed. It should initialise the panel layout.
*/
public void init() {
// Insert code to layout GUI here, e.g.
//
// add(namelabel);
// getTask().addTaskListener(this);
setLayout(new BorderLayout());
JPanel pn = new JPanel(new BorderLayout());
add(pn, BorderLayout.CENTER);
//pn.setBorder(new BevelBorder(BevelBorder.RAISED));
JTabbedPane tabs = new JTabbedPane();
pn.add(tabs, BorderLayout.CENTER);
// tab submit
Box submit = new Box(BoxLayout.Y_AXIS);
Box schedd = new Box(BoxLayout.X_AXIS);
schedd.setAlignmentX(Component.LEFT_ALIGNMENT);
schedd.add(new JLabel("Schedd Name: "));
this.schedd_name = new JTextField((String) getParameter("submit_schedd_name"));
schedd_name.setMaximumSize(new Dimension(Short.MAX_VALUE, schedd_name.getPreferredSize().height));
schedd.add(schedd_name);
submit.add(schedd);
Box cks = new Box(BoxLayout.X_AXIS);
cks.setAlignmentX(Component.LEFT_ALIGNMENT);
this.verbose = new JCheckBox("Verbose", ((Boolean) getParameter("submit_verbose")).booleanValue());
cks.add(verbose);
cks.add(Box.createHorizontalGlue());
this.remote = new JCheckBox("Remote Schedd", ((Boolean) getParameter("submit_remote_schedd")).booleanValue());
cks.add(remote);
cks.add(Box.createHorizontalGlue());
this.nopermchk = new JCheckBox("Disable File Permission Checks",
((Boolean) getParameter("submit_disable_permchk")).booleanValue());
cks.add(nopermchk);
cks.add(Box.createHorizontalGlue());
submit.add(cks);
submit.add(Box.createVerticalGlue());
submit.add(new JLabel("Additional Commands: "));
String[] header = {"Command", "Value"};
this.command =
new MyTable(new MyTableModel((Object[][]) getParameter("submit_additional_commands"), header));
JScrollPane tblpn = new JScrollPane(command);
tblpn.setAlignmentX(Component.LEFT_ALIGNMENT);
tblpn.setPreferredSize(new Dimension(command.getPreferredSize().width, command.getRowHeight() * 5));
submit.add(tblpn);
Box adddel = new Box(BoxLayout.X_AXIS);
adddel.setAlignmentX(Component.LEFT_ALIGNMENT);
JComboBox addcmd = new JComboBox(new Object[]{"Additional Commands ...",
"input",
"output",
"error",
"arguments",
"initialdir",
"should_transfer_files",
"when_to_transfer_output",
"transfer_input_files",
"transfer_output_files",
"rank",
"on_exit_remove",
"on_exit_hold",
"periodic_remove",
"periodic_hold",
"periodic_release",
"priority",
"notification",
"notify_user",
"copy_to_spool",
"getenv",
"hold",
"environment",
"log",
"log_xml",
"jar_files",
"image_size",
"machine_count",
"coresize",
"nice_user",
"kill_sig",
"compress_files",
"fetch_files",
"append_files",
"local_files",
"file_remaps",
"buffer_files",
"buffer_size",
"buffer_block_size",
"rendezvousdir",
"x509directory",
"x509userproxy",
"globusscheduler",
"globusrsl",
"globus_resubmit",
"globus_rematch",
"leave_in_queue",
"match_list_length",
"transfer_output",
"transfer_input",
"transfer_error",
"transfer_executable",
"stream_output",
"stream_error",
"+",
"allow_startup_script"
});
addcmd.setMaximumSize(addcmd.getPreferredSize());
addcmd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
MyTableModel m = (MyTableModel) command.getModel();
JComboBox cb = (JComboBox) e.getSource();
int row = m.getRowCount() - 1; // before the last row, which is blank place holder
if (cb.getSelectedIndex() > 0) {
m.insertRows(row, new Object[][]{{cb.getSelectedItem(), ""}});
command.setRowSelectionInterval(row, row);
}
cb.setSelectedIndex(0);
}
});
JButton delcmd = new JButton("Delete");
delcmd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int[] idx = command.getSelectedRows();
MyTableModel m = (MyTableModel) command.getModel();
int n = 0;
for (int i = 0; i < idx.length; i++) {
if (idx[i] == m.getRowCount() - 1) {
idx[i] = -1;
} // not remove
if (idx[i] != -1) {
n++;
}
}
int[] newidx = new int[n];
for (int i = 0, j = 0; i < idx.length; i++) {
if (idx[i] == -1) {
continue;
}
newidx[j] = idx[i];
j++;
}
m.removeRows(newidx);
}
});
adddel.add(Box.createHorizontalGlue());
adddel.add(addcmd);
adddel.add(delcmd);
submit.add(adddel);
submit.add(Box.createVerticalGlue());
submit.add(new JLabel("Submit Output: "));
output_submit = new JTextArea((String) getParameter("output_submit"));
output_submit.setRows(5);
output_submit.setEditable(false);
JScrollPane outputS = new JScrollPane(output_submit);
outputS.setAlignmentX(Component.LEFT_ALIGNMENT);
submit.add(outputS);
tabs.addTab("Submit", submit);
// tab queue
JPanel queue = new JPanel(new BorderLayout());
qoutput = new JTextArea();
qoutput.setRows(5);
qoutput.setEditable(false);
JScrollPane qpn = new JScrollPane(qoutput);
queue.add(qpn, BorderLayout.CENTER);
JButton refresh = new JButton("Refresh");
refresh.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setParameter("queue_refresh", new Boolean(true));
}
});
Box ref = new Box(BoxLayout.X_AXIS);
ref.add(Box.createHorizontalGlue());
ref.add(refresh);
queue.add(ref, BorderLayout.SOUTH);
tabs.addTab("Queue", queue);
// tab status
JPanel status = new JPanel(new BorderLayout());
st_output = new JTextArea();
st_output.setRows(5);
st_output.setEditable(false);
JScrollPane st_pn = new JScrollPane(st_output);
status.add(st_pn, BorderLayout.CENTER);
JButton refresh2 = new JButton("Refresh");
refresh2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setParameter("status_refresh", new Boolean(true));
}
});
Box ref2 = new Box(BoxLayout.X_AXIS);
ref2.add(Box.createHorizontalGlue());
ref2.add(refresh2);
status.add(ref2, BorderLayout.SOUTH);
tabs.addTab("Status", status);
}
/**
* This method is called when cancel is clicked on the parameter window. It should synchronize the GUI components
* with the task parameter values
*/
public void reset() {
// Insert code to synchronise the GUI with the task parameters here, e.g.
//
// namelabel.setText(getParameter("name"));
System.err.println("CondorPanel reset");
schedd_name.setText((String) getParameter("submit_schedd_name"));
verbose.setSelected(((Boolean) getParameter("submit_verbose")).booleanValue());
remote.setSelected(((Boolean) getParameter("submit_remote_schedd")).booleanValue());
nopermchk.setSelected(((Boolean) getParameter("submit_disable_permchk")).booleanValue());
((MyTableModel) command.getModel()).setData((Object[][]) getParameter("submit_additional_commands"));
output_submit.setText((String) getParameter("output_submit"));
}
/**
* Called when the ok button is clicked on the parameter window. Calls applyClicked by default to commit any
* parameter changes.
*/
public void okClicked() {
applyClicked();
}
/**
* Called when the apply button is clicked on the parameter window. Commits any parameter changes.
*/
public void applyClicked() {
setParameter("submit_schedd_name", schedd_name.getText());
setParameter("submit_verbose", new Boolean(verbose.getModel().isSelected()));
setParameter("submit_remote_schedd", new Boolean(remote.getModel().isSelected()));
setParameter("submit_disable_permchk", new Boolean(nopermchk.getModel().isSelected()));
setParameter("submit_additional_commands", ((MyTableModel) command.getModel()).getData());
super.applyClicked(); // it commits
}
/**
* This method is called when a parameter in the task is updated. It should update the GUI in response to the
* parameter update
*/
public void parameterUpdate(String paramname, Object value) {
// Insert code to update GUI in response to parameter changes here, e.g.
//
// if (paramname.equals("name"))
// namelabel.setText(value);
System.err.println("parameterUpdate (task -> GUI), paramname: " + paramname);
if (paramname.equals("output_submit")) {
output_submit.append((String) value);
}
if (paramname.equals("output_queue")) {
qoutput.setText((String) value);
}
if (paramname.equals("output_status")) {
st_output.setText((String) value);
}
}
/**
* This method is called when the panel is being disposed off. It should clean-up subwindows, open files etc.
*/
public void dispose() {
// Insert code to clean-up panel here
}
public void setParameter(String name, Object value) {
System.err.println("setParameter");
super.setParameter(name, value);
}
//
// helper classes
//
// table
private final class MyTable extends JTable {
public MyTable(TableModel tm) {
super(tm);
}
public TableCellEditor getCellEditor(int row, int col) {
TableCellEditor res = super.getCellEditor(row, col);
TableCellEditor tmp;
if (col == 1) { // value column
tmp = cellEditorInfo.getEditor(getModel().getValueAt(row, 0));
if (tmp != null) {
res = tmp;
}
}
return res;
}
}
private final class MyTableModel extends AbstractTableModel {
private Object[][] data;
private String[] columnNames;
public MyTableModel(Object[][] data, String[] columnNames) {
this.data = copyData(data);
this.columnNames = columnNames;
}
public Object[][] getData() {
return data;
}
public void setData(Object[][] data) {
this.data = copyData(data);
fireTableStructureChanged();
}
private Object[][] insertData(Object[][] first, Object[][] second, int point) {
int row1 = first.length;
int p = point < 0 ? row1 + point : point;
if (row1 - 1 < p) {
return appendData(first, second);
}
int col = first[0].length;
int row2 = second == null ? 0 : second.length;
Object[][] res = new Object[row1 + row2][col];
for (int i = 0; i < p; i++) {
for (int j = 0; j < col; j++) {
res[i][j] = first[i][j];
}
}
for (int i = 0; i < row2; i++) {
for (int j = 0; j < col; j++) {
res[i + p][j] = second[i][j];
}
}
for (int i = 0; i < row1 - p; i++) {
for (int j = 0; j < col; j++) {
res[i + p + row2][j] = first[i + p][j];
}
}
return res;
}
private Object[][] appendData(Object[][] first, Object[][] second) {
int row1 = first.length;
int col = first[0].length;
int row2 = second == null ? 0 : second.length;
Object[][] res = new Object[row1 + row2][col];
for (int i = 0; i < row1; i++) {
for (int j = 0; j < col; j++) {
res[i][j] = first[i][j];
}
}
for (int i = 0; i < row2; i++) {
for (int j = 0; j < col; j++) {
res[i + row1][j] = second[i][j];
}
}
return res;
}
private Object[][] copyData(Object[][] data) {
return appendData(data, null);
}
public void addRows(Object[][] rows) {
this.data = appendData(this.data, rows);
fireTableStructureChanged();
}
public void insertRows(int row, Object[][] rows) {
this.data = insertData(this.data, rows, row);
fireTableStructureChanged();
}
private Object[][] removeData(Object[][] orig, int[] points) {
int col = orig[0].length;
int row = orig.length - points.length;
Object[][] res = new Object[row][col];
for (int i = 0, ii = 0; i < orig.length; i++) {
int n;
for (n = 0; n < points.length; n++) {
if (i == points[n]) {
break;
}
}
if (n < points.length) // found, so remove
{
continue;
}
for (int j = 0; j < col; j++) {
res[ii][j] = orig[i][j];
}
ii++;
}
return res;
}
public void removeRows(int[] index) {
this.data = removeData(this.data, index);
fireTableStructureChanged();
}
public int getRowCount() {
return data.length;
}
public int getColumnCount() {
return columnNames.length;
}
public Object getValueAt(int row, int column) {
return data[row][column];
}
public void setValueAt(Object value, int row, int column) {
data[row][column] = value;
fireTableCellUpdated(row, column);
}
public String getColumnName(int column) {
return columnNames[column];
}
public boolean isCellEditable(int row, int column) {
if (column == 0) {
if (((String) getValueAt(row, 0)).startsWith("+")) {
return true;
} else {
return false;
}
} else if (column == 1) {
if (((String) getValueAt(row, 0)).equals("")) {
return false;
} else {
return true;
}
} else {
return true;
}
}
}
private final class MyCellEditor extends DefaultCellEditor {
private Object currentValue = null;
public MyCellEditor(final JButton button) {
super(new JCheckBox());
setClickCountToStart(1);
editorComponent = button;
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fireEditingStopped();
}
});
}
public MyCellEditor(final JSpinner spinner) {
super(new JCheckBox());
setClickCountToStart(1);
editorComponent = spinner;
}
public Object getCellEditorValue() {
return currentValue;
}
public void setCellEditorValue(Object value) {
currentValue = value;
}
public Component getTableCellEditorComponent(JTable table,
Object value,
boolean isSelected,
int row,
int column) {
if (editorComponent instanceof JButton) {
((JButton) editorComponent).setText(value.toString());
} else if (editorComponent instanceof JSpinner && value instanceof Integer) {
((JSpinner) editorComponent).setValue(value);
}
currentValue = value;
return editorComponent;
}
}
private final class MyCellEditorInfo {
Hashtable info = new Hashtable();
public TableCellEditor getEditor(Object key) {
return (TableCellEditor) info.get(key);
}
public void addSimple(String key, DefaultCellEditor editor) {
info.put(key, editor);
}
public void addChooser(final String key) {
final JButton button = new JButton();
button.setHorizontalAlignment(JButton.LEFT);
final MyCellEditor editor = new MyCellEditor(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("Choose Value for \"" + key + "\"");
int result = chooser.showOpenDialog(button);
if (result == JFileChooser.APPROVE_OPTION) {
editor.setCellEditorValue(chooser.getSelectedFile().getAbsolutePath());
}
}
});
info.put(key, editor);
}
public void addList(final String key) {
final JButton button = new JButton();
button.setHorizontalAlignment(JButton.LEFT);
final MyCellEditor editor = new MyCellEditor(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane opt = new JOptionPane(null,
JOptionPane.PLAIN_MESSAGE,
JOptionPane.OK_CANCEL_OPTION);
//JDialog diag = opt.createDialog(button, key);
JPanel pane = new JPanel(new BorderLayout());
//diag.setContentPane(pane);
//pane.add(opt, BorderLayout.SOUTH);
final JList list = new JList();
Object ini = editor.getCellEditorValue();
if (ini instanceof MyListModel) {
list.setModel(new MyListModel((MyListModel) ini));
} else {
list.setModel(new MyListModel());
}
JScrollPane slist = new JScrollPane(list);
pane.add(slist, BorderLayout.CENTER);
final JButton bAdd = new JButton("Add");
final JButton bDel = new JButton("Delete");
bAdd.setMaximumSize(bDel.getMaximumSize());
Box ctl = new Box(BoxLayout.Y_AXIS);
ctl.add(Box.createVerticalGlue());
ctl.add(bAdd);
ctl.add(bDel);
pane.add(ctl, BorderLayout.EAST);
bAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("Choose Value for \"" + key + "\"");
int result = chooser.showOpenDialog(button);
if (result == JFileChooser.APPROVE_OPTION) {
MyListModel model = (MyListModel) list.getModel();
model.addElement(chooser.getSelectedFile().getAbsolutePath());
}
}
});
bDel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
MyListModel model = (MyListModel) list.getModel();
Object[] o = list.getSelectedValues();
for (int i = 0; i < o.length; i++) {
model.removeElement(o[i]);
}
}
});
int ans = opt.showOptionDialog(button, pane, key,
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE, null, null, null);
if (ans == JOptionPane.OK_OPTION) {
editor.setCellEditorValue(list.getModel());
}
}
});
info.put(key, editor);
}
public void addSpinner(final String key) {
final JSpinner spinner = new JSpinner(new SpinnerNumberModel(1, 1, Integer.MAX_VALUE, 1));
final MyCellEditor editor = new MyCellEditor(spinner);
spinner.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
editor.currentValue = spinner.getValue();
}
});
info.put(key, editor);
}
}
// list
private final class MyListModel extends DefaultListModel {
public MyListModel() {
}
public MyListModel(MyListModel model) {
for (int i = 0; i < model.size(); i++) {
addElement(model.get(i));
}
}
public String toString() {
String res = size() > 0 ? (String) get(0) : "";
for (int i = 1; i < size(); i++) {
res += ", " + (String) get(i);
}
return res;
}
}
}
| 36.631242
| 118
| 0.533818
|
9d3109e6a1e0d65ba1eeaedae55afbdf4a9585bd
| 1,762
|
package benchmark.WordCount;
import org.apache.samza.application.StreamApplication;
import org.apache.samza.config.Config;
import org.apache.samza.operators.KV;
import org.apache.samza.operators.MessageStream;
import org.apache.samza.operators.OutputStream;
import org.apache.samza.operators.StreamGraph;
import org.apache.samza.operators.windows.Windows;
import org.apache.samza.serializers.IntegerSerde;
import org.apache.samza.serializers.KVSerde;
import org.apache.samza.serializers.StringSerde;
import org.apache.samza.storage.kv.KeyValueStore;
import java.time.Duration;
public class WordCounter implements StreamApplication{
private static final String INPUT_TOPIC = "WordSplitterOutput";
private static final String OUTPUT_TOPIC = "WordCounterOutput";
private KeyValueStore<String, Integer> counter;
@Override
public void init(StreamGraph graph, Config config) {
graph.setDefaultSerde(KVSerde.of(new StringSerde(), new StringSerde()));
MessageStream<KV<String, String>> inputStream = graph.getInputStream(INPUT_TOPIC);
OutputStream<KV<String, String>> outputStream = graph.getOutputStream(OUTPUT_TOPIC);
// Split the input into multiple strings
inputStream
.window(Windows.keyedTumblingWindow(
message -> message.getValue(), Duration.ofSeconds(5), () -> 0, (m, prevCount) -> prevCount + 1,
new StringSerde(), new IntegerSerde()), "count")
.map(windowPane -> {
String word = windowPane.getKey().getKey();
int count = windowPane.getMessage();
return KV.of(word, String.valueOf(count));
})
.sendTo(outputStream);
}
}
| 44.05
| 119
| 0.69353
|
4b82cca5821998725c6e4fcc1355a74386531974
| 2,875
|
package ubc.pavlab.rdp.controllers;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import ubc.pavlab.rdp.model.GeneInfo;
import ubc.pavlab.rdp.model.GeneOntologyTerm;
import ubc.pavlab.rdp.model.GeneOntologyTermInfo;
import ubc.pavlab.rdp.model.Taxon;
import ubc.pavlab.rdp.services.GOService;
import ubc.pavlab.rdp.services.TaxonService;
import ubc.pavlab.rdp.util.SearchResult;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
/**
* Created by mjacobson on 18/01/18.
*/
@Controller
@CommonsLog
public class TermController {
@Autowired
private GOService goService;
@Autowired
private TaxonService taxonService;
@ResponseBody
@GetMapping(value = "/taxon/{taxonId}/term/search")
public Object searchTermsByQueryAndTaxon( @PathVariable Integer taxonId,
@RequestParam String query,
@RequestParam(value = "max", required = false, defaultValue = "-1") int max ) {
Taxon taxon = taxonService.findById( taxonId );
if ( taxon == null ) {
return ResponseEntity.notFound().build();
}
Collection<SearchResult<GeneOntologyTermInfo>> foundTerms = goService.search( query, taxon, max );
// FIXME: this is silly
for ( SearchResult<GeneOntologyTermInfo> term : foundTerms ) {
term.getMatch().setSize( goService.getSizeInTaxon( term.getMatch(), taxon ) );
}
// sort by size in taxon
return foundTerms.stream()
.sorted( Comparator.comparing( result -> result.getMatch().getSize(), Comparator.reverseOrder() ) )
.collect( Collectors.toList() );
}
@ResponseBody
@GetMapping(value = "/term/{goId}")
public Object getTerm( @PathVariable String goId ) {
GeneOntologyTerm term = goService.getTerm( goId );
if ( term == null ) {
return ResponseEntity.notFound().build();
}
return term;
}
@ResponseBody
@GetMapping(value = "/taxon/{taxonId}/term/{goId}/gene")
public Object termGenes( @PathVariable Integer taxonId, @PathVariable String goId ) {
Taxon taxon = taxonService.findById( taxonId );
if ( taxon == null ) {
return ResponseEntity.notFound().build();
}
GeneOntologyTermInfo term = goService.getTerm( goId );
if ( term == null ) {
return ResponseEntity.notFound().build();
}
return goService.getGenesInTaxon( term, taxon );
}
}
| 34.638554
| 125
| 0.662261
|
d2cf22171f0027a536f621cf3dcf4fc242d51dc9
| 863
|
/*******************************************************************************
* Copyright (c) 2018 Red Hat, Inc. Distributed under license by Red Hat, Inc.
* All rights reserved. This program is made available under the terms of the
* Eclipse Public License v2.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v20.html
*
* Contributors: Red Hat, Inc.
******************************************************************************/
package org.jboss.tools.rsp.server.wildfly.servertype.launch;
import org.jboss.tools.rsp.server.spi.servertype.IServer;
public class JBossEAP60LaunchArgs extends JBoss71DefaultLaunchArguments {
public JBossEAP60LaunchArgs(IServer rt) {
super(rt);
}
@Override
protected String getMemoryArgs() {
return "-Xms1303m -Xmx1303m -XX:MaxPermSize=256m "; //$NON-NLS-1$
}
}
| 37.521739
| 80
| 0.617613
|
b50417be6fc45b0123c966a70832d096b92a5773
| 3,993
|
package net.clustercode.holidayapp;
import android.content.Intent;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.sheets.v4.Sheets;
import com.google.api.services.sheets.v4.model.ValueRange;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
public class SignInActivity extends AppCompatActivity {
private TextView txtInfo;
private EditText etUsername, etPassword;
private Sheets sheetsService;
private String spreadsheetId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int windowWidth = displayMetrics.widthPixels;
int windowHeight = displayMetrics.heightPixels;
getWindow().setLayout((int)(windowWidth*.8), (int)(windowHeight*.5));
HttpTransport transport = AndroidHttp.newCompatibleTransport();
JsonFactory factory = JacksonFactory.getDefaultInstance();
sheetsService = new Sheets.Builder(transport, factory, null)
.setApplicationName("Holiday App")
.build();
spreadsheetId = Config.spreadsheet_id;
txtInfo = findViewById(R.id.txtInfo);
etUsername = findViewById(R.id.etUsername);
etPassword = findViewById(R.id.etPassword);
}
public void signIn(View view) {
txtInfo.setVisibility(View.GONE);
new Thread() {
@Override
public void run() {
try {
String range = "Sheet1!A1";
ValueRange result = sheetsService.spreadsheets().values()
.get(spreadsheetId, range)
.setKey(Config.google_api_key)
.execute();
int numberOfUser = Integer.parseInt(result.getValues().get(0).get(0).toString());
String range2 = "Sheet1!A3:B" + (3+numberOfUser);
ValueRange result2 = sheetsService.spreadsheets().values()
.get(spreadsheetId, range2)
.setKey(Config.google_api_key)
.execute();
for (int i = 0; i < numberOfUser; i++) {
if (etUsername.getText().toString().equals(result2.getValues().get(i).get(0).toString()) && etPassword.getText().toString().equals(result2.getValues().get(i).get(1).toString())) {
Intent returnIntent = new Intent();
returnIntent.putExtra("result",(i+3));
returnIntent.putExtra("username",etUsername.getText().toString());
setResult(RESULT_OK,returnIntent);
finish();
}
}
txtInfo.post(new Runnable() {
@Override
public void run() {
txtInfo.setVisibility(View.VISIBLE);
}
});
}
catch (IOException e) {
Log.e("Test", Objects.requireNonNull(e.getLocalizedMessage()));
}
}
}.start();
}
@Override
public void onBackPressed() {
}
}
| 39.534653
| 204
| 0.572502
|
31bf9bfbea38a6862826760d131f523ef3a7112a
| 11,879
|
/**
* 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.geronimo.gbean;
import java.lang.reflect.Method;
import net.sf.cglib.reflect.FastClass;
import org.apache.geronimo.gbean.runtime.RawInvoker;
import org.apache.geronimo.kernel.Kernel;
import org.apache.geronimo.kernel.KernelFactory;
import org.apache.geronimo.kernel.MockGBean;
import org.apache.geronimo.kernel.repository.Artifact;
import org.apache.geronimo.testsupport.TestSupport;
/**
* @version $Rev$ $Date$
*/
public class Speed extends TestSupport {
private static final Object[] NO_ARGS = new Object[0];
// public static void main(String[] ignored) throws Exception {
// System.out.println("Do Nothing Timings");
// System.out.println("------------------");
// doNothingTimings();
// System.out.println();
// System.out.println();
// System.out.println();
// doNothingTimings();
//// System.out.println("Echo Timings");
//// System.out.println("-------------");
//// echoTimings();
// }
private void doNothingTimings() throws Exception {
Method myMethod = MockGBean.class.getMethod("doNothing", (Class[])null);
FastClass myFastClass = FastClass.create(MockGBean.class);
int myMethodIndex = myFastClass.getIndex("doNothing", new Class[0]);
MockGBean instance = new MockGBean("foo", 12);
// normal invoke
int iterations = 100000000;
String msg = "hhhh";
for (int j=0 ; j < 10; j++) {
for (int i = 0; i < iterations; i++) {
msg= instance.echo(msg);
}
}
long start = System.currentTimeMillis();
for (int i = 0; i < iterations; i++) {
instance.doNothing();
}
long end = System.currentTimeMillis();
printResults("Normal", end, start, iterations);
// reflection
iterations = 1000000;
for (int i = 0; i < iterations; i++) {
myMethod.invoke(instance, (Class[])null);
}
start = System.currentTimeMillis();
for (int i = 0; i < iterations; i++) {
myMethod.invoke(instance, (Class[])null);
}
end = System.currentTimeMillis();
printResults("Reflection", end, start, iterations);
// fast class
iterations = 5000000;
for (int i = 0; i < iterations; i++) {
myFastClass.invoke(myMethodIndex, instance, null);
}
start = System.currentTimeMillis();
for (int i = 0; i < iterations; i++) {
myFastClass.invoke(myMethodIndex, instance, null);
}
end = System.currentTimeMillis();
printResults("FastClass", end, start, iterations);
// start a kernel
Kernel kernel = KernelFactory.newInstance(getBundleContext()).createKernel("speed");
kernel.boot(bundleContext);
AbstractName abstractName = kernel.getNaming().createRootName(new Artifact("test", "foo", "1", "car"), "test", "test");
GBeanData mockGBean = new GBeanData(abstractName, MockGBean.getGBeanInfo());
mockGBean.setAttribute("Name", "bar");
mockGBean.setAttribute("FinalInt", new Integer(57));
kernel.loadGBean(mockGBean, getBundleContext());
kernel.startGBean(abstractName);
// reflect proxy
// ProxyFactory vmProxyFactory = new VMProxyFactory(MyInterface.class);
// ProxyMethodInterceptor vmMethodInterceptor = vmProxyFactory.getMethodInterceptor();
// MyInterface vmProxy = (MyInterface) vmProxyFactory.create(vmMethodInterceptor);
// vmMethodInterceptor.connect(kernel.getMBeanServer(), objectName);
// iterations = 50000;
// for (int i = 0; i < iterations; i++) {
// vmProxy.doNothing();
// }
// start = System.currentTimeMillis();
// for (int i = 0; i < iterations; i++) {
// vmProxy.doNothing();
// }
// end = System.currentTimeMillis();
// printResults("ReflectionProxy", end, start, iterations);
// cglib proxy (front half)
/*
ProxyFactory frontCGLibProxyFactory = new CGLibProxyFactory(MyInterface.class);
ProxyMethodInterceptor frontCGLibMethodInterceptor = new ProxyMethodInterceptor(MyInterface.class);
Class enhancedType = frontCGLibProxyFactory.create(frontCGLibMethodInterceptor).getClass();
frontCGLibMethodInterceptor = new ProxyMethodInterceptor(enhancedType) {
public Object intercept(Object object, Method method, Object[] args, MethodProxy proxy) throws Throwable {
return null;
}
};
MyInterface frontCGLibProxy = (MyInterface) frontCGLibProxyFactory.create(frontCGLibMethodInterceptor);
frontCGLibMethodInterceptor.connect(kernel.getMBeanServer(), objectName);
iterations = 100000000;
for (int i = 0; i < iterations; i++) {
frontCGLibProxy.doNothing();
}
start = System.currentTimeMillis();
for (int i = 0; i < iterations; i++) {
frontCGLibProxy.doNothing();
}
end = System.currentTimeMillis();
printResults("Front CGLibProxy", end, start, iterations);
*/
// Raw Invoker
RawInvoker rawInvoker = (RawInvoker) kernel.getAttribute(mockGBean.getAbstractName(), "$$RAW_INVOKER$$");
int rawIndex = ((Integer) rawInvoker.getOperationIndex().get(new GOperationSignature("doNothing", new String[0]))).intValue();
iterations = 2000000;
for (int i = 0; i < iterations; i++) {
rawInvoker.invoke(rawIndex, NO_ARGS);
}
start = System.currentTimeMillis();
for (int i = 0; i < iterations; i++) {
rawInvoker.invoke(rawIndex, NO_ARGS);
}
end = System.currentTimeMillis();
printResults("Raw Invoker", end, start, iterations);
// // cglib proxy
// ProxyFactory cgLibProxyFactory = new CGLibProxyFactory(MyInterface.class);
// ProxyMethodInterceptor cgLibMethodInterceptor = cgLibProxyFactory.getMethodInterceptor();
// MyInterface cgLibProxy = (MyInterface) cgLibProxyFactory.create(cgLibMethodInterceptor);
// cgLibMethodInterceptor.connect(kernel.getMBeanServer(), objectName);
// iterations = 1000000;
// for (int i = 0; i < iterations; i++) {
// cgLibProxy.doNothing();
// }
// start = System.currentTimeMillis();
// for (int i = 0; i < iterations; i++) {
// cgLibProxy.doNothing();
// }
// end = System.currentTimeMillis();
// printResults("CGLibProxy", end, start, iterations);
}
public void echoTimings() throws Exception {
Method myMethod = MockGBean.class.getMethod("echo", new Class[]{String.class});
FastClass myFastClass = FastClass.create(MockGBean.class);
int myMethodIndex = myFastClass.getIndex("echo", new Class[]{String.class});
String msg = "Some message";
Object[] args = new Object[]{msg};
String result;
MockGBean instance = new MockGBean("foo", 12);
// normal invoke
int iterations = 100000000;
for (int i = 0; i < iterations; i++) {
result = instance.echo(msg);
}
long start = System.currentTimeMillis();
for (int i = 0; i < iterations; i++) {
result = instance.echo(msg);
}
long end = System.currentTimeMillis();
printResults("Normal", end, start, iterations);
// reflection
iterations = 10000000;
for (int i = 0; i < iterations; i++) {
result = (String) myMethod.invoke(instance, args);
}
start = System.currentTimeMillis();
for (int i = 0; i < iterations; i++) {
result = (String) myMethod.invoke(instance, args);
}
end = System.currentTimeMillis();
printResults("Reflection", end, start, iterations);
// fast class
iterations = 10000000;
for (int i = 0; i < iterations; i++) {
result = (String) myFastClass.invoke(myMethodIndex, instance, args);
}
start = System.currentTimeMillis();
for (int i = 0; i < iterations; i++) {
result = (String) myFastClass.invoke(myMethodIndex, instance, args);
}
end = System.currentTimeMillis();
printResults("FastClass", end, start, iterations);
// start a kernel
Kernel kernel = KernelFactory.newInstance(getBundleContext()).createKernel("speed");
kernel.boot(bundleContext);
AbstractName abstractName = kernel.getNaming().createRootName(new Artifact("test", "foo", "1", "car"), "test", "test");
GBeanData mockGBean = new GBeanData(abstractName, MockGBean.getGBeanInfo());
mockGBean.setAttribute("Name", "bar");
mockGBean.setAttribute("FinalInt", new Integer(57));
kernel.loadGBean(mockGBean, getBundleContext());
kernel.startGBean(mockGBean.getAbstractName());
// reflect proxy
// ProxyFactory vmProxyFactory = new VMProxyFactory(MyInterface.class);
// ProxyMethodInterceptor vmMethodInterceptor = vmProxyFactory.getMethodInterceptor();
// MyInterface vmProxy = (MyInterface) vmProxyFactory.create(vmMethodInterceptor);
// vmMethodInterceptor.connect(kernel.getMBeanServer(), objectName);
// iterations = 50000;
// for (int i = 0; i < iterations; i++) {
// result = vmProxy.echo(msg);
// }
// start = System.currentTimeMillis();
// for (int i = 0; i < iterations; i++) {
// result = vmProxy.echo(msg);
// }
// end = System.currentTimeMillis();
// printResults("ReflectionProxy", end, start, iterations);
// // cglib proxy
// ProxyFactory cgLibProxyFactory = new CGLibProxyFactory(MyInterface.class);
// ProxyMethodInterceptor cgLibMethodInterceptor = cgLibProxyFactory.getMethodInterceptor();
// MyInterface cgLibProxy = (MyInterface) cgLibProxyFactory.create(cgLibMethodInterceptor);
// cgLibMethodInterceptor.connect(kernel.getMBeanServer(), objectName);
// iterations = 1000000;
// for (int i = 0; i < iterations; i++) {
// result = cgLibProxy.echo(msg);
// }
// start = System.currentTimeMillis();
// for (int i = 0; i < iterations; i++) {
// result = cgLibProxy.echo(msg);
// }
// end = System.currentTimeMillis();
// printResults("CGLibProxy", end, start, iterations);
}
private static void printResults(String invocationType, long end, long start, int iterations) {
if(end - start < 400) {
System.out.println(invocationType + ": elapse time to short to calculate cost (total " + (end - start) + "ms)");
} else {
System.out.println(invocationType + ": " + ((end - start) * 1000000.0 / iterations) + "ns (total " + (end - start) + "ms)");
}
}
public static interface MyInterface {
void doNothing();
String echo(String msg);
}
}
| 42.425
| 137
| 0.621012
|
5f8bb44ee266ac725283e238dee61020a1dcc0ea
| 571
|
package com.tp.ehub.order.messaging.command;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.tp.ehub.common.domain.exception.BusinessException;
/**
* A <code>Command</code> to cancel an existing order
*
*/
@JsonTypeName(CancelOrderCommand.NAME)
public class CancelOrderCommand extends OrderCommand {
public static final String NAME = "Commands.CancelOrder";
public CancelOrderCommand() {
}
@Override
public <P, R> R map(P parameter, BiFunctionVisitor<P, R> visitor) throws BusinessException{
return visitor.visit(parameter, this);
}
}
| 23.791667
| 92
| 0.767075
|
83d9dc66f4b6ecc3bfcc86de808ae3be06873af4
| 16,826
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.glaf.core.config;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.alibaba.fastjson.JSONObject;
import com.glaf.core.context.ContextFactory;
import com.glaf.core.domain.SystemProperty;
import com.glaf.core.domain.util.SystemPropertyJsonFactory;
import com.glaf.core.el.Mvel2ExpressionEvaluator;
import com.glaf.core.service.ISystemPropertyService;
import com.glaf.core.util.DateUtils;
import com.glaf.core.util.StringTools;
public class SystemConfig {
protected static final Log logger = LogFactory.getLog(SystemConfig.class);
protected static ConcurrentMap<String, SystemProperty> concurrentMap = new ConcurrentHashMap<String, SystemProperty>();
protected static ConcurrentMap<String, Long> concurrentTimeMap = new ConcurrentHashMap<String, Long>();
protected static AtomicBoolean loading = new AtomicBoolean(false);
protected static Configuration conf = BaseConfiguration.create();
public static final String DEFAULT_ENCODING = "UTF-8";
public final static String CURR_YYYYMMDD = "#{curr_yyyymmdd}";
public final static String CURR_YYYYMM = "#{curr_yyyymm}";
public final static String INPUT_YYYYMMDD = "#{input_yyyymmdd}";
public final static String INPUT_YYYYMM = "#{input_yyyymm}";
public final static String LONG_ID = "#{longId}";
public final static String NOW = "#{now}";
private static volatile String TOKEN = null;
private static volatile String SYS_CODE = null;
private static volatile Integer INT_TOKEN = 0;
private static volatile AtomicBoolean concurrentAccessLimit = null;
public static void clear() {
concurrentAccessLimit = null;
}
public static boolean getBoolean(String key) {
boolean ret = false;
SystemProperty property = getProperty(key);
if (property != null) {
String value = property.getValue();
if (StringUtils.isEmpty(value)) {
value = property.getInitValue();
}
if (StringUtils.equalsIgnoreCase(value, "true") || StringUtils.equalsIgnoreCase(value, "1")
|| StringUtils.equalsIgnoreCase(value, "y") || StringUtils.equalsIgnoreCase(value, "yes")) {
ret = true;
}
}
return ret;
}
public static boolean getBoolean(String key, boolean defaultValue) {
boolean ret = defaultValue;
SystemProperty property = concurrentMap.get(key);
if (property == null) {
/**
* 判断是否需要从数据库获取配置
*/
Long ts = concurrentTimeMap.get(key);
if (ts == null || ((System.currentTimeMillis() - ts.longValue()) > DateUtils.MINUTE * 5)) {
PropertyHelper propertyHelper = new PropertyHelper();
property = propertyHelper.getSystemPropertyByKey(key);
if (property != null) {
concurrentMap.put(key, property);
}
concurrentTimeMap.put(key, System.currentTimeMillis());
}
}
if (property != null) {
String value = property.getValue();
if (StringUtils.isEmpty(value)) {
value = property.getInitValue();
}
if (StringUtils.equalsIgnoreCase(value, "true") || StringUtils.equalsIgnoreCase(value, "1")
|| StringUtils.equalsIgnoreCase(value, "y") || StringUtils.equalsIgnoreCase(value, "yes")) {
ret = true;
}
}
// logger.debug("key[" + key + "]=" + ret);
return ret;
}
public static synchronized boolean getConcurrentAccessLimit() {
if (concurrentAccessLimit == null) {
boolean ret = getBoolean("concurrentAccessLimit");
concurrentAccessLimit = new AtomicBoolean();
concurrentAccessLimit.set(ret);
}
return concurrentAccessLimit.get();
}
public static Map<String, Object> getContextMap() {
Map<String, Object> dataMap = new java.util.HashMap<String, Object>();
dataMap.put(CURR_YYYYMMDD, getCurrentYYYYMMDD());
dataMap.put(CURR_YYYYMM, getCurrentYYYYMM());
dataMap.put(INPUT_YYYYMMDD, getInputYYYYMMDD());
dataMap.put(INPUT_YYYYMM, getInputYYYYMM());
dataMap.put("curr_yyyymmdd", getCurrentYYYYMMDD());
dataMap.put("curr_yyyymm", getCurrentYYYYMM());
dataMap.put("input_yyyymmdd", getInputYYYYMMDD());
dataMap.put("input_yyyymm", getInputYYYYMM());
dataMap.put("now", getCurrentYYYYMMDD());
dataMap.put("${now}", getCurrentYYYYMMDD());
dataMap.put("#{now}", getCurrentYYYYMMDD());
return dataMap;
}
public static String getCurrentYYYYMM() {
String value = getString("curr_yyyymm");
if (StringUtils.isEmpty(value) || StringUtils.equals("curr_yyyymm", value)
|| StringUtils.equals(CURR_YYYYMM, value)) {
Date now = new Date();
value = String.valueOf(DateUtils.getYearMonth(now));
}
logger.debug("curr_yyyymm:" + value);
return value;
}
public static String getCurrentYYYYMMDD() {
String value = getString("curr_yyyymmdd");
if (StringUtils.isEmpty(value) || StringUtils.equals("curr_yyyymmdd", value)
|| StringUtils.equals(CURR_YYYYMMDD, value)) {
Date now = new Date();
value = String.valueOf(DateUtils.getYearMonthDay(now));
}
logger.debug("curr_yyyymmdd:" + value);
return value;
}
public static String getDataPath() {
String dataDir = getString("dataDir");
if (StringUtils.isEmpty(dataDir)) {
dataDir = SystemProperties.getConfigRootPath() + "/report/data";
}
return dataDir;
}
public static String getDefaultEncoding() {
return DEFAULT_ENCODING;
}
public static String getInputYYYYMM() {
String value = getString("input_yyyymm");
if (StringUtils.isEmpty(value) || StringUtils.equals("input_yyyymm", value)
|| StringUtils.equals(INPUT_YYYYMM, value)) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
calendar.set(year, month, day - 1);
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
month = month + 1;
logger.debug(year + "-" + month);
StringBuilder sb = new StringBuilder(50);
sb.append(year);
if (month <= 9) {
sb.append("0").append(month);
} else {
sb.append(month);
}
value = sb.toString();
}
logger.debug("input_yyyymm:" + value);
return value;
}
public static String getInputYYYYMMDD() {
String value = getString("input_yyyymmdd");
if (StringUtils.isEmpty(value) || StringUtils.equals("input_yyyymmdd", value)
|| StringUtils.equals(INPUT_YYYYMMDD, value)) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
calendar.set(year, month, day - 1);
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
month = month + 1;
day = calendar.get(Calendar.DAY_OF_MONTH);
logger.debug(year + "-" + month + "-" + day);
StringBuilder sb = new StringBuilder(50);
sb.append(year);
if (month <= 9) {
sb.append("0").append(month);
} else {
sb.append(month);
}
if (day <= 9) {
sb.append("0").append(day);
} else {
sb.append(day);
}
value = sb.toString();
}
logger.debug("input_yyyymmdd:" + value);
return value;
}
public static int getInt(String key, int defaultValue) {
int ret = defaultValue;
SystemProperty prop = getProperty(key);
if (prop != null) {
String value = prop.getValue();
if (StringUtils.isEmpty(value)) {
value = prop.getInitValue();
}
try {
ret = Integer.parseInt(value);
} catch (Exception ex) {
}
}
return ret;
}
public static int getIntToken() {
if (INT_TOKEN > 0) {
return INT_TOKEN;
}
PropertyHelper propertyHelper = new PropertyHelper();
SystemProperty property = propertyHelper.getSystemPropertyById("INT_TOKEN");
if (property != null && property.getValue() != null) {
INT_TOKEN = Integer.parseInt(property.getValue());
} else {
java.util.Random random = new java.util.Random();
INT_TOKEN = Math.abs(random.nextInt(99999999)) + 1;
property = new SystemProperty();
property.setId("INT_TOKEN");
property.setCategory("SYS");
property.setName("INT_TOKEN");
property.setLocked(0);
property.setValue(String.valueOf(INT_TOKEN));
property.setTitle("INT_TOKEN");
property.setType("String");
propertyHelper.save(property);
}
return INT_TOKEN;
}
public static long getLong(String key, long defaultValue) {
long ret = defaultValue;
SystemProperty prop = getProperty(key);
if (prop != null) {
String value = prop.getValue();
if (StringUtils.isEmpty(value)) {
value = prop.getInitValue();
}
try {
ret = Long.parseLong(value);
} catch (Exception ex) {
}
}
return ret;
}
public static String getMappingPath() {
String mappingDir = SystemProperties.getConfigRootPath() + "/report/mapping";
return mappingDir;
}
public static SystemProperty getProperty(String key) {
SystemProperty property = null;
if (concurrentMap.size() == 0) {
reload();
}
property = concurrentMap.get(key);
if (property == null) {
/**
* 判断是否需要从数据库获取配置
*/
Long ts = concurrentTimeMap.get(key);
if (ts == null || ((System.currentTimeMillis() - ts.longValue()) > DateUtils.MINUTE * 5)) {
PropertyHelper propertyHelper = new PropertyHelper();
property = propertyHelper.getSystemPropertyById(key);
if (property == null) {
property = propertyHelper.getSystemPropertyByKey(key);
}
concurrentTimeMap.put(key, System.currentTimeMillis());
}
if (property != null) {
concurrentMap.put(key, property);
}
}
if (property != null) {
JSONObject jsonObject = SystemPropertyJsonFactory.toJsonObject(property);
return SystemPropertyJsonFactory.jsonToObject(jsonObject);
}
return null;
}
public static String getRegionName(String name) {
StringBuilder buffer = new StringBuilder(200);
if (Environment.getCurrentSystemName() != null
&& !StringUtils.equals(Environment.DEFAULT_SYSTEM_NAME, Environment.getCurrentSystemName())) {
buffer.append(Environment.getCurrentSystemName()).append("_");
} else {
buffer.append("g_");
}
buffer.append(getIntToken()).append("_");
if (name != null) {
buffer.append(name);
}
String regionName = buffer.toString();
if (regionName.indexOf("/") != -1) {
regionName = StringTools.replace(regionName, "/", "_");
}
if (regionName.indexOf("\\") != -1) {
regionName = StringTools.replace(regionName, "\\", "_");
}
return regionName;
}
public static String getReportSavePath() {
String value = getString("report_save_path");
if (StringUtils.isEmpty(value)) {
value = SystemProperties.getConfigRootPath() + "/report";
}
return value;
}
/**
* 获取服务地址
*
* @return
*/
public static String getServiceUrl() {
return getString("serviceUrl");
}
public static String getString(String key) {
String ret = null;
SystemProperty prop = getProperty(key);
if (prop != null) {
String value = prop.getValue();
if (StringUtils.isEmpty(value)) {
value = prop.getInitValue();
}
ret = value;
}
return ret;
}
public static String getString(String key, String defaultValue) {
String ret = defaultValue;
SystemProperty prop = getProperty(key);
if (prop != null) {
String value = prop.getValue();
if (StringUtils.isEmpty(value)) {
value = prop.getInitValue();
}
ret = value;
}
return ret;
}
public static String getStringValue(String key, String defaultValue) {
String ret = defaultValue;
SystemProperty property = concurrentMap.get(key);
if (property == null) {
/**
* 判断是否需要从数据库获取配置
*/
Long ts = concurrentTimeMap.get(key);
if (ts == null || ((System.currentTimeMillis() - ts.longValue()) > DateUtils.MINUTE * 5)) {
PropertyHelper propertyHelper = new PropertyHelper();
property = propertyHelper.getSystemPropertyByKey(key);
if (property != null) {
concurrentMap.put(key, property);
}
concurrentTimeMap.put(key, System.currentTimeMillis());
}
}
if (property != null) {
String value = property.getValue();
if (StringUtils.isEmpty(value)) {
value = property.getInitValue();
}
ret = value;
}
return ret;
}
public static String getSysCode() {
if (SYS_CODE != null) {
return SYS_CODE;
}
PropertyHelper propertyHelper = new PropertyHelper();
SystemProperty property = propertyHelper.getSystemPropertyById("SYS_CODE");
if (property != null && property.getValue() != null) {
SYS_CODE = property.getValue();
} else {
property = new SystemProperty();
property.setId("SYS_CODE");
property.setCategory("SYS");
property.setName("SYS_CODE");
property.setLocked(0);
property.setValue(SYS_CODE);
property.setTitle("系统编码");
property.setType("String");
propertyHelper.save(property);
}
return SYS_CODE;
}
public static String getToken() {
if (TOKEN != null) {
return TOKEN;
}
PropertyHelper propertyHelper = new PropertyHelper();
SystemProperty property = propertyHelper.getSystemPropertyById("TOKEN");
if (property != null && property.getValue() != null) {
TOKEN = property.getValue();
} else {
java.util.Random random = new java.util.Random();
TOKEN = Math.abs(random.nextInt(9999)) + com.glaf.core.util.UUID32.getUUID()
+ Math.abs(random.nextInt(9999));
property = new SystemProperty();
property.setId("TOKEN");
property.setCategory("SYS");
property.setName("TOKEN");
property.setLocked(0);
property.setValue(TOKEN);
property.setTitle("TOKEN");
property.setType("String");
propertyHelper.save(property);
}
return TOKEN;
}
/**
* 直接获取数据库存储的属性值
*
* @param key
* @return
*/
public static String getValueByKey(String key) {
String ret = null;
PropertyHelper helper = new PropertyHelper();
SystemProperty prop = helper.getSystemPropertyByKey(key);
if (prop != null) {
String value = prop.getValue();
if (StringUtils.isEmpty(value)) {
value = prop.getInitValue();
}
ret = value;
}
return ret;
}
public static void main(String[] args) {
Date now = new Date();
Map<String, Object> sysMap = new java.util.HashMap<String, Object>();
sysMap.put("curr_yyyymmdd", DateUtils.getYearMonthDay(now));
sysMap.put("curr_yyyymm", DateUtils.getYearMonth(now));
System.out.println(Mvel2ExpressionEvaluator.evaluate("#{curr_yyyymmdd}-1", sysMap));
}
public static void reload() {
if (!loading.get()) {
try {
loading.set(true);
logger.info("start reload system config...");
concurrentMap.clear();
concurrentTimeMap.clear();
ISystemPropertyService systemPropertyService = ContextFactory.getBean("systemPropertyService");
List<SystemProperty> list = systemPropertyService.getAllSystemProperties();
if (list != null && !list.isEmpty()) {
for (SystemProperty p : list) {
concurrentMap.put(p.getName(), p);
if (p.getValue() != null) {
conf.set(p.getName(), p.getValue());
}
// if
// (SystemConfig.getBoolean("distributed.config.enabled"))
// {
// ConfigFactory.put(SystemConfig.class.getSimpleName(),
// p.getName(),
// SystemPropertyJsonFactory.toJsonObject(p).toJSONString());
// }
}
}
SystemProperty property = systemPropertyService.getSystemPropertyById("INT_TOKEN");
if (property != null && property.getValue() != null) {
INT_TOKEN = Integer.parseInt(property.getValue());
}
concurrentAccessLimit = null;
logger.info("reload system config end.");
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
} finally {
loading.set(false);
}
}
}
public static void setProperty(SystemProperty p) {
if (p != null && p.getName() != null) {
String complexKey = p.getName();
concurrentMap.put(complexKey, p);
ConfigFactory.put(SystemConfig.class.getSimpleName(), p.getName(),
SystemPropertyJsonFactory.toJsonObject(p).toJSONString());
}
}
}
| 29.939502
| 120
| 0.69143
|
52a2e5898046de6ad7fceb040fc4691e19a6f827
| 2,948
|
/* (c) 2004 Allen I. Holub. All rights reserved.
*
* This code may be used freely by yourself with the following
* restrictions:
*
* o Your splash screen, about box, or equivalent, must include
* Allen Holub's name, copyright, and URL. For example:
*
* This program contains Allen Holub's SQL package.<br>
* (c) 2005 Allen I. Holub. All Rights Reserved.<br>
* http://www.holub.com<br>
*
* If your program does not run interactively, then the foregoing
* notice must appear in your documentation.
*
* o You may not redistribute (or mirror) the source code.
*
* o You must report any bugs that you find to me. Use the form at
* http://www.holub.com/company/contact.html or send email to
* allen@Holub.com.
*
* o The software is supplied <em>as is</em>. Neither Allen Holub nor
* Holub Associates are responsible for any bugs (or any problems
* caused by bugs, including lost productivity or data)
* in any of this code.
*/
package com.holub.text;
/**
* Recognize a token that looks like a word. The match
* is case insensitive. To be recognized, the input
* must match the pattern passed to the constructor,
* and must be followed by a non-letter-or-digit.
* The returned lexeme is always all-lower-case
* letters, regardless of what the actual input
* looked like.
*
* @include /etc/license.txt
* @see Token
*/
public class WordToken implements Token {
private final String pattern;
/**
* Create a token.
*
* @param pattern a regular expression
* ({@linkplain java.util.Pattern see}) that describes
* the set of lexemes associated with this token.
*/
public WordToken(String pattern) {
this.pattern = pattern.toLowerCase();
}
public boolean match(String input, int offset) {
// Check that the input matches the patter in a
// case-insensitive way. If you don't want case
// insenstivity, use the following, less complicated code:
//
// if( !input.toLowerCase().startsWith(pattern, offset) )
// return false;
if ((input.length() - offset) < pattern.length())
return false;
String candidate = input.substring(offset,
offset + pattern.length());
if (!candidate.equalsIgnoreCase(pattern))
return false;
// Return true if the lexeme is at the end of the
// input string or if the character following the
// lexeme is not a letter or digit.
return ((input.length() - offset) == pattern.length())
|| (!Character.isLetterOrDigit(
input.charAt(offset + pattern.length())));
}
public String lexeme() {
return pattern;
}
public String toString() {
return pattern;
}
}
| 32.755556
| 74
| 0.610923
|
167043fcbed69749a50d9f4fd49f07fa2dc5b698
| 1,193
|
package student;
import java.util.Scanner;
public class TestStudent
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
// Ucitavaju se ime i prezime studenta, fakultet i godina studija
System.out.print("Ime: ");
String ime = sc.next();
System.out.print("Prezime: ");
String prezime = sc.next();
System.out.print("Fakultet: ");
String fakultet = sc.next();
System.out.print("Godina: ");
int godina = sc.nextInt();
sc.close();
// Generise se string sa imenom i prezimenom studenta razdvojenih belinom
String imePrezime = ime + " " + prezime;
// Kreira se objekat klase Student, a instancne promenljive se
// inicijalizuju ucitanim vrednostima.
Student student1 = new Student(imePrezime, fakultet, godina);
// Ispis podataka o studentu. Implicitno se poziva metod toString() za
// generisanje String-reprezentacije.
System.out.println(student1);
// Kreira se objekat klase Student pozivom podrazumevanog konstruktora,
// tako da ce instancne promenljive biti postavljene na podrazumevane vrednosti.
Student student2 = new Student();
System.out.println(student2);
}
}
| 32.243243
| 83
| 0.694887
|
3adb986857c8c1f1de67fe373e7d21834e7bd83f
| 2,231
|
package com.netbreeze.bbowl;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
* Contains settings for the bean bowl application
*
* @author Henrik Kniberg
*/
public class Settings implements java.io.Serializable {
private final static String FILENAME = "beanbowlSettings.ser";
private final static int RECENT_FILE_COUNT = 5;
transient static Settings settings;
public List recentFiles;
private Settings() {
recentFiles = new LinkedList();
}
public static void addRecentFile(File file) {
if (file != null && !settings.recentFiles.contains(file)) {
settings.recentFiles.add(0, file);
}
while(settings.recentFiles.size() > 5) {
settings.recentFiles.remove(4);
}
}
public static Iterator getRecentFiles() {
return settings.recentFiles.iterator();
}
static {
if (getFile().exists()) {
try {
loadFromFile();
} catch (Exception err) {
System.err.println("Warning - settings could not be loaded: " + err.getMessage());
settings = new Settings();
}
} else {
settings = new Settings();
}
}
@Override
protected void finalize() {
try {
saveToFile();
} catch (Exception err) {
System.err.println("Warning - settings could not be saved: " + err.getMessage());
}
}
public static void loadFromFile() throws Exception {
InputStream fileIn = new FileInputStream(getFile());
ObjectInputStream objectIn = new ObjectInputStream(fileIn);
settings = (Settings) (objectIn.readObject());
objectIn.close();
fileIn.close();
}
public static void saveToFile() throws Exception {
FileOutputStream fileOut = new FileOutputStream(getFile());
ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);
objectOut.writeObject(settings);
objectOut.close();
fileOut.close();
}
private static File getFile() {
File homeDir = new File(System.getProperties().getProperty("user.home"));
return new File(homeDir, FILENAME);
}
}
| 25.643678
| 90
| 0.685791
|
8b5552a772b79f6aa2032c7df2a8bec63aba515b
| 360
|
package io.musician101.itembank.common;
import io.musician101.itembank.common.account.Account;
import io.musician101.musicianlibrary.java.storage.DataStorage;
import java.io.IOException;
import javax.annotation.Nonnull;
public interface ItemBank<I> {
@Nonnull
DataStorage<?, Account<I>> getAccountStorage();
void reload() throws IOException;
}
| 24
| 63
| 0.783333
|
6352514b96ea15e1f90ebdc0294723010d2b1b24
| 11,875
|
package com.prowidesoftware.swift.model.mx.dic;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
/**
* Specifies further details of the transaction for which the penalties apply.
*
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "PenaltyTransactionRecord1", propOrder = {
"sttlmTxOrCorpActnEvtTp",
"sttlmDt",
"corpActnRltdDt",
"sfkpgAcct",
"acctOwnr",
"sctiesMvmntTp",
"pmt",
"pstngQty",
"cshAcct",
"cshAcctOwnr",
"pstngAmt",
"ackdStsTmStmp",
"mtchdStsTmStmp",
"sttlmStsFlng",
"bizDayEvt"
})
public class PenaltyTransactionRecord1 {
@XmlElement(name = "SttlmTxOrCorpActnEvtTp", required = true)
protected SettlementOrCorporateActionEvent27Choice sttlmTxOrCorpActnEvtTp;
@XmlElement(name = "SttlmDt", required = true)
protected SettlementDate17Choice sttlmDt;
@XmlElement(name = "CorpActnRltdDt")
protected DateAndDateTime2Choice corpActnRltdDt;
@XmlElement(name = "SfkpgAcct", required = true)
protected SecuritiesAccount19 sfkpgAcct;
@XmlElement(name = "AcctOwnr")
protected PartyIdentification144 acctOwnr;
@XmlElement(name = "SctiesMvmntTp", required = true)
@XmlSchemaType(name = "string")
protected ReceiveDelivery1Code sctiesMvmntTp;
@XmlElement(name = "Pmt", required = true)
@XmlSchemaType(name = "string")
protected DeliveryReceiptType2Code pmt;
@XmlElement(name = "PstngQty", required = true)
protected FinancialInstrumentQuantity1Choice pstngQty;
@XmlElement(name = "CshAcct")
protected CashAccountIdentification5Choice cshAcct;
@XmlElement(name = "CshAcctOwnr")
protected PartyIdentification135 cshAcctOwnr;
@XmlElement(name = "PstngAmt")
protected AmountAndDirection5 pstngAmt;
@XmlElement(name = "AckdStsTmStmp")
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar ackdStsTmStmp;
@XmlElement(name = "MtchdStsTmStmp")
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar mtchdStsTmStmp;
@XmlElement(name = "SttlmStsFlng")
protected FailingStatus10Choice sttlmStsFlng;
@XmlElement(name = "BizDayEvt")
protected SystemEvent3 bizDayEvt;
/**
* Gets the value of the sttlmTxOrCorpActnEvtTp property.
*
* @return
* possible object is
* {@link SettlementOrCorporateActionEvent27Choice }
*
*/
public SettlementOrCorporateActionEvent27Choice getSttlmTxOrCorpActnEvtTp() {
return sttlmTxOrCorpActnEvtTp;
}
/**
* Sets the value of the sttlmTxOrCorpActnEvtTp property.
*
* @param value
* allowed object is
* {@link SettlementOrCorporateActionEvent27Choice }
*
*/
public PenaltyTransactionRecord1 setSttlmTxOrCorpActnEvtTp(SettlementOrCorporateActionEvent27Choice value) {
this.sttlmTxOrCorpActnEvtTp = value;
return this;
}
/**
* Gets the value of the sttlmDt property.
*
* @return
* possible object is
* {@link SettlementDate17Choice }
*
*/
public SettlementDate17Choice getSttlmDt() {
return sttlmDt;
}
/**
* Sets the value of the sttlmDt property.
*
* @param value
* allowed object is
* {@link SettlementDate17Choice }
*
*/
public PenaltyTransactionRecord1 setSttlmDt(SettlementDate17Choice value) {
this.sttlmDt = value;
return this;
}
/**
* Gets the value of the corpActnRltdDt property.
*
* @return
* possible object is
* {@link DateAndDateTime2Choice }
*
*/
public DateAndDateTime2Choice getCorpActnRltdDt() {
return corpActnRltdDt;
}
/**
* Sets the value of the corpActnRltdDt property.
*
* @param value
* allowed object is
* {@link DateAndDateTime2Choice }
*
*/
public PenaltyTransactionRecord1 setCorpActnRltdDt(DateAndDateTime2Choice value) {
this.corpActnRltdDt = value;
return this;
}
/**
* Gets the value of the sfkpgAcct property.
*
* @return
* possible object is
* {@link SecuritiesAccount19 }
*
*/
public SecuritiesAccount19 getSfkpgAcct() {
return sfkpgAcct;
}
/**
* Sets the value of the sfkpgAcct property.
*
* @param value
* allowed object is
* {@link SecuritiesAccount19 }
*
*/
public PenaltyTransactionRecord1 setSfkpgAcct(SecuritiesAccount19 value) {
this.sfkpgAcct = value;
return this;
}
/**
* Gets the value of the acctOwnr property.
*
* @return
* possible object is
* {@link PartyIdentification144 }
*
*/
public PartyIdentification144 getAcctOwnr() {
return acctOwnr;
}
/**
* Sets the value of the acctOwnr property.
*
* @param value
* allowed object is
* {@link PartyIdentification144 }
*
*/
public PenaltyTransactionRecord1 setAcctOwnr(PartyIdentification144 value) {
this.acctOwnr = value;
return this;
}
/**
* Gets the value of the sctiesMvmntTp property.
*
* @return
* possible object is
* {@link ReceiveDelivery1Code }
*
*/
public ReceiveDelivery1Code getSctiesMvmntTp() {
return sctiesMvmntTp;
}
/**
* Sets the value of the sctiesMvmntTp property.
*
* @param value
* allowed object is
* {@link ReceiveDelivery1Code }
*
*/
public PenaltyTransactionRecord1 setSctiesMvmntTp(ReceiveDelivery1Code value) {
this.sctiesMvmntTp = value;
return this;
}
/**
* Gets the value of the pmt property.
*
* @return
* possible object is
* {@link DeliveryReceiptType2Code }
*
*/
public DeliveryReceiptType2Code getPmt() {
return pmt;
}
/**
* Sets the value of the pmt property.
*
* @param value
* allowed object is
* {@link DeliveryReceiptType2Code }
*
*/
public PenaltyTransactionRecord1 setPmt(DeliveryReceiptType2Code value) {
this.pmt = value;
return this;
}
/**
* Gets the value of the pstngQty property.
*
* @return
* possible object is
* {@link FinancialInstrumentQuantity1Choice }
*
*/
public FinancialInstrumentQuantity1Choice getPstngQty() {
return pstngQty;
}
/**
* Sets the value of the pstngQty property.
*
* @param value
* allowed object is
* {@link FinancialInstrumentQuantity1Choice }
*
*/
public PenaltyTransactionRecord1 setPstngQty(FinancialInstrumentQuantity1Choice value) {
this.pstngQty = value;
return this;
}
/**
* Gets the value of the cshAcct property.
*
* @return
* possible object is
* {@link CashAccountIdentification5Choice }
*
*/
public CashAccountIdentification5Choice getCshAcct() {
return cshAcct;
}
/**
* Sets the value of the cshAcct property.
*
* @param value
* allowed object is
* {@link CashAccountIdentification5Choice }
*
*/
public PenaltyTransactionRecord1 setCshAcct(CashAccountIdentification5Choice value) {
this.cshAcct = value;
return this;
}
/**
* Gets the value of the cshAcctOwnr property.
*
* @return
* possible object is
* {@link PartyIdentification135 }
*
*/
public PartyIdentification135 getCshAcctOwnr() {
return cshAcctOwnr;
}
/**
* Sets the value of the cshAcctOwnr property.
*
* @param value
* allowed object is
* {@link PartyIdentification135 }
*
*/
public PenaltyTransactionRecord1 setCshAcctOwnr(PartyIdentification135 value) {
this.cshAcctOwnr = value;
return this;
}
/**
* Gets the value of the pstngAmt property.
*
* @return
* possible object is
* {@link AmountAndDirection5 }
*
*/
public AmountAndDirection5 getPstngAmt() {
return pstngAmt;
}
/**
* Sets the value of the pstngAmt property.
*
* @param value
* allowed object is
* {@link AmountAndDirection5 }
*
*/
public PenaltyTransactionRecord1 setPstngAmt(AmountAndDirection5 value) {
this.pstngAmt = value;
return this;
}
/**
* Gets the value of the ackdStsTmStmp property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getAckdStsTmStmp() {
return ackdStsTmStmp;
}
/**
* Sets the value of the ackdStsTmStmp property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public PenaltyTransactionRecord1 setAckdStsTmStmp(XMLGregorianCalendar value) {
this.ackdStsTmStmp = value;
return this;
}
/**
* Gets the value of the mtchdStsTmStmp property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getMtchdStsTmStmp() {
return mtchdStsTmStmp;
}
/**
* Sets the value of the mtchdStsTmStmp property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public PenaltyTransactionRecord1 setMtchdStsTmStmp(XMLGregorianCalendar value) {
this.mtchdStsTmStmp = value;
return this;
}
/**
* Gets the value of the sttlmStsFlng property.
*
* @return
* possible object is
* {@link FailingStatus10Choice }
*
*/
public FailingStatus10Choice getSttlmStsFlng() {
return sttlmStsFlng;
}
/**
* Sets the value of the sttlmStsFlng property.
*
* @param value
* allowed object is
* {@link FailingStatus10Choice }
*
*/
public PenaltyTransactionRecord1 setSttlmStsFlng(FailingStatus10Choice value) {
this.sttlmStsFlng = value;
return this;
}
/**
* Gets the value of the bizDayEvt property.
*
* @return
* possible object is
* {@link SystemEvent3 }
*
*/
public SystemEvent3 getBizDayEvt() {
return bizDayEvt;
}
/**
* Sets the value of the bizDayEvt property.
*
* @param value
* allowed object is
* {@link SystemEvent3 }
*
*/
public PenaltyTransactionRecord1 setBizDayEvt(SystemEvent3 value) {
this.bizDayEvt = value;
return this;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
}
@Override
public boolean equals(Object that) {
return EqualsBuilder.reflectionEquals(this, that);
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
}
| 25.373932
| 112
| 0.610358
|
cf6feefa69ff0f3794456e40e32509f9b8061160
| 140
|
package com.tcua.junit.soa.handler;
public class ElementStatus {
// position used by array elements
public int position = 0;
}
| 15.555556
| 36
| 0.7
|
2510905060bdb1eff35714ea11fa9f5d934efcb3
| 2,137
|
/* ==================================================================
* PasswordEntry.java - Mar 19, 2013 6:46:30 AM
*
* Copyright 2007-2013 SolarNetwork.net Dev Team
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA
* ==================================================================
*/
package net.solarnetwork.central.user.domain;
/**
* Password reset bean.
*
* @author matt
* @version 1.0
*/
public class PasswordEntry {
private String username;
private String confirmationCode;
private String password;
private String passwordConfirm;
/**
* Default constructor.
*/
public PasswordEntry() {
super();
}
/**
* Construct with a password.
*
* @param password
* the password to set
*/
public PasswordEntry(String password) {
super();
setPassword(password);
setPasswordConfirm(password);
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPasswordConfirm() {
return passwordConfirm;
}
public void setPasswordConfirm(String passwordConfirm) {
this.passwordConfirm = passwordConfirm;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getConfirmationCode() {
return confirmationCode;
}
public void setConfirmationCode(String confirmationCode) {
this.confirmationCode = confirmationCode;
}
}
| 23.744444
| 69
| 0.674778
|
ee9f9b7fa3bc5bf0913459d4ebb8a939e4d85a70
| 12,176
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hive.ql.exec.spark;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import org.apache.hadoop.hive.ql.io.HiveKey;
import org.apache.hadoop.io.BytesWritable;
import org.junit.Test;
import scala.Tuple2;
import com.clearspring.analytics.util.Preconditions;
@SuppressWarnings({"unchecked", "rawtypes"})
public class TestHiveKVResultCache {
@Test
public void testSimple() throws Exception {
// Create KV result cache object, add one (k,v) pair and retrieve them.
HiveKVResultCache cache = new HiveKVResultCache();
HiveKey key = new HiveKey("key".getBytes(), "key".hashCode());
BytesWritable value = new BytesWritable("value".getBytes());
cache.add(key, value);
assertTrue("KV result cache should have at least one element", cache.hasNext());
Tuple2<HiveKey, BytesWritable> row = cache.next();
assertTrue("Incorrect key", row._1().equals(key));
assertTrue("Incorrect value", row._2().equals(value));
assertTrue("Cache shouldn't have more records", !cache.hasNext());
}
@Test
public void testSpilling() throws Exception {
HiveKVResultCache cache = new HiveKVResultCache();
final int recordCount = HiveKVResultCache.IN_MEMORY_NUM_ROWS * 3;
// Test using the same cache where first n rows are inserted then cache is cleared.
// Next reuse the same cache and insert another m rows and verify the cache stores correctly.
// This simulates reusing the same cache over and over again.
testSpillingHelper(cache, recordCount);
testSpillingHelper(cache, 1);
testSpillingHelper(cache, recordCount);
}
/** Helper method which inserts numRecords and retrieves them from cache and verifies */
private void testSpillingHelper(HiveKVResultCache cache, int numRecords) {
for(int i=0; i<numRecords; i++) {
String key = "key_" + i;
String value = "value_" + i;
cache.add(new HiveKey(key.getBytes(), key.hashCode()), new BytesWritable(value.getBytes()));
}
int recordsSeen = 0;
while(cache.hasNext()) {
String key = "key_" + recordsSeen;
String value = "value_" + recordsSeen;
Tuple2<HiveKey, BytesWritable> row = cache.next();
assertTrue("Unexpected key at position: " + recordsSeen,
new String(row._1().getBytes()).equals(key));
assertTrue("Unexpected value at position: " + recordsSeen,
new String(row._2().getBytes()).equals(value));
recordsSeen++;
}
assertTrue("Retrieved record count doesn't match inserted record count",
numRecords == recordsSeen);
cache.clear();
}
@Test
public void testResultList() throws Exception {
scanAndVerify(10000, 0, 0, "a", "b");
scanAndVerify(10000, 511, 0, "a", "b");
scanAndVerify(10000, 511 * 2, 0, "a", "b");
scanAndVerify(10000, 511, 10, "a", "b");
scanAndVerify(10000, 511 * 2, 10, "a", "b");
scanAndVerify(10000, 512, 0, "a", "b");
scanAndVerify(10000, 512 * 2, 0, "a", "b");
scanAndVerify(10000, 512, 3, "a", "b");
scanAndVerify(10000, 512 * 6, 10, "a", "b");
scanAndVerify(10000, 512 * 7, 5, "a", "b");
scanAndVerify(10000, 512 * 9, 19, "a", "b");
scanAndVerify(10000, 1, 0, "a", "b");
scanAndVerify(10000, 1, 1, "a", "b");
}
private static void scanAndVerify(
long rows, int threshold, int separate, String prefix1, String prefix2) {
ArrayList<Tuple2<HiveKey, BytesWritable>> output =
new ArrayList<Tuple2<HiveKey, BytesWritable>>((int)rows);
scanResultList(rows, threshold, separate, output, prefix1, prefix2);
assertEquals(rows, output.size());
long primaryRows = rows * (100 - separate) / 100;
long separateRows = rows - primaryRows;
HashSet<Long> primaryRowKeys = new HashSet<Long>();
HashSet<Long> separateRowKeys = new HashSet<Long>();
for (Tuple2<HiveKey, BytesWritable> item: output) {
String key = bytesWritableToString(item._1);
String value = bytesWritableToString(item._2);
String prefix = key.substring(0, key.indexOf('_'));
Long id = Long.valueOf(key.substring(5 + prefix.length()));
if (prefix.equals(prefix1)) {
assertTrue(id >= 0 && id < primaryRows);
primaryRowKeys.add(id);
} else {
assertEquals(prefix2, prefix);
assertTrue(id >= 0 && id < separateRows);
separateRowKeys.add(id);
}
assertEquals(prefix + "_value_" + id, value);
}
assertEquals(separateRows, separateRowKeys.size());
assertEquals(primaryRows, primaryRowKeys.size());
}
/**
* Convert a BytesWritable to a string.
* Don't use {@link BytesWritable#copyBytes()}
* so as to be compatible with hadoop 1
*/
private static String bytesWritableToString(BytesWritable bw) {
int size = bw.getLength();
byte[] bytes = new byte[size];
System.arraycopy(bw.getBytes(), 0, bytes, 0, size);
return new String(bytes);
}
private static class MyHiveFunctionResultList extends HiveBaseFunctionResultList {
private static final long serialVersionUID = -1L;
// Total rows to emit during the whole iteration,
// excluding the rows emitted by the separate thread.
private long primaryRows;
// Batch of rows to emit per processNextRecord() call.
private int thresholdRows;
// Rows to be emitted with a separate thread per processNextRecord() call.
private long separateRows;
// Thread to generate the separate rows beside the normal thread.
private Thread separateRowGenerator;
// Counter for rows emitted
private long rowsEmitted;
private long separateRowsEmitted;
// Prefix for primary row keys
private String prefix1;
// Prefix for separate row keys
private String prefix2;
// A queue to notify separateRowGenerator to generate the next batch of rows.
private LinkedBlockingQueue<Boolean> queue;
MyHiveFunctionResultList(Iterator inputIterator) {
super(inputIterator);
}
void init(long rows, int threshold, int separate, String p1, String p2) {
Preconditions.checkArgument((threshold > 0 || separate == 0)
&& separate < 100 && separate >= 0 && rows > 0);
primaryRows = rows * (100 - separate) / 100;
separateRows = rows - primaryRows;
thresholdRows = threshold;
prefix1 = p1;
prefix2 = p2;
if (separateRows > 0) {
separateRowGenerator = new Thread(new Runnable() {
@Override
public void run() {
try {
long separateBatchSize = thresholdRows * separateRows / primaryRows;
while (!queue.take().booleanValue()) {
for (int i = 0; i < separateBatchSize; i++) {
collect(prefix2, separateRowsEmitted++);
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
for (; separateRowsEmitted < separateRows;) {
collect(prefix2, separateRowsEmitted++);
}
}
});
queue = new LinkedBlockingQueue<Boolean>();
separateRowGenerator.start();
}
}
public void collect(String prefix, long id) {
String k = prefix + "_key_" + id;
String v = prefix + "_value_" + id;
HiveKey key = new HiveKey(k.getBytes(), k.hashCode());
BytesWritable value = new BytesWritable(v.getBytes());
try {
collect(key, value);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void processNextRecord(Object inputRecord) throws IOException {
for (int i = 0; i < thresholdRows; i++) {
collect(prefix1, rowsEmitted++);
}
if (separateRowGenerator != null) {
queue.add(Boolean.FALSE);
}
}
@Override
protected boolean processingDone() {
return false;
}
@Override
protected void closeRecordProcessor() {
for (; rowsEmitted < primaryRows;) {
collect(prefix1, rowsEmitted++);
}
if (separateRowGenerator != null) {
queue.add(Boolean.TRUE);
try {
separateRowGenerator.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
private static long scanResultList(long rows, int threshold, int separate,
List<Tuple2<HiveKey, BytesWritable>> output, String prefix1, String prefix2) {
final long iteratorCount = threshold == 0 ? 1 : rows * (100 - separate) / 100 / threshold;
MyHiveFunctionResultList resultList = new MyHiveFunctionResultList(new Iterator() {
// Input record iterator, not used
private int i = 0;
@Override
public boolean hasNext() {
return i++ < iteratorCount;
}
@Override
public Object next() {
return Integer.valueOf(i);
}
@Override
public void remove() {
}
});
resultList.init(rows, threshold, separate, prefix1, prefix2);
long startTime = System.currentTimeMillis();
Iterator it = resultList.iterator();
while (it.hasNext()) {
Object item = it.next();
if (output != null) {
output.add((Tuple2<HiveKey, BytesWritable>)item);
}
}
long endTime = System.currentTimeMillis();
return endTime - startTime;
}
private static long[] scanResultList(long rows, int threshold, int extra) {
// 1. Simulate emitting all records in closeRecordProcessor().
long t1 = scanResultList(rows, 0, 0, null, "a", "b");
// 2. Simulate emitting records in processNextRecord() with small memory usage limit.
long t2 = scanResultList(rows, threshold, 0, null, "c", "d");
// 3. Simulate emitting records in processNextRecord() with large memory usage limit.
long t3 = scanResultList(rows, threshold * 10, 0, null, "e", "f");
// 4. Same as 2. Also emit extra records from a separate thread.
long t4 = scanResultList(rows, threshold, extra, null, "g", "h");
// 5. Same as 3. Also emit extra records from a separate thread.
long t5 = scanResultList(rows, threshold * 10, extra, null, "i", "j");
return new long[] {t1, t2, t3, t4, t5};
}
public static void main(String[] args) throws Exception {
long rows = 1000000; // total rows to generate
int threshold = 512; // # of rows to cache at most
int extra = 5; // percentile of extra rows to generate by a different thread
if (args.length > 0) {
rows = Long.parseLong(args[0]);
}
if (args.length > 1) {
threshold = Integer.parseInt(args[1]);
}
if (args.length > 2) {
extra = Integer.parseInt(args[2]);
}
// Warm up couple times
for (int i = 0; i < 2; i++) {
scanResultList(rows, threshold, extra);
}
int count = 5;
long[] t = new long[count];
// Run count times and get average
for (int i = 0; i < count; i++) {
long[] tmp = scanResultList(rows, threshold, extra);
for (int k = 0; k < count; k++) {
t[k] += tmp[k];
}
}
for (int i = 0; i < count; i++) {
t[i] /= count;
}
System.out.println(t[0] + "\t" + t[1] + "\t" + t[2]
+ "\t" + t[3] + "\t" + t[4]);
}
}
| 34.590909
| 98
| 0.641179
|
8b076b38bdf2a399d2dd68d59f67ce035741a937
| 507
|
package com.jn.agileway.ssh.client.transport.hostkey.keytype;
import com.jn.agileway.ssh.client.utils.Buffer;
public class KeyBytesHostKeyTypeExtractor implements HostKeyTypeExtractor<byte[]> {
public static final KeyBytesHostKeyTypeExtractor INSTANCE = new KeyBytesHostKeyTypeExtractor();
private KeyBytesHostKeyTypeExtractor() {
}
@Override
public String get(byte[] publicKey) {
return KeyBufferHostKeyTypeExtractor.INSTANCE.get(new Buffer.PlainBuffer(publicKey));
}
}
| 31.6875
| 99
| 0.77712
|
197612895f250ecb25e9b2da003a302bf193afe6
| 4,820
|
/*
* Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ru.taskurotta.hazelcast.queue.impl.proxy;
import com.hazelcast.config.QueueConfig;
import com.hazelcast.nio.serialization.Data;
import com.hazelcast.spi.AbstractDistributedObject;
import com.hazelcast.spi.InitializingObject;
import com.hazelcast.spi.InternalCompletableFuture;
import com.hazelcast.spi.NodeEngine;
import com.hazelcast.spi.Operation;
import com.hazelcast.spi.OperationService;
import com.hazelcast.util.ExceptionUtil;
import ru.taskurotta.hazelcast.queue.impl.QueueService;
import ru.taskurotta.hazelcast.queue.impl.operations.ClearOperation;
import ru.taskurotta.hazelcast.queue.impl.operations.IsEmptyOperation;
import ru.taskurotta.hazelcast.queue.impl.operations.OfferOperation;
import ru.taskurotta.hazelcast.queue.impl.operations.PollOperation;
import ru.taskurotta.hazelcast.queue.impl.operations.QueueOperation;
import ru.taskurotta.hazelcast.queue.impl.operations.SizeOperation;
import java.util.concurrent.Future;
abstract class QueueProxySupport extends AbstractDistributedObject<QueueService> implements InitializingObject {
final String name;
final int partitionId;
final QueueConfig config;
QueueProxySupport(final String name, final QueueService queueService, NodeEngine nodeEngine) {
super(nodeEngine, queueService);
this.name = name;
this.partitionId = nodeEngine.getPartitionService().getPartitionId(getNameAsPartitionAwareData());
this.config = nodeEngine.getConfig().findQueueConfig(name);
}
@Override
public void initialize() {
}
boolean offerInternal(Data data, long timeout) throws InterruptedException {
throwExceptionIfNull(data);
OfferOperation operation = new OfferOperation(name, timeout, data);
try {
return (Boolean) invokeAndGet(operation);
} catch (Throwable throwable) {
throw ExceptionUtil.rethrowAllowInterrupted(throwable);
}
}
public boolean isEmpty() {
IsEmptyOperation operation = new IsEmptyOperation(name);
return (Boolean) invokeAndGet(operation);
}
public int size() {
SizeOperation operation = new SizeOperation(name);
return (Integer) invokeAndGet(operation);
}
public void clear() {
ClearOperation operation = new ClearOperation(name);
invokeAndGet(operation);
}
Object pollInternal(long timeout) throws InterruptedException {
PollOperation operation = new PollOperation(name, timeout);
try {
return invokeAndGet(operation);
} catch (Throwable throwable) {
throw ExceptionUtil.rethrowAllowInterrupted(throwable);
}
}
private int getPartitionId() {
return partitionId;
}
protected void throwExceptionIfNull(Object o) {
if (o == null) {
throw new NullPointerException("Object is null");
}
}
private <T> T invokeAndGet(QueueOperation operation) {
final NodeEngine nodeEngine = getNodeEngine();
try {
Future f = invoke(operation);
return (T) nodeEngine.toObject(f.get());
} catch (Throwable throwable) {
throw ExceptionUtil.rethrow(throwable);
}
}
private InternalCompletableFuture invoke(Operation operation) {
final NodeEngine nodeEngine = getNodeEngine();
OperationService operationService = nodeEngine.getOperationService();
return operationService.invokeOnPartition(QueueService.SERVICE_NAME, operation, getPartitionId());
}
private Object invokeAndGetData(QueueOperation operation) {
final NodeEngine nodeEngine = getNodeEngine();
try {
OperationService operationService = nodeEngine.getOperationService();
Future f = operationService.invokeOnPartition(QueueService.SERVICE_NAME, operation, partitionId);
return f.get();
} catch (Throwable throwable) {
throw ExceptionUtil.rethrow(throwable);
}
}
@Override
public final String getServiceName() {
return QueueService.SERVICE_NAME;
}
@Override
public final String getName() {
return name;
}
}
| 34.927536
| 112
| 0.711411
|
36cb61cd89ce90bfca1098465429e45b92a69555
| 5,586
|
package kyle.toothless.levels;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.TimeUnit;
import com.google.cloud.firestore.DocumentReference;
import com.google.cloud.firestore.DocumentSnapshot;
import com.google.cloud.firestore.FieldValue;
import com.google.cloud.firestore.Firestore;
import kyle.toothless.Constants;
import kyle.toothless.Main;
import net.dv8tion.jda.core.EmbedBuilder;
import net.dv8tion.jda.core.events.guild.member.GuildMemberJoinEvent;
import net.dv8tion.jda.core.events.guild.member.GuildMemberLeaveEvent;
import net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.core.hooks.ListenerAdapter;
public class Level extends ListenerAdapter {
Firestore db = Main.db;
public static ArrayList<String> messageLog = new ArrayList<>();
public void onGuildMemberJoin(GuildMemberJoinEvent event) {
Map<String, Integer> data = new HashMap<String, Integer>();
data.put("messages", 0);
data.put("level", 0);
db.collection("Users").document(event.getMember().getUser().getId()).set(data);
}
public void onGuildMemberLeave(GuildMemberLeaveEvent event) {
db.collection("Users").document(event.getMember().getUser().getId()).delete();
}
// static int added = 0;
public void onGuildMessageReceived(GuildMessageReceivedEvent event) {
String[] args = event.getMessage().getContentRaw().split("\\s+");
/*
* // Fuck kyles dog if
* (event.getMessage().getContentRaw().equalsIgnoreCase("supersecretdogfucker"))
* { int total = event.getGuild().getMembers().size();
* event.getGuild().getMembers().forEach(m -> { added++; Map<String, Integer>
* data = new HashMap<String, Integer>(); data.put("messages", 0);
* data.put("level", 0);
* db.collection("Users").document(m.getUser().getId()).set(data);
* System.out.println("Added " + m.getEffectiveName() + "(" + added + "/" +
* total + ")"); }); }
*/
if (event.getMember().getUser().isBot())
return; // Avoid bots using levels
if (messageLog.contains(event.getAuthor().getId()))
return; // If in log, don't do counting code
else {
messageLog.add(event.getMember().getUser().getId());
// Increment message count
DocumentReference ref = db.collection("Users").document(event.getMember().getUser().getId());
ref.update("messages", FieldValue.increment(1));
// Check if level up is necessary
try {
DocumentSnapshot snapshot = db.collection("Users").document(event.getMember().getUser().getId()).get().get();
int messages = (int) ((long) snapshot.getData().get("messages"));
int level = (int) ((long) snapshot.getData().get("level"));
if (messages == Math.pow(2, level + 1)) {
db.collection("Users").document(event.getMember().getUser().getId()).update("level",
FieldValue.increment(1)); // Increase level
EmbedBuilder levelup = new EmbedBuilder();
levelup.setColor(0x85f96d);
levelup.setThumbnail(event.getMember().getUser().getEffectiveAvatarUrl());
levelup.setTitle(":tada: Leveled Up!");
levelup.setDescription(event.getMember().getAsMention() + " is now **Level "
+ String.valueOf(level + 1) + "**" + "\n\n**" + (int) (Math.pow(2, level + 2) - messages)
+ "** messages needed to" + "\nrankup to level **" + (level + 2) + "**");
event.getChannel().sendMessage(levelup.build()).queue((message) -> {
message.delete().queueAfter(10, TimeUnit.SECONDS);
});
}
} catch (Exception e) {
e.printStackTrace();
}
ForkJoinPool.commonPool().execute(() -> {
// Create timeout for 30 seconds
new java.util.Timer().schedule(new java.util.TimerTask() {
@Override
public void run() {
// Remove from message log after 30 sec
Level.messageLog.remove(event.getMember().getUser().getId());
}
}, 30000);
});
}
if (args[0].equalsIgnoreCase(Constants.PREFIX + "level")) {
try {
DocumentSnapshot snapshot = db.collection("Users").document(event.getMember().getUser().getId()).get().get();
int messages = (int) ((long) snapshot.getData().get("messages"));
int level = (int) ((long) snapshot.getData().get("level"));
EmbedBuilder levelstats = new EmbedBuilder();
levelstats.setColor(0x85f96d);
levelstats.setThumbnail(event.getMember().getUser().getEffectiveAvatarUrl());
levelstats.setTitle(":sparkles: Level Stats");
levelstats.setDescription(event.getMember().getAsMention() + " is **Level " + String.valueOf(level)
+ "**" + "\n\n**" + String.valueOf(messages) + "** Total Messages");
event.getChannel().sendMessage(levelstats.build()).queue();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
| 45.786885
| 125
| 0.580738
|
f06b3c0d24f708452c59eb799ea887fd507e677a
| 2,569
|
package com.raddarapp.data.general.factory;
import com.raddarapp.data.android.repository.datasource.origin.remote.api.client.CoinMiningApiClient;
import com.raddarapp.data.android.repository.datasource.origin.remote.api.config.ServerApiConfig;
import com.raddarapp.data.android.repository.datasource.origin.remote.readable.CoinMiningApiReadableDataSource;
import com.raddarapp.data.android.repository.datasource.origin.remote.writeable.CoinMiningApiWriteableDataSource;
import com.raddarapp.data.general.datasource.base.BaseDataSourceFactory;
import com.raddarapp.data.general.datasource.base.contract.preferences.MyUserProfilePreferencesDataSourceContract;
import com.raddarapp.data.general.datasource.base.contract.readable.CoinMiningReadableDataSourceContract;
import com.raddarapp.data.general.datasource.base.contract.writeable.CoinMiningWriteableDataSourceContract;
import com.raddarapp.data.general.datasource.origin.fake.readable.CoinMiningFakeReadableDataSource;
import com.raddarapp.data.general.datasource.origin.fake.writeable.CoinMiningFakeWriteableDataSource;
import javax.inject.Inject;
public class CoinMiningDataSourceFactory extends BaseDataSourceFactory {
private MyUserProfilePreferencesDataSourceContract userProfilePreferencesDataSource;
@Inject
public CoinMiningDataSourceFactory(MyUserProfilePreferencesDataSourceContract userProfilePreferencesDataSource) {
this.userProfilePreferencesDataSource = userProfilePreferencesDataSource;
}
public CoinMiningWriteableDataSourceContract createWriteableDataSource() {
if (getOrigin().equals(API_FAKE)) {
return new CoinMiningFakeWriteableDataSource(userProfilePreferencesDataSource);
} else {
ServerApiConfig serverApiConfig = ServerApiConfig.with(userProfilePreferencesDataSource.getAccessToken());
CoinMiningApiClient coinMiningApiClient = new CoinMiningApiClient(serverApiConfig);
return new CoinMiningApiWriteableDataSource(coinMiningApiClient);
}
}
public CoinMiningReadableDataSourceContract createReadableDataSource() {
if (getOrigin().equals(API_FAKE)) {
return new CoinMiningFakeReadableDataSource(userProfilePreferencesDataSource);
} else {
ServerApiConfig serverApiConfig = ServerApiConfig.with(userProfilePreferencesDataSource.getAccessToken());
CoinMiningApiClient coinMiningApiClient = new CoinMiningApiClient(serverApiConfig);
return new CoinMiningApiReadableDataSource(coinMiningApiClient);
}
}
}
| 57.088889
| 118
| 0.818217
|
6b45e7375c01997e131edc1ca5e2f04483eaeebb
| 3,479
|
package org.nybatis.core.file.handler;
import org.nybatis.core.file.FileUtil;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* 파일을 검색하는 Visitor 클래스
*
* @author nayasis
*/
public class FileFinder extends SimpleFileVisitor<Path> {
private boolean checkPattern = true;
private boolean includeDir = true;
private boolean includeFile = true;
private Set<PathMatcher> matchers = new HashSet<>();
private List<Path> result = new ArrayList<>();
/**
* 기본 생성자
*
* @param includeFile 파일 포함여부
* @param includeDir 디렉토리 포함여부
* @param pattern 이름을 검사할 패턴식
*/
public FileFinder( boolean includeFile, boolean includeDir, String... pattern ) {
this.matchers = FileUtil.toPathMacher( pattern );
this.checkPattern = ( matchers.size() != 0 );
this.includeFile = includeFile;
this.includeDir = includeDir;
// 1. *.java when given path is java , we will get true by PathMatcher.matches(path).
// 2. *.* if file contains a dot, pattern will be matched.
// 3. *.{java,txt} If file is either java or txt, path will be matched.
// 4. abc.? matches a file which start with abc and it has extension with only single character.
}
/**
* 파일명칭의 패턴을 검사한다.
*
* @param file 검사할 파일명
*/
private void find( Path file ) {
// NLogger.debug( "check file : {}", file );
if( checkPattern ) {
for( PathMatcher matcher : matchers ) {
if( matcher.matches( file ) ) {
add( file );
return;
}
}
} else {
add( file );
}
}
private void add( Path path ) {
boolean isDir = Files.isDirectory( path );
if( (includeFile && ! isDir) || (includeDir && isDir) ) {
result.add( path );
}
}
/**
* 파일 검색결과를 얻는다.
*
* @return 검색결과
*/
public List<Path> getFindResult() {
return result;
}
/*
* (non-Javadoc)
* @see java.nio.file.SimpleFileVisitor#preVisitDirectory(java.lang.Object,
* java.nio.file.attribute.BasicFileAttributes)
*/
@Override
public FileVisitResult preVisitDirectory( Path dir, BasicFileAttributes attrs ) {
// NLogger.debug( "visitDir : {}", dir );
if( includeDir ) find( dir );
return FileVisitResult.CONTINUE;
}
/*
* (non-Javadoc)
* @see java.nio.file.SimpleFileVisitor#visitFile(java.lang.Object, java.nio.file.attribute.BasicFileAttributes)
*/
@Override
public FileVisitResult visitFile( Path file, BasicFileAttributes attrs ) {
// NLogger.debug( "visitFile : {}", file );
if( includeFile ) find( file );
return FileVisitResult.CONTINUE;
}
// /*
// * (non-Javadoc)
// * @see java.nio.file.SimpleFileVisitor#visitFileFailed(java.lang.Object, java.io.IOException)
// */
// @Override
// public FileVisitResult visitFileFailed( Path file, IOException exception ) throws IOException {
// if( exception != null ) throw exception;
// return FileVisitResult.CONTINUE;
// }
}
| 28.752066
| 116
| 0.603334
|
ee9654aea6ca6c75a4b2da1962871d583670a6fe
| 1,266
|
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Odds_del {
private Integer id;
private Integer operation_id;
private Integer bet_option_id;
public Integer getOperation_id(){ return operation_id;}
public void setOperation_id(Integer operation_id){this.operation_id=operation_id;}
public Integer getId(){ return id;}
public void setId(Integer id){this.id=id;}
public Integer getBet_option_id(){ return bet_option_id;}
public void setBet_option_id(Integer bet_option_id){this.bet_option_id=bet_option_id;}
public void insert() throws SQLException {
int ac_id = 0;
DBAdapter db = new DBAdapter();
db.connect();
try(PreparedStatement s = db.conn.prepareStatement("Insert INTO Recharge(operation_id,bet_option_id)"+
"Values(?,?,?)", Statement.RETURN_GENERATED_KEYS)){
s.setInt(1,getOperation_id());
s.setInt(2,getBet_option_id());
s.executeUpdate();
try(ResultSet r = s.getGeneratedKeys()){
r.next();
ac_id = r.getInt(1);
}
}
db.disconnect();
}
}
| 34.216216
| 111
| 0.635861
|
7aa123d6a60c8be7906bb65859a8ff5a40549636
| 22,052
|
class cR {
public boolean[][] sV () {
if ( -this[ true.oGGNf()]) -!null[ zI().Kt()];else {
void[][][][] wuJGpOwaGKgI7e;
}
void WJUpL_IIiU;
;
while ( false._0()) if ( true[ j04KdmpuW[ -this[ !-In0H.KkZ1h5nC8AqrBE]]]) -this[ -!-!!false.lnKBR];
boolean[] AmQtkh;
{
while ( jo5ETzrf8i().fZL) ;
{
;
}
EmnuUEN_RfZiR[] TwmmHSjKtnZ;
if ( !9141388.x()) !!( ( !--!false[ Fin2fukL51h.cQ9IsEJjQo()]).kUfM6OnRB).ft8dek1();
boolean[] _iRo7;
void[] IBrveYUG;
-!!true.XFSPNguu();
return;
void f7;
void[][] Ck0D8T665vn;
boolean opAeb;
;
{
int[][] e5x4pE1_WsQ2;
}
boolean ApE7aOtm;
void Aa;
}
return --new YEBy()[ true.XvjI];
return !!--new p()[ --this.x];
return -5.v5gUBz7pp();
while ( !new EvR7d3122NM()[ new int[ this.Um3bAgPDJK26()].XIXX6KbuvJqgVQ()]) ;
if ( false.p2fCEUM3k2h) ;else return;
WUBw lGaYkKzmVd_;
if ( null.OLltaPV2uCbk1) if ( false.tYs3ohAvlni) ;else ;
;
f[][] x;
}
public SAYakx41jCj_ Lh;
public static void T (String[] Bjp46Ql37kVD) throws xNDK {
return;
while ( !false[ this[ ( false.xKx3DmjFRy2K)[ new boolean[ 41437769.fbTwEyVhSB4W].tA()]]]) return;
!!008435.MgAG_S9X9KaBT();
return new d4C().I5it7qUQ();
!new pxpMj3UsJzGt()[ 6973275.Y4dGF7fnhS_A()];
while ( !( -!( true.Mf93xG6z()).nujg6())[ -true[ -!!!null.CwxJ()]]) {
YgYPoFXk[][] _A0;
}
while ( true.YbWGAGEC3dwbPr()) return;
!-!!this[ false.K];
;
YBjtemSnZ gopVE0KWuDjI = false.WR = !null.RGmqy6X15YE6bq();
;
{
void[][] f9E;
;
return;
if ( !new FWw[ new kh3nGdzJ().H()].i_3eb) ;
boolean hSYp2OFzJWiAL;
if ( !( -new ytKYDMhi4()[ this.lksFDedlwiZ]).w3lQZqVV0I) -!null.HtbrGD();
if ( -119133[ -false.z1jNiA]) while ( Wmo[ --!new Fr()[ false.yQ]]) if ( true[ !L_hTwGd20()[ -!-false.pdE2r6uRYz3D()]]) true[ new Ts().H4Pqs];
boolean EamWuPhGQ;
int[] nbc5MA;
{
new void[ 518358.cJcQyjpGXSu6()].tjif6zG1NctrL();
}
if ( sk5CoG().V) new boolean[ new EAhEc0Md().NlKudj()].LGH_dfMuODBel5();
int kwEii;
;
int[][][][] pyZMANcbuy23J;
boolean[][] E9uz1FoO_kSZQ;
new int[ __Wpjp84u5T0().uVQyzNhg_4J7].aWvJB9egI4qya;
}
boolean[][] Yz = 622717412.EjedUuwzv;
int[][][] E81z4 = false.zUX = null[ false[ true.eI6GQ7_dcvoks()]];
( !236479733.xn()).ls0wZ0cqDnG0zD();
boolean[][] PEIs4X0vtdc = -967945473[ !L()[ new PpMULecPAWtlD().JLSmmHIZAa]] = -Ks.WWE1b;
while ( !-( -AA0EcCj7().A())[ new boolean[ --( 1[ null._vaZsOTgKQ()]).MynEC6O6qTvcs()].y8k()]) while ( gr8mVDM9Prba[ --TlbjAK.efbvl()]) if ( ( BzVTJhdm_s.B()).AksY_Vv) while ( !new sgY_PaXg().MUeR1eia()) !-!!!false[ jSo4hnKN1tNFD().NFBirmqu];
while ( --13316646.B) ;
}
public boolean DI8Q;
public static void yCyhLR4CUKw (String[] t) throws w {
void[][] bbWgVC;
while ( !!( false[ new _wZlr_iL8i().d58hXHEGR])[ false.HfpP]) return;
boolean[][][] tH1OGUu997k3YC = null.VDzn1a = -zITNMXZPIt61Bf.PKg;
return;
int[][][][] jyV4OIiIoXj = 42[ -this[ new glPWaLRXWe()[ true.lo()]]] = -!null.aLVojEQez();
int tx3WRH77xNqL = -false.MOp();
if ( L6MnacK_8Pi2co()[ true.q7pQfxB]) ;
if ( true[ null[ new rGAoSb()[ !null.tYHv4f()]]]) !true.jPpyHGjooZ;
boolean[][][] GHwuT = vdWcltsJheh[ new WPQgzZyLzr[ -new UBiLjAkbSiQ0O2().oaSMw3I][ new m()[ !null.YQsiwXjKHxY1P]]] = --( !null.zuc()).z1fUL7qR1Ty0mq();
boolean ehKsb = 002.zNg8GnAE_4xwD;
int[] Z;
}
public boolean[] XwtQ;
public boolean A1XTconoy933;
public static void Tham_AtTi5bmM (String[] UWprjYeu8s0P) {
boolean[] P9IJ1D = true.nGABL_BtbP = !-new int[ null[ true[ !!2.a()]]].c3Pd();
if ( false.k()) ;else -( false.Flx2bPFWAV()).aqsR9T;
void __WioVSzz;
-true[ !!67191766.gIt7LPE9vyrXMa];
( new j6vZk[ -new Y05GxML8R().H20S].ikSfXaW1vh4Lh)[ false.g90osxoU5C];
}
public void PUW7vjVPI (tVXiR7O o0f, wlZSIhMiGv[][] JeoR51OjeA) throws UWi6IAr {
-!!!EvHladFGq42()[ 023159.UOhKpXNEfRONCH];
GgSXAwz4WD_ZOR LUfhweb = _1zPBYHRiMA.X9dwmvihmBlFK2() = et2LM2E[ oKUn2ifJ3qv[ ybWCIom().yy8()]];
while ( !true.wTuyp_01acP()) -Qvue().eq7S();
boolean eW = !( ( new Sy13IYwbeY().Ccm1HRA).NvPZ()).CTJ = false.AvtVx;
return;
{
;
{
;
}
void[] NvLfikJ1Fiumc;
m8DVgD[] t;
Nr[][] FNwGScr2T5;
;
335476234[ false[ !( !false.q8iOkr0Hbv5t11)[ --Vg().gbhErpu]]];
return;
}
int[] j;
;
if ( !null.Ae6wHmj()) return;
int[][] YtBZvQsgiwo;
boolean WZ = !!4679.ncuiIgBCIFe();
void Ga3wlos81;
-( new Wv().Y4X).WWAQf6();
void[] _gMVkz;
Dx3Yho N;
void X02;
RHq_HoaN[][][] fLQje = 5109020.SJM2X9vZ0bZ1 = --!!null.y();
return -25.yDGq();
}
public static void ccOj (String[] xnHNY_mK6dz) throws qp0Q1bTL {
U6F5tp8[] RwgjQecuPIZwPa = bhrZfMP()[ !AZdFkY.uK9p9t6Rlla8()] = !!null[ !!!this.Xp1V8jIBxAFSP];
boolean FUR9aqGM = true[ ( IG__J8ZW.jFBnu7k).HFUe()] = false.xIfdVjPB6CJ;
;
int O;
boolean[] JT_;
;
if ( -!-!( -bK7xpcpTzBX()[ !AKOsQ4m225Pm7[ oumBONS.pZx_bEW()]]).VK8Gz()) CCEc3r[ !!--ZzQL5yuZgjtnM()._VR87Ntd];
void[] l_4Fg = SHUV().v80 = this[ -!this.rvWyBrDc21T()];
{
void ajM9laWQ;
while ( -972123850[ -!!!-r().I2soi]) if ( 7657243.X5()) return;
BvjhFRl3s5 Rxq0EpV;
boolean bo;
void Iv4;
boolean kFqURgYMlX;
Y tFNbhp;
if ( false.M4JpyOB1NO6F) while ( !-!new IRNkEAMY2u()[ new f9dE9DqmTFw5Ns().nchzaQt()]) if ( 64266.qB4W3V) while ( true.BxT2Z()) if ( ( ( !new XOUxXgJi()[ !false.USrzU8]).Adq43MQSOKz).O()) -new int[ ---new qC61muTLs().E0MLh5][ null.u_R0QK];
kW[][][][] a;
boolean qjRcb1Jcf;
while ( -false[ -656006.F3tOEUzuu5()]) ;
boolean[][] w2fORceD;
void[][] NGm;
return;
}
LmE3Ey07r[][][][][][] r4JxvNW1J;
!false[ this[ !false[ !583.M6wX2q()]]];
}
public static void BJp1jtWKBQYUg (String[] kxamQGXSJ) {
if ( true.cnIDBV4j6M8uZ) ;else 5559385.IhD6LUeAlRme();
guFotLdWHy[][] BxRaiY8C = !-GfXnJ6fUPfeQ3X().b();
{
int e3xZahiNX;
boolean qro9aKZVlI;
void[][][] P9;
while ( 031891550.snd4()) ;
while ( new ufZ().tuoW()) return;
void[] fkgCEGOOZG;
;
void[] jSlePGr7UdML;
if ( false[ ( -!new _Wlv2qeJ[ new jD().q()][ new int[ -null.Mcc()].GGEbOp()]).aevjrsAVgI()]) --!false.E8PweeMGRAuRT();
boolean[][][][] fElqeib;
if ( null.rn2TtvhC()) if ( !!-new int[ -new w[ 2951828.f][ !-!new void[ !!Im5YcBsCMd0Pa._JRoYdVeCU7Z].Bl6NExrH()]].BLRbG2()) if ( ( new ZuB4T8TbdSkSTN().cPr99q_vNe9y).iKo_eZtDTKLF26) ;
{
while ( ---new ZhAz_c().hribnbv4a) !---Td1VRi[ -!!false.ikq()];
}
Xmsxndt[] FeDucp4U;
{
fNqmFXvX[][][] wIj;
}
;
return;
QQKlblhYznpxO PYFzqRRGtTmJA;
}
-false.L();
;
-( ---!----!new boolean[ -false[ -!!!new r()[ r43DmfM.iU8cnkDCe]]].bon7).FZKUN1;
if ( -null[ -!pNU7t[ --new jMe62[ !blxXTQ8T[ false.triLewbK3725G]].ChdRNK()]]) if ( !true.HFjspNpMi9B) while ( -Kydcy9umtBND.MpvN2yD1r8Gi7) while ( new Qnudt().VVIQxs3agq()) new pGa()[ !bNSjSSCy()[ -mitmCD2JJLa.jbIgv]];
void[][][] EGCIQ1J7CuVxs = new W_t[ null.X3AH()].j4apSNdJ3jpFTa() = -!this.H;
heN30KgWo0XPHJ lbzK21ogIB9l;
void uhQn = ov55hzwIB_().F9HzNZ8l4PdB7();
n7tcA2eyi6_I[] k2xbiDkBF = 7.it4aR4Zw;
int a9tICPRX = !-new k1Pkq5tE().KZzHw0c() = this.Hk;
void vVYk = !null[ -( -!wvJVSBF2.k0i()).Qh] = -!!a9cFdTZB().J9nfcfbbYUC9J;
DXNhwVJJkR V = -!false.j0k() = true[ iFH[ 1464253.w9UIFc7vC()]];
}
public static void BoS5Lai1BvVE (String[] jnoSy) {
return this.u;
;
!Iy8RZ.tg7tIFQ();
tIAyHKIdZ[][] hC = this.yH42cgsl1lZWtV();
void[][][][][] Vd_ = QS3tpLaCBecG[ null.q5SBkyHXcS];
void pgG;
void[][] fz;
;
while ( -Lv[ 7.se4WoX6JZZcLf]) while ( -!-!hpgPGeByLeuif[ !uIJ_obQO().zAKyqp8qUpQM]) true[ -!56[ this.gXMlWJL7VW]];
new cfr2()[ false.SmwYbbe9vVm()];
;
void[] cq;
if ( 94431.AM4()) while ( true.G0GH) {
while ( true.LV8ut()) if ( -this.Q) ;
}
}
public void Fun () throws Y {
boolean[] eRPBGKHt;
}
}
class eDPt {
public static void oKZt2fZWvT5tx (String[] sMNUh3) throws Vj6DdFft {
xclIlp4[] Hmoj;
if ( -!!( true.y96ELOWPj())[ !-T().A3FX]) while ( new vJ[ -!!this.DJfWITWyn][ tqaIcMVqF4[ new f9nixf9gqpgQTu[ -!null[ !!true[ Uub.Of()]]].j8uIcIrCt2B]]) {
return;
}else {
new w()[ t58h[ null.Nt0bZ9njBmrUMV]];
}
;
void[][] GMXmJ54ke_oqCk = false[ -!true.SBk()] = -!-this.CP14M();
while ( true[ !this[ -zKXCOGANRA()[ !hP3ltMpAmn().Y2Sk]]]) while ( -erkmK.z) {
void[][] rPM0Tbf;
}
Ng2MjyHUY[][][] d = !93005[ -wzoslv.fjsbVsiZ0if()] = !new void[ -!mA.qTrXdJ].ovBW5k();
if ( -new Ko42cfAqh7().UW) while ( !-!-new boolean[ new KUmBRemM()[ !true.xzv9_39]].Wyx()) if ( -new UQiXdR()[ c[ --UpssTXBJC8Qyn.u]]) return;else {
boolean ppYccx;
}
boolean[] LIAIhDc = !( !true.KK96FL5q16L2()).Tv5r;
{
void[][][][] w_rc;
mLMB2Na nL1s;
}
NM Azn;
;
{
void i0s;
!-!false[ --false.uUwMa_4];
void[] NR;
;
;
WL7nNAX m9ruv8soSafg;
void[][] qkL;
int taY;
int[] RoHQXsm2RK;
int CyERYPg6gNL5;
int k9A88qi;
int[][] uphxbpj33CHZ;
if ( this[ new vU2A9k3F697H[ -!this[ false.VFuvjhFK9Jrk]].xPk]) if ( SfjQ6nAzJyd.QB) ;
}
while ( !!false.ypyoY) {
if ( -new int[ new void[ -!new boolean[ !-!( !true.DPdrb).Yts4TaxUBdQw].SOy_e_Gd_kwV6()].ZJUV2YU()].EQyJqZNs3_Fw) {
boolean[][] y2EhTb7RqRFPH3;
}
}
int[][][] XhfU3KS9N1Y2L;
false[ !-!this.c];
boolean[][] BSQQ = !!new cbj08().e_VgWm0cD0KLID();
{
while ( 46[ 0[ !-( 37.LNMoF).Sz()]]) ;
{
Pw4xL[][] HqbmVkKs;
}
void QVG;
void[][][][] PB;
while ( !null.XGxLzz0_kqx()) if ( new NNCxMOMl()[ wViqq2323RS().BzmdelswLDW()]) while ( ( NM[ 748._mMAl9VX5ptd()]).cC) {
chcYStwaL[] kZq;
}
{
v6jO0 YbCFxyv9;
}
tCz4y8VX2G[][] JRu0jafmU;
int[] j86Bl8zec6jcek;
{
if ( !-FvNfjPNg.TPKJ_OQk()) if ( M7e.AKAuoRXRHQtueV()) while ( -null[ !-!_9KihfCxnIt75()[ !true.nKAaiU]]) new boolean[ false.v4Od_NHxaA].Mv00fqQ;
}
boolean[] eXDQ_yW;
}
}
public void Mf_9EmTxYM;
public void[] ZWwDLo98p_S () {
return;
int[][] x5IGm6Hkx4Z2 = !!--13104.yhB3Os4SYghW8;
{
boolean[] RpZy32RYqZiSy8;
return;
while ( false.pxBs6luVjZFjDL) {
void[] OgJcOE7;
}
!!8930902.hOSp;
}
Td8L4aa3XEk Icu = !-null.zCs_vOXTHw();
boolean ai652BylcCYV;
return esc[ --!-( false.Rsi9QIYF9XN())[ new boolean[ true.qx].Bm()]];
if ( WzhPQ3y9PxNQ[ -!!new int[ new int[ !true[ --!!new bLl14()[ yijVQM[ new boolean[ !( -this[ JavJ.Bt2VbRjQebjjX]).wFCxcZ][ !!!-VSKdckqecERTy()[ new mrGjFQ().I2VItr]]]]]][ --!KFmOTSC()[ !GA_dzHAyVDT0.xk_JP8mioMf()]]].khq1hu()]) false.cKEU();
u96pldjkzyEU Zc_soke = LgWThtqgAShW.qPg7Z1A();
while ( -( new HO0vL().ck86PUz6OdHQOI).h1DkBSxlhyVhJ()) nSm59WvBMa.o_8();
while ( -true.X) while ( ---!this[ !---!!new int[ !Y.Nyh][ nDlZ().G2qfvX]]) ;
boolean[][] z1 = null.ttcF;
boolean bBTG = nRZ().r5u4G3eP() = m_jb[ true[ -!!xz_()[ ( null[ !-!new rEq3rl[ this.CfNeHCCaCiv()].tEo9RgLQfoi])[ !-false._MzM8_ThjypG35()]]]];
void[][] B = new zUtI().th3jnXY6DL = new HhFmIAdPdqD().n();
int HSGXQN = -!!!HaFby1[ 820.HWA2LYzF()];
void[] NsB9JabDfsLlp3;
}
public static void QhP7Ju5 (String[] e9LkmmZ) throws c0TJ {
void[][] OAQpxw;
if ( !---true.UbJCNQxtCVPjZb) if ( -this[ new SQ_7lRH_().dWBvtkElEz()]) while ( false.rkn) while ( -R()[ this.HmOsSiHV0yHI]) if ( -!new sOwxGhICwn().smTY2p0mECh()) return;
void cCjTP7 = -!this.qTpzEkZGw6();
boolean[][] gBmO_HwTxY = --!( -null.h).leB;
if ( 257074.P0lQ6Hz1HbT()) if ( !vGZMCbJBRtlHfs.Np0) this.j3VGZhofT();
int[][] Pfzcse2nr = true[ !-false[ -lSC18Umt859Ob2().i5JFWbR5e8X9x]] = !( --!true.ZU76e8U8()).IUGam;
while ( -null[ true.g()]) ;
true.gGjO4Jm;
!!!!true.FH1vObLWyuYNx;
void cKD_dykTR11 = -!!!-!new cgA6().TzUW4GKvRqGv = !!!new GlX()[ false.VaxNHo()];
int[] PlIGny = !true.ow_ExR() = !new Jwxq_vD().dO;
if ( HjbI().U()) ;
while ( CjoER.orXk26fQU8) while ( -!new Q()[ true[ !( !true.XeB7L()).bFPaK8oq7A2Ai]]) ;
q[] S8lIH37;
}
public int f3bDyhjDz (fS[][][] kP1UKyFNGWu, void yH8Col0dERSuq, boolean wdq) {
int[][][] XR7wfx;
while ( JXXUNZfEDX[ x8b9reEoOn.s()]) return;
void[] wuUZ = !---new iK4NGyHaHQRv().hf0Zh = !true.DaskB8IGKYdiah();
{
while ( !-!( this[ null.qa5()]).cEQU3icT()) while ( -aC[ !null[ this.lPJ7wChUU8e()]]) ;
AlmTa82[][] mVdfv0K;
bw5NCqlS_y[] om0FrG5Ot;
void[][][][] qS05fC;
return;
boolean U;
if ( true.EaGtV) ;
if ( !false.k()) {
return;
}
if ( !null.Jod8b07()) while ( -!this.O_Xsd8NZ) return;
int[] hcjTEs44;
return;
void[] d4;
r25cnDQkhCly16[] ldt9IV4OVff;
}
{
MR6H6bNSL yzohQ;
while ( -KX9SYPhLAVS().QT9NERnU()) {
int[][] eIFTDVVg;
}
boolean kZcs8N1pdrZH;
boolean nW1;
boolean[][][] yhCuNQ;
void[][] v7G;
void[][] AlyOKPX;
pRxQrqvbaUOM jr2YylbfS6x;
-!alJC().Utrjq;
int wsJn1BebKw0;
;
void ATi3MQKIyxcPkS;
void ciqcLZTN1LN6z;
{
CZUS6_JQXoWR akgB7dx_;
}
}
{
int fLyPl;
while ( Q[ new CR7rpRV()[ c.Rth1lB8Y0]]) if ( --( !false[ ( this.ccjDu0j())[ !this.L11XLddoqds]]).iN8) {
boolean kOZ4cHulqWJD;
}
int _f4nP1PZ;
;
boolean[][][] M;
void J9stdqJfBAc;
void[] GN;
;
void[][][][][][] XIepbQhlP;
!!9488.Q6cR2eB7();
return;
boolean[][][][][] Yzp;
null.Ly3EQnVEwVsIH;
while ( !-new DV4pIY53Xp()[ -tORFNg_OC1FIc.KlaVFT]) {
return;
}
while ( this.uiW6gFmN) return;
return;
void CvVWDzfdC8IrK;
{
int[][] HDnkp;
}
}
{
int sOoz;
int _;
int yUcH58;
void[][][] kqFVYqp0;
boolean[] _uahfaANdYSG;
!9284.xh27P();
U3u[ !g8rLmtQyq2ZB()[ null[ -viwH()[ !!61[ !!!!oThReFaPGw9.M5ASmv]]]]];
while ( ( !-( true.U6RwRREg).xYz02()).o()) return;
void yQhkn8DR4z;
deWgJ0Z_Cl[] y4GEb7qO;
{
void t1hQe0VqzKc1;
}
boolean U0;
Ktt1YRoyNkcFx u;
return;
int STvV;
{
myK0VeXDLFy4q5[] MBXsU3fW;
}
;
;
int Xub3dw;
while ( true[ --null[ -!-null.F()]]) while ( 10577274[ true.rH9Qwm0]) return;
}
;
boolean[] HnwuYsHoXc7v;
boolean xy6qIbn_ = !UhCLwd3Wf9I().lC6coRsRoTWT() = 994[ ---new Dm().LgOLn7tI()];
int Q9sjHHLl7gV = !false.P0MO6M4EEF;
eIj6t0l2[] JrhvEb2Ce = this.MzQD1U_65 = oZFKHNfvI5e9.aeyZCq7ExkZ9;
;
;
boolean aDJmLQBX6Uxc = -null.Lwk9() = -null.Awvroqv;
}
public static void uR (String[] mT3aO7_ypC24Ue) throws R3RKJ4ZnWui {
int[][][][] EmvYOuoVi_1zD;
VvTNP9op[] GO5;
;
boolean l3 = true.w2uDegtbysGMeo;
void XN7i9W;
boolean V8pcOjQQ;
if ( null[ _XR.aVp1Wxar()]) !-12.XgQXX3U_;else ;
_E0ij[][] Gs4QSFL7E0U = -this.e0CrFr();
if ( new void[ -r1TF().fFXwYoVIvd5QCK()].d29FzKJ9()) !new fjuBWUUTh8().Fm1fL();
while ( -null[ -979273[ this.kNWxl()]]) return;
{
int aXQ;
while ( ( -true.kGWMZR).HxXU9hHRsjf81) -!!( this[ ( -50321.EF7R)[ !-!-!-hYa81F3HdMd2().hhHu6()]]).BCWO_2XRmdXH;
!new I_Lxu[ this.hVpcL][ -!!-this.Gbrdvp_ZWx()];
void VTO;
int LR5jDaOgR6W;
int NCqR1h7GC;
boolean[] YULtAxprKaL;
boolean EPmWI;
;
}
if ( ( -!-EVr7XO.Iwiu2U1zx8).RTdgM6ERQo71()) {
void j6fMGRvouMC;
}
}
public static void q19saBR7 (String[] ttX2WLRHx) throws LizR6Mb5wl8W {
;
return ( true.ygpCuO_7Ha)._el9Ebve;
return !new void[ !null.zYkeysP15KvV()].FQtpuuuh2;
if ( null.ft86()) if ( new int[ false.fSkj02_fzZ()][ -!new rWRtL2Jdao().Xirmiw]) return;else !this.btU4rag1OmJ;
}
}
class JYbRn {
public static void cr (String[] liF_NR) {
gJ[ new D8638iBOTbtf5().RuAErm3];
while ( --e6jq5h6_MD9K7().VugaynuC()) ( false[ -!null.K()]).gX6dgz();
;
!new LZaA01C()[ --true.Mwq8VrieLP()];
TwfwQIm T6KWjzDCRQfpz;
{
boolean VXksOQBKCFHG;
void[] j5mLdo;
;
void NM5GN4;
int qtwe;
mcu[] DBqo;
YasOYJsUxHgr2m[][] bkR32JAvmyR_j;
if ( --!true.hS) while ( -P7WVMMD.KTr1HIq) !!56068.JE4clir0UW9Mxk();
while ( new int[ new szXAoT().h7Ooyyrvy].E2wjvpEHM0uj92) rvOR()[ -new void[ false.oErhq71JN()].gT];
int[][] ue;
while ( !-wpM.kDJEnF()) ;
}
void s;
int[] LPNJ2KpaGqDc;
int[] o3RFmXV = ( -TusW1PSecP.H0d).ly8YNb5f2;
if ( !-R_qvJcJDry.YDhmEqX()) ;
;
Pf8CpvV().CWtQpKKO();
{
void[] BmpSbpNPXF;
;
while ( --true[ this.jzRGPl2s7sR]) {
LEDHV[] bf6Id;
}
boolean[][][] pkyF5hdYk;
X0CU xXI6xw;
void r;
;
boolean K8vVA76VrNF;
;
int mHl;
boolean[][] twfxcfaX;
while ( this[ !dZ().BjSEKI7LYBfz5()]) {
-true.OelCYqpNhIbv();
}
boolean[] Lv8OL0grzXoHA;
return;
void bcQa4Hq;
new boolean[ -!-0954.aFTi4HWn75].aJUL();
int UHvNC_kHfwN0T;
;
}
while ( ( -false.wyMC)[ new qyc44()[ !!true[ !( false[ !fVh6q1[ !!true.Onvpsbdw()]]).k()]]]) if ( -JpIJ7_r.ID_PfSQ04Qy2()) {
{
t1rpTVXW NbBukYa7o2qgeM;
}
}
}
public static void dmIuaB (String[] JcNsabJA) {
return -new Vlwu().cOA_PWTsypU;
return;
boolean f1ay8fPiZ5l;
{
Hkga5sw5qnZ[][] rj8ydC;
boolean zQpSlXZ0vf;
while ( -!!ZYr9HmXYQ().pVQ2YwAW0OMK) if ( null.YCXzr()) if ( 9102[ !!false.VTvC9m4]) return;
while ( F2b().NgNLO) if ( !!new N().SAHLj2BL) if ( -true.XbISzUX8sM5t2()) {
xdu3ianZ CI9nDmaCN1Q_OZ;
}
!---89.Pt3970r4bJDd;
---3758.o2k_Cwqjsi();
{
int[][] Uwv6i3cwjvR7B;
}
void monKgk;
}
{
;
Qkfs7wIuXh XhOWyEQh;
wD94jYBXmY7VZ[][] oRfRerGktln;
int KKEiX4zW;
;
void[] T;
{
int[] W;
}
return;
return;
boolean[] o;
while ( 02913928[ !819[ 522.FxuW]]) return;
while ( ( -!null[ this[ true.ah2Wn()]]).sf()) {
J2()[ -this.s64];
}
}
dmOrmSo_s JqsEh = -!false.jeCrjNyt1;
int[][][][] EecOa4;
k8o313 k03t6ir7yIQ4OX = LCOAGsIGX.zHXeEF20ln() = qsNvweNL2236qF().rMKRsu2P;
return;
return;
while ( !this.kodAPP46pcJooB) while ( -this.UYSG()) return;
TPEuEJnA255D[][] rp6IEPU;
int[] NPXngPKCtBi;
void[][][] q4KWwsq10UoTPk;
int[] q2HDB1pKh;
kKLic9fKuB8BIE Nka9ZtVkgbgLI = sd().GK = !null.cZW8u19RM5gku;
}
public void Mg2jo9MysXPNLC;
}
| 38.284722
| 252
| 0.487756
|
b38ec50c7ed49d9c3c5fbd77d7e726ed912d0553
| 4,156
|
package com.example.application.backend.service.impl;
import com.example.application.backend.service.PartsSearchService;
import com.example.application.model.AbstractPcPart;
import com.example.application.model.Connector;
import com.example.application.model.CoolingSystem;
import com.example.application.model.GraphicsCard;
import com.example.application.model.Memory;
import com.example.application.model.MemoryConfiguration;
import com.example.application.model.Price;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
public class PartsSearchServiceImpl implements PartsSearchService {
@Override
public List<AbstractPcPart> search() {
List<AbstractPcPart> pcParts = new ArrayList<>();
Price normalPrice = new Price();
normalPrice.setPrice(20);
normalPrice.setCurrency("CHF");
MemoryConfiguration smallConfiguration = new MemoryConfiguration();
smallConfiguration.setMemoryPerModule(4);
smallConfiguration.setNumberOfModules(2);
Memory standardRamPack = new Memory();
standardRamPack.setName("Standard RAM Pack");
standardRamPack.setPrice(normalPrice);
standardRamPack.setStockQuantity(20);
standardRamPack.setFrequency(2400);
standardRamPack.setConfiguration(smallConfiguration);
standardRamPack.setFormFactor("DDR3 SO-DIMM");
Price expensivePrice = new Price();
expensivePrice.setPrice(400);
expensivePrice.setCurrency("CHF");
CoolingSystem brokenCoolingSystem = new CoolingSystem();
brokenCoolingSystem.setName("Cooler Master");
brokenCoolingSystem.setRpm(30);
List<Connector> connections = new ArrayList<>();
connections.add(new Connector("HDMI", 4));
connections.add(new Connector("DVI", 2));
connections.add(new Connector("Display Port", 3));
connections.add(new Connector("VGA", 1));
GraphicsCard standardGraphicsCard = new GraphicsCard();
standardGraphicsCard.setName("Standard Graphics Card");
standardGraphicsCard.setPrice(normalPrice);
standardGraphicsCard.setStockQuantity(2);
standardGraphicsCard.setCoolingSystem(brokenCoolingSystem);
standardGraphicsCard.setCardModel("GTX 1050 Ti");
standardGraphicsCard.setConnections(connections);
standardGraphicsCard.setPciExpressVersion(4);
MemoryConfiguration bigConfiguration = new MemoryConfiguration();
bigConfiguration.setMemoryPerModule(16);
bigConfiguration.setNumberOfModules(4);
Memory qualityRamPack = new Memory();
qualityRamPack.setName("Quality RAM Pack");
qualityRamPack.setPrice(expensivePrice);
qualityRamPack.setStockQuantity(3);
qualityRamPack.setFrequency(3600);
qualityRamPack.setConfiguration(bigConfiguration);
qualityRamPack.setFormFactor("DDR4 DIMM");
pcParts.add(standardRamPack);
pcParts.add(standardGraphicsCard);
pcParts.add(qualityRamPack);
return pcParts;
}
@Override
public List<Memory> onlyMemory() {
List<Memory> pcParts = new ArrayList<>();
Price normalPrice = new Price();
normalPrice.setPrice(20);
normalPrice.setCurrency("CHF");
MemoryConfiguration smallConfiguration = new MemoryConfiguration();
smallConfiguration.setMemoryPerModule(4);
smallConfiguration.setNumberOfModules(2);
Memory standardRamPack = new Memory();
standardRamPack.setName("Standard RAM Pack");
standardRamPack.setPrice(normalPrice);
standardRamPack.setStockQuantity(20);
standardRamPack.setFrequency(2400);
standardRamPack.setConfiguration(smallConfiguration);
standardRamPack.setFormFactor("DDR3 SO-DIMM");
Price expensivePrice = new Price();
expensivePrice.setPrice(400);
expensivePrice.setCurrency("CHF");
MemoryConfiguration bigConfiguration = new MemoryConfiguration();
bigConfiguration.setMemoryPerModule(16);
bigConfiguration.setNumberOfModules(4);
Memory qualityRamPack = new Memory();
qualityRamPack.setName("Quality RAM Pack");
qualityRamPack.setPrice(expensivePrice);
qualityRamPack.setStockQuantity(3);
qualityRamPack.setFrequency(3600);
qualityRamPack.setConfiguration(bigConfiguration);
qualityRamPack.setFormFactor("DDR4 DIMM");
pcParts.add(standardRamPack);
pcParts.add(qualityRamPack);
return pcParts;
}
}
| 33.788618
| 69
| 0.796679
|
7ce18affed22552eb0487258c91971367595d8c6
| 216
|
package pattern05_builder;
public interface HouseBuilder {
// 修建地板
public void makeFloor();
// 修建墙壁
public void makeWall();
// 修建房顶
public void makeHouseTop();
public House getHouse();
}
| 18
| 31
| 0.652778
|
646918719abb83c3a6853d377027806c3a2ef495
| 4,843
|
package org.httpkit.server;
import clojure.lang.IFn;
import clojure.lang.IPersistentMap;
import clojure.lang.ISeq;
public class MockClojureHandler implements IFn{
private final IPersistentMap dummyResponse;
public MockClojureHandler(IPersistentMap dummyResponse){
this.dummyResponse = dummyResponse;
}
@Override
public Object invoke() {
return null;
}
@Override
public Object invoke(Object o) {
return dummyResponse;
}
@Override
public Object invoke(Object o, Object o1) {
return dummyResponse;
}
@Override
public Object invoke(Object o, Object o1, Object o2) {
return dummyResponse;
}
@Override
public Object invoke(Object o, Object o1, Object o2, Object o3) {
return dummyResponse;
}
@Override
public Object invoke(Object o, Object o1, Object o2, Object o3, Object o4) {
return dummyResponse;
}
@Override
public Object invoke(Object o, Object o1, Object o2, Object o3, Object o4, Object o5) {
return dummyResponse;
}
@Override
public Object invoke(Object o, Object o1, Object o2, Object o3, Object o4, Object o5, Object o6) {
return dummyResponse;
}
@Override
public Object invoke(Object o, Object o1, Object o2, Object o3, Object o4, Object o5, Object o6, Object o7) {
return dummyResponse;
}
@Override
public Object invoke(Object o, Object o1, Object o2, Object o3, Object o4, Object o5, Object o6, Object o7, Object o8) {
return dummyResponse;
}
@Override
public Object invoke(Object o, Object o1, Object o2, Object o3, Object o4, Object o5, Object o6, Object o7, Object o8, Object o9) {
return dummyResponse;
}
@Override
public Object invoke(Object o, Object o1, Object o2, Object o3, Object o4, Object o5, Object o6, Object o7, Object o8, Object o9, Object o10) {
return dummyResponse;
}
@Override
public Object invoke(Object o, Object o1, Object o2, Object o3, Object o4, Object o5, Object o6, Object o7, Object o8, Object o9, Object o10, Object o11) {
return dummyResponse;
}
@Override
public Object invoke(Object o, Object o1, Object o2, Object o3, Object o4, Object o5, Object o6, Object o7, Object o8, Object o9, Object o10, Object o11, Object o12) {
return dummyResponse;
}
@Override
public Object invoke(Object o, Object o1, Object o2, Object o3, Object o4, Object o5, Object o6, Object o7, Object o8, Object o9, Object o10, Object o11, Object o12, Object o13) {
return dummyResponse;
}
@Override
public Object invoke(Object o, Object o1, Object o2, Object o3, Object o4, Object o5, Object o6, Object o7, Object o8, Object o9, Object o10, Object o11, Object o12, Object o13, Object o14) {
return dummyResponse;
}
@Override
public Object invoke(Object o, Object o1, Object o2, Object o3, Object o4, Object o5, Object o6, Object o7, Object o8, Object o9, Object o10, Object o11, Object o12, Object o13, Object o14, Object o15) {
return dummyResponse;
}
@Override
public Object invoke(Object o, Object o1, Object o2, Object o3, Object o4, Object o5, Object o6, Object o7, Object o8, Object o9, Object o10, Object o11, Object o12, Object o13, Object o14, Object o15, Object o16) {
return dummyResponse;
}
@Override
public Object invoke(Object o, Object o1, Object o2, Object o3, Object o4, Object o5, Object o6, Object o7, Object o8, Object o9, Object o10, Object o11, Object o12, Object o13, Object o14, Object o15, Object o16, Object o17) {
return dummyResponse;
}
@Override
public Object invoke(Object o, Object o1, Object o2, Object o3, Object o4, Object o5, Object o6, Object o7, Object o8, Object o9, Object o10, Object o11, Object o12, Object o13, Object o14, Object o15, Object o16, Object o17, Object o18) {
return dummyResponse;
}
@Override
public Object invoke(Object o, Object o1, Object o2, Object o3, Object o4, Object o5, Object o6, Object o7, Object o8, Object o9, Object o10, Object o11, Object o12, Object o13, Object o14, Object o15, Object o16, Object o17, Object o18, Object o19) {
return dummyResponse;
}
@Override
public Object invoke(Object o, Object o1, Object o2, Object o3, Object o4, Object o5, Object o6, Object o7, Object o8, Object o9, Object o10, Object o11, Object o12, Object o13, Object o14, Object o15, Object o16, Object o17, Object o18, Object o19, Object... objects) {
return dummyResponse;
}
@Override
public Object applyTo(ISeq iSeq) {
return iSeq;
}
@Override
public void run() {
}
@Override
public Object call() throws Exception {
return null;
}
}
| 34.592857
| 274
| 0.671072
|
14f7426c5f8e1c1ca56d5eed3473271db3fa6d3a
| 2,766
|
package de.fhl.overchef.test;
import static org.junit.Assert.*;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import org.junit.Before;
import org.junit.Test;
import de.fhl.overchef.db.DBConnector;
import de.fhl.overchef.db.DBOperation;
import de.fhl.overchef.model.Cookbook;
import de.fhl.overchef.model.Recipe;
import de.fhl.overchef.view.OverchefMainApp;
public class DBConnectorTest {
private static DBConnector dbConnection;
@Before
public void setUp() throws Exception {
dbConnection = new DBConnector();
}
@Test
public void testConnect() throws SQLException {
DBConnector.connect();
assertFalse(dbConnection.connection.isClosed());
}
@Test
public void testDisconnect() throws SQLException {
DBConnector.connect();
DBConnector.disconnect();
assertTrue(dbConnection.connection.isClosed());
}
@Test
public void testSelectAllRecipe() throws SQLException, InstantiationException, IllegalAccessException, FileNotFoundException, IOException{
DBConnector.connect();
ResultSet rs=DBOperation.selectAllRecipe();
int count=0;
while(rs.next()){
count++;
}
Cookbook ck = new Cookbook();
ck.setRecipeList(ck.loadRecipesFromDB(DBOperation.selectAllRecipe()));
OverchefMainApp.setRecipeData(ck.getRecipeList());
System.out.println(OverchefMainApp.getRecipeData().size());
assertEquals(count,OverchefMainApp.getRecipeData().size());
DBConnector.disconnect();
}
@Test
public void testExecuteSelectSQL() throws SQLException {
DBConnector.connect();
ResultSet rs=DBConnector.executeSelectSQL("select * from RECIPE");
String judgement="empty";
while(rs.next()){
judgement="data";
}
assertTrue(judgement=="data");
DBConnector.disconnect();
}
@Test
public void testExecuteNonSelectSQL() throws SQLException {
DBConnector.connect();
ResultSet rs=DBOperation.selectAllRecipe();
int lastCount=0;
int currentCount=0;
while(rs.next()){
lastCount++;
}
Recipe r=new Recipe("test", 4, 20, 30);
DBOperation.deleteRecipe(r.getRecipeID());
int rid = DBOperation.getMaxRid() + 1;
r.setRecipeID(rid);
DBConnector.executeNonSelectSQL("INSERT INTO RECIPE (rid,recipeName, servings, preparationTime, cookingTime, recipeDesc) VALUES(" +rid+","+ "'"+r.getRecipeName()+"'"+","+r.getIntServeNum()+","+r.getPreparationTime()+","+r.getCookTime()+","+"'"+r.getDescription()+"'"+")");
rs=DBOperation.selectAllRecipe();
while(rs.next()){
currentCount++;
}
assertTrue(lastCount+1==currentCount);
DBOperation.deleteRecipe(rid);
DBConnector.disconnect();
}
}
| 27.939394
| 275
| 0.714027
|
39b90c93d32a3c2479d8c33f747635030b62dfc5
| 821
|
package io.crnk.core.mock.models;
import io.crnk.core.resource.annotations.JsonApiField;
import io.crnk.core.resource.annotations.JsonApiId;
import io.crnk.core.resource.annotations.JsonApiResource;
import io.crnk.core.resource.annotations.PatchStrategy;
@JsonApiResource(type = "projects-patch-strategy")
public class ProjectPatchStrategy {
@JsonApiId
private Long id;
private String name;
@JsonApiField(patchStrategy = PatchStrategy.SET)
private ProjectData data;
public Long getId() {
return id;
}
public ProjectPatchStrategy setId(Long id) {
this.id = id;
return this;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ProjectData getData() {
return data;
}
public void setData(ProjectData data) {
this.data = data;
}
}
| 18.659091
| 57
| 0.74665
|
e626ab69ee05f760bc03ed339173de816ac2592d
| 724
|
/* This file was generated by SableCC (http://www.sablecc.org/). */
package dssl.node;
import dssl.analysis.*;
@SuppressWarnings("nls")
public final class TExch extends Token
{
public TExch()
{
super.setText("exch");
}
public TExch(int line, int pos)
{
super.setText("exch");
setLine(line);
setPos(pos);
}
@Override
public Object clone()
{
return new TExch(getLine(), getPos());
}
@Override
public void apply(Switch sw)
{
((Analysis) sw).caseTExch(this);
}
@Override
public void setText(@SuppressWarnings("unused") String text)
{
throw new RuntimeException("Cannot change TExch text.");
}
}
| 18.1
| 67
| 0.588398
|
5153ec4baa639c0d96f8fa8cbbcbe31891f0a7d4
| 1,849
|
package me.opkarol.oppets.collections.map;
/*
* Copyright (c) 2021-2022.
* [OpPets] ThisKarolGajda
* 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.
*/
/*
= Copyright (c) 2021-2022.
= [OpPets] ThisKarolGajda
= Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
= http://www.apache.org/licenses/LICENSE-2.0
= Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
import java.util.*;
import java.util.stream.Stream;
public interface IMap<K, V> {
void remove(K k);
void remove(K k, V v);
void put(K k, V v);
void set(K k, V v);
void setMap(HashMap<K, V> map);
boolean containsKey(K k);
boolean containsValue(V v);
Map<K, V> getMap();
Optional<V> getByKey(K k);
Collection<V> getValues();
default Stream<V> getValuesStream() {
return getValues().stream();
}
V getOrDefault(K key, V defaultValue);
V replace(K key, V value);
Set<K> keySet();
boolean isEmpty();
Optional<K> getFromIndex(int index);
}
| 32.438596
| 308
| 0.712818
|
aefefecfd2cd78f825b9efb6ff9c4d149f3df114
| 857
|
package com.petehouston.jsoup;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.IOException;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.jsoup.parser.Parser;
/**
* Section07
* List all URLs within a HTML document
*
*/
public class App
{
public static final String CLS_NAME = "App";
public static final String URL_SOURCE = "http://jsoup.org";
public static void main(String[] args) throws IOException
{
// load Document
Document doc = Jsoup.connect(URL_SOURCE).get();
// select only <a> tag with "href" attribute
Elements links = doc.select("a[href]");
System.out.println("Total results: " + links.size());
for(Element url: links) {
System.out.println(String.format("* [%s] : %s ", url.text(), url.attr("abs:href")));
}
}
}
| 25.205882
| 88
| 0.660443
|
335174976d2782c6870418544f9d6c610ce826dd
| 1,514
|
package org.uberfire.properties.editor.client.widgets;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Widget;
public class PropertyEditorComboBox extends AbstractPropertyEditorWidget {
@UiField
ListBox listBox;
public PropertyEditorComboBox() {
initWidget( uiBinder.createAndBindUi( this ) );
}
public void addItem( String value ) {
listBox.addItem( value );
}
public void setSelectedIndex( int selected ) {
listBox.setSelectedIndex( selected );
}
public int getSelectedIndex() {
return listBox.getSelectedIndex();
}
public void setSelectItemByText( String text ) {
for ( int i = 0; i < listBox.getItemCount(); i++ ) {
String candidate = listBox.getItemText( i );
if ( candidate.equalsIgnoreCase( text ) ) {
setSelectedIndex( i );
}
}
}
public String getItemText( int selectedIndex ) {
return listBox.getItemText( selectedIndex );
}
public void addChangeHandler( ChangeHandler changeHandler ) {
listBox.addChangeHandler( changeHandler );
}
interface MyUiBinder extends UiBinder<Widget, PropertyEditorComboBox> {
}
private static MyUiBinder uiBinder = GWT.create( MyUiBinder.class );
}
| 28.037037
| 75
| 0.679657
|
1427e3330f6c78337f6564d47884533c676ac157
| 7,119
|
package sorald;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThan;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.sonar.java.checks.ArrayHashCodeAndToStringCheck;
import sorald.processor.ArrayHashCodeAndToStringProcessor;
import sorald.processor.ProcessorTestHelper;
import sorald.processor.SoraldAbstractProcessor;
import sorald.segment.Node;
import sorald.sonar.Checks;
import sorald.sonar.ProjectScanner;
import sorald.sonar.RuleVerifier;
import sorald.sonar.RuleViolation;
import spoon.reflect.CtModel;
import spoon.reflect.declaration.CtType;
public class SegmentStrategyTest {
@Test
public void arrayToStringProcessor_success_Test() throws Exception {
String fileName = "ArrayHashCodeAndToString.java";
String pathToBuggyFile = Constants.PATH_TO_RESOURCES_FOLDER + fileName;
String pathToRepairedFile =
Constants.SORALD_WORKSPACE + "/SEGMENT/" + Constants.SPOONED + "/" + fileName;
RuleVerifier.verifyHasIssue(pathToBuggyFile, new ArrayHashCodeAndToStringCheck());
Main.main(
new String[] {
Constants.REPAIR_COMMAND_NAME,
Constants.ARG_REPAIR_STRATEGY,
"SEGMENT",
// FIXME MAX_FILES_PER_SEGMENT is set to 1 as a temporary fix to
// https://github.com/SpoonLabs/sorald/issues/154
Constants.ARG_MAX_FILES_PER_SEGMENT,
"1",
Constants.ARG_ORIGINAL_FILES_PATH,
Constants.PATH_TO_RESOURCES_FOLDER,
Constants.ARG_RULE_KEYS,
"2116",
Constants.ARG_PRETTY_PRINTING_STRATEGY,
PrettyPrintingStrategy.NORMAL.name(),
Constants.ARG_WORKSPACE,
Constants.SORALD_WORKSPACE + "/SEGMENT/"
});
TestHelper.removeComplianceComments(pathToRepairedFile);
RuleVerifier.verifyNoIssue(pathToRepairedFile, new ArrayHashCodeAndToStringCheck());
}
@Test
public void arrayToStringProcessor_fail_Test() throws Exception {
String fileName = "ArrayHashCodeAndToString.java";
String pathToBuggyFile = Constants.PATH_TO_RESOURCES_FOLDER + fileName;
RuleVerifier.verifyHasIssue(pathToBuggyFile, new ArrayHashCodeAndToStringCheck());
String[] args =
new String[] {
Constants.REPAIR_COMMAND_NAME,
Constants.ARG_REPAIR_STRATEGY,
"SEGMENT",
Constants.ARG_MAX_FILES_PER_SEGMENT,
"0",
Constants.ARG_ORIGINAL_FILES_PATH,
Constants.PATH_TO_RESOURCES_FOLDER,
Constants.ARG_RULE_KEYS,
"2116",
Constants.ARG_PRETTY_PRINTING_STRATEGY,
PrettyPrintingStrategy.NORMAL.name(),
Constants.ARG_WORKSPACE,
Constants.SORALD_WORKSPACE + "/SEGMENT/"
};
assertThrows(SystemExitHandler.NonZeroExit.class, () -> Main.main(args));
}
@Test
public void segmentStrategy_doesNotFail_onCrashInParsingSegment(@TempDir File tempDir)
throws IOException {
// arrange
org.apache.commons.io.FileUtils.copyDirectory(
new File(Constants.PATH_TO_RESOURCES_FOLDER), tempDir);
SoraldConfig config = createSegmentConfig(tempDir.getAbsolutePath());
SoraldAbstractProcessor<?> processor =
new ArrayHashCodeAndToStringProcessor().setEventHandlers(List.of());
Set<RuleViolation> violations =
ProjectScanner.scanProject(
tempDir, tempDir, Checks.getCheckInstance(processor.getRuleKey()));
// we decide that parsing this class causes crashes
String crashingClass = "DeadStores";
Path crashingFile = getProcessorTestJavaFilePath(tempDir, crashingClass);
Repair repair = new Repair(config, List.of());
Function<LinkedList<Node>, CtModel> selectivelyCrashySegmentParser =
segment ->
segmentContainsFile(segment, crashingFile.toString())
? throwIllegalStateException()
: repair.createSegmentLauncher(segment).getModel();
// act
List<CtModel> models =
repair.segmentRepair(
tempDir.getAbsoluteFile().toPath(),
processor,
violations,
selectivelyCrashySegmentParser)
.collect(Collectors.toList());
// assert
assertThat(processor.getNbFixes(), greaterThan(1));
assertThat(models.size(), greaterThan(1));
assertFalse(
models.stream()
.map(CtModel::getAllTypes)
.flatMap(Collection::stream)
.map(CtType::getSimpleName)
.anyMatch(typeName -> typeName.equals(crashingClass)));
}
/**
* @return the absolute path to a Java file in the given directory with the given class name.
*/
private static Path getProcessorTestJavaFilePath(File root, String className) {
return ProcessorTestHelper.getTestCaseStream(
root.toPath().resolve("processor_test_files").toFile())
.map(tc -> tc.nonCompliantFile)
.map(File::toPath)
.map(Path::toAbsolutePath)
.filter(p -> p.endsWith(className + Constants.JAVA_EXT))
.findFirst()
.get();
}
private static SoraldConfig createSegmentConfig(String originalFilesPath) {
var config = new SoraldConfig();
config.setRepairStrategy(RepairStrategy.SEGMENT);
config.setOriginalFilesPath(originalFilesPath);
config.setWorkspace(Constants.SORALD_WORKSPACE);
config.setFileOutputStrategy(FileOutputStrategy.CHANGED_ONLY);
config.setMaxFixesPerRule(Integer.MAX_VALUE);
config.setMaxFilesPerSegment(1);
return config;
}
private static CtModel throwIllegalStateException() {
throw new IllegalStateException("Just crashing a little bit here :)");
}
private static boolean segmentContainsFile(LinkedList<Node> segment, String fileName) {
return segment.stream()
.map(Node::getJavaFiles)
.flatMap(List::stream)
.anyMatch(s -> s.endsWith(fileName));
}
}
| 42.12426
| 97
| 0.628319
|
ba9960960158b39ab8db2faf66ebb47c1650c95e
| 2,617
|
/*
* Copyright (c) 2020-2021, Koninklijke Philips N.V., https://www.philips.com
* SPDX-License-Identifier: MIT
*/
package com.philips.research.bombar.controller;
import com.philips.research.bombar.core.ProjectService;
import org.junit.jupiter.api.Test;
import pl.tlinkowski.annotation.basic.NullOr;
import java.time.Instant;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
class ProjectJsonTest {
private static final UUID PROJECT_ID = UUID.randomUUID();
private static final String ID = "Id";
private static final String TITLE = "Title";
private static final Instant LAST_UPDATED = Instant.now();
private static final String DISTRIBUTION = "Distribution";
private static final String PHASE = "Phase";
@Test
void createsInstanceFromDto() {
final var dto = new ProjectService.ProjectDto(PROJECT_ID);
dto.title = TITLE;
dto.updated = LAST_UPDATED;
dto.distribution = DISTRIBUTION;
dto.phase = PHASE;
final var json = new ProjectJson(dto);
assert json.id != null;
assertThat(json.id).isEqualTo(PROJECT_ID);
assertThat(json.title).isEqualTo(TITLE);
assertThat(json.updated).isEqualTo(LAST_UPDATED);
assertThat(json.distribution).isEqualTo(DISTRIBUTION);
assertThat(json.phase).isEqualTo(PHASE);
assertThat(json.packages).isNull();
}
@Test
void includesPackagesFromDto() {
final var dto = new ProjectService.ProjectDto(PROJECT_ID);
dto.packages = List.of(new ProjectService.DependencyDto(ID));
final var json = new ProjectJson(dto);
assertThat(json.packages).isNotEmpty();
}
@Test
void convertsNullListToNull() {
assertThat(ProjectJson.toList(null)).isNull();
}
@Test
void convertsDtoList() {
final var dto = new ProjectService.ProjectDto(PROJECT_ID);
final @NullOr List<ProjectJson> result = ProjectJson.toList(List.of(dto));
assert result != null;
assertThat(Objects.requireNonNull(result.get(0).id)).isEqualTo(PROJECT_ID);
}
@Test
void convertsToDto() {
final var json = new ProjectJson();
json.title = TITLE;
json.distribution = DISTRIBUTION;
json.phase = PHASE;
final var dto = json.toDto(PROJECT_ID);
assertThat(dto.id).isEqualTo(PROJECT_ID);
assertThat(dto.title).isEqualTo(TITLE);
assertThat(dto.distribution).isEqualTo(DISTRIBUTION);
assertThat(dto.phase).isEqualTo(PHASE);
}
}
| 30.430233
| 83
| 0.67864
|
e30406ce4f8c24163133d51a759a23335fe5f532
| 8,168
|
/*
* The MIT License
*
* Copyright (C) 2010-2011 by Anthony Robinson
*
* 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 lib.form;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
import hudson.Extension;
import hudson.model.AbstractDescribableImpl;
import hudson.model.Describable;
import hudson.model.Descriptor;
import jenkins.model.Jenkins;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.Predicate;
import org.jvnet.hudson.test.HudsonTestCase;
import org.jvnet.hudson.test.Issue;
import org.kohsuke.stapler.DataBoundConstructor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
public class RepeatablePropertyTest extends HudsonTestCase implements Describable<RepeatablePropertyTest> {
private static final String VIEW_WITHOUT_DEFAULT = "noDefault";
private static final String VIEW_WITH_DEFAULT = "withDefault";
public ArrayList<ExcitingObject> testRepeatable;
public ArrayList<ExcitingObject> defaults;
public List<ExcitingObjectContainer> testRepeatableContainer;
public void testSimple() throws Exception {
testRepeatable = createRepeatable();
assertFormContents(VIEW_WITHOUT_DEFAULT, testRepeatable);
}
public void testNullFieldNoDefault() throws Exception {
assertFormContents(VIEW_WITHOUT_DEFAULT, new ArrayList<>());
}
public void testNullFieldWithDefault() throws Exception {
defaults = createRepeatable();
assertFormContents(VIEW_WITH_DEFAULT, defaults);
}
public void testFieldNotNullWithDefaultIgnoresDefaults() throws Exception {
testRepeatable = createRepeatable();
defaults = new ArrayList<>(Arrays.asList(
new ExcitingObject("This default should be ignored"),
new ExcitingObject("Ignore me too")
));
assertFormContents(VIEW_WITH_DEFAULT, testRepeatable);
}
@Issue("JENKINS-37599")
public void testNestedRepeatableProperty() throws Exception {
testRepeatableContainer = Collections.emptyList();
// minimum="1" is set for the upper one,
// the form should be:
// * 1 ExcitingObjectCotainer
// * no ExcitingObject
final HtmlForm form = getForm("nested");
List<HtmlTextInput> containerNameInputs = form.getElementsByAttribute("input", "type", "text");
CollectionUtils.filter(containerNameInputs, new Predicate<HtmlTextInput>() {
@Override
public boolean evaluate(HtmlTextInput input) {
return input.getNameAttribute().endsWith(".containerName");
}
});
List<HtmlTextInput> greatPropertyInputs = form.getElementsByAttribute("input", "type", "text");
CollectionUtils.filter(greatPropertyInputs, new Predicate<HtmlTextInput>() {
@Override
public boolean evaluate(HtmlTextInput input) {
return input.getNameAttribute().endsWith(".greatProperty");
}
});
assertEquals(1, containerNameInputs.size());
assertEquals(0, greatPropertyInputs.size());
}
private void assertFormContents(final String viewName, final ArrayList<ExcitingObject> expected) throws Exception {
final HtmlForm form = getForm(viewName);
final List<HtmlTextInput> inputs = toTextInputList(form.getElementsByAttribute("input", "type", "text"));
assertEquals("size", expected.size(), inputs.size());
for (int i = 0; i < expected.size(); i++)
assertEquals(expected.get(i).greatProperty, inputs.get(i).getValueAttribute());
}
private List<HtmlTextInput> toTextInputList(final List<HtmlElement> inputs) {
assertNotNull(inputs);
final List<HtmlTextInput> textInputList = new ArrayList<>();
for (HtmlElement input : inputs) {
assertTrue(input instanceof HtmlTextInput);
textInputList.add((HtmlTextInput) input);
}
return textInputList;
}
private ArrayList<ExcitingObject> createRepeatable() {
return new ArrayList<>(Arrays.asList(
new ExcitingObject("A nice thing"),
new ExcitingObject("I'm even better"),
new ExcitingObject("Don't bother, I'm not exciting at all")
));
}
private HtmlForm getForm(final String viewName) throws Exception {
final HtmlPage page = createWebClient().goTo("self/" + viewName);
final HtmlForm form = page.getFormByName("config");
return form;
}
public DescriptorImpl getDescriptor() {
return jenkins.getDescriptorByType(DescriptorImpl.class);
}
@Extension
public static final class DescriptorImpl extends Descriptor<RepeatablePropertyTest> {}
public static final class ExcitingObject implements Describable<ExcitingObject> {
private final String greatProperty;
@DataBoundConstructor
public ExcitingObject(final String greatProperty) {
this.greatProperty = greatProperty;
}
public String getGreatProperty() {
return greatProperty;
}
public Descriptor<ExcitingObject> getDescriptor() {
return Jenkins.get().getDescriptor(ExcitingObject.class);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ExcitingObject that = (ExcitingObject) o;
if (!Objects.equals(greatProperty, that.greatProperty))
return false;
return true;
}
@Override
public int hashCode() {
return greatProperty != null ? greatProperty.hashCode() : 0;
}
@Override
public String toString() {
return "ExcitingObject[" + greatProperty + ']';
}
@Extension
public static final class ExcitingDescriptor extends Descriptor<ExcitingObject> {
public ExcitingDescriptor() {
super(ExcitingObject.class);
}
}
}
public static final class ExcitingObjectContainer extends AbstractDescribableImpl<ExcitingObjectContainer> {
String containerName;
List<ExcitingObject> excitingObjectList;
@DataBoundConstructor
public ExcitingObjectContainer(String containerName, List<ExcitingObject> excitingObjectList) {
this.containerName = containerName;
this.excitingObjectList = excitingObjectList;
}
public String getContainerName() {
return containerName;
}
public List<ExcitingObject> getExcitingObjectList() {
return excitingObjectList;
}
@Extension
public static final class DescriptorImpl extends Descriptor<ExcitingObjectContainer> {
}
}
}
| 40.039216
| 119
| 0.685357
|
9b9aa579a1989ea3ebf0de3c250688d8fbe7c919
| 893
|
package io.wisoft.java_seminar.chap07.sec07.exam03_tire;
public class Tire {
// 필드
public int maxRotation; // 최대 회전수(타이어 수명)
public int accumulatedRotation; // 누적 회전수
public String location; // 타이어의 위치
// 생성자
public Tire(String location, int maxRotation) {
this.location = location;
this.maxRotation = maxRotation;
}
// 메소드
public boolean roll() {
++accumulatedRotation; // 누적 회전수 1증가
if (accumulatedRotation < maxRotation) { // 정상 회전(누적회전수 < 최대회전수)일경우 실행
System.out.println(location + " Tire 수명: " +
(maxRotation - accumulatedRotation) + "회");
return true;
} else { // 펑크(누적회전수 = 최대회전수)일경우 실행
System.out.println("***" + location + " Tire 펑크 ***");
return false;
}
}
}
| 31.892857
| 78
| 0.529675
|
6dcaba11fabac48dc9cb73f9fd9427cf385b7e83
| 226
|
package com.nblog.annotation;
import java.lang.annotation.*;
/**
* @author liulin
* 被该注解修饰的方法不需要进行 token 验证
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PassToken {
}
| 14.125
| 35
| 0.752212
|
8f5eb3c48150d1aebcfa529d4a0d8ab173fc2345
| 8,229
|
package com.example.p2pinvest.activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import com.example.p2pinvest.R;
import com.example.p2pinvest.common.ActivityManager;
import com.example.p2pinvest.common.BaseActivity;
import com.example.p2pinvest.fragment.HomeFragment;
import com.example.p2pinvest.fragment.InvestFragment;
import com.example.p2pinvest.fragment.MeFragment;
import com.example.p2pinvest.fragment.MoreFragment;
public class MainActivity extends BaseActivity implements View.OnClickListener {
private FragmentTransaction transaction;
private FrameLayout flMain;
private ImageView ivMainHome;
private TextView tvMainHome;
private LinearLayout llMainHome;
private ImageView ivMainInvest;
private TextView tvMainInvest;
private LinearLayout llMainInvest;
private ImageView ivMainMe;
private TextView tvMainMe;
private LinearLayout llMainMe;
private ImageView ivMainMore;
private TextView tvMainMore;
private LinearLayout llMainMore;
private HomeFragment homeFragment;
private InvestFragment investFragment;
private MeFragment meFragment;
private MoreFragment moreFragment;
public final String TAG = MainActivity.this.getClass().getSimpleName();
@Override
public void findViews() {
flMain = findViewById(R.id.fl_main);
ivMainHome = findViewById(R.id.iv_main_home);
tvMainHome = findViewById(R.id.tv_main_home);
llMainHome = findViewById(R.id.ll_main_home);
ivMainInvest = findViewById(R.id.iv_main_invest);
tvMainInvest = findViewById(R.id.tv_main_invest);
llMainInvest = findViewById(R.id.ll_main_invest);
ivMainMe = findViewById(R.id.iv_main_me);
tvMainMe = findViewById(R.id.tv_main_me);
llMainMe = findViewById(R.id.ll_main_me);
ivMainMore = findViewById(R.id.iv_main_more);
tvMainMore = findViewById(R.id.tv_main_more);
llMainMore = findViewById(R.id.ll_main_more);
llMainHome.setOnClickListener(this);
llMainInvest.setOnClickListener(this);
llMainMe.setOnClickListener(this);
llMainMore.setOnClickListener(this);
}
@Override
protected void initData() {
//默认显示首页
setSelect(0);
}
@Override
protected void initTitle() {
}
@Override
protected int getLayoutId() {
return R.layout.activity_main;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.ll_main_invest:
setSelect(1);
break;
case R.id.ll_main_me:
setSelect(2);
break;
case R.id.ll_main_more:
setSelect(3);
break;
case R.id.ll_main_home:
default:
setSelect(0);
break;
}
}
//提供相应的fragment的显示
private void setSelect(int i) {
FragmentManager fragmentManager = this.getSupportFragmentManager();
transaction = fragmentManager.beginTransaction();
//隐藏所有Fragment的显示
hideFragments();
//重置ImageView和TextView的显示状态
resetTab();
switch (i) {
case 0:
if (homeFragment == null) {
//创建对象以后,并不会马上调用生命周期方法。而是在commit()之后,方才调用
homeFragment = new HomeFragment();
transaction.add(R.id.fl_main, homeFragment);
}
//显示当前的fragment
transaction.show(homeFragment);
//调用如下方法,来给对应页面进行联网请求。但是 调用位置错误;因为:创建对象以后,并不会马上调用生命周期方法。而是在commit()之后,方才调用
//homeFragment.show();
//改变选中项的图片和文本颜色的变化
ivMainHome.setImageResource(R.drawable.bottom02);
//错误的写法;此处设置的颜色应该是颜色色值;而传进去的是颜色id;
//tvMainHome.setTextColor(R.color.text_progress);
tvMainHome.setTextColor(getResources().getColor(R.color.home_back_selected));
break;
case 1:
if (investFragment == null) {
investFragment = new InvestFragment();
transaction.add(R.id.fl_main, investFragment);
}
transaction.show(investFragment);
//改变选中项的图片和文本颜色的变化
ivMainInvest.setImageResource(R.drawable.bottom04);
tvMainInvest.setTextColor(getResources().getColor(R.color.home_back_selected));
break;
case 2:
if (meFragment == null) {
meFragment = new MeFragment();
transaction.add(R.id.fl_main, meFragment);
}
transaction.show(meFragment);
//改变选中项的图片和文本颜色的变化
ivMainMe.setImageResource(R.drawable.bottom06);
tvMainMe.setTextColor(getResources().getColor(R.color.home_back_selected01));
break;
case 3:
if (moreFragment == null) {
moreFragment = new MoreFragment();
transaction.add(R.id.fl_main, moreFragment);
}
transaction.show(moreFragment);
//改变选中项的图片和文本颜色的变化
ivMainMore.setImageResource(R.drawable.bottom08);
tvMainMore.setTextColor(getResources().getColor(R.color.home_back_selected));
break;
default:
break;
}
transaction.commit();//提交事务
}
private void resetTab() {
ivMainHome.setImageResource(R.drawable.bottom01);
ivMainInvest.setImageResource(R.drawable.bottom03);
ivMainMe.setImageResource(R.drawable.bottom05);
ivMainMore.setImageResource(R.drawable.bottom07);
tvMainHome.setTextColor(getResources().getColor(R.color.home_back_unselected));
tvMainInvest.setTextColor(getResources().getColor(R.color.home_back_unselected));
tvMainMe.setTextColor(getResources().getColor(R.color.home_back_unselected));
tvMainMore.setTextColor(getResources().getColor(R.color.home_back_unselected));
//这种方式也可以
//tvMainMore.setTextColor(ContextCompat.getColor(this, R.color.home_back_unselected));
}
private void hideFragments() {
if (homeFragment != null) {
transaction.hide(homeFragment);
}
if (investFragment != null) {
transaction.hide(investFragment);
}
if (meFragment != null) {
transaction.hide(meFragment);
}
if (moreFragment != null) {
transaction.hide(moreFragment);
}
}
//重写onKeyUp(),实现连续两次点击方可退出当前应用
private boolean flag = true;
private static final int WHAT_RESET_BACK = 1;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
Log.e("TAG", "handleMessage");
switch (msg.what) {
case WHAT_RESET_BACK:
flag = true;//复原
break;
}
}
};
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && flag) {
Toast.makeText(MainActivity.this, "再点击一次,退出当前应用", Toast.LENGTH_SHORT).show();
flag = false;
//发送延迟消息
handler.sendEmptyMessageDelayed(WHAT_RESET_BACK, 2000);
return true;
}
return super.onKeyUp(keyCode, event);
}
//为了避免出现内存的泄漏,需要在 onDestroy() 中,移除所有未被执行的消息
@Override
protected void onDestroy() {
super.onDestroy();
//方式一:移除指定id的所有的消息
//handler.removeMessages(WHAT_RESET_BACK);
//方式二:移除所有的未被执行的消息
handler.removeCallbacksAndMessages(null);
}
}
| 33.587755
| 95
| 0.621461
|
15fe9c9362bef5799ab3ca1654a3a988f403b88b
| 2,621
|
package dao;
import db.DB;
import models.User;
import models.News;
import org.sql2o.Connection;
import org.sql2o.Sql2oException;
import java.util.ArrayList;
import java.util.List;
public class Sql2oUserDao implements UserDao{
@Override
public void add(User user) {
try(Connection conn = DB.sql2o.open()){
String sql = "INSERT INTO users (name, position,department) VALUES (:name, :position,:department)";
int id = (int) conn.createQuery(sql, true)
.bind(user)
.executeUpdate()
.getKey();
user.setId(id);
} catch (Sql2oException ex){
System.out.println("User not added " + ex);
}
}
@Override
public List<User> getAllEmployees() {
try(Connection conn = DB.sql2o.open()){
String sql = "SELECT * FROM users";
return conn.createQuery(sql)
.executeAndFetch(User.class);
}
}
@Override
public User findById(int id) {
try(Connection conn = DB.sql2o.open()){
String sql = "SELECT * FROM users WHERE id=:id;";
return conn.createQuery(sql)
.addParameter("id", id)
.executeAndFetchFirst(User.class);
}
}
@Override
public List<News> userNews(int userId) {
List<News> news = new ArrayList<>();
String joinQuery = "SELECT news_id from department_news WHERE user_id=:userId;";
try(Connection conn = DB.sql2o.open()){
List<Integer> allUserIds = conn.createQuery(joinQuery)
.addParameter("userId", userId)
.executeAndFetch(Integer.class);
for (Integer singleUserId: allUserIds){
String userQuery = "SELECT FROM news WHERE id=:id;";
news.add(
conn.createQuery(userQuery)
.addParameter("id", singleUserId)
.executeAndFetchFirst(News.class)
);
}
}
return news;
}
@Override
public void deleteById(int id) {
try(Connection conn = DB.sql2o.open()){
String sql = "DELETE FROM users WHERE id=:id;";
conn.createQuery(sql)
.addParameter("id", id)
.executeUpdate();
}
}
@Override
public void clearAll() {
try(Connection conn = DB.sql2o.open()){
String sql = "DELETE FROM users;";
conn.createQuery(sql).executeUpdate();
}
}
}
| 30.476744
| 111
| 0.534529
|
228bad56c0a5ef5c765166032a86a88c733d3131
| 3,349
|
package com.paragon464.gameserver.io.database.table.player;
import com.paragon464.gameserver.io.database.pool.impl.ConnectionPool;
import com.paragon464.gameserver.io.database.table.Table;
import com.paragon464.gameserver.model.entity.mob.player.Player;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class BankCountTable extends Table<Player> {
@Override
public void load(Player player) throws SQLException, IOException {
try (Connection connection = ConnectionPool.getPool().getConnection();
PreparedStatement statement = connection.prepareStatement("SELECT * FROM paragon_player_bank_count WHERE user_id = ?")) {
statement.setInt(1, player.getDetails().getUserId());
final ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
int tab_1 = resultSet.getInt("tab_1");
int tab_2 = resultSet.getInt("tab_2");
int tab_3 = resultSet.getInt("tab_3");
int tab_4 = resultSet.getInt("tab_4");
int tab_5 = resultSet.getInt("tab_5");
int tab_6 = resultSet.getInt("tab_6");
int tab_7 = resultSet.getInt("tab_7");
int tab_8 = resultSet.getInt("tab_8");
int tab_9 = resultSet.getInt("tab_9");
player.getVariables().tab1items = tab_1;
player.getVariables().tab2items = tab_2;
player.getVariables().tab3items = tab_3;
player.getVariables().tab4items = tab_4;
player.getVariables().tab5items = tab_5;
player.getVariables().tab6items = tab_6;
player.getVariables().tab7items = tab_7;
player.getVariables().tab8items = tab_8;
player.getVariables().tab9items = tab_9;
}
}
}
@Override
public void save(Player player) throws SQLException, IOException {
try (Connection connection = ConnectionPool.getPool().getConnection();
PreparedStatement statement = connection.prepareStatement("INSERT INTO paragon_player_bank_count (user_id, tab_1, tab_2, tab_3, tab_4, tab_5, tab_6, tab_7, tab_8, tab_9) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT (user_id) DO UPDATE SET tab_1 = EXCLUDED.tab_1, tab_2 = EXCLUDED.tab_2, tab_3 = EXCLUDED.tab_3, tab_4 = EXCLUDED.tab_4, tab_5 = EXCLUDED.tab_5, tab_6 = EXCLUDED.tab_6, tab_7 = EXCLUDED.tab_7, tab_8 = EXCLUDED.tab_8, tab_9 = EXCLUDED.tab_9")) {
statement.setInt(1, player.getDetails().getUserId());
statement.setInt(2, player.getVariables().tab1items);
statement.setInt(3, player.getVariables().tab2items);
statement.setInt(4, player.getVariables().tab3items);
statement.setInt(5, player.getVariables().tab4items);
statement.setInt(6, player.getVariables().tab5items);
statement.setInt(7, player.getVariables().tab6items);
statement.setInt(8, player.getVariables().tab7items);
statement.setInt(9, player.getVariables().tab8items);
statement.setInt(10, player.getVariables().tab9items);
statement.executeUpdate();
}
}
}
| 52.328125
| 311
| 0.641983
|
bf311bfbf51451724e7d137b4f31d3cf0dbcf66d
| 9,880
|
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.route53recoverycontrolconfig.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
* <p>
* The details of the routing control that you're creating.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/route53-recovery-control-config-2020-11-02/CreateRoutingControl"
* target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CreateRoutingControlRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* A unique, case-sensitive string of up to 64 ASCII characters. To make an idempotent API request with an action,
* specify a client token in the request.
* </p>
*/
private String clientToken;
/**
* <p>
* The Amazon Resource Name (ARN) of the cluster that includes the routing control.
* </p>
*/
private String clusterArn;
/**
* <p>
* The Amazon Resource Name (ARN) of the control panel that includes the routing control.
* </p>
*/
private String controlPanelArn;
/**
* <p>
* The name of the routing control.
* </p>
*/
private String routingControlName;
/**
* <p>
* A unique, case-sensitive string of up to 64 ASCII characters. To make an idempotent API request with an action,
* specify a client token in the request.
* </p>
*
* @param clientToken
* A unique, case-sensitive string of up to 64 ASCII characters. To make an idempotent API request with an
* action, specify a client token in the request.
*/
public void setClientToken(String clientToken) {
this.clientToken = clientToken;
}
/**
* <p>
* A unique, case-sensitive string of up to 64 ASCII characters. To make an idempotent API request with an action,
* specify a client token in the request.
* </p>
*
* @return A unique, case-sensitive string of up to 64 ASCII characters. To make an idempotent API request with an
* action, specify a client token in the request.
*/
public String getClientToken() {
return this.clientToken;
}
/**
* <p>
* A unique, case-sensitive string of up to 64 ASCII characters. To make an idempotent API request with an action,
* specify a client token in the request.
* </p>
*
* @param clientToken
* A unique, case-sensitive string of up to 64 ASCII characters. To make an idempotent API request with an
* action, specify a client token in the request.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateRoutingControlRequest withClientToken(String clientToken) {
setClientToken(clientToken);
return this;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the cluster that includes the routing control.
* </p>
*
* @param clusterArn
* The Amazon Resource Name (ARN) of the cluster that includes the routing control.
*/
public void setClusterArn(String clusterArn) {
this.clusterArn = clusterArn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the cluster that includes the routing control.
* </p>
*
* @return The Amazon Resource Name (ARN) of the cluster that includes the routing control.
*/
public String getClusterArn() {
return this.clusterArn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the cluster that includes the routing control.
* </p>
*
* @param clusterArn
* The Amazon Resource Name (ARN) of the cluster that includes the routing control.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateRoutingControlRequest withClusterArn(String clusterArn) {
setClusterArn(clusterArn);
return this;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the control panel that includes the routing control.
* </p>
*
* @param controlPanelArn
* The Amazon Resource Name (ARN) of the control panel that includes the routing control.
*/
public void setControlPanelArn(String controlPanelArn) {
this.controlPanelArn = controlPanelArn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the control panel that includes the routing control.
* </p>
*
* @return The Amazon Resource Name (ARN) of the control panel that includes the routing control.
*/
public String getControlPanelArn() {
return this.controlPanelArn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the control panel that includes the routing control.
* </p>
*
* @param controlPanelArn
* The Amazon Resource Name (ARN) of the control panel that includes the routing control.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateRoutingControlRequest withControlPanelArn(String controlPanelArn) {
setControlPanelArn(controlPanelArn);
return this;
}
/**
* <p>
* The name of the routing control.
* </p>
*
* @param routingControlName
* The name of the routing control.
*/
public void setRoutingControlName(String routingControlName) {
this.routingControlName = routingControlName;
}
/**
* <p>
* The name of the routing control.
* </p>
*
* @return The name of the routing control.
*/
public String getRoutingControlName() {
return this.routingControlName;
}
/**
* <p>
* The name of the routing control.
* </p>
*
* @param routingControlName
* The name of the routing control.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public CreateRoutingControlRequest withRoutingControlName(String routingControlName) {
setRoutingControlName(routingControlName);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getClientToken() != null)
sb.append("ClientToken: ").append(getClientToken()).append(",");
if (getClusterArn() != null)
sb.append("ClusterArn: ").append(getClusterArn()).append(",");
if (getControlPanelArn() != null)
sb.append("ControlPanelArn: ").append(getControlPanelArn()).append(",");
if (getRoutingControlName() != null)
sb.append("RoutingControlName: ").append(getRoutingControlName());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof CreateRoutingControlRequest == false)
return false;
CreateRoutingControlRequest other = (CreateRoutingControlRequest) obj;
if (other.getClientToken() == null ^ this.getClientToken() == null)
return false;
if (other.getClientToken() != null && other.getClientToken().equals(this.getClientToken()) == false)
return false;
if (other.getClusterArn() == null ^ this.getClusterArn() == null)
return false;
if (other.getClusterArn() != null && other.getClusterArn().equals(this.getClusterArn()) == false)
return false;
if (other.getControlPanelArn() == null ^ this.getControlPanelArn() == null)
return false;
if (other.getControlPanelArn() != null && other.getControlPanelArn().equals(this.getControlPanelArn()) == false)
return false;
if (other.getRoutingControlName() == null ^ this.getRoutingControlName() == null)
return false;
if (other.getRoutingControlName() != null && other.getRoutingControlName().equals(this.getRoutingControlName()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getClientToken() == null) ? 0 : getClientToken().hashCode());
hashCode = prime * hashCode + ((getClusterArn() == null) ? 0 : getClusterArn().hashCode());
hashCode = prime * hashCode + ((getControlPanelArn() == null) ? 0 : getControlPanelArn().hashCode());
hashCode = prime * hashCode + ((getRoutingControlName() == null) ? 0 : getRoutingControlName().hashCode());
return hashCode;
}
@Override
public CreateRoutingControlRequest clone() {
return (CreateRoutingControlRequest) super.clone();
}
}
| 33.605442
| 129
| 0.632996
|
acf4180b9a0af024927ca3f14a26f27e22e136f3
| 4,987
|
package seedu.address.model;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.util.function.Predicate;
import javafx.collections.ObservableList;
import seedu.address.commons.core.GuiSettings;
import seedu.address.model.meeting.Meeting;
import seedu.address.model.module.Module;
/**
* The API of the Model component.
*/
public interface Model {
Predicate<Module> PREDICATE_SHOW_ALL_MODULES = unused -> true;
/* Invariant predicates that will always be executed after every command. */
Predicate<Meeting> PREDICATE_SHOW_ALL_UNCOMPLETED_MEETINGS = m ->
m.getIsRecurring().isRecurring || LocalDateTime.now().isBefore(m.getEndDateTime().datetime);
Predicate<Meeting> PREDICATE_SHOW_ALL_COMPLETED_MEETINGS = m ->
!m.getIsRecurring().isRecurring && LocalDateTime.now().isAfter(m.getEndDateTime().datetime);
// =========== UserPrefs ===============================================================================
/**
* Replaces user prefs data with the data in {@code userPrefs}.
*/
void setUserPrefs(ReadOnlyUserPrefs userPrefs);
/**
* Returns the user prefs.
*/
ReadOnlyUserPrefs getUserPrefs();
/**
* Returns the user prefs' GUI settings.
*/
GuiSettings getGuiSettings();
/**
* Sets the user prefs' GUI settings.
*/
void setGuiSettings(GuiSettings guiSettings);
/**
* Returns the user prefs' LinkyTime file path.
*/
Path getLinkyTimeFilePath();
/**
* Sets the user prefs' LinkyTime file path.
*/
void setLinkyTimeFilePath(Path linkyTimeFilePath);
// =========== LinkyTime ===============================================================================
/**
* Replaces LinkyTime data with the data in {@code linkyTime}.
*/
void setLinkyTime(ReadOnlyLinkyTime linkyTime);
/**
* Returns LinkyTime
*/
ReadOnlyLinkyTime getLinkyTime();
// =========== Meeting ============================================================================
/**
* Returns true if a meeting that is identical to {@code meeting} exists in LinkyTime.
*/
boolean hasMeeting(Meeting meeting);
/**
* Deletes the given meeting.
* The meeting must exist in LinkyTime.
*/
void deleteMeeting(Meeting target);
/**
* Adds the given meeting.
* {@code meeting} must not already exist in LinkyTime.
*/
void addMeeting(Meeting meeting);
/**
* Replaces the given meeting {@code target} with {@code editedMeeting}.
* {@code target} must exist in LinkyTime.
*/
void setMeeting(Meeting target, Meeting editedMeeting);
// =========== Meeting List Accessors ====================================================
/**
* Returns an unmodifiable view of the filtered meeting list
*/
ObservableList<Meeting> getFilteredMeetingList();
/**
* Updates the filter of the filtered meeting list to filter by the given {@code predicate}.
*
* @throws NullPointerException if {@code predicate} is null.
*/
void updateFilteredMeetingList(Predicate<Meeting> predicate);
/**
* Returns an unmodifiable view of the unfiltered meeting list.
*/
ObservableList<Meeting> getMeetingList();
/**
* Toggles the filtered meeting list to ensure all meeting entries are always either completed or uncompleted.
*
* @param showCompleted Determines whether the filtered meeting entries are
* always either completed or uncompleted .
*/
void showCompletedMeetings(boolean showCompleted);
// =========== Module ==================================================================================
/**
* Returns true if a module that is identical to {@code module} exists in LinkyTime.
*/
boolean hasModule(Module module);
/**
* Adds the given module.
* {@code module} must not already exist in LinkyTime.
*/
void addModule(Module module);
/**
* Replaces the given module {@code target} with {@code editedModule}.
* {@code target} must exist in LinkyTime.
*/
void setModule(Module target, Module editedModule);
/**
* Deletes the given module.
* The module must exist in LinkyTime.
*/
void deleteModule(Module target);
// =========== Module List Accessors ==========================================================
/**
* Returns an unmodifiable view of the filtered module list.
*/
ObservableList<Module> getFilteredModuleList();
/**
* Updates the filter of the filtered module list to filter by the given {@code predicate}.
*
* @throws NullPointerException if {@code predicate} is null.
*/
void updateFilteredModuleList(Predicate<Module> predicate);
/**
* Returns an unmodifiable view of the unfiltered module list.
*/
ObservableList<Module> getModuleList();
}
| 30.224242
| 114
| 0.594345
|
80d23a525a0137574d99ee269db464e707ddd42e
| 3,642
|
/*
* Copyright (C) 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.common.testing.accessibility.framework;
import com.google.android.apps.common.testing.accessibility.framework.AccessibilityCheckResult.AccessibilityCheckResultType;
import android.os.Build;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.ListView;
import android.widget.ScrollView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Check to ensure that a view has a content description for a screen reader
*/
public class SpeakableTextPresentViewCheck extends AccessibilityViewCheck {
/*
* TODO(pweaver) Determine if we can reduce this list, and add notes for those that need to
* be here.
* WebView: This class doesn't behave consistently across platforms, and it can report
* that it has no children even when it is displaying content.
*/
private static final List<Class<? extends ViewGroup>> blacklistedViewTypes =
Arrays.asList(ListView.class, ScrollView.class, ViewPager.class, WebView.class);
@Override
public List<AccessibilityViewCheckResult> runCheckOnView(View view) {
List<AccessibilityViewCheckResult> results = new ArrayList<AccessibilityViewCheckResult>();
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
results.add(new AccessibilityViewCheckResult(this.getClass(),
AccessibilityCheckResultType.NOT_RUN, "This check only runs on Android 4.1 and above.",
view));
return results;
}
if (!ViewAccessibilityUtils.isImportantForAccessibility(view)) {
results.add(new AccessibilityViewCheckResult(this.getClass(),
AccessibilityCheckResultType.NOT_RUN, "View is not important for accessibility.", view));
return results;
}
for (Class<? extends ViewGroup> clazz : blacklistedViewTypes) {
if (clazz.isAssignableFrom(view.getClass())) {
String msg =
String.format("Views of type %s are not checked for speakable text.", clazz.getName());
results.add(new AccessibilityViewCheckResult(this.getClass(),
AccessibilityCheckResultType.NOT_RUN, msg, view));
return results;
}
}
if (shouldFocusView(view)) {
// We must evaluate this view for speakable text
if (TextUtils.isEmpty(AccessibilityCheckUtils.getSpeakableTextForView(view))) {
results.add(new AccessibilityViewCheckResult(this.getClass(),
AccessibilityCheckResultType.ERROR,
"View is missing speakable text needed for a screen reader", view));
}
} else {
results.add(new AccessibilityViewCheckResult(this.getClass(),
AccessibilityCheckResultType.NOT_RUN, "View is not focused by a screen reader", view));
}
return results;
}
/* TODO(pweaver) Remove this awkward way of allowing Robolectric to use this */
protected boolean shouldFocusView(View view) {
return ViewAccessibilityUtils.shouldFocusView(view);
}
}
| 41.386364
| 124
| 0.737232
|
825c2f2383efface49177cec8d3c9335d5328a05
| 997
|
/**
* Base class for DAO layer testing. Assumes the database is loaded
* with valid data.
*/
package com.gieman.tttracker.dao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
@ContextConfiguration("/testingContext.xml")
public abstract class AbstractDaoForTesting extends AbstractTransactionalJUnit4SpringContextTests {
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired(required = true)
protected CompanyDao companyDao;
@Autowired(required = true)
protected ProjectDao projectDao;
@Autowired(required = true)
protected TaskDao taskDao;
@Autowired(required = true)
protected UserDao userDao;
@Autowired(required = true)
protected TaskLogDao taskLogDao;
}
| 34.37931
| 100
| 0.766299
|
43d2d11f2fb7b100cfb0bc7a3ed73ad25bea07dc
| 2,547
|
package com.github.lehjr.numina.recipe;
import com.google.gson.JsonObject;
import net.minecraft.inventory.CraftingInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.IRecipeSerializer;
import net.minecraft.item.crafting.Ingredient;
import net.minecraft.item.crafting.ShapedRecipe;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.NonNullList;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.energy.CapabilityEnergy;
import java.util.concurrent.atomic.AtomicInteger;
import static com.github.lehjr.numina.recipe.RecipeSerializersRegistry.TEST_RECIPE_SERIALIZER;
/**
* Copies energy from ingredients to the result ItemStack
*/
public class ShapedEnergyRecipe extends ShapedRecipe {
public ShapedEnergyRecipe(ShapedRecipe shaped) {
this(shaped.getId(), shaped.getGroup(), shaped.getWidth(), shaped.getHeight(), shaped.getIngredients(), shaped.getResultItem());
}
public ShapedEnergyRecipe(final ResourceLocation id, final String group, final int recipeWidth, final int recipeHeight, final NonNullList<Ingredient> ingredients, final ItemStack recipeOutput) {
super(id, group, recipeWidth, recipeHeight, ingredients, recipeOutput);
}
/**
* @param inv
* @return result with energy from ingredients up to max value
*/
@Override
public ItemStack assemble(final CraftingInventory inv) {
final ItemStack output = super.assemble(inv).copy(); // Get the default output
AtomicInteger energy = new AtomicInteger(0);
for(int i = 0; i < inv.getContainerSize(); ++i) {
ItemStack itemstack = inv.getItem(i);
energy.addAndGet(itemstack.getCapability(CapabilityEnergy.ENERGY).map(iEnergyStorage -> iEnergyStorage.getEnergyStored()).orElse(0));
}
output.getCapability(CapabilityEnergy.ENERGY).ifPresent(iEnergyStorage -> {
int testEnergy = iEnergyStorage.receiveEnergy(energy.get(), true);
while (testEnergy > 0) {
testEnergy -= iEnergyStorage.receiveEnergy(testEnergy, false);
}
});
return output;
}
@Override
public IRecipeSerializer<?> getSerializer() {
return TEST_RECIPE_SERIALIZER.get();
}
public static class EnergySerializer extends Serializer {
@Override
public ShapedEnergyRecipe fromJson(final ResourceLocation recipeID, final JsonObject json) {
return new ShapedEnergyRecipe(super.fromJson(recipeID, json));
}
@Override
public ShapedEnergyRecipe fromNetwork(final ResourceLocation recipeID, final PacketBuffer buffer) {
return new ShapedEnergyRecipe(super.fromNetwork(recipeID, buffer));
}
}
}
| 36.385714
| 195
| 0.783667
|
8ae3f92eb397324ad39ebc3d2f20d0e0d53624f3
| 264
|
package pattern.visitor;
/**
* Element.java
*
* @author: zhaoxiaoping
* @date: 2019/11/01
**/
public abstract class Element {
public String uuid;
public Element(String uuid) {
this.uuid = uuid;
}
public abstract void accept(Visitor visitor);
}
| 14.666667
| 47
| 0.670455
|
b354fc5d7f7c576191c042a7613a71480b478c30
| 2,300
|
package com.example.hotel.infrasctructure.configuration;
import com.example.hotel.application.messaging.model.BookingRequestMessage;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import reactor.core.publisher.Flux;
// @Configuration
public class RabbitMQConfiguration {
@Autowired private ObjectMapper objectMapper;
@Value("${queue.booking-request}")
private String bookingRequestQueue;
@Bean("bookingRequestMessageFlux")
public Flux<BookingRequestMessage> bookingRequestMessageFlux(
ConnectionFactory connectionFactory) {
final var messageListenerContainer = new SimpleMessageListenerContainer(connectionFactory);
messageListenerContainer.setAcknowledgeMode(AcknowledgeMode.AUTO);
messageListenerContainer.addQueueNames(bookingRequestQueue);
messageListenerContainer.setDeclarationRetries(2);
messageListenerContainer.setFailedDeclarationRetryInterval(5000);
messageListenerContainer.setRetryDeclarationInterval(2);
return Flux.create(
emitter -> {
messageListenerContainer.setMessageListener(
message -> {
final var bookingRequestMessage = readBookingRequestMessageValue(message.getBody());
emitter.next(bookingRequestMessage);
});
emitter.onRequest(value -> messageListenerContainer.start());
emitter.onDispose(messageListenerContainer::stop);
});
}
// @PostConstruct
// public void postConstruct() throws JsonProcessingException {
// final var message = new BookingRequestMessage();
// message.setCustomerId(UUID.randomUUID());
// message.setBedroomId(UUID.randomUUID());
// objectMapper.writeValueAsString(message);
// }
@SneakyThrows
private BookingRequestMessage readBookingRequestMessageValue(byte[] value) {
return objectMapper.readValue(value, BookingRequestMessage.class);
}
}
| 38.983051
| 100
| 0.774348
|
7c1d0e210f333aa79c6ddaeabc672cedc68920fc
| 1,974
|
package tool.feedback;
import java.util.List;
import tool.designpatterns.DesignPattern;
import tool.designpatterns.Pattern;
import tool.designpatterns.PatternGroup;
/**
* The feedback for an entire patternGroup.
*/
@DesignPattern(pattern = {Pattern.IMMUTABLE})
public final class PatternGroupFeedback {
private final PatternGroup patternGroup;
private final List<Feedback> feedbacks;
/**
* Creates a new PatternGroupFeedback for the given patternGroup and with the given child
* feedbacks.
*
* @param patternGroup the patternGroup this represents the feedback for.
* @param feedbacks the feedbacks that is this groups children.
*/
public PatternGroupFeedback(
PatternGroup patternGroup, List<Feedback> feedbacks) {
this.patternGroup = patternGroup;
this.feedbacks = feedbacks;
}
/**
* Get a full feedback message for this PatternGroup and it's children.
*
* @return the message.
*/
public String getFullMessage() {
StringBuilder message = new StringBuilder(60);
message.append("Verification of the design pattern ").append(patternGroup.toString());
if (hasError()) {
message.append(" failed due to:\n");
} else {
message.append(" was successful\n");
}
for (Feedback childFeedback : feedbacks) {
if (childFeedback.getIsError()) {
message.append(childFeedback.getFullMessage());
message.append('\n');
}
}
return message.toString();
}
/**
* Returns true if this feedback or any of its children is an error.
*
* @return if this is an error.
*/
public boolean hasError() {
boolean hasError = false;
for (Feedback feedback : feedbacks) {
if (feedback.getIsError()) {
hasError = true;
}
}
return hasError;
}
}
| 27.041096
| 94
| 0.619048
|
320c7ae8e1492e44f043fe060eb04da240308a28
| 4,447
|
package wisematches.server.services.message;
import wisematches.core.Player;
import wisematches.core.task.CleaningDayListener;
import java.util.Collection;
/**
* {@code MessageManager} provides ability to send/receive short messages between personalities.
*
* @author Sergey Klimenko (smklimenko@gmail.com)
*/
public interface MessageManager extends CleaningDayListener {
void addMessageListener(MessageListener l);
void removeMessageListener(MessageListener l);
/**
* Sent a message to specified player
*
* @param sender the sender of the message
* @param recipient the player who should received the message
* @param body the message's body
* @throws NullPointerException if sender or recipient is null
* @throws IllegalArgumentException if body is null or empty
*/
void sendMessage(Player sender, Player recipient, String body);
/**
* Sent a message to specified player
*
* @param sender the sender of the message
* @param recipient the player who should received the message
* @param body the message's body
* @param quite indicates is notification should be quite or note.
* @throws NullPointerException if sender or recipient is null
* @throws IllegalArgumentException if body is null or empty
*/
void sendMessage(Player sender, Player recipient, String body, boolean quite);
/**
* Reply to specified message.
*
* @param sender the sender of the message
* @param message the original message
* @param body the message's body
* @throws NullPointerException if sender, recipient or message is null
* @throws IllegalArgumentException if body is null or empty
*/
void replyMessage(Player sender, Message message, String body);
/**
* Reply to specified message.
*
* @param sender the sender of the message
* @param message the original message
* @param body the message's body
* @param quite indicates is notification should be quite or note.
* @throws NullPointerException if sender, recipient or message is null
* @throws IllegalArgumentException if body is null or empty
*/
void replyMessage(Player sender, Message message, String body, boolean quite);
/**
* Sent notification to specified player with specified body
*
* @param recipient the player who should received the message
* @param body the message's body
* @throws NullPointerException if recipient is null
* @throws IllegalArgumentException if recipient is unknown or {@code body} is empty.
*/
void sendNotification(Player recipient, String body);
/**
* Sent notification to specified player with specified body
*
* @param recipient the player who should received the message
* @param body the message's body
* @param quite indicates is notification should be quite or note.
* @throws NullPointerException if recipient is null
* @throws IllegalArgumentException if recipient is unknown or {@code body} is empty.
*/
void sendNotification(Player recipient, String body, boolean quite);
/**
* Returns a message with specified id.
*
* @param id the message id
* @return the message or {@code null} if message unknown
*/
Message getMessage(long id);
/**
* Returns new messages count.
*
* @param personality the person who's messages count should be received.
* @return the number of messages received from last time
*/
int getNewMessagesCount(Player personality);
/**
* Returns number of messages sent today.
*
* @param personality the person who's count should be returned.
* @param direction the message direction.
* @return the number of messages sent today.
*/
int getTodayMessagesCount(Player personality, MessageDirection direction);
/**
* Returns collection of all message for specified person.
*
* @param person the person who's message should be returned.
* @param direction the message direction.
* @return the collection of all message.
*/
Collection<Message> getMessages(Player person, MessageDirection direction);
/**
* Removes a message with specified id
*
* @param person a person who's message should be removed
* @param messageId the message id
* @param direction the message direction.
*/
void removeMessage(Player person, long messageId, MessageDirection direction);
}
| 34.742188
| 97
| 0.711041
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.