text
stringlengths
10
2.72M
package com.xuecheng.manage_cms_client.config; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; @Data @ConfigurationProperties(prefix = "xuecheng.mq") public class RabbitmqProperties { private String queue; private String routingKey; }
package diana_p2; import java.util.Scanner; public class bmi { public static void main(String[] args) { double bmi = 0, weight, height; int input; Scanner scnr = new Scanner(System.in); System.out.println("Enter the integer of the mesurement would you like to use? " + "\n(1) Customary\n(2) Metric"); input = scnr.nextInt(); while(input != 1 && input != 2) { System.out.println("Please Enter 1 for customary or 2 for metric."); input = scnr.nextInt(); } if(input == 1) { System.out.println("Please enter your height in inches."); height = scnr.nextDouble(); System.out.println("Please enter your weight in pounds."); weight = scnr.nextDouble(); bmi = (703 * weight) / Math.pow(height, 2); } else if(input == 2) { System.out.println("Please enter your height in meters."); height = scnr.nextDouble(); System.out.println("Please enter your weight in kilograms."); weight = scnr.nextDouble(); bmi = weight / Math.pow(height, 2); } System.out.println("-------------------Body Weight Catagories-------------------"); System.out.println("Underweight =< 18.5"); System.out.println("Normal weight = 18.5 - 24.9"); System.out.println("Overweight = 25 - 29.9"); System.out.println("Obesity >= 30"); System.out.println("------------------------------------------------------------"); System.out.printf("The users BMI is: %2.2f", bmi); if(bmi < 18.5) { System.out.println(" and is considered underweight."); } else if(bmi >= 18.5 && bmi <= 24.9) { System.out.println(" and is considered normal weight."); } else if(bmi >= 25 && bmi <=29.9) { System.out.println(" and is considered overweight."); } else System.out.println(" and is considered obese."); } }
package com.jk.jkproject.ui.dialog; import android.annotation.SuppressLint; import android.app.Dialog; import android.content.Context; import android.graphics.Typeface; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.fragment.app.DialogFragment; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; import androidx.viewpager.widget.PagerAdapter; import androidx.viewpager.widget.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.LinearLayout; import android.widget.TextView; import com.jk.jkproject.R; import com.jk.jkproject.base.BaseFragmentPageAdapter; import com.jk.jkproject.ui.entity.LiveGiftInfoBean; import com.jk.jkproject.ui.fragment.LiveHomePKContribution2Fragment; import com.jk.jkproject.ui.fragment.LiveHomePKContributionFragment; import com.jk.jkproject.ui.widget.NoScrollViewPager; import com.jk.jkproject.utils.ScreenUtils; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.Unbinder; @SuppressLint({"ValidFragment"}) public class DialogLiveRoomPkContributionList extends DialogFragment implements ViewPager.OnPageChangeListener { @BindView(R.id.tv_left_name) TextView tvLeftName; @BindView(R.id.tv_right_name) TextView tvRightName; @BindView(R.id.ll_1) LinearLayout ll1; @BindView(R.id.live_vp_pager) NoScrollViewPager vp; protected int animId = -1; private OnClickDataListener mClickDataListener; private Context mContext; private FragmentManager supportFragmentManager; Unbinder unbinder; private List<Fragment> fragList = new ArrayList<>(); private FragmentManager fragmentManager; private BaseFragmentPageAdapter mAdapter; private int mType = 0; private String userId, tagUserId; private String pkId; private String roomId, tagRoomId; private LiveHomePKContributionFragment contributionFragment; private LiveHomePKContribution2Fragment contribution2Fragment; public DialogLiveRoomPkContributionList(Context context, int mType, String pkid, String userId, String roomId, String tagUserId, String tagRoomId) { this.mContext = context; this.mType = mType; this.pkId = pkid; this.userId = userId; this.roomId = roomId; this.tagUserId = tagUserId; this.tagRoomId = tagRoomId; } public DialogLiveRoomPkContributionList(Context context) { this.mContext = context; } private void initFullScreen() { Dialog dialog = getDialog(); if (dialog != null) { Window window = dialog.getWindow(); if (window != null) { WindowManager.LayoutParams layoutParams = window.getAttributes(); layoutParams.width = -1; layoutParams.height = ScreenUtils.dp2px(mContext, 443); layoutParams.dimAmount = 0.0F; window.setAttributes(layoutParams); } } } private void setupViewPager() { contributionFragment = LiveHomePKContributionFragment.newInstance(1); contribution2Fragment = LiveHomePKContribution2Fragment.newInstance(2); fragList.add(contributionFragment); fragList.add(contribution2Fragment); fragmentManager = getChildFragmentManager(); mAdapter = new BaseFragmentPageAdapter(this.fragmentManager, fragList); vp.setAdapter((PagerAdapter) mAdapter); vp.setOffscreenPageLimit(fragList.size()); // vp.setCurrentItem(0); vp.addOnPageChangeListener(this); setData(mType, pkId, userId, roomId, tagUserId, tagRoomId); } @Subscribe public void onCreate(@Nullable Bundle paramBundle) { super.onCreate(paramBundle); setStyle(1, R.style.MyDialog); setCancelable(true); EventBus.getDefault().register(this); } @Nullable public View onCreateView(LayoutInflater paramLayoutInflater, @Nullable ViewGroup paramViewGroup, @Nullable Bundle paramBundle) { Window window = getDialog().getWindow(); WindowManager.LayoutParams layoutParams = window.getAttributes(); layoutParams.systemUiVisibility = 2050; window.setAttributes(layoutParams); View view = paramLayoutInflater.inflate(R.layout.dialog_live_room_pk_contribution, paramViewGroup, false); getDialog().setCanceledOnTouchOutside(true); setWindow(); this.unbinder = ButterKnife.bind(this, view); setupViewPager(); return view; } public void onDestroy() { super.onDestroy(); } public void onDestroyView() { EventBus.getDefault().unregister(this); super.onDestroyView(); this.unbinder.unbind(); } public void onStart() { super.onStart(); initFullScreen(); } public void setCancelListener(OnClickDataListener paramOnClickDataListener) { this.mClickDataListener = paramOnClickDataListener; } protected void setWindow() { Window window = getDialog().getWindow(); if (window != null) { WindowManager.LayoutParams layoutParams = window.getAttributes(); layoutParams.width = -1; layoutParams.height = ScreenUtils.dp2px(mContext, 443); layoutParams.gravity = 80; int i = this.animId; if (i != -1) window.setWindowAnimations(i); window.setAttributes(layoutParams); } } public void show(FragmentManager paramFragmentManager, String paramString) { try { Class<?> clazz = Class.forName("android.support.v4.app.DialogFragment"); Object object = clazz.getConstructor(new Class[0]).newInstance(new Object[0]); Field field2 = clazz.getDeclaredField(" mDismissed"); field2.setAccessible(true); field2.set(object, Boolean.valueOf(false)); Field field1 = clazz.getDeclaredField("mShownByMe"); field1.setAccessible(true); field1.set(object, Boolean.valueOf(false)); } catch (Exception exception) { exception.printStackTrace(); } FragmentTransaction fragmentTransaction = paramFragmentManager.beginTransaction(); fragmentTransaction.add((Fragment) this, paramString); fragmentTransaction.commitAllowingStateLoss(); } @OnClick({R.id.tv_left_name, R.id.tv_right_name}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.tv_left_name: tvLeftName.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD)); tvRightName.setTypeface(Typeface.DEFAULT); tvLeftName.setBackgroundResource(R.drawable.bg_pk_contribution); tvRightName.setBackgroundResource(R.drawable.bg_pk_contribution_default); vp.setCurrentItem(0); break; case R.id.tv_right_name: tvRightName.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD)); tvLeftName.setTypeface(Typeface.DEFAULT); tvRightName.setBackgroundResource(R.drawable.bg_pk_contribution); tvLeftName.setBackgroundResource(R.drawable.bg_pk_contribution_default); vp.setCurrentItem(1); break; } } public void setData(int mType, String pkId, String userId, String roomId, String tagUserId, String tagRoomId) { if (vp != null) { vp.setCurrentItem(mType); } if (contributionFragment != null) { contributionFragment.getData(pkId, userId, roomId); } if (contribution2Fragment != null) { contribution2Fragment.getData(pkId, tagUserId, tagRoomId); } } public static interface OnClickDataListener { void onClickData(LiveGiftInfoBean.DataBean param1DataBean); } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { switch (position) { case 0: tvLeftName.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD)); tvRightName.setTypeface(Typeface.DEFAULT); tvLeftName.setBackgroundResource(R.drawable.bg_pk_contribution); tvRightName.setBackgroundResource(R.drawable.bg_pk_contribution_default); break; case 1: tvRightName.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD)); tvLeftName.setTypeface(Typeface.DEFAULT); tvRightName.setBackgroundResource(R.drawable.bg_pk_contribution); tvLeftName.setBackgroundResource(R.drawable.bg_pk_contribution_default); break; } this.vp.setCurrentItem(position); } @Override public void onPageScrollStateChanged(int state) { } }
package main; import java.awt.geom.Point2D; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import isochrone.IsoPolygon; import isochrone.Timezone; public class OutputWriter { private File fileZone; private File fileComponent; private int nBins = 16; public OutputWriter(File statsDir) { this.fileZone = new File(statsDir, "stats_zone.csv"); this.fileComponent = new File(statsDir, "stats_component.csv"); } public void writeResult(ResultSet result) { if (result.getTimezone() == null) return; boolean writeHeader = !fileZone.exists(); try (BufferedWriter bw = new BufferedWriter(new FileWriter(fileZone, true))) { if (writeHeader) writeZoneHeader(); bw.write(generateZoneString(result)); bw.newLine(); } catch (IOException e) { e.printStackTrace(); } writeHeader = !fileComponent.exists(); try (BufferedWriter bw = new BufferedWriter(new FileWriter(fileComponent, true))) { if (writeHeader) writeComponentHeader(); bw.write(generateComponentsString(result)); bw.newLine(); } catch (IOException e) { e.printStackTrace(); } } private String generateZoneString(ResultSet rs) { StringBuffer sb = new StringBuffer(); Timezone<Point2D> timezone = rs.getTimezone(); sb.append(rs.getTimezone().getId() + ","); sb.append((rs.getTimezone().isSuccess() ? 1 : 0) + ","); sb.append(rs.getConfig().getStartId() + ","); sb.append(rs.getTimezone().getTime() + ","); sb.append(rs.getConfig().getStarttime() + ","); sb.append(rs.getConfig().getVisualizationType() + ","); sb.append(rs.getConfig().getFilter() + ","); sb.append(rs.getConfig().getMaxDoR() + ","); sb.append(rs.getConfig().iterDoR() + ","); sb.append(rs.getConfig().getDilationFactor() + ","); sb.append(rs.getConfig().getRoad() + ","); sb.append(rs.getConfig().getTrain() + ","); sb.append(timezone.getPerimeter() + ","); sb.append(timezone.getOctiPerimeter() + ","); sb.append(timezone.getArea() + ","); sb.append(timezone.getNumHoles() + ","); sb.append(timezone.getAreaHoles() + ","); sb.append(timezone.getNumTurns() + ","); sb.append(timezone.getTP() + ","); sb.append(timezone.getFP() + ","); sb.append(timezone.getTN() + ","); sb.append(timezone.getFN() + ","); sb.append(timezone.getPolyList().size() + ","); sb.append(rs.getStopwatch().getTotalRuntime() + ","); sb.append(rs.getStopwatch().getRuntime("travelTimes") + ","); sb.append(rs.getStopwatch().getRuntime("visualizationGraph") + ","); sb.append(rs.getStopwatch().getRuntime("dcel") + ","); sb.append(rs.getStopwatch().getRuntime("findSplitnodes") + ","); sb.append(rs.getStopwatch().getRuntime("seperateSplitnodes") + ","); sb.append(rs.getStopwatch().getRuntime("faceIdentification") + ","); sb.append(rs.getStopwatch().getRuntime("graphCombine") + ","); sb.append(rs.getStopwatch().getRuntime("faceProcessing") + ","); sb.append(rs.getStopwatch().getRuntime("faceRouting") + ","); sb.append(rs.getStopwatch().getRuntime("innerIdentification") + ","); sb.append(rs.getStopwatch().getRuntime("recolor") + ","); sb.append(rs.getStopwatch().getRuntime("validation") + ","); sb.append(histToString(timezone.outerAngleHistogramm(nBins)) + ","); return sb.toString(); } private String generateZoneHeader() { String[] headers = { "zone_id", "success", "start_id", "zone_time", "start_time", "type", "filter", "maxDoR", "iterDoR", "dilFactor", "road_path", "gtfs_path", "perimeter", "perimeter_octi", "area", "num_holes", "area_holes", "turns", "tp", "fp", "tn", "fn", "num_components", "run_time", "t_travelTimes", "t_visGraph", "t_dcel", "t_findSplitnodes", "t_seperateSplitnodes", "t_faceIden", "t_graphCombine", "t_faceProc", "t_faceRoute", "t_innerIden", "t_recolor", "t_validate", binIndexToString(nBins) }; return generateHeader(headers); } public void writeZoneHeader() { try (BufferedWriter bw = new BufferedWriter(new FileWriter(fileZone, true))) { bw.write(generateZoneHeader()); bw.newLine(); } catch (IOException e) { e.printStackTrace(); } } private String generateComponentsString(ResultSet rs) { StringBuffer sb = new StringBuffer(); Timezone<Point2D> timezone = rs.getTimezone(); boolean first = true; for (IsoPolygon<Point2D> poly : rs.getTimezone().getPolyList()) { if (!first) { sb.append("\n"); } else { first = false; } sb.append(timezone.getId() + ","); sb.append(poly.getPerimeter() + ","); sb.append(poly.getOctiPerimeter() + ","); sb.append(poly.getArea() + ","); sb.append(poly.getNumHoles() + ","); sb.append(poly.getAreaHoles() + ","); sb.append(poly.getNumTurns() + ","); sb.append(poly.getCompactness() + ","); sb.append(poly.getComplexity() + ","); sb.append(poly.getNotchNorm() + ","); sb.append(poly.getAmplitudeOfVibration() + ","); sb.append(poly.getFrequencyOfVibration() + ","); sb.append(poly.getConvexity() + ","); sb.append(poly.getMessage() + ","); sb.append(histToString(poly.outerAngleHistogramm(nBins)) + ","); } return sb.toString(); } private String generateComponentHeader() { String[] headers = { "zone_id", "perimeter", "perimeter_octi", "area", "num_holes", "area_holes", "turns", "compactness", "complexity", "nn", "aov", "fov", "convexity", "message", binIndexToString(nBins) }; return generateHeader(headers); } public void writeComponentHeader() { try (BufferedWriter bw = new BufferedWriter(new FileWriter(fileComponent, true))) { bw.write(generateComponentHeader()); bw.newLine(); } catch (IOException e) { e.printStackTrace(); } } private String generateHeader(String[] headers) { if (headers == null || headers.length < 1) return ""; StringBuffer sb = new StringBuffer(); sb.append(headers[0]); for (int i = 1; i < headers.length; ++i) { sb.append(","); sb.append(headers[i]); } return sb.toString(); } private String histToString(int[] bins) { StringBuilder sb = new StringBuilder(); sb.append(bins[0]); for (int i = 1; i < bins.length; ++i) { sb.append(","); sb.append(bins[i]); } return sb.toString(); } private String binIndexToString(int nBins) { StringBuilder sb = new StringBuilder(); sb.append(String.format("bin%02d", 0)); for (int i = 1; i < nBins + 1; ++i) { sb.append(","); sb.append(String.format("bin%02d", i)); } return sb.toString(); } @SuppressWarnings("unused") private String histToString(double[] bins) { StringBuilder sb = new StringBuilder(); sb.append(String.format("%6.2f", bins[0])); for (int i = 1; i < bins.length; ++i) { sb.append(","); // sb.append(String.format("%6.2f", bins[i])); sb.append(bins[i]); } return sb.toString(); } }
package game.commands; import game.model.Field; import game.model.Field.AllowedContent; import game.ui.MainWindow; import java.awt.AWTEvent; /** * Der RemoveArrowCommand ist für das Entfernen eines Pfeils verantwortlich. * * @author Nikolaj */ public class RemoveArrowCommand extends AbstractCommand { private static final long serialVersionUID = -5609261504063576278L; /** * Konstruktor * * @param stacks * - CommandStack Referenz * * @param e * - Das den Command aufrufende Event */ public RemoveArrowCommand(CommandStack stacks, AWTEvent e) { super(stacks, e); } /** * Initiiert das Entfernen eines Pfeils durch die im Event übergebene Quelle Field. */ @Override public void execute() { ((Field) MainWindow.getInstance().getCurrentStarfield().getField(getxCoord(), getyCoord())).setUserContent(AllowedContent.CONTENT_EMPTY); } }
package JavaSE.OO.guanjianzi; /* * super关键字 * 1、super不是引用类型,super中存储的不是内存地址 * 2、this是引用,this中存储的是内存地址 * 3、super代表的是当前子类对象中的父类型特征 * 什么时候使用super * 子类和父类中都有某个属性或方法 * 在子类中想要访问父类的方法或属性需要使用super * 直接访问会默认加this.表示当前类中的数据,而不是父类中的数据 * super可以用在什么地方 * super可以用在实例方法中 * super可以用在构造方法中,this用在构造方法中是this() * super不能用在静态方法中,因为没有对象 */ class Employee{ String name="张三"; public void work() { System.out.println("员工工作"); } } class Manager extends Employee{ String name="李四"; //将work方法重写 public void work() { System.out.println("经理工作"); } public void m1(){ work();//此时表示this.work输出经理工作 super.work();//此时输出员工工作 System.out.println(name);//表示this.name输出李四 System.out.println(super.name);//输出张三 } /*this和super相同,都不能直接用在静态上下文中 public static void m2() { System.out.println(super.name); } */ } public class SuperTest01 { public static void main(String[] args) { Manager m=new Manager(); m.m1(); } }
package com.sporsimdi.action.facadeBean; import java.io.Serializable; import java.util.List; import java.util.Map; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import org.primefaces.model.SortOrder; import com.sporsimdi.action.facade.UyeFacade; import com.sporsimdi.model.entity.Isletme; import com.sporsimdi.model.entity.Uye; import com.sporsimdi.model.type.Status; @Stateless public class UyeFacadeBean implements UyeFacade, Serializable { private static final long serialVersionUID = 1351677350164757297L; @PersistenceContext(unitName = "sporsimdi") EntityManager entityManager; public UyeFacadeBean() { } public void persist(Uye uye) { entityManager.persist(uye); } public void merge(Uye uye) { entityManager.merge(uye); } public void remove(Uye uye) { entityManager.remove(uye); } public void delete(Uye uye) { uye.setStatus(Status.PASSIVE); entityManager.merge(uye); } public Uye findById(long id) { return entityManager.find(Uye.class, id); } @SuppressWarnings("unchecked") @Override public List<Uye> getByStatus(Status status) { Query q = entityManager.createQuery("select k from Uye k where k.status =:status").setParameter("status", status); return q.getResultList(); } @SuppressWarnings("unchecked") @Override public List<Uye> listAll() { Query q = entityManager.createQuery("select u from Uye u join fetch u.grupListesi gl join fetch u.isletme o"); return q.getResultList(); } @Override public List<Uye> getUye(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, String> filters) { @SuppressWarnings("unchecked") List<Uye> list = entityManager.createQuery("select k from Uye k").setFirstResult(first).setMaxResults(pageSize).getResultList(); for (Uye uye : list) { entityManager.detach(uye); } return list; } @Override public Long getCount() { return (Long) entityManager.createQuery("select count(k) from Uye k").getSingleResult(); } @Override public Uye findByIdEager(long id) { Uye uye = (Uye) entityManager .createQuery( "select u from Uye u " + " left outer join fetch u.grupListesi gl " + " left outer join fetch gl.grup g " + " join fetch u.meslek m " + " where u.id=:id").setParameter("id", id).getSingleResult(); return uye; } @Override public Uye getWithIsletmeByIdEager(long id) { Uye uye = (Uye) entityManager.createQuery("select u from Uye u " + " join fetch u.isletmeListesi il " + " where u.id=:id").setParameter("id", id) .getSingleResult(); return uye; } @SuppressWarnings("unchecked") @Override public List<Uye> listByIsletme(Isletme isletme) { Query q = entityManager.createQuery( "select u from Uye u " + "join u.isletmeListesi il " + "join fetch u.meslek m " + "where il.id = :id " + "order by u.ad, u.soyad") .setParameter("id", isletme.getId()); return q.getResultList(); } @SuppressWarnings("unchecked") @Override public List<Uye> listByGrup(Long grupId) { return entityManager .createQuery( "select u from Uye u " + "join u.grupListesi g " + "left outer join fetch u.meslek m " + "where g.grup.id = :id " + " and g.status = 'ACTIVE' " + "order by u.ad, u.soyad").setParameter("id", grupId).getResultList(); } }
package dyvilx.tools.gradle; import groovy.lang.Closure; import org.gradle.api.Action; import org.gradle.api.file.SourceDirectorySet; public interface DyvilVirtualDirectory { String NAME = "dyvil"; SourceDirectorySet getDyvil(); DyvilVirtualDirectory dyvil(Closure configureClosure); DyvilVirtualDirectory dyvil(Action<? super SourceDirectorySet> configureAction); }
package ad.joyplus.com.myapplication.managers; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.net.Uri; import android.util.Log; import com.miaozhen.mzmonitor.MZMonitor; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Properties; import ad.joyplus.com.myapplication.AppUtil.Consts; import ad.joyplus.com.myapplication.AppUtil.TvManagerUtil; import ad.joyplus.com.myapplication.AppUtil.gson.Gson; import ad.joyplus.com.myapplication.AppUtil.gson.reflect.TypeToken; import ad.joyplus.com.myapplication.compoment.OpeningView; import ad.joyplus.com.myapplication.entity.AdModel; import ad.joyplus.com.myapplication.entity.ConfigModel; import ad.joyplus.com.myapplication.entity.EndMediaModel; import ad.joyplus.com.myapplication.entity.IHtmlInfo; import ad.joyplus.com.myapplication.entity.ImageViewModel; import ad.joyplus.com.myapplication.entity.OpeningAdModel; import ad.joyplus.com.myapplication.entity.StartMediaModel; import ad.joyplus.com.myapplication.entity.URLModel; import ad.joyplus.com.myapplication.network.IRequest; import ad.joyplus.com.myapplication.network.NetworkFactory; import ad.joyplus.com.myapplication.network.RequestIterface; import cn.com.mma.mobile.tracking.api.Countly; /** * Manager类具体来管理相关广告的请求及配置信息的读写、更新等 * <p/> * Created by UPC on 2016/8/31. */ public class AppADSDKManager { private Context mContext; private IRequest request; private ConfigModel<Map<String ,String>> basemodel; private OpeningAdModel openingAdModel; private StartMediaModel startMediaModel; private EndMediaModel endMediaModel; private ImageViewModel videoimgmodel; private ImageViewModel cornerimgmodel; private ImageViewModel simpleimgmodel; private String sdkKey; private OpeningView view ; private ILoadListener loadlistener; private static AppADSDKManager appADSDKManager; //常量 /** * 调用manager的initOPeningAD,使用者传入开屏页面的view,SDK将会下载并展示到该View上面 * 使用该方法时,是需要自己先建立ImageView的,另外的方法是直接调用OpeningScreenAD在布局上使用 */ private AppADSDKManager(Context context){ this.mContext = context.getApplicationContext(); } public static synchronized AppADSDKManager getInstance(Context context){ if(appADSDKManager == null){ if(context == null){ throw new NullPointerException("context was null"); } appADSDKManager = new AppADSDKManager(context); } return appADSDKManager; } public void init(String sdkkey) { sdkKey = sdkkey; view = new OpeningView(mContext); Countly.sharedInstance().init(mContext,getAdmaster()); request = NetworkFactory.newInstance(mContext); basemodel = getModelFromSp(); if (basemodel == null) { getInfoFromShare(); }else{ getAllModelFromConfig(); } } /** * 进行上报的时候调用该方法 * @param info 将请求到的Model传入 */ public void sendReprot(IHtmlInfo info) { System.out.println(info); String reportURL = ""; String reportTojoy = ""; List<String> thridList = new ArrayList<>(); if (info instanceof OpeningAdModel) { reportURL = ((OpeningAdModel) info).getHtml5_url(); reportTojoy = ((OpeningAdModel) info).getImpressionurl(); thridList = ((OpeningAdModel) info).getThridreport(); } else if (info instanceof ImageViewModel) { reportURL = ((ImageViewModel) info).getHtml5_url(); reportTojoy = ((ImageViewModel) info).getImpressionurl(); thridList = ((ImageViewModel) info).getThridreport(); } else if (info instanceof StartMediaModel) { reportURL = ((StartMediaModel) info).getHtml5_url(); reportTojoy = ((StartMediaModel) info).getImpressionurl(); thridList = ((StartMediaModel) info).getThridreport(); } else if (info instanceof EndMediaModel) { reportURL = ((EndMediaModel) info).getHtml5_url(); reportTojoy = ((EndMediaModel) info).getImpressionurl(); thridList = ((EndMediaModel) info).getThridreport(); } if (null!=reportTojoy&&!reportTojoy.isEmpty()) { reportToJoy(reportTojoy); } else { Log.e("AppADSDK", "Impressionurl was null"); } if (null!=reportURL&&!reportURL.isEmpty()){ System.out.println(reportURL); request.getHitmlInfo(reportURL, new RequestIterface.IHtmlInfoCallBack() { @Override public void OnHtmlBack(URLModel modle) { for (URLModel.UrlInfoEntity entity : modle.getUrl_info()) { request.reportInfo(entity.getUrl() + "&id=" + entity.getId(), new RequestIterface.IReportInfoCallBack() { @Override public void onReportBack(boolean state) { Log.i("AppADSDK", "Html5_report state " + state); } }); } } }); } if(null!=thridList&&!thridList.isEmpty()) { for (String thrids : thridList) { reportToThrid(thrids); } } } // TODO: 2016/12/26 添加上报及第三方上报,待测试。 private void reportToThrid(String thridURL){ if(thridURL.contains("ns=__IP__")){ thridURL = thridURL.replace("ns=__IP__","ns="+TvManagerUtil.getInstance(mContext).getIPAdress()); }else{ thridURL = thridURL+"&ns="+TvManagerUtil.getInstance(mContext).getIPAdress(); } if(thridURL.contains("m6a=__MAC__")){ thridURL = thridURL.replace("m6a=__MAC__","m6a="+TvManagerUtil.getInstance(mContext).getMacAdress()); }else{ thridURL = thridURL+"&m6a="+TvManagerUtil.getInstance(mContext).getMacAdress(); } if(thridURL.contains("m1a=__ANDROIDID__")){ thridURL = thridURL.replace("m1a=__ANDROIDID__","m1a="+TvManagerUtil.getInstance(mContext).getDeviceID()); }else{ thridURL = thridURL+"&m1a="+TvManagerUtil.getInstance(mContext).getDeviceID(); } if(thridURL.contains(Consts.MIAOZHEN)){ MZMonitor.retryCachedRequests(mContext); MZMonitor.adTrack(mContext, thridURL); }else if(thridURL.contains(Consts.ADMASTER)){ Countly.sharedInstance().onExpose(thridURL); }else{ request.reportInfo(thridURL, new RequestIterface.IReportInfoCallBack() { @Override public void onReportBack(boolean state) { Log.i("AppADSDK","ThridReport state "+state); } }); } } /** * 给自己服务器上报 * @param url */ private void reportToJoy(String url){ if(url.contains("i=%mac%")) { url = url.replace("%mac%",TvManagerUtil.getInstance(mContext).getMacAdress()); }else { url = url+"&i="+TvManagerUtil.getInstance(mContext).getMacAdress(); } if(url.contains("appkey=")){ url = url.replace("appkey=","appkey="+sdkKey); }else{ url = url+"&appkey="+sdkKey; } System.out.println(url+"url"); request.reportInfo(url, new RequestIterface.IReportInfoCallBack() { @Override public void onReportBack(boolean state) { } }); } public OpeningView getOpenView(ILoadListener listener) { this.loadlistener = listener; if(openingAdModel != null){ this.loadlistener.hasLoad(); } return view; } public ImageViewModel getVideoImgModel(){ if(videoimgmodel == null){ Log.e("APPADSDK","NO_AD"); return null; } refreshVideoImgView(); return videoimgmodel; } public ImageViewModel getCornerImgModel(){ if(cornerimgmodel == null){ Log.e("APPADSDK","NO_AD"); return null; } refreshCornerImgView(); return cornerimgmodel; } public ImageViewModel getSimpleImgModel(){ if(simpleimgmodel == null){ Log.e("APPADSDK","NO_AD"); return null; } refreshSimpleImgView(); return simpleimgmodel; } public OpeningAdModel getOpeningModel(){ if(openingAdModel == null){ Log.e("APPADSDK","NO_AD"); return null; } refreshOpenImage(); return openingAdModel; } public String getStartMediaModel(){ if(startMediaModel == null){ Log.e("APPADSDK","NO_AD"); return null; } refreshStartMedia(); return startMediaModel.getVideourl(); } public String getEndMediaModel(){ if(endMediaModel == null){ Log.e("APPADSDK","NO_AD"); return null; } refreshEndMedia(); return endMediaModel.getVideourl(); } private void getAllModelFromConfig(){ request.getBaseModel(Consts.OPEN, BuildURL(basemodel.getPublishID().get(Consts.AD_OPEN)), new RequestIterface.IADmodel() { @Override public void onAdModelBack(AdModel model) { openingAdModel = (OpeningAdModel) model.data; if(loadlistener != null) { loadlistener.hasLoad(); } view.disPlay(); checkversionCode(model.VersonCode); getOtherModelInfo(); } }); } private void getOtherModelInfo(){ if(basemodel.getPublishID().containsKey(Consts.AD_VIDEOIMG)){ request.getBaseModel(Consts.VIDEOIMG, BuildURL(basemodel.getPublishID().get(Consts.AD_VIDEOIMG)), new RequestIterface.IADmodel() { @Override public void onAdModelBack(AdModel model) { if(null != model) { videoimgmodel = (ImageViewModel) model.data; } } }); } if(basemodel.getPublishID().containsKey(Consts.AD_STARTMEDIA)){ request.getBaseModel(Consts.STARTMEDIA, BuildURL(basemodel.getPublishID().get(Consts.AD_STARTMEDIA)), new RequestIterface.IADmodel() { @Override public void onAdModelBack(AdModel model) { if(null != model) { startMediaModel = (StartMediaModel) model.data; } } }); } if(basemodel.getPublishID().containsKey(Consts.AD_ENDMEDIA)){ request.getBaseModel(Consts.ENDMEDIA, BuildURL(basemodel.getPublishID().get(Consts.AD_ENDMEDIA)), new RequestIterface.IADmodel() { @Override public void onAdModelBack(AdModel model) { if(null != model) { endMediaModel = (EndMediaModel) model.data; } } }); } if(basemodel.getPublishID().containsKey(Consts.AD_CORNERIMG)){ request.getBaseModel(Consts.CORNERIMG, BuildURL(basemodel.getPublishID().get(Consts.AD_CORNERIMG)), new RequestIterface.IADmodel() { @Override public void onAdModelBack(AdModel model) { if(null != model) { cornerimgmodel = (ImageViewModel) model.data; } } }); } if(basemodel.getPublishID().containsKey(Consts.AD_SIMPLEIMG)){ request.getBaseModel(Consts.SIMPLEIMG, BuildURL(basemodel.getPublishID().get(Consts.AD_SIMPLEIMG)), new RequestIterface.IADmodel() { @Override public void onAdModelBack(AdModel model) { if(null != model) { simpleimgmodel = (ImageViewModel) model.data; } } }); } } //添加参数 private String BuildURL(String type){ Uri.Builder b = Uri.parse(basemodel.getBaseURL().substring(0,basemodel.getBaseURL().length()-2)).buildUpon(); if(type != null) { b.appendQueryParameter("z", type);//广告位ID } b.appendQueryParameter(Consts.I_,TvManagerUtil.getInstance(mContext).getMacAdress());//Mac的Md5加密地址 b.appendQueryParameter(Consts.KEY,sdkKey);//App的key b.appendQueryParameter(Consts.DEV,TvManagerUtil.getInstance(mContext).getDeviceID());//机器的DevicceID b.appendQueryParameter(Consts.U_,TvManagerUtil.getInstance(mContext).getDefaultUserAgentString());//UA b.appendQueryParameter(Consts.T_,String.valueOf(System.currentTimeMillis()));//当前系统时间 b.appendQueryParameter(Consts.CONNECTION_TYPE,TvManagerUtil.getInstance(mContext).getConnectionType().toString());//网络连接方式 return b.toString(); } /** * 但版本号有变化则直接调该方法来更新当前的Config配置 */ private void getInfoFromShare() { /** * 获取baseurl第一次默认从properties文件内获取 * 之后直接从服务器获取baseurl */ String baseurl = ""; if(basemodel != null){ baseurl = basemodel.getBaseURL(); }else{ baseurl = getBaseURL(); } String requesturl = baseurl+ Consts.REQUEST_HEAD_LINK; Uri.Builder b = Uri.parse(requesturl).buildUpon(); if(sdkKey!=null){ b.appendQueryParameter("sdkkey",sdkKey); } if(!TvManagerUtil.getInstance(mContext).getDeviceID().isEmpty()){ b.appendQueryParameter(Consts.DEV,TvManagerUtil.getInstance(mContext).getDeviceID()); } if(!TvManagerUtil.getInstance(mContext).getIPAdress().isEmpty()){ b.appendQueryParameter(Consts.IP_,TvManagerUtil.getInstance(mContext).getIPAdress()); } if(!TvManagerUtil.getInstance(mContext).getMacAdress().isEmpty()){ b.appendQueryParameter(Consts.I_,TvManagerUtil.getInstance(mContext).getMacAdress()); } if(!TvManagerUtil.getInstance(mContext).getDefaultUserAgentString().isEmpty()){ b.appendQueryParameter(Consts.U_,TvManagerUtil.getInstance(mContext).getDefaultUserAgentString()); } if(!TvManagerUtil.getInstance(mContext).getConnectionType().toString().isEmpty()){ b.appendQueryParameter(Consts.CONNECTION_TYPE,TvManagerUtil.getInstance(mContext).getConnectionType().toString()); } if(!TvManagerUtil.getInstance(mContext).getVersionCode().isEmpty()){ b.appendQueryParameter(Consts.V_,TvManagerUtil.getInstance(mContext).getVersionCode()); } request.getConfigInfo(b.toString(), new RequestIterface.IModelCallBack() { @Override public void onConfigModelBack(AdModel<ConfigModel<Map<String,String>>> adModel) { setConfigInfotoPrefrence(adModel); basemodel = adModel.data; getAllModelFromConfig(); } }); } /** * 将Config配置信息写入shareprefrence * @param model */ private void setConfigInfotoPrefrence(AdModel<ConfigModel<Map<String,String>>> model) { SharedPreferences preferences = mContext.getSharedPreferences(Consts.SP_NAME, Activity.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putString(Consts.CONFIG_VERSION, model.VersonCode); editor.putString(Consts.SP_JSON_INFO, new Gson().toJson(model.data)); editor.commit(); } /** * 从shareprefrence里面获取Config配置信息 * @return ConfigModel */ private ConfigModel getModelFromSp() { SharedPreferences preferences = mContext.getSharedPreferences(Consts.SP_NAME, Activity.MODE_PRIVATE); String info_json = preferences.getString(Consts.SP_JSON_INFO, ""); return new Gson().fromJson(info_json, new TypeToken<ConfigModel<Map<String ,String>>>(){}.getType()); } /** * 判断传入的版本号,如果版本号有升级则请求AppSDk的配置文件 * @param newcode 传入的版本 */ private void checkversionCode(String newcode){ SharedPreferences preferences = mContext.getSharedPreferences(Consts.SP_NAME, Activity.MODE_PRIVATE); String version = preferences.getString(Consts.CONFIG_VERSION,""); if(!newcode.equals(version)){ getInfoFromShare(); } } private void refreshVideoImgView(){ request.getBaseModel(Consts.VIDEOIMG, BuildURL(basemodel.getPublishID().get(Consts.AD_VIDEOIMG)), new RequestIterface.IADmodel() { @Override public void onAdModelBack(AdModel model) { if(null != model) { videoimgmodel = (ImageViewModel) model.data; } } }); } private void refreshCornerImgView(){ request.getBaseModel(Consts.VIDEOIMG, BuildURL(basemodel.getPublishID().get(Consts.AD_CORNERIMG)), new RequestIterface.IADmodel() { @Override public void onAdModelBack(AdModel model) { if(null != model) { cornerimgmodel = (ImageViewModel) model.data; } } }); } private void refreshSimpleImgView(){ request.getBaseModel(Consts.VIDEOIMG, BuildURL(basemodel.getPublishID().get(Consts.AD_SIMPLEIMG)), new RequestIterface.IADmodel() { @Override public void onAdModelBack(AdModel model) { if(null != model) { simpleimgmodel = (ImageViewModel) model.data; } } }); } private void refreshStartMedia(){ request.getBaseModel(Consts.STARTMEDIA, BuildURL(basemodel.getPublishID().get(Consts.AD_STARTMEDIA)), new RequestIterface.IADmodel() { @Override public void onAdModelBack(AdModel model) { if(null != model) { startMediaModel = (StartMediaModel) model.data; } } }); } private void refreshEndMedia(){ request.getBaseModel(Consts.ENDMEDIA, BuildURL(basemodel.getPublishID().get(Consts.AD_ENDMEDIA)), new RequestIterface.IADmodel() { @Override public void onAdModelBack(AdModel model) { if(null != model) { endMediaModel = (EndMediaModel) model.data; } } }); } private void refreshOpenImage(){ request.getBaseModel(Consts.OPEN, BuildURL(basemodel.getPublishID().get(Consts.AD_OPEN)), new RequestIterface.IADmodel() { @Override public void onAdModelBack(AdModel model) { if(null != model) { openingAdModel = (OpeningAdModel) model.data; } } }); } private String getBaseURL(){ Properties properties = new Properties(); String baseurl = ""; try { properties.load(mContext.getAssets().open(Consts.CONFIG_NAME)); baseurl = (String) properties.get(Consts.BASEURL); } catch (IOException e) { e.printStackTrace(); } return baseurl; } private String getAdmaster(){ Properties properties = new Properties(); String admaster = ""; try { properties.load(mContext.getAssets().open(Consts.CONFIG_NAME)); admaster = (String) properties.get(Consts.BASEURL); } catch (IOException e) { e.printStackTrace(); } return admaster; } }
package com.framework.service; import java.util.List; import com.framework.bean.common.JsTreeNodeBean; import com.framework.bean.vo.SysDepartmentTreeVo; import com.framework.model.SysDepartment; public interface DepartmentService { JsTreeNodeBean getDeptWithUserJsTreeData() throws Exception; List<SysDepartmentTreeVo> queryMenuListByPCode(String pCode) throws Exception; void saveDepartment(List<SysDepartment> departments) throws Exception; }
package com.rails.ecommerce.admin.common.controller; import java.util.List; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.rails.ecommerce.core.common.domain.TreeNodeList; @Controller public class LoginController { @RequestMapping(value = "/") public ModelAndView login() { // Subject subject = SecurityUtils.getSubject(); // Object principal = subject.getPrincipal();//获取用户登录信息 // Session session=subject.getSession(); // session.setAttribute("userName", principal.toString());//获取用户登录放入session ModelAndView model = new ModelAndView(); model.setViewName("main"); return model; } @RequestMapping(value = "/main") public ModelAndView loginIn() { // Subject subject = SecurityUtils.getSubject(); // Object principal = subject.getPrincipal();//获取用户登录信息 // Session session=subject.getSession(); // session.setAttribute("userName", principal.toString());//获取用户登录放入session ModelAndView model = new ModelAndView(); model.setViewName("main"); return model; } // @RequestMapping(value = "/mainmenu") // @ResponseBody // public List<SystemMenu> sysmenulist() { // Subject subject = SecurityUtils.getSubject(); // Object principal = subject.getPrincipal();//获取用户登录信息 // Session session=subject.getSession(); // List<SystemMenu> treeList1=(List<SystemMenu>)session.getAttribute("treeList"); // if(treeList1==null){ // List<SystemMenu> treeList2 = new ArrayList<SystemMenu>(); // try { // SystemMenu sm=ClientImpl.getResoucer(principal.toString()); // treeList2.add(sm); // session.setAttribute("treeList", treeList2); // return treeList2; // } catch (Exception e) { // System.out.println("链接webservice服务器失败:"+e); // // } // } // return treeList1; // // } // @RequestMapping(value = "/organization") // @ResponseBody // public List<TreeNodeList> getOrganization() { // Subject subject = SecurityUtils.getSubject(); // Object principal = subject.getPrincipal();//获取用户登录信息 // Session session=subject.getSession(); // String orgIds =""; // List<TreeNodeList> orgaTree=(List<TreeNodeList>)session.getAttribute("orgaTree"); // if(orgaTree==null){ // try { // orgaTree=ClientImpl.getOrganization(principal.toString()); // session.setAttribute("orgaTree", orgaTree); // //拼所有节点字符串 // if(orgaTree.size()>0){ // orgIds = findChildred(orgaTree,orgIds); // } // session.setAttribute("orgIds", orgIds.substring(0,orgIds.length()-1)); //将字符串放入session // return orgaTree; // } catch (Exception e) { // System.out.println("链接webservice服务器失败:"+e); // return null; // } // } // //拼所有节点字符串 // if(orgaTree.size()>0){ // orgIds = findChildred(orgaTree,orgIds); // } // session.setAttribute("orgIds", orgIds.substring(0,orgIds.length()-1)); //将字符串放入session // return orgaTree; // // } // @RequestMapping(value = "/userOrganization") // @ResponseBody // public List<Organization> getUserOrganization() { // Subject subject = SecurityUtils.getSubject(); // Object principal = subject.getPrincipal();//获取用户登录信息 // Session session=subject.getSession(); // List<Organization> uo1=(List<Organization>)session.getAttribute("uo"); // if(uo1==null){ // try { // List<Organization> uo2=ClientImpl.getUserOrganization(principal.toString()); // session.setAttribute("uo", uo2); // return uo2; // } catch (Exception e) { // System.out.println("链接webservice服务器失败:"+e); // } // } // return uo1; // // } /** * * Function:检查webservice是否启动 * * @author zjf DateTime 2015-1-31 上午9:09:21 * @return */ // @RequestMapping(value = "/checkWeb") // @ResponseBody // public String checkWebservicIsOk(){ // Subject subject = SecurityUtils.getSubject(); // Object principal = subject.getPrincipal();//获取用户登录信息 // try { // ClientImpl.getUserOrganization(principal.toString()); // } catch (Exception e) { // System.out.println("链接webservice服务器失败:"+e); // return "fail"; // } // return "ok"; // } /** * 拼权限字符串 * Function: * * @author gxl DateTime 2015-2-6 上午9:38:48 * @param nodeList * @param ids * @return */ public String findChildred(List<TreeNodeList> nodeList,String ids){ for(int i=0;i<nodeList.size();i++){ TreeNodeList node = nodeList.get(i); ids = ids + "'"+node.getId()+"',"; if(node.getChildren()!=null){ if(node.getChildren().size()>0){ ids = findChildred(node.getChildren(),ids); } } } return ids; } }
package eseo.techerguillaume.android.ui.scan.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; import eseo.techerguillaume.android.R; import eseo.techerguillaume.android.remote.LedStatus; /** * Created by techergu on 16/01/2019. */ public class LedAdapter extends ArrayAdapter<LedStatus> { public LedAdapter(Context context, ArrayList<LedStatus> ledStatuses) { super(context, 0, ledStatuses); } @Override public View getView(int position, View convertView, ViewGroup parent) { // Get the data item for this position LedStatus ledStatus = getItem(position); // Check if an existing view is being reused, otherwise inflate the view if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.led , parent, false); } // Lookup view for data population TextView ledIdentifier = (TextView) convertView.findViewById(R.id.identifier); ImageView statusImage = (ImageView) convertView.findViewById(R.id.status); // Populate the data into the template view using the data object ledIdentifier.setText(ledStatus.getIdentifier()); if (ledStatus.getStatus()){ statusImage.setVisibility(View.VISIBLE); }else{ statusImage.setVisibility(View.INVISIBLE); } // Return the completed view to render on screen return convertView; } }
package com.sx.service.impl; import org.springframework.stereotype.Service; import com.sx.service.AdminService; @Service public class AdminServiceImpl implements AdminService { }
import java.io.*; import java.security.*; import java.security.spec.InvalidParameterSpecException; import javax.crypto.*; import javax.crypto.spec.*; public class SessionEncrypter { private static String Algorithm_type1 = "AES"; private static String Algorithm_type2 = "AES/CTR/PKCS5Padding"; public SecretKey sessionkey; public Cipher cipher = null; public byte[] IV_byte = null; public SessionEncrypter(Integer keylength) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidParameterSpecException { KeyGenerator generator; generator = KeyGenerator.getInstance(Algorithm_type1); generator.init(keylength); this.sessionkey = generator.generateKey(); this.cipher = Cipher.getInstance(Algorithm_type2); this.cipher.init(Cipher.ENCRYPT_MODE, this.sessionkey); this.IV_byte = this.cipher.getParameters().getParameterSpec(IvParameterSpec.class).getIV(); } public SessionEncrypter(byte[] keybytes, byte[] ivbytes) throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchPaddingException { this.sessionkey = new SecretKeySpec(keybytes,Algorithm_type1); this.IV_byte = ivbytes; this.cipher = Cipher.getInstance(Algorithm_type2); this.cipher.init(Cipher.ENCRYPT_MODE, this.sessionkey, new IvParameterSpec(ivbytes)); } public CipherOutputStream openCipherOutputStream(OutputStream output) { return new CipherOutputStream(output,this.cipher); } public byte[] getKeyBytes() { return this.sessionkey.getEncoded(); } public byte[] getIVBytes() { return this.IV_byte; } }
package com.sixmac.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; /** * Created by Administrator on 2016/5/24 0024. */ @Entity @Table(name = "t_system_insurance") public class SysInsurance extends BaseEntity{ @Column(name = "name") private String name; @Column(name = "price") private Double price; @Column(name = "status") private Integer status; @Column(name = "content") private String content; public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
package com.hjtech.base.app; import android.app.Application; import android.content.Context; import com.alibaba.android.arouter.facade.annotation.Autowired; import com.alibaba.android.arouter.launcher.ARouter; import com.hjtech.base.router.mannager.IModelManager; import com.hjtech.base.router.provider.IDetectProvider; import com.hjtech.base.router.provider.IHomeProvider; import com.hjtech.base.router.provider.IStatisticsProvider; import com.hjtech.base.router.provider.IUserProvider; import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator; import com.nostra13.universalimageloader.cache.memory.impl.UsingFreqLimitedMemoryCache; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.nostra13.universalimageloader.core.assist.QueueProcessingType; import com.nostra13.universalimageloader.core.download.BaseImageDownloader; import com.squareup.leakcanary.LeakCanary; /* * 项目名: HjtechARouterFrame * 包名 com.hjtech.base.app * 文件名: MyApp * 创建者: ZJB * 创建时间: 2017/10/26 on 15:03 * 描述: TODO */ public class MyApp extends Application implements App { @Autowired IModelManager iModelManager; private static MyApp application; @Override public void onCreate() { super.onCreate(); application = this; // initARouter(); LeakCanary.install(this); initImageLoader(this); } public static MyApp getApplication() { return application; } public IModelManager getModelManager() { return iModelManager; } @Override public void initARouter() { ARouter.openLog(); // 打印日志 ARouter.openDebug(); // 开启调试模式(如果在InstantRun模式下运行,必须开启调试模式!线上版本需要关闭,否则有安全风险) ARouter.init(this); // 尽可能早,推荐在Application中初始化 ARouter.getInstance().inject(this); //将需要使用的模块添加进管理 iModelManager.addModel(IHomeProvider.HOME_LOGIN, IHomeProvider.HOME_LOGIN); } // 图片框架初始化 public static void initImageLoader(Context context) { ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder( context) // .memoryCacheExtraOptions(480, 800) // max width, max // height,即保存的每个缓存文件的最大长宽 .threadPoolSize(3) // 线程池内加载的数量 .threadPriority(Thread.NORM_PRIORITY - 1) .denyCacheImageMultipleSizesInMemory() .diskCacheFileNameGenerator(new Md5FileNameGenerator()) // 将保存的时候的URI名称用MD5 // 加密 .memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024)) // You // can // pass // your // own // memory // cache // implementation/你可以通过自己的内存缓存实现 .memoryCacheSize(50 * 1024 * 1024) // 内存缓存的最大值 .diskCacheSize(50 * 1024 * 1024) // 50 Mb sd卡(本地)缓存的最大值 .tasksProcessingOrder(QueueProcessingType.LIFO) // 由原先的discCache -> diskCache .imageDownloader( new BaseImageDownloader(context, 5 * 1000, 30 * 1000)) // connectTimeout // (5 // s), // readTimeout // (30 // s)超时时间 .writeDebugLogs() // Remove for release app .build(); // 全局初始化此配置 ImageLoader.getInstance().init(config); } }
package com.rc.portal.vo; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import com.rc.app.framework.webapp.model.BaseModel; public class TLongExample extends BaseModel{ protected String orderByClause; protected List oredCriteria; public TLongExample() { oredCriteria = new ArrayList(); } protected TLongExample(TLongExample example) { this.orderByClause = example.orderByClause; this.oredCriteria = example.oredCriteria; } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public List getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); } public static class Criteria { protected List criteriaWithoutValue; protected List criteriaWithSingleValue; protected List criteriaWithListValue; protected List criteriaWithBetweenValue; protected Criteria() { super(); criteriaWithoutValue = new ArrayList(); criteriaWithSingleValue = new ArrayList(); criteriaWithListValue = new ArrayList(); criteriaWithBetweenValue = new ArrayList(); } public boolean isValid() { return criteriaWithoutValue.size() > 0 || criteriaWithSingleValue.size() > 0 || criteriaWithListValue.size() > 0 || criteriaWithBetweenValue.size() > 0; } public List getCriteriaWithoutValue() { return criteriaWithoutValue; } public List getCriteriaWithSingleValue() { return criteriaWithSingleValue; } public List getCriteriaWithListValue() { return criteriaWithListValue; } public List getCriteriaWithBetweenValue() { return criteriaWithBetweenValue; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteriaWithoutValue.add(condition); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } Map map = new HashMap(); map.put("condition", condition); map.put("value", value); criteriaWithSingleValue.add(map); } protected void addCriterion(String condition, List values, String property) { if (values == null || values.size() == 0) { throw new RuntimeException("Value list for " + property + " cannot be null or empty"); } Map map = new HashMap(); map.put("condition", condition); map.put("values", values); criteriaWithListValue.add(map); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } List list = new ArrayList(); list.add(value1); list.add(value2); Map map = new HashMap(); map.put("condition", condition); map.put("values", list); criteriaWithBetweenValue.add(map); } public Criteria andIdIsNull() { addCriterion("id is null"); return this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return this; } public Criteria andIdEqualTo(Long value) { addCriterion("id =", value, "id"); return this; } public Criteria andIdNotEqualTo(Long value) { addCriterion("id <>", value, "id"); return this; } public Criteria andIdGreaterThan(Long value) { addCriterion("id >", value, "id"); return this; } public Criteria andIdGreaterThanOrEqualTo(Long value) { addCriterion("id >=", value, "id"); return this; } public Criteria andIdLessThan(Long value) { addCriterion("id <", value, "id"); return this; } public Criteria andIdLessThanOrEqualTo(Long value) { addCriterion("id <=", value, "id"); return this; } public Criteria andIdIn(List values) { addCriterion("id in", values, "id"); return this; } public Criteria andIdNotIn(List values) { addCriterion("id not in", values, "id"); return this; } public Criteria andIdBetween(Long value1, Long value2) { addCriterion("id between", value1, value2, "id"); return this; } public Criteria andIdNotBetween(Long value1, Long value2) { addCriterion("id not between", value1, value2, "id"); return this; } public Criteria andNameIsNull() { addCriterion("name is null"); return this; } public Criteria andNameIsNotNull() { addCriterion("name is not null"); return this; } public Criteria andNameEqualTo(String value) { addCriterion("name =", value, "name"); return this; } public Criteria andNameNotEqualTo(String value) { addCriterion("name <>", value, "name"); return this; } public Criteria andNameGreaterThan(String value) { addCriterion("name >", value, "name"); return this; } public Criteria andNameGreaterThanOrEqualTo(String value) { addCriterion("name >=", value, "name"); return this; } public Criteria andNameLessThan(String value) { addCriterion("name <", value, "name"); return this; } public Criteria andNameLessThanOrEqualTo(String value) { addCriterion("name <=", value, "name"); return this; } public Criteria andNameLike(String value) { addCriterion("name like", value, "name"); return this; } public Criteria andNameNotLike(String value) { addCriterion("name not like", value, "name"); return this; } public Criteria andNameIn(List values) { addCriterion("name in", values, "name"); return this; } public Criteria andNameNotIn(List values) { addCriterion("name not in", values, "name"); return this; } public Criteria andNameBetween(String value1, String value2) { addCriterion("name between", value1, value2, "name"); return this; } public Criteria andNameNotBetween(String value1, String value2) { addCriterion("name not between", value1, value2, "name"); return this; } public Criteria andRuleIsNull() { addCriterion("rule is null"); return this; } public Criteria andRuleIsNotNull() { addCriterion("rule is not null"); return this; } public Criteria andRuleEqualTo(String value) { addCriterion("rule =", value, "rule"); return this; } public Criteria andRuleNotEqualTo(String value) { addCriterion("rule <>", value, "rule"); return this; } public Criteria andRuleGreaterThan(String value) { addCriterion("rule >", value, "rule"); return this; } public Criteria andRuleGreaterThanOrEqualTo(String value) { addCriterion("rule >=", value, "rule"); return this; } public Criteria andRuleLessThan(String value) { addCriterion("rule <", value, "rule"); return this; } public Criteria andRuleLessThanOrEqualTo(String value) { addCriterion("rule <=", value, "rule"); return this; } public Criteria andRuleLike(String value) { addCriterion("rule like", value, "rule"); return this; } public Criteria andRuleNotLike(String value) { addCriterion("rule not like", value, "rule"); return this; } public Criteria andRuleIn(List values) { addCriterion("rule in", values, "rule"); return this; } public Criteria andRuleNotIn(List values) { addCriterion("rule not in", values, "rule"); return this; } public Criteria andRuleBetween(String value1, String value2) { addCriterion("rule between", value1, value2, "rule"); return this; } public Criteria andRuleNotBetween(String value1, String value2) { addCriterion("rule not between", value1, value2, "rule"); return this; } public Criteria andAmountIsNull() { addCriterion("amount is null"); return this; } public Criteria andAmountIsNotNull() { addCriterion("amount is not null"); return this; } public Criteria andAmountEqualTo(BigDecimal value) { addCriterion("amount =", value, "amount"); return this; } public Criteria andAmountNotEqualTo(BigDecimal value) { addCriterion("amount <>", value, "amount"); return this; } public Criteria andAmountGreaterThan(BigDecimal value) { addCriterion("amount >", value, "amount"); return this; } public Criteria andAmountGreaterThanOrEqualTo(BigDecimal value) { addCriterion("amount >=", value, "amount"); return this; } public Criteria andAmountLessThan(BigDecimal value) { addCriterion("amount <", value, "amount"); return this; } public Criteria andAmountLessThanOrEqualTo(BigDecimal value) { addCriterion("amount <=", value, "amount"); return this; } public Criteria andAmountIn(List values) { addCriterion("amount in", values, "amount"); return this; } public Criteria andAmountNotIn(List values) { addCriterion("amount not in", values, "amount"); return this; } public Criteria andAmountBetween(BigDecimal value1, BigDecimal value2) { addCriterion("amount between", value1, value2, "amount"); return this; } public Criteria andAmountNotBetween(BigDecimal value1, BigDecimal value2) { addCriterion("amount not between", value1, value2, "amount"); return this; } public Criteria andStartTimeIsNull() { addCriterion("start_time is null"); return this; } public Criteria andStartTimeIsNotNull() { addCriterion("start_time is not null"); return this; } public Criteria andStartTimeEqualTo(Date value) { addCriterion("start_time =", value, "startTime"); return this; } public Criteria andStartTimeNotEqualTo(Date value) { addCriterion("start_time <>", value, "startTime"); return this; } public Criteria andStartTimeGreaterThan(Date value) { addCriterion("start_time >", value, "startTime"); return this; } public Criteria andStartTimeGreaterThanOrEqualTo(Date value) { addCriterion("start_time >=", value, "startTime"); return this; } public Criteria andStartTimeLessThan(Date value) { addCriterion("start_time <", value, "startTime"); return this; } public Criteria andStartTimeLessThanOrEqualTo(Date value) { addCriterion("start_time <=", value, "startTime"); return this; } public Criteria andStartTimeIn(List values) { addCriterion("start_time in", values, "startTime"); return this; } public Criteria andStartTimeNotIn(List values) { addCriterion("start_time not in", values, "startTime"); return this; } public Criteria andStartTimeBetween(Date value1, Date value2) { addCriterion("start_time between", value1, value2, "startTime"); return this; } public Criteria andStartTimeNotBetween(Date value1, Date value2) { addCriterion("start_time not between", value1, value2, "startTime"); return this; } public Criteria andEndTimeIsNull() { addCriterion("end_time is null"); return this; } public Criteria andEndTimeIsNotNull() { addCriterion("end_time is not null"); return this; } public Criteria andEndTimeEqualTo(Date value) { addCriterion("end_time =", value, "endTime"); return this; } public Criteria andEndTimeNotEqualTo(Date value) { addCriterion("end_time <>", value, "endTime"); return this; } public Criteria andEndTimeGreaterThan(Date value) { addCriterion("end_time >", value, "endTime"); return this; } public Criteria andEndTimeGreaterThanOrEqualTo(Date value) { addCriterion("end_time >=", value, "endTime"); return this; } public Criteria andEndTimeLessThan(Date value) { addCriterion("end_time <", value, "endTime"); return this; } public Criteria andEndTimeLessThanOrEqualTo(Date value) { addCriterion("end_time <=", value, "endTime"); return this; } public Criteria andEndTimeIn(List values) { addCriterion("end_time in", values, "endTime"); return this; } public Criteria andEndTimeNotIn(List values) { addCriterion("end_time not in", values, "endTime"); return this; } public Criteria andEndTimeBetween(Date value1, Date value2) { addCriterion("end_time between", value1, value2, "endTime"); return this; } public Criteria andEndTimeNotBetween(Date value1, Date value2) { addCriterion("end_time not between", value1, value2, "endTime"); return this; } public Criteria andQuantityIsNull() { addCriterion("quantity is null"); return this; } public Criteria andQuantityIsNotNull() { addCriterion("quantity is not null"); return this; } public Criteria andQuantityEqualTo(Integer value) { addCriterion("quantity =", value, "quantity"); return this; } public Criteria andQuantityNotEqualTo(Integer value) { addCriterion("quantity <>", value, "quantity"); return this; } public Criteria andQuantityGreaterThan(Integer value) { addCriterion("quantity >", value, "quantity"); return this; } public Criteria andQuantityGreaterThanOrEqualTo(Integer value) { addCriterion("quantity >=", value, "quantity"); return this; } public Criteria andQuantityLessThan(Integer value) { addCriterion("quantity <", value, "quantity"); return this; } public Criteria andQuantityLessThanOrEqualTo(Integer value) { addCriterion("quantity <=", value, "quantity"); return this; } public Criteria andQuantityIn(List values) { addCriterion("quantity in", values, "quantity"); return this; } public Criteria andQuantityNotIn(List values) { addCriterion("quantity not in", values, "quantity"); return this; } public Criteria andQuantityBetween(Integer value1, Integer value2) { addCriterion("quantity between", value1, value2, "quantity"); return this; } public Criteria andQuantityNotBetween(Integer value1, Integer value2) { addCriterion("quantity not between", value1, value2, "quantity"); return this; } public Criteria andStatusIsNull() { addCriterion("status is null"); return this; } public Criteria andStatusIsNotNull() { addCriterion("status is not null"); return this; } public Criteria andStatusEqualTo(Integer value) { addCriterion("status =", value, "status"); return this; } public Criteria andStatusNotEqualTo(Integer value) { addCriterion("status <>", value, "status"); return this; } public Criteria andStatusGreaterThan(Integer value) { addCriterion("status >", value, "status"); return this; } public Criteria andStatusGreaterThanOrEqualTo(Integer value) { addCriterion("status >=", value, "status"); return this; } public Criteria andStatusLessThan(Integer value) { addCriterion("status <", value, "status"); return this; } public Criteria andStatusLessThanOrEqualTo(Integer value) { addCriterion("status <=", value, "status"); return this; } public Criteria andStatusIn(List values) { addCriterion("status in", values, "status"); return this; } public Criteria andStatusNotIn(List values) { addCriterion("status not in", values, "status"); return this; } public Criteria andStatusBetween(Integer value1, Integer value2) { addCriterion("status between", value1, value2, "status"); return this; } public Criteria andStatusNotBetween(Integer value1, Integer value2) { addCriterion("status not between", value1, value2, "status"); return this; } public Criteria andCreateTimeIsNull() { addCriterion("create_time is null"); return this; } public Criteria andCreateTimeIsNotNull() { addCriterion("create_time is not null"); return this; } public Criteria andCreateTimeEqualTo(Date value) { addCriterion("create_time =", value, "createTime"); return this; } public Criteria andCreateTimeNotEqualTo(Date value) { addCriterion("create_time <>", value, "createTime"); return this; } public Criteria andCreateTimeGreaterThan(Date value) { addCriterion("create_time >", value, "createTime"); return this; } public Criteria andCreateTimeGreaterThanOrEqualTo(Date value) { addCriterion("create_time >=", value, "createTime"); return this; } public Criteria andCreateTimeLessThan(Date value) { addCriterion("create_time <", value, "createTime"); return this; } public Criteria andCreateTimeLessThanOrEqualTo(Date value) { addCriterion("create_time <=", value, "createTime"); return this; } public Criteria andCreateTimeIn(List values) { addCriterion("create_time in", values, "createTime"); return this; } public Criteria andCreateTimeNotIn(List values) { addCriterion("create_time not in", values, "createTime"); return this; } public Criteria andCreateTimeBetween(Date value1, Date value2) { addCriterion("create_time between", value1, value2, "createTime"); return this; } public Criteria andCreateTimeNotBetween(Date value1, Date value2) { addCriterion("create_time not between", value1, value2, "createTime"); return this; } public Criteria andInstroIsNull() { addCriterion("instro is null"); return this; } public Criteria andInstroIsNotNull() { addCriterion("instro is not null"); return this; } public Criteria andInstroEqualTo(String value) { addCriterion("instro =", value, "instro"); return this; } public Criteria andInstroNotEqualTo(String value) { addCriterion("instro <>", value, "instro"); return this; } public Criteria andInstroGreaterThan(String value) { addCriterion("instro >", value, "instro"); return this; } public Criteria andInstroGreaterThanOrEqualTo(String value) { addCriterion("instro >=", value, "instro"); return this; } public Criteria andInstroLessThan(String value) { addCriterion("instro <", value, "instro"); return this; } public Criteria andInstroLessThanOrEqualTo(String value) { addCriterion("instro <=", value, "instro"); return this; } public Criteria andInstroLike(String value) { addCriterion("instro like", value, "instro"); return this; } public Criteria andInstroNotLike(String value) { addCriterion("instro not like", value, "instro"); return this; } public Criteria andInstroIn(List values) { addCriterion("instro in", values, "instro"); return this; } public Criteria andInstroNotIn(List values) { addCriterion("instro not in", values, "instro"); return this; } public Criteria andInstroBetween(String value1, String value2) { addCriterion("instro between", value1, value2, "instro"); return this; } public Criteria andInstroNotBetween(String value1, String value2) { addCriterion("instro not between", value1, value2, "instro"); return this; } } }
package com.pangpang6.books.concurrent; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * Created by jiangjiguang on 2018/2/6. */ public class ThreadPoolExecutorTest { ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 6, 5, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>()); Runnable myRunnable = new Runnable() { @Override public void run() { try { Thread.sleep(2000); System.out.println(Thread.currentThread().getName() + " run"); } catch (InterruptedException e) { e.printStackTrace(); } } }; }
package com.MQ.www; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class TwitterLoginTest { public static void main(String[] args) { WebDriver driver=new ChromeDriver(); driver.manage().window().maximize(); driver.get("https://twitter.com/login"); driver.findElement(By.name("session[username_or_email]")).sendKeys("venkatareddy65852@gmail.com"); driver.findElement(By.name("session[password]")).sendKeys("Venkat@123"); } }
package unalcol.agents.search.classic; import unalcol.sort.Order; /** * <p>Title: </p> * <p> * <p>Description: </p> * <p> * <p>Copyright: Copyright (c) 2007</p> * <p> * <p>Company: Universidad Nacional de Colombia</p> * * @author Jonatan Gómez * @version 1.0 */ public class ClassicSearchNodeOrder extends Order<ClassicSearchNode> { public ClassicSearchNodeOrder() { } public String getCanonicalName() { return ClassicSearchNode.class.getCanonicalName(); } public int compare(ClassicSearchNode one, ClassicSearchNode two) { return (int) (one.cost - two.cost); } }
package com.example.asmaa.almoon.view.activity; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.example.asmaa.almoon.R; import com.example.asmaa.almoon.presenter.SignUpActivityPresenter; import java.util.regex.Pattern; public class SignUpActivity extends AppCompatActivity implements ISignUpActivityView { SignUpActivityPresenter mSignUpActivityPresenter; TextView tv_login; EditText ed_email,ed_fname,ed_lname,ed_phone,ed_code,ed_password,ed_conPass; Button btn_signUp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sign_up); tv_login=(TextView)findViewById(R.id.tv_login); ed_email=(EditText)findViewById(R.id.ed_email); ed_fname=(EditText)findViewById(R.id.ed_fname); ed_password=(EditText)findViewById(R.id.ed_password); ed_conPass=(EditText)findViewById(R.id.ed_confirmPassword); ed_lname=(EditText)findViewById(R.id.ed_lname); ed_code=(EditText)findViewById(R.id.ed_code); ed_phone=(EditText)findViewById(R.id.ed_phone); btn_signUp=(Button)findViewById(R.id.btn_signUp); mSignUpActivityPresenter=new SignUpActivityPresenter(this,this); btn_signUp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(ed_fname.length()==0){ ed_fname.setError("Required Field!"); ed_fname.setFocusable(true);} else if(!(Pattern.matches("^[\\p{L} .'-]+$", ed_fname.getText().toString()))){ ed_fname.setError("Allow only spaces and letters"); ed_fname.setFocusable(true);} if(ed_lname.length()==0){ ed_lname.setError("Required Field!"); ed_lname.setFocusable(true);} else if(!(Pattern.matches("^[\\p{L} .'-]+$", ed_lname.getText().toString()))){ ed_lname.setError("Allow only spaces and letters"); ed_lname.setFocusable(true);} if (ed_email.length() == 0){ ed_email.setError("Required Field!"); ed_email.setFocusable(true);} else if(!(isValidEmail(ed_email.getText().toString()))){ ed_email.setError("Invalid Email Address"); ed_email.setFocusable(true);} if(ed_phone.length() == 0){ ed_phone.setError("Required Field!"); ed_phone.setFocusable(true);} else if(ed_phone.length() != 11 || !(ed_phone.getText().toString().startsWith("01")) || !(isValidCellPhone(ed_phone.getText().toString()))){ ed_phone.setError("Incorrect Phone Number"); ed_phone.setFocusable(true);} if(ed_password.length()==0){ ed_password.setError("Required Field!"); ed_password.setFocusable(true);} else if(ed_password.length() < 8) { ed_password.setError("Minimum 8 digits"); ed_password.setFocusable(true);} if(ed_conPass.length()==0){ed_conPass.setError("Required Field!");} else if(!(ed_conPass.getText().toString().equals(ed_password.getText().toString()))){ ed_conPass.setError("Not Matched"); } if((ed_fname.length()!=0)&&(Pattern.matches("^[\\p{L} .'-]+$", ed_fname.getText().toString()))&& (ed_lname.length()!=0)&&(Pattern.matches("^[\\p{L} .'-]+$", ed_lname.getText().toString()))&& (ed_email.length() != 0)&&(isValidEmail(ed_email.getText().toString()))&& (ed_phone.length() != 0)&&(ed_phone.length()==11)&&(ed_phone.getText().toString().startsWith("01"))&& (isValidCellPhone(ed_phone.getText().toString()))&&(ed_password.length()!=0)&&(ed_password.length() >= 8)&& (ed_password.getText().toString().equals(ed_conPass.getText().toString()))) { //calling registration function mSignUpActivityPresenter.signUp(); } else { Toast.makeText(SignUpActivity.this, "Unable to register", Toast.LENGTH_SHORT).show();} } }); tv_login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent=new Intent(SignUpActivity.this,LoginActivity.class); startActivity(intent); } }); } @Override public String getFname() { return ed_fname.getText().toString(); } @Override public String getLname() { return ed_lname.getText().toString(); } @Override public String getPassword() { return ed_password.getText().toString(); } @Override public String getConPass() { return ed_conPass.getText().toString(); } @Override public String getCode() { return ed_code.getText().toString(); } @Override public String getPhone() { return ed_phone.getText().toString(); } @Override public String getEmail() { return ed_email.getText().toString(); } @Override public boolean isValidEmail(CharSequence target) { return !TextUtils.isEmpty(target) && android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();} @Override public boolean isValidCellPhone(String number) { return android.util.Patterns.PHONE.matcher(number).matches();} }
package com.lbconsulting.alist_02.adapters; import android.content.Context; import android.database.Cursor; import android.graphics.Paint; import android.graphics.Typeface; import android.support.v4.widget.CursorAdapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.lbconsulting.alist_02.R; import com.lbconsulting.alist_02.database.CategoriesTable; import com.lbconsulting.alist_02.database.ListsTable; import com.lbconsulting.alist_02.database.MasterListItemsTable; public class ListsCursorAdapter extends CursorAdapter { public Context context; private boolean colorsSet = false; private int backgroundColor; private int normalTextColor; private int strikeoutTextColor; private boolean showCategories = false; public ListsCursorAdapter(Context context, Cursor c, int flags) { super(context, c, flags); this.context = context; } @Override public void bindView(View view, Context context, final Cursor cursor) { TextView txtListItemName = (TextView) view.findViewById(R.id.txtListItemName); txtListItemName.setBackgroundColor(this.backgroundColor); txtListItemName.setText(cursor.getString(cursor.getColumnIndex(MasterListItemsTable.COL_ITEM_NAME))); int isStruckOut = cursor.getInt(cursor.getColumnIndex(ListsTable.COL_STRUCK_OUT)); if (isStruckOut > 0) { // item has been struck out txtListItemName.setTypeface(null, Typeface.ITALIC); txtListItemName.setTextColor(this.strikeoutTextColor); txtListItemName.setPaintFlags(txtListItemName.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); } else { // item is NOT struck out txtListItemName.setTypeface(null, Typeface.NORMAL); txtListItemName.setTextColor(this.normalTextColor); txtListItemName.setPaintFlags(txtListItemName.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG)); } TextView txtListItemCategory = (TextView) view.findViewById(R.id.txtListItemCategory); if (this.showCategories) { txtListItemCategory.setVisibility(View.VISIBLE); txtListItemCategory.setBackgroundColor(this.backgroundColor); String categoryText = "(" + cursor.getString(cursor.getColumnIndex(CategoriesTable.COL_CATEGORY_NAME)) + ")"; String defalutCategoryValue = context.getResources().getString(R.string.defalutCategoryValue); if (categoryText.startsWith("([")) { categoryText = "(" + defalutCategoryValue.substring(1, defalutCategoryValue.length() - 1) + ")"; } txtListItemCategory.setText(categoryText); txtListItemCategory.setTypeface(null, Typeface.ITALIC); if (isStruckOut > 0) { // item has been struck out txtListItemCategory.setTextColor(this.strikeoutTextColor); //txtListItemCategory.setPaintFlags(txtListItemName.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); } else { // item is NOT struck out //txtListItemCategory.setTextColor(this.normalTextColor); txtListItemCategory.setTextColor(this.strikeoutTextColor); } } else { txtListItemCategory.setVisibility(View.GONE); } } @Override public View newView(Context c, Cursor cursor, ViewGroup parent) { LayoutInflater inflater = LayoutInflater.from(c); View v = inflater.inflate(R.layout.list_items_row, parent, false); bindView(v, c, cursor); return v; } public void setColors(int backgroundColor, int normalTextColor, int strikeoutTextColor) { this.backgroundColor = backgroundColor; this.normalTextColor = normalTextColor; this.strikeoutTextColor = strikeoutTextColor; this.colorsSet = true; } public void setShowCategories(boolean showCategoriesValue) { this.showCategories = showCategoriesValue; } }
package com.esprit.lyricsplus; import android.content.Context; import android.media.MediaPlayer; import android.media.MediaRecorder; import android.net.ConnectivityManager; import android.os.Bundle; import android.os.Environment; import android.os.Vibrator; import android.text.Html; import android.util.Base64; import android.util.Log; import android.view.View; import android.view.WindowManager; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.esprit.lyricsplus.DAO.RecordDAO; import com.esprit.lyricsplus.entities.Song; import com.esprit.lyricsplus.entities.User; import com.skyfishjy.library.RippleBackground; import org.apache.commons.io.IOUtils; import java.io.File; import java.io.IOException; import java.io.InputStream; import cn.pedant.SweetAlert.SweetAlertDialog; public class AudioOnTouchActivity extends HomeActivity2 { private static final String LOG_TAG = "AudioRecordTest"; private static String mFileName = null; private static LinearLayout FileLayout; private static Animation shakeAnimation; String encoded; boolean deleted ; User user ; Song song ; TextView mRecordButton ,mPlayButton ,addLyrics , tv_lyrics , reset; EditText fileName,lyrics ; RippleBackground rippleBackground ; LinearLayout linear_add ; boolean mStartRecording = true; boolean mStartPlaying = false; private MediaRecorder mRecorder = null; private MediaPlayer mPlayer = null; private void onRecord(boolean start) { if (start) { startRecording(); } else { stopRecording(); } } private void onPlay(boolean start) { if (start) { startPlaying(); } else { stopPlaying(); } } private void startPlaying() { mPlayer = new MediaPlayer(); try { mPlayer.setDataSource(mFileName); mPlayer.prepare(); mPlayer.start(); } catch (IOException e) { Log.e(LOG_TAG, "prepare() failed"); } } private void stopPlaying() { mPlayer.release(); mPlayer = null; } private void startRecording() { mRecorder = new MediaRecorder(); mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); mRecorder.setOutputFile(mFileName); mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); try { mRecorder.prepare(); } catch (IOException e) { Log.e(LOG_TAG, "prepare() failed"); } mRecorder.start(); } private void stopRecording() { mRecorder.stop(); mRecorder.release(); mRecorder = null; } @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); FrameLayout contentFrameLayout = (FrameLayout) findViewById(R.id.content_frame); getLayoutInflater().inflate(R.layout.activity_audio_on_touch, contentFrameLayout); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); user = (User) getIntent().getSerializableExtra("user"); song = (Song) getIntent().getSerializableExtra("song"); FileLayout = (LinearLayout) findViewById(R.id.ontouch); linear_add = (LinearLayout) findViewById(R.id.linear_add); final RecordDAO recordDAO = new RecordDAO() ; shakeAnimation = AnimationUtils.loadAnimation(this, R.anim.shake); mRecordButton = (TextView) findViewById(R.id.record_btn); mPlayButton = (TextView) findViewById(R.id.start_btn); addLyrics = (TextView) findViewById(R.id.submit_btn); reset = (TextView) findViewById(R.id.reset); tv_lyrics = (TextView) findViewById(R.id.tv_lyrics); fileName = (EditText) findViewById(R.id.filename); lyrics = (EditText) findViewById(R.id.et_lyrics); if(song!=null) { tv_lyrics.setVisibility(View.VISIBLE); fileName.setText(song.getTitle()); tv_lyrics.setText(Html.fromHtml(song.getLyrics())); fileName.setEnabled(false); lyrics.setVisibility(View.INVISIBLE); } else { tv_lyrics.setVisibility(View.INVISIBLE); lyrics.setVisibility(View.VISIBLE); } rippleBackground=(RippleBackground)findViewById(R.id.content); mRecordButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(fileName.getText().toString().equals("")) { checkValidation(v); } else { mFileName = Environment.getExternalStorageDirectory().getAbsolutePath(); mFileName += "/"+fileName.getText().toString()+".mp3"; if (mStartRecording) { onRecord(mStartRecording); rippleBackground.startRippleAnimation(); mStartPlaying= false ; mStartRecording=false ; mRecordButton.setText("Stop recording"); Toast.makeText(AudioOnTouchActivity.this,"Start Recording !", Toast.LENGTH_SHORT).show(); } else if(mRecorder!=null && !mStartRecording) { onRecord(mStartRecording); rippleBackground.stopRippleAnimation(); linear_add.setVisibility(View.VISIBLE); reset.setVisibility(View.VISIBLE); mRecordButton.setText("Start recording"); mStartRecording =true ; Toast.makeText(AudioOnTouchActivity.this,"Recording Stopped ! file saved in "+mFileName, Toast.LENGTH_SHORT).show(); mStartPlaying=true ; try { File file = new File(mFileName); byte[] bytes =FileUtils.readFileToByteArray(file); encoded = Base64.encodeToString(bytes, 0); } catch (IOException e) { e.printStackTrace(); } } } } }); mPlayButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (fileName.getText().toString().equals("")) { checkValidation(v); } else { if (mStartPlaying) { onPlay(mStartPlaying); mStartPlaying=false ; Toast.makeText(AudioOnTouchActivity.this,"Start Playing !", Toast.LENGTH_SHORT).show(); mPlayButton.setText("Stop playing"); mRecordButton.setEnabled(false); } else if(mPlayer!=null && !mStartPlaying){ onPlay(mStartPlaying); mStartPlaying= true ; Toast.makeText(AudioOnTouchActivity.this,"Stop Playing !", Toast.LENGTH_SHORT).show(); mPlayButton.setText("Start playing"); mRecordButton.setEnabled(true); } } } }); addLyrics.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(isOnline()) { if (song == null) { if (fileName.getText().toString().equals("") || lyrics.getText().toString().equals("")) { checkValidation(v); } else { new SweetAlertDialog(AudioOnTouchActivity.this.getWindow().getContext(), SweetAlertDialog.WARNING_TYPE) .setTitleText("Are you sure?") .setContentText("Won't be able to change your record!") .setConfirmText("Yes,add it!") .setCancelText("No,cancel plz!") .showCancelButton(true) .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() { @Override public void onClick(SweetAlertDialog sDialog) { sDialog .setTitleText("Added") .setContentText("Your information are added!") .setConfirmText("OK") .setConfirmClickListener(null) .changeAlertType(SweetAlertDialog.SUCCESS_TYPE); recordDAO.insertRecord(user, fileName.getText().toString(), mFileName, lyrics.getText().toString(),encoded); } }) .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() { @Override public void onClick(SweetAlertDialog sDialog) { sDialog.cancel(); } }) .show(); } } else { new SweetAlertDialog(AudioOnTouchActivity.this.getWindow().getContext(), SweetAlertDialog.WARNING_TYPE) .setTitleText("Are you sure?") .setContentText("Won't be able to change your record!") .setConfirmText("Yes,add it!") .setCancelText("No,cancel plz!") .showCancelButton(true) .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() { @Override public void onClick(SweetAlertDialog sDialog) { sDialog .setTitleText("Added") .setContentText("Your information are added!") .setConfirmText("OK") .setConfirmClickListener(null) .changeAlertType(SweetAlertDialog.SUCCESS_TYPE); recordDAO.insertRecord(user, fileName.getText().toString(), mFileName, tv_lyrics.getText().toString(),encoded); } }) .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() { @Override public void onClick(SweetAlertDialog sDialog) { sDialog.cancel(); } }) .show(); } } else { displayAlert("You have no internet connection"); } } }); reset.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new SweetAlertDialog(AudioOnTouchActivity.this.getWindow().getContext(), SweetAlertDialog.WARNING_TYPE) .setTitleText("Are you sure to reset?") .setContentText("Won't be able to play your record!") .setConfirmText("Yes,reset it!") .setCancelText("No,cancel plz!") .showCancelButton(true) .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() { @Override public void onClick(SweetAlertDialog sDialog) { sDialog .setTitleText("Deleted") .setContentText("Your record is deleted!") .setConfirmText("OK") .setConfirmClickListener(null) .changeAlertType(SweetAlertDialog.SUCCESS_TYPE); File file = new File(mFileName); deleted = file.delete(); mFileName=null ; linear_add.setVisibility(View.GONE); reset.setVisibility(View.GONE); } }) .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() { @Override public void onClick(SweetAlertDialog sDialog) { sDialog.cancel(); } }) .show(); } }); } @Override public void onPause() { super.onPause(); if (mRecorder != null) { mRecorder.release(); mRecorder = null; } if (mPlayer != null) { mPlayer.release(); mPlayer = null; } } private void checkValidation(View view) { FileLayout.startAnimation(shakeAnimation); new CustomToast().Show_Toast(this, view , "Enter File Name or lyrics."); Vibrator v = (Vibrator) getBaseContext().getSystemService(Context.VIBRATOR_SERVICE); // Vibrate for 500 milliseconds v.vibrate(500); } public boolean isOnline() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); return cm.getActiveNetworkInfo() != null; } public void displayAlert(String message) { new SweetAlertDialog(this.getWindow().getContext(), SweetAlertDialog.WARNING_TYPE) .setTitleText("Alert") .setContentText(message) .setConfirmText("OK") .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() { @Override public void onClick(SweetAlertDialog sDialog) { sDialog.cancel(); } }) .show(); } public static class FileUtils { /** * Instances should NOT be constructed in standard programming. */ public FileUtils() { } /** * The number of bytes in a kilobyte. */ public static final long ONE_KB = 1024; /** * The number of bytes in a megabyte. */ public static final long ONE_MB = ONE_KB * ONE_KB; /** * The number of bytes in a gigabyte. */ public static final long ONE_GB = ONE_KB * ONE_MB; public static byte[] readFileToByteArray( File file) throws IOException { InputStream in = new java.io.FileInputStream(file); try { return IOUtils.toByteArray(in); } finally { IOUtils.closeQuietly(in); } } public static String readFileToString( File file, String encoding) throws IOException { InputStream in = new java.io.FileInputStream(file); try { return IOUtils.toString(in, encoding); } finally { IOUtils.closeQuietly(in); } }} }
package com.cachecats.data.shop.repository; import com.cachecats.data.db.MeituanDB; import com.cachecats.data.shop.entity.ShopGroupInfoEntity; import com.cachecats.data.shop.mapper.ShopGroupInfoMapper; import com.cachecats.domin.shop.model.ShopGroupInfoModel; import com.cachecats.domin.shop.repository.ShopGroupInfoRepo; import com.raizlabs.android.dbflow.config.FlowManager; import com.raizlabs.android.dbflow.structure.database.transaction.FastStoreModelTransaction; import java.util.List; import javax.inject.Inject; /** * Created by solo on 2018/1/25. */ public class ShopGroupInfoRepoImpl implements ShopGroupInfoRepo { private ShopGroupInfoMapper mapper; @Inject public ShopGroupInfoRepoImpl(ShopGroupInfoMapper mapper) { this.mapper = mapper; } @Override public boolean save(ShopGroupInfoModel model) { ShopGroupInfoEntity entity = mapper.toEntity(model); return entity.save(); } @Override public void saveGroupInfos(List<ShopGroupInfoModel> models) { FastStoreModelTransaction<ShopGroupInfoEntity> transaction = FastStoreModelTransaction .saveBuilder(FlowManager.getModelAdapter(ShopGroupInfoEntity.class)) .addAll(mapper.toEntities(models)) .build(); FlowManager.getDatabase(MeituanDB.class) .beginTransactionAsync(transaction) .build().execute(); } }
package enstabretagne.BE.AnalyseSousMarine.SimEntity.Artefact.Representation3D; import enstabretagne.monitor.interfaces.IMovable; import javafx.scene.paint.Color; public interface IArtefactRepresentation3D extends IMovable{ Color getColor(); double getSize(); int getType(); }
package com.tencent.mm.modelsimple; import com.tencent.mm.ab.b; import com.tencent.mm.ab.b.a; import com.tencent.mm.ab.e; import com.tencent.mm.ab.l; import com.tencent.mm.network.k; import com.tencent.mm.network.q; import com.tencent.mm.plugin.report.service.h; import com.tencent.mm.protocal.c.cic; import com.tencent.mm.protocal.c.cid; import com.tencent.mm.sdk.platformtools.MultiProcessSharedPreferences; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.w; import com.tencent.mm.sdk.platformtools.x; public final class ad extends l implements k { private e diJ; private final b efk; private int retryCount = 3; public ad(String str, int i) { a aVar = new a(); aVar.dIG = new cic(); aVar.dIH = new cid(); aVar.uri = "/cgi-bin/micromsg-bin/yybgetpkgsig"; aVar.dIF = 729; aVar.dII = 0; aVar.dIJ = 0; this.efk = aVar.KT(); cic cic = (cic) this.efk.dID.dIL; cic.iwP = w.chP(); cic.reQ = com.tencent.mm.plugin.normsg.a.b.lFJ.ub(0); cic.sCa = str; cic.jPh = i; x.i("MicroMsg.NetSceneYybGetPkgSig", "summertoken YybGetPkgSig Language[%s], PkgName[%s], versionCode[%d], stack[%s]", new Object[]{cic.iwP, str, Integer.valueOf(i), bi.cjd()}); } public final int getType() { return 729; } public final int a(com.tencent.mm.network.e eVar, e eVar2) { this.diJ = eVar2; return a(eVar, this.efk, this); } public final void a(int i, int i2, int i3, String str, q qVar, byte[] bArr) { cic cic = (cic) this.efk.dID.dIL; cid cid = (cid) this.efk.dIE.dIL; x.i("MicroMsg.NetSceneYybGetPkgSig", "summertoken YybGetPkgSig onGYNetEnd netId[%d], errType[%d], errCode[%d], errMsg[%s], ret[%d], sig[%s]", new Object[]{Integer.valueOf(i), Integer.valueOf(i2), Integer.valueOf(i3), str, Integer.valueOf(cid.sCb), cid.sCc}); h hVar; Object[] objArr; if (i2 == 0 && i3 == 0) { if (cid.sCb == 2 || cid.sCb == 3) { this.retryCount--; if (this.retryCount <= 0) { x.w("MicroMsg.NetSceneYybGetPkgSig", "summertoken err and return with no try!"); h.mEJ.a(322, 2, 1, false); hVar = h.mEJ; objArr = new Object[2]; objArr[0] = Integer.valueOf(4002); objArr[1] = String.format("%s,%d", new Object[]{cic.sCa, Integer.valueOf(cic.jPh)}); hVar.h(11098, objArr); this.diJ.a(3, -1, "", this); return; } x.i("MicroMsg.NetSceneYybGetPkgSig", "summertoken do scene again retryCount:%d", new Object[]{Integer.valueOf(this.retryCount)}); a(this.dIX, this.diJ); } else if (cid.sCb == 1) { MultiProcessSharedPreferences.getSharedPreferences(com.tencent.mm.sdk.platformtools.ad.getContext(), "yyb_pkg_sig_prefs", 4).edit().remove(cic.sCa).commit(); h.mEJ.a(322, 5, 1, false); hVar = h.mEJ; objArr = new Object[2]; objArr[0] = Integer.valueOf(4005); objArr[1] = String.format("%s,%d", new Object[]{cic.sCa, Integer.valueOf(cic.jPh)}); hVar.h(11098, objArr); x.i("MicroMsg.NetSceneYybGetPkgSig", "summertoken ret no sig[%s] and remove", new Object[]{cid.sCc}); } else if (cid.sCb == 4) { x.w("MicroMsg.NetSceneYybGetPkgSig", "summertoken ret no need try and revise"); h.mEJ.a(322, 4, 1, false); hVar = h.mEJ; objArr = new Object[2]; objArr[0] = Integer.valueOf(4004); objArr[1] = String.format("%s,%d", new Object[]{cic.sCa, Integer.valueOf(cic.jPh)}); hVar.h(11098, objArr); } else { x.i("MicroMsg.NetSceneYybGetPkgSig", "summertoken ret sig[%s]", new Object[]{cid.sCc}); MultiProcessSharedPreferences.getSharedPreferences(com.tencent.mm.sdk.platformtools.ad.getContext(), "yyb_pkg_sig_prefs", 4).edit().putString(cic.sCa, cid.sCc).commit(); h.mEJ.a(322, 3, 1, false); hVar = h.mEJ; objArr = new Object[2]; objArr[0] = Integer.valueOf(4003); objArr[1] = String.format("%s,%d,%s", new Object[]{cic.sCa, Integer.valueOf(cic.jPh), cid.sCc}); hVar.h(11098, objArr); } this.diJ.a(i2, i3, str, this); return; } x.w("MicroMsg.NetSceneYybGetPkgSig", "summertoken YybGetPkgSig err and return!"); h.mEJ.a(322, 1, 1, false); hVar = h.mEJ; objArr = new Object[2]; objArr[0] = Integer.valueOf(4001); objArr[1] = String.format("%s,%d,%d,%d", new Object[]{cic.sCa, Integer.valueOf(cic.jPh), Integer.valueOf(i2), Integer.valueOf(i3)}); hVar.h(11098, objArr); this.diJ.a(i2, i3, str, this); } }
/** * Copyright (c) 2004-2011 QOS.ch * All rights reserved. * * 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 org.slf4j; public class NDC { public final static String PREFIX = "NDC"; private static int size() { int i = 0; while (true) { String val = MDC.get(PREFIX + i); if (val != null) { i++; } else { break; } } return i; } public static void push(String val) { int next = size(); MDC.put(PREFIX + next, val); } public static String pop() { int next = size(); if (next == 0) { return ""; } int last = next - 1; String key = PREFIX + last; String val = MDC.get(key); MDC.remove(key); return val; } }
package com.polsl.edziennik.desktopclient.view.common.panels.button; import javax.swing.JButton; public class GradeDetailsButtonPanel extends SaveExitButtonPanel { private JButton details; public GradeDetailsButtonPanel(String title, String hint) { super(hint); details = Button.getButton(title, hint); add(details); add(exit); } public JButton getDetailsButton() { return details; } @Override public void activate(boolean b) { save.setEnabled(b); details.setEnabled(b); } }
package actionlabstest; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; /** * * @author José Ricardo Carvalho Prado de Almeida */ public class ActionLabsTest { /** * @param args the command line arguments */ public static void main(String[] args) { ActionLabsTest test = new ActionLabsTest(); // Test 1 - FizzBuzz test.printFizzBuzz(); Random rand = new Random(); int amount = 10 + rand.nextInt(100); int[] notes = new int[amount]; int[] doors = new int[amount]; int[] zombies = new int[amount]; for (int i = 0; i < amount; i++) { notes[i] = rand.nextInt(10); doors[i] = 1 + rand.nextInt(19); zombies[i] = 1 + rand.nextInt(19); } // Test 2 - Rare Notes int[] rareNotes = test.getRareNotes(notes); System.out.println(Arrays.toString(rareNotes)); // Test 3 - Hold The Door int strength = rand.nextInt(100); System.out.println(test.holdTheDoor(strength, doors, zombies)); // Test 4 - Anagrams System.out.println(test.areAnagrams("anagram", "nag a ram")); System.out.println(test.areAnagrams("test1", "test2")); System.out.println(test.sqlQuery()); } void printFizzBuzz() { // Would be better if the maximum number was passed as a parameter. for (int index = 1; index <= 100; index++) { String fizzBuzz = ""; // Starts with the gratest modulo since its the compound of others // That way, if it was later in the test it would be taken by those before it. if (index % 15 == 0) { fizzBuzz = "FizzBuzz"; } else if (index % 5 == 0) { fizzBuzz = "Buzz"; } else if (index % 3 == 0) { fizzBuzz = "Fizz"; } String result; // There's no need to print unecessary characters if the number is not a FizzBuzz. if (fizzBuzz.isEmpty()) { result = "" + index; } else { result = String.format("%d - %s", index, fizzBuzz); } System.out.println(result); } } int[] getRareNotes(int[] notes) { // Used to count how many times a note appears Map<Integer, Integer> collisions = new HashMap<>(); // Counts how many times a note appears in the song. // We're interested only on the ones which are unique for (int index = 0; index < notes.length; index++) { int note = notes[index]; Integer currentValue = collisions.get(note); int amount = (currentValue == null) ? 1 : currentValue + 1; collisions.put(note, amount); } // Lists all the unique ones. // This is step ensures the resulting array will be of the correct size. List<Integer> rare = new ArrayList<>(); for (Integer key : collisions.keySet()) { if (collisions.get(key) == 1) { rare.add(key); } } // If the list is blank, it means no unique notes were found and thus we should return null. // Otherwise, return all the unique notes found. int[] result = null; if (!rare.isEmpty()) { result = new int[rare.size()]; for (int rareIndex = 0; rareIndex < rare.size(); rareIndex++) { result[rareIndex] = rare.get(rareIndex); } } return result; } int holdTheDoor(int hodorStrength, int[] doorsStrength, int[] zombiesInflux) { // Given that the doorsStrength and zombiesInflux array are guaranteed // to be the same size, we won't be checking (but we should). // This array keeps the calculated times of all doors for debugging purposes int[] time = new int[doorsStrength.length]; // The index of the door that can hold the longest int bestDoor = 0; // The strength of the best door, used to compare int bestStrength = 0; for (int index = 0; index < doorsStrength.length; index++) { int totalStrength = hodorStrength + doorsStrength[index]; int currentStrength = totalStrength / zombiesInflux[index]; if (currentStrength > bestStrength) { bestDoor = index; bestStrength = currentStrength; } time[index] = currentStrength; } return bestDoor; } boolean areAnagrams(String word1, String word2) { // Its easier to compare anagrams if all the characters are listed // So we strip spaces and downcase them to make comparison easier. char[] word1Chars = word1.replace(" ", "").toLowerCase().toCharArray(); char[] word2Chars = word2.replace(" ", "").toLowerCase().toCharArray(); // Anagrams should have the same length. if (word1Chars.length != word2Chars.length) { return false; } // Sorts the character arrays to ensure both words have all the same characters // and all of them are in the same position. Arrays.sort(word1Chars); Arrays.sort(word2Chars); // If both sorted character arrays are equal, we have a anagram return Arrays.equals(word1Chars, word2Chars); } String sqlQuery() { return "SELECT candidate.name AS candidate_name,\n" + " sum(question_score.score) AS candidate_score\n" + " FROM question_score\n" + " JOIN candidate ON candidate.candidate_id = question_score.candidate_id\n" + " JOIN test ON test.test_id = question_score.test_id\n" + " WHERE test.name = \"Java backend\"\n" + " ORDER BY candidate_score, candidate_name\n" + " GROUP BY candidate_name;"; } }
package com.training.day11.loops; public class FourteenFactorial { public static void main(String[] args) { int number = 5; int result = 1; for (int i=number ; i >=2 ; i--) { result = result * i ; } System.out.println("Factorial of " + number + " = " + result); } }
package me.buildcarter8.FreedomOpMod.Commands; import java.util.Arrays; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import me.buildcarter8.FreedomOpMod.FOPM_AdministratorList; import me.buildcarter8.FreedomOpMod.Main; public class Command_saconfig extends FOPM_Command { private final Main plugin; public Command_saconfig(Main plugin) { super("saconfig", "saconfig [add] [player]", "SA Command - Super Admin Management", PERM_MESSAGE, Arrays.asList("admin")); this.plugin = plugin; } @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (args.length == 0) { return false; } else if (args.length == 2) { if (!isConsoleSender(sender)) { msgNoPerms(sender); return true; } if (args[0].equalsIgnoreCase("add")) { Player p = getPlayer(args[1]); if (p == null) { notFound(sender); return true; } FOPM_AdministratorList.addSuperadmin(p); Bukkit.broadcastMessage(ChatColor.RED + "Adding " + p + " to the super admin list"); } } return true; } }
public class TestMyException { public static void firstException() throws MyFirstException { throw new MyFirstException( "firstException() method occurs an exception!"); } public static void secondException() throws MySecondException { throw new MySecondException( "secondException() method occurs an exception!"); } public static void main(String[] args) { try { TestMyException.firstException(); TestMyException.secondException(); } catch (MyFirstException e1) { System.out.println("Exception: " + e1.getMessage()); e1.printStackTrace(); } catch (MySecondException e2) { System.out.println("Exception: " + e2.getMessage()); e2.printStackTrace(); } } }
package com.stark.design23.template; /** * Created by Stark on 2018/3/26. * 抽象类:公司的薪水系统 */ public abstract class AbsSalarySystem { public abstract void count(); public abstract void give(); public final void pay() { count(); give(); } }
package com.jyhd.black.dao; import com.jyhd.black.domain.GameData; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; public interface GameDataDao extends JpaRepository<GameData, Long> { @Query(value = "select count(distinct(user_id)) from game_datas where date_stamp=?1",nativeQuery = true) int countByDate(String date); }
package com.androidapp.yemyokyaw.movieapp.dagger; import com.androidapp.yemyokyaw.movieapp.MovieApp; import com.androidapp.yemyokyaw.movieapp.activities.MovieListActivity; import com.androidapp.yemyokyaw.movieapp.data.model.MovieModel; import com.androidapp.yemyokyaw.movieapp.mvp.presenters.MovieListPresenter; import javax.inject.Singleton; import dagger.Component; import dagger.Module; /** * Created by GL-553VD on 1/12/2018. */ @Component(modules={MovieAppModule.class,UtilsModule.class}) @Singleton public interface MovieAppComponent { void inject(MovieApp app); void inject(MovieModel movieModel); void inject(MovieListPresenter movieListPresenter); void inject(MovieListActivity movieListActivity); }
package entity; /** * Created by ypl on 17-4-26. */ public class Lemma { private int lemmaId; private String LemmaTitle; private String lemmaParas; private String lemmaCreator; private int historyViewCount; private int likeCount; public Lemma(){} public Lemma(int lemmaId, String lemmaTitle, int historyViewCount, int likeCount, int shareCount, int editCount) { this.lemmaId = lemmaId; LemmaTitle = lemmaTitle; this.historyViewCount = historyViewCount; this.likeCount = likeCount; this.shareCount = shareCount; this.editCount = editCount; } public int getLemmaId() { return lemmaId; } public void setLemmaId(int lemmaId) { this.lemmaId = lemmaId; } public String getLemmaTitle() { return LemmaTitle; } public void setLemmaTitle(String lemmaTitle) { LemmaTitle = lemmaTitle; } public String getLemmaParas() { return lemmaParas; } public void setLemmaParas(String lemmaParas) { this.lemmaParas = lemmaParas; } public String getLemmaCreator() { return lemmaCreator; } public void setLemmaCreator(String lemmaCreator) { this.lemmaCreator = lemmaCreator; } public int getHistoryViewCount() { return historyViewCount; } public void setHistoryViewCount(int historyViewCount) { this.historyViewCount = historyViewCount; } public int getLikeCount() { return likeCount; } public void setLikeCount(int likeCount) { this.likeCount = likeCount; } public int getShareCount() { return shareCount; } public void setShareCount(int shareCount) { this.shareCount = shareCount; } public String[] getLemmaTags() { return lemmaTags; } public void setLemmaTags(String[] lemmaTags) { this.lemmaTags = lemmaTags; } public int getEditCount() { return editCount; } public void setEditCount(int editCount) { this.editCount = editCount; } private int shareCount; private String[] lemmaTags; private int editCount; }
package com.thread.threadPool.sendService; /** * @author zhangbingquan * @version 2019年09月12日 * @since 2019年09月12日 **/ public class SendMessageService { public void sendMessage(String email, String content) { System.out.println("发送邮件=======================================>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); } }
package com.ygrik.currencyrate.app.di; import android.app.Application; import android.content.Context; import com.squareup.leakcanary.LeakCanary; import com.squareup.leakcanary.RefWatcher; import com.ygrik.currencyrate.app.di.components.AppComponent; public class AppApplication extends Application { private static Application application; private static AppComponent graph; private RefWatcher refWatcher; public static RefWatcher getRefWatcher(Context context) { AppApplication application = (AppApplication) context.getApplicationContext(); return application.refWatcher; } @Override public void onCreate() { super.onCreate(); application = this; buildComponentAndInject(); refWatcher = LeakCanary.install(this); } public static AppComponent component() { return graph; } public static void buildComponentAndInject() { graph = AppComponent.Initializer.init(application); } }
package com.fanniemae.mcasrest.controllers; import com.fanniemae.mcasrest.domain.LenderProfile; import com.fanniemae.mcasrest.services.LenderProfileService; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping(LenderProfileController.BASE_URL) public class LenderProfileController { public static final String BASE_URL = "/api/v1/lenderprofiles"; private final LenderProfileService lenderProfileService; public LenderProfileController(LenderProfileService lenderProfileService) { this.lenderProfileService = lenderProfileService; } @GetMapping List<LenderProfile> getAllLenderProfiles() { System.out.println("Running getAllLenderProfiles"); return lenderProfileService.findAllLenderProfiles(); } @GetMapping("/id/{id}") LenderProfile getLenderProfilebyId(@PathVariable Long id) { System.out.println("Running getLenderProfilebyId"); return lenderProfileService.findLenderProfileById(id); } @GetMapping("/unid/{unid}") LenderProfile getLenderProfilebyUnid(@PathVariable String unid) { System.out.println("Running getLenderProfilebyUnid"); return lenderProfileService.findLenderProfileByUnid(unid); } }
package com.one.sugarcane.entity; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; @Entity @Table(name="COURSE") public class Course { private Integer courseID; private String courseName; private String courseBrief; private double price; private String phoneNumber; private String introductionImg1; private String introductionImg2; private String introductionImg3; private SellerCourseType sellerCourseType; private SellerInfo sellerInfo; private PublicCourseType publicCourseType; private SellerLogin sellerLogin; private String teacher; private String video; private Set<Evaluate>evaluate = new HashSet<Evaluate>(); private Set<UserCollections>userCollections = new HashSet<UserCollections>(); @Id @GeneratedValue(generator="a") @GenericGenerator(name="a",strategy="identity") public Integer getCourseID() { return courseID; } public void setCourseID(Integer courseID) { this.courseID = courseID; } public String getCourseName() { return courseName; } public void setCourseName(String courseName) { this.courseName = courseName; } public String getCourseBrief() { return courseBrief; } public void setCourseBrief(String courseBrief) { this.courseBrief = courseBrief; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getIntroductionImg1() { return introductionImg1; } public void setIntroductionImg1(String introductionImg1) { this.introductionImg1 = introductionImg1; } public String getIntroductionImg2() { return introductionImg2; } public void setIntroductionImg2(String introductionImg2) { this.introductionImg2 = introductionImg2; } public String getIntroductionImg3() { return introductionImg3; } public void setIntroductionImg3(String introductionImg3) { this.introductionImg3 = introductionImg3; } @ManyToOne @JoinColumn(name="sellerCourseTypeId") public SellerCourseType getSellerCourseType() { return sellerCourseType; } public void setSellerCourseType(SellerCourseType sellerCourseType) { this.sellerCourseType = sellerCourseType; } @ManyToOne @JoinColumn(name="sellerId",insertable = false, updatable = false) public SellerInfo getSellerInfo() { return sellerInfo; } public void setSellerInfo(SellerInfo sellerInfo) { this.sellerInfo = sellerInfo; } @ManyToOne @JoinColumn(name="pub_publicTypeId") public PublicCourseType getPublicCourseType() { return publicCourseType; } public void setPublicCourseType(PublicCourseType publicCourseType) { this.publicCourseType = publicCourseType; } @ManyToOne @JoinColumn(name="sellerID") public SellerLogin getSellerLogin() { return sellerLogin; } public void setSellerLogin(SellerLogin sellerLogin) { this.sellerLogin = sellerLogin; } @OneToMany(mappedBy="course",targetEntity=Evaluate.class,cascade=CascadeType.MERGE) public Set<Evaluate> getEvaluate() { return evaluate; } public void setEvaluate(Set<Evaluate> evaluate) { this.evaluate = evaluate; } @OneToMany(mappedBy="course",targetEntity=UserCollections.class,cascade=CascadeType.MERGE) public Set<UserCollections> getUserCollections() { return userCollections; } public void setUserCollections(Set<UserCollections> userCollections) { this.userCollections = userCollections; } public String getTeacher() { return teacher; } public void setTeacher(String teacher) { this.teacher = teacher; } public Course() {} public Course(Integer courseID, String courseName, String courseBrief, double price, String phoneNumber, String introductionImg1, String introductionImg2, String introductionImg3, SellerCourseType sellerCourseType, SellerInfo sellerInfo,PublicCourseType publicCourseType, SellerLogin sellerLogin, String teacher, Set<Evaluate> evaluate, Set<UserCollections> userCollections) { super(); this.courseID = courseID; this.courseName = courseName; this.courseBrief = courseBrief; this.price = price; this.phoneNumber = phoneNumber; this.introductionImg1 = introductionImg1; this.introductionImg2 = introductionImg2; this.introductionImg3 = introductionImg3; this.sellerCourseType = sellerCourseType; this.sellerInfo = sellerInfo; this.publicCourseType = publicCourseType; this.sellerLogin = sellerLogin; this.teacher = teacher; this.evaluate = evaluate; this.userCollections = userCollections; } public String getVideo() { return video; } public void setVideo(String video) { this.video = video; } }
package gui; import bbdd.GestionBDFactory; import java.awt.Color; import java.awt.Toolkit; import java.util.List; import java.util.Vector; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; import javax.swing.table.JTableHeader; import javax.swing.table.TableColumn; import model.Clientes; import model.Historicos; public class frmHistorial extends javax.swing.JFrame { private Clientes cliente; public frmHistorial(List<Historicos> historial, Clientes cli) { initComponents(); this.setLocationRelativeTo(null); this.setIconImage(Toolkit.getDefaultToolkit().getImage("C:/Program Files/Gestion Clientes v3.0/resources/estrella_peque.png")); this.cliente = cli; lblNombre.setText(cli.getNombre() + " " + cli.getApellido1()); printHistorial(historial); formateoTabla(); } private void printHistorial(List<Historicos> listaHistoricos) { Historicos historico = null; Vector<String> tableHeaders = new Vector<String>(); Vector tableData = new Vector(); tableHeaders.add("Id Historico"); tableHeaders.add("Fecha"); tableHeaders.add("Tratamiento"); tableHeaders.add("Producto"); tableHeaders.add("Precio"); tableHeaders.add("Recomendaciones"); for (Object o : listaHistoricos) { historico = (Historicos) o; Vector<Object> row = new Vector<Object>(); row.add(historico.getIdHistorico()); row.add(historico.getFecha()); row.add(historico.getTratamiento()); row.add(historico.getProducto()); row.add(historico.getPrecio()); row.add(historico.getRecomendaciones()); tableData.add(row); } tablaHistorico.setModel(new DefaultTableModel(tableData, tableHeaders)); JTableHeader header = tablaHistorico.getTableHeader(); header.setBackground(Color.DARK_GRAY); } private void formateoTabla() { TableColumn column = null; for (int i = 0; i < tablaHistorico.getColumnCount(); i++) { column = tablaHistorico.getColumnModel().getColumn(i); switch (i) { case 0: column.setPreferredWidth(100); column.setMaxWidth(200); column.sizeWidthToFit(); break; case 1: column.setPreferredWidth(120); column.setMaxWidth(200); column.sizeWidthToFit(); break; case 2: column.setPreferredWidth(200); column.sizeWidthToFit(); break; case 3: column.setPreferredWidth(200); column.sizeWidthToFit(); break; case 4: column.setPreferredWidth(60); column.setMaxWidth(200); column.sizeWidthToFit(); break; case 5: column.setPreferredWidth(200); column.sizeWidthToFit(); break; } } } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); lblLogo = new javax.swing.JLabel(); lblNombre = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); tablaHistorico = new javax.swing.JTable(); btnAgregar = new javax.swing.JButton(); btnEliminar = new javax.swing.JButton(); setTitle("Historial del Cliente"); jPanel1.setBackground(new java.awt.Color(225, 183, 222)); lblLogo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/logo_ambar_transp4.png"))); // NOI18N lblNombre.setFont(new java.awt.Font("Ubuntu", 2, 24)); // NOI18N lblNombre.setForeground(new java.awt.Color(8, 6, 6)); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(58, 58, 58) .addComponent(lblNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 487, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 45, Short.MAX_VALUE) .addComponent(lblLogo, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(12, 12, 12) .addComponent(lblNombre, javax.swing.GroupLayout.DEFAULT_SIZE, 41, Short.MAX_VALUE)) .addComponent(lblLogo)) .addContainerGap()) ); tablaHistorico.setFont(new java.awt.Font("Verdana", 0, 14)); // NOI18N tablaHistorico.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { } )); tablaHistorico.setDoubleBuffered(true); tablaHistorico.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); tablaHistorico.setShowHorizontalLines(false); jScrollPane1.setViewportView(tablaHistorico); btnAgregar.setFont(new java.awt.Font("Comic Sans MS", 1, 15)); // NOI18N btnAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/add.png"))); // NOI18N btnAgregar.setText("Añadir"); btnAgregar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnAgregarActionPerformed(evt); } }); btnEliminar.setFont(new java.awt.Font("Comic Sans MS", 1, 15)); // NOI18N btnEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/Cerrar.png"))); // NOI18N btnEliminar.setText("Eliminar"); btnEliminar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnEliminarActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(434, Short.MAX_VALUE) .addComponent(btnEliminar) .addGap(18, 18, 18) .addComponent(btnAgregar, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 682, Short.MAX_VALUE) .addContainerGap()) ); layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnAgregar, btnEliminar}); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnAgregar) .addComponent(btnEliminar)) .addContainerGap()) ); layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btnAgregar, btnEliminar}); pack(); }// </editor-fold>//GEN-END:initComponents private void btnAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarActionPerformed frmAddHistorico addHistorico = new frmAddHistorico(cliente); addHistorico.setVisible(true); this.setVisible(false); }//GEN-LAST:event_btnAgregarActionPerformed private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed int eliminar = JOptionPane.showConfirmDialog(rootPane, "Va a eliminar el histórico, ¿Está seguro?", "Eliminar", JOptionPane.YES_NO_OPTION); if (eliminar == JOptionPane.YES_OPTION) { Object idHistorico; try { idHistorico = tablaHistorico.getModel().getValueAt(tablaHistorico.getSelectedRow(), 0); } catch (ArrayIndexOutOfBoundsException ex) { JOptionPane.showMessageDialog(rootPane, "Debe seleccionar la fila a eliminar!!", "Error", JOptionPane.ERROR_MESSAGE); return; } try { GestionBDFactory.getInstance().getBDMySQL().removeHistorico(Integer.parseInt(idHistorico.toString())); JOptionPane.showMessageDialog(rootPane, "Histórico eliminado correctamente...", "Información!", JOptionPane.INFORMATION_MESSAGE); this.setVisible(false); List<Historicos> listaHistoricos = GestionBDFactory.getInstance().getBDMySQL().findHistoricos(cliente.getId()); frmHistorial historial = new frmHistorial(listaHistoricos, cliente); historial.setVisible(true); } catch (Exception ex) { JOptionPane.showMessageDialog(rootPane, "No se ha podido eliminar el histórico!!!", "Error!", JOptionPane.ERROR_MESSAGE); } } }//GEN-LAST:event_btnEliminarActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnAgregar; private javax.swing.JButton btnEliminar; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JLabel lblLogo; private javax.swing.JLabel lblNombre; private javax.swing.JTable tablaHistorico; // End of variables declaration//GEN-END:variables }
package com.tencent.mm.plugin.pwdgroup.ui; import com.tencent.mm.plugin.pwdgroup.ui.FacingCreateChatRoomAllInOneUI.a; /* synthetic */ class FacingCreateChatRoomAllInOneUI$10 { static final /* synthetic */ int[] maq = new int[a.bnX().length]; static { try { maq[a.mar - 1] = 1; } catch (NoSuchFieldError e) { } try { maq[a.mas - 1] = 2; } catch (NoSuchFieldError e2) { } try { maq[a.mat - 1] = 3; } catch (NoSuchFieldError e3) { } try { maq[a.mau - 1] = 4; } catch (NoSuchFieldError e4) { } } }
package mod.tainan; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import android.app.Activity; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.util.Log; public class HttpLoadActivity extends Activity { protected class HttpAsyncTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... urls) { return GET(urls[0]); } // onPostExecute displays the results of the AsyncTask. @Override protected void onPostExecute(String result) { } } private static String GET(String url) { InputStream inputStream = null; String result = ""; try { // create HttpClient HttpClient httpclient = new DefaultHttpClient(); // make GET request to the given URL HttpResponse httpResponse = httpclient.execute(new HttpGet(url)); // receive response as inputStream inputStream = httpResponse.getEntity().getContent(); // convert inputstream to string if (inputStream != null) result = convertInputStreamToString(inputStream); else result = "Did not work!"; } catch (Exception e) { Log.d("InputStream", e.getLocalizedMessage()); } return result; } private static String convertInputStreamToString(InputStream inputStream) throws IOException { BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream, "utf-16"), 32); int i = 0; String line = ""; StringBuilder result = new StringBuilder(); try { while ((line = bufferedReader.readLine()) != null) { if (i < 100) i++; if (i == 52 ) result = new StringBuilder("{"); result.append((line + "\n")); Log.i("", line); } } finally { inputStream.close(); } return result.toString(); } protected boolean isConnected() { ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) return true; else return false; } }
package com.adm.tools.common.result; import com.adm.tools.common.sdk.Logger; import com.adm.tools.common.SSEException; import com.adm.tools.common.result.model.junit.Testsuites; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import java.io.File; import java.io.PrintWriter; import java.io.StringWriter; import java.nio.file.Paths; import java.text.Format; import java.text.SimpleDateFormat; import java.util.Date; public class ResultSerializer { private ResultSerializer(){} public static String saveResults(Testsuites testsuites, String workingDirectory, Logger logger) throws SSEException { String filePath = getFullFilePath(workingDirectory, getFileName()); try { if (testsuites != null) { StringWriter writer = new StringWriter(); JAXBContext context = JAXBContext.newInstance(Testsuites.class); Marshaller marshaller = context.createMarshaller(); marshaller.marshal(testsuites, writer); PrintWriter resultWriter = new PrintWriter(filePath); resultWriter.print(writer.toString()); resultWriter.close(); return filePath; } else { String message ="Empty Results"; logger.log(message); throw new SSEException(message); } } catch (Throwable cause) { String message=String.format( "Failed to create run results, Exception: %s", cause.getMessage()); logger.log(message); throw new SSEException(message); } } public static Testsuites Deserialize(File file) throws JAXBException { JAXBContext jaxbContext = JAXBContext.newInstance(Testsuites.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); Testsuites testsuites = (Testsuites)jaxbUnmarshaller.unmarshal(file); return testsuites; } private static String getFullFilePath(String workingDirectoryPath, String fileName) { return Paths.get(workingDirectoryPath, fileName).toString(); } private static String getFileName() { Format formatter = new SimpleDateFormat("ddMMyyyyHHmmssSSS"); String time = formatter.format(new Date()); return String.format("Results%s.xml", time); } }
package com.itfdms.common.bean.xss; import com.itfdms.common.util.exception.CheckedException; import org.apache.commons.lang3.StringUtils; /** * java类简单作用描述 * * @ProjectName: itfdms_blog * @Package: com.itfdms.common.bean.xss * @ClassName: SqlFilter * @Description: java类作用描述 * @Author: lxr * @CreateDate: 2018-08-14 22:07 * @UpdateUser: lxr * @UpdateDate: 2018-08-14 22:07 * @UpdateRemark: The modified content * @Version: 1.0 **/ public class SqlFilter { /** * 方法实现说明 * @className: SqlFilter * @methodName sqlInject * @description: sql注入过滤 * @author lxr * @createDate 2018-08-14 22:09 * @updateUser: lxr * @updateDate: 2018-08-14 22:09 * @updateRemark: The modified content * @version 1.0 * @see /对类、属性、方法的说明 参考转向 * @param str 待验证的字符串 * @return * @exception **/ public static String sqlInject(String str){ if (StringUtils.isBlank(str)) { return null; } //去掉'|"|;|\字符 str = StringUtils.replace(str, "'", ""); str = StringUtils.replace(str, "\"", ""); str = StringUtils.replace(str, ";", ""); str = StringUtils.replace(str, "\\", ""); //转换成小写 str = str.toLowerCase(); //非法字符 String[] keywords = {"master", "truncate", "insert", "select", "delete", "update", "declare", "alert", "drop"}; //判断是否包含非法字符 for(String keyword : keywords){ if(str.indexOf(keyword) != -1){ throw new CheckedException("包含非法字符"); } } return str; } }
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class runner { public static void main(String args[]) { nbaGui gui = new nbaGui(); gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); gui.pack(); gui.setVisible(true); gui.setTitle("NBA Predictor"); } }
package com.twu.infrastructure; import com.twu.model.Book; import com.twu.model.User; import com.twu.model.BookReservation; import java.util.List; import java.util.ArrayList; import java.util.Scanner; public class ManageBooks { private static boolean checkOutSuccess = false; private static boolean returnSuccess = false; private ManageBookMenu menu; private static List<Book> allBooks = new ArrayList<Book>(); private static List<Book> availableBooks = new ArrayList<Book>(); private User user; public ManageBooks(User user, ManageBookMenu menu) { this.user = user; this.menu = menu; } public static void addBookToList(Book book){ allBooks.add(book); } public static void createAvailableList(){ for (Book book : allBooks){ boolean availability = book.getAvailable(); if(availability == true && !availableBooks.contains(book)){ availableBooks.add(book); } } } public static void showAvailableBooks(){ createAvailableList(); for (Book book : availableBooks) { boolean availability = book.getAvailable(); if(availability == true) { String title = book.getTitle(); String author = book.getAuthor(); int year = book.getPublicationYear(); System.out.println(title + "|" + author + "|" + year); } } } public void checkOutBook(){ Scanner scan = new Scanner(System.in); while(scan.hasNextLine()) { String bookChoice = scan.nextLine(); for (Book book : allBooks) { boolean availability = book.getAvailable(); String title = book.getTitle(); if (title.equals(bookChoice) && availability == true) { BookReservation reservation = new BookReservation(book, user); book.setAvailable(false); checkOutSuccess = true; } } if (checkOutSuccess == true) { menu.bookCheckOutSuccess(); checkOutSuccess = false; } else { menu.bookCheckOutError(); } } } public void returnBook(){ Scanner scanner = new Scanner(System.in); while(scanner.hasNextLine()) { String returnChoice = scanner.nextLine(); for (Book book : allBooks) { boolean availability = book.getAvailable(); String title = book.getTitle(); if (title.equals(returnChoice) && availability == false) { book.setAvailable(true); returnSuccess = true; } } if (returnSuccess == true) { menu.bookReturnSuccess(); returnSuccess = false; } else { menu.bookReturnError(); } } } }
package StormD1; import java.util.concurrent.ConcurrentHashMap; public class LocalCache { private LocalCache() { } // 防止在外部实例化 // 使用volatile延迟初始化,防止编译器重排序 private static volatile LocalCache instance; public static LocalCache getInstance() { // 对象实例化时与否判断(不使用同步代码块,instance不等于null时,直接返回对象,提高运行效率) if (instance == null) { // 同步代码块(对象未初始化时,使用同步代码块,保证多线程访问时对象在第一次创建后,不再重复被创建) synchronized (LocalCache.class) { // 未初始化,则初始instance变量 if (instance == null) { instance = new LocalCache(); } } } return instance; } private static final ConcurrentHashMap<String, Long> dataMap = new ConcurrentHashMap<String, Long>(); public ConcurrentHashMap<String, Long> getMap(){ return dataMap; } }
package com.linda.framework.rpc.net; import com.linda.framework.rpc.RpcObject; public interface RpcSender { /** * @param rpc * @param timeout * @return */ public boolean sendRpcObject(RpcObject rpc, int timeout); }
package com.dzz.policy.service.service.common; import com.dzz.policy.api.domain.dto.PolicyCommonSaveParam; import com.dzz.policy.service.domain.model.Policy; import com.dzz.util.id.IdService; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * bean 转换工具 * * @author dzz * @version 1.0.0 * @since 2019年08月13 09:21 */ @Service public class BeanToolsService { private IdService idService; @Autowired public void setIdService(IdService idService) { this.idService = idService; } /** * 转换成Policy * @param saveParam param * @return policy 实体 */ public Policy convertToPolicy(PolicyCommonSaveParam saveParam) { Policy policy = new Policy(); BeanUtils.copyProperties(saveParam, policy); policy.setId(idService.getId()); return policy; } }
package com.lti.handson2; public class STRINGQUESTION8 { public static void main(String[] args) { String s="Try to learn something about everything and everything about something"; System.out.println(s.charAt(10)); System.out.println(s.contains("is")); System.out.println(s + " otherwise fix it "); System.out.println(s.endsWith("how")); String s1="Try to learn something about Everything and Everything about SOmehting"; System.out.println(s.equals(s1)); System.out.println(s.equals("Try to learn something about everything and everything about something")); System.out.println(s.indexOf("a")); int l=s.lastIndexOf("e"); System.out.println(l); System.out.println(s.length()); } }
package ru.molkov.dao; import java.util.List; import org.hibernate.criterion.Restrictions; import org.springframework.stereotype.Repository; import ru.molkov.core.ModelWorker; import ru.molkov.model.Disc; @Repository public class DiscDaoImpl extends ModelWorker<Disc> implements DiscDao { public DiscDaoImpl() { super(Disc.class); } @SuppressWarnings("unchecked") public List<Disc> getDiscsByUser(Integer userId) { return getSession().createCriteria(Disc.class) .add(Restrictions.eq("ownerId", userId)).list(); } }
package by.ez.smm.service; import by.ez.smm.dao.orm.entity.User; import by.ez.smm.dao.orm.filter.UserFilter; public interface UserService extends AbstractServiceImpl<User, Integer, UserFilter> { }
public class BankAccount { public BankAccount(int money) { this.money = money; } private int money; public int getMoney() { return money; } public void inputMoney(int moneyAdded){ money += moneyAdded; } public void withdrawFromBalance(int takenMoney) { money -= takenMoney; } }
package com.rc.utils; import com.rc.app.Launcher; import java.io.*; import java.text.DecimalFormat; /** * Created by song on 2017/6/11. */ public class FileCache { public static String FILE_CACHE_ROOT_PATH; private static DecimalFormat decimalFormat = new DecimalFormat("#.0"); private FileCache() { } static { try { FILE_CACHE_ROOT_PATH = Launcher.appFilesBasePath + "/cache/file"; createCacheDir(); } catch (Throwable e) { FILE_CACHE_ROOT_PATH = "./"; createCacheDir(); } } private static void createCacheDir() { File file = new File(FILE_CACHE_ROOT_PATH); if (!file.exists()) { file.mkdirs(); System.out.println("创建文件缓存目录:" + file.getAbsolutePath()); } } public static String tryGetFileCache(String identify, String name) { File cacheFile = new File(FILE_CACHE_ROOT_PATH + "/" + identify + "_" + name); if (cacheFile.exists()) { return cacheFile.getAbsolutePath(); } return null; } public static String cacheFile(String identify, String name, byte[] data) { if (data == null || data.length < 1) { return null; } File cacheFile = new File(FILE_CACHE_ROOT_PATH + "/" + identify + "_" + name); try { FileOutputStream outputStream = new FileOutputStream(cacheFile); outputStream.write(data); outputStream.close(); return cacheFile.getAbsolutePath(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } public static String fileSizeString(String path) { File file = new File(path); if (file == null) { return null; } long size = file.length(); String retString = prettySizeString(size); return retString; } public static String prettySizeString(long size) { String retString; if (size < 1024) { retString = size + " 字节"; } else if (size < 1024 * 1024) { retString = decimalFormat.format(size * 1.0F / 1024) + " KB"; } else { retString = decimalFormat.format(size * 1.0F / 1024 / 1024) + " MB"; } return retString; } }
package com.emoney.web.dto.responseDto; import com.emoney.core.model.ResponseDtoBase; import lombok.Getter; import lombok.Setter; @Getter @Setter public class UserRatingResponseDto extends ResponseDtoBase { private Integer posterReview; private Integer workerReview; private Long posterId; private Long transactionId; private Long workerId; }
package com.beiyelin.projectportal.repository; import com.beiyelin.commonsql.jpa.BaseAbstractRepository; import com.beiyelin.commonsql.jpa.BaseItemRepository; import com.beiyelin.projectportal.entity.SettleDetailBorrowMoneyTicket; import org.springframework.stereotype.Repository; /** * @Author: xinsh * @Description: 结算单考勤单清单 * @Date: Created in 16:38 2018/02/21. */ @Repository public interface SettleDetailBorrowMoneyTicketRepository extends BaseItemRepository<SettleDetailBorrowMoneyTicket,String> { }
/** * */ package com.yougou.merchant.api.monitor.vo; import java.io.Serializable; import java.util.Date; /** * @author huang.tao * */ public class MonitorTemplateDetail implements Serializable { private static final long serialVersionUID = -235975555326266247L; private String id; //模板编号 private String templateNo; //apiId private String apiId; //频率上限 private Integer frequency; //频率单位 1:次/时 2:次/分钟 3:次/秒 private Integer frequencyUnit; //日调用次数上限 private Integer callNum; //是否开启频率限制 private Integer isFrequency; //是否开启日调用次数限制 private Integer isCallNum; private Date createTime; private Date updateTime; /** * 模板关联字段 */ private String apiCode; private String apiName; private String categoryName; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getTemplateNo() { return templateNo; } public void setTemplateNo(String templateNo) { this.templateNo = templateNo; } public String getApiId() { return apiId; } public void setApiId(String apiId) { this.apiId = apiId; } public Integer getFrequency() { return frequency; } public void setFrequency(Integer frequency) { this.frequency = frequency; } public Integer getFrequencyUnit() { return frequencyUnit; } public void setFrequencyUnit(Integer frequencyUnit) { this.frequencyUnit = frequencyUnit; } public Integer getCallNum() { return callNum; } public void setCallNum(Integer callNum) { this.callNum = callNum; } public Integer getIsFrequency() { return isFrequency; } public void setIsFrequency(Integer isFrequency) { this.isFrequency = isFrequency; } public Integer getIsCallNum() { return isCallNum; } public void setIsCallNum(Integer isCallNum) { this.isCallNum = isCallNum; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public String getApiCode() { return apiCode; } public void setApiCode(String apiCode) { this.apiCode = apiCode; } public String getApiName() { return apiName; } public void setApiName(String apiName) { this.apiName = apiName; } public String getCategoryName() { return categoryName; } public void setCategoryName(String categoryName) { this.categoryName = categoryName; } }
import java.util.Scanner; public class pattern1 { public static void main(String[] args) { Scanner scan=new Scanner(System.in); int n= scan.nextInt(); scan.close(); int nrows=n; int nst=n; int nsp=-1; //rows for (int row = 1; row <=nrows; row++) { //first stars int digit=1; for (int cst = 1; cst <= nst; cst++) { System.out.print(digit+" "); digit++; } //second stars for (int csp = 1; csp <=nsp; csp++) { System.out.print("*"+" "); } //changeline System.out.println(""); //cdtn nst--; nsp+=2; } } }
package newdemo; /** * @Author: Prongs * @Date: 2020/6/13 15:32 */ public class Dianlubuxian { public int[] c; public int[][] size; public int[] net; public Dianlubuxian(int[] cc) { this.c = cc; this.size = new int[cc.length][cc.length]; this.net = new int[cc.length]; } public void mnset(int[] c, int[][] size) { int n = c.length - 1; //i=1时,分了两种情况,分别等于0,1 for (int j = 0; j < c[1]; j++) { size[1][j] = 0; } for (int j = c[1]; j <= n; j++) { size[1][j] = 1; } //i大于1时,同样分了两种情况(当i=n时单独计算,即此方法最后一行) for (int i = 2; i < n; i++) { //第一种 if (c[i] >= 0) { System.arraycopy(size[i - 1], 0, size[i], 0, c[i]); } //第二种 for (int j = c[i]; j <= n; j++) { size[i][j] = Math.max(size[i - 1][j], (size[i - 1][c[i] - 1] + 1)); } } size[n][n] = Math.max(size[n - 1][n], (size[n - 1][c[n] - 1] + 1)); } public int traceback(int[] c, int[][] size, int[] net) { int n = c.length - 1; int j = n; int m = 0; for (int i = n; i > 1; i--) { if (size[i][j] != size[i - 1][j]) { net[m++] = i; j = c[i] - 1; } } if (j >= c[1]) { net[m++] = 1; } System.out.println("最大不相交连线分别为:"); for (int t = m - 1; t >= 0; t--) { System.out.println(net[t] + " " + c[net[t]]); } return m; } public static void main(String[] args) { //下标从1开始,第一个数,0不算,总共10个数 int[] c = {0, 8, 7, 4, 2, 5, 1, 9, 3, 10, 6}; Dianlubuxian di = new Dianlubuxian(c); di.mnset(di.c, di.size); int x = di.traceback(di.c, di.size, di.net); System.out.println("最大不相交连线数目为:" + x); } }
package com.tencent.xweb.extension.video; import android.webkit.ValueCallback; import com.tencent.xweb.extension.video.c.15; class c$15$1 implements ValueCallback<String> { final /* synthetic */ 15 vCn; c$15$1(15 15) { this.vCn = 15; } public final /* bridge */ /* synthetic */ void onReceiveValue(Object obj) { } }
/* * 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 registrosql; import com.itextpdf.text.Document; import com.itextpdf.text.PageSize; import com.itextpdf.text.pdf.PdfContentByte; import com.itextpdf.text.pdf.PdfTemplate; import com.itextpdf.text.pdf.PdfWriter; import java.awt.Component; import java.awt.Graphics2D; import java.io.File; import java.io.FileOutputStream; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.DefaultTableModel; /** * * @author Gonchoi5 */ public class Registrar extends javax.swing.JFrame { /** * Creates new form Registrar */ public Registrar() { initComponents(); setTitle("Registrar"); conexion=new ConexionSQL(); mdl1=(DefaultTableModel)tablaTemas.getModel(); mdl2=(DefaultTableModel)tablaPracticas.getModel(); mdl3=(DefaultTableModel)tablaVisitas.getModel(); ListSelectionModel selec=tablaTemas.getSelectionModel(); selec.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); selec.addListSelectionListener(new ListSelectionListener(){ @Override public void valueChanged(ListSelectionEvent e){ if(!e.getValueIsAdjusting()&&mdl1.getRowCount()>0){ ListSelectionModel mdl=tablaTemas.getSelectionModel(); sel1=mdl.getLeadSelectionIndex(); } } }); ListSelectionModel selec2=tablaPracticas.getSelectionModel(); selec2.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); selec2.addListSelectionListener(new ListSelectionListener(){ @Override public void valueChanged(ListSelectionEvent e){ if(!e.getValueIsAdjusting()&&mdl2.getRowCount()>0){ ListSelectionModel mdl=tablaPracticas.getSelectionModel(); sel2=mdl.getLeadSelectionIndex(); } } }); ListSelectionModel selec3=tablaVisitas.getSelectionModel(); selec3.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); selec3.addListSelectionListener(new ListSelectionListener(){ @Override public void valueChanged(ListSelectionEvent e){ if(!e.getValueIsAdjusting()&&mdl3.getRowCount()>0){ ListSelectionModel mdl=tablaVisitas.getSelectionModel(); sel3=mdl.getLeadSelectionIndex(); } } }); tablaTemas.setModel(mdl1); tablaPracticas.setModel(mdl2); tablaVisitas.setModel(mdl3); setDefaultCloseOperation(DISPOSE_ON_CLOSE); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jSeparator1 = new javax.swing.JSeparator(); jLabel2 = new javax.swing.JLabel(); materia = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); prof = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); periodo = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); grupo = new javax.swing.JTextField(); jLabel6 = new javax.swing.JLabel(); carrera = new javax.swing.JTextField(); jLabel7 = new javax.swing.JLabel(); jSeparator2 = new javax.swing.JSeparator(); jScrollPane2 = new javax.swing.JScrollPane(); tablaTemas = new javax.swing.JTable(); addtema = new javax.swing.JButton(); eliminartema = new javax.swing.JButton(); jLabel8 = new javax.swing.JLabel(); jSeparator3 = new javax.swing.JSeparator(); jScrollPane3 = new javax.swing.JScrollPane(); tablaPracticas = new javax.swing.JTable(); addpractica = new javax.swing.JButton(); eliminapractica = new javax.swing.JButton(); jLabel9 = new javax.swing.JLabel(); jSeparator4 = new javax.swing.JSeparator(); jScrollPane4 = new javax.swing.JScrollPane(); tablaVisitas = new javax.swing.JTable(); addvisita = new javax.swing.JButton(); eliminavisita = new javax.swing.JButton(); terminar = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jScrollPane1.setPreferredSize(null); jPanel1.setPreferredSize(new java.awt.Dimension(800, 600)); jLabel1.setText("Información de Materia"); jLabel2.setText("Materia"); jLabel3.setText("Catedrático"); jLabel4.setText("Periodo"); jLabel5.setText("Grupo"); jLabel6.setText("Carrera"); jLabel7.setText("Temas"); tablaTemas.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {" ", " ", "Inicio/Fin-Avance%", "Inicio/Fin-Avance%", "DD/MM/YY"} }, new String [] { "#", "Tema", "Horas programadas", "Horas reales", "Fecha" } ) { boolean[] canEdit = new boolean [] { false, true, true, true, true }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); tablaTemas.setColumnSelectionAllowed(true); tablaTemas.getTableHeader().setReorderingAllowed(false); jScrollPane2.setViewportView(tablaTemas); tablaTemas.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); if (tablaTemas.getColumnModel().getColumnCount() > 0) { tablaTemas.getColumnModel().getColumn(0).setResizable(false); tablaTemas.getColumnModel().getColumn(1).setResizable(false); tablaTemas.getColumnModel().getColumn(2).setResizable(false); tablaTemas.getColumnModel().getColumn(3).setResizable(false); tablaTemas.getColumnModel().getColumn(4).setResizable(false); } addtema.setText("Añadir"); addtema.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addtemaActionPerformed(evt); } }); eliminartema.setText("Eliminar seleccionado"); eliminartema.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { eliminartemaActionPerformed(evt); } }); jLabel8.setText("Prácticas"); tablaPracticas.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, " ", " ", "DD/MM/YY-DD/MM/YY"} }, new String [] { "#", "Nombre", "Unidad", "Fecha programada y realizada" } ) { boolean[] canEdit = new boolean [] { false, true, true, true }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); tablaPracticas.setColumnSelectionAllowed(true); tablaPracticas.getTableHeader().setReorderingAllowed(false); jScrollPane3.setViewportView(tablaPracticas); tablaPracticas.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); if (tablaPracticas.getColumnModel().getColumnCount() > 0) { tablaPracticas.getColumnModel().getColumn(0).setResizable(false); tablaPracticas.getColumnModel().getColumn(1).setResizable(false); tablaPracticas.getColumnModel().getColumn(2).setResizable(false); tablaPracticas.getColumnModel().getColumn(3).setResizable(false); } addpractica.setText("Añadir"); addpractica.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addpracticaActionPerformed(evt); } }); eliminapractica.setText("Eliminar seleccionado"); eliminapractica.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { eliminapracticaActionPerformed(evt); } }); jLabel9.setText("Visitas"); tablaVisitas.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, " ", " ", "DD/MM/YY-DD/MM/YY"} }, new String [] { "#", "Empresa", "Unidad", "Fecha programada y realizada" } ) { boolean[] canEdit = new boolean [] { false, true, true, true }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); tablaVisitas.setColumnSelectionAllowed(true); tablaVisitas.getTableHeader().setReorderingAllowed(false); jScrollPane4.setViewportView(tablaVisitas); tablaVisitas.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); if (tablaVisitas.getColumnModel().getColumnCount() > 0) { tablaVisitas.getColumnModel().getColumn(0).setResizable(false); tablaVisitas.getColumnModel().getColumn(1).setResizable(false); tablaVisitas.getColumnModel().getColumn(2).setResizable(false); tablaVisitas.getColumnModel().getColumn(3).setResizable(false); } addvisita.setText("Añadir"); addvisita.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addvisitaActionPerformed(evt); } }); eliminavisita.setText("Eliminar seleccionado"); eliminavisita.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { eliminavisitaActionPerformed(evt); } }); terminar.setText("Terminar"); terminar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { terminarActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jSeparator1) .addComponent(jSeparator2, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jSeparator3, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jSeparator4) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel1) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(materia, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(prof))) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(periodo, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(grupo))) .addGap(18, 18, 18) .addComponent(jLabel6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(carrera, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jLabel7)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 624, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(16, 16, 16) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(eliminartema, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(addtema, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addComponent(jLabel8) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 624, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(addpractica, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(eliminapractica))) .addComponent(jLabel9) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 624, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(addvisita, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(eliminavisita)))) .addGap(0, 15, Short.MAX_VALUE)))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(terminar) .addGap(364, 364, 364)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(materia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4) .addComponent(periodo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6) .addComponent(carrera, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(prof, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5) .addComponent(grupo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(33, 33, 33) .addComponent(jLabel7) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(addtema) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(eliminartema)) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(jLabel8) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(addpractica) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(eliminapractica)) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(jLabel9) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSeparator4, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(addvisita) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(eliminavisita))) .addGap(18, 18, 18) .addComponent(terminar) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jScrollPane1.setViewportView(jPanel1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 743, javax.swing.GroupLayout.PREFERRED_SIZE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void addtemaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addtemaActionPerformed mdl1.addRow(new Object[]{mdl1.getRowCount(),"","","",""}); }//GEN-LAST:event_addtemaActionPerformed private void eliminartemaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_eliminartemaActionPerformed if(sel1>0){ mdl1.removeRow(sel1); } }//GEN-LAST:event_eliminartemaActionPerformed private void addpracticaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addpracticaActionPerformed mdl2.addRow(new Object[]{mdl2.getRowCount(),"","",""}); }//GEN-LAST:event_addpracticaActionPerformed private void eliminapracticaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_eliminapracticaActionPerformed if(sel2>0){ mdl2.removeRow(sel2); } }//GEN-LAST:event_eliminapracticaActionPerformed private void addvisitaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addvisitaActionPerformed mdl3.addRow(new Object[]{mdl3.getRowCount(),"","",""}); }//GEN-LAST:event_addvisitaActionPerformed private void eliminavisitaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_eliminavisitaActionPerformed if(sel3>0){ mdl3.removeRow(sel3); } }//GEN-LAST:event_eliminavisitaActionPerformed private void terminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_terminarActionPerformed if(validacampos()){ if(validatabla(tablaTemas)&&validatabla(tablaPracticas)&&validatabla(tablaVisitas)){ if(checkTableCells(tablaTemas)&&checkTableCells(tablaPracticas)&&checkTableCells(tablaVisitas)){ try{ PreparedStatement st=conexion.darConsultaPreparada("insert into materia values(default,?,?,?,?,?)"); st.setString(1,getS(materia)); st.setString(2,getS(periodo)); st.setString(3,getS(prof)); st.setString(4,getS(carrera)); st.setString(5,getS(grupo)); st.execute(); st.close(); ResultSet res=conexion.ConsultaSelect("select last_insert_id() as id;"); res.first(); int idmateria=res.getInt("id"); for(int _i=1;_i<mdl1.getRowCount();_i++){ ArrayList<Object>owo=new ArrayList<>(); for(int _j=0;_j<mdl1.getColumnCount();_j++){ owo.add(tablaTemas.getValueAt(_i,_j)); } if(owo.size()!=0){ st=conexion.darConsultaPreparada("insert into temas values(default,?,?,?,?)"); st.setInt(1,idmateria); st.setString(2,owo.get(1).toString()); st.setString(3,owo.get(2).toString()); st.setString(4,owo.get(3).toString()); st.execute(); st.close(); } } for(int _i=1;_i<mdl2.getRowCount();_i++){ ArrayList<Object>owo=new ArrayList<>(); for(int _j=0;_j<mdl2.getColumnCount();_j++){ owo.add(tablaPracticas.getValueAt(_i,_j)); } if(owo.size()>0){ st=conexion.darConsultaPreparada("insert into practicas values(default,?,?,?,?)"); st.setInt(1,idmateria); st.setString(2,owo.get(1).toString()); st.setString(3,owo.get(2).toString()); st.setString(4,owo.get(3).toString()); st.execute(); st.close(); } } for(int _i=1;_i<mdl3.getRowCount();_i++){ ArrayList<Object>owo=new ArrayList<>(); for(int _j=0;_j<mdl3.getColumnCount();_j++){ owo.add(tablaVisitas.getValueAt(_i,_j)); } if(owo.size()!=0){ st=conexion.darConsultaPreparada("insert into visitas values(default,?,?,?,?)"); st.setInt(1,idmateria); st.setString(2,owo.get(1).toString()); st.setString(3,owo.get(2).toString()); st.setString(4,owo.get(3).toString()); st.execute(); st.close(); } } }catch(Exception e){e.printStackTrace();} PrintFrameToPDF(new File("documento"+System.currentTimeMillis()+".pdf")); javax.swing.JOptionPane.showMessageDialog(null,"Éxito"); } else{ javax.swing.JOptionPane.showMessageDialog(null,"Existen campos incorrectos en las tablas, favor de verificar"); } } else{ javax.swing.JOptionPane.showMessageDialog(null,"Se requieren todos los campos de las tablas"); } } else{ javax.swing.JOptionPane.showMessageDialog(null,"Se requieren todos los campos"); } }//GEN-LAST:event_terminarActionPerformed public String getS(JTextField campo){ return campo.getText(); } public boolean validacampos(){ return getS(carrera).length()>0&&getS(grupo).length()>0&&getS(materia).length()>0&&getS(prof).length()>0&&getS(periodo).length()>0; } public boolean checkTableCells(JTable tbl){ DefaultTableModel mdl=(DefaultTableModel) tbl.getModel(); if(mdl.getRowCount()>1){ System.out.println("\t owo cells "+mdl.getColumnName(1)); if(mdl.getColumnName(1).equals("Tema")){ for(int _i=1;_i<mdl.getRowCount();_i++){ if(!(tbl.getValueAt(_i,2).toString().matches(horasTema)&&tbl.getValueAt(_i,3).toString().matches(horasTema)&&tbl.getValueAt(_i,4).toString().matches(fecha))){ return false; } } } else if(mdl.getColumnName(1).equals("Nombre")||mdl.getColumnName(1).equals("Empresa")){ for(int _i=1;_i<mdl.getRowCount();_i++){ if(!(tbl.getValueAt(_i,2).toString().matches("(\\d{1,2})")&&tbl.getValueAt(_i,3).toString().matches(fechaprog))){ return false; } } } } return true; } public boolean validatabla(JTable tbl){ DefaultTableModel mdl=(DefaultTableModel) tbl.getModel(); if(mdl.getRowCount()>1){ for(int _i=1;_i<mdl.getRowCount();_i++){ for(int _j=0;_j<mdl.getColumnCount();_j++){ if(tbl.getValueAt(_i,_j).toString().length()==0){ return false; } } } } else{ return false; } return true; } public void PrintFrameToPDF(File file) { try { Document d = new Document(); PdfWriter writer = PdfWriter.getInstance(d, new FileOutputStream(file)); d.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate template = cb.createTemplate(PageSize.LETTER.getWidth(),PageSize.LETTER.getHeight()); cb.addTemplate(template, 0, 0); Graphics2D g2d = template.createGraphics(PageSize.LETTER.getWidth(),PageSize.LETTER.getHeight()); g2d.scale(0.4, 0.4); for(int i=0; i< this.getContentPane().getComponents().length; i++){ Component c = this.getContentPane().getComponent(i); if(c instanceof JLabel || c instanceof JScrollPane){ g2d.translate(c.getBounds().x,c.getBounds().y); if(c instanceof JScrollPane){c.setBounds(0,0,(int)PageSize.LETTER.getWidth()*2,(int)PageSize.LETTER.getHeight()*2);} c.paintAll(g2d); c.addNotify(); } } g2d.dispose(); d.close(); } catch (Exception e) { System.out.println("ERROR: " + e.toString()); } } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Registrar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Registrar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Registrar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Registrar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Registrar().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton addpractica; private javax.swing.JButton addtema; private javax.swing.JButton addvisita; private javax.swing.JTextField carrera; private javax.swing.JButton eliminapractica; private javax.swing.JButton eliminartema; private javax.swing.JButton eliminavisita; private javax.swing.JTextField grupo; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JScrollPane jScrollPane4; private javax.swing.JSeparator jSeparator1; private javax.swing.JSeparator jSeparator2; private javax.swing.JSeparator jSeparator3; private javax.swing.JSeparator jSeparator4; private javax.swing.JTextField materia; private javax.swing.JTextField periodo; private javax.swing.JTextField prof; private javax.swing.JTable tablaPracticas; private javax.swing.JTable tablaTemas; private javax.swing.JTable tablaVisitas; private javax.swing.JButton terminar; // End of variables declaration//GEN-END:variables private DefaultTableModel mdl1,mdl2,mdl3; private int sel1,sel2,sel3; private final String horasTema="(\\d{1,2}:\\d{2})\\/(\\d{1,2}:\\d{2})-(\\d{1,3})%",fecha="(\\d{2}\\/\\d{2}\\/\\d{2})",fechaprog="(\\d{2}\\/\\d{2}\\/\\d{2})-(\\d{2}\\/\\d{2}\\/\\d{2})"; private ConexionSQL conexion; }
package com.coalesce.chat; import com.coalesce.plugin.CoPlugin; import org.bukkit.ChatColor; import static org.bukkit.ChatColor.*; public final class CoFormatter { private String prefix; //Constants private final static int CENTER_PX = 154; public CoFormatter() { this.prefix = GRAY + "[" + AQUA + "CoalesceCore" + GRAY + "]" + RESET; } public CoFormatter(CoPlugin plugin) { this.prefix = GRAY + "[" + WHITE + plugin.getDisplayName() + GRAY + "]" + RESET; } public String format(String message) { return prefix + " " + message; } /** * Centers a string for chat. * * @param message The message to center in chat. * @return A centered string. */ public String centerString(String message) { if (message == null || message.equals("")) { return ""; } message = ChatColor.translateAlternateColorCodes('&', message); int messagePxSize = getWidth(message); int halvedMessageSize = messagePxSize / 2; int toCompensate = CENTER_PX - halvedMessageSize; int spaceLength = FontInfo.getCharSize(' '); int compensated = 0; StringBuilder sb = new StringBuilder(); while (compensated < toCompensate) { sb.append(" "); compensated += spaceLength; } return sb.toString() + message; } /** * Gets the width of the string message. * * @param message The message to get the width of. * @return The width (in pixels) of the string in minecraft. */ public int getWidth(String message) { int messagePxSize = 0; boolean previousCode = false; boolean isBold = false; for (char c : message.toCharArray()) { if (c == '\u00A7') { previousCode = true; continue; } else if (previousCode == true) { previousCode = false; if (c == 'l' || c == 'L') { isBold = true; continue; } else { isBold = false; } } else { messagePxSize += FontInfo.getCharSize(c, isBold); } } return messagePxSize; } /** * Alternate color codes in a string, if the chars variable is null then it will use a rainbow effect. * If string already contains color codes, they will be stripped. * * @param str String to add color to. * @param chars Colors that will be alternated in the string, if null then its rainbow. * @return Changed String */ public String rainbowifyString(String str, char... chars) { str = ChatColor.stripColor(str); if (chars == null || chars.length == 0) { chars = new char[]{'c', '6', 'e', 'a', 'b', '3', 'd'}; } int index = 0; String returnValue = ""; for (char c : str.toCharArray()) { returnValue += "&" + chars[index] + c; index++; if (index == chars.length) { index = 0; } } return ChatColor.translateAlternateColorCodes('&', returnValue); } }
package com.quickblox.sample.videochatwebrtcnew.definitions; public class Consts { public static final String APP_ID = "92"; public static final String AUTH_KEY = "wJHdOcQSxXQGWx5"; public static final String AUTH_SECRET = "BTFsj7Rtt27DAmT"; public static final String EMPTY_STRING = ""; public static final int CALL_ACTIVITY_CLOSE = 1000; //CALL ACTIVITY CLOSE REASONS public static final int CALL_ACTIVITY_CLOSE_WIFI_DISABLED = 1001; public static final String WIFI_DISABLED = "wifi_disabled"; }
package exceptions.exceptionmappers; import javax.ws.rs.NotFoundException; import javax.ws.rs.core.Response; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; @Provider public class NietGevondenExceptionMapper implements ExceptionMapper<NotFoundException> { @Override public Response toResponse(NotFoundException e) { return Response.status(401).entity(e).build(); } }
import java.io.Serializable; import java.util.GregorianCalendar; @SuppressWarnings("serial") public class MyDate implements Serializable { private int minute; private int hour; private int day; private int month; private int year; public MyDate() { GregorianCalendar currentDate = new GregorianCalendar(); minute = currentDate.get(GregorianCalendar.MINUTE); hour = currentDate.get(GregorianCalendar.HOUR); day = currentDate.get(GregorianCalendar.DATE); // Add a value of plus one to add to the initial value of 0. month = currentDate.get(GregorianCalendar.MONTH) + 1; year = currentDate.get(GregorianCalendar.YEAR); } public MyDate(int minute, int hour, int day, int month, int year) { this.minute = minute; this.hour = hour; this.day = day; this.month = month; this.year = year; } public int getMinute() { return minute; } public int getHour() { return hour; } public int getDay() { return day; } public int getMonth() { return month; } public int getYear() { return year; } public void setMinute(int minute) { this.minute = minute; } public void setHour(int hour) { this.hour = hour; } public void setDay(int day) { this.day = day; } public void setMonth(int month) { this.month = month; } public void setYear(int year) { this.year = year; } public static MyDate currentDate() { return new MyDate(); } public void setDate(int mimnute, int hour, int day, int month, int year) { // SafeGuard for invalid inputs. this.day = day; this.month = month; this.year = year; if (hour < 0) { hour = hour * -1; } if (hour > 23) { hour = 23; } if (minute < 0) { minute = minute * -1; } if (minute > 59) { minute = 59; } if (day > numberOfDaysInMonth(month)) { day = numberOfDaysInMonth(month); } if (month < 1) { month = 1; } if (year < 0) { year = year * -1; } } public static int monthNameToString(String month) { switch (month.toLowerCase()) { case "january": return 1; case "february": return 2; case "march": return 3; case "april": return 4; case "may": return 5; case "june": return 6; case "july": return 7; case "august": return 8; case "september": return 9; case "october": return 10; case "november": return 11; case "december": return 12; default: return -1; } } public void setDateMonth(int hour, int minute, int day, String month, int year) { setDate(hour, minute, day, monthNameToString(month), year); } public boolean isOtherDate(MyDate other) { if (year < other.getYear()) return true; else if (year == other.getYear()) if (month < other.getMonth()) return true; else if (month == other.getMonth()) if (day < other.getDay()) return true; if (hour < other.getDay()) return true; else if (hour == other.getHour()) if (minute < other.getMinute()) return true; return false; } public boolean isLeapYear() { if (year % 400 == 0) { return true; } else if (year % 100 != 0 && year % 4 == 0) return true; return false; } public int numberOfDaysInMonth(int month) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) return 31; else if (month != 2) return 30; else if (isLeapYear()) return 29; else return 28; } public MyDate copy() { return new MyDate(minute, hour, day, month, year); } public int daysBetween(MyDate other) { MyDate baseDate; MyDate focusDate; if (isOtherDate(other)) { baseDate = this.copy(); focusDate = other.copy(); } else { baseDate = other.copy(); focusDate = this.copy(); } int i = 0; while (!baseDate.equals(focusDate)) { baseDate.stepForwardOneDay(); i++; } return i; } public int yearsBetween(MyDate other) { if (!isOtherDate(other)) { return other.yearsBetween(this); } int dayDifference = day - other.getDay(); int monthDifference = month - other.getMonth(); int j = 0; if (monthDifference > 0) j++; else if (monthDifference == 0) if (dayDifference > 0) j++; return other.getYear() - year - j; } public void stepForwardOneDay() { day++; if (day > numberOfDaysInMonth(month)) { day = 1; month++; } if (month > 12) { month = 1; year++; } } public void stepForward(int days) { for (int i = 0; i < days; i++) stepForwardOneDay(); } public boolean equals(Object input) { if (!(input instanceof MyDate)) return false; else { MyDate obj = (MyDate) input; if (day == obj.day && month == obj.month && year == obj.year) return true; else return false; } } public String toString() { if (month < 10) { String myDate = day + "/0" + month + "/" + year; return myDate; } else { String myDate = day + "/" + month + "/" + year; return myDate; } } }
package omicron_15; import java.awt.Graphics; //System Manager public class ComboDealer { public OrderManager oD; public WebManager wM; private Scenario sO; private ScoreControler sC; public ComboDealer(){ this.oD=new OrderManager(this); this.wM=new WebManager(3); this.sC=new ScoreControler(); } public void paintComponent(Graphics g){ this.sC.paint(g); this.wM.paintNode(g); } public void reciber(int key){ this.oD.builder(key); System.out.println("Orden recibida "+key); } public void timelapse() { this.oD.incrementer(); } public void getScore(String key) { this.sC.scoreMaker(key); } public void CharacterMovement() { this.wM.incrementNode(); } } class ComboKiller{ }
package server.rest.controllers; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import server.database.DatabaseConnection; import server.model.HRPayGrade; import server.rest.responses.HRAddEditPayGradeResponse; import server.rest.responses.HRPayGradeResponse; import server.rest.responses.Response; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; /** * Controller for HR PayGrade table * Provides all the REST endpoints related to HR Pay Grades and stored SQL procedures */ @CrossOrigin(origins = {"http://localhost:1234","http://theterminal.s3-website.us-west-2.amazonaws.com"}) @RestController public class HRPayGradeController extends Controller { private static String getQuery = "select * from HRPayGrade"; private static String addQuery = "insert into HRPayGrade values(?, ?, ?, ?)"; private static String editQuery = "update HRPayGrade set startAmount=?, endAmount=?, name=? where id=?"; /** * Get all the paygrades in the database * @return The list of all paygrades * @throws SQLException if something goes wrong whilst querying the database */ public ArrayList<HRPayGrade> getPayGrades() throws SQLException{ DatabaseConnection connection = new DatabaseConnection(dbConnectionUrl, dbUsername, dbPassword); ArrayList<HRPayGrade> payGrades = new ArrayList<HRPayGrade>(); connection.openConnection(); if(!connection.isConnected()) { throw new SQLException("Failed to connect to database"); } PreparedStatement st = connection.getPreparedStatement(getQuery); ResultSet set = st.executeQuery(); while(set.next()) { HRPayGrade payGrade = new HRPayGrade(set.getString("id"), set.getInt("startAmount"), set.getInt("endAmount"), set.getString("name")); payGrades.add(payGrade); } connection.closeConnection(); return payGrades; } /** * Adds a pay grade to the database * @param startAmt The start amount * @param endAmt The end amount * @param name The name of the pay grade * @return Newly created paygrade object * @throws SQLException */ public HRPayGrade addPayGrade(int startAmt, int endAmt, String name) throws SQLException { DatabaseConnection connection = new DatabaseConnection(dbConnectionUrl, dbUsername, dbPassword); String id = UUID.randomUUID().toString(); HRPayGrade payGrade = new HRPayGrade(id, startAmt, endAmt, name); connection.openConnection(); if (!connection.isConnected()) { throw new SQLException("Failed to connect to database"); } PreparedStatement st = connection.getPreparedStatement(addQuery); int index = 1; st.setString(index++, payGrade.getId()); st.setInt(index++, payGrade.getStartAmount()); st.setInt(index++, payGrade.getEndAmount()); st.setString(index++, payGrade.getName()); int success = st.executeUpdate(); if (success == 0) { throw new SQLException("Failed to add Pay Grade"); } connection.commitTransaction(); connection.closeConnection(); return payGrade; } /** * Update an existing pay grade in the database * @param id ID of the paygrade to update * @param startAmt Start amount of the paygrade * @param endAmt End amount of the pay grade * @param name Name of the pay grade * @return The updated pay grade object * @throws SQLException */ public HRPayGrade editPayGrade(String id, int startAmt, int endAmt, String name) throws SQLException { DatabaseConnection connection = new DatabaseConnection(dbConnectionUrl, dbUsername, dbPassword); HRPayGrade payGrade = new HRPayGrade(id, startAmt, endAmt, name); connection.openConnection(); if (!connection.isConnected()) { throw new SQLException("Failed to connect to database"); } PreparedStatement st = connection.getPreparedStatement(editQuery); int index = 1; st.setInt(index++, payGrade.getStartAmount()); st.setInt(index++, payGrade.getEndAmount()); st.setString(index++, payGrade.getName()); st.setString(index++, payGrade.getId()); int success = st.executeUpdate(); if (success == 0) { throw new SQLException("Failed to edit Paygrade"); } connection.commitTransaction(); connection.closeConnection(); return payGrade; } /** * REST API link to view all the pay grades * @param token The unique token of the user making the API call * @return Response containing all the paygrades or an error response */ @RequestMapping("/paygrades/view") public HRPayGradeResponse paygrades(@RequestParam("token") String token) { if (!isUserLoggedIn(token)) { return HRPayGradeResponse.hrPayGradeFailure("User is not logged in"); } ArrayList<HRPayGrade> payGrades; try { payGrades = this.getPayGrades(); } catch (SQLException e) { Logger logger = Logger.getAnonymousLogger(); logger.log(Level.INFO, "Get HRPayGrades Failed: " + e.getMessage()); return HRPayGradeResponse.hrPayGradeFailure(e.getMessage()); } return new HRPayGradeResponse(payGrades); } /** * REST API link to add a pay grade in the database * @param token The unique token of the User making the API call * @param startAmt The start amount of the pay grade * @param endAmt The end amount of the pay grade * @param name The name of the pay grade * @return Response containing the newly added paygrade or an error response */ @RequestMapping("/paygrades/add") public Response addPayGrade( @RequestParam("token") String token, @RequestParam("startAmount") int startAmt, @RequestParam("endAmount") int endAmt, @RequestParam("name") String name){ if (!isUserLoggedIn(token)) { return HRAddEditPayGradeResponse.payGradeFailure("User is not logged in"); } HRPayGrade payGrade; try { payGrade = this.addPayGrade(startAmt, endAmt, name); } catch(SQLException e) { Logger logger = Logger.getAnonymousLogger(); logger.log(Level.INFO, "Add Paygrades failed" + e.getMessage()); return HRAddEditPayGradeResponse.payGradeFailure(e.getMessage()); } return new HRAddEditPayGradeResponse(payGrade); } /** * REST API link to edit a pay grade in the database * @param token The unique token of the User making the API call * @param id The id of the pay grade being edited * @param startAmt The start amount of the pay grade * @param endAmt The end amount of the pay grade * @param name The name of the pay grade * @return Response containing the updated paygrade or an error response */ @RequestMapping("/paygrades/edit") public HRAddEditPayGradeResponse editPayGrade( @RequestParam("token") String token, @RequestParam("id") String id, @RequestParam("startAmount") int startAmt, @RequestParam("endAmount") int endAmt, @RequestParam("name") String name){ if (!isUserLoggedIn(token)) { return HRAddEditPayGradeResponse.payGradeFailure("User is not logged in"); } HRPayGrade payGrade; try { payGrade = this.editPayGrade(id, startAmt, endAmt, name); } catch (SQLException e) { Logger logger = Logger.getAnonymousLogger(); logger.log(Level.INFO, "Edit Paygrade failed" + e.getMessage()); return HRAddEditPayGradeResponse.payGradeFailure(e.getMessage()); } return new HRAddEditPayGradeResponse(payGrade); } }
package com.sorting; import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.regex.*; public class closestNumber { // Complete the closestNumbers function below. private static int[] closestNumbers(int[] arr) { Arrays.sort(arr); int size = arr.length; int min = Integer.MAX_VALUE; for(int i = 1; i < size; i++){ if(min > (arr[i] - arr[i-1])){ min = Math.abs(arr[i] - arr[i-1]); } } List<Integer> a = new ArrayList<>(); for(int i = 1; i < size; i++){ if(Math.abs(arr[i-1] - arr[i]) == min){ a.add(arr[i-1]); a.add(arr[i]); } } int[] ret = new int[a.size()]; for (int i=0; i < ret.length; i++) { ret[i] = a.get(i).intValue(); } return ret; } public static void main(String[] args) throws IOException { Scanner scanner = new Scanner(new FileInputStream(new File("input/dummy"))); int n = scanner.nextInt(); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); int[] arr = new int[n]; String[] arrItems = scanner.nextLine().split(" "); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); for (int i = 0; i < n; i++) { int arrItem = Integer.parseInt(arrItems[i]); arr[i] = arrItem; } int[] result = closestNumbers(arr); for (int i = 0; i < result.length; i++) { System.out.println(String.valueOf(result[i])); if (i != result.length - 1) { System.out.print(" "); } } System.out.println(); scanner.close(); } }
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class Demo { public static void main(String[] args) { Employee[]emp=new Employee[3]; emp[0]=new Employee(3, "david", 4000, "IT"); emp[2]=new Employee(2, "tani", 5000, "Klaus"); System.out.println("gefore sorting"); // for (employee employee : emp) { // System.out.println(employee); // } // // System.out.println(); // //Arrays.sort(emp); // for (employee employee : emp) { // System.out.println(employee); // } ArrayList<Employee>list=new ArrayList<>(); list.add(new Employee(1, "daminik", 3000, "IT")); list.add(new Employee(3, "dvminik", 3000, "IT")); list.add(new Employee(2, "dominik", 3000, "IT")); //Collections.sort((List<employee>)); for (Employee employee : list) { System.out.println(employee); } } }
package com.github.ntltl.money; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Assertions.*; public class RmbTest { @Test void sum() { // Rmb rmb = new Rmb(); } }
package com.lrs.admin.controller; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.lrs.admin.controller.base.BaseController; import com.lrs.admin.entity.ReturnModel; import com.lrs.admin.service.IEsotericaService; import com.lrs.admin.util.Jurisdiction; import com.lrs.admin.util.ParameterMap; @Controller @RequestMapping("/esoterica") public class EsotericaController extends BaseController{ private String qxurl = "esoterica/list"; @Autowired private IEsotericaService esotericaService; @GetMapping("/list") public Object list(Model model){ if(!Jurisdiction.buttonJurisdiction(qxurl,"query", this.getSession())){return ReturnModel.getNotAuthModel();} ParameterMap pm = this.getParameterMap(); Map<String,Object> map = esotericaService.getSpeechraftList(pm); model.addAttribute("lists", map.get("data")); model.addAttribute("page", map.get("page")); return "page/esoterica/list"; } @GetMapping("/list/{page_no}") public Object listPage(Model model,@PathVariable("page_no") String pageNo){ if(!Jurisdiction.buttonJurisdiction(qxurl,"query", this.getSession())){return ReturnModel.getNotAuthModel();} ParameterMap pm = this.getParameterMap(); pm.put("page_no", pageNo); System.out.println("pageNo="+pageNo); Map<String,Object> map = esotericaService.getSpeechraftList(pm); model.addAttribute("lists", map.get("data")); model.addAttribute("page", map.get("page")); model.addAttribute("type", pm.getString("type")); model.addAttribute("kw", pm.getString("kw")); return "page/esoterica/list"; } /** * 保存 * @return */ @PostMapping("/save") @ResponseBody public Object save(){ if(!Jurisdiction.buttonJurisdiction(qxurl,"add", this.getSession())){return ReturnModel.getNotAuthModel();} return esotericaService.save(getParameterMap()); } /** * 更新 * @return */ @PostMapping("/update") @ResponseBody public Object update(){ if(!Jurisdiction.buttonJurisdiction(qxurl,"edit", this.getSession())){return ReturnModel.getNotAuthModel();} return esotericaService.update(getParameterMap()); } /** * 删除 * @return */ @PostMapping("/del") @ResponseBody public Object del(){ if(!Jurisdiction.buttonJurisdiction(qxurl,"del", this.getSession())){return ReturnModel.getNotAuthModel();} return esotericaService.del(getParameterMap()); } }
package com.codingdojo.world.services; import java.util.List; import org.springframework.stereotype.Service; import com.codingdojo.world.models.Country; import com.codingdojo.world.models.Language; import com.codingdojo.world.repository.CityRepository; import com.codingdojo.world.repository.CountryRepository; import com.codingdojo.world.repository.LanguageRepository; @Service public class ApiService { private final CountryRepository countryRepo; private final LanguageRepository languageRepo; private final CityRepository cityRepo; public ApiService(CountryRepository countryRepo, LanguageRepository languageRepo, CityRepository cityRepo) { this.countryRepo = countryRepo; this.languageRepo = languageRepo; this.cityRepo = cityRepo; } public List<Object[]> question1() { List<Object[]> table = countryRepo.joinAllCountriesSlovene(); return table; } public List<Object[]> question2(){ List<Object[]> table = countryRepo.findAllCountriesTotalCities(); return table; } public List<Object[]> question3(){ List<Object[]> table = cityRepo.findCitiesMexicoPopulation(); return table; } public List<Object[]> question4(){ List<Object[]> table = languageRepo.findAllCountriesLanguegePercentage(); return table; } public List<Object[]> question5(){ List<Object[]> table = countryRepo.findallCountriesSurfaceArea500(); return table; } public List<Object[]> question6(){ List<Object[]> table = countryRepo.findAllCountriesGovermentFormMonarchy(); return table; } public List<Object[]> question7(){ List<Object[]> table = cityRepo.findCitiesInDistrictBuenosAires(); return table; } public List<Object[]> question8(){ List<Object[]> table = countryRepo.findAllCountCitiesForRegion(); return table; } }
package com.stackfortech.redispubsub.controller; import com.stackfortech.redispubsub.configuration.RedisMessagePublisher; import com.stackfortech.redispubsub.configuration.RedisMessageSubscriber; import com.stackfortech.redispubsub.model.Message; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/api/redis") public class RedisController { private static Logger logger = LoggerFactory.getLogger(RedisController.class); @Autowired private RedisMessagePublisher messagePublisher; @PostMapping("/publish") public void publish(@RequestBody Message message) { logger.info(">> publishing : {}", message); messagePublisher.publish(message.toString()); } @GetMapping("/subscribe") public List<String> getMessages(){ return RedisMessageSubscriber.messageList; } }
package com.cg.project.castleglobalproject.base.network.base; import com.cg.project.castleglobalproject.base.network.base.params.exception.ParameterMissingException; import com.cg.project.castleglobalproject.base.network.base.params.exception.ParameterReadException; import com.cg.project.castleglobalproject.base.network.base.response.BaseResponse; import java.util.Map; public interface IHttpClient<DATA_OUT extends BaseResponse> { void success(DATA_OUT data); void failure(byte[] bytes); String getPath(); Map<String, String> getParams() throws ParameterMissingException, ParameterReadException; byte[] getData(); int getMethod(); Class<DATA_OUT> getClazz(); }
package org.lqz.module.view; import java.awt.*; import java.awt.event.*; import java.awt.geom.Ellipse2D; import java.util.Calendar; import javax.swing.*; public class SuperClock { public static void main(String []args) { new SCframe(); } } class SCframe extends JFrame { SCpanel panel=new SCpanel(); public SCframe() { final Point origin=new Point(0,0); int w=440; int h=440; setUndecorated(true); //setDefaultLookAndFeelDecorated(true); com.sun.awt.AWTUtilities.setWindowShape(this, new Ellipse2D.Double(0, 0,w,h)); com.sun.awt.AWTUtilities.setWindowOpacity(this, 0.75f); Toolkit kit = Toolkit.getDefaultToolkit(); Dimension D=kit.getScreenSize(); setBounds((D.width-w)/2,(D.height-h)/2,w,h); panel.setBackground(Color.black); add(panel); setVisible(true); addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { super.mousePressed(e); origin.x=e.getX(); origin.y=e.getY(); } }) ; addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseDragged(MouseEvent e) { super.mouseDragged(e); Point p=getLocation(); //窗口当前位置+鼠标当前位置-鼠标按下位置 setLocation(p.x+e.getX()-origin.x,p.y+e.getY()-origin.y); } }); addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { super.keyPressed(e); if (KeyEvent.VK_ESCAPE == e.getKeyCode()) { System.exit(0); } } }); while(true) { panel.repaint(); } } } class SCpanel extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2=(Graphics2D)g; Calendar curtime =Calendar.getInstance() ; //绘制表盘 g2.translate(220,220); int i=0; double E=0.0; double R=200; double []x1=new double[31]; double []y1=new double[31]; double []_x1=new double[31]; double [] _y1=new double[31]; double []x2=new double[31]; double []_x2=new double[31]; double []y2=new double[31]; double [] _y2=new double[31]; final double PI=3.1416; g2.setPaint(Color.white); //设置颜色 g2.setStroke(new BasicStroke(3)); //设置线条宽度 E=0.0; for(i=0;i<31;i++) { if(i%5==0) //设置红色 { g2.setPaint(Color.red); } if(i%15==0) { x1[i]=(R-12.0)*Math.cos(E*PI/180.0); y1[i]=(R-12.0)*Math.sin(E*PI/180.0); } else { x1[i]=(R-5.0)*Math.cos(E*PI/180.0); y1[i]=(R-5.0)*Math.sin(E*PI/180.0); } _x1[i]=-x1[i]; _y1[i]=-y1[i]; x2[i]=(R+5.0)*Math.cos(E*PI/180.0); y2[i]=(R+5.0)*Math.sin(E*PI/180.0); _x2[i]=-x2[i]; _y2[i]=-y2[i]; g2.drawLine((int)x1[i],(int)y1[i],(int)x2[i],(int)y2[i]); g2.drawLine((int)_x1[i],(int)_y1[i],(int)_x2[i],(int)_y2[i]); E+=6.0; if(i%5==0) { g2.setPaint(Color.white); } } //绘制指针 int hour=curtime.get(Calendar.HOUR_OF_DAY); int minute=curtime.get(Calendar.MINUTE); int second=curtime.get(Calendar.SECOND); g2.setPaint(Color.RED); //设置颜色 g2.setStroke(new BasicStroke(1)); //设置线条宽度 g2.drawLine(0,0,(int)((R-15.0)*Math.cos( ((double) second/60.0-0.25)*PI*2.0) ),(int)((R-15.0)*Math.sin( ((double) second/60.0-0.25)*PI*2.0) )); g2.setPaint(Color.BLUE); g2.setStroke(new BasicStroke(4)); g2.drawLine(0,0,(int)((R-25.0)*Math.cos( ((double) minute/60.0-0.25)*PI*2.0) ),(int)((R-25.0)*Math.sin( ((double) minute/60.0-0.25)*PI*2.0) )); g2.setPaint(Color.DARK_GRAY); g2.setStroke(new BasicStroke(7)); g2.drawLine(0,0,(int)((R-70.0)*Math.cos( ((double) hour/12.0-0.25)*PI*2.0) ),(int)((R-70.0)*Math.sin( ((double) hour/12.0-0.25)*PI*2.0) )); g2.setPaint(Color.white); g2.setStroke(new BasicStroke(1)); g2.fillArc(-7,-7,14,14,0,360); } }
/** * MOTECH PLATFORM OPENSOURCE LICENSE AGREEMENT * * Copyright (c) 2010-11 The Trustees of Columbia University in the City of * New York and Grameen Foundation USA. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of Grameen Foundation USA, Columbia University, or * their respective contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY GRAMEEN FOUNDATION USA, COLUMBIA UNIVERSITY * AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRAMEEN FOUNDATION * USA, COLUMBIA UNIVERSITY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.motechproject.server.service.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.motechproject.server.service.ExpectedCareEvent; import org.motechproject.server.service.ExpectedCareSchedule; import org.motechproject.server.service.Requirement; import org.motechproject.server.svc.RegistrarBean; import org.motechproject.server.time.TimePeriod; import org.openmrs.Patient; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; public class ExpectedCareScheduleImpl implements ExpectedCareSchedule { private static Log log = LogFactory.getLog(ExpectedCareScheduleImpl.class); protected String name; protected Integer lateValue; protected TimePeriod latePeriod; protected Integer maxValue; protected TimePeriod maxPeriod; protected List<ExpectedCareEvent> events = new ArrayList<ExpectedCareEvent>(); protected List<Requirement> requirements = new ArrayList<Requirement>(); protected RegistrarBean registrarBean; public void updateSchedule(Patient patient, Date date) { log.debug("Evaluating schedule: " + name + ", patient: " + patient.getPatientId()); if (meetsRequirements(patient, date)) { performScheduleUpdate(patient, date); } else { log.debug("Failed to meet requisites, removing events for schedule"); removeExpectedCare(patient); } } public boolean meetsRequirements(Patient patient, Date date) { for (Requirement requirement : requirements) { if (!requirement.meetsRequirement(patient, date)) { return false; } } return true; } protected void performScheduleUpdate(Patient patient, Date date) { } protected void removeExpectedCare(Patient patient) { } protected Date getReferenceDate(Patient patient) { return patient.getBirthdate(); } protected boolean validReferenceDate(Date referenceDate, Date currentDate) { return referenceDate != null; } protected Date getMinDate(Date date, ExpectedCareEvent event) { return calculateDate(date, event.getMinValue(), event.getMinPeriod()); } protected Date getDueDate(Date date, ExpectedCareEvent event) { return calculateDate(date, event.getDueValue(), event.getDuePeriod()); } protected Date getLateDate(Date date, ExpectedCareEvent event) { if (event.getLateValue() != null && event.getLatePeriod() != null) { return calculateDate(date, event.getLateValue(), event.getLatePeriod()); } else { return calculateDate(date, lateValue, latePeriod); } } protected Date getMaxDate(Date date, ExpectedCareEvent event) { if (event.getMaxValue() != null && event.getMaxPeriod() != null) { return calculateDate(date, event.getMaxValue(), event.getMaxPeriod()); } else { return calculateDate(date, maxValue, maxPeriod); } } protected Date calculateDate(Date date, Integer value, TimePeriod period) { if (date == null || value == null || period == null) { return null; } Calendar calendar = Calendar.getInstance(); calendar.setTime(date); if (period.equals(TimePeriod.week)) calendar.add(period.getCalendarPeriod(), value * 7); else calendar.add(period.getCalendarPeriod(), value); return calendar.getTime(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getLateValue() { return lateValue; } public void setLateValue(Integer lateValue) { this.lateValue = lateValue; } public TimePeriod getLatePeriod() { return latePeriod; } public void setLatePeriod(TimePeriod latePeriod) { this.latePeriod = latePeriod; } public Integer getMaxValue() { return maxValue; } public void setMaxValue(Integer maxValue) { this.maxValue = maxValue; } public TimePeriod getMaxPeriod() { return maxPeriod; } public void setMaxPeriod(TimePeriod maxPeriod) { this.maxPeriod = maxPeriod; } public List<ExpectedCareEvent> getEvents() { return events; } public void setEvents(List<ExpectedCareEvent> events) { this.events = events; } public List<Requirement> getRequirements() { return requirements; } public void setRequirements(List<Requirement> requirements) { this.requirements = requirements; } public RegistrarBean getRegistrarBean() { return registrarBean; } public void setRegistrarBean(RegistrarBean registrarBean) { this.registrarBean = registrarBean; } }
package com.uzeal.db.dao; import java.lang.reflect.Field; import java.lang.reflect.Method; public class DBField { private Field field; private Method getMethod; private Method setMethod; private String dbName; public DBField() { } public DBField(Field field, Method getMethod, Method setMethod, String dbName) { super(); this.field = field; this.getMethod = getMethod; this.setMethod = setMethod; this.dbName = dbName; } public Field getField() { return field; } public void setField(Field field) { this.field = field; } public String getDbName() { return dbName; } public void setDbName(String dbName) { this.dbName = dbName; } public Method getGetMethod() { return getMethod; } public void setGetMethod(Method getMethod) { this.getMethod = getMethod; } public Method getSetMethod() { return setMethod; } public void setSetMethod(Method setMethod) { this.setMethod = setMethod; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("DBField [field=").append(field).append(", dbName=").append(dbName).append("]"); return builder.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((dbName == null) ? 0 : dbName.hashCode()); result = prime * result + ((field == null) ? 0 : field.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DBField other = (DBField) obj; if (dbName == null) { if (other.dbName != null) return false; } else if (!dbName.equals(other.dbName)) return false; if (field == null) { if (other.field != null) return false; } else if (!field.equals(other.field)) return false; return true; } }
package br.com.alura.carteira.controller; import java.net.URI; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.web.PageableDefault; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.util.UriComponentsBuilder; import br.com.alura.carteira.dto.UsuarioDto; import br.com.alura.carteira.dto.UsuarioFormDto; import br.com.alura.carteira.service.UsuarioService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; @RestController @RequestMapping("/usuarios") @Api(tags = "Usuario") public class UsuarioController { @Autowired private UsuarioService service; @GetMapping @ApiOperation("Listar usuarios") public Page<UsuarioDto> listar(@PageableDefault(size = 10) Pageable paginacao) { return service.listar(paginacao); } @PostMapping @ApiOperation("Cadastrar novo usuario") public ResponseEntity<UsuarioDto> cadastrar(@RequestBody @Valid UsuarioFormDto dto, UriComponentsBuilder uriBuilder) { UsuarioDto cadastrado = service.cadastrar(dto); URI endereco = uriBuilder.path("/usuarios/{id}").buildAndExpand(cadastrado.getId()).toUri(); return ResponseEntity.created(endereco).body(cadastrado); } }
package br.usp.memoriavirtual.controle; import java.io.Serializable; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.ejb.EJB; import javax.el.ELResolver; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.context.FacesContext; import br.usp.memoriavirtual.modelo.entidades.Aprovacao; import br.usp.memoriavirtual.modelo.entidades.Usuario; import br.usp.memoriavirtual.modelo.fachadas.ModeloException; import br.usp.memoriavirtual.modelo.fachadas.remoto.EditarCadastroUsuarioRemote; import br.usp.memoriavirtual.modelo.fachadas.remoto.ExcluirUsuarioRemote; import br.usp.memoriavirtual.modelo.fachadas.remoto.MemoriaVirtualRemote; import br.usp.memoriavirtual.utils.MVModeloAcao; import br.usp.memoriavirtual.utils.MVModeloEmailParser; import br.usp.memoriavirtual.utils.MVModeloEmailTemplates; import br.usp.memoriavirtual.utils.MVModeloMapeamentoUrl; import br.usp.memoriavirtual.utils.MVModeloParametrosEmail; @ManagedBean(name = "excluirUsuarioMB") @SessionScoped public class ExcluirUsuarioMB extends EditarCadastroUsuarioMB implements Serializable { private static final long serialVersionUID = -6957046653709643226L; @EJB private ExcluirUsuarioRemote excluirUsuarioEJB; @EJB private MemoriaVirtualRemote memoriaVirtualEJB; @EJB private EditarCadastroUsuarioRemote editarCadastroUsuarioEJB; private MensagensMB mensagens; public ExcluirUsuarioMB() { super(); FacesContext facesContext = FacesContext.getCurrentInstance(); ELResolver resolver = facesContext.getApplication().getELResolver(); this.mensagens = (MensagensMB) resolver.getValue(facesContext.getELContext(), null, "mensagensMB"); } @Override public String selecionarUsuario() { try { this.usuario = this.memoriaVirtualEJB.getUsuario(this.id); return this.redirecionar("/restrito/excluirusuario.jsf", true); } catch (ModeloException m) { this.getMensagens().mensagemErro(this.traduzir("erroInterno")); m.printStackTrace(); return null; } } public String solicitarExclusao() { if (this.validar()) { try { Calendar calendario = Calendar.getInstance(); calendario.setTime(new Date()); calendario.add(Calendar.DATE, 30); DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); String expiraEm = dateFormat.format(calendario.getTime()); Aprovacao aprovacao = new Aprovacao(); aprovacao.setAcao(MVModeloAcao.excluir_usuario); Usuario analista = memoriaVirtualEJB.getUsuario(this.analista); aprovacao.setAnalista(analista); aprovacao.setExpiraEm(calendario.getTime()); aprovacao.setSolicitante(this.solicitante); String dados = "id;" + new Long(this.usuario.getId()).toString() + ";justificativa;" + this.justificativa; aprovacao.setDados(dados); long id = this.excluirUsuarioEJB.solicitarExclusao( this.usuario, aprovacao); Map<String, String> tags = new HashMap<String, String>(); tags.put(MVModeloParametrosEmail.ANALISTA000.toString(), analista.getNomeCompleto()); tags.put(MVModeloParametrosEmail.EXPIRACAO000.toString(), expiraEm); tags.put(MVModeloParametrosEmail.JUSTIFICATIVA000.toString(), this.justificativa); tags.put(MVModeloParametrosEmail.SOLICITANTE000.toString(), this.solicitante.getNomeCompleto()); tags.put(MVModeloParametrosEmail.USUARIO000.toString(), this.usuario.getNomeCompleto()); Map<String, String> parametros = new HashMap<String, String>(); parametros.put("id", new Long(id).toString()); String url = this.memoriaVirtualEJB.getUrl( MVModeloMapeamentoUrl.excluirUsuario, parametros); tags.put(MVModeloParametrosEmail.URL000.toString(), url); String email = new MVModeloEmailParser().getMensagem(tags, MVModeloEmailTemplates.excluirUsuario); String assunto = this.traduzir("excluirUsuarioAssuntoEmail"); this.memoriaVirtualEJB.enviarEmail(analista.getEmail(), assunto, email); this.getMensagens().mensagemSucesso(this.traduzir("sucesso")); return this.redirecionar("/restrito/index.jsf", true); } catch (Exception e) { this.getMensagens().mensagemErro(this.traduzir("erroInterno")); e.printStackTrace(); return null; } } return null; } @Override public boolean validar() { return this.validarJustificativa(); } public MensagensMB getMensagens() { return mensagens; } public void setMensagens(MensagensMB mensagens) { this.mensagens = mensagens; } }
package com.lubarov.daniel.junkmail; import com.lubarov.daniel.data.option.Option; import com.lubarov.daniel.web.http.HttpRequest; import com.lubarov.daniel.web.http.HttpResponse; import com.lubarov.daniel.web.http.server.PartialHandler; public class InboxHandler implements PartialHandler { public static final InboxHandler singleton = new InboxHandler(); @Override public Option<HttpResponse> tryHandle(HttpRequest request) { return Option.none(); } }
package LC0_200.LC100_150; /** * 2020-09-23 10:07 PM at Hangzhou */ public class LC134_Gas_Station { public int canCompleteCircuit(int[] gas, int[] cost) { int ans = 0, filled = 0, required = 0; for (int i = 0; i < gas.length; ++i) { filled += gas[i] - cost[i]; if (filled < 0) { required += filled; ans = i + 1; filled = 0; } } return filled >= Math.abs(required) ? ans : -1; } }
package ru.lember.neointegrationadapter.handler; public interface ConditionalBiSplitter extends Handler { Handler first(); Handler second(); }
package com.finix.bean; import java.io.Serializable; import java.util.ArrayList; import java.util.Map; @SuppressWarnings("serial") public class UserBean implements Serializable { private String name; private String email; private String mobile; private String password; private int user_id; private String sms_pin; private String sms_pin_status; private String status; private Map<Integer, String> cityMap; private Map<Integer, String> theaterMap; private Map<Integer, String> movieMap; private int city_id; private ArrayList<TheaterOwnerBean> movieList; private ArrayList<TheaterOwnerBean> majorCityList; private String show_values; private int theater_id; private int screen_id; private int movie_details_id; private int show_detail_id; private int show_timing_id; private String show_timing; private int seat_count; private String movie_date; private String seat_name_str; private String movie_name; private int total_amount; private int seat_status_id; private int date_id; private String date; private String dayName; private String booking_seat; private String booking_date; private String total_price; private ArrayList<TheaterOwnerBean> theaterList; private ArrayList<TheaterOwnerBean> cityList; private String screen_name; private String show_time_str; private ArrayList<TheaterDetailBean> theaterRowList; private ArrayList<TheaterDetailBean> seatCountList; private ArrayList<ScreenDetailBean> seatCategoryList; private String theatre_name; private int selected_seat_count; private double amount; private Map<String, String> responseMap; private int ticket_count; private ArrayList<ScreenDetailBean> showTimingList; private String certification_name; private int master_movie_id; private String qr_code; private String booking_id; private double sgst_percentage; private double cgst_percentage; private double et_percentage; private double convenient_tax; private double sgst_amount; private double cgst_amount; private double et_amount; private double convenient_amount; private String qr_code_path; private double total_transaction_amount; public Map<String, String> getResponseMap() { return responseMap; } public void setResponseMap(Map<String, String> responseMap) { this.responseMap = responseMap; } public double getAmount() { return amount; } public void setAmount(double amount) { this.amount = amount; } //Getter and Setter public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getUser_id() { return user_id; } public void setUser_id(int user_id) { this.user_id = user_id; } public String getSms_pin() { return sms_pin; } public void setSms_pin(String sms_pin) { this.sms_pin = sms_pin; } public String getSms_pin_status() { return sms_pin_status; } public void setSms_pin_status(String sms_pin_status) { this.sms_pin_status = sms_pin_status; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Map<Integer, String> getCityMap() { return cityMap; } public void setCityMap(Map<Integer, String> cityMap) { this.cityMap = cityMap; } public Map<Integer, String> getTheaterMap() { return theaterMap; } public void setTheaterMap(Map<Integer, String> theaterMap) { this.theaterMap = theaterMap; } public Map<Integer, String> getMovieMap() { return movieMap; } public void setMovieMap(Map<Integer, String> movieMap) { this.movieMap = movieMap; } public int getCity_id() { return city_id; } public void setCity_id(int city_id) { this.city_id = city_id; } public ArrayList<TheaterOwnerBean> getMovieList() { return movieList; } public void setMovieList(ArrayList<TheaterOwnerBean> movieList) { this.movieList = movieList; } public String getShow_values() { return show_values; } public void setShow_values(String show_values) { this.show_values = show_values; } public int getTheater_id() { return theater_id; } public void setTheater_id(int theater_id) { this.theater_id = theater_id; } public int getScreen_id() { return screen_id; } public void setScreen_id(int screen_id) { this.screen_id = screen_id; } public int getShow_timing_id() { return show_timing_id; } public void setShow_timing_id(int show_timing_id) { this.show_timing_id = show_timing_id; } public int getMovie_details_id() { return movie_details_id; } public void setMovie_details_id(int movie_details_id) { this.movie_details_id = movie_details_id; } public int getShow_detail_id() { return show_detail_id; } public void setShow_detail_id(int show_detail_id) { this.show_detail_id = show_detail_id; } public ArrayList<TheaterDetailBean> getTheaterRowList() { return theaterRowList; } public void setTheaterRowList(ArrayList<TheaterDetailBean> theaterRowList) { this.theaterRowList = theaterRowList; } public ArrayList<TheaterDetailBean> getSeatCountList() { return seatCountList; } public void setSeatCountList(ArrayList<TheaterDetailBean> seatCountList) { this.seatCountList = seatCountList; } public ArrayList<ScreenDetailBean> getSeatCategoryList() { return seatCategoryList; } public void setSeatCategoryList(ArrayList<ScreenDetailBean> seatCategoryList) { this.seatCategoryList = seatCategoryList; } public String getShow_timing() { return show_timing; } public void setShow_timing(String show_timing) { this.show_timing = show_timing; } public int getSeat_count() { return seat_count; } public void setSeat_count(int seat_count) { this.seat_count = seat_count; } public String getMovie_date() { return movie_date; } public void setMovie_date(String movie_date) { this.movie_date = movie_date; } public String getSeat_name_str() { return seat_name_str; } public void setSeat_name_str(String seat_name_str) { this.seat_name_str = seat_name_str; } public String getMovie_name() { return movie_name; } public void setMovie_name(String movie_name) { this.movie_name = movie_name; } public int getTotal_amount() { return total_amount; } public void setTotal_amount(int total_amount) { this.total_amount = total_amount; } public int getSeat_status_id() { return seat_status_id; } public void setSeat_status_id(int seat_status_id) { this.seat_status_id = seat_status_id; } public int getDate_id() { return date_id; } public void setDate_id(int date_id) { this.date_id = date_id; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getDayName() { return dayName; } public void setDayName(String dayName) { this.dayName = dayName; } public String getTheatre_name() { return theatre_name; } public void setTheatre_name(String theatre_name) { this.theatre_name = theatre_name; } public ArrayList<TheaterOwnerBean> getTheaterList() { return theaterList; } public void setTheaterList(ArrayList<TheaterOwnerBean> theaterList) { this.theaterList = theaterList; } public ArrayList<TheaterOwnerBean> getCityList() { return cityList; } public void setCityList(ArrayList<TheaterOwnerBean> cityList) { this.cityList = cityList; } public String getScreen_name() { return screen_name; } public void setScreen_name(String screen_name) { this.screen_name = screen_name; } public String getShow_time_str() { return show_time_str; } public void setShow_time_str(String show_time_str) { this.show_time_str = show_time_str; } public String getBooking_seat() { return booking_seat; } public void setBooking_seat(String booking_seat) { this.booking_seat = booking_seat; } public String getBooking_date() { return booking_date; } public void setBooking_date(String booking_date) { this.booking_date = booking_date; } public String getTotal_price() { return total_price; } public void setTotal_price(String total_price) { this.total_price = total_price; } public int getSelected_seat_count() { return selected_seat_count; } public void setSelected_seat_count(int selected_seat_count) { this.selected_seat_count = selected_seat_count; } public int getTicket_count() { return ticket_count; } public void setTicket_count(int ticket_count) { this.ticket_count = ticket_count; } public ArrayList<ScreenDetailBean> getShowTimingList() { return showTimingList; } public void setShowTimingList(ArrayList<ScreenDetailBean> showTimingList) { this.showTimingList = showTimingList; } public String getCertification_name() { return certification_name; } public void setCertification_name(String certification_name) { this.certification_name = certification_name; } public int getMaster_movie_id() { return master_movie_id; } public void setMaster_movie_id(int master_movie_id) { this.master_movie_id = master_movie_id; } public ArrayList<TheaterOwnerBean> getMajorCityList() { return majorCityList; } public void setMajorCityList(ArrayList<TheaterOwnerBean> majorCityList) { this.majorCityList = majorCityList; } public String getQr_code() { return qr_code; } public void setQr_code(String qr_code) { this.qr_code = qr_code; } public String getBooking_id() { return booking_id; } public void setBooking_id(String booking_id) { this.booking_id = booking_id; } public double getSgst_percentage() { return sgst_percentage; } public void setSgst_percentage(double sgst_percentage) { this.sgst_percentage = sgst_percentage; } public double getCgst_percentage() { return cgst_percentage; } public void setCgst_percentage(double cgst_percentage) { this.cgst_percentage = cgst_percentage; } public double getEt_percentage() { return et_percentage; } public void setEt_percentage(double et_percentage) { this.et_percentage = et_percentage; } public double getConvenient_tax() { return convenient_tax; } public void setConvenient_tax(double convenient_tax) { this.convenient_tax = convenient_tax; } public double getSgst_amount() { return sgst_amount; } public void setSgst_amount(double sgst_amount) { this.sgst_amount = sgst_amount; } public double getCgst_amount() { return cgst_amount; } public void setCgst_amount(double cgst_amount) { this.cgst_amount = cgst_amount; } public double getEt_amount() { return et_amount; } public void setEt_amount(double et_amount) { this.et_amount = et_amount; } public double getConvenient_amount() { return convenient_amount; } public void setConvenient_amount(double convenient_amount) { this.convenient_amount = convenient_amount; } public double getTotal_transaction_amount() { return total_transaction_amount; } public void setTotal_transaction_amount(double total_transaction_amount) { this.total_transaction_amount = total_transaction_amount; } public String getQr_code_path() { return qr_code_path; } public void setQr_code_path(String qr_code_path) { this.qr_code_path = qr_code_path; } }
package com.tencent.tencentmap.mapsdk.a; import android.os.Handler; import android.os.Message; import java.lang.ref.WeakReference; class ks$a extends Handler { private final WeakReference<ks> a; public ks$a(ks ksVar) { this.a = new WeakReference(ksVar); } public void handleMessage(Message message) { super.handleMessage(message); if (this.a != null && this.a.get() != null) { ks ksVar = (ks) this.a.get(); or i = ks.i(ksVar); if (i != null) { if (ksVar.p == null) { if (message.what == 0) { if (ksVar.n != null) { ks.a(ksVar, false); ks.b(ksVar, true); ksVar.n.a(i); } } else if (message.what == 1) { if (ksVar.n != null) { ks.a(ksVar, true); if (ks.j(ksVar) && ks.k(ksVar) == 0) { ks.b(ksVar, false); ksVar.n.b(i); } } if (ks.l(ksVar) != null && ks.m(ksVar)) { ks.l(ksVar).a(); } ksVar.getMap().E(); } } ks.n(ksVar); } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.bowlong.text; import java.nio.charset.Charset; import java.nio.charset.IllegalCharsetNameException; /** * <p> * Character encoding names required of every implementation of the Java * platform. * </p> * * <p> * According to <a href= * "http://java.sun.com/j2se/1.3/docs/api/java/lang/package-summary.html#charenc" * >JRE character encoding names</a>: * </p> * * <p> * <cite>Every implementation of the Java platform is required to support the * following character encodings. Consult the release documentation for your * implementation to see if any other encodings are supported. </cite> * </p> * * @see <a href= * "http://download.oracle.com/javase/1.3/docs/guide/intl/encoding.doc.html"> * JRE character encoding names</a> * @since 2.1 * @version $Id: CharEncoding.java 1088899 2011-04-05 05:31:27Z bayard $ */ public class Encoding { /** * <p> * ISO Latin Alphabet #1, also known as ISO-LATIN-1. * </p> * * <p> * Every implementation of the Java platform is required to support this * character encoding. * </p> */ public static final String ISO_8859_1 = "ISO-8859-1"; public static final Charset ISO8859_1 = Charset.forName(ISO_8859_1); /** * <p> * Seven-bit ASCII, also known as ISO646-US, also known as the Basic Latin * block of the Unicode character set. * </p> * * <p> * Every implementation of the Java platform is required to support this * character encoding. * </p> */ public static final String US_ASCII = "US-ASCII"; public static final Charset USASCII = Charset.forName(US_ASCII); /** * <p> * Sixteen-bit Unicode Transformation Format, byte order specified by a * mandatory initial byte-order mark (either order accepted on input, * big-endian used on output). * </p> * * <p> * Every implementation of the Java platform is required to support this * character encoding. * </p> */ public static final String UTF_16 = "UTF-16"; public static final Charset UTF16 = Charset.forName(UTF_16); /** * <p> * Sixteen-bit Unicode Transformation Format, big-endian byte order. * </p> * * <p> * Every implementation of the Java platform is required to support this * character encoding. * </p> */ public static final String UTF_16BE = "UTF-16BE"; public static final Charset UTF16BE = Charset.forName(UTF_16BE); /** * <p> * Sixteen-bit Unicode Transformation Format, little-endian byte order. * </p> * * <p> * Every implementation of the Java platform is required to support this * character encoding. * </p> */ public static final String UTF_16LE = "UTF-16LE"; public static final Charset UTF16LE = Charset.forName(UTF_16LE); /** * <p> * Eight-bit Unicode Transformation Format. * </p> * * <p> * Every implementation of the Java platform is required to support this * character encoding. * </p> */ public static final String UTF_8 = "UTF-8"; public static final Charset UTF8 = Charset.forName(UTF_8); static public final String G_B_K = "GBK"; static public final Charset GBK = Charset.forName(G_B_K); static public final String GB_2312 = "GB2312"; static public final Charset GB2312 = Charset.forName(GB_2312); // ----------------------------------------------------------------------- /** * <p> * Returns whether the named charset is supported. * </p> * * <p> * This is similar to <a href= * "http://download.oracle.com/javase/1.4.2/docs/api/java/nio/charset/Charset.html#isSupported%28java.lang.String%29" * > java.nio.charset.Charset.isSupported(String)</a> but handles more * formats * </p> * * @param name * the name of the requested charset; may be either a canonical * name or an alias, null returns false * @return {@code true} if the charset is available in the current Java * virtual machine */ public static boolean isSupported(String name) { if (name == null || "".equals(name.trim())) { return false; } try { return Charset.isSupported(name); } catch (IllegalCharsetNameException ex) { return false; } } }
package eight.abstracts; // final的使用: // final可以修饰变量:表示变量的值不可变。 // final可以修饰方法:表示方法不可以被重写 。 // final可以修饰类:表示类不可以被继承。 // public class FinalDemo { }
package com.azure; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.management.AzureEnvironment; import com.azure.core.management.Region; import com.azure.core.management.profile.AzureProfile; import com.azure.identity.ClientSecretCredential; import com.azure.identity.ClientSecretCredentialBuilder; import com.azure.identity.CredentialUnavailableException; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.keyvault.models.IpRule; import com.azure.resourcemanager.keyvault.models.NetworkRuleAction; import com.azure.resourcemanager.keyvault.models.NetworkRuleBypassOptions; import com.azure.resourcemanager.keyvault.models.NetworkRuleSet; import com.azure.resourcemanager.keyvault.models.Vault; import com.azure.resourcemanager.keyvault.models.VirtualNetworkRule; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class NetworkAclSample { protected static AzureResourceManager azure; protected static final Region VAULT_REGION = Region.US_WEST; protected static final Integer RESOURCE_NAME_MAX_LENGTH = 24; protected static final String AZURE_CLIENT_ID = System.getProperty("AZURE_CLIENT_ID"); protected static final String AZURE_OBJECT_ID = System.getProperty("AZURE_OBJECT_ID"); protected static final String AZURE_CLIENT_SECRET = System.getProperty("AZURE_CLIENT_SECRET"); protected static final String AZURE_TENANT_ID = System.getProperty("AZURE_TENANT_ID"); protected static final String AZURE_SUBSCRIPTION_ID = System.getProperty("AZURE_SUBSCRIPTION_ID"); protected static final String DEFAULT_IP_ADDRESS = "0.0.0.0/0"; protected static final String DEFAULT_VAULT_NAME_PREFIX = "vault-sample"; protected static final String RESOURCE_GROUP_NAME = azure.resourceGroups() .manager() .internalContext() .randomResourceName("rg-sample", RESOURCE_NAME_MAX_LENGTH); protected static final String FIRST_VAULT_NAME = azure.resourceGroups() .manager() .internalContext() .randomResourceName(DEFAULT_VAULT_NAME_PREFIX, RESOURCE_NAME_MAX_LENGTH); protected static final String SECOND_VAULT_NAME = azure.resourceGroups() .manager() .internalContext() .randomResourceName(DEFAULT_VAULT_NAME_PREFIX, RESOURCE_NAME_MAX_LENGTH); static { // Authenticates to Azure with Client_ID and CLIENT_SECRET authenticateToAzure(); } public void createSampleVaultWithNetworkAcl() { // Create sample resource group. azure.resourceGroups() .define(RESOURCE_GROUP_NAME) .withRegion(VAULT_REGION) .create(); System.out.println("Created a resource group with name: " + RESOURCE_GROUP_NAME); // If you have a virtual network, set it here. List<VirtualNetworkRule> rules = new ArrayList<>(); // Setting the network rules NetworkRuleSet networkRuleSet = new NetworkRuleSet() .withBypass(NetworkRuleBypassOptions.AZURE_SERVICES)// Allows bypass of network ACLs from Azure services. Accepted values: 'AzureServices' or 'None'. .withDefaultAction(NetworkRuleAction.DENY) // Action to take if access attempt does not match any rule. Accepted values: 'Allow' or 'Deny'. // IP rules .withIpRules(new ArrayList<IpRule>( Arrays.asList(new IpRule().withValue(DEFAULT_IP_ADDRESS)) )) // Allow access from all IPv4 addresses. // Virtual network rules (Allows access to Azure Virtual Networks by their Azure Resource ID). .withVirtualNetworkRules(rules); // Create a new sample vault with Vault firstVault = azure.vaults() .define(FIRST_VAULT_NAME) .withRegion(Region.US_WEST) .withExistingResourceGroup(RESOURCE_GROUP_NAME) .defineAccessPolicy() .forObjectId(AZURE_OBJECT_ID) .allowSecretAllPermissions() .attach() .withDeploymentDisabled() .withBypass(NetworkRuleBypassOptions.AZURE_SERVICES) .withDefaultAction(NetworkRuleAction.DENY) .withAccessFromIpAddress(DEFAULT_IP_ADDRESS) .create(); Vault secondVault = azure.vaults() .define(SECOND_VAULT_NAME) .withRegion(Region.US_WEST) .withExistingResourceGroup(RESOURCE_GROUP_NAME) .defineAccessPolicy() .forObjectId(AZURE_OBJECT_ID) .allowSecretAllPermissions() .attach() .withDeploymentDisabled() .withAccessFromAzureServices() //Essentially sets Bypass to AZURE_SERVICES .withAccessFromSelectedNetworks() //Sets default Action to Deny .withAccessFromIpAddress(DEFAULT_IP_ADDRESS) .create(); System.out.println("Created vault: " + firstVault.vaultUri()); System.out.println("Created vault: " + secondVault.vaultUri()); } private static void authenticateToAzure() { AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); // Authentication for general Azure service. ClientSecretCredential credentials = new ClientSecretCredentialBuilder() .clientId(AZURE_CLIENT_ID) .tenantId(AZURE_TENANT_ID) .clientSecret(AZURE_CLIENT_SECRET) .build(); try { azure = AzureResourceManager.configure() .withLogLevel(HttpLogDetailLevel.BASIC) .authenticate(credentials, profile) .withSubscription(AZURE_SUBSCRIPTION_ID); } catch (Exception e) { e.printStackTrace(); throw new CredentialUnavailableException( "Error authenticating to Azure - check your credentials in your environment."); } } }
package com.sneaker.mall.api.model; import java.util.Comparator; /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class GType extends BaseModel<Long> implements Comparable<GType> { /** * 公司ID */ private long cid; /** * 编码 */ private String code; /** * 名称 */ private String name; /** * 商城后台的设置信息 */ private CompanyGtype companyGtype; public CompanyGtype getCompanyGtype() { return companyGtype; } public void setCompanyGtype(CompanyGtype companyGtype) { this.companyGtype = companyGtype; } public long getCid() { return cid; } public void setCid(long cid) { this.cid = cid; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public int compareTo(GType o2) { GType o1=this; if (o1.getCompanyGtype() == null) return 0; if (o2.getCompanyGtype() == null) return 0; if (o1.getCompanyGtype().getCsort() > o2.getCompanyGtype().getCsort()) { return 1; } else { return -1; } } }
package com.e6soft.form.controllers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.e6soft.core.views.ViewMsg; import com.e6soft.form.FormController; import com.e6soft.form.FormFactory; import com.e6soft.form.model.BusinessBase; import com.e6soft.form.service.BusinessBaseService; @Controller @RequestMapping(value=FormFactory.module+"/businessbase") public class BusinessBaseController extends FormController{ @Autowired private BusinessBaseService businessBaseService; @RequestMapping(value="save") @ResponseBody public String save(BusinessBase businessBase) { businessBaseService.save(businessBase); return new ViewMsg(1,"保存成功").toString(); } @RequestMapping(value="delete") @ResponseBody public String delete(BusinessBase businessBase) { businessBaseService.deleteById(businessBase.getId()); return new ViewMsg(1).toString(); } }
public class LightBoardStart { public LightBoardStart() { LightBoard sim = new LightBoard(7, 5); System.out.println(sim); System.out.println(); String[] stars = {"**.**", "*..*.", "*..**", "*...*", "*...*", "**.**", "....."}; boolean[][] lights = sim.lights; for (int r = 0; r < stars.length; r++) for (int c = 0; c < stars[0].length(); c++) lights[r][c] = stars[r].charAt(c) == '*'; System.out.println(sim.evaluateLight(0, 3) + " " + sim.evaluateLight(6, 0) + " " + sim.evaluateLight(4, 1) + " " + sim.evaluateLight(5, 4)); } }
import jssc.SerialPort; import jssc.SerialPortException; public class Main { SerialPort serialPort; ControlFrame controlFrame; int previous=-1; public Main(){ try { serialPort = new SerialPort("/dev/ttyACM0"); serialPort.openPort(); serialPort.setParams(19200, 8, 1, 0); } catch (SerialPortException e) {e.printStackTrace();} controlFrame=new ControlFrame(this); } public void close(){ try { System.out.println("Port closed: " + serialPort.closePort()); } catch (SerialPortException e) {e.printStackTrace();} } public void sendMsg(float angle, int pwm, int pulse, int stack){ System.out.println(angle); int id=-1; if (stack==0){ if (angle<10 || angle>=347.5) id=04; else if (angle>=10 && angle<30) id=03; else if (angle>=30 && angle<50) id=02; else if (angle>=50 && angle<70) id=01; else if (angle>=70 && angle<90) id=00; else if (angle>=90 && angle<110) id=50; else if (angle>=110 && angle<130) id=51; else if (angle>=130 && angle<150) id=52; else if (angle>=150 && angle<170) id=53; else if (angle>=170 && angle<192.5) id=54; else if (angle>=192.5 && angle<218) id=55; else if (angle>=218 && angle<243.5) id=56; else if (angle>=243.5 && angle<269) id=57; else if (angle>=269 && angle<294.5) id=07; else if (angle>=294.5 && angle<320) id=06; else if (angle>=320 && angle<347.5) id=05; } if (stack==1){ if (angle<10 || angle>=347.5) id=14; else if (angle>=10 && angle<30) id=13; else if (angle>=30 && angle<50) id=12; else if (angle>=50 && angle<70) id=11; else if (angle>=70 && angle<90) id=10; else if (angle>=90 && angle<110) id=40; else if (angle>=110 && angle<130) id=41; else if (angle>=130 && angle<150) id=42; else if (angle>=150 && angle<170) id=43; else if (angle>=170 && angle<192.5) id=44; else if (angle>=192.5 && angle<218) id=45; else if (angle>=218 && angle<243.5) id=46; else if (angle>=243.5 && angle<269) id=47; else if (angle>=269 && angle<294.5) id=17; else if (angle>=294.5 && angle<320) id=16; else if (angle>=320 && angle<347.5) id=15; } if (stack==2){ if (angle<10 || angle>=347.5) id=24; else if (angle>=10 && angle<30) id=23; else if (angle>=30 && angle<50) id=22; else if (angle>=50 && angle<70) id=21; else if (angle>=70 && angle<90) id=20; else if (angle>=90 && angle<110) id=30; else if (angle>=110 && angle<130) id=31; else if (angle>=130 && angle<150) id=32; else if (angle>=150 && angle<170) id=33; else if (angle>=170 && angle<192.5) id=34; else if (angle>=192.5 && angle<218) id=35; else if (angle>=218 && angle<243.5) id=36; else if (angle>=243.5 && angle<269) id=37; else if (angle>=269 && angle<294.5) id=27; else if (angle>=294.5 && angle<320) id=26; else if (angle>=320 && angle<347.5) id=25; } if (id!=-1){ // turn off previous motor if (id!=previous) stop(); String msg="+"; if (id<10) msg+="0"; msg+=id+""+pwm+"000"; System.out.println("sent : "+msg); try { serialPort.writeBytes(msg.getBytes()); } catch (SerialPortException e) {e.printStackTrace();}/**/ /*String msg="-"; if (id<10) msg+="0"; msg+=id+""+pwm; System.out.println("sent : "+msg); try { serialPort.writeBytes(msg.getBytes()); } catch (SerialPortException e) {e.printStackTrace();}/**/ previous=id; } } public void stop(){ if (previous>=0){ /*String msg="+"; if (previous<10) msg+="0"; msg+=previous+"0000"; System.out.println("sent : "+msg); try { serialPort.writeBytes(msg.getBytes()); } catch (SerialPortException e) {e.printStackTrace();}*/ String msg="-"; if (previous<10) msg+="0"; msg+=previous+"0"; System.out.println("sent : "+msg); try { serialPort.writeBytes(msg.getBytes()); } catch (SerialPortException e) {e.printStackTrace();} } } public static void main(String[] args) { Main main=new Main(); while (true){ main.controlFrame.repaint(); try {Thread.sleep(10);} catch (InterruptedException e){e.printStackTrace();} } } }
package com.inayat.yourrooms.dto; import com.inayat.yourrooms.entity.BookingTransaction; public class BookingResponse { private Long id; private Double booking_price; private Double discount_price; private Double coupon_discount; private String discount_coupon; private Double gst; private Long[] rooms; private int noOfGuests; private BookingTransaction transaction; private String bookingStatus; private String paymentStatus; private String checkinDate; private String checkout_date; private String checkout_status; private String checkin_status; private String bookingId; private Long userId; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Double getBooking_price() { return booking_price; } public void setBooking_price(Double booking_price) { this.booking_price = booking_price; } public Double getGst() { return gst; } public void setGst(Double gst) { this.gst = gst; } public int getNoOfGuests() { return noOfGuests; } public void setNoOfGuests(int noOfGuests) { this.noOfGuests = noOfGuests; } public BookingTransaction getTransaction() { return transaction; } public void setTransaction(BookingTransaction transaction) { this.transaction = transaction; } public String getBookingStatus() { return bookingStatus; } public void setBookingStatus(String bookingStatus) { this.bookingStatus = bookingStatus; } public String getPaymentStatus() { return paymentStatus; } public void setPaymentStatus(String paymentStatus) { this.paymentStatus = paymentStatus; } public String getCheckinDate() { return checkinDate; } public void setCheckinDate(String checkinDate) { this.checkinDate = checkinDate; } public String getCheckout_date() { return checkout_date; } public void setCheckout_date(String checkout_date) { this.checkout_date = checkout_date; } public String getBookingId() { return bookingId; } public void setBookingId(String bookingId) { this.bookingId = bookingId; } public String getDiscount_coupon() { return discount_coupon; } public void setDiscount_coupon(String discount_coupon) { this.discount_coupon = discount_coupon; } public Long[] getRooms() { return rooms; } public void setRooms(Long[] rooms) { this.rooms = rooms; } public Double getDiscount_price() { return discount_price; } public void setDiscount_price(Double discount_price) { this.discount_price = discount_price; } public Double getCoupon_discount() { return coupon_discount; } public void setCoupon_discount(Double coupon_discount) { this.coupon_discount = coupon_discount; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public String getCheckout_status() { return checkout_status; } public void setCheckout_status(String checkout_status) { this.checkout_status = checkout_status; } public String getCheckin_status() { return checkin_status; } public void setCheckin_status(String checkin_status) { this.checkin_status = checkin_status; } }
package com.codehub.testtest; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder>{ String[] headings = { "Heading 1", "Heading 2", "Heading 3", "Heading 4", "Heading 5", "Heading 6", "Heading 7", "Heading 8", "Heading 9", "Heading 10" }; String[] tagLine = { "tagLine 1", "tagLine 2", "tagLine 3", "tagLine 4", "tagLine 5", "tagLine 6", "tagLine 7", "tagLine 8", "tagLine 9", "tagLine 10" }; @NonNull @Override public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_main2, parent, false); return new MyViewHolder(view); } @Override public void onBindViewHolder(@NonNull MyViewHolder holder, int position) { holder.view1.setText(headings[position]); holder.view2.setText(tagLine[position]); } @Override public int getItemCount() { return headings.length; } public class MyViewHolder extends RecyclerView.ViewHolder { TextView view1, view2; public MyViewHolder(@NonNull View itemView) { super(itemView); view1 = itemView.findViewById(R.id.view1); view2 = itemView.findViewById(R.id.view2); } } }
package Practicas2; public class ArranqueInterfaz { public static void main( String[]args) { Persona p = new Persona(); hacerCantar(p); Canario c= new Canario(); c.setcolor("verde"); c.setnombre("Margarot"); c.volar(); hacerCantar(c); } public static void hacerCantar(Cantante c) { c.cantar(); } }
package ua.project.protester.model.executable.result.subtype; import lombok.Getter; import lombok.Setter; @Getter @Setter public class SqlColumnCell { private Integer id; private Integer sqlColumnId; private Integer orderNumber; private String value; }
package com.lyx.pattern.proxy.staticproxy; public interface IUserDao { void save(); }
package controller.datamapper; import controller.dtos.AfspeellijstDTO; import controller.dtos.AfspeellijstenDTO; import domain.Afspeellijst; import javax.enterprise.inject.Any; import javax.inject.Inject; import java.util.ArrayList; import java.util.List; public class SpotitubeDataMapper { AfspeellijstDataMapper afspeellijstDM; @Inject public void setAfspeellijstDM(AfspeellijstDataMapper afspeellijstDM) { this.afspeellijstDM = afspeellijstDM; } public AfspeellijstenDTO mapToDTO(List<Afspeellijst> afspeellijsten) { List<AfspeellijstDTO> afspeellijstDTOs = new ArrayList<AfspeellijstDTO>(); int lengte = 0; for (Afspeellijst afspeellijst : afspeellijsten) { afspeellijstDTOs.add(afspeellijstDM.mapToDTO(afspeellijst)); lengte += afspeellijst.berekenAfspeellijstLengte(); } AfspeellijstenDTO afspeellijstenDTO = new AfspeellijstenDTO(); afspeellijstenDTO.setPlaylists(afspeellijstDTOs); afspeellijstenDTO.setLength(lengte); return afspeellijstenDTO; } }
package com.frank.service; import com.frank.bean.Fan; import com.frank.bean.Subscribe; import java.util.List; /** * Created by 啸 on 2017/6/1. */ public interface Subs_fanService { public int countUserSubscribe(String username); public int countUserFans(String username); public List<Subscribe> showUserSubscribe(String username); public void unfollowUser(String username,String sub_name); public void followUser(String username,String sub_name); public List<Fan> showUserFans(String username); }
package tema17.recheios; import tema17.IPizza; public class RecheioDeBacon extends DecoradorRecheio { private static final double PRECO_BACON = 3.50; public RecheioDeBacon(IPizza pizza) { super(pizza); } @Override public double getPrice() { return super.getPrice() + PRECO_BACON; } }