text stringlengths 10 2.72M |
|---|
package com.grocery.codenicely.vegworld_new.splash_screen;
import com.grocery.codenicely.vegworld_new.splash_screen.model.data.SplashScreenData;
/**
* Created by meghal on 23/10/16.
*/
public interface SplashScreenCallback {
void onSuccess(SplashScreenData splashScreenData);
void onFailed();
}
|
package site.lzlz.mainbody.mapper;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import site.lzlz.mainbody.entity.dataobject.WxMessageDO;
@RunWith(SpringRunner.class)
@SpringBootTest
public class WxMessageMapperTest {
@Autowired
WxMessageMapper wxMessageMapper;
@Test
public void selectMessageByKey() {
WxMessageDO wxMessage = wxMessageMapper.selectMessageByKey("help");
System.out.println(wxMessage);
Assert.assertNotNull(wxMessage);
}
} |
/**
* This class is generated by jOOQ
*/
package schema.tables.records;
import java.sql.Timestamp;
import javax.annotation.Generated;
import org.jooq.Field;
import org.jooq.Record1;
import org.jooq.Record8;
import org.jooq.Row8;
import org.jooq.impl.UpdatableRecordImpl;
import schema.tables.MilestonesUsermilestone;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.8.4"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class MilestonesUsermilestoneRecord extends UpdatableRecordImpl<MilestonesUsermilestoneRecord> implements Record8<Integer, Timestamp, Timestamp, Integer, String, Timestamp, Byte, Integer> {
private static final long serialVersionUID = 1719160968;
/**
* Setter for <code>bitnami_edx.milestones_usermilestone.id</code>.
*/
public void setId(Integer value) {
set(0, value);
}
/**
* Getter for <code>bitnami_edx.milestones_usermilestone.id</code>.
*/
public Integer getId() {
return (Integer) get(0);
}
/**
* Setter for <code>bitnami_edx.milestones_usermilestone.created</code>.
*/
public void setCreated(Timestamp value) {
set(1, value);
}
/**
* Getter for <code>bitnami_edx.milestones_usermilestone.created</code>.
*/
public Timestamp getCreated() {
return (Timestamp) get(1);
}
/**
* Setter for <code>bitnami_edx.milestones_usermilestone.modified</code>.
*/
public void setModified(Timestamp value) {
set(2, value);
}
/**
* Getter for <code>bitnami_edx.milestones_usermilestone.modified</code>.
*/
public Timestamp getModified() {
return (Timestamp) get(2);
}
/**
* Setter for <code>bitnami_edx.milestones_usermilestone.user_id</code>.
*/
public void setUserId(Integer value) {
set(3, value);
}
/**
* Getter for <code>bitnami_edx.milestones_usermilestone.user_id</code>.
*/
public Integer getUserId() {
return (Integer) get(3);
}
/**
* Setter for <code>bitnami_edx.milestones_usermilestone.source</code>.
*/
public void setSource(String value) {
set(4, value);
}
/**
* Getter for <code>bitnami_edx.milestones_usermilestone.source</code>.
*/
public String getSource() {
return (String) get(4);
}
/**
* Setter for <code>bitnami_edx.milestones_usermilestone.collected</code>.
*/
public void setCollected(Timestamp value) {
set(5, value);
}
/**
* Getter for <code>bitnami_edx.milestones_usermilestone.collected</code>.
*/
public Timestamp getCollected() {
return (Timestamp) get(5);
}
/**
* Setter for <code>bitnami_edx.milestones_usermilestone.active</code>.
*/
public void setActive(Byte value) {
set(6, value);
}
/**
* Getter for <code>bitnami_edx.milestones_usermilestone.active</code>.
*/
public Byte getActive() {
return (Byte) get(6);
}
/**
* Setter for <code>bitnami_edx.milestones_usermilestone.milestone_id</code>.
*/
public void setMilestoneId(Integer value) {
set(7, value);
}
/**
* Getter for <code>bitnami_edx.milestones_usermilestone.milestone_id</code>.
*/
public Integer getMilestoneId() {
return (Integer) get(7);
}
// -------------------------------------------------------------------------
// Primary key information
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Record1<Integer> key() {
return (Record1) super.key();
}
// -------------------------------------------------------------------------
// Record8 type implementation
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Row8<Integer, Timestamp, Timestamp, Integer, String, Timestamp, Byte, Integer> fieldsRow() {
return (Row8) super.fieldsRow();
}
/**
* {@inheritDoc}
*/
@Override
public Row8<Integer, Timestamp, Timestamp, Integer, String, Timestamp, Byte, Integer> valuesRow() {
return (Row8) super.valuesRow();
}
/**
* {@inheritDoc}
*/
@Override
public Field<Integer> field1() {
return MilestonesUsermilestone.MILESTONES_USERMILESTONE.ID;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Timestamp> field2() {
return MilestonesUsermilestone.MILESTONES_USERMILESTONE.CREATED;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Timestamp> field3() {
return MilestonesUsermilestone.MILESTONES_USERMILESTONE.MODIFIED;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Integer> field4() {
return MilestonesUsermilestone.MILESTONES_USERMILESTONE.USER_ID;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field5() {
return MilestonesUsermilestone.MILESTONES_USERMILESTONE.SOURCE;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Timestamp> field6() {
return MilestonesUsermilestone.MILESTONES_USERMILESTONE.COLLECTED;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Byte> field7() {
return MilestonesUsermilestone.MILESTONES_USERMILESTONE.ACTIVE;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Integer> field8() {
return MilestonesUsermilestone.MILESTONES_USERMILESTONE.MILESTONE_ID;
}
/**
* {@inheritDoc}
*/
@Override
public Integer value1() {
return getId();
}
/**
* {@inheritDoc}
*/
@Override
public Timestamp value2() {
return getCreated();
}
/**
* {@inheritDoc}
*/
@Override
public Timestamp value3() {
return getModified();
}
/**
* {@inheritDoc}
*/
@Override
public Integer value4() {
return getUserId();
}
/**
* {@inheritDoc}
*/
@Override
public String value5() {
return getSource();
}
/**
* {@inheritDoc}
*/
@Override
public Timestamp value6() {
return getCollected();
}
/**
* {@inheritDoc}
*/
@Override
public Byte value7() {
return getActive();
}
/**
* {@inheritDoc}
*/
@Override
public Integer value8() {
return getMilestoneId();
}
/**
* {@inheritDoc}
*/
@Override
public MilestonesUsermilestoneRecord value1(Integer value) {
setId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public MilestonesUsermilestoneRecord value2(Timestamp value) {
setCreated(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public MilestonesUsermilestoneRecord value3(Timestamp value) {
setModified(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public MilestonesUsermilestoneRecord value4(Integer value) {
setUserId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public MilestonesUsermilestoneRecord value5(String value) {
setSource(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public MilestonesUsermilestoneRecord value6(Timestamp value) {
setCollected(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public MilestonesUsermilestoneRecord value7(Byte value) {
setActive(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public MilestonesUsermilestoneRecord value8(Integer value) {
setMilestoneId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public MilestonesUsermilestoneRecord values(Integer value1, Timestamp value2, Timestamp value3, Integer value4, String value5, Timestamp value6, Byte value7, Integer value8) {
value1(value1);
value2(value2);
value3(value3);
value4(value4);
value5(value5);
value6(value6);
value7(value7);
value8(value8);
return this;
}
// -------------------------------------------------------------------------
// Constructors
// -------------------------------------------------------------------------
/**
* Create a detached MilestonesUsermilestoneRecord
*/
public MilestonesUsermilestoneRecord() {
super(MilestonesUsermilestone.MILESTONES_USERMILESTONE);
}
/**
* Create a detached, initialised MilestonesUsermilestoneRecord
*/
public MilestonesUsermilestoneRecord(Integer id, Timestamp created, Timestamp modified, Integer userId, String source, Timestamp collected, Byte active, Integer milestoneId) {
super(MilestonesUsermilestone.MILESTONES_USERMILESTONE);
set(0, id);
set(1, created);
set(2, modified);
set(3, userId);
set(4, source);
set(5, collected);
set(6, active);
set(7, milestoneId);
}
}
|
// moda/module.info.java
module moda {
exports pkga;
}
|
package pinno.demo.hackernews.screen.collection;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InOrder;
import org.mockito.Mock;
import pinno.demo.hackernews.api.HackerNewsApi;
import pinno.demo.hackernews.api.data.NewsItem;
import pinno.demo.hackernews.unittest.base.BaseTest;
import pinno.demo.hackernews.unittest.tools.ResponseFactory;
import rx.Observable;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyBoolean;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
public class CollectionPresenterTest extends BaseTest {
@Mock
private CollectionRepository mCollectionRepository;
@Mock
private CollectionContract.View mCollectionView;
private CollectionPresenter mCollectionPresenter;
@Before
public void setup() {
mCollectionPresenter = new CollectionPresenter(mCollectionRepository);
mCollectionPresenter.attachView(mCollectionView);
mCollectionPresenter.setup(HackerNewsApi.COLLECTION_TOP_STORIES);
}
@After
public void tearDown() {
rxJavaRule.rxJavaHooker.reset();
mCollectionPresenter.detachView();
}
@Test
public void initStatusTest() {
verify(mCollectionRepository).setup(HackerNewsApi.COLLECTION_TOP_STORIES,
CollectionPresenter.PAGE_SIZE);
}
@Test
public void refreshFlowTest() {
mCollectionPresenter = spy(mCollectionPresenter);
doNothing().when(mCollectionPresenter).loadNext(true);
mCollectionPresenter.refresh();
verify(mCollectionPresenter).loadNext(true);
}
@Test
public void retryFlowTest() {
mCollectionPresenter = spy(mCollectionPresenter);
doNothing().when(mCollectionPresenter).loadNext(false);
mCollectionPresenter.retry();
verify(mCollectionPresenter).loadNext(false);
}
@Test
public void handlePagination_positionBelowThreshold() {
mCollectionPresenter = spy(mCollectionPresenter);
//Below threshold
final int itemCount = CollectionPresenter.PAGE_SIZE;
mCollectionPresenter.handlePagination(itemCount, CollectionPresenter.LOAD_NEXT_THRESHOLD - 1);
verify(mCollectionPresenter, never()).loadNext(anyBoolean());
}
@Test
public void handlePagination_positionEqualToThreshold() {
mCollectionPresenter = spy(mCollectionPresenter);
doNothing().when(mCollectionPresenter).loadNext(false);
final int itemCount = CollectionPresenter.PAGE_SIZE;
//Equal to threshold
mCollectionPresenter.handlePagination(itemCount, CollectionPresenter.LOAD_NEXT_THRESHOLD);
getTestScheduler().advanceTimeBy(1, TimeUnit.SECONDS);
verify(mCollectionPresenter).loadNext(false);
}
@Test
public void handlePagination_positionGreaterThanThreshold() {
mCollectionPresenter = spy(mCollectionPresenter);
doNothing().when(mCollectionPresenter).loadNext(false);
final int itemCount = CollectionPresenter.PAGE_SIZE;
//Greater than threshold
mCollectionPresenter.handlePagination(itemCount, CollectionPresenter.LOAD_NEXT_THRESHOLD + 1);
getTestScheduler().advanceTimeBy(1, TimeUnit.SECONDS);
verify(mCollectionPresenter).loadNext(false);
}
@Test
public void onCommentClicked_withNull() {
mCollectionPresenter.newsItemViewHolderClicked(null);
verify(mCollectionView, never()).launchDetailPage(any(NewsItem.class));
}
@Test
public void loadNext_noNextItemAnymore() {
doReturn(false).when(mCollectionRepository).hasNext();
mCollectionPresenter.loadNext(false);
verify(mCollectionRepository, never()).loadNext();
verify(mCollectionRepository, never()).reset();
}
@Test
public void loadNext_continualExecution() {
doReturn(true).when(mCollectionRepository).hasNext();
doReturn(Observable.just(ResponseFactory.STORY_COLLECTIONS).delay(2, TimeUnit.SECONDS)).when(
mCollectionRepository).loadNext();
mCollectionPresenter.loadNext(false);
getTestScheduler().advanceTimeBy(1, TimeUnit.SECONDS);
mCollectionPresenter.loadNext(false);
verify(mCollectionRepository, times(1)).loadNext();
}
@Test
public void loadNext_reloadSuccess() {
InOrder inOrder = inOrder(mCollectionView, mCollectionRepository);
doReturn(true).when(mCollectionRepository).hasNext();
doReturn(Observable.just(ResponseFactory.STORY_COLLECTIONS)).when(mCollectionRepository)
.loadNext();
mCollectionPresenter.loadNext(true);
inOrder.verify(mCollectionRepository).reset();
getTestScheduler().advanceTimeBy(1, TimeUnit.SECONDS);
inOrder.verify(mCollectionView).showLoading();
inOrder.verify(mCollectionView).hideErrorRetry();
inOrder.verify(mCollectionView).clearItems();
inOrder.verify(mCollectionView).hideLoadingNext();
inOrder.verify(mCollectionView).addItems(ResponseFactory.STORY_COLLECTIONS);
inOrder.verify(mCollectionView).hideLoading();
inOrder.verify(mCollectionView, never()).hideLoadingNext();
}
@Test
public void loadNext_reloadFail() {
InOrder inOrder = inOrder(mCollectionView, mCollectionRepository);
doReturn(true).when(mCollectionRepository).hasNext();
doReturn(Observable.error(new RuntimeException())).when(mCollectionRepository).loadNext();
mCollectionPresenter.loadNext(true);
inOrder.verify(mCollectionRepository).reset();
getTestScheduler().advanceTimeBy(1, TimeUnit.SECONDS);
inOrder.verify(mCollectionView).showLoading();
inOrder.verify(mCollectionView).hideErrorRetry();
inOrder.verify(mCollectionView).hideLoading();
inOrder.verify(mCollectionView).showErrorRetry();
verify(mCollectionView, never()).clearItems();
}
@Test
public void loadNext_SuccessWithoutReload() {
InOrder inOrder = inOrder(mCollectionView, mCollectionRepository);
doReturn(true).when(mCollectionRepository).hasNext();
doReturn(Observable.just(ResponseFactory.STORY_COLLECTIONS)).when(mCollectionRepository)
.loadNext();
mCollectionPresenter.loadNext(false);
inOrder.verify(mCollectionRepository, never()).reset();
getTestScheduler().advanceTimeBy(1, TimeUnit.SECONDS);
inOrder.verify(mCollectionView).showLoadingNext();
inOrder.verify(mCollectionView).hideErrorRetry();
inOrder.verify(mCollectionView).hideLoadingNext();
inOrder.verify(mCollectionView).addItems(ResponseFactory.STORY_COLLECTIONS);
verify(mCollectionView, never()).clearItems();
}
@Test
public void loadNext_FailWithoutReload() {
InOrder inOrder = inOrder(mCollectionView, mCollectionRepository);
doReturn(true).when(mCollectionRepository).hasNext();
doReturn(Observable.error(new RuntimeException())).when(mCollectionRepository).loadNext();
mCollectionPresenter.loadNext(false);
inOrder.verify(mCollectionRepository, never()).reset();
getTestScheduler().advanceTimeBy(1, TimeUnit.SECONDS);
inOrder.verify(mCollectionView).showLoadingNext();
inOrder.verify(mCollectionView).hideErrorRetry();
inOrder.verify(mCollectionView).hideLoadingNext();
inOrder.verify(mCollectionView).showErrorRetry();
verify(mCollectionView, never()).clearItems();
}
} |
package cn.shizihuihui.ssweddingserver.service.impl;
import cn.shizihuihui.ssweddingserver.entity.Config;
import cn.shizihuihui.ssweddingserver.mapper.ConfigMapper;
import cn.shizihuihui.ssweddingserver.service.IConfigService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 小程序配置表 服务实现类
* </p>
*
* @author song
* @since 2019-10-19
*/
@Service
public class ConfigServiceImpl extends ServiceImpl<ConfigMapper, Config> implements IConfigService {
}
|
package utils.benchmarking;
/**
*
* @author Luis Garay
*/
public class MemoryUsage {
public static long memoryUsageInBytes() {
return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
}
public static long memoryUsageInKBytes() {
return memoryUsageInBytes() / 1024;
}
public static long memoryUsageInMBytes() {
return memoryUsageInKBytes() / 1024;
}
}
|
package no.ntnu.stud.ubilearn.server.service;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import no.ntnu.stud.ubilearn.server.models.User;
import com.google.common.base.Optional;
import com.yammer.metrics.annotation.Timed;
@Path("/user")
@Produces(MediaType.APPLICATION_JSON)
public class UserResource {
@GET
@Timed
public User getArticle(@QueryParam("user") Optional<String> name){
return new User("knut@gmail.com", "abcdefg");
}
@POST
}
|
package com.gymteam.tom.gymteam;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.gymteam.tom.gymteam.model.Gym;
import com.gymteam.tom.gymteam.model.Model;
import com.gymteam.tom.gymteam.model.User;
import com.gymteam.tom.gymteam.model.WorkoutInvite;
/**
* Created by Tom on 8/19/2017.
*/
public class InviteDetailsFragment extends Fragment {
public final static String ARG_POSITION = "position_details";
public final static String ARG_GYM_NAME = "gym_name_details";
public final static String ARG_USER_ID = "gym_user_id";
InviteDetailsActions mCallback;
WorkoutInvite selectedInvite;
boolean userIsTheCreator;
boolean userIsParticipating;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.invite_details_fragment, container, false);
Bundle args = getArguments();
Gym gym = Model.getInstance().gymsList.get(args.getString(ARG_GYM_NAME));
if(gym != null){
selectedInvite = gym.workoutInvites.get(args.getInt(ARG_POSITION));
}else {
//User user = Model.getInstance().usersList.get(args.getString(ARG_USER_ID));
User user = Model.getInstance().getActiveUser();
selectedInvite = user.invites.get(args.getInt(ARG_POSITION));
}
userIsParticipating = checkIfUserParticipating();
userIsTheCreator = checkIfUserIsTheCreator();
TextView textView = (TextView) view.findViewById(R.id.invite_title);
textView.setText(selectedInvite.getName());
TextView textView2 = (TextView) view.findViewById(R.id.at_gym_details);
textView2.setText(selectedInvite.getGymOfInvite().getName());
TextView textView3 = (TextView) view.findViewById(R.id.creator_name);
textView3.setText(selectedInvite.getCreatorOfInvite().getName());
TextView textView4 = (TextView) view.findViewById(R.id.description_invite);
textView4.setText(selectedInvite.getDescription());
Button participate_btn = (Button) view.findViewById(R.id.participate);
if(userIsParticipating) {
participate_btn.setText("Don't Participate");
}
participate_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(userIsParticipating){
dontParticipate();
} else{
participate();
}
}
});
Button back_to_list_btn = (Button) view.findViewById(R.id.back_to_list);
back_to_list_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mCallback.goBackToList();
}
});
return view;
}
public void participate(){
Log.d("PAR","par called ");
Model m = Model.getInstance();
m.participateUserInInvite(selectedInvite);
mCallback.goBackToList();
}
public void dontParticipate(){
Log.d("PAR","dont par called ");
Model m = Model.getInstance();
m.dontParticipateUserInInvite(selectedInvite);
mCallback.goBackToList();
}
private boolean checkIfUserIsTheCreator(){
Model m = Model.getInstance();
if(m.activeUser.getId().equals(this.selectedInvite.getCreatorOfInvite().getId())){
return true;
}
return false;
}
private boolean checkIfUserParticipating(){
Model m = Model.getInstance();
for(WorkoutInvite invite : m.activeUser.invites){
if(invite.getName().equals(selectedInvite.getName())){
return true;
}
}
return false;
}
public interface InviteDetailsActions{
public void goBackToList();
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
try {
mCallback = (InviteDetailsActions) getParentFragment();
} catch (ClassCastException e) {
throw new ClassCastException(getActivity().toString() +
"must implement ");
}
}
}
|
package com.proky.booking.dto;
import lombok.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.io.Serializable;
@Data
@NoArgsConstructor
public class UserDto implements Serializable {
private String id;
@NotBlank
@Size(min=2, max=50)
private String firstName;
@NotBlank
@Size(min=2, max=50)
private String lastName;
@NotBlank
@Email
private String email;
@NotBlank
@Size(min=6, max=80)
private String password;
private String newPassword;
private String userTypeId;
private boolean isAdministrator;
}
|
package com.test;
import com.test.base.Solution;
/**
* DFS
* 公式:f(n) = 1f(n) + 2f(n) + 3f(n) + 4f(n) + 5f(n) + 6f(n) + 7f(n) + 8f(n) + 9f(n)
* 函数f(n), 表示为:从左到右,剩余的最终的解(由于有值,因此,可以直接从0开始遍历)
*
* @author YLine
*
* 2018年11月13日 上午11:44:21
*/
public class SolutionA implements Solution
{
private static final char Empty = '.';
@Override
public void solveSudoku(char[][] board)
{
if (null == board || board.length == 0)
{
return;
}
solve(board);
}
private boolean solve(char[][] board)
{
for (int i = 0; i < board.length; i++)
{
for (int j = 0; j < board[i].length; j++)
{
if (Empty == board[i][j])
{
for (char num = '1'; num <= '9'; num++)
{
board[i][j] = num; // 尝试
if (isValid(board, i, j, num) && solve(board))
{
return true;
}
board[i][j] = Empty; // 回退
}
return false;
}
}
}
return true;
}
private boolean isValid(char[][] board, int i, int j, char c)
{
// check column
for (int row = 0; row < 9; row++)
{
if (i != row && board[row][j] == board[i][j])
{
return false;
}
}
// check row
for (int col = 0; col < 9; col++)
{
if (j != col && board[i][col] == board[i][j])
{
return false;
}
}
// check block
for (int row = i / 3 * 3; row < i / 3 * 3 + 3; row++)
{
for (int col = j / 3 * 3; col < j / 3 * 3 + 3; col++)
{
if ((i != row || col != j) && board[row][col] == board[i][j])
{
return false;
}
}
}
return true;
}
}
|
package com.customerservicecenter.model;
import javax.persistence.Id;
// TODO: Auto-generated Javadoc
/**
* The Enum UserType.
*/
public enum UserType {
/** The customer. */
@Id
CUSTOMER,
/** The operator. */
OPERATOR
}
|
package com.marvell.cmmb.manager;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import com.marvell.cmmb.resolver.ChannelItem;
import com.marvell.cmmb.aidl.LogMask;
public class VicePlayerManager {
private Context mContext;
private static VicePlayerManager sInstance;
private ArrayList<ChannelItem> mMainChannelList;
private ArrayList<ChannelItem> mViceChannelList;
private int mViceListPosition;
private static final String TAG = "VicePlayerManager";
private VicePlayerManager(Context context) {
mContext = context;
}
public static VicePlayerManager getInstance(Context context) {
if(sInstance == null) {
sInstance = new VicePlayerManager(context);
}
return sInstance;
}
public void init(ArrayList<ChannelItem> channelList) {
if(mMainChannelList == null) {
mMainChannelList = new ArrayList<ChannelItem>();
}
if(mViceChannelList == null) {
mViceChannelList = new ArrayList<ChannelItem>();
}
mMainChannelList = channelList;
}
public void resetViceChannelList(int freq) {
mViceChannelList.clear();
for(int i = 0; i < mMainChannelList.size(); i++) {
if(mMainChannelList.get(i).getFrequecy() == freq) {
mViceChannelList.add(mMainChannelList.get(i));
}
}
LogMask.LOGM(TAG, LogMask.LOG_APP_COMMON, LogMask.getLineInfo(), "vice channel list size is " + mViceChannelList.size(), LogMask.APP_COMMON);
}
public int getVicePosition(ChannelItem item) {
return mMainChannelList.indexOf(item);
}
public void setViceListPosition(ChannelItem item) {
mViceListPosition = mViceChannelList.indexOf(item);
}
public ChannelItem getCurrentChannel() {
return mViceChannelList.get(mViceListPosition);
}
public void switchToRight(boolean right) {
if(right) {
if(mViceListPosition < mViceChannelList.size() - 1) {
mViceListPosition = mViceListPosition + 1;
} else {
mViceListPosition = 0;
}
} else {
if(mViceListPosition > 0) {
mViceListPosition = mViceListPosition - 1;
} else {
mViceListPosition = mViceChannelList.size() - 1;
}
}
}
}
|
package work.binder.ui;
public class Constants {
public static final String DOT_ZIP = ".zip";
}
|
package com.designPatterns.iteratorPattern.productCollection;
public interface ProductIterator {
public boolean hasNext();
public void next();
public Product current();
}
|
package com.oa.bbs.dao;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.oa.base.dao.BaseDaoImpl;
import com.oa.bbs.form.Forum;
import com.oa.page.form.Page;
@Repository
public class ForumDaoImpl extends BaseDaoImpl<Forum> implements ForumDao {
@Override
public void addForum(Forum forum) {
this.add(forum);
}
@Override
public void updateForum(Forum forum) {
this.update(forum);
}
@Override
public void deleteForum(int forumId) {
this.delete(forumId);
}
@Override
public List<Forum> findAllForumByUserId(Integer userId) {
return this.list("From "+ getEntityClass().getName() + " where SUserId=?", new Object[]{userId});
}
@Override
public Forum findForumById(Integer forumId) {
return this.load(forumId);
}
@Override
public List<Forum> findForumByPage(Page page) {
return this.selectEntitysByPage(page);
}
@Override
public List<Forum> findForums() {
return this.findAll();
}
}
|
package fudan.database.project.dao.impl;
import fudan.database.project.dao.BedDAO;
import fudan.database.project.dao.DAO;
import fudan.database.project.entity.Bed;
import java.util.List;
public class BedDAOJdbcImpl extends DAO<Bed> implements BedDAO {
@Override
public List<Bed> getFreeBedsByArea(int areaId) {
String sql = "SELECT bedId, patientId, roomId FROM bed WHERE roomId in (SELECT roomId FROM room WHERE areaId = ?) AND patientId = ''";
return getForList(sql, areaId);
}
@Override
public List<Bed> getBedsByArea(int areaId) {
String sql = "SELECT bedId, patientId, roomId FROM bed WHERE roomId in (SELECT roomId FROM room WHERE areaId = ?)";
return getForList(sql, areaId);
}
@Override
public void updateByPatientId(String patientId, int bedId) {
String sql = "UPDATE bed SET patientId = ? WHERE bedId = ?";
update(sql, patientId, bedId);
}
@Override
public Bed getBedByPatientId(String patientId) {
String sql = "SELECT bedId, patientId, roomId FROM bed WHERE patientId = ?";
return get(sql, patientId);
}
}
|
package nesto.servicetest;
import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import nesto.base.util.LogUtil;
import nesto.base.widget.LineView;
public class MainActivity extends AppCompatActivity implements OnUpdateTimeListener {
public static final String KEY = "save";
private TimeReceiver receiver;
@BindView(R.id.time_from_callback) TextView timeFromCallback;
@BindView(R.id.time_from_receiver) TextView timeFromReceiver;
@BindView(R.id.lineView) LineView lineView;
@BindView(R.id.switcher) Switch switcher;
private boolean isServiceBinded = false;
public static final int ID = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
receiver = new TimeReceiver();
if (savedInstanceState != null) {
String save = savedInstanceState.getString(KEY);
if (save != null) {
Toast.makeText(this, save, Toast.LENGTH_SHORT).show();
}
}
setSwitcher();
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
hideNotification();
}
@SuppressLint("NewApi")
private void showNotification() {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification.Builder(this)
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(false)
.setContentText("content")
.setContentTitle("from activity")
.setSmallIcon(R.mipmap.ic_launcher)
.setOngoing(true)
.setVibrate(new long[]{100, 100, 200, 300, 500, 800, 1300})
.setDefaults(Notification.DEFAULT_ALL)
.setContentIntent(PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), PendingIntent.FLAG_CANCEL_CURRENT))
.build();
notificationManager.notify(ID, notification);
}
private void hideNotification() {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(ID);
}
private void setSwitcher() {
switcher.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
lineView.startAnim();
showNotification();
} else {
hideNotification();
lineView.stopAnim();
}
}
});
}
@Override
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction(TimeReceiver.UPDATE_TIME);
registerReceiver(receiver, filter);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(KEY, "saved");
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}
@OnClick(R.id.start)
void start() {
Intent startIntent = new Intent(this, SimpleService.class);
startService(startIntent);
startService(new Intent(this, LongRunService.class));
}
@OnClick(R.id.stop)
void stop() {
Intent stopIntent = new Intent(this, SimpleService.class);
stopService(stopIntent);
AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent newIntent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, newIntent, 0);
manager.cancel(pendingIntent);
stopService(new Intent(this,LongRunService.class));
}
@OnClick(R.id.bind)
void bind() {
Intent startIntent = new Intent(this, SimpleService.class);
bindService(startIntent, connection, BIND_AUTO_CREATE);
}
@OnClick(R.id.unbind)
void unbind() {
if (isServiceBinded) {
unbindService(connection);
isServiceBinded = false;
}
}
private ServiceConnection connection = new ServiceConnection() {
/**
* onServiceDisconnected is only called in extreme situations (crashed / killed).
*/
@Override
public void onServiceDisconnected(ComponentName name) {
LogUtil.d("onServiceDisconnected " + name.flattenToString());
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
SimpleService.SimpleBinder binder = (SimpleService.SimpleBinder) service;
binder.startDoingTaskA();
binder.getService().setListener(MainActivity.this);
binder.getTime();
isServiceBinded = true;
}
};
@Override
public void updateTime(final String time) {
runOnUiThread(new Runnable() {
@Override
public void run() {
MainActivity.this.timeFromCallback.setText(time);
}
});
}
public class TimeReceiver extends BroadcastReceiver {
public static final String UPDATE_TIME = "UPDATE_TIME";
@Override
public void onReceive(Context context, Intent intent) {
String time = intent.getStringExtra("time");
timeFromReceiver.setText(time);
}
}
}
|
package moe.tristan.easyfxml.util;
import static javafx.scene.input.MouseButton.PRIMARY;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.Test;
import moe.tristan.easyfxml.test.FxNodeTest;
public class ClickableTextTest extends FxNodeTest {
@Test
public void shouldExecuteActionGiven() {
final AtomicBoolean called = new AtomicBoolean();
final ClickableText clickableText = new ClickableText("Sample text", () -> called.set(true));
withNodes(clickableText)
.willDo(() -> clickOn(clickableText, PRIMARY))
.andAwaitFor(called::get);
assertThat(called).isTrue();
}
}
|
package algorithms.graph.practice;
import algorithms.graph.Graph;
import algorithms.graph.GraphFactory;
import algorithms.graph.PathLogUtil;
import algorithms.graph.process.Paths;
import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.Test;
/**
* Created by Chen Li on 2018/5/27.
*/
@Slf4j
public class DepthFirstPathsTest {
@Test
public void pathTest() {
Graph graph = new GraphImpl();
GraphFactory gf = new GraphFactory();
gf.loadGraph(graph, "algorithms/graph/practice/directed/directedNoCycle14.txt");
Paths path = new DepthFirstPaths();
path.init(graph, 0);
doTest(path, 12, true);
doTest(path, 13, false);
}
@Test
public void directedTest() {
Graph graph = new DigraphImpl();
GraphFactory gf = new GraphFactory();
gf.loadGraph(graph, "algorithms/graph/practice/directed/directedNoCycle13.txt");
Paths path = new DepthFirstPaths();
path.init(graph, 0);
doTest(path, 12, true);
doTest(path, 10, true);
doTest(path, 9, true);
doTest(path, 8, true);
//unreachable
Paths pathFrom11 = new DepthFirstPaths();
pathFrom11.init(graph, 11);
doTest(pathFrom11, 12, false);
doTest(pathFrom11, 6, true);
doTest(pathFrom11, 3, false);
}
private void doTest(Paths path, int vertex, boolean expectedHasPath) {
Assert.assertEquals(expectedHasPath, path.hasPathTo(vertex));
if (expectedHasPath) {
log.info("from {} path to {} is : {}", path.from(), vertex, PathLogUtil.pathToString(path.pathTo(vertex)));
} else {
log.info("from {} NO path to {}", path.from(), vertex);
}
}
}
|
package com.apap.igd.controller;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.apap.igd.service.DetailPenangananService;
import com.apap.igd.service.KebutuhanObatService;
import com.apap.igd.service.PenangananPasienService;
import com.apap.igd.model.PenangananPasienModel;
import com.apap.igd.model.TagihanPasienModel;
import com.apap.igd.rest.BillingRest;
import com.apap.igd.service.BillingPasienService;
/**
* TagihanPasienController
* @author debora
*/
@Controller
public class BillingPasienController {
@Autowired
private KebutuhanObatService kebutuhanObatService;
@Autowired
private PenangananPasienService penangananPasienService;
@Autowired
private DetailPenangananService detailPenangananService;
@Autowired
private BillingPasienService billingService;
@RequestMapping(value="/pasien/tagihan/lihat", method = RequestMethod.GET)
private String lihatTagihan(Model model) {
List<TagihanPasienModel> listOfTagihan = billingService.getListTagihan();
model.addAttribute("listOfTagihan", listOfTagihan);
return "lihat-tagihan";
}
}
|
package com.zxt.compplatform.formengine.entity.view;
import com.zxt.compplatform.formengine.entity.database.Dictionary;
import com.zxt.framework.common.entity.BasicEntity;
/**
* Title: CacheInterface Description: 界面控件 Create DateTime: 2010-9-27
*
* @author xxl
* @since v1.0
*
*/
public class EditMode extends BasicEntity {
/**
* 主键
*/
private String id;
/**
* 类型
*/
private String type;
/**
*
*/
private String reminder;
/**
* 数据字典数据
*/
private Dictionary data;
/**
* 验证规则
*/
private ValidateRule validateRule;//
/**
* 是否存在sql
*/
private String isExistSQL;
/**
* 日期
*/
private String compDate;
/**
*
*/
private String compCon;
/**
* 指数
*/
private String compIndex;
/**
* 数据源是否存在
*/
private String isExistDBSource;
/**
* 是否为必填项,默认为不是必填
*/
private Boolean required = new Boolean(false);//
/**
* 数据库最大长度
*/
private String maxLength;//
/**
* 最小长度
*/
private String minLength;
/**
* 用户设定最大长度
*/
private String maxLength2;//
private String tdWidth;//
private String textWidth;//
public String getMaxLength2() {
return maxLength2;
}
public void setMaxLength2(String maxLength2) {
this.maxLength2 = maxLength2;
}
public String getMinLength() {
return minLength;
}
public void setMinLength(String minLength) {
this.minLength = minLength;
}
public String getCompIndex() {
return compIndex;
}
public void setCompIndex(String compIndex) {
this.compIndex = compIndex;
}
public String getCompCon() {
return compCon;
}
public void setCompCon(String compCon) {
this.compCon = compCon;
}
public String getCompDate() {
return compDate;
}
public void setCompDate(String compDate) {
this.compDate = compDate;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Dictionary getData() {
return data;
}
public void setData(Dictionary data) {
this.data = data;
}
public ValidateRule getValidateRule() {
return validateRule;
}
public void setValidateRule(ValidateRule validateRule) {
this.validateRule = validateRule;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getReminder() {
return reminder;
}
public void setReminder(String reminder) {
this.reminder = reminder;
}
public Boolean getRequired() {
return required;
}
public void setRequired(Boolean required) {
this.required = required;
}
public String getMaxLength() {
return maxLength;
}
public void setMaxLength(String maxLength) {
this.maxLength = maxLength;
}
public String getIsExistSQL() {
return isExistSQL;
}
public void setIsExistSQL(String isExistSQL) {
this.isExistSQL = isExistSQL;
}
public String getIsExistDBSource() {
return isExistDBSource;
}
public void setIsExistDBSource(String isExistDBSource) {
this.isExistDBSource = isExistDBSource;
}
public String getTdWidth() {
return tdWidth;
}
public void setTdWidth(String tdWidth) {
this.tdWidth = tdWidth;
}
public String getTextWidth() {
return textWidth;
}
public void setTextWidth(String textWidth) {
this.textWidth = textWidth;
}
}
|
package renderEngine;
import java.util.HashMap;
import java.util.Map;
import org.lwjgl.util.vector.Matrix4f;
import org.lwjgl.util.vector.Vector3f;
import colladaLoader.AnimationData;
import colladaLoader.ColladaLoader;
import colladaLoader.JointTransformData;
import colladaLoader.KeyFrameData;
import models.animation.JointTransform;
import toolbox.Quaternion;
public class AnimationCreator {
public static Animation loadAnimation(String colladaFileName){
AnimationData animationData = ColladaLoader.loadColladaAnimation("/res/" + colladaFileName);
KeyFrame[] frames = new KeyFrame[animationData.keyFrames.length];
int pointer = 0;
for(KeyFrameData frameData : animationData.keyFrames){
frames[pointer++] = createKeyFrame(frameData);
}
return new Animation(animationData.lengthSeconds, frames);
}
private static KeyFrame createKeyFrame(KeyFrameData data){
Map<String, JointTransform> map = new HashMap<String, JointTransform>();
for(JointTransformData jointData : data.jointTransforms){
JointTransform jointTransform = createTransform(jointData);
map.put(jointData.jointNameId, jointTransform);
}
return new KeyFrame(data.time, map);
}
private static JointTransform createTransform(JointTransformData data){
Matrix4f mat = data.jointLocalTransform;
Vector3f translation = new Vector3f(mat.m30, mat.m31, mat.m32);
Quaternion rotation = new Quaternion(mat);
return new JointTransform(translation, rotation);
}
}
|
package pl.pawel.weekop.controller;
import pl.pawel.weekop.model.Discovery;
import pl.pawel.weekop.model.User;
import pl.pawel.weekop.model.Vote;
import pl.pawel.weekop.model.VoteType;
import pl.pawel.weekop.service.DiscoveryService;
import pl.pawel.weekop.service.VoteService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/*
example URL : /vote?discovery_di=3&vote=Vote.UP
*/
@WebServlet("/vote")
public class VoteServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
User loggedUser = (User) request.getSession().getAttribute("user");
if (loggedUser != null)
{
VoteType voteType = VoteType.valueOf(request.getParameter("vote"));
long userId = loggedUser.getId();
long discovery_id = Long.parseLong(request.getParameter("discovery_id"));
System.out.println(userId + " " + discovery_id + " " + voteType);
updateVote(userId, discovery_id, voteType);
}
response.sendRedirect(request.getContextPath() +"/");
}
private void updateVote(long userId, long discovery_id, VoteType voteType)
{
VoteService voteService = new VoteService();
Vote existingVote =voteService.getVoteByDiscoveryUserId(discovery_id,userId);
//System.out.println("Existing vote "+ existingVote);
Vote updatedVote = voteService.addOrUpdateVote(discovery_id,userId ,voteType);
//System.out.println("updated vote "+ updatedVote);
if (existingVote != updatedVote && !updatedVote.equals(existingVote))
{
updateDiscovery(discovery_id, existingVote, updatedVote);
System.out.println("Update discovery");
}
}
private void updateDiscovery(long discovery_id, Vote oldVote, Vote newVote)
{
DiscoveryService service = new DiscoveryService();
Discovery discoveryById = service.getDiscoveryById(discovery_id);
//System.out.println("Discovery By Id: "+ discovery_id );
Discovery updatedDiscovery = null;
if (oldVote == null && newVote != null)
{
updatedDiscovery = addDiscoveryVote(discoveryById, newVote.getVoteType());
}
else if (oldVote != null && newVote != null)
{
updatedDiscovery = removeDiscovery(discoveryById, oldVote.getVoteType());
updatedDiscovery = addDiscoveryVote(discoveryById, newVote.getVoteType());
}
service.updateDiscovery(updatedDiscovery);
}
private Discovery addDiscoveryVote(Discovery discovery, VoteType voteType)
{
Discovery discoveryCopy = new Discovery(discovery);
if (voteType == VoteType.VOTE_UP)
{
discoveryCopy.setUpVote(discoveryCopy.getUpVote() + 1);
}
else if (voteType == VoteType.VOTE_DOWN)
{
discoveryCopy.setDownVote(discoveryCopy.getDownVote() + 1);
}
return discoveryCopy;
}
private Discovery removeDiscovery(Discovery discovery, VoteType voteType)
{
Discovery discoveryCopy = new Discovery(discovery);
if (voteType == VoteType.VOTE_DOWN)
{
discoveryCopy.setDownVote(discovery.getDownVote() -1);
}
else if (voteType == VoteType.VOTE_UP)
{
discoveryCopy.setUpVote(discovery.getUpVote() -1);
}
return discoveryCopy;
}
}
|
package com.sourav.fcm.fcmservices;
import com.google.firebase.messaging.FirebaseMessagingService;
/**
* Created by sourav on 5/6/16.
*/
public class FCMReceiver extends FirebaseMessagingService {
}
|
package com.hellofresh.challenge.pages.pageObjects;
import com.hellofresh.challenge.pages.BasePage;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
/**
* Category Items Page object
*/
public class CategoryItemsPage extends BasePage {
private static final Logger logger = LogManager.getLogger(CategoryItemsPage.class);
private By categoryLink = By.className("cat-name");
// Locator defined as String to use it flexibly for multiple elements.
private String productNameLink = "//a[@title='name_placeholder'][@class='product-name']";
public CategoryItemsPage(WebDriver driver) {
super(driver);
this.driver = driver;
urlFragment = "my-account";
getElementByVisibility(categoryLink);
}
/**
* This method can be used to select any product visible on the page
* by product name
* @param name product name String
*/
public void selectProduct(String name) {
logger.info("Selecting product: " + name);
productNameLink = productNameLink.replace("name_placeholder", name);
getElementByVisibility(By.xpath(productNameLink)).click();
}
}
|
/**
* Copyright (C) 2008 Atlassian
*
* 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.atlassian.theplugin.idea.util.memoryvfs;
import com.intellij.openapi.components.ApplicationComponent;
import com.intellij.openapi.vfs.DeprecatedVirtualFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
/**
* A file system for content that resides only in memory.
*
* @author Steve Chaloner
*/
public final class PlainTextMemoryVirtualFileSystem extends DeprecatedVirtualFileSystem implements ApplicationComponent {
/**
* The name of the component.
*/
private static final String COMPONENT_NAME = "PlainText-MemoryFileSystem";
@NonNls
public String getProtocol() {
return Constants.PLAINTEXT_PROTOCOL;
}
@Nullable
public VirtualFile findFileByPath(@NotNull @NonNls String s) {
return null;
}
public void refresh(boolean b) {
}
@Nullable
public VirtualFile refreshAndFindFileByPath(String s) {
return null;
}
protected void deleteFile(Object o, VirtualFile virtualFile) throws IOException {
throw new UnsupportedOperationException("method deleteFile not implemented");
}
protected void moveFile(Object o, VirtualFile virtualFile, VirtualFile virtualFile1) throws IOException {
throw new UnsupportedOperationException("method moveFile not implemented");
}
protected void renameFile(Object o, VirtualFile virtualFile, String s) throws IOException {
throw new UnsupportedOperationException("method renameFile not implemented");
}
protected VirtualFile createChildFile(Object o, VirtualFile virtualFile, String s) throws IOException {
throw new UnsupportedOperationException("method createChildFile not implemented");
}
protected VirtualFile createChildDirectory(Object o, VirtualFile virtualFile, String s) throws IOException {
throw new UnsupportedOperationException("method createChildDirectory not implemented");
}
protected VirtualFile copyFile(Object o, VirtualFile virtualFile, VirtualFile virtualFile1, String s) throws IOException {
throw new UnsupportedOperationException("method copyFile not implemented");
}
private static final PlainTextMemoryVirtualFileSystem INSTANCE = new PlainTextMemoryVirtualFileSystem();
public static PlainTextMemoryVirtualFileSystem getInstance() {
return INSTANCE;
}
public void disposeComponent() {
}
@NonNls
@NotNull
public String getComponentName() {
return COMPONENT_NAME;
}
public void initComponent() {
}
} |
package Problem_10942;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
static int[] arr;
static int[][] dp;
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
arr = new int[N+1];
dp = new int[N+1][N+1];
StringTokenizer st = new StringTokenizer(br.readLine());
for(int i = 1; i<=N; i++) { arr[i] = Integer.parseInt(st.nextToken()); }
for(int i = 0 ; i<=N; i++) Arrays.fill(dp[i], -1);
int M = Integer.parseInt(br.readLine());
String tmp;
StringBuilder sb = new StringBuilder();
while(M-- > 0) {
tmp = br.readLine();
sb.append(answer(Integer.parseInt(tmp.split(" ")[0]),Integer.parseInt(tmp.split(" ")[1]))).append("\n");
}
System.out.print(sb.toString());
}
public static int answer(int S, int E) {
if(dp[S][E] > 0) return dp[S][E];
if(E-S == 1) return dp[S][E] = arr[S] == arr[E] ? 1 : 0;
if(S == E) return dp[S][E] = 1;
if(arr[S] != arr[E]) return dp[S][E] = 0;
dp[S][E] = answer(S+1,E-1);
return dp[S][E];
}
}
|
import java.net.*;
import java.nio.*;
public class EncapsulationACK
{
private int dataOrAck; // data=0, ack=1;
private int pOrnACK;//negtive=0, positive=1:
private int fileType; //txt=0, PDF=1;
private int sequenceNumber; //after convert to byte, need byte[4]
private byte checksum = (byte)0x00;//after checksum, replace checksum result to this byte
private byte[] filename=new byte[60];//filename is 60 byte long
//constructor
public EncapsulationACK (int dataOrAck, int pOrnACK, int fileType,
int sequenceNumber,
byte[]filename)
{
if(dataOrAck==0||dataOrAck==1)
this.dataOrAck=dataOrAck;
if(pOrnACK==0||pOrnACK==1)
this.pOrnACK=pOrnACK;
if(fileType==0||fileType==1)
this.fileType=fileType;
this.sequenceNumber=sequenceNumber;
for(int j=0;j<filename.length;j++)
this.filename[j]=filename[j];
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++=
public byte[] getFragment()
{
//total fragment long
byte[] fragment=new byte[65525];
//fragment[1]: include data/ACk, transferType,fileType
byte dOrA =(byte)dataOrAck;
dOrA=(byte)(dOrA<<6);
byte pOrn=(byte)pOrnACK;
pOrn=(byte)(pOrn<<4);
byte fType=(byte)fileType;
fragment[0]=(byte)((dOrA^pOrn)^fType);
//convert sequenceNumber to byte[4]
byte convertSeqNo[]=getByteArrayFromInteger(sequenceNumber);
fragment[1]=convertSeqNo[0];
fragment[2]=convertSeqNo[1];
fragment[3]=convertSeqNo[2];
fragment[4]=convertSeqNo[3];
/*
*filename is 60 byte long.
first filename fragment is fragment[5];
last filename fragment is fragment[64];
*/
for(int p=0;p<filename.length;p++)
fragment[p+5]=filename[p];
/*
*total fragment is 65525.
*total head fragment is 82.
*data fragment is 65525-82= 65443 byte.(This case means all data fragments are used)
first data fragment is fragment[81];
last data fragment is fragment[65523];
*/
//fragment[65524] store checksum;
CRC8 crc8 = new CRC8();
byte crc= crc8.checksum(fragment);
fragment[65524]=crc;
//System.out.println("fragment[65524]: "+Integer.toBinaryString(fragment[65524]&0x000000ff));
return fragment;
}
//==============================================================================================
private byte[] getByteArrayFromInteger(int intValue)
{
ByteBuffer wrapped = ByteBuffer.allocate(4);
wrapped.putInt(intValue);
byte[] byteArray = wrapped.array();
return byteArray;
}
private byte[] getByteArrayFromDouble(double doubleValue)
{
byte[] byteArray = new byte[8];
long lng = Double.doubleToLongBits(doubleValue);
for(int i = 0; i < 8; i++)
byteArray[i] = (byte)((lng >> ((7 - i) * 8)) & 0xff);
return byteArray;
}
}//the end of class |
package Chapter2;
import java.util.*;
public class ScannerInput {
/*scan.nextInt gives all itegers.*/
/*array.length and arraylist.size();*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
/*int a = scan.nextInt();
scan.nextLine();
int b=scan.nextInt();
scan.nextLine();
int c=scan.nextInt();*/
int[] arr=new int[3];
for(int i=0;i<arr.length;i++)
{
arr[i]=scan.nextInt();
System.out.println(arr[i]);
}
// Complete this line
// Complete this line
// System.out.println(a);
// System.out.println(b);
// System.out.println(c);
// Complete this line
// Complete this line
}
}
/*the scan.next() gives one word. scan.nextLine gives one line. scan.hasDouble() gives the double in the stdin*/
class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
double d=scan.nextDouble();
String s=null;
while(scan.hasNext()){
s=scan.nextLine();
}
// Write your code here.
System.out.println("String: " + s);
System.out.println("Double: " + d);
System.out.println("Int: " + i);
}
}
|
package com.itcia.itgoo.dto;
import java.util.List;
import org.apache.ibatis.type.Alias;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
//@Getter@Setter
@NoArgsConstructor
@AllArgsConstructor
@Alias("recent")
@Data
@Accessors(chain=true)
public class Recent {
private int dogid;
private String id;
private int recentid;
private String message;
private String dogname;
private List<String> recentpic;
private String recentthumb;
}
|
package arcs.api;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import javax.inject.Inject;
public class ParticleExecutionContextImpl implements ParticleExecutionContext {
private ParticleLoader particleLoader;
private PortableJsonParser jsonParser;
private ArrayList<Particle> particles;
private HandleFactory handleFactory;
@Inject
public ParticleExecutionContextImpl(
PortableJsonParser jsonParser, ParticleLoader particleLoader, HandleFactory handleFactory) {
this.jsonParser = jsonParser;
this.particleLoader = particleLoader;
this.particles = new ArrayList<>();
this.handleFactory = handleFactory;
}
@Override
public Particle instantiateParticle(
String particleId,
ParticleSpec spec,
Map<String, StorageProxy> proxies,
IdGenerator idGenerator) {
// TODO: use the full spec.implPath, instead of the filename.
Particle particle =
particleLoader
.loadParticle(spec.getFileName())
.flatMap(x -> Optional.ofNullable(x.createParticle()))
.orElse(null);
particle.setId(particleId);
initializeParticle(particle, spec, proxies, idGenerator);
return particle;
}
@Override
public void initializeParticle(
Particle particle,
ParticleSpec spec,
Map<String, StorageProxy> proxies,
IdGenerator idGenerator) {
Objects.requireNonNull(particle).setSpec(spec);
particle.setJsonParser(jsonParser);
this.particles.add(particle);
Map<String, Handle> handleMap = new HashMap<>();
Map<Handle, StorageProxy> registerMap = new HashMap<>();
for (String proxyName : proxies.keySet()) {
StorageProxy storageProxy = proxies.get(proxyName);
Handle handle =
this.handleFactory.handleFor(
storageProxy,
idGenerator,
proxyName,
particle.getId(),
spec.isInput(proxyName),
spec.isOutput(proxyName));
handleMap.put(proxyName, handle);
registerMap.put(handle, storageProxy);
}
particle.setHandles(handleMap);
for (Handle handle : registerMap.keySet()) {
StorageProxy storageProxy = registerMap.get(handle);
storageProxy.register(particle, handle);
}
}
}
|
package io.fabiandev.validator;
import io.fabiandev.validator.contracts.Request;
import io.fabiandev.validator.core.MapRequest;
import org.junit.Before;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.*;
public class MapRequestTest
{
private Request request;
private Request emptyRequest;
@Before
public void createMapRequest()
{
Map<String, String> map = new HashMap<String, String>();
map.put("test1", "value1");
map.put("test2", "value2");
this.request = new MapRequest(map);
this.emptyRequest = new MapRequest();
}
@Test
public void testGet()
{
String value1 = this.request.get("test1");
String value2 = this.request.get("test2");
String value3 = this.request.get("test3");
String value4 = this.emptyRequest.get("test");
assertEquals("value1", value1);
assertEquals("value2", value2);
assertEquals(null, value3);
assertEquals(null, value4);
}
@Test
public void testContains()
{
assertTrue(this.request.contains("value1"));
assertTrue(this.request.contains("value2"));
assertFalse(this.request.contains("value3"));
assertFalse(this.emptyRequest.contains("value"));
}
@Test
public void testContainsKey()
{
assertTrue(this.request.containsKey("test1"));
assertTrue(this.request.containsKey("test2"));
assertFalse(this.request.containsKey("test3"));
assertFalse(this.emptyRequest.containsKey("test"));
}
@Test
public void testIsEmpty()
{
assertFalse(this.request.isEmpty());
assertTrue(this.emptyRequest.isEmpty());
}
@Test
public void testSize()
{
assertEquals(2, this.request.size());
assertEquals(0, this.emptyRequest.size());
}
@Test
public void testPut()
{
this.request.put("test3", "value3");
this.emptyRequest.put("test", "value");
this.request.containsKey("test3");
this.request.contains("value3");
this.emptyRequest.containsKey("test");
this.emptyRequest.contains("value");
}
@Test
public void testClear()
{
this.request.clear();
this.emptyRequest.clear();
assertTrue(this.request.isEmpty());
assertTrue(this.emptyRequest.isEmpty());
}
}
|
package practice;
import java.util.Arrays;
public class ReverseAWordInAString {
public static void main(String []args)
{
String str = "I am Venkatesh Chirunomula , Programming is good";
String[] split = str.split(" ");
System.out.println(split[5]);
String newString = split[5];
String ReveredString ="";
for(int i =newString.length()-1; i >=0; i--) {
ReveredString = ReveredString+newString.charAt(i);
}
System.out.println(ReveredString);
split[5]= ReveredString;
System.out.println(Arrays.toString(split));
}
}
|
package com.delrima.webgene.arch.client.interfaces;
/**
* <code><B>View<code><B>
* <p>
* Marker interface used to indicate a "view" (i.e. page) in a GWT application
* </p>
*
* @author bhavesh.thakker@ihg.com
* @since Sep 22, 2008
*
*/
public interface View {
/**
* <p>
* Pre-process before displaying widget
* </p>
*
* @return
*/
void process();
}
|
package com.company;
class MyArraySizeException extends Exception {
int someLength;
int length;
public MyArraySizeException(String s) {
super(s);
}
}
|
package com.codekarma.service.Impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.codekarma.domain.Item;
import com.codekarma.domain.Member;
import com.codekarma.domain.ResourceRequest;
import com.codekarma.domain.ResourceStatus;
import com.codekarma.domain.Transaction;
import com.codekarma.domain.TranscationStatus;
import com.codekarma.exception.InvalidOperationException;
import com.codekarma.repository.ItemsRepository;
import com.codekarma.repository.MemberRepositoryImp2;
import com.codekarma.repository.RequestRepository;
import com.codekarma.repository.TransactionRepository;
import com.codekarma.service.ResourcesService;
@Service
@Transactional
public class ResourceServiceImpl implements ResourcesService {
@Autowired
ItemsRepository itemsRepository;
// @Autowired
// CategoryRepository categoryRepository;
// @Autowired
// BuildingRepository buildingRepository;
// @Autowired
// RoomRepository roomRepository;
@Autowired
RequestRepository requestRepository;
@Autowired
MemberRepositoryImp2 memberRepository;
@Autowired
TransactionRepository transactionRepository;
public Item addNewItem(Item item) {
// updating categories
// Category category;
// if (item.getCategoryItem().getId() != -10) {
// category = categoryRepository.findOne(item.getCategoryItem()
// .getId());
// } else {
// category = categoryRepository.getCategoryByName(item
// .getCategoryItem().getName());
// }
// if (category == null) {
// category = new Category();
// category.setName(item.getCategoryItem().getName());
// category.setLstCategoryItems(new ArrayList<Item>());
// }
// category.getLstCategoryItems().add(item);
// item.setCategoryItem(category);
//
// //updating room
// Building building = buildingRepository.findByBuildingName(item.getRoomItem().getBuilding().getName());
// Room room = roomRepository.findByRoomName(item.getRoomItem().getName());
// if(building == null){
// building = new Building();
// building.setName(item.getRoomItem().getBuilding().getName());
// building.setLstRoomInBuilding(new ArrayList<Room> ());
// building.setDescription(" ");
// }
// if(room == null){
// room = new Room();
// room.setName(item.getRoomItem().getName());
// room.setLstItemsInRoom(new ArrayList<Item>());
// room.setLstMemberInRoom(new ArrayList<Member>());
// room.setLstTranscationRoom(new ArrayList<Transaction>());
// room.setStatus(ResourceStatus.AVAILABLE);
// }
// room.setBuilding(building);
// if(!building.getLstRoomInBuilding().contains(room)){
// building.getLstRoomInBuilding().add(room);
// }
// room.getLstItemsInRoom().add(item);
//
return itemsRepository.save(item);
}
@Override
public List<Item> getItems(int numberOfItems) {
Iterable<Item> items = itemsRepository.findAll();
List<Item> lstItem = new ArrayList<Item>();
for(Item i: items){
if(lstItem.size() > numberOfItems){
break;
}
lstItem.add(i);
}
return lstItem;
}
@Override
public Item getById(Long id) {
return itemsRepository.findOne(id);
}
@Override
public ResourceRequest addNewRequest(Long itemId,String username) {
ResourceRequest previousRequest = requestRepository.findByItemId(itemId);
if(previousRequest != null){
throw new InvalidOperationException("", "The resource was already requested (may be by other user).");
}
ResourceRequest request = new ResourceRequest();
Item item = itemsRepository.findOne(itemId);
request.setItem(item);
request.setRequestdate(new Date());
Member member = memberRepository.getMemberByUsername(username);
request.setMember(member);
ResourceRequest saved = requestRepository.save(request);
return saved;
}
@Override
public List<ResourceRequest> getResourceRequests() {
List<ResourceRequest> requests = new ArrayList<ResourceRequest>();
for(ResourceRequest r: requestRepository.findAll()){
requests.add(r);
}
return requests;
}
@PreAuthorize(value="hasRole('ADMIN')")
public void grantRequestForRequestId(Integer requestId) {
ResourceRequest request = requestRepository.findOne(requestId);
Member member = request.getMember();
Item item = request.getItem();
Transaction transaction = new Transaction();
transaction.setAssignDate(new Date());
transaction.setTransactionStatus(TranscationStatus.ACTIVE);
//transactionRepository.save(transaction);
transaction.setItemTranscation(item);
transaction.setMemberTranscation(member);
transaction.setRoomTanscation(null);
item.setStatus(ResourceStatus.OCCUPIED);
item.setMemberItem(member);
item.getLstTranscationItem().add(transaction);
member.getLstMemberItems().add(item);
member.getLstTranscationMember().add(transaction);
transactionRepository.save(transaction);
itemsRepository.save(item);
memberRepository.save(member);
requestRepository.delete(request);
}
@PreAuthorize(value="hasRole('ADMIN')")
public void discardRequestForRequestId(Integer requestId) {
requestRepository.delete(requestId);
}
}
|
package com.example.bigasslayout.bigasslayout;
import android.app.Application;
import android.content.Context;
import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;
/**
* Created by demo on 5/24/15.
*/
//added an application class to install Leak Canary
public class AmiAGoat extends Application {
//LeakCanary reference watcher
public static RefWatcher getRefWatcher(Context context) {
AmiAGoat application = (AmiAGoat) context.getApplicationContext();
return application.refWatcher;
}
private RefWatcher refWatcher;
@Override
public void onCreate() {
super.onCreate();
//on app creation - turn on leakcanary
refWatcher = LeakCanary.install(this);
}
}
|
package DAOTest;
import java.util.List;
import org.junit.jupiter.api.Test;
import com.qst.dms.dao.impl.ImplMatchedTransportDao;
import com.qst.dms.entity.MatchedTransport;
public class ImplMatchedTransportDaoTest {
/**
* 测试添加新的对象
*/
@Test
public void testSave(){
ImplMatchedTransportDao dao = new ImplMatchedTransportDao();
// dao.save(1,3,7);
}
/**
* 测试 删除对象
*/
@Test
public void testRemove(){
ImplMatchedTransportDao dao = new ImplMatchedTransportDao();
System.out.println(dao.remove(1, 3,7));
}
/**
* 测试获取单个对象
*/
@Test
public void testGet(){
ImplMatchedTransportDao dao = new ImplMatchedTransportDao();
MatchedTransport t = dao.get(1,2,3);
System.out.println(t);
}
/**
* 测试获取多个对象
*/
@Test
public void testGetAll(){
ImplMatchedTransportDao dao = new ImplMatchedTransportDao();
List<MatchedTransport> list =dao.getAll();
for(MatchedTransport t :list){
System.out.println(t);
}
}
}
|
package com.cm.caption3;
public class WxMediaMessage extends ReqBaseMsg {
public WxMediaMessage(){ }
public String media_id;
public String mediaType;
public String title;
public String description;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
protected String safe;
public String getMedia_id() {
return media_id;
}
public String getMediaType() {
return mediaType;
}
public void setMediaType(String mediaType) {
this.mediaType = mediaType;
}
public void setMedia_id(String media_id) {
this.media_id = media_id;
}
public String getSafe() {
return safe;
}
public void setSafe(String safe) {
this.safe = safe;
}
public WxMediaMessage(String touser, String toparty, String totag, String msgtype, String mediaType, String agentid, String media_id, String safe){
super();
super.touser = touser;
super.toparty= toparty;
super.totag = totag;
super.agentid = agentid;
super.msgtype = msgtype;
this.media_id = media_id;
this.safe = safe;
this.mediaType = mediaType;
}
public WxMediaMessage(String touser, String toparty, String totag,
String msgtype, String mediaType, String agentid,
String media_id,
String title,
String description,
String safe){
super();
super.touser = touser;
super.toparty= toparty;
super.totag = totag;
super.agentid = agentid;
super.msgtype = msgtype;
this.media_id = media_id;
this.title = title;
this.description = description;
this.safe = safe;
this.mediaType = mediaType;
}
public String toJsonStr() {
StringBuffer jsonStr = new StringBuffer("{");
StringBuffer str_tmp = new StringBuffer("");
if(null!=touser&&!"".equals(touser)){
if(!"".equals(str_tmp.toString())){
str_tmp.append(",");
}
str_tmp.append("\"touser\": \""+touser+"\"");
}
if(null!=toparty&&!"".equals(toparty)){
if(!"".equals(str_tmp.toString())){
str_tmp.append(",");
}
str_tmp.append("\"toparty\": \""+toparty+"\"");
}
if(null!=totag&&!"".equals(totag)){
if(!"".equals(str_tmp.toString())){
str_tmp.append(",");
}
str_tmp.append("\"totag\": \""+totag+"\"");
}
if(null!=msgtype&&!"".equals(msgtype)){
//去除空格
msgtype=msgtype.trim();
//判断是否加逗号
if(!"".equals(str_tmp.toString())){
str_tmp.append(",");
}
str_tmp.append("\"msgtype\": \""+msgtype+"\"");
//图片
if(null!=media_id&&!"".equals(media_id)){
if(!"".equals(str_tmp.toString())){
str_tmp.append(",");
}
if("video".equals(mediaType)){
str_tmp.append("\""+mediaType+"\": {\"media_id\": \""+media_id+"\"," +
"\"title\":" +"\""+title+"\","+
"\"description\":" +"\""+description+"\""+
"}");
}else {
str_tmp.append("\""+mediaType+"\": {\"media_id\": \""+media_id+"\"}");
}
}
}
if(null!=agentid&&!"".equals(agentid)){
if(!"".equals(str_tmp.toString())){
str_tmp.append(",");
}
str_tmp.append("\"agentid\": \""+agentid+"\"");
}
if(null!=safe&&!"".equals(safe)){
if(!"".equals(str_tmp.toString())){
str_tmp.append(",");
}
str_tmp.append("\"safe\": \""+safe+"\"");
}
jsonStr.append(str_tmp);
jsonStr.append("}");
return jsonStr.toString();
}
}
|
package lecturesharingproject.lecturesharing;
import lecturesharingproject.lecturesharing.service.ILectureService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class LecturesharingApplication {
public static void main(String[] args) {
SpringApplication.run(LecturesharingApplication.class, args);
}
}
|
/*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.util;
import java.util.Iterator;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link LinkedCaseInsensitiveMap}.
*
* @author Juergen Hoeller
* @author Phillip Webb
*/
class LinkedCaseInsensitiveMapTests {
private final LinkedCaseInsensitiveMap<String> map = new LinkedCaseInsensitiveMap<>();
@Test
void putAndGet() {
assertThat(map.put("key", "value1")).isNull();
assertThat(map.put("key", "value2")).isEqualTo("value1");
assertThat(map.put("key", "value3")).isEqualTo("value2");
assertThat(map).hasSize(1);
assertThat(map.get("key")).isEqualTo("value3");
assertThat(map.get("KEY")).isEqualTo("value3");
assertThat(map.get("Key")).isEqualTo("value3");
assertThat(map.containsKey("key")).isTrue();
assertThat(map.containsKey("KEY")).isTrue();
assertThat(map.containsKey("Key")).isTrue();
assertThat(map.keySet().contains("key")).isTrue();
assertThat(map.keySet().contains("KEY")).isTrue();
assertThat(map.keySet().contains("Key")).isTrue();
}
@Test
void putWithOverlappingKeys() {
assertThat(map.put("key", "value1")).isNull();
assertThat(map.put("KEY", "value2")).isEqualTo("value1");
assertThat(map.put("Key", "value3")).isEqualTo("value2");
assertThat(map).hasSize(1);
assertThat(map.get("key")).isEqualTo("value3");
assertThat(map.get("KEY")).isEqualTo("value3");
assertThat(map.get("Key")).isEqualTo("value3");
assertThat(map.containsKey("key")).isTrue();
assertThat(map.containsKey("KEY")).isTrue();
assertThat(map.containsKey("Key")).isTrue();
assertThat(map.keySet().contains("key")).isTrue();
assertThat(map.keySet().contains("KEY")).isTrue();
assertThat(map.keySet().contains("Key")).isTrue();
}
@Test
void getOrDefault() {
assertThat(map.put("key", "value1")).isNull();
assertThat(map.put("KEY", "value2")).isEqualTo("value1");
assertThat(map.put("Key", "value3")).isEqualTo("value2");
assertThat(map.getOrDefault("key", "N")).isEqualTo("value3");
assertThat(map.getOrDefault("KEY", "N")).isEqualTo("value3");
assertThat(map.getOrDefault("Key", "N")).isEqualTo("value3");
assertThat(map.getOrDefault("keeeey", "N")).isEqualTo("N");
assertThat(map.getOrDefault(new Object(), "N")).isEqualTo("N");
}
@Test
void getOrDefaultWithNullValue() {
assertThat(map.put("key", null)).isNull();
assertThat(map.put("KEY", null)).isNull();
assertThat(map.put("Key", null)).isNull();
assertThat(map.getOrDefault("key", "N")).isNull();
assertThat(map.getOrDefault("KEY", "N")).isNull();
assertThat(map.getOrDefault("Key", "N")).isNull();
assertThat(map.getOrDefault("keeeey", "N")).isEqualTo("N");
assertThat(map.getOrDefault(new Object(), "N")).isEqualTo("N");
}
@Test
void computeIfAbsentWithExistingValue() {
assertThat(map.putIfAbsent("key", "value1")).isNull();
assertThat(map.putIfAbsent("KEY", "value2")).isEqualTo("value1");
assertThat(map.put("Key", "value3")).isEqualTo("value1");
assertThat(map.computeIfAbsent("key", key2 -> "value1")).isEqualTo("value3");
assertThat(map.computeIfAbsent("KEY", key1 -> "value2")).isEqualTo("value3");
assertThat(map.computeIfAbsent("Key", key -> "value3")).isEqualTo("value3");
assertThat(map.put("null", null)).isNull();
assertThat(map.putIfAbsent("NULL", "value")).isNull();
assertThat(map.put("null", null)).isEqualTo("value");
assertThat(map.computeIfAbsent("NULL", s -> "value")).isEqualTo("value");
assertThat(map.get("null")).isEqualTo("value");
}
@Test
void computeIfAbsentWithComputedValue() {
assertThat(map.computeIfAbsent("key", key2 -> "value1")).isEqualTo("value1");
assertThat(map.computeIfAbsent("KEY", key1 -> "value2")).isEqualTo("value1");
assertThat(map.computeIfAbsent("Key", key -> "value3")).isEqualTo("value1");
}
@Test
void mapClone() {
assertThat(map.put("key", "value1")).isNull();
LinkedCaseInsensitiveMap<String> copy = map.clone();
assertThat(copy.getLocale()).isEqualTo(map.getLocale());
assertThat(map.get("key")).isEqualTo("value1");
assertThat(map.get("KEY")).isEqualTo("value1");
assertThat(map.get("Key")).isEqualTo("value1");
assertThat(copy.get("key")).isEqualTo("value1");
assertThat(copy.get("KEY")).isEqualTo("value1");
assertThat(copy.get("Key")).isEqualTo("value1");
copy.put("Key", "value2");
assertThat(map).hasSize(1);
assertThat(copy).hasSize(1);
assertThat(map.get("key")).isEqualTo("value1");
assertThat(map.get("KEY")).isEqualTo("value1");
assertThat(map.get("Key")).isEqualTo("value1");
assertThat(copy.get("key")).isEqualTo("value2");
assertThat(copy.get("KEY")).isEqualTo("value2");
assertThat(copy.get("Key")).isEqualTo("value2");
}
@Test
void clearFromKeySet() {
map.put("key", "value");
map.keySet().clear();
map.computeIfAbsent("key", k -> "newvalue");
assertThat(map.get("key")).isEqualTo("newvalue");
}
@Test
void removeFromKeySet() {
map.put("key", "value");
map.keySet().remove("key");
map.computeIfAbsent("key", k -> "newvalue");
assertThat(map.get("key")).isEqualTo("newvalue");
}
@Test
void removeFromKeySetViaIterator() {
map.put("key", "value");
nextAndRemove(map.keySet().iterator());
assertThat(map).isEmpty();
map.computeIfAbsent("key", k -> "newvalue");
assertThat(map.get("key")).isEqualTo("newvalue");
}
@Test
void clearFromValues() {
map.put("key", "value");
map.values().clear();
assertThat(map).isEmpty();
map.computeIfAbsent("key", k -> "newvalue");
assertThat(map.get("key")).isEqualTo("newvalue");
}
@Test
void removeFromValues() {
map.put("key", "value");
map.values().remove("value");
assertThat(map).isEmpty();
map.computeIfAbsent("key", k -> "newvalue");
assertThat(map.get("key")).isEqualTo("newvalue");
}
@Test
void removeFromValuesViaIterator() {
map.put("key", "value");
nextAndRemove(map.values().iterator());
assertThat(map).isEmpty();
map.computeIfAbsent("key", k -> "newvalue");
assertThat(map.get("key")).isEqualTo("newvalue");
}
@Test
void clearFromEntrySet() {
map.put("key", "value");
map.entrySet().clear();
assertThat(map).isEmpty();
map.computeIfAbsent("key", k -> "newvalue");
assertThat(map.get("key")).isEqualTo("newvalue");
}
@Test
void removeFromEntrySet() {
map.put("key", "value");
map.entrySet().remove(map.entrySet().iterator().next());
assertThat(map).isEmpty();
map.computeIfAbsent("key", k -> "newvalue");
assertThat(map.get("key")).isEqualTo("newvalue");
}
@Test
void removeFromEntrySetViaIterator() {
map.put("key", "value");
nextAndRemove(map.entrySet().iterator());
assertThat(map).isEmpty();
map.computeIfAbsent("key", k -> "newvalue");
assertThat(map.get("key")).isEqualTo("newvalue");
}
private void nextAndRemove(Iterator<?> iterator) {
iterator.next();
iterator.remove();
}
}
|
package com.cs.item;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlRootElement;
/**
* @author Omid Alaepour.
*/
@XmlRootElement
@XmlEnum
public enum ItemType {
FREE_ROUNDS, BONUS_MONEY, DEPOSIT_BONUS
}
|
package com.springboot.web.service;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.springboot.web.controller.SearchController;
import com.springboot.web.model.UserInfoEntityCrudRepo;
import com.springboot.web.model.UserInfoEntityCrudRepo;
import com.springboot.web.model.UserInfoEntity;
@Service
public class EditService {
@Autowired
UserInfoEntityCrudRepo userEntityCrudRepository;
private static Logger logger = LoggerFactory.getLogger(SearchController.class);
public boolean updateUser(UserInfoEntityCrudRepo user) {
logger.info("Inside updateUser fileName = EditService.java");
userEntityCrudRepository.save(user);
return true;
}
} |
import java.applet.Applet;
import java.awt.*;
import com.sun.j3d.utils.applet.MainFrame;
import com.sun.j3d.utils.geometry.*;
import com.sun.j3d.utils.universe.*;
import javax.media.j3d.*;
import javax.vecmath.*;
import com.sun.j3d.utils.behaviors.mouse.*;
public class beziercurve extends Applet{
public BranchGroup createBranchGroupSceneGraph(){
BranchGroup BranchGroupRoot=new BranchGroup();
BoundingSphere bounds=new BoundingSphere(new Point3d(0.0,0.0,0.0),100.0);
Color3f bgColor=new Color3f(1.0f,1.0f,1.0f);
Background bg=new Background(bgColor);
bg.setApplicationBounds(bounds);
BranchGroupRoot.addChild(bg);
Color3f directionalColor=new Color3f(1.f,0.f,0.f);
Vector3f vec=new Vector3f(0.f,0.f,-1.0f);
DirectionalLight directionalLight=new DirectionalLight(directionalColor,vec);
directionalLight.setInfluencingBounds(bounds);
BranchGroupRoot.addChild(directionalLight);
Appearance app=new Appearance();//24
Material material=new Material();
material.setDiffuseColor(new Color3f(1.0f,1.0f,0.0f));
app.setMaterial(material);
TransformGroup transformgroup=new TransformGroup();
transformgroup.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
transformgroup.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);
BranchGroupRoot.addChild(transformgroup);
MouseRotate mouserotate=new MouseRotate();
mouserotate.setTransformGroup(transformgroup);
BranchGroupRoot.addChild(mouserotate);
mouserotate.setSchedulingBounds(bounds);
MouseZoom mousezoom = new MouseZoom();
mousezoom.setTransformGroup(transformgroup);
BranchGroupRoot.addChild(mousezoom);
mousezoom.setSchedulingBounds(bounds);
MouseTranslate mousetranslate=new MouseTranslate();
mousetranslate.setTransformGroup(transformgroup);
BranchGroupRoot.addChild(mousetranslate);
mousetranslate.setSchedulingBounds(bounds);
Shape3D Bezier=new BezierThreeOrderCurve();
transformgroup.addChild(Bezier);
BranchGroupRoot.compile();
return BranchGroupRoot;
}
public beziercurve(){
setLayout(new BorderLayout());
GraphicsConfiguration gc = SimpleUniverse.getPreferredConfiguration();
Canvas3D c=new Canvas3D(gc);
add("Center",c);
BranchGroup BranchGroupScene=createBranchGroupSceneGraph();
SimpleUniverse u=new SimpleUniverse(c);
u.getViewingPlatform().setNominalViewingTransform();
u.addBranchGraph(BranchGroupScene);
}
public static void main(String[] args){
new MainFrame(new beziercurve(),400,400);
}
}
//BezierCurve
class BezierThreeOrderCurve extends Shape3D {
public BezierThreeOrderCurve(){
int i,j,k;
float[] t=new float[100];
//存放[1 u u2 u3]参数矩阵的数组
float[][] UU=new float[1][4];
//存放Bezier曲线上点的坐标的数组
float[][] curvepoints=new float[100][4];
//存放控制顶点坐标的数组
float[][] P={{-0.8f,-0.6f,0.f,1.f},
{-0.2f,0.2f,0.f,1.f},
{0.2f,0.3f,0.f,1.f},
{0.8f,-0.5f,0.f,1.f} };
//存放系数矩阵M的数组
float[][] M={{1.f,0.f,0.f,0.f},
{-3.f,3.f,0.f,0.f},
{3.f,-6.f,3.f,0.f},
{-1.f,3.f,-3.f,1.f}
};
int n;//对参数t在[0,1]区间的等分点数
float division;//参数t在[0,1]区间的等分线段长度
n=50;
division=1.f/n;
for(i=0;i<n+1;i++){
t[i]=i*division;
}
for(i=0;i<n+1;i++){
UU[0][0]=1.f;
UU[0][1]=t[i];
UU[0][2]=t[i]*t[i];
UU[0][3]=t[i]*t[i]*t[i];
matrixm g0=new matrixm(1,4,4,UU,M);
matrixm g1=new matrixm(1,4,4,g0.CC,P);
curvepoints[i][0]=g1.CC[0][0];
curvepoints[i][1]=g1.CC[0][1];
curvepoints[i][2]=g1.CC[0][2];
curvepoints[i][3]=g1.CC[0][3];
curvepoints[i][0]=g1.CC[0][0]/curvepoints[i][3];
curvepoints[i][1]=g1.CC[0][1]/curvepoints[i][3];
curvepoints[i][2]=g1.CC[0][2]/curvepoints[i][3];
}
//定义曲线上点的数组
Point3f[] curvepoints0=new Point3f[100];
for(i=0;i<100;i++)
curvepoints0[i]=new Point3f();
for(k=0;k<n+1;k++){
curvepoints0[k].x=curvepoints[k][0];
curvepoints0[k].y=curvepoints[k][1];
curvepoints0[k].z=curvepoints[k][2];
}
Point3f[] contralpoints=new Point3f[4];
for(i=0;i<4;i++)
contralpoints[i]=new Point3f();
for(i=0;i<4;i++){
contralpoints[i].x=P[i][0];
contralpoints[i].y=P[i][1];
contralpoints[i].z=P[i][2];
}
int[] contralpointscount=new int[1];
int[] curvepointscount=new int[1];
contralpointscount[0]=4;
curvepointscount[0]=51;
LineStripArray contralpointslines=new LineStripArray(100,LineArray.COORDINATES,contralpointscount);
contralpointslines.setCoordinates(0,contralpoints);
LineStripArray curvelines=new LineStripArray(100,LineArray.COORDINATES,curvepointscount);
curvelines.setCoordinates(0,curvepoints0);
LineAttributes lineattributes=new LineAttributes();
lineattributes.setLineWidth(1.0f);
lineattributes.setLineAntialiasingEnable(true);
lineattributes.setLinePattern(0);
Appearance app=new Appearance();
app.setLineAttributes(lineattributes);
//针对整个曲线定义颜色,而不是针对顶点定义颜色
ColoringAttributes color=new ColoringAttributes();
color.setColor(0.f,1.f,0.f);
app.setColoringAttributes(color);
this.addGeometry(curvelines);
this.addGeometry(contralpointslines);
//this.insertGeometry(curvelines,0);
//this.insertGeometry(contralpointslines,1);
this.setAppearance(app);
}
}
//end of Beziercurv
//matrixm
class matrixm{
public float CC[][]=new float[4][4];
int ll,mm,kk;
public matrixm(int mmm, int kkk, int nnn,float a[][],float b[][]){
for(ll=0;ll<mmm;ll++)
for(mm=0;mm<nnn;mm++){
CC[ll][mm]=0.f;
}
for(ll=0;ll<mmm;ll++)
for(mm=0;mm<nnn;mm++){
for(kk=0;kk<kkk;kk++)
CC[ll][mm]=CC[ll][mm]+a[ll][kk]*b[kk][mm];
}
}
}
//end of matrixm
|
package msip.go.kr.member.service.impl;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import msip.go.kr.member.entity.InstMember;
import msip.go.kr.member.entity.Member;
import msip.go.kr.member.entity.MemberVO;
/**
* 산하기관 회원 데이터 처리를 위한 DAO 클래스 정의
*
* @author 정승철
* @since 2015.07.06
* @see <pre>
* == 개정이력(Modification Information) ==
*
* 수정일 수정자 수정내용
* ---------------------------------------------------------------------------------
* 2015.07.06 정승철 최초생성
*
* </pre>
*/
@Repository("instMemberDAO")
public class InstMemberDAO {
private static final Logger LOGGER = LoggerFactory.getLogger(InstMemberDAO.class);
/**
* @PersistenceContext 어노테이션을 이용하여 컨테이너로부터 EntityManger DI
* @param EntityManager em
*/
@PersistenceContext
private EntityManager em;
/**
* 새로운 산하기관 사용자 정보를 입력받아 데이터베이스에 저장
* @param InstMember entity
* @throws Exception
*/
public void persist(InstMember entity) throws Exception {
this.em.persist(entity);
}
/**
* 선택된 id에 따라 데이터베이스에서 회원 정보를 읽어와 화면에 출력
* @param Long id
* @return InstMember entity
* @throws Exception
*/
public InstMember findById(Long id) throws Exception{
return em.find(InstMember.class, id);
}
/**
* 수정된 회원 정보를 데이터베이스에 반영
* @param InstMember entity
* @throws Exception
*/
public void merge(InstMember entity) throws Exception {
em.merge(entity);
}
/**
* 선택된 id 에 따라 산하기관 회원 정보를 데이터베이스에서 삭제
* @param InstMember entity
* @throws Exception
*/
public void remove(InstMember entity) throws Exception {
em.remove(em.merge(entity));
}
/**
* 산하기관 회원의 전체 목록을 데이터베이스에서 읽어와 화면에 출력
* @return List<InstMember> 산하기관 회원 목록
* @throws Exception
*/
public List<InstMember> findAll() throws Exception {
String hql = "from InstMember c order by c.id";
List<InstMember> categories = em.createQuery(hql, InstMember.class).getResultList();
return categories;
}
/**
* 사용자 고유 아이디로 사용자 정보를 조회
* @param esntlId 사용자 고유 아이디
* @return
* @throws Exception
*/
public InstMember findByEsntlId(String esntlId) throws Exception{
String hql = "from InstMember Where esntlId = :esntlId";
InstMember member = null;
try {
Query query = em.createQuery(hql.toString(), InstMember.class);
query.setParameter("esntlId", esntlId);
member = (InstMember) query.getSingleResult();
} catch(javax.persistence.NoResultException nre) {
LOGGER.info(esntlId+" member not exitst");
} catch(Exception e) {
LOGGER.error("InstMember findByEsntlId esntlId : "+esntlId, e.getCause(), e);
}
return member;
}
/**
* 회원가입시 발급된 key로 사용자 정보를 조회
* @param signKey 회원가입 발급 key
* @return
* @throws Exception
*/
public InstMember findBySignKey(String signKey) throws Exception{
String hql = "from InstMember Where signKey = :signKey";
Query query = em.createQuery(hql.toString(), InstMember.class);
query.setParameter("signKey", signKey);
return (InstMember) query.getSingleResult();
}
/**
* 회원 이름과 이메일로 회원정보를 조회한다.
* @param userName 회원 이름
* @param eMail 이메일
* @return
* @throws Exception
*/
public InstMember findByNameAndEmail(String userName, String email) throws Exception{
String hql = "from InstMember Where userName = :userName and email = :email";
Query query = em.createQuery(hql.toString(), InstMember.class);
query.setParameter("userName", userName);
query.setParameter("email", email);
InstMember member = null;
try {
member = (InstMember) query.getSingleResult();
} catch(javax.persistence.NoResultException nre) {
LOGGER.info("InstMember findByNameAndEmail NoResultException "+userName+" "+email);
} catch(Exception e) {
LOGGER.info("InstMember findByNameAndEmail Exception "+userName+" "+email);
}
return member;
}
/**
* 전체 산하기관 조직 회원의 목록을 데이터베이스에서 읽어와 화면에 출력 (탭클릭시)
* @return List<InstMember> 산하기관 회원 목록
* @throws Exception
*/
public List<Member> findAll(MemberVO vo) throws Exception {
StringBuffer hql = new StringBuffer();
String ls = System.lineSeparator();
hql.append("SELECT NEW msip.go.kr.member.entity.Member(");
hql.append("id, orgName, dprtName, dprtid, email, esntlId, gradeName, mblPhn, ofcePhn, duty, userName, terms) ");
hql.append("FROM InstMember").append(ls);
hql.append("WHERE status = :status ").append(ls);
if (vo.getSearchKeyword() != null && !"".equals(vo.getSearchKeyword()))
hql.append("AND ").append(vo.getSearchCondition()).append(" LIKE :searchKeyword ").append(ls);
hql.append("ORDER BY userName ASC ").append(ls);
Query query = em.createQuery(hql.toString(), Member.class);
query.setParameter("status", vo.getStatus());
if (vo.getSearchKeyword() != null && !"".equals(vo.getSearchKeyword()))
query.setParameter("searchKeyword", "%"+vo.getSearchKeyword()+"%");
query.setFirstResult(vo.getFirstIndex());
query.setMaxResults(vo.getRecordCountPerPage());
@SuppressWarnings("unchecked")
List<Member> resultList = query.getResultList();
return resultList;
}
/**
* 선택된 산하기관 조직 회원의 목록을 데이터베이스에서 읽어와 화면에 출력
* @return List<InstMember> 산하기관 회원 목록
* @throws Exception
*/
public List<Member> findListByDprtId(MemberVO vo) throws Exception {
StringBuffer hql = new StringBuffer();
String ls = System.lineSeparator();
hql.append("SELECT NEW msip.go.kr.member.entity.Member(");
hql.append("a.id, a.orgName, a.dprtName, a.dprtid, a.email, a.esntlId, a.gradeName, a.mblPhn, a.ofcePhn, a.duty, a.userName, a.terms) ");
hql.append("FROM InstMember a, InstDprt b").append(ls);
hql.append("WHERE (a.dprtid = :id OR b.id = :id)").append(ls);
hql.append("AND status = :status ").append(ls);
if (vo.getSearchKeyword() != null && !"".equals(vo.getSearchKeyword()))
hql.append("AND ").append(vo.getSearchCondition()).append(" LIKE :searchKeyword ").append(ls);
hql.append("AND a.dprtid = b.id").append(ls);
hql.append("ORDER BY a.userName ASC ").append(ls);
Query query = em.createQuery(hql.toString(), Member.class);
query.setParameter("status", vo.getStatus());
query.setParameter("id", vo.getNodeId());
if (vo.getSearchKeyword() != null && !"".equals(vo.getSearchKeyword()))
query.setParameter("searchKeyword", "%"+vo.getSearchKeyword()+"%");
query.setFirstResult(vo.getFirstIndex());
query.setMaxResults(vo.getRecordCountPerPage());
@SuppressWarnings("unchecked")
List<Member> resultList = query.getResultList();
return resultList;
}
/**
* 산하기관 그룹별 회원목록을 조회한다.
* @return List<InstMember> 산하기관 회원 목록
* @throws Exception
*/
public List<Member> findListByDprtGroup(MemberVO vo) throws Exception {
StringBuffer hql = new StringBuffer();
String ls = System.lineSeparator();
hql.append("SELECT NEW msip.go.kr.member.entity.Member(");
hql.append("a.id, a.orgName, a.dprtName, a.dprtid, a.email, a.esntlId, a.gradeName, a.mblPhn, a.ofcePhn, a.duty, a.userName, a.terms) ");
hql.append("FROM InstMember a, InstDprt b").append(ls);
hql.append("WHERE status = :status ").append(ls);
hql.append("AND b.groupId = :groupId").append(ls);
hql.append("AND a.dprtid = b.id").append(ls);
if (vo.getSearchKeyword() != null && !"".equals(vo.getSearchKeyword()))
hql.append("AND ").append(vo.getSearchCondition()).append(" LIKE :searchKeyword ").append(ls);
hql.append("ORDER BY a.userName ASC ").append(ls);
Query query = em.createQuery(hql.toString(), Member.class);
query.setParameter("status", vo.getStatus());
query.setParameter("groupId", vo.getNodeId());
if (vo.getSearchKeyword() != null && !"".equals(vo.getSearchKeyword()))
query.setParameter("searchKeyword", "%"+vo.getSearchKeyword()+"%");
query.setFirstResult(vo.getFirstIndex());
query.setMaxResults(vo.getRecordCountPerPage());
@SuppressWarnings("unchecked")
List<Member> resultList = query.getResultList();
return resultList;
}
/**
* 공통그룹별 산하기관 사용자 목록을 조회한다.
* @param vo
* @return
* @throws Exception
*/
public List<Member> findListByWorkGroup(MemberVO vo) throws Exception {
StringBuffer hql = new StringBuffer();
hql.append("SELECT NEW msip.go.kr.member.entity.Member(");
hql.append("a.id, a.orgName, a.dprtName, a.dprtid, a.email, a.esntlId, a.gradeName, a.mblPhn, a.ofcePhn, a.duty, a.userName, a.terms) ");
hql.append("FROM InstMember a, WorkGroup b ");
hql.append("WHERE a.status = :status ");
hql.append("AND a.esntlId = b.esntlId ");
hql.append("AND b.code.id = :codeId ");
if (vo.getSearchKeyword() != null && !"".equals(vo.getSearchKeyword()))
hql.append("AND ").append(vo.getSearchCondition()).append(" LIKE :searchKeyword ");
hql.append("ORDER BY a.userName ASC ");
Query query = em.createQuery(hql.toString(), Member.class);
query.setParameter("status", vo.getStatus());
query.setParameter("codeId", vo.getNodeId());
if (vo.getSearchKeyword() != null && !"".equals(vo.getSearchKeyword()))
query.setParameter("searchKeyword", "%"+vo.getSearchKeyword()+"%");
query.setFirstResult(vo.getFirstIndex());
query.setMaxResults(vo.getRecordCountPerPage());
@SuppressWarnings("unchecked")
List<Member> resultList = query.getResultList();
return resultList;
}
/**
* 전체 산하기관 조직 회원의 목록 카운트를 데이터베이스에서 읽어와 화면에 출력
* @return int 산하기관 회원 카운트
* @throws Exception
*/
public int countAll(MemberVO vo) throws Exception {
StringBuffer hql = new StringBuffer();
String ls = System.lineSeparator();
hql.append("SELECT count(*)").append(ls);
hql.append("FROM InstMember ").append(ls);
hql.append("WHERE status = :status ").append(ls);
if (vo.getSearchKeyword() != null && !"".equals(vo.getSearchKeyword()))
hql.append("AND ").append(vo.getSearchCondition()).append(" LIKE :searchKeyword").append(ls);
Query query = em.createQuery(hql.toString());
query.setParameter("status", vo.getStatus());
if (vo.getSearchKeyword() != null && !"".equals(vo.getSearchKeyword()))
query.setParameter("searchKeyword", "%"+vo.getSearchKeyword()+"%");
Long result = (Long) query.getSingleResult();
return result.intValue();
}
/**
* 선택된 산하기관 조직 회원의 목록 카운트를 데이터베이스에서 읽어와 화면에 출력
* @return int 산하기관 회원 카운트
* @throws Exception
*/
public int countByDprtId(MemberVO vo) throws Exception {
StringBuffer hql = new StringBuffer();
String ls = System.lineSeparator();
hql.append("SELECT count(*)").append(ls);
hql.append("FROM InstMember a, InstDprt b").append(ls);
hql.append("WHERE (a.dprtid = :id OR b.id = :id)").append(ls);
hql.append("AND status = :status ").append(ls);
if (vo.getSearchKeyword() != null && !"".equals(vo.getSearchKeyword()))
hql.append("AND ").append(vo.getSearchCondition()).append(" LIKE :searchKeyword").append(ls);
hql.append("AND a.dprtid = b.id").append(ls);
Query query = em.createQuery(hql.toString());
query.setParameter("status", vo.getStatus());
query.setParameter("id", vo.getNodeId());
if (vo.getSearchKeyword() != null && !"".equals(vo.getSearchKeyword()))
query.setParameter("searchKeyword", "%"+vo.getSearchKeyword()+"%");
Long result = (Long) query.getSingleResult();
return result.intValue();
}
/**
* 산하기관 그룹별 회원수를 조회한다.
* @param vo
* @return
* @throws Exception
*/
public int countByDprtGroup(MemberVO vo) throws Exception {
StringBuffer hql = new StringBuffer();
hql.append("SELECT count(*)");
hql.append("FROM InstMember a, InstDprt b ");
hql.append("WHERE a.status = :status ");
hql.append("AND b.groupId = :groupId ");
hql.append("AND a.dprtid = b.id ");
if (vo.getSearchKeyword() != null && !"".equals(vo.getSearchKeyword()))
hql.append("AND ").append(vo.getSearchCondition()).append(" LIKE :searchKeyword ");
Query query = em.createQuery(hql.toString());
query.setParameter("status", vo.getStatus());
query.setParameter("groupId", vo.getNodeId());
if (vo.getSearchKeyword() != null && !"".equals(vo.getSearchKeyword()))
query.setParameter("searchKeyword", "%"+vo.getSearchKeyword()+"%");
Long result = (Long) query.getSingleResult();
return result.intValue();
}
/**
* 공통그룹별 산하기관 회원수를 조회한다.
* @param vo
* @return
* @throws Exception
*/
public int countByWorkGroup(MemberVO vo) throws Exception {
StringBuffer hql = new StringBuffer();
hql.append("SELECT count(*) ");
hql.append("FROM InstMember a, WorkGroup b ");
hql.append("WHERE a.status = :status ");
hql.append("AND a.esntlId = b.esntlId ");
hql.append("AND b.code.id = :codeId ");
if (vo.getSearchKeyword() != null && !"".equals(vo.getSearchKeyword()))
hql.append("AND ").append(vo.getSearchCondition()).append(" LIKE :searchKeyword ");
Query query = em.createQuery(hql.toString());
query.setParameter("status", vo.getStatus());
query.setParameter("codeId", vo.getNodeId());
if (vo.getSearchKeyword() != null && !"".equals(vo.getSearchKeyword()))
query.setParameter("searchKeyword", "%"+vo.getSearchKeyword()+"%");
Long result = (Long) query.getSingleResult();
return result.intValue();
}
public List<Member> searchByName(String userName) throws Exception {
StringBuffer hql = new StringBuffer();
hql.append("SELECT NEW msip.go.kr.member.entity.Member(");
hql.append("id, orgName, dprtName, dprtid, email, esntlId, gradeName, mblPhn, ofcePhn, duty, userName) ");
hql.append("FROM InstMember ");
hql.append("WHERE userName LIKE :userName ");
hql.append("AND terms =1 ");
hql.append("AND status = :status ");
hql.append("ORDER BY userName ASC ");
Query query = em.createQuery(hql.toString(), Member.class);
query.setParameter("userName", "%"+userName+"%");
query.setParameter("status", Member.APPROVED);
@SuppressWarnings("unchecked")
List<Member> resultList = query.getResultList();
return resultList;
}
/**
* 유효 사용자 중 검색 조건 이메일과 동일한 사용자 수를 조회한다.
* @param email
* @return
* @throws Exception
*/
public int countByEmail(String email) throws Exception {
StringBuffer hql = new StringBuffer();
hql.append("SELECT count(*) ");
hql.append("FROM InstMember ");
hql.append("WHERE email = :email ");
hql.append("AND status > -1 ");
Query query = em.createQuery(hql.toString());
query.setParameter("email", email);
Long count = (Long) query.getSingleResult();
return count.intValue();
}
/**
* 기관 소속 사용자의 기관명을 수정한다.
* @param dprtid 기관일련번호
* @param orgName 기관명
* @throws Exception
*/
public void updateOrgName(Long dprtid, String orgName) throws Exception {
String hql = "UPDATE InstMember SET orgName = :orgName WHERE dprtid = :dprtid";
Query query = em.createQuery(hql.toString());
query.setParameter("orgName", orgName);
query.setParameter("dprtid", dprtid);
query.executeUpdate();
}
}
|
package com.adaming.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.adaming.entities.Affaire;
import com.adaming.utils.ServiceGeneric;
@RestController
public class AffaireController {
@Autowired
ServiceGeneric<Affaire> phaseService;
@RequestMapping(value="affaire", method=RequestMethod.GET)
public List<Affaire> findAll(Class<Affaire> obj ){
return phaseService.findAll(obj);
}
@RequestMapping(value ="affaire/{id}", method=RequestMethod.GET)
public Affaire findOne(@PathVariable("id") Long id) {
return phaseService.getById(Affaire.class , id);
}
@RequestMapping(value="affaire", method=RequestMethod.POST)
public void savePhase(@RequestBody Affaire affaire) {
phaseService.update(affaire);
}
@RequestMapping(value="affaire/{id}", method=RequestMethod.DELETE)
public void deletePhase(@PathVariable("id") Long id) {
Affaire ph=phaseService.getById(Affaire.class, id);
phaseService.delete(ph);
}
@RequestMapping(value="affaire", method=RequestMethod.PUT)
public void updatePhase(@PathVariable("id") Long id, @RequestBody Affaire affaire) {
Affaire currentUser= phaseService.getById(Affaire.class, id);
currentUser.setReferenceAffaire(affaire.getReferenceAffaire());
currentUser.setTitreAffaire(affaire.getTitreAffaire());
currentUser.setDescriptionAffaire(affaire.getDescriptionAffaire());
phaseService.update(currentUser);
}
}
|
package projetZoo;
import java.util.LinkedList;
public class Cabane {
private LinkedList<Oiseau> oiseuax = new LinkedList<Oiseau>();
private int numeroCabane;
public LinkedList<Oiseau> getOiseuax() {
return oiseuax;
}
public void setOiseuax(LinkedList<Oiseau> oiseuax) {
this.oiseuax = oiseuax;
}
public int getNumeroCabane() {
return numeroCabane;
}
public void setNumeroCabane(int numeroCabane) {
this.numeroCabane = numeroCabane;
}
}
|
package ico.maze;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import ico.maze.Laberinto.Busqueda;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
@SuppressWarnings("serial")
public class Interfaz extends JPanel implements MouseListener, KeyListener {
public final static int tamanoCelda = 70;
private int mazeSize = 4;
private Laberinto laberinto;
private DisplayPanel displayPanel;
private DisplayPanel displayPanel1;
private DisplayPanel displayPanel2;
private DisplayPanel displayPanel3;
private Celda.Type ultimaPosicionClick;
public Interfaz() {
this.setLayout(new BorderLayout());
try {
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
| UnsupportedLookAndFeelException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
/**
* Recogemos el tamaño de nuestro laberinto mediante un JOptionPane.
*/
String dialog = "4";
dialog = JOptionPane.showInputDialog("Introduzca el tamaño del laberinto [4,10] : ", dialog);
mazeSize = Integer.parseInt(dialog);
if(mazeSize<4)
mazeSize=4;
if(mazeSize>10)
mazeSize=10;
/**
* Pasamos el tamaño del laberinto para crearlo.
*/
this.laberinto = new Laberinto(mazeSize);
/**
* Generamos la barra de pestañas.
*/
JTabbedPane tabbedPane = new JTabbedPane();
this.displayPanel = new DisplayPanel(laberinto);
this.displayPanel1 = new DisplayPanel(laberinto);
this.displayPanel2 = new DisplayPanel(laberinto);
this.displayPanel3 = new DisplayPanel(laberinto);
/**
* Añadimos los listeners.
*/
displayPanel.addMouseListener(this);
displayPanel.addKeyListener(this);
displayPanel1.addKeyListener(this);
displayPanel2.addKeyListener(this);
displayPanel3.addKeyListener(this);
ultimaPosicionClick = null;
/**
* Añadimos los paneles y las pestañas.
*/
tabbedPane.addTab("Laberinto",displayPanel);
tabbedPane.addTab("Dijkstra",displayPanel1);
tabbedPane.addTab("Avara",displayPanel2);
tabbedPane.addTab("A*",displayPanel3);
/**
* Dependiendo de la pestaña que pulsemos hace una cosa u otra.
*/
tabbedPane.addChangeListener(new ChangeListener() { //add the Listener
public void stateChanged(ChangeEvent e) {
switch(tabbedPane.getSelectedIndex())
{
case 0:
laberinto.limpiarLaberinto();
displayPanel.repaint();
break;
case 1:
laberinto.setTypeBusqueda(Laberinto.Busqueda.DIJKSTRA);
laberinto.resetearFichero(Busqueda.DIJKSTRA);
laberinto.limpiarLaberinto();
laberinto.procesarBusqueda();
displayPanel.repaint();
break;
case 2:
laberinto.setTypeBusqueda(Laberinto.Busqueda.AVARA);
laberinto.resetearFichero(Busqueda.AVARA);
laberinto.limpiarLaberinto();
laberinto.procesarBusqueda();
displayPanel2.repaint();
break;
case 3:
laberinto.setTypeBusqueda(Laberinto.Busqueda.ASTAR);
laberinto.resetearFichero(Busqueda.ASTAR);
laberinto.limpiarLaberinto();
laberinto.procesarBusqueda();
displayPanel3.repaint();
break;
}
}
});
this.add(tabbedPane);
}
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode())
{
/**
* Si pulsa R se reinicia la pestaña Laberinto.
*/
case KeyEvent.VK_R:
laberinto.limpiarLaberinto();
displayPanel.repaint();
break;
// Paso a paso.
//case KeyEvent.VK_SPACE:
//break;
/**
* Cierra el programa con la tecla ESC desde cualquier pestaña.
*/
case KeyEvent.VK_ESCAPE:
System.exit(1);
break;
/**
* Muestra las heurísticas en la pestaña Laberinto.
*/
case KeyEvent.VK_H:
laberinto.calcularHeuristicas();
displayPanel.repaint();
break;
}
}
public void keyReleased(KeyEvent e) { }
public void keyTyped(KeyEvent e) { }
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
/**
* Obtenemos la celda que ha sido clickada.
*/
Celda celda = laberinto.getPosiciones()[e.getY() / tamanoCelda][e.getX() / tamanoCelda];
if(ultimaPosicionClick == null){
ultimaPosicionClick = celda.getType();
}else{
/**
* En caso de que la celda pulsa sea tipo GOAL llamamos a cambiarFinal.
*/
if (ultimaPosicionClick.equals(Celda.Type.FINAL)) {
laberinto.cambiarFinal(celda);
ultimaPosicionClick = Celda.Type.CAMPO;
}
/**
* En caso de que la celda pulsa sea tipo START llamamos a cambiarInicio.
*/
else if (ultimaPosicionClick.equals(Celda.Type.INICIO)) {
laberinto.cambiarInicio(celda);
ultimaPosicionClick = Celda.Type.CAMPO;
}
/**
* Como último caso, el resto de celdas cambian mediante cambiarCelda.
*/
else{
laberinto.cambiarCelda(celda);
ultimaPosicionClick = celda.getType();
}
}
/**
* Actualiza el estado de la interfaz del laberinto.
*/
displayPanel.repaint();
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
public class DisplayPanel extends JPanel {
private Laberinto laberinto;
public DisplayPanel(Laberinto laberinto) {
this.laberinto = laberinto;
}
public void setLaberinto(Laberinto laberinto) {
this.laberinto = laberinto;
}
public void paintComponent(Graphics g) {
requestFocus();
int sqsize = tamanoCelda;
int yoffset;
int xoffset;
for (int i = 0; i < laberinto.getsize(); i++) {
for (int j = 0; j < laberinto.getsize(); j++) {
Celda celda = laberinto.getPosiciones()[i][j];
yoffset = sqsize * i;
xoffset = sqsize * j;
/**
* Coloreamos las celdas dependiendo del tipo.
*/
switch (celda.getType()) {
case INICIO:
/**
* Color del fondo del cuadrado.
*/
g.setColor(new Color(0,153,0));
/**
* Dibujamos el cuadrado.
*/
g.fillRect(xoffset, yoffset, sqsize, sqsize);
/**
* Color del borde.
*/
g.setColor(Color.blue);
/**
* Dibujamos el borde.
*/
g.drawRect(xoffset, yoffset, sqsize, sqsize);
continue;
case FINAL:
/**
* Color del fondo del cuadrado.
*/
g.setColor(Color.red);
break;
// De momento no hay diferencia entre sucesor, cerrado y grass.
// case CERRADO:
//case SUCESOR:
case CAMPO:
/**
* Color del fondo del cuadrado.
*/
g.setColor(Color.black);
break;
case BOSQUE:
/**
* Color del fondo del cuadrado.
*/
g.setColor(new Color(153,153,0));
break;
case RIO:
/**
* Color del fondo del cuadrado.
*/
g.setColor(new Color(0,204,204));
break;
case MONTANA:
/**
* Color del fondo del cuadrado.
*/
g.setColor(new Color(0,0,204));
/**
* Dibujamos el cuadrado.
*/
g.fillRect(xoffset, yoffset, sqsize, sqsize);
/**
* Color del borde.
*/
g.setColor(Color.blue);
/**
* Dibujamos el borde.
*/
g.drawRect(xoffset, yoffset, sqsize, sqsize);
continue;
default:
/**
* Color del fondo del cuadrado.
*/
g.setColor(Color.white);
break;
}
/**
* Dibujamos el cuadrado.
*/
g.fillRect(xoffset, yoffset, sqsize, sqsize);
/**
* Color del borde.
*/
g.setColor(Color.blue);
/**
* Dibujamos el borde.
*/
g.drawRect(xoffset, yoffset, sqsize, sqsize);
g.setColor(Color.white);
/**
* Escribir heuristica
*/
g.drawString(""+celda.getHn(), xoffset + 50, yoffset + 65);
/**
* Escribir Coste
*/
g.drawString(""+celda.getGn(), xoffset + 5, yoffset + 65);
/**
* Escribir funcion
*/
g.drawString("" + celda.getFn(), xoffset + 5, yoffset + 15);
/**
* En caso de que la celda sea parte de la solución tendrá otro dibujo, en este caso un borde amarillo y un punto rojo.
*/
if(celda.isSolucion()){
/**
* Color del fondo del cuadrado.
*/
g.setColor(celda.getType().getColor());
/**
* Dibujamos el cuadrado.
*/
g.fillRect(xoffset, yoffset, sqsize, sqsize);
/**
* Color del borde.
*/
g.setColor(Color.yellow);
/**
* Dibujamos el borde.
*/
g.drawRect(xoffset, yoffset, sqsize-1, sqsize-1);
/**
* Color del texto.
*/
g.setColor(Color.white);
/**
* Escribir heuristica
*/
g.drawString(""+celda.getHn(), xoffset + 50, yoffset + 65);
/**
* Escribir Coste
*/
g.drawString(""+celda.getGn(), xoffset + 5, yoffset + 65);
/**
* Escribir funcion
*/
g.drawString("" + celda.getFn(), xoffset + 5, yoffset + 15);
/**
* Color del círculo.
*/
g.setColor(Color.red);
/**
* Dibujamos el círculo.
*/
g.fillOval(xoffset+23,yoffset+23,sqsize/3,sqsize/3);
}// Cierra if.
else if(celda.isGenerado())
{
/**
* Color del fondo del cuadrado.
*/
g.setColor(celda.getType().getColor());
/**
* Dibujamos el cuadrado.
*/
g.fillRect(xoffset, yoffset, sqsize, sqsize);
/**
* Color del borde.
*/
g.setColor(Color.green);
/**
* Dibujamos el borde.
*/
g.drawRect(xoffset, yoffset, sqsize-1, sqsize-1);
/**
* Color del texto.
*/
g.setColor(Color.white);
/**
* Escribir heuristica
*/
g.drawString(""+celda.getHn(), xoffset + 50, yoffset + 65);
/**
* Escribir Coste
*/
g.drawString(""+celda.getGn(), xoffset + 5, yoffset + 65);
/**
* Escribir funcion
*/
g.drawString("" + celda.getFn(), xoffset + 5, yoffset + 15);
}// Cierra elseif.
}// Cierra for.
}// Cierra for.
}// Cierra PaintComponent.
}// Cierra DisplayPanel.
public int getMazeSize() {
return mazeSize;
}
public void setMazeSize(int mazeSize) {
this.mazeSize = mazeSize;
}
}
|
package com.ihq.capitalpool.ssoserver.ServiceImpl;
import com.ihq.capitalpool.ssoserver.Enum.TokenType;
import com.ihq.capitalpool.ssoserver.Service.PasswordTokenService;
import org.springframework.stereotype.Service;
import java.util.Map;
@Service
public class PasswordTokenServiceImpl extends BasicTokenServiceImpl implements PasswordTokenService {
@Override
public Map<String, String> generator(String uuid, String data, String key) {
return super.generator(uuid, data, key, String.valueOf(TokenType.Password.getCode()));
}
}
|
package com.spring.scrapper.users;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Repository;
import com.spring.scrapper.dao.CommonDAO;
import com.spring.scrapper.users.vo.UserVO;
@Repository
public class UserDAOImpl extends CommonDAO implements UserDAO{
@Override
public boolean insertUser(UserVO vo) throws Exception {
return super.getSession().insert("users.insertUser", vo) >0 ? true : false;
}
@Override
public UserVO selectUser(UserVO vo) throws Exception {
Map<String, Object> parameterMap = new HashMap<String, Object>();
parameterMap.put("id", vo.getId());
parameterMap.put("password", vo.getPassword());
return super.getSession().selectOne("users.selectUser", parameterMap);
}
}
|
package com.hillel.javaElementary.classes.Lesson_8.Task_5;
import java.util.Date;
public class MulticastingLifecycleObserver implements IHumanLifecycleObserver {
private final IHumanLifecycleObserver[] observers;
public MulticastingLifecycleObserver(IHumanLifecycleObserver[] observers) {
this.observers = observers;
}
@Override
public void onHumanWasBorn(BornParams params) {
for (IHumanLifecycleObserver observer:observers){
observer.onHumanWasBorn(params);
}
}
@Override
public void onWentToKindergarten(EducationParams params) {
for (IHumanLifecycleObserver observer:observers){
observer.onWentToKindergarten(params);
}
}
@Override
public void onWentToSchool(EducationParams params) {
for (IHumanLifecycleObserver observer:observers){
observer.onWentToSchool(params);
}
}
@Override
public void onWentToUniversity(EducationParams params) {
for (IHumanLifecycleObserver observer:observers){
observer.onWentToUniversity(params);
}
}
@Override
public void onGotWork(WorkParams params) {
for (IHumanLifecycleObserver observer:observers){
observer.onGotWork(params);
}
}
@Override
public void onBoughtCar(BoughtCarParams params) {
for (IHumanLifecycleObserver observer:observers){
observer.onBoughtCar(params);
}
}
@Override
public void onCreatingFamily(CreatingFamilyParams params) {
for (IHumanLifecycleObserver observer:observers){
observer.onCreatingFamily(params);
}
}
@Override
public void onGaveBirth(GaveBirthParams params) {
for (IHumanLifecycleObserver observer:observers){
observer.onGaveBirth(params);
}
}
@Override
public void onDeath(Date date) {
for (IHumanLifecycleObserver observer:observers){
observer.onDeath(date);
}
}
}
|
public class Ch12_05 {
//returns the largest integer whose square is less than or equal to a given nonnegative integer
// - takes O(logn) time complexity and O(1) space complexity
public static int integerSquareRoot(int num) {
int L = 0;
int U = num;
int mid = -1;
while (L <= U) {
mid = L + (U - L) / 2;
if (mid * mid > num) {
U = mid - 1;
} else {
L = mid + 1;
}
}
return (mid * mid <= num) ? mid : mid - 1;
}
public static void main(String [] args) {
System.out.println(integerSquareRoot(4));
}
}
|
package domain.tiles;
import java.util.EnumMap;
import java.util.Map;
import api.TileAction;
import api.TileInfo;
import domain.Clock;
import domain.Game;
import domain.MsgQue;
import domain.Product;
import domain.Savable;
import domain.Tile;
import domain.TileState;
import exceptions.InvalidStateException;
import exceptions.InventoryFullException;
public class Factory extends Savable implements TileState {
private enum State{
NONE,IDLE,WORKING,DONE,DAMAGED;
}
private enum Actions implements TileAction {
FACTORY_START(0),
CLEAR(500),
COLLECT(0);
private Actions(int cost) {
this.cost = cost;
}
public int cost;
public int time=0;
public int getCost() {return cost;}
public int getTime() {return time;}
}
public static enum Factories implements TileAction {
BUTTERFACTORY(750,Product.BUTTER,3,Product.MILK),
CHEESEFACTORY(1000,Product.CHEESE,4,Product.MILK,Product.MILK),
FLOURFACTORY(3000,Product.FLOUR,5,Product.CORN,Product.WHEAT,Product.WHEAT),
JUICEFACTORY(5000,Product.JUICE,6,Product.STRAWBERRY,Product.RASPBERRY,Product.GRAPE,Product.GRAPE),
SALADFACTORY(15000,Product.SALAD,8,Product.CARROT,Product.LETTUCE,Product.TOMATO,Product.TOMATO),
OILFACTORY(25000,Product.CORNOIL,8,Product.CORN,Product.CORN,Product.CORN,Product.CORN,Product.CORN),
CHOCOLATEFACTORY(40000,Product.CHOCOLATE,7,Product.COCOA,Product.COCOA,Product.MILK),
BREADFACTORY(50000,Product.BREAD,6,Product.WHEAT,Product.WHEAT,Product.MILK,Product.EGGS),
TRUFFLEFACTORY(100000,Product.TRUFFLES,12,Product.COCOA,Product.COCOA,Product.CORNOIL);
EnumMap<Product,Integer> input;
Product output;
int price,time;
Factories(int price, Product output, int time, Product...input){
this.input = new EnumMap<Product,Integer>(Product.class);
for(Product prod:input){
if(this.input.containsKey(prod))
this.input.put(prod, this.input.get(prod)+1);
else
this.input.put(prod, 1);
}
this.output=output;
this.price=price;
this.time=time;
}
public Map<Product,Integer> getInput() {return input;}
public Product getOutput() {return output;}
public int getCost() {return price;}
public int getTime() {return time;}
}
Factories factory;
State state=State.NONE;
long damage;
long start;
public Factory(String type, long start, long damage, String state) {
if(type.equals("NONE"))
this.factory=null;
else
this.factory = Factories.valueOf(type);
this.start = start;
this.damage = damage;
this.state = State.valueOf(state);
}
public Factory(){
state=State.NONE;
}
public TileAction[] getActions() throws InvalidStateException {
switch(state){
case NONE:
TileAction[] actions = new TileAction[Factories.values().length+1];
int i=0;
for(Factories f:Factories.values())
actions[i++]=(TileAction) f;
actions[actions.length-1] = TileAction.Defaults.CANCEL;
return actions;
case IDLE:
Actions.FACTORY_START.time=factory.getTime();
return new TileAction[]{Actions.FACTORY_START,Actions.CLEAR};
case DONE:
return new TileAction[]{Actions.COLLECT};
default:
return null;
}
}
public TileState executeAction(TileAction action, Tile tile, long timestamp) throws InventoryFullException {
if(action instanceof domain.Storm && state == State.WORKING){
damage=timestamp;
state=State.DAMAGED;
return this;
}
if(action instanceof Factories) {
factory = (Factories) action;
state = State.IDLE;
return this;
}
if(action == TileAction.Defaults.EXPIRE) {
switch (state){
case DAMAGED:
state=State.WORKING;
start += Clock.MSECONDSADAY*2;
return this;
case WORKING:
state=State.DONE;
return this;
default:
return null;
}
}
if(action == Actions.FACTORY_START) {
if(!checkInput()){
MsgQue.get().put("MSG_FACTORY_NOINPUT", timestamp);
return null;
}
takeInput();
state=State.WORKING;
start=timestamp;
return this;
}
if(action == Actions.COLLECT) {
domain.Game.getGame().getInv().add(factory.getOutput());
state = State.IDLE;
return this;
}
if(action == Actions.CLEAR || action == TileAction.Defaults.CANCEL) {
return new None();
}
return null;
}
private void takeInput() {
for(Map.Entry<Product, Integer> entry:factory.getInput().entrySet()){
Game.getGame().getInv().remove(entry.getKey(), entry.getValue());
}
}
private boolean checkInput() {
for(Map.Entry<Product, Integer> entry:factory.getInput().entrySet()){
if(Game.getGame().getInv().get(entry.getKey()) < entry.getValue())
return false;
}
return true;
}
public long getExpiryTime() {
switch(state){
case DAMAGED: return damage+ (Clock.MSECONDSADAY * 2);
case WORKING: return start + (Clock.MSECONDSADAY * factory.getTime());
default: return 0;
}
}
public TileInfo getInfo() {
if(factory==null)
return new TileInfo(getClass().getSimpleName(), null, state.name());
return new TileInfo(getClass().getSimpleName(), factory.name(), state.name());
}
public String getType() {
if(factory==null)
return "NONE";
return factory.name();
}
public long getStart() {
return start;
}
public String getState() {
return state.name();
}
public long getDamage() {
return damage;
}
}
|
package com.qqy.ancientpoetry.crawler.prase;
import com.gargoylesoftware.htmlunit.html.DomNodeList;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.qqy.ancientpoetry.crawler.common.Page;
import java.util.function.Consumer;
/**
* 非详情页解析
* Author:qqy
*/
public class DocumentParse implements Parse {
@Override
public void parse(final Page page) {
if (page.isDetail()) {
return;
}
HtmlPage htmlPage = page.getHtmlPage();
htmlPage.getBody()
.getElementsByAttribute("div", "class", "typecont")
.forEach(new Consumer<HtmlElement>() {
@Override
public void accept(HtmlElement div) {
DomNodeList<HtmlElement> aNodelist = div.getElementsByTagName("a");
aNodelist.forEach(new Consumer<HtmlElement>() {
@Override
public void accept(HtmlElement aNode) {
String path = aNode.getAttribute("href");
Page subPage = new Page(page.getBase(), path, true);
page.getSubPage().add(subPage);
}
});
}
});
}
}
|
package com.qfc.yft;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.util.Log;
import com.qfc.yft.data.CachMsg;
import com.qfc.yft.entity.User;
import com.qfc.yft.entity.offline.JsonOffline;
import com.qfc.yft.entity.offline.OfflineData;
import com.qfc.yft.net.HttpReceiver;
import com.qfc.yft.net.JackRequestManager;
import com.qfc.yft.net.OfflineDownloadBuilder;
import com.qfc.yft.net.chat.GIMSocketServer;
import com.qfc.yft.utils.APIDesUtils;
import com.qfc.yft.utils.JackUtils;
import com.qfc.yft.utils.OfflineUtill;
import com.qfc.yft.vo.SystemParams;
public class YftValues {
final static String TAG = "YFT_VALUES";
public static int SCREEN_WIDTH, SCREEN_HEIGHT;
public static boolean FZL_RELOGIN;
public static final String NO_DATA = "暂无";
// 192.168.200.244:80 访问代理
public static final String PROXY_HOST = "192.168.200.244";//
public static final int PROXY_PORT = 80;
public static final long TIMEOUT_REQUEST = 1000 * 60 * 2;
public static final long TIMEOUT_REQUEST_10 = 1000 * 60 * 2;//
public static final String URL_FORGETPWD = "http://member.qfc.cn/my/get-password.action";
// kaifa环境
// public static final String _URL =
// "http://open.qfc.test.ctcn.com.cn/invoke/json";
//// public static final String _URL ="http://192.168.199.201:8091/invoke/json";
// public static final String OPEN_API_APP_SECRET = "iPad_shop";
// public static final String OPEN_API_APP_KEY = "iPad_shop";
// public static final String
// URL_REGISTER="http://member.qfc.test.ctcn.com.cn/my/ipad/register.action?registType=android";
public static final boolean DEBUG = false;// 测试环境
// 正式环境
public static final String _URL = "http://open.qfc.cn/invoke/json";
public static final String OPEN_API_APP_SECRET = "Can3ppGcPQDCYbRy";
public static final String OPEN_API_APP_KEY = "iPad_MShop";
public static final String URL_REGISTER = "http://member.qfc.cn/my/ipad/register.action?registType=android";
private static final String URL_APPKEY = "openApiAppKey";
private static final String URL_BUSICODE = "openApiBusiCode";
private static final String URL_TIMESTAMP = "openApiTimestamp";
private static final String URL_VALIDCODE = "openApiValidCode";
private static final String URL_USERNAME = "userName";
private static final String URL_PASSWORD = "password";
private static final String URL_USERCODE = "userCode";
private static final String URL_SHOPID = "shopId";
private static final String URL_SERIESID = "proSeriesId";
private static final String URL_PRODUCTID = "productId";// 1128
private static final String URL_RECOMMEND = "isRecommend";
private static final String URL_SEARCH = "keyword";
private static final String URL_PAGESIZE = "pageSize";
private static final String URL_PAGENO = "pageNo";
private static final String URL_SYNC = "jsonString";// ="xmlString";
private static final String URL_ACCOUNT_ID = "accountId";
private static final String URL_TO_MEMBER = "toMember";
private static final String URL_FROM_MEMBER = "fromMember";
private static final String URL_MEMBER_ID = "memberId";
private static final String URL_FROM_ID = "fromId";
private static final String URL_COLLECT_TYPE = "collectType";
public static final String REQUEST_PATH_COMPANY_PRO = "open.api.product.findSeriesByShopIdForIphone"; // 获取产品系列
public static final String REQUEST_PATH_COMPANY_SUBPRO = "open.api.product.searchProductByShopIdAndSeriesIdForIphone"; // 系列下所有产品
public static final String REQUEST_PATH_RECOMMEND = "open.api.shop.searchShopForIphone"; // 企业推荐
public static final String REQUEST_PATH_SEARCH = "open.api.shop.searchShopForIphone"; // 企业搜索接口
public static final String REQUEST_PATH_CHECKVERSION = "cn.shop.getIOSVersionConfig"; // 检查最新客户端版本
public static final String REQUEST_PATH_LOGIN = "cn.member.sso.pointVerify"; // 验证登录
public static final String REQUEST_PATH_MEMBER_INFO = "cn.member.getMemberByUserCode";// 获取用户信息
public static final String REQUEST_PATH_COMPANY_INFO = "cn.shop.getShopAndCompanyById";// 获取公司信息
// public static final String REQUEST_PATH_SYNC =
// "cn.motion.basic.parseOffLineData";//同步 1113
public static final String REQUEST_PATH_SYNC = "cn.motion.basic.parseOffLineDataForAndriod";// 1122
public static final String REQUEST_PATH_SERIESFORMOTION = "cn.product.series.getSeriesForMotion";// 1128
public static final String REQUEST_PATH_PRODUCTFORMOTION = "cn.product.getProductForMotion1";// 1128
public static final String REQUEST_CATEGORY = "cn.product.category.findAllWithJSON";
public static final String REQUEST_CARD_SEARCH = "cn.member.card.searchCardsByKeyword";// 搜索人脉
public static final String REQUEST_CARD_MY = "cn.member.card.search";// 我的人脉
public static final String REQUEST_SEARCH_PRODCUT = "open.api.product.searchProduct";// 搜索产品
public static final String REQUEST_COLLECTION_SAVE = "cn.collection.saveForOpenAPI"; // 收藏新增
public static final String REQUEST_IS_COLLECTION_PRODUCT = "cn.collection.isCollectByProductId"; // 是否收藏
public static final String REQUEST_IS_COLLECTION_COMPANY = "cn.collection.isCollectByShopId"; // 是否收藏
public static final String REQUEST_IS_ATTENTION = "cn.attention.isAttention"; // 是否收藏
public static final String REQUEST_COLLECTION_DELETE = "cn.collection.deleteForOpenAPI"; // 收藏QUXIAO
public static final String REQUEST_FIND_COMPANY = "cn.collection.findCompany";// 收藏的商铺
public static final String REQUEST_FIND_PRODUCT = "cn.collection.findProduct";// 收藏的产品
public static final String REQUEST_CARD_ADD = "cn.member.attention.doAttention";// 收藏人脉
public static final String REQUEST_CARD_REMOVE = "cn.member.attention.cancelAttention";// 取消关注人脉
public static final String REQUEST_SEARCH_IMAGINE = "open.api.keyword.searchKeyword";
public static final String REQUEST_GETSHOPBYUID = "cn.attention.getShopByMemberId";//
public static final String DES_KEY = "88211711";// "ipad_motion_key";
public static final String RESULT_SIGN = "resultSign";
public static final String RESULT_OBJECT = "resultObj";
public static final String JSON_SERIES_NAME_PRODUCTSERIES = "productSeriesName";
public static final String JSON_SERIES_NAME_PARENTSERIES = "parentSeriesName";
public static final String JSON_SERIES_ID_PRODUCT = "productSeriesId";
public static final String JSON_SERIES_PIC = "productSeriesPic";
public static final String JSON_SERIES_ID_PARENT = "parentSid";
public static final String LOC_DEFAULT_LAT = "30.100285";
public static final String LOC_DEFAULT_LON = "120.511389";
public static final String FAV_PID = "pid";
public static final String FAV_PNAME = "pname";
public static final String FAV_PPIC = "ppic";
public static final String FAV_PINTRO = "pintro";
public static final String FAV_MOTION = "motion";
public static final String SHOWPIC_PATHS = "pics";
public static final String SHOWPIC_PAGE = "page";
public static final String EXTRAS_REGISTER_URL = "url";
public static final String EXTRAS_HUB_TAB = "hubTab";
public static final String EXTRAS_HUB_KEYWORD = "hubKeyword";
public static final String EXTRAS_SHOP_NAME = "shopName";
/*
* public static final String EXTRAS_MEMBER_TYPE = "memberType"; public
* static final String EXTRAS_SHOP_ID = "shopId";
*/
public static final String EXTRAS_PRODUCT_ID = "productId";
public static final String EXTRAS_SHOP_TAB = "shopTab";
public static final String EXTRAS_SHOP_MEMBER_TYPE = "shopMemberType";
public static final String EXTRAS_ACCOUNT_ID = "accountId";
public static final String EXTRA_CATEGORY_ID = "secondCategoryId";
public static final String PREF_LOCAL = ".local";
public static final int DEFULAT_PAGESIZE = 10;
public enum RequestType {
NONE, POINT_VERIFY(REQUEST_PATH_LOGIN), MEMBER_INFO(
REQUEST_PATH_MEMBER_INFO), SHOP_INFO(REQUEST_PATH_COMPANY_INFO), SERIES_INFO(
REQUEST_PATH_COMPANY_PRO), PRODUCT_INFO(
REQUEST_PATH_COMPANY_SUBPRO), SEARCH_RECOMMEND(
REQUEST_PATH_RECOMMEND), SEARCH(REQUEST_PATH_SEARCH), UPDATE(
REQUEST_PATH_CHECKVERSION), SYNC(REQUEST_PATH_SYNC), SM(
REQUEST_PATH_SERIESFORMOTION), PM(REQUEST_PATH_PRODUCTFORMOTION), CATEGORY_ALL(
REQUEST_CATEGORY), CARDSEARCH(REQUEST_CARD_SEARCH), CARDMY(
REQUEST_CARD_MY), SEARCH_PRODUCT(REQUEST_SEARCH_PRODCUT), COLLECTION_SAVE(
REQUEST_COLLECTION_SAVE), COLLECTION_DELETE(
REQUEST_COLLECTION_DELETE), FIND_COMPANY(REQUEST_FIND_COMPANY), FIND_PRODUCT(
REQUEST_FIND_PRODUCT), CARD_ADD(REQUEST_CARD_ADD), CARD_REMOVE(
REQUEST_CARD_REMOVE), SEARCH_IMAGINE(REQUEST_SEARCH_IMAGINE), ISCOLLECTEDSHOP(
REQUEST_IS_COLLECTION_COMPANY), ISATTENTION(
REQUEST_IS_ATTENTION), ISCOLLECTEDPRODUCT(
REQUEST_IS_COLLECTION_PRODUCT), USERSHOP(REQUEST_GETSHOPBYUID);
private RequestType(String loc) {
this.location = loc;
}
private RequestType() {
this("");
}
private String location;
@Override
public String toString() {
return location;
}
public Map<String, String> getParamMap(String... params) {
Map<String, String> result = new HashMap<String, String>();
int size = params.length;
switch (this) {
case POINT_VERIFY:
String pwdDesStr;
try {
pwdDesStr = new APIDesUtils().encrypt(params[1], DES_KEY);
result.put(URL_USERNAME, params[0]);
result.put(URL_PASSWORD, pwdDesStr);
} catch (Exception e) {
Log.e(TAG, "密码加密有问题");
}
break;
case MEMBER_INFO:
result.put(URL_USERCODE, params[0]);
break;
case SHOP_INFO:
result.put(URL_SHOPID, params[0]);
break;
case SERIES_INFO:
result.put(URL_SHOPID, params[0]);
break;
case PRODUCT_INFO:// shopId,proSeriesId(系列id),pageSize(每次请求的产品数量10),pageNo(每次请求索引从1开始)
if (size < 4)
break;
result.put(URL_SHOPID, params[0]);
if (!params[1].isEmpty())
result.put(URL_SERIESID, params[1]);
result.put(URL_PAGESIZE, params[2]);
result.put(URL_PAGENO, params[3]);
break;
case SEARCH_RECOMMEND:
if (size < 3)
break;
result.put(URL_RECOMMEND, params[0]);
result.put(URL_PAGESIZE, params[1]);
result.put(URL_PAGENO, params[2]);
break;
case SEARCH:
if (size < 3)
break;
result.put(URL_SEARCH, params[0]);
result.put(URL_PAGESIZE, params[1]);
result.put(URL_PAGENO, params[2]);
break;
case UPDATE:
break;
case SYNC:
result.put(URL_SYNC, params[0]);
break;
case SM:// 1128
result.put(URL_SERIESID, params[0]);
break;
case PM:// 1128
result.put(URL_PRODUCTID, params[0]);
break;
case CATEGORY_ALL:
result.put("status", "1");
break;
case CARDSEARCH:// String keyword, Integer pageSize, Integer pageNo
result.put(URL_SEARCH, params[0]);
result.put(URL_PAGESIZE, params[1]);
result.put(URL_PAGENO, params[2]);
break;
case CARDMY:// Long accountId, Integer pageSize, Integer pageNo
result.put(URL_ACCOUNT_ID, params[0]);
if (params.length > 1)
result.put(URL_PAGESIZE, params[1]);
if (params.length > 2)
result.put(URL_PAGENO, params[2]);
break;
case SEARCH_PRODUCT:
result.put(URL_SEARCH, params[0]);// 1. keyword(关键字)
// result.put("cateCodes", "001");//2.
// cateCodes(分类代码,多个用逗号分开.比如:“001,002”) //TODO
result.put(URL_PAGESIZE, params[1]);
result.put(URL_PAGENO, params[2]);
break;
case COLLECTION_SAVE:
result.put(URL_ACCOUNT_ID, params[0] + "");// 36662
result.put(URL_FROM_ID, params[1] + "");// 14723
result.put(URL_COLLECT_TYPE, params[2] + "");// 0 产品 3 商铺
result.put("collectTitle", params[3]);// ?
break;
case COLLECTION_DELETE:
// Long accountId, Long fromId, Integer collectType
result.put(URL_ACCOUNT_ID, params[0]);// 36662
result.put(URL_FROM_ID, params[1]);// 14723
result.put(URL_COLLECT_TYPE, params[2]);// 0 产品 3 商铺
break;
case FIND_COMPANY:// Long accountId, Integer pageNo, Integer
// pageSize
result.put(URL_ACCOUNT_ID, params[0] + "");
if (params.length > 1)
result.put(URL_PAGESIZE, params[1]);
if (params.length > 2)
result.put(URL_PAGENO, params[2]);
break;
case FIND_PRODUCT:// Long accountId, Integer pageNo, Integer
// pageSize
result.put(URL_ACCOUNT_ID, params[0] + "");
if (params.length > 1)
result.put(URL_PAGESIZE, params[1]);
if (params.length > 2)
result.put(URL_PAGENO, params[2]);
break;
case CARD_ADD:// Long fromMember,Long toMember,String fromIp
result.put(URL_FROM_MEMBER, params[0]);
result.put(URL_TO_MEMBER, params[1]);
result.put("fromIp", "wtf");
break;
case CARD_REMOVE:
result.put(URL_FROM_MEMBER, params[0]);
result.put(URL_TO_MEMBER, params[1]);
break;
case SEARCH_IMAGINE:// {keyword=h, pageSize=3, searchType=product}
result.put(URL_SEARCH, params[0]);
result.put(URL_PAGESIZE, params[1]);
result.put("searchType", params[2]);
break;
case ISCOLLECTEDPRODUCT:// Integer productId, Long accountId
result.put(URL_PRODUCTID, params[0]);
result.put(URL_ACCOUNT_ID, params[1]);
break;
case ISCOLLECTEDSHOP:// Long shopId, Long accountId
result.put(URL_SHOPID, params[0]);
result.put(URL_ACCOUNT_ID, params[1]);
break;
case ISATTENTION:// Long memberId, Long accountId
result.put(URL_MEMBER_ID, params[0]);
result.put(URL_ACCOUNT_ID, params[1]);
break;
case USERSHOP:
result.put(URL_MEMBER_ID, params[0]);
break;
default:
break;
}
return result;
}
}
public static String getHTTPBodyString(RequestType type, String... params) {
Map<String, String> paramKV = new HashMap<String, String>();
paramKV.put(URL_APPKEY, OPEN_API_APP_KEY);
paramKV.put(URL_BUSICODE, type.toString());
paramKV.put(URL_TIMESTAMP, JackUtils.getTimeStamp());// TODO 时区
paramKV.putAll(type.getParamMap(params));
return finishTheURL(paramKV);
}
public static JSONObject getResultObject(String json) throws JSONException {
JSONObject job = new JSONObject(json);
if (job.has(RESULT_SIGN)) {
if (job.getBoolean(RESULT_SIGN)) {
return job.getJSONObject(RESULT_OBJECT);
} else {
// TODO 请求失败
}
}
return null;
}
private static String finishTheURL(Map<String, String> map) {
StringBuffer url, valid;
url = new StringBuffer();
valid = new StringBuffer();
// 排序
String[] arrays = new String[] {};
arrays = map.keySet().toArray(arrays);
Arrays.sort(arrays);
// 验签
for (String str : arrays) {
valid.append(str).append(map.get(str));
url.append(str).append("=").append(new String(map.get(str)))
.append("&");
}
valid.append(OPEN_API_APP_SECRET);
// Log.i(TAG, "valid::"+valid);
Log.i(TAG, "url::" + url);
// 拼接
url.append(URL_VALIDCODE).append("=")
.append(JackUtils.getMD5(valid.toString()));
return url.toString();
}
public static void tryGetOfflineDataHere(HttpReceiver receiver) {
if (receiver == null)
return;
if (YftData.data().isMe() && YftData.data().getMe() != null) {
int shopId = YftData.data().getMe().getShopId();
// try local
String param = YftValues.getOffdataAsParam(shopId);
try {
JSONObject job = new JSONObject(param);
if (null == job)
;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// JackUtils.writeToSomeWhere(YftApplication.getApp(), param);
// do network
if (!param.isEmpty())
JackRequestManager.getInstance().tryRequest(
YftValues.getHTTPBodyString(RequestType.SYNC, param),
receiver, 3000);
} else {
Log.e(TAG, "try offline data failed");
}
}
public static String getOffdataAsParam(int shopId) {
JsonOffline od = YftData.data().getOfflineData();
String param = "";
try {
if (od == null) {
param = OfflineUtill.initOfflineJsonStr(shopId + "");
} else {
param = od.toJsonStr();
}
} catch (JSONException e) {
e.printStackTrace();
}
return param;
}
public static String getMyLocalPath() {
User user = YftData.data().getMe();
if (user == null)
return "00";
int shid = user.getShopId();
return Environment.getExternalStorageDirectory().getPath()
+ "/qfc/imgs/" + shid;
}
public static void logout() {
try {
YftApplication.app().unregisterReceiver(
YftApplication.app().getUIBadgeReceiver());// TODO tobe
// test
YftApplication.app().stopService(
new Intent(YftApplication.app(), GIMSocketServer.class));
if (!OfflineDownloadBuilder.shouldStart()) {
OfflineDownloadBuilder.cancel();// 0421
}
} catch (Exception e) {
e.printStackTrace();
}
CachMsg.getInstance().clear();// 0319
YftData.data().destroy();
// fzl
SystemParams.getInstance().clear();
CachMsg.getInstance().clear();
}
public static final String EXTRAS_SINGLEBACK = "singleback";
public static final String HINT_NOCHAT = "该用户没有纺织聊账号,请考虑其他联系方式";
// private static NotificationManager nm;
public static int notification_id = 19172439;
/**
* ugly ,temp
*/
public static boolean isopen(Context context) {
if (!JackUtils.isOpenNetwork()) {
OfflineData offlineData = YftData.data().getOfflineData();
if (offlineData != null) {
JackUtils.showToast(context, "请检查您的网络或切换到离线模式");
} else {
JackUtils.showToast(context, "请检查您的网络");
}
return false;
}
return true;
}
}
|
package typecastingexample;
/**
*
* @author valen
*/
import java.util.*;
public class TypeCastingExample {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
double floatValue;
int intValue;
System.out.println("Enter a floating point value.");
Scanner in = new Scanner(System.in);
floatValue = in.nextDouble();
intValue = (int)floatValue;
System.out.println("The floating value "+floatValue+" "
+ "type casts to the integer value " +intValue);
}
}
|
package cs261_project.config;
import java.util.Properties;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.sqlite.SQLiteConfig;
/**
* Configurate the database connectors
* @author Group 12 - Stephen Xu, JuanYan Huo, Ellen Tatum, JiaQi Lv, Alexander Odewale
*/
@Configuration
public class DatabaseConfiguration {
//Database name goes here, the root location is /app/, same as which for build.gradle
private static final String DATABASE_NAME = "data.db";
public DatabaseConfiguration(){
}
@Bean
static public DataSource dataSource(){
DriverManagerDataSource source = new DriverManagerDataSource();
//tell JDBC something about the database we are using
source.setDriverClassName("org.sqlite.JDBC");
source.setUrl("jdbc:sqlite:" + DatabaseConfiguration.DATABASE_NAME);
//enable foreign key
Properties prop = new Properties();
prop.setProperty("foreign_keys", "true");
source.setConnectionProperties(prop);
return source;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(){
LocalContainerEntityManagerFactoryBean entity = new LocalContainerEntityManagerFactoryBean();
//since Spring doesn't support SQLite, we need to tell the API how to use it...
entity.setDataSource(DatabaseConfiguration.dataSource());
entity.setPersistenceXmlLocation("classpath:/static/persistence/persistence.xml");
//entity.setPackagesToScan("");
entity.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
return entity;
}
}
|
package com.codingame.gameengine.core;
import java.util.ArrayList;
import java.util.List;
import com.google.inject.Inject;
import com.google.inject.Provider;
/**
* The representation of the a player's AI during the game's execution.
*
*/
public abstract class AbstractPlayer {
@Inject Provider<GameManager<AbstractPlayer>> gameManagerProvider;
/**
* An Exception thrown by <code>getOutputs()</code> when the player's AI did not respond in time after an <code>execute()</code>.
* <p>
* You can change the timeout value with <code>GameManager</code>'s <code>setTurnMaxTime</code> method.
* </p>
*
*/
public static class TimeoutException extends Exception {
private static final long serialVersionUID = 42L;
}
private int index;
private List<String> inputs = new ArrayList<>();
private List<String> outputs;
private boolean active = true;
private boolean timeout;
private int score;
private boolean hasBeenExecuted;
private boolean hasNeverBeenExecuted = true;
/**
* Returns a string that will be converted into the real nickname by the viewer.
*
* @return the player's nickname token.
*/
public final String getNicknameToken() {
return "$" + this.index;
}
/**
* Returns an integer that will be converted into the player's real color by the viewer.
*
* @return the player's color token.
*/
public final int getColorToken() {
return -(this.index + 1);
}
/**
* Returns a string that will be converted into the real avatar by the viewer, if it exists.
*
* @return the player's avatar token.
*/
public final String getAvatarToken() {
return "$" + this.index;
}
/**
* Returns true is the player is still active in the game (can be executed).
*
* @return true is the player is active.
*/
public final boolean isActive() {
return this.active;
}
/**
* Get player index from 0 (included) to number of players (excluded).
*
* @return the player index.
*/
public final int getIndex() {
return this.index;
}
/**
* Get current score.
*
* @return current player score
*/
public final int getScore() {
return this.score;
}
/**
* Set current score. This is used to rank the players at the end of the game.
*
* @param score
*/
public final void setScore(int score) {
this.score = score;
}
/**
* Deactivate a player. The player can't play after this and is no longer in the list of active players.
*/
public final void deactivate() {
this.deactivate(null);
}
/**
* Deactivate a player and adds a tooltip with the reason. The player can't play after this and is no longer in the list of active players.
*
* @param reason
* Message to display in the tooltip.
*/
public final void deactivate(String reason) {
this.active = false;
if (reason != null) {
gameManagerProvider.get().addTooltip(new Tooltip(index, reason));
}
}
/**
* Adds a new line to the input to send to the player on execute.
*
* @param line
* The input to send.
*/
public final void sendInputLine(String line) {
if (hasBeenExecuted) {
throw new RuntimeException("Impossible to send new inputs after calling execute");
}
if (this.gameManagerProvider.get().getOuputsRead()) {
throw new RuntimeException("Sending input data to a player after reading any output is forbidden.");
}
this.inputs.add(line);
}
/**
* Executes the player for a maximum of turnMaxTime milliseconds and store the output.
*/
public final void execute() {
gameManagerProvider.get().execute(this);
this.hasBeenExecuted = true;
this.hasNeverBeenExecuted = false;
}
/**
* Gets the output obtained after an execution.
*
* @return a list of output lines
* @throws TimeoutException
*/
public final List<String> getOutputs() throws TimeoutException {
this.gameManagerProvider.get().setOuputsRead(true);
if (!this.hasBeenExecuted) {
throw new RuntimeException("Can't get outputs without executing it!");
}
if (this.timeout) {
throw new TimeoutException();
}
return this.outputs;
}
/**
* Returns the number of lines that the player must return.
*
* If the player do not write that amount of lines before the timeout delay, no outputs at all will be available for this player. The game engine
* will not read more than the expected output lines. Extra lines will be available for next turn.
*
* @return the expected amount of lines the player must output
*/
public abstract int getExpectedOutputLines();
//
// The following methods are only used by the GameManager:
//
final void setIndex(int index) {
this.index = index;
}
final List<String> getInputs() {
return this.inputs;
}
final void resetInputs() {
this.inputs = new ArrayList<>();
}
final void resetOutputs() {
this.outputs = null;
}
final void setOutputs(List<String> outputs) {
this.outputs = outputs;
}
final void setTimeout(boolean timeout) {
this.timeout = timeout;
}
final boolean hasBeenExecuted() {
return hasBeenExecuted;
}
final void setHasBeenExecuted(boolean hasBeenExecuted) {
this.hasBeenExecuted = hasBeenExecuted;
}
final boolean hasNeverBeenExecuted() {
return hasNeverBeenExecuted;
}
}
|
package saboteur.ai;
import saboteur.model.Operation;
public class MediumDwarfComputer extends Computer {
/**
*
*/
private static final long serialVersionUID = 5038175066629537120L;
@Override
void operationCollapseCard(Operation o) {
// TODO Auto-generated method stub
}
@Override
void operationPathCard(Operation o) {
// TODO Auto-generated method stub
}
@Override
void operationSabotageCard(Operation o) {
// TODO Auto-generated method stub
}
@Override
void operationDoubleRescueCard(Operation o) {
// TODO Auto-generated method stub
}
@Override
void operationRescueCard(Operation o) {
// TODO Auto-generated method stub
}
@Override
void operationPlanCard(Operation o) {
// TODO Auto-generated method stub
}
}
|
package com.bistel.common;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.MasterNotRunningException;
import org.apache.hadoop.hbase.ZooKeeperConnectionException;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.HTableInterface;
import org.apache.hadoop.hbase.client.HTablePool;
import org.apache.hadoop.hbase.filter.BinaryComparator;
import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;
import org.apache.hadoop.hbase.filter.Filter;
import org.apache.hadoop.hbase.filter.FilterList;
import org.apache.hadoop.hbase.filter.FilterList.Operator;
import org.apache.hadoop.hbase.filter.ValueFilter;
import org.apache.hadoop.hbase.util.Bytes;
import com.google.protobuf.ServiceException;
public class HbaseUtil
{
private static HTablePool hTablePool = null;
private static final Log LOG = LogFactory.getLog( HbaseUtil.class );
private static Configuration config = HBaseConfiguration.create();
private static Map<String, HTable> tableMap = new HashMap<String, HTable>();
static {
config.addResource( BistelConstants.HBASE_SITE_XML );
}
/**
* This method is used for getting a connection to a hbase table
* @param tableName
* @return HTable instance
* @throws IOException
*/
public static HTable getHbaseTableConnection( String tableName )
throws IOException
{
if ( !tableMap.containsKey( tableName ) ) {
tableMap.put( tableName, HbaseUtil.getConnectionToHbaseTable( tableName ) );
}
return tableMap.get( tableName );
}
/**
* The method creates a cache of connections to base table using the same configuration to use Hbase table connections optimally
* @throws IOException
*/
public static void setUpForMR(String tableName)
throws IOException
{
try {
HBaseAdmin.checkHBaseAvailable( config );
} catch( MasterNotRunningException e ) {
LOG.info( "HBase is not running!" );
System.exit( 1 );
} catch( ZooKeeperConnectionException e ) {
LOG.info( "Problem with connecting to Zookeeper Ensemble!" );
System.exit( 1 );
} catch (ServiceException e) {
LOG.info( "ServiceException " + e.getMessage());
System.exit( 1 );
}
tableMap.put( tableName, HbaseUtil.getConnectionToHbaseTable( tableName ) );
}
/**
* The metho uses Hbase connection pool to pull HTable connection from the Pool.
* @throws IOException
*/
public static void setUpForWeb()
throws IOException
{
HbaseUtil.createHTablePool();
}
/**
* The method closes the HBasePool.
* @throws IOException
*/
public static void cleanUpForWeb()
throws IOException
{
HbaseUtil.closeHTablePool();
}
/**
* Create filter for getting values between a given range, including extreme values. <B>Equivalent to >= && <= operator</B>.
* @param val1
* String Lower value of the range
* @param val2
* String Higher value of the range
* @return Filter
* @see ValueFilter
*/
public static Filter getFilterForValueRangeInclusive( String val1, String val2 )
{
Filter filter1 = new ValueFilter( CompareOp.GREATER_OR_EQUAL, new BinaryComparator( Bytes.toBytes( val1 ) ) );
Filter filter2 = new ValueFilter( CompareOp.LESS_OR_EQUAL, new BinaryComparator( Bytes.toBytes( val2 ) ) );
List<Filter> filters = Arrays.asList( filter1, filter2 );
return new FilterList( Operator.MUST_PASS_ALL, filters );
}
/**
* This method closes connection with a given HBase table.
* @param table
* Table name
* @throws ZooKeeperConnectionException
* @throws IOException
*/
private static void createHTablePool()
{
try {
HBaseAdmin.checkHBaseAvailable( config );
} catch( MasterNotRunningException e ) {
LOG.info( "HBase is not running!" );
System.exit( 1 );
} catch( ZooKeeperConnectionException e ) {
LOG.info( "Problem with connecting to Zookeeper Ensemble!" );
System.exit( 1 );
} catch (ServiceException e) {
LOG.info( "ServiceException " + e.getMessage());
System.exit( 1 );
} catch (IOException e) {
LOG.info( "IOException " + e.getMessage());
System.exit( 1 );
}
hTablePool = new HTablePool( config, 50 );
}
private static void closeHTablePool()
throws IOException
{
if ( hTablePool != null )
// hTablePool.close();
hTablePool = null;
}
/**
* This method connect to a given HTable
* @param tableName
* HBase table name to be connected with.
* @return HTable
* @throws IOException
*/
public static HTableInterface getTableFromPool( String tableName )
throws IOException
{
if ( tableName == null ){
throw new IOException( "Invalid input for getting connection to table " + tableName );
}
if(hTablePool==null){
createHTablePool();
}
return hTablePool.getTable( tableName );
}
/**
* This method closes connection with a given HBase table.
* @param table
* Table name
* @throws IOException
*/
public static void returnTableToPool( HTableInterface table )
{
try {
hTablePool.putTable( table );
} catch (IOException e) {
LOG.info( "IOException " + e.getMessage());
System.exit( 1 );
}
}
/**
* The method returns a connection with HTable with the given name.
* @param tableName
* String table Name
* @return HTable
* @throws IOException
*/
public static HTable getConnectionToHbaseTable( String tableName )
throws IOException
{
return new HTable( config, tableName );
}
/**
* <p>
* See {@link #setconfig(Configuration)}
* </p>
* @return Returns the config.
*/
public static final Configuration getConfig()
{
return config;
}
} |
package com.juancrud.miscontactos.restApi.deserializador;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.juancrud.miscontactos.pojo.Contacto;
import com.juancrud.miscontactos.restApi.JsonKeys;
import com.juancrud.miscontactos.restApi.model.ContactoResponse;
import java.lang.reflect.Type;
import java.util.ArrayList;
public class ContactoDeserializador implements JsonDeserializer<ContactoResponse> {
@Override
public ContactoResponse deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
Gson gson = new Gson();
ContactoResponse contactoResponse = gson.fromJson(json, ContactoResponse.class);
JsonArray contactoResponseData = json.getAsJsonObject().getAsJsonArray(JsonKeys.MEDIA_RESPONSE_ARRAY);
contactoResponse.setContactos(deserializadorContactoDeJson(contactoResponseData));
return contactoResponse;
}
private ArrayList<Contacto> deserializadorContactoDeJson(JsonArray contactoResponseData) {
ArrayList<Contacto> contactos = new ArrayList<>();
for (int i = 0; i < contactoResponseData.size(); i++) {
JsonObject contactoResponseDataObject = contactoResponseData.get(i).getAsJsonObject();
JsonObject userJson = contactoResponseDataObject.getAsJsonObject(JsonKeys.USER);
String id = userJson.get(JsonKeys.USER_ID).getAsString();
String nombreCompleto = userJson.get(JsonKeys.USER_FULLNAME).getAsString();
JsonObject imageJson = contactoResponseDataObject.getAsJsonObject(JsonKeys.MEDIA_IMAGES);
JsonObject stdResolutionJson = imageJson.getAsJsonObject(JsonKeys.MEDIA_STANDARD_RESOLUTION);
String urlFoto = stdResolutionJson.get(JsonKeys.MEDIA_URL).getAsString();
JsonObject likesJson = contactoResponseDataObject.getAsJsonObject(JsonKeys.MEDIA_LIKES);
int likes = likesJson.get(JsonKeys.MEDIA_LIKES_COUNT).getAsInt();
Contacto contacto = new Contacto();
contacto.setId(id);
contacto.setNombreCompleto(nombreCompleto);
contacto.setUrlFoto(urlFoto);
contacto.setLikes(likes);
contactos.add(contacto);
}
return contactos;
}
}
|
package br.com.wasys.gfin.cheqfast.cliente.model;
import android.content.Context;
import android.support.annotation.DrawableRes;
import android.support.annotation.StringRes;
import br.com.wasys.gfin.cheqfast.cliente.Application;
import br.com.wasys.gfin.cheqfast.cliente.R;
import br.com.wasys.library.model.Model;
/**
* Created by pascke on 11/08/17.
*/
public class ContaBancoModel extends Model {
public Status status;
public String banco;
public String agencia;
public String conta;
public String cpfCnpj;
public String nomeTitular;
public Double valor;
public Double custo;
public Double valorTransferencia;
public enum Status {
ATIVO (R.string.ativo),
INATIVO (R.string.inativo),
HISTORICO (R.string.historico);
public int stringRes;
Status(@StringRes int stringRes) {
this.stringRes = stringRes;
}
}
}
|
package com.api.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.api.domain.Metrics;
import com.api.interf.MetricsRepositoryCustom;
@Repository
public interface MetricsRepository extends CrudRepository<Metrics, Long> , MetricsRepositoryCustom {
}
|
/* Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where:
'.' Matches any single character.????
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
Example 1:
Input: s = "aa", p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".
Example 2:
Input: s = "aa", p = "a*"
Output: true
Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa".
Example 3:
Input: s = "ab", p = ".*"
Output: true
Explanation: ".*" means "zero or more (*) of any character (.)".
Example 4:
Input: s = "aab", p = "c*a*b"
Output: true
Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore, it matches "aab".
Example 5:
Input: s = "mississippi", p = "mis*is*p*."
Output: false
*/
class Solution {
public boolean isMatch(String s, String p) {
if(p.isEmpty()){
return s.isEmpty();
}
boolean firstMatch =(!s.isEmpty() && (p.charAt(0)== s.charAt(0)|| p.charAt(0)=='.'));
if (p.length()>=2 && p.charAt(1)=='*')
// Check the first characters if not empty.
{
return (isMatch(s,p.substring(2)) || (firstMatch && isMatch(s.substring(1),p)));
// Recusively check with first match wheather substring is matching or not.
It will get incremented automatically.
}
else{
return(firstMatch && isMatch(s.substring(1), p.substring(1)));
// Else String is less than 2
}
}
} |
package com.example.jobbay;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class JobDetails extends AppCompatActivity {
private TextView mTitle;
private TextView mDate;
private TextView mCompany;
private TextView mDescription;
private TextView mSkills;
private TextView mSalary;
private TextView mLocation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_job_details);
mTitle = findViewById(R.id.job_details_title);
mDate = findViewById(R.id.job_details_date);
mCompany = findViewById(R.id.job_details_company);
mDescription = findViewById(R.id.job_details_description);
mSkills = findViewById(R.id.job_details_skills);
mSalary = findViewById(R.id.job_details_salary);
mLocation = findViewById(R.id.job_details_location);
//Recieve data from all job activity using intent...
Intent intent = getIntent();
String title = intent.getStringExtra("title");
String date = intent.getStringExtra("date");
String company = intent.getStringExtra("company name");
String description = intent.getStringExtra("description");
String skills = intent.getStringExtra("skills");
String location = intent.getStringExtra("location");
mTitle.setText(title);
mDate.setText(date);
mCompany.setText(company);
mDescription.setText(description);
mSkills.setText(skills);
mLocation.setText(location);
}
}
|
package br.com.candleanalyser.advisors;
import br.com.candleanalyser.calculators.TrendChannelCalculator;
import br.com.candleanalyser.engine.Candle;
import br.com.candleanalyser.engine.Helper;
import br.com.candleanalyser.util.FixedQueue;
public class TrendChannelAdvisor implements SellAdvisor, BuyAdvisor {
private TrendChannelCalculator trendChannel;
private Candle lastCandle;
private FixedQueue<Candle> delayedQueue;
private int direction;
private int confirmationCandles;
public TrendChannelAdvisor(int channelNumberOfCandles, float containedCandlesRatio, int trendDelayDays, int confirmationCandles) {
this.trendChannel = new TrendChannelCalculator(channelNumberOfCandles, containedCandlesRatio, false);
this.delayedQueue = new FixedQueue<Candle>(trendDelayDays);
this.confirmationCandles = confirmationCandles;
}
@Override
public void nextCandle(Candle candle) {
//keep trend channel at 3 days ago
delayedQueue.add(candle);
if(delayedQueue.isFull()) {
trendChannel.addCandle(delayedQueue.get(0));
}
//define direction
if(lastCandle!=null) {
if(candle.getClose()>lastCandle.getClose()) {
if(direction>0) direction++;
else direction = 1;
} else if(candle.getClose()<lastCandle.getClose()) {
if(direction<0) direction--;
else direction = -1;
} else {
direction = 0;
}
}
lastCandle = candle;
}
@Override
public float getBuyStrength() {
if(!trendChannel.isFull()) return 0;
//breaking tendency strategy
double diffToUpper = lastCandle.getClose() - trendChannel.getUpperPrice(lastCandle.getDate().getTime());
if(diffToUpper>0) {
if(direction>confirmationCandles) {
return 1;
}
}
return 0;
//top/bottom channel strategy
// double potential = trendChannel.getMainPrice2() - lastCandle.getClose();
// return (float)Helper.clamp(potential/trendChannel.getChannelWidth(), -1, 1);
}
@Override
public float getSellStrength() {
if(!trendChannel.isFull()) return 0;
//breaking tendency strategy
double diffToUpper = lastCandle.getClose() - trendChannel.getLowerPrice(lastCandle.getDate().getTime());
if(diffToUpper<0) {
if(direction<-confirmationCandles) {
return 1;
}
}
return 0;
//if trend line is 30 degrees (down trend), sell is 1!
//top/bottom channel strategy
// return (float)Helper.clamp(-getBuyStrength() + ((float)trendChannel.getMainTrendLine().getB()/0.57F), -1, 1);
}
@Override
public String getCurrentInfo() {
if(trendChannel.getMainTrendLine()==null) return null;
return "buy=" + Helper.formatNumber(getBuyStrength()) + "; sell=" + Helper.formatNumber(getBuyStrength()) + "; b=" + Helper.formatNumber(trendChannel.getMainTrendLine().getB());
}
public TrendChannelCalculator getTrendChannel() {
return trendChannel;
}
@Override
public void onBuy(float value) {
}
@Override
public void onSell(float value) {
}
}
|
package apps.configs.netty;
import org.springframework.context.annotation.Configuration;
@Configuration
public class NettyConfig {
}
|
package com.nikita.recipiesapp.views.recipes;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import com.nikita.recipiesapp.App;
import com.nikita.recipiesapp.R;
import com.nikita.recipiesapp.actions.SelectRecipe;
import com.nikita.recipiesapp.common.AppState;
import com.nikita.recipiesapp.common.models.Recipe;
import com.nikita.recipiesapp.common.redux.Renderer;
import com.nikita.recipiesapp.common.utils.GridLayoutManagerDividerDecoration;
import com.nikita.recipiesapp.views.steps.StepListActivity;
public final class RecipesActivity extends AppCompatActivity implements Renderer<AppState> {
private AppBarLayout appBar;
private final RecipesController recipesController = new RecipesController(this::onRecipeSelection);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recipes_activity);
appBar = findViewById(R.id.app_bar);
setSupportActionBar(findViewById(R.id.toolbar));
RecyclerView recyclerView = findViewById(R.id.recycler_view);
int spanCount = getResources().getInteger(R.integer.recipes_column_count);
Drawable divider = getResources().getDrawable(R.drawable.item_offset_divider);
GridLayoutManagerDividerDecoration offsetItemDecoration = new GridLayoutManagerDividerDecoration(divider, divider, spanCount);
recyclerView.setLayoutManager(new GridLayoutManager(this, spanCount));
recyclerView.addItemDecoration(offsetItemDecoration);
recyclerView.setAdapter(recipesController.getAdapter());
App.appStore.subscribe(this);
}
@Override
public void render(@NonNull AppState appState) {
recipesController.setData(appState.recipes, appState.isDataLoading);
String error = appState.error;
if (error != null && !error.isEmpty()) {
Snackbar.make(appBar, error, Snackbar.LENGTH_INDEFINITE).show();
}
String notification = appState.notification;
if (notification != null && !notification.isEmpty()) {
Snackbar.make(appBar, notification, Snackbar.LENGTH_INDEFINITE).show();
}
}
private void onRecipeSelection(Recipe recipe) {
App.appStore.dispatch(new SelectRecipe(recipe));
startActivity(new Intent(this, StepListActivity.class));
}
}
|
package com.clicky.semarnat.adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.clicky.semarnat.R;
import com.parse.ParseObject;
import java.util.List;
/**
*
* Created by Clicky on 4/3/15.
*
*/
public class EmpresasAdapter extends ArrayAdapter<ParseObject> {
private LayoutInflater inflater;
public EmpresasAdapter(Context context, int resource, List<ParseObject> items) {
super(context, resource, items);
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
ViewHolder holder;
if (view == null) {
view = inflater.inflate(R.layout.item_empresa, parent, false);
holder = new ViewHolder();
holder.txtEmpresa = (TextView) view.findViewById(R.id.txt_empresa);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
ParseObject empresa = getItem(position);
holder.txtEmpresa.setText(empresa.getString("Nombre"));
return view;
}
private static class ViewHolder {
TextView txtEmpresa;
}
}
|
package com.oracle.curd.bean;
public class Manager {
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column manager.managerid
*
* @mbg.generated Wed Dec 23 13:56:28 CST 2020
*/
private String managerid;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column manager.managername
*
* @mbg.generated Wed Dec 23 13:56:28 CST 2020
*/
private String managername;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column manager.card
*
* @mbg.generated Wed Dec 23 13:56:28 CST 2020
*/
private String card;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column manager.sex
*
* @mbg.generated Wed Dec 23 13:56:28 CST 2020
*/
private String sex;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column manager.tel
*
* @mbg.generated Wed Dec 23 13:56:28 CST 2020
*/
private String tel;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column manager.stafftype
*
* @mbg.generated Wed Dec 23 13:56:28 CST 2020
*/
private String stafftype;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column manager.pwd
*
* @mbg.generated Wed Dec 23 13:56:28 CST 2020
*/
private String pwd;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column manager.managerid
*
* @return the value of manager.managerid
*
* @mbg.generated Wed Dec 23 13:56:28 CST 2020
*/
public String getManagerid() {
return managerid;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column manager.managerid
*
* @param managerid the value for manager.managerid
*
* @mbg.generated Wed Dec 23 13:56:28 CST 2020
*/
public void setManagerid(String managerid) {
this.managerid = managerid == null ? null : managerid.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column manager.managername
*
* @return the value of manager.managername
*
* @mbg.generated Wed Dec 23 13:56:28 CST 2020
*/
public String getManagername() {
return managername;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column manager.managername
*
* @param managername the value for manager.managername
*
* @mbg.generated Wed Dec 23 13:56:28 CST 2020
*/
public void setManagername(String managername) {
this.managername = managername == null ? null : managername.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column manager.card
*
* @return the value of manager.card
*
* @mbg.generated Wed Dec 23 13:56:28 CST 2020
*/
public String getCard() {
return card;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column manager.card
*
* @param card the value for manager.card
*
* @mbg.generated Wed Dec 23 13:56:28 CST 2020
*/
public void setCard(String card) {
this.card = card == null ? null : card.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column manager.sex
*
* @return the value of manager.sex
*
* @mbg.generated Wed Dec 23 13:56:28 CST 2020
*/
public String getSex() {
return sex;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column manager.sex
*
* @param sex the value for manager.sex
*
* @mbg.generated Wed Dec 23 13:56:28 CST 2020
*/
public void setSex(String sex) {
this.sex = sex == null ? null : sex.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column manager.tel
*
* @return the value of manager.tel
*
* @mbg.generated Wed Dec 23 13:56:28 CST 2020
*/
public String getTel() {
return tel;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column manager.tel
*
* @param tel the value for manager.tel
*
* @mbg.generated Wed Dec 23 13:56:28 CST 2020
*/
public void setTel(String tel) {
this.tel = tel == null ? null : tel.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column manager.stafftype
*
* @return the value of manager.stafftype
*
* @mbg.generated Wed Dec 23 13:56:28 CST 2020
*/
public String getStafftype() {
return stafftype;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column manager.stafftype
*
* @param stafftype the value for manager.stafftype
*
* @mbg.generated Wed Dec 23 13:56:28 CST 2020
*/
public void setStafftype(String stafftype) {
this.stafftype = stafftype == null ? null : stafftype.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column manager.pwd
*
* @return the value of manager.pwd
*
* @mbg.generated Wed Dec 23 13:56:28 CST 2020
*/
public String getPwd() {
return pwd;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column manager.pwd
*
* @param pwd the value for manager.pwd
*
* @mbg.generated Wed Dec 23 13:56:28 CST 2020
*/
public void setPwd(String pwd) {
this.pwd = pwd == null ? null : pwd.trim();
}
@Override
public String toString() {
return "Manager{" +
"managerid='" + managerid + '\'' +
", managername='" + managername + '\'' +
", card='" + card + '\'' +
", sex='" + sex + '\'' +
", tel='" + tel + '\'' +
", stafftype='" + stafftype + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
} |
/*
* 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 PPI.Vistas.Interfaces;
import javax.swing.Icon;
/**
*
* @author Personal
*/
public interface InterfazReservasAdmin {
public void setTextLblImagenPublicar(String texto);
public void setIconLblImagenPublicar(Icon icono);
public void setTextLblNombreProducto(String texto);
public void setTextLblCantidadDeReserva(String texto);
public void setTextLblPrecio(String texto);
public void setTextLblCorreo(String texto);
public int getWidthImagen();
public int getHeightImagen();
public void reservaClickedModificar(int idReserva);
public void reservaClickedEliminar(int idReserva);
}
|
/**
* NOTE: This class is auto generated by the swagger code generator program (2.3.1).
* https://github.com/swagger-api/swagger-codegen
* Do not edit the class manually.
*/
package io.swagger.api;
import io.swagger.model.Operation;
import io.swagger.annotations.*;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;
import javax.validation.Valid;
import javax.validation.constraints.*;
import java.util.List;
@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2018-03-28T08:27:01.906Z")
@Api(value = "Account", description = "the Account API")
public interface AccountApi {
@ApiOperation(value = "Finds Account by ID", nickname = "findAccountbyID", notes = "Multiple status values can be provided with comma separated strings", response = Operation.class, responseContainer = "List", tags={ "Account", })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "successful operation", response = Operation.class, responseContainer = "List"),
@ApiResponse(code = 404, message = "le compte n'existe pas") })
@RequestMapping(value = "/Account/Operation",
produces = { "application/xml", "application/json" },
method = RequestMethod.GET)
ResponseEntity<List<Operation>> findAccountbyID(@NotNull @ApiParam(value = "Status values that need to be considered for filter", required = true) @Valid @RequestParam(value = "ID", required = true) String ID);
}
|
package com.caiyi.interfaces;
import android.content.Context;
import android.graphics.Canvas;
import android.view.MotionEvent;
public interface ITrendChart {
void draw(Canvas canvas, int i, int i2, int i3, int i4, float f);
boolean getCanScale();
boolean[] getCanScroll();
float[] getScaleRange();
int[] getScrollRange();
void initChart(Context context, int i, int i2, float f);
boolean onClick(MotionEvent motionEvent, float f, float f2, int i, int i2, float f3);
boolean onLongClick(MotionEvent motionEvent, float f, float f2, int i, int i2, float f3);
void reCalcScroll(float f, int i, int i2);
void setInitPosition();
}
|
package exam03;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class Histogram {
public static final String FILL_CHAR = "*";
public String createHistogram(BufferedReader reader) {
StringBuilder builder = new StringBuilder();
try(reader) {
String line;
while ((line = reader.readLine()) != null) {
int repeatNumber = Integer.parseInt(line);
builder.append(FILL_CHAR.repeat(repeatNumber))
.append("\n");
}
} catch (IOException e) {
throw new IllegalStateException("File read error");
}
return builder.toString();
}
public static void main(String[] args) throws IOException {
System.out.println( new Histogram().createHistogram(Files.newBufferedReader(Path.of("exam2test.txt"))));
}
}
|
package com.example.datepikertimepiker;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
//import android.support.annotation.RequiresPermission;
import android.text.InputType;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
public class MainActivity extends Activity implements OnClickListener {
EditText et_dt_picker,et_tm_picker;
//@RequiresApi(api = Build.VERSION_CODES.N)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewsById();
}
public void onClick(View v) {
if(v == et_dt_picker) {
showDatePicker();
}
if(v == et_tm_picker) {
showTimePicker();
}
}
private void findViewsById() {
et_dt_picker = (EditText) findViewById(R.id.btn_dt_picker);
et_tm_picker = (EditText) findViewById(R.id.btn_tm_picker);
et_dt_picker.setInputType(InputType.TYPE_NULL);
et_tm_picker.setInputType(InputType.TYPE_NULL);
et_dt_picker.requestFocus();
et_dt_picker.setOnClickListener(this);
et_tm_picker.setOnClickListener(this);
// TODO Auto-generated method stub
}
private void showTimePicker() {
Calendar mcurrentTime = Calendar.getInstance();
int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
int minute = mcurrentTime.get(Calendar.MINUTE);
TimePickerDialog mTimePicker;
mTimePicker = new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
et_tm_picker.setText( selectedHour + ":" + selectedMinute);
// TODO Auto-generated method stub
}
}, hour, minute, true);//Yes 24 hour time
mTimePicker.setTitle("Select Time");
mTimePicker.show();
// TODO Auto-generated method stub
}
private void showDatePicker() {
Calendar mcurrentDate=Calendar.getInstance();
final int mYear=mcurrentDate.get(Calendar.YEAR);
final int mMonth=mcurrentDate.get(Calendar.MONTH);
final int mDay=mcurrentDate.get(Calendar.DAY_OF_MONTH);
DatePickerDialog mDatePicker=new DatePickerDialog(MainActivity.this, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday) {
// TODO Auto-generated method stub
selectedmonth=selectedmonth+1;
et_dt_picker.setText(selectedday+"/"+selectedmonth+"/"+selectedyear);
}
},mYear, mMonth, mDay);
mDatePicker.setTitle("Select date");
mDatePicker.show();
}
}
|
package kxg.searchaf.url.saks_cat;
import java.util.ArrayList;
import java.util.List;
public class SaksPage {
public String url;
public SaksPage(String url) {
this.url = url;
}
public static List<SaksPage> getWomenSale() {
ArrayList<SaksPage> urllist = new ArrayList<SaksPage>();
// String type = "sale";
// String category = "";
// page 1
String url = "http://www.saksfifthavenue.com/search/EndecaSearch.jsp?N=306418048+1553";
SaksPage page = new SaksPage(url);
urllist.add(page);
for (int i = 1; i < 10; i++) {
String url1 = url + "&Nao=" + i * 60;
page = new SaksPage(url1);
urllist.add(page);
}
// page 2
// url =
// "http://www.saksfifthavenue.com/search/EndecaSearch.jsp?Nao=180&N=306418048+1553";
// page = new SaksPage(url);
// urllist.add(page);
return urllist;
}
public static List<SaksPage> getMakeUPSale() {
ArrayList<SaksPage> urllist = new ArrayList<SaksPage>();
// String type = "sale";
// String category = "";
// page 1
String url = "http://www.saksfifthavenue.com/Beauty-and-Fragrance/For-Her/shop/_/N-52flrm?FOLDER%3C%3Efolder_id=2534374306418162";
SaksPage page = new SaksPage(url);
urllist.add(page);
for (int i = 1; i < 100; i++) {
String url1 = url + "&Nao=" + i * 60;
page = new SaksPage(url1);
urllist.add(page);
}
// for (int i = 1; i < 42; i++) {
// String url1 = url + "&Nao=" + i * 60;
// page = new SaksPage(url1);
// urllist.add(page);
// }
// page 2
// url =
// "http://www.saksfifthavenue.com/search/EndecaSearch.jsp?Nao=180&N=306418048+1553";
// page = new SaksPage(url);
// urllist.add(page);
return urllist;
}
}
|
package de.varylab.discreteconformal.unwrapper.koebe;
import java.util.HashMap;
import de.jtem.halfedge.Edge;
import de.jtem.halfedge.Face;
import de.jtem.halfedge.HalfEdgeDataStructure;
import de.jtem.halfedge.Vertex;
public class KoebePolyhedronContext<
V extends Vertex<V, E, F>,
E extends Edge<V, E, F>,
F extends Face<V, E, F>
> {
public HalfEdgeDataStructure<V, E, F>
circlePattern = null,
medial = null,
polyhedron = null;
public HashMap<E, E>
edgeEdgeMap = null;
public HashMap<E, V>
edgeVertexMap = null;
public HashMap<F, F>
faceFaceMap = null;
public HashMap<V, F>
vertexFaceMap = new HashMap<V, F>();
public V
northPole = null;
public HashMap<E, E> getEdgeEdgeMap() {
return edgeEdgeMap;
}
public HalfEdgeDataStructure<V, E, F> getMedial() {
return medial;
}
public HalfEdgeDataStructure<V, E, F> getPolyeder() {
return polyhedron;
}
public HashMap<E, V> getEdgeVertexMap() {
return edgeVertexMap;
}
public V getNorthPole() {
return northPole;
}
public void setNorthPole(V northPole) {
this.northPole = northPole;
}
} |
package com.clouway.task1;
import java.util.Random;
/**
* Stefan.Dimitrov
*/
public class StringGenerator {
public StringGenerator(){
}
/**
* Generates a random string from printable ascii characters
* @param length specifies the number of characters the string should have
* @return the generated string
*/
public static String randString(int length){
Random rndGen = new Random();
StringBuffer strBuff = new StringBuffer(length);
for(int i=0; i<length; i++){
int asciiChar;
asciiChar = 33 + rndGen.nextInt(93);
strBuff.append((char)asciiChar);
}
return strBuff.toString();
}
}
|
package demo;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
//import javax.servlet.annotation.WebInitParam;
//import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//@WebServlet(urlPatterns = {"/name"},initParams = {@WebInitParam(name = "name",value = "Fasttrack Se 2020")})
public class Config extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String name = super.getServletConfig().getInitParameter("name");
resp.setContentType("text/html");
PrintWriter pw = resp.getWriter();
pw.println("Xin chao "+name);
}
}
|
package example;
public interface IDeviceWriter {
public String saveToDevice();
}
|
/*
* 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 laundry;
/**
*
* @author User
*/
public class Pegawai {
private long idpeg;
private Person[] person;
private int nPerson;
public Pegawai(long idpeg, int nPerson) {
this.idpeg = idpeg;
person = new Person[nPerson];
}
public void addPerson(String nama, String kelamin, String alamat, String tgl_lahir){
getPerson()[nPerson++] = new Person(nama,kelamin,alamat,tgl_lahir);
}
public long getIdpeg() {
return idpeg;
}
public void setIdpeg(long idpeg) {
this.idpeg = idpeg;
}
public Person[] getPerson() {
return person;
}
public void setPerson(Person[] person) {
this.person = person;
}
}
|
import java.util.*;
import java.lang.Iterable;
class Shuffle2 extends Shuffle{
//___Class Member:__
//decide the joker card from 52 cards
int taken=(int)((Math.random())*52+3);
//___Class Method__
//Distribute Card to 4 players
//Override distribute method
void distribute(Player0 p0,Player1 p1,Player2 p2,Player3 p3){
int j=3; //the number of card
while(j<55)
{
if(j==taken)
{j++;
continue;}
int x=(int)((Math.random())*4);
switch(x)
{
//Use "if" to make sure the # of hand-card will be 14,14,13,13 for Player 0 to 3
case 0:
if(t0<13)
{
p0.setcard(j);
t0++;
j++;}
break;
case 1:
if(t1<13)
{
p1.setcard(j);
t1++;
j++;}
break;
case 2:
if(t2<13)
{
p2.setcard(j);
t2++;
j++;}
break;
case 3:
if(t3<12)
{
p3.setcard(j);
t3++;
j++;}
break;
default: //If someone who have already got his maximum # of card get another new card this turn, this turn will be skipped
continue;
}
}
}
//show the joker card
String getjoker(Card cd){
return cd.getcard(taken);
}
} |
package br.unb.poo.mh;
public abstract class ExpressaoUnaria implements Expressao {
protected Expressao expEsquerda;
public ExpressaoUnaria(Expressao expEsquerda) {
this.expEsquerda = expEsquerda;
}
}
|
package RootClasses;
/**
* Class made on 26.06.2018
* Class made at 14:55
* Creator: Howhannes O.
*/
public class Infos
{
private static int kartennummer;
public static void setKartennummer(int nummer){
kartennummer=nummer;
}
public static int getKartennummer(){
return kartennummer;
}
}
|
package com.esum.router.monitor.control;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.TabularDataSupport;
import org.quartz.core.jmx.QuartzSchedulerMBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.esum.framework.common.util.DateUtil;
import com.esum.framework.core.component.ComponentManagerFactory;
import com.esum.framework.core.config.Configurator;
import com.esum.framework.core.exception.FrameworkException;
import com.esum.framework.core.management.ManagementException;
import com.esum.framework.core.management.resource.SchedulerControl;
import com.esum.framework.core.node.table.NodeInfo;
import com.esum.router.monitor.MonitorCode;
import com.esum.router.monitor.dao.MonitorDaoFactory;
import com.esum.router.monitor.dao.QuartzDao;
import com.esum.router.monitor.notify.Notifier;
import com.esum.router.monitor.vo.QuartzStatus;
import com.esum.router.table.monitor.MonitorInfoRecord;
public class QuartzMonitor implements ResourceMonitor {
private Logger logger = LoggerFactory.getLogger(QuartzMonitor.class);
private MonitorInfoRecord batchInfo;
private String traceId;
private int timeout;
private String host;
private int port;
private SchedulerControl control;
@Override
public void initResource() {
this.traceId = "["+batchInfo.getNodeId()+"]["+batchInfo.getBatchId()+"] ";
if(logger.isDebugEnabled())
logger.debug(traceId+"Quartz Monitor called.");
try {
this.timeout = Configurator.getInstance().getInt("quartz.active.timeout", 300);
} catch (FrameworkException e) {
}
try {
NodeInfo nodeInfo = ComponentManagerFactory.getInstance().getComponentManager(batchInfo.getNodeId()).getNodeInfo(batchInfo.getNodeId());
this.host = nodeInfo.getHostName();
this.port = nodeInfo.getPort();
} catch (Exception e) {
logger.error(traceId+"Server connection failed.", e);
}
}
@Override
public void callByCron() {
long stime = System.currentTimeMillis();
if(logger.isDebugEnabled())
logger.debug(traceId+"Checking Quartz Scheduler status.");
if(control==null) {
try {
control = SchedulerControl.getControl(host, port);
} catch (ManagementException e) {
logger.error(traceId+"Could not get SchedulerControl.", e);
return;
}
}
QuartzDao quartzDao = null;
try {
QuartzSchedulerMBean mbean = control.getDefaultQuartzScheduler();
quartzDao = MonitorDaoFactory.getInstance().createDao(QuartzDao.class);
TabularDataSupport data = (TabularDataSupport)mbean.getCurrentlyExecutingJobs();
Iterator<Object> i = data.keySet().iterator();
while(i.hasNext()) {
Collection<?> key = (Collection<?>)i.next();
CompositeData value = data.get(key.toArray());
if(logger.isDebugEnabled()) {
logger.debug(traceId+"["+value.get("jobName").toString()+
"]"+value.get("fireTime").toString()+value.get("nextFireTime").toString());
}
insertQuartzStatus(quartzDao, value);
if(isNotFired((Date)value.get("nextFireTime"))) {
String message = "Job is not executed. jobName("+value.get("jobName+")+")";
Notifier.sendNotify(batchInfo.getNodeId(), MonitorCode.TYPE_ERROR, message);
}
}
} catch(Exception e){
logger.warn(traceId+"Quartz Monitoring failed.", e);
} finally {
if(quartzDao!=null)
quartzDao.close();
closeResource();
}
logger.info(traceId+"Quartz Monitoring completed. elapsed time : "+(System.currentTimeMillis()-stime)+"ms");
}
@Override
public void closeResource() {
try {
if(control!=null)
control.close();
} catch (Exception e) {
}
control = null;
}
private void insertQuartzStatus(QuartzDao quartzDao, CompositeData value) {
QuartzStatus quartzStatus = new QuartzStatus();
try {
quartzStatus.setLogDate(DateUtil.getCYMD());
quartzStatus.setLogTime(DateUtil.getHHMISSS());
quartzStatus.setJobName(value.get("jobName").toString());
quartzStatus.setNodeId(batchInfo.getNodeId());
quartzStatus.setTriggerName(value.get("triggerName").toString());
quartzStatus.setFireTime(DateUtil.format("yyyyMMddHHmmssSSS", (Date)value.get("fireTime")));
quartzStatus.setNextFireTime(DateUtil.format("yyyyMMddHHmmssSSS", (Date)value.get("nextFireTime")));
quartzDao.insert(quartzStatus);
quartzDao.commit();
} catch (Exception e) {
logger.error(traceId+"Status insert failed. {] {} {} {}",
quartzStatus.getLogDate(),
quartzStatus.getLogTime(),
quartzStatus.getNodeId(),
quartzStatus.getJobName(),
e);
quartzDao.rollback();
}
}
protected boolean isNotFired(Date nextFireTime) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.SECOND, -(timeout));
if(nextFireTime.getTime()<cal.getTimeInMillis()) {
return true;
}
return false;
}
@Override
public void setBatchInfo(MonitorInfoRecord batchInfo) {
this.batchInfo = batchInfo;
}
}
|
package client;
public class MoreComplexObserver extends ConcreteObserver implements Runnable {
public MoreComplexObserver(ConcreteSubject[] subjects) {
super(subjects);
Thread t = new Thread(this);
t.start();
}
private String speaking = "";
private String time = "";
private Object origin=null;
@Override
public synchronized void update(Message m) {
//System.out.println("received a "+ m.payload+" message from "+m.origin);
if(m.topic=="time") {
time = m.payload;
origin = m.origin;
}
else if(m.topic =="speaking") {
speaking = m.payload;
}
}
@Override
public void run() {
while(true) {
try {
speaking = "no";
Thread.sleep(5000);
System.out.println("The last click from clock "+origin+" was at "+time);
if(speaking=="no") {
System.out.println("No one spoke during the last 5 seconds");
} else {
System.out.println("Someone spoke during the last 5 seconds");
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
|
package com.pruebatecnicaomar.PruebaTecnicaOmar.dto;
import java.util.Date;
import lombok.Data;
@Data
public class CoinHistorial {
private Long id;
private Date fecha;
private Criptomoneda moneda;
public CoinHistorial() {
super();
// TODO Auto-generated constructor stub
}
public CoinHistorial(Long id, Date fecha, Criptomoneda moneda) {
super();
this.id = id;
this.fecha = fecha;
this.moneda = moneda;
}
}
|
package com.turo.stepdef;
import com.turo.pages.MainPage;
import com.turo.utils.ConfigurationReader;
import com.turo.utils.MyDriver;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.turo.pages.Base.waitSomeTime;
public class MainPageSteps {
Logger logger = LoggerFactory.getLogger(MainPageSteps.class);
MainPage mainPage = new MainPage();
@Given("user is in landing page")
public void userIsInLandingPage() {
MyDriver.get().get(ConfigurationReader.getProperty("baseUrl"));
MyDriver.get().manage().deleteAllCookies();
// MyDriver.get().navigate().refresh();
waitSomeTime(5L);
String expected = "Turo | The world's largest car sharing marketplace";
String actual = MyDriver.get().getTitle();
Assert.assertEquals(expected,actual);
logger.info("Turo.com website title is {}", actual);
}
@Then("Verify that Turo logo is present")
public void verifyThatTuroLogoIsPresent() {
mainPage.logo.isDisplayed();
logger.info("Turo logo is displayed");
}
@Then("Verify that {string} is present")
public void verifyThatIsPresent(String value) {
mainPage.verifyTheFields(value);
}
@Then("Verify that Liberty mutual insurance logo is present")
public void verifyThatLibertyMutualInsuranceLogoIsPresent() {
mainPage.verifyInsuranceLogo();
}
}
|
package com.selfspring.gimi.algo;
import com.alibaba.fastjson.JSON;
import org.junit.Test;
/**
* Created by ckyang on 2019/7/23.
*/
public class AlgorithmTest {
@Test
public void testTwoSum() throws Exception {
System.out.println(JSON.toJSONString(Algorithm.twoSum(new int[]{2,7,11,13},9)));
}
} |
package cn.novelweb.tool.upload.qcloud;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.novelweb.tool.upload.qcloud.callback.ListObjectCompletionHandler;
import com.alibaba.fastjson.JSONObject;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.MultiObjectDeleteException;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import com.qcloud.cos.transfer.TransferManager;
import com.qcloud.cos.transfer.Upload;
import lombok.extern.slf4j.Slf4j;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
/**
* <p>腾讯云上传</p>
* <p>2019-11-23 15:47</p>
*
* @author Dai Yuanchuan
**/
@Slf4j
public class CosUpload {
/**
* 腾讯云secretId信息
*/
public static String secretId;
/**
* 腾讯云secretKey信息
*/
public static String secretKey;
/**
* 存储桶的名称 如 qcloud-1256166828
* 在存储桶列表中的所属地域查看
* 存储桶名称格式:BucketName-APPID
*/
public static String bucket;
/**
* cos 地区 regionName = new com.qcloud.cos.region.Region("ap-shanghai");
* 可用区域简称 Region 参考下表
* 地域 地域简称
* 北京一区(华北) ap-beijing-1
* 北京 ap-beijing
* 上海(华东) ap-shanghai
* 广州(华南) ap-guangzhou
* 成都(西南) ap-chengdu
* 重庆 ap-chongqing
* 香港 ap-hongkong
* 新加坡 ap-singapore
* 多伦多 na-toronto
* 法兰克福 eu-frankfurt
* 孟买 ap-mumbai
* 首尔 ap-seoul
* 硅谷 na-siliconvalley
* 弗吉尼亚 na-ashburn
* 曼谷 ap-bangkok
* 莫斯科 eu-moscow
*/
public static Region regionName;
/**
* 使用临时密钥时需要指定
* 临时密钥允许操作的权限列表
* 简单上传、表单上传和分片上传需要以下的权限
* 其他权限参考 //cloud.tencent.com/document/product/436/31923
*/
public static String[] allowActions = new String[]{
// 简单上传
"name/cos:PutObject",
// 表单上传、小程序上传
"name/cos:PostObject",
// 分片上传
"name/cos:InitiateMultipartUpload",
"name/cos:ListMultipartUploads",
"name/cos:ListParts",
"name/cos:UploadPart",
"name/cos:CompleteMultipartUpload"
};
/**
* 使用 永久密钥 初始化 COSClient
*
* @return 返回 永久密钥 COSClient 对象
*/
public static COSClient initCosClient() {
COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
ClientConfig clientConfig = new ClientConfig(regionName);
return new COSClient(cred, clientConfig);
}
/**
* 使用自定义的 ClientConfig 类
* 使用 永久密钥 初始化 COSClient
*
* @param clientConfig 自定义的 ClientConfig 类 参考:https://cloud.tencent.com/document/product/436/10199
* @return 返回 永久密钥 COSClient 对象
*/
public static COSClient initCosClient(ClientConfig clientConfig) {
COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
return new COSClient(cred, clientConfig);
}
/**
* 创建存储桶
* 用户确定地域和存储桶名称后,即可创建存储桶
* 创建存储桶需要使用永久密钥初始化的COSClient
*
* @param regionName cos 地区,定义你要在哪创建这个存储桶 "ap-shanghai"
* @param bucket 需要创建的存储桶名称,格式:BucketName-APPID
* @param controlList 存储桶 bucket 的权限 PublicRead(公有读私有写), 其他可选有私有读写, 公有读写
* @return 返回存储桶对象
*/
public static Bucket createBucket(String regionName, String bucket, CannedAccessControlList controlList) {
// 获取COS客户端实例
COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
ClientConfig clientConfig = new ClientConfig(new Region(regionName));
COSClient cosClient = new COSClient(cred, clientConfig);
CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucket);
createBucketRequest.setCannedAcl(controlList);
return cosClient.createBucket(createBucketRequest);
}
/**
* 查询存储桶列表
* 查询用户的存储桶列表
*
* @return 存储桶列表
*/
public static List<Bucket> getBucketList() {
COSClient cosClient = initCosClient();
return cosClient.listBuckets();
}
/**
* 查询存储桶列表
* 查询用户的存储桶列表
* 使用自定义的cos客户端
*
* @param cosClient 自定义的cos客户端
* @return 存储桶列表
*/
public static List<Bucket> getBucketList(COSClient cosClient) {
return cosClient.listBuckets();
}
/**
* 创建目录
* 创建目录 实际上就是创建一个 以 / 为结尾的空文件
*
* @param cosClient cos 客户端
* @param key 目录的名称
* @return 返回创建目录的请求结果
*/
public static PutObjectResult mkdir(COSClient cosClient, String key) {
// 目录对象即是一个/结尾的空文件,上传一个长度为 0 的 byte 流
InputStream input = new ByteArrayInputStream(new byte[0]);
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(0);
PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, key, input, objectMetadata);
return cosClient.putObject(putObjectRequest);
}
/**
* 简单的将本地文件上传到COS
* 适用于20M以下图片类小文件上传,最大支持上传不超过5GB文件
* 若 COS 上已存在同样 Key 的对象,上传时则会覆盖旧的对象。
*
* @param cosClient 构建的cos客户端
* @param file 需要上传的本地文件(小于20M以下)
* @param key 对象键(Key)是对象在存储桶中的唯一标识
* @return 返回简单上传的请求结果
*/
public static PutObjectResult uploader(COSClient cosClient, File file, String key) {
return cosClient.putObject(bucket, key, file);
}
/**
* 简单的从输入流上传(需提前告知输入流的长度, 否则可能导致 oom)
* 适用于20M以下图片类小文件上传,最大支持上传不超过5GB文件
* 若 COS 上已存在同样 Key 的对象,上传时则会覆盖旧的对象。
*
* @param cosClient 构建的cos客户端
* @param cosFile 数据流
* @param key 对象键(Key)是对象在存储桶中的唯一标识
* @param contentType 设置 Content type, 默认是 application/octet-stream
* @return 返回简单上传的请求结果
*/
public static PutObjectResult uploader(COSClient cosClient, InputStream cosFile,
String key, String contentType) {
ObjectMetadata objectMetadata = new ObjectMetadata();
try {
objectMetadata.setContentLength(cosFile.available());
objectMetadata.setContentType(contentType);
return cosClient.putObject(bucket, key, cosFile, objectMetadata);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 上传对象
* 上传接口根据用户文件的长度,自动选择简单上传以及分块上传
* 用户不用关心分块上传的每个步骤。
*
* @param cosClient 构建的cos客户端
* @param file 需要上传的本地文件
* @param key 对象键(Key)是对象在存储桶中的唯一标识
* @param threadSize 需要构建的线程池大小
* 建议在客户端与 COS 网络充足的情况下,设置成16或32即可
* 对于使用公网传输且网络带宽质量不高的情况,建议减小该值,避免因网速过慢,造成请求超时
* @return 返回 Upload 实例,可以查询上传是否结束,也可同步的等待上传结束。
* 如果想同步的等待上传结束,则调用 upload.waitForCompletion() 方法
*/
public static Upload uploader(COSClient cosClient, File file, String key, int threadSize) {
ExecutorService threadPool = ThreadUtil.newExecutor(threadSize);
TransferManager transferManager = new TransferManager(cosClient, threadPool);
PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, key, file);
return transferManager.upload(putObjectRequest);
}
/**
* 下载对象
* 下载对象到本地
*
* @param cosClient 构建的cos客户端
* @param file 需要写入到本地的文件
* @param key 对象键,需要进行下载的对象key值
* @return 返回文件的属性 ObjectMetadata,包含文件的自定义头和 content-type 等属性。
*/
public static ObjectMetadata download(COSClient cosClient, File file, String key) {
GetObjectRequest getObjectRequest = new GetObjectRequest(bucket, key);
return cosClient.getObject(getObjectRequest, file);
}
/**
* 删除单个指定的对象
*
* @param cosClient 构建的cos客户端
* @param key 对象键,你需要删除的对象key值
* @return 返回删除状态:true 删除成功 false:删除失败
*/
public static boolean delete(COSClient cosClient, String key) {
return delete(cosClient, key, bucket);
}
/**
* 删除单个指定的对象
* 指定删除存储桶下指定的对象
*
* @param cosClient 构建的 cos 客户端
* @param key 对象键,你需要删除的对象key值
* @param bucketName 指定存储桶的名称,Bucket 的命名格式为 BucketName-APPID
* @return 返回删除状态:true 删除成功 false:删除失败
*/
public static boolean delete(COSClient cosClient, String key, String bucketName) {
try {
cosClient.deleteObject(bucketName, key);
return true;
} catch (Exception e) {
return false;
}
}
/**
* 指定存储桶删除多个对象
* 删除多个指定的对象
*
* @param cosClient 构建的cos客户端
* @param bucketName 指定存储桶的名称,Bucket 的命名格式为 BucketName-APPID
* @param key 对象键数组,你需要删除的对象key值列表,最多一次删除1000个
* @return 返回删除状态:true 删除成功 false:删除失败
*/
public static boolean delete(COSClient cosClient, String bucketName, String... key) {
if (ArrayUtil.isEmpty(key)) {
return false;
}
// 设置要删除的key列表, 最多一次删除1000个
List<DeleteObjectsRequest.KeyVersion> keyList = new ArrayList<>();
for (String str : key) {
keyList.add(new DeleteObjectsRequest.KeyVersion(str));
}
DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest(bucketName);
deleteObjectsRequest.setKeys(keyList);
// 批量删除文件
try {
cosClient.deleteObjects(deleteObjectsRequest);
return true;
} catch (MultiObjectDeleteException mde) {
log.error("部分删除成功部分失败:{}", JSONObject.toJSON(mde.getErrors()));
log.error("已经删除的key:{}", mde.getDeletedObjects());
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 删除多个对象
* 删除多个指定的对象
*
* @param cosClient 构建的cos客户端
* @param key 对象键数组,你需要删除的对象key值列表,最多一次删除1000个
* @return 返回删除状态:true 删除成功 false:删除失败
*/
public static boolean delete(COSClient cosClient, String... key) {
return delete(cosClient, bucket, key);
}
/**
* 查询存储桶中的文件列表
* 查询存储桶下的部分或者全部对象
*
* @param cosClient COS客户端
* @param prefix 你需要列出的目录前缀
* 如:images/ 表示列出的object的key以images/开始
* @param delimiter 表示分隔符,设置为/表示列出当前目录下的object,设置为空表示列出所有的object
* @param maxKeys 设置最大遍历出多少个对象,一次listObject最大支持1000
* @param handler 获取完成后的回调接口
*/
public static void getFilesList(COSClient cosClient, String prefix,
String delimiter, int maxKeys,
ListObjectCompletionHandler handler) {
ListObjectsRequest listObjectsRequest = new ListObjectsRequest();
listObjectsRequest.setBucketName(bucket);
listObjectsRequest.setPrefix(prefix);
listObjectsRequest.setDelimiter(delimiter);
listObjectsRequest.setMaxKeys(maxKeys);
ObjectListing objectListing;
try {
do {
objectListing = cosClient.listObjects(listObjectsRequest);
List<String> commonPrefixes = objectListing.getCommonPrefixes();
List<COSObjectSummary> cosObjectSummaries = objectListing.getObjectSummaries();
String nextMarker = objectListing.getNextMarker();
listObjectsRequest.setMarker(nextMarker);
handler.complete(commonPrefixes, cosObjectSummaries);
} while (objectListing.isTruncated());
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package br.edu.fadam.estruturadedados.ead.aula4.revisao;
public class TesteArvoreBinaria {
public static void main(String[] args) {
ArvoreBinaria arvoreBinaria = new ArvoreBinaria();
System.out.println("A árvore está vazia? " + (arvoreBinaria.isArvoreVazia() ? "Siiim!" : "Nao"));
//7 3 2 10 11 4
NoBinario no1 = new NoBinario();
no1.valor = 7;
NoBinario no2 = new NoBinario();
no2.valor = 3;
NoBinario no3 = new NoBinario();
no3.valor = 2;
NoBinario no4 = new NoBinario();
no4.valor = 10;
NoBinario no5 = new NoBinario();
no5.valor = 11;
NoBinario no6 = new NoBinario();
no6.valor = 4;
arvoreBinaria.adicionar(no1);
arvoreBinaria.adicionar(no2);
arvoreBinaria.adicionar(no3);
arvoreBinaria.adicionar(no4);
arvoreBinaria.adicionar(no5);
arvoreBinaria.adicionar(no6);
arvoreBinaria.percorrerPreOrdem();
arvoreBinaria.percorrerEmOrdem();
arvoreBinaria.percorrerPosOrdem();
}
}
|
package cn.tedu.reivew;
//day10 接口练习
public class Test3 {
public static void main(String[] args) {
Pigeon p=new Pigeon();
p.eggnumber=6;
p.fly();
p.layEggs();
Swallow s=new Swallow();
s.eggnumber=8;
s.fly();
s.layEggs();
s.makehome();
Ant a=new Ant();
a.eggnumber=100;
a.fly();
a.spawn();
Bee b=new Bee();
b.eggnumber=200;
b.fly();
b.spawn();
b.makehoney();
}
}
interface FlyAnimal{
void fly();
}
abstract class Bird {
int legnumber=2;
int eggnumber;
public abstract void layEggs();
}
abstract class Insect{
int legnumber=6;
int eggnumber;
public abstract void spawn();
}
class Pigeon extends Bird implements FlyAnimal{
@Override
public void fly() {
System.out.println("小鸽子可以飞");
}
@Override
public void layEggs() {
System.out.println("小鸽子下蛋数为:"+eggnumber);
}
}
class Swallow extends Bird implements FlyAnimal{
@Override
public void fly() {
System.out.println("小燕子可以飞");
}
@Override
public void layEggs() {
System.out.println("小燕子下蛋数:"+eggnumber);
}
public void makehome(){
System.out.println("小燕子可以用口水筑巢");
}
}
class Ant extends Insect implements FlyAnimal{
@Override
public void fly() {
System.out.println("小蚂蚁可以飞");
}
@Override
public void spawn() {
System.out.println("小蚂蚁蚕卵数:"+eggnumber);
}
}
class Bee extends Insect implements FlyAnimal{
@Override
public void fly() {
System.out.println("小蜜蜂可以飞");
}
@Override
public void spawn() {
System.out.println("小蜜蜂产卵数:"+eggnumber);
}
public void makehoney(){
System.out.println("蜜蜂可以造蜂蜜");
}
}
|
package com.cinema.sys.utils.spring;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.io.IOUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.cinema.sys.dao.SqlMapper;
import com.cinema.sys.utils.ExcelImportUtil;
import com.cinema.sys.utils.MyUUID;
import com.cinema.sys.utils.PoiUtil;
import com.cinema.sys.utils.SafeSqlUtil;
import com.cinema.sys.utils.TimeUtil;
@Service
public class DataImportUtil {
@Autowired
private SqlMapper sqlDao;
private DecimalFormat df = new DecimalFormat("###############");//15位数字
private SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//单次导入的记录数
// private int singleRows=10;
private void deleteExcelTable(String excelTable) {
sqlDao.execSql("delete from "+excelTable);
}
public MultipartFile getFile(HttpServletRequest request) throws Exception{
Iterator<String> fileNames = ((MultipartHttpServletRequest) request).getFileNames();
MultipartFile file=fileNames.hasNext()? ((MultipartHttpServletRequest) request).getFile(fileNames.next()):null;
if (file==null) {
throw new Exception("未读取到上传文件!");
}
return file;
}
// CellType 类型 值
// CELL_TYPE_NUMERIC 数值型 0
// CELL_TYPE_STRING 字符串型 1
// CELL_TYPE_FORMULA 公式型 2
// CELL_TYPE_BLANK 空值 3
// CELL_TYPE_BOOLEAN 布尔型 4
// CELL_TYPE_ERROR 错误 5
/**
* excel文件导入到数据库对应的excel数据表
*/
public int excel2DbTable(HttpSession session,MultipartFile file,String dbTable,Map<String, String> typeMap,String head,String titles,int singleRows) throws Exception{
if (session.getAttribute("isUpdate") != null) {
throw new Exception("存在未完成的上传任务,请稍后再试!");
}
session.setAttribute("isUpdate", true);//文件正在上传
session.setAttribute("gropress", 0);
deleteExcelTable(dbTable);
int total=0;
InputStream in=null;
try {
PoiUtil eu1 = new PoiUtil();//用来读取源xls
//第一次导入
in = file.getInputStream();
session.setAttribute("gropress", 0.01);
Workbook xwb = ExcelImportUtil.getWorkbook(file.getOriginalFilename(), in);
Sheet sheet = xwb.getSheetAt(0);// 读取第一个sheet页内容
List<Row> rows=eu1.readExcel(xwb);
session.setAttribute("gropress", 0.05);
total=rows.size()-1;
eu1.setEndSheetIdx(0);
String title="";
String values="";
String sql="";
int j=0;
//检查excel表头格式
Row titleRow=rows.get(0);
for (int i = titleRow.getFirstCellNum(); i < titleRow.getLastCellNum(); i++) {
if(titleRow.getCell(i) !=null) {
title=titleRow.getCell(i).getStringCellValue().trim();
if((","+head+",").indexOf(","+title+",")==-1)
throw new Exception("excel表头格式不正确,正确表头应包含:"+head);
}
}
// titles=titles.substring(0, titles.length()-1);//去掉最后,号
String[] titleArr=titles.split(",");
// titles="\""+titles.replace(",", "\",\"")+"\"";
titles=String.format("insert into %s(row_num,error,id,create_time,%s)values(#values#);", dbTable,titles);
Integer celltype=0;
j=0;
String rowStr="";
Cell cell;
for (Row row : rows){
if(row.getCell(0) !=null && j>0){//排除首行为空的情况
values="";
for (int i = row.getFirstCellNum(); i < titleArr.length; i++) {
celltype=row.getCell(i).getCellType();
cell=row.getCell(i);
String type=typeMap.get(titleArr[i])==null?"string":typeMap.get(titleArr[i]);
switch(type){
case "string":
if(row.getCell(i).getCellType()==0) {//数值类型转字符串
values+="'"+df.format(row.getCell(i).getNumericCellValue())+"',";
}
else {
values+="'"+SafeSqlUtil.getSafeString(row.getCell(i).toString().trim())+"',";
}
break;
case "num":
if(row.getCell(i).toString().trim().equals("")) {
values+="null,";
}
else if(row.getCell(i).getCellType()==1) {//字符串类型转数值
try{
values+=Double.valueOf(row.getCell(i).toString().trim()).intValue()+",";
}catch(Exception ex) {
throw new Exception("第"+row.getRowNum()+"行:["+titleArr[i]+"]应为数值格式!");
}
}
else {
//处理数值为3.012E7此类情况
rowStr=row.getCell(i).toString();
if(rowStr.contains("E"))
values+=df.format(row.getCell(i).getNumericCellValue())+",";
else
values+=row.getCell(i).toString()+",";
}
break;
case "date":
if(row.getCell(i).toString().trim().equals("")) {
values+="null,";
}
else if(row.getCell(i).getCellType()==0) {//数值形式的时间格式
if (HSSFDateUtil.isCellDateFormatted(cell)) {// 处理日期格式、时间格式
values+="'"+fmt.format(cell.getDateCellValue())+"',";
}
else if (cell.getCellStyle().getDataFormat() == 58) {
// 处理自定义日期格式:m月d日(通过判断单元格的格式id解决,id的值是58)
double value = cell.getNumericCellValue();
Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(value);
values+="'"+fmt.format(date)+"',";
}
else
throw new Exception("第"+row.getRowNum()+"行:["+titleArr[i]+"]应为时间格式!");
}
else if(row.getCell(i).getCellType()==1) {//字符串形式的时间格式
try {
Date date = TimeUtil.stringToDateNew(row.getCell(i).toString());
values+="'"+fmt.format(date)+"',";
} catch (Exception e) {
throw new Exception("第"+row.getRowNum()+"行:["+titleArr[i]+"]应为时间格式!");
}
}
else
throw new Exception("第"+row.getRowNum()+"行:["+titleArr[i]+"]应为时间格式!");
break;
case "bool":
if(row.getCell(i).getCellType()==4) //布尔型 4
values+=row.getCell(i).toString()+",";
else
throw new Exception("第"+row.getRowNum()+"行:["+titleArr[i]+"]应为布尔格式!");
break;
}
}
values=values.substring(0, values.length()-1);
values=row.getRowNum()+",'','"+MyUUID.getUUID()+"','"+fmt.format(new Date())+"',"+values;
sql+=titles.replace("#values#", values);
if((j+1)%singleRows==0){
sqlDao.execSql(sql);
session.setAttribute("gropress", 0.85*j/total+0.05);
sql="";
}
values="";
}
j++;
}
sqlDao.execSql(sql);
session.setAttribute("gropress", 0.9);
} catch (Exception e) {
total=0;
throw e;
}
finally {
IOUtils.closeQuietly(in);
}
return total;
}
} |
package com.openfarmanager.android.dialogs;
import android.content.Context;
import android.os.Bundle;
import android.util.TypedValue;
import android.widget.TextView;
import com.openfarmanager.android.R;
/**
* @author Vlad Namashko.
*/
public class MarginSetupDialog extends FontSetupDialog {
protected final static int MIN_VALUE = 0;
protected final static int MAX_VALUE = 10;
public MarginSetupDialog(Context context, SaveAction runnable) {
super(context, runnable);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((TextView) mDialogView.findViewById(R.id.dialog_label)).setText(R.string.margin_size);
}
@Override
protected int getMinValue() {
return MIN_VALUE;
}
@Override
protected int getMaxValue() {
return MAX_VALUE;
}
@Override
protected void onValueChanged(int progress, TextView fontSizeSample) {
mNewFontSize = progress;
fontSizeSample.setText(Integer.toString(progress));
}
@Override
protected void setInitFontSize(int fontSize, TextView fontSizeSample) {
fontSizeSample.setText(Integer.toString(fontSize));
fontSizeSample.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
}
}
|
public class Shipments {
private String wellCd;
private String loadingLevelCd;
private Shipment shipment;
public Shipments() {
}
public Shipments(String wellCd, String loadingLevelCd, Shipment shipment) {
this.wellCd = wellCd;
this.loadingLevelCd = loadingLevelCd;
this.shipment = shipment;
}
public String getWellCd() {
return wellCd;
}
public void setWellCd(String wellCd) {
this.wellCd = wellCd;
}
public String getLoadingLevelCd() {
return loadingLevelCd;
}
public void setLoadingLevelCd(String loadingLevelCd) {
this.loadingLevelCd = loadingLevelCd;
}
public Shipment getShipment() {
return shipment;
}
public void setShipment(Shipment shipment) {
this.shipment = shipment;
}
}
|
package net.cattaka.android.learnaccount;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class LoginActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final EditText nameEdit = (EditText) findViewById(R.id.name);
final EditText passwordEdit = (EditText) findViewById(R.id.password);
Button button = (Button) findViewById(R.id.login);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name = nameEdit.getText().toString();
String password = passwordEdit.getText().toString();
login(name, password);
}
});
}
// ログイン処理
public void login(final String name, final String password) {
// TODO:このメソッドは非同期の通信処理でログインを試みます。
// ログインに成功した場合、loginSuccess()を呼び出します。
loginSuccess(name, password);
}
// ログイン処理のコールバック
public void loginSuccess(final String name, final String password) {
Account account = new Account(name, "net.cattaka.android.learnaccount");
AccountManager am = AccountManager.get(this);
// アカウント情報を保存
// TODO:本来はパスワードを暗号化する必要があります
Bundle bundle = new Bundle();
bundle.putString("test", "mytest");
am.addAccountExplicitly(account, password, bundle);
// 認証画面終了
setResult(RESULT_OK);
finish();
}
}
|
package com.github.nnnnusui.format;
import java.nio.ByteBuffer;
import java.util.BitSet;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class Base32hex {
public static String encode(byte[] source) { return instance._encode(source); }
public static byte[] decode(String source) { return instance._decode(source); }
// public static Base32hex getInstance() { return instance; }
private static Base32hex instance = new Base32hex();
private Base32hex() {}
private final int radix = 32;
private final int blockSize = 40; // bit per base32 block
private final int wordSize = 5; // bit per base32 word
private final char fillCharacter = '=';
private final int bitPerByte = 8;
public String _encode(byte[] _source){
final int sourceBitQuantity = _source.length * bitPerByte;
final int resultWordQuantity = ((sourceBitQuantity -1) / wordSize) +1;
final int resultBitQuantity = ((sourceBitQuantity -1) / blockSize +1) * blockSize;
final BitSet source = reverse(BitSet.valueOf(_source), bitPerByte);
return IntStream.range(0, resultWordQuantity)
.mapToObj(index-> source.get(index * wordSize, (index +1) * wordSize))
.map(this::getWord)
.map(it-> Integer.toString(it, radix))
.map(String::valueOf)
.collect(Collectors.joining())
.toUpperCase()
+ Stream.generate(() -> Character.toString(fillCharacter))
.limit((resultBitQuantity - sourceBitQuantity) / wordSize)
.collect(Collectors.joining());
}
public byte[] _decode(String _source){
final String source = _source.replace(Character.toString(fillCharacter), "");
final ByteBuffer sourceBytes = ByteBuffer.allocate(source.length() * wordSize);
source.chars()
.mapToObj(it -> (char) it)
.map(it -> Character.toString(it))
.map(it -> Byte.parseByte(it, radix))
.forEach(sourceBytes::put);
final BitSet result = setWords(sourceBytes.array());
return result.toByteArray();
}
private int getWord(BitSet bitSet){
return IntStream.range(0, wordSize)
.mapToObj(bitSet::get)
.map(it-> it ? 1 : 0)
.reduce(0, (sum, bit) -> (sum << 1) + bit); // Binary to decimal.
}
private BitSet setWords(byte[] values){ // TODO: Refactoring
final BitSet bitSet = new BitSet(values.length * wordSize);
IntStream.range(0, values.length)
.forEach(index->
reverse(BitSet.valueOf(new byte[]{ values[index] }), wordSize)
.stream()
.map(it-> it + (index * wordSize))
.forEach(bitSet::set)
);
return reverse(bitSet, bitPerByte);
}
private BitSet reverse(BitSet source, int unitSize){
final BitSet result = new BitSet(source.length());
source.stream()
.forEach(it-> {
int multiplesOfUnit = (it / unitSize) * unitSize;
int lowerThanUnit = (unitSize -1) - (it % unitSize);
result.set(multiplesOfUnit + lowerThanUnit);
});
return result;
}
}
|
package domainapp.dom.superscore;
import java.util.List;
import org.apache.isis.applib.DomainObjectContainer;
import org.apache.isis.applib.Identifier;
import org.apache.isis.applib.annotation.Action;
import org.apache.isis.applib.annotation.ActionLayout;
import org.apache.isis.applib.annotation.BookmarkPolicy;
import org.apache.isis.applib.annotation.DomainService;
import org.apache.isis.applib.annotation.DomainServiceLayout;
import org.apache.isis.applib.annotation.MemberOrder;
import org.apache.isis.applib.annotation.NatureOfService;
import org.apache.isis.applib.annotation.ParameterLayout;
import org.apache.isis.applib.annotation.Programmatic;
import org.apache.isis.applib.annotation.SemanticsOf;
import org.apache.isis.applib.query.QueryDefault;
import org.apache.isis.applib.services.eventbus.ActionDomainEvent;
import org.apache.isis.applib.services.i18n.TranslatableString;
import org.isisaddons.module.security.dom.role.ApplicationRole;
import org.isisaddons.module.security.dom.role.ApplicationRoleRepository;
import org.isisaddons.module.security.dom.user.ApplicationUser;
import org.isisaddons.module.security.dom.user.ApplicationUserRepository;
import com.google.common.collect.Lists;
@DomainService(
nature = NatureOfService.VIEW,
repositoryFor = Team.class
)
@DomainServiceLayout(
menuOrder = "8"
)
public class Teams {
//region > title
public TranslatableString title() {
return TranslatableString.tr("Teams");
}
//endregion
//region > listAll (action)
@Action(
semantics = SemanticsOf.SAFE
)
@ActionLayout(
bookmarking = BookmarkPolicy.AS_ROOT,
named="List All Teams"
)
@MemberOrder(sequence = "1")
public List<Team> listAll() {
return container.allInstances(Team.class);
}
//endregion
//region > create (action)
@SuppressWarnings("serial")
public static class CreateDomainEvent extends ActionDomainEvent<Teams> {
@SuppressWarnings("deprecation")
public CreateDomainEvent(final Teams source, final Identifier identifier, final Object... arguments) {
super(source, identifier, arguments);
}
}
@Action(
domainEvent = CreateDomainEvent.class
)
@MemberOrder(sequence = "3")
public Team create(
final @ParameterLayout(named="Player 1") ApplicationUser player1,
final @ParameterLayout(named="Player 2") ApplicationUser player2
) {
Team team = container.uniqueMatch(new QueryDefault<>(Team.class, "findByPlayers", "playerA", player1, "playerB", player2));
if (team == null) {
final Team obj = container.newTransientInstance(Team.class);
obj.setPlayer1(player1);
obj.setPlayer2(player2);
container.persistIfNotAlready(obj);
return obj;
} else
return team;
}
//endregion
public List<ApplicationUser> autoComplete0Create(final String search) {
String _search = "";
if (search != null) _search = search;
return getSuperscoreUsers(_search);
}
public List<ApplicationUser> autoComplete1Create(final String search) {
String _search = "";
if (search != null) _search = search;
return getSuperscoreUsers(_search);
}
@Programmatic
public List<ApplicationUser> getSuperscoreUsers(final String search) {
List<ApplicationUser> l = Lists.newArrayList();
ApplicationRole supercoreRole = applicationRoleRepository.findByName("superscore-regular-user");
List<ApplicationUser> users = null;
if (search == null) {
users = applicationUserRepository.allUsers();
} else {
users = applicationUserRepository.autoComplete(search);
}
for (ApplicationUser applicationUser : users) {
if (applicationUser.getRoles().contains(supercoreRole))
l.add(applicationUser);
}
return l;
}
// {{ actionName (action)
@MemberOrder(sequence = "5")
public List<Team> careateAllTeams() {
List<ApplicationUser> allusers = getSuperscoreUsers(null);
for (int i = 0; i < allusers.size(); i++) {
ApplicationUser user = allusers.get(i);
for (int j = i + 1; j < allusers.size(); j++) {
create(user, allusers.get(j));
}
}
return listAll();
}
// }}
public String validateCreate(
final @ParameterLayout(named="Player 1") ApplicationUser player1,
final @ParameterLayout(named="Player 2") ApplicationUser player2
) {
if (player1 == player2)
return "Select different player for the team";
return null;
}
//region > injected services
// {{ autoComplete (action)
@Action(
semantics = SemanticsOf.SAFE
)
@MemberOrder(sequence = "2")
public List<Team> findByNames(final @ParameterLayout(named="Players name") String search) {
if (search != null && search.length() > 0) {
String[] parts = search.split(" ");
if (parts.length > 1) {
return findByNames(parts[0].trim(), parts[1].trim());
} else {
return findByName(parts[0].trim());
}
}
return Lists.newArrayList();
}
// }}
@Programmatic
public List<Team> findByName(final String search) {
final String regex = String.format("(?i).*%s.*", search.replace("*", ".*").replace("?", "."));
return container.allMatches(new QueryDefault<>(
Team.class,
"findByPlayerName", "regex", regex));
}
@Programmatic
public List<Team> findByNames(String name1, String name2) {
final String regex1 = String.format("(?i).*%s.*", name1.replace("*", ".*").replace("?", "."));
final String regex2 = String.format("(?i).*%s.*", name2.replace("*", ".*").replace("?", "."));
return container.allMatches(new QueryDefault<>(
Team.class,
"findByPlayersName", "regex1", regex1, "regex2", regex2));
}
@javax.inject.Inject
DomainObjectContainer container;
@javax.inject.Inject
ApplicationUserRepository applicationUserRepository;
@javax.inject.Inject
ApplicationRoleRepository applicationRoleRepository;
//endregion
}
|
/*
* Copyright Verizon Media, Licensed under the terms of the Apache License, Version 2.0. See LICENSE file in project root for terms.
*/
package com.yahoo.cubed.source;
import com.yahoo.cubed.model.Field;
import com.yahoo.cubed.model.FieldKey;
import com.yahoo.cubed.model.Pipeline;
import com.yahoo.cubed.model.PipelineProjection;
import com.yahoo.cubed.model.PipelineProjectionVM;
import com.yahoo.cubed.model.Schema;
import com.yahoo.cubed.model.FunnelGroup;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
/**
* Factory manager for Hibernate sessions.
*/
public class HibernateSessionFactoryManager {
private static SessionFactory sessionFactory;
/**
* Get a new session factory.
*/
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
Configuration cfg = new Configuration();
// add class
cfg.addPackage("com.yahoo.cubed.model");
cfg.addAnnotatedClass(Field.class);
cfg.addAnnotatedClass(Pipeline.class);
cfg.addAnnotatedClass(PipelineProjection.class);
cfg.addAnnotatedClass(PipelineProjectionVM.class);
cfg.addAnnotatedClass(FieldKey.class);
cfg.addAnnotatedClass(Schema.class);
cfg.addAnnotatedClass(FunnelGroup.class);
// add connection
cfg.setProperty("hibernate.connection.driver_class", ConfigurationLoader.getProperty(ConfigurationLoader.DRIVER));
cfg.setProperty("hibernate.connection.url", ConfigurationLoader.getProperty(ConfigurationLoader.DATABASEURL));
cfg.setProperty("hibernate.connection.username", ConfigurationLoader.getProperty(ConfigurationLoader.USERNAME));
cfg.setProperty("hibernate.connection.password", ConfigurationLoader.getProperty(ConfigurationLoader.PASSWORD));
cfg.setProperty("hibernate.dialect", ConfigurationLoader.getProperty(ConfigurationLoader.DIALECT));
cfg.setProperty("hibernate.connection.autoReconnect", "true");
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
sessionFactory = cfg.buildSessionFactory(serviceRegistry);
}
return sessionFactory;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.