blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
284073fe425ede51bb1175fdfd6a085622a1e569
Java
DeveloperCry/java-learning
/java-zookeeper/src/main/java/com/learning/zookeeper/locks/lock/DistributedLock.java
UTF-8
5,253
2.890625
3
[ "MIT" ]
permissive
package com.learning.zookeeper.locks.lock; import org.apache.zookeeper.*; import org.apache.zookeeper.data.Stat; import org.springframework.util.CollectionUtils; import java.util.Collections; import java.util.List; import java.util.concurrent.CountDownLatch; /** * 锁实现的原理就是:当某个线程释放锁的时候,每个线程都去请求zookeeper,然后去抢锁,如果是数量非常的多,会给服务器造成压力,(其实这个时候就类似非公平锁) * 但是我们可以优化,类似公平锁,每个锁都会无watch它前面的一个锁,如果它前面的锁释放了,那么久只有它才去获取锁,而不是所有的都去获取锁 */ public class DistributedLock implements Watcher, AsyncCallback.Create2Callback, AsyncCallback.Children2Callback { private static final String LOCK_PATH = "/lock"; private CountDownLatch countDownLatch = new CountDownLatch(1);// 该变量不能是静态的,如果是静态的,因为这个是要在各自的线程中独自占有,静态的将实例化一份 private ZooKeeper zooKeeper; private String threadName; private String pathName; public DistributedLock(ZooKeeper zooKeeper) { this.zooKeeper = zooKeeper; } private void createLock() { // try { // 这样写时有问题的,因为创建完了马上就去调用getData的话,这个时候其实都是有值了,同时如果将await写在getData后面的话,前一个已经被删除了,而后一个再去监听就永远都不会存在 // 因此在开始创建的时候就应该使用callback // return this.zooKeeper.create(LOCK_PATH, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); // } catch (KeeperException e) { // e.printStackTrace(); // } catch (InterruptedException e) { // e.printStackTrace(); // } this.zooKeeper.create(LOCK_PATH, this.threadName.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL, this, this.threadName); // return null; } public void lock() { try { this.createLock(); //这里不能用getData方法,如果是这样,await将失效,应该是create的时候就应该出现callback // this.zooKeeper.getData(this.pathName, false, this, this.pathName); this.countDownLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } } public void unlock() { try { this.zooKeeper.delete(this.pathName, -1); System.out.println(this.threadName + "释放锁。。。。。。"); } catch (InterruptedException e) { e.printStackTrace(); } catch (KeeperException e) { e.printStackTrace(); } } // Watcher @Override public void process(WatchedEvent event) { // System.out.println(event); //如果第一个等待的线程,那个锁释放了,其实只有第二个收到了回调事件!! //如果,不是第一个等待的线程,某一个,挂了,也能造成他后边的收到这个通知,从而让他后边那个跟去watch挂掉这个排队的线程前边的。。。 if (Event.EventType.NodeDeleted.equals(event.getType())) { this.zooKeeper.getChildren("/", false, this, this.threadName); } } public void setThreadName(String threadName) { this.threadName = threadName; } // create2 callback @Override public void processResult(int rc, String path, Object ctx, String name, Stat stat) { if (name != null) { System.out.println(ctx + ":创建锁:" + name); this.pathName = name; this.zooKeeper.getChildren("/", false, this, (String) ctx); } } // Child2 callback @Override public void processResult(int rc, String path, Object ctx, List<String> children, Stat stat) { try { if (!CollectionUtils.isEmpty(children)) { Collections.sort(children); // System.out.println(this.threadName + ":" + children); String currentPath = this.pathName.substring(1); int index = children.indexOf(currentPath); if (index == 0) { System.out.println("当前抢到锁的线程是:" + this.threadName); // this.zooKeeper.setData("/", this.threadName.getBytes(), -1); this.countDownLatch.countDown(); } else { Stat exists = this.zooKeeper.exists("/" + children.get(index - 1), this); if (exists == null) {// 判断它的前一位是否存在,如果不存在,说明锁已经被释放了,就不用再去注册监听器了 this.countDownLatch.countDown(); } } } } catch (KeeperException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } }
true
6b316c50b44505a154fff4dfd9dc3721e8153b71
Java
sarathkrishna2018/employeemanager
/src/main/java/com/employeemanager/employeemanager/repo/RequestRepoCustomImpl.java
UTF-8
1,044
2.171875
2
[]
no_license
package com.employeemanager.employeemanager.repo; import com.employeemanager.employeemanager.model.Request; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.stereotype.Repository; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import javax.transaction.Transactional; import java.util.List; @Repository @Transactional public class RequestRepoCustomImpl implements RequestRepoCustom{ @PersistenceContext EntityManager entityManager; @Override public List<Request> getEmployeeRequests(String id){ Query query = entityManager.createNativeQuery("SELECT * from request WHERE emp_id = :emp ", Request.class); System.out.println("DEBUG: [ID]" + id); query.setParameter("emp",id); List<Request> requests = query.getResultList(); return requests; } }
true
43722bc358808b971697deb25a56d14b49e14870
Java
xoghks1397/HappyHouse
/src/main/java/com/ssafy/happyhouse/controller/MainServlet.java
UTF-8
1,019
1.882813
2
[]
no_license
package com.ssafy.happyhouse.controller; import java.io.IOException; 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 org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; /** * Servlet implementation class MainServlet */ @Controller @RequestMapping("") public class MainServlet extends HttpServlet { @GetMapping("/") protected String index() { return "index"; } @GetMapping("/search") protected String search() { return "search"; } @GetMapping("/searchDetail") protected String searchDeatil() { return "searchDetail"; } @GetMapping("/findPassword") protected String findPassword() { return "login/findPassword"; } @GetMapping("/include/Error") protected String erorr() { return "/include/Error"; } }
true
1db819304064050efc76dfeecd8d9c77eae15446
Java
madhutota/ChatApp
/app/src/main/java/com/dev/chatapp/UsersAdapter.java
UTF-8
769
2.25
2
[]
no_license
package com.dev.chatapp; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.View; import android.view.ViewGroup; public class UsersAdapter extends RecyclerView.Adapter<UsersAdapter.UsersViewHolder> { @NonNull @Override public UsersAdapter.UsersViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { return null; } @Override public void onBindViewHolder(@NonNull UsersAdapter.UsersViewHolder holder, int position) { } @Override public int getItemCount() { return 0; } public class UsersViewHolder extends RecyclerView.ViewHolder { public UsersViewHolder(View itemView) { super(itemView); } } }
true
84fabefb9e235a5da0bf1394ec584610a0a0cff8
Java
fei11111/FirstProject
/app/src/main/java/com/fei/firstproject/adapter/NcwAdapter.java
UTF-8
2,989
2.25
2
[]
no_license
package com.fei.firstproject.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions; import com.fei.firstproject.R; import com.fei.firstproject.entity.NcwEntity; import com.fei.firstproject.inter.OnItemClickListener; import com.fei.firstproject.utils.GlideUtils; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; /** * Created by Administrator on 2017/8/14. */ public class NcwAdapter extends RecyclerView.Adapter<NcwAdapter.NcwViewHolder> { private List<NcwEntity> ncwEntities; private Context mContext; private OnItemClickListener onItemClickListener; public NcwAdapter(Context mContext, List<NcwEntity> ncwEntities) { this.mContext = mContext; this.ncwEntities = ncwEntities; } public void setNcwEntities(List<NcwEntity> ncwEntities) { this.ncwEntities = ncwEntities; } public List<NcwEntity> getNcwEntities() { return ncwEntities; } public void setOnItemClickListener(OnItemClickListener onItemClickListener) { this.onItemClickListener = onItemClickListener; } @Override public NcwViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(mContext).inflate(R.layout.item_ncw, parent, false); return new NcwViewHolder(view); } @Override public void onBindViewHolder(NcwViewHolder holder, int position) { NcwEntity ncwEntity = ncwEntities.get(position); holder.tvNcwTitle.setText(ncwEntity.getTitle()); holder.tvNwcDesp.setText(ncwEntity.getDescription().replaceAll("\\s*", "")); Glide.with(mContext) .load(ncwEntity.getThumb()) .transition(new DrawableTransitionOptions().crossFade(2000)) .apply(GlideUtils.getOptions()) .into(holder.ivNcw); } @Override public long getItemId(int i) { return i; } @Override public int getItemCount() { return ncwEntities.size() > 3 ? 3 : ncwEntities.size(); } class NcwViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { @BindView(R.id.iv_ncw) ImageView ivNcw; @BindView(R.id.tv_ncw_title) TextView tvNcwTitle; @BindView(R.id.tv_nwc_desp) TextView tvNwcDesp; public NcwViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); itemView.setOnClickListener(this); } @Override public void onClick(View v) { if (onItemClickListener != null) { onItemClickListener.onItemClick(v); } } } }
true
662f2d4b03b81ed8319e6b4451dec5463959bf11
Java
mathisGilliot/database-project
/java/interface/src/vehlib/Vehlib.java
UTF-8
178
1.5625
2
[]
no_license
package vehlib; public class Vehlib { public static void main(String args[]) { MainFrame mainWindow = new MainFrame(); mainWindow.setVisible(true); } }
true
631f29a39d14554df2a7fbb175f648a4b8b40f6a
Java
DanyBin/code_diary
/TwoHundred/src/main/java/Code_03_ReverseOfString.java
UTF-8
235
2.609375
3
[ "Apache-2.0" ]
permissive
/** * Given s = "leetcode", return "leotcede". * leotcede */ public class Code_03_ReverseOfString { public static void main(String[] args) { } private static String reverse(String target) { return null; } }
true
1d713b323bc2b0ca5f43f1a069072f3ffb0250cc
Java
CcCoffee/CoffeeWeather
/library/src/main/java/com/coffee/library/view/BaseView.java
UTF-8
245
1.695313
2
[]
no_license
package com.coffee.library.view; /** * Created by Administrator on 2016/6/23. */ public interface BaseView { void showLoading(); void hideLoading(); void showNetWorkError(String message); void showLoadError(String message); }
true
371cbd394932d446023f2e643dbd74536f5071bd
Java
blue995/de.hs_coburg.mgse.application
/restapi/src/main/java/de/hs_coburg/mgse/business/view/ViewFootnote.java
UTF-8
533
2.546875
3
[]
no_license
package de.hs_coburg.mgse.business.view; public class ViewFootnote { private int number; private String text; public ViewFootnote() { } public ViewFootnote(int number, String text) { this.number = number; this.text = text; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public String getText() { return text; } public void setText(String text) { this.text = text; } }
true
0305b92f5845d900eee8848a162f5a5a9f681f84
Java
cyjie/chromium
/chrome/android/features/autofill_assistant/java/src/org/chromium/chrome/browser/autofill_assistant/trigger_scripts/AssistantTriggerScript.java
UTF-8
8,612
1.640625
2
[ "BSD-3-Clause" ]
permissive
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.autofill_assistant.trigger_scripts; import android.content.Context; import android.view.LayoutInflater; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.ScrollView; import android.widget.Space; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import org.chromium.chrome.autofill_assistant.R; import org.chromium.chrome.browser.autofill_assistant.AssistantBottomBarDelegate; import org.chromium.chrome.browser.autofill_assistant.AssistantBottomSheetContent; import org.chromium.chrome.browser.autofill_assistant.AssistantRootViewContainer; import org.chromium.chrome.browser.autofill_assistant.BottomSheetUtils; import org.chromium.chrome.browser.autofill_assistant.carousel.AssistantChip; import org.chromium.chrome.browser.autofill_assistant.carousel.AssistantChipViewHolder; import org.chromium.chrome.browser.autofill_assistant.generic_ui.AssistantDimension; import org.chromium.chrome.browser.autofill_assistant.header.AssistantHeaderCoordinator; import org.chromium.chrome.browser.autofill_assistant.header.AssistantHeaderModel; import org.chromium.components.browser_ui.bottomsheet.BottomSheetController; import org.chromium.components.browser_ui.bottomsheet.BottomSheetController.StateChangeReason; import org.chromium.components.browser_ui.bottomsheet.BottomSheetObserver; import org.chromium.components.browser_ui.bottomsheet.EmptyBottomSheetObserver; import java.util.ArrayList; import java.util.List; /** * Represents the UI for a particular trigger script. Notifies a delegate about user interactions. */ public class AssistantTriggerScript { /** Interface for delegates of this class who will be notified of user interactions. */ public interface Delegate { void onTriggerScriptAction(@TriggerScriptAction int action); void onBottomSheetClosedWithSwipe(); void onBackButtonPressed(); void onFeedbackButtonClicked(); } @Nullable private final AssistantBottomSheetContent mContent; private final Context mContext; private final Delegate mDelegate; private final BottomSheetController mBottomSheetController; private final BottomSheetObserver mBottomSheetObserver; private final AssistantRootViewContainer mRootViewContainer; private final ScrollView mScrollableContent; private final AssistantHeaderCoordinator mHeaderCoordinator; private final AssistantHeaderModel mHeaderModel; private final LinearLayout mChipsContainer; private final int mInnerChipSpacing; private final List<AssistantChip> mLeftAlignedChips = new ArrayList<>(); private final List<AssistantChip> mRightAlignedChips = new ArrayList<>(); private boolean mAnimateBottomSheet = true; public AssistantTriggerScript( Context context, Delegate delegate, BottomSheetController controller) { assert delegate != null; mContext = context; mDelegate = delegate; mBottomSheetController = controller; mBottomSheetObserver = new EmptyBottomSheetObserver() { @Override public void onSheetClosed(@StateChangeReason int reason) { if (reason == StateChangeReason.SWIPE) { mDelegate.onBottomSheetClosedWithSwipe(); } } }; mContent = new AssistantBottomSheetContent(mContext, () -> new AssistantBottomBarDelegate() { @Override public boolean onBackButtonPressed() { // We need to handle this event, because by default the bottom sheet will // close when the back button is pressed. mDelegate.onBackButtonPressed(); return true; } @Override public void onBottomSheetClosedWithSwipe() { // TODO(micantox): introduce a dedicated AssistantBottomSheetContent // delegate, rather than reuse the bottom bar delegate, as it forces // implementation of methods that the bottom sheet will never invoke. assert false : "This should never happen"; mDelegate.onBottomSheetClosedWithSwipe(); } }); // Allow swipe-to-dismiss. mContent.setPeekModeDisabled(true); mHeaderModel = new AssistantHeaderModel(); mHeaderModel.set( AssistantHeaderModel.FEEDBACK_BUTTON_CALLBACK, mDelegate::onFeedbackButtonClicked); mHeaderCoordinator = new AssistantHeaderCoordinator(context, mHeaderModel); mChipsContainer = new LinearLayout(context); mChipsContainer.setOrientation(LinearLayout.HORIZONTAL); int horizontalMargin = context.getResources().getDimensionPixelSize( R.dimen.autofill_assistant_bottombar_horizontal_spacing); int verticalMargin = AssistantDimension.getPixelSizeDp(context, 16); mChipsContainer.setPadding( horizontalMargin, verticalMargin, horizontalMargin, verticalMargin); mInnerChipSpacing = mContext.getResources().getDimensionPixelSize( R.dimen.autofill_assistant_actions_spacing); mRootViewContainer = (AssistantRootViewContainer) LayoutInflater.from(context).inflate( R.layout.autofill_assistant_bottom_sheet_content, /* root= */ null); mScrollableContent = mRootViewContainer.findViewById(R.id.scrollable_content); mRootViewContainer.addView(mHeaderCoordinator.getView(), 0); mRootViewContainer.addView(mChipsContainer, new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); mContent.setContent(mRootViewContainer, mScrollableContent); } public void destroy() { mBottomSheetController.removeObserver(mBottomSheetObserver); mHeaderCoordinator.destroy(); } @VisibleForTesting public void disableBottomSheetAnimationsForTesting(boolean disable) { mAnimateBottomSheet = !disable; } @VisibleForTesting public AssistantHeaderModel getHeaderModelForTest() { return mHeaderModel; } @VisibleForTesting public List<AssistantChip> getLeftAlignedChipsForTest() { return mLeftAlignedChips; } @VisibleForTesting public List<AssistantChip> getRightAlignedChipsForTest() { return mRightAlignedChips; } @VisibleForTesting public AssistantBottomSheetContent getBottomSheetContentForTest() { return mContent; } private void addChipsToContainer(LinearLayout container, List<AssistantChip> chips) { for (int i = 0; i < chips.size(); ++i) { AssistantChipViewHolder viewHolder = AssistantChipViewHolder.create(container, chips.get(i).getType()); viewHolder.bind(chips.get(i)); container.addView(viewHolder.getView()); if (i < chips.size() - 1) { container.addView(new Space(mContext), new LinearLayout.LayoutParams( mInnerChipSpacing, ViewGroup.LayoutParams.MATCH_PARENT)); } } } // TODO(b/171776026): before calling this method, native needs to send the necessary // information to populate and update the views. @VisibleForTesting public void update() { mChipsContainer.removeAllViews(); addChipsToContainer(mChipsContainer, mLeftAlignedChips); mChipsContainer.addView(new Space(mContext), new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, 1.0f)); addChipsToContainer(mChipsContainer, mRightAlignedChips); } public void show() { update(); mBottomSheetController.removeObserver(mBottomSheetObserver); mBottomSheetController.addObserver(mBottomSheetObserver); BottomSheetUtils.showContentAndMaybeExpand(mBottomSheetController, mContent, /* shouldExpand = */ true, /* animate = */ mAnimateBottomSheet); } public void hide() { mBottomSheetController.removeObserver(mBottomSheetObserver); mBottomSheetController.hideContent(mContent, /* animate = */ mAnimateBottomSheet); } }
true
d1a0c73b26b3f8a783532bd5d77632ae4199675e
Java
Luuck4s/DigitalInnovation
/SantanderFullStack/DesenvolvimentoAvancadoJava/src/main/java/Thread/PararelStreamExemplo.java
UTF-8
967
3.78125
4
[]
no_license
package Thread; import java.util.stream.IntStream; public class PararelStreamExemplo { public static void main(String[] args) { long start = System.currentTimeMillis(); IntStream.range(1, 100000).forEach(num -> fatorial(num)); long end = System.currentTimeMillis(); System.out.println("(Serial) Tempo de execução: " + (end - start)); /** * É interessante utilizar o pararel Stream quando * temos um grande número de objetos que não dependem * um do outro */ start = System.currentTimeMillis(); IntStream.range(1, 100000).parallel().forEach(num -> fatorial(num)); end = System.currentTimeMillis(); System.out.println("(Parallel)Tempo de execução: " + (end - start)); } public static long fatorial(long num){ long fat = 1; for(long i = 2; i <= num; i++){ fat *= i; } return fat; } }
true
2d54768958e2786672a71b33fcca670bdc081726
Java
scaliby/market-aggregator
/market-aggregator-core/src/test/java/net/scaliby/marketaggregator/core/market/MarketAggregateTest.java
UTF-8
14,308
2.765625
3
[ "MIT" ]
permissive
package net.scaliby.marketaggregator.core.market; import net.scaliby.marketaggregator.core.common.DoubleWrapper; import net.scaliby.marketaggregator.core.common.PriceSummary; import org.junit.Test; import java.util.Arrays; import java.util.Collections; import java.util.Map; import java.util.Optional; import static junit.framework.TestCase.*; public class MarketAggregateTest { private final MarketAggregate<String> marketAggregate = new MarketAggregate<>( "BTC_USD", 1000, new BasicMutableOrderBook(false), new BasicMutableOrderBook(true) ); @Test public void askingIfCanApplyEvent_returnsTrue_forNewlyCreatedAggregate() { // given StockEvent stockEvent = StockEvent.builder() .timestamp(1000L) .build(); // when boolean result = marketAggregate.canApply(stockEvent); // then assertTrue(result); } @Test public void askingIfAggregateCanApplyEmptyEventsList_returnsTrue_forAggregateAtSomeTimeState() { // given StockEvent existingEvent = StockEvent.builder() .timestamp(1000L) .build(); // when marketAggregate.apply(existingEvent); boolean result = marketAggregate.canApply(Collections.emptyList()); // then assertTrue(result); } @Test public void askingIfAggregateCanApplyEvent_returnsFalse_forEventThatIsNewerThanCurrentAggregateTimeWindow() { // given StockEvent initialStockEvent = StockEvent.builder() .timestamp(1000L) .build(); StockEvent newStockEvent = StockEvent.builder() .timestamp(2500L) .build(); // when marketAggregate.apply(initialStockEvent); boolean result = marketAggregate.canApply(newStockEvent); // then assertFalse(result); } @Test public void askingIfAggregateCanApplyEventAfterTicking_returnTrue_forEventThatIsFittingIntoNextAggregateTimeWindow() { // given StockEvent initialStockEvent = StockEvent.builder() .timestamp(1000L) .build(); StockEvent newStockEvent = StockEvent.builder() .timestamp(2500L) .build(); // when marketAggregate.apply(initialStockEvent); marketAggregate.tick(); boolean result = marketAggregate.canApply(newStockEvent); // then assertTrue(result); } @Test public void askingIfAggregateCanApplyEvent_returnsTrue_forEventThatIsFittingIntoCurrentAggregateTimeWindow() { // given StockEvent initialStockEvent = StockEvent.builder() .timestamp(1000L) .build(); StockEvent newStockEvent = StockEvent.builder() .timestamp(1500L) .build(); // when marketAggregate.apply(initialStockEvent); boolean result = marketAggregate.canApply(newStockEvent); // then assertTrue(result); } @Test public void applyingStockEventList_makesGetLastEventReturnLastEventFromList() { // given StockEvent firstStockEvent = StockEvent.builder() .type("ASK") .sequence(1L) .build(); StockEvent secondStockEvent = StockEvent.builder() .type("ASK") .sequence(2L) .build(); // when marketAggregate.apply(Arrays.asList(firstStockEvent, secondStockEvent)); // then StockEvent result = marketAggregate.getLastEvent("ASK"); assertEquals(secondStockEvent, result); } @Test public void applyingStockEvent_makesAskOrderBookReturnValidTotalAmountInBaseCurrency_forASKEvent() { // given StockEvent stockEvent = StockEvent.builder() .type("ASK") .price(new DoubleWrapper(10)) .amount(10D) .build(); // when marketAggregate.apply(stockEvent); // then double result = marketAggregate.getAsk().getTotalAmountInBaseCurrency(); assertEquals(100, result, 0.001); } @Test public void applyingStockEvent_makesAskOrderBookReturnValidTotalAmountInBaseCurrency_forBIDEvent() { // given StockEvent stockEvent = StockEvent.builder() .type("BID") .price(new DoubleWrapper(10)) .amount(10D) .build(); // when marketAggregate.apply(stockEvent); // then double result = marketAggregate.getBid().getTotalAmountInBaseCurrency(); assertEquals(10, result, 0.001); } @Test public void applyingSeriesOfStockEvents_makesGetTimeReturnTimeOfLastEventFromBatch_forSingleBatch() { // given StockEvent firstStockEvent = StockEvent.builder() .timestamp(100L) .build(); StockEvent secondStockEvent = StockEvent.builder() .timestamp(200L) .build(); // when marketAggregate.apply(Arrays.asList(firstStockEvent, secondStockEvent)); // then long currentTime = marketAggregate.getCurrentTime(); assertEquals(currentTime, 200L); } @Test public void applyingSeriesOfStockEvents_makesGetTimeReturnTimeOfLastEventFromFirstBatch_forMultipleBatches() { // given StockEvent firstStockEvent = StockEvent.builder() .timestamp(100L) .build(); StockEvent secondStockEvent = StockEvent.builder() .timestamp(200L) .build(); // when marketAggregate.apply(firstStockEvent); marketAggregate.apply(secondStockEvent); // then long currentTime = marketAggregate.getCurrentTime(); assertEquals(currentTime, 100L); } @Test public void tickingAggregateAfterApplyingSeriesOfStockEvents_makesGetPriceSummaryReturnEmptyOptional() { // given StockEvent buyEvent = StockEvent.builder() .type("BUY") .price(new DoubleWrapper(100)) .build(); StockEvent sellEvent = StockEvent.builder() .type("SELL") .price(new DoubleWrapper(200)) .build(); // when marketAggregate.apply(buyEvent); marketAggregate.apply(sellEvent); marketAggregate.tick(); // then Optional<PriceSummary> priceSummaryOptional = marketAggregate.getPriceSummary(); assertFalse(priceSummaryOptional.isPresent()); } @Test public void applyingSeriesOfStockEvents_makesGetPriceSummaryReturnValidOpenCloseValues_forBuySellEvents() { // given StockEvent buyEvent = StockEvent.builder() .type("BUY") .price(new DoubleWrapper(100)) .build(); StockEvent sellEvent = StockEvent.builder() .type("SELL") .price(new DoubleWrapper(200)) .build(); // when marketAggregate.apply(buyEvent); marketAggregate.apply(sellEvent); // then Optional<PriceSummary> priceSummaryOptional = marketAggregate.getPriceSummary(); assertTrue(priceSummaryOptional.isPresent()); PriceSummary priceSummary = priceSummaryOptional.get(); assertEquals(100d, priceSummary.getOpen(), 0.00001); assertEquals(200d, priceSummary.getClose(), 0.00001); } @Test public void applyingSeriesOfStockEvents_makesGetPriceSummaryReturnValidTransactionCountValues_forBuySellEvents() { // given StockEvent buyEvent = StockEvent.builder() .type("BUY") .price(new DoubleWrapper(100)) .build(); StockEvent sellEvent = StockEvent.builder() .type("SELL") .price(new DoubleWrapper(200)) .build(); // when marketAggregate.apply(buyEvent); marketAggregate.apply(sellEvent); // then Optional<PriceSummary> priceSummaryOptional = marketAggregate.getPriceSummary(); assertTrue(priceSummaryOptional.isPresent()); PriceSummary priceSummary = priceSummaryOptional.get(); assertEquals(1, priceSummary.getBuyTransactionCount()); assertEquals(1, priceSummary.getSellTransactionCount()); } @Test public void applyingSeriesOfSingleTypeStockEvents_makesGetPriceSummaryReturnNullOppositeTypePriceSummary_forBuyEvents() { // given StockEvent buyEvent = StockEvent.builder() .type("BUY") .price(new DoubleWrapper(1000)) .amount(10d) .build(); // when marketAggregate.apply(buyEvent); // then Optional<PriceSummary> priceSummaryOptional = marketAggregate.getPriceSummary(); assertTrue(priceSummaryOptional.isPresent()); PriceSummary priceSummary = priceSummaryOptional.get(); assertNull(priceSummary.getSell()); } @Test public void applyingSeriesOfSingleTypeStockEvents_makesGetPriceSummaryReturnNullOppositeTypePriceSummary_forSellEvents() { // given StockEvent sellEvent = StockEvent.builder() .type("SELL") .price(new DoubleWrapper(1000)) .amount(10d) .build(); // when marketAggregate.apply(sellEvent); // then Optional<PriceSummary> priceSummaryOptional = marketAggregate.getPriceSummary(); assertTrue(priceSummaryOptional.isPresent()); PriceSummary priceSummary = priceSummaryOptional.get(); assertNull(priceSummary.getBuy()); } @Test public void applyingSeriesOfStockEvents_makesGetPriceSummaryReturnValidBuyPriceSummary_forBuyEvents() { // given StockEvent firstBuyEvent = StockEvent.builder() .type("BUY") .price(new DoubleWrapper(1000)) .amount(10d) .build(); StockEvent secondBuyEvent = StockEvent.builder() .type("BUY") .price(new DoubleWrapper(100)) .amount(100d) .build(); StockEvent thirdBuyEvent = StockEvent.builder() .type("BUY") .price(new DoubleWrapper(10)) .amount(1000d) .build(); // when marketAggregate.apply(firstBuyEvent); marketAggregate.apply(secondBuyEvent); marketAggregate.apply(thirdBuyEvent); // then Optional<PriceSummary> priceSummaryOptional = marketAggregate.getPriceSummary(); assertTrue(priceSummaryOptional.isPresent()); PriceSummary priceSummary = priceSummaryOptional.get(); PriceSummary.ByTypePriceSummary buyPriceSummary = priceSummary.getBuy(); assertEquals(10d, buyPriceSummary.getMin()); assertEquals(1000d, buyPriceSummary.getMax()); assertEquals(1110d, buyPriceSummary.getVolume()); assertEquals(370d, buyPriceSummary.getAvg()); assertEquals(10000d, buyPriceSummary.getWeightedAvg()); } @Test public void applyingSeriesOfStockEvents_makesGetPriceSummaryReturnValidSellPriceSummary_forSellEvents() { // given StockEvent firstSellEvent = StockEvent.builder() .type("SELL") .price(new DoubleWrapper(1000)) .amount(10d) .build(); StockEvent secondSellEvent = StockEvent.builder() .type("SELL") .price(new DoubleWrapper(100)) .amount(100d) .build(); StockEvent thirdSellEvent = StockEvent.builder() .type("SELL") .price(new DoubleWrapper(10)) .amount(1000d) .build(); // when marketAggregate.apply(firstSellEvent); marketAggregate.apply(secondSellEvent); marketAggregate.apply(thirdSellEvent); // then Optional<PriceSummary> priceSummaryOptional = marketAggregate.getPriceSummary(); assertTrue(priceSummaryOptional.isPresent()); PriceSummary priceSummary = priceSummaryOptional.get(); PriceSummary.ByTypePriceSummary sellPriceSummary = priceSummary.getSell(); assertEquals(10d, sellPriceSummary.getMin()); assertEquals(1000d, sellPriceSummary.getMax()); assertEquals(1110d, sellPriceSummary.getVolume()); assertEquals(370d, sellPriceSummary.getAvg()); assertEquals(10000d, sellPriceSummary.getWeightedAvg()); } @Test public void tickingAggregate_makesGetChangesCountReturnEmptyMap_forAsk() { // given StockEvent stockEvent = StockEvent.builder() .type("ASK") .price(new DoubleWrapper(100)) .build(); // when marketAggregate.apply(stockEvent); marketAggregate.tick(); // then Map<DoubleWrapper, Integer> changes = marketAggregate.getAsk().getChangesCount(100d); assertTrue(changes.isEmpty()); } @Test public void tickingAggregate_makesGetChangesCountReturnEmptyMap_forBid() { // given StockEvent stockEvent = StockEvent.builder() .type("BID") .price(new DoubleWrapper(100)) .build(); // when marketAggregate.apply(stockEvent); marketAggregate.tick(); // then Map<DoubleWrapper, Integer> changes = marketAggregate.getBid().getChangesCount(100d); assertTrue(changes.isEmpty()); } @Test public void tickingAggregate_makesGetTimeReturnTimeOfNextTimeWindow_forSingleTick() { // given StockEvent firstStockEvent = StockEvent.builder() .timestamp(100L) .build(); // when marketAggregate.apply(firstStockEvent); marketAggregate.tick(); // then long currentTime = marketAggregate.getCurrentTime(); assertEquals(currentTime, 1100L); } }
true
58a77149400d1e600e62b8c5a5f7042cb0c29af9
Java
liuxianchun/weshare-SpringCloud
/system/src/main/java/com/lxc/system/feign/fallback/LoginServiceImpl.java
UTF-8
1,132
1.757813
2
[ "Apache-2.0" ]
permissive
package com.lxc.system.feign.fallback; import com.lxc.common.entity.ResultBean; import com.lxc.common.entity.user.User; import com.lxc.system.feign.api.LoginService; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; /** * @author liuxianchun * @date 2021/5/23 */ @Service public class LoginServiceImpl implements LoginService { @Override public ResultBean findAccount(String account) { return null; } @Override public ResultBean findUserName(String username) { return null; } @Override public ResultBean isLogin(String token) { return null; } @Override public ResultBean userLogout(String token) { return null; } @Override public ResultBean userLogin(String loginCode, User user) { return null; } @Override public ResultBean userRegister(User user) { return null; } @Override public ResponseEntity<byte[]> getVerifyCode() { return null; } @Override public ResultBean getMailCode(String account){ return null; }; }
true
adaa5d0a4015aa1663041c5569f84664a3c5dc92
Java
ahnuljz/docx4j-template
/docx4j-template-core/src/test/java/org/docx4j/template/Docx4j_读取内容控件_S3_Test.java
UTF-8
7,318
1.914063
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2018, hiwepy (https://github.com/hiwepy). * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.docx4j.template; import java.io.File; import java.io.StringWriter; import java.util.ArrayList; import java.util.List; import javax.xml.bind.JAXBElement; import org.docx4j.TextUtils; import org.docx4j.TraversalUtil; import org.docx4j.TraversalUtil.CallbackImpl; import org.docx4j.XmlUtils; import org.docx4j.openpackaging.packages.WordprocessingMLPackage; import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart; import org.docx4j.wml.Body; import org.docx4j.wml.CTLock; import org.docx4j.wml.CTSdtCell; import org.docx4j.wml.ContentAccessor; import org.docx4j.wml.Document; import org.docx4j.wml.Id; import org.docx4j.wml.SdtBlock; import org.docx4j.wml.SdtContent; import org.docx4j.wml.SdtPr; import org.docx4j.wml.SdtPr.Alias; import org.docx4j.wml.SdtRun; import org.docx4j.wml.Tag; import org.jvnet.jaxb2_commons.ppp.Child; /** * Docx4j读取word 2007内容控件 * http://53873039oycg.iteye.com/blog/2193684 */ public class Docx4j_读取内容控件_S3_Test { public static void main(String[] args) throws Exception { Docx4j_读取内容控件_S3_Test t = new Docx4j_读取内容控件_S3_Test(); t.printSdtContent("f:/saveFile/temp/kkk - 副本.docx"); } public void printSdtContent(String filePath) throws Exception { WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage .load(new File(filePath)); MainDocumentPart mdp = wordMLPackage.getMainDocumentPart(); Document wmlDocumentEl = (Document) mdp.getContents(); Body body = wmlDocumentEl.getBody(); SdtFinder sdtFinder = new SdtFinder(); new TraversalUtil(body, sdtFinder); for (Child sdtChild : sdtFinder.sdtList) { if (sdtChild instanceof SdtRun) { SdtRun sdtRun = (SdtRun) sdtChild; SdtPr sdtPr = sdtRun.getSdtPr(); printSdtPrContent(sdtPr); // System.out.println(XmlUtils.marshaltoString(sdtPr, true, // true)); SdtContent sdtContent = sdtRun.getSdtContent(); System.out.println("-----------p content=" + getContentAccessorContent(sdtContent)); } else if (sdtChild instanceof CTSdtCell) { CTSdtCell sdtCell = (CTSdtCell) sdtChild; SdtPr sdtPr = sdtCell.getSdtPr(); printSdtPrContent(sdtPr); SdtContent sdtContent = sdtCell.getSdtContent(); System.out.println("-----------table content=" + getContentAccessorContent(sdtContent)); } else if (sdtChild instanceof SdtBlock) { SdtBlock sdtBlock = (SdtBlock) sdtChild; SdtPr sdtPr = sdtBlock.getSdtPr(); printSdtPrContent(sdtPr); SdtContent sdtContent = sdtBlock.getSdtContent(); System.out.println("-----------sdtblock content=" + getContentAccessorContent(sdtContent)); } } } // 没有解析样式 public void printSdtPrContent(SdtPr sdtPr) { StringBuffer sb = new StringBuffer(); List<Object> rprList = sdtPr.getRPrOrAliasOrLock(); for (Object obj : rprList) { if (obj instanceof JAXBElement) { String eName = ((JAXBElement) obj).getName().getLocalPart(); // 布尔类型特殊处理 if ("temporary".equals(eName)) { sb.append(" 替换后是否删除内容控件:").append("是"); } obj = XmlUtils.unwrap(obj); // System.out.println("------after="+ obj.getClass().getName()); if (obj instanceof CTLock) { CTLock lock = (CTLock) obj; if (lock != null) { sb.append(" 锁定方式:").append(lock.getVal()); } } else if (obj instanceof Alias) { Alias alias = (Alias) obj; if (alias != null) { sb.append(" 标题:").append(alias.getVal()); } } } else if (obj instanceof Tag) { Tag tag = (Tag) obj; if (tag != null) { sb.append(" tag标记:").append(tag.getVal()); } } else if (obj instanceof Id) { Id id = (Id) obj; if (id != null) { sb.append(" id:").append(id.getVal()); } } } System.out.println(sb.toString()); } public String getContentAccessorContent(SdtContent contentAcc) throws Exception { StringWriter stringWriter = new StringWriter(); TextUtils.extractText(contentAcc, stringWriter); return stringWriter.toString(); } } class SdtFinder extends CallbackImpl { List<Child> sdtList = new ArrayList<Child>(); public List<Object> apply(Object o) { if (o instanceof javax.xml.bind.JAXBElement && (((JAXBElement) o).getName().getLocalPart().equals("sdt"))) { sdtList.add((Child) XmlUtils.unwrap(o)); } else if (o instanceof SdtBlock) { sdtList.add((Child) o); } return null; } // to setParent public void walkJAXBElements(Object parent) { List children = getChildren(parent); if (children != null) { for (Object o : children) { if (o instanceof javax.xml.bind.JAXBElement && (((JAXBElement) o).getName().getLocalPart() .equals("sdt"))) { ((Child) ((JAXBElement) o).getValue()).setParent(XmlUtils .unwrap(parent)); } else { o = XmlUtils.unwrap(o); if (o instanceof Child) { ((Child) o).setParent(XmlUtils.unwrap(parent)); } } this.apply(o); if (this.shouldTraverse(o)) { walkJAXBElements(o); } } } } }
true
0c7d237877182b749ba22845b159d8f21e42ae9f
Java
Saurabhtilekar/java
/src/Loopprograms/Breakex.java
UTF-8
311
2.984375
3
[]
no_license
package Loopprograms; public class Breakex { public static void main(String[] args) { int n1=4,n2=5,n3=n1+n2; boolean t=true; System.out.println(n1+""+n2); while(t) { n3=n1+n2; if(n3>40) break; System.out.println(""+n3); n1=n2; n2=n3; } } }
true
63615f9fc0a585342f9ddf041777cdedbc66bbca
Java
Acodebitch/LeetCode
/src/leetcode/_3Sum.java
UTF-8
760
3.125
3
[]
no_license
package leetcode; import java.util.*; public class _3Sum { public List<List<Integer>> threeSum(int[] num) { List<List<Integer>> list = new ArrayList<List<Integer>>(); Arrays.sort(num); for(int i=0;i<num.length-2;i++) if (i == 0 || (i > 0 && num[i] != num[i-1])) { int j = i+1; int k = num.length - 1; int temp = 0-num[i]; while(j<k) { if(num[j]+num[k]==temp) { while(j<k&&num[j] == num[j+1])j++; while(j<k&&num[k]==num[k-1])k--; list.add(Arrays.asList(num[i],num[j],num[k])); j++; k--; } else if(num[j]+num[k]<temp) j++; else k--; } } return list; } }
true
6c7100e4ff85406d94b81c7cf1d3c7cbbb0cfce8
Java
Irina849/SuperProjectQA
/src/test/java/com/it/pages/DashboardPage.java
UTF-8
779
2
2
[]
no_license
package com.it.pages; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class DashboardPage extends BasePage { @FindBy(xpath = "//span[@class='sn_menu_title']") private WebElement ldUserEmail; public String getLBUserEmail() { // WebDriverWait webDriverWait = new WebDriverWait(driver,20); // WebElement element = webDriverWait.until(s-> s.findElement(By.xpath("//span[@class='sn_menu_title']"))); // return element.getText(); return ldUserEmail.getText(); } }
true
45fc714ccf28be1e85e46378f810f8b3693c8ae7
Java
filippocastrogiovanni/IF3Tserver
/src/main/java/if3t/services/ActionIngredientService.java
UTF-8
425
2
2
[]
no_license
package if3t.services; import java.util.List; import java.util.Map; import if3t.entities.ActionIngredient; public interface ActionIngredientService { public ActionIngredient readActionIngredient(Long id); public List<ActionIngredient> readActionIngredients(); public List<ActionIngredient> getRecipeActionIngredients(Long recipeId); public Map<Long, ActionIngredient> getRecipeActionIngredientsMap(Long recipeId); }
true
02a2a989c7aaba70a56f17954d0667803bea16cf
Java
mihabin/Algorithm
/src/com/jyami/baekjoon/Main_10845_2.java
UTF-8
2,218
3.390625
3
[]
no_license
package com.jyami.baekjoon; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main_10845_2 { public static BufferedReader br; public static StringBuilder sb; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); sb = new StringBuilder(); int t = Integer.parseInt(br.readLine()); Queue queue = new Queue(); for (int i = 0; i < t; i++) { command(br.readLine(), queue); } } public static void command(String text, Queue queue) { switch (text) { case "pop": System.out.println(queue.pop()); break; case "size": System.out.println(queue.size()); break; case "empty": System.out.println(queue.empty()); break; case "front": System.out.println(queue.front()); break; case "back": System.out.println(queue.back()); break; default: int temp = Integer.parseInt(text.split(" ")[1]); queue.push(temp); break; } } private static class Queue { private int data[] = new int[10000]; private int front = 0; private int back = 0; public void push(int x) { data[back++] = x; } public int empty() { if (front == back) return 1; return 0; } public int pop() { if (front != back) { int temp = data[front]; data[front] = 0; front++; return temp; } return -1; } public int front() { if (front != back) return data[front]; return -1; } public int size() { return back - front; } public int back() { if (front != back) return data[back - 1]; return -1; } } }
true
4cace64733d6cae90b11ac3376506aea66f60d07
Java
AlinMH/acs-sma-lab
/lab07/src/agents/MyAgent.java
UTF-8
2,235
2.90625
3
[ "MIT" ]
permissive
package agents; import java.util.LinkedList; import java.util.List; import agents.behaviors.*; import jade.core.AID; import jade.core.Agent; /** * The Agent. */ public class MyAgent extends Agent { /** * The serial UID. */ private static final long serialVersionUID = 2081456560111009192L; /** * Known child agents. */ List<AID> childAgents = new LinkedList<>(); /** * The ID of the parent. */ AID parentAID; /** * The value associated to the agent. */ int agentValue; /** * @param childAID the ID of the child to add. */ public void addChildAgent(AID childAID) { childAgents.add(childAID); } /** * @return the list of IDs of child agents. */ public List<AID> getChildAgents() { return childAgents; } @Override protected void setup() { parentAID = (AID) getArguments()[0]; agentValue = ((Integer) getArguments()[1]).intValue(); System.out.println("[HELLO] Hello from agent: " + getAID().getName() + " with parentAID: " + parentAID); // add the RegistrationSendBehavior if (parentAID != null) { System.out.println("[REGISTRATION] Registration sender behavior for this agent starts in 1 second"); addBehaviour(new RegistrationSenderBehavior(this, 1000, parentAID)); } else { System.out.println("[REGISTRATION] Registration sender behavior need not start for agent " + getAID().getName()); } // add the RegistrationReceiveBehavior addBehaviour(new RegistrationReceiverBehavior(this)); addBehaviour(new ProcedureStartReceiverBehavior(this)); addBehaviour(new MaxBehavior(this)); addBehaviour(new ReceiveMaxValueBehavior(this)); } public AID getParentAID() { return parentAID; } public int getAgentValue() { return agentValue; } public void setAgentValue(int agentValue) { this.agentValue = agentValue; } @Override protected void takeDown() { // Printout a dismissal message String out = "[END PROCEDURE] Agent " + getAID().getLocalName() + " max value is " + agentValue; System.out.println(out); } }
true
ca99549a74803332d5472f31981f1a7c0239e1c3
Java
uwitec/bdswcrm
/src/com/sw/cms/xls/ExportProductSerialXshzResult.java
GB18030
4,823
2.078125
2
[]
no_license
package com.sw.cms.xls; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import jxl.write.Label; import jxl.write.WritableSheet; import com.sw.cms.service.ProductSerialNumXsHzService; import com.sw.cms.util.DateComFunc; import com.sw.cms.util.JMath; import com.sw.cms.util.StaticParamDo; import com.sw.cms.util.StringUtils; import com.sw.cms.xls.template.ExportXlsTemplate; public class ExportProductSerialXshzResult extends ExportXlsTemplate { private ProductSerialNumXsHzService productSerialNumXsHzService; @Override public void writeExcelFile(HttpServletRequest request, WritableSheet sheet) { try{ String start_date = StringUtils.nullToStr(request.getParameter("start_date")); String end_date = StringUtils.nullToStr(request.getParameter("end_date")); String dept_id = StringUtils.nullToStr(request.getParameter("dept_id")); String clientId = StringUtils.nullToStr(request.getParameter("clientId")); String client_name = StringUtils.nullToStr(request.getParameter("client_name")); String product_name = StringUtils.nullToStr(request.getParameter("product_name")); String product_kind = StringUtils.nullToStr(request.getParameter("product_kind")); String xsry_name = StringUtils.nullToStr(request.getParameter("xsry_name")); String con = ""; con = "ڣ" + start_date + "" + end_date; if(!clientId.equals("")){ con += " ͻƣ" + clientId; } if(!dept_id.equals("")){ con += " ţ" + StaticParamDo.getDeptNameById(dept_id); } if(!product_kind.equals("")){ con += " Ʒ" + StaticParamDo.getProductKindNameById(product_kind); } con += "ʱ䣺" + DateComFunc.getCurTime(); Label label = null; //дͳƱ sheet.mergeCells(0, 0, 7, 0); label = new Label(0,0,"Ʒкۻ",this.getFt_title()); sheet.addCell(label); //дͳ sheet.mergeCells(0, 1, 7, 1); label = new Label(0,1,con,this.getFt_item_center()); sheet.addCell(label); //дͳƱͷ label = new Label(0,2,"",this.getFt_item_center_bold()); sheet.addCell(label); label = new Label(1,2,"к",this.getFt_item_center_bold()); sheet.addCell(label); label = new Label(2,2,"Ʒ",this.getFt_item_center_bold()); sheet.addCell(label); label = new Label(3,2,"Ʒ",this.getFt_item_center_bold()); sheet.addCell(label); label = new Label(4,2,"ͻ",this.getFt_item_center_bold()); sheet.addCell(label); label = new Label(5,2,"ͻ绰",this.getFt_item_center_bold()); sheet.addCell(label); label = new Label(6,2,"Ա",this.getFt_item_center_bold()); sheet.addCell(label); label = new Label(7,2,"ۼ۸",this.getFt_item_center_bold()); sheet.addCell(label); List resultList = productSerialNumXsHzService.getSerialNumXsList(start_date, end_date, product_kind, product_name, dept_id, xsry_name,clientId); int hj_nums = 0; double hj_je = 0; int k = 3; //дͳ if(resultList != null && resultList.size()>0){ for(int i=0;i<resultList.size();i++){ Map map = (Map)resultList.get(i); double je = map.get("xsdj")==null?0:((Double)map.get("xsdj")).doubleValue(); label = new Label(0,k,StringUtils.nullToStr(map.get("fs_date")),this.getFt_item_left()); sheet.addCell(label); label = new Label(1,k,StringUtils.nullToStr(map.get("serial_num")),this.getFt_item_left()); sheet.addCell(label); label = new Label(2,k,StringUtils.nullToStr(map.get("product_name")),this.getFt_item_left()); sheet.addCell(label); label = new Label(3,k,StringUtils.nullToStr(map.get("product_xh")),this.getFt_item_left()); sheet.addCell(label); label = new Label(4,k,StringUtils.nullToStr(map.get("client_name")),this.getFt_item_left()); sheet.addCell(label); label = new Label(5,k,StringUtils.nullToStr(map.get("tel")),this.getFt_item_left()); sheet.addCell(label); label = new Label(6,k,StringUtils.nullToStr(map.get("jsr")),this.getFt_item_left()); sheet.addCell(label); label = new Label(7,k,JMath.round(je,2),this.getFt_item_right()); sheet.addCell(label); k++; } } }catch(Exception ex){ log.info(ex); } } public ProductSerialNumXsHzService getProductSerialNumXsHzService() { return productSerialNumXsHzService; } public void setProductSerialNumXsHzService(ProductSerialNumXsHzService productSerialNumXsHzService) { this.productSerialNumXsHzService = productSerialNumXsHzService; } }
true
b3fe0b7037f6ac5e254c729d88bd03cd287bf8b3
Java
VerRan/amazon-kinesis-data-visualization-sample
/src/main/java/com/amazonaws/services/kinesis/samples/datavis/kcl/persistence/ddb/DynamoDBCountPersister.java
UTF-8
10,135
2.421875
2
[ "MIT-0" ]
permissive
/* * Copyright 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: MIT-0 */ package com.amazonaws.services.kinesis.samples.datavis.kcl.persistence.ddb; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TimeZone; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper.FailedBatch; import com.amazonaws.services.kinesis.samples.datavis.kcl.persistence.CountPersister; import com.amazonaws.services.kinesis.samples.datavis.model.HttpReferrerPair; import com.amazonaws.services.kinesis.samples.datavis.model.HttpReferrerPairsCount; import com.amazonaws.services.kinesis.samples.datavis.model.ReferrerCount; /** * Persists counts to DynamoDB. This uses a separate thread to send counts to DynamoDB to decouple any network latency * from affecting the thread we use to update counts. */ public class DynamoDBCountPersister implements CountPersister<HttpReferrerPair> { private static final Log LOG = LogFactory.getLog(DynamoDBCountPersister.class); // Generate UTC timestamps private static final TimeZone UTC = TimeZone.getTimeZone("UTC"); private DynamoDBMapper mapper; /** * This is used to limit the in memory queue. This number is the total counts we could generate for 10 unique * resources in 10 minutes if our update interval is 100ms. * * 10 resources * 10 minutes * 60 seconds * 10 intervals per second = 60,000. */ private static final int MAX_COUNTS_IN_MEMORY = 60000; // The queue holds all pending referrer pair counts to be sent to DynamoDB. private BlockingQueue<HttpReferrerPairsCount> counts = new LinkedBlockingQueue<>(MAX_COUNTS_IN_MEMORY); // The thread to use for sending counts to DynamoDB. private Thread dynamoDBSender; /** * The hostname of this machine. Used to indicate which host updated a set of counts. */ private String hostname; /** * Create a new persister with a DynamoDBMapper to translate counts to items and send to Amazon DynamoDB. * * @param mapper Amazon DynamoDB Mapper to use. */ public DynamoDBCountPersister(DynamoDBMapper mapper) { if (mapper == null) { throw new NullPointerException("mapper must not be null"); } this.mapper = mapper; } @Override public void initialize() { // Resolve our hostname so we can tag the counts this persister produces. hostname = resolveHostname(); // This thread is responsible for draining the queue of new counts and sending them in batches to DynamoDB dynamoDBSender = new Thread() { @Override public void run() { // Create a reusable buffer to drain our queue into. List<HttpReferrerPairsCount> buffer = new ArrayList<>(MAX_COUNTS_IN_MEMORY); // Continuously attempt to drain the queue and send counts to DynamoDB until this thread is interrupted while (!Thread.currentThread().isInterrupted()) { try { // Drain anything that's in the queue to the buffer and write the items to DynamoDB sendQueueToDynamoDB(buffer); // We wait for an empty queue before checkpointing. Notify that thread when we're empty in // case it is waiting. synchronized(counts) { if (counts.isEmpty()) { counts.notify(); } } } catch (InterruptedException e) { LOG.error("Thread that handles persisting counts to DynamoDB was interrupted. Counts will no longer be persisted!", e); return; } finally { // Clear the temporary buffer to release references to persisted counts buffer.clear(); } } } }; dynamoDBSender.setDaemon(true); dynamoDBSender.start(); } @Override public void persist(Map<HttpReferrerPair, Long> objectCounts) { if (objectCounts.isEmpty()) { // short circuit to avoid creating a map when we have no objects to persist return; } // Use a local collection to batch writing the new counts into the queue. This will allow the queue drainer // to remain simple as it doesn't have to account for less than full batches. // We map resource to pair counts so we can easily look up a resource and add referrer counts to it Map<String, HttpReferrerPairsCount> countMap = new HashMap<>(); for (Map.Entry<HttpReferrerPair, Long> count : objectCounts.entrySet()) { // Check for an existing counts for this resource HttpReferrerPair pair = count.getKey(); HttpReferrerPairsCount pairCount = countMap.get(pair.getResource()); if (pairCount == null) { // Create a new pair if this resource hasn't been seen yet in this batch pairCount = new HttpReferrerPairsCount(); pairCount.setResource(pair.getResource()); pairCount.setTimestamp(Calendar.getInstance(UTC).getTime()); pairCount.setReferrerCounts(new ArrayList<ReferrerCount>()); pairCount.setHost(hostname); countMap.put(pair.getResource(), pairCount); } // Add referrer to list of refcounts for this resource and time ReferrerCount refCount = new ReferrerCount(); refCount.setReferrer(pair.getReferrer()); refCount.setCount(count.getValue()); pairCount.getReferrerCounts().add(refCount); } // Top N calculation for this interval // By sorting the referrer counts list in descending order the consumer of the count data can choose their own // N. for (HttpReferrerPairsCount count : countMap.values()) { Collections.sort(count.getReferrerCounts(), new Comparator<ReferrerCount>() { @Override public int compare(ReferrerCount c1, ReferrerCount c2) { if (c2.getCount() > c1.getCount()) { return 1; } else if (c1.getCount() == c2.getCount()) { return 0; } else { return -1; } } }); } counts.addAll(countMap.values()); } /** * We will block until the entire queue of counts has been drained. */ @Override public void checkpoint() throws InterruptedException { // We need to make sure all counts are flushed to DynamoDB before we return successfully. if (dynamoDBSender.isAlive()) { // If the DynamoDB thread is running wait until our counts queue is empty synchronized(counts) { while (!counts.isEmpty()) { counts.wait(); } // All the counts we currently know about have been persisted. It is now safe to return from this blocking call. } } else { throw new IllegalStateException("DynamoDB persister thread is not running. Counts are not persisted and we should not checkpoint!"); } } /** * Drain the queue of pending counts into the provided buffer and write those counts to DynamoDB. This blocks until * data is available in the queue. * * @param buffer A reusable buffer with sufficient space to drain the entire queue if necessary. This is provided as * an optimization to avoid allocating a new buffer every interval. * @throws InterruptedException Thread interrupted while waiting for new data to arrive in the queue. */ protected void sendQueueToDynamoDB(List<HttpReferrerPairsCount> buffer) throws InterruptedException { // Block while waiting for data buffer.add(counts.take()); // Drain as much of the queue as we can. // DynamoDBMapper will handle splitting the batch sizes for us. counts.drainTo(buffer); try { long start = System.nanoTime(); // Write the contents of the buffer as items to our table List<FailedBatch> failures = mapper.batchWrite(buffer, Collections.emptyList()); long end = System.nanoTime(); LOG.info(String.format("%d new counts sent to DynamoDB in %dms", buffer.size(), TimeUnit.NANOSECONDS.toMillis(end - start))); for (FailedBatch failure : failures) { LOG.warn("Error sending count batch to DynamoDB. This will not be retried!", failure.getException()); } } catch (Exception ex) { LOG.error("Error sending new counts to DynamoDB. The some counts may not be persisted.", ex); } } /** * Resolve the hostname of the machine executing this code. * * @return The hostname, or "unknown", if one cannot be determined. */ private String resolveHostname() { try { return InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException uhe) { LOG.warn("Unable to determine hostname. Counts from this worker will be registered as counted by 'unknown'!", uhe); } return "unknown"; } }
true
109f4f512184b47747e25c0612b4a3591c740c76
Java
Peter554/adventofcode
/2015/aoc2015java/src/main/java/aoc2015/day10/Solution.java
UTF-8
709
3.390625
3
[]
no_license
package aoc2015.day10; public class Solution { public static String lookAndSay(String s, int nTimes) { if (nTimes == 0) { return s; } var pointer = 0; var sb = new StringBuilder(); while (pointer < s.length()) { var character = s.charAt(pointer); var characterCount = 1; while (pointer + 1 < s.length() && s.charAt(pointer + 1) == character) { characterCount++; pointer++; } pointer++; sb.append(String.format("%d%d", characterCount, Character.getNumericValue(character))); } return lookAndSay(sb.toString(), nTimes - 1); } }
true
f38f3d92058ea62264115fe121fbd86bcc2336aa
Java
apache/commons-jcs
/commons-jcs3-core/src/test/java/org/apache/commons/jcs3/auxiliary/AuxiliaryCacheConfiguratorUnitTest.java
UTF-8
5,074
2.046875
2
[ "LicenseRef-scancode-generic-cla", "Apache-2.0" ]
permissive
package org.apache.commons.jcs3.auxiliary; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.Properties; import org.apache.commons.jcs3.engine.behavior.IElementSerializer; import org.apache.commons.jcs3.engine.control.MockElementSerializer; import org.apache.commons.jcs3.engine.logging.MockCacheEventLogger; import org.apache.commons.jcs3.utils.serialization.StandardSerializer; import org.junit.Test; /** Unit tests for the auxiliary cache configurator. */ public class AuxiliaryCacheConfiguratorUnitTest { /** * Verify that we don't get an error. */ @Test public void testParseCacheEventLogger_Null() { // SETUP final Properties props = new Properties(); // DO WORK final MockCacheEventLogger result = (MockCacheEventLogger) AuxiliaryCacheConfigurator.parseCacheEventLogger( props, "junk" ); // VERIFY assertNull( "Should not have a logger.", result ); } /** * Verify that we don't get an error. */ @Test public void testParseCacheEventLogger_NullName() { // SETUP final Properties props = new Properties(); // DO WORK final MockCacheEventLogger result = (MockCacheEventLogger) AuxiliaryCacheConfigurator.parseCacheEventLogger( props, null ); // VERIFY assertNull( "Should not have a logger.", result ); } /** * Verify that we can parse the event logger. */ @Test public void testParseCacheEventLogger_Normal() { // SETUP final String auxPrefix = "jcs.auxiliary." + "MYAux"; final String testPropertyValue = "This is the value"; final String className = MockCacheEventLogger.class.getName(); final Properties props = new Properties(); props.put( auxPrefix + AuxiliaryCacheConfigurator.CACHE_EVENT_LOGGER_PREFIX, className ); props.put( auxPrefix + AuxiliaryCacheConfigurator.CACHE_EVENT_LOGGER_PREFIX + AuxiliaryCacheConfigurator.ATTRIBUTE_PREFIX + ".testProperty", testPropertyValue ); // DO WORK final MockCacheEventLogger result = (MockCacheEventLogger) AuxiliaryCacheConfigurator .parseCacheEventLogger( props, auxPrefix ); // VERIFY assertNotNull( "Should have a logger.", result ); assertEquals( "Property should be set.", testPropertyValue, result.getTestProperty() ); } /** * Verify that we can parse the ElementSerializer. */ @Test public void testParseElementSerializer_Normal() { // SETUP final String auxPrefix = "jcs.auxiliary." + "MYAux"; final String testPropertyValue = "This is the value"; final String className = MockElementSerializer.class.getName(); final Properties props = new Properties(); props.put( auxPrefix + AuxiliaryCacheConfigurator.SERIALIZER_PREFIX, className ); props.put( auxPrefix + AuxiliaryCacheConfigurator.SERIALIZER_PREFIX + AuxiliaryCacheConfigurator.ATTRIBUTE_PREFIX + ".testProperty", testPropertyValue ); // DO WORK final MockElementSerializer result = (MockElementSerializer) AuxiliaryCacheConfigurator .parseElementSerializer( props, auxPrefix ); // VERIFY assertNotNull( "Should have a Serializer.", result ); assertEquals( "Property should be set.", testPropertyValue, result.getTestProperty() ); } /** * Verify that we can parse the ElementSerializer. */ @Test public void testParseElementSerializer_Null() { // SETUP final Properties props = new Properties(); // DO WORK final IElementSerializer result = AuxiliaryCacheConfigurator .parseElementSerializer( props, "junk" ); // VERIFY assertTrue( "Should have the default Serializer.", result instanceof StandardSerializer ); } }
true
fc3b6175339547e555ef1800ba4f89ab68ad72a0
Java
premvreddy/Test
/MyProject/src/com/services/DraftWithdrawService.java
UTF-8
629
1.875
2
[]
no_license
package com.services; import java.util.Date; import java.util.List; import com.entities.DraftWithdrawEntity; public interface DraftWithdrawService { DraftWithdrawEntity addUser(String bankname, String bankcode,String branchname, String branchcode, String userName, String memberid, String withdrawno, Date withdrawdate, String accoounttype, String accountno, String name, long amount, long cell, String remarks, int thousand, int fivehundered, int hundered, int fifty, int twenty, int ten, int five, int two, int one, int coins); List<DraftWithdrawEntity> getWithdrawInfo(); }
true
c1d31a80bc47c9faba58bfc9be5bac9fa8e43af5
Java
hrbyangnan/Java_assignment
/src/readAILevelException.java
UTF-8
200
2.203125
2
[]
no_license
import java.io.IOException; public class readAILevelException extends Exception { public readAILevelException () { } readAILevelException(String message){ super(message); } }
true
737dca8e60786e9f6f4a11b983224c04bcf9d0e1
Java
wangwenwang/tms-android
/app/src/main/java/com/kaidongyuan/app/kdydriver/ui/activity/NotifyActivity.java
UTF-8
4,926
2.0625
2
[ "MIT" ]
permissive
package com.kaidongyuan.app.kdydriver.ui.activity; import android.os.Bundle; import android.view.View; import android.widget.TextView; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.kaidongyuan.app.basemodule.interfaces.AsyncHttpCallback; import com.kaidongyuan.app.basemodule.widget.SlidingTitleView; import com.kaidongyuan.app.kdydriver.R; import com.kaidongyuan.app.kdydriver.bean.order.Notify; import com.kaidongyuan.app.kdydriver.constants.Constants; import com.kaidongyuan.app.kdydriver.httpclient.OrderAsyncHttpClient; import com.kaidongyuan.app.kdydriver.ui.base.BaseActivity; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 咨询通知 Activity */ public class NotifyActivity extends BaseActivity implements AsyncHttpCallback { private SlidingTitleView titleView; private TextView tv_content; private TextView tv_title; private TextView tv_info; private static final String Tag_Detail = "Tag_Detail"; private OrderAsyncHttpClient client; // private static final String TEST = "<p style=\\\"text-indent:28px;\\\"><span style=\\\"color:#FF0000;\\\"><b>特价1:购买100桶怡宝纯净水(13元/桶)赠送20桶(仅限部分商业用户);</b></span></p><span style=\\\"font-size:14px;\\\"><p style=\\\"text-indent:28px;\\\"><span style=\\\"color:#FF0000;\\\"><b>特价2:购买 50桶怡宝纯净水(13元/桶)赠送 5桶(仅限部分商业用户);</b></span></p></span>"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_notify); titleView = (SlidingTitleView) findViewById(R.id.title_notify); tv_content = (TextView) findViewById(R.id.tv_content); tv_title = (TextView) findViewById(R.id.tv_title); tv_info = (TextView) findViewById(R.id.tv_info); titleView.setMode(SlidingTitleView.MODE_NULL); findViewById(R.id.btn_read).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); titleView.setText("资讯信息"); if (getIntent()!=null&&getIntent().hasExtra("id")){ client = new OrderAsyncHttpClient(this, this); Map<String, String> params = new HashMap<>(); params.put("strLicense", ""); params.put("strIDX",getIntent().getStringExtra("id")); client.sendRequest(Constants.URL.GetMessageDetils, params, Tag_Detail); } // mWebView.loadDataWithBaseURL(null, source, "text/html", "utf-8", null); /*if (url != null) mWebView.loadUrl(url); mWebView.setWebViewClient(new WebViewClient() { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); showLoadingDialog(); } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); cancelLoadingDialog(); } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { super.onReceivedError(view, errorCode, description, failingUrl); cancelLoadingDialog(); } }); WebSettings settings = mWebView.getSettings(); settings.setDefaultTextEncodingName("UTF-8"); settings.setBuiltInZoomControls(true); // 设置显示缩放按钮 settings.setSupportZoom(true); // 支持缩放 settings.setBuiltInZoomControls(true); settings.setDefaultZoom(WebSettings.ZoomDensity.CLOSE); settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL); settings.setUseWideViewPort(true); settings.setLoadWithOverviewMode(true); settings.setJavaScriptEnabled(true);*/ } @Override protected void onDestroy() { client.cancleRequest(Tag_Detail); super.onDestroy(); } @Override public void postSuccessMsg(String msg, String request_tag) { if (msg.equals("error")){ tv_content.setText("数据丢失,请返回重载~"); return; } if (request_tag.equals(Tag_Detail)) { JSONObject jo = JSON.parseObject(msg); List<Notify> notifies = JSON.parseArray(jo.getString("result"), Notify.class); if (notifies.size() > 0) { Notify notify = notifies.get(0); tv_title.setText(notify.getTITLE()); tv_content.setText("\t\t"+notify.getMESSAGE()); } } } }
true
795f7273a3404bda1e2d88d80b7934849207ba38
Java
cmccarthy-ucc/FYP
/app/src/main/java/com/example/ciara/drugsmart/ActivityGroupHome.java
UTF-8
6,285
1.890625
2
[]
no_license
package com.example.ciara.drugsmart; import android.app.Activity; import android.app.ActivityGroup; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.NavigationView; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.Toast; public class ActivityGroupHome extends AppCompatActivity { Button addGroup; Button viewGroups; Button addGroupVaccination; Button viewGroupVaccination; Button searchGroups; Button addGroupDose; Button viewDoses; //https://medium.com/quick-code/android-navigation-drawer-e80f7fc2594f private DrawerLayout dl; private ActionBarDrawerToggle t; private NavigationView nv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_group_home); addGroup = (Button) findViewById(R.id.btnAddGroup); addGroup.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(ActivityGroupHome.this, ActivityAddGroup.class); startActivity(intent); } }); viewGroups = (Button) findViewById(R.id.btnViewGroups); viewGroups.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(ActivityGroupHome.this, ActivityAllGroups.class); startActivity(intent); } }); viewGroupVaccination = (Button) findViewById(R.id.btnViewGroupVaccinations); viewGroupVaccination.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(ActivityGroupHome.this, ActivityAllGroupVaccinations.class); startActivity(intent); } }); addGroupVaccination = (Button) findViewById(R.id.btnAddGroupVaccinations); addGroupVaccination.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(ActivityGroupHome.this, ActivityAllGroups.class); startActivity(intent); } }); searchGroups = (Button) findViewById(R.id.buttonSearchGroups); searchGroups.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(ActivityGroupHome.this, SearchDatabase.class); startActivity(intent); } }); addGroupDose = (Button) findViewById(R.id.buttonAddGroupDose); addGroupDose.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(ActivityGroupHome.this, ActivityAllGroups.class); startActivity(intent); } }); viewDoses = (Button) findViewById(R.id.buttonViewDoses); viewDoses.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(ActivityGroupHome.this, ActivityAllDoses.class); startActivity(intent); } }); //Navigation Drawer dl = (DrawerLayout)findViewById(R.id.activity_main); t = new ActionBarDrawerToggle(this, dl,R.string.Open, R.string.Close); dl.addDrawerListener(t); t.syncState(); getSupportActionBar().setDisplayHomeAsUpEnabled(true); nv = (NavigationView)findViewById(R.id.nv); nv.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { int id = item.getItemId(); switch (id) { case R.id.animals: //Toast.makeText(ActivityOptions.this, "Animals",Toast.LENGTH_SHORT).show(); Intent intentAnimal = new Intent(ActivityGroupHome.this, ActivityIndividualHome.class); startActivity(intentAnimal); break; case R.id.vaccinations: Toast.makeText(ActivityGroupHome.this, "Medical Records", Toast.LENGTH_SHORT).show(); Intent intentVaccination = new Intent(ActivityGroupHome.this, ActivityMedicalRecords2.class); startActivity(intentVaccination); break; case R.id.groups: Toast.makeText(ActivityGroupHome.this, "Groups", Toast.LENGTH_SHORT).show(); Intent intentGroups = new Intent(ActivityGroupHome.this, ActivityGroupHome.class); startActivity(intentGroups); break; case R.id.home: Toast.makeText(ActivityGroupHome.this,"Home", Toast.LENGTH_SHORT).show(); Intent intentHome = new Intent(ActivityGroupHome.this, ActivityOptionsTwo.class); startActivity(intentHome); break; case R.id.todo: Toast.makeText(ActivityGroupHome.this,"To-Do List", Toast.LENGTH_SHORT).show(); Intent intentToDo = new Intent(ActivityGroupHome.this, ActivityToDoList.class); startActivity(intentToDo); break; default: return true; } return true; } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { if(t.onOptionsItemSelected(item)) return true; return super.onOptionsItemSelected(item); } }
true
ceabb2b2a8b2eec00c8cb30bb2262433c8b53ef3
Java
Syed-Bakhtiyar/ARRAYMATRIX
/MissLecture2/src/misslecture2/NewClass1.java
UTF-8
352
1.929688
2
[]
no_license
/* * 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 misslecture2; /** * * @author bakhtiyar */ public class NewClass1 { private int a = 2; public void abs(){ System.err.println(a); } }
true
25ad688006d596d4cd6b63354de0d8e074c5f19d
Java
AntoninoAN/OpenWeatherApp
/app/src/main/java/com/example/tony/myweatherapp/Model/DBContract.java
UTF-8
305
1.90625
2
[]
no_license
package com.example.tony.myweatherapp.Model; import android.database.sqlite.SQLiteDatabase; import android.support.annotation.Nullable; /** * Created by tony on 10/13/17. */ public interface DBContract { void saveCurrentWeather(@Nullable String location, @Nullable String zip, String current); }
true
6aeb8b2e0b2bf0709327c04e202f475917372a80
Java
mikestuartorg/config
/sample/src/main/java/com/example/config/SampleProperties.java
UTF-8
469
1.835938
2
[]
no_license
package com.example.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.stereotype.Component; @RefreshScope @Component public class SampleProperties { @Value("${sample.index}") String index; @Value("${sample.secret}") String secret; public String getIndex() { return index; } public String getSecret() { return secret; } }
true
6d480beee7461c9792a96760a07b939ccb50aa06
Java
ttim/mps-core
/languages/notation/source_gen/jetbrains/mps/core/notation/editor/goodEnterHandling.java
UTF-8
1,578
2.078125
2
[]
no_license
package jetbrains.mps.core.notation.editor; /*Generated by MPS */ import jetbrains.mps.nodeEditor.cells.EditorCell; import jetbrains.mps.smodel.SNode; import jetbrains.mps.nodeEditor.EditorContext; import jetbrains.mps.nodeEditor.CellActionType; import jetbrains.mps.nodeEditor.EditorCellAction; import jetbrains.mps.internal.collections.runtime.ListSequence; import jetbrains.mps.lang.smodel.generator.smodelAdapter.SLinkOperations; import jetbrains.mps.smodel.action.SNodeFactoryOperations; public class goodEnterHandling { public static void setCellActions(EditorCell editorCell, SNode node, EditorContext context) { editorCell.setAction(CellActionType.INSERT, new goodEnterHandling.goodEnterHandling_INSERT(node)); } public static class goodEnterHandling_INSERT extends EditorCellAction { /*package*/ SNode myNode; public goodEnterHandling_INSERT(SNode node) { this.myNode = node; } public void execute(EditorContext editorContext) { this.execute_internal(editorContext, this.myNode); } public void execute_internal(EditorContext editorContext, SNode node) { if (ListSequence.fromList(SLinkOperations.getTargets(node, "alternatives", true)).isEmpty()) { SNodeFactoryOperations.addNewChild(node, "alternatives", "jetbrains.mps.core.notation.structure.SNotationAlternativePart"); } else { SNodeFactoryOperations.addNewChild(ListSequence.fromList(SLinkOperations.getTargets(node, "alternatives", true)).last(), "parts", "jetbrains.mps.core.notation.structure.SNotationPart"); } } } }
true
7a2e6e831f0647442ab39029a3bb84cf9eed56ed
Java
brandonlamb/game-server-mmorpg
/draco/src/java/game/com/game/draco/action/internal/FactionRoleRemoveInternalAction.java
UTF-8
1,390
2.203125
2
[]
no_license
//package com.game.draco.action.internal; // //import java.util.Date; // //import com.game.draco.GameContext; //import com.game.draco.message.internal.C0073_UnionRoleRemoveInternalMessage; // //import sacred.alliance.magic.action.BaseAction; //import sacred.alliance.magic.core.Message; //import sacred.alliance.magic.core.action.ActionContext; //import sacred.alliance.magic.vo.RoleInstance; // //public class FactionRoleRemoveInternalAction extends BaseAction<C0073_UnionRoleRemoveInternalMessage> { // // @Override // public Message execute(ActionContext context,C0073_UnionRoleRemoveInternalMessage reqMsg) { // String roleId = reqMsg.getRoleId(); // try{ // RoleInstance role = GameContext.getOnlineCenter().getRoleInstanceByRoleId(String.valueOf(roleId)); // boolean isOnline = false; // if(null == role){ // role = GameContext.getBaseDAO().selectEntity(RoleInstance.class, "roleId", roleId); // }else{ // isOnline = true; // } // if(null == role) { // return null; // } // role.setUnionId("");//先不用更新角色数据库 // //如果角色没有在线则库中role对象上存在公会ID // //只更新ROLE对象的公会字段 // role.setLeaveFactionTime(new Date()); // if(!isOnline){ // GameContext.getRoleDAO().updateRoleLeaveFactionTime(role); // } // }catch (Exception e) { // e.printStackTrace(); // } // return null; // } //}
true
0c21faaef8922512ddaf2fffe1a598380a033f89
Java
aline-brilhante/turma21
/Java/AULAS/src/lista6objetos/Preguica.java
ISO-8859-3
658
3.21875
3
[]
no_license
package lista6objetos; public class Preguica extends Animal { private String som; private String escalar; public Preguica(String nome, int idade, String som, String escalar) { super(nome, idade); this.som = som; this.escalar = escalar; } public String getSom() { return som; } public void setSom(String som) { this.som = som; } public String getEscalar() { return escalar; } public void setEscalar(String escalar) { this.escalar = escalar; } public String getNome() { return "Nome da preguia: "+super.getNome()+"\nIdade: "+super.getIdade()+"\nBarulho do animal: "+this.getSom()+"\nMovimento: "+this.getEscalar(); } }
true
bdd4762ce3b68a7e2d53cd160985ec8e3c17922b
Java
gsvishnugs/airplane-core
/src/main/java/com/airlines/core/util/SeatBookingUtil.java
UTF-8
5,403
3.09375
3
[]
no_license
package com.airlines.core.util; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import com.airlines.core.enums.SeatType; import com.airlines.core.model.Input; import com.airlines.core.model.Seat; import com.airlines.core.model.SeatManagementProperties; /** * Functions that helps prioritized seat booking * */ public class SeatBookingUtil { public static int SPACER_LENGTH = 5; /** * Extract properties that would enhance prioritization and iterating over seats * * @param seatMetadata * @return */ public static SeatManagementProperties buildSeatManagementProperties(List<List<Integer>> seatMetadata) { List<SeatType> breadthWiseSeatTypes = new ArrayList<SeatType>(); Map<Integer, Integer> seatBatchMaxRowMap = new HashMap<Integer, Integer>(); int breadth = 0; for (List<Integer> seatGroupMetadata : seatMetadata) { for (int rowIdx = 0; rowIdx < seatGroupMetadata.get(0); rowIdx++) { if (rowIdx == 0 || rowIdx == seatGroupMetadata.get(0) - 1) { breadthWiseSeatTypes.add(SeatType.aisle); } else { breadthWiseSeatTypes.add(SeatType.center); } seatBatchMaxRowMap.put(breadth++, seatGroupMetadata.get(1)); } } breadthWiseSeatTypes.set(0, SeatType.window); breadthWiseSeatTypes.set(breadthWiseSeatTypes.size() - 1, SeatType.window); int maxRowLength = 0; for (List<Integer> seatGroupMetadata : seatMetadata) { maxRowLength = maxRowLength < seatGroupMetadata.get(0) ? seatGroupMetadata.get(1) : maxRowLength; } SeatManagementProperties properties = new SeatManagementProperties(); properties.setBreadthWiseSeatTypes(breadthWiseSeatTypes); properties.setSeatBatchMaxRowMap(seatBatchMaxRowMap); properties.setMaxRowLength(maxRowLength); return properties; } /** * Prioritize seats by seat type. Aisle takes precedence over Window which in * turn takes precedence over Center seats. * * @param properties * @return */ public static PriorityQueue<Seat> pioritize(SeatManagementProperties properties) { PriorityQueue<Seat> seatingQueue = new PriorityQueue<Seat>(); int seatNumber = 1; for (int rowIdx = 0; rowIdx < properties.getMaxRowLength(); rowIdx++) { for (int colIdx = 0; colIdx < properties.getBreadthWiseSeatTypes().size(); colIdx++) { if (properties.getSeatBatchMaxRowMap().get(colIdx) > rowIdx) { Seat seat = new Seat(seatNumber++, properties.getBreadthWiseSeatTypes().get(colIdx)); seatingQueue.add(seat); } } } return seatingQueue; } /** * Mark seats that are allocated to passengers and add all seats to a map of * seatNumber -> Seat for ease of output beautification. * * @param input * @param seatingQueue * @return */ public static Map<Integer, Seat> allocate(Input input, PriorityQueue<Seat> seatingQueue) { Map<Integer, Seat> seatNumberSeatMap = new HashMap<Integer, Seat>(); int numPassengers = input.getNumberOfPassengers(); for (int i = 0; i < numPassengers; i++) { Seat allocatedSeat = seatingQueue.poll(); if (allocatedSeat != null) { // Allocate seat allocatedSeat.setPassengerId(i + 1); seatNumberSeatMap.put(Integer.valueOf(allocatedSeat.getNumber()), allocatedSeat); } } // Dump all unallocated seats while (seatingQueue.peek() != null) { Seat unallocatedSeat = seatingQueue.poll(); seatNumberSeatMap.put(Integer.valueOf(unallocatedSeat.getNumber()), unallocatedSeat); } return seatNumberSeatMap; } /** * Find the largest sized cell in the output * * @param seatNumberSeatMap * @return */ public static int getCellLengthForBeautification(Map<Integer, Seat> seatNumberSeatMap) { return seatNumberSeatMap.values().stream().map(value -> value.toString().length()).max(Integer::compare).get() + SPACER_LENGTH; } /** * Builds the output string * * @param properties * @param seatNumberSeatMap * @param maxCellLength * @return */ public static String beautifyOutput(SeatManagementProperties properties, Map<Integer, Seat> seatNumberSeatMap, int maxCellLength) { StringBuffer sb = new StringBuffer(); int seatNumber = 1; for (int rowIdx = 0; rowIdx < properties.getMaxRowLength(); rowIdx++) { for (int colIdx = 0; colIdx < properties.getBreadthWiseSeatTypes().size(); colIdx++) { if (properties.getSeatBatchMaxRowMap().get(colIdx) > rowIdx) { Seat printableSeat = seatNumberSeatMap.get(seatNumber++); sb.append(String.format("%1$" + maxCellLength + "s", printableSeat)); } else { sb.append(String.format("%1$" + maxCellLength + "s", "")); } } sb.append("\n"); } return sb.toString(); } }
true
4278aad1772ae5260296cc440f36f1cb76ce0509
Java
Retera/ReterasModelStudio
/craft3data/src/com/hiveworkshop/wc3/gui/modeledit/actions/SelectionActionType.java
UTF-8
480
2.171875
2
[ "MIT" ]
permissive
package com.hiveworkshop.wc3.gui.modeledit.actions; public enum SelectionActionType { SELECT, ADD, DESELECT, SELECT_ALL, INVERT_SELECTION, EXPAND_SELECTION; ; public static SelectionActionType fromLegacyId(final int selectionType) { switch (selectionType) { case 0: return SELECT; case 1: return ADD; case 2: return DESELECT; case 3: return SELECT_ALL; case 4: return INVERT_SELECTION; case 5: return EXPAND_SELECTION; } return null; } }
true
88afdf770c14b9e6b0cf18ba60287126281ba2eb
Java
h879426654/mnc
/gtl/src/main/java/com/basics/support/mybatis/SpringCacheAdapter.java
UTF-8
1,923
2.5
2
[]
no_license
package com.basics.support.mybatis; import java.util.concurrent.locks.ReadWriteLock; import org.apache.ibatis.cache.Cache; import org.springframework.cache.Cache.ValueWrapper; import org.springframework.cache.CacheManager; import com.basics.support.Application; import com.basics.support.LogUtils; public final class SpringCacheAdapter implements Cache { /** Cache id. */ private final String id; /** {@code ReadWriteLock}. */ private final ReadWriteLock readWriteLock = new DummyReadWriteLock(); CacheManager cacheManager; org.springframework.cache.Cache cache; public org.springframework.cache.Cache onBuildCache() { if (this.cacheManager == null) { this.cacheManager = (CacheManager) Application.getInstance().getBean("app.cacheManager"); } if (this.cacheManager == null) { throw new RuntimeException("CacheManager with name app.cacheManager not found."); } return this.cacheManager.getCache(this.id); } public org.springframework.cache.Cache getCache() { if (this.cache == null) { this.cache = this.onBuildCache(); } return cache; } /** * Constructor. * * @param id * Cache id. */ public SpringCacheAdapter(String id) { if (id == null) throw new IllegalArgumentException("Cache instances require an ID"); this.id = id; } public String getId() { return this.id; } public void putObject(Object key, Object value) { getCache().put(key, value); } public Object getObject(Object key) { return getCache().get(key); } public Object removeObject(Object key) { LogUtils.performance.debug("removeObject:{}", key); ValueWrapper wrap = this.getCache().get(key); Object obj = null; if (wrap != null) { obj = wrap.get(); } getCache().evict(key); return obj; } public void clear() { getCache().clear(); } public int getSize() { return 1024; } public ReadWriteLock getReadWriteLock() { return readWriteLock; } }
true
3766b35424106d1c3835c4bc35adc89eb6a7a704
Java
SarathBabu/easy-android
/library/src/main/java/com/sarath/easyandroid/network/NetworkInfoGroup.java
UTF-8
267
2.203125
2
[]
no_license
package com.sarath.easyandroid.network; /** * Created by sarath with 23/2/17. */ public interface NetworkInfoGroup { /** * Select the NetworkInfo from the group. * * @param type * @return */ NetworkInfo getNetworkInfo(int type); }
true
b17ebde0dfcf3c6341422fca5feaa9daf0bf1e28
Java
tkopton/sapl-demos
/sapl-demo-filterchain/src/main/java/io/sapl/demo/filterchain/AuthManager.java
UTF-8
2,212
2.421875
2
[ "Apache-2.0" ]
permissive
package io.sapl.demo.filterchain; import java.util.ArrayList; import java.util.List; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.DisabledException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import io.sapl.demo.domain.User; import io.sapl.demo.repository.UserRepo; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @Slf4j @RequiredArgsConstructor public class AuthManager implements AuthenticationManager { private final BCryptPasswordEncoder passwdEncoder = new BCryptPasswordEncoder(); private final UserRepo userRepo; @Override public Authentication authenticate(Authentication authentication) { LOGGER.trace("enter authentication manager"); String username = authentication.getPrincipal().toString(); User user = userRepo.findById(username) .orElseThrow(() -> new BadCredentialsException("no valid user name provided")); if (user == null) { LOGGER.debug("user not found in repo"); throw new BadCredentialsException("no user name provided"); } if (user.isDisabled()) { LOGGER.debug("user is disabled"); throw new DisabledException("user disabled"); } String rawPassword = authentication.getCredentials().toString(); if (!passwdEncoder.matches(rawPassword, user.getPassword())) { LOGGER.debug("password does not match"); throw new BadCredentialsException("user and/or password do not match"); } LOGGER.trace("user successfully authenticated, will create UsernamePasswordAuthenticationToken..."); List<GrantedAuthority> userAuthorities = new ArrayList<>(); user.getFunctions().forEach(function -> userAuthorities.add(new SimpleGrantedAuthority(function))); return new UsernamePasswordAuthenticationToken(username, user.getPassword(), userAuthorities); } }
true
9e3a00cbe7f9b2f800c959ba23b7f4c0e7f78e3d
Java
donhatch/donhatchsw
/com/donhatchsw/util/UndoTreeSquirrel.prejava
UTF-8
85,109
2.875
3
[]
no_license
/* vim: set filetype=java: */ package com.donhatchsw.util; import com.donhatchsw.compat.regex; #include "macros.h" /** * Experimenting with the idea of an undo/redo tree. * <a href="http://www.geocities.com/Hollywood/Set/4159/COULDWRK.WAV">It could work</a>! * <p> * An UndoTreeSquirrel represents the notion of a current position * in an undo tree. It can travel up and down the tree (undo and redo), * and it also has a memory of where it's been; * when given a choice of possible redo branches, it will choose * the branch it was most recently in. * <p> * Multiple squirrels can live in the same undo tree, * and one squirrel can be told to follow another, possibly * at a limited speed. * This can be useful in Model/View/Controller scenario * in which the Controller's notion of current state * is allowed to change very fast or instantaneously, * while the View's animation lags behind, progressing continuously * at a slower speed. * This scenario would be represented by two squirrels * living in the same tree: the Controller squirrel * moves around fast and can create new branches, * while the View squirrel follows the Controller squirrel around, * always moving towards it. * <p> * Currently there is no way for an application to have a direct * handle to an undo tree; undo trees are only accessed and manipulated * through squirrels. This includes growing the tree: the only way * to add nodes to a tree is by the actions of a squirrel * (the Do method). * XXX no longer true */ public class UndoTreeSquirrel { public interface ItemLengthizer { /** * The length the given edge should be; use 1 for an average edge. * For example, in a Rubik's-cube-like puzzle program, * where each graph edge represents a puzzle twist * through an angle of 90, 120, or 180 degrees, * and 90 is the most common, * you'd give the edges lengths 1, 4./3., 2 respectively. * When using the undo tree for animation, * the time it takes to traverse an edge in the tree * (i.e. to animate a Do, undo, or redo) * will be proportional to the square root of this edge length. * I.e. a 180 degree twist will take sqrt(2) times as long * as a 90 degree twist. */ double length(Object item); } /** A listening callback that you can create and install using addListener to listen for changes to the UndoTreeSquirrel. Hears changes to both the shared model (the actual tree, which other views (UndoTrees) might be listening to) and your individual view (i.e. current position and private node labels). */ public interface Listener { public void somethingChanged(); } // It's a model/view setup, where UndoTreeSquirrel itself is the view and UndoTreeSquirrel.UndoTree is the model (the tree itself). public static class UndoTree { // A node represents a state of the application; // the edges are editing operations that go from node to node. // Do, undo, and redo means traversing an edge // (although that is a Squirrel concept, since the model // has no concept of current position). public static class Node { public int parent; // index relative to mine public Object itemOnEdgeFromParentToMe; public long timeCreated; public Object sharedLabel = null; // views might want to share a label or have their own private one public int children[] = new int[0]; // indices relative to mine public Node(int parent, Object itemOnEdgeFromParentToMe, long timeCreated) { this.parent = parent; this.itemOnEdgeFromParentToMe = itemOnEdgeFromParentToMe; this.timeCreated = timeCreated; } } // Node public com.donhatchsw.compat.ArrayList/*<Node>*/ nodes = new com.donhatchsw.compat.ArrayList(); // The model has listeners (the views), // and each view has listeners. // Each view installs a listener on the model // that simply propagates model change notifications // into view change notifications (since every model change // is also a view change, for the purposes of someone // displaying the view in a viewer, for example). // XXX this should be PRIVATE to the view (UndoTreeSquirrel)! // XXX I don't have any way // XXX of enforcing that because java's privacy semantics are screwed, // XXX but there should be no cases where the UndoTreeSquirrel accesses // XXX this list directly. private com.donhatchsw.compat.ArrayList modelListeners = new com.donhatchsw.compat.ArrayList(); // XXX document this... who can call this? should they? this class used to be private public UndoTree() { this.nodes.add(new Node(-1,null,System.currentTimeMillis())); } public void addListener(Listener listener) { synchronized(this) { modelListeners.remove(listener); // XXX should throw IllegalStateException instead modelListeners.add(listener); } } public void removeListener(Listener notifier) { synchronized(this) { modelListeners.remove(notifier); } } // removeListener public void Clear() { synchronized(this) { nodes.clear(); nodes.add(new UndoTree.Node(-1,null,System.currentTimeMillis())); } // XXX hmm, idea... should we pass down a callback that lets them ask the old-to-new of any node index they are interested in? hmm notifyListenersSomethingChanged(modelListeners); } // Clear // caller must be synchronized on this model since it's // expecting parentNodeIndex to be valid. // returns the index of the newly created child, // and its index in the parent. public int[] Do(int parentNodeIndex, Object item, long timeStampMillis) { if (item == null) throw new IllegalArgumentException("UndoTreeSquirrel.Do called with null item"); int newChildIndex = nodes.size(); Node newChild = new Node(parentNodeIndex-newChildIndex, item, timeStampMillis); nodes.add(newChild); Node parentNode = (Node)nodes.get(parentNodeIndex); int newChildIndexInCurrent = parentNode.children.length; parentNode.children = Arrays.append(parentNode.children, newChildIndex-parentNodeIndex); notifyListenersSomethingChanged(modelListeners); return new int[]{newChildIndex, newChildIndexInCurrent}; } // UndoTree.Do // The fact that the caller has a node // means they are required to be inside a synchronized(model) // block, so we don't need to do additional synchronization here. public void setNodeLabel(Node node, Object sharedLabel) { node.sharedLabel = sharedLabel; notifyListenersSomethingChanged(modelListeners); } } // UndoTree private UndoTree model; // set in ctor private static PrivateNodeInfo getOrMakePrivateNodeInfo(java.util.HashMap<UndoTree.Node,PrivateNodeInfo> privateNodeInfosHashMap, UndoTree.Node node) { PrivateNodeInfo info = privateNodeInfosHashMap.get(node); if (info == null) { info = new PrivateNodeInfo(); privateNodeInfosHashMap.put(node, info); } return info; } // PrivateNodeInfo private com.donhatchsw.compat.ArrayList viewListeners = new com.donhatchsw.compat.ArrayList(); // // An UndoTreeSquirrel is actually a view into the nodes (the model). // So we don't store view-specific info on the nodes themselves; // that way multiple views can look at the same model. // private static class PrivateNodeInfo { public Object privateLabel = null; public int preferredChildIndex = -1; } private java.util.HashMap<UndoTree.Node,PrivateNodeInfo> privateNodeInfosHashMap = new java.util.HashMap<UndoTree.Node,PrivateNodeInfo>(); // XXX get rid of this, make it an array instead? not sure private int currentNodeIndex; // set in ctor private SmoothlyVaryingViewingParameter currentNodeFraction = new SmoothlyVaryingViewingParameter(1.); // current fraction of the way from parent to current node. Usually in (0,1] but can be outside that range in the case of a bouncy system. // XXX these haven't been thought out well... probably should not be here, are not safe... bleah bleah bleah public void setCurrentNodeIndex(int currentNodeIndex) { synchronized(privateNodeInfosHashMap) { this.currentNodeIndex = currentNodeIndex; // Correct the preferred child path from the root // XXX this is more costly than it should be! there should be an O(1) way to do this! maybe { int iChild = this.currentNodeIndex; UndoTree.Node child = (UndoTree.Node)model.nodes.get(iChild); while (iChild != 0) { int iParent = iChild + child.parent; UndoTree.Node parent = (UndoTree.Node)model.nodes.get(iParent); int childIndex = Arrays.indexOf(parent.children, -child.parent); PrivateNodeInfo parentInfo = getOrMakePrivateNodeInfo(privateNodeInfosHashMap, parent); parentInfo.preferredChildIndex = childIndex; iChild = iParent; child = parent; } } } this.currentNodeFraction.snap(1.); notifyListenersSomethingChanged(viewListeners); } public int getCurrentNodeIndex() { return currentNodeIndex; } public double getCurrentNodeFraction() { return currentNodeFraction.get(); } public Object getItemOnEdgeFromParentToCurrentNode() // XXX definitely shouldn't have to be public... root out the usages of it and see if we can handle it a different way { synchronized(model.nodes) // XXX should model handle this instead? { return ((UndoTree.Node)model.nodes.get(currentNodeIndex)).itemOnEdgeFromParentToMe; } } public void setCurrentNodeFraction(double currentNodeFraction) { this.currentNodeFraction.snap(currentNodeFraction); notifyListenersSomethingChanged(viewListeners); } /** * Creates a new view onto an existing undo tree, or a new undo tree (if other is null). * XXX fix this, wrong now */ // CTOR (for quick find in editor) public UndoTreeSquirrel(UndoTreeSquirrel other) { this(other==null ? null : other.model); // XXX probably don't need this any more if (other != null) { this.model = other.model; this.currentNodeIndex = other.currentNodeIndex; this.currentNodeFraction.setTargetPosition(other.currentNodeFraction.getTargetPosition()); this.currentNodeFraction.snap(other.currentNodeFraction.get()); // XXX should copy preferred child indices from the other too! and maybe private labels, but not sure about that. maybe that should be an argument to the constructor? } } public UndoTreeSquirrel(UndoTree tree) { if (tree == null) { this.model = new UndoTree(); } else { this.model = tree; } this.currentNodeIndex = 0; // XXX might an existing tree have this pruned away? this.currentNodeFraction.setTargetPosition(1.); this.currentNodeFraction.snap(1.); // Propagate model change notifications // to this view's view change listeners. // Note, this could also be accomplished by simply // making our addListener(newListener) // call model.addListener(newListener) // in addition to adding the new listener to our own listeners list, // so that the listener would get notified directly... // however that would be a mess if the model was ever changed, so // I think it's cleaner this way. this.model.addListener(new Listener() { // XXX this never gets removed! should it be a weak reference or something? OVERRIDE public void somethingChanged() { if (UndoTreeSquirrel.this.model.nodes.size() == 1) // it's always at least 1 { // XXX lock something down? // XXX might deadlock, should we just set a flag // XXX and do this lazily when someone wants something? currentNodeIndex = 0; // XXX hmm, this is destructive, puzzle state needs to be reset if this happens currentNodeFraction.snap(1.); privateNodeInfosHashMap.clear(); } CHECK(currentNodeIndex < UndoTreeSquirrel.this.model.nodes.size()); // XXX will need to do something more sophisticated if pruning is implemented; for now, the only destructive operation is Clear which we just handled // Regardless of whether we changed our private stuff, // every model change is regarded as noteworthy // for view listeners, so notify them. notifyListenersSomethingChanged(viewListeners); } }); } // UndoTreeSquirrel (view) ctor /** Creates a new undo tree (view) with a brand new empty tree; equivalent to UndoTreeSquirrel(null). */ public UndoTreeSquirrel() { this((UndoTree)null); } /** Equivalent to Do(item, System.currentTimeMillis()). */ public void Do(Object item) { Do(item, System.currentTimeMillis()); } /** Changes the current position to be a newly created child * of the current current position, * associating the given Object with the newly created transition to the new child. * The new child is made to be the preferred child * of the former current position. * This method actually affects the model, i.e. it modifies the tree * (whereas other methods such as undo, and redo * only affects the individual view of the model). * <p> * The time stamp is stored as the creation time of the new child. * NOTE this is currently not saved or restored via fromString and toString! * (but it should be!) */ public void Do(Object item, long timeStampMillis) { if (item == null) throw new IllegalArgumentException("UndoTreeSquirrel.Do called with null item"); synchronized(this) // note currentNodeIndex can change while waiting for this lock! that will make us hang it off the new currentNodeIndex instead. that's the way the ball bounces. { currentNodeFraction.snap(1.); // XXX seems safe, didn't think about this much synchronized(model) // currentNodeIndex can also change while waiting for *this* lock, since if someone is clearing the model, that will notify us and *we* will set it to zero. that's the way the ball bounces. { int newChildIndex_and_newChildIndexInCurrent[] = model.Do(currentNodeIndex, item, timeStampMillis); int newChildIndex = newChildIndex_and_newChildIndexInCurrent[0]; int newChildIndexInCurrent = newChildIndex_and_newChildIndexInCurrent[1]; PrivateNodeInfo currentNodeInfo = getOrMakePrivateNodeInfo(privateNodeInfosHashMap, (UndoTree.Node)model.nodes.get(currentNodeIndex)); currentNodeInfo.preferredChildIndex = newChildIndexInCurrent; currentNodeIndex = newChildIndex; // XXX could just do a redo? } notifyListenersSomethingChanged(viewListeners); // XXX hmm... we already notified them inside the model changed callback which got called from inside model.Do, so this is notifying them twice... bleah. wonder if there is a clean way to prevent that. Ultimately it should just amount to a repaint(), I hope... not sure about that though. } } // Do /** Destroys the entire underlying tree. */ public void Clear() { model.Clear(); // That will notify us that the model changed, // which will cause us to update // our currentNodeIndex and hash table // (and it will make all other views do that too) // so we don't need to do that here. } /** Performs an undo; that is, changes the current position to be one step closer to the root of the tree, returning the Object that was originally passed to Do() when the tree edge was created. */ public Object undo() { if (currentNodeIndex != 0) { UndoTree.Node currentNode = (UndoTree.Node)model.nodes.get(currentNodeIndex); Object item = currentNode.itemOnEdgeFromParentToMe; currentNodeIndex += currentNode.parent; // relative currentNodeFraction.snap(1.); notifyListenersSomethingChanged(viewListeners); return item; } else { return null; } } /** Performs a redo; that is, changes the current position to be the preferred child of the current current position, returning the Object that was originally passed to Do() when that tree edge was created. If you want to go to a different child, you need to explicitly make that the preferred child first. */ public Object redo() { UndoTree.Node currentNode = (UndoTree.Node)model.nodes.get(currentNodeIndex); if (currentNode.children.length == 0) return null; PrivateNodeInfo currentNodeInfo = getOrMakePrivateNodeInfo(privateNodeInfosHashMap, currentNode); if (currentNodeInfo.preferredChildIndex == -1) currentNodeInfo.preferredChildIndex = currentNode.children.length-1; // we didn't create any of currentNode's children nor have we traversed any of them, so we don't have a preference... just take the last one XXX maybe should prefer the preferred one of whoever made it? or of the latest child that *anyone* traversed or has been hanging out in? hmm... currentNodeIndex += currentNode.children[currentNodeInfo.preferredChildIndex]; // relative currentNode = (UndoTree.Node)model.nodes.get(currentNodeIndex); currentNodeFraction.snap(1.); notifyListenersSomethingChanged(viewListeners); return currentNode.itemOnEdgeFromParentToMe; } /** * Changes the preferred child of the current position (i.e. the path that will be taken by a redo) to the next older child than the current favorite, if there is one. */ public boolean preferOlderChild() { UndoTree.Node currentNode = (UndoTree.Node)model.nodes.get(currentNodeIndex); PrivateNodeInfo currentNodeInfo = getOrMakePrivateNodeInfo(privateNodeInfosHashMap, currentNode); synchronized(currentNode) { if (currentNodeInfo.preferredChildIndex == -1) currentNodeInfo.preferredChildIndex = currentNode.children.length-1; // we didn't create any of currentNode's children nor have we traversed any of them, so we don't have a preference... just take the last one XXX maybe should prefer the preferred one of whoever made it? or of the latest child that *anyone* traversed or has been hanging out in? hmm... if (currentNodeInfo.preferredChildIndex-1 < 0) return false; currentNodeInfo.preferredChildIndex--; } notifyListenersSomethingChanged(viewListeners); return true; } // preferOlderChild /** * Changes the preferred child of the current position (i.e. the path that will be taken by a redo) to the next younger child than the current favorite, if there is one. */ public boolean preferYoungerChild() { UndoTree.Node currentNode = (UndoTree.Node)model.nodes.get(currentNodeIndex); PrivateNodeInfo currentNodeInfo = getOrMakePrivateNodeInfo(privateNodeInfosHashMap, currentNode); synchronized(currentNode) { if (currentNodeInfo.preferredChildIndex == -1) currentNodeInfo.preferredChildIndex = currentNode.children.length-1; // we didn't create any of currentNode's children nor have we traversed any of them, so we don't have a preference... just take the last one XXX maybe should prefer the preferred one of whoever made it? or of the latest child that *anyone* traversed or has been hanging out in? hmm... if (currentNodeInfo.preferredChildIndex+1 >= currentNode.children.length) return false; currentNodeInfo.preferredChildIndex++; } notifyListenersSomethingChanged(viewListeners); return true; } // preferYoungerChild /** Oh, and this one updates the model too. Sets a label at the current position that will be seen by other views of this undo tree. */ public void setSharedLabel(Object sharedLabel) { synchronized(model) // required whenever getting a node { // XXX what if some other view has done a clear? UndoTree.Node currentNode = (UndoTree.Node)model.nodes.get(currentNodeIndex); model.setNodeLabel(currentNode, sharedLabel); } } /** Sets a label at the current position that will not be seen by other views of this undo tree. */ public void setPrivateLabel(Object privateLabel) { synchronized(this) { UndoTree.Node currentNode = (UndoTree.Node)model.nodes.get(currentNodeIndex); PrivateNodeInfo privateNodeInfo = getOrMakePrivateNodeInfo(privateNodeInfosHashMap, currentNode); privateNodeInfo.privateLabel = privateLabel; } notifyListenersSomethingChanged(viewListeners); } /** awkward as hell, but incrementViewTowardsOtherView needs to return an int and an Object, so here it is. */ public class ReturnValueOfIncrementViewTowardsOtherView { public int dir; /** -1 for undo, 1 for redo */ public Object item; /** the item to undo (if dir==-1) or redo (if dir==1) */ private ReturnValueOfIncrementViewTowardsOtherView(int dir, Object item) { this.dir = dir; this.item = item; } } // ReturnValueOfIncrementViewTowardsOtherView /** * Returns true if a call to incrementViewTowardsOtherView(target) would actually change anything. */ public boolean isMoving(UndoTreeSquirrel target) { return currentNodeIndex != target.currentNodeIndex || currentNodeFraction.get() != target.currentNodeFraction.get(); } /** * Moves my current position one step towards the current position of the other view. Returns a structure describing the discrete state change involved (if any) and the fractional offset from the new integer state that should be used to display the new fractional state. * XXX that doesn't seem to be true any more... doesn't return the fractional offset, just stores it */ // XXX restructure this function to make it clearer public ReturnValueOfIncrementViewTowardsOtherView incrementViewTowardsOtherView(UndoTreeSquirrel otherView, double referenceTripDistance, double referenceTripTime, double dt, double bounce, UndoTreeSquirrel.ItemLengthizer lengthizer) { boolean debug = false; // manually set to true to debug this function if (debug) System.out.println("in incrementViewTowardsOtherView"); if (otherView.model.nodes != model.nodes) throw new IllegalStateException("UndoTreeSquirrel.incrementViewTowardsOtherView called with a different underlying tree!"); // XXX need to lock something down while we do this... if someone else changes currentNodeIndex out from under us we are super screwed!!! int targetNodeIndex = otherView.currentNodeIndex; double targetNodeFraction = otherView.currentNodeFraction.get(); UndoTree.Node currentNode = (UndoTree.Node)model.nodes.get(currentNodeIndex); if (currentNodeIndex == targetNodeIndex) { if (debug) System.out.println(" home stretch"); currentNodeFraction.setTargetPosition(targetNodeFraction); // if it wasn't already if (!currentNodeFraction.isMoving()) { if (debug) System.out.println(" already there"); if (debug) System.out.println("out incrementViewTowardsOtherView (no change)"); return null; } // // We're on the home stretch, // between the target's parent and the target... // Just need to redo a little more (or undo if we overshot). // if (debug) System.out.println(" evolving "+currentNodeFraction.get()+" -> "+currentNodeFraction.getTargetPosition()+""); double referenceTripFraction = referenceTripDistance/lengthizer.length(currentNode.itemOnEdgeFromParentToMe); currentNodeFraction.evolve(referenceTripFraction, referenceTripTime, dt, bounce); notifyListenersSomethingChanged(viewListeners); if (debug) System.out.println("out incrementViewTowardsOtherView (no discrete change)"); return null; // no discrete state change } int ancestorIndex = findLowestCommonAncestorIndex(currentNodeIndex, targetNodeIndex, model.nodes); ReturnValueOfIncrementViewTowardsOtherView returnVal = null; if (ancestorIndex == currentNodeIndex) { // Go down in the redo direction if (debug) System.out.println(" going in redo direction"); currentNodeFraction.setTargetPosition(1.); // if it wasn't already if (!currentNodeFraction.isMoving()) { if (debug) System.out.println(" already there, transitioning"); // currentNode = the child on the way towards target node. // Note, the following is kind of bogus, // since we didn't lock anything down // so the other view might have changed its // preferred children. But, we'll assume // that there is a clear redo path to the target // via other view's preferred children... // if we get it wrong, // the worst that can happen is we will have to backtrack // a little next time, // and it will never be noticed by the user. // XXX unless someone calls Clear.... then we might be screwed PrivateNodeInfo currentNodeInfo = getOrMakePrivateNodeInfo(privateNodeInfosHashMap, currentNode); synchronized(otherView.privateNodeInfosHashMap) // XXX I'm positive this is the wrong thing { PrivateNodeInfo currentNodeInfoInOtherView = otherView.privateNodeInfosHashMap.get(currentNode); if (currentNodeInfoInOtherView == null || currentNodeInfoInOtherView.preferredChildIndex == -1) currentNodeInfo.preferredChildIndex = currentNode.children.length-1; else currentNodeInfo.preferredChildIndex = currentNodeInfoInOtherView.preferredChildIndex; } currentNodeIndex += currentNode.children[currentNodeInfo.preferredChildIndex]; currentNodeFraction.snap(0.); CHECK_EQ(currentNodeFraction.get(), 0.); currentNode = (UndoTree.Node)model.nodes.get(currentNodeIndex); returnVal = new ReturnValueOfIncrementViewTowardsOtherView(1, currentNode.itemOnEdgeFromParentToMe/*AFTER we change current node*/); // In this case don't evolve... wait for next time around, // which will do something or other depending // on whether the new one is the target or not. } else // currentNodeFraction.isMoving() { if (debug) System.out.println(" evolving "+currentNodeFraction.get()+" -> "+currentNodeFraction.getTargetPosition()+""); // // Okay, this will be the coolest thing ever // if we can pull this off... // look ahead to see if there are one or more // other redos ahead of us that are identical to this one. // If so, set our target to be the end of the stretch // of identical redos, so that we don't slow down // at the transition. // (XXX need a smarter transition mechanism... !isMoving won't cut it any more) (XXX what did I mean by this??) // if (true) { double currentItemLength = lengthizer.length(currentNode.itemOnEdgeFromParentToMe); int nodeIndex = currentNodeIndex; UndoTree.Node node = currentNode; Object item = currentNode.itemOnEdgeFromParentToMe; //System.out.println(" Should I add power?"); while (true) { if (node.children.length == 0) { //System.out.println(" no, because no children"); break; } int preferredChildIndex; if (node.children.length == 1) preferredChildIndex = 0; else { // XXX for now, only do it if there's only one child. that will cover the Do-Do-Do case which is the most important one. I'll implement the more general thing later. //System.out.println(" no, because more than one child although this will work some day)"); break; } int childIndex = nodeIndex + node.children[preferredChildIndex]; UndoTree.Node childNode = (UndoTree.Node)model.nodes.get(childIndex); // XXX synch!? Object childItem = childNode.itemOnEdgeFromParentToMe; if (!childItem.equals(item)) { //System.out.println(" no, child item is different from this item"); break; } // // Advance the target farther. // currentNodeFraction.setTargetPosition(currentNodeFraction.getTargetPosition() + (lengthizer.length(childItem) / currentItemLength)); //System.out.println(" power -> "+currentNodeFraction.getTargetPosition()+" baby!"); //System.out.println(" should I add more?"); nodeIndex = childIndex; node = childNode; } if (!currentNodeFraction.isMoving()) { // this should NOT happen, // since we WERE moving originally before we started // glomming on additional segments. // but this will happen // if we get all the way to the target // without doing the switcheroo for some reason. System.out.println("SOMEONE STOP THIS THING, I WANT TO GET OFF!"); } } double referenceTripFraction = referenceTripDistance/lengthizer.length(currentNode.itemOnEdgeFromParentToMe); currentNodeFraction.evolve(referenceTripFraction, referenceTripTime, dt, bounce); // // Switch rails here! // if (currentNodeFraction.getTargetPosition() > 1. && currentNodeFraction.get() > 1.) { // Just do one switch even though potentially get() // might be > 2, since we are only capable of returning // one discrete state change to the caller. // We'll get the next one next time around (hopefully). //System.out.println("SWITCHING HORSES, BABY!"); currentNodeFraction.setPosition(currentNodeFraction.get()-1.); // i.e. change position without changing velocity XXX in more general circumstances, we may have to rescale the velocity, although this is fine for now since we only merge when consecutive edges are identical CHECK_EQ(currentNode.children.length, 1); // XXX for now currentNodeIndex += currentNode.children[0]; // XXX should be preferred child index currentNode = (UndoTree.Node)model.nodes.get(currentNodeIndex); CHECK_EQ(returnVal, null); // there shouldn't be any other discrete change we're trying to return returnVal = new ReturnValueOfIncrementViewTowardsOtherView(1, currentNode.itemOnEdgeFromParentToMe/*AFTER we change current node*/); } } } else // ancestorIndex != currentNodeIndex { // Go up in the undo direction if (debug) System.out.println(" going in undo direction"); currentNodeFraction.setTargetPosition(0.); // if it wasn't already if (!currentNodeFraction.isMoving()) { if (debug) System.out.println(" already there, transitioning"); returnVal = new ReturnValueOfIncrementViewTowardsOtherView(-1, currentNode.itemOnEdgeFromParentToMe/*BEFORE we change current node*/); // tell caller there was a discrete undo currentNodeIndex += currentNode.parent; currentNodeFraction.snap(1.); CHECK_EQ(currentNodeFraction.get(), 1.); currentNode = (UndoTree.Node)model.nodes.get(currentNodeIndex); // In this case don't evolve... wait for next time around, // which will do something or other depending // on whether the new one is the target or not. } else // currentNodeFraction.isMoving() { // // Do the combining-consecutive-identical-targets- // into-one-long-target thing. // Doing this here in the undo case is easier // than in the redo case since there is only one choice // of parent. if (true) { Object currentItem = currentNode.itemOnEdgeFromParentToMe; double currentItemLength = lengthizer.length(currentItem); // redundant calculation, maybe move this to a more outer scope // Immediate target starts as the parent, // but we might make it the grandparent, etc. int immediateTargetNodeIndex = currentNodeIndex+currentNode.parent; UndoTree.Node immediateTargetNode = (UndoTree.Node)model.nodes.get(immediateTargetNodeIndex); //System.out.println(" Should I add power?"); while (true) { if (immediateTargetNodeIndex == ancestorIndex) { // too hairy to try to do this over the ancestor transition, so don't bother for now //System.out.println(" no, at ancestor hump"); break; } if (!immediateTargetNode.itemOnEdgeFromParentToMe.equals(currentItem)) { //System.out.println(" no, child item is different from this item"); break; } // // Advance the immediate target farther. // currentNodeFraction.setTargetPosition(currentNodeFraction.getTargetPosition() - (lengthizer.length(immediateTargetNode.itemOnEdgeFromParentToMe) / currentItemLength)); immediateTargetNodeIndex += immediateTargetNode.parent; immediateTargetNode = (UndoTree.Node)model.nodes.get(immediateTargetNodeIndex); //System.out.println(" power -> "+currentNodeFraction.getTargetPosition()+" baby!"); //System.out.println(" should I add more?"); } if (!currentNodeFraction.isMoving()) { // this should NOT happen, // since we WERE moving originally before we started // glomming on additional segments. // but this will happen // if we get all the way to the target // without doing the switcheroo for some reason. //System.out.println("SOMEONE STOP THIS THING, I WANT TO GET OFF!"); } } if (debug) System.out.println(" evolving "+currentNodeFraction.get()+" -> "+currentNodeFraction.getTargetPosition()+""); double referenceTripFraction = referenceTripDistance/lengthizer.length(currentNode.itemOnEdgeFromParentToMe); currentNodeFraction.evolve(referenceTripFraction, referenceTripTime, dt, bounce); // // Switch rails here! // if (currentNodeFraction.getTargetPosition() < 0. && currentNodeFraction.get() < 0.) { // Just do one switch even though potentially get() // might be < -1, since we are only capable of returning // one discrete state change to the caller. // We'll get the next one next time around (hopefully). //System.out.println("SWITCHING HORSES, BABY!"); currentNodeFraction.setPosition(currentNodeFraction.get()+1.); // i.e. change position without changing velocity XXX in more general circumstances, we may have to rescale the velocity, although this is fine for now since we only merge when consecutive edges are identical CHECK_EQ(returnVal, null); // there shouldn't be any other discrete change we're trying to return returnVal = new ReturnValueOfIncrementViewTowardsOtherView(-1, currentNode.itemOnEdgeFromParentToMe/*BEFORE we change current node*/); // tell caller there was a discrete undo currentNodeIndex += currentNode.parent; currentNode = (UndoTree.Node)model.nodes.get(currentNodeIndex); } } // // Hack for beautiful smooth transition in the undo tree viewer // as we turn around. // If we are about to switch to redos when we hit the parent, // then set its preferred child *now* instead of when // we get to the parent. // (Usually the preferred child is always the branch we are in, // so this is nonstandard but I don't think anything depends // on that assumption.) // Then when the drawing code (actually the chooseNodePositions // utility function, down below in this file) // sees that the preferred child // isn't the one the current node is under, // it knows that this is happening and can reposition // the parent horizonally in proportion to how far // the child has gone so far. // if (currentNodeIndex != 0) { UndoTree.Node parentNode = (UndoTree.Node)model.nodes.get(currentNodeIndex+currentNode.parent); PrivateNodeInfo parentNodeInfo = getOrMakePrivateNodeInfo(privateNodeInfosHashMap, parentNode); synchronized(otherView.privateNodeInfosHashMap) // XXX I'm positive this is the wrong thing { PrivateNodeInfo parentNodeInfoInOtherView = otherView.privateNodeInfosHashMap.get(parentNode); if (parentNodeInfoInOtherView == null || parentNodeInfoInOtherView.preferredChildIndex == -1) parentNodeInfo.preferredChildIndex = parentNode.children.length-1; else parentNodeInfo.preferredChildIndex = parentNodeInfoInOtherView.preferredChildIndex; } } } notifyListenersSomethingChanged(viewListeners); if (debug) System.out.println("out incrementViewTowardsOtherView"); return returnVal; } // incrementViewTowardsOtherView // XXX this will be made easier and faster in the future, // XXX when I'll make each view mark its path // XXX from its current node to the root; // XXX then we won't have to walk up and down to the root // XXX each time. (actually just marking each node with its depth // XXX would suffice-- that would be easy... // XXX although it might prevent some local pruning operations // XXX from being fast... hmm) private static int findLowestCommonAncestorIndex(int i0, int i1, com.donhatchsw.compat.ArrayList nodes) { // Do the common cases fast... if (i0 == i1) return i0; if (i0 != 0 && i0+((UndoTree.Node)nodes.get(i0)).parent == i1) return i1; if (i1 != 0 && i1+((UndoTree.Node)nodes.get(i1)).parent == i0) return i0; // No clue where they are with respect to each other. // Figure out the depths... int depth0 = 0; for (int i = i0; i > 0; i += ((UndoTree.Node)nodes.get(i)).parent) depth0++; int depth1 = 0; for (int i = i1; i > 0; i += ((UndoTree.Node)nodes.get(i)).parent) depth1++; // Walk up the deeper side til they are at common depth... while (depth0 > depth1) { i0 += ((UndoTree.Node)nodes.get(i0)).parent; depth0--; } while (depth1 > depth0) { i1 += ((UndoTree.Node)nodes.get(i1)).parent; depth1--; } // Then keep walking up til they are equal. while (i0 != i1) { i0 += ((UndoTree.Node)nodes.get(i0)).parent; i1 += ((UndoTree.Node)nodes.get(i1)).parent; } return i0; } // findLowestCommonAncestorIndex // This would get moved into UndoTree if UndoTree was to be made autonomous private static void notifyListenersSomethingChanged(com.donhatchsw.compat.ArrayList listeners) { synchronized(listeners) { for (int i = 0; i < listeners.size(); ++i) ((Listener)listeners.get(i)).somethingChanged(); } } /** * Installs a callback that will get called after * any change is made, * that is, when Do or setSharedLabel is called (by any view of the tree) * or when one of undo, redo, preferOlderChild, preferYoungerChild, setPrivateLabel * is called by this view of the tree. */ public void addListener(Listener notifier) { synchronized(viewListeners) { viewListeners.remove(notifier); // should throw IllegalStateException viewListeners.add(notifier); } } // addListener /** Removes a callback that was previously installed with addListener(). */ public void removeListener(Listener notifier) { synchronized(viewListeners) { viewListeners.remove(notifier); } } // removeListener public static class Snapshot { public int nNodes = -1; public int currentNode; public double currentNodeFraction; public int parents[] = null; public Object edgeItems[] = null; public Object sharedLabels[] = null; public Object privateLabels[] = null; public int preferredChild[] = null; public int nOtherSquirrels = -1; public int otherSquirrelsCurrentNodes[] = null; public double otherSquirrelsCurrentNodeFractions[] = null; } // Snapshot /** Take a snapshot of the undo tree, locking down the shared data structures for as short a time as possible. */ public void takeSnapshot(Snapshot snapshot, UndoTreeSquirrel otherSquirrels[]) { for (int i = 0; i < otherSquirrels.length; ++i) if (otherSquirrels[i].model != model) throw new IllegalArgumentException("UndoTreeSquirrel.takeSnapshot called with other squirrel that's not in the same tree!"); // Don't lock down while allocating, // just re-do the allocations if something changed, // which will almost never happen. // Note also, we do need to lock down even the private stuff // since other threads might be accessing it // (private here doesn't mean thread-local, it means // "view-local"-- it's all relative) while (true) { int nNodes = model.nodes.size(); int nOtherSquirrels = otherSquirrels.length; snapshot.nNodes = nNodes; snapshot.nOtherSquirrels = nOtherSquirrels; if (snapshot.parents == null || snapshot.parents.length < nNodes) snapshot.parents = new int[nNodes]; if (snapshot.edgeItems == null || snapshot.edgeItems.length < nNodes) snapshot.edgeItems = new Object[nNodes]; if (snapshot.sharedLabels == null || snapshot.sharedLabels.length < nNodes) snapshot.sharedLabels = new String[nNodes]; if (snapshot.privateLabels == null || snapshot.privateLabels.length < nNodes) snapshot.privateLabels = new String[nNodes]; if (snapshot.preferredChild == null || snapshot.preferredChild.length < nNodes) snapshot.preferredChild = new int[nNodes]; if (snapshot.otherSquirrelsCurrentNodes == null || snapshot.otherSquirrelsCurrentNodes.length < nOtherSquirrels) snapshot.otherSquirrelsCurrentNodes = new int[nOtherSquirrels]; if (snapshot.otherSquirrelsCurrentNodeFractions == null || snapshot.otherSquirrelsCurrentNodeFractions.length < nOtherSquirrels) snapshot.otherSquirrelsCurrentNodeFractions = new double[nOtherSquirrels]; synchronized(model.nodes) // model.nodes.size can change while waiting for this lock... and our currentNodeIndex might change with it due to our listener being called { if (model.nodes.size() != nNodes) { continue; // someone changed something! try allocations again } for (int iNode = 0; iNode < nNodes; ++iNode) { UndoTree.Node node = (UndoTree.Node)model.nodes.get(iNode); PrivateNodeInfo privateNodeInfo = privateNodeInfosHashMap.get(node); snapshot.parents[iNode] = iNode + node.parent; // change relative to absolute snapshot.edgeItems[iNode] = node.itemOnEdgeFromParentToMe; snapshot.sharedLabels[iNode] = node.sharedLabel; int preferredChildLocalIndex; if (privateNodeInfo != null) { //System.out.println("CARED, "+iNode+" prefers "+(iNode + privateNodeInfo.preferredChildIndex)); snapshot.privateLabels[iNode] = privateNodeInfo.privateLabel; preferredChildLocalIndex = privateNodeInfo.preferredChildIndex; snapshot.preferredChild[iNode] = privateNodeInfo.preferredChildIndex==-1 ? -1 : iNode + privateNodeInfo.preferredChildIndex; // change relative to absolute } else { //System.out.println("DIDN'T CARE, "+iNode+" doesn't really prefer "+(iNode-1)); snapshot.privateLabels[iNode] = null; preferredChildLocalIndex = -1; } if (preferredChildLocalIndex == -1) preferredChildLocalIndex = node.children.length-1; snapshot.preferredChild[iNode] = node.children.length == 0 ? -1 : iNode+node.children[preferredChildLocalIndex]; // change relative to absolute } snapshot.currentNode = currentNodeIndex; snapshot.currentNodeFraction = currentNodeFraction.get(); for (int i = 0; i < nOtherSquirrels; ++i) { snapshot.otherSquirrelsCurrentNodes[i] = otherSquirrels[i].currentNodeIndex; snapshot.otherSquirrelsCurrentNodeFractions[i] = otherSquirrels[i].currentNodeFraction.get(); } break; } // synchronized(model.nodes) } // we could nicify it here if we want... perhaps putting in the children pointers as well, we're in no hurry any more CHECK(snapshot.currentNode >= 0); CHECK(snapshot.currentNode < snapshot.nNodes); } // takeSnapshot /** * Returns a string something like this if stretchOutAlongTimeLine is true: * <pre> * +---------+ * | 0 | * | +-+ | A * | 1 | | * | +-+ | | B * | 2 | | | * | | | | C * | | 3 | * | | | D * | 4 | * | | | E * | (5) | * +---------+ * </pre> * and something like this if stretchOutAlongTimeLine is false: * <pre> * +---------+ * | 0 | * | +-+ | A C * | 1 3 | * | +-+ | B D * | 2 4 | * | | | E * | (5) | * +---------+ * </pre> * These were created by executing the following commands: * <pre> * UndoTreeSquirrel squirrel = new UndoTreeSquirrel(); * squirrel.Do("A"); * squirrel.Do("B"); * squirrel.undo(); * squirrel.undo(); * squirrel.Do("C"); * squirrel.undo(); * squirrel.preferYoungerChild(); * squirrel.redo(); * squirrel.Do("D"); * squirrel.Do("E"); * System.out.println(squirrel.toStringVisualCool(true)); * System.out.println(squirrel.toStringVisualCool(false)); * </pre> */ // TODO: compactify even more if it gets bushy then stringy then bushy, the lower bush can go under the upper bush public String toStringVisualCool(boolean stretchOutAlongTimeLine) { // XXX should use chooseNodePositions instead of this code // FROM ABOUT HERE ============================================== int nNodes = model.nodes.size(); // // Bottom up, figure out the number of leaves // under the node. That will be the logical width // allotted to this node. // int widths[] = new int[nNodes]; // zeros for (int iNode = nNodes-1; iNode >= 0; iNode--) { UndoTree.Node node = (UndoTree.Node)model.nodes.get(iNode); for (int iChild = 0; iChild < node.children.length; ++iChild) { int childIndex = iNode + node.children[iChild]; widths[iNode] += widths[childIndex]; } if (widths[iNode] == 0) widths[iNode] = 1; // leaf } // // Top down, figure out the left and right logical bounds allotted to // each node. Parent decides for each child. // int xstarts[] = new int[nNodes]; xstarts[0] = 0; for (int iNode = 0; iNode < nNodes; iNode++) { UndoTree.Node node = (UndoTree.Node)model.nodes.get(iNode); int childStart = xstarts[iNode]; for (int iChild = 0; iChild < node.children.length; ++iChild) { int childIndex = iNode + node.children[iChild]; xstarts[childIndex] = childStart; childStart += widths[childIndex]; } } // // Bottom up, decide the x position within the node's bounds // that we will display the node. We want to display it // directly over its preferred child. // These are physical, not logical any more. // int x[] = new int[nNodes]; for (int iNode = nNodes-1; iNode >= 0; iNode--) { UndoTree.Node node = (UndoTree.Node)model.nodes.get(iNode); PrivateNodeInfo privateNodeInfo = getOrMakePrivateNodeInfo(privateNodeInfosHashMap, node); // XXX shouldn't make it if it doesn't exist, that's lame if (node.children.length == 0) { x[iNode] = 2*xstarts[iNode]+1; } else { int preferredChildIndex = privateNodeInfo.preferredChildIndex; if (preferredChildIndex == -1) preferredChildIndex = node.children.length-1; x[iNode] = x[iNode + node.children[preferredChildIndex]]; } } // TO ABOUT HERE ============================================== int possibleEdgeLengths[] = {3,4,6}; int edgeLengths[] = new int[nNodes]; for (int iNode = 0; iNode < nNodes; ++iNode) edgeLengths[iNode] = possibleEdgeLengths[(int)(Math.random()*possibleEdgeLengths.length)]; int y[] = new int[nNodes]; // // Decide the y position // where we will display the node. // if (stretchOutAlongTimeLine) { // Easy! for (int iNode = 0; iNode < nNodes; ++iNode) y[iNode] = 2*iNode; } else { // // Top down, put each child at a level // just below its parent. // (Well leave one line between them for the edge.) // y[0] = 0; for (int iNode = 0; iNode < nNodes; iNode++) { UndoTree.Node node = (UndoTree.Node)model.nodes.get(iNode); int childStart = xstarts[iNode]; for (int iChild = 0; iChild < node.children.length; ++iChild) { int childIndex = iNode + node.children[iChild]; y[childIndex] = y[iNode] + 2; } } } int maxy = 0; for (int iNode = 0; iNode < nNodes; iNode++) maxy = Math.max(maxy, y[iNode]); char buf[][] = new char[maxy+1][1 + 2*widths[0]]; for (int i = 0; i < buf.length; ++i) for (int j = 0; j < buf[i].length; ++j) buf[i][j] = ' '; // // Top down or bottom up, it doesn't matter, // draw the stuff into the rectangular buffer. // for (int iNode = 0; iNode < nNodes; ++iNode) { UndoTree.Node node = (UndoTree.Node)model.nodes.get(iNode); buf[y[iNode]][x[iNode]] = (char)('0'+(iNode%10)); // XXX just last digit for now if (iNode == currentNodeIndex) { buf[y[iNode]][x[iNode]-1] = '('; // XXX argh, index out of bounds buf[y[iNode]][x[iNode]+1] = ')'; } if (node.children.length > 0) { if (node.children.length >= 1) { int firstChildX = x[iNode+node.children[0]]; int lastChildX = x[iNode+node.children[node.children.length-1]]; for (int i = firstChildX; i <= lastChildX; ++i) buf[y[iNode]+1][i] = '-'; } for (int iChild = 0; iChild < node.children.length; ++iChild) { int childIndex = iNode + node.children[iChild]; buf[y[iNode]+1][x[childIndex]] = node.children.length==1 ? '|' : '+'; for (int j = y[iNode]+2; j < y[childIndex]; ++j) buf[j][x[childIndex]] = '|'; } } } // // Put annotations into the annotation buffer. // StringBuilder annotations[] = new StringBuilder[buf.length]; for (int i = 0; i < annotations.length; ++i) annotations[i] = new StringBuilder(); for (int iNode = 0; iNode < nNodes; ++iNode) { UndoTree.Node node = (UndoTree.Node)model.nodes.get(iNode); if (iNode != 0) { annotations[y[iNode]-1].append(" "+node.itemOnEdgeFromParentToMe); } if (node.sharedLabel != null) annotations[y[iNode]].append(" sharedLabel="+Arrays.toStringCompact(node.sharedLabel)); PrivateNodeInfo privateNodeInfo = getOrMakePrivateNodeInfo(privateNodeInfosHashMap, node); // XXX shouldn't make it if it doesn't exist, that's lame if (privateNodeInfo.privateLabel != null) annotations[y[iNode]].append(" privateLabel="+Arrays.toStringCompact(privateNodeInfo.privateLabel)); } // // Put the rectangular buffer on the left, // with annotations on the right, into a StringBuilder // in preparation for final output. // String nl = System.getProperty("line.separator"); StringBuilder sb = new StringBuilder(); sb.append("+"+repeat("-", buf[0].length+2)+"+"+nl); for (int i = 0; i < buf.length; ++i) { sb.append("| "); sb.append(buf[i]); sb.append(" |" ); sb.append(annotations[i]); sb.append(nl); } sb.append("+"+repeat("-", buf[0].length+2)+"+"); // no nl return sb.toString(); } // toStringVisualCool /** Static utility function for choosing a nice graphical layout, given the tree relation and edge lengths. The root node will be at y=0, with other y positions depending on the given edge lengths (if stretchOutAlongTimeLine is true, the y position will be the sum of the edge lengths that preceded this node in time; otherwise it will be the sum of the edge lengths from the root to this node). The x positions will be integers from 0 to number of leaf nodes minus 1: each node will have the same x position as the leaf that would be reached by following its preferred children. */ // XXX see if I can leverage this in toStringVisualCool? currently it duplicates this code I think public static void chooseNodePositions(int nNodes, int parents[], int preferredChild[], double edgeLengths[], int currentNodeIndex, double currentNodeFrac, double stretchOutAlongTimeLine, double x[], // output double y[]) // output { // // Fill in firstChild,nextSibling array so we // Fill in a nextSibling array so we can easily traverse top-down // as well as bottom-up. // int firstChild[] = new int[nNodes]; int nextSibling[] = new int[nNodes]; for (int iNode = 0; iNode < nNodes; ++iNode) firstChild[iNode] = -1; for (int iChild = nNodes-1; iChild >= 0; iChild--) { int iParent = parents[iChild]; if (iParent != -1) { nextSibling[iChild] = firstChild[iParent]; firstChild[iParent] = iChild; } else nextSibling[iChild] = -1; } // // Bottom up, figure out the number of leaves // under the node. That will be the logical width // allotted to this node. // int widths[] = new int[nNodes]; // zeros for (int iChild = nNodes-1; iChild >= 0; iChild--) { if (firstChild[iChild] == -1) widths[iChild] = 1; if (parents[iChild] != -1) widths[parents[iChild]] += widths[iChild]; } // // Top down, figure out the left and right logical bounds allotted to // each node. Parent decides for each child. // int xstarts[] = new int[nNodes]; xstarts[0] = 0; for (int iParent = 0; iParent < nNodes; iParent++) { int childStart = xstarts[iParent]; for (int iChild = firstChild[iParent]; iChild != -1; iChild = nextSibling[iChild]) { xstarts[iChild] = childStart; childStart += widths[iChild]; } } // // Bottom up, decide the x position within the node's bounds // that we will display the node. We want to display it // directly over its preferred child. // // SPECIAL CASE: // If we get to the parent of currentNode // and its preferred child is *not* currentNode, // we know currentNode is moving towards // the new preferred child, in which case linearly // interpolate the parent's horizontal position // between the old and new preferred child. // for (int iChild = nNodes-1; iChild >= 0; iChild--) { if (firstChild[iChild] == -1) x[iChild] = (double)xstarts[iChild]; if (iChild == parents[currentNodeIndex] && preferredChild[iChild] != currentNodeIndex) { // the SPECIAL CASE described above if (false) { OUT("SPECIAL CASE"); PRINT(x.length); PRINT(iChild); PRINT(currentNodeIndex); } x[iChild] = LERP(x[currentNodeIndex], x[iChild], 1.-currentNodeFrac); } int iParent = parents[iChild]; if (iParent != -1) { if (preferredChild[iParent] == iChild) x[iParent] = x[iChild]; } } // // Decide the y position // where we will display the node. // for (int iNode = 0; iNode < nNodes; ++iNode) { if (parents[iNode] == -1) y[iNode] = 0; else y[iNode] = LERP(y[parents[iNode]], y[iNode-1], stretchOutAlongTimeLine) + edgeLengths[iNode]; } } // chooseNodePositions /* XXX no this isn't right, we use relative offsets now Example: {"oh boy a puzzle!" 0 A 1 B "just did B" 2 C 1 D 4 E 5 F 2 G 4 H "oh boy I solved it"} Compact would be: {"oh boy a puzzle!" A B "just did B" C u D E F u2 G u3 H I "oh boy I solved it"} */ public interface ItemToString { public String regex(); public String itemToString(Object item); } public interface ItemFromString { public String regex(); public Object itemFromString(String s); } /** * Returns a string something like this: * <pre> * { A B (0) u2 C (you are here) u2 D E } * </pre> * You tell it how to stringify the individual items * by passing in an itemToString functor, and a regex that describes * what an item string can look like. * The result can be turned back into another UndoTreeSquirrel * by calling fromString(), so this is suitable for a save/load * mechanism. * <p> * Note that the tokens "u", "u2", "u3" etc. are used * to signify branching. Your individual item regex is not allowed * to accept any of these strings (since if it did, it would be * impossible to tell whether "u" denoted an item or a branch indicator). * <p> * Similarly, the tokens "(0)", "(1)", etc. are used to signify * the preferred child of a given position (i.e. which edge * will be followed by a redo from that position). * Your individual item regex is not allowed to accept these either. * <p> * XXX More salient example coming soon. */ public String toString(ItemToString itemToString, String indentSpaces, String separatorSpaces) // hmm, I guess itemToString isn't needed, it could just use the item's toString... but then where do we get the regex from? { System.out.println("in UndoTreeSquirrel.toString"); if (!regex.matches(indentSpaces, "\\s*")) throw new IllegalArgumentException("UndoTreeSquirrel.toString given indent string "+Arrays.toStringCompact(indentSpaces)+", should be zero or more spaces"); if (!regex.matches(separatorSpaces, "\\s+")) throw new IllegalArgumentException("UndoTreeSquirrel.toString given separator string "+Arrays.toStringCompact(separatorSpaces)+", should be one or more spaces"); String itemRegex = itemToString.regex(); regex.Matcher itemMatcher = regex.Pattern.compile(itemRegex).matcher("dummy"); // XXX dup code in the other place, should combine if (itemMatcher.reset("").matches()) throw new IllegalArgumentException("UndoTreeSquirrel.toString given item regex "+Arrays.toStringCompact(itemRegex)+" which matches the empty string, that's messed up!"); if (itemMatcher.reset("u").matches() || itemMatcher.reset("u1").matches() || itemMatcher.reset("u10").matches()) throw new IllegalArgumentException("UndoTreeSquirrel.toString given item regex "+Arrays.toStringCompact(itemRegex)+" which matches something starting with \"u\", can't do that because it's special!"); if (itemMatcher.reset("(0)").matches() || itemMatcher.reset("(1)").matches() || itemMatcher.reset("(10)").matches()) throw new IllegalArgumentException("UndoTreeSquirrel.toString given item regex "+Arrays.toStringCompact(itemRegex)+" which matches a parenthesized number something like (2), can't do that because it's special!"); StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append(separatorSpaces); int nNodes = model.nodes.size(); for (int iNode = 0; iNode < nNodes; ++iNode) { sb.append(indentSpaces); UndoTree.Node node = (UndoTree.Node)model.nodes.get(iNode); if (iNode != 0) { String itemString = itemToString.itemToString(node.itemOnEdgeFromParentToMe); if (!itemMatcher.reset(itemString).matches()) { throw new IllegalArgumentException("UndoTreeSquirrel.toString given itemToString functor that produced string "+Arrays.toStringCompact(itemString)+" which does not match its regex pattern "+itemRegex+"!"); } if (node.parent == -1) ; // nothing, this is the default else if (node.parent == -2) sb.append("u "); else // -3 -> 2, -4 -> 3, etc. sb.append("u").append(-node.parent-1).append(" "); sb.append(itemString).append(" "); } PrivateNodeInfo privateNodeInfo = getOrMakePrivateNodeInfo(privateNodeInfosHashMap, node); // If printing private label and there's no shared label, // print "null" for the shared label if (node.sharedLabel != null || privateNodeInfo.privateLabel != null) sb.append(Arrays.toStringCompact(node.sharedLabel!=null ? node.sharedLabel.toString() : "null")+" "); if (privateNodeInfo.privateLabel != null) sb.append(Arrays.toStringCompact(privateNodeInfo.privateLabel).toString()+" "); if (iNode == currentNodeIndex) sb.append("(you are here) "); if (privateNodeInfo.preferredChildIndex != -1 && node.children.length > 1) // XXX a little odd... can go from having a preference of the single child, to having no preference which means can be overridden by someone else making a child... think about this. it's only an issue if collabarative editing sb.append("("+privateNodeInfo.preferredChildIndex+") "); while (" \r\n".indexOf(sb.charAt(sb.length()-1)) != -1) // XXX lame test! sb.deleteCharAt(sb.length()-1); sb.append(separatorSpaces); } sb.append("}"); String s = sb.toString(); System.out.println("out UndoTreeSquirrel.toString"); return s; } // toString /** Parses a string that was created by toString(). */ public static UndoTreeSquirrel fromString(String s, ItemFromString itemFromString) { String itemRegex = itemFromString.regex(); regex.Matcher itemMatcher = regex.Pattern.compile(itemRegex).matcher("dummy"); // XXX dup code in the other place, should combine if (itemMatcher.reset("").matches()) throw new IllegalArgumentException("UndoTreeSquirrel.fromString given item regex "+Arrays.toStringCompact(itemRegex)+" which matches the empty string, that's messed up!"); if (itemMatcher.reset("u").matches() || itemMatcher.reset("u1").matches() || itemMatcher.reset("u10").matches()) throw new IllegalArgumentException("UndoTreeSquirrel.fromString given item regex "+Arrays.toStringCompact(itemRegex)+" which matches something starting with \"u\", can't do that because it's special!"); if (itemMatcher.reset("(0)").matches() || itemMatcher.reset("(1)").matches() || itemMatcher.reset("(10)").matches()) throw new IllegalArgumentException("UndoTreeSquirrel.toString given item regex "+Arrays.toStringCompact(itemRegex)+" which matches a parenthesized number something like (2), can't do that because it's special!"); regex.Matcher doubleQuotedStringMatcher = regex.Pattern.compile( "\"((\\\\|.)*)\"" ).matcher("dummy"); // XXX maybe should retain original s for error messages s = s.trim(); if (s.length() < 2 || s.charAt(0) != '{' || s.charAt(s.length()-1) != '}') throw new IllegalArgumentException("UndoTreeSquirrel.fromStringCompact called on string not surrounded by '{'"); s = s.substring(1, s.length()-1).trim(); String words[]; { if (true) { // Brain dead way... works if there are no spaces at all // in the items or labels words = regex.split(s, "\\s+"); } else { com.donhatchsw.compat.ArrayList/*<String>*/ wordsVector = new com.donhatchsw.compat.ArrayList(); unimplemented(); // XXX implement me! words = new String[wordsVector.size()]; wordsVector.toArray(words); } } // XXX ARGH! should save and restore Do times! for now, when reading back in, just label everything with the read-back-in time long currentTimeMillis = System.currentTimeMillis(); // We'll stick these in the created undoTree when we // create it at the end int currentNodeIndex = -1; java.util.HashMap<UndoTree.Node,PrivateNodeInfo> privateNodeInfosHashMap = new java.util.HashMap<UndoTree.Node,PrivateNodeInfo>(); UndoTree.Node nodes[] = new UndoTree.Node[Math.max(words.length,1)]; // at most this many com.donhatchsw.compat.ArrayList/*UndoTree.Node*/ childrens[] = new com.donhatchsw.compat.ArrayList[nodes.length]; int nNodes = 0; nodes[nNodes++] = new UndoTree.Node(-1, null, currentTimeMillis); childrens[nNodes-1] = new com.donhatchsw.compat.ArrayList(); int iWord = 0; while (iWord < words.length) { // // optional quoted shared label for this node... or "null" // (without the quotes) // if (words[iWord].equals("null")) { // just leave it null... this is a placeholder // because there's a private label coming iWord++; } else if (doubleQuotedStringMatcher.reset(words[iWord]).matches()) { nodes[nNodes-1].sharedLabel = words[iWord].substring(1,words[iWord].length()-1); // XXX need to unescapify! iWord++; } if (iWord == words.length) break; // // optional quoted private label for this node // if (doubleQuotedStringMatcher.reset(words[iWord]).matches()) { PrivateNodeInfo privateNodeInfo = getOrMakePrivateNodeInfo(privateNodeInfosHashMap, nodes[nNodes-1]); privateNodeInfo.privateLabel = words[iWord].substring(1,words[iWord].length()-1); // XXX need to unescapify! iWord++; } if (iWord == words.length) break; // // optional (you are here) for this node // if (words[iWord].equals("(you are here)") || (iWord+2 < words.length // XXX this is only needed if doing the brain dead word tokenizing && words[iWord].equals("(you") && words[iWord+1].equals("are") && words[iWord+2].equals("here)"))) { if (currentNodeIndex != -1) throw new IllegalArgumentException("UndoTreeSquirrel.fromString given an undo tree with more than one current node!"); currentNodeIndex = nNodes-1; if (words[iWord].equals("(you")) iWord += 2; iWord++; } if (iWord == words.length) break; // // optional parenthesized (<preferredChild>) for this node // if (regex.matches(words[iWord], "\\(-?\\d+\\)")) { PrivateNodeInfo privateNodeInfo = getOrMakePrivateNodeInfo(privateNodeInfosHashMap, nodes[nNodes-1]); privateNodeInfo.preferredChildIndex = Integer.parseInt(words[iWord].substring(1,words[iWord].length()-1)); // XXX should bounds check, but have to do that at the end! iWord++; } if (iWord == words.length) break; // // Not at the end of the input, so there's another node // nodes[nNodes++] = new UndoTree.Node(-1, null, currentTimeMillis); childrens[nNodes-1] = new com.donhatchsw.compat.ArrayList(); // // optional parent offset... // nothing means -1 // "u" means -2 // "u2" means -3 // etc. // if (regex.matches(words[iWord], "u\\d*")) // XXX precompile! { int parentOffset = -1 - (words[iWord].equals("u") ? 1 : Integer.parseInt(words[iWord].substring(1))); if (nNodes-1+parentOffset < 0) // e.g. node 3 can have offset at most 2, which makes its parent node 0 throw new IllegalArgumentException("UndoTreeSquirrel.fromString node "+(nNodes-1)+"'s parent offset is "+parentOffset+", which would put the parent at "+(nNodes-1+parentOffset)+""); nodes[nNodes-1].parent = parentOffset; int parentIndex = nNodes-1+parentOffset; iWord++; } childrens[nNodes-1 + nodes[nNodes-1].parent].add(Integer.valueOf(-nodes[nNodes-1].parent)); if (iWord == words.length) throw new IllegalArgumentException("UndoTreeSquirrel.fromString premature end of input trying to read item at word "+iWord+""); // // required item from regex // if (itemMatcher.reset(words[iWord]).matches()) { Object item = itemFromString.itemFromString(words[iWord]); nodes[nNodes-1].itemOnEdgeFromParentToMe = item; iWord++; } else { PRINT(words[iWord]); throw new IllegalArgumentException("UndoTreeSquirrel.fromString expected item at word "+iWord+" but got "+Arrays.toStringCompact(words[iWord])+" which does not match regex "+Arrays.toStringCompact(itemRegex)+""); } } // while (iWord < words.length) if (currentNodeIndex == -1) throw new IllegalArgumentException("UndoTreeSquirrel.fromString given an undo tree with no current node!"); // // Now go through and hang each child on each parent, // and verify that its preferred child index is in bounds // for (int iNode = 0; iNode < nNodes; ++iNode) { nodes[iNode].children = new int[childrens[iNode].size()]; for (int iChild = 0; iChild < nodes[iNode].children.length; ++iChild) { nodes[iNode].children[iChild] = ((Integer)childrens[iNode].get(iChild)).intValue(); } PrivateNodeInfo privateNodeInfo = privateNodeInfosHashMap.get(nodes[iNode]); if (privateNodeInfo != null && (privateNodeInfo.preferredChildIndex < -1 // -1 is always okay || privateNodeInfo.preferredChildIndex >= nodes[iNode].children.length)) { throw new IllegalArgumentException("UndoTreeSquirrel.fromString node "+iNode+"'s preferred child is "+privateNodeInfo.preferredChildIndex+" but only has "+nodes[iNode].children.length+" children!"); } } UndoTreeSquirrel squirrel = new UndoTreeSquirrel(); squirrel.currentNodeIndex = currentNodeIndex; squirrel.privateNodeInfosHashMap = privateNodeInfosHashMap; squirrel.model.nodes = new com.donhatchsw.compat.ArrayList(nNodes); for (int iNode = 0; iNode < nNodes; ++iNode) squirrel.model.nodes.add(nodes[iNode]); squirrel.checkSane(); return squirrel; } // fromString private void checkSane() { for (int iNode = 0; iNode < model.nodes.size(); ++iNode) { UndoTree.Node node = (UndoTree.Node)model.nodes.get(iNode); for (int iChild = 0; iChild < node.children.length; ++iChild) { int childIndex = iNode + node.children[iChild]; UndoTree.Node child = (UndoTree.Node)model.nodes.get(childIndex); //System.out.println(""+iNode+"->"+childIndex); CHECK_EQ(childIndex+child.parent, iNode); } } } private static String repeat(String s, int n) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; ++i) sb.append(s); return sb.toString(); } /** Test/example program. */ public static void main(String args[]) { System.out.println("in main"); UndoTreeSquirrel squirrel = new UndoTreeSquirrel(); squirrel.Do("A"); squirrel.Do("B"); squirrel.setPrivateLabel("private_before_fork"); squirrel.undo(); squirrel.undo(); squirrel.Do("C"); squirrel.setPrivateLabel("shared_before_fork"); squirrel.undo(); squirrel.preferYoungerChild(); squirrel.redo(); squirrel.Do("D"); squirrel.Do("E"); UndoTreeSquirrel squirrel0 = squirrel; UndoTreeSquirrel squirrel1 = new UndoTreeSquirrel(squirrel); squirrel0.Do("F0"); squirrel1.Do("G1"); squirrel0.Do("H0"); squirrel0.setPrivateLabel("0_private_after_fork"); squirrel1.setPrivateLabel("1_private_after_fork"); squirrel0.setSharedLabel("0_shared_after_fork"); squirrel1.setSharedLabel("1_shared_after_fork"); System.out.println("Tree 0:"); System.out.println(squirrel0.toStringVisualCool(true)); System.out.println(squirrel0.toStringVisualCool(false)); System.out.println("Tree 1:"); System.out.println(squirrel1.toStringVisualCool(true)); System.out.println(squirrel1.toStringVisualCool(false)); UndoTreeSquirrel.ItemToString itemToString = new UndoTreeSquirrel.ItemToString(){ public String regex() { //return "-?\\d+"; // ints if (false) return "[.0-9_a-zA-Z]+"; // make sure this gets rejected because it accepts 'u' else return "[.0-9_a-tv-zA-Z]+"; // identifiers and numbers and stuff... but can't start with a 'u'! } public String itemToString(Object obj) { // is this method necessary? could just take the regex //return obj.toString(); // ints return obj.toString(); // identifiers too } }; UndoTreeSquirrel.ItemFromString itemFromString = new UndoTreeSquirrel.ItemFromString(){ public String regex() { // return "-?\\d+"; // ints if (false) return "[.0-9_a-zA-Z]+"; // make sure this gets rejected because it accepts 'u' else return "[.0-9_a-tv-zA-Z]+"; // identifiers and numbers and stuff... but can't start with a 'u'! } public Object itemFromString(String s) { //return Integer.valueOf(s); // ints return s; // identifiers } }; //String indentSpaces = " "; //String separatorSpaces = System.getProperty("line.separator"); String indentSpaces = ""; String separatorSpaces = " "; String s0 = squirrel0.toString(itemToString, indentSpaces, separatorSpaces); String s1 = squirrel1.toString(itemToString, indentSpaces, separatorSpaces); UndoTreeSquirrel t0 = UndoTreeSquirrel.fromString(s0, itemFromString); UndoTreeSquirrel t1 = UndoTreeSquirrel.fromString(s1, itemFromString); String u0 = t0.toString(itemToString, indentSpaces, separatorSpaces); String u1 = t1.toString(itemToString, indentSpaces, separatorSpaces); PRINT(s0); PRINT(u0); CHECK(u0.equals(s0)); CHECK(u1.equals(s1)); // XXX maybe should compare the visualcools too? } // main } // class UndoTreeSquirrel
true
833715b12d26f1d1dcde87f3bddfdb425d6e7482
Java
phwd/quest-tracker
/hollywood/com.oculus.browser-base/sources/defpackage/C4351q70.java
UTF-8
415
1.632813
2
[]
no_license
package defpackage; /* renamed from: q70 reason: default package and case insensitive filesystem */ /* compiled from: chromium-OculusBrowser.apk-stable-281887347 */ public final /* synthetic */ class C4351q70 implements Q31 { public final C4521r70 F; public C4351q70(C4521r70 r70) { this.F = r70; } @Override // defpackage.Q31 public Object get() { return this.F.v0; } }
true
6834e8b5c2f6436daf51186daa8fd5a36a4fb7b7
Java
Candie-H/LeetCode-Solutions-in-Good-Style
/lcof/0062-yuan-quan-zhong-zui-hou-sheng-xia-de-shu-zi-lcof/src/Solution.java
UTF-8
1,330
3.765625
4
[ "Apache-2.0" ]
permissive
import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class Solution { // 约瑟夫环问题 // 其实并不一定要构造出一个真的循环链表 public int lastRemaining(int n, int m) { // 先处理极端输入 if (n <= 1) { return -1; } // 这里用链表是为了提升性能,如果用 ArrayList 在删除操作中,就会有大量的性能消耗 List<Integer> list = new ArrayList<>(n); for (int i = 0; i < n; i++) { list.add(i); } // System.out.println(list); int bt = 0; while (list.size() > 1) { // 表示的是索引的值 bt = (bt + m - 1) % list.size(); // 下面这一行代码可以帮助调试 // System.out.println(bt + " " + list); // bt 是链表的索引 list.remove(bt); } // 思考为什么会有最后这个判断 return list.get(0); } // 测试用例: n = 6,[0,1,2,3,4,5],m=3 public static void main(String[] args) { Solution solution = new Solution(); int n = 70866; int m = 116922; int lastRemainingSolution = solution.lastRemaining(n, m); System.out.println(lastRemainingSolution); } }
true
d3fb7522c8551678cd5e949835a52367bca208a7
Java
Uhbyxer/security
/spring-security/src/main/java/com/acme/springsecurity/config/SecurityConfig.java
UTF-8
2,881
2.15625
2
[]
no_license
package com.acme.springsecurity.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.password.PasswordEncoder; import static org.springframework.http.HttpMethod.GET; @Configuration @EnableWebSecurity //switch-off out of the box security @EnableGlobalMethodSecurity(securedEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter { private UserDetailsService userDetailsService; private TokenConfig tokenConfig; private PasswordEncoder passwordEncoder; @Autowired public void setUserDetailsService(UserDetailsService userDetailsService) { this.userDetailsService = userDetailsService; } @Autowired public void setTokenConfig(TokenConfig tokenConfig) { this.tokenConfig = tokenConfig; } @Autowired public void setPasswordEncoder(PasswordEncoder passwordEncoder) { this.passwordEncoder = passwordEncoder; } @Override protected void configure(HttpSecurity http) throws Exception { // http.authorizeRequests() // .antMatchers(GET, "/hello").permitAll() // .antMatchers(GET, "/admin/users").permitAll() //temporary // .anyRequest().authenticated().and().httpBasic(); http .httpBasic().disable() .csrf().disable() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeRequests() .antMatchers(GET, "/hello").permitAll() .antMatchers("/auth/login").permitAll() .antMatchers("/admin/**").hasRole("ADMIN") // .antMatchers("/admin/**").authenticated() .anyRequest().authenticated() .and() .apply(tokenConfig); } @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } //@Autowired //public void configureGrobal(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception { // authenticationManagerBuilder // .inMemoryAuthentication() // .withUser("user") // .password("{noop}password") //withDefaultPasswordEncoder // .roles("ROLE_USER"); // authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder); //} }
true
23f22a09c7b1acd0713e7828ad5a23f0a5d34b3f
Java
slepoj/myTask
/src/task1/myTask2/LessonsTime.java
UTF-8
687
3.328125
3
[]
no_license
package task1.myTask2; public class LessonsTime { private int numLessons; private int hours; private int mins; public LessonsTime(int numLessons) { this.numLessons = numLessons; } public void whatTime() { int k = numLessons / 2; mins = (60 + 45 - 2 * k * 5) % 60; hours = 8 + numLessons - numLessons / 10; } public void viewResult() { System.out.print("time is "); System.out.printf("%2d %02d%n", hours, mins); } public static void start(int a) { System.out.println("task 2:"); LessonsTime time = new LessonsTime(a); time.whatTime(); time.viewResult(); } }
true
c297c19bd8d749563220179c78c6ec610c397fdf
Java
dbarreto22/Paaps
/TecnopotifyWeb/src/java/Serlvets/ServletCliente.java
UTF-8
3,973
2.171875
2
[]
no_license
/* * 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 Serlvets; import edu.tecnopotify.datatypes.dataArtista; import edu.tecnopotify.datatypes.dataCliente; import edu.tecnopotify.datatypes.dataFecha; import edu.tecnopotify.datatypes.dataUsuario; import edu.tecnopotify.fabrica.Fabrica; import edu.tecnopotify.interfaces.IControlador; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Iterator; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.tomcat.util.http.fileupload.FileItem; import org.apache.tomcat.util.http.fileupload.RequestContext; import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload; /** * * @author Carlox */ public class ServletCliente extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs * * */ private IControlador crl; // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); String comando = request.getParameter("comando"); Fabrica fabrica = Fabrica.getInstance(); crl = fabrica.getInstancia(); if (comando != null && comando.equals("altaCliente")) { //Procesar el formulario String nickName = request.getParameter("nickname"); String nombre = request.getParameter("nombre"); String apellido = request.getParameter("apellido"); String mail = request.getParameter("mail"); int dia = request.getIntHeader("dia"); int mes = request.getIntHeader("mes"); int anio = request.getIntHeader("anio"); dataFecha fecha = new dataFecha(dia, mes, anio); String contrasenia = request.getParameter("contrasenia"); // String img = request.getParameter("fimg"); dataUsuario cli = new dataCliente(nickName, nombre, apellido, mail, fecha, contrasenia, ""); crl.crearCliente(cli); request.setAttribute("nickName",nickName); } RequestDispatcher despachador = request.getRequestDispatcher("/subirImg.jsp"); despachador.forward(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
true
037f1799e0e3ee0d4ec3568fef05564166db958c
Java
kinnara-digital-studio/shark
/src/org/enhydra/shark/corba/poa/ProcessIteratorExpressionBuilderCORBA.java
UTF-8
8,976
1.890625
2
[]
no_license
package org.enhydra.shark.corba.poa; import org.enhydra.shark.corba.ExpressionBuilders.ProcessIteratorExpressionBuilder; import org.enhydra.shark.corba.ExpressionBuilders.ProcessIteratorExpressionBuilderPOA; import org.omg.CORBA.Any; import org.omg.CORBA.ORB; import org.omg.WfBase.BaseException; /** * ProcessIteratorExpressionBuilderCORBA * * @author David Forslund */ public class ProcessIteratorExpressionBuilderCORBA extends ProcessIteratorExpressionBuilderPOA { org.enhydra.shark.api.common.ProcessIteratorExpressionBuilder myEB; public ProcessIteratorExpressionBuilderCORBA(org.enhydra.shark.api.common.ProcessIteratorExpressionBuilder eb) { this.myEB = eb; // _this(orb); } public boolean isComplete() { return myEB.isComplete(); } public String toSQL() { return myEB.toSQL(); } public String toScript() { return myEB.toScript(); } public String toExpression() { return myEB.toExpression(); } public ProcessIteratorExpressionBuilder and() { myEB.and(); return _this(); } public ProcessIteratorExpressionBuilder or() { myEB.or(); return _this(); } public ProcessIteratorExpressionBuilder not() { myEB.not(); return _this(); } public ProcessIteratorExpressionBuilder addPackageIdEquals(String exp) { myEB.addPackageIdEquals(exp); return _this(); } public ProcessIteratorExpressionBuilder addProcessDefIdEquals(String exp) { myEB.addProcessDefIdEquals(exp); return _this(); } public ProcessIteratorExpressionBuilder addMgrNameEquals(String exp) { myEB.addMgrNameEquals(exp); return _this(); } public ProcessIteratorExpressionBuilder addVersionEquals(String exp) { myEB.addVersionEquals(exp); return _this(); } public ProcessIteratorExpressionBuilder addIsMgrEnabled() { myEB.addIsMgrEnabled(); return _this(); } public ProcessIteratorExpressionBuilder addStateEquals(String arg) { myEB.addStateEquals(arg); return _this(); } public ProcessIteratorExpressionBuilder addStateStartsWith(String arg) { myEB.addStateStartsWith(arg); return _this(); } public ProcessIteratorExpressionBuilder addIdEquals(String arg) { myEB.addIdEquals(arg); return _this(); } public ProcessIteratorExpressionBuilder addNameEquals(String arg) { myEB.addNameEquals(arg); return _this(); } public ProcessIteratorExpressionBuilder addPriorityEquals(int arg) { myEB.addPriorityEquals(arg); return _this(); } public ProcessIteratorExpressionBuilder addDescriptionEquals(String arg) { myEB.addDescriptionEquals(arg); return _this(); } public ProcessIteratorExpressionBuilder addDescriptionContains(String arg) { myEB.addDescriptionContains(arg); return _this(); } public ProcessIteratorExpressionBuilder addRequesterIdEquals(String arg) { myEB.addRequesterIdEquals(arg); return _this(); } public ProcessIteratorExpressionBuilder addRequesterUsernameEquals(String arg) { myEB.addRequesterUsernameEquals(arg); return _this(); } public ProcessIteratorExpressionBuilder addCreatedTimeEquals(long arg) { myEB.addCreatedTimeEquals(arg); return _this(); } public ProcessIteratorExpressionBuilder addCreatedTimeBefore(long arg) { myEB.addCreatedTimeBefore(arg); return _this(); } public ProcessIteratorExpressionBuilder addCreatedTimeAfter(long arg) { myEB.addCreatedTimeAfter(arg); return _this(); } public ProcessIteratorExpressionBuilder addStartTimeEquals(long arg) { myEB.addStartTimeEquals(arg); return _this(); } public ProcessIteratorExpressionBuilder addStartTimeBefore(long arg) { myEB.addStartTimeBefore(arg); return _this(); } public ProcessIteratorExpressionBuilder addStartTimeAfter(long arg) { myEB.addStartTimeAfter(arg); return _this(); } public ProcessIteratorExpressionBuilder addLastStateTimeEquals(long arg) { myEB.addLastStateTimeEquals(arg); return _this(); } public ProcessIteratorExpressionBuilder addLastStateTimeBefore(long arg) { myEB.addLastStateTimeBefore(arg); return _this(); } public ProcessIteratorExpressionBuilder addLastStateTimeAfter(long arg) { myEB.addLastStateTimeAfter(arg); return _this(); } public ProcessIteratorExpressionBuilder addActiveActivitiesCountEquals(long arg) { // FIXME: not implemented yet return _this(); } public ProcessIteratorExpressionBuilder addActiveActivitiesCountGreaterThan(long arg) { // FIXME: not implemented yet return _this(); } public ProcessIteratorExpressionBuilder addActiveActivitiesCountLessThan(long arg) { // FIXME: not implemented yet return _this(); } public ProcessIteratorExpressionBuilder addVariableAnyEquals(String vName, Any vValue) throws BaseException { try { myEB.addVariableEquals(vName, SharkCORBAUtilities.extractValueFromAny(vValue)); } catch (Exception ex) { throw new BaseException(); } return _this(); } public ProcessIteratorExpressionBuilder addVariableStrEquals(String vName, String vValue) { myEB.addVariableEquals(vName, vValue); return _this(); } public ProcessIteratorExpressionBuilder addVariableLngEquals(String vName, long vValue) { myEB.addVariableEquals(vName, vValue); return _this(); } public ProcessIteratorExpressionBuilder addVariableLngGreaterThan(String vName, long vValue) { myEB.addVariableGreaterThan(vName, vValue); return _this(); } public ProcessIteratorExpressionBuilder addVariableLngLessThan(String vName, long vValue) { myEB.addVariableLessThan(vName, vValue); return _this(); } public ProcessIteratorExpressionBuilder addVariableDblEquals(String vName, double vValue) { myEB.addVariableEquals(vName, vValue); return _this(); } public ProcessIteratorExpressionBuilder addVariableDblGreaterThan(String vName, double vValue) { myEB.addVariableGreaterThan(vName, vValue); return _this(); } public ProcessIteratorExpressionBuilder addVariableDblLessThan(String vName, double vValue) { myEB.addVariableLessThan(vName, vValue); return _this(); } public ProcessIteratorExpressionBuilder addExpressionStr(String exp) { myEB.addExpression(exp); return _this(); } public void disconnect() { // TODO Auto-generated method stub } public ProcessIteratorExpressionBuilder addExpression(ProcessIteratorExpressionBuilder eb) { myEB.addExpression((org.enhydra.shark.api.common.ProcessIteratorExpressionBuilder)eb.getTheImpl().extract_Value()); return _this(); } public Any getTheImpl() { Any ret = this._orb().create_any(); ret.insert_Value(myEB); return ret; } public ProcessIteratorExpressionBuilder setOrderByMgrName(boolean ascending) { myEB.setOrderByMgrName(ascending); return _this(); } public ProcessIteratorExpressionBuilder setOrderById(boolean ascending) { myEB.setOrderById(ascending); return _this(); } public ProcessIteratorExpressionBuilder setOrderByName(boolean ascending) { myEB.setOrderByName(ascending); return _this(); } public ProcessIteratorExpressionBuilder setOrderByState(boolean ascending) { myEB.setOrderByState(ascending); return _this(); } public ProcessIteratorExpressionBuilder setOrderByPriority(boolean ascending) { myEB.setOrderByPriority(ascending); return _this(); } public ProcessIteratorExpressionBuilder setOrderByCreatedTime(boolean ascending) { myEB.setOrderByCreatedTime(ascending); return _this(); } public ProcessIteratorExpressionBuilder setOrderByStartTime(boolean ascending) { myEB.setOrderByStartTime(ascending); return _this(); } public ProcessIteratorExpressionBuilder setOrderByLastStateTime(boolean ascending) { myEB.setOrderByLastStateTime(ascending); return _this(); } public ProcessIteratorExpressionBuilder setOrderByResourceRequesterId(boolean ascending) { myEB.setOrderByResourceRequesterId(ascending); return _this(); } }
true
2ebc5e9bbbbbfe1a3bc30a33ddd82461d14267d7
Java
bert82503/book-study-note
/the-java-tutorials/src/main/java/com/java/tutorial/essential/io/Scanning.java
UTF-8
1,927
3.34375
3
[]
no_license
package com.java.tutorial.essential.io; import com.java.common.FilePathUtils; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.Locale; import java.util.Scanner; /** * <a href="https://docs.oracle.com/javase/tutorial/essential/io/scanning.html">Scanning</a> * * @author feimen * @since 2020-03-17 */ public class Scanning { public static void main(String[] args) throws FileNotFoundException { // Breaking Input into Tokens try (Scanner scanner = new Scanner(new BufferedReader(new FileReader( FilePathUtils.getFilePath("xanadu.txt"))))) { // To use a different token separator, invoke useDelimiter(), specifying a regular expression. scanner.useDelimiter(System.lineSeparator()); while (scanner.hasNext()) { System.out.println(scanner.next()); } } // Translating Individual Tokens try (Scanner scanner = new Scanner(new BufferedReader(new FileReader( FilePathUtils.getFilePath("usnumbers.txt"))))) { scanner.useLocale(Locale.US); double sum = 0.0D; while (scanner.hasNext()) { if (scanner.hasNextDouble()) { sum += scanner.nextDouble(); } else { // ignore scanner.next(); } } System.out.println("sum = " + sum); } // The "standard" input stream. try (Scanner scanner = new Scanner(System.in)) { scanner.useDelimiter(System.lineSeparator()); while (scanner.hasNext()) { String next = scanner.next(); if (next == null || next.isEmpty()) { System.exit(1); } System.out.println(next); } } } }
true
1a40b5b07403d9ae085a07dabf2a15d9aaea5af1
Java
nemethjandras/JavaHF
/Game_dev/src_Némó/src/Network.java
UTF-8
3,733
2.828125
3
[]
no_license
package src; import java.net.*; import java.util.concurrent.TimeUnit; import java.io.*; enum ConnectionType { Password_Fail, Password_Ok, Connected, Connected_Win, Not_Connected } public class Network { protected Socket socket = null; protected ObjectOutputStream outputStream = null; protected ObjectInputStream inputStream =null; protected int port; protected Inet4Address ip; protected BufferedReader in = null; protected PrintWriter out = null; protected NetworkData sendData; protected NetworkData incomData; protected boolean Won; protected int timeout; public boolean isClosed() { return socket.isClosed(); } public boolean isBound() { return socket.isBound(); } public NetworkData getSending() { return sendData; } public void setSending(NetworkData sending) { this.sendData = sending; } public int getTimeout() { return timeout; } public void setTimeout(int timeout) { this.timeout = timeout; } public NetworkData getIncoming() { return incomData; } public void setIncoming(NetworkData incoming) { this.incomData = incoming; } public String getLocalAddress() { return socket.getInetAddress().getHostAddress(); } public int getPort() { System.out.println("Sending port info->"); return port; } public void setPort(int port) { this.port = port; } public BufferedReader getInputStream() { return in; } public PrintWriter getOutputStream() { return out; } public void setWon(boolean Won) { this.Won = Won; } public boolean isWon() { return Won; } public void sending (NetworkData sendData) { try { //System.out.println("Norm�l m�k�d�s elkezd�d�tt kliens oldalon!"); ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream()); if(sendData != null) { if(this.Won != true) { outputStream.writeObject(sendData); } else { System.out.println("The game is already won"); } } else { System.out.println("A k�ldend� csomag null"); } } catch (IOException i) { System.out.println(i); } } public NetworkData incoming () { try { NetworkData data = null; ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream()); data =((NetworkData) inputStream.readObject()); if(data != null) { incomData = data; this.Won = incomData.Won; } else { System.out.println("A kapott csomag null"); } } catch(IOException i) { System.out.println(i); } catch (ClassNotFoundException e) { e.printStackTrace(); } return incomData; } //Minden kezdeti kapcsolattfel�p�t�shez sz�ks�ges adat csatorn�t becsukja public void closing_datachannels() { try { // close connection if ( in != null || inputStream != null) { System.out.println("Data input buffers are closing!"); in.close(); } else { System.out.println("Data input buffers are already closed!"); } if (out != null ||outputStream != null ) { System.out.println("Data output buffers are closing!"); out.flush(); out.close(); } else { System.out.println("Data output buffers are already closed!"); } } catch (IOException i) { System.out.println(i); } } public void closing_all() { try { if (socket !=null) { if(outputStream != null) { outputStream.flush(); outputStream.close(); } if(inputStream != null) { inputStream.close(); } socket.close(); } } catch(IOException i) { System.out.println(i); } } }
true
fae440ff34c548a2c7da7812a5d7a8f3147e77da
Java
xingi386/zktest
/zktest-main/src/main/java/net.xuanyutech.app.test.zktest/app/ZkTestStatisticController.java
UTF-8
759
1.804688
2
[]
no_license
/** * 深圳玄羽科技有限公司 http://www.xuanyutech.net/ Copyright ©2020 XuanYuTech Inc. All rights reserved. */ package net.xuanyutech.app.test.zktest.app; import com.alibaba.fastjson.JSON; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @Title: ZkTestStatisticController * @Description: * @author: 玄羽1107 * @create: 2020/4/16 19:46 * @version V1.0 */ @RestController public class ZkTestStatisticController { @Autowired ZkTestApp zkTestApp ; @RequestMapping("/") public String getTestStatistic() { return JSON.toJSONString(zkTestApp.getTaskList().toString()) ; } }
true
74e31e923a73d44340600ba29856c634a726471f
Java
ryanlr/EnglishOrJavaCode
/src/EnglishOrCode.java
UTF-8
1,865
2.71875
3
[]
no_license
import java.io.IOException; import org.apache.commons.lang.StringUtils; public class EnglishOrCode { private static Tokenizer tokenizer = null; public static void initializeTokenizer() { tokenizer = new Tokenizer(); //key words String keyString = "abstract assert boolean break byte case catch " + "char class const continue default do double else enum" + " extends false final finally float for goto if implements " + "import instanceof int interface long native new null " + "package private protected public return short static " + "strictfp super switch synchronized this throw throws true " + "transient try void volatile while todo"; String[] keys = keyString.split(" "); String keyStr = StringUtils.join(keys, "|"); tokenizer.add(keyStr, 1); tokenizer.add("\\(|\\)|\\{|\\}|\\[|\\]|;|,|\\.|=|>|<|!|~|" + "\\?|:|==|<=|>=|!=|&&|\\|\\||\\+\\+|--|" + "\\+|-|\\*|/|&|\\||\\^|%|\'|\"|\n|\r|\\$|\\#", 2);//separators, operators, etc tokenizer.add("[0-9]+", 3); //number tokenizer.add("[a-zA-Z][a-zA-Z0-9_]*", 4);//identifier tokenizer.add("@", 4); } public static void main(String[] args) throws ClassNotFoundException, IOException { initializeTokenizer(); String s = "do something in English"; if(isEnglish(s)){ System.out.println("English"); }else{ System.out.println("Java Code"); } s = "for (int i = 0; i < b.size(); i++) {"; if(isEnglish(s)){ System.out.println("English"); }else{ System.out.println("Java Code"); } } private static boolean isEnglish(String replaced) { tokenizer.tokenize(replaced); String patternString = tokenizer.getTokensString(); if(patternString.matches(".*444.*") || patternString.matches("4+")){ return true; }else{ return false; } } }
true
028cbd89723cfcba4ad173cea8c57aa68971a155
Java
MayurSTechnoCredit/JAVATechnoJuly2021
/src/madhavi/SwapVowel.java
UTF-8
1,194
3.546875
4
[]
no_license
package madhavi; import java.util.ArrayList; import java.util.Arrays; public class SwapVowel { void getSwapVowel(String str) { String[] str1 = str.split(""); ArrayList<String> list1 = new ArrayList<String>(Arrays.asList(str1)); int firstindex = list1.size(); int lastindex = 0; String ftemp = ""; String ltemp = ""; for (int index = 0; index < list1.size(); index++) { if (isVowel(list1.get(index).toString())) { if (firstindex > index) { firstindex = index; ftemp = list1.get(firstindex).toString(); } if (lastindex < index) { lastindex = index; ltemp = list1.get(lastindex).toString(); } } } // System.out.println(lastindex); // System.out.println(firstindex); list1.set(firstindex, ltemp); list1.set(lastindex, ftemp); System.out.println(list1.toString()); } static boolean isVowel(String c) { // c = Character.toLowerCase(c); if (c.equals("a") || c.equals("e") || c.equals("i") || c.equals("o") || c.equals("u")) { return true; } return false; } public static void main(String[] args) { SwapVowel swapVowel = new SwapVowel(); String input = "good morning"; swapVowel.getSwapVowel(input); } }
true
d9e46f41ded9f9bebf6bbe2c69a24e986254e88a
Java
williamlema/user-management
/src/main/java/com/user/management/app/repository/RolRepository.java
UTF-8
362
1.8125
2
[]
no_license
package com.user.management.app.repository; import com.user.management.app.model.entity.Rol; import org.springframework.data.jpa.repository.JpaRepository; /** * Repository to handle {@link Rol} entity in database * * @author <a href="weleonm@gmail.com">William Leon</a> * @version 1.0 * @since 1.0 */ public interface RolRepository extends JpaRepository<Rol, Long> { }
true
6ad009a6e9cfe5c32a749e08826c346af0b8e1b5
Java
MaxBeyer/simple-web-app
/src/main/java/com/zeus/examples/simplewebapp/db/FoodItem.java
UTF-8
750
2.578125
3
[ "MIT" ]
permissive
package com.zeus.examples.simplewebapp.db; import com.zeus.examples.simplewebapp.domain.FoodType; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.Id; import java.util.UUID; @Entity @Getter @Setter @NoArgsConstructor @EqualsAndHashCode public class FoodItem { @Id private UUID id; private String fridgeName; @Enumerated(EnumType.STRING) private FoodType foodType; public FoodItem(UUID id, String fridgeName, FoodType foodType){ this.id = id; this.fridgeName = fridgeName; this.foodType = foodType; } }
true
67677db0bbb8c50b7ff33c9c72700601a11d48ac
Java
huangfusuper/seckill-demo
/src/main/java/com/demo/OptimisticLockTest.java
UTF-8
3,523
3.0625
3
[]
no_license
package com.demo; import com.demo.utils.RedisUtil; import redis.clients.jedis.Jedis; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * Redis乐观锁秒杀实例 * 大多数是基于数据版本(version)的记录机制实现的。 * 即为数据增加一个版本标识,在基于数据库表的版本解决方案中, * 一般是通过为数据库表增加一个”version”字段来实现读取出数据时, * 将此版本号一同读出,之后更新时,对此版本号加1。 * 此时,将提交数据的版本号与数据库表对应记录的当前版本号进行比对, * 如果提交的数据版本号大于数据库当前版本号,则予以更新,否则认为是过期数据。 * redis中可以使用watch命令会监视给定的key, * 当exec时候如果监视的key从调用watch后发生过变化, * 则整个事务会失败。也可以调用watch多次监视多个key。 * 这样就可以对指定的key加乐观锁了。 * 注意watch的key是对整个连接有效的,事务也一样。如果连接断开,监视和事务都会被自动清除。 * 当然了exec,discard,unwatch命令都会清除连接中的所有监视。 * @author huangfu */ public class OptimisticLockTest { public static void main(String[] args) throws InterruptedException { long starTime=System.currentTimeMillis(); initProduct(); initClient(); printResult(); long endTime=System.currentTimeMillis(); long Time=endTime-starTime; System.out.println("程序运行时间: "+Time+"ms"); } /** * 打印签到商品的用户名单 */ public static void printResult(){ Jedis jedis = RedisUtil.getInstance().getJedis(); //取所有抢到商品的用户 Set<String> clientList = jedis.smembers("clientList"); int i= 1; for (String s : clientList) { System.out.println("第" + i++ + "个抢到商品,"+s + " "); } RedisUtil.returnPool(jedis); } /** * 初始化客户端 */ public static void initClient(){ ExecutorService cacheThreadPool = Executors.newCachedThreadPool(); //模拟客户数目 int clientNum = 1000; for (int i = 0; i < clientNum; i++) { cacheThreadPool.execute(new ClientThread(i)); } cacheThreadPool.shutdown(); //等待线程完毕 while (true){ if(cacheThreadPool.isTerminated()){ System.out.println("所有的线程都结束了"); break; }else { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } /** * 初始化商品 */ public static void initProduct(){ //商品个数 100 int prdNum = 100; String key = "prdNum"; // 抢购到商品的顾客列表 String clientList = "clientList"; Jedis jedis = RedisUtil.getInstance().getJedis(); //存在该键 就删除 if(jedis.exists(key)){ jedis.del(key); } //TODO 待分析 if (jedis.exists(clientList)) { jedis.del(clientList); } //初始化 商品数目 jedis.set(key,String.valueOf(prdNum)); RedisUtil.returnPool(jedis); } }
true
03ecad1c5c47b6944a737790afc72be3dca19772
Java
sunliangyu/iviewback
/system-service/src/main/java/com/qust/entity/RestaurantMember.java
UTF-8
1,497
2.21875
2
[]
no_license
package com.qust.entity; import javax.persistence.*; import java.io.Serializable; import java.sql.Date; // 系统餐厅成员表 @Entity public class RestaurantMember implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column private Long user; @Column private Date createtime; @Column private String name; @Column private String address; @Column private String contactWay; @Column private int level; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getUser() { return user; } public void setUser(Long user) { this.user = user; } public Date getCreatetime() { return createtime; } public void setCreatetime(Date createtime) { this.createtime = createtime; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getContactWay() { return contactWay; } public void setContactWay(String contactWay) { this.contactWay = contactWay; } public int getLevel() { return level; } public void setLevel(int level) { this.level = level; } }
true
718eb6e3419129fa5cdc44c1836d958ddf5e8af0
Java
SumeetBhong/PressureTransmitterApp
/app/src/main/java/com/orion_instruments/www/pressuretransmitterver11/Settings.java
UTF-8
18,606
1.828125
2
[]
no_license
package com.orion_instruments.www.pressuretransmitterver11; import android.app.ProgressDialog; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothSocket; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.GridView; import android.widget.TextView; import java.util.UUID; public class Settings extends AppCompatActivity { //////////////////////////////////////////////////////////////////////////////////////////////// /////////////////BLUETOOTH PARAMETERS //////////////////////////////////////////////////////////////////////////////////////////////// final int handlerState = 0; Handler bluetoothIn; private BluetoothAdapter btAdapter = null; private BluetoothSocket btSocket = null; // public BluetoothAdapter myBluetooth = null; private StringBuilder recDataString = new StringBuilder(); // private Settings.ConnectedThread mConnectedThread; private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // SPP UUID service - this should work for most devices public static String EXTRA_ADDRESS = "device_address"; // Button buttonUpdate; ProgressDialog progressDialog; TextView sensor, testText; private static String address; GridView gridView1; String[] gridViewString = { <<<<<<< HEAD "Mode", "Switch", "Sector", "Transmitter", "Device calibration","Calibration","Data logger","WiFi","About", "Device settings" ======= "Mode", "Switch", "Sector", "Transmitter", "Data Logger", "Calibration", "Device Settings", "WiFi", "About" >>>>>>> 9c9722a7a55377d26820d8d4656724b65ea11c92 }; int[] gridViewImageId = { R.drawable.modelogo, R.drawable.switchlogo, R.drawable.guagelogo, R.drawable.transmission, <<<<<<< HEAD R.drawable.calibration, R.drawable.calibrationlogo, R.drawable.logger, R.drawable.wifilogo, R.drawable.aboutlogo, R.drawable.editdevicelogo ======= R.drawable.logger, R.drawable.calibrationlogo, R.drawable.devicesettingslogo, R.drawable.wifilogo, R.drawable.aboutlogo >>>>>>> 9c9722a7a55377d26820d8d4656724b65ea11c92 }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); setTitle("Settings"); CustomGridViewActivity customGridViewActivity = new CustomGridViewActivity(Settings.this, gridViewString, gridViewImageId); <<<<<<< HEAD ======= >>>>>>> 9c9722a7a55377d26820d8d4656724b65ea11c92 testText = (TextView) findViewById(R.id.textView30); gridView1 = (GridView) findViewById(R.id.gridView); gridView1.setAdapter(customGridViewActivity); testText.setText(address); testText.setVisibility(View.INVISIBLE); <<<<<<< HEAD ======= testText = (TextView) findViewById(R.id.textView30); gridView1 = (GridView) findViewById(R.id.gridView); gridView1.setAdapter(customGridViewActivity); testText.setText(address); testText.setVisibility(View.INVISIBLE); >>>>>>> 9c9722a7a55377d26820d8d4656724b65ea11c92 Intent intent = getIntent(); //Get the MAC address from the DeviceListActivty via EXTRA address = intent.getStringExtra(EXTRA_ADDRESS); gridView1.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { if (i == 0) { progressDialog = new ProgressDialog(Settings.this); progressDialog.setMessage("Loading..."); // Setting Message // progressDialog.setTitle("ProgressDialog"); // Setting Title progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // Progress Dialog Style Spinner // Set the progress dialog background color progressDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FFD4D9D0"))); progressDialog.show(); // Display Progress Dialog progressDialog.setCancelable(false); new Thread(new Runnable() { public void run() { try { Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); } progressDialog.dismiss(); } }).start(); Intent intent = new Intent(Settings.this, Mode.class); intent.putExtra(EXTRA_ADDRESS, address); // Intent = new Intent(Settings.this, Mode.class); intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); overridePendingTransition(0, 0); } if (i == 1) { progressDialog = new ProgressDialog(Settings.this); progressDialog.setMessage("Loading..."); // Setting Message // progressDialog.setTitle("ProgressDialog"); // Setting Title progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // Progress Dialog Style Spinner // Set the progress dialog background color progressDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FFD4D9D0"))); progressDialog.show(); // Display Progress Dialog progressDialog.setCancelable(false); new Thread(new Runnable() { public void run() { try { Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); } progressDialog.dismiss(); } }).start(); Intent intent = new Intent(Settings.this, Relay.class); intent.putExtra(EXTRA_ADDRESS, address); startActivity(intent); } if (i == 2) { progressDialog = new ProgressDialog(Settings.this); progressDialog.setMessage("Loading..."); // Setting Message // progressDialog.setTitle("ProgressDialog"); // Setting Title progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // Progress Dialog Style Spinner // Set the progress dialog background color progressDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FFD4D9D0"))); progressDialog.show(); // Display Progress Dialog progressDialog.setCancelable(false); new Thread(new Runnable() { public void run() { try { Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); } progressDialog.dismiss(); } }).start(); Intent intent = new Intent(Settings.this, Gauge.class); intent.putExtra(EXTRA_ADDRESS,address); startActivity(intent); } if (i == 3) { progressDialog = new ProgressDialog(Settings.this); progressDialog.setMessage("Loading..."); // Setting Message // progressDialog.setTitle("ProgressDialog"); // Setting Title progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // Progress Dialog Style Spinner // Set the progress dialog background color progressDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FFD4D9D0"))); progressDialog.show(); // Display Progress Dialog progressDialog.setCancelable(false); new Thread(new Runnable() { public void run() { try { Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); } progressDialog.dismiss(); } }).start(); Intent intent = new Intent(Settings.this, Transmitter.class); intent.putExtra(EXTRA_ADDRESS,address); startActivity(intent); } if (i == 4) { progressDialog = new ProgressDialog(Settings.this); progressDialog.setMessage("Loading..."); // Setting Message // progressDialog.setTitle("ProgressDialog"); // Setting Title progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // Progress Dialog Style Spinner // Set the progress dialog background color progressDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FFD4D9D0"))); progressDialog.show(); // Display Progress Dialog progressDialog.setCancelable(false); new Thread(new Runnable() { public void run() { try { Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); } progressDialog.dismiss(); } }).start(); <<<<<<< HEAD Intent intent = new Intent(Settings.this, devicecalibration.class); intent.putExtra(EXTRA_ADDRESS,address); startActivity(intent); } ======= Intent intent = new Intent(Settings.this, Datalogger.class); intent.putExtra(EXTRA_ADDRESS,address); startActivity(intent); } >>>>>>> 9c9722a7a55377d26820d8d4656724b65ea11c92 if (i == 5) { progressDialog = new ProgressDialog(Settings.this); progressDialog.setMessage("Loading..."); // Setting Message // progressDialog.setTitle("ProgressDialog"); // Setting Title progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // Progress Dialog Style Spinner // Set the progress dialog background color progressDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FFD4D9D0"))); progressDialog.show(); // Display Progress Dialog progressDialog.setCancelable(false); new Thread(new Runnable() { public void run() { try { Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); } progressDialog.dismiss(); } }).start(); Intent intent = new Intent(Settings.this, Calibration.class); intent.putExtra(EXTRA_ADDRESS,address); startActivity(intent); } if (i == 6) { progressDialog = new ProgressDialog(Settings.this); progressDialog.setMessage("Loading..."); // Setting Message // progressDialog.setTitle("ProgressDialog"); // Setting Title progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // Progress Dialog Style Spinner // Set the progress dialog background color progressDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FFD4D9D0"))); progressDialog.show(); // Display Progress Dialog progressDialog.setCancelable(false); new Thread(new Runnable() { public void run() { try { Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); } progressDialog.dismiss(); } }).start(); <<<<<<< HEAD Intent intent = new Intent(Settings.this, Datalogger.class); ======= Intent intent = new Intent(Settings.this, DeviceSettings.class); >>>>>>> 9c9722a7a55377d26820d8d4656724b65ea11c92 intent.putExtra(EXTRA_ADDRESS,address); startActivity(intent); } if (i == 7) { progressDialog = new ProgressDialog(Settings.this); progressDialog.setMessage("Loading..."); // Setting Message // progressDialog.setTitle("ProgressDialog"); // Setting Title progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // Progress Dialog Style Spinner // Set the progress dialog background color progressDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FFD4D9D0"))); progressDialog.show(); // Display Progress Dialog progressDialog.setCancelable(false); new Thread(new Runnable() { public void run() { try { Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); } progressDialog.dismiss(); } }).start(); Intent intent = new Intent(Settings.this, WiFI.class); intent.putExtra(EXTRA_ADDRESS,address); startActivity(intent); } if (i == 8) { progressDialog = new ProgressDialog(Settings.this); progressDialog.setMessage("Loading..."); // Setting Message // progressDialog.setTitle("ProgressDialog"); // Setting Title progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // Progress Dialog Style Spinner // Set the progress dialog background color progressDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FFD4D9D0"))); progressDialog.show(); // Display Progress Dialog progressDialog.setCancelable(false); new Thread(new Runnable() { public void run() { try { Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); } progressDialog.dismiss(); } }).start(); Intent intent = new Intent(Settings.this, About.class); intent.putExtra(EXTRA_ADDRESS,address); startActivity(intent); } <<<<<<< HEAD if (i == 9) { progressDialog = new ProgressDialog(Settings.this); progressDialog.setMessage("Loading..."); // Setting Message // progressDialog.setTitle("ProgressDialog"); // Setting Title progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // Progress Dialog Style Spinner // Set the progress dialog background color progressDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FFD4D9D0"))); progressDialog.show(); // Display Progress Dialog progressDialog.setCancelable(false); new Thread(new Runnable() { public void run() { try { Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); } progressDialog.dismiss(); } }).start(); Intent intent = new Intent(Settings.this,DeviceSettings.class); intent.putExtra(EXTRA_ADDRESS,address); startActivity(intent); } ======= >>>>>>> 9c9722a7a55377d26820d8d4656724b65ea11c92 // Toast.makeText(MainActivity.this,"Selected: "+gridViewString[+i], Toast.LENGTH_LONG).show(); } }); ///////////////////////////////////////////////////////////////////////////////////////////////////// // Code for Send Receive ////////////////////////////////////////////////////////////////////////////////////////////////////// /* @Override public void onResume() { super.onResume(); //I send a character when resuming.beginning transmission to check device is connected //If it is not an exception will be thrown in the write method and finish() will be called } @Override public void onPause() { super.onPause(); }*/ //////////////////////////////////////////////////////////////////////////////////////////////////// } }
true
bc3abdad5a09db683234966f36c73ed2b54e255b
Java
Mohsin5665/Tanish
/app/src/main/java/com/itpvt/tanish/Adapters/Recycler_Adapter_Sub_catagories.java
UTF-8
2,227
2.1875
2
[]
no_license
package com.itpvt.tanish.Adapters; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import com.itpvt.tanish.Categories; import com.itpvt.tanish.Pojo.Sub_Categories_pojo; import com.itpvt.tanish.R; import java.util.ArrayList; /** * Created by Itpvt on 13-Jan-18. */ public class Recycler_Adapter_Sub_catagories extends RecyclerView.Adapter<Recycler_Adapter_Sub_catagories.MyViewHolder>{ ArrayList<Sub_Categories_pojo> arrayList= new ArrayList<>(); Activity activity; String WebUrl; public Recycler_Adapter_Sub_catagories(ArrayList<Sub_Categories_pojo> arrayList, Context context) { this.arrayList=arrayList; activity=(Activity)context; } @Override public Recycler_Adapter_Sub_catagories.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.categories_item,parent,false); return new Recycler_Adapter_Sub_catagories.MyViewHolder(view); } @Override public void onBindViewHolder(Recycler_Adapter_Sub_catagories.MyViewHolder holder, final int position) { holder.name.setText(arrayList.get(position).getName()); holder.name.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(activity,Categories.class); intent.putExtra("id",arrayList.get(position).getCategory_id()); intent.putExtra("title",arrayList.get(position).getName()); activity.startActivity(intent); activity.finish(); } }); } @Override public int getItemCount() { return arrayList.size(); } public static class MyViewHolder extends RecyclerView.ViewHolder { Button name; public MyViewHolder(View itemView) { super(itemView); name=(Button)itemView.findViewById(R.id.name); } } }
true
4f9e5199c51ef8e8c448a2f16138d001918ae253
Java
bculkin2442/bjc-utils2
/base/src/main/java/bjc/utils/ioutils/blocks/MappedBlockReader.java
UTF-8
1,121
3.234375
3
[]
no_license
package bjc.utils.ioutils.blocks; import java.io.IOException; import java.util.function.UnaryOperator; /** * A block reader that applies a transform to each block. * * @author EVE * */ public class MappedBlockReader implements BlockReader { private BlockReader reader; private Block current; private UnaryOperator<Block> transform; private int blockNo; /** * Create a new mapped block reader. * * @param source * The source for blocks * @param trans * The transform to apply. */ public MappedBlockReader(BlockReader source, UnaryOperator<Block> trans) { reader = source; transform = trans; blockNo = 0; } @Override public boolean hasNextBlock() { return reader.hasNextBlock(); } @Override public Block getBlock() { return current; } @Override public boolean nextBlock() { if (hasNextBlock()) { current = transform.apply(reader.next()); blockNo += 1; return true; } return false; } @Override public int getBlockCount() { return blockNo; } @Override public void close() throws IOException { reader.close(); } }
true
123512a0df51271084a0e7e0e2f31f8287277bac
Java
alancesar/flight-plan
/flight-plan-core/src/main/java/org/alancesar/service/RouteService.java
UTF-8
975
2.890625
3
[]
no_license
package org.alancesar.service; import org.alancesar.model.Route; import org.alancesar.repository.RouteRepository; import java.util.List; import java.util.function.Function; public class RouteService implements Service<Route> { private final RouteRepository repository; private Function<Route, String> routeToString = (route) -> String.format( "%s,%s,%.0f\r\n", route.getOrigin(), route.getDestination(), route.getPrice()); private Function<String, Route> stringToRoute = (line) -> { String[] items = line.split(","); double price = Double.valueOf(items[2]); return new Route(items[0], items[1], price); }; public RouteService(RouteRepository repository) { this.repository = repository; } @Override public List<Route> getAll() { return repository.readAll(stringToRoute); } @Override public void save(Route route) { repository.write(route, routeToString); } }
true
c686dac4ff9e5bc5dd15feed7898c62d19024a38
Java
wahabjan123/coco
/Desktop/src/main/java/com/gazman/coco/desktop/miner/requests/CocoRequest.java
UTF-8
5,026
2.375
2
[]
no_license
package com.gazman.coco.desktop.miner.requests; import com.gazman.coco.core.api.ErrorData; import com.gazman.coco.core.hash.Sha256Hash; import com.gazman.coco.core.utils.GsonHelper; import com.gazman.coco.desktop.wallet.WalletModel; import com.gazman.lifecycle.Factory; import com.gazman.lifecycle.utils.Command; import okhttp3.*; import java.io.InputStream; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.concurrent.TimeUnit; /** * Created by Ilya Gazman on 1/27/2018. */ @SuppressWarnings("unchecked") public class CocoRequest<DATA, COCO_REQUEST extends CocoRequest<DATA, ?>> implements Command { static final OkHttpClient client; static { client = new OkHttpClient.Builder() .connectTimeout(1, TimeUnit.MINUTES) .readTimeout(5, TimeUnit.MINUTES) .build(); } private static final SecureRandom random; static { try { random = SecureRandom.getInstanceStrong(); } catch (NoSuchAlgorithmException e) { throw new Error(e); } } protected final String host; protected final int port; private final byte[] publicKey; private final long randomNumber; private WalletModel walletModel = Factory.inject(WalletModel.class); private Class<DATA> responseClass; protected String path = ""; private Callback<DATA> callback; public COCO_REQUEST setCallback(Callback<DATA> callback) { this.callback = callback; return (COCO_REQUEST) this; } @SuppressWarnings("ConstantConditions") protected HttpUrl.Builder httpUrlBuilder = new HttpUrl.Builder() .scheme("http"); private GsonHelper gsonHelper = Factory.inject(GsonHelper.class); public static <T, C extends CocoRequest<T, ?>> C create(Class<T> response, PoolData poolData) { return (C) new CocoRequest<T, C>(poolData).setResponseClass(response); } protected CocoRequest(PoolData poolData) { if (random == null) { throw new Error("Error initializing random"); } this.randomNumber = random.nextLong(); this.host = poolData.host; this.port = poolData.port; this.publicKey = poolData.publicKey; } protected COCO_REQUEST setResponseClass(Class<DATA> responseClass) { this.responseClass = responseClass; return (COCO_REQUEST) this; } public COCO_REQUEST setPath(String path) { this.path = path; return (COCO_REQUEST) this; } public COCO_REQUEST addQueryParameter(String name, Object value) { httpUrlBuilder.addQueryParameter(name, value.toString()); return (COCO_REQUEST) this; } public void execute() { addQueryParameter("publicKey", walletModel.getPublicKey()); httpUrlBuilder .host(host) .port(port) .addPathSegments(path); HttpUrl url = httpUrlBuilder.build(); String normalizedUrl = url.host() + url.query(); String signature = walletModel.signToString(normalizedUrl); Request request = new Request.Builder() .url(url) .header("Signature", signature) .build(); execute(request); } protected void execute(Request request) { try (Response response = client.newCall(request).execute()) { ResponseBody body = response.body(); if (body == null) { sendError("Connection error"); return; } byte[] data; try (InputStream inputStream = body.byteStream()) { int dataSize = (int) body.contentLength(); data = new byte[dataSize]; if (inputStream.read(data) != dataSize) { sendError("Connection error"); } } String reposeData = new String(data, Sha256Hash.UTF_8); if (response.isSuccessful()) { callback.onSuccess(gsonHelper.gson.fromJson(reposeData, responseClass)); } else { callback.onError(gsonHelper.gson.fromJson(reposeData, ErrorData.class)); } } catch (Throwable e) { e.printStackTrace(); sendError("Unexpected error"); } } private void sendError(String message) { ErrorData errorData = new ErrorData(message, -1); callback.onError(errorData); } private String sign() { HttpUrl httpUrl = httpUrlBuilder.build(); String query = httpUrl.query(); String signature = walletModel.signToString(query); System.out.println("Signature " + signature); System.out.println("query " + query); System.out.println("public key " + walletModel.getPublicKey()); return signature; } public interface Callback<T> { void onSuccess(T data); void onError(ErrorData errorData); } }
true
a4a4e53ef5a8562d4adae32885ead80c2e738045
Java
ybxxszl/qs
/src/com/wjy/util/URLUtil.java
UTF-8
2,438
2.921875
3
[]
no_license
package com.wjy.util; import java.util.HashMap; import java.util.Map; public class URLUtil { public static Map<String, Object> getPathAndParamsByURL(String url) throws Exception { Map<String, Object> map = new HashMap<String, Object>(); if (url != null && !"".equals(url)) { String[] pathAndParams = url.split("[?]"); // 请求路径 map.put("path", pathAndParams[0]); if (pathAndParams.length == 2) { String[] params = pathAndParams[1].split("[&]"); for (String param : params) { String[] keyAndValue = param.split("[=]"); if (keyAndValue.length == 2) { // 请求参数 map.put(keyAndValue[0], keyAndValue[1]); } } } else { throw new Exception("URL中不含参数"); } } else { throw new Exception("无URL"); } return map; } public static String getPathByURL(String url) throws Exception { String path = null; if (url != null && !"".equals(url)) { String[] pathAndParams = url.split("[?]"); // 请求路径 path = pathAndParams[0]; } else { throw new Exception("无URL"); } return path; } public static Map<String, Object> getParamsByURL(String url) throws Exception { Map<String, Object> map = new HashMap<String, Object>(); if (url != null && !"".equals(url)) { String[] pathAndParams = url.split("[?]"); if (pathAndParams.length == 2) { String[] params = pathAndParams[1].split("[&]"); for (String param : params) { String[] keyAndValue = param.split("[=]"); if (keyAndValue.length == 2) { // 请求参数 map.put(keyAndValue[0], keyAndValue[1]); } } } else { throw new Exception("URL中不含参数"); } } else { throw new Exception("无URL"); } return map; } public static Map<String, Object> getParamsByParam(String param) throws Exception { Map<String, Object> map = new HashMap<String, Object>(); if (param != null && !"".equals(param)) { String[] params = param.split("[&]"); for (String str : params) { String[] keyAndValue = str.split("[=]"); if (keyAndValue.length == 2) { // 请求参数 map.put(keyAndValue[0], keyAndValue[1]); } } } else { throw new Exception("无参数"); } return map; } }
true
5c2ee7337126875745360e77b9fdad2e9bd13680
Java
liuyaoCS/spydroid-NEW
/app/src/main/java/com/spydroid/net/rtsp/client/message/RtspEntityMessage.java
UTF-8
2,333
2.265625
2
[]
no_license
package com.spydroid.net.rtsp.client.message; /** * Copyright 2010 Voice Technology Ind. e Com. Ltda. * * RTSPClientLib is free software: you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * RTSPClientLib is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this software. If not, see <http://www.gnu.org/licenses/>. * * * This class has been adapted to the needs of the RtspCamera project * @author Stefan Krusche (krusche@dr-kruscheundpartner.de) * */ import com.spydroid.net.rtsp.client.api.EntityMessage; import com.spydroid.net.rtsp.client.api.Message; import com.spydroid.net.rtsp.client.header.ContentEncodingHeader; import com.spydroid.net.rtsp.client.header.ContentLengthHeader; import com.spydroid.net.rtsp.client.header.ContentTypeHeader; import com.spydroid.net.rtsp.client.header.RtspContent; public class RtspEntityMessage implements EntityMessage { private RtspContent content; private final Message message; public RtspEntityMessage(Message message) { this.message = message; } public RtspEntityMessage(Message message, RtspContent body) { this(message); setContent(body); } @Override public Message getMessage() { return message; }; public byte[] getBytes() throws Exception { message.getHeader(ContentTypeHeader.NAME); message.getHeader(ContentLengthHeader.NAME); return content.getBytes(); } @Override public RtspContent getContent() { return content; } @Override public void setContent(RtspContent content) { if(content == null) throw new NullPointerException(); this.content = content; message.addHeader(new ContentTypeHeader(content.getType())); if(content.getEncoding() != null) message.addHeader(new ContentEncodingHeader(content.getEncoding())); message.addHeader(new ContentLengthHeader(content.getBytes().length)); } @Override public boolean isEntity() { return content != null; } }
true
819419f431bea2dcbd223b6d865823bc23d1e0ff
Java
Jessevanduijne/2.3_Conway_Game_of_Life
/src/PauzeButtonView.java
UTF-8
377
2.546875
3
[]
no_license
import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.Timer; @SuppressWarnings("serial") public class PauzeButtonView extends JPanel { private Timer timer; public PauzeButtonView(Timer timer) { this.timer = timer; JButton pauzeKnop = new JButton("Pauzeer"); pauzeKnop.addActionListener(new TimerController(timer)); add(pauzeKnop); } }
true
814c804cd0264ae20f8ba3928f6d0e972e53d9e3
Java
ramonaflower/Awesome_Music_New
/app/src/main/java/com/example/ramona/music_player/Adapter/AdapterRecyclerViewListArtist.java
UTF-8
2,967
2.328125
2
[]
no_license
package com.example.ramona.music_player.Adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.example.ramona.music_player.Entities.ArtistEntities; import com.example.ramona.music_player.Interface.ClickListener; import com.example.ramona.music_player.R; import java.util.List; /** * Created by Ramona on 9/29/2017. */ public class AdapterRecyclerViewListArtist extends RecyclerView.Adapter<AdapterRecyclerViewListArtist.MyViewHolder> { private List<ArtistEntities> mListArtist; private Context mContext; private ArtistEntities entities; private ClickListener mClickListener; public AdapterRecyclerViewListArtist(List<ArtistEntities> mListArtist, Context mContext) { this.mListArtist = mListArtist; this.mContext = mContext; } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(parent.getContext()); View view = inflater.inflate(R.layout.lt_item_album_artist, parent, false); return new MyViewHolder(view); } @Override public void onBindViewHolder(MyViewHolder holder, int position) { entities = mListArtist.get(position); int numberOfSong = entities.getmSongQuantity(); int numberOfAlbum = entities.getmAlbumQuantity(); holder.mTextArtistName.setText(entities.getmArtistName()); holder.mTextDetail.setText(mContext.getString(R.string.number_of_album_artist, numberOfAlbum, numberOfSong)); } @Override public int getItemCount() { return mListArtist.size(); } public class MyViewHolder extends RecyclerView.ViewHolder { public TextView mTextArtistName, mTextDetail; public ImageView mImgArtist; public MyViewHolder(View itemView) { super(itemView); mTextArtistName = itemView.findViewById(R.id.text_album_name_or_artist_name); mTextDetail = itemView.findViewById(R.id.text_artist_name_or_number_of_song_album); mImgArtist = itemView.findViewById(R.id.img_album_artist); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mClickListener.OnItemClick(getLayoutPosition()); } }); itemView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { mClickListener.OnLongItemClick(getLayoutPosition()); return false; } }); } } public void SetOnItemClickListener(ClickListener clickListener) { mClickListener = clickListener; } }
true
80aaafb4f3384be76a86ac313273b6768549bc39
Java
vernonsoftwaresolutions/MoodleDotAccounts
/src/main/java/com/moodle/account/client/MoodleTenantClient.java
UTF-8
443
2.015625
2
[]
no_license
package com.moodle.account.client; import com.moodle.account.model.moodle.MoodleSiteRequest; import com.moodle.account.model.moodle.SQSResponse; /** * Created by andrewlarsen on 11/9/17. */ public interface MoodleTenantClient { /** * Method to post Moodle Tenant request to service to be * place on the appropriate queue * @param request * @return */ SQSResponse postMessage(MoodleSiteRequest request); }
true
54459248f5f20dd5e8a30466ce809df12fb2ed57
Java
yulmaso/ComputerGraphics
/src/main/java/ThreadHandler/ThreadHandler.java
UTF-8
2,279
2.828125
3
[]
no_license
package ThreadHandler; import GUI.MainWindow; import GUI.controllers.LabFiveController; import GUI.controllers.LabFourController; import GUI.controllers.LabSixController; import GUI.controllers.LabThreeController; import lab1.AppRoot1; import lab2.AppRoot2; import lab3.AppRoot3; import lab4.AppRoot4; import lab5.AppRoot5; import lab6.AppRoot6; public class ThreadHandler { private static Thread appRootThread; private static AppRoot appRoot; public static void startFirstScene(){ kill(); appRootThread = new Thread(appRoot = new AppRoot1()); appRootThread.start(); System.err.print("AppRoot1 started on "); System.err.println(appRootThread.toString()); } public static void startSecondScene(){ kill(); appRootThread = new Thread(appRoot = new AppRoot2()); appRootThread.start(); System.err.print("AppRoot2 started on "); System.err.println(appRootThread.toString()); } public static void startThirdScene(LabThreeController c){ kill(); appRootThread = new Thread(appRoot = new AppRoot3(c)); appRootThread.start(); System.err.print("AppRoot3 started on "); System.err.println(appRootThread.toString()); } public static void startFourthScene(LabFourController c){ kill(); appRootThread = new Thread(appRoot = new AppRoot4(c)); appRootThread.start(); System.err.print("AppRoot4 started on "); System.err.println(appRootThread.toString()); } public static void startFifthScene(LabFiveController c){ kill(); appRootThread = new Thread(appRoot = new AppRoot5(c)); appRootThread.start(); System.err.print("AppRoot5 started on "); System.err.println(appRootThread.toString()); } public static void startSixthScene(LabSixController c){ kill(); appRootThread = new Thread(appRoot = new AppRoot6(c)); appRootThread.start(); System.err.print("AppRoot6 started on "); System.err.println(appRootThread.toString()); } public static void kill(){ if (appRootThread != null){ // appRootThread.interrupt(); appRoot.stop(); // } } }
true
633f777d3212864010db8d80ea9f316663af0aff
Java
czarodziejkarol/warsaw-trails
/warsaw-trails-spdb/src/com/carlncarl/spdb/android/NewTrailActivity.java
WINDOWS-1250
12,678
1.867188
2
[]
no_license
package com.carlncarl.spdb.android; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter; import org.springframework.web.client.RestTemplate; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.location.Location; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.NavUtils; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ListView; import com.carlncarl.spdb.android.dto.CoordinateDto; import com.carlncarl.spdb.android.dto.MainPointDto; import com.carlncarl.spdb.android.dto.PointDto; import com.carlncarl.spdb.android.dto.TrailDto; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMap.OnMapClickListener; import com.google.android.gms.maps.GoogleMap.OnMyLocationChangeListener; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.PolylineOptions; public class NewTrailActivity extends Activity implements OnMyLocationChangeListener, OnMapClickListener , OnItemClickListener{ public static final String NEW_TRAIL_KEY = "new_trail"; private int position; LinearLayout newPointOrEndTrailLayout; LinearLayout addPointLayout; EditText textPointName; EditText textPointDesc; EditText textPointTrailDesc; ListView listExistingPoints; GoogleMap map; TrailDto trail; LinkedList<Location> locations; List<MarkerOptions> markers; PolylineOptions polyline; private PointDto currentPoint; private List<MainPointDto> nearPoints; private ArrayAdapter<MainPointDto> adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); locations = new LinkedList<Location>(); markers = new ArrayList<MarkerOptions>(); setContentView(R.layout.activity_new_trail); MapFragment mapFragment = (MapFragment) getFragmentManager() .findFragmentById(R.id.map); map = mapFragment.getMap(); setUpMap(); Button buttonNewPoint = (Button) findViewById(R.id.button_new_point); buttonNewPoint.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { showAddPointLayout(); } }); Button buttonEndTrail = (Button) findViewById(R.id.button_end_trail); buttonEndTrail.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { endTrail(); } }); Button buttonAddPoint = (Button) findViewById(R.id.button_add_point); buttonAddPoint.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { addNewPoint(); } }); Button buttonCancelAdding = (Button) findViewById(R.id.button_cancel); buttonCancelAdding.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { cancelAddingPoint(); } }); textPointName = (EditText) findViewById(R.id.edit_point_name); textPointDesc = (EditText) findViewById(R.id.edit_point_description); textPointTrailDesc = (EditText) findViewById(R.id.edit_description_trail_point); listExistingPoints = (ListView) findViewById(R.id.list_points_existing); nearPoints = new ArrayList<MainPointDto>(); adapter = new ArrayAdapter<MainPointDto>(this, android.R.layout.simple_list_item_1, android.R.id.text1, nearPoints); listExistingPoints.setAdapter(adapter ); listExistingPoints.setVisibility(View.GONE); listExistingPoints.setOnItemClickListener(this); newPointOrEndTrailLayout = (LinearLayout) findViewById(R.id.new_or_end_layout); newPointOrEndTrailLayout.setVisibility(View.VISIBLE); addPointLayout = (LinearLayout) findViewById(R.id.add_point_layout); addPointLayout.setVisibility(View.GONE); Intent intent = getIntent(); position = intent.getIntExtra(NaviActivity.SELECTED_MAIN_ITEM, 0); trail = (TrailDto) intent.getSerializableExtra(NEW_TRAIL_KEY); setupActionBar(); } protected void cancelAddingPoint() { newPointOrEndTrailLayout.setVisibility(View.VISIBLE); addPointLayout.setVisibility(View.GONE); currentPoint = null; this.textPointName.setText(""); this.textPointDesc.setText(""); this.textPointTrailDesc.setText(""); listExistingPoints.setVisibility(View.GONE); } protected void addNewPoint() { Location loc = map.getMyLocation(); PointDto point = currentPoint; point.setName(this.textPointName.getText().toString()); point.setDescription(this.textPointDesc.getText().toString()); point.setPointDescription(this.textPointTrailDesc.getText().toString()); point.setLatitude(loc.getLatitude()); point.setLongitude(loc.getLongitude()); point.setEndTime(new Date()); MarkerOptions marker = new MarkerOptions(); marker.position(new LatLng(point.getLatitude(), point.getLongitude())); marker.title(point.getName()); marker.visible(true); marker.snippet(point.getDescription()); marker.icon(IconChooser.chooseBitmap(markers.size())); trail.getPoints().add(point); map.addMarker(marker); markers.add(marker); cancelAddingPoint(); } protected void showAddPointLayout() { newPointOrEndTrailLayout.setVisibility(View.GONE); addPointLayout.setVisibility(View.VISIBLE); nearPoints = new ArrayList<MainPointDto>(); this.currentPoint = new PointDto(); Location lastLoc = locations.getLast(); new LoadNearPointsTask().execute(lastLoc.getLatitude() +"", lastLoc.getLongitude()+"","200"); } protected void endTrail() { this.trail.setEndTime(new Date()); Intent resultIntent = new Intent(); resultIntent.putExtra(NEW_TRAIL_KEY, trail); setResult(Activity.RESULT_OK, resultIntent); finish(); // /navigateUpTo(true); } private void setUpMap() { // LocationManager manager = (LocationManager) // this.getSystemService(Context.LOCATION_SERVICE); map.setMyLocationEnabled(true); LatLng latLng = new LatLng(52.2297700, 21.0117800); // gMap.moveCamera(CameraUpdateFactory.newLatLng(latLng )); map.animateCamera(CameraUpdateFactory.zoomTo(11)); map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11)); map.setOnMyLocationChangeListener(this); map.setOnMapClickListener(this); } /** * Set up the {@link android.app.ActionBar}. */ private void setupActionBar() { getActionBar().setDisplayHomeAsUpEnabled(true); } @Override public boolean dispatchTouchEvent(MotionEvent event) { View view = getCurrentFocus(); boolean ret = super.dispatchTouchEvent(event); if (view instanceof EditText) { View w = getCurrentFocus(); int scrcoords[] = new int[2]; w.getLocationOnScreen(scrcoords); float x = event.getRawX() + w.getLeft() - scrcoords[0]; float y = event.getRawY() + w.getTop() - scrcoords[1]; if (event.getAction() == MotionEvent.ACTION_UP && (x < w.getLeft() || x >= w.getRight() || y < w.getTop() || y > w.getBottom()) ) { InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(getWindow().getCurrentFocus().getWindowToken(), 0); } } return ret; } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.new_trail, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: navigateUpTo(false); return true; } return super.onOptionsItemSelected(item); } protected void navigateUpTo(boolean trail) { Intent intent = getParentActivityIntent(); intent.putExtra(NaviActivity.SELECTED_MAIN_ITEM, position); if (trail) { intent.putExtra(NEW_TRAIL_KEY, this.trail); } NavUtils.navigateUpTo(this, intent); } @Override public void onMyLocationChange(Location location) { if (location.getAccuracy() > 10) { if(locations.size() == 0){ locations.add(location); } return; } LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude()); if (polyline == null) { polyline = new PolylineOptions(); polyline.color(Color.GREEN); //dodanie poprzednich punktw if(trail != null && trail.getPath().size() > 0){ for (CoordinateDto coordinate : trail.getPath()) { polyline.add(new LatLng(coordinate.getLatitude(), coordinate.getLongitude())); } } map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 21)); } else { map.animateCamera(CameraUpdateFactory.newLatLng(latLng)); } polyline.add(latLng); map.addPolyline(polyline); this.trail.getPath().add(new CoordinateDto(location.getLatitude(), location.getLongitude())); locations.add(location); } @Override public void onMapClick(LatLng arg0) { // TODO Auto-generated method stub } private class LoadNearPointsTask extends AsyncTask<String, Integer, MainPointDto[]> { @Override protected MainPointDto[] doInBackground(String... params) { String url = Constants.SERVER_PATH + "api/near-points?latitude={latitude}&longitude={longitude}" + "&distance={distance}"; RestTemplate restTemplate = new RestTemplate( new HttpComponentsClientHttpRequestFactory()); Map<String, Object> urlVariables = new HashMap<String, Object>(); urlVariables.put("latitude", params[0]); urlVariables.put("longitude", params[1]); urlVariables.put("distance", params[2]); restTemplate.getMessageConverters().add( new MappingJacksonHttpMessageConverter()); MainPointDto[] list = restTemplate.getForObject(url, MainPointDto[].class,urlVariables); PlacesService service = new PlacesService( "AIzaSyDDQmSFM5YGLpvBFitj1TZwpH9AvPHzhbg"); String places; ArrayList<Place> findPlaces = service.findPlaces(Double.valueOf(params[0]), Double.valueOf(params[1]), "", params[2]); ArrayList<MainPointDto> found = new ArrayList<MainPointDto>(); for (int i = 0; i < findPlaces.size(); i++) { Place placeDetail = findPlaces.get(i); for (MainPointDto mpoint : list) { if(placeDetail.getId().equals(mpoint.getPoiReference())){ break; } } MainPointDto mpoint = new MainPointDto(); mpoint.setCoordinate(new CoordinateDto(placeDetail.getLatitude(),placeDetail.getLongitude())); mpoint.setName(placeDetail.getName()); mpoint.setDescription(placeDetail.getVicinity()); mpoint.setPoiReference(placeDetail.getId()); found.add(mpoint); } for (MainPointDto mpoint : list) { found.add(mpoint); } MainPointDto[] retList = new MainPointDto[found.size()]; for (int i = 0; i < found.size(); i++) { retList[i] = found.get(i); } return retList; } @Override protected void onPostExecute(MainPointDto[] result) { super.onPostExecute(result); if (result != null) { addItemsToAdapter(result); } } } @Override public void onItemClick(AdapterView<?> arg0, View arg1, int index, long arg3) { MainPointDto point = nearPoints.get(index); currentPoint.setMainPointId(point.getId()); currentPoint.setPoiRef(point.getPoiReference()); textPointName.setText(point.getName()); textPointDesc.setText(point.getDescription()); } public void addItemsToAdapter(MainPointDto[] result) { for (MainPointDto mainPointDto : result) { nearPoints.add(mainPointDto); } listExistingPoints.setVisibility(View.VISIBLE); adapter.clear(); adapter.addAll(nearPoints); adapter.notifyDataSetChanged(); } }
true
6ae3044052856b10f93c9d5b1a4d17be82e1201c
Java
HimuroV/projeto_poee
/src/main/java/com/projeto/view/produto/BuscaProduto.java
UTF-8
7,039
2.359375
2
[]
no_license
package com.projeto.view.produto; import java.awt.BorderLayout; import java.awt.FlowLayout; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.table.TableRowSorter; import com.projeto.model.models.Produto; import com.projeto.model.service.ProdutoService; import com.projeto.view.produto.TabelaProdutoModel; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import javax.swing.RowFilter; import javax.swing.LayoutStyle.ComponentPlacement; import javax.swing.JScrollPane; import javax.swing.JTable; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.List; import java.util.regex.PatternSyntaxException; public class BuscaProduto extends JDialog { private static final long serialVersionUID = 3538690718870328680L; private static final int CODIGO = 0; private static final int NOME = 1; private static final int VALOR_VENDA = 2; private static final int DESCRICAO = 3; private final JPanel contentPanel = new JPanel(); private JLabel lblNewLabel; private JTextField textField; private JScrollPane scrollPane; private JTable tableProduto; private TabelaProdutoModel tabelaProdutoModel; private TableRowSorter<TabelaProdutoModel> sortTabelaProduto; private List<Produto> listaProduto; private Integer codigoProduto; private String nomeProduto; private double valor_vendaProduto; private String descricaoProduto; private boolean selectProduto; public void setSelectProduto(boolean selectProduto) { this.selectProduto = selectProduto; } public BuscaProduto(JFrame frame, boolean modal) { super(frame, modal); initComponents(); setResizable(false); iniciarDados(); } private void iniciarDados() { listaProduto = new ArrayList<Produto>(); } private void initComponents() { setBounds(100, 100, 611, 411); getContentPane().setLayout(new BorderLayout()); contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); getContentPane().add(contentPanel, BorderLayout.CENTER); lblNewLabel = new JLabel("Pesquisar Nome do Produto:"); textField = new JTextField(); textField.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { String filtro = textField.getText(); filtraNomeProduto(filtro); } }); textField.setColumns(10); scrollPane = new JScrollPane(); GroupLayout gl_contentPanel = new GroupLayout(contentPanel); gl_contentPanel.setHorizontalGroup( gl_contentPanel.createParallelGroup(Alignment.LEADING) .addGroup(gl_contentPanel.createSequentialGroup() .addContainerGap() .addGroup(gl_contentPanel.createParallelGroup(Alignment.LEADING) .addGroup(gl_contentPanel.createSequentialGroup() .addComponent(lblNewLabel) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(textField, GroupLayout.PREFERRED_SIZE, 401, GroupLayout.PREFERRED_SIZE)) .addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 541, GroupLayout.PREFERRED_SIZE)) .addContainerGap(34, Short.MAX_VALUE)) ); gl_contentPanel.setVerticalGroup( gl_contentPanel.createParallelGroup(Alignment.LEADING) .addGroup(gl_contentPanel.createSequentialGroup() .addGap(22) .addGroup(gl_contentPanel.createParallelGroup(Alignment.BASELINE) .addComponent(lblNewLabel) .addComponent(textField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 220, GroupLayout.PREFERRED_SIZE) .addContainerGap(61, Short.MAX_VALUE)) ); tableProduto = new JTable(); tabelaProdutoModel = new TabelaProdutoModel(); tabelaProdutoModel.setListaProduto(carregarListaProduto()); tableProduto.setModel(tabelaProdutoModel); scrollPane.setViewportView(tableProduto); tableProduto.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); sortTabelaProduto = new TableRowSorter<TabelaProdutoModel>(tabelaProdutoModel); tableProduto.setRowSorter(sortTabelaProduto); tableProduto.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); contentPanel.setLayout(gl_contentPanel); { JPanel buttonPane = new JPanel(); buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT)); getContentPane().add(buttonPane, BorderLayout.SOUTH); { JButton okButton = new JButton("OK"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { selecionaProduto(); } }); okButton.setActionCommand("OK"); buttonPane.add(okButton); getRootPane().setDefaultButton(okButton); } { JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setSelectProduto(false); } }); cancelButton.setActionCommand("Cancel"); buttonPane.add(cancelButton); } } } protected void selecionaProduto() { if(tableProduto.getSelectedRow() != -1 && tableProduto.getSelectedRow() < tabelaProdutoModel.getRowCount()) { setCodigoProduto(Integer.valueOf(tableProduto.getValueAt(tableProduto.getSelectedRow(), CODIGO).toString())); setNomeProduto(tableProduto.getValueAt(tableProduto.getSelectedRow(), NOME).toString()); setValor_vendaProduto(Double.valueOf(tableProduto.getValueAt(tableProduto.getSelectedRow(), VALOR_VENDA).toString())); setDescricaoProduto(tableProduto.getValueAt(tableProduto.getSelectedRow(), DESCRICAO).toString()); setSelectProduto(true); dispose(); } else { setSelectProduto(false); } } private List<Produto> carregarListaProduto() { ProdutoService produtoService = new ProdutoService(); return produtoService.findAll(); } private void filtraNomeProduto(String filtro) { RowFilter<TabelaProdutoModel, Object> rowFilter = null; try { rowFilter = RowFilter.regexFilter(filtro); } catch(PatternSyntaxException e) { return; } sortTabelaProduto.setRowFilter(rowFilter); } public Integer getCodigoProduto() { return codigoProduto; } public void setCodigoProduto(Integer codigoProduto) { this.codigoProduto = codigoProduto; } public String getNomeProduto() { return nomeProduto; } public void setNomeProduto(String nomeProduto) { this.nomeProduto = nomeProduto; } public double getValor_vendaProduto() { return valor_vendaProduto; } public void setValor_vendaProduto(double valor_vendaProduto) { this.valor_vendaProduto = valor_vendaProduto; } public String getDescricaoProduto() { return descricaoProduto; } public void setDescricaoProduto(String descricaoProduto) { this.descricaoProduto = descricaoProduto; } public boolean isSelectProduto() { return selectProduto; } }
true
8e4409785fabf1b022d8fe2f6a20fa600a6e5321
Java
SunGitShine/tgm-server
/domain/src/main/java/com/juma/tgm/mq/domain/CustomerInvoiceEvent.java
UTF-8
6,529
2.015625
2
[]
no_license
package com.juma.tgm.mq.domain; import java.io.Serializable; import java.math.BigDecimal; /** * 功能 : * * @author : Bruce(刘正航) 15:35 2019-05-28 */ public class CustomerInvoiceEvent implements Serializable { /**来源单号(物流传对账单号)**/ private String sourceDocumentNo; /**来源单类型:RECONCILIATION(对账单),RENT_SALE(租售订单)**/ private String sourceDocumentType; /**业务类型:LOGISTICS(物流),SALE(销售),RENT(租赁),AFFILIATED(挂靠)**/ private String businessType; private Integer customerId; private String customerName; /**客户类型:PERSONAL(个人),ENTERPRISE(企业)**/ private String customerType; /**项目合同编号**/ private String contractCode; /**单据日期:对账单创建日期,格式yyyy-MM-dd**/ private String sourceDocumentCreateDate; /**车牌号**/ private String plateNumber; /**车架号**/ private String vin; /**本次不传:数量/期数**/ private Integer count; /**其他信息:物流格式:项目名称/运单完成时间,格式:测试项目/yyyy-mm-dd HH:mm:ss**/ private String otherInfo; /**运单税率: 运单 客户侧 税率 (默认该对账单下运单税率一致)**/ private BigDecimal taxRate; /**客户侧:运单含税金额(所有运单含税金额求和)**/ private BigDecimal amountIncludeTax; /**运单签约主体公司**/ private Integer companyId; private String companyCode; private String companyName; /**公司纳税人识别号**/ private String companyTaxNumber; /**对账单:业务区域id**/ private Integer businessAreaId; /**对账单:业务区域编码**/ private String businessAreaCode; /**对账单:业务区域名称**/ private String businessAreaName; /**租户id**/ private Integer tenantId; /**是否是关联单中的主单**/ private Boolean isMain; /**是否是关联单**/ private Boolean isRelation; /**开票相关的运单信息**/ private CustomerInvoiceWaybill payload; public String getSourceDocumentNo() { return sourceDocumentNo; } public void setSourceDocumentNo(String sourceDocumentNo) { this.sourceDocumentNo = sourceDocumentNo; } public String getSourceDocumentType() { return sourceDocumentType; } public void setSourceDocumentType(String sourceDocumentType) { this.sourceDocumentType = sourceDocumentType; } public String getBusinessType() { return businessType; } public void setBusinessType(String businessType) { this.businessType = businessType; } public Integer getCustomerId() { return customerId; } public void setCustomerId(Integer customerId) { this.customerId = customerId; } public String getCustomerName() { return customerName; } public void setCustomerName(String customerName) { this.customerName = customerName; } public String getCustomerType() { return customerType; } public void setCustomerType(String customerType) { this.customerType = customerType; } public String getContractCode() { return contractCode; } public void setContractCode(String contractCode) { this.contractCode = contractCode; } public String getSourceDocumentCreateDate() { return sourceDocumentCreateDate; } public void setSourceDocumentCreateDate(String sourceDocumentCreateDate) { this.sourceDocumentCreateDate = sourceDocumentCreateDate; } public String getPlateNumber() { return plateNumber; } public void setPlateNumber(String plateNumber) { this.plateNumber = plateNumber; } public String getVin() { return vin; } public void setVin(String vin) { this.vin = vin; } public Integer getCount() { return count; } public void setCount(Integer count) { this.count = count; } public String getOtherInfo() { return otherInfo; } public void setOtherInfo(String otherInfo) { this.otherInfo = otherInfo; } public BigDecimal getTaxRate() { return taxRate; } public void setTaxRate(BigDecimal taxRate) { this.taxRate = taxRate; } public BigDecimal getAmountIncludeTax() { return amountIncludeTax; } public void setAmountIncludeTax(BigDecimal amountIncludeTax) { this.amountIncludeTax = amountIncludeTax; } public Integer getCompanyId() { return companyId; } public void setCompanyId(Integer companyId) { this.companyId = companyId; } public String getCompanyCode() { return companyCode; } public void setCompanyCode(String companyCode) { this.companyCode = companyCode; } public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } public String getCompanyTaxNumber() { return companyTaxNumber; } public void setCompanyTaxNumber(String companyTaxNumber) { this.companyTaxNumber = companyTaxNumber; } public Integer getBusinessAreaId() { return businessAreaId; } public void setBusinessAreaId(Integer businessAreaId) { this.businessAreaId = businessAreaId; } public String getBusinessAreaCode() { return businessAreaCode; } public void setBusinessAreaCode(String businessAreaCode) { this.businessAreaCode = businessAreaCode; } public String getBusinessAreaName() { return businessAreaName; } public void setBusinessAreaName(String businessAreaName) { this.businessAreaName = businessAreaName; } public Integer getTenantId() { return tenantId; } public void setTenantId(Integer tenantId) { this.tenantId = tenantId; } public Boolean getIsMain() { return isMain; } public void setIsMain(Boolean main) { isMain = main; } public Boolean getIsRelation() { return isRelation; } public void setIsRelation(Boolean relation) { isRelation = relation; } public CustomerInvoiceWaybill getPayload() { return payload; } public void setPayload(CustomerInvoiceWaybill payload) { this.payload = payload; } }
true
8e9a3d518fac6353c93a68cde99bcf7185e8bd07
Java
gjk911/PaoPaoGame
/server/CentreSrv/src/jack911/pp/centre/goods/GoodsInfo.java
UTF-8
2,506
2.40625
2
[]
no_license
package jack911.pp.centre.goods; import org.apache.log4j.Logger; import org.json.JSONObject; import jack911.pp.config.ConfigManager; import jack911.pp.config.table.GoodsTblUnit; import jack911.pp.server.MsgUnit; import jack911.util.JsonUtil; import jack911.util.MyUtil; public class GoodsInfo { private Logger logger = Logger.getLogger(this.getClass()); /** 唯一id */ public long uid = 0; /** 物品位置 */ public int index = 0; /** 物品配置id */ public int cfgId = 0; /** 物品数量 */ public int num = 0; /** 物品基础配置 */ public GoodsTblUnit cfg; /** 可供再增加的数目 */ public int numRoom() { return this.cfg.maxHeap - this.num; } /** 数据是否合法可用 */ public boolean available() { return cfg != null; } public boolean isEquip() { return cfg.type == GoodsType.EQUIP; } /** 作为武器,所处的位置 */ public int equipPos() { switch(cfg.equipType) { case EquipType.HELMET: return 0; case EquipType.NECKLACE: return 1; case EquipType.WEAPON: return 2; case EquipType.CLOTHES: return 3; case EquipType.BELT: return 4; case EquipType.SHOES: return 5; default: return -1; } } public GoodsInfo() { // } /** 创建新的uid */ public void createUid() { this.uid = MyUtil.createUidLong(); } public void create(int cfgId) { this.cfgId = cfgId; createUid(); build(); } protected void build() { this.cfg = ConfigManager.goods.get(cfgId); if(cfg == null) { logger.error("找不到mid=" + cfgId + "的物品"); } } public void write(MsgUnit msg) { msg.writeLong(uid); msg.writeInt(index); msg.writeInt(cfgId); msg.writeInt(num); } public void read(MsgUnit msg) { uid = msg.readLong(); index = msg.readInt(); cfgId = msg.readInt(); num = msg.readInt(); build(); } /** 拷贝 */ public void copy(GoodsInfo source) { this.uid = source.uid; this.index = source.index; this.cfgId = source.cfgId; this.num = source.num; build(); } /** 数据库存储编码 */ public JSONObject encode() { JSONObject jso = new JSONObject(); JsonUtil.putLong(jso, "uid", uid); JsonUtil.putInt(jso, "index", index); JsonUtil.putInt(jso, "cfg", cfgId); JsonUtil.putInt(jso, "num", num); return jso; } /** 数据库存储解码 */ public void decode(JSONObject jso) { uid = JsonUtil.getLong(jso, "uid"); index = JsonUtil.getInt(jso, "index"); cfgId = JsonUtil.getInt(jso, "cfg"); num = JsonUtil.getInt(jso, "num"); } }
true
150250ddca3f39c5cee6f10a18d67bf9a7cc0bb6
Java
Mahendran-Natarajan/Mock_Hack_Workspace
/src/main/java/com/hcl/app/ecommerce/repository/StoreDetailRepository.java
UTF-8
352
1.742188
2
[]
no_license
package com.hcl.app.ecommerce.repository; import com.hcl.app.ecommerce.entity.StoreDetail; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; /** * The interface Store detail repository. */ @Repository public interface StoreDetailRepository extends JpaRepository<StoreDetail, Long> { }
true
bf53f1711d3623a966b125029ec8a8deb62bc2a6
Java
shree8884/Rest_management
/Home.java
UTF-8
2,708
2.609375
3
[]
no_license
package restaurant; import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JTextField; import javax.swing.JLabel; import javax.swing.ImageIcon; import javax.swing.JToggleButton; import javax.swing.JComboBox; import javax.swing.DefaultComboBoxModel; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.Font; import javax.swing.JButton; import java.awt.Color; public class Home extends JFrame { private JPanel contentPane; /** * Launch the application. */ public static Home home_frame = new Home(); public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { Home frame = new Home(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public Home() { setTitle("Retaurant Management System"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 412, 406); contentPane = new JPanel(); contentPane.setBackground(Color.PINK); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JLabel lblFoodAndDrinks = new JLabel("Food And Drinks"); lblFoodAndDrinks.setForeground(Color.WHITE); lblFoodAndDrinks.setBackground(Color.WHITE); lblFoodAndDrinks.setFont(new Font("Tahoma", Font.BOLD, 20)); lblFoodAndDrinks.setBounds(10, 149, 179, 52); contentPane.add(lblFoodAndDrinks); JButton btnDrinks = new JButton("Food\r\n"); btnDrinks.setBackground(Color.BLACK); btnDrinks.setFont(new Font("Tahoma", Font.BOLD, 16)); btnDrinks.setBounds(52, 224, 96, 36); contentPane.add(btnDrinks); btnDrinks.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { new Drinks().setVisible(true); Home.home_frame.setVisible(false); } }); JButton btnFood = new JButton("Drinks"); btnFood.setFont(new Font("Tahoma", Font.BOLD, 16)); btnFood.setBounds(52, 294, 96, 36); contentPane.add(btnFood); JLabel lblNewLabel = new JLabel("New label"); lblNewLabel.setIcon(new ImageIcon("C:\\Users\\Shruthi\\Desktop\\restscreenshots\\fooddrinks5.jpg")); lblNewLabel.setBounds(0, 0, 403, 367); contentPane.add(lblNewLabel); btnFood.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { new Food().setVisible(true); Home.home_frame.setVisible(false); } }); } }
true
b87d1423c5af72f455118661789d1600ec055bc2
Java
sssavundharya/WiproMilestones
/Milestone3/src/Pgm2.java
UTF-8
754
3.390625
3
[]
no_license
import java.util.Scanner; public class Pgm2 { public static void main(String[] args) { Scanner scan=new Scanner(System.in); int n=scan.nextInt(); int opt=scan.nextInt(); int c=1,r=0; switch(opt){ case 1: fun1(n); break; case 2: fun2(n); break; } } public static void fun1(int n){ int c=0,r=0; while((n-c)>=1){ if(c%2==0)r+=(n-c); else r-=(n-c); //System.out.println((n-c)+"->"+r); c++; } System.out.println(r); } public static void fun2(int n){ int c=0,r=0; while((n-c)>=1){ if(c==0)r+=(n-c); else if(c%2==0 && c!=0)r-=(n-c); else r+=(n-c); //System.out.println((n-c)+"->"+r); c++; } System.out.println(r); } }
true
76e409a1a70a19aac9249b57743bad0ece64cca4
Java
rsudev/c-geo-opensource
/main/src/cgeo/geocaching/storage/extension/FoundNumCounter.java
UTF-8
1,265
2.375
2
[ "Apache-2.0" ]
permissive
package cgeo.geocaching.storage.extension; import cgeo.geocaching.storage.DataStore; import androidx.annotation.Nullable; /** * Offline storage for the connector specific found number counter, mainly used in the NUMBER log template. * */ public class FoundNumCounter extends DataStore.DBExtension { private static final DataStore.DBExtensionType type = DataStore.DBExtensionType.DBEXTENSION_FOUNDNUM; private FoundNumCounter(final DataStore.DBExtension copyFrom) { super(copyFrom); } public int getCounter(final boolean incrementCounter) { return (int) (incrementCounter ? getLong1() + 1 : getLong1()); } @Nullable public static FoundNumCounter load(final String serviceName) { final DataStore.DBExtension temp = load(type, serviceName); return null == temp ? null : new FoundNumCounter(temp); } public static void updateFoundNum(final String serviceName, final int foundNum) { //avoid recreation of same key/value pair final FoundNumCounter f = load(serviceName); if (f != null && f.getCounter(false) == foundNum) { return; } removeAll(type, serviceName); add(type, serviceName, foundNum, 0, 0, 0, "", "", "", ""); } }
true
5a2a0d37cdce7626be0adcb8926a859670b7af1d
Java
MaddisonK/COMP-301-Foundations-of-Programming
/a08-shopping-MaddisonK-main/a08-shopping-MaddisonK-main/src/main/java/com/comp301/a08shopping/Customer.java
UTF-8
1,019
3.25
3
[]
no_license
package com.comp301.a08shopping; import java.util.List; public interface Customer extends StoreObserver { /** Gets the customer's name */ String getName(); /** Gets the amount of money that the customer currently has (in dollars) */ double getBudget(); /** * Purchases a particular product from a store by performing the following actions, in order: * * <p>1. If the sale price of the product costs more money then the customer has, throw an * IllegalStateException exception * * <p>2. Decrease the customer's money by the sale price of the product * * <p>3. Purchase the object from the store by calling store.purchaseProduct() * * <p>4. Add the returned ReceiptItem from the store to the customer's purchase history */ void purchaseProduct(Product product, Store store); /** * Gets a list of the products that the customer has purchased (Note: The returned value should be * a copy of the encapsulated field) */ List<ReceiptItem> getPurchaseHistory(); }
true
0a512756033b7a433cd23c23f0a179c2dfab078d
Java
kathy-a/udacity-BakingApp
/app/src/main/java/com/udacity/baking/MainActivity.java
UTF-8
5,155
2.390625
2
[]
no_license
package com.udacity.baking; import androidx.appcompat.app.AppCompatActivity; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProviders; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.annotation.SuppressLint; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.util.Log; import com.udacity.baking.database.RecipeIngredientDetails; import com.udacity.baking.database.RecipeIngredientsEntity; import com.udacity.baking.database.RecipeStepDetails; import com.udacity.baking.database.RecipeStepsEntity; import com.udacity.baking.model.Recipe; import com.udacity.baking.network.AssertConnectivity; import com.udacity.baking.ui.RecipeViewAdapter; import com.udacity.baking.viewmodel.MainViewModel; import java.util.List; public class MainActivity extends AppCompatActivity { private RecyclerView mRecyclerView; private RecipeViewAdapter mAdapter; private static final String TAG = "MAIN ACTIVITY"; public static boolean sIsTablet; private MainViewModel mViewModel; @SuppressLint("SourceLockedOrientationActivity") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Set device orientation supported boolean allowRotation = getResources().getBoolean(R.bool.portrait_only); if(allowRotation){ setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); sIsTablet = false; }else{ sIsTablet = true; } new AssertConnectivity(MainActivity.this); if(AssertConnectivity.isOnline()){ initViewModel(); }else { AssertConnectivity.errorConnectMessage(); } } private void initViewModel() { // set the reference for view model mViewModel = ViewModelProviders.of(this) .get(MainViewModel.class); // Get and observe recipelist from webservice mViewModel.getRecipeListObservable().observe(this, new Observer<List<Recipe>>() { @Override public void onChanged(List<Recipe> recipes) { if (recipes != null){ initRecyclerView(recipes); // Add recipe to DB addRecipeList(recipes); } } } ); //logDisplayRecipeSteps(); //logDisplayRecipeIngredients(); } // Display recipe steps in log private void logDisplayRecipeSteps() { // Get recipeStep from DB mViewModel.getRecipeStepDetails().observe(this, new Observer<List<RecipeStepDetails>>() { @Override public void onChanged(List<RecipeStepDetails> recipeStepDetails) { if(recipeStepDetails != null){ String recipeName; recipeName = recipeStepDetails.get(1).getRecipeEntity().getName(); Log.d(TAG, recipeName); List<RecipeStepsEntity> recipeSteps = recipeStepDetails.get(0).getSteps(); for(int i = 0; i < recipeSteps.size(); i++){ String description; description = recipeSteps.get(i).getDescription(); Log.d(TAG, description); } }else{ Log.d(TAG, "Recipe Step details null"); } } }); } // Display recipe ingredients in log private void logDisplayRecipeIngredients() { mViewModel.getRecipeIngredientDetails().observe(this, new Observer<List<RecipeIngredientDetails>>() { @Override public void onChanged(List<RecipeIngredientDetails> recipeIngredientDetails) { if(recipeIngredientDetails != null){ List<RecipeIngredientsEntity> recipeIngredients = recipeIngredientDetails.get(1).getIngredients(); for(int i = 0; i < recipeIngredients.size(); i++){ String ingredient; ingredient = recipeIngredients.get(i).getIngredient(); Log.d(TAG, "Ingredient: " + ingredient); } }else{ Log.d(TAG, "Recipe Ingredient details null"); } } }); } // Add recipe list to local storage private void addRecipeList(List<Recipe> recipes) { mViewModel.addRecipeData(recipes); } private void initRecyclerView(List<Recipe> recipeList) { mRecyclerView = findViewById(R.id.recycler_MainActivity); mAdapter = new RecipeViewAdapter(this, recipeList); int gridsize; if(sIsTablet){ gridsize = 4; }else{ gridsize = 2; } mRecyclerView.setLayoutManager(new GridLayoutManager(this, gridsize)); mRecyclerView.setAdapter(mAdapter); } }
true
2a5aa499ef4576ea28dd596e701f01624b74c56a
Java
arianr2014/EduCorpMiddleware
/src/com/educorp/eduinteractive/ecommerce/dao/impl/HorarioDAOImpl.java
WINDOWS-1250
10,170
2.375
2
[]
no_license
package com.educorp.eduinteractive.ecommerce.dao.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.educorp.eduinteractive.ecommerce.dao.service.DAOUtils; import com.educorp.eduinteractive.ecommerce.dao.service.JDBCUtils; import com.educorp.eduinteractive.ecommerce.dao.service.Results; import com.educorp.eduinteractive.ecommerce.dao.spi.HorarioDAO; import com.educorp.eduinteractive.ecommerce.exceptions.DataException; import com.educorp.eduinteractive.ecommerce.exceptions.DuplicateInstanceException; import com.educorp.eduinteractive.ecommerce.exceptions.InstanceNotFoundException; import com.educorp.eduinteractive.ecommerce.model.Horario; public class HorarioDAOImpl implements HorarioDAO{ private Logger logger = LogManager.getLogger(HorarioDAOImpl.class); @Override public Horario findById(Connection connection, Integer id) throws InstanceNotFoundException, DataException { if(logger.isDebugEnabled()) logger.debug("id: {}", id); Horario h = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { String sql; sql = "SELECT ID_HORARIO, ID_PROFESOR, ID_DIA, ID_HORA " +"FROM HORARIO " +"WHERE ID_HORARIO = ? "; if(logger.isDebugEnabled()) logger.debug(sql); // Preparar a query preparedStatement = connection.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); // Establece os parmetros int i = 1; preparedStatement.setLong(i++, id); resultSet = preparedStatement.executeQuery(); //STEP 5: Extract data from result set if (resultSet.next()) { h = loadNext(resultSet); } else { if(logger.isDebugEnabled()) logger.debug("Non se encontrou o horario {}", id); } if (resultSet.next()) { if(logger.isDebugEnabled()) logger.debug("horario {} duplicado", id); } } catch (SQLException ex) { logger.warn(ex.getMessage(), ex); throw new DataException(ex); } finally { JDBCUtils.closeResultSet(resultSet); JDBCUtils.closeStatement(preparedStatement); } return h; } @Override public Results<Horario> findBy(Connection connection, Integer idProfesor, Integer idDia, Date fecha, int startIndex, int count) throws DataException { if(logger.isDebugEnabled()) logger.debug("Busqueda= idProfesor: {}; idDia: {}; fecha: {}", idProfesor, idDia, fecha); PreparedStatement preparedStatement = null; ResultSet resultSet = null; StringBuilder queryString = null; try { queryString = new StringBuilder( "SELECT ID_HORARIO, ID_PROFESOR, ID_DIA, ID_HORA " +" FROM HORARIO " + " where id_horario not in (SELECT ID_HORARIO " + " FROM sesion " + " where fecha_sesion = ? and id_profesor = ? and (id_estado = 'S' || id_estado = 'A')) " + " and id_profesor = ? and id_dia = ? " ); if(logger.isDebugEnabled()) logger.debug(queryString); preparedStatement = connection.prepareStatement(queryString.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); int i = 1; preparedStatement.setDate(i++, new java.sql.Date(fecha.getTime())); preparedStatement.setInt(i++, idProfesor); preparedStatement.setInt(i++, idProfesor); preparedStatement.setInt(i++, idDia); resultSet = preparedStatement.executeQuery(); List<Horario> horarios = new ArrayList<Horario>(); Horario h = null; int currentCount = 0; if((startIndex >= 1) && resultSet.absolute(startIndex)) { do { h = loadNext(resultSet); horarios.add(h); currentCount++; }while((currentCount < count) && resultSet.next()); } int totalRows = JDBCUtils.getTotalRows(resultSet); if(logger.isDebugEnabled()) logger.debug("Total rows: " + totalRows); Results<Horario> results = new Results<Horario>(horarios, startIndex, totalRows); return results; } catch (SQLException e) { logger.warn(e.getMessage(), e); throw new DataException(e); } finally { JDBCUtils.closeResultSet(resultSet); JDBCUtils.closeStatement(preparedStatement); } } @Override public void update(Connection connection, Horario h) throws InstanceNotFoundException, DataException { if(logger.isDebugEnabled()) logger.debug("Horario= idHorario: {}; idProfesor: {}; idDia: {}; idHora: {}", h.getIdHorario(), h.getIdProfesor(), h.getIdDia(), h.getIdHora()); PreparedStatement preparedStatement = null; StringBuilder queryString = null; try { queryString = new StringBuilder( " UPDATE HORARIO" ); boolean first = true; if (h.getIdHorario() != null) { DAOUtils.addUpdate(queryString, first, " ID_HORARIO = ? "); first = false; } if (h.getIdProfesor() != null) { DAOUtils.addUpdate(queryString, first, " ID_PROFESOR = ? "); first = false; } if (h.getIdDia() != null) { DAOUtils.addUpdate(queryString, first, " ID_DIA = ? "); first = false; } if (h.getIdHora() != null) { DAOUtils.addUpdate(queryString, first, " ID_HORA = ? "); first = false; } queryString.append("WHERE ID_PROFESOR = ?"); if(logger.isDebugEnabled()) logger.debug(queryString); preparedStatement = connection.prepareStatement(queryString.toString()); int i = 1; if (h.getIdHorario() != null) preparedStatement.setInt(i++, h.getIdHorario()); if (h.getIdProfesor() != null) preparedStatement.setInt(i++, h.getIdProfesor()); if (h.getIdDia() != null) preparedStatement.setInt(i++, h.getIdDia()); if (h.getIdHora() != null) preparedStatement.setInt(i++, h.getIdHora()); int updatedRows = preparedStatement.executeUpdate(); if (updatedRows == 0) { if(logger.isDebugEnabled()) logger.debug("Non se actualizou o horario {}", h.getIdHorario()); } if (updatedRows > 1) { if(logger.isDebugEnabled()) logger.debug("Duplicate row from id_horario = {}", h.getIdHorario()); } } catch (SQLException ex) { logger.warn(ex.getMessage(), ex); throw new DataException(ex); } finally { JDBCUtils.closeStatement(preparedStatement); } } @Override public Horario create(Connection connection, Horario h) throws DuplicateInstanceException, DataException { if(logger.isDebugEnabled()) logger.debug("Horario= idHorario: {}; idProfesor: {}; idDia: {}; idHora: {}", h.getIdHorario(), h.getIdProfesor(), h.getIdDia(), h.getIdHora()); PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { // Creamos el preparedstatement String queryString = "INSERT INTO HORARIO (ID_PROFESOR, ID_DIA, ID_HORA) " + "VALUES (?, ?, ?)"; if(logger.isDebugEnabled()) logger.debug(queryString); preparedStatement = connection.prepareStatement(queryString, Statement.RETURN_GENERATED_KEYS); // Rellenamos el "preparedStatement" int i = 1; preparedStatement.setInt(i++, h.getIdProfesor()); preparedStatement.setInt(i++, h.getIdDia()); preparedStatement.setInt(i++, h.getIdHora()); // Execute query int insertedRows = preparedStatement.executeUpdate(); if (insertedRows == 0) { if(logger.isDebugEnabled()) logger.debug("Can not add row to table 'Horario'"); } // Recuperamos la PK generada resultSet = preparedStatement.getGeneratedKeys(); if (resultSet.next()) { Integer pk = resultSet.getInt(1); h.setIdHorario(pk); } else { if(logger.isDebugEnabled()) logger.debug("Unable to fetch autogenerated primary key"); } // Return the DTO return h; } catch (SQLException ex) { logger.warn(ex.getMessage(), ex); throw new DataException(ex); } finally { JDBCUtils.closeResultSet(resultSet); JDBCUtils.closeStatement(preparedStatement); } } @Override public Horario delete(Connection connection, Horario h) throws DataException { return null; } @Override public List<Horario> findByProfesor(Connection connection, Integer idProfesor) throws DataException { if(logger.isDebugEnabled()) logger.debug("idProfesor = {} ", idProfesor); PreparedStatement preparedStatement = null; ResultSet resultSet = null; try{ String sql; sql = "SELECT ID_HORARIO, ID_PROFESOR, ID_DIA, ID_HORA " +" FROM HORARIO " +" WHERE ID_PROFESOR = ? "; // Preparar a query if(logger.isDebugEnabled()) logger.debug(sql); preparedStatement = connection.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); // Establece os parmetros int i = 1; preparedStatement.setInt(i++, idProfesor); resultSet = preparedStatement.executeQuery(); //STEP 5: Extract data from result set List<Horario> horarios = new ArrayList<Horario>(); Horario e = null; while (resultSet.next()) { e = loadNext(resultSet); horarios.add(e); } return horarios; } catch (SQLException ex) { logger.warn(ex.getMessage(), ex); throw new DataException("Non se encontrou o horario para o profesor " + idProfesor); } finally { JDBCUtils.closeResultSet(resultSet); JDBCUtils.closeStatement(preparedStatement); } } private Horario loadNext(ResultSet resultSet) throws SQLException, DataException { Horario h = new Horario(); int i = 1; Integer idHorario = resultSet.getInt(i++); Integer idProfesor = resultSet.getInt(i++); Integer idDia = resultSet.getInt(i++); Integer idHora = resultSet.getInt(i++); h = new Horario(); h.setIdHorario(idHorario); h.setIdProfesor(idProfesor); h.setIdDia(idDia); h.setIdHora(idHora); return h; } }
true
b4321b4d6114a0ebf67453f7596b606fe286750e
Java
Xarhel/GestionMagasin
/GestionMagasin-ejb/src/java/facades/ReclamationLotFacadeLocal.java
UTF-8
697
1.921875
2
[]
no_license
/* * 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 facades; import Entites.Autre.ReclamationLot; import java.util.List; import javax.ejb.Local; /** * * @author 3137574 */ @Local public interface ReclamationLotFacadeLocal { void create(ReclamationLot reclamationLot); void edit(ReclamationLot reclamationLot); void remove(ReclamationLot reclamationLot); ReclamationLot find(Object id); List<ReclamationLot> findAll(); List<ReclamationLot> findRange(int[] range); int count(); }
true
460c0adbc64c1bf21abf0bc17de75201707b147b
Java
Minionguyjpro/Ghostly-Skills
/sources/com/facebook/ads/AdSettings.java
UTF-8
5,244
1.804688
2
[ "MIT" ]
permissive
package com.facebook.ads; import android.content.Context; import com.facebook.ads.internal.settings.AdInternalSettings; import java.io.Serializable; import java.util.Collection; public class AdSettings { public static final boolean DEBUG = false; public enum IntegrationErrorMode { INTEGRATION_ERROR_CRASH_DEBUG_MODE, INTEGRATION_ERROR_CALLBACK_MODE; public static final long serialVersionUID = 1; } public enum TestAdType implements Serializable { DEFAULT("DEFAULT", "Default"), IMG_16_9_APP_INSTALL("IMG_16_9_APP_INSTALL", "Image App install"), IMG_16_9_LINK("IMG_16_9_LINK", "Image link"), VIDEO_HD_16_9_46S_APP_INSTALL("VID_HD_16_9_46S_APP_INSTALL", "Video 46 sec App install"), VIDEO_HD_16_9_46S_LINK("VID_HD_16_9_46S_LINK", "Video 46 sec link"), VIDEO_HD_16_9_15S_APP_INSTALL("VID_HD_16_9_15S_APP_INSTALL", "Video 15 sec App install"), VIDEO_HD_16_9_15S_LINK("VID_HD_16_9_15S_LINK", "Video 15 sec link"), VIDEO_HD_9_16_39S_APP_INSTALL("VID_HD_9_16_39S_APP_INSTALL", "Video 39 sec App install"), VIDEO_HD_9_16_39S_LINK("VID_HD_9_16_39S_LINK", "Video 39 sec link"), CAROUSEL_IMG_SQUARE_APP_INSTALL("CAROUSEL_IMG_SQUARE_APP_INSTALL", "Carousel App install"), CAROUSEL_IMG_SQUARE_LINK("CAROUSEL_IMG_SQUARE_LINK", "Carousel link"), PLAYABLE("PLAYABLE", "Playable ad"); public static final long serialVersionUID = 1; private final String adTypeString; private final String humanReadable; private TestAdType(String str, String str2) { this.adTypeString = str; this.humanReadable = str2; } public String getAdTypeString() { return this.adTypeString; } public String getHumanReadable() { return this.humanReadable; } } public static void setDebugBuild(boolean z) { AdInternalSettings.setDebugBuild(z); } public static void turnOnSDKDebugger(Context context) { AdInternalSettings.turnOnSDKDebugger(context); } public static void addTestDevice(String str) { AdInternalSettings.addTestDevice(str); } public static void addTestDevices(Collection<String> collection) { AdInternalSettings.addTestDevices(collection); } public static void clearTestDevices() { AdInternalSettings.clearTestDevices(); } public static boolean isTestMode(Context context) { return AdInternalSettings.isTestMode(context); } public static void setTestMode(boolean z) { AdInternalSettings.setTestMode(z); } public static void setUrlPrefix(String str) { AdInternalSettings.setUrlPrefix(str); } public static String getUrlPrefix() { return AdInternalSettings.getUrlPrefix(); } public static boolean isVideoAutoplay() { return AdInternalSettings.isVideoAutoplay(); } public static boolean isVideoAutoplayOnMobile() { return AdInternalSettings.isVideoAutoplayOnMobile(); } public static void setVideoAutoplay(boolean z) { AdInternalSettings.setVideoAutoplay(z); } public static void setVideoAutoplayOnMobile(boolean z) { AdInternalSettings.setVideoAutoplayOnMobile(z); } public static void setMediationService(String str) { AdInternalSettings.setMediationService(str); } public static String getMediationService() { return AdInternalSettings.getMediationService(); } public static void setMixedAudience(boolean z) { AdInternalSettings.sSettingsBundle.putBoolean(AdInternalSettings.BOOL_MIXED_AUDIENCE_KEY, z); } public static boolean isMixedAudience() { return AdInternalSettings.sSettingsBundle.getBoolean(AdInternalSettings.BOOL_MIXED_AUDIENCE_KEY, false); } public static void setTestAdType(TestAdType testAdType) { AdInternalSettings.sSettingsBundle.putSerializable(AdInternalSettings.TEST_AD_TYPE_KEY, testAdType); } public static TestAdType getTestAdType() { Serializable serializable = AdInternalSettings.sSettingsBundle.getSerializable(AdInternalSettings.TEST_AD_TYPE_KEY); if (serializable != null && (serializable instanceof TestAdType)) { return (TestAdType) serializable; } AdInternalSettings.sSettingsBundle.putSerializable(AdInternalSettings.TEST_AD_TYPE_KEY, TestAdType.DEFAULT); return TestAdType.DEFAULT; } public static void setVisibleAnimation(boolean z) { AdInternalSettings.setVisibleAnimation(z); } public static void setIntegrationErrorMode(IntegrationErrorMode integrationErrorMode) { AdInternalSettings.sSettingsBundle.putSerializable(AdInternalSettings.SRL_INTEGRATION_ERROR_MODE_KEY, integrationErrorMode); } public static void setDataProcessingOptions(String[] strArr) { AdInternalSettings.setDataProcessingOptions(strArr, (Integer) null, (Integer) null); } public static void setDataProcessingOptions(String[] strArr, int i, int i2) { AdInternalSettings.setDataProcessingOptions(strArr, Integer.valueOf(i), Integer.valueOf(i2)); } }
true
e4ab70216ee459d0ac8a68a50e76255ee82df9b8
Java
SatyaRaghuNandan/designpatterns
/abstractfactory/ShapeFactory.java
UTF-8
375
3.0625
3
[]
no_license
package com.saftware.pattern.abstractfactory; public class ShapeFactory extends AbstractFactory { public Shape getShape(String type){ if(type.equalsIgnoreCase("Circle")){ return new Circle(); }else if(type.equalsIgnoreCase("Rectangle")){ return new Rectangle(); }else return null; } @Override public Color getColor(String choice) { return null; } }
true
dd2d17450f90ee378d3995844aeb344abfc230c8
Java
informatique-cdc/ebad
/src/main/java/fr/icdc/ebad/web/rest/dto/ChaineAssociationDto.java
UTF-8
350
1.726563
2
[ "Apache-2.0" ]
permissive
package fr.icdc.ebad.web.rest.dto; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; /** * Created by dtrouillet on 13/06/2016. */ @Data @EqualsAndHashCode(exclude = {"batch"}) @ToString(exclude = {"batch"}) public class ChaineAssociationDto { private int batchOrder; private ChaineAssociationBatchDto batch; }
true
4d1e991c7ca37975ace11a249bb850cb61e75190
Java
yinkaf/CurrencyApp
/app/src/main/java/com/xipsoft/currency/app/services/CurrencyService.java
UTF-8
2,798
2.328125
2
[]
no_license
package com.xipsoft.currency.app.services; import android.app.IntentService; import android.content.Intent; import android.os.Bundle; import android.os.Parcel; import android.os.ResultReceiver; import android.text.TextUtils; import com.xipsoft.currency.app.Constants; import com.xipsoft.currency.app.helpers.CurrencyParserHelper; import com.xipsoft.currency.app.receivers.CurrencyReceiver; import com.xipsoft.currency.app.utils.LogUtils; import com.xipsoft.currency.app.utils.WebServiceUtils; import com.xipsoft.currency.app.value_objects.Currency; import org.json.JSONObject; /** * Created by yinka on 2/3/16. */ public class CurrencyService extends IntentService { public static final String TAG = CurrencyService.class.getName(); /** * Creates an IntentService. Invoked by your subclass's constructor. * * @param name Used to name the worker thread, important only for debugging. */ public CurrencyService(String name) { super(TAG); } public CurrencyService(){ super(TAG); } @Override protected void onHandleIntent(Intent intent) { LogUtils.log(TAG,"Currency Service has started"); Bundle intentBundle = intent.getBundleExtra(Constants.BUNDLE); final ResultReceiver resultReceiver = intentBundle.getParcelable(Constants.RECEIVER); Parcel parcel = Parcel.obtain(); resultReceiver.writeToParcel(parcel,0); parcel.setDataPosition(0); ResultReceiver resultReceiverForSending = ResultReceiver.CREATOR.createFromParcel(parcel); parcel.recycle(); String url = intentBundle.getString(Constants.URL); String currencyName = intentBundle.getString(Constants.CURRENCY_NAME); Bundle bundle = new Bundle(); if(url != null && !TextUtils.isEmpty(url)){ resultReceiverForSending.send(Constants.STATUS_RUNNING, Bundle.EMPTY); if(WebServiceUtils.hasInternetConnection(getApplicationContext())){ try { JSONObject obj = WebServiceUtils.requestJSONObject(url); if(obj != null){ Currency currency = CurrencyParserHelper.parseCurrency(obj, currencyName); bundle.putParcelable(Constants.RESULT,currency); resultReceiverForSending.send(Constants.STATUS_FINISHED,bundle); } } catch (Exception e) { bundle.putString(Intent.EXTRA_TEXT,e.getMessage()); resultReceiverForSending.send(Constants.STATUS_ERROR,bundle); } }else{ LogUtils.log(TAG,"No Internet Connection."); } } LogUtils.log(TAG,"Currency Service Stopped!"); stopSelf(); } }
true
28991563ad48496486c337025f627eba692d4a29
Java
jaya429/CoreJavaProject
/CoreJava/src/com/svr/threads/MyThread.java
UTF-8
258
2.375
2
[]
no_license
/** * */ package com.svr.threads; /** * @author Venkata Saripella * */ public class MyThread extends Thread { @Override public void run(){ for(Integer i=0; i<10; i++){ System.out.println("child thread :: "+i); } } }
true
508c91b1028be09f5653ecf36b95b4deefe6dc66
Java
gaurav-4uk/JAVATechnoMar2021
/src/shivani/coding_exam_13/ReturnWordwithTwoVowel.java
UTF-8
1,277
3.703125
4
[]
no_license
package shivani.coding_exam_13; import java.util.ArrayList; /*2. Return all the words having more than two vowels from given array. input: ["aashay","sandesh","madhavi","ankit","ami","priyanka"] output: ["aashay","madhavi","priyanka"]*/ public class ReturnWordwithTwoVowel { ArrayList<String> getVowels(String[] names) { ArrayList<String> output = new ArrayList<String>(); for (int i = 0; i < names.length; i++) { int count = 0; boolean flag = false; for (int innerIndex = 0; innerIndex < names[i].length(); innerIndex++) { String ch = String.valueOf(names[i].charAt(innerIndex)); if (ch.equalsIgnoreCase("a") || ch.equalsIgnoreCase("e") || ch.equalsIgnoreCase("i") || ch.equalsIgnoreCase("o") || ch.equalsIgnoreCase("u")) { count++; if (count > 2) { flag = true; break; } } } if (flag) { output.add(names[i]); } } return output; } public static void main(String[] args) { String input[]= {"Shivani","Sakshi","deepa","Anjali","Saloni"}; ReturnWordwithTwoVowel returnWordwithTwoVowel = new ReturnWordwithTwoVowel(); ArrayList<String> output = new ArrayList<String>(); output=returnWordwithTwoVowel.getVowels(input); System.out.println("output"+output); } }
true
fb3c05a4f1038a1c8fa208bc14e7d44a710ce428
Java
Ajmat5392/IOCProj1
/src/edu/aptech/test/ClientApp.java
UTF-8
1,068
2.3125
2
[]
no_license
package edu.aptech.test; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import edu.aptech.bean.Test; public class ClientApp { public static void main(String[] args) { Resource resource=new ClassPathResource("edu/aptech/cfgs/spring.xml"); BeanFactory factory=new XmlBeanFactory(resource); Test test=(Test)factory.getBean("t"); test.syaHello(); Test test1=(Test)factory.getBean("t"); test1.syaHello(); Test test2=(Test)factory.getBean("t"); test2.syaHello(); //Using Advanced Container /*ApplicationContext ctx=new ClassPathXmlApplicationContext("edu/aptech/cfgs/spring.xml"); Test t11=(Test)ctx.getBean("t"); t11.syaHello(); Test t12=(Test)ctx.getBean("t"); t12.syaHello(); Test t13=(Test)ctx.getBean("t"); t13.syaHello();*/ } }
true
231952287137f5256d14c477beaedbce73a7c575
Java
learning-layers/Expert-Identification-Service
/src/main/i5/las2peer/services/servicePackage/utils/AlgorithmType.java
UTF-8
356
1.5
2
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
/** * */ package i5.las2peer.services.servicePackage.utils; /** * @author sathvik * */ public class AlgorithmType { public static final String PAGE_RANK = "pagerank"; public static final String HITS = "hits"; public static final String CA_PR = "communityAwarePagerank"; public static final String CA_HITS = "communityAwareHITS"; }
true
c3817af03304ea37e88d8d0c42e91d792c0d8752
Java
ThanhHang29/CustomView
/app/src/main/java/com/ttth/myview/MyView.java
UTF-8
4,142
2.515625
3
[]
no_license
package com.ttth.myview; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Point; import android.util.AttributeSet; import android.view.View; import java.util.Random; /** * Created by Thanh Hang on 16/01/17. */ public class MyView extends View { private Paint mPaint; private QuaDrangle quaDrangle, parallelogram, retangle, square, diamond, traingle, trapezium, oval, circle; public MyView(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init() { mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setStrokeWidth(10); mPaint.setStyle(Paint.Style.STROKE); initQuaDrangle(); initParallelogram(); initRetangle(); initSquare(); initDiamond(); initTraingle(); initTrapezium(); initCircle(); initOval(); } private void initOval() { Point point = new Point(50, 350); Point point1 = new Point(); oval = new QuaDrangle(point, point1); oval.caculOval(50, 90); } // hình tròn private void initCircle() { Point point = new Point(250, 100); Point point1 = new Point(); circle = new QuaDrangle(point, point1); circle.caculCircle(80); } // hình thang private void initTrapezium() { Point point = new Point(250, 100); Point point1 = new Point(); Point point2 = new Point(); Point point3 = new Point(); trapezium = new QuaDrangle(point, point1, point2, point3); trapezium.trapezium(200,70,90,120, true); } //tam giác private void initTraingle() { Point point = new Point(100, 500); Point point1 = new Point(40, 100); Point point2 = new Point(140, 200); traingle = new QuaDrangle(point, point1, point2); } // hình thoi private void initDiamond() { Point point = new Point(100, 500); Point point1 = new Point(); Point point2 = new Point(); Point point3 = new Point(); diamond = new QuaDrangle(point, point1, point2, point3); diamond.diamond(200, 50); } private void initSquare() { Point point = new Point(300, 500); Point point1 = new Point(); Point point2 = new Point(); Point point3 = new Point(); square = new QuaDrangle(point, point1, point2, point3); square.square(150); } private void initRetangle() { Point point = new Point(300, 300); Point point1 = new Point(); Point point2 = new Point(); Point point3 = new Point(); retangle = new QuaDrangle(point, point1, point2, point3); retangle.retangle(200, 100); } // hình bình hành private void initParallelogram() { Point point = new Point(100, 100); Point point1 = new Point(); Point point2 = new Point(); Point point3 = new Point(); parallelogram = new QuaDrangle(point, point1, point2, point3); parallelogram.parallelogram(250, 300, 70, true); } // tứ giác private void initQuaDrangle() { Point point1 = new Point(100, 50); Point point2 = new Point(120, 100); Point point3 = new Point(70, 120); Point point4 = new Point(20, 80); quaDrangle = new QuaDrangle(point1,point2,point3,point4); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); quaDrangle.drawShape(canvas, mPaint,150, 70, 60); parallelogram.drawShape(canvas, mPaint,200, 230, 70); retangle.drawShape(canvas, mPaint,30, 60, 100); square.drawShape(canvas, mPaint, 250, 30, 190); diamond.drawShape(canvas, mPaint, 190, 60, 190); traingle.drawTraingle(canvas, mPaint, 250, 50, 100); trapezium.drawShape(canvas, mPaint, 240, 250, 180); circle.drawMyOval(canvas, mPaint, 150, 60, 190); oval.drawMyOval(canvas, mPaint, 190, 80, 200); } }
true
8ac49da66094f92b5370c4f2a40b6622854fe75c
Java
atiqamjad/SupplyChain-EE
/scs-ee-web-api/src/main/java/com/nowgroup/scsee/packingList/PackingList.java
UTF-8
22,166
1.65625
2
[ "MIT" ]
permissive
/** * Copyright 2016 https://github.com/diego-torres * * Licensed under the MIT License (MIT). * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sub-license, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.nowgroup.scsee.packingList; import java.math.BigDecimal; import java.util.Date; import java.util.HashSet; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.UniqueConstraint; import org.hibernate.annotations.ColumnDefault; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.nowgroup.scsee.cat.assessmentMethod.AssessmentMethod; import com.nowgroup.scsee.cat.bundleType.BundleType; import com.nowgroup.scsee.cat.company.Company; import com.nowgroup.scsee.cat.currency.Currency; import com.nowgroup.scsee.cat.customsRegime.CustomsRegime; import com.nowgroup.scsee.cat.incoterm.Incoterm; import com.nowgroup.scsee.cat.part.Part; import com.nowgroup.scsee.cat.unit.Unit; import com.nowgroup.scsee.geo.country.Country; import com.nowgroup.scsee.model.BaseGenericModel; /** * @author https://github.com/diego-torres * */ @Entity @Table(name = "packing_list", uniqueConstraints = { @UniqueConstraint(columnNames = { "folio", "seller_company_id" }, name = "ux_packing_list_seller_folio") }) @JsonIgnoreProperties({ "hibernateLazyInitializer", "handler" }) public class PackingList extends BaseGenericModel { private static final long serialVersionUID = 1L; private String folio; private Date packingListDate; private String purchaseOrderFolio; private String salesOrderFolio; private String incontermLocation; private Integer bundleQuantity; private String bundleComment; private String publicComments; private String internalComments; private String instructions; private String additionalInstructions; private Boolean blocked; private Currency currency; private Incoterm inconterm; private Country originCountry; private CustomsRegime customsRegime; private AssessmentMethod assessmentMethod; private BundleType bundleType; private Company purchaser; private Company seller; private Company sender; private Company receiver; private Set<PackingListItem> items = new HashSet<>(); /** * */ public PackingList() { super(); } /** * @param folio * @param packingListDate * @param purchaseOrderFolio * @param salesOrderFolio * @param incontermLocation * @param bundleQuantity * @param bundleComment * @param publicComments * @param internalComments * @param instructions * @param additionalInstructions * @param blocked * @param currency * @param inconterm * @param originCountry * @param customsRegime * @param assessmentMethod * @param bundleType * @param purchaser * @param seller * @param sender * @param receiver * @param items */ public PackingList( String folio, Date packingListDate, String purchaseOrderFolio, String salesOrderFolio, String incontermLocation, Integer bundleQuantity, String bundleComment, String publicComments, String internalComments, String instructions, String additionalInstructions, Boolean blocked, Currency currency, Incoterm inconterm, Country originCountry, CustomsRegime customsRegime, AssessmentMethod assessmentMethod, BundleType bundleType, Company purchaser, Company seller, Company sender, Company receiver, Set<PackingListItem> items) { this.folio = folio; this.packingListDate = packingListDate; this.purchaseOrderFolio = purchaseOrderFolio; this.salesOrderFolio = salesOrderFolio; this.incontermLocation = incontermLocation; this.bundleQuantity = bundleQuantity; this.bundleComment = bundleComment; this.publicComments = publicComments; this.internalComments = internalComments; this.instructions = instructions; this.additionalInstructions = additionalInstructions; this.blocked = blocked; this.currency = currency; this.inconterm = inconterm; this.originCountry = originCountry; this.customsRegime = customsRegime; this.assessmentMethod = assessmentMethod; this.bundleType = bundleType; this.purchaser = purchaser; this.seller = seller; this.sender = sender; this.receiver = receiver; this.items = items; } /** * @return the folio */ @Column(length = 50) public String getFolio() { return folio; } /** * @param folio * the folio to set */ public void setFolio(String folio) { this.folio = folio; } /** * @return the packingListDate */ @Column @Temporal(TemporalType.DATE) public Date getPackingListDate() { return packingListDate; } /** * @param packingListDate * the packingListDate to set */ public void setPackingListDate(Date packingListDate) { this.packingListDate = packingListDate; } /** * @return the purchaseOrderFolio */ @Column(name = "purchase_order_folio", length = 50) public String getPurchaseOrderFolio() { return purchaseOrderFolio; } /** * @param purchaseOrderFolio * the purchaseOrderFolio to set */ public void setPurchaseOrderFolio(String purchaseOrderFolio) { this.purchaseOrderFolio = purchaseOrderFolio; } /** * @return the salesOrderFolio */ @Column(name = "sales_order_folio", length = 50) public String getSalesOrderFolio() { return salesOrderFolio; } /** * @param salesOrderFolio * the salesOrderFolio to set */ public void setSalesOrderFolio(String salesOrderFolio) { this.salesOrderFolio = salesOrderFolio; } /** * @return the incontermLocation */ @Column(name = "incoterm_location", length = 150) public String getIncontermLocation() { return incontermLocation; } /** * @param incontermLocation * the incontermLocation to set */ public void setIncontermLocation(String incontermLocation) { this.incontermLocation = incontermLocation; } /** * @return the bundleQuantity */ @Column(name = "bundle_quantity") public Integer getBundleQuantity() { return bundleQuantity; } /** * @param bundleQuantity * the bundleQuantity to set */ public void setBundleQuantity(Integer bundleQuantity) { this.bundleQuantity = bundleQuantity; } /** * @return the bundleComment */ @Column(name = "bundle_comment", length = 150) public String getBundleComment() { return bundleComment; } /** * @param bundleComment * the bundleComment to set */ public void setBundleComment(String bundleComment) { this.bundleComment = bundleComment; } /** * @return the publicComments */ @Column(name = "public_comments", length = 250) public String getPublicComments() { return publicComments; } /** * @param publicComments * the publicComments to set */ public void setPublicComments(String publicComments) { this.publicComments = publicComments; } /** * @return the internalComments */ @Column(name = "internal_comments", length = 250) public String getInternalComments() { return internalComments; } /** * @param internalComments * the internalComments to set */ public void setInternalComments(String internalComments) { this.internalComments = internalComments; } /** * @return the instructions */ @Column(name = "instructions", length = 250) public String getInstructions() { return instructions; } /** * @param instructions * the instructions to set */ public void setInstructions(String instructions) { this.instructions = instructions; } /** * @return the additionalInstructions */ @Column(name = "additional_instructions", length = 250) public String getAdditionalInstructions() { return additionalInstructions; } /** * @param additionalInstructions * the additionalInstructions to set */ public void setAdditionalInstructions(String additionalInstructions) { this.additionalInstructions = additionalInstructions; } /** * @return the blocked */ @Column public Boolean isBlocked() { return blocked; } /** * @param blocked * the blocked to set */ public void setBlocked(Boolean blocked) { this.blocked = blocked; } /** * @return the currency */ @ManyToOne(fetch = FetchType.EAGER, optional = false) @JoinColumn(name = "currency_id") public Currency getCurrency() { return currency; } /** * @param currency * the currency to set */ public void setCurrency(Currency currency) { this.currency = currency; } /** * @return the inconterm */ @ManyToOne(fetch = FetchType.EAGER, optional = false) @JoinColumn(name = "incoterm_id") public Incoterm getInconterm() { return inconterm; } /** * @param inconterm * the inconterm to set */ public void setInconterm(Incoterm inconterm) { this.inconterm = inconterm; } /** * @return the originCountry */ @ManyToOne(fetch = FetchType.EAGER, optional = false) @JoinColumn(name = "origin_country_id") public Country getOriginCountry() { return originCountry; } /** * @param originCountry * the originCountry to set */ public void setOriginCountry(Country originCountry) { this.originCountry = originCountry; } /** * @return the customsRegime */ @ManyToOne(fetch = FetchType.EAGER, optional = false) @JoinColumn(name = "customs_regime_id") public CustomsRegime getCustomsRegime() { return customsRegime; } /** * @param customsRegime * the customsRegime to set */ public void setCustomsRegime(CustomsRegime customsRegime) { this.customsRegime = customsRegime; } /** * @return the assessmentMethod */ @ManyToOne(fetch = FetchType.EAGER, optional = false) @JoinColumn(name = "assessment_method_id") public AssessmentMethod getAssessmentMethod() { return assessmentMethod; } /** * @param assessmentMethod * the assessmentMethod to set */ public void setAssessmentMethod(AssessmentMethod assessmentMethod) { this.assessmentMethod = assessmentMethod; } /** * @return the bundleType */ @ManyToOne(fetch = FetchType.EAGER, optional = false) @JoinColumn(name = "bundle_type_id") public BundleType getBundleType() { return bundleType; } /** * @param bundleType * the bundleType to set */ public void setBundleType(BundleType bundleType) { this.bundleType = bundleType; } /** * @return the purchaser */ @ManyToOne(fetch = FetchType.EAGER, optional = false) @JoinColumn(name = "purchaser_company_id") public Company getPurchaser() { return purchaser; } /** * @param purchaser * the purchaser to set */ public void setPurchaser(Company purchaser) { this.purchaser = purchaser; } /** * @return the seller */ @ManyToOne(fetch = FetchType.EAGER, optional = false) @JoinColumn(name = "seller_company_id") public Company getSeller() { return seller; } /** * @param seller * the seller to set */ public void setSeller(Company seller) { this.seller = seller; } /** * @return the sender */ @ManyToOne(fetch = FetchType.EAGER, optional = false) @JoinColumn(name = "sender_company_id") public Company getSender() { return sender; } /** * @param sender * the sender to set */ public void setSender(Company sender) { this.sender = sender; } /** * @return the receiver */ @ManyToOne(fetch = FetchType.EAGER, optional = false) @JoinColumn(name = "receiver_company_id") public Company getReceiver() { return receiver; } /** * @param receiver * the receiver to set */ public void setReceiver(Company receiver) { this.receiver = receiver; } /** * @return the items */ @OneToMany(mappedBy = "packingList", fetch = FetchType.EAGER, orphanRemoval = true) public Set<PackingListItem> getItems() { return items; } /** * @param items * the items to set */ public void setItems(Set<PackingListItem> items) { this.items = items; } /** * * @author https://github.com/diego-torres * */ @Entity @Table(name = "packing_list_item", uniqueConstraints = { @UniqueConstraint(columnNames = { "packing_list_id", "item_seq" }, name = "ux_packing_list_item_seq") }) public static class PackingListItem extends BaseGenericModel { private static final long serialVersionUID = 1L; private PackingList packingList; private String itemSeq; private Part part; private BigDecimal quantity = new BigDecimal(0.0); private BigDecimal unitPrice = new BigDecimal(0.0); private Boolean tlc; private Boolean ma; private BigDecimal weightKilos = new BigDecimal(0.0); private String lot; private Integer bundles; private Integer pieces; private BigDecimal lengthInches = new BigDecimal(0.0); private BigDecimal widthInches = new BigDecimal(0.0); private BigDecimal heightInches = new BigDecimal(0.0); private String marks; private String models; private String series; private String observations; private Boolean blocked; private Unit unitOfMeasure; private Country originCountry; private Incoterm inconterm; private CustomsRegime customsRegime; private AssessmentMethod assessmentMethod; /** * @return the packingList */ @ManyToOne(fetch = FetchType.EAGER, optional = false) @JoinColumn(name = "packing_list_id") @JsonIgnore public PackingList getPackingList() { return packingList; } /** * @param packingList * the packingList to set */ public void setPackingList(PackingList packingList) { this.packingList = packingList; } /** * @return the itemSeq */ @Column(name = "item_seq", length = 4) public String getItemSeq() { return itemSeq; } /** * @param itemSeq * the itemSeq to set */ public void setItemSeq(String itemSeq) { this.itemSeq = itemSeq; } /** * @return the part */ @ManyToOne(fetch = FetchType.EAGER, optional = false) @JoinColumn(name = "part_id") public Part getPart() { return part; } /** * @param part * the part to set */ public void setPart(Part part) { this.part = part; } /** * @return the quantity */ @Column(nullable = false, precision = 18, scale = 6) @ColumnDefault(value = "0") public BigDecimal getQuantity() { return quantity; } /** * @param quantity * the quantity to set */ public void setQuantity(BigDecimal quantity) { this.quantity = quantity; } /** * @return the unitPrice */ @Column(name = "unit_price", nullable = false, precision = 18, scale = 6) @ColumnDefault(value = "0") public BigDecimal getUnitPrice() { return unitPrice; } /** * @param unitPrice * the unitPrice to set */ public void setUnitPrice(BigDecimal unitPrice) { this.unitPrice = unitPrice; } /** * @return the tlc */ @Column public Boolean getTlc() { return tlc; } /** * @param tlc * the tlc to set */ public void setTlc(Boolean tlc) { this.tlc = tlc; } /** * @return the ma */ @Column public Boolean getMa() { return ma; } /** * @param ma * the ma to set */ public void setMa(Boolean ma) { this.ma = ma; } /** * @return the weightKilos */ @Column(name="weight_kilos", nullable = false, precision = 18, scale = 6) @ColumnDefault(value = "0") public BigDecimal getWeightKilos() { return weightKilos; } /** * @param weightKilos * the weightKilos to set */ public void setWeightKilos(BigDecimal weightKilos) { this.weightKilos = weightKilos; } /** * @return the lot */ @Column public String getLot() { return lot; } /** * @param lot * the lot to set */ public void setLot(String lot) { this.lot = lot; } /** * @return the bundles */ @Column public Integer getBundles() { return bundles; } /** * @param bundles * the bundles to set */ public void setBundles(Integer bundles) { this.bundles = bundles; } /** * @return the pieces */ @Column public Integer getPieces() { return pieces; } /** * @param pieces * the pieces to set */ public void setPieces(Integer pieces) { this.pieces = pieces; } /** * @return the lengthInches */ @Column(name="length_inches", nullable = false, precision = 18, scale = 6) @ColumnDefault(value = "0") public BigDecimal getLengthInches() { return lengthInches; } /** * @param lengthInches * the lengthInches to set */ public void setLengthInches(BigDecimal lengthInches) { this.lengthInches = lengthInches; } /** * @return the widthInches */ @Column(name="width_inches", nullable = false, precision = 18, scale = 6) @ColumnDefault(value = "0") public BigDecimal getWidthInches() { return widthInches; } /** * @param widthInches * the widthInches to set */ public void setWidthInches(BigDecimal widthInches) { this.widthInches = widthInches; } /** * @return the heightInches */ @Column(name="height_inches", nullable = false, precision = 18, scale = 6) @ColumnDefault(value = "0") public BigDecimal getHeightInches() { return heightInches; } /** * @param heightInches * the heightInches to set */ public void setHeightInches(BigDecimal heightInches) { this.heightInches = heightInches; } /** * @return the marks */ @Column(length=1024) public String getMarks() { return marks; } /** * @param marks * the marks to set */ public void setMarks(String marks) { this.marks = marks; } /** * @return the models */ @Column(length=1024) public String getModels() { return models; } /** * @param models * the models to set */ public void setModels(String models) { this.models = models; } /** * @return the series */ @Column(length=1024) public String getSeries() { return series; } /** * @param series * the series to set */ public void setSeries(String series) { this.series = series; } /** * @return the observations */ @Column(length=1024) public String getObservations() { return observations; } /** * @param observations * the observations to set */ public void setObservations(String observations) { this.observations = observations; } /** * @return the blocked */ @Column public Boolean isBlocked() { return blocked; } /** * @param blocked * the blocked to set */ public void setBlocked(Boolean blocked) { this.blocked = blocked; } /** * @return the unitOfMeasure */ @ManyToOne(fetch = FetchType.EAGER, optional = false) @JoinColumn(name = "unit_of_measure_id") public Unit getUnitOfMeasure() { return unitOfMeasure; } /** * @param unitOfMeasure * the unitOfMeasure to set */ public void setUnitOfMeasure(Unit unitOfMeasure) { this.unitOfMeasure = unitOfMeasure; } /** * @return the originCountry */ @ManyToOne(fetch = FetchType.EAGER, optional = false) @JoinColumn(name = "origin_country_id") public Country getOriginCountry() { return originCountry; } /** * @param originCountry * the originCountry to set */ public void setOriginCountry(Country originCountry) { this.originCountry = originCountry; } /** * @return the inconterm */ @ManyToOne(fetch = FetchType.EAGER, optional = false) @JoinColumn(name = "incoterm_id") public Incoterm getInconterm() { return inconterm; } /** * @param inconterm * the inconterm to set */ public void setInconterm(Incoterm inconterm) { this.inconterm = inconterm; } /** * @return the customsRegime */ @ManyToOne(fetch = FetchType.EAGER, optional = false) @JoinColumn(name = "customs_regime_id") public CustomsRegime getCustomsRegime() { return customsRegime; } /** * @param customsRegime * the customsRegime to set */ public void setCustomsRegime(CustomsRegime customsRegime) { this.customsRegime = customsRegime; } /** * @return the assessmentMethod */ @ManyToOne(fetch = FetchType.EAGER, optional = false) @JoinColumn(name = "assessment_method_id") public AssessmentMethod getAssessmentMethod() { return assessmentMethod; } /** * @param assessmentMethod * the assessmentMethod to set */ public void setAssessmentMethod(AssessmentMethod assessmentMethod) { this.assessmentMethod = assessmentMethod; } } }
true
b5a8bf2e49a554b1178541f7078c7381ec598f36
Java
HPI-BP2017N2/ShopRulesGenerator-deprecated-
/src/main/java/de/hpi/shoprulesgenerator/service/ShopRulesGeneratorService.java
UTF-8
2,441
1.914063
2
[]
no_license
package de.hpi.shoprulesgenerator.service; import de.hpi.restclient.clients.BPBridgeClient; import de.hpi.restclient.clients.URLCleanerClient; import de.hpi.restclient.pojo.Rules; import de.hpi.shoprulesgenerator.model.*; import de.hpi.shoprulesgenerator.properties.ShopRulesGeneratorSettingsProperties; import de.hpi.shoprulesgenerator.repository.RulesDBEntry; import de.hpi.shoprulesgenerator.repository.RulesRepository; import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service @Getter(AccessLevel.PRIVATE) @Setter(AccessLevel.PRIVATE) public class ShopRulesGeneratorService { private BPBridgeClient bpBridgeClient; private RulesRepository rulesRepository; private SelectorGenerator selectorGenerator; private ShopRulesGenerator shopRulesGenerator; private ShopRulesGeneratorSettingsProperties properties; private WebHTMLFetcher webHTMLFetcher; @Autowired public ShopRulesGeneratorService(ShopRulesGeneratorSettingsProperties properties, BPBridgeClient bpBridgeClient, URLCleanerClient urlCleanerClient, RulesRepository rulesRepository) { setBpBridgeClient(bpBridgeClient); setProperties(properties); setWebHTMLFetcher(new WebHTMLFetcher(new URLCleaner(urlCleanerClient), getProperties().getUserAgent())); setSelectorGenerator(new SelectorGenerator()); setShopRulesGenerator(new ShopRulesGenerator( getProperties().getMaxOfferCount(), getProperties().getMinMatchCountPerAttribute(), getProperties().getMinConfidence(), getProperties().getFetchDelay())); setRulesRepository(rulesRepository); } public Rules getRulesForShop(long shopID) { RulesDBEntry entry = getRulesRepository().findByShopID(shopID); if (entry == null) { return null; } return entry.getRules(); } public Rules generateForShop(long shopID) { OfferFetcher offerFetcher = new OfferFetcher(getBpBridgeClient(), shopID, getProperties().getPageSize()); Rules generatedRules = getShopRulesGenerator().generate(offerFetcher, getWebHTMLFetcher(), getSelectorGenerator()); getRulesRepository().save(new RulesDBEntry(shopID, generatedRules)); return generatedRules; } }
true
e8e0c020cc8d633355ef68fb63fb8276ecad0bfb
Java
barathkumar2699/NetbeansProject
/8b/src/pkg8b/client.java
UTF-8
1,172
2.765625
3
[]
no_license
/* * 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 pkg8b; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import java.util.Scanner; public class client { public static void main(String args[]) throws IOException { Scanner scan =new Scanner(System.in); Socket client=new Socket("localhost",4453); DataOutputStream data=new DataOutputStream(client.getOutputStream()); DataInputStream indata=new DataInputStream(client.getInputStream()); String creceived ="",send; System.out.println("ENTER TO START MESSAGE"); send=scan.nextLine(); data.writeUTF(send); data.flush(); while(!creceived.equalsIgnoreCase("bye")){ creceived=indata.readUTF(); System.out.println("Server:\t"+creceived); send=scan.nextLine(); data.writeUTF(send); data.flush(); } client.close(); }}
true
02aafeeaff3596f2820709f290fb6fcd1608e92c
Java
WagnerSP/MMS
/mms/src/main/java/com/wagner/mms/bean/Role.java
UTF-8
1,483
2.21875
2
[ "Apache-2.0" ]
permissive
package com.wagner.mms.bean; public class Role { private String roleid; private String rolepermission; private String identify; private String description; private Integer orderno; public String getRoleid() { return roleid; } public void setRoleid(String roleid) { this.roleid = roleid == null ? null : roleid.trim(); } public String getRolepermission() { return rolepermission; } public void setRolepermission(String rolepermission) { this.rolepermission = rolepermission == null ? null : rolepermission.trim(); } public String getIdentify() { return identify; } public void setIdentify(String identify) { this.identify = identify == null ? null : identify.trim(); } public String getDescription() { return description; } public void setDescription(String description) { this.description = description == null ? null : description.trim(); } public Integer getOrderno() { return orderno; } public void setOrderno(Integer orderno) { this.orderno = orderno; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Role [roleid="); builder.append(roleid); builder.append(", rolepermission="); builder.append(rolepermission); builder.append(", identify="); builder.append(identify); builder.append(", description="); builder.append(description); builder.append(", orderno="); builder.append(orderno); builder.append("]"); return builder.toString(); } }
true
af5734221c706f989fece30c79a63c01a62c1aee
Java
yebanme/racing
/src/main/java/com/github/hornta/race/events/RaceCheckpointEvent.java
UTF-8
708
2.484375
2
[]
no_license
package com.github.hornta.race.events; import com.github.hornta.race.objects.Race; import com.github.hornta.race.objects.RaceCheckpoint; import org.bukkit.event.HandlerList; abstract public class RaceCheckpointEvent extends RaceEvent { private static final HandlerList handlers = new HandlerList(); private RaceCheckpoint checkpoint; RaceCheckpointEvent(Race race, RaceCheckpoint checkpoint) { super(race); this.checkpoint = checkpoint; } public static HandlerList getHandlerList() { return handlers; } public RaceCheckpoint getCheckpoint() { return checkpoint; } @Override public HandlerList getHandlers() { return handlers; } }
true
36029cec29d17cd866279b71777042b3e7fd1400
Java
baygoit/GoJava
/trunk/GoJava5/victor.homyak/KickStarterMVC/src/main/java/goit/vh/kickstarter/mvc/view/ProjectView.java
UTF-8
2,678
2.6875
3
[]
no_license
package goit.vh.kickstarter.mvc.view; import java.util.ArrayList; import java.util.Date; import java.util.concurrent.TimeUnit; import goit.vh.kickstarter.Input; import goit.vh.kickstarter.Output; import goit.vh.kickstarter.mvc.model.ProjectModel; /** * Created by Viktor on 14.07.2015. */ public class ProjectView { private String input; private Output output; public ProjectView(Output output) { this.output = output; } public void renderList(ArrayList<ProjectModel> projects) { for (int i = 0; i < projects.size(); i++) { output.println(String.valueOf(i + 1) + " " + projects.get(i).getProjectName() + " " + projects.get(i).getShortDescription() + "\n Sum to raise: " + projects.get(i).getSumToRaise() + "; Already collected: " + projects.get(i).getCurrentSum() + "; Days to end raising money: " + getDateDiff(new Date(), projects.get(i).getEndDate(), TimeUnit.DAYS)); } readUserInput(); setInput(new Input().getInput()); } public void render(ProjectModel projectModel) { // output.println("You choose option " + projectModel.getProjectName()); output.println(projectModel.getShortDescription() + "\n Sum to raise: " + projectModel.getSumToRaise() + "; Already collected: " + projectModel.getCurrentSum() + "; Days to end raising money: " + getDateDiff(new Date(), projectModel.getEndDate(), TimeUnit.DAYS) + "\n Project history: " + projectModel.getProjectHistory() + "\n Demo video: " + projectModel.getDemoURL() + ";\nFAQ: " + projectModel.getfAQ()); } public void readUserInput() { output.println("If you want to go back, choose '0'"); } public void readInProjectUserInput() { output.println("If you want to go back, choose '1'\nIf you want retern to mani menu, choose '0'"); setInput(new Input().getInput()); } /** * Get a diff between two dates * * @param date1 the oldest date * @param date2 the newest date * @param timeUnit the unit in which you want the diff * @return the diff value, in the provided unit */ public static long getDateDiff(Date date1, Date date2, TimeUnit timeUnit) { long diffInMillies = date2.getTime() - date1.getTime(); return timeUnit.convert(diffInMillies, TimeUnit.MILLISECONDS); } public void setInput(String input) { this.input = input; } public String getInput() { return input; } }
true
86458719e8b8a72d11a2beabad3108e4c1892e4e
Java
Moderocky/ByteSkript
/src/main/java/org/byteskript/skript/compiler/Context.java
UTF-8
8,825
2.078125
2
[ "BSD-3-Clause" ]
permissive
/* * Copyright (c) 2021 ByteSkript org (Moderocky) * View the full licence information and permissions: * https://github.com/Moderocky/ByteSkript/blob/master/LICENSE */ package org.byteskript.skript.compiler; import mx.kenzie.foundation.*; import mx.kenzie.foundation.compiler.State; import org.byteskript.skript.api.*; import org.byteskript.skript.api.syntax.Section; import org.byteskript.skript.compiler.structure.*; import java.util.*; import java.util.function.Consumer; /** * This keeps track of what happens during a compiler pass. */ public abstract class Context { protected final List<Library> libraries = new ArrayList<>(); protected final List<Unit> units = new ArrayList<>(); protected final List<SectionMeta> sections = new ArrayList<>(); protected ErrorDetails error; protected State state; protected String storedVariableName; public ErrorDetails getError() { return error; } public String getStoredVariableName() { return storedVariableName; } public void setStoredVariableName(String storedVariableName) { this.storedVariableName = storedVariableName; } public abstract boolean hasFlag(Flag flag); public abstract void addFlag(Flag flag); public abstract void removeFlag(Flag flag); public abstract Collection<Type> getAvailableTypes(); public abstract Map<String, Type> getTypeMap(); public abstract void setIndentUnit(String string); public abstract ClassBuilder getBuilder(); public abstract void useSubBuilder(final ClassBuilder builder); public abstract ClassBuilder endSubBuilder(); public abstract ClassBuilder addSuppressedBuilder(final Type type); public abstract ClassBuilder getSuppressedBuilder(Type type); public abstract ClassBuilder getSuppressedBuilder(); public abstract MethodBuilder getMethod(); public abstract void setMethod(MethodBuilder method); public abstract MethodBuilder getTriggerMethod(); public abstract void setMethod(MethodBuilder method, boolean trigger); public abstract FieldBuilder getField(); public abstract void setField(FieldBuilder field); public abstract int lineNumber(); public abstract SyntaxElement currentEffect(); /** * Force an unspecified variable into the register. * Used to store internal details without upsetting index-order. */ public abstract PreVariable forceUnspecVariable(PreVariable variable); public abstract PreVariable getVariable(String name); public abstract PreVariable getVariable(int slot); public abstract void emptyVariables(); public abstract int getVariableCount(); public abstract Collection<PreVariable> getVariables(); public abstract int slotOf(PreVariable variable); public abstract boolean hasVariable(String name); public abstract ElementTree getLine(); public abstract ElementTree getCompileCurrent(); public abstract void setCompileCurrent(ElementTree element); public abstract void createTree(ProgrammaticSplitTree tree); public abstract void closeAllTrees(); public abstract void removeTree(ProgrammaticSplitTree tree); public abstract void addInnerClass(Type type, int modifiers); public abstract int getLambdaIndex(); public abstract void increaseLambdaIndex(); public abstract void addSkipInstruction(Consumer<Context> consumer); public abstract boolean isSectionHeader(); public abstract int methodIndexShift(); public abstract boolean hasHandle(String property, HandlerType type); public abstract MethodErasure useHandle(String property, HandlerType type); public abstract HandlerType getHandlerMode(); public abstract void setHandlerMode(HandlerType type); public MultiLabel getSectionBreak() { return getCurrentTree().getEnd(); } public abstract ProgrammaticSplitTree getCurrentTree(); public void appendSection(Section handler) { if (sections.isEmpty()) addSection(handler); else sections.get(0).getHandlers().add(handler); } public void addSection(Section handler) { sections.add(0, new SectionMeta(handler)); } public SectionMeta getSection() { if (sections.isEmpty()) return null; return sections.get(0); } public SectionMeta getSection(int index) { if (sections.isEmpty()) return null; return sections.get(index); } public SectionMeta getTriggerSection() { final TriggerTree tree = this.findTree(TriggerTree.class); if (tree == null) return null; return tree.owner(); } public abstract <Tree extends ProgrammaticSplitTree> Tree findTree(Class<Tree> type); public Section getParent() { if (sections.isEmpty()) return null; return sections.get(0).handler(); } public void destroySections() { do destroySection(); while (!sections.isEmpty()); } public void destroySection() { if (sections.isEmpty()) return; final SectionMeta meta = sections.remove(0); final Section[] handlers = meta.getHandlers().toArray(new Section[0]); for (int i = handlers.length - 1; i >= 0; i--) { final Section section = handlers[i]; section.onSectionExit(this, meta); } final ProgrammaticSplitTree tree = this.getTree(meta); if (tree != null) tree.close(this); } public abstract ProgrammaticSplitTree getTree(SectionMeta meta); public abstract boolean hasFunction(String name, int arguments); public Function getDefaultFunction(String name, int arguments) { final Function function = this.getFunction(name, arguments); if (function != null) return function.copy(arguments); // we pass objects even if types are specified final Type[] types = new Type[arguments]; Arrays.fill(types, CommonTypes.OBJECT); // assert all types are actually object :) return new Function(name, this.getType(), CommonTypes.OBJECT, types); } public abstract Function getFunction(String name, int arguments); public abstract Type getType(); public abstract void registerFunction(Function function); public void addLibrary(Library provider) { this.libraries.add(provider); } public Unit getCurrentUnit() { return units.isEmpty() ? null : units.get(0); } public boolean hasCurrentUnit() { return !units.isEmpty(); } public void destroyUnit() { if (units.isEmpty()) return; units.remove(0); } public void destroyUnits() { units.clear(); } public void createUnit(final LanguageElement element) { units.add(0, new Unit(element)); } public Collection<SyntaxElement> getHandlers(State state) { return getHandlers(state, getExpected()); } public Collection<SyntaxElement> getHandlers(State state, LanguageElement expected) { final List<SyntaxElement> elements = new ArrayList<>(); for (final Library library : getLibraries()) { elements.addAll(library.getHandlers(state, expected, this)); } return elements; } public abstract LanguageElement getExpected(); public Collection<Library> getLibraries() { return libraries; } public Collection<SyntaxElement> getHandlers() { return this.getHandlers(this.getState(), this.getExpected()); } public State getState() { return state; } public void setState(State state) { this.state = state; } public void registerType(Type type) { if (type.isArray()) this.registerType(type.componentType().getSimpleName() + "s", type); else this.registerType(type.getSimpleName(), type); } public abstract void registerType(String name, Type type); public String expectedIndent() { if (indentUnit() == null) return ""; final StringBuilder builder = new StringBuilder(); for (int i = 0; i < indent(); i++) { builder.append(indentUnit()); } return builder.toString(); } public abstract String indentUnit(); public abstract int indent(); public Type findType(String internal) { final Type type = this.getType(internal); if (type != null) return type; return new Type(internal); } public abstract Type getType(String name); }
true
c79453bdb40200fa094a3463b526df1e4384e3b2
Java
vinkrish/study-manager
/app/src/main/java/com/app/studymanager/util/DisplayUtil.java
UTF-8
1,588
2.78125
3
[]
no_license
package com.app.studymanager.util; import android.content.Context; import android.util.DisplayMetrics; /** * Created by Vinay on 30-10-2016. */ public class DisplayUtil { public static int pxToDp(Context context, int px) { DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics(); int dp = Math.round(px / (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT)); return dp; } public static int px2dp(Context context, int px){ float scale = context.getResources().getDisplayMetrics().density; return (int) (px - 0.5f / scale); } public static float convertPixelsToDp(Context context, float px){ DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics(); float dp = px / ((float)displayMetrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT); return dp; } public static int dpToPx(Context context, int dp) { DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics(); int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT)); return px; } public static int dp2px(Context context, int dp){ float scale = context.getResources().getDisplayMetrics().density; return (int) (dp * scale + 0.5f); } public static float convertDpToPixel(Context context, float dp){ DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics(); float px = dp * ((float)displayMetrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT); return px; } }
true
3d6cb76e8e452169f0610837769059c32a7fc805
Java
Pushkar16/CSE-Bank-master
/src/main/java/exception/csebank_controllers/asu/edu/KYCNotFound.java
UTF-8
450
2.1875
2
[ "MIT" ]
permissive
package exception.csebank_controllers.asu.edu; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(value=HttpStatus.NOT_FOUND, reason="KYC ID Not found.") public class KYCNotFound extends IllegalArgumentException{ private static final long serialVersionUID = 110L; public KYCNotFound(String error){ super(error); } public KYCNotFound() { super("KYC ID Not found"); } }
true
809ce04d1ac17ad365a3ad0ea3b3b1173f5a361a
Java
Christoffersenry/BarberShop
/src/barbershop/customerControllers/CLogCon.java
UTF-8
3,030
2.546875
3
[]
no_license
/* * 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 barbershop.customerControllers; import barbershop.customerViews.CHomeV; import barbershop.customerModels.User; import barbershop.customerViews.CLogV; import barbershop.customerViews.CRegV; import barbershop.customerDAO.UserDAOImpl; import barbershop.index.IndexCon; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; /** * * @author rcvb8 */ public class CLogCon implements ActionListener, MouseListener { CLogV cLogV; UserDAOImpl userDAOImpl; boolean result; // INSTANTIATION OF CUSTOMER LOGIN VIEW AND DAO CLASS public CLogCon(CLogV cLogV) { this.cLogV = cLogV; this.userDAOImpl = new UserDAOImpl(); } // LOGIN METHOD WHEN BUTTON IS CLICKED (RESULT TRUE = DIRECT TO HOME / RESULT FALSE = INVALID MESSAGE) @Override public void actionPerformed(ActionEvent e) { // PREVIOUS BUTTON TO RETURN TO INDEX SCREEN if(e.getActionCommand().equals("Previous")) { new IndexCon(); this.cLogV.dispose(); } // IDENTIFIES LOGIN BUTTON IN VIEW if (e.getActionCommand().equals("Login")) { // STORES USER INPUT IN STRINGS String uE = cLogV.getUserEmail(); String pw = cLogV.getUserPassword(); // PASSES USER INPUT INTO USER CLASS User user = new User(uE, pw); // STORES BOOLEAN RESULT FROM LOGIN METHOD IN DAO this.result = userDAOImpl.login(user); // CHANGES VIEW OR DISPLAYS INVALID MESSAGE BASED ON RESULT if (!result) { cLogV.getInvalidMessage(); } else { new CHomeV(); this.cLogV.dispose(); } } } // METHOD TO TO TAKE USER TO REGISTRATION PAGE @Override public void mouseClicked(MouseEvent e) { new CRegV(); this.cLogV.dispose(); } // UNUSED METHODS, BUT NEEDED IN ORDER TO USE MOUSE LISTENER @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void mousePressed(MouseEvent e) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void mouseReleased(MouseEvent e) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
true
411fd3741cd070643b8307ccdb9741a4a845cd07
Java
Cop-Tur/Algorithm_Review
/src/chapter_7/radixsort/RadixSort.java
UTF-8
753
3.703125
4
[]
no_license
package chapter_7.radixsort; import java.util.ArrayList; public class RadixSort { public static void radixSortA(String[] arr, int stringLen) { //用一个ArrayList做桶 final int BUCKETS = 256; ArrayList<String>[] buckets = new ArrayList[BUCKETS]; for (int i = 0; i < BUCKETS; i++) buckets[i] = new ArrayList<>(); for (int pos = stringLen - 1; pos >= 0; pos--) { for (String s : arr) { buckets[s.charAt(pos)].add(s); } int idx = 0; for (ArrayList<String> thisBucket : buckets) { for (String s : thisBucket) arr[idx++] = s; thisBucket.clear(); } } } }
true
f0befeff574e93ea86914e7c96fba6b3b036ffd0
Java
priyatiwari419/MPS
/src/main/java/mps/commisioner/controller/CommissionerController.java
UTF-8
1,979
2.046875
2
[]
no_license
package mps.commisioner.controller; import lombok.AllArgsConstructor; import mps.commisioner.dto.ArrestHistoryDto; import mps.commisioner.request.ArrestHistoryRequest; import mps.commisioner.response.ArrestHistoryResponse; import mps.commisioner.response.ExpenditureResponse; import mps.commisioner.service.ArrestService; import mps.members.service.MemberService; import mps.members.translator.BaseObjectTranslator; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; @RestController @RequestMapping("/commissioners") @AllArgsConstructor @Validated public class CommissionerController { private final ArrestService arrestService; private final MemberService memberService; private final BaseObjectTranslator baseObjectTranslator; @PostMapping("/submit") public ResponseEntity<Object> submitRequestForArresting(@Valid @RequestBody ArrestHistoryRequest arrestHistoryRequest, @RequestHeader(value = "Authorization") String token){ return new ResponseEntity<>(arrestService.submitRequestForArresting(baseObjectTranslator.map(arrestHistoryRequest, ArrestHistoryDto.class),token.substring(7)),HttpStatus.CREATED); } @GetMapping("/{submitId}") public ResponseEntity<Object> findArrestHistoryById(@PathVariable Long submitId){ return new ResponseEntity<>(baseObjectTranslator.map(arrestService.findArrestHistoryByArrestHistoryId(submitId), ArrestHistoryResponse.class),HttpStatus.OK); } @GetMapping public ResponseEntity<ExpenditureResponse> findSpendingExceedFlagByMemberIdAndMemberRole(@RequestParam Long memberId,@RequestParam String memberRole){ return new ResponseEntity<>(baseObjectTranslator.map(memberService.findExpenditureByMemberIdAndMemberRole(memberId,memberRole), ExpenditureResponse.class),HttpStatus.OK); } }
true
3e953f9949587a68159c80be75c0f69524d87098
Java
frfontoura/destiny-event-scheduler
/src/main/java/com/destinyEventScheduler/factory/MemberHistoryDTOFactory.java
UTF-8
651
2.640625
3
[]
no_license
package com.destinyEventScheduler.factory; import com.destinyEventScheduler.dto.MemberHistoryDTO; import com.destinyEventScheduler.model.Member; public abstract class MemberHistoryDTOFactory { public static MemberHistoryDTO createMemberHistoryDTO(Member member) { MemberHistoryDTO memberHistoryDTO = new MemberHistoryDTO(); memberHistoryDTO.setMembership(member.getMembership()); memberHistoryDTO.setName(member.getName()); memberHistoryDTO.setIcon(member.getIcon()); memberHistoryDTO.setTotalLikes(0); memberHistoryDTO.setTotalDislikes(0); memberHistoryDTO.setMemberTitle(member.getMemberTitle()); return memberHistoryDTO; } }
true