text
stringlengths 10
2.72M
|
|---|
package com.example.fragmentlab;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.fragment.app.Fragment;
import com.example.fragmentlab.data.model.Mail;
import java.util.List;
public class MailListFragment extends Fragment {
public List<Mail> mails;
private MailAdapter.MailItemClickListener listener = null;
public MailListFragment(List<Mail> mails) {
this.mails = mails;
}
public void onAttach(Context context) {
super.onAttach(context);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.mail_list, container, false);
RecyclerView recyclerView = view.findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
listener = new MailAdapter.MailItemClickListener() {
@Override
public void itemClick(int position, Mail mail) {
Fragment fragment = getFragmentManager().findFragmentById(R.id.mail_detail);
((MailDetailFragment)fragment).draw(mail);
}
};
MailAdapter adapter = new MailAdapter(this.mails, listener);
recyclerView.setAdapter(adapter);
return view;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
|
package com.tencent.mm.plugin.exdevice.ui;
import com.tencent.mm.ab.l;
import com.tencent.mm.plugin.exdevice.a.b;
import com.tencent.mm.plugin.exdevice.c.a.a;
import com.tencent.mm.sdk.platformtools.x;
class ExdeviceConnectedRouterActivateStateUI$1 implements b<a> {
final /* synthetic */ ExdeviceConnectedRouterActivateStateUI iCC;
ExdeviceConnectedRouterActivateStateUI$1(ExdeviceConnectedRouterActivateStateUI exdeviceConnectedRouterActivateStateUI) {
this.iCC = exdeviceConnectedRouterActivateStateUI;
}
public final /* synthetic */ void b(int i, int i2, String str, l lVar) {
try {
x.d("MicroMsg.ConnectedRouterActivateStateUi", "onNetSceneEndCallback, errType(%s), errCode(%s), errMsg(%s)", new Object[]{Integer.valueOf(i), Integer.valueOf(i2), str});
if (this.iCC.isFinishing()) {
x.i("MicroMsg.ConnectedRouterActivateStateUi", "ExdeviceConnectedRouter destroyed.");
} else {
this.iCC.runOnUiThread(new 1(this, i2, i));
}
} catch (Exception e) {
x.d("MicroMsg.ConnectedRouterActivateStateUi", e.toString());
}
}
}
|
package com.tencent.mm.plugin.shake.ui;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import com.tencent.mm.R;
import com.tencent.mm.k.g;
import com.tencent.mm.model.au;
import com.tencent.mm.model.c;
import com.tencent.mm.platformtools.af;
import com.tencent.mm.plugin.shake.a;
import com.tencent.mm.pluginsdk.ui.tools.l;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.ui.base.h;
import com.tencent.mm.ui.base.preference.CheckBoxPreference;
import com.tencent.mm.ui.base.preference.MMPreference;
import com.tencent.mm.ui.base.preference.Preference;
import com.tencent.mm.ui.base.preference.f;
public class ShakePersonalInfoUI extends MMPreference {
private f eOE;
public final int Ys() {
return R.o.shake_settings_pref_personal_info;
}
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
initView();
}
public void onDestroy() {
a.ezo.vl();
super.onDestroy();
}
protected final void initView() {
setMMTitle(R.l.shake_item_setting);
this.eOE = this.tCL;
CheckBoxPreference checkBoxPreference = (CheckBoxPreference) this.eOE.ZZ("shake_item_sound");
au.HU();
if (c.DT().get(4112, null) == null) {
au.HU();
c.DT().set(4112, Boolean.valueOf(true));
}
au.HU();
checkBoxPreference.qpJ = bi.c((Boolean) c.DT().get(4112, null));
setBackBtn(new 1(this));
if (!com.tencent.mm.an.c.Qf()) {
this.eOE.aaa("shake_item_shake_music_list");
}
}
public void onResume() {
boolean z = false;
super.onResume();
if (au.HX()) {
a.ezo.vl();
}
if (this.eOE.ZZ("shake_item_shake_tv_list") == null) {
x.e("MicroMsg.mmui.MMPreference", "shake_tv_list preference is null");
return;
}
if (bi.getInt(g.AU().G("ShowConfig", "showShakeTV"), 0) == 1) {
z = true;
}
x.d("MicroMsg.ConfigListDecoder", "isShowShakeTV : " + z);
if (!z && !af.exd) {
this.eOE.bw("shake_item_shake_tv_list", true);
}
}
public boolean onKeyDown(int i, KeyEvent keyEvent) {
if (i != 4) {
return super.onKeyDown(i, keyEvent);
}
finish();
return true;
}
public final boolean a(f fVar, Preference preference) {
Intent intent;
String str = preference.mKey;
if ("shake_item_default_bgimg".equals(str)) {
au.HU();
c.DT().set(4110, Boolean.valueOf(true));
h.bA(this, getResources().getString(R.l.shake_settings_laert_reset_bg_ok));
}
if ("shake_item_change_bgimg".equals(str)) {
l.a(this, 1, null);
}
if ("shake_item_sound".equals(str)) {
au.HU();
boolean c = bi.c((Boolean) c.DT().get(4112, null));
au.HU();
c.DT().set(4112, Boolean.valueOf(!c));
}
if ("say_hi_list_shake_title".equals(str)) {
intent = new Intent(this, ShakeSayHiListUI.class);
intent.putExtra("IntentSayHiType", 1);
startActivity(intent);
}
if ("shake_item_histoty_list".equals(str)) {
intent = new Intent(this, ShakeItemListUI.class);
intent.putExtra("_key_show_type_", 100);
intent.putExtra("_key_title_", getString(R.l.shake_item_history_list));
startActivity(intent);
}
if ("shake_msg_list".equals(str)) {
intent = new Intent(this, ShakeMsgListUI.class);
intent.putExtra("shake_msg_from", 2);
intent.putExtra("shake_msg_list_title", getString(R.l.shake_tv_msg_center_title));
startActivity(intent);
}
return false;
}
public void onActivityResult(int i, int i2, Intent intent) {
switch (i) {
case 1:
if (intent != null) {
Intent intent2 = new Intent();
intent2.putExtra("CropImageMode", 4);
intent2.putExtra("CropImage_Filter", true);
intent2.putExtra("CropImage_DirectlyIntoFilter", true);
StringBuilder stringBuilder = new StringBuilder();
au.HU();
intent2.putExtra("CropImage_OutputPath", stringBuilder.append(c.Gb()).append("custom_shake_img_filename.jpg").toString());
a.ezn.a(intent2, 2, this, intent);
return;
}
return;
case 2:
if (intent != null) {
String stringExtra = intent.getStringExtra("CropImage_OutputPath");
au.HU();
c.DT().set(4110, Boolean.valueOf(false));
au.HU();
c.DT().set(4111, stringExtra);
return;
}
return;
default:
return;
}
}
}
|
package com.github.hippo.util;
/**
* 序列化工具 fst
*
* @author sl
*/
public class SerializationUtils {
private SerializationUtils() {
}
/**
* 序列化
*
* @param obj obj
* @param <T> 泛型
* @return data[]
*/
@SuppressWarnings("unchecked")
public static <T> byte[] serialize(T obj) {
return org.springframework.util.SerializationUtils.serialize(obj);
}
/**
* 反序列化
*
* @param data origin data
* @param cls obj
* @return cls.instance
*/
public static <T> T deserialize(byte[] data, Class<T> cls) {
return (T) org.springframework.util.SerializationUtils.deserialize(data);
}
}
|
package com.example.solo.newremindapp.domain;
public class Remind {
private int id;
private String date;
private String time;
private String remind;
public Remind() {
}
public Remind(int id, String date, String time, String remind) {
this.id = id;
this.date = date;
this.time = time;
this.remind = remind;
}
public Remind(String date, String time, String remind) {
this.date = date;
this.time = time;
this.remind = remind;
}
public int getId() {
return id;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getRemind() {
return remind;
}
public void setRemind(String remind) {
this.remind = remind;
}
}
|
package pages;
import elements.Language;
import elements.ProductItem;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.FindBy;
public class HomePage extends BasePage {
@FindBy(className = "blocks__item--cfd")
public ProductItem cfdProduct;
@FindBy(id = "language-menu")
public Language homeLanguage;
public HomePage(WebDriver driver) {
super(driver);
}
}
|
package com.goodhealth.framework.entity.user;
/**
* 用户客户端信息
*/
public class UserClientInfoEntity {
/**
* 客户端ip
*/
private String clientIp;
/**
* 标识客户使用的操作系统及版本、CPU 类型、浏览器及版本、浏览器渲染引擎、浏览器语言、浏览器插件等
*/
private String userAgent;
public String getClientIp() {
return clientIp;
}
public void setClientIp(String clientIp) {
this.clientIp = clientIp;
}
public String getUserAgent() {
return userAgent;
}
public void setUserAgent(String userAgent) {
this.userAgent = userAgent;
}
}
|
package com.vilio.nlbs.commonMapper.pojo;
public class NlbsRoleMenu {
private Integer id;
private String code;
private String roleCode;
private String menuCode;
public NlbsRoleMenu(Integer id, String code, String roleCode, String menuCode) {
this.id = id;
this.code = code;
this.roleCode = roleCode;
this.menuCode = menuCode;
}
public NlbsRoleMenu() {
super();
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code == null ? null : code.trim();
}
public String getRoleCode() {
return roleCode;
}
public void setRoleCode(String roleCode) {
this.roleCode = roleCode == null ? null : roleCode.trim();
}
public String getMenuCode() {
return menuCode;
}
public void setMenuCode(String menuCode) {
this.menuCode = menuCode == null ? null : menuCode.trim();
}
}
|
package com.links.gaurav.lnotes;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MotionEvent;
import android.view.View;
import android.support.v7.widget.Toolbar.*;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.davemorrissey.labs.subscaleview.ImageSource;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
/**
* Created by Gaurav on 7/19/2017.
*/
public class FullscreenImage extends AppCompatActivity{
String path;
SubsamplingScaleImageView imgDisplay;
Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.full_screen_image);
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if (extras == null) {
path = null;
} else {
path = extras.getString("path");
}
} else {
path = (String) savedInstanceState.getSerializable("path");
}
toolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(toolbar);
toolbar.setVisibility(View.VISIBLE);
imgDisplay = (SubsamplingScaleImageView) findViewById(R.id.imgDisplay);//else write v.find....
//PhotoView photoView = (PhotoView) findViewById(R.id.photo_view);
//Glide.with(this).load(path).into(imgDisplay);
imgDisplay.setImage(ImageSource.uri(path));
imgDisplay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
toggle_bar();
}
});
}
void toggle_bar(){
if(toolbar.getVisibility()==View.VISIBLE)
toolbar.setVisibility(View.GONE);
else toolbar.setVisibility(View.VISIBLE);
}
}
|
/**HW3 - Factory design Decorator
* Cesar Hernandez
* cherna83
*
*/
//=============================================================
public class FactoryDecorator
{
public static void main(String[] args)
{
System.out.println("\nChoose between 5 burger decorators to build your burger:");
System.out.println("\nBurger options include basicBurger, SalmonBurger, GrassfedBurger, BlackbeanBurger");
System.out.println("with GrilledOnions, FriedEgg, Bacon, Avocado & RoastedPeppers\n");
//order #1
Burger order = new Avocado(new FriedEgg (new GrilledOnions(BurgerFactory.getBurger("IB"))));
double cost = order.makeBurger();
System.out.println("Total: $" + cost);
System.out.println("\n");
//order #2
Burger order2 = new FriedEgg(new GrilledOnions(BurgerFactory.getBurger("blb")));
double cost2 = order2.makeBurger();
System.out.println("Total: $" + cost2 );
System.out.println("\n");
//order #3
Burger order3 = new RoastedPeppers(new FriedEgg(new Bacon(new GrilledOnions(new Avocado(BurgerFactory.getBurger("sb"))))));
double cost3 = order3.makeBurger();
System.out.println("Total: $" + cost3);
System.out.println("\n");
//order #4
Burger order4 = new Avocado(new FriedEgg(new RoastedPeppers(BurgerFactory.getBurger("gb"))));
double cost4 = order4.makeBurger();
System.out.println("Total: $" + cost4);
System.out.print("\n\n");
}
}
//=============================================================
//---------------------------------------------------------
//interface one operator
//Interface = Burger
interface Burger
{
public double makeBurger();
}
//---------------------------------------------------------
//base class
//concrete component
class basicBurger implements Burger
{
private double cost = 3.00;
public double makeBurger()
{
System.out.println("Basic Burger: $3.00");
return cost;
}
}
//================----------------------------------------
class SalmonBurger implements Burger
{
private double cost = 4.00;
public double makeBurger()
{
System.out.println("Salmon Burger: $4.00");
return cost;
}
}
//================----------------------------------------
class GrassfedBurger implements Burger
{
private double cost = 5.00;
public double makeBurger()
{
System.out.println("GrassfedBurger: $5.00");
return cost;
}
}
//================----------------------------------------
class BlackbeanBurger implements Burger
{
private double cost = 6.00;
public double makeBurger()
{
System.out.println("Black bean Burger: $6.00");
return cost;
}
}
//================----------------------------------------
class BurgerFactory
{
public static Burger getBurger(String type)
{
switch(type)
{
case "sb":
return new SalmonBurger();
case "gb":
return new GrassfedBurger();
case "blb":
return new BlackbeanBurger();
default:
System.out.println("unknown option returning basic Burger");
return new basicBurger();
}
}
}
//---------------------------------------------------------
//aggragates an interface
//abstract class
//decorator
abstract class BurgerDecorator implements Burger
{
protected Burger specialBurger;
public BurgerDecorator(Burger specialBurger)
{
this.specialBurger = specialBurger;
}
//single abstract method
public double makeBurger()
{
return specialBurger.makeBurger();
}
}
//---------------------------------------------------------
//decorator #1
class FriedEgg extends BurgerDecorator
{
private double cost = 1.50;
public FriedEgg(Burger specialBurger)
{
super(specialBurger);
}
public double makeBurger()
{
return specialBurger.makeBurger() + addFriedEgg();
}
public double addFriedEgg()
{
System.out.println(" + FriedEgg: $1.50");
return cost;
}
}
//---------------------------------------------------------
//decorator #2
class Avocado extends BurgerDecorator
{
private double cost = .75;
public Avocado(Burger specialBurger)
{
super(specialBurger);
}
public double makeBurger()
{
return specialBurger.makeBurger() + addAvocado();
}
public double addAvocado()
{
System.out.println(" + Avocado: $.75");
return cost;
}
}
//---------------------------------------------------------
//Concrete
//Decorator #3
class Bacon extends BurgerDecorator
{
private double cost = 2.00;
public Bacon(Burger specialBurger)
{
super(specialBurger);
}
public double makeBurger()
{
return specialBurger.makeBurger() + addBacon();
}
public double addBacon()
{
System.out.println(" + Bacon: $2.00");
return cost;
}
}
//---------------------------------------------------------
//decorator #4
class GrilledOnions extends BurgerDecorator
{
private double cost = 1.00;
public GrilledOnions(Burger specialBurger)
{
super(specialBurger);
}
public double makeBurger()
{
return specialBurger.makeBurger() + addGrilledOnions();
}
public double addGrilledOnions()
{
System.out.println(" + GrilledOnions: $1.00");
return cost;
}
}
//---------------------------------------------------------
//decorator #5
class RoastedPeppers extends BurgerDecorator
{
private double cost = 5.00;
public RoastedPeppers(Burger specialBurger)
{
super(specialBurger);
}
public double makeBurger()
{
return specialBurger.makeBurger() + addRoastedPeppers();
}
public double addRoastedPeppers()
{
System.out.println(" + RoastedPeppers: $5.00");
return cost;
}
}
//---------------------------------------------------------
//=======================================================================
|
package myproject;
import java.util.ArrayList;
import java.util.Collections;
public class Mainclass {
public static void main(String[] args) {
ArrayList<String> F = new ArrayList<String>();
F.add("Rose");
F.add("Lilly");
F.add("Hibiscus");
F.add("Jasmine");
System.out.println("Original items in arraylist are:\n");
for(String flowers:F) {
System.out.println(flowers);
}
System.out.println("\nThe item at index 3 is: "+F.get(3));
F.set(3,"Blossom");
System.out.println("\nThe item at index 3 after altering is: "+F.get(3));
System.out.println("\nAfter altering.. items in arraylist are:\n");
for(String flowers:F) {
System.out.println(flowers);
}
System.out.println("\n....Sorting.....");
Collections.sort(F);
System.out.println("\nAfter sorting.. items in arraylist are:\n");
for(String flowers:F) {
System.out.println(flowers);
}
System.out.println("\n..... Removing element at 1.....");
F.remove(1);
System.out.println("\nAfter removing.. items in arraylist are:\n");
for(String flowers:F) {
System.out.println(flowers);
}
System.out.println("\nSize of arraylist is:"+F.size());
System.out.println("\n...........Clearing all elements.......");
System.out.println("\nAfter clearing.. items in arraylist are:");
F.clear();
System.out.println(F);
// TODO Auto-generated method stub
}
}
|
package com.hqhcn.android.service.impl;
import com.hqh.android.dao.KsldMapper;
import com.hqh.android.entity.Carinfo;
import com.hqh.android.entity.CarinfoExample;
import com.hqh.android.entity.Ksld;
import com.hqh.android.entity.KsldExample;
import com.hqh.android.service.CarinfoService;
import com.hqh.android.service.KsldService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
public class KsldServiceImpl implements KsldService {
@Autowired
private KsldMapper mapper;
@Autowired
private CarinfoService carinfoService;
@Override
public List<Ksld> queryToPage(KsldExample example) {
return mapper.selectByExampleToPage(example);
}
@Override
public List<Ksld> selectByExample(KsldExample example) {
return mapper.selectByExample(example);
}
@Override
public Ksld get(String id) {
return mapper.selectByPrimaryKey(id);
}
@Override
public Ksld getByName(String name) {
if (StringUtils.isNotEmpty(name)) {
KsldExample example = new KsldExample();
example.createCriteria().andNameEqualTo(name);
List<Ksld> kslds = selectByExample(example);
return kslds == null ? null : kslds.get(0);
}else{
return null;
}
}
@Override
public int add(Ksld entity) {
return mapper.insertSelective(entity);
}
@Override
public void update(Ksld entity) {
mapper.updateByPrimaryKeySelective(entity);
}
@Override
public void update(Ksld entity, KsldExample example) {
mapper.updateByExampleSelective(entity, example);
}
@Override
@Transactional
public void del(Ksld entity) throws Exception {
entity = get(entity.getId());
CarinfoExample carinfoExample = new CarinfoExample();
carinfoExample.createCriteria().andKsldEqualTo(entity.getName());
List<Carinfo> carinfos = carinfoService.query(carinfoExample);
if (CollectionUtils.isEmpty(carinfos)){
mapper.deleteByPrimaryKey(entity.getId());
}else {
throw new Exception("此考试路线正在使用中,删除失败!");
}
}
}
|
package edu.mayo.cts2.framework.core.timeout;
import java.util.concurrent.ConcurrentHashMap;
public class Timeout
{
private static ConcurrentHashMap<Long, Boolean> timedOutThreads = new ConcurrentHashMap<Long, Boolean>();
public static boolean isTimeLimitExceeded()
{
return isTimeLimitExceeded(Thread.currentThread().getId());
}
public static boolean isTimeLimitExceeded(Long threadId)
{
Boolean b = timedOutThreads.get(threadId);
return (b == null ? false : b.booleanValue());
}
public static void setTimeLimitExceeded(Long threadId)
{
timedOutThreads.put(threadId, true);
}
public static void clearThreadFlag(Long threadId)
{
timedOutThreads.remove(threadId);
}
}
|
package org.star.uml.designer.ui.newWiazrds;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.internal.ide.IDEWorkbenchMessages;
import org.eclipse.ui.internal.ide.filesystem.FileSystemConfiguration;
import org.eclipse.ui.internal.ide.filesystem.FileSystemSupportRegistry;
public class ClassSorceCodeGenerationPage extends WizardPage {
public static final String PAGE_NAME = "Summary";
private Label textLabel;
private Button button;
private Text text;
protected ClassSorceCodeGenerationPage(String pageName) {
super(PAGE_NAME, "Source Code Generation", null);
setDescription("Generation java source code from Classdiagram.");
}
@Override
public void createControl(final Composite parent) {
Composite topLevel = new Composite(parent, SWT.NONE);
topLevel.setLayout(new GridLayout(3, false));
Label l = new Label(topLevel, SWT.CENTER);
l.setText("Source code generate loaction : ");
text = new Text(topLevel, SWT.SINGLE);
text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
text.setSize(100, 15);
button = new Button(topLevel, SWT.BUTTON1);
button.setText("Browser");
final String dirName = "";
button.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
FileSystemConfiguration config = FileSystemSupportRegistry.getInstance().getDefaultConfiguration();
DirectoryDialog dialog = new DirectoryDialog(button.getShell(), SWT.SHEET);
dialog.setMessage(IDEWorkbenchMessages.ProjectLocationSelectionDialog_directoryLabel);
dialog.setFilterPath(dirName);
String selectedDirectory = dialog.open();
text.setText(selectedDirectory);
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
setControl(topLevel);
setPageComplete(true);
}
}
|
/**
* TaskSpider Testing class
* @author Simone Notargiacomo, Giuseppe Schipani
*/
package taskspider.spider.testing;
import websphinx.searchengine.*;
import websphinx.*;
import java.net.*;
import java.io.*;
import java.util.*;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.store.*;
import taskspider.spider.core.*;
import taskspider.util.properties.*;
import taskspider.data.document.*;
import taskspider.retrieval.core.*;
import taskspider.retrieval.wordnet.*;
/**
* @author Simone Notargiacomo, Giuseppe Schipani
*/
public class Testing {
/**
* @param args
*/
public static void main(String[] args) {
// try {
// if(!IndexReader.indexExists(taskspider.util.properties.PropertiesReader.getProperty("wordnetIndexPath"))) {
// Syns2Index.generateIndex();
// }
// Link[] links = { new Link("http://www.mtv.com/") /*new Link("http://www.mtv.it")/*new Link("http://www.beppegrillo.it") *//*new Link("http://www.maglificiosalerno.it"),*/ /*new Link("http://www.alessioluffarelli.it")/*, new Link("http://www.google.com"), new Link("http://www.ibm.com")*/ };
// Spider spider = new Spider(links);
// spider.setMaxLevel(1);
// spider.start();
// SpiderExplorer spiderExplorer = new SpiderExplorer(spider);
// spiderExplorer.start();
// Indexer indexer = new Indexer("musica", spiderExplorer);
// Vector<Document> docs = spiderExplorer.getDocs();
// TermSearcher searcher = new TermSearcher("musica");
// int start = 0;
// int end = docs.size();
// indexer.indexDocs(docs, start, end);
// int retry=0;
// while(start!=end || retry<4) {
// if(start==end)
// retry++;
// else
// retry=0;
// System.out.println("start: "+start+", end: "+end);
//
// indexer.indexDocs(spiderExplorer.getDocs(), start, end);
// Thread.sleep(2000);
// start = end;
// end = docs.size();
// searcher.search("url:music AND body:music");
//
// }
// spiderExplorer.interrupt();
// System.out.println("STOPPED "+start+" "+end);
// indexer.getDocument();
//
// }
// catch(MalformedURLException ex) {ex.printStackTrace();}
// catch(InterruptedException ex1) {ex1.printStackTrace();}
}
}
|
/*
* Copyright (c) 2012-2013 ${developer}, <http://windwaker.me>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package me.windwaker.permissions.permissible;
import java.util.Map;
import me.windwaker.permissions.WindPerms;
import me.windwaker.permissions.io.UserManager;
import org.spout.api.data.DataValue;
/**
* Represents a user entity.
* @author Windwaker
*/
public class User extends Permissible {
private final UserManager userManager;
private Group group;
/**
* Constructs a new user with the specified name.
* @param name
*/
public User(WindPerms plugin, String name) {
super(name);
userManager = plugin.getUserManager();
}
/**
* Sets the user's group
* @param group
*/
public void setGroup(Group group) {
// Update group references to user
if (this.group != null) {
this.group.removeUser(this);
}
this.group = group;
group.addUser(this);
// inherit the group's data
inherit(group);
// Save
if (autoSave) {
save();
}
}
public void inherit(Group group) {
// inherit nodes
for (Map.Entry<String, Boolean> node : group.getInheritedPermissions().entrySet())
inheritedNodes.put(node.getKey(), node.getValue());
for (Map.Entry<String, Boolean> node : group.getPermissions().entrySet())
inheritedNodes.put(node.getKey(), node.getValue());
// inherit data
for (Map.Entry<String, DataValue> data : group.getInheritedMetadataMap().entrySet())
inheritedMetadata.put(data.getKey(), data.getValue());
for (Map.Entry<String, DataValue> data : group.getMetadataMap().entrySet())
inheritedMetadata.put(data.getKey(), data.getValue());
}
/**
* Gets the user's group.
* @return the user's group.
*/
public Group getGroup() {
return group;
}
@Override
public void save() {
userManager.saveUser(this);
}
}
|
/*
* @file GoodcatManageDaoImpl.java
* 文件摘要.
* 文件的详细说明
* :
* @author 刘青勇
* @copyright 青岛一凌网集成有限公司2013
* @version 20120101 刘青勇 v1.0
*/
package com.lingnet.vocs.dao.impl.jcsj;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.SQLQuery;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import com.lingnet.common.dao.impl.BaseDaoImplInit;
import com.lingnet.util.Pager;
import com.lingnet.vocs.dao.jcsj.GoodcatManageDao;
import com.lingnet.vocs.entity.Goodcat;
import com.lingnet.vocs.entity.Item;
/*************************************************/
/*
* GoodcatManageDaoImpl
* 摘要说明.
* @Description:
* :
* @author 刘青勇
* @version 2013-9-12
*/
/*************************************************/
@Repository("goodcatManageDao")
public class GoodcatManageDaoImpl extends BaseDaoImplInit<Goodcat, String> implements GoodcatManageDao {
private static int seq = 0;
private static long currentTime = 0;
/**
* 商品类型代码查询
*/
@Override
public Goodcat getByGoodcatcode(String goodcatcode){
String Hql = "from Goodcat as goodcat where goodcat.goodcatcode = ? and goodcat.is_delete = '0' ";
Goodcat goodcat=uniqueResult(Hql, goodcatcode);
return goodcat;
}
/**
* 分页查询
*/
@Override
public Pager findPagerByCode(Pager pager,String pgoodcatcode,String flag) throws Exception {
//声明Criteria
Criteria criteria=getSession().createCriteria(Item.class);
//Criteria执行查询
criteria.add(Restrictions.eq("is_delete", "0"));
if("goodcat".equals(flag)){
criteria.add(Restrictions.eq("itemclassId",(pgoodcatcode.trim())));
}else{
criteria.add(Restrictions.eq("unit",(pgoodcatcode.trim())));
}
pager = findPager(pager,criteria);
return pager;
}
@Override
public Goodcat getByGoodcatName(String goodcatName) {
String Hql = "from Goodcat as goodcat where goodcat.goodcatname = ? and is_delete = '0'";
return uniqueResult(Hql, goodcatName);
}
@Override
public String beachAdd(String fromLine, String toLine, List<String[]> list)
throws Exception {
SimpleDateFormat sdf= new SimpleDateFormat("yyMMddHHmmss");
Date datem=new Date();
String sql = "insert into jcsj_wllx(id,createdate,modifydate,BMQZ,LJF,WLLXDM,WLLXMC,P_WLLXDM,IS_DELETE)"
+"VALUES(?,?,?,?,?,?,?,?,?)";
this.getSession().connection().setAutoCommit(false);
PreparedStatement prest = this .getSession().connection().prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
Long isLocked = 0l;
String allowValue="true";
for (int i = 0; i < list.size(); i++) {
String[] str = new String[5];
String[] values = list.get(i);
if(values.length>5){
throw new Exception("请选择正确的产品类别导入文件!");
}
for(int q=0;q<values.length;q++){
str[q]=values[q];
}
for(int k=values.length;k<4;k++){
str[k]="";
}
//得到唯一ID
currentTime = System.currentTimeMillis();
long t1 = System.currentTimeMillis();
if (Math.abs(Math.abs(t1) - Math.abs(currentTime)) < 1) {
if ((seq + 1) >= 100) {
seq = 0;
}
seq++;
}
StringBuilder id = new StringBuilder();
id.append(t1);
id.append(seq);
prest.setString(1, id.toString());
//创建时间,修改时间
prest.setDate(2, new java.sql.Date(datem.getTime()));
prest.setDate(3, new java.sql.Date(datem.getTime()));
int a= Integer.parseInt(fromLine);
for (int j = 0; j <str.length; j++) {
if(j==0){
if(str[0]!=null && !"".equals(str[0])){
if(str[0].length()>50){
return "导入数据:第"+(i+a)+"行,</br>商品种类代号大于50字符!导入失败!";
}
//begain zrl 2016-7-4 筛选商品种类代号重复
StringBuilder xdm=new StringBuilder()
.append(" SELECT q.BMQZ,q.WLLXDM,q.WLLXMC ")
.append(" FROM JCSJ_WLLX q ")
.append(" WHERE WLLXDM = '"+str[0]+" ' and is_delete ='0' ")
;
SQLQuery query=this.getSession().createSQLQuery(xdm.toString());
List resultxdm=query.list();
if(null == resultxdm || resultxdm.size() ==0){
prest.setString(6, str[0]);//商品种类代号
}
else{
return "导入数据:第"+(i+a)+"行,</br>商品种类代号与之前重复!</br>商品种类代号不能重复,导入失败!";
}
//end zrl 2016-7-4 筛选商品种类代号重复
}else{
return "导入数据:第"+(i+a)+"行,</br>商品种类代号为空!</br>商品种类代号不能为空,导入失败!";
}
}
if(j==1){
if(str[1].length()>50){
return "导入数据:第"+(i+a)+"行,</br>商品种类名称大于50字符!导入失败!";
}
if(str[1]!=null && !"".equals(str[1])){
//begain mzm 2016/7/16 原因 商品代号,名称,前缀,各不能与数据库相同!
Goodcat goodcatna=this.get(Restrictions.eq("goodcatname", str[1].toString()),Restrictions.eq("is_delete", "0"));
if(goodcatna!=null && Goodcat.DELETE != goodcatna.getIs_delete()){
throw new Exception("导入数据:第"+(i+a)+"行,</br>商品种类名称与之前重复!</br>商品种类名称不能重复,导入失败!");
}
//end mzm 2016/7/16 原因 商品代号,名称,前缀,各不能与数据库相同!
prest.setString(7, str[1]);//商品种类名称
}else{
return "导入数据:第"+(i+a)+"行,</br>商品种类名称为空!</br>商品种类名称不能为空,导入失败!";
}
}
if(j==2){
if(str[2]!=null && !"".equals(str[2])){
//begain mzm 2016/7/16 原因 商品代号,名称,前缀,各不能与数据库相同!
Goodcat codehead=this.get(Restrictions.eq("codeheader", str[2].toString()),Restrictions.eq("is_delete", "0"));
if(codehead!=null && Goodcat.DELETE != codehead.getIs_delete()){
throw new Exception("导入数据:第"+(i+a)+"行,</br>编码前缀与之前重复!</br>编码前缀不能重复,导入失败!");
}
//end mzm 2016/7/16 原因 商品代号,名称,前缀,各不能与数据库相同!
prest.setString(4, str[2]);//编码前缀
}else{
return "导入数据:第"+(i+a)+"行,</br>编码前缀为空!</br>编码前缀不能为空,导入失败!";
}
}
if(j==3){
if("-".equals(str[3])){
prest.setInt(5, 1);
} else {
prest.setInt(5, 0);
}
}
//begain mzm 2016/7/25 商品父类导入
if(j==4){
if(str[4]!=null && !"".equals(str[4])){
Goodcat goodcatna=this.get(Restrictions.eq("goodcatname", str[4].toString()));
if(goodcatna!=null && Goodcat.DELETE != goodcatna.getIs_delete()){
prest.setString(8, str[4]);
}else{
throw new Exception("导入数据:第"+(i+a)+"行,</br>没有该商品种类名称!</br>请核对父类名称!导入失败!");
}
} else {
prest.setString(8, "all");
}
}
//end mzm 2016/7/25 商品父类导入
}
//未删除状态
prest.setString(9, isLocked.toString());
prest.addBatch();
}
try{
prest.executeBatch();
}catch (Exception e){
throw new Exception("上传格式不正确");
}
this.getSession().connection().commit();
return "success";
}
}
|
package com.ht.springboot_shiro.controller;
import com.ht.springboot_shiro.domain.User;
import com.ht.springboot_shiro.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpSession;
/**
* @company 宏图
* @User Kodak
* @create 2019-06-02 -20:02
* @Email:2270301642@qq.com
*/
@Controller
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("testThymeleaf")
public String testThymeleaf(Model model){
return "hello";
}
@RequestMapping("add")
public String add(){
return "user/add";
}
@RequestMapping("upd")
public String update(){
return "user/update";
}
@RequestMapping("tologin")
public String tologin(){
return "login";
}
@RequestMapping("noAuth")
public String noAuth(){
return "noAuth";
}
@RequestMapping("/login")
public String login(String name, String pwd, Model model, HttpSession session){
System.out.println(name+" "+pwd);
//获取subject
Subject subject= SecurityUtils.getSubject();
//封装用户数据
UsernamePasswordToken token=new UsernamePasswordToken(name,pwd);
//执行登录方法
try {
subject.login(token);
User user=(User) subject.getPrincipal();
session.setAttribute("user",user);
System.out.println(user.getName()+user.getPwd()+"session");
// System.out.println("shiro中的session");
// System.out.println("用户IP地址"+session.getHost()+" 用户shiroID"+session.getId());
// session.touch();
return "hello";
}catch (UnknownAccountException e){
model.addAttribute("msg","用户名不存在");
return "login";
}catch (IncorrectCredentialsException e){
model.addAttribute("msg","密码错误");
return "login";
}
}
//移除session
@RequestMapping("/loginout")
public String loginout(HttpSession session){
session.removeAttribute("user");
return "hello";
}
}
|
package com.tencent.mm.plugin.sport.ui;
import android.content.Intent;
import com.tencent.mm.model.au;
import com.tencent.mm.model.c;
import com.tencent.mm.model.s;
import com.tencent.mm.plugin.sport.b.d;
import com.tencent.mm.pluginsdk.ui.applet.ContactListExpandPreference.a;
class SportBlackListUI$2 implements a {
final /* synthetic */ SportBlackListUI opx;
SportBlackListUI$2(SportBlackListUI sportBlackListUI) {
this.opx = sportBlackListUI;
}
public final void of(int i) {
String Cc = SportBlackListUI.a(this.opx).Cc(i);
SportBlackListUI.b(this.opx).remove(Cc);
SportBlackListUI.a(this.opx).p(null, SportBlackListUI.b(this.opx));
SportBlackListUI.a(this.opx).refresh();
au.HU();
s.g(c.FR().Yg(Cc));
d.kB(40);
}
public final void oh(int i) {
SportBlackListUI.c(this.opx);
}
public final void og(int i) {
String Cc = SportBlackListUI.a(this.opx).Cc(i);
Intent intent = new Intent();
intent.putExtra("Contact_User", Cc);
com.tencent.mm.bg.d.b(this.opx, "profile", ".ui.ContactInfoUI", intent);
}
public final void aAK() {
SportBlackListUI.a(this.opx).cdV();
}
}
|
package ioio.examples.hello;
import ioio.lib.api.exception.ConnectionLostException;
public interface MotorController {
public void turnMotorA(boolean direction) throws ConnectionLostException;
public void turnMotorB(boolean direction) throws ConnectionLostException;
public void setMotorA_speed(float speed) throws ConnectionLostException;
public void setMotorB_speed(float speed) throws ConnectionLostException;
public void stop() throws ConnectionLostException;
public void close();
}
|
/*
* 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 contactmanagementsoftware;
/**
*
* @author jiefo
*/
public class VoidState extends PanelState {
public VoidState(MUI mui) {
super(mui);
}
@Override
void setFormFieldEditable() {
setFormFieldEditable(false);
}
@Override
void setPanelTitle() {
setPanelTitle("");
}
@Override
void setConfirmButton() {
mui.getJButtonConfirmDetails().setVisible(false);
}
@Override
void setCancelButton() {
mui.getJButtonCancleDetails().setVisible(false);
}
}
|
package com.johan.workexecutor;
/**
* Created by Administrator on 2016/9/26.
*/
public interface WorkResultReceiver {
void receiveWorkSuccess(DataProvider dataProvider);
void receiveWorkCancel();
void receiveWorkFail(Exception exception);
}
|
package it.unical.asd.group6.computerSparePartsCompany.core.services.implemented;
import it.unical.asd.group6.computerSparePartsCompany.core.services.WarehouseService;
import it.unical.asd.group6.computerSparePartsCompany.data.dao.WarehouseDao;
import it.unical.asd.group6.computerSparePartsCompany.data.entities.Warehouse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
public class WarehouseServiceImpl implements WarehouseService {
@Autowired
WarehouseDao warehouseDao;
@Override //TODO PROBABILE REFACTOR
public Warehouse getWarehouseById(Long id){
Optional<Warehouse> wh = warehouseDao.findWarehouseById(id);
if (wh.isPresent())
return wh.get();
return null;
}
}
|
package com.vilio.plms.service.quartz;
import com.vilio.plms.exception.ErrorException;
public interface PayRepaymentScheduleDetailService{
void execute()throws Exception;
}
|
package omr.caesarcipher;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class CaesarCipherEncryptDecryptTest {
@Test
public void caesarCipherRotateLeft() {
assertEquals("E", new CaesarCipher("E").rotateLeft(0).getText());
assertEquals("D", new CaesarCipher("E").rotateLeft(1).getText());
assertEquals("C", new CaesarCipher("E").rotateLeft(2).getText());
assertEquals("B", new CaesarCipher("E").rotateLeft(3).getText());
assertEquals("A", new CaesarCipher("E").rotateLeft(4).getText());
assertEquals("Z", new CaesarCipher("E").rotateLeft(5).getText());
assertEquals("Y", new CaesarCipher("E").rotateLeft(6).getText());
assertEquals("E", new CaesarCipher("E").rotateLeft(26).getText());
assertEquals("C", new CaesarCipher("E").rotateLeft(28).getText());
assertEquals("A", new CaesarCipher("E").rotateLeft(30).getText());
assertEquals("Z", new CaesarCipher("E").rotateLeft(31).getText());
assertEquals("E", new CaesarCipher("E").rotateLeft(52).getText());
assertEquals("L", new CaesarCipher("E").rotateLeft(19).getText());
assertEquals("!", new CaesarCipher("!").rotateLeft(12).getText());
assertEquals(".", new CaesarCipher(".").rotateLeft(2).getText());
assertEquals(".", new CaesarCipher(".").rotateLeft(1).getText());
}
@Test
public void caesarCipherRotateRight() {
assertEquals("V", new CaesarCipher("V").rotateRight(0).getText());
assertEquals("W", new CaesarCipher("V").rotateRight(1).getText());
assertEquals("X", new CaesarCipher("V").rotateRight(2).getText());
assertEquals("Y", new CaesarCipher("V").rotateRight(3).getText());
assertEquals("Z", new CaesarCipher("V").rotateRight(4).getText());
assertEquals("A", new CaesarCipher("V").rotateRight(5).getText());
assertEquals("B", new CaesarCipher("V").rotateRight(6).getText());
assertEquals("V", new CaesarCipher("V").rotateRight(26).getText());
assertEquals("X", new CaesarCipher("V").rotateRight(28).getText());
assertEquals("Z", new CaesarCipher("V").rotateRight(30).getText());
assertEquals("A", new CaesarCipher("V").rotateRight(31).getText());
assertEquals("V", new CaesarCipher("V").rotateRight(52).getText());
assertEquals("L", new CaesarCipher("V").rotateRight(16).getText());
assertEquals("!", new CaesarCipher("!").rotateRight(12).getText());
assertEquals(".", new CaesarCipher(".").rotateRight(2).getText());
assertEquals(".", new CaesarCipher(".").rotateRight(1).getText());
}
}
|
package org.ah.minecraft.armour.utils;
import org.ah.minecraft.armour.Plugin;
import org.bukkit.Effect;
import org.bukkit.Material;
import org.bukkit.block.Block;
public class FrostedBlock {
private Block b;
public long time = 0;
public long max = 30;
private Material to;
private Material type;
public FrostedBlock(Block b, Material to) {
this.b = b;
this.to = to;
type = b.getType();
}
public FrostedBlock(Block b, Material to, long time) {
this.b = b;
this.to = to;
max = time;
type = b.getType();
}
public boolean tick() {
time++;
if (b.getType() != type) {
return true;
}
b.setType(type);
if (time > max * 0.9) {
}
if (time > max) {
b.getWorld().playEffect(b.getLocation(), Effect.STEP_SOUND, b.getType());
b.setType(to);
return true;
}
return false;
}
public Block getB() {
return b;
}
public void setB(Block b) {
this.b = b;
}
public static void setBlock(Block b, Material m) {
setBlock(b, m, 100);
}
public static void setBlock(Block b, Material m, int t) {
Material ty = b.getType();
b.getWorld().playEffect(b.getLocation(), Effect.STEP_SOUND, m);
b.setType(m);
Plugin.s.add(new FrostedBlock(b, ty, t));
}
}
|
package MRTopUser;
import java.io.IOException;
import java.net.URISyntaxException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
public class TopUserDriver {
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException, URISyntaxException {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "analysisTopUser");
// //skip the bad records
// job.getConfiguration().setInt("mapreduce.max.map.failures.percent", 10);
// job.getConfiguration().setInt("mapreduce.max.reduce.failures.percent", 10);
//input
job.setInputFormatClass(TextInputFormat.class);
TextInputFormat.addInputPath(job, new Path(args[0]));
job.setJarByClass(TopUserDriver.class);
job.setMapperClass(TopUserMapper.class);
job.setReducerClass(TopUserReducer.class);
job.setPartitionerClass(TopUserPartitioner.class);
job.setGroupingComparatorClass(GroupComparator.class);
job.setMapOutputKeyClass(CompositeKey.class);
job.setMapOutputValueClass(LongWritable.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(LongWritable.class);
//output
job.setOutputFormatClass(TextOutputFormat.class);
TextOutputFormat.setOutputPath(job, new Path(args[1]));
boolean b = job.waitForCompletion(true);
System.exit(b? 0 : 1);
}
}
|
//347. Top K Frequent Elements
class Solution {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer>
hashMap = new HashMap();
int count = 0;
for (int i = 0; i < nums.length; i++)
{
count = hashMap.getOrDefault(nums[i], 0);
hashMap.put(nums[i], count+1);
}
PriorityQueue<Integer>
queue = new PriorityQueue((n1,n2) -> hashMap.get(n2) - hashMap.get(n1));
Set<Integer>
keys = hashMap.keySet();
for (int ele : keys)
{
queue.offer(ele);
}
int[] ans = new int[k];
int i = 0;
while(k != 0)
{
ans[i++] = queue.poll();
k--;
}
return ans;
}
}
|
package algorithms.tasks;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class PowerSumTest {
@Test
void testCase1() {
int x = 10;
int y = 2;
int expected = 1;
int result = PowerSum.powerSum(x, y);
assertThat(result).isEqualTo(expected);
}
@Test
void testCase2() {
int x = 100;
int y = 2;
int expected = 3;
int result = PowerSum.powerSum(x, y);
assertThat(result).isEqualTo(expected);
}
@Test
void testCase3() {
int x = 100;
int y = 3;
int expected = 1;
int result = PowerSum.powerSum(x, y);
assertThat(result).isEqualTo(expected);
}
}
|
package com.xiaoxiao.service.backend.impl;
import com.xiaoxiao.feign.RedisCacheFeignClient;
import com.xiaoxiao.mapper.MenuMapper;
import com.xiaoxiao.pojo.XiaoxiaoMenu;
import com.xiaoxiao.service.backend.MenuService;
import com.xiaoxiao.utils.Result;
import com.xiaoxiao.utils.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* _ooOoo_
* o8888888o
* 88" . "88
* (| -_- |)
* O\ = /O
* ____/`---'\____
* .' \\| |// `.
* / \\||| : |||// \
* / _||||| -:- |||||- \
* | | \\\ - /// | |
* | \_| ''\---/'' | |
* \ .-\__ `-` ___/-. /
* ___`. .' /--.--\ `. . __
* ."" '< `.___\_<|>_/___.' >'"".
* | | : `- \`.;`\ _ /`;.`/ - ` : | |
* \ \ `-. \_ __\ /__ _/ .-` / /
* ======`-.____`-.___\_____/___.-`____.-'======
* `=---='
* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
* 佛祖保佑 永无BUG
* 佛曰:
* 写字楼里写字间,写字间里程序员;
* 程序人员写程序,又拿程序换酒钱。
* 酒醒只在网上坐,酒醉还来网下眠;
* 酒醉酒醒日复日,网上网下年复年。
* 但愿老死电脑间,不愿鞠躬老板前;
* 奔驰宝马贵者趣,公交自行程序员。
* 别人笑我忒疯癫,我笑自己命太贱;
* 不见满街漂亮妹,哪个归得程序员?
*
* @project_name:xiaoxiao_blogs
* @date:2019/11/26:17:18
* @author:shinelon
* @Describe:
*/
@Service
public class MenuServiceImpl implements MenuService
{
@Autowired
private MenuMapper menuMapper;
@Autowired
private RedisCacheFeignClient client;
/**
* 查询全部的数据
* @return
*/
@Override
public Result findAllMenu()
{
/**
* 先查询缓存
*/
List<XiaoxiaoMenu> allMenu = null;
try
{
List<XiaoxiaoMenu> menuToRedis = this.client.getMenuToRedis();
if(menuToRedis != null){
return Result.ok(StatusCode.OK, true,menuToRedis);
}
allMenu = this.menuMapper.findAllMenu();
/**
* 如果没有缓存则插入缓存数据
*/
this.client.insertMenuToRedis(allMenu);
if(allMenu != null && allMenu.size() > 0){
return Result.ok(StatusCode.OK, true, allMenu);
}
} catch (Exception e)
{
e.printStackTrace();
}
return Result.error(StatusCode.ERROR, "暂无数据");
}
}
|
package org.throwable.wheel;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
/**
* =========================================================
* 北京五八信息技术有限公司架构部
*
* @author chenyang E-mail: chenyang@58.com
* @version Created :2014-1-17 下午01:37:00
* 类说明:
* =========================================================
* 修订日期 修订人 描述
*/
public final class Wheel<E> {
private final AtomicInteger currentIndex = new AtomicInteger(0);
private final Map<E, Slot<E>> elementsMap = new ConcurrentHashMap<>();
private final ArrayList<Slot<E>> slots;
private WheelState state = WheelState.RUNNING;
private final AtomicBoolean shutdown = new AtomicBoolean(false);
private static final Object MONITOR = new Object();
private static final int MAX_ALIVE_SECONDS = 60 * 60 * 24; // 最大存活时间为一天,86400秒
private final CopyOnWriteArrayList<ExpirationIntecepter<E>> expirationIntecepters = new CopyOnWriteArrayList<>();
private final Thread releasePoolThread;
private final Thread clockerThread;
private final ReleasePool<E> releasePool;
public synchronized static <E> Wheel<E> getInstance(int liveSeconds) {
if (liveSeconds < 1 || liveSeconds > MAX_ALIVE_SECONDS)
throw new IllegalArgumentException("Element live seconds must between 1 to 86400");
return new Wheel<>(liveSeconds);
}
private Wheel(int liveSeconds) {
// 每秒钟一个槽
slots = new ArrayList<>(liveSeconds);
for (int i = 0; i < liveSeconds; i++) {
slots.add(new Slot<>(i));
}
slots.trimToSize();
clockerThread = new Thread(new Clocker<>(this));
clockerThread.start();
releasePool = new ReleasePool<>(this);
releasePoolThread = new Thread(releasePool);
releasePoolThread.start();
}
private int expiredIndex() {
int current = currentIndex.get();
if (current == slots.size() - 1)
return 0;
return current + 1;
}
private void indexIncrement() {
if (!this.currentIndex.compareAndSet(slots.size() - 1, 0))
this.currentIndex.incrementAndGet();
}
Slot<E> getExpiredSlot() {
return slots.get(expiredIndex());
}
Slot<E> getCurrentSlot() {
return slots.get(currentIndex.get());
}
void doExpired(Slot<E> slot) {
HashSet<E> expiredElements = slot.getElementsAndFlush();
indexIncrement();
releasePool.add(expiredElements);
}
public void add(E e) {
if (WheelState.RUNNING != this.state)
throw new IllegalStateException("timing wheel is shuting down");
synchronized (MONITOR) {
removeExsit(e); // 把已有的元素删除掉
Slot<E> slot = getCurrentSlot();
slot.add(e);
elementsMap.put(e, slot);
System.out.println("add element:" + e);
}
}
public void add(E e, int peroid) {
if (WheelState.RUNNING != this.state)
throw new IllegalStateException("timing wheel is shuting down");
if (peroid > slots.size()){
throw new IllegalStateException("peroid must be less than wheel circle size");
}
synchronized (MONITOR) {
removeExsit(e); // 把已有的元素删除掉
int targetIndex = currentIndex.get() + peroid;
if (targetIndex > slots.size()){
targetIndex = targetIndex - slots.size();
}
Slot<E> slot = slots.get(targetIndex);
slot.add(e);
elementsMap.put(e, slot);
System.out.println("add element:" + e);
}
}
private void removeExsit(E e) {
Slot<E> slot = elementsMap.get(e);
if (slot != null) {
slot.remove(e);
}
elementsMap.remove(e);
}
void remove(E e) {
removeExsit(e);
for (ExpirationIntecepter<E> listener : expirationIntecepters) {
listener.expired(e);
}
}
public void stop() {
if (this.shutdown.compareAndSet(false, true)) {
this.state = WheelState.CLOSEING;
} else {
this.state = WheelState.SHUTDOWN;
}
}
public WheelState getWheelState() {
return this.state;
}
public boolean clockerAlive() {
return clockerThread.isAlive();
}
public int getSlotsCount() {
return slots.size();
}
public void addExpirationIntecepter(ExpirationIntecepter<E> intecepter) {
this.expirationIntecepters.add(intecepter);
}
public void removeExpirationIntecepter(ExpirationIntecepter<E> intecepter) {
this.expirationIntecepters.remove(intecepter);
}
}
|
package com.tt.miniapphost;
import com.storage.async.Scheduler;
import java.util.concurrent.ThreadPoolExecutor;
public class LaunchThreadPool implements Scheduler {
private static volatile boolean sIsLowPriorityLaunch;
private ThreadPoolExecutor mHighPriorityExecutor = getHighPriorityThreadPool();
private ThreadPoolExecutor mLowPriorityExecutor = getLowPriorityThreadPool();
private volatile ThreadPoolExecutor sHighPriorityThreadPool;
private volatile ThreadPoolExecutor sLowPriorityThreadPool;
private LaunchThreadPool() {}
private ThreadPoolExecutor getHighPriorityThreadPool() {
// Byte code:
// 0: aload_0
// 1: getfield sHighPriorityThreadPool : Ljava/util/concurrent/ThreadPoolExecutor;
// 4: ifnonnull -> 74
// 7: ldc com/tt/miniapphost/LaunchThreadPool
// 9: monitorenter
// 10: aload_0
// 11: getfield sHighPriorityThreadPool : Ljava/util/concurrent/ThreadPoolExecutor;
// 14: ifnonnull -> 62
// 17: aload_0
// 18: new java/util/concurrent/ThreadPoolExecutor
// 21: dup
// 22: bipush #8
// 24: bipush #8
// 26: ldc2_w 5
// 29: getstatic java/util/concurrent/TimeUnit.SECONDS : Ljava/util/concurrent/TimeUnit;
// 32: new java/util/concurrent/LinkedBlockingQueue
// 35: dup
// 36: invokespecial <init> : ()V
// 39: new com/tt/miniapp/thread/HighPriorityThreadFactory
// 42: dup
// 43: ldc 'high-priority'
// 45: invokespecial <init> : (Ljava/lang/String;)V
// 48: invokespecial <init> : (IIJLjava/util/concurrent/TimeUnit;Ljava/util/concurrent/BlockingQueue;Ljava/util/concurrent/ThreadFactory;)V
// 51: putfield sHighPriorityThreadPool : Ljava/util/concurrent/ThreadPoolExecutor;
// 54: aload_0
// 55: getfield sHighPriorityThreadPool : Ljava/util/concurrent/ThreadPoolExecutor;
// 58: iconst_1
// 59: invokevirtual allowCoreThreadTimeOut : (Z)V
// 62: ldc com/tt/miniapphost/LaunchThreadPool
// 64: monitorexit
// 65: goto -> 74
// 68: astore_1
// 69: ldc com/tt/miniapphost/LaunchThreadPool
// 71: monitorexit
// 72: aload_1
// 73: athrow
// 74: aload_0
// 75: getfield sHighPriorityThreadPool : Ljava/util/concurrent/ThreadPoolExecutor;
// 78: areturn
// Exception table:
// from to target type
// 10 62 68 finally
// 62 65 68 finally
// 69 72 68 finally
}
public static LaunchThreadPool getInst() {
return Holder.sInstance;
}
private ThreadPoolExecutor getLowPriorityThreadPool() {
// Byte code:
// 0: aload_0
// 1: getfield sLowPriorityThreadPool : Ljava/util/concurrent/ThreadPoolExecutor;
// 4: ifnonnull -> 72
// 7: ldc com/tt/miniapphost/LaunchThreadPool
// 9: monitorenter
// 10: aload_0
// 11: getfield sLowPriorityThreadPool : Ljava/util/concurrent/ThreadPoolExecutor;
// 14: ifnonnull -> 60
// 17: aload_0
// 18: new java/util/concurrent/ThreadPoolExecutor
// 21: dup
// 22: iconst_4
// 23: iconst_4
// 24: ldc2_w 5
// 27: getstatic java/util/concurrent/TimeUnit.SECONDS : Ljava/util/concurrent/TimeUnit;
// 30: new java/util/concurrent/LinkedBlockingQueue
// 33: dup
// 34: invokespecial <init> : ()V
// 37: new com/tt/miniapp/thread/LowPriorityThreadFactory
// 40: dup
// 41: ldc 'low-priority'
// 43: invokespecial <init> : (Ljava/lang/String;)V
// 46: invokespecial <init> : (IIJLjava/util/concurrent/TimeUnit;Ljava/util/concurrent/BlockingQueue;Ljava/util/concurrent/ThreadFactory;)V
// 49: putfield sLowPriorityThreadPool : Ljava/util/concurrent/ThreadPoolExecutor;
// 52: aload_0
// 53: getfield sLowPriorityThreadPool : Ljava/util/concurrent/ThreadPoolExecutor;
// 56: iconst_1
// 57: invokevirtual allowCoreThreadTimeOut : (Z)V
// 60: ldc com/tt/miniapphost/LaunchThreadPool
// 62: monitorexit
// 63: goto -> 72
// 66: astore_1
// 67: ldc com/tt/miniapphost/LaunchThreadPool
// 69: monitorexit
// 70: aload_1
// 71: athrow
// 72: aload_0
// 73: getfield sLowPriorityThreadPool : Ljava/util/concurrent/ThreadPoolExecutor;
// 76: areturn
// Exception table:
// from to target type
// 10 60 66 finally
// 60 63 66 finally
// 67 70 66 finally
}
public void execute(Runnable paramRunnable) {
if (sIsLowPriorityLaunch) {
this.mLowPriorityExecutor.execute(paramRunnable);
return;
}
this.mHighPriorityExecutor.execute(paramRunnable);
}
public void setLowPriorityLaunch(boolean paramBoolean) {
// Byte code:
// 0: getstatic com/tt/miniapphost/LaunchThreadPool.sIsLowPriorityLaunch : Z
// 3: iload_1
// 4: if_icmpeq -> 31
// 7: ldc com/tt/miniapphost/LaunchThreadPool
// 9: monitorenter
// 10: getstatic com/tt/miniapphost/LaunchThreadPool.sIsLowPriorityLaunch : Z
// 13: iload_1
// 14: if_icmpeq -> 21
// 17: iload_1
// 18: putstatic com/tt/miniapphost/LaunchThreadPool.sIsLowPriorityLaunch : Z
// 21: ldc com/tt/miniapphost/LaunchThreadPool
// 23: monitorexit
// 24: return
// 25: astore_2
// 26: ldc com/tt/miniapphost/LaunchThreadPool
// 28: monitorexit
// 29: aload_2
// 30: athrow
// 31: return
// Exception table:
// from to target type
// 10 21 25 finally
// 21 24 25 finally
// 26 29 25 finally
}
static class Holder {
public static LaunchThreadPool sInstance = new LaunchThreadPool();
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapphost\LaunchThreadPool.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package com.cz.android.simplehttp.request;
import com.sun.istack.internal.Nullable;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* A request.
*/
public final class Request {
final String url;
final Map<Class<?>, Object> tags;
Request(Builder builder) {
this.url = builder.url;
this.tags = Util.immutableMap(builder.tags);
}
public String url() {
return url;
}
/**
* Returns the tag attached with {@code Object.class} as a key, or null if no tag is attached with
* that key.
*
* <p>Prior to OkHttp 3.11, this method never returned null if no tag was attached. Instead it
* returned either this request, or the request upon which this request was derived with {@link
* #newBuilder()}.
*/
public @Nullable Object tag() {
return tag(Object.class);
}
/**
* Returns the tag attached with {@code type} as a key, or null if no tag is attached with that
* key.
*/
public @Nullable <T> T tag(Class<? extends T> type) {
return type.cast(tags.get(type));
}
public Builder newBuilder() {
return new Builder(this);
}
@Override public String toString() {
return "Request{method="
+ ", url="
+ url
+ ", tags="
+ tags
+ '}';
}
public static class Builder {
String url;
/** A mutable map of tags, or an immutable empty map if we don't have any. */
Map<Class<?>, Object> tags = Collections.emptyMap();
public Builder() {
}
Builder(Request request) {
this.url = request.url;
this.tags = request.tags.isEmpty()
? Collections.<Class<?>, Object>emptyMap()
: new LinkedHashMap<>(request.tags);
}
/**
* Sets the URL target of this request.
*
* @throws IllegalArgumentException if {@code url} is not a valid HTTP or HTTPS URL. Avoid this
* exception by calling {@link HttpUrl#parse}; it returns null for invalid URLs.
*/
public Builder url(String url) {
if (url == null) throw new NullPointerException("url == null");
// Silently replace web socket URLs with HTTP URLs.
if (url.regionMatches(true, 0, "ws:", 0, 3)) {
url = "http:" + url.substring(3);
} else if (url.regionMatches(true, 0, "wss:", 0, 4)) {
url = "https:" + url.substring(4);
}
return this;
}
/** Attaches {@code tag} to the request using {@code Object.class} as a key. */
public Builder tag(@Nullable Object tag) {
return tag(Object.class, tag);
}
/**
* Attaches {@code tag} to the request using {@code type} as a key. Tags can be read from a
* request using {@link Request#tag}. Use null to remove any existing tag assigned for {@code
* type}.
*
* <p>Use this API to attach timing, debugging, or other application data to a request so that
* you may read it in interceptors, event listeners, or callbacks.
*/
public <T> Builder tag(Class<? super T> type, @Nullable T tag) {
if (type == null) throw new NullPointerException("type == null");
if (tag == null) {
tags.remove(type);
} else {
if (tags.isEmpty()) tags = new LinkedHashMap<>();
tags.put(type, type.cast(tag));
}
return this;
}
public Request build() {
if (url == null) throw new IllegalStateException("url == null");
return new Request(this);
}
}
}
|
execute(des, src, registers, memory) {
if(src.isRegister()) {
String EAXRegister;
int size = registers.getBitSize(src);
switch(size) {
case 8:
EAXRegister = registers.get("AL");
break;
case 16:
EAXRegister = registers.get("AX");
break;
case 32:
EAXRegister = registers.get("EAX");
break;
}
if ( des.isRegister() ) {
if(des.isRegister() && registers.getBitSize(des) == size) {
if(isEqual(des, src, registers, memory, EAXRegister)) {
registers.set(des, registers.get(src));
}
else{
switch(size) {
case 8:
EAXRegister = registers.get("AL");
registers.set("AL", registers.get(des));
break;
case 16:
EAXRegister = registers.get("AX");
registers.set("AX", registers.get(des));
break;
case 32:
EAXRegister = registers.get("EAX");
registers.set("EAX", registers.get(des));
break;
}
}
}
}
if ( des.isMemory() ) {
if(des.isMemory() ) {
if(isEqual(des, src, registers, memory, EAXRegister)) {
memory.write(des, registers.get(src), size);
}
else{
switch(size) {
case 8:
EAXRegister = registers.get("AL");
registers.set("AL", memory.read(des, size));
break;
case 16:
EAXRegister = registers.get("AX");
registers.set("AX", memory.read(des, size));
break;
case 32:
EAXRegister = registers.get("EAX");
registers.set("EAX", memory.read(des, size));
break;
}
}
}
}
}
}
boolean isEqual(des, src, registers, memory, eaxReg){
int desSize = registers.getBitSize(src);
Calculator calculator = new Calculator(registers, memory);
BigInteger i = new BigInteger(eaxReg, 16);
String EAXRegister = i.toString(2);
int missingZeroesEAX = desSize - EAXRegister.length();
String destination = "";
if(des.isRegister())
destination = calculator.hexToBinaryString(registers.get(des), des);
else
destination = calculator.hexToBinaryString(memory.read(des, desSize), des);
destination = zeroExtend(destination, desSize);
EAXRegister = zeroExtend(EAXRegister, desSize);
String result = "";
int r = 0;
int borrow = 0;
int carry = 0;
int overflow = 0;
for(int i = desSize - 1; i >= 0; i--) {
r = Integer.parseInt(String.valueOf(destination.charAt(i))) - Integer.parseInt(String.valueOf(EAXRegister.charAt(i))) - borrow;
if( r < 0 ) {
borrow = 1;
r += 2;
result = result.concat(r.toString());
if( i == 0 ) {
carry = 1;
}
if( i == 0 || i == 1) {
overflow++;
}
}
else {
borrow = 0;
result = result.concat(r.toString());
}
}
String d = new StringBuffer(result).reverse().toString();
BigInteger compareToZero = new BigInteger(d, 2);
//FLAGS
EFlags flags = registers.getEFlags();
flags.setCarryFlag(carry.toString());
if(overflow == 1) {
flags.setOverflowFlag("1");
}
else {
flags.setOverflowFlag("0");
}
String sign = "" + compareToZero.toString(2).charAt(0);
flags.setSignFlag(sign);
String parity = calculator.checkParity(compareToZero.toString(2));
flags.setParityFlag(parity);
String auxiliary = calculator.checkAuxiliarySub(destination, EAXRegister);
flags.setAuxiliaryFlag(auxiliary);
if(d.matches("[0]+")) {
flags.setZeroFlag("1");
return true;
}
else {
flags.setZeroFlag("0");
return false;
}
}
String zeroExtend(str, size){
int missingZeroes = size - str.length();
for(int x = 0; x < missingZeroes; x++) {
str = "0" + str;
}
return str;
}
/*
CONCERN: Where do we put the logic for CC
*/
|
import java.text.*;
public class Students {
public static void main(String[] args) {
DecimalFormat fmt = new DecimalFormat("0.00");
Grades student1 = new Grades(100, 92, 98, 95);
Grades student2 = new Grades(100, 100, 100, 100);
Grades student3 = new Grades(98, 90, 83, 80);
double stu1Avg = (student1.getGrade1() + student1.getGrade2() + student1.getGrade3() + student1.getGrade4()) / 4;
double stu2Avg = (student2.getGrade1() + student2.getGrade2() + student2.getGrade3() + student2.getGrade4()) / 4;
double stu3Avg = (student3.getGrade1() + student3.getGrade2() + student3.getGrade3() + student3.getGrade4()) / 4;
System.out.println("Student 1 Average: " + fmt.format(stu1Avg));
System.out.println("Student 2 Average: " + fmt.format(stu2Avg));
System.out.println("Student 3 Average: " + fmt.format(stu3Avg));
}
}
|
package com.yuorfei.interceptor;
import com.yuorfei.service.VisitorService;
import com.yuorfei.util.RequestUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
/**
* 页面拦截器,用来对页面返回时加入java方法
* 适用于freemarker的页面直接调用方法
* Created by hxy on 2015/9/4.
*/
@Component
public class AdminPageInterceptor extends HandlerInterceptorAdapter {
@Autowired
VisitorService visitorService;
@Autowired
RequestUtil requestUtil;
private static final Log log = LogFactory.getLog(HomePageInterceptor.class);
public AdminPageInterceptor() {
super();
}
@Override
public boolean preHandle(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler) throws Exception {
String requestUri = request.getRequestURI();
if( !requestUtil.isAdmin() && !requestUri.endsWith("/admin/login") ){
log.info( "please login" );
response.sendRedirect(request.getContextPath() + "/admin/login");
}
return super.preHandle(request, response, handler);
}
@Override
public void postHandle(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
super.postHandle(request, response, handler, modelAndView);
log.info(" admin ");
}
@Override
public void afterCompletion(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler, Exception ex) throws Exception {
super.afterCompletion(request, response, handler, ex);
}
@Override
public void afterConcurrentHandlingStarted(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler) throws Exception {
super.afterConcurrentHandlingStarted(request, response, handler);
}
}
|
package javaProject;
import java.util.*;
// Find the sub array with given sum
// Sliding window solution
public class subarraycount {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int arr[] = new int[10];
for(int i=0; i<10; i++) {
arr[i] = sc.nextInt();
}
int sum = sc.nextInt();
subarraycount sb = new subarraycount();
int result = sb.subArrayCount(arr, 10, sum);
System.out.println(result);
}
int subArrayCount(int arr[], int n, int sum) {
int current_count = arr[0];
int start = 0;
int i;
int count = 0;
int flag = 0;
for(i = 1; i < n; i++) {
if(current_count == sum) {
System.out.println((start+1) + " " + (i));
return 1;
}
else if(current_count < sum) {
current_count += arr[i];
}
else {
while(current_count > sum) {
current_count -= arr[start++];
}
}
}
if(current_count == sum) {
System.out.println(start + " " + (i-1));
}
return (flag == 1 ? count : 0);
}
}
|
class Shape {
int x; int y; double total;
public void setArea(int x, int y){
this.x = x;
this.y = y;
}
public double getArea(){
return total;
}
}
class Circle extends Shape{
public void setArea(int x, int y){
total = x*y*3.14;
}
public double getArea(){
return total;
}
}
class Rect extends Shape{
public void setArea(int x, int y){
total = x*y/2;
}
public double getArea(){
return total;
}
}
class Diamond extends Shape{
public void setArea(int x, int y){
total = x*y;
}
public double getArea(){
return total;
}
}
|
package day4_arithmeticOperator;
//this progrsm calculate the hourly wages
public class Wages {
public static void main(String[] args) {
// TODO Auto-generated method stub
double regularWage;
double basePay=25;
double regularHours=40;
double overtimeWages;
double overTimePay=37.5;
double overTimeHours=10;
double totalWage;
regularWage=basePay*regularHours;
overtimeWages=overTimePay*overTimeHours;
totalWage=overtimeWages+regularWage;
System.out.println("Wage for this are $ " + totalWage);
}
}
|
package daggerok;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.Json;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.StaticHandler;
import lombok.SneakyThrows;
import lombok.experimental.FieldDefaults;
import java.net.Inet4Address;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonMap;
import static lombok.AccessLevel.PRIVATE;
@FieldDefaults(level = PRIVATE)
public class App {
final static int port = 8080;
final static Vertx vertx = Vertx.vertx();
final static Router router = Router.router(vertx);
public static void main(String[] args) {
router.route("/static/*")
.handler(StaticHandler.create("static"));
/*
router.route("/") // useless with static handler
.handler(App::indexHtml);
*/
router.route("/api/v1/hello")
.handler(App::hello);
router.route("/api/v1/hello/:name")
.handler(App::helloName);
router.route("/*")
.handler(App::info);
vertx.createHttpServer()
.requestHandler(router::accept)
.listen(port);
}
/* router handlers */
static void indexHtml(final RoutingContext routingContext) {
routingContext.response()
.putHeader("content-type", "text/html")
.sendFile("static/index.html");
}
static void hello(final RoutingContext routingContext) {
responseFrom(routingContext).end(jsonOf("message", "Hi!"));
}
private static void helloName(final RoutingContext routingContext) {
responseFrom(routingContext).end(jsonOf("message", "Hello, " + routingContext.pathParam("name") + "!"));
}
static void info(final RoutingContext routingContext) {
responseFrom(routingContext).end(
jsonOf("api", asList(
singletonMap("get", base() + "/"),
singletonMap("get", base() + "/api/v1/hello"))));
}
/* helpers */
@SneakyThrows
static String base() {
return "http://" + Inet4Address.getLocalHost().getHostAddress() + ":" + port;
}
static String jsonOf(final String key, final Object value) {
return Json.encodePrettily(singletonMap(key, value));
}
static HttpServerResponse responseFrom(final RoutingContext request) {
return request.response()
.putHeader("content-type", "application/json; charset=utf-8");
}
}
|
package com.cmpickle.volumize.domain;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Build;
import android.preference.PreferenceManager;
import android.provider.Settings;
import com.cmpickle.volumize.util.preferences.Preferences;
import javax.inject.Inject;
/**
* @author Cameron Pickle
* Copyright (C) Cameron Pickle (cmpickle) on 4/13/2017.
*/
public class VolumeService extends IntentFilter {
AudioManager audioManager;
Preferences preferences;
public static final String OPTION = "option";
public static final String AMOUNT = "amount";
public static final String VIBRATE = "vibrate";
public static final String REPEAT_WEEKLY = "repeatWeekly";
public static final String DAYS = "days";
public static final String ACTIVE = "active";
public static final int ALL = 0;
public static final int RING_TONE = 1;
public static final int MEDIA = 2;
public static final int NOTIFICATIONS = 3;
public static final int SYSTEM = 4;
@Inject
public VolumeService(Context context) {
audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
preferences = new Preferences(PreferenceManager.getDefaultSharedPreferences(context));
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !notificationManager.isNotificationPolicyAccessGranted()) {
Intent intent = new Intent(Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_HISTORY);
context.startActivity(intent);
}
}
public int getRingToneMaxVolume() {
return audioManager.getStreamMaxVolume(AudioManager.STREAM_RING);
}
public int getMediaVolumeMaxVolume() {
return audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
}
public int getNotificationsMaxVolume() {
return audioManager.getStreamMaxVolume(AudioManager.STREAM_NOTIFICATION);
}
public int getSystemVolumeMaxVolume() {
return audioManager.getStreamMaxVolume(AudioManager.STREAM_SYSTEM);
}
public int getRingToneVolume() {
return audioManager.getStreamVolume(AudioManager.STREAM_RING);
}
public int getMediaVolumeVolume() {
return audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
}
public int getNotificationsVolume() {
return audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION);
}
public int getSystemVolume() {
return audioManager.getStreamVolume(AudioManager.STREAM_SYSTEM);
}
public boolean isSilentMode() {
return audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT;
}
public void setRingToneVolume(int level, boolean vibrate) {
if(preferences.getDisplayVolumeRestoreDialog() && level == 0) {
preferences.setPrefPauseVolumeRestoreDialog(true);
}
if(vibrate) {
audioManager.setStreamVolume(AudioManager.STREAM_RING, level, AudioManager.FLAG_PLAY_SOUND);
} else {
audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
}
}
public void setMediaVolume(int level) {
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, level, AudioManager.FLAG_PLAY_SOUND);
}
public void setNotificationVolume(int level) {
audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION, level, AudioManager.FLAG_PLAY_SOUND);
}
public void setSystemVolume(int level) {
audioManager.setStreamVolume(AudioManager.STREAM_SYSTEM, level, AudioManager.FLAG_PLAY_SOUND);
}
}
|
/*
* Copyright (C) 2015 Miquel Sas
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
package com.qtplaf.library.task;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import com.qtplaf.library.app.Session;
import com.qtplaf.library.util.StringUtils;
import com.qtplaf.library.util.list.ListUtils;
/**
* A task made of multiple tasks that are executed in concurrent threads. The tasks to be executed must correctly manage
* the <code>TaskListener</code> idiom.
* <p>
* There are three possible execution scenarios:
* <ol>
* <li>One or more tasks are indeterminate. The number of records is not known and the overall number of steps will be
* the number of tasks to execute.</li>
* <li>No task is indeterminate, but one or more does not support <code>countSteps()</code>. The total number of steps
* changes as tasks are being started and notify their number of steps.</li>
* <li>No task is indeterminate and all support <code>countSteps()</code>. An initital count is made on every task.</li>
* </ol>
*
* @author Miquel Sas
*/
public class TaskRunnerThreads extends TaskRunner {
/**
* The comparator to sort processes by currentStep count ascending.
*/
class TaskComparator implements Comparator<Task> {
@Override
public int compare(Task task0, Task task1) {
long steps0 = task0.getSteps();
long steps1 = task1.getSteps();
if (steps0 < steps1) {
return -1;
} else if (steps0 > steps1) {
return 1;
} else {
return 0;
}
}
}
/**
* The task listener that interacts with the task monitored.
*/
class TaskAdapter extends TaskHandler {
/**
* Invoked to notify that the task is counting the number of steps.
*
* @param task The task.
*/
@Override
public void counting(Task task) {
notifyCounting(task);
}
/**
* Invoked to notify that the task has started processing.
*
* @param task The task.
*/
@Override
public void processing(Task task) {
// Notify strategy: Tasks -> notify a currentStep start.
if (isNotifyTasks()) {
notifyStepStart(task);
}
}
/**
* Invoked to notify that the task has effectively been cancelled (after a cancel request).
*
* @param task The task.
*/
@Override
public void cancelled(Task task) {
}
/**
* Invoked to know if task cancellation has been requested.
*
* @param task The task.
* @return A boolean that indicates if task cancellation has been requested.
*/
@Override
public boolean cancelRequested(Task task) {
return cancelRequesting;
}
/**
* Invoked to notify that the task has effectively been paused (after a pause request).
*
* @param task The task.
*/
@Override
public void paused(Task task) {
if (allExecutingTasksArePaused()) {
notifyPaused();
}
}
/**
* Invoked to know if the task has been requested to pause. In non indeterminate tasks, it would normally be
* invoked at every currentStep.
*
* @param task The task.
* @return A boolean indicating if the task has been requested to pause.
*/
@Override
public boolean pauseRequested(Task task) {
return pauseRequesting;
}
/**
* Invoked to notify that the task has effectively been resumed (after a resume request).
*
* @param task The task.
*/
@Override
public void resumed(Task task) {
if (allExecutingTasksAreNotPaused()) {
notifyResumed();
}
}
/**
* Invoked to know that after pausing, if resume has beeen requested.
*
* @param task The task.
* @return A boolean that indicates if resumen has been requested.
*/
@Override
public boolean resumeRequested(Task task) {
return resumeRequesting;
}
/**
* Invoked to notify that the task has terminated.
*
* @param task The task.
*/
@Override
public void terminated(Task task) {
// Notify strategy: Tasks -> notify a currentStep end.
if (isNotifyTasks()) {
notifyStepEnd(task);
}
}
/**
* Invoked to notify that the non indeterminate task is going to executed the argument number of steps.
*
* @param task The task.
*/
@Override
public void stepCount(Task task) {
// Notify strategy: StepsUnknown. The total number of steps changes while tasks enter the pool and notify
// their number of steps.
if (isNotifyStepsUnknown()) {
notifyStepCount(task);
}
}
/**
* Invoked to notify that the currentStep is going to start. Note that steps should start at 1 and end at the
* total number of steps to properly manage notification modulus and monitor.
*
* @param task The task.
* @param text The text explaining the currentStep.
*/
@Override
public void stepStart(Task task, String text) {
// Notify strategy: StepsUnknown/StepsKnown. Notify the current currentStep of the pool using the common
// message.
if (isNotifyStepsUnknown() || isNotifyStepsKnown()) {
increaseCurrentStepAndNotifyStepStart(task);
}
}
/**
* Invoked to notify that the currentStep has ended.
*
* @param task The task.
*/
@Override
public void stepEnd(Task task) {
// Notify strategy: StepsUnknown/StepsKnown. Notify the current currentStep of the pool, no matter what task
// notified its own.
if (isNotifyStepsUnknown() || isNotifyStepsKnown()) {
notifyStepEnd(task);
}
}
}
/**
* An enumeration of the possible notify strategies.
*/
enum NotifyStrategy {
Tasks,
StepsUnknown,
StepsKnown;
}
/** The list of tasks to be executed. */
private List<Task> tasks = new ArrayList<>();
/** List of executing tasks. */
private List<Task> executingTasks = new ArrayList<>();
/** The number of maximum concurrent tasks. */
private int maximumConcurrentTasks = 10;
/** Unique task listener. */
private final TaskAdapter listener = new TaskAdapter();
/** Operation boolean indicating that cancel is being requested to executing tasks. */
private boolean cancelRequesting = false;
/** Operation boolean indicating that pause is being requested to executing tasks. */
private boolean pauseRequesting = false;
/** Operation boolean indicating that resume is being requested to executing tasks. */
private boolean resumeRequesting = false;
/** Notify strategy. */
private NotifyStrategy notifyStrategy;
/** Current currentStep must be tracked by the process. */
private long currentStep = 0;
/** A boolean that indicates if cancel is supported, by asking the list of tasks. */
private Boolean cancelSupported;
/** A boolean that indicates if pause is supported, by asking the list of tasks. */
private Boolean pauseSupported;
/**
* Constructor with default maximum number of concurrent tasks.
*
* @param session The working session.
*/
public TaskRunnerThreads(Session session) {
super(session);
}
/**
* Add a task to the list of tasks to be executed. The tasks must be added before any execution is started.
*
* @param task The task to be added.
*/
public void addTask(Task task) {
if (isProcessing()) {
throw new IllegalStateException("Can not add tasks when processing.");
}
task.addListener(listener);
tasks.add(task);
}
/**
* Increase current step and notify step start.
*
* @param task The task.
*/
synchronized private void increaseCurrentStepAndNotifyStepStart(Task task) {
currentStep += task.getStepIncrease();
notifyStepStart(currentStep, getStepMessage(currentStep, getSteps(), null, null));
}
/**
* Notify step count (synchronized).
*
* @param task The notifying task.
*/
synchronized private void notifyStepCount(Task task) {
notifyStepCount(getSteps() + task.getSteps());
}
/**
* Forward notify counting.
*
* @param task The task.
*/
synchronized private void notifyCounting(Task task) {
notifyCounting();
}
/**
* Forward notify start when notify strategy is Tasks.
*
* @param task The task.
*/
synchronized private void notifyStepStart(Task task) {
long step = getStep() + 1;
long steps = getSteps();
notifyStepStart(step, getStepMessage(step, steps, null, null));
}
/**
* Forward notify step end.
*
* @param task The task.
*/
synchronized private void notifyStepEnd(Task task) {
notifyStepEnd();
}
/**
* Returns the notify strategy.
*
* @return The notify strategy.
*/
private NotifyStrategy getNotifyStrategy() {
if (notifyStrategy == null) {
// Any indeterminate -> Tasks
for (Task task : tasks) {
if (task.isIndeterminate()) {
notifyStrategy = NotifyStrategy.Tasks;
return notifyStrategy;
}
}
// Any does not support count steps -> StepsUnknown
for (Task task : tasks) {
if (!task.isCountStepsSupported()) {
notifyStrategy = NotifyStrategy.StepsUnknown;
return notifyStrategy;
}
}
notifyStrategy = NotifyStrategy.StepsKnown;
}
return notifyStrategy;
}
/**
* Returns a boolean indicating if notify strategy is <i>Tasks</i>.
*
* @return A boolean.
*/
private boolean isNotifyTasks() {
return getNotifyStrategy() == NotifyStrategy.Tasks;
}
/**
* Returns a boolean indicating if notify strategy is <i>StepsUnknown</i>.
*
* @return A boolean.
*/
private boolean isNotifyStepsUnknown() {
return getNotifyStrategy() == NotifyStrategy.StepsUnknown;
}
/**
* Returns a boolean indicating if notify strategy is <i>StepsKnown</i>.
*
* @return A boolean.
*/
private boolean isNotifyStepsKnown() {
return getNotifyStrategy() == NotifyStrategy.StepsKnown;
}
/**
* Constructor.
*
* @param session The working session.
* @param maximumConcurrentTasks The maximum number of concurrent tasks.
*/
public TaskRunnerThreads(Session session, int maximumConcurrentTasks) {
super(session);
this.maximumConcurrentTasks = maximumConcurrentTasks;
}
/**
* Returns the maximum number of concurrent tasks.
*
* @return The maximum number of concurrent tasks.
*/
public int getMaximumConcurrentTasks() {
return maximumConcurrentTasks;
}
/**
* Sets the maximum number of concurrent tasks.
*
* @param maximumConcurrentTasks The maximum number of concurrent tasks.
*/
public void setMaximumConcurrentTasks(int maximumConcurrentTasks) {
this.maximumConcurrentTasks = maximumConcurrentTasks;
}
/**
* If the task is determinate, a call to this method forces counting (and storing) the number of steps. If the task
* is not derteminate, this method has no sense.
* <p>
* Steps are counted if the overall process is determinate.
*
* @return The number of steps.
*/
@Override
public long countSteps() {
return getSteps();
}
/**
* Process step count when notify strategy is StepsKnown.
*
* @throws Exception If such an error occurs.
*/
private void processStepCount() throws Exception {
// Already counted...
if (getSteps() > 0) {
return;
}
long steps = 0;
long step = 0;
String prefix = getSession().getString("panelProgressCounting") + ": ";
// Save notify modulus and set it to one.
int notifyModulus = getNotifyModulus();
setNotifyModulus(1);
// and trace it while performing...
notifyStepCount(tasks.size());
int i = 0;
while (i < tasks.size()) {
if (checkCancel()) {
break;
}
if (checkPause()) {
continue;
}
step += 1;
Task task = tasks.get(i);
notifyStepStart(step, getStepMessage(step, tasks.size(), prefix, null));
steps += task.countSteps();
notifyStepEnd();
i++;
}
// Restore notify modulus.
setNotifyModulus(notifyModulus);
// Notify step count.
notifyStepCount(steps);
}
/**
* Ensure that all tasks have a name and description.
*/
private void ensureTasksNamesAndDescriptions() {
for (int i = 0; i < tasks.size(); i++) {
Task task = tasks.get(i);
if (task.getName() == null || task.getName().isEmpty()) {
task.setName(StringUtils.leftPad(Integer.toString(i), tasks.size(), "0"));
}
if (task.getDescription() == null || task.getDescription().isEmpty()) {
task.setDescription("Task " + StringUtils.leftPad(Integer.toString(i), tasks.size(), "0"));
}
}
}
/**
* Executes the underlying task processing.
*
* @throws Exception If an unrecoverable error occurs during execution.
*/
@Override
public void execute() throws Exception {
// Reset control member in case of re-execute.
executingTasks.clear();
cancelRequesting = false;
pauseRequesting = false;
resumeRequesting = false;
notifyStrategy = null;
currentStep = 0;
cancelSupported = null;
pauseSupported = null;
// Ensure tasks names and descriptions.
ensureTasksNamesAndDescriptions();
// Notify strategy: Tasks.
if (isNotifyTasks()) {
executeNotifyStrategyTasks();
return;
}
// Notify strategy: StepsUnknown.
if (isNotifyStepsUnknown()) {
executeNotifyStrategyStepsUnknown();
return;
}
// Notify strategy: StepsKnow.
if (isNotifyStepsKnown()) {
executeNotifyStrategyStepsKnown();
return;
}
}
/**
* Impements the tasks notify strategy.
*
* @throws Exception If such an error occurs.
*/
private void executeNotifyStrategyTasks() throws Exception {
// Fill the list of tasks to be executed.
List<Task> tasksToExecute = new ArrayList<>(tasks);
// Notify the total number of steps.
notifyStepCount(tasksToExecute.size());
// Lauch execution.
executeList(tasksToExecute);
}
/**
* Impements the steps unknown notify strategy.
*
* @throws Exception If such an error occurs.
*/
private void executeNotifyStrategyStepsUnknown() throws Exception {
// Fill the list of tasks to be executed.
List<Task> tasksToExecute = new ArrayList<>(tasks);
// The total number of steps is unknown at this point, just lauch execution.
executeList(tasksToExecute);
}
/**
* Impements the steps known notify strategy.
*
* @throws Exception If such an error occurs.
*/
private void executeNotifyStrategyStepsKnown() throws Exception {
// Do count steps.
processStepCount();
// Once counted, sort tasks.
Task[] taskArray = tasks.toArray(new Task[tasks.size()]);
Arrays.sort(taskArray, new TaskComparator());
// Fill the list of tasks to be executed.
List<Task> tasksToExecute = new ArrayList<>();
for (Task task : taskArray) {
tasksToExecute.add(task);
}
// The total number of steps is unknown at this point, just lauch execution.
executeList(tasksToExecute);
}
/**
* Remove the tasks terminated from the list of executing tasks.
*/
private void removeTerminated() {
List<Task> toRemove = new ArrayList<>();
for (Task task : executingTasks) {
if (task.isTerminated()) {
toRemove.add(task);
}
}
executingTasks.removeAll(toRemove);
}
/**
* Add task pending to execute to the list of executing tasks and start them.
*
* @param tasksToExecute The list of task to execute.
*/
private void addPendingTasksToExecute(List<Task> tasksToExecute) {
while (!tasksToExecute.isEmpty() && executingTasks.size() < getMaximumConcurrentTasks()) {
Task task = ListUtils.removeLast(tasksToExecute);
executingTasks.add(task);
new Thread(task, task.toString()).start();
}
}
/**
* Execute the list of tasks adding them at the pool in the inverse list order.
*
* @param tasksToExecute The list of tasks to execute.
* @throws Exception If any executing tasks throws it.
*/
private void executeList(List<Task> tasksToExecute) throws Exception {
// Process them. To avoid repetitive questions to tasks, previously check if cancel and pause are supported.
boolean continueProcessing = true;
while (true) {
// Remove already terminated tasks from the executing list.
removeTerminated();
// Manage cancel request.
if (checkCancel()) {
// Do not break, must wait for all executing tasks to cancel.
continueProcessing = false;
}
// Manage pause request.
if (checkPause()) {
continue;
}
// If not should continue processing, the exit when all currently executing tasks are terminated.
if (!continueProcessing) {
if (executingTasks.isEmpty()) {
break;
}
}
// Add tasks to execute if continue processing applies.
if (continueProcessing && !pauseRequesting) {
addPendingTasksToExecute(tasksToExecute);
}
// If all tasks have terminated, exit
if (tasksToExecute.isEmpty() && executingTasks.isEmpty()) {
break;
}
}
}
/**
* Convenience method to deal with cancel requests when cancel is supported. Usage: at the begining of the main
* loop, if check break the loop.
* <p>
* <code>if (checkCancel()) break;</code>
*
* @return A boolean indicating that cancel has been accepted and processing should terminate.
*/
@Override
protected boolean checkCancel() {
if (super.checkCancel()) {
synchronized (this) {
cancelRequesting = true;
}
return true;
}
return false;
}
/**
* Convinience method to deal with pause/resume requests when pause/resume is supported. Usage: at the begining of
* the main loop, if check continue.
* <p>
* <code>if (checkPause()) continue;</code>
*
* @return A boolean indicating that pause has been accepted and processing should pause.
*/
@Override
protected boolean checkPause() {
if (isPauseSupported()) {
if (!isPaused()) {
if (pauseRequested()) {
if (executingTasks.isEmpty()) {
notifyPaused();
return true;
}
// Forward the request, will notify paused when all executing tasks are paused.
synchronized (this) {
resumeRequesting = false;
pauseRequesting = true;
}
return true;
}
return false;
}
if (resumeRequested()) {
if (executingTasks.isEmpty()) {
notifyResumed();
return true;
}
// Forward the request, will notify resumed when all executing tasks are not paused.
synchronized (this) {
resumeRequesting = true;
pauseRequesting = false;
}
return false;
}
return true;
}
return false;
}
/**
* Returns a boolean indicating if all current executing tasks are paused.
*
* @return A boolean.
*/
private boolean allExecutingTasksArePaused() {
for (Task task : executingTasks) {
if (!task.isPaused()) {
return false;
}
}
return true;
}
/**
* Returns a boolean indicating if all current executing tasks are not paused.
*
* @return A boolean.
*/
private boolean allExecutingTasksAreNotPaused() {
for (Task task : executingTasks) {
if (task.isPaused()) {
return false;
}
}
return true;
}
/**
* Returns a boolean indicating whether the task will support cancel requests. Cancel is supported if all tasks to
* be executed support cancel.
*
* @return A boolean.
*/
@Override
public boolean isCancelSupported() {
if (cancelSupported == null) {
cancelSupported = true;
for (Task task : tasks) {
if (!task.isCancelSupported()) {
cancelSupported = false;
break;
}
}
}
return cancelSupported;
}
/**
* Returns a boolean indicating if the task is indeterminate, that is, the task can not count its number of steps.
* This concurrent task is indeterminate is always determinate.
*
* @return A boolean indicating if the task is indeterminate.
*/
@Override
public boolean isIndeterminate() {
return false;
}
/**
* Returns a boolean indicating whether the task will support the pause/resume requests. Pause/resume is supported
* if all tasks to be executed support pause/resume.
*
* @return A boolean.
*/
@Override
public boolean isPauseSupported() {
if (pauseSupported == null) {
pauseSupported = true;
for (Task task : tasks) {
if (!task.isPauseSupported()) {
pauseSupported = false;
}
}
}
return pauseSupported;
}
/**
* Returns a boolean indicating if the task supports counting steps through a call to <code>countSteps()</code>.
* This task supports it if the notify strategy is <i>StepsKnown</i>.
*
* @return A boolean.
*/
@Override
public boolean isCountStepsSupported() {
return isNotifyStepsKnown();
}
}
|
package www.limo.com.mymovies.entities;
import java.util.*;
public class Network {
private long id;
private String name;
private Country country;
public long getID() { return id; }
public void setID(long value) { this.id = value; }
public String getName() { return name; }
public void setName(String value) { this.name = value; }
public Country getCountry() { return country; }
public void setCountry(Country value) { this.country = value; }
}
|
package lotto.step2.domain;
import java.util.*;
public class Lotto {
private static final int LOTTO_PRICE = 1000;
private List<LottoTicket> lottoTickets;
public Lotto(int money) {
if (money < LOTTO_PRICE) {
throw new IllegalArgumentException("돈이 부족합니다. 로또 1장의 가격은 " + LOTTO_PRICE + "원입니다.");
}
this.lottoTickets = new ArrayList<>();
int lottoCount = money / LOTTO_PRICE;
for (int i = 0; i < lottoCount; i++) {
generate(LottoMachine.mixLottoNumbers());
}
}
public Lotto(List<LottoTicket> lottoTickets) {
this.lottoTickets = lottoTickets;
}
@Override
public String toString() {
return lottoTickets.toString();
}
public void generate(List<LottoNumber> lottoNumbers) {
lottoTickets.add(new LottoTicket(new HashSet<>(lottoNumbers)));
}
public List<LottoTicket> getLottoTickets() {
return lottoTickets;
}
public LottoResult matchLottoTicket(LottoTicket winningNumber) {
Map<WinningRank, Integer> winningRankInfo = new HashMap<>();
for (LottoTicket lottoTicket : this.lottoTickets) {
int matchCount = lottoTicket.matchWinningNumber(winningNumber);
WinningRank findRank = WinningRank.findWinningRank(matchCount);
winningRankInfo.put(findRank, winningRankInfo.getOrDefault(findRank, 0) + 1);
}
return new LottoResult(winningRankInfo);
}
}
|
package com.lingnet.vocs.service.leaguer;
import com.lingnet.common.service.BaseService;
import com.lingnet.qxgl.entity.QxUsers;
import com.lingnet.util.Pager;
/**
* 会员信息管理
*
* @ClassName: LeaguerService
* @Description: TODO
* @author wanl
* @date 2017年7月10日 上午10:15:09
*
*/
public interface LeaguerService extends BaseService<QxUsers, String> {
/**
* 会员信息列表查询
*
* @Title: getListData
* @param pager
* @return String
* @author wanl
* @since 2017年7月10日 V 1.0
*/
public String getListData(Pager pager, String id);
/**
* 会员信息编辑保存
*
* @Title: memberEditor
* @return String
* @author wanl
* @since 2017年7月10日 V 1.0
*/
public String saveOrUpdate(QxUsers qxUsers) throws Exception;
}
|
/*!
* Copyright 2002 - 2017 Webdetails, a Pentaho company. All rights reserved.
*
* This software was developed by Webdetails and is provided under the terms
* of the Mozilla Public License, Version 2.0, or any later version. You may not use
* this file except in compliance with the license. If you need a copy of the license,
* please go to http://mozilla.org/MPL/2.0/. The Initial Developer is Webdetails.
*
* Software distributed under the Mozilla Public License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
* the license for the specific language governing your rights and limitations.
*/
package pt.webdetails.cdf.dd.structure;
import java.util.HashMap;
//TODO: ever used?
public interface IDashboardStructure {
public abstract HashMap<String, String> save( HashMap<String, Object> parameters ) throws Exception;
public abstract Object load( String filePath ) throws Exception;
public abstract void delete( HashMap<String, Object> parameters ) throws Exception;
}
|
package com.spower.business.desktop.controller;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import com.spower.basesystem.common.Constants;
import com.spower.basesystem.common.command.Page;
import com.spower.basesystem.common.menu.MenuManager;
import com.spower.basesystem.common.menu.valueobject.MenuTree;
import com.spower.basesystem.common.systemdata.SystemData;
import com.spower.basesystem.dictionary.service.DictionaryLoader;
import com.spower.basesystem.manage.valueobject.User;
import com.spower.business.notice.command.NoticeQueryInfo;
import com.spower.business.notice.service.INoticeService;
import com.spower.business.notice.valueobject.Notice;
/**
* @author hl
*
* 2013-12-11
*/
public class DesktopQueryController extends MultiActionController {
private String mainView;
private INoticeService noticeService;
public ModelAndView loadDeskTop(HttpServletRequest request, HttpServletResponse response) {
User user = (User) Constants.getCurrentLoginUser(request);
Map data = (Map) SystemData.getInstance().getSystemData(Constants.MAIN_MENU_DATATYPE_KEY, null);
List mList = new ArrayList();
// 首先取得所有module的列表
Map mod = (Map) SystemData.getInstance().getSystemData(Constants.MAIN_MENU_DATATYPE_KEY, null);
List mainMenuList = (List) mod.get("index");
String moduleName;
String from = "desktop";
MenuTree mt;
for (Iterator it = mainMenuList.iterator(); it.hasNext();) {
moduleName = (String) it.next();
Map root = (Map) SystemData.getInstance().getSystemData(Constants.MAIN_MENU_DATATYPE_KEY, moduleName);
// 将所有module的菜单树写入list,以便在view中构造显示
mt = MenuManager.buildMenuTree(root, user);
if (mt != null)
mList.add(mt);
}
Map model = new HashMap();
model.put("from", from);
// ----加载首页----开始------
// 加载公告
NoticeQueryInfo noticeInfo = new NoticeQueryInfo();
noticeInfo.setStatus(Notice.STATUS_PUBLISH);
noticeInfo.setOrderType("publishDate");
Page pageNotice = noticeService.selectNoticeList(noticeInfo);
List listNotice;
String noticeBeginDateStr = "";
listNotice = pageNotice.getData();
try {
Date lastDate = this.noticeService.getLastDate();
noticeBeginDateStr = lastDate.toString().substring(0, 10);
for (int i = 0; i < listNotice.size(); i++) {
Notice notice = (Notice) listNotice.get(i);
String noticePublishDate = notice.getPublishDate().toString().substring(0, 10);
if (noticePublishDate.equals(noticeBeginDateStr)) {
notice.setNoticePublishDate(noticePublishDate);
}
}
} catch (Exception e) {
// TODO: handle exception
}
model.put("noticeLastDate", noticeBeginDateStr);
if(listNotice.size()!=0){
model.put("listNotice", listNotice);
}
// ----加载首页---结束------
model.put(Constants.USER_KEY, user);
model.put("menuTreeList", mList);
model.put("dicData", DictionaryLoader.getInstance().getAllDictionary());
return new ModelAndView(this.mainView, model);
}
protected Map referenceData(HttpServletRequest arg0) throws Exception {
Map model = new HashMap();
model.put("dicData", DictionaryLoader.getInstance().getAllDictionary());
return model;
}
public INoticeService getNoticeService() {
return noticeService;
}
public void setNoticeService(INoticeService noticeService) {
this.noticeService = noticeService;
}
public String getMainView() {
return mainView;
}
public void setMainView(String mainView) {
this.mainView = mainView;
}
}
|
package server;
import java.net.InetSocketAddress;
import java.net.InetAddress;
import java.util.Set;
import java.util.HashSet;
import java.util.Map;
import java.util.HashMap;
import client.*;
import util.*;
public class KVServer extends GroupMemberServer {
private Map<Integer, String> dataMap = new HashMap<Integer, String>();
int ringSize;
public KVServer(int port, InetSocketAddress master) {
super(port, master);
}
@Override
protected Shell getShell() {
return new Shell(myID, list, dataMap);
}
@Override
protected void postProcessLeave() {
if (isMaster()) {
MemberID newMasterID = list.getCeilingMemberID(myID.getTimestamp());
if (newMasterID != null) {
InetSocketAddress newMaster = newMasterID.getInetSocketAddress();
try {
list.multicast("Master:"+SocketUtil.inetSocketAddressToString(newMaster));
} catch (Exception e) {}
}
}
rebalanceData();
}
@Override
protected void postProcessGroupMemberMsg(String msg, InetSocketAddress origin) {
if (msg.indexOf("RingSize:") == 0) {
try {
int ringSize = Integer.parseInt(msg.substring(9));
list.setRingSize(ringSize);
} catch (Exception e) {
log("Invalid ring size");
}
return;
}
processKVMsg(msg, origin);
}
private void processKVMsg(String msg, InetSocketAddress origin) {
// TODO: remove log
log(msg);
int key;
String action, value = null;
try {
int left = msg.indexOf(":"), right = msg.indexOf("=");
action = msg.substring(0, left).toLowerCase();
if (right == -1) {
key = Integer.parseInt(msg.substring(left+1));
} else {
key = Integer.parseInt(msg.substring(left+1, right));
value = msg.substring(right+1);
}
} catch (Exception e) {
report(origin, "Invalid message = "+msg);
return;
}
MemberID targetID = list.getCeilingMemberID(key);
if (!targetID.equals(myID)) {
InetSocketAddress targetSockAddr = targetID.getInetSocketAddress();
try {
UDPClient client = new UDPClient(500);
client.connect(targetSockAddr);
client.sendString(msg);
client.disconnect();
String result = client.receiveString(128);
report(origin, result);
client.close();
log("Transferred request = "+msg+" to "+targetID);
} catch (Exception e) {
log("Transferring request to "+targetID+" failed");
report(origin, "Something wrong");
return;
}
} else {
Pair<Integer, String> data = new Pair<Integer, String>(key, value);
if (action.equals("insert")) {
processInsert(data, origin);
} else if (action.equals("update")) {
processUpdate(data, origin);
} else if (action.equals("delete")) {
processDelete(key, origin);
} else if (action.equals("lookup")) {
processLookup(key, origin);
} else {
log("Invalid message = \""+msg+"\"");
}
}
}
@Override
protected void postProcessMemberUpdate() {
rebalanceData();
}
private void rebalanceData() {
log("Rebalancing ... ");
UDPClient client = new UDPClient(500);
Set<Integer> keyToRemove = new HashSet<Integer>();
for (Map.Entry<Integer, String> entry : dataMap.entrySet()) {
int key = entry.getKey();
MemberID targetID = list.getCeilingMemberID(key);
if (targetID != null && !targetID.equals(myID)) {
client.connect(targetID.getInetSocketAddress());
client.sendString("Insert:"+key+"="+entry.getValue());
client.disconnect();
keyToRemove.add(key);
log("Transferred "+entry+" to "+targetID);
}
}
dataMap.keySet().removeAll(keyToRemove);
}
protected void processInsert(
Pair<Integer, String> data,
InetSocketAddress origin) {
addData(dataMap, data, origin, "insert");
}
protected void processUpdate(
Pair<Integer, String> data,
InetSocketAddress origin) {
addData(dataMap, data, origin, "update");
}
protected void processDelete(int key, InetSocketAddress origin) {
deleteData(dataMap, key, origin);
}
protected void processLookup(int key, InetSocketAddress origin) {
lookupData(dataMap, key, origin);
}
public void addData(
Map<Integer, String> dataMap,
Pair<Integer, String> data,
InetSocketAddress origin,
String action) {
int key = data.getLeft();
String value = data.getRight();
if (action.equals("insert") && dataMap.containsKey(key)) {
report(origin, "Key already exists");
} else if (action.equals("update") && !dataMap.containsKey(key)) {
report(origin, "Key does not exist");
} else {
if (action.equals("insert")) {
log("Inserting ("+key+"="+value+")");
} else {
log("Udating ("+key+"="+value+")");
}
dataMap.put(key, value);
log("Succeed");
report(origin, "Succeed");
}
}
public void deleteData(
Map<Integer, String> dataMap,
int key,
InetSocketAddress origin) {
if (dataMap.containsKey(key)) {
log("Deleting entry with key = "+key);
dataMap.remove(key);
log("Succeed");
report(origin, "Succeed");
} else {
report(origin, "Key not found");
}
}
public void lookupData(
Map<Integer, String> dataMap,
int key,
InetSocketAddress origin) {
String value = dataMap.get(key);
if (value == null) {
report(origin, "No result found");
} else {
report(origin, "\""+value+"\"");
}
}
public void report(InetSocketAddress origin, Object o) {
if (origin != null) {
UDPClient client = new UDPClient(500);
client.connect(origin);
client.sendString(o.toString());
client.disconnect();
client.close();
} else {
System.out.println(o);
}
}
public static void main(String [] args) {
assert(args.length >= 2);
int port;
try {
port = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
System.err.println("Invalid port number");
return;
}
InetSocketAddress master;
try {
if (args[1].equals("master")) {
master = SocketUtil.parseInetSocketAddress(
InetAddress.getLocalHost().getHostAddress()+":"+port
);
} else {
master = SocketUtil.parseInetSocketAddress(args[1]);
}
} catch (Exception e) {
System.err.println("Invalid master socket address");
return;
}
KVServer server = new KVServer(port, master);
if (args.length >= 3) {
server.setLogFileName(args[2]);
}
server.start();
server.stop();
}
}
|
package projetobd.DAO;
import java.sql.Connection;
import projetobd.connection.ConectarBD;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import projetobd.bean.Item;
import projetobd.bean.Destino;
import projetobd.bean.HistoricodeConsumo;
/**
*
* @author sampa
*/
public class HistoricodeConsumoDAO {
public void inserir (HistoricodeConsumo obj){
ConectarBD objBD = new ConectarBD();
String lCNPJDestino = obj.getDestino().getCNPJ();
int lMes = obj.getMes();
int lIdItem = obj.getItem().getIdItem();
int lQuantidadeMensal = obj.getQuantidadeMensal();
objBD.conectar();
try {
String sql = ("INSERT INTO HistoricodeConsumo (CNPJ, Mes, IdItem, QuantidadeMensal) VALUES (?,?,?,?)");
PreparedStatement stmt = objBD.conexao.prepareStatement(sql);
stmt.setString (1, lCNPJDestino);
stmt.setInt(2, lMes);
stmt.setInt(3, lIdItem);
stmt.setInt(4, lQuantidadeMensal);
stmt.execute();
JOptionPane.showMessageDialog(null, "Comando executado com sucesso");
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Erro na execução do insert"+ex.getMessage());
}
}
public ResultSet selecionar (){
ConectarBD objBD = new ConectarBD();
objBD.conectar();
try {
String sql = "SELECT HistoricodeConsumo.* FROM HistoricodeConsumo " ;
PreparedStatement objstmt = objBD.conexao.prepareStatement(sql);
ResultSet rs = objstmt.executeQuery();
JOptionPane.showMessageDialog(null, "Comando executado com sucesso");
return rs;
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Erro na execução do select "+ex.getMessage());
}
return null;
}
public void atualizar (HistoricodeConsumo obj){
ConectarBD objBD = new ConectarBD();
String lCNPJDestino = obj.getDestino().getCNPJ();
int lMes = obj.getMes();
int lIdItem = obj.getItem().getIdItem();
int lQuantidadeMensal = obj.getQuantidadeMensal();
objBD.conectar();
objBD.conectar();
try {
String sql = "UPDATE HistoricodeConsumo SET CNPJ = ?, Mes = ?,IdItem = ?, QuantidadeMensal = ? WHERE CNPJ = ?" ;
PreparedStatement objstmt = objBD.conexao.prepareStatement(sql);
objstmt.setString (1, lCNPJDestino);
objstmt.setInt(2, lMes);
objstmt.setInt(3, lIdItem);
objstmt.setInt(4, lQuantidadeMensal);
objstmt.execute();
JOptionPane.showMessageDialog(null, "Comando executado com sucesso");
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Erro na execução do update"+ex.getMessage());
}
}
public void deletar (HistoricodeConsumo obj){
ConectarBD objBD = new ConectarBD();
String lCNPJDestino = obj.getDestino().getCNPJ();
objBD.conectar();
try {
String sql = "DELETE FROM HistoricodeConsumo WHERE CNPJ = ?" ;
PreparedStatement objstmt = objBD.conexao.prepareStatement(sql);
objstmt.setString(4, lCNPJDestino);
objstmt.execute();
JOptionPane.showMessageDialog(null, "Comando executado com sucesso");
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Erro na execução "+ex.getMessage());
}
}
}
|
/* To ignore the warning
"The serializable class ClASSNAME does not declare a static final serialVersionUID......
*/
@SuppressWarnings("serial")
public class NumberInhabitantsException extends Exception {
public NumberInhabitantsException() {
System.out.println("You're trying to instanciate a City class with a negative number of inhabitants!");
}
}
|
package org.tomat.translate.brooklyn.exceptions;
import org.tomat.translate.exceptions.NotSupportedTypeByTechnologyException;
/**
* Created by Kiuby88 on 19/10/14.
*/
public class BrooklynVisitorRelationConfigurationNotSupportedType extends Exception implements
BrooklynException{
public BrooklynVisitorRelationConfigurationNotSupportedType() {
super();
}
public BrooklynVisitorRelationConfigurationNotSupportedType(String msg) {
super(msg);
}
}
|
package ds1_project.Responses;
import java.io.Serializable;
public class ReadResponse implements Serializable {
/**
* ReadResponse : Message replied by a node to a client
* requesting to read its value. It takes as argument the
* node value.
*/
private static final long serialVersionUID = 1L;
private final int value;
public int getValue() {
return this.value;
}
public ReadResponse(final int value2) {
this.value = value2;
}
}
|
package SeliniumSessions;
public class GoogleTest {
public static void main(String[] args) {
BrowserActions br=new BrowserActions();
br.launchBrowser("chrome");
br.launchUrl("http://www.Google.com");
String title=br.doGetTitle();
System.out.println("page title is:"+title);
if(title.equals("Google")) {
System.out.println("correct title");
}
else {
System.out.println("in correct title");
}
}
}
|
package 그래픽프로그램;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class 버튼3개 {
public static void main(String[] args) {
JFrame r = new JFrame();
r.getContentPane().setBackground(Color.MAGENTA);
r.setSize(500, 500);
r.getContentPane().setLayout(null); // 레이아웃을 지정하지 않으면
JButton btnNewButton = new JButton("별 10개");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for(int i=0; i<10; i++) {
System.out.print("*");
}
System.out.println();
}
});
btnNewButton.setFont(new Font("Lucida Grande", Font.BOLD, 40));
btnNewButton.setBackground(Color.GREEN);
btnNewButton.setBounds(110, 44, 270, 59);
r.getContentPane().add(btnNewButton);
JButton btnNewButton_1 = new JButton("커피*5");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for(int i=0; i<5; i++) {
System.out.print("커피*");
}
System.out.println();
}
});
btnNewButton_1.setFont(new Font("Lucida Grande", Font.BOLD, 40));
btnNewButton_1.setBackground(Color.GREEN);
btnNewButton_1.setBounds(110, 115, 270, 59);
r.getContentPane().add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("커피*우유3");
btnNewButton_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for(int i=0; i<3; i++) {
System.out.println("커피*우유");
}
}
});
btnNewButton_2.setFont(new Font("Lucida Grande", Font.BOLD, 40));
btnNewButton_2.setBackground(Color.GREEN);
btnNewButton_2.setBounds(110, 186, 270, 59);
r.getContentPane().add(btnNewButton_2);
JButton btnNewButton_2_1 = new JButton("1:짱!");
btnNewButton_2_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for(int i=0; i<3; i++) {
System.out.println( (i + 1) + ":짱!");
}
}
});
btnNewButton_2_1.setFont(new Font("Lucida Grande", Font.BOLD, 40));
btnNewButton_2_1.setBackground(Color.GREEN);
btnNewButton_2_1.setBounds(110, 265, 270, 59);
r.getContentPane().add(btnNewButton_2_1);
// 내가 넣고 싶은 위치에 넣을 수 있다
r.setVisible(true);
}
}
|
package leecode.DP;
//对最后一行一列修改一定要注意,如果有一个1,则后面全部为0;不像上个题目全赋值为1,从后向前赋值
public class 不同路径Ⅱ_63 {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int m=obstacleGrid.length;
int n=obstacleGrid[0].length;
if(m<0||n<0){
return 0;
}
int[][]dp=new int[m][n];
if(obstacleGrid[m-1][n-1]==1){
return 0;
}
for (int i = m-1,j=n-1; i >=0 ; i--) {
if(obstacleGrid[i][j]==1){
dp[i][j]=0;
break;
}
dp[i][j]=1;
}
for (int i = m-1,j=n-1; j >=0 ; j--) {
if(obstacleGrid[i][j]==1){
dp[i][j]=0;
break;
}
dp[i][j]=1;
}
for (int i = m-2; i >=0 ; i--) {
for (int j = n-2; j >=0 ; j--) {
dp[i][j]=obstacleGrid[i][j]==1?0:(dp[i+1][j]+dp[i][j+1]);
}
}
return dp[0][0];
}
}
|
/**
* Created by Мутщь on 24.03.2016.
*/
public class ArrayQueue extends AbstractQueue{
static final int SIZE = 3;
private Object[] queue = new Object[SIZE];
private int first = 0;
private void check(int size) {
if (size <= this.queue.length) {
return;
}
Object[] narray = new Object[this.queue.length * 2];
System.arraycopy(this.queue, this.first, narray, 0, this.queue.length - this.first);
System.arraycopy(this.queue, 0, narray, this.queue.length - this.first, this.first);
this.first = 0;
this.queue = narray;
}
public void doEnqueue(Object element) {
check(this.size);
this.queue[(this.first + this.size - 1) % this.queue.length] = element;
}
public Object element() {
return this.queue[this.first];
}
protected ArrayQueue createEmpty() {
return new ArrayQueue();
}
public Object doDequeue() {
Object ret = this.queue[this.first];
this.queue[this.first] = null;
this.first++;
this.first %= this.queue.length;
return ret;
}
public void doClear() {
this.queue = new Object[SIZE];
this.first = 0;
}
}
|
/**
* The CommandMe package is a suite of tools that can be used to easily create CLI tools in Java.
*
* @author Rukmal Weerawarana
*
* @version 1.0.0
*
* @since 1.0.0
*/
package me.rukmal.commandme;
|
package com.pfchoice.springboot.service.impl;
import com.pfchoice.springboot.configuration.ConfigProperties;
import com.pfchoice.springboot.model.MembershipHedisMeasure;
import com.pfchoice.springboot.repositories.MembershipHedisMeasureRepository;
import com.pfchoice.springboot.service.MembershipHedisMeasureService;
import com.pfchoice.springboot.util.PrasUtil;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service("membershipHedisMeasureService")
@Transactional
public class MembershipHedisMeasureServiceImpl implements MembershipHedisMeasureService {
@Autowired
private MembershipHedisMeasureRepository membershipHedisMeasureRepository;
@Autowired
ConfigProperties configProperties;
@Autowired
PrasUtil prasUtil;
public MembershipHedisMeasure findById(Integer id) {
return membershipHedisMeasureRepository.findOne(id);
}
public void saveMembershipHedisMeasure(MembershipHedisMeasure membershipHedisMeasure) {
membershipHedisMeasureRepository.save(membershipHedisMeasure);
}
public void updateMembershipHedisMeasure(MembershipHedisMeasure membershipHedisMeasure) {
saveMembershipHedisMeasure(membershipHedisMeasure);
}
public void deleteMembershipHedisMeasureById(Integer id) {
membershipHedisMeasureRepository.delete(id);
}
public void deleteAllMembershipHedisMeasures() {
membershipHedisMeasureRepository.deleteAll();
}
public List<MembershipHedisMeasure> findAllMembershipHedisMeasures() {
return (List<MembershipHedisMeasure>) membershipHedisMeasureRepository.findAll();
}
public Page<MembershipHedisMeasure> findAllMembershipHedisMeasuresByPage(Specification<MembershipHedisMeasure> spec,
Pageable pageable) {
return membershipHedisMeasureRepository.findAll(spec, pageable);
}
public boolean isMembershipHedisMeasureExist(MembershipHedisMeasure membershipHedisMeasure) {
return findById(membershipHedisMeasure.getId()) != null;
}
public boolean isDataExistsInTable(String tableName) {
return (membershipHedisMeasureRepository.isDataExistsInTable() == 0) ? false : true;
}
public int unloadCSV2Table() {
return membershipHedisMeasureRepository.unloadCSV2Table();
}
public Integer loadData(final Map<String, Object> parameters, String insuranceCode) throws IOException, InterruptedException{
return prasUtil.executeSQLQuery(membershipHedisMeasureRepository,insuranceCode, parameters, configProperties.getQueryTypeInsert() );
}
}
|
package me.jprichards.elsimclient;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONObject;
import me.jprichards.elsimclient.model.ModelRepresentation;
/**
* Abstract class containing basic logic for an external controller for
* our modified elevator simulator.
* Contains empty methods that are called to handle all event types and upcalls
* to performs actions. Performs initial set-up of the model and handles action responses.
* Subclasses need only override the handler methods for the events they wish to handle.
* @author Joshua Richards
*
*/
public abstract class Controller
{
private NetworkHelper connection;
protected ModelRepresentation model;
private int nextActionId = 0;
private Map<Integer, Runnable> successCallbacks = new HashMap<>();
private Map<Integer, Runnable> failureCallbacks = new HashMap<>();
/*
Data on the model (set up of building)
*/
protected int noFloors;
protected int noCars;
protected int carCapacity;
protected int currFloor;
protected boolean simulationHasEnd = false;
public Controller(String host, int port) throws IOException
{
connection = new NetworkHelper(host, port);
}
/**
* Synchronously runs the main loop for the client side of the an elevator simulation.
* @throws IOException if there is a connection problem
*/
public void start() throws IOException
{
while (true)
{
JSONObject event = connection.receiveMessage();
handleEvent(event);
}
}
/**
* Calls the corresponding handler method for the given event type.
* If the type is unknown, an error message will be printed to stderr
* @param event the entire event message as sent from the server
*/
protected void handleEvent(JSONObject event) throws IOException
{
switch (event.getString("type"))
{
case "modelChange":
onModelChange(event);
break;
case "carRequested":
onCarRequested(event);
break;
case "doorOpened":
onDoorOpened(event);
break;
case "doorClosed":
onDoorClosed(event);
break;
case "doorSensorClear":
onDoorSensorClear(event);
break;
case "carArrived":
onCarArrived(event);
break;
case "personEnteredCar":
onPersonEnteredCar(event);
break;
case "personLeftCar":
onPersonLeftCar(event);
break;
case "floorRequest":
onFloorRequest(event);
break;
case "actionResponse":
onActionPerformed(event);
break;
case "floorPassed":
OnFloorPassed(event);
break;
case "simulationTimeout":
OnSimulationTimeOut(event);
break;
case "actionProcessed":
OnActionprocessed(event);
break;
case "modelChanged":
OnModelChanged(event);
break;
case "heartbeat":
OnHeartBeat(event);
break;
default:
System.err.println("Unknown event type: " + event.toString(4));
break;
}
}
/**
* Constructs an action message with a unique id, transmits the message,
* and stores the given callbacks to be called in onActionPerformed.
* @param type a String that the server will recognize as a valid action type
* @param params a JSONObject containing all the required information the server is expecting
* @param onSuccess Runnable to be called once the action is successfully performed
* @param onFailure Runnable to be called if the action is unsuccessful
* @throws IOException if there is a connection problem
*/
private void performAction(String type, JSONObject params,
Runnable onSuccess, Runnable onFailure) throws IOException
{
int id = nextActionId++;
JSONObject action = new JSONObject();
action.put("type", type);
action.put("id", id++);
action.put("params", params);
// Just for debugging to see JSON of action sent to server
System.out.println(action.toString(4));
successCallbacks.put(id, onSuccess);
failureCallbacks.put(id, onFailure);
connection.sendMessage(action);
}
/**
* Performs the sendCar action
* @param carId the car to be sent
* @param floorId the floor to send it to
* @param nextDirection the direction it will travel after it arrives
* @param onSuccess success callback
* @param onFailure failure callback
* @throws IOException if there is a connection problem
*/
protected void sendCar(int carId, int floorId, String nextDirection,
Runnable onSuccess, Runnable onFailure) throws IOException
{
// This builds the arguments of the sendCar action
JSONObject params = new JSONObject();
params.put("car", carId);
params.put("floor", floorId);
params.put("nextDirection", nextDirection);
performAction("sendCar", params, onSuccess, onFailure);
}
/**
* Performs the changeNextDirection action
* @param carId the id of the car whose nextDirection is being changes
* @param nextDirection the car's new nextDirection
* @param onSuccess success callback
* @param onFailure failure callback
* @throws IOException
*/
protected void changeNextDirection(int carId, String nextDirection,
Runnable onSuccess, Runnable onFailure) throws IOException
{
JSONObject params = new JSONObject();
params.put("car", carId);
params.put("nextDirection", nextDirection);
performAction("changeNextDirection", params, onSuccess, onFailure);
}
/**
* Handler method for the modelChange event
* @param event the full event message
*/
protected void onModelChange(JSONObject event) throws IOException
{
model = new ModelRepresentation(event.getJSONObject("description"));
}
/**
* Handler method for the carRequested event.
* Should be overridden by subclasses wishing to handle this event
* @param event the full event message
*/
protected void onCarRequested(JSONObject event) throws IOException {}
/**
* Handler method for the doorOpened event.
* Should be overridden by subclasses wishing to handle this event
* @param event the full event message
*/
protected void onDoorOpened(JSONObject event) throws IOException {}
/**
* Handler method for the doorClosed event.
* Should be overridden by subclasses wishing to handle this event
* @param event the full event message
*/
protected void onDoorClosed(JSONObject event) throws IOException {}
/**
* Handler method for the doorSensorClear event.
* Should be overridden by subclasses wishing to handle this event
* @param event the full event message
*/
protected void onDoorSensorClear(JSONObject event) throws IOException {}
/**
* Handler method for the carArrived event.
* Should be overridden by subclasses wishing to handle this event
* @param event the full event message
*/
protected void onCarArrived(JSONObject event) throws IOException {}
/**
* Handler method for the personEnteredCar event.
* Should be overridden by subclasses wishing to handle this event
* @param event the full event message
*/
protected void onPersonEnteredCar(JSONObject event) throws IOException {}
/**
* Handler method for the personLeftCar event.
* Should be overridden by subclasses wishing to handle this event
* @param event the full event message
*/
protected void onPersonLeftCar(JSONObject event) throws IOException {}
/**
* Handler method for the floorRequest event.
* Should be overridden by subclasses wishing to handle this event
* @param event the full event message
*/
protected void onFloorRequest(JSONObject event) throws IOException {}
/**
* Handler method for the floorRequest event.
* Removes the corresponding callbacks for the action and calls
* the correct one.
* @param event the full event message
*/
protected void onActionPerformed(JSONObject event)
{
JSONObject description = event.getJSONObject("description");
int actionId = description.getInt("actionId");
boolean success = description.getBoolean("success");
Runnable onSuccess = successCallbacks.remove(actionId);
Runnable onFailure = failureCallbacks.remove(actionId);
Runnable callback = (success) ? onSuccess : onFailure;
if (callback != null)
{
callback.run();
}
}
/**
* Simulator has sent end of simulation event, client terminates
*
* @param event
*/
protected void OnSimulationTimeOut(JSONObject event)
{
simulationHasEnd = true;
// System.exit(0);
}
/**
* Simulator has sent a heart beat to keep communication live
*
* @param event
*/
protected void OnHeartBeat(JSONObject event) throws IOException {}
/**
* Handler method for the floorPased event.
* Should be overridden by subclasses wishing to handle this event
* @param event the full event message
*/
protected void OnFloorPassed(JSONObject event) throws IOException {}
/**
* Handler method for the onModelChangedevent.
* Get some basic information about the environment
* @param event the full event message
*/
protected void OnModelChanged(JSONObject event) throws IOException
{
JSONObject description = event.getJSONObject("description");
noFloors = description.getJSONArray("floors").length();
noCars = description.getJSONArray("cars").length();
carCapacity = description.getJSONArray("cars").getJSONObject(0).getInt("capacity");
}
protected void OnActionprocessed(JSONObject event) throws IOException {}
}
|
package assignment;
/**
* An {@link UpdateVisitor} to update all of the {@link GUIElement}s.
* @author I.A
*/
public final class DefaultUpdateVisitor implements UpdateVisitor {
// TODO missing code here
public void updateButton(Button element, float deltaTime) {
// TODO missing code here
}
// TODO missing code here
public void updateLabel(Label element, float deltaTime) {
// TODO missing code here
}
// TODO missing code here
public void updateGUI(GUIManager gui, float deltaTime) {
// TODO missing code here
}
}
|
package edu.oakland.GUI;
import edu.oakland.*;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.VPos;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.paint.Color;
import javafx.stage.FileChooser;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javax.xml.bind.annotation.XmlList;
import java.io.File;
import java.net.URL;
import java.text.DecimalFormat;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.YearMonth;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Locale;
import java.util.Set;
import java.util.SortedSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import static java.time.temporal.ChronoUnit.DAYS;
public class MainGUI {
private static final Logger logger = Logger.getLogger(MainGUI.class.getName());
/**
* Currently used account for the logged in user
*/
private Account currentAccount;
/**
* Currently displayed month in the calendar
*/
private ZonedDateTime currentMonth;
/**
* Currently displayed day in detail pane
*/
private LocalDate currentDate;
/**
* Currently selected event in detail pane
*/
private Event currentEvent;
/**
* Each day in the calendar view has a VBox to put things in
*/
private HashMap<LocalDate, VBox> VBoxesByDay = new HashMap<>();
/**
* Each event has a label made for it
*/
private HashMap<Label, Event> eventsByLabel = new HashMap<>();
/*
* Calendar Page Objects
*/
/**
* Matrix used to return the selected date on click
*/
private int[][] daylayout;
private LocalDate oldDateValue;
private Set<Color> eventColors = new HashSet<>();
@FXML
private Button updateButton, removeButton, leftArrow, rightArrow;
@FXML
private GridPane calendarGridPane;
@FXML
private Label calendarHeaderLabel, dateLabel;
@FXML
private MenuBar myMenuBar;
@FXML
private TabPane tabPane;
@FXML
private TextArea eventOutput;
@FXML
private ToggleButton toggleCompleted;
/*
* Add Event Page Objects
*/
@FXML
private DatePicker startDateField, endDateField, recurrenceEndDate;
@FXML
private CheckBox allDay, highPrior;
@FXML
private ComboBox startTimeDropdown, endTimeDropdown, recurField;
@FXML
private TextField eventNameField, eventLocationField, eventAttendeesField, searchBox;
@FXML
private TextArea eventDescriptionField, completedEventsArea;
@FXML
public void initialize() {
//NB Only pure GUI setup! Others use postInit
//"good" colors for events that are next to each other
eventColors.add(Color.web("#D7FFF1"));
eventColors.add(Color.web("#A0DDE6"));
eventColors.add(Color.web("#80C2AF"));
eventColors.add(Color.web("#30C5FF"));
//Create labels for day of week header
int columnIndex = 0; //Which column to put the next label in
for (int i = 6; i < 13; i++) { //Each day of the week by number, want to start at sunday so numbering is offset
DayOfWeek dayOfWeek = DayOfWeek.of((i % 7) + 1); //Start at sunday, which is day 7
Label DoWLabel = new Label();
DoWLabel.setText(dayOfWeek.getDisplayName(TextStyle.FULL, Locale.US));
calendarGridPane.add(DoWLabel, columnIndex++, 0);
GridPane.setHalignment(DoWLabel, HPos.CENTER);
GridPane.setValignment(DoWLabel, VPos.BOTTOM);
}
//Set the time comboboxes with good values
GUIHelper.setupTimeCombobox(startTimeDropdown, LocalTime.MIDNIGHT);
GUIHelper.setupTimeCombobox(endTimeDropdown, LocalTime.MIDNIGHT.plusSeconds(1));
startTimeDropdown.getSelectionModel().selectFirst();
endTimeDropdown.getSelectionModel().selectFirst();
//Set the date fields
oldDateValue = LocalDate.now();
endDateField.setValue(oldDateValue);
startDateField.setValue(LocalDate.now());
//Set the recurrence dropdown
recurField.getItems().clear();
for (Frequency freq : Frequency.values()) {
recurField.getItems().add(freq);
}
recurField.getSelectionModel().selectFirst();
}
/**
* Handles creation of dummy events for testing purposes
* TODO Delete
*/
public void postInit() {
Set<SingularEvent> dummyEvents = new HashSet<>();
if (getCurrentAccount().getUserName().equals("y")) {
getCurrentAccount().setCalendar(new Calendar());
SingularEvent dummyEvent1 = new SingularEvent(ZonedDateTime.now(),
ZonedDateTime.now().plusSeconds(120),
"High Prio SingularEvent");
dummyEvent1.setHighPriority(true);
dummyEvent1.setEventDesc("Description");
dummyEvents.add(dummyEvent1);
dummyEvents.add(new SingularEvent(ZonedDateTime.now().plusMinutes(5),
ZonedDateTime.now().plusMinutes(120),
"SingularEvent 1.5"));
dummyEvents.add(new SingularEvent(ZonedDateTime.now().plusDays(2),
ZonedDateTime.now().plusDays(3),
"SingularEvent 123"));
dummyEvents.add(new SingularEvent(ZonedDateTime.now().plusDays(2).plusSeconds(1),
ZonedDateTime.now().plusDays(3).plusMinutes(1),
"After 123"));
dummyEvents.add(new SingularEvent(ZonedDateTime.now().minusDays(7),
ZonedDateTime.now().minusDays(3),
"LongEvent"));
dummyEvents.add(new SingularEvent(ZonedDateTime.now().minusDays(8).plusHours(6),
ZonedDateTime.now().minusDays(6).plusHours(6),
"Overlap 1"));
dummyEvents.add(new SingularEvent(ZonedDateTime.now().minusDays(8),
ZonedDateTime.now().minusDays(6).plusHours(6),
"Overlap 2"));
dummyEvents.add(new SingularEvent(ZonedDateTime.now().minusDays(6),
ZonedDateTime.now().minusDays(4),
"48HrEvent"));
RecurrentEvent dummyEventRecurring = new RecurrentEvent(ZonedDateTime.now().minusWeeks(2),
ZonedDateTime.now().minusWeeks(2).plusMinutes(30),
"repeating event",
Frequency.DAILY,
ZonedDateTime.now().minusWeeks(2),
ZonedDateTime.now().minusWeeks(1));
dummyEvents.add(dummyEventRecurring);
dummyEvent1.setCompleted(true);
dummyEvents.forEach(getCurrentAccount().getCalendar()::addEvent);
}
toggleCompleted.setDisable(true);
updateButton.setDisable(true);
removeButton.setDisable(true);
leftArrow.setDisable(true);
rightArrow.setDisable(true);
viewMonth(ZonedDateTime.now());
}
/**
* Initializes the calendar display to draw out the dates for each day of the week in that given month
*
* @param theMonth The input month which will be rendered
*/
public void viewMonth(ZonedDateTime theMonth) {
calendarGridPane.getChildren().removeAll(VBoxesByDay.values());
//todo cache?
VBoxesByDay.clear();
eventsByLabel.clear();
daylayout = new int[7][7];
currentMonth = theMonth.withDayOfMonth(1);
int rowIndex = 1;
int columnIndex = currentMonth.getDayOfWeek().getValue() % 7; //Sunday -> 0
calendarHeaderLabel.setText(currentMonth.format(DateTimeFormatter.ofPattern("MMMM YYYY")));
//YearMonth yearMonth = YearMonth.of(currentMonth.getYear(), currentMonth.getMonth());
//Set<Event> monthEvents = getCurrentAccount().getCalendar().getMonthEvents(yearMonth);
Iterator<Color> goodColors = eventColors.iterator();
LocalDate current = currentMonth.toLocalDate();
while (current.getMonth() == currentMonth.getMonth()) { //For every day of month
//When reached sunday (the first day of week) move down a row
if (current.getDayOfWeek() == DayOfWeek.SUNDAY && current.getDayOfMonth() != 1) {
rowIndex++;
}
//The VBox will hold any GUI things for the day
VBox dayVBox = new VBox();
dayVBox.setPadding(new Insets(1));
dayVBox.setOnMouseClicked(this::getCellData);
//Label for date of month
Label DoMLabel = new Label();
DoMLabel.setText(current.format(DateTimeFormatter.ofPattern("d")));
dayVBox.getChildren().add(DoMLabel);
int currC = columnIndex++ % 7;
int currR = rowIndex;
Set<Event> dayEvents = getCurrentAccount().getCalendar().getDayEvents(current);
for (Event currEvent : dayEvents) {
Label eventLabel = new Label();
eventLabel.setText(currEvent.getEventName());
if (currEvent.getHighPriority()) {
eventLabel.setStyle("-fx-background-color: OrangeRed;");
} else {
if (!goodColors.hasNext()) goodColors = eventColors.iterator();
eventLabel.setBackground(new Background(new BackgroundFill(goodColors.next(), null, null)));
}
eventLabel.setMaxWidth(Double.MAX_VALUE); //So it fills the width
eventLabel.addEventFilter(MouseEvent.MOUSE_CLICKED, this::viewEventDetail);
eventsByLabel.put(eventLabel, currEvent);
dayVBox.getChildren().add(eventLabel);
}
calendarGridPane.add(dayVBox, currC, currR);
VBoxesByDay.put(current, dayVBox);
daylayout[currR][currC] = Integer.valueOf(DoMLabel.getText());
current = current.plusDays(1);
}
}
/**
* Opens the create account GUI page
*/
@FXML
private void openCreateAccountGUI() {
Stage stage;
try {
stage = new Stage();
URL resourceFXML = getClass().getClassLoader().getResource("CreateAccountGUI.fxml");
URL resourceCSS = getClass().getClassLoader().getResource("mystyle.css");
if (resourceFXML == null || resourceCSS == null) {
System.out.println("Missing resource detected, ABORT!");
System.exit(-1);
}
Parent root = FXMLLoader.load(resourceFXML);
Scene scene = new Scene(root, 400, 600);
String css = resourceCSS.toExternalForm();
scene.getStylesheets().add(css);
stage.setScene(scene);
stage.setTitle("Create Account");
stage.initModality(Modality.APPLICATION_MODAL);
Stage oldStage = (Stage) myMenuBar.getScene().getWindow();
stage.initOwner(oldStage.getScene().getWindow());
stage.showAndWait();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Allows the user to import data from the menubar
*/
@FXML
private void importData() {
FileChooser chooser = new FileChooser();
chooser.setTitle("Import data");
chooser.setInitialDirectory(Account.getAccountFile().getParentFile());
File importFile = chooser.showOpenDialog(new Stage());
if (importFile == null) return;
if (Account.loadAccounts(importFile)) {
setCurrentAccount(Account.getAccount(getCurrentAccount().getUserName())); //Refresh from what was loaded
viewMonth(currentMonth);
GUIHelper.alert("Load me", "Data were loaded", "Loaded data successfully!", Alert.AlertType.INFORMATION);
} else {
GUIHelper.errorAlert("This will not do.", "Couldn't load data!", "There was an error loading that file!");
}
}
/**
* Allows the user to export data from the menubar
*/
@FXML
private void exportData() {
FileChooser chooser = new FileChooser();
chooser.setInitialDirectory(Account.getAccountFile().getParentFile());
chooser.setInitialFileName("accounts.dat");
File exportFile = chooser.showSaveDialog(null);
if (exportFile == null) return;
if (Account.saveAccounts(exportFile)) {
GUIHelper.alert("Save me", "Data were saved", "Exported data successfully!", Alert.AlertType.INFORMATION);
} else {
GUIHelper.errorAlert("This will not do.", "Couldn't save data!", "There was an error saving that file!");
}
}
@FXML
private void saveData() {
Account.saveAccounts();
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("Saving Completed");
alert.setHeaderText("Saving Completed");
alert.setContentText("You did it! (I knew you could)");
alert.showAndWait();
}
@FXML
private void logoutApp() {
Alert alert = new Alert(Alert.AlertType.CONFIRMATION,
"Are you sure you want to logout?",
ButtonType.YES,
ButtonType.NO,
ButtonType.CANCEL);
alert.showAndWait();
if (alert.getResult() == ButtonType.YES) {
if (currentAccount == null) {
logger.warning("Wanted to logout but the current user was already null");
return;
}
try {
URL resourceFXML = getClass().getClassLoader().getResource("LoginGUI.fxml");
URL resourceCSS = getClass().getClassLoader().getResource("mystyle.css");
if (resourceFXML == null || resourceCSS == null) {
System.out.println("Missing resource detected, ABORT!");
System.exit(-1);
}
Parent root = FXMLLoader.load(resourceFXML);
Stage oldStage = (Stage) myMenuBar.getScene().getWindow();
oldStage.close();
setCurrentAccount(null);
Scene scene = new Scene(root, 400, 400);
String css = resourceCSS.toExternalForm();
scene.getStylesheets().add(css);
Stage newStage = new Stage();
newStage.setTitle("Cadmium Calendar");
newStage.setScene(scene);
newStage.show();
} catch (Exception e) {
logger.log(Level.SEVERE, "Couldn't make a new loginGUI so can't logout", e);
}
}
}
@FXML
private void exitApp() {
Platform.exit();
}
@FXML
private void gotoAddEventTab() {
SingleSelectionModel<Tab> selector = tabPane.getSelectionModel();
selector.select(1);
}
@FXML
private void gotoReportTab() {
SingleSelectionModel<Tab> selector = tabPane.getSelectionModel();
selector.select(2);
}
@FXML
private void search() {
completedEventsArea.setText("");
SortedSet<Event> list = getCurrentAccount().getCalendar().searchEvents(searchBox.getText());
StringBuilder outputText = new StringBuilder();
for (Event currEvent : list) {
outputText.append(currEvent.getEventName() + "\n");
}
completedEventsArea.setText(outputText.toString());
}
/**
* Opens the settings GUI page
*/
@FXML
private void openSettingsGUI() {
Stage stage;
try {
stage = new Stage();
URL resourceFXML = getClass().getClassLoader().getResource("SettingsGUI.fxml");
URL resourceCSS = getClass().getClassLoader().getResource("mystyle.css");
if (resourceFXML == null || resourceCSS == null) {
System.out.println("Missing resource detected, ABORT!");
System.exit(-1);
}
Parent root = FXMLLoader.load(resourceFXML);
Scene scene = new Scene(root, 400, 400);
String css = resourceCSS.toExternalForm();
scene.getStylesheets().add(css);
stage.setScene(scene);
stage.setTitle("Settings");
stage.initModality(Modality.APPLICATION_MODAL);
stage.initOwner(tabPane.getScene().getWindow());
stage.showAndWait();
} catch (Exception e) {
e.printStackTrace();
}
}
@FXML
private void aboutApp() {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Cadmium Calendar");
alert.setHeaderText("Copyright 2018");
alert.setContentText(
"Created by:\nIsida Ndreu\nJustin Kur\nSean Ramocki\nEric Ramocki\nJosh Baird\nMichael Koempel");
alert.showAndWait();
}
@FXML
private void viewMonthPrevious() {
viewMonth(currentMonth.minusMonths(1));
}
@FXML
private void viewMonthNext() {
viewMonth(currentMonth.plusMonths(1));
}
@FXML
private void viewEventDetail(MouseEvent event) {
Node sourceNode = (Node) event.getSource();
Label source;
try {
source = (Label) sourceNode;
} catch (ClassCastException e) {
logger.log(Level.WARNING, "SingularEvent came from unexpected source (not a label)", e);
return;
}
if (eventsByLabel.containsKey(source)) {
currentEvent = eventsByLabel.get(source);
printToView();
} else {
logger.log(Level.WARNING, "SingularEvent came from unexpected source or label got removed");
return;
}
event.consume(); //Prevent the event from being propagated up through normal channels
//FX normally calls getCellData again if event.consume was not called, but in that case
//the event source is set to the VBox, not the label, so we were overwriting
//the stuff shown in the right pane. By manually calling getCellDate ourselves,
//the source is still the Label and we can handle better based on that
getCellData(event);
}
/**
* Toggles the button's status to show if the event has been marked completed (or not)
*/
@FXML
private void eventCompletionStatus() {
if (toggleCompleted.isSelected()) {
currentEvent.setCompleted(true);
toggleCompleted.setText("Mark\nUncompleted");
} else {
currentEvent.setCompleted(false);
toggleCompleted.setText("Mark\nCompleted");
}
printToView();
}
/**
* Handles printing text to the side view of a selected event.
*/
public void printToView() {
if (currentEvent == null) {
eventOutput.setText("");
eventOutput.setDisable(true);
viewMonth(currentMonth);
return;
}
StringBuilder temp = new StringBuilder();
temp.append("\nEvent Name: ").append("\n\t").append(currentEvent.getEventName()).append("\n");
ZonedDateTime st = currentEvent.getStart();
ZonedDateTime end = currentEvent.getEnd();
if (currentEvent.getEventLocation() != null) {
temp.append("\nLocation: ").append("\n\t").append(currentEvent.getEventLocation()).append("\n");
}
if (currentEvent.getEventAttendees() != null) {
temp.append("\nAttendees:").append("\n\t").append(currentEvent.getEventAttendees()).append("\n");
}
if (!currentEvent.getEventAllDay()) {
temp.append("\nStart time:").append("\n\t");
temp.append(st.toLocalDateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm\n")));
temp.append("\nEnd time:").append("\n\t");
temp.append(end.toLocalDateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm\n")));
} else {
temp.append("\nAll Day event\n\n");
temp.append("Start time:").append("\n\t");
temp.append(st.toLocalDateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd\n")));
temp.append("End time:").append("\n\t");
temp.append(end.toLocalDateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd\n")));
}
if (currentEvent.getHighPriority()) {
temp.append("\nEvent marked High Priority\n");
}
if (currentEvent.getEventDesc() != null) {
temp.append("\nDescription:").append("\n\t").append(currentEvent.getEventDesc()).append("\n");
}
if(!(currentEvent instanceof SingularEvent)) {
if (currentEvent.getFrequency().equals(Frequency.WEEKLY)) {
temp.append("\nRecurs Weekly");
} else if (currentEvent.getFrequency().equals(Frequency.MONTHLY)) {
temp.append("\nRecurs Monthly");
} else if (currentEvent.getFrequency().equals(Frequency.DAILY)) {
temp.append("\nRecurs Daily");
}
temp.append("\n").append("Recurrence ends on:\n\t");
temp.append(((EphemeralEvent) currentEvent).getParent().getRecurrenceEnd().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm\n")));
}
eventOutput.setText(temp.toString());
eventOutput.setDisable(false);
toggleCompleted.setDisable(false);
updateButton.setDisable(false);
removeButton.setDisable(false);
leftArrow.setDisable(false);
rightArrow.setDisable(false);
if (currentEvent.getCompleted()) {
toggleCompleted.setSelected(true);
toggleCompleted.setText("Mark\nUncompleted");
} else {
toggleCompleted.setSelected(false);
toggleCompleted.setText("Mark\nCompleted");
}
viewMonth(currentMonth);
}
/**
* Prints the current Year, month, and date to the right side panel of the calendar based on the date clicked.
* Clicking on unlabeled date prior to the month will cause the calendar to go back a month, and clicking ahead will
* move the calendar a month ahead.
*
* @param e SingularEvent on mouseclick
*/
@FXML
private void getCellData(MouseEvent e) {
/*
* If an event label is pressed the source is a Label,
* but GridPane.getIndex needs the VBox that is in the cell to get row and column numbers
*/
Node origSource = (Node) e.getSource();
Node source = (Node) e.getSource();
if (origSource instanceof Label) {
//An event label was pressed
source = origSource.getParent();
}
Integer columnVal = (GridPane.getColumnIndex(source) == null) ? 0 : (GridPane.getColumnIndex(source));
Integer rowVal = (GridPane.getRowIndex(source) == null) ? 0 : (GridPane.getRowIndex(source));
//Collects date that matches the 7x7 grid
Integer curdate = daylayout[rowVal][columnVal];
//prevents throwing an DateTimeException if the column value = 0 (sunday needs to be 7)
if (columnVal == 0) {
columnVal = 7;
}
char[] weekArray = DayOfWeek.of(columnVal).toString().toLowerCase().toCharArray();
weekArray[0] = Character.toUpperCase(weekArray[0]);
String dayWeek = new String(weekArray);
String[] dateSuffix = {"th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"};
int dateMod = curdate % 100;
String correctedDate = String.valueOf(curdate) + dateSuffix[(dateMod > 3 && dateMod < 21) ? 0 : (dateMod % 10)];
StringBuilder output = new StringBuilder();
output.append(dayWeek).append(", ").append(currentMonth.format(DateTimeFormatter.ofPattern("MMMM"))).append(" ").append(correctedDate);
dateLabel.setText(output.toString());
currentDate = LocalDate.of(currentMonth.getYear(), currentMonth.getMonth(), curdate);
Set<Event> dayEvents = getCurrentAccount().getCalendar().getDayEvents(currentDate);
if (dayEvents.isEmpty()) {
eventOutput.setDisable(true);
eventOutput.setText("");
toggleCompleted.setDisable(true);
toggleCompleted.setSelected(false);
updateButton.setDisable(true);
removeButton.setDisable(true);
leftArrow.setDisable(true);
rightArrow.setDisable(true);
} else {
//If an event label was pressed we shouldn't overwrite the event it already displayed
if (!(origSource instanceof Label)) {
//It doesn't matter what event we show
currentEvent = (dayEvents.iterator().next());
printToView();
}
}
}
/**
* Views the next event for that given day. Triggered by the right arrow below event details.
*/
@FXML
private void viewNextEvent() {
if (currentDate == null) return;
SortedSet<Event> dayEvents = getCurrentAccount().getCalendar().getDayEvents(currentDate);
if (dayEvents.isEmpty()) {
eventOutput.setDisable(true);
leftArrow.setDisable(true);
rightArrow.setDisable(true);
eventOutput.setText("");
return;
}
if (currentEvent == null || !dayEvents.contains(currentEvent)) {
currentEvent = dayEvents.first();
printToView();
return;
}
if (dayEvents.last() == currentEvent) {
currentEvent = dayEvents.first();
printToView();
} else {
Iterator<Event> it = dayEvents.tailSet(currentEvent).iterator();
it.next();
currentEvent = it.next(); //.tailSet() is inclusive, so need second in set
printToView();
}
}
/**
* Views the next event for that given day. Triggered by the left arrow below event details.
*/
@FXML
private void viewPreviousEvent() {
if (currentDate == null) return;
SortedSet<Event> dayEvents = getCurrentAccount().getCalendar().getDayEvents(currentDate);
if (dayEvents.isEmpty()) {
eventOutput.setDisable(true);
eventOutput.setText("");
return;
}
if (currentEvent == null || !dayEvents.contains(currentEvent)) {
currentEvent = dayEvents.first();
printToView();
return;
}
if (dayEvents.first() == currentEvent) {
currentEvent = dayEvents.last();
printToView();
} else {
currentEvent = dayEvents.headSet(currentEvent).last();
printToView();
}
}
/**
* Deletes the event from the GUI, and triggers the calendar to remove it from the TreeSet
*/
@FXML
private void deleteCurrentEvent() {
if (currentEvent != null) {
Alert alert = new Alert(Alert.AlertType.CONFIRMATION,
"Are you sure you want to delete " + currentEvent.getEventName() + "?",
ButtonType.YES,
ButtonType.NO,
ButtonType.CANCEL);
alert.showAndWait();
if (alert.getResult() == ButtonType.YES) {
Event eventToDelete = currentEvent;
viewNextEvent();
getCurrentAccount().getCalendar().removeEvent(eventToDelete);
Account.saveAccounts();
if (!getCurrentAccount().getCalendar().getDayEvents(currentDate).contains(currentEvent)) {
currentEvent = null;
}
printToView();
}
}
}
/**
* Opens the update event GUI page
*/
@FXML
private void openUpdatePage() {
if (currentEvent != null) {
Stage stage;
try {
stage = new Stage();
java.net.URL resource = getClass().getClassLoader().getResource("UpdateEventGUI.fxml");
if (resource == null) {
resource = getClass().getResource("UpdateEventGUI.fxml");
}
FXMLLoader fxmlLoader = new FXMLLoader(resource);
Parent root4 = fxmlLoader.load();
UpdateEventController updateEventController = fxmlLoader.getController();
updateEventController.mainGUI = this;
stage.setScene(new Scene(root4, 800, 650));
stage.setTitle("Update SingularEvent " + currentEvent.getEventName());
stage.initModality(Modality.APPLICATION_MODAL);
stage.initOwner(updateButton.getScene().getWindow());
stage.showAndWait();
} catch (Exception e) {
e.printStackTrace();
}
} else {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("This will not do.");
alert.setHeaderText("Try again, friend.");
alert.setContentText("You don't have an event selected");
}
}
@FXML
private void fetchCompleted() {
completedEventsArea.setText("");
Set<Event> completedEvents = getCurrentAccount().getCalendar().getCompletedEvents();
StringBuilder temp = new StringBuilder();
for (Event currEvent : completedEvents) {
temp.append(currEvent.getEventName()).append("\n");
}
DecimalFormat df = new DecimalFormat("#.##");
int numEvents = getCurrentAccount().getCalendar().getStartingSet().size();
temp.append("\n\nCompleted " + completedEvents.size() + "/" + numEvents);
temp.append(" (" + df.format((float) completedEvents.size() / numEvents * 100.0) + " %)");
completedEventsArea.setText(temp.toString());
}
@FXML
private void fetchAll() {
completedEventsArea.setText("");
SortedSet<RecurrentEvent> allEventsRec = getCurrentAccount().getCalendar().getRecurringEndingSet();
SortedSet<Event> allEvents = getCurrentAccount().getCalendar().getStartingSet();
StringBuilder temp = new StringBuilder();
for (Event currEvent : allEvents) {
temp.append(currEvent.getEventName()).append("\n");
}
for (RecurrentEvent currRecEvent : allEventsRec) {
temp.append(currRecEvent.getEventName()).append("\n");
}
completedEventsArea.setText(temp.toString());
}
@FXML
private void submitEvent() {
LocalDate startDate = startDateField.getValue();
LocalDate endDate = endDateField.getValue();
String startingTime = startTimeDropdown.getSelectionModel().getSelectedItem().toString();
String endingTime = endTimeDropdown.getSelectionModel().getSelectedItem().toString();
String[] splitStartHM = startingTime.split(":");
String[] splitEndHM = endingTime.split(":");
try {
ZonedDateTime start = ZonedDateTime.of(startDate.getYear(),
startDate.getMonthValue(),
startDate.getDayOfMonth(),
Integer.parseInt(splitStartHM[0]),
Integer.parseInt(splitStartHM[1]),
0,
0,
ZoneId.systemDefault());
ZonedDateTime end = ZonedDateTime.of(endDate.getYear(),
endDate.getMonthValue(),
endDate.getDayOfMonth(),
Integer.parseInt(splitEndHM[0]),
Integer.parseInt(splitEndHM[1]),
0,
0,
ZoneId.systemDefault());
int dateCompare = endDate.compareTo(startDate);
if (dateCompare < 0) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("This will not do.");
alert.setHeaderText("Try again, friend.");
alert.setContentText("Your end date cannot be before your start date!");
alert.showAndWait();
} else if (dateCompare == 0 && end.compareTo(start) < 0) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("This will not do.");
alert.setHeaderText("Try again, friend.");
alert.setContentText("Your end time cannot be before your start time unless you adjust your dates appropriately");
alert.showAndWait();
} else if (eventNameField.getText().equals("")) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("This will not do.");
alert.setHeaderText("Try again, friend.");
alert.setContentText("Your event name cannot be blank");
alert.showAndWait();
} else {
SingularEvent event;
Frequency freq = (Frequency) recurField.getSelectionModel().getSelectedItem();
switch (freq) {
case NEVER:
event = new SingularEvent(start, end, eventNameField.getText(), freq);
break;
default:
LocalDate d = recurrenceEndDate.getValue();
ZonedDateTime recurEnd = ZonedDateTime.of(d, end.toLocalTime(), end.getZone());
event = new RecurrentEvent(start, end, eventNameField.getText(), freq, start, recurEnd); //Todo fix end
}
event.setEventAllDay(allDay.isSelected());
if (allDay.isSelected()) {
ZonedDateTime min = ZonedDateTime.of(startDate.getYear(),
startDate.getMonthValue(),
startDate.getDayOfMonth(),
LocalTime.MIN.getHour(),
LocalTime.MIN.getMinute(),
0,
0,
ZoneId.systemDefault());
ZonedDateTime max = ZonedDateTime.of(startDate.getYear(),
startDate.getMonthValue(),
startDate.getDayOfMonth(),
LocalTime.MAX.getHour(),
LocalTime.MAX.getMinute(),
0,
0,
ZoneId.systemDefault());
event.setStart(min);
event.setEnd(max);
}
event.setEventDesc(eventDescriptionField.getText());
event.setEventLocation(eventLocationField.getText());
event.setEventAttendees(eventAttendeesField.getText());
event.setHighPriority(highPrior.isSelected());
getCurrentAccount().getCalendar().addEvent(event);
Account.saveAccounts();
viewMonth(currentMonth);
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("Success");
alert.setHeaderText("Event Created");
alert.setContentText("Your event has been added to the calendar");
alert.showAndWait();
SingleSelectionModel<Tab> selector = tabPane.getSelectionModel();
clearEvent();
selector.selectFirst();
}
} catch (Exception e) { //Unable to parse start/end times
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Error");
alert.setHeaderText("Unable to Parse Start/End Times");
alert.setContentText("Please ensure that your times are valid.");
alert.showAndWait();
}
}
private void clearEvent() {
eventNameField.setText("");
eventDescriptionField.setText("");
eventLocationField.setText("");
eventAttendeesField.setText("");
highPrior.setSelected(false);
allDay.setSelected(false);
startDateField.setValue(LocalDate.now());
endDateField.setValue(LocalDate.now());
startTimeDropdown.getSelectionModel().selectFirst();
endTimeDropdown.getSelectionModel().selectFirst();
recurField.getSelectionModel().selectFirst();
recurrenceEndDate.setValue(LocalDate.now());
}
@FXML
private void adjustEndDate() {
LocalDate startDate = startDateField.getValue();
long days = DAYS.between(oldDateValue, startDate);
endDateField.setValue(endDateField.getValue().plusDays(days));
oldDateValue = startDate;
}
@FXML
private void validateEndDate() {
LocalDate startDate = startDateField.getValue();
LocalDate endDate = endDateField.getValue();
if (startDate.isAfter(endDate)) {
endDateField.setValue(startDate);
GUIHelper.alert("Validation",
"Whoops...",
"You chose an end date that is earlier than the selected start date. Time travel is strictly prohibited in this universe.",
Alert.AlertType.INFORMATION);
}
}
@FXML
private void validateRecurrenceEndDate() {
LocalDate RDate = recurrenceEndDate.getValue();
LocalDate endDate = endDateField.getValue();
if (endDate.isAfter(RDate)) {
recurrenceEndDate.setValue(endDate);
GUIHelper.alert("Validation",
"Whoops...",
"You chose to end recurrence before the end of the event. You'll never get anything done if you don't try.",
Alert.AlertType.INFORMATION);
}
}
public Account getCurrentAccount() {
return currentAccount;
}
public void setCurrentAccount(Account currentAccount) {
this.currentAccount = currentAccount;
}
public Event getCurrentEvent() {
return currentEvent;
}
public void setCurrentEvent(Event event) {
currentEvent = event;
}
public ZonedDateTime getCurrentMonth() {
return currentMonth;
}
}
|
package com.zengjx.test;
import com.zengjx.dao.UserDao;
import com.zengjx.domain.User;
import com.zengjx.mybatis.SqlSession;
import com.zengjx.mybatis.SqlSessionFactory;
import com.zengjx.mybatis.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.InputStream;
import java.util.List;
/**
* @ClassName HelloController
* @Description TODO
* @Author zengjx
* @Company zengjx
* @Date 2020/2/18 17:36
* @Version V1.0
*/
public class MybatisTest {
@Test
public void test(){
InputStream is= this.getClass().getClassLoader().getResourceAsStream("SqlMapConfig.xml");
//创建SqlsessionFacotry
SqlSessionFactory sqlSessionFactory = SqlSessionFactoryBuilder.builder(is);
SqlSession sqlSession = sqlSessionFactory.openSession();
//3. 使用SqlSession获取映射器 实现类对象(代理模式,是一个代理对象) Proxy.newProxyInstance(类加载器,接口字节码数组, 代理对象的行为)
UserDao userDao = sqlSession.getMapper(UserDao.class);
//让代理对象去操作数据库,需要的信息,都在Configuration对象里:写代理对象的行为,操作数据库(调用Executor.selectList方法)
List<User> userList = (List<User>) userDao.queryAll();
System.out.println(userList);
sqlSession.close();
}
}
|
package com.tencent.mm.compatible.loader;
import android.os.Process;
import com.tencent.mm.sdk.platformtools.ad;
import com.tencent.mm.sdk.platformtools.bd;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
class f$1 extends bd<String> {
final /* synthetic */ f dfO;
public f$1(f fVar) {
this.dfO = fVar;
super(2000, null, (byte) 0);
}
private static String zS() {
while (true) {
String an = bi.an(ad.getContext(), Process.myPid());
if (an != null) {
return an;
}
try {
Thread.sleep(100);
} catch (Throwable e) {
x.printErrStackTrace("MicroMsg.ProfileFactoryImpl", e, "", new Object[0]);
}
}
}
}
|
package com.dungeonsandoodragons;
/**
* Bugbear.java
*
* A Bugbear is intended to be a "medium-strength" monster.
*/
class Bugbear extends NonPlayerCharacter {
private final int GOLD_MULTIPLIER = 200;
private final int HEALTH_MULTIPLIER = 15;
public Bugbear() {
name = "Bugbear";
this.myWeapon = new Weapon("Really Big Fly Swatter", 8);
this.myArmor = new Armor("Hefty Garbage Bag, with Holes Cut Out for Arms", 4);
health = (int) ((Math.random() * HEALTH_MULTIPLIER) + 10);
gold = (int) ((Math.random() * GOLD_MULTIPLIER) + 20);
}
}
|
package Task3;
import lombok.SneakyThrows;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class RegularTest {
@Test
@SneakyThrows
void getImgReferences() {
System.out.println(Regular.getImgReferences());
}
@Test
@SneakyThrows
void checkImgRefOrder() {
assertFalse(Regular.checkImgRefOrder());
}
}
|
package rent.common.projection;
import org.springframework.data.rest.core.config.Projection;
import rent.common.entity.AccountEntity;
import java.time.LocalDate;
import java.util.List;
@Projection(types = {AccountEntity.class})
public interface AccountBasic extends AbstractBasic {
String getAccountNumber();
LocalDate getDateOpen();
LocalDate getDateClose();
ContractorBasic getContractor();
ApartmentBasic getApartment();
List<AccountParameterBasic> getParameters();
List<AccountServiceBasic> getServices();
List<AccountOwnerBasic> getOwners();
List<AccountRegisteredBasic> getRegistered();
List<AccountMeterBasic> getMeters();
}
|
package com.yash.pms.daoimpl;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.yash.pms.dao.ProductDAO;
import com.yash.pms.model.Product;
import com.yash.pms.util.JDBCUtil;
public class ProductDAOImpl extends JDBCUtil implements ProductDAO {
@Override
public void save(Product product) {
try {
String sql="insert into products (name,price) values(?,?)";
PreparedStatement preparedStatement=JDBCUtil.prepareStatement(sql);
preparedStatement.setString(1, product.getName());
preparedStatement.setInt(2, Integer.parseInt(product.getPrice()));
int i=preparedStatement.executeUpdate();
if(i!=0) {
System.out.println("Product is inserted");
}else {
System.out.println("Product is not inserted");
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
@Override
public List<Product> findAll() {
List<Product> list=new ArrayList<Product>();
try {
String sql="select * from products";
PreparedStatement preparedStatement=JDBCUtil.prepareStatement(sql);
ResultSet rs=preparedStatement.executeQuery();
while(rs.next()){
list.add(new Product(rs.getInt(1),rs.getString(2),Integer.toString(rs.getInt(3))));
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
return list;
}
@Override
public void update(Product product) {
try {
String sql="update products set name=(?),price=(?) where id=(?)";
PreparedStatement preparedStatement=JDBCUtil.prepareStatement(sql);
preparedStatement.setString(1, product.getName());
preparedStatement.setInt(2, Integer.parseInt(product.getPrice()));
preparedStatement.setInt(3, product.getId());
int i=preparedStatement.executeUpdate();
if(i!=0) {
System.out.println("Product is updated");
}else {
System.out.println("Product is not updated");
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
@Override
public void delete(int id) {
try {
String sql="delete from products where id =(?)";
PreparedStatement preparedStatement=JDBCUtil.prepareStatement(sql);
preparedStatement.setInt(1,id);
preparedStatement.executeUpdate();
System.out.println("product deleted.");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
@Override
public Product findProductsById(Long id) {
Product product=new Product();
try {
String sql="select * from products where id =(?)";
PreparedStatement preparedStatement=JDBCUtil.prepareStatement(sql);
preparedStatement.setLong(1,id);
ResultSet rs=preparedStatement.executeQuery();
while(rs.next()){
product=new Product(rs.getInt(1),rs.getString(2),Integer.toString(rs.getInt(3)));
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
return product;
}
}
|
package controller.commands;
import controller.commands.impl.*;
import controller.commands.impl.api.*;
import java.util.HashMap;
import java.util.Map;
/**
* Created by vlad on 20.04.17.
*/
public class CommandFactory {
private final String GET_PATH="GET:";
private final String POST_PATH="POST:";
private final Command INVALID_URL_COMMAND;
private Map<String,Command> commands;
private CommandFactory(){
INVALID_URL_COMMAND =new GoInvalidUrlCommand();
init();
}
private static class InstanceHolder{
static CommandFactory commandFactory=new CommandFactory();
}
public static CommandFactory getInstance(){
return InstanceHolder.commandFactory;
}
private void init(){
commands=new HashMap<>();
/*COMMON COMMANDS*/
commands.put(GET_PATH + "/wav",new GoHomeCommand());
commands.put(GET_PATH + "/wav/handle",new GoHandlingCommand());
commands.put(GET_PATH + "/wav/download",new GoDownloadCommand());
commands.put(GET_PATH + "/wav/about",new GoAboutCommand());
commands.put(POST_PATH + "/api/upload",new UploadFileCommand());
commands.put(POST_PATH + "/api/download",new DownloadFileCommand());
commands.put(POST_PATH + "/api/filter",new FilterFileCommand());
}
public Command getCommand(String url) {
if(url.startsWith(GET_PATH + "/static"))
return new GetStaticFileCommand();
return commands.getOrDefault(url,INVALID_URL_COMMAND);
}
}
|
/**
*
*/
package com.cnk.travelogix.common.facades.product.impl;
import de.hybris.platform.core.Registry;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.collections.CollectionUtils;
import com.cnk.travelogix.common.facades.product.data.CnkFacetData;
import com.cnk.travelogix.common.facades.product.data.CnkFacetDataList;
import com.cnk.travelogix.common.facades.product.data.CnkProductSearchPageData;
import com.cnk.travelogix.common.facades.product.data.flight.FlightData;
import com.cnk.travelogix.common.facades.product.data.flight.FlightResultData;
import com.cnk.travelogix.common.facades.product.provider.CnkFacetValueProvider;
/**
* @author i323616
*
*/
public class MulticityIntlFlightFacetCnkProductSearchFacade extends FacetCnkProductSearchFacade<FlightData>
{
/*
* (non-Javadoc)
*
* @see
* com.cnk.travelogix.common.facades.product.impl.FacetCnkProductSearchFacade#HandleFacet(com.cnk.travelogix.common.
* facades.product.data.CnkProductSearchPageData, java.util.List)
*/
@Override
protected void HandleFacet(final CnkProductSearchPageData result, final List<CnkFacetDataList> facetList)
{
final List<FlightResultData> resultList = result.getResult();
final List<FlightResultData> bestPriceList = result.getBestPriceRecommend();
if (0 == facetList.size())
{
final CnkFacetDataList facet = new CnkFacetDataList();
facet.setFacets(buildFacetSkeleton());
facetList.add(facet);
}
final List<CnkFacetData> facets = facetList.get(0).getFacets();
final List<FlightResultData> flightGroupList = new ArrayList<FlightResultData>();
for (final FlightResultData singleData : resultList)
{
if (getCnkProductFacetHandler().handleFacet(singleData, facets, getFacetToModelMapper()))
{
flightGroupList.add(singleData);
}
}
result.setResult(flightGroupList);
// final FlightResultData bestPrice = bestPriceList.get(0);
// bestPriceList.clear();
// bestPriceList.add(bestPrice);
bestPriceList.get(0).getListOfFlights().clear();
if (!resultList.isEmpty())
{
bestPriceList.get(0).setListOfFlights(resultList.get(0).getListOfFlights());
}
setStartAtAndTotal(result);
result.setFacets(facetList);
}
@Override
protected void preHandleFacet(final List<CnkFacetDataList> facetList)
{
super.preHandleFacet(facetList);
if (CollectionUtils.isEmpty(facetList))
{
return;
}
final List<CnkFacetData> facetSkeleton = buildFacetSkeleton();
for (final CnkFacetDataList theFacetDataList : facetList)
{
if (theFacetDataList == null)
{
continue;
}
for (int i = 0; i < theFacetDataList.getFacets().size(); i++)
{
final CnkFacetData facet = theFacetDataList.getFacets().get(i);
final CnkFacetData facetSKData = facetSkeleton.get(i);
if (!facet.getCode().equals(facetSKData.getCode()))
{
facet.setCode(facetSKData.getCode());
facet.setName(facetSKData.getName());
facet.setValues(null);
}
}
}
}
// @Override
// protected void postHandleFacet(final CnkProductSearchPageData result, final List<CnkFacetDataList> facetList)
// {
// final List<CnkFacetData> skeletonFacets = buildFacetSkeleton();
// for (int i = 0; i < skeletonFacets.size(); i++)
// {
// final CnkFacetData facet = skeletonFacets.get(i);
// for (final CnkFacetData calculatedFacet : facetList.get(0).getFacets())
// {
// if (calculatedFacet.getCode().equals(facet.getCode()))
// {
// skeletonFacets.set(i, calculatedFacet);
// }
// }
// }
//
// facetList.get(0).setFacets(skeletonFacets);
// super.postHandleFacet(result, facetList);
// }
private void setStartAtAndTotal(final CnkProductSearchPageData<FlightResultData> result)
{
if (result.getBestPriceRecommend().size() > 0)
{
result.setStartAtPrice(this.getBestPrice(result.getBestPriceRecommend().get(0)));
}
if (result.getResult().size() > 0)
{
int totalSize = 0;
for (final FlightResultData flightResult : result.getResult())
{
totalSize += flightResult.getListOfFlights().size();
}
result.setTotalSize(totalSize);
}
}
private double getBestPrice(final FlightResultData flightResultData)
{
final CnkFacetValueProvider<FlightData> flightPriceValueProvider = (CnkFacetValueProvider) Registry.getApplicationContext()
.getBean("flightPriceValueProvider"); //TODO: not good
double bestPrice = Double.MAX_VALUE;
for (final FlightData flight : flightResultData.getListOfFlights())
{
final double flightPrice = Double.parseDouble(flightPriceValueProvider.getFacetValue(flight, "price").toString());
if (bestPrice > flightPrice)
{
bestPrice = flightPrice;
}
}
return bestPrice;
}
}
|
package animatronics.utils.helper;
import java.util.Iterator;
import java.util.List;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.CraftingManager;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.item.crafting.ShapedRecipes;
import com.google.common.collect.Lists;
import animatronics.Animatronics;
import animatronics.utils.inventory.container.ContainerBase;
import animatronics.utils.misc.ItemUtils;
public class RecipeRemover{
public static void removeRecipe(ItemStack toRemove){
Iterator<IRecipe> iterator = CraftingManager.getInstance().getRecipeList().iterator();
while(iterator.hasNext()){
IRecipe recipe = iterator.next();
if(recipe == null){
continue;
}
ItemStack output = recipe.getRecipeOutput();
if(output != null && ItemStack.areItemStacksEqual(output, toRemove)){
iterator.remove();
}
}
}
public static void removeRecipe(Object... components){
Iterator<IRecipe> iterator = CraftingManager.getInstance().getRecipeList().iterator();
while(iterator.hasNext()){
IRecipe recipe = iterator.next();
InventoryCrafting dummyInventory = new InventoryCrafting(new ContainerBase(), 3, 3);
for(int i = 0; i < components.length; i++){
dummyInventory.setInventorySlotContents(i, ItemUtils.getItemStack(components[i]));
}
if(recipe.matches(dummyInventory, null)){
iterator.remove();
Animatronics.logger.info("Remove recipe for " + recipe.getRecipeOutput().getDisplayName() + ".");
}
}
}
}
|
package chapter13.Exercise13_19;
import java.math.BigInteger;
import java.util.Scanner;
public class TestExercise13_19 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a decimal number: ");
String number = input.next();
boolean positive = number.charAt(0) != '-';
if (!positive) {
number = number.replace("-", "");
}
int fraction = number.length() - (number.indexOf(".") + 1);
number = number.replace(".", "");
Rational r = new Rational(new BigInteger(number), new BigInteger((long) Math.pow(10, fraction) + ""));
System.out.println("The fraction number is " + r);
input.close();
}
}
|
package graphics;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.Group;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.image.Image;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.animation.AnimationTimer;
import javafx.event.EventHandler;
import javafx.scene.input.KeyEvent;
import java.util.ArrayList;
import java.util.Iterator;
import items.*;
import engine.*;
import main.*;
public class Inventory_Screen extends Application {
public static void open() {
System.setProperty("prism.lcdtext", "false");
String[] args = {};
launch(args);
}
public void start(Stage stage) throws Exception {
stage.setTitle("Inventory Screen");
Group root = new Group();
Scene scene = new Scene(root);
stage.setScene(scene);
Canvas canvas = new Canvas(600, 400);
root.getChildren().add(canvas);
Inventory test_inventory = new Inventory(30);
test_inventory.addItem("Cherry", 100);
test_inventory.addItem("Apple", 100);
test_inventory.addItem("Wheat", 100);
test_inventory.addItem("Cherry", 100);
test_inventory.addItem("Apple", 100);
test_inventory.addItem("Wheat", 100);
test_inventory.addItem("Cherry", 100);
test_inventory.addItem("Apple", 100);
test_inventory.addItem("Wheat", 100);
GraphicsContext gc = canvas.getGraphicsContext2D();
ArrayList<Sprite> items = new ArrayList<Sprite>();
ArrayList<Text_Sprite> stack_sizes = new ArrayList<Text_Sprite>();
Font theFont = Font.font( "Helvetica", FontWeight.THIN, 100 );
gc.setFont( theFont );
gc.setStroke( Color.rgb(255, 50, 100));
gc.setLineWidth(1);
for (int i = 0; i < test_inventory.size(); i++)
{
Sprite item = new Sprite();
Text_Sprite text = new Text_Sprite();
item.setImage(test_inventory.getIcon(i));
int row_position = i%10;
double px = 50 + row_position*50;
double py = 50 + i/10 * 50;
String stack_size = "" + test_inventory.getStackSize(i);
text.setText(stack_size);
text.setPosition(px+40, py+40);
item.setPosition(px,py);
stack_sizes.add(text);
items.add(item);
}
System.out.println(javafx.scene.text.Font.getFamilies());
new AnimationTimer() {
public void handle(long currentNanoTime) {
for (Sprite item : items )
item.render( gc );
for (Text_Sprite stack_size : stack_sizes )
stack_size.render( gc );
}
}.start();
stage.show();
}
}
|
package com.winterchen.lambda;
import com.winterchen.lambda.interfaces.SayHello;
import com.winterchen.lambda.model.User;
/**
* @author CENTURY
* @version 1.0
* @date 2021/9/22 10:35
**/
public class LambdaDemo02 {
public static void main(String[] args) {
User user = new User();
user.setUsername("winter chen");
String say = user.say((username) -> "hello " + username);
System.out.println("say = " + say);
}
}
|
package com.dzz.gateway.routers;
import com.dzz.gateway.config.CommonProperties;
import com.dzz.gateway.filter.TimingFilter;
import com.dzz.gateway.limiter.RateLimitByIpGatewayFilter;
import java.time.Duration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.web.bind.annotation.RestController;
/**
* 路由处理
*
* @author dzz
* @version 1.0.0
* @since 2019年07月11 18:12
*/
@RestController
public class Router {
@Autowired
private ReactiveRedisTemplate<String,String> redisTemplate;
@Autowired
private CommonProperties commonProperties;
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
//policy_service_route
.route("policy_service_route", r -> r.path("/api/hello/**")
.filters(f -> f.hystrix(
config -> config.setName("mycmd").setFallbackUri("forward:/fallback")))
// .filters(f -> f.requestRateLimiter()
// .configure(c -> c.setRateLimiter(getRedisRateLimiter())))
.uri("lb://POLICY-SERVICE")
.filter(new TimingFilter())
.filters(new RateLimitByIpGatewayFilter(10, 1, Duration.ofSeconds(1)))
.order(1)
.id("policy-service-router"))
//权限服务
.route("authority_service_route", r -> r.path("/oauth/**")
.filters(f -> f.hystrix(
config -> config.setName("mycmd2").setFallbackUri("forward:/authorityFallback")))
// .filters(f -> f.requestRateLimiter()
// .configure(c -> c.setRateLimiter(getRedisRateLimiter())))
.uri(commonProperties.getAuthorityUrl())
.filter(new TimingFilter())
.filters(new RateLimitByIpGatewayFilter(10, 1, Duration.ofSeconds(1)))
.order(2)
.id("authority-router"))
.build();
}
@Bean
public RateLimitByIpGatewayFilter hostAddrKeyResolver() {
return new RateLimitByIpGatewayFilter();
}
@Bean
public RedisRateLimiter getRedisRateLimiter() {
return new RedisRateLimiter(100,2);
}
}
|
package fr.pederobien.uhc.commands.configuration.edit.editions.bawn;
import fr.pederobien.uhc.commands.configuration.edit.editions.AbstractMapEdition;
import fr.pederobien.uhc.interfaces.IBawn;
import fr.pederobien.uhc.interfaces.IMessageCode;
public abstract class AbstractBawnEdition<T extends IBawn> extends AbstractMapEdition<T> {
public AbstractBawnEdition(String label, IMessageCode explanation) {
super(label, explanation);
}
}
|
package com.example.accounting_app.listener;
import android.app.Dialog;
import android.content.Intent;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import com.example.accounting_app.R;
import com.example.accounting_app.activity.activity_home_about;
import com.example.accounting_app.activity.activity_home_login;
import com.example.accounting_app.activity.activity_house_rate;
import com.example.accounting_app.activity.activity_home_register;
import com.example.accounting_app.fragment.fragment_home;
import com.yatoooon.screenadaptation.ScreenAdapterTools;
/**
* @Creator cetwag yuebanquan
* @Version V2.0.0
* @Time 2019.6.28
* @Description 首页fragment的监听类
*/
public class listener_fragment_home implements View.OnClickListener {
fragment_home frag_h;//声明对应类的对象,通过构造函数传参传入赋值,否则无法获取对应的控件
/**
* @parameter
* @description 编写两个有参和无参构造函数,用于获取对应类的控件
* @Time 2019/6/28 9:02
*/
public listener_fragment_home() {
}
public listener_fragment_home(fragment_home fh) {
frag_h = fh;
}
/**
* @parameter
* @description 首页碎片的侧滑菜单的动态控件点击显示事件
* @Time 2019/6/28 9:12
*/
public void listener_hf() {
frag_h.btn_slide.setOnClickListener(this);
frag_h.btn_login.setOnClickListener(this);
frag_h.btn_register.setOnClickListener(this);
}
/**
* @parameter
* @description 实现View.onClickListener接口, 可以采用switch case简化setOnClickListener
* @Time 2019/6/28 13:10
*/
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_slide:
//openDrawer()函数用来打开侧滑菜单,Gravity.START表示布局文件里设置的滑出方向
frag_h.drawerlayout.openDrawer(Gravity.START);
break;
case R.id.my_create_btn_login:
Intent intent_login = new Intent(frag_h.getContext(), activity_home_login.class);
frag_h.startActivity(intent_login);
//startActivityForResult(intent,TOLOG);
break;
case R.id.my_create_btn_register:
Intent intent_register = new Intent(frag_h.getContext(), activity_home_register.class);
frag_h.startActivity(intent_register);
break;
}
}
/**
* @parameter
* @description 首页碎片的侧滑菜单的列表控件点击显示事件
* @Time 2019/6/28 14:47
*/
public void listener_hf_lv_item() {
//对listview里的item设置监听事件
frag_h.lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch ((int) id) {
case 3://汇率计算器弹窗编写
DisplayMetrics dm=new DisplayMetrics();
frag_h.getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
int width =dm.widthPixels;//获取屏幕宽度
int height = dm.heightPixels;//获取屏幕高度
Dialog dialog = new Dialog(frag_h.getContext());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
LayoutInflater inflater = LayoutInflater.from(frag_h.getContext());
View v = inflater.inflate(R.layout.dialog_exchange_rate, null);//弹窗视图在这里
ScreenAdapterTools.getInstance().loadView(v);
dialog.setContentView(v);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
Window window = dialog.getWindow();
lp.copyFrom(window.getAttributes());
lp.width = width;
lp.height = height/2;
lp.gravity = Gravity.CENTER;
dialog.show();
window.setAttributes(lp);
break;
case 4://跳转到房贷计算器
Intent intent_house_calculation= new Intent(frag_h.getContext(), activity_house_rate.class);
frag_h.startActivity(intent_house_calculation);
break;
case 6:
Intent intent_about = new Intent(frag_h.getContext(), activity_home_about.class);
frag_h.startActivity(intent_about);
break;
}
}
});
}
}
|
package com.dreamcatcher.admin.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 com.dreamcatcher.factory.AdminActionFactory;
import com.dreamcatcher.factory.MemberActionFactory;
import com.dreamcatcher.util.CharacterConstant;
import com.dreamcatcher.util.PageMove;
@WebServlet("/admin")
public class AdminController extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
execute(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding(CharacterConstant.DEFAULT_CHAR);
execute(request, response);
}
private void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String root = request.getContextPath();
String act = request.getParameter("act");
String path = "/main";
System.out.println("action = " + act);
if("sendPassword".equals(act)){
AdminActionFactory.getAdminSendPasswordAction().execute(request, response);
} else if("sendAuthCode".equals(act)) {
AdminActionFactory.getAdminSendAuthCodeAction().execute(request, response);
} else if("memberJoinConfirm".equals(act)) {
AdminActionFactory.getAdminMemberJoinConfirmAction().execute(request, response);
//PageMove.forward(request, response, path + "?" + queryString);
} else if("moveStatistics".equals(act)) {
PageMove.redirect(response, root + "/admin/statistics.tiles");
} else if("statistics".equals(act)) {
AdminActionFactory.getAdminStatisticsAction().execute(request, response);
} else if("locationRank".equals(act)) {
AdminActionFactory.getAdminLocationRankAction().execute(request, response);
} else if("siteRank".equals(act)) {
AdminActionFactory.getAdminSiteRankAction().execute(request, response);
} else if("routeRank".equals(act)) {
AdminActionFactory.getAdminSiteRankByRouteAction().execute(request, response);
} else {
PageMove.redirect(response, root + path);
}
}
}
|
package net.sourceforge.vrapper.utils;
import java.math.BigInteger;
import java.util.Comparator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.sourceforge.vrapper.platform.SimpleConfiguration;
/**
* Numeric comparator for the sort command.
* @author Brian Detweiler
*/
public class NumericStringComparator implements Comparator<String>{
private boolean binary = false;
private boolean octal = false;
private boolean hex = false;
private boolean usePattern = false;
private boolean usePatternR = false;
private String pattern = null;
public NumericStringComparator(boolean binary, boolean octal, boolean hex, String pattern, boolean patternR) throws Exception {
super();
//numeric is assumed, no need for a flag
this.binary = binary;
this.octal = octal;
this.hex = hex;
if(pattern != null) {
this.pattern = pattern;
usePattern = true;
usePatternR = patternR;
}
}
/**
* Gets the first number in the string with respect to the base.
* In decimal mode, it handles negative numbers.
*
* NOTE: Special note on Java Regular Expressions - I had a hell
* of a time with this because I had never worked this deeply
* with Java regex's before. Look up Reluctant quantifiers vs.
* Possessive quantifiers before you start bashing your head against
* the wall. Also note that the . character means "any" character
* EXCEPT the new line.
*
* @param str
* @return
*/
private double getFirstNumber(String str) {
SimpleConfiguration config = new SimpleConfiguration();
String newLine = config.getNewLine();
try {
if(binary) {
Pattern number = Pattern.compile(".*?((0|1)+)(.|" + newLine + ")*");
Matcher m = number.matcher(str);
if(m.matches())
return Double.parseDouble(m.group(1));
throw new Exception("No binary string found.");
} else if(octal) {
Pattern number = Pattern.compile(".*?(([0-7])+)(.|" + newLine + ")*");
Matcher m = number.matcher(str);
if(m.matches())
return Double.parseDouble("0" + m.group(1));
throw new Exception("No octal string found.");
}
else if(hex) {
Pattern number = Pattern.compile(".*?(([A-Fa-f0-9])+)(.|" + newLine + ")*");
Matcher m = number.matcher(str);
if(m.matches())
return new BigInteger(m.group(1), 16).doubleValue();
throw new Exception("No hex string found.");
} else { //assume numeric ('n')
// Checks for both negative and non-negative numbers
Pattern number = Pattern.compile(".*?([-]?[0-9]+)(.|" + newLine + ")*");
Matcher m = number.matcher(str);
if(m.matches())
return Double.parseDouble(m.group(1));
throw new Exception("No numeric string found.");
}
} catch(Exception e) {
return 0;
}
}
/**
* Numbers can come in a variety of formats.
* Since we just want to know which is bigger (if it parses at all),
* BigDecimal should suffice for just about any number.
*
* TODO: It would be handy if we could parse numbers bigger than a double.
* This would require a separate method that takes a string and returns
* a BigDecimal. Note that Vim does not do this, it just won't sort
* anything bigger than a double. I think we could do better!
*/
public int compare(String str1, String str2) {
if(usePattern) {
str1 = str1.substring(usePatternR ? str1.indexOf(pattern) : str1.indexOf(pattern) + pattern.length());
str2 = str2.substring(usePatternR ? str2.indexOf(pattern) : str2.indexOf(pattern) + pattern.length());
}
double dub1 = getFirstNumber(str1);
double dub2 = getFirstNumber(str2);
if(dub1 > dub2)
return 1;
else if(dub1 < dub2)
return -1;
return 0;
}
}
|
package com.cse308.sbuify.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.crypto.bcrypt.BCryptPasswordEncoder;
import static com.cse308.sbuify.security.SecurityConstants.*;
/**
* Spring Security configuration.
*/
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurity extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsServiceImpl userDetailsService;
@Autowired
private BCryptPasswordEncoder passwordEncoder;
/**
* Customize the default web security configuration.
*
* Only a basic security policy is enforced at the web-application level. In general, method
* security should be used to control access.
*
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
// TODO: configure CSRF/CORS
http
.csrf()
.disable()
.authorizeRequests()
// sign up, login, reset pass, and change pass are publicly accessible
.antMatchers(HttpMethod.POST, SIGN_UP_URL).permitAll()
.antMatchers(HttpMethod.POST, LOGIN_URL).permitAll()
.antMatchers(HttpMethod.POST, RESET_URL).permitAll()
.antMatchers(HttpMethod.POST, CHANGE_PASS_URL).permitAll()
// static images are publicly accessible
.antMatchers(HttpMethod.GET, IMAGE_PATTERN).permitAll()
// the stream endpoint is publicly accessible (access controls in stream method)
.antMatchers(HttpMethod.GET, STREAM_PATTERN).permitAll()
// admin endpoints are only accessible to admins
.antMatchers(ADMIN_PATTERN).hasRole("ADMIN")
// customer endpoints are only accessible to customers
.antMatchers(CUSTOMER_PATTERN).hasAnyRole("CUSTOMER", "ADMIN")
// cron endpoints are only accessible by localhost
.antMatchers(CRON_PATTERN).hasIpAddress("localhost")
// by default, endpoints are only accessible to authenticated users
.anyRequest().authenticated()
.and()
.addFilter(new JWTAuthenticationFilter(authenticationManager()))
.addFilter(new JWTAuthorizationFilter(authenticationManager(), userDetailsService))
.sessionManagement()
// disable session creation
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
/**
* Configure the UserDetailsService implementation and password encoder used by the AuthenticationManager.
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
}
}
|
package com.rekoe.msg;
import com.rekoe.model.gameobjects.client.Client;
/**
* @author 科技㊣²º¹³
* Feb 16, 2013 2:35:33 PM
* http://www.rekoe.com
* QQ:5382211
*/
public abstract class AbstractMessage extends BaseIoMessage<Client>{
protected Client player;
private String charId;
public String getCharId() {
return charId;
}
public void setCharId(String charId) {
this.charId = charId;
}
@Override
public Client getSender() {
return player;
}
@Override
public void setSender(Client p) {
player = p;
}
}
|
package tweakedindentical;
public class Solution2 {
public boolean tweakedsame(TreeNode a, TreeNode b){
if(a == null && b == null){
return true;
}
if(a == null || b == null){
return false;
}
else if(a.key != b.key){
return false;
}
return (tweakedsame(a.left, b.right) && tweakedsame(a.right, b.left)) || (tweakedsame(a.right, b.right) && tweakedsame(a.left, b.left));
}
}
|
/*
* Minesweeper Project
* by Group3 : Arnaud BABOL, Guillaume SIMMONEAU
*/
package Controler;
import Controler.Exceptions.AlreadyInstanciedApplet;
import Controler.Listeners.ConsoleListener;
import Model.Events.RefreshEvent;
import Model.Events.ResizeEvent;
import Model.Game.WorldModel;
import Model.Game.WorldModelImpl;
import Model.Options.GameDifficulty;
import Model.Options.OptionModel;
import Model.Options.OptionModelImpl;
import Model.Scores.ScoresModel;
import View.GraphicalViews.Game.GameFrame;
import View.GraphicalViews.Game.GraphicalGameView;
import View.GraphicalViews.Options.GraphicalOptionView;
import View.GraphicalViews.Scores.GraphicalLogscoreView;
import View.GraphicalViews.Scores.ScorePanel;
import View.TextViews.OptionTextView;
import View.TextViews.WorldTextView;
import View.View;
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JApplet;
/**
*
* @author simonneau
*/
public class Minesweeper extends JApplet {
/**
*
* @param args
*/
public static void main(String args[]) {
Minesweeper.standAlone = true;
Minesweeper ms = Minesweeper.getInstance();
ms.init();
}
private Rules rules = null;
private boolean resumeGame = true;
private boolean resumeSetOption = false;
private OptionModel optionPanel = null;
private ScoresModel scores = null;
private static boolean standAlone = false;
private static Minesweeper instance;
private GameFrame standAloneFrame;
public static Minesweeper getInstance() {
if (instance == null) {
instance = new Minesweeper();
}
return instance;
}
@Override
public void init() {
super.init();
this.initGame();
this.setVisible(true);
while (true) {
this.play();
this.setOptions();
}
}
public boolean standAlone() {
return Minesweeper.standAlone;
}
public GameFrame getStandAloneFrame() {
return this.standAloneFrame;
}
/**
*
* @return
*/
public OptionModel getOptionPanel() {
return this.optionPanel;
}
private void initGame() {
this.optionPanel = new OptionModelImpl();
this.scores = new ScoresModel();
WorldModel wm = this.createWorldModel();
int width = this.optionPanel.getWidth();
int height = this.optionPanel.getHeight();
this.setSize(new Dimension(width * 55, height * 55));
OptionTextView optionTextv = new OptionTextView();
optionTextv.addListener(ConsoleListener.getInstance());
View wTextv = new WorldTextView(width * height);
wTextv.addListener(ConsoleListener.getInstance());
GraphicalGameView ggV = new GraphicalGameView(width, height, wm.getBombNumber(), optionPanel.isThorique(), wm.getMessage());
GraphicalOptionView goV = new GraphicalOptionView(width, height, wm.getBombNumber(), optionPanel.isThorique());
GraphicalLogscoreView glV = new GraphicalLogscoreView();
this.add(ggV.getPanel());
if (Minesweeper.standAlone) {
this.standAloneFrame = new GameFrame(width, height);
this.standAloneFrame.add(this, BorderLayout.CENTER);
}
wm.addView(ggV);
wm.addView(wTextv);
this.optionPanel.addView(goV);
this.optionPanel.addView(optionTextv);
if (this.standAlone()) {
wm.addView(glV);
this.scores.addView(new ScorePanel());
}
this.rules = new Rules(wm);
}
public Minesweeper() {
if (Minesweeper.instance != null) {
throw new AlreadyInstanciedApplet();
} else {
instance = this;
}
}
/**
*
* @return
*/
public ScoresModel getScores() {
return this.scores;
}
/**
*
* @return
*/
public boolean getResumeGame() {
return this.resumeGame;
}
/**
*
* @return
*/
public boolean getResumeSetOption() {
return this.resumeSetOption;
}
/**
*
*/
public void startGame() {
this.optionPanel.setUnderWay(false);
this.resumeSetOption = false;
this.resumeGame = true;
}
/**
*
*/
public void jumToOptions() {
this.resumeSetOption = true;
this.resumeGame = false;
this.optionPanel.setUnderWay(true);
}
/**
*
*/
public void restart() {
this.startGame();
this.rules.reset(this.createWorldModel());
}
/**
*
*/
public void exit() {
System.exit(0);
}
/**
*
* @return
*/
public Rules getRules() {
return this.rules;
}
private void setOptions() {
while (this.resumeSetOption) {
}
}
private void play() {
this.rules.getGameboard().notifyViews();
while (this.resumeGame) {
}
}
private WorldModel createWorldModel() {
int width = this.optionPanel.getWidth();
int height = this.optionPanel.getHeight();
double bombPercentage = this.optionPanel.getBombPercentage();
boolean isThorique = this.optionPanel.isThorique();
GameDifficulty gd = optionPanel.getDifficulty();
WorldModel m = new WorldModelImpl(width, height, bombPercentage, isThorique, gd);
return m;
}
public void resize(RefreshEvent event) {
if (this.standAlone()) {
this.standAloneFrame.resize(event);
}else{
int width = ((ResizeEvent) event).getWidth() * 50;
int height = ((ResizeEvent) event).getHeight() * 50;
this.setSize(new Dimension(width,height));
this.setMinimumSize(new Dimension(width, height));
}
}
}
|
package com.dennistjahyadigotama.soaya.activities.CategoryActivity.adapter;
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.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.dennistjahyadigotama.soaya.R;
import com.dennistjahyadigotama.soaya.activities.CategoryActivity.SubCategoryActivity;
import com.squareup.picasso.Picasso;
import java.util.List;
/**
* Created by Denn on 7/7/2016.
*/
public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.MyViewHolder> {
List<CategoryGetter> categoryListGetterList;
Context context;
class MyViewHolder extends RecyclerView.ViewHolder {
LinearLayout lin,lin2;
ImageView ivPic;
TextView tvName,tvDesc;
public MyViewHolder(View itemView) {
super(itemView);
context = itemView.getContext();
lin = (LinearLayout)itemView.findViewById(R.id.lin);
lin2 = (LinearLayout)itemView.findViewById(R.id.lin2);
ivPic = (ImageView)itemView.findViewById(R.id.imageViewImage);
tvName = (TextView)itemView.findViewById(R.id.textViewName);
tvDesc = (TextView)itemView.findViewById(R.id.textViewDescription);
}
}
public CategoryAdapter(List<CategoryGetter> categoryListGetterList){
this.categoryListGetterList=categoryListGetterList;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_forum_category_view,parent,false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
final CategoryGetter categoryListGetter = categoryListGetterList.get(position);
if(categoryListGetter.getPicurl()==null || categoryListGetter.getPicurl().equals("") || categoryListGetter.getPicurl().isEmpty())
{
holder.ivPic.setImageResource(R.drawable.border);
}else
{
Picasso.with(context).load(categoryListGetter.getPicurl()).into(holder.ivPic);
}
holder.tvName.setText(categoryListGetter.getName());
holder.tvDesc.setText(categoryListGetter.getDesc());
holder.lin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Toast.makeText(context,categoryListGetter.getName(),Toast.LENGTH_SHORT).show();
Intent i = new Intent(context, SubCategoryActivity.class);
i.putExtra("categoryid",categoryListGetter.getId());
i.putExtra("categoryname",categoryListGetter.getName().replace(" ", "")); //volley can't pass white space ex: get post
i.putExtra("titlename",categoryListGetter.getName());
context.startActivity(i);
}
});
}
@Override
public int getItemCount() {
return categoryListGetterList.size();
}
}
|
int main() {
printInt(-9);
return 0;
}
|
package com.junior.dwan.testuran.ui.fragments;
import android.app.ListFragment;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.view.menu.MenuBuilder;
import android.support.v7.view.menu.MenuPopupHelper;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.junior.dwan.testuran.R;
import com.junior.dwan.testuran.data.Controller;
import com.junior.dwan.testuran.data.Model;
import com.junior.dwan.testuran.utils.DBUtils;
import com.junior.dwan.testuran.utils.GenerateData;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
/**
* Created by Might on 28.12.2016.
*/
public class MainFragment extends ListFragment {
ArrayList<Model> mListModel;
Controller mController;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mController=Controller.getInstance(getActivity());
mListModel =mController.getListModels(getActivity());
setupAdapterforList();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return super.onCreateView(inflater, container, savedInstanceState);
}
private void setupAdapterforList() {
ModelAdapter adapter = new ModelAdapter(mListModel);
setListAdapter(adapter);
}
private class ModelAdapter extends ArrayAdapter<Model> {
public ModelAdapter(ArrayList<Model> models) {
super(getActivity(), 0, models);
}
@NonNull
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null)
convertView = getActivity().getLayoutInflater().inflate(R.layout.list_item, null);
registerForContextMenu(convertView);
Model model = getItem(position);
View colorBarOrange = convertView.findViewById(R.id.colorLeftBarOrange);
View colorBarBlue = convertView.findViewById(R.id.colorLeftBarBlue);
if (model.isBlue() && !model.isOrange()) {
colorBarOrange.setVisibility(View.GONE);
colorBarBlue.setVisibility(View.VISIBLE);
} else if (!model.isBlue() && model.isOrange()) {
colorBarOrange.setVisibility(View.VISIBLE);
colorBarBlue.setVisibility(View.GONE);
} else if (model.isOrange() && model.isBlue()) {
colorBarOrange.setVisibility(View.VISIBLE);
colorBarBlue.setVisibility(View.VISIBLE);
} else if (!model.isOrange() && !model.isBlue()) {
colorBarOrange.setVisibility(View.GONE);
colorBarBlue.setVisibility(View.GONE);
}
ImageView imgType = (ImageView) convertView.findViewById(R.id.type_imageView);
model.checkFileType();
if (model.checkFileType().equals("image")) {
imgType.setBackground(getResources().getDrawable(R.drawable.ic_photo_size_select_actual_black_24dp));
} else if (model.checkFileType().equals("doc")) {
imgType.setBackground(getResources().getDrawable(R.drawable.ic_insert_drive_file_black_24dp));
} else if (model.checkFileType().equals("none")) {
imgType.setBackground(getResources().getDrawable(R.drawable.ic_folder_black_24dp));
}
TextView tvtitle = (TextView) convertView.findViewById(R.id.list_title);
tvtitle.setText(model.getFilename());
TextView tvDate = (TextView) convertView.findViewById(R.id.list_date);
SimpleDateFormat sdf;
sdf = new SimpleDateFormat("MMMM d, yyyy");
String format = sdf.format(model.getModDate());
String dateString = "modified " + format;
tvDate.setText(dateString);
return convertView;
}
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
Model model = ((ModelAdapter) getListAdapter()).getItem(position);
if (!model.isFolder()) {
Log.i("TAG", "was clicked " + model.getFilename());
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
MenuBuilder menuBuilder = new MenuBuilder(getActivity());
MenuInflater inflater = new MenuInflater(getActivity());
inflater.inflate(R.menu.popup_menu, menuBuilder);
MenuPopupHelper optionsMenu = new MenuPopupHelper(getActivity(), menuBuilder, v);
optionsMenu.setForceShowIcon(true);
optionsMenu.show(250, 0);
}
}
|
package Iterator;
/**
*
* @author MSI
*/
public class patientDemo {
public static void main(String[] args) {
patientListIterator iterator = new patientListIterator();
for(Iterator iteratorPattern = iterator.getIterator();iteratorPattern.hasNext();){
String nameOfPatient = (String) iteratorPattern.next();
System.out.println("Name of patient: " + nameOfPatient);
}
}
}
|
package jwscert.jaxws.services.fromjava.wsannotation;
import javax.jws.WebService;
/*
<portType name="LogServiceImpl2">...</portType>
<binding name="LogServiceImpl2PortBinding" type="tns:LogServiceImpl2">...</binding>
<service name="LogWebService2">
<port name="LogServiceImpl2Port" binding="tns:LogServiceImpl2PortBinding">...</port>
</service>
*/
@WebService(serviceName = "LogWebService2")
public class LogServiceImpl2 {
public void log(String msg) {
System.out.println(msg);
}
}
|
package laserlight;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
public class Mirror extends GameObjects{
private int typeMirrorSignum = 0;
public MirrorType type;
@Override
public Point transformujVektor(Point dir) {
return new Point(this.typeMirrorSignum * dir.y, this.typeMirrorSignum * dir.x);
}
public enum MirrorType { left, right }
public void setMirrorType(MirrorType mirrType){
BufferedImage mirr = null;
this.type = mirrType;
this.typeMirrorSignum = (mirrType == MirrorType.left) ? +1 : -1;
try {
if(mirrType == MirrorType.left){
mirr = ImageIO.read(getClass().getResource("/images/mirrorL.png"));
}
if(mirrType == MirrorType.right){
mirr = ImageIO.read(getClass().getResource("/images/mirrorR.png"));
}
}
catch(IOException ex){
System.out.println("Chyba pri nacitani zrcadel.");
}
initObjekt(mirr);
}
public MirrorType getMirrorType(){
return this.type;
}
}
|
package jwscert.rest.services.annotations;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
@Path("/queryparam")
public class QueryParamAnnotation {
@QueryParam("param1")
private String param1;
@GET
public String helloWithParams(@QueryParam("param2") String param2){
return param1 + " " + param2;
}
}
|
/**
*
*/
package com.goodhealth.design.demo.StatePattern;
/**
* @author 24663
* @date 2018年10月27日
* @Description
*/
public class StopAndOpen extends AbstractState {
/* (non-Javadoc)
* @see com.goodhealth.design.demo.StatePattern.AbstractState#run()
*/
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("无操作--未关门不允许运行");
}
/* (non-Javadoc)
* @see com.goodhealth.design.demo.StatePattern.AbstractState#stop()
*/
@Override
public void stop() {
// TODO Auto-generated method stub
System.out.println("无操作--电梯已经停止了");
}
/* (non-Javadoc)
* @see com.goodhealth.design.demo.StatePattern.AbstractState#open()
*/
@Override
public void open() {
// TODO Auto-generated method stub
System.out.println("无操作--电梯门是开的");
}
/* (non-Javadoc)
* @see com.goodhealth.design.demo.StatePattern.AbstractState#close()
*/
@Override
public void close() {
// TODO Auto-generated method stub
System.out.println("电梯关门");
this.context.setCurrentState(context.stopandclose);
}
}
|
/**
* Created by lin on 2016/8/27.
*/
/*下面的TwoDShape和Triangle。这两个类都添加了把对象作为形参的构造函数。*/
public class TwoDShape8 {
private double width;
private double height;
// 一个默认的构造函数。
TwoDShape8() {
width = height = 0.0;
}
// 参数化构造函数。
TwoDShape8(double w, double h) {
width = w;
height = h;
}
// 构造一个对象以同样的宽度和高度。
TwoDShape8(double x) {
width = height = x;
}
// 构造一个对象的对象。
TwoDShape8(TwoDShape8 ob) {// 从一个对象构造对象
width = ob.width;
height = ob.height;
}
// 宽度和高度的访问方法。
double getWidth() { return width; }
double getHeight() { return height; }
//void setWidth(double w) { width = w; }
//void setHeight(double h) { height = h; }
void showDim() {
System.out.println("Width and heght are " + width + " and " + height);
}
}
// 一个子类的TwoDShape8三角形
class Triangle8 extends TwoDShape8{
private String style;
// 一个默认的构造函数。
Triangle8(){
super();
style = " none ";
}
// 构造函数为三角。
Triangle8(String s, double w, double h) {
super(w, h);
style = s;
}
// 一个参数的构造函数。
/*Triangle8(double x) {
super (x);
style = "filled";
}*/
// 构造一个对象形成一个对象
Triangle8(Triangle8 ob) {
super(ob); // 向TwoDShape的构造函数传递一个Triangle引用。
style = ob.style;
}
double area() {
return getWidth() * getHeight() / 2;
}
void showStyle() {
System.out.println("Triangle8 is" + style);
}
}
class Shapes8 {
public static void main(String args[]) {
Triangle8 t1 = new Triangle8("outlined", 8.0, 12.0);
// 复制t1.
Triangle8 t2 = new Triangle8(t1);
System.out.println("Info for t1: ");
t1.showStyle();
t1.showDim();
System.out.println("Area is " + t1.area());
System.out.println();
System.out.println("Info for t2: ");
t2.showStyle();
t2.showDim();
System.out.println("Area is " + t2.area());
}
}
|
package com.capgemini.service;
import java.util.List;
import com.capgemini.exceptions.DuplicateParkingFloorException;
import com.capgemini.exceptions.DuplicateParkingPremiseException;
import com.capgemini.exceptions.InvalidLoginCredintialException;
import com.capgemini.exceptions.NoSuchParkingFloorException;
import com.capgemini.exceptions.NoSuchParkingPremiseException;
import com.capgemini.exceptions.NoSuchUserException;
import com.capgemini.model.Login;
import com.capgemini.model.ParkingFloor;
import com.capgemini.model.ParkingPremise;
import com.capgemini.model.User;
public interface AdminService {
public boolean login(Login login) throws InvalidLoginCredintialException;
public boolean blockUser(User user) throws NoSuchUserException;
// Parking Premise
public boolean addParkingPremise(ParkingPremise parkingPremise) throws DuplicateParkingPremiseException;
public ParkingPremise getParkingPremiseById(long parkingPremiseId) throws NoSuchParkingPremiseException;
public List<ParkingPremise> getParkingPremiseByName(String premiseName) throws NoSuchParkingPremiseException;
public List<ParkingPremise> getAllParkingPremises();
public ParkingPremise modifyParkingPremise(ParkingPremise parkingPremise);
public boolean removeParkingPremise(int parkingPremiseId) throws NoSuchParkingPremiseException;
// Parking Floor
public boolean addParkingFloor(ParkingFloor parkingFloor) throws DuplicateParkingFloorException;
public ParkingFloor getParkingFloorById(long parkingFloorId) throws NoSuchParkingFloorException;
public List<ParkingFloor> getParkingFloorByNumber(long parkingPremiseId, String floorNumber) throws NoSuchParkingFloorException;
public List<ParkingFloor> getAllParkingFloors(long parkingPremiseId);
public ParkingFloor modifyParkingCapacity(ParkingFloor parkingFloor);
public boolean removeParkingFloor(long parkingFloorId) throws NoSuchParkingPremiseException;
}
|
package ${package}.config;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SampleApplicationConfig {
}
|
package hadoop_rpc_test.server;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.ipc.RPC;
import org.apache.hadoop.ipc.RPC.Server;
public class RPCServer {
public static void main(String[] args) throws Exception {
// 定义一个RPC Builder
RPC.Builder builder = new RPC.Builder(new Configuration());
// 指定RPC Server的参数
builder.setBindAddress("localhost");
builder.setPort(7788);
// 将自己的程序部署到Server上
builder.setProtocol(MyInterface.class);
builder.setInstance(new MyInterfaceImpl());
// 创建Server
Server server = builder.build();
// 启动
server.start();
}
}
|
package test;
import config.Message;
public class StringMessage extends Message<String> {
public StringMessage(String value) {
super(value);
}
}
|
package com.example.testimage.services;
import java.util.Vector;
import java.util.List;
/*
* QQ:1650941960
* by:hui
*
*
* */
public class Model {
int count;//手数
int value;//权值
//一组牌
List<String> a1 = new Vector<String>(); //单张
List<String> a2 = new Vector<String>(); //对子
List<String> a3 = new Vector<String>(); //3带
List<String> a123 = new Vector<String>(); //顺子
List<String> a112233 = new Vector<String>(); //连队
List<String> a111222 = new Vector<String>(); //飞机
List<String> a4 = new Vector<String>(); //炸弹
}
|
package com.tencent.mm.plugin.fingerprint.b;
import android.os.Bundle;
import android.os.Message;
import com.tencent.mm.plugin.fingerprint.b.h.a;
import com.tencent.mm.sdk.platformtools.x;
class h$a$2 implements Runnable {
final /* synthetic */ String jgB;
final /* synthetic */ a jgJ;
h$a$2(a aVar, String str) {
this.jgJ = aVar;
this.jgB = str;
}
public final void run() {
x.i("MicroMsg.HwFingerprintOpenDelegate", "GenRsaKeySync.callback running");
Message obtainMessage = this.jgJ.jgH.jgz.obtainMessage();
obtainMessage.what = 1;
Bundle bundle = new Bundle();
bundle.putString("rsaKey", this.jgB);
obtainMessage.setData(bundle);
obtainMessage.sendToTarget();
}
}
|
package com.tencent.magicbrush.a;
public final class b {
private static a bnl = new 1();
public static void a(a aVar) {
bnl = aVar;
}
public static void loadLibrary(String str) {
bnl.loadLibrary(str);
}
}
|
package com.jiuzhe.app.hotel.module;
import com.aliyun.opensearch.sdk.generated.search.Order;
public class OpenSearchQuery {
/**
* 服务器名称
*/
private String appName;
/**
* 起始位置
*/
private int start;
/**
* 返回结果数目
*/
private int hits;
/**
* 查询语句
*/
private String query;
/**
* 过滤条件
*/
private String filter;
/**
* 排序字段
*/
private String sortFiled;
/**
* 排序规则
*/
private Order sortType;
public OpenSearchQuery() {
}
public OpenSearchQuery(String appName, int start, int hits, String query, String filter, String sortFiled, Order sortType) {
this.appName = appName;
this.start = start;
this.hits = hits;
this.query = query;
this.filter = filter;
this.sortFiled = sortFiled;
this.sortType = sortType;
}
public String getAppName() {
return appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
public int getHits() {
return hits;
}
public void setHits(int hits) {
this.hits = hits;
}
public String getQuery() {
return query;
}
public void setQuery(String query) {
this.query = query;
}
public String getFilter() {
return filter;
}
public void setFilter(String filter) {
this.filter = filter;
}
public String getSortFiled() {
return sortFiled;
}
public void setSortFiled(String sortFiled) {
this.sortFiled = sortFiled;
}
public Order getSortType() {
return sortType;
}
public void setSortType(Order sortType) {
this.sortType = sortType;
}
}
|
package com.wj.service;
import com.wj.service.entity.Health;
import java.util.List;
/**
* @author jun.wang
* @title: RegisterService
* @projectName ownerpro
* @description: TODO
* @date 2019/4/28 14:20
*/
public interface RegisterService {
List<Health> getAllService();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.