text
stringlengths
10
2.72M
package com.rile.methotels.pages; import com.rile.methotels.entities.Soba; import com.rile.methotels.services.dao.SobaDao; import java.util.List; import org.apache.tapestry5.ComponentResources; import org.apache.tapestry5.annotations.OnEvent; import org.apache.tapestry5.annotations.Property; import org.apache.tapestry5.hibernate.annotations.CommitAfter; import org.apache.tapestry5.ioc.annotations.Inject; import org.apache.tapestry5.services.ajax.AjaxResponseRenderer; import org.got5.tapestry5.jquery.components.InPlaceEditor; /** * * @author Stefan */ public class PrimerInPlaceEditor { @Property private Soba soba; @Property private List<Soba> sobe; @Inject private AjaxResponseRenderer ajaxResponseRenderer; @Inject private SobaDao sobaDao; @Inject private ComponentResources componentResources; void onActivate() { sobe = sobaDao.loadAll(); } @CommitAfter @OnEvent(component = "nazivSobe", value = InPlaceEditor.SAVE_EVENT) void setNazivSobe(Long id, String value) { soba = sobaDao.getByID(id.intValue()); soba.setNaziv(value); sobaDao.merge(soba); } }
package domain.model; import javax.persistence.MappedSuperclass; import javax.validation.constraints.NotNull; import lombok.Data; import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper=true) @MappedSuperclass public abstract class Security extends Instrument { @NotNull private String isin; @NotNull private Long quantity; }
package com.example.suresh.downloader.service; import android.app.ActivityManager; import android.content.Context; import android.util.Log; public class StatusChecking { public static boolean isMyServiceRunning(Class<?> serviceClass, Context context) throws Exception { ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if (serviceClass.getName().equals(service.service.getClassName())) { Log.i("Service already", "running"); return true; } } Log.i("Service not", "running"); return false; } }
package pwr.chrzescijanek.filip.gifa.util; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.stage.Stage; import javafx.stage.Window; import pwr.chrzescijanek.filip.gifa.controller.CompareViewController; import pwr.chrzescijanek.filip.gifa.view.FXView; import static javafx.scene.control.Alert.AlertType; import static javafx.stage.Modality.APPLICATION_MODAL; import static javafx.stage.StageStyle.UNDECORATED; import static pwr.chrzescijanek.filip.gifa.util.ControllerUtils.initializeSampleController; /** * Provides utility methods for handling stages. */ public final class StageUtils { private StageUtils() { } /** * @return about dialog */ public static Alert getAboutDialog() { final Alert alert = new Alert(AlertType.INFORMATION, "Global image features analyzer\n" + "GitHub repository: https://github.com/FilipChrzescijanek/gifa/\n" + "\nCopyright © 2016 Filip Chrześcijanek\nfilip.chrzescijanek@gmail.com", ButtonType.OK); alert.setTitle("About"); alert.setHeaderText("gifa"); alert.setGraphic(new ImageView(new Image(StageUtils.class.getResourceAsStream("/images/icon-big.png")))); ((Stage) alert.getDialogPane().getScene().getWindow()) .getIcons().add(new Image(StageUtils.class.getResourceAsStream("/images/icon-small.png"))); return alert; } /** * @param content alert content * @return error alert */ public static Alert getErrorAlert(final String content) { return new Alert(AlertType.ERROR, content, ButtonType.OK); } /** * @param window application window * @return new undecorated modal dialog */ public static Stage initDialog(final Window window) { final Stage dialog = new Stage(); dialog.initOwner(window); dialog.initStyle(UNDECORATED); dialog.initModality(APPLICATION_MODAL); return dialog; } /** * Constructs new application's compare view's stage with FXML view from given path, label, title and compare views * of vertex with given index. * * @param viewPath FXML view path * @param info label * @param title stage title * @param sampleIndex sample index * @return new application's compare stage */ public static Stage getCompareSampleStage(final String viewPath, final String info, final String title, final int sampleIndex) { final Stage newStage = new Stage(); final FXView fxView = new FXView(viewPath); final CompareViewController controller = initializeSampleController(info, sampleIndex, fxView); showStage(newStage, fxView, controller, title); return newStage; } /** * Shows given applications' compare view's stage. * * @param newStage stage * @param fxView FXML view * @param controller compare view's controller * @param title stage title */ public static void showStage(final Stage newStage, final FXView fxView, final CompareViewController controller, final String title) { preparePanelStage(newStage, title, fxView); controller.refresh(); newStage.show(); } /** * Prepares applications' compare view's stage. * * @param stage stage on which compare view will be shown * @param title stage title * @param view compare view */ public static void preparePanelStage(final Stage stage, final String title, final FXView view) { setTitleAndIcon(stage, title); setPanelScene(stage, view); } private static void setTitleAndIcon(final Stage stage, final String title) { stage.setTitle(title); final Image icon = new Image(StageUtils.class.getResourceAsStream("/images/icon-small.png")); stage.getIcons().add(icon); } private static void setPanelScene(final Stage stage, final FXView fxView) { final Parent root = fxView.getView(); setScene(stage, root, 720, 360); } private static void setScene(final Stage stage, final Parent root, final int width, final int height) { final Scene scene = new Scene(root, width, height); stage.setScene(scene); } /** * Prepares application's help view stage. * * @param stage stage on which help will be shown * @param root help view */ public static void prepareHelpStage(final Stage stage, final Parent root) { setTitleAndIcon(stage, "Help"); setScene(stage, root, 960, 540); } /** * Prepares application stages. * * @param stage stage on which given view will be shown * @param title stage title * @param view FXML view */ public static void prepareStage(final Stage stage, final String title, final FXView view) { setTitleAndIcon(stage, title); setScene(stage, view); } private static void setScene(final Stage stage, final FXView fxView) { final Parent root = fxView.getView(); final Scene scene = new Scene(root, root.minWidth(-1), root.minHeight(-1)); stage.setMinWidth(960); stage.setMinHeight(540); stage.setScene(scene); } }
package id.co.games.tictactoe; public class Player { public String Marker; public void setMarker(String marker){ Marker = marker; } public String getMarker(){ return Marker; } }
package io.bega.kduino.services; import java.io.IOException; import java.util.List; /** * Created by usuario on 18/07/15. */ public interface IBluetoothServiceManager { void sendMessage(String message) throws IOException; String recieveMessage(ICounter counter, boolean needsCounter) throws IOException; Boolean isConnected(); void connect(String address); void disconnect(); void registerReciever(); void unregisterReciever(); }
import java.time.LocalDate; import java.util.*; public class Lab1 { public static LocalDate parseStringToLocalDateFormat(String str){ String[] strDate = str.split("\\."); LocalDate date; if(strDate.length == 3){ int day = Integer.parseInt(strDate[0]); int month = Integer.parseInt(strDate[1]); int year = Integer.parseInt(strDate[2]); date = LocalDate.of(year, month , day); } else{ throw new Error("Incorrect date format."); } return date; } public static void main(String[] args){ Scanner scanner = new Scanner(System.in); FootballClub footballClub = new FootballClub(); Footballer footballer; LocalDate dateOfBirth; System.out.print("Введите количество футболистов:"); int length = scanner.nextInt(); for(int i = 0; i < length; i++) { System.out.println("Футболист №" + (i+1) + ":"); footballer = new Footballer(); System.out.print("Фамилия: "); footballer.setLastName(scanner.next()); System.out.print("Дата рождения(в формате дд.мм.гггг): "); dateOfBirth = parseStringToLocalDateFormat(scanner.next()); footballer.setDateOfBirth(dateOfBirth); System.out.print("Место рождения: "); footballer.setBirthLocation(scanner.next()); System.out.print("Роль: "); footballer.setRole(scanner.next()); System.out.print("Количество игр: "); footballer.setGamesNumber(scanner.nextInt()); System.out.print("Количество желтых карточек: "); footballer.setYellowCardNumber(scanner.nextInt()); footballClub.add(footballer); } FootballClub.printFootballerData(footballClub); } }
package com.company; public enum Product { IPAD, IPHONE, IPOD, IMAC }
package com.tencent.mm.plugin.sns.ui; import com.tencent.mm.plugin.sns.i.j; import com.tencent.mm.ui.base.h; class SnsTimeLineUI$24 implements Runnable { final /* synthetic */ SnsTimeLineUI odw; SnsTimeLineUI$24(SnsTimeLineUI snsTimeLineUI) { this.odw = snsTimeLineUI; } public final void run() { h.a(this.odw, this.odw.getString(j.notification_need_resend_dialog_prompt), "", this.odw.getString(j.notification_need_resend_dialog_prompt_resend_now), this.odw.getString(j.app_cancel), new 1(this), new 2(this)); } }
package thread_pattern.event_driven_modle.demo; import org.junit.jupiter.api.Test; import thread_pattern.event_driven_modle.BaseEvent; import thread_pattern.event_driven_modle.EventDispatcher; import thread_pattern.event_driven_modle.GlobalEventType; /** * reference: https://blog.csdn.net/liulianglin/article/details/124325950 * * - eventLister 也可以称为 eventHandler ,意思是一样的 * - UserEventListenerManager 同理也可以称为 EventHandlerManager。 如果是Spring可以用@Component单例创建一个bean;如果非Spring项目需要手动创建 * * 整体思路 * 1. 有些事件(login, exit) 是一些人关心的( some listenerManager) * 2. 主线程产生了一些时间,交给dispatcher分发 * 3. dispatcher 根据事件排序及时性的要求处理事件(handler event 就行把一个event 交给这些 listener 调用自己的 handleEvent处理) * <li>如果消息线程要求事件被同步处理, 则消息线程调用 instance.dispatchEvent(), 进一步就调用了 handler, 即 dispatchEvent {handler} </li> * <li>如果消息线程不要求事件被同步处理, 则会由 Dispatcher内部的worker-thread 异步调用 handler 方法</li> * 4. dispatcher 可以开始,也可以被关闭(调用dispatcher.stop) * * @author sunyindong.syd */ public class UserEventDrivenDemo { @Test void test() { // 手动创建一个 事件监听管理类 UserEventListenerManager createByManual = new UserEventListenerManager(); BaseEvent event = new UserLoginEvent(GlobalEventType.LOGIN, "超级管理员"); event.setSync(false); EventDispatcher.INSTANCE.dispatchEvent(event); try { System.out.println("模拟业务处理1秒钟...."); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("处理完毕,关闭"); //EventDispatcher.INSTANCE.shutdown(); } }
package com.example.demo.core.components; import com.example.demo.core.compatibility.CompositePowerConsumer; import com.example.demo.core.compatibility.FormFactor; import com.example.demo.core.compatibility.FormFactors; import com.example.demo.core.compatibility.PowerConsumer; import java.util.ArrayList; import java.util.List; public abstract class Cabinet implements FormFactor , CompositePowerConsumer { public static Cabinet create(FormFactors formFactors) { return new Cabinet() { @Override public List<PowerConsumer> getChildPowerConsumer() { return new ArrayList<>(); } @Override public int selfConsumedPower() { return 0; } @Override public FormFactors formFactors() { return formFactors; } }; } }
package example.nz.org.take.compiler.userv.generated; import nz.org.take.rt.*; /** * Class generated by the take compiler. * @version Mon Feb 11 13:49:16 NZDT 2008 */ @SuppressWarnings("unchecked") class KBFragement_greater_than_11 { /** * Method generated for query greater_than[in,in] * @param nz.org.take.compiler.reference.Slot@acdd02 * @param nz.org.take.compiler.reference.Slot@e1dac2 * @return an iterator * code generated using velocity template Comparison_11.vm */ static ResourceIterator<greater_than> greater_than_11(final double slot1, final double slot2, final DerivationController _derivation) { _derivation.log(">", DerivationController.COMPARISON); if (slot1 > slot2) { greater_than result = new greater_than(); result.slot1 = slot1; result.slot2 = slot2; return new SingletonIterator<greater_than>(result); } return EmptyIterator.DEFAULT; } }
package com.example.postgresdemo.model; import javax.persistence.*; import java.util.Date; import java.util.List; import org.springframework.data.annotation.CreatedDate; @Entity @Table(name = "survey") public class Survey extends AuditModel { public Survey(Employee employee, Project project, Employee reviewer, String status) { this.employee = employee; this.project = project; this.reviewer = reviewer; this.status = status; this.setCreatedAt(new Date()); this.setUpdatedAt(new Date()); //fix this } public Survey() { } @Id @GeneratedValue(generator = "survey_generator") @SequenceGenerator( name = "survey_generator", sequenceName = "survey_sequence", initialValue = 1000 ) private Long id; //foreign key @ManyToOne @JoinColumn(name="employee_id") private Employee employee; //foreign key @ManyToOne @JoinColumn(name="reviewer_id") private Employee reviewer; //foreign key @ManyToOne @JoinColumn(name="project_id") private Project project; @Column(name = "status", nullable = false) private String status; @Temporal(TemporalType.TIMESTAMP) @Column(name = "start_date", nullable = false, updatable = false) @CreatedDate private Date start_date; @Temporal(TemporalType.TIMESTAMP) @Column(name = "complete_date") private Date complete_date; @OneToMany(mappedBy = "survey") private List<SurveyToolRating> surveyToolRatings; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Date getStart_date() { return start_date; } public void setStart_date(Date start_date) { this.start_date = start_date; } public Date getComplete_date() { return complete_date; } public void setComplete_date(Date complete_date) { this.complete_date = complete_date; } public Employee getEmployee() { return employee; } public void setEmployee(Employee employee) { this.employee = employee; } public Employee getReviewer() { return reviewer; } public void setReviewer(Employee reviewer) { this.reviewer = reviewer; } public Project getProject() { return project; } public void setProject(Project project) { this.project = project; } public List<SurveyToolRating> getSurveyToolRatings() { return surveyToolRatings; } public void setSurveyToolRatings(List<SurveyToolRating> surveyToolRatings) { this.surveyToolRatings = surveyToolRatings; } }
package com.beiyelin.addressservice.entity; import com.beiyelin.commonsql.jpa.BaseDomainEntity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import javax.persistence.Transient; import java.util.List; import static com.beiyelin.commonsql.constant.Repository.CODE_LENGTH; import static com.beiyelin.commonsql.constant.Repository.NAME_LENGTH; /** * @Description: 国家 * @Author: newmann * @Date: Created in 21:02 2018-02-11 */ @Data @NoArgsConstructor @AllArgsConstructor @EqualsAndHashCode(callSuper=true) @Entity @Table(name = Country.TABLE_NAME) public class Country extends BaseDomainEntity { public static final String TABLE_NAME= "g_country"; private static final long serialVersionUID = 1L; @Column(nullable = false,length = CODE_LENGTH,unique = true) private String code; @Column(nullable = false,length = NAME_LENGTH) private String name; // @Column // private String description; // @OneToMany(mappedBy = "country",fetch=FetchType.EAGER) @Transient private List<Province> provinceSet; }
/* * 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 clases; /** * * @author josev */ public class tipoHabitacion { private int id; private String nombre; private String descripcion; private String imagen; private int precioDia; public tipoHabitacion(int id, String nombre, String descripcion, int precioDia) { this.id = id; this.nombre = nombre; this.descripcion = descripcion; this.precioDia = precioDia; } public tipoHabitacion(int id, String nombre, String descripcion, String imagen, int precioDia) { this.id = id; this.nombre = nombre; this.descripcion = descripcion; this.imagen = imagen; this.precioDia = precioDia; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public int getPrecioDia() { return precioDia; } public void setPrecioDia(int precioDia) { this.precioDia = precioDia; } public String getImagen() { return imagen; } public void setImagen(String imagen) { this.imagen = imagen; } }
package edu.northeastern.cs5200.model; import java.util.*; import java.util.Date; public class Developer extends Person{ private String developerKey; private Collection<Website> websites; public String getDeveloperKey() { return developerKey; } public void setDeveloperKey(String developerKey) { this.developerKey = developerKey; } public Developer(String developerKey, int id, String firstName, String lastName) { super(id,firstName,lastName); this.developerKey = developerKey; } public Developer(String developerKey, int id, String firstName, String lastName, String userName, String password, String email, Date dob) { super(id,firstName,lastName, userName, password, email, dob); this.developerKey = developerKey; } public Developer(String developerKey, int id, String firstName, String lastName, String userName, String password, String email) { super(id,firstName,lastName, userName, password, email); this.developerKey = developerKey; } public Developer(String developerKey, int id, String firstName, String lastName, String userName, String password, String email, Date dob, Collection<Address> addresses, Collection<Phone> phoneNumbers) { super(id,firstName,lastName,userName,password,email,dob,addresses,phoneNumbers); this.developerKey = developerKey; } }
package pages; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; /** * Page object class for LinkedInLoginPage */ public class LinkedInLoginPage extends BasePage{ @FindBy(xpath = "//*[@id=\"login-email\" and @class = \"login-email\"]") private WebElement loginField; @FindBy(xpath = "//*[@id=\"login-password\"]") private WebElement passwordField; @FindBy(xpath = "//*[@id=\"login-submit\"]") private WebElement signInButton; @FindBy(xpath = "//a[contains(@class, 'link-forgot')]") private WebElement forgotPasswordLink; @FindBy(xpath = "//*[@id=\"nav-settings__dropdown-trigger\"]/div/span[1]") private WebElement profileMenu; @FindBy(xpath = "//button[@class='form__submit']") private WebElement confirmButton; /** * Constructor of LinkedInLoginPage class. * @param browser - WebDriver instance from test. */ public LinkedInLoginPage(WebDriver browser) { this.browser = browser; PageFactory.initElements(browser, this); } /** * This method enters credentials and click 'logIn' button. * @param username - String with user email. * @param userpass - String with user password. * @<T> - generic type to return corresponding pageObject * @return - either LinkedInHomePage or LinkedInLoginSubmitPage or LinkedInLoginPage */ public <T> T login (String username, String userpass){ loginField.sendKeys(username); passwordField.sendKeys(userpass); signInButton.click(); if (getCurrentUrl().contains("/feed")) { return (T) new LinkedInHomePage(browser); } if (getCurrentUrl().contains("/uas/login")) { return (T) new LinkedInLoginSubmitPage(browser); } else{ //return (T) this; return (T) new LinkedInLoginPage(browser); } } /** * This method checks that required page was loaded */ public boolean isLoaded() { return getCurrentPageTitle().contains("LinkedIn"); } public LinkedInRequestPasswordResetPage clickOnForgotPasswordLink(){ forgotPasswordLink.click(); waitUntilElementIsVisible(confirmButton, 10); return new LinkedInRequestPasswordResetPage(browser); } }
package com.Li.serviceThread; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.Socket; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.json.JSONException; import org.json.JSONObject; import org.yanzi.shareserver.Car_Data; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.HandlerThread; import android.os.Looper; import android.os.Message; import android.util.Log; import android.widget.Toast; import com.Li.data.GroupData; import com.Li.register.RegisterActivity; import com.main.activity.MainActivity; import com.main.activity.MyApplication; import com.main.activity.OverlayDemo; import Utili.Package.LogUtil; public class ServiceClient extends Thread { private Intent intent = new Intent("com.Li.ServiceThread.receiver"); // COME AND CHANGE FLAG NAME public static boolean isConnect = true; public static boolean isConnectService = true; public Socket socketClient; private BufferedWriter bos; private BufferedReader br; private InputStreamReader isr; private OutputStreamWriter ls; Context context; private final static String TAG = "ServiceClient"; String matches = ""; //定义Map集合 存储后台发过来的群组内 其他成员信息 public static Map<String, Car_Data> mapGroup = new HashMap<String, Car_Data>(); //定义Map集合 存储后台发过来的群组成员位置信息 public static HashMap<String, String> cargroup_member = new HashMap<String, String>(); //定义Map集合 存储后台发过来判断后的群组成员位置信息 public static HashMap<Integer, Car_Data> cargroup_member_Location = new HashMap<Integer, Car_Data>(); public static HashMap<String, Car_Data> cargroup_member_LocationWithUsername = new HashMap<String, Car_Data>(); // 存储需要移除的车队成员的VIN public static List<Integer> cargroup_member_LocationRemove = new ArrayList<Integer>(); //定义Map集合 存储后台发过来的已经存在的车群组 信息 public static HashMap<Integer, CarGroup> carGroup_Exist = new HashMap<Integer, CarGroup>(); String chatContent, from_id;//群组聊天信息, 信息哪个车 String announcementContent;//后台推送的车队公告信息 String vin; int intVin; public ServiceClient(Socket s, Context c) { this.socketClient = s; this.context = c; } public void run() { try { Log.i(TAG, "ServiceClient is running"); ls = new OutputStreamWriter(socketClient.getOutputStream()); bos = new BufferedWriter(ls); isr = new InputStreamReader(socketClient.getInputStream()); br = new BufferedReader(isr); // bw初始化过后,回传一个信号给MainActivity(),告诉它 已经初始化ok。 MainActivity.initServiceThread = true; // 在线程池中取出线程 循环解析后台传来的消息 ExecutorService fixedThreadPool = Executors.newFixedThreadPool(5); // 线程池中定时开启线程 检测与后台的连接 // MyApplication.scheduledThreadPool.scheduleAtFixedRate( // connectRunnable, 0, 3000, TimeUnit.MILLISECONDS); while (isConnect) { if (isConnectService) {// 首先判断其他界面有没有点击 退出按钮,若点击了 // 则这里的标志位会职位false // 读取传过来的数据 while ((matches = br.readLine()) != null) { Log.i(TAG, "-----------" + matches); fixedThreadPool.execute(command); } } else { Log.i(TAG, "serviceClient() 关闭"); MyApplication.scheduledThreadPool.wait(); bos.close(); br.close(); ls.close(); isr.close(); isConnect = false; } } } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /*************************************************/ Runnable command = new Runnable() { @Override public void run() { // TODO Auto-generated method stub try { parseJson(matches); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }; /*************************************************/ /* * 检测 与后台链接 */ Runnable connectRunnable = new Runnable() { @Override public void run() { if (socketClient.isInputShutdown() && socketClient.isOutputShutdown() && socketClient.isClosed()) { if (bos != null && br != null && ls != null && isr != null) { try { bos.close(); br.close(); ls.close(); isr.close(); socketClient.close(); isConnect = false; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } socketClient = null; } }; public void send(JSONObject headParam) { try { bos.write(headParam.toString()); bos.flush(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // 绑定client 来发送Jason包 public void ServiceSend(ServiceClient sc, JSONObject out) { sc.send(out); } // 解析json包 public void parseJson(String strResult) throws JSONException,UnsupportedEncodingException { if (strResult != null) { if ("LIVE".equals(strResult)) { ServerConnectService.rcvTime = System.currentTimeMillis(); Log.i("LIVE", "parseJson: 接收到服务器的心跳数据"); } JSONObject connetJSon = new JSONObject(strResult); // 注册 解析 if (connetJSon.has("isSuccess")) { sendRegisterLogin(connetJSon.getBoolean("isSuccess"), connetJSon.getString("content")); } /* * 登录 解析 */ if (connetJSon.has("isSuccesslogin")) { String loginContent = connetJSon.getString("content"); if ((Boolean) connetJSon.get("isSuccesslogin")) { if (MyApplication.register_login){ sendRegisterLoginSuccess(); MyApplication.register_login = false; } else { sendLogin(loginContent); } } else { sendLogin(loginContent); } } // if (connetJSon.has("EmergencyPushBackGround")) { MyApplication.houtai_msg_rcvtime = System.currentTimeMillis(); MyApplication.houtai_msg_push = connetJSon .getString("EmergencyPushBackGround"); } //车群组创建返回信息 if (connetJSon.has("isGroupSuccess")) { if ((Boolean) connetJSon.get("isGroupSuccess")) { // 如果为后台传来的值为true 则发送广播 sendGroupSuccess(); } else { Looper.prepare(); Toast.makeText(MyApplication.getcontext(), "对不起,您注册的信息有误,请重新注册!", Toast.LENGTH_SHORT).show(); Looper.loop(); } } // 解散车队 if (connetJSon.has("isDismissSuccess")) { if (connetJSon.getBoolean("isDismissSuccess")) { // 如果为后台传来的值为true 则发送广播 cargroup_member_Location.clear(); cargroup_member.clear(); sendDeleteSuccess(); } else { Looper.prepare(); Toast.makeText(MyApplication.getcontext(),"对不起,您删除的信息有误,请从新删除!", Toast.LENGTH_SHORT).show(); Looper.loop(); } } // 解析 后台发送来的 邀请请求 是否发送成功 if(connetJSon.has("isAskSuccess")){ MyApplication.AskRequest = connetJSon.getBoolean("isAskSuccess"); sendInviteAsk(); } // 解析 被邀请车辆是否同意被邀请 if(connetJSon.has("isInviteSuccess")){ Log.i(TAG, "邀请同意了--------------------------------"); Boolean isAskSuccess = connetJSon.getBoolean("isInviteSuccess"); String AskReturnContent = connetJSon.getString("content"); sendAskAnswer(isAskSuccess, AskReturnContent); Log.i(TAG, connetJSon.getString("content")+"----------------------------------"); Log.i(TAG, AskReturnContent+"------------------------------------------------"); } String datatype = connetJSon.getString("datatype"); Log.i(TAG, datatype+"----------------------------------"); // 后台发送的邀请请求信息 if ("TEAM_INVITE".equals(datatype)) { Log.i(TAG, "team_invite----------------------------------"); MyApplication.editName = connetJSon.getString("team_name"); MyApplication.veh_lpn = connetJSon.getString("fromid"); OverlayDemo.car_group_id_random = connetJSon.getString("team_id"); MyApplication.teamID = connetJSon.getString("team_id"); String teamStart = connetJSon.getString("team_start"); String teamEnd = connetJSon.getString("team_end"); sendAddCarRegister(teamStart, teamEnd); Log.i(TAG, "team_invite111111111----------------------------------"); } // 解析 后台发送来的车队成员 if("MEMBER_UPDATE".equals(datatype)){ MyApplication.member_update = strResult; sendGroupMember(); } // 解析 后台发送来的车队成员 经纬度信息 if("MEMBER_LOCATION_DATA".equals(datatype)){ String teamId = connetJSon.getString("team_id"); String cargroupMemberInfo = connetJSon.getString("data"); cargroup_member.put(teamId, cargroupMemberInfo); for (String intvin : cargroup_member.keySet()) { Log.d(TAG, "cargroup member location is " + intvin); } // if (!connetJSon.getString("veh_id").equals(MyApplication.user_name)) { // // try { // Log.d(TAG, "car group member location is sava " + connetJSon.getString("veh_id")); // vin = connetJSon.getString("VIN"); // intVin = Integer.valueOf(vin); // if (cargroup_member_Location.containsKey(intVin) && (cargroup_member_LocationWithUsername.containsKey(connetJSon.getString("veh_id")))) { // cargroup_member_Location.get(intVin).lat_cloud = Double.valueOf(connetJSon.getString("veh_lat")); // cargroup_member_Location.get(intVin).longi_cloud = Double.valueOf(connetJSon.getString("veh_lon")); // // } else if (!cargroup_member_Location.containsKey(intVin) && (cargroup_member_LocationWithUsername.containsKey(connetJSon.getString("veh_id")))){ // int hashMapWithVin = cargroup_member_LocationWithUsername.get(connetJSon.getString("veh_id")).vin; // cargroup_member_Location.remove(hashMapWithVin); // cargroup_member_LocationWithUsername.remove(connetJSon.getString("veh_id")); // cargroup_member_LocationRemove.add(hashMapWithVin); // // Car_Data mCar_Data = new Car_Data(); // mCar_Data.lat_cloud = Double.valueOf(connetJSon.getString("veh_lat")); // mCar_Data.longi_cloud = Double.valueOf(connetJSon.getString("veh_lon")); // mCar_Data.user_name = connetJSon.getString("veh_id"); // mCar_Data.vin = intVin; // cargroup_member_Location.put(intVin, mCar_Data); // cargroup_member_LocationWithUsername.put(mCar_Data.user_name, mCar_Data); // // } else { // Car_Data mCar_Data = new Car_Data(); // mCar_Data.lat_cloud = Double.valueOf(connetJSon.getString("veh_lat")); // mCar_Data.longi_cloud = Double.valueOf(connetJSon.getString("veh_lon")); // mCar_Data.user_name = connetJSon.getString("veh_id"); // mCar_Data.vin = intVin; // cargroup_member_Location.put(intVin, mCar_Data); // cargroup_member_LocationWithUsername.put(mCar_Data.user_name, mCar_Data); // } // } catch(Exception e) { // e.printStackTrace(); // } // // for (int vin : cargroup_member_Location.keySet()) { // Log.d(TAG, "cargroup member location is " + cargroup_member_Location.get(vin).lat_cloud + cargroup_member_Location.get(vin).longi_cloud); // } // // Log.d(TAG, "cloud traslation lat is " + connetJSon.getString("veh_lat") + " longi is " + connetJSon.getString("veh_lon")); // // } } // 解析 后台发送来的车群组聊天信息 if("MEMBER_CHAT".equals(datatype)){ chatContent = connetJSon.getString("chatContent"); from_id = connetJSon.getString("from_id"); sendChat(chatContent, from_id); } // 解析 后台推送的车队公告信息 if("team_announce".equals(datatype)){ announcementContent = connetJSon.getString("announce_content"); sendAnnouncement(announcementContent); } // 解析 后台发送的已经存在的车群组 信息 if("TEAM_UPDATE".equals(datatype)){ carGroup_Exist.clear(); try{ for(int i = 1; i <= (connetJSon.length()-1)/2; i++) { CarGroup mcarGroup= new CarGroup(); mcarGroup.team_id = String.valueOf(connetJSon.getString("team"+i+"_id")); mcarGroup.team_name = String.valueOf(connetJSon.getString("team"+i+"_name")); carGroup_Exist.put(i , mcarGroup); } }catch(JSONException e){ e.printStackTrace(); } sendGroupExist(); } /* * 根据String类型的车辆id 来存储群组成员信息 */ // String groupMember=connetJSon.getString("fromid"); // // if(mapGroup.containsKey(groupMember)){ // // }else{ // sendAddCarRegister(); // MyApplication.editName = connetJSon.getString("team_name"); // MyApplication.veh_lpn = connetJSon.getString("fromid"); // OverlayDemo.car_group_id_random = connetJSon.getString("team_id"); // // } // // if (connetJSon.has("team_id")) { // MyApplication.teamID = connetJSon.getString("team_id"); // } } } /* * 当收到后台isSuccesslogin=true 并且 isRegister = false */ // 发广播进入,在MAIN ACT 里接收广播跳到TAB ACTIVITY WYL public void sendLogin(String s) { Intent intent = new Intent("com.Li.ServiceClient.sentLogin"); intent.putExtra("loginContent", s); context.sendBroadcast(intent); } // 第一次注册成功后,立即登录后后台回复的登录成功广播 public void sendRegisterLoginSuccess() { Intent intent1 = new Intent("com.Li.ServiceClient.sentRegisterLoginSuccess"); context.sendBroadcast(intent1); } // 向后台发送登陆成功注册的JSON车辆信息在 registeractivity MsgReceiverServiceRegisterLogin /* * broadcaster receiver get the bradcaster and send register info to houtai * in regiteractivity MsgReceiverServiceRegisterLogin set isRegister = true */ // 在注册活动中收到广播,广播接收器MsgReceiverServiceRegisterLogin,向后台发送注册信息,并置isRegister = // true public void sendRegisterLogin(boolean b, String s) { Intent intent1 = new Intent("com.Li.ServiceClient.sentRegisterLogin"); intent1.putExtra("isRegister", b); intent1.putExtra("content", s); context.sendBroadcast(intent1); } /* * 当收到后台isSuccesslogin=true 并且 isRegister = true 发广播,广播接收器在REGISTER * ACTIVITY使程序跑到TAB -->MAP活动 WYL */ public void sendRegisterLoginTrue() { Intent intent1 = new Intent( "com.Li.ServiceClient.sendRegisterLoginTrue"); context.sendBroadcast(intent1); } public void sendGroupSuccess() { Intent intent2 = new Intent("com.Li.ServiceClient.sendGroupSuccess"); context.sendBroadcast(intent2); } public void sendDeleteSuccess() { Intent intent2 = new Intent("com.Li.ServiceClient.sendDeleteSuccess"); context.sendBroadcast(intent2); } public void sendAddCarRegister(String start, String end){ Intent intent = new Intent("com.Li.ServiceClient.sendAddCarRegister"); intent.putExtra("team_start", start); intent.putExtra("team_end", end); context.sendBroadcast(intent); } public void sendIsInviteSuccess(){ Intent intent2 = new Intent("com.Li.ServiceClient.sendIsInviteSuccess"); context.sendBroadcast(intent2); } public void sendGroupMember(){ Intent intent2 = new Intent("com.Li.ServiceClient.sendMemberUpdate"); context.sendBroadcast(intent2); } public void sendInviteAsk(){ Intent intent2 = new Intent("com.Li.ServiceClient.sendInviteAsk"); context.sendBroadcast(intent2); } public void sendAskAnswer(Boolean b, String s){ Intent intent = new Intent("com.Li.ServiceClient.sendAskAnswer"); intent.putExtra("isAskSuccess", b); intent.putExtra("AskReturnContent", s); context.sendBroadcast(intent); } public void sendChat(String s, String t) { Intent intent = new Intent("com.Li.ServiceClient.sendChat"); intent.putExtra("CHAT", s); intent.putExtra("FROM", t); context.sendBroadcast(intent); intent.removeExtra("CHAT"); intent.removeExtra("FROM"); } public void sendAnnouncement(String s) { Intent intent = new Intent("com.Li.ServiceClient.sendAnnouncement"); intent.putExtra("Announcement", s); context.sendBroadcast(intent); intent.removeExtra("Announcement"); } public void sendGroupExist() { Intent intent = new Intent("com.Li.ServiceClient.GroupExistRegister"); context.sendBroadcast(intent); } }
package consumer.eureka.service; import consumer.eureka.pojo.User; import java.util.List; public interface UserService { List<User> getUser(); }
package com.tencent.mm.plugin.appbrand.jsapi.camera; import com.tencent.mm.plugin.appbrand.e; import com.tencent.mm.plugin.appbrand.e.b; import com.tencent.mm.plugin.appbrand.page.p; class g$1 extends b { final /* synthetic */ p fJO; final /* synthetic */ int fKG; final /* synthetic */ AppBrandCameraView fOG; final /* synthetic */ g fOH; g$1(g gVar, p pVar, AppBrandCameraView appBrandCameraView, int i) { this.fOH = gVar; this.fJO = pVar; this.fOG = appBrandCameraView; this.fKG = i; } public final void onDestroy() { this.fJO.b(this.fOG); this.fJO.b(this.fOG); this.fJO.b(this.fOG); a$a.fNY.h(Integer.valueOf(this.fKG)); e.b(this.fJO.mAppId, this); } }
package com.zhao.leetcode; import java.lang.annotation.Target; public class Trie { public class TrieNode{ public char data; public TrieNode children[] =new TrieNode[26]; public boolean isEndingChar =false; public TrieNode(char data){ this.data =data; } } private TrieNode root =new TrieNode('/'); public void insert(char [] text){ TrieNode p = root; for (int i=0;i<text.length;++i){ int index = text[i]-'a'; if (p.children[index]==null){ TrieNode newNode =new TrieNode(text[i]); p.children[i] = newNode; } p=p.children[index]; } p.isEndingChar=true; } public boolean find(char [] text){ TrieNode p =root; for (int i=0;i<text.length;++i){ int index = text[i]-'a'; if (p.children[index]==null){ return false; } p=p.children[index]; } if (p.isEndingChar==false) return false; return true; } }
/* * This class is auto generated by https://github.com/hauner/openapi-processor-spring. * DO NOT EDIT. */ package generated.api; import generated.model.Bar; import generated.model.Foo; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; public interface EnumApi { @GetMapping(path = "/endpoint") ResponseEntity<Void> getEndpoint( @RequestParam(name = "foo") Foo foo, @RequestParam(name = "bar") Bar bar); }
/* * 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 tubes; import QuestionAnswering.InformationExtractor; import IndonesianNLP.IndonesianPOSTagger; import IndonesianNLP.IndonesianPhraseChunker; import java.util.List; import model.Entity; import static QuestionAnswering.InformationExtractor.extractEntity; import static QuestionAnswering.InformationExtractor.printSentence; /** * * @author gilang */ public class TestClass { public static void main(String[] args){ String line = "\"#indonesia #diskon Dominos Pizza Promo Menu Terbaru - Cheesy Bread Hanya Rp. 27.727\",\"661699269133541378\",\"GilaPromoDotCom\",\"2015-11-04 07:19:34\",\"\",\"\""; String[] temp = line.split("\","); line = temp[0]; line = line.replace("(?i)#diskon", "diskon"); line = line.replace("(?i)#promo", "promo"); line = line.replaceAll("@[\\w]*|#[\\w]*|[\\S]+\\.[\\S]+/[\\S]+", " "); // remove hashtag + url line = line.replaceAll("[!\"$'()*+/:;,<=>?@\\^_`{|}]+", " "); //remove punctiation line = line.replaceAll("(?i)cuma|hanya|rp.", ""); List<String[]> sentence = IndonesianPOSTagger.doPOSTag(line); Entity e = InformationExtractor.extractEntity(sentence); // for(String[] word : sentence){ // for(String s : word){ // System.out.print(s + " "); // } // } System.out.println(" discount: " + e.discount + " item: " + e.item); } }
package util; import play.i18n.Messages; import play.mvc.Http; /** * Flash message helper */ public class Message { public static final String MESSAGE = "message"; public static final String MESSAGE_TYPE = "message_type"; private static Http.Flash flash() { return Http.Context.current().flash(); } public static void error(){ danger(Messages.get("error.message")); } public static void success(){ success(Messages.get("success.message")); } public static void danger(String text){ flash().put(MESSAGE, text); flash().put(MESSAGE_TYPE, "danger"); } public static void info(String text){ flash().put(MESSAGE, text); flash().put(MESSAGE_TYPE, "info"); } public static void warning(String text){ flash().put(MESSAGE, text); flash().put(MESSAGE_TYPE, "warning"); } public static void success(String text){ flash().put(MESSAGE, text); flash().put(MESSAGE_TYPE, "success"); } }
package com.zitiger.plugin.xdkt.servicetemplate.generator; import com.intellij.openapi.components.ServiceManager; import com.intellij.psi.JavaPsiFacade; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiElementFactory; import com.intellij.psi.PsiField; import com.intellij.psi.PsiMethod; import com.intellij.psi.PsiParameter; import com.intellij.psi.codeStyle.JavaCodeStyleManager; import com.zitiger.plugin.xdkt.dictionary.Translator; import com.zitiger.plugin.xdkt.exception.PluginException; import com.zitiger.plugin.xdkt.template.TemplateManager; import com.zitiger.plugin.xdkt.utils.AnnotationUtils; import com.zitiger.plugin.xdkt.utils.MethodUtils; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * @author zitiger */ public class ServiceTemplateGenerator { private final static Set<String> READ_ACTION_NAME_SET = new HashSet<>(); static { READ_ACTION_NAME_SET.add("read"); READ_ACTION_NAME_SET.add("select"); READ_ACTION_NAME_SET.add("get"); READ_ACTION_NAME_SET.add("query"); READ_ACTION_NAME_SET.add("list"); } public void generateCode(PsiClass psiClass, PsiMethod psiMethod) throws PluginException { if (psiMethod.isConstructor()) { throw new PluginException("Method is the constructor"); } if (null == psiMethod.getBody()) { throw new PluginException("Method body is null"); } addServiceTemplateField(psiClass); addAutowiredAnnotation(psiClass); addFinalModifier(psiMethod); PsiClass returnPsiClass = MethodUtils.getReturnPsiClass(psiMethod); PsiClass genericPsiClass = MethodUtils.getGenericReturnPsiClass(psiMethod); Map<String, Object> map = new HashMap<>(); map.put("desc", Translator.translate(psiMethod.getName())); map.put("frameworkPackage", "cn.com.ser"+"vyou.xqy.framework"); map.put("isTransactional", isTransactional(psiMethod)); map.put("returnClass", returnPsiClass.getName()); map.put("realClass", genericPsiClass == null ? null : genericPsiClass.getName()); TemplateManager templateManager = ServiceManager.getService(TemplateManager.class); String bodyString = templateManager.process("servicetemplate/ServiceTemplate", map); PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(psiClass.getProject()); psiMethod.getBody().add(elementFactory.createStatementFromText(bodyString, psiClass)); JavaCodeStyleManager.getInstance(psiClass.getProject()).shortenClassReferences(psiClass); } private void addServiceTemplateField(PsiClass psiClass) { if (findServiceTemplateField(psiClass) != null) { return; } PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(psiClass.getProject()); PsiField psiField = elementFactory.createFieldFromText("cn.com.ser" + "vyou.xqy.framework.rpc.facadeimpl.ServiceTemplate serviceTemplate;", psiClass); PsiField[] psiFields = psiClass.getFields(); if (psiFields.length > 0) { psiClass.addAfter(psiField, psiFields[psiFields.length - 1]); } else { psiClass.addBefore(psiField, psiClass.getMethods()[0]); } } private void addAutowiredAnnotation(PsiClass psiClass) { PsiField psiField = findServiceTemplateField(psiClass); if (psiField == null) { return; } AnnotationUtils.addAnnotation(psiField, "org.springframework.beans.factory.annotation.Autowired", "@org.springframework.beans.factory.annotation.Autowired"); } private PsiField findServiceTemplateField(PsiClass psiClass) { PsiField[] psiFields = psiClass.getFields(); for (PsiField psiField : psiFields) { if ("serviceTemplate".equals(psiField.getName())) { return psiField; } } return null; } private void addFinalModifier(PsiMethod psiMethod) { for (PsiParameter psiParameter : psiMethod.getParameterList().getParameters()) { if (!psiParameter.getModifierList().hasExplicitModifier("final") ) { psiParameter.getModifierList().setModifierProperty("final", true); } } } private boolean isTransactional(PsiMethod psiMethod) { for (String string : READ_ACTION_NAME_SET) { if (psiMethod.getName().startsWith(string)) { return false; } } return true; } }
package net.skykrowd; import java.util.Scanner; public class Ejercicio1 { public static void main(String[] args){ Scanner leer = new Scanner(System.in); int n,i=0,k; System.out.print("Ingrese N: "); n=leer.nextInt(); if (n%2==0) n=9; char mat[][]= new char [n][]; while(i<mat.length/2+1){ mat[i]=new char [i]; for (int j=0;j<mat[i].length;j++) mat[i][j]='*'; i++; } k=mat.length/2+1; while(k>=0&&i<n){ mat[i]=new char [k]; for (int j=0;j<mat[i].length;j++) mat[i][j]='*'; i++; k--; } mat[n-1][0]='*'; mostrar(mat); } private static void mostrar(char mat[][]){ for (int i=0;i<mat.length;i++) { for (int j = 0; j < mat[i].length; j++) { System.out.print(mat[i][j] + "\t"); } System.out.print("\n"); } System.out.print(mat[mat.length-1][mat[mat.length-1].length-1]); } }
package com.tree.binary; import java.util.Scanner; public class TreeTraversalApplication { public static void main(String[] args) { BinaryTree tree = new BinaryTree(); Scanner s = new Scanner(System.in); int numOfNodes = s.nextInt(); for (int i = 0; i < numOfNodes; i++) { tree.insert(new Node(s.nextInt())); } System.out.println("Pre order traversal"); tree.preOrder(); System.out.println(); System.out.println("In order traversal"); tree.inOrder(); System.out.println(); System.out.println("Post order traversal"); tree.postOrder(); System.out.println(); System.out.println("Level order traversal"); tree.levelOrder(); } }
package com.tencent.mm.u; public interface a$a { void CT(); void fM(String str); }
package log; import com.github.motoki317.traq_bot.model.MessageCreatedEvent; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; /** * ConsoleLogger only logs to standard output. */ public class ConsoleLogger implements Logger { private final DateFormat logFormat; private final boolean debug; public ConsoleLogger(TimeZone logTimeZone) { this.logFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS"); this.logFormat.setTimeZone(logTimeZone); this.debug = "1".equals(System.getenv("DEBUG")); } @Override public void log(CharSequence message) { Date now = new Date(); String msg = this.logFormat.format(now) + " " + message; System.out.println(msg); } @Override public void debug(CharSequence message) { if (!debug) return; this.log(message); } @Override public void logEvent(MessageCreatedEvent event, boolean isSpam) { String logMsg = createCommandLog(event, isSpam); this.log(logMsg); } /** * Create a user command log String. <br/> * Example output <br/> * 2018/10/01 11:02:46.430 [Channel]&lt;User&gt;: `>ping` <br/> * @param event Guild message received event. * @return Human readable user command usage log. */ static String createCommandLog(MessageCreatedEvent event, boolean isSpam) { return String.format( "[%s]<%s>: `%s`%s", event.getMessage().getChannelId(), event.getMessage().getUser().getName(), event.getMessage().getPlainText(), isSpam ? " Spam detected" : "" ); } @Override public void logException(CharSequence message, Throwable e) { this.log(message); e.printStackTrace(); } }
package com.creativewidgetworks.goldparser.engine; import junit.framework.TestCase; import org.junit.Test; import com.creativewidgetworks.goldparser.engine.CharacterSetList; public class CharacterSetListTest extends TestCase { @Test public void testListConstructorWithSizing() { CharacterSetList sets = new CharacterSetList(5); assertEquals("wrong number of placeholders", 5, sets.size()); for (int i = 0; i < sets.size(); i++) { assertNull(sets.get(i)); } } }
/** * API / 其他設定 / 運行程序 */ package com.ericlam.mc.minigames.core;
package swm11.jdk.jobtreaming.back.app.payment.model; import lombok.Getter; import lombok.Setter; import swm11.jdk.jobtreaming.back.app.common.model.Common; import swm11.jdk.jobtreaming.back.app.lecture.model.Lecture; import swm11.jdk.jobtreaming.back.app.user.model.User; import swm11.jdk.jobtreaming.back.enums.payment.PayStatus; import swm11.jdk.jobtreaming.back.enums.payment.PayType; import javax.persistence.*; import java.io.Serializable; @Entity @Table(name = "payment") @Getter public class Payment extends Common implements Serializable { @ManyToOne @JoinColumn(nullable = false, referencedColumnName = "id") private User user; // 결제한 사람 @ManyToOne @JoinColumn(nullable = false, referencedColumnName = "id") private Lecture lecture; // 결제한 강연 @Setter @Column(nullable = false, length = 20) @Enumerated(EnumType.STRING) private PayStatus status; // 결제 상태 @Setter @Column(nullable = false, length = 20) @Enumerated(EnumType.STRING) private PayType type; // 결제 종류 @Column(nullable = false) private Integer price; // 금액 }
package com.uptc.prg.maze.view.panels; import com.uptc.prg.maze.view.UIStrings; import javax.swing.*; import java.awt.*; public class StatusBarPanel extends JPanel { private JLabel mStatus; public StatusBarPanel() { this.initialize(); this.initializeStatusBar(); } public final void setStatusMessage(String message) { this.mStatus.setText(message); } /*====================================== PRIVATE METHODS =====================================*/ private void initializeStatusBar() { JPanel content = new JPanel(); content.setLayout(new BoxLayout(content, BoxLayout.PAGE_AXIS)); this.mStatus = new JLabel(); this.mStatus.setAlignmentX(Component.CENTER_ALIGNMENT); this.mStatus.setHorizontalAlignment(SwingConstants.CENTER); this.mStatus.setHorizontalTextPosition(SwingConstants.CENTER); content.add(this.mStatus); this.add(content); } private void initialize() { this.setLayout(new GridBagLayout()); } }
package com.mes.old.meta; // Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final /** * Erpinv generated by hbm2java */ public class Erpinv implements java.io.Serializable { private ErpinvId id; public Erpinv() { } public Erpinv(ErpinvId id) { this.id = id; } public ErpinvId getId() { return this.id; } public void setId(ErpinvId id) { this.id = id; } }
package series; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class seriesTest { static SeriesDatabase serieData; @BeforeAll static void initClass() { serieData = new SeriesDatabase(); } @BeforeEach void open() { assertTrue(serieData.openConnection()); assertFalse(serieData.openConnection()); assertTrue(serieData.closeConnection()); assertTrue(serieData.openConnection()); } @AfterEach void close() { assertTrue(serieData.closeConnection()); } @Test void createCapitulo() { assertTrue(serieData.createTableCapitulo()); assertFalse(serieData.createTableCapitulo()); assertEquals(2400, serieData.loadCapitulos("capitulos.csv")); } @Test void createValora() { assertTrue(serieData.createTableValora()); assertFalse(serieData.createTableValora()); assertEquals(2106, serieData.loadValoraciones("valoraciones.csv")); } }
// package com.todos.api.services; // import com.todos.api.models.Todo; // import org.springframework.stereotype.Service; // import java.util.ArrayList; // import java.util.List; // @Service // public class TodosServiceFake { // private List<Todo> _todos = new ArrayList<>(); // { // _todos.add(new Todo(1,"First todo", false));; // }; // public List<Todo> GetAll(){ return _todos;} // public Todo Get(int id){ // return _todos.stream().filter(x->x.getId() == id).findFirst().get();} // public Todo create(Todo todo) { // todo.setId(_todos.size() + 1); // _todos.add(todo); // return todo; // } // public Todo update(int id, Todo todo) { // Todo td = _todos.stream().filter(x-> x.getId() == id) // .findFirst().get(); // if (td != null){ // td.setCompleted(todo.isCompleted()); // td.setTitle(todo.getTitle()); // } // return td; // } // public void delete(int id){ // _todos.remove( // _todos.stream().filter(x-> x.getId() == id) // .findFirst().get()); // } // }
package com.stem.service.impl; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.stem.dao.TigerUserOperationMapper; import com.stem.entity.TigerUserOperation; import com.stem.entity.TigerUserOperationExample; import com.stem.service.TigerUserOperationService; @Service("tigerUserOperationService") public class TigerUserOperationServiceImpl implements TigerUserOperationService { private TigerUserOperationMapper tigerUserOperationMapper; @Override public List<TigerUserOperation> list(TigerUserOperationExample example){ return this.tigerUserOperationMapper.selectByExample(example); } @Override public TigerUserOperation getByPK(Integer id){ return this.tigerUserOperationMapper.selectByPrimaryKey(id); } @Override public int getTotal(TigerUserOperationExample example){ return this.tigerUserOperationMapper.countByExample(example); } @Override public int update(TigerUserOperation model,TigerUserOperationExample example){ return this.tigerUserOperationMapper.updateByExample(model,example); } @Override public int updateByPK(TigerUserOperation model){ return this.updateByPK(model); } @Override public int deleteByPK(Integer id){ return this.tigerUserOperationMapper.deleteByPrimaryKey(id); } @Override public int delete(TigerUserOperationExample example){ return this.tigerUserOperationMapper.deleteByExample(example); } @Override public int add(TigerUserOperation model){ return this.tigerUserOperationMapper.insert(model); } @Resource public void setTigerUserOperationMapper(TigerUserOperationMapper TigerUserOperationMapper){ this.tigerUserOperationMapper = TigerUserOperationMapper; } }
package com.yunhe.cargomanagement.dao; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.yunhe.cargomanagement.entity.PurComm; import com.yunhe.cargomanagement.entity.WarehouseReceipt; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Repository; import java.util.List; /** * <p> * 入库历史 Mapper 接口 * </p> * * @author 史江浩 * @since 2019-01-17 */ @Repository @Mapper public interface WarehouseReceiptMapper extends BaseMapper<WarehouseReceipt> { /** * 查询待入库单分页 * @param page 分页插件 * @param warehouseReceipt 入库实体类 * @return 待入库单数据 */ List<WarehouseReceipt> selectwarehouseReceiptByState(Page page,WarehouseReceipt warehouseReceipt); /** * 查询入库单分页 * @param page 分页插件 * @param warehouseReceipt 入库实体类 * @return 入库单数据 */ List<WarehouseReceipt> selectwarehouseReceiptTwoByState(Page page,WarehouseReceipt warehouseReceipt); /** * 根据ID删除入库单 * @param warehouseReceipt 入库实体类 * @return int */ int deletewarehouseReceiptTwoById(WarehouseReceipt warehouseReceipt); /** * 待入库单详情 * @param id 根据id查询 * @return 待入库单详情 */ WarehouseReceipt selectWarhouseXiangList(int id); /** * 入库单详情 * @param id 根据id查询 * @return 入库单详情 */ WarehouseReceipt selectWarhouseXiangTwoList(int id); /** * 一对一 * @return 商品信息 */ List<PurComm> selectWarHouseZhong(int id); /** * 根据订单号查询待入库单详情 * @param wreNumber * @return */ WarehouseReceipt selectWarhouseByNumber(String wreNumber); /** * 根据id修改入库状态 * @param wreState 入库状态 * @param id id * @return int */ int updateWareHouseById(String wreState,int id); }
package com.ahmetkizilay.yatlib4j.blocks; import com.ahmetkizilay.yatlib4j.oauthhelper.OAuthHolder; public class GetBlocksList { private static final String BASE_URL = "https://api.twitter.com/1.1/blocks/list.json"; private static final String HTTP_METHOD = "GET"; public static GetBlocksList.Response sendRequest(GetBlocksList.Parameters params, OAuthHolder oauthHolder) { throw new UnsupportedOperationException(); } public static class Response { } public static class Parameters { } }
package com.shaoye.quartz.test; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.shaoye.thread.test.MyThread; @RunWith(SpringJUnit4ClassRunner.class) // 表示继承了SpringJUnit4ClassRunner类 @ContextConfiguration(locations = { "classpath:applicationContext.xml" }) public class Transfer4DB { private static Logger logger = LoggerFactory.getLogger(Transfer4DB.class); @Test public void testJob() { logger.info("dasdasd"); MyThread t = new MyThread(); Thread t1 = new Thread(t, "线程1"); t1.start(); } }
package com.corbin.topcoder; import org.junit.*; import static org.junit.Assert.assertTrue; public class AccountBalanceTest { private static AccountBalance accountBalance = new AccountBalance(); private static String[] transaction0 = {"C 1000", "D 500", "D 350"}; private static String[] transaction1 = {}; private static String[] transaction2 = {"D 50", "D 20", "D 40"}; private static String[] transaction3 = {"D 1234", "C 987", "D 2345", "C 654", "D 6789", "D 34567"}; @Test public void testCase0() { assertTrue("Ending balance should be $250", accountBalance.processTransactions(100, transaction0) == 250); } @Test public void testCase1() { assertTrue("Ending balance should be $100", accountBalance.processTransactions(100, transaction1) == 100); } @Test public void testCase2() { assertTrue("Ending balance should be -$10", accountBalance.processTransactions(100, transaction2) == -10); } @Test public void testCase3() { assertTrue("Ending balance should be $10580", accountBalance.processTransactions(53874, transaction3) == 10580); } }
package com.mihoyo.hk4e.wechat.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import java.util.Date; @Entity public class Token { /** * 因为Token只有一个 所有操作都针对这个ID */ public static final Long ID = 1L; @Id private Long id; @Column private String content; @Column private Date expireDate; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Date getExpireDate() { return expireDate; } public void setExpireDate(Date expireDate) { this.expireDate = expireDate; } public boolean valid(){ return this.expireDate != null && this.expireDate.after(new Date()); } public static Token createOne(String content, Date expireDate){ Token token = new Token(); token.setId(ID); token.setContent(content); token.setExpireDate(expireDate); return token; } }
package com.example.administrator.halachavtech.Model.Hazmana; /** * Created by Administrator on 11/01/2017. */ public class OrderProduct { public enum Ezor{ Darom_rahok, Darom, Merkaz, Zafon, Zafon_rahok, WITHOUT_HATKANA } public static final int DEFAULT_QUANTITY = 1; private Product product; private int quantity; private double price; private Contact contact; private String notes; private Ezor ezor; private boolean hatkana; private int stock; /** * The Constructor with default quantity = 1 * @param product */ public OrderProduct(Product product) { this.product = product; this.quantity = DEFAULT_QUANTITY; } public OrderProduct(Product product, int quantity) { this.product = product; this.quantity = quantity; this.contact = new Contact(); } public OrderProduct(Product product, int quantity, double price, Contact contact, String notes, Boolean hatkana, Ezor ezor, int stock) { this.product = product; this.quantity = quantity; this.price = price; this.contact = contact; this.notes = notes; this.hatkana = hatkana; this.ezor = ezor; this.stock = stock; } public int getStock() { return stock; } public void setStock(int stock) { this.stock = stock; } public Contact getContact() { return contact; } public void setContact(Contact contact) { this.contact = contact; } public String getNotes() { return notes; } public void setNotes(String notes) { this.notes = notes; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public Product getProduct() { return product; } public void setProduct(Product product) { this.product = product; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public Ezor getEzor() { return ezor; } public void setEzor(Ezor ezor) { this.ezor = ezor; } public boolean isHatkana() { return hatkana; } public void setHatkana(boolean hatkana) { this.hatkana = hatkana; } @Override public String toString() { return "OrderProduct{" + "product=" + product + ", \n quantity=" + quantity + ", \n price=" + price + ", \n contact=" + contact + ", \n notes='" + notes + '\'' + ", \n hatkana=" + hatkana + ", \n ezor=" + ezor + '}'; } }
package com.amoraesdev.mobify.repositories; import java.util.List; import java.util.UUID; import org.springframework.data.cassandra.repository.CassandraRepository; import org.springframework.data.cassandra.repository.Query; import com.amoraesdev.mobify.entities.Notification; public interface NotificationRepository extends CassandraRepository<Notification> { @Query("select * from notification where username = ?0 and application_id = ?1") public List<Notification> findByUsernameAndApplicationId(String username, String applicationId); @Query("select * from notification where username = ?0 and received = false") public List<Notification> findByUsernameAndNotReceived(String username); @Query("select * from notification where username = ?0 and application_id = ?1 and id = ?2") public Notification findByUsernameAndApplicationIdAndId(String username, String applicationId, UUID id); }
package com.supconit.kqfx.web.fxzf.warn.daos.Impl; import java.util.List; import org.springframework.stereotype.Repository; import hc.orm.AbstractBasicDaoImpl; import com.supconit.kqfx.web.fxzf.warn.daos.WarnInfoDao; import com.supconit.kqfx.web.fxzf.warn.entities.WarnInfo; @Repository("fxzf_warn_warninfo_dao") public class WarnInfoDaoImpl extends AbstractBasicDaoImpl<WarnInfo, String> implements WarnInfoDao { private static final String NAMESPACE = WarnInfo.class.getName(); @Override protected String getNamespace() { return NAMESPACE; } @Override public List<WarnInfo> getAll() { return selectList("getAll"); } @Override public WarnInfo getByTempletTypeAndStation(WarnInfo warnInfo) { return this.selectOne("getByTempletTypeAndStation", warnInfo); } }
/* * 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 entities.dto; import entities.SchoolClass; import entities.SchoolCourse; import java.util.List; /** * * @author emilt */ public class SchoolCourseDTO { // private String courseName; private String description; private List<SchoolClassDTO> classes; private int amountOfClasses; private final Long id; // public SchoolCourseDTO(SchoolCourse sco) { this.courseName = sco.getCourseName(); this.description = sco.getDescription(); if (sco.getClasses() != null) { if (!sco.getClasses().isEmpty()) { this.amountOfClasses = sco.getClasses().size(); } } this.id = sco.getId(); } // public String getCourseName() { return courseName; } public void setCourseName(String courseName) { this.courseName = courseName; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public List<SchoolClassDTO> getClasses() { return classes; } public void setClasses(List<SchoolClassDTO> classes) { this.classes = classes; } public void addClass(SchoolClass sc) { this.classes.add(new SchoolClassDTO(sc)); } public void addClassDTO(SchoolClassDTO sc) { this.classes.add(sc); } public Long getId() { return id; } public int getAmountOfClasses() { return amountOfClasses; } }
import java.util.Map; import java.util.ArrayList; import java.util.HashMap; public class Patient { private String patientName; private ArrayList<Sensor> sensor = new ArrayList<Sensor>(); private Map<Sensor, SafeRange> safety = new HashMap<Sensor, SafeRange>(); private int frequency; private int sensorCount = 0; public Patient(String name, int feq) { this.patientName = name; this.frequency = feq; } public void attachSensor(Sensor sen, SafeRange sr) { this.safety.put(sen, sr); this.sensor.add(sen); this.sensorCount ++; } public String getPatientName(){ return this.patientName; } public int getFrequency(){ return this.frequency; } public ArrayList<Sensor> getSensor(){ return this.sensor; } public Map<Sensor, SafeRange> getSafety(){ return this.safety; } }
package de.adesso.gitstalker.core.requests; import de.adesso.gitstalker.core.enums.RequestType; import de.adesso.gitstalker.core.objects.Query; /** * This is the request used for requesting the organization details. */ public class OrganizationDetailRequest { private final int estimatedQueryCost = 1; private String query; private String organizationName; private RequestType requestType; public OrganizationDetailRequest(String organizationName) { this.organizationName = organizationName; /** * GraphQL Request for the organization details. * Requesting the relevant information for the requested organization. * Requests the current rate limit of the token at the API. */ this.query = "query {\n" + "organization(login:\"" + organizationName + "\") {\n" + "name \n" + "location \n" + "websiteUrl \n" + "url \n" + "avatarUrl \n" + "description \n" + "members(first: 1) {\n" + "totalCount\n" + "}\n" + "teams(first: 1) {\n" + "totalCount\n" + "}\n" + "repositories(first: 1) {\n" + "totalCount\n" + "}\n" + "}\n" + "rateLimit {\n" + "cost\n" + "remaining\n" + "resetAt\n" + "}\n" + "}"; this.requestType = RequestType.ORGANIZATION_DETAIL; } /** * Generates the query for the organizationDetail request. * @return Generated query for the request type. */ public Query generateQuery() { return new Query(this.organizationName, this.query, this.requestType, this.estimatedQueryCost); } }
package api.service; import api.arq.exception.ApiErroGeralException; import api.arq.rest.CRUDService; import api.arq.util.AutenticacaoUtil; import api.arq.validator.dto.ApiErroCodigo; import api.controller.dto.ComplexoEolicoDTO; import api.model.ComplexoEolico; import api.model.Usuario; import api.repository.ComplexoEolicoRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.Optional; @Service public class ComplexoEolicoService extends CRUDService<ComplexoEolico>{ @Autowired private ComplexoEolicoRepository complexoEolicoRepository; @Autowired private AutenticacaoUtil autenticacaoUtil; @Override public void executarAntesDeSalvar(ComplexoEolico entidade) { Optional<Usuario> usuarioAutenticado = autenticacaoUtil.getUsuarioAutenticado(); } @Override public void executarAposSalvar(ComplexoEolico entidade) {} @Override public void executarAntesDeRemover(ComplexoEolico entidade) {} @Override public void executarAposRemover(ComplexoEolico entidadePersistida) {} public Object buscarComplexosEolicosCompletos() throws Exception{ ArrayList<ComplexoEolicoDTO> listComplexoEolicoDTO = new ArrayList<ComplexoEolicoDTO>(); List<ComplexoEolico> complexosEolicos = complexoEolicoRepository.findAll(); if (!complexosEolicos.isEmpty()) { for (ComplexoEolico complexoEolico : complexosEolicos) { ComplexoEolicoDTO complexoEolicoDTO = new ComplexoEolicoDTO(complexoEolico.getId(), complexoEolico.getNome(), complexoEolico.getUf(), complexoEolico.getParquesEolicos()); listComplexoEolicoDTO.add(complexoEolicoDTO); } return listComplexoEolicoDTO; } else { throw new ApiErroGeralException(ApiErroCodigo.NAO_ENCONTRADO); } } }
package cn.jboa.conversion; import java.math.BigDecimal; import java.util.Map; import ognl.DefaultTypeConverter; public class DoubleConversion extends DefaultTypeConverter{ public Object convertValue(Map<?, ?> context, String[] values, Class<?> toClass) { if(toClass != Double.class||values == null || values.length==0){ return null; } String score = values[0]; Double value =new BigDecimal(score).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue(); return value; } }
package com.example.smn_arggregator; import android.telephony.AccessNetworkConstants; import android.util.Log; import java.io.File; import java.util.ArrayList; import java.util.List; import twitter4j.Query; import twitter4j.QueryResult; import twitter4j.Status; import twitter4j.StatusUpdate; import twitter4j.Trend; import twitter4j.Trends; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.TwitterFactory; import twitter4j.conf.ConfigurationBuilder; public class GetTwitterData { private static final String ConsumerKey = BuildConfig.ConsumerKey; private static final String ConsumerSecretKey = BuildConfig.ConsumerSecretKey; private static final String AccessToken = BuildConfig.AccessToken; private static final String AccessSecretToken = BuildConfig.AccessSecretToken; private Twitter twitter; public GetTwitterData(){ ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true) .setOAuthConsumerKey(ConsumerKey) .setOAuthConsumerSecret(ConsumerSecretKey) .setOAuthAccessToken(AccessToken) .setOAuthAccessTokenSecret(AccessSecretToken); TwitterFactory tf = new TwitterFactory(cb.build()); twitter = tf.getInstance(); } public ArrayList<String> getTrends(){ ArrayList<String> Hashtags = new ArrayList<>(); ArrayList<Integer> woeid = new ArrayList<>(); woeid.add(23424975); woeid.add(23424977); woeid.add(1100968); woeid.add(2459115); for(int i=0 ; i<4;i++) { try{ // UK = 23424975 United States: 23424977 New York: 2459115 Trends trends = twitter.getPlaceTrends(woeid.get(i)); int count =0; for(Trend trend : trends.getTrends()){ if(trend.getName().startsWith("#")){ if(!Hashtags.contains(trend.getName())){ Hashtags.add(trend.getName()); } } Log.d("Bull",count+" "+trend.getName()); count++; } }catch(TwitterException exception){ exception.printStackTrace(); } } return Hashtags; } public List<Status> getPost(String hashtag){ try { Query query = new Query(hashtag); query.setCount(10); query.setLang("en"); query.setResultType(Query.ResultType.popular); QueryResult result; result = twitter.search(query); List<Status> tweets = result.getTweets(); // *****for debug******* for (Status tweet : tweets) { Log.d("Bull","@" + tweet.getUser().getName()+ " ---- " + tweet.getText()); } //********* return tweets; } catch (TwitterException te) { te.printStackTrace(); Log.d("Bull","Failed to search tweets: " + te.getMessage()); } return null; } public void postTweet(String text, String path){ File file = new File(path); StatusUpdate status = new StatusUpdate(text); // set the text to be uploaded here. if(!path.isEmpty()) status.setMedia(file); // set the image to be uploaded here. try { twitter.updateStatus(status); Log.d("Bull","Manage to post tweet: "); } catch (TwitterException e) { e.printStackTrace(); Log.d("Bull","Failed to post tweet: " + e.getMessage()); } } public ArrayList<Status> getReplies(String screenName, long tweetID) { ArrayList<Status> replies = new ArrayList<>(); try { Query query = new Query("to:" + screenName + " since_id:" + tweetID); //query.setCount(10); //query.setLang("en"); QueryResult results; // if you want all the replies just do the do - while loop //do { results = twitter.search(query); List<Status> tweets = results.getTweets(); for (Status tweet : tweets) if (tweet.getInReplyToStatusId() == tweetID) replies.add(tweet); //} while ((query = results.nextQuery()) != null); } catch (Exception e) { e.printStackTrace(); } return replies; } }
package code; //displays boardArray, Scannerman passes in our boardArray, then displays it public class BoardDisplay { public BoardDisplay(char[][] boardArray){ for(int i = 0; i < 50; i++){ for(int j = 0; j < 51; j++){ System.out.print(boardArray[i][j]); } } } }
package com.cts.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.cts.model.Users; @Repository public interface UserRepository extends JpaRepository<Users, Long> { public Users findByEmail(String email); public Users findByEmailAndPassword(String email,String password); public Users findByEmailAndPasswordAndActive(String email,String password, Integer active); }
package com.koreait.spring; public interface Speaker { public void volumeUp(); public void vulumeDown(); }
package testcase; import es.utils.mapper.Mapper; import es.utils.mapper.exception.MappingException; import es.utils.mapper.exception.MappingNotFoundException; import es.utils.mapper.impl.object.EnumMapper; import org.junit.jupiter.api.Test; import java.time.temporal.ChronoUnit; import java.util.concurrent.TimeUnit; import static org.assertj.core.api.Assertions.assertThat; public class EnumMapperTest { @Test public void shouldReturnFromClass() throws MappingNotFoundException, MappingException { Mapper mapper = new Mapper(); EnumMapper<TimeUnit, ChronoUnit> mapping = mapper.addForEnum(TimeUnit.class, ChronoUnit.class); mapper.build(); assertThat(mapping.fromClass()).isEqualTo(TimeUnit.class); } @Test public void shouldReturnToClass() throws MappingNotFoundException, MappingException { Mapper mapper = new Mapper(); EnumMapper<TimeUnit, ChronoUnit> mapping = mapper.addForEnum(TimeUnit.class, ChronoUnit.class); mapper.build(); assertThat(mapping.toClass()).isEqualTo(ChronoUnit.class); } @Test public void shouldAddNewEnumMapping() throws MappingNotFoundException, MappingException { Mapper mapper = new Mapper(); EnumMapper<TimeUnit, ChronoUnit> mapping = mapper.addForEnum(TimeUnit.class, ChronoUnit.class); mapper.build(); assertThat(mapper.map(TimeUnit.NANOSECONDS, ChronoUnit.class)).isNull(); mapping.add(TimeUnit.NANOSECONDS, ChronoUnit.NANOS); assertThat(mapper.map(TimeUnit.NANOSECONDS, ChronoUnit.class)).isEqualTo(ChronoUnit.NANOS); } @Test public void shouldIgnoreEnumMapping() throws MappingNotFoundException, MappingException { Mapper mapper = new Mapper(); EnumMapper<TimeUnit, ChronoUnit> mapping = mapper.addForEnum(TimeUnit.class, ChronoUnit.class); mapper.build(); assertThat(mapper.map(TimeUnit.DAYS, ChronoUnit.class)).isEqualTo(ChronoUnit.DAYS); assertThat(mapper.map(TimeUnit.MINUTES, ChronoUnit.class)).isEqualTo(ChronoUnit.MINUTES); mapping.ignore(TimeUnit.DAYS,TimeUnit.MINUTES); assertThat(mapper.map(TimeUnit.DAYS, ChronoUnit.class)).isNull(); assertThat(mapper.map(TimeUnit.MINUTES, ChronoUnit.class)).isNull(); } @Test public void shouldReturnDefaultEnumValue() throws MappingNotFoundException, MappingException { Mapper mapper = new Mapper(); EnumMapper<TimeUnit, ChronoUnit> mapping = mapper.addForEnum(TimeUnit.class, ChronoUnit.class); mapper.build(); assertThat(mapper.map(TimeUnit.NANOSECONDS, ChronoUnit.class)).isNull(); mapping.setDefaultDestinationEnumValue(ChronoUnit.FOREVER); assertThat(mapper.map(TimeUnit.NANOSECONDS, ChronoUnit.class)).isEqualTo(ChronoUnit.FOREVER); } @Test public void shouldReturnStringRappresentation() throws MappingException { EnumMapper<TimeUnit,ChronoUnit> em = new EnumMapper<>(TimeUnit.class,ChronoUnit.class); assertThat(em.toString()).isEqualTo("EnumMapper[<class java.util.concurrent.TimeUnit,class java.time.temporal.ChronoUnit>]"); } }
package MatriculaEstudiantes; import java.util.Objects; public class Estudiantes { public static boolean verificar = false; String nombre; String apellido; public Estudiantes(String nombre, String apellido) { this.nombre = nombre; this.apellido = apellido; } /*public static boolean isVerificar() { return verificar; } public static void setVerificar(boolean verificar) { Estudiantes.verificar = verificar; }*/ public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getApellido() { return apellido; } public void setApellido(String apellido) { this.apellido = apellido; } @Override public boolean equals(Object obj) { final Estudiantes otroEstudiante = (Estudiantes) obj; return false; } @Override public String toString() { return nombre + " " + apellido + " " ; } }
import java.util.HashMap; public class CountTheNumberOfConsistentStrings { public static int countConsistentStrings(String allowed, String[] words) { int result = 0; HashMap<Integer,Character> map = new HashMap<>(); for (int i = 0; i<allowed.length(); i++){ map.put(i,allowed.charAt(i)); } for (String word : words){ int count =0; for (int i = 0;i<word.length();i++){ if (map.containsValue(word.charAt(i))){ count = count+1; } if (count== word.length()){ result = result+1; } } } return result; } public static void main(String[] args) { String[] words = {"cc","acd","b","ba","bac","bad","ac","d"}; int result = countConsistentStrings("cad", words); System.out.println(result); } }
package com.eb.service; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.List; import javax.naming.NamingException; import com.eb.dao.CalBoardDAO; import com.eb.dto.CalBoardDTO; import com.lol.comm.DBConn; public class CalBoardService { private static CalBoardService service=new CalBoardService(); public static CalBoardService getService(){ return service; } private CalBoardService() {} public List<CalBoardDTO> list() { DBConn db=DBConn.getDB(); Connection conn=null; List<CalBoardDTO> list=null; try { conn=db.getConn(); conn.setAutoCommit(false); CalBoardDAO dao=CalBoardDAO.getCalBoardDAO(); list=dao.List(conn); conn.commit(); } catch (SQLException e) { try {conn.rollback();} catch (SQLException e1) {} System.out.println(e); } finally { if(conn!=null) try {conn.close();} catch(SQLException e) {} } return list; } public CalBoardDTO detail(int bno) { DBConn db=DBConn.getDB(); Connection conn=null; CalBoardDTO dto=null; try { conn=db.getConn(); conn.setAutoCommit(false); CalBoardDAO dao=CalBoardDAO.getCalBoardDAO(); dto=dao.Detail(conn,bno); conn.commit(); } catch(SQLException e) { try {conn.rollback();} catch (SQLException e1) {} System.out.println(e); } finally { if(conn!=null) try {conn.close();} catch(SQLException e) {} } return dto; } public void Insert(CalBoardDTO dto) { DBConn db=DBConn.getDB(); Connection conn=null; try { conn=db.getConn(); conn.setAutoCommit(false); CalBoardDAO dao=CalBoardDAO.getCalBoardDAO(); dao.Insert(conn, dto); conn.commit(); } catch (SQLException e) { try {conn.rollback();} catch (SQLException e1) {} System.out.println(e); }finally { if(conn!=null) try {conn.close();} catch(SQLException e) {} } } public void Delete(int bno) { // TODO Auto-generated method stub } }
package cn.edu.zucc.web.service; /** * Created by zxy on 11/20/2016. */ public interface AsyncDataService { String getUserData(String userno); }
package main.java.Server.Exceptions; public class PieceNotFoundException extends Exception { private String message; public PieceNotFoundException(String message) { this.message = message; } public String getMessage() { return this.message; } }
package com.fansolomon.Structural.Decorator.Shape.impl; import com.fansolomon.Structural.Decorator.Shape.Shape; /** * ConcreteComponent * 定义一个对象(可以给这个对象动态地添加职责) */ public class Circle implements Shape { @Override public void draw() { System.out.println("Circle draw..."); } }
/* Implement a Queue using Singly Linked List */ /* A queue is a FIFO(First In First Out) data structure. A queue has to maintain two pointers, front and back. New elements are inserted from the back and elements are deleted from the front. The two operations mentioned here are push and pop, which are actually given in reference to a stack, but apply to a queue as well. I have also defined the peek operation which is just returning the value at the front of the queue without removing it. The benefit of implementing a Queue using a Linked List is that memory use is optimum. We create new nodes when we are inserting and memory is allocated then. */ class QueueNode { int val; QueueNode next; public QueueNode(int val) { this.val = val; this.next = null; } } class Queue { QueueNode front, back; public Queue() { this.front = this.back = null; } // Push a value onto the queue and update the back pointer. void push(int val) { QueueNode newNode = new QueueNode(val); if(this.back == null) { this.front = this.back = newNode; } else { this.back.next = newNode; this.back = newNode; } } // Remove the value at the front of the queue, if exists and return it. Update the front pointer. void pop() { if(this.front == null) return; QueueNode temp = this.front; this.front = this.front.next; // In the event, the removed node was the only node in the list and the queue is now empty. if(this.front == null) this.back = null; } // Return the value at the front of the queue, without removing the node. int peek() { return this.front.val; } }
package view; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.geom.Point2D; import java.util.ArrayList; import java.util.List; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.table.DefaultTableModel; import Model.Data; import Model.Element; import Model.Model; /** * The Class Fenetre. */ public class Fenetre extends JFrame { /** The Constant serialVersionUID. */ private static final long serialVersionUID = -6521378809519608384L; /** The title. */ private JLabel title = new JLabel(); /** The view. */ private View view; /** The model. */ final Model model; /** * Instantiates a new fenetre. */ public Fenetre() { this.setTitle("mon stock"); this.setSize(new Dimension(800, 600)); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Dessine le graphe représentant le stock List<Element> elements = new ArrayList<Element>(); elements.add(new Element("livre", 40)); elements.add(new Element("banane", 10)); elements.add(new Element("chocolat", 50)); elements.add(new Element("soda", 70)); title.setText(" "); this.getContentPane().add(title, BorderLayout.SOUTH); model = new Model(elements); view = new View(); view.setModel(model); this.getContentPane().add(view); DefaultTableModel m = new DefaultTableModel(); final Data table = new Data(m, model); table.setModel(m); this.getContentPane().add(new JScrollPane(table), BorderLayout.EAST); } /** * Gets the view. * * @return the view */ public View getView() { return view; } /** * Handle mouse click. * * @param p the p */ public void handleMouseClick(Point2D p) { int index = view.getArcPointClicked(p); if (index != -1) { title.setText("produit : " + model.getElements().get(index).getName() + " - " + " nombre en stock : " + model.getElements().get(index).getValue()); revalidate(); } } }
package com.ayushman999.urbanclapclone.Adapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.ayushman999.urbanclapclone.Listener.ClickListener; import com.ayushman999.urbanclapclone.Model.Seller; import com.ayushman999.urbanclapclone.R; import com.ayushman999.urbanclapclone.databinding.SellingModelBinding; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; public class SellingAdapter extends RecyclerView.Adapter<SellingAdapter.SellerHolder> { ArrayList<Seller> list; ClickListener listener; public SellingAdapter(ArrayList<Seller> list, ClickListener listener) { this.list=list; this.listener=listener; } @NonNull @NotNull @Override public SellerHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) { View myView= LayoutInflater.from(parent.getContext()).inflate(R.layout.selling_model,parent,false); SellerHolder holder=new SellerHolder(myView); return holder; } @Override public void onBindViewHolder(@NonNull @NotNull SellerHolder holder, int position) { Seller s=list.get(position); holder.binding.sellerName.setText(s.getName()); holder.binding.sellerSkill.setText(s.getSkill()); holder.binding.sellerAddress.setText(s.getAddress()); holder.binding.sellerCard.setOnClickListener(v->{ listener.onSellerClick(s); }); } @Override public int getItemCount() { return list.size(); } public class SellerHolder extends RecyclerView.ViewHolder { SellingModelBinding binding; public SellerHolder(@NonNull @NotNull View itemView) { super(itemView); binding=SellingModelBinding.bind(itemView); } } }
package cn.neepu.service; import org.springframework.ui.Model; import cn.neepu.po.User; public interface RegistService { public String regist(User user, Model model); }
/* * 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 pe.gob.onpe.adan.controller.local; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import pe.gob.onpe.adan.constants.Constants; import pe.gob.onpe.adan.model.adan.AsignacionLocal; import pe.gob.onpe.adan.model.adan.Local; import pe.gob.onpe.adan.service.Adan.AsignacionLocalService; import pe.gob.onpe.adan.service.Adan.LocalService; import pe.gob.onpe.adan.service.Adan.MesaService; import pe.gob.onpe.adan.service.Adan.TipoSolucionService; /** * * @author marrisueno */ @RestController @RequestMapping(value="/local/*") public class LocalController { @Autowired LocalService localService; @Autowired TipoSolucionService solucionService; @Autowired MesaService mesaService; @Autowired AsignacionLocalService asignacionLocalService; // private String ubigeo; // @RequestMapping("/init") // public String init(HttpServletRequest request, @RequestParam("ubigeo") String ubigeo) { // this.ubigeo = ubigeo; // return ubigeo; // } // // @RequestMapping("/nuevo") // public ModelAndView index(HttpServletRequest request) { // ModelAndView view; // view = new ModelAndView("mantenimiento/localDashboard"); // return view; // } // @RequestMapping(value="/getUbigeo", method = RequestMethod.GET) // @ResponseBody // public String getUbigeo(HttpServletRequest request){ // String ubigeo = this.ubigeo; // return ubigeo; // } @RequestMapping(value="/getSoluciones", method = RequestMethod.GET) @ResponseBody public List getSoluciones(HttpServletRequest request){ List soluciones = solucionService.findAllByEstado(Constants.ESTADO_SOLUCION_ACTIVO); return soluciones; } @RequestMapping(value="/getSoluciones/{type}", method = RequestMethod.GET) @ResponseBody public List getSolucionesIn(HttpServletRequest request, @PathVariable("type") String type){ List<Integer> list = new ArrayList<>(); for (String val : type.split(",")) { list.add(Integer.parseInt(val)); } List soluciones = solucionService.findAllByIdIn(list); return soluciones; } @RequestMapping(value = "/save", method = RequestMethod.POST, headers = "Accept=application/json", produces = "application/json;charset=UTF-8") @ResponseBody public String save(HttpServletRequest request, @RequestParam("local") String slocal) { Gson g = new Gson(); Local local = g.fromJson(slocal, Local.class); Date date = new Date(); String executeDisabled = "", executeEnabled = ""; boolean success; try { if (local.getN_LOCAL_PK() != null) { local.setC_AUD_USUARIO_MODIFICACION(getPrincipal()); local.setD_AUD_FECHA_MODIFICACION(date); } else { local.setC_AUD_USUARIO_CREACION(getPrincipal()); local.setD_AUD_FECHA_CREACION(date); } localService.saveLocal(local); //local.setC_NOMBRE(new String(local.getC_NOMBRE().getBytes("ISO-8859-1"), "UTF-8")); // if (local.getN_LOCAL_PK() != null) { // if (local.getN_ESTADO() == 0) { // executeDisabled = localService.disabledLocal(getPrincipal(), local.getC_CODIGO()); // } else { // executeEnabled = localService.enabledLocal(getPrincipal(), local.getC_CODIGO()); // } // } success = true; } catch (Exception ex) { success = false; } Map<String, Object> map = new HashMap<>(); map.put("data", local); map.put("success", success); map.put("disabled", executeDisabled); map.put("enabled", executeEnabled); return new Gson().toJson(map); } @RequestMapping(value = "/disabled", method = RequestMethod.POST, headers = "Accept=application/json") @ResponseBody public String disabled(HttpServletRequest request, @RequestParam("code") String code) { String executeDisabled = ""; try { executeDisabled = localService.disabledLocal(getPrincipal(), code); } catch (Exception ex) { ex.printStackTrace(); } Map<String, Object> map = new HashMap<>(); map.put("data", executeDisabled); return new Gson().toJson(map); } @RequestMapping(value = "/enabled", method = RequestMethod.POST, headers = "Accept=application/json") @ResponseBody public String enabled(HttpServletRequest request, @RequestParam("code") String code) { String executeEnabled = ""; try { executeEnabled = localService.enabledLocal(getPrincipal(), code); } catch (Exception ex) { ex.printStackTrace(); } Map<String, Object> map = new HashMap<>(); map.put("data", executeEnabled); return new Gson().toJson(map); } @RequestMapping(value = "/ubigeo/{ubigeo}/{code}", method = RequestMethod.GET) public ResponseEntity<List<Local>> allProcess(@PathVariable("ubigeo") String ubigeo, @PathVariable("code") String code) { if (code.length() == 8) { AsignacionLocal asignacionLocal = asignacionLocalService.findByDni(code); if (asignacionLocal != null) { code = asignacionLocal.getC_LOCAL(); } } List<Local> list = localService.findAllLocalByUbigeo(ubigeo, code); if (list.isEmpty()) { return new ResponseEntity<List<Local>>(HttpStatus.NO_CONTENT); } return new ResponseEntity<List<Local>>(list, HttpStatus.OK); } @RequestMapping(value = "/{id}", method = RequestMethod.GET) public String getLocalById(@PathVariable("id") String id) { Gson gson = new Gson(); JsonParser jsonParser = new JsonParser(); JsonObject jResponse = new JsonObject(); boolean success = true; try { Local local = localService.findLocalByCode(id); JsonObject localJ = (JsonObject)jsonParser.parse(gson.toJson(local)); jResponse.add("data", localJ); } catch (Exception e) { success = false; jResponse.addProperty("message", "Error cargando datos de Local."); } jResponse.addProperty("success", success); return new Gson().toJson(jResponse); } @RequestMapping(value = "/mesa/{mesa}", method = RequestMethod.GET) public String getLocalByMesa(@PathVariable("mesa") String id) { Gson gson = new Gson(); JsonParser jsonParser = new JsonParser(); JsonObject jResponse = new JsonObject(); boolean success = true; try { String idLocal = mesaService.findMesaById(id); Local local = localService.findLocalByCode(idLocal); JsonObject localJ = (JsonObject)jsonParser.parse(gson.toJson(local)); jResponse.add("data", localJ); } catch (Exception e) { success = false; jResponse.addProperty("message", "Error cargando datos de Local."); } jResponse.addProperty("success", success); return new Gson().toJson(jResponse); } private String getPrincipal(){ String userName = null; Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if(principal instanceof UserDetails){ userName = ((UserDetails)principal).getUsername(); } else { userName = principal.toString(); } return userName; } }
package com.didiglobal.thriftmock.server; public interface MockIface { }
package graphSeries; import java.util.*; public class PrimsAlgo { public static void main(String[] args) { int n = 5; ArrayList<ArrayList<Node>> adj = new ArrayList<ArrayList<Node>>(); for (int i = 0; i < n; i++) adj.add(new ArrayList<Node>()); adj.get(0).add(new Node(1, 2)); adj.get(1).add(new Node(0, 2)); adj.get(1).add(new Node(2, 3)); adj.get(2).add(new Node(1, 3)); adj.get(0).add(new Node(3, 6)); adj.get(3).add(new Node(0, 6)); adj.get(1).add(new Node(3, 8)); adj.get(3).add(new Node(1, 8)); adj.get(1).add(new Node(4, 5)); adj.get(4).add(new Node(1, 5)); adj.get(2).add(new Node(4, 7)); adj.get(4).add(new Node(2, 7)); PrimsAlgo obj = new PrimsAlgo(); obj.primsAlgoOptimized(adj, n); } void primsAlgo(ArrayList<ArrayList<Node>> adj, int N) { int key[] = new int[N]; boolean mstSet[] = new boolean[N]; int parent[] = new int[N]; Arrays.fill(key, Integer.MAX_VALUE); Arrays.fill(mstSet, false); Arrays.fill(parent, -1); // Starting with the first node in the graph key[0] = 0; parent[0] = -1; // In a Minimum Spanning Tree there could only be N - 1 edges for (int i = 0; i < N - 1; i++) { int min = Integer.MAX_VALUE; int u = 0; // select the minimum weight edge from the key array for (int v = 0; v < N; v++) { if (!mstSet[v] && key[v] < min) { min = key[v]; u = v; } } // Add it to the MST mstSet[u] = true; // Iterate through the adjacent nodes for (Node it : adj.get(u)) { // If the weight of is smaller than the already existing weight update it if (!mstSet[it.v] && it.weight < key[it.v]) { // Update the parent and key value parent[it.v] = u; key[it.v] = it.weight; } } } for (int i = 1; i < N; i++) { System.out.println(parent[i] + " -- " + i); } } void primsAlgoOptimized(ArrayList<ArrayList<Node>> adj, int N) { int key[] = new int[N]; int parent[] = new int[N]; boolean mstSet[] = new boolean[N]; Arrays.fill(key, Integer.MAX_VALUE); Arrays.fill(parent, -1); Arrays.fill(mstSet, false); // Here we are taking a priority queue so we don't have to search through the // array for the smallest element PriorityQueue<Node> pq = new PriorityQueue<Node>(N, new Node()); key[0] = 0; pq.add(new Node(key[0], 0)); while (!pq.isEmpty()) { int u = pq.poll().v; mstSet[u] = true; for (Node it : adj.get(u)) { if (!mstSet[it.v] && it.weight < key[it.v]) { parent[it.v] = u; key[it.v] = it.weight; pq.add(new Node(it.v, key[it.v])); } } } for (int i = 1; i < N; i++) { System.out.println(parent[i] + " -- " + i); } } static class Node implements Comparator<Node> { int v; int weight; Node() { } Node(int v, int weight) { this.v = v; this.weight = weight; } @Override public int compare(Node node1, Node node2) { if (node1.weight < node2.weight) { return -1; } else if (node1.weight > node2.weight) { return 1; } return 0; } } }
package edu.uci.ics.sdcl.firefly; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import java.util.Vector; public class QuestionFactory { /* Template Lists */ public ArrayList<String> templateMethodInvocation = new ArrayList<String>(); public ArrayList<String> templateConditional = new ArrayList<String>(); public ArrayList<String> templateLoop = new ArrayList<String>(); public ArrayList<String> templateVariable = new ArrayList<String>(); private String questionPrompt; private Microtask question; /* for the Range-values (ACE Editor) */ private Integer startingLine; private Integer startingColumn; private Integer endingLine; private Integer endingColumn; private Hashtable<Integer, Microtask> microtaskMap; public QuestionFactory() { this.microtaskMap = new Hashtable<Integer, Microtask>(); /* Method invocation */ templateMethodInvocation.add("Is there any issue with the method invocation(s) \"<M>\" at line <#> that might be related to the failure?"); /* Conditional */ templateConditional.add("Is there any issue with the conditional clause between lines <#1> and <#2> that might be related to the failure?"); /* Loops */ templateLoop.add("Is there any issue with the <L>-loop between lines <#1> and <#2> that might be related to the failure?"); /* Variables */ templateVariable.add("Is there any issue with the use or the definition of variable \"<#>\" in the source code below that might be related to the failure?"); } /** * * @param methodsParsed only the code snippets for which microtasks will be generated * @param i * @param bugReport * @return the map of microtasks */ public Hashtable<Integer, Microtask> generateMicrotasks(Vector<CodeSnippet> methodsParsed, String bugReport, String testCase, int numberOfExistingMicrotasks) { Integer microtaskId = numberOfExistingMicrotasks; this.microtaskMap = new Hashtable<Integer, Microtask>(); for (CodeSnippet codeSnippet : methodsParsed) { Vector<CodeElement> statements = codeSnippet.getStatements(); // now getting the question for the statements for (CodeElement element : statements) { //System.out.println("Question type: "+ element.getType()); switch (element.getType()) { case CodeElement.METHOD_INVOCATION: for (String templateForQuestion : templateMethodInvocation) { boolean addQuestion = false; // assuming question is NOT good formed MyMethodCall elementCall = (MyMethodCall)element; /* setting up the position for the element */ StringBuilder methodNames = new StringBuilder(); methodNames.append(elementCall.getName()); if(elementCall.getNestedMethods().size() > 0) { List<String> nestedMethods = elementCall.getNestedMethods(); for(int i=0; i<nestedMethods.size();i++) { methodNames.append(", "); methodNames.append(nestedMethods.get(i)); } } questionPrompt = new String(templateForQuestion); if ( -1 != questionPrompt.indexOf("parameters")) // question about parameters { // are there parameters? ('2' for the brackets) if (1 < elementCall.getNumberOfParameters()) addQuestion = true; // question is all set } else addQuestion = true; // other questions are always good formed if (addQuestion) { // then add question! this.startingLine = elementCall.getElementStartingLine(); this.startingColumn = elementCall.getElementStartingColumn(); this.endingLine = elementCall.getElementEndingLine(); this.endingColumn = elementCall.getElementEndingColumn(); questionPrompt = questionPrompt.replaceAll("<M>", methodNames.toString()); //questionPrompt = questionPrompt.replaceAll("<G>", codeSnippet.getMethodSignature().getName()); questionPrompt = questionPrompt.replaceAll("<#>", this.startingLine.toString()); question = new Microtask(CodeElement.METHOD_INVOCATION, codeSnippet, elementCall, questionPrompt, this.startingLine, this.startingColumn, this.endingLine, this.endingColumn, microtaskId, bugReport, testCase); this.microtaskMap.put(question.getID(),question); microtaskId++; } } break; case CodeElement.IF_CONDITIONAL: for (String templateForQuestion : templateConditional) { MyIfStatement elementIf = (MyIfStatement)element; questionPrompt = new String(templateForQuestion); // the starting line of the body this.startingLine = elementIf.getElementStartingLine(); this.startingColumn = elementIf.getElementStartingColumn(); // Verifies existence of else clause if (elementIf.isThereIsElse()) { // get Else statement end this.endingLine = elementIf.getElseEndingLine(); this.endingColumn = elementIf.getElseEndingColumn(); } else { // no Else then get just body end (then statement end) this.endingLine = elementIf.getBodyEndingLine(); this.endingColumn = elementIf.getBodyEndingColumn(); } // Changes the template according to the line structure of the statement if ( !(this.startingLine.equals(this.endingLine))) { questionPrompt = questionPrompt.replaceAll("<#1>", this.startingLine.toString()); questionPrompt = questionPrompt.replaceAll("<#2>", this.endingLine.toString()); } else { questionPrompt = questionPrompt.substring(0, questionPrompt.indexOf("between")) + "at line " + this.startingLine + questionPrompt.substring(questionPrompt.indexOf("<#2>")+4); } question = new Microtask(CodeElement.IF_CONDITIONAL, codeSnippet, elementIf, questionPrompt, this.startingLine, this.startingColumn, this.endingLine, this.endingColumn, microtaskId, bugReport, testCase); this.microtaskMap.put(question.getID(),question); microtaskId++; } break; case CodeElement.SWITCH_CONDITIONAL: for (String templateForQuestion : templateConditional) { questionPrompt = new String(templateForQuestion); questionPrompt = this.setUpQuestionPrompt(questionPrompt, element); question = new Microtask(CodeElement.SWITCH_CONDITIONAL, codeSnippet, element, questionPrompt, element.getElementStartingLine(), element.getElementStartingColumn() , element.getBodyEndingLine(),element.getBodyEndingColumn() , microtaskId, bugReport, testCase); this.microtaskMap.put(question.getID(),question); microtaskId++; } break; case CodeElement.FOR_LOOP: case CodeElement.DO_LOOP: case CodeElement.WHILE_LOOP: for (String templateLoopQuestion : templateLoop) { questionPrompt = new String(templateLoopQuestion); questionPrompt = this.setUpQuestionPrompt(questionPrompt, element); questionPrompt = questionPrompt.replaceAll("<#1>", element.getElementStartingLine().toString()); questionPrompt = questionPrompt.replaceAll("<#2>", element.getElementEndingLine().toString()); this.startingLine = element.getElementStartingLine(); this.startingColumn = element.getElementStartingColumn(); /*this.endingLine = element.getElementEndingLine(); this.endingColumn = element.getElementEndingColumn();*/ switch (element.getType()) { case CodeElement.FOR_LOOP: questionPrompt = questionPrompt.replaceAll("<L>", "For"); question = new Microtask(CodeElement.FOR_LOOP, codeSnippet, element, questionPrompt, this.startingLine, this.startingColumn, this.endingLine, this.endingColumn, microtaskId, bugReport, testCase); break; case CodeElement.DO_LOOP: this.startingLine = element.getBodyStartingLine(); this.startingColumn = element.getBodyStartingColumn(); this.endingColumn = element.getBodyEndingColumn(); this.endingLine = element.getBodyEndingLine(); questionPrompt = questionPrompt.replaceAll("<L>", "Do"); question = new Microtask(CodeElement.DO_LOOP, codeSnippet, element, questionPrompt, this.startingLine, this.startingColumn, this.endingLine,this.endingColumn, microtaskId, bugReport, testCase); break; case CodeElement.WHILE_LOOP: questionPrompt = questionPrompt.replaceAll("<L>", "While"); question = new Microtask(CodeElement.WHILE_LOOP, codeSnippet, element, questionPrompt, this.startingLine, this.startingColumn, this.endingLine,this.endingColumn, microtaskId, bugReport, testCase); break; } this.microtaskMap.put(question.getID(),question); microtaskId++; } break; // Variable declarations case CodeElement.VARIABLE_DECLARATION: this.startingLine = element.getElementStartingLine(); this.startingColumn = element.getElementStartingColumn(); this.endingLine = element.getElementEndingLine(); this.endingColumn = element.getElementEndingColumn(); for (String templateVariableQuestion : templateVariable) { questionPrompt = new String(templateVariableQuestion); questionPrompt = questionPrompt.replaceAll("<#>", ((MyVariable)element).getName() ); question = new Microtask(CodeElement.VARIABLE_DECLARATION, codeSnippet, element, questionPrompt, this.startingLine, this.startingColumn, this.endingLine, this.endingColumn, microtaskId, bugReport, testCase); this.microtaskMap.put(question.getID(), question); microtaskId++; } break; // Add more cases here default: System.out.println("!!! Type of element did not matched: " + element.getType() + " !!!"); break; } } } return this.microtaskMap; } private String setUpQuestionPrompt(String questionPromptArg, CodeElement elementArg) { if (questionPromptArg.indexOf("<#1>") > 0) //it means it will ask about the body { /* setting up the position for the body */ this.startingLine = elementArg.getBodyStartingLine(); this.startingColumn = elementArg.getBodyStartingColumn(); this.endingLine = elementArg.getBodyEndingLine(); this.endingColumn = elementArg.getBodyEndingColumn(); // System.out.println("Starting and ending line: " + this.startingLine + ", " + this.endingLine); if ( this.startingLine != this.endingLine ) { questionPromptArg = questionPromptArg.replaceAll("<#1>", this.startingLine.toString()); questionPromptArg = questionPromptArg.replaceAll("<#2>", this.endingLine.toString()); } else { // System.out.println("Old question: " + questionPromptArg); questionPromptArg = questionPromptArg.substring(0, questionPromptArg.indexOf("between")) + "at line " + this.startingLine + questionPromptArg.substring(questionPromptArg.indexOf("<#2>")+4); // System.out.println("New question: " + questionPromptArg); } } else { /* setting up the position for the element */ this.startingLine = elementArg.getElementStartingLine(); this.startingColumn = elementArg.getElementStartingColumn(); this.endingLine = elementArg.getElementEndingLine(); this.endingColumn = elementArg.getElementEndingColumn(); questionPromptArg = questionPromptArg.replaceAll("<#>", this.startingLine.toString()); } return questionPromptArg; } public Hashtable<Integer, Microtask> getConcreteQuestions() { return microtaskMap; } }
package ru.sbt.jmm2; import ru.sbt.jmm2.implementations.SimpleExecutionManager; import ru.sbt.jmm2.implementations.Task; import org.apache.log4j.Logger; import static java.lang.Thread.sleep; public class JmmExample { private final static Logger logger = Logger.getLogger( JmmExample.class ); public static void main( String[] args ) throws InterruptedException { Runnable[] tasks = new Runnable[50]; for ( int i = 0; i < tasks.length; i++ ) { tasks[i] = new Task( i ); } SimpleExecutionManager manager = new SimpleExecutionManager( 20, tasks.length ); Context context = manager.execute( ( ) -> logger.warn( "All tasks are completed !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" ), tasks ); for ( int i = 0; i < 4; i++ ) { sleep( 2000 ); printResult( context ); logger.warn( "INTERRUPT!!!" ); context.interrupt(); } } private static void printResult( Context context ) { logger.info( "Completed " + context.getCompletedTaskCount() + ", Failed " + context.getFailedTaskCount() + ", Interrupted " + context.getInterruptedTaskCount() + ", Finished " + context.isFinished() ); } }
package util; /** * @author malf * @description TODO * @project how2jStudy * @since 2020/11/2 */ public class MysqlUtil { }
package com.example.girlswhocode.test; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.content.Intent; import android.view.View; import android.widget.*; public class Police extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_police); Button b1= (Button) findViewById(R.id.button14); b1.setOnClickListener(new View.OnClickListener() { public void onClick(View v) {rights(); } }); Button b2= (Button) findViewById(R.id.button15); b2.setOnClickListener(new View.OnClickListener() { public void onClick(View v) {resources(); } }); } private void rights() { Intent intent = new Intent(this, PoliceRights.class); startActivity(intent); } private void resources() { Intent intent = new Intent(this, PoliceResources.class); startActivity(intent); } }
package com.eigen.model; import java.math.BigDecimal; import java.util.Calendar; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; @Entity @Table(name = "hist_data") public class MHistData { @Id @GeneratedValue @Column(name="id") private long id = -1; @Column(name="profile_id") private long profile_id = -1; @JsonSerialize(using = CalendarSerializer.class) @JsonDeserialize(using = CalendarDeserializer.class) @Column(name="ts") private Calendar ts = Calendar.getInstance(); @Column(name="type") private String type = ""; @Column(name="open") private BigDecimal open = null; @Column(name="low") private BigDecimal low = null; @Column(name="high") private BigDecimal high = null; @Column(name="close") private BigDecimal close = null; @Column(name="adj_close") private BigDecimal adjClose = null; @Column(name="nav") private BigDecimal nav = null; @Column(name="volume") private BigDecimal volume = null; public long getId() { return id; } public void setId(long id) { this.id = id; } public long getProfile_id() { return profile_id; } public void setProfile_id(long profile_id) { this.profile_id = profile_id; } public Calendar getTs() { return ts; } public void setTs(Calendar ts) { this.ts = ts; } public String getType() { return type; } public void setType(String type) { this.type = type; } public BigDecimal getOpen() { return open; } public void setOpen(BigDecimal open) { this.open = open; } public BigDecimal getLow() { return low; } public void setLow(BigDecimal low) { this.low = low; } public BigDecimal getHigh() { return high; } public void setHigh(BigDecimal high) { this.high = high; } public BigDecimal getClose() { return close; } public void setClose(BigDecimal close) { this.close = close; } public BigDecimal getAdjClose() { return adjClose; } public void setAdjClose(BigDecimal adjClose) { this.adjClose = adjClose; } public BigDecimal getNav() { return nav; } public void setNav(BigDecimal nav) { this.nav = nav; } public BigDecimal getVolume() { return volume; } public void setVolume(BigDecimal volume) { this.volume = volume; } }
package com.lspring.iocother; import java.util.Date; public class Person { private String name; private Integer age = 25; private String tel; private Person parent; private Date bornDate; public Date getBornDate() { return bornDate; } public void setBornDate(Date bornDate) { this.bornDate = bornDate; } public String getName() { return name; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + ", tel=" + tel + ", parent=" + parent + "]"; } public Person(String name) { super(); this.name = name; System.out.println("创建Person,构造 函数1"); } public void setName(String name) { this.name = name; } // public Person(String name, Integer age) { // super(); // this.name = name; // this.age = age; // System.out.println("创建Person,构造 函数2"); // } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } public Person getParent() { return parent; } public void setParent(Person parent) { this.parent = parent; } }
import java.io.*; import java.util.*; public class Unigram { private Map<String, Map<String, Double>> probabilityMap = new HashMap<String, Map<String, Double>>(); public Unigram (String inFilePath) { buildModel(inFilePath); } /* * Given a string that occurs in the created model, * return a string based on the probability distribution of subsequent strings */ public String getNextState (String inputString) { //for the current state, get the probability distribution of the next state TreeMap<String, Double> probVector = (TreeMap<String, Double>) probabilityMap.get(inputString); if (probVector.size() <= 0) { //terminal case return null; } String prevKey = probVector.firstKey(); if (probVector.size() == 1) { return prevKey; } //generate a random value, iterate over the probabilities until a match is found Object[] keyArray = probVector.keySet().toArray(); Object[] probArray = probVector.values().toArray(); double randVal = Math.random(); for (int i = 0; i < keyArray.length - 1; i++) { if (randVal >= (double) probArray[i] && randVal <= (double) probArray[i + 1]) { return (String) keyArray[i]; } } return (String) keyArray[keyArray.length - 1]; } /* * Create the Markov Chain probability distributions based on the input text. * The model is in the form of a hash map that has a string for a key and a * map for a value. The value map has the next state probabilities. */ private void buildModel (String filePath) { // Read in text from file // for each unique word in file, put unique into wordMap as key // put a map of unique following words and an occurrence count as value Map<String, Map<String, Integer>> wordMap = new TreeMap<String, Map<String, Integer>>(); //followingWordTot is a count of the number of times a given word occurs in document Map<String, Integer> followingWordTot = new TreeMap<String, Integer>(); Scanner input = null; try { input = new Scanner(new File(filePath)); String thisString = input.next().replaceAll("[^a-zA-Z0-9_-]", "").toLowerCase(); String nextString = null; while(input.hasNext()){ nextString = input.next().replaceAll("[^a-zA-Z0-9_-]", "").toLowerCase(); //case 1: thisString does not exist in map if (wordMap.get(thisString) == null) { Map<String, Integer> tempMap = new TreeMap<String, Integer>(); tempMap.put(nextString, 1); wordMap.put(thisString, tempMap); followingWordTot.put(thisString, 1); } //case 2: thisString does exist, but nextString //has not yet been associated with thisString else if(wordMap.get(thisString).get(nextString) == null) { wordMap.get(thisString).put(nextString, 1); int followingWordInc = followingWordTot.get(thisString) + 1; followingWordTot.put(thisString, followingWordInc); } //case 3: thisString does exist in map, and nextString //has already been associated with it else if (wordMap.get(thisString).get(nextString) >= 1) { int incVal = wordMap.get(thisString).get(nextString) + 1; wordMap.get(thisString).put(nextString, incVal); int followingWordInc = followingWordTot.get(thisString) + 1; followingWordTot.put(thisString, followingWordInc); } thisString = nextString; } } catch (FileNotFoundException e) { System.out.println("invalid input file path, exiting"); e.printStackTrace(); System.exit(1); } finally { if (input != null) input.close(); } //Iterate over wordMap and calculate the percentage of //times a given word will follow each unique word Iterator it = wordMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry mainPairs = (Map.Entry)it.next(); String mainKey = (String) mainPairs.getKey(); int nextWordCnt = followingWordTot.get(mainKey); Map<String, Integer> subMap = (TreeMap<String, Integer>) mainPairs.getValue(); Iterator it2 = subMap.entrySet().iterator(); Map<String, Double> probabilityVector = new TreeMap<String, Double>(); double probTot = 0.0; while (it2.hasNext()) { Map.Entry subPairs = (Map.Entry)it2.next(); String subKey = (String) subPairs.getKey(); int cnt = (int) subPairs.getValue(); double prob = cnt / (nextWordCnt * 1.0); probTot += prob; probabilityVector.put(subKey, probTot); } probabilityMap.put(mainKey, probabilityVector); } } /* * Generate new content based on the built model */ private String createNewContent (int numTokens) { if (numTokens < 1) { System.out.println("Unigrams.createNewContent requires a positive integer"); return null; } StringBuilder outputText = new StringBuilder(); StringBuilder currentLine = new StringBuilder(); currentLine.append("\n"); //start with random word List<String> keys = new ArrayList<String>(probabilityMap.keySet()); int randomIndex = (int) Math.floor( (keys.size() - 1) * Math.random()); String lastWord = keys.get(randomIndex); //get next word n times for (int i = 0; i < numTokens; i++) { String nextWord = getNextState(lastWord); if (lastWord != null) { //keep the output terminal friendly if (currentLine.length() + nextWord.length() > 78) { outputText.append(currentLine.toString()); outputText.append("\n"); currentLine = new StringBuilder(); } //add the next word and move on to next iteration currentLine.append(nextWord); currentLine.append(" "); lastWord = nextWord; } } outputText.append(currentLine.toString()); outputText.append("\n"); return outputText.toString(); } private static String getUsage () { StringBuilder sb = new StringBuilder(); sb.append("usage: Unigram inFile sizeOfOutput\n"); sb.append("\tinFile: path to the input text file from which to build a markov chain\n"); sb.append("\tsizeOfOutput: number of strings to print to stdout\n"); return sb.toString(); } public static void main (String[] args) { if (args.length != 2) { System.out.print(getUsage()); return; } Unigram uni = new Unigram(args[0]); System.out.print(uni.createNewContent(Integer.parseInt(args[1]))); } }
package imports; public class RadixSortQueue{ GQueue<Integer> bucket0 = new GQueue<Integer>(); //Se hace la creacion de las 9 queues necesitadas como buckets GQueue<Integer> bucket1 = new GQueue<Integer>(); // GQueue<Integer> bucket2 = new GQueue<Integer>(); // GQueue<Integer> bucket3 = new GQueue<Integer>(); // GQueue<Integer> bucket4 = new GQueue<Integer>(); // GQueue<Integer> bucket5 = new GQueue<Integer>(); // GQueue<Integer> bucket6 = new GQueue<Integer>(); // GQueue<Integer> bucket7 = new GQueue<Integer>(); // GQueue<Integer> bucket8 = new GQueue<Integer>(); // GQueue<Integer> bucket9 = new GQueue<Integer>(); // GQueue<Integer> value = new GQueue<Integer>(); //Se crea la queue que guardata los valores que van a ser ordenados GQueue<Integer> finalval = new GQueue<Integer>(); //Se crea una queue que desplegara la queue ordenada int mod = 10; //Valor inicial de modulo int div = 1; //Valor inicial del divisor int digitlen = 0; //Valor inicial del tamano de los digitos int j=0; //Valor inicial del contador public RadixSortQueue(){ this(null); } public RadixSortQueue(GQueue<Integer> x){ this.value=x; } public String sort(){ //Metodo llamada sort() que regresa en string los valores ordenados de la queue return Listpass().toString(); } private GQueue<Integer> Listpass(){ return Listpass(value, mod, div); } private GQueue<Integer> Listpass(GQueue<Integer> valuen, int modn, int divn){ //Metodo listpass que recibe laqueue original, y regresa la queue final val, ccn los valores ordenados GQueue<Integer> trash = new GQueue<Integer>(); //Se crea una queue de basura temporal while(!valuen.isEmpty()){ //Este while esta engargado de recibir los elementos de la queue y guardadlos en uno de los buckets, hasta que se vacie el queue original int element = valuen.dequeue(); //Se guarda el valor de el elemento acutal en un entero llamado element int sort = ((element%modn)/divn); //Sort almacena el numero que se obtiene despues de aplicar la funcion modulo y dvidirlo, para asi decidir en que cubeta sera guardado dicho elemnto int length = String.valueOf(element).length(); //Almacena el numero de digitos del elemento que esta siendo usado en el momento en el entero length if (j==0){ //Solo en la vuelta inicial se corre este if if (digitlen<length){ //se compara el valor de digitlen(que al inicio es 0) y si es que length es mayor que digitlengt, digitlength toma el valor de length digitlen=length; } } if (j==digitlen){ //Si es que el contador es igual al numero e digitos en el mayor integer se corre este if finalval.enqueue(element); //A la queue finalval se le hace enqueue de los elementos ya ordenados } bucketstore(element,sort); //Se corre el metodo bucket store que recibe el elemento, y la llave (llamada sort) } trash=bucketrelease(); //La queue temporal trash toma el valor de bucketrelease (El cual es un metodo que regresa una queue) modn*=10; //modn se multiplica por 10 divn*=10; //divn se multiplica por 10 while(j<digitlen){ //Este while hace recursion siempre y cuando el contador sea menor a digitlen j++; //Se hace un aumento al contador Listpass(trash,modn,divn); //Se hace recursion ahora con la queue almacenada en trash, asi con los nuevos valores de mod y div } return finalval; //Cuando termina el while, se regresa la queue final val } private void bucketstore(int element, int sort){ //Metodo que hace el uso de switch cases que utilizan sort como llave para almacenar el elemento en su determinado queue switch(sort){ case 0 :bucket0.enqueue(element); break; case 1 :bucket1.enqueue(element); break; case 2 :bucket2.enqueue(element); break; case 3 :bucket3.enqueue(element); break; case 4 :bucket4.enqueue(element); break; case 5 :bucket5.enqueue(element); break; case 6 :bucket6.enqueue(element); break; case 7 :bucket7.enqueue(element); break; case 8 :bucket8.enqueue(element); break; case 9 :bucket9.enqueue(element); break; } } private GQueue<Integer> bucketrelease(){ //Metodo que obtiene las cubetas en orden de 0-9 que va vaciando y anadiendo elementos a un nuevo queue llamado valuefin GQueue<Integer> valuefin= new GQueue<Integer>(); if (!bucket0.isEmpty()){ while(bucket0.size()>0){ valuefin.enqueue(bucket0.dequeue()); } } if (!bucket1.isEmpty()){ while(bucket1.size()>0){ valuefin.enqueue(bucket1.dequeue()); } } if (!bucket2.isEmpty()){ while(bucket2.size()>0){ valuefin.enqueue(bucket2.dequeue()); } } if (!bucket3.isEmpty()){ while(bucket3.size()>0){ valuefin.enqueue(bucket3.dequeue()); } } if (!bucket4.isEmpty()){ while(bucket4.size()>0){ valuefin.enqueue(bucket4.dequeue()); } } if (!bucket5.isEmpty()){ while(bucket5.size()>0){ valuefin.enqueue(bucket5.dequeue()); } } if (!bucket6.isEmpty()){ while(bucket6.size()>0){ valuefin.enqueue(bucket6.dequeue()); } } if (!bucket7.isEmpty()){ while(bucket7.size()>0){ valuefin.enqueue(bucket7.dequeue()); } } if (!bucket8.isEmpty()){ while(bucket8.size()>0){ valuefin.enqueue(bucket8.dequeue()); } } if (!bucket9.isEmpty()){ while(bucket9.size()>0){ valuefin.enqueue(bucket9.dequeue()); } } return valuefin; } }
package com.satya.springfeatures.client; /** * Injectable client for the spring Trail Service. * * @author Satya Vulisetti * @version 1.0.0 * @since 1.0.0 */ import java.lang.reflect.AnnotatedElement; import java.util.List; import javax.ws.rs.Path; import javax.ws.rs.client.AsyncInvoker; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import org.glassfish.jersey.client.proxy.WebResourceFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import com.satya.springfeatures.model.Request; import com.satya.springfeatures.model.Response; /** * Public class for the spring client which is part of the spring Trail Service. * * @author Satya Vulisetti * @version 1.0.0 * @since 1.0.0 */ @Component public class SpringClient implements SpringResource { /** The endpoint url. */ @Value("${service.endpoint.url:}") private String endpointUrl; /** The spring resource. */ private SpringResource SpringResource = null; /** * Constructor * */ public SpringClient() { super(); } /** * Constructor * * @param endpointUrl * the endpoint url */ public SpringClient(String endpointUrl) { this.endpointUrl = endpointUrl; } /** * Set the endpoint url. * * @param endpointUrl * the new endpoint */ public void setEndpointUrl(String endpointUrl) { this.endpointUrl = endpointUrl; } /** * Lazy initializes and returns spring resource. * * @return the spring resource */ public synchronized SpringResource getSpringResource() { if (SpringResource == null) { SpringResource = WebResourceFactory.newResource(SpringResource.class, ClientBuilder.newBuilder().build().target(endpointUrl)); } return SpringResource; } /* * (non-Javadoc) * * @see * com.sca.spring.client.SpringResource#savespringInfo(com.sca.spring * .model.spring) */ public void saveRequestInfo(Request request) throws Exception { WebTarget target = addPathFromAnnotation(SpringResource.class, ClientBuilder.newBuilder().build().target(endpointUrl)); final AsyncInvoker asyncInvoker = target.request().async(); asyncInvoker.post(Entity.entity(request, MediaType.APPLICATION_JSON), SpringResource.class); } private static WebTarget addPathFromAnnotation(final AnnotatedElement ae, WebTarget target) { final Path p = ae.getAnnotation(Path.class); if (p != null) { target = target.path(p.value()); } return target; } }
package com.huawei.esdk.demo.action; import java.io.IOException; import java.net.SocketTimeoutException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.Duration; import org.apache.struts2.ServletActionContext; import com.huawei.esdk.demo.autogen.CameraControlEx; import com.huawei.esdk.demo.autogen.FreeBusyStateEx; import com.huawei.esdk.demo.autogen.SiteInfoEx; import com.huawei.esdk.demo.autogen.TPSDKResponseEx; import com.huawei.esdk.demo.common.BaseAction; import com.huawei.esdk.demo.common.Constant; import com.huawei.esdk.demo.service.ConferenceService; import com.huawei.esdk.demo.service.SiteService; public class SiteCtrlAction extends BaseAction { /** * */ private static final long serialVersionUID = 1L; private static final int CAMERA_STATE = 0; private static final int CAMERA_POS = 255; private SiteService siteService = SiteService.getInstance(); private ConferenceService conferenceService = ConferenceService.getInstance(); // 摄像头控制 public void cameraAction() { HttpServletRequest request = ServletActionContext.getRequest(); String siteUri = request.getParameter("siteUri"); String actionCode = request.getParameter("actionCode"); String cameraSrc = request.getParameter("auxSrc"); CameraControlEx cc = new CameraControlEx(); cc.setCamAction(Integer.valueOf(actionCode)); cc.setCamPos(CAMERA_POS); cc.setCamSrc(Integer.valueOf(cameraSrc)); cc.setCamState(CAMERA_STATE); Integer result = siteService.ctrlCameraEx(siteUri, cc); int cationCode = 0; if( 0 == result) { switch (Integer.valueOf(actionCode)) { case 0: cationCode = 8; break; case 1: cationCode = 9; break; case 2: cationCode = 10; break; case 3: cationCode = 11; break; default : cationCode = -1; break; } if(-1 != cationCode) { cc.setCamAction(cationCode); siteService.ctrlCameraEx(siteUri, cc); } } outString(String.valueOf(result)); } public String querySites() throws Exception { List<SiteInfoEx> lSiteInfoExs = null; TPSDKResponseEx<List<SiteInfoEx>> result = conferenceService .querySitesEx(); StringBuffer reJson = new StringBuffer(); // json的格式{root:[{siteuri:'01010086',sitename:'xxxx', // sitetype:'4'},{siteuri:'01010010',sitename:'xxxx', sitetype:'4'}]} reJson.append("{root:["); if (0 == result.getResultCode()) { lSiteInfoExs = result.getResult(); // 获取会场状态 List<String> siteUriList = new ArrayList<String>(); for (SiteInfoEx siteinfo : lSiteInfoExs) { siteUriList.add(siteinfo.getUri()); } Map<String, Integer> siteStatusMap = querySiteStatusEx(siteUriList); //拼装json消息发往页面 boolean isFirst = true; for (SiteInfoEx siteinfo : lSiteInfoExs) { if (null != siteinfo) { if (!isFirst) { reJson.append(","); } isFirst = false; // 会场URI reJson.append("{siteUri:'").append(siteinfo.getUri()); // 会场名称 reJson.append("',siteName:'").append(siteinfo.getName()); // 会场类型 reJson.append("',siteType:'").append(siteinfo.getType()); // 会场状态 Integer sts = siteStatusMap.get(siteinfo.getUri()); if (null == sts) { reJson.append("',siteStatus:'").append(2); } else { reJson.append("',siteStatus:'").append(sts); } reJson.append("'}"); } } } reJson.append("]}"); HttpServletResponse response = ServletActionContext.getResponse(); response.setCharacterEncoding("utf-8"); try { response.getWriter().write(reJson.toString()); } catch (IOException e) { e.printStackTrace(); } return null; } public Map<String, Integer> querySiteStatusEx(List<String> siteUris) { Map<String, Integer> result = new HashMap<String, Integer>(); Duration duration = null; try { duration = DatatypeFactory.newInstance().newDuration("PT300M"); } catch (DatatypeConfigurationException e1) { return result; } // 当前时间30分钟内的会场忙闲 TPSDKResponseEx<Map<String, List<FreeBusyStateEx>>> resultSiteSts = conferenceService.querySiteStatusEx(siteUris, new Date(), duration); Map<String, List<FreeBusyStateEx>> siteStauts = null; if (0 == resultSiteSts.getResultCode()) { siteStauts = resultSiteSts.getResult(); for (String key : siteStauts.keySet()) { List<FreeBusyStateEx> fbse = siteStauts.get(key); if (null != fbse) { result.put(key, fbse.get(0).getState()); } } return result; } else { return result; } } public void isConnectAuxSourceEx() { HttpServletRequest request = ServletActionContext.getRequest(); String siteUri = request.getParameter("siteUri"); try { TPSDKResponseEx<Integer> result = siteService.isConnectAuxSourceEx(siteUri); if (0 == result.getResultCode()) { if (1 == result.getResult()) { outString("true"); } else { outString("false"); } } else { outString(String.valueOf(result.getResultCode())); } } catch (Exception e) { if(e.getCause() instanceof SocketTimeoutException) { outString(String.valueOf(Constant.ERROR_CODE_DEVICE_CONN_ERROR)); } } } public void isSendAuxStreamEx() { HttpServletRequest request = ServletActionContext.getRequest(); String siteUri = request.getParameter("siteUri"); TPSDKResponseEx<Integer> result = siteService.isSendAuxStreamEx(siteUri); if (0 == result.getResultCode()) { if (1 == result.getResult()) { outString("true"); } else { outString("false"); } } else { outString(String.valueOf(result.getResultCode())); } } public void queryMainStreamSourcesEx() { HttpServletRequest request = ServletActionContext.getRequest(); String siteUri = request.getParameter("siteUri"); TPSDKResponseEx<Map<Integer, String>> result = siteService.queryMainStreamSourcesEx(siteUri); StringBuffer reJson = new StringBuffer(); // json的格式{root:[{auxID:'01',auxName:'xxxx'}]} if (0 == result.getResultCode()) { reJson.append("{root:["); Map<Integer, String> mapAux = result.getResult(); boolean isFirst = true; Set<Map.Entry<Integer, String>> items = mapAux.entrySet(); for (Map.Entry<Integer, String> entry : items) { if (null != entry) { if (!isFirst) { reJson.append(","); } isFirst = false; // 输入源ID reJson.append("{auxID:'").append(entry.getKey()); // 输入源名称 reJson.append("',auxName:'").append(entry.getValue()).append("'}"); } } reJson.append("]}"); outString(reJson.toString()); } else { outString(String.valueOf(result.getResultCode())); } } }
public interface Video{ void brighter(); void darker(); }
import java.util.Scanner; public class SalesTax { public static void main(String[] args) { /*Scanner input = new Scanner(System.in); System.out.print("Enter a purchase value : "); double purchaseAmount = input.nextDouble(); double tax = purchaseAmount * 0.06; System.out.println("Sales tax is $" +(int)(tax *100)/100);*/ } }
/** * Copyright 2009 Joe LaPenna */ package com.chuxin.family.utils; import com.chuxin.family.net.CxNetDownloadFile; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Observable; import java.util.Observer; import java.util.concurrent.ConcurrentHashMap; import android.content.Context; import android.net.Uri; public class CxAudioFileResourceManager extends Observable{ private static final String TAG = "RkAudioFileResourceManager"; private static ConcurrentHashMap<String, CxAudioFileResourceManager> mResourceManagers = new ConcurrentHashMap<String, CxAudioFileResourceManager>(); private CxFileBaseDiskCache mDiskCache; private CxAudioFileFetcher mRemoteResourceFetcher; private FetcherObserver mFetcherObserver = new FetcherObserver(); //1 public static CxAudioFileResourceManager getAudioFileResourceManager(Context ctx) { return getResourceManager("audio", ctx); } //2 private static CxAudioFileResourceManager getResourceManager( String category, Context ctx) { if (mResourceManagers.containsKey(category)) { return mResourceManagers.get(category); } else { CxAudioFileResourceManager resourceManager = new CxAudioFileResourceManager(category, ctx); mResourceManagers.put(category, resourceManager); return resourceManager; } } //3 private CxAudioFileResourceManager(String cacheName, Context ctx) { this(new CxFileBaseDiskCache(cacheName, ctx)); } //4 private CxAudioFileResourceManager(CxFileBaseDiskCache cache) { // super(cache, ctx); mDiskCache = cache; mRemoteResourceFetcher = new CxAudioFileFetcher(mDiskCache); mRemoteResourceFetcher.addObserver(mFetcherObserver); } /** * If IOException is thrown, we don't have the resource available. */ public File getFile(Uri uri) { return mDiskCache.getFile(uri.toString()); } /** * If IOException is thrown, we don't have the resource available. */ public InputStream getInputStream(Uri uri) throws IOException { return mDiskCache.getInputStream(uri.toString()); } //检测如果本地没有,才调用此接口 public void request(Uri uri) { CxLog.d("request audio file path ", uri.toString()); mRemoteResourceFetcher.fetch(uri, uri.toString()); } /** * Explicitly expire an individual item. */ public void invalidate(Uri uri) { mDiskCache.invalidate(Uri.encode(uri.toString())); } public boolean exists(Uri uri) { return mDiskCache.exists(uri.toString()); } public void shutdown() { mRemoteResourceFetcher.shutdown(); mDiskCache.cleanup(); } public void clear() { mRemoteResourceFetcher.shutdown(); mDiskCache.clear(); } public static abstract class ResourceRequestObserver implements Observer { private Uri mRequestUri; abstract public void requestReceived(Observable observable, Uri uri, long len); public ResourceRequestObserver(Uri requestUri) { mRequestUri = requestUri; } @Override public void update(Observable observable, Object data) { CxNetDownloadFile dataFile = (CxNetDownloadFile)data; if (dataFile.fileUri.equals(mRequestUri)) { //防止异步出错 requestReceived(observable, dataFile.fileUri, dataFile.len); } } } //监听下载完成 private class FetcherObserver implements Observer { @Override public void update(Observable observable, Object data) { setChanged(); notifyObservers(data); } } }
package com.suhid.practice.model; import lombok.Getter; import lombok.Setter; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Getter @Setter @Table(name = "COURSES") public class AddCourseModel { @Id private String courseId; private String courseName; }
package com.tencent.mm.g.a; import com.tencent.mm.sdk.b.b; public final class il extends b { public a bRT; public il() { this((byte) 0); } private il(byte b) { this.bRT = new a(); this.sFm = false; this.bJX = null; } }
package com.uinsk.mobileppkapps.adapter; import android.graphics.Color; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.uinsk.mobileppkapps.R; import java.util.Arrays; public class ListNilaiAdapter extends RecyclerView.Adapter<ListNilaiAdapter.ViewHolder> { String[] listNilai; public ListNilaiAdapter(String[] listNilai){ this.listNilai = listNilai; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list_nilai, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { //tv Nilai holder.tvNilai.setText(listNilai[position]); } @Override public int getItemCount() { return listNilai.length; } public class ViewHolder extends RecyclerView.ViewHolder { TextView tvNilai; public ViewHolder(@NonNull View itemView) { super(itemView); tvNilai = itemView.findViewById(R.id.tv_nilai); } } }
package com.sharpower.entity; import java.util.Date; public class ReportDayRecode { private Integer id; private Date date; private Fun fun; private Float maxEngergy=null; private Float averageWindSpeed=null; private Float averagePower=null; private Float averageReactivePower=null; private Float maxSpeed=null; private Float maxPower=null; private Float availabilityRatio=null; private Float nacelleOutdoorTemperature=null; private Integer dataTimeEnergy=null; private Integer dataTimeService=null; private Integer dataTimeAllError=null; private Integer dataTimeNormal=null; private Integer dataTimeTotal=null; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public Fun getFun() { return fun; } public void setFun(Fun fun) { this.fun = fun; } public Float getMaxEngergy() { return maxEngergy; } public void setMaxEngergy(Float engergy) { this.maxEngergy = engergy; } public Float getAverageWindSpeed() { return averageWindSpeed; } public void setAverageWindSpeed(Float averageWindSpeed) { this.averageWindSpeed = averageWindSpeed; } public Float getAveragePower() { return averagePower; } public void setAveragePower(Float averagePower) { this.averagePower = averagePower; } public Float getAverageReactivePower() { return averageReactivePower; } public void setAverageReactivePower(Float averageReactivePower) { this.averageReactivePower = averageReactivePower; } public Float getMaxSpeed() { return maxSpeed; } public void setMaxSpeed(Float maxSpeed) { this.maxSpeed = maxSpeed; } public Float getMaxPower() { return maxPower; } public void setMaxPower(Float maxPower) { this.maxPower = maxPower; } public Float getAvailabilityRatio() { return availabilityRatio; } public void setAvailabilityRatio(Float availabilityRatio) { this.availabilityRatio = availabilityRatio; } public Float getNacelleOutdoorTemperature() { return nacelleOutdoorTemperature; } public void setNacelleOutdoorTemperature(Float nacelleOutdoorTemperature) { this.nacelleOutdoorTemperature = nacelleOutdoorTemperature; } public Integer getDataTimeEnergy() { return dataTimeEnergy; } public void setDataTimeEnergy(Integer dataTimeEnergy) { this.dataTimeEnergy = dataTimeEnergy; } public Integer getDataTimeService() { return dataTimeService; } public void setDataTimeService(Integer dataTimeService) { this.dataTimeService = dataTimeService; } public Integer getDataTimeAllError() { return dataTimeAllError; } public void setDataTimeAllError(Integer dataTimeAllError) { this.dataTimeAllError = dataTimeAllError; } public Integer getDataTimeNormal() { return dataTimeNormal; } public void setDataTimeNormal(Integer dataTimeNormal) { this.dataTimeNormal = dataTimeNormal; } public Integer getDataTimeTotal() { return dataTimeTotal; } public void setDataTimeTotal(Integer dataTimeTotal) { this.dataTimeTotal = dataTimeTotal; } }
package com.phone1000.martialstudyself.models; import java.util.ArrayList; import java.util.List; /** * Created by my on 2016/11/29. */ public class WushubaikeModel { public List<String> 全部 = new ArrayList<>(); public List<String> 武术门派 = new ArrayList<>(); public List<String> 经络脉穴 = new ArrayList<>(); public List<String> 武术名家 = new ArrayList<>(); public List<String> 兵器库 = new ArrayList<>(); public List<String> 说文解字 = new ArrayList<>(); public List<String> 武林玄学 = new ArrayList<>(); private List<String> data = new ArrayList<>(); private static WushubaikeModel model = null; private WushubaikeModel() { 经络脉穴.add("全部"); 经络脉穴.add("奇经八脉"); 经络脉穴.add("十二正经"); 经络脉穴.add("经脉知识"); 武术名家.add("全部"); 武术名家.add("少林名家"); 武术名家.add("武当名家"); 武术名家.add("峨眉名家"); 武术名家.add("太极拳名家"); 武术名家.add("八卦掌名家"); 武术名家.add("形意拳名家"); 武术名家.add("心意拳名家"); 武术名家.add("大成拳名家"); 武术名家.add("八极拳名家"); 武术名家.add("长拳名家"); 武术名家.add("南全明家"); 武术名家.add("咏春拳名家"); 武术名家.add("通背拳名家"); 武术名家.add("劈挂拳名家"); 武术名家.add("三皇炮锤名家"); 武术名家.add("戳脚名家"); 武术名家.add("翻子拳名家"); 武术名家.add("査拳名家"); 武术名家.add("地躺拳名家"); 武术名家.add("象形拳名家"); 武术名家.add("气功名家"); 武术名家.add("格斗名家"); 武术名家.add("摔跤名家"); 武术名家.add("刀术名家"); 武术名家.add("枪术名家"); 武术名家.add("剑术名家"); 武术名家.add("棍术名家"); 武术名家.add("斧法名家"); 武术名家.add("鞭法名家"); 武术名家.add("棒法名家"); 武术名家.add("日本剑道名家"); 武术名家.add("日本空手道名家"); 武术名家.add("泰拳名家"); 武术名家.add("韩国跆拳道名家"); 武术名家.add("日本柔道名家"); 武术名家.add("拳击名家"); 武术名家.add("截拳道名家"); 武术名家.add("巴西柔术名家"); 武术名家.add("日本合气道名家"); 武术名家.add("其他武术名家"); 兵器库.add("全部"); 兵器库.add("十八般兵器"); 兵器库.add("长兵器"); 兵器库.add("短兵器"); 兵器库.add("双兵器"); 兵器库.add("软兵器"); 兵器库.add("暗兵器"); 兵器库.add("御射兵器"); 兵器库.add("其他兵器"); 武林玄学.add("全部"); 武林玄学.add("轻功玄学"); 武林玄学.add("硬功玄学"); 武林玄学.add("气功玄学"); 武林玄学.add("特技玄学"); 武林玄学.add("其他玄学"); } public static WushubaikeModel getWushubaike() { if (model == null) { model = new WushubaikeModel(); } return model; } }
package com.uptc.prgIII.group2.game.model; public class Ship { }
package game.model.critter.impl; import game.model.Move; import game.model.Obstacle; import game.model.critter.base.CritterBase; /** * Created by Stephen on 11/28/2014. */ public class Food extends CritterBase { @Override public Move getMove(Obstacle front, Obstacle back, Obstacle left, Obstacle right) { return Move.WAIT; } }
package com.example.bratwurst.service; import com.example.bratwurst.model.Message; import com.example.bratwurst.repo.MessageRepo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.time.Clock; import java.time.LocalDateTime; import java.util.List; @Service public class MessageServiceImpl implements MessageService { @Autowired private MessageRepo messageRepo; @Autowired private SanitizingService sanitizingService; @Autowired private EncryptionService encryptionService; @Override public List<Message> getConversation(int sender, int receiver) { //TODO check if the token belongs to either sender or receiver. If not then block List<Message> messages = messageRepo.getConversation(sender, receiver); for (int i = 0; i < messages.size(); i++) { messages.get(i).setContent(encryptionService.decrypt(messages.get(i).getContent())); } return messages; } @Override public void postMessage(Message msg) { //TODO check if token belongs to either sender or receiver String sanitizedMsg = sanitizingService.sanitizeString(msg.getContent()); msg.setContent(encryptionService.encrypt(sanitizedMsg)); msg.setTimestamp(LocalDateTime.now(Clock.systemUTC()).toString()); messageRepo.postMessage(msg); } }
package extra_Practices; import java.util.Scanner; public class sign { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Please enter your number"); int num= sc.nextInt(); System.out.println(sign(num)); } public static int sign(int x) { if(x<0) { return -1; }else if (x==0){ return 0; }else return 1; } }
package com.yixin.kepler.core.mqmessage;/** * Created by liushuai2 on 2018/6/6. */ /** * Package : com.yixin.kepler.core.mqmessage * * @author YixinCapital -- liushuai2 * 2018年06月06日 14:32 */ public class MqMsgDealResult { }
package com.box.androidsdk.content.models; import com.eclipsesource.json.JsonArray; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; /** * A collection that contains BoxJsonObject items * * @param <E> the type of elements in this partial collection. */ public class BoxArray<E extends BoxJsonObject> implements Collection<E> { protected final Collection<E> collection = new ArrayList<E>(); public BoxArray() { super(); } public String toJson() { JsonArray array = new JsonArray(); for (int i = 0; i < size(); i++) { array.add(get(i).toJsonObject()); } return array.toString(); } @Override public boolean add(E e) { return this.collection.add(e); } @Override public boolean addAll(Collection<? extends E> c) { return this.collection.addAll(c); } @Override public void clear() { this.collection.clear(); } @Override public boolean contains(Object o) { return this.collection.contains(o); } @Override public boolean containsAll(Collection<?> c) { return this.collection.containsAll(c); } @Override public boolean equals(Object o) { return this.collection.equals(o); } @Override public int hashCode() { return this.collection.hashCode(); } @Override public boolean isEmpty() { return this.collection.isEmpty(); } @Override public Iterator<E> iterator() { return this.collection.iterator(); } @Override public boolean remove(Object o) { return this.collection.remove(o); } @Override public boolean removeAll(Collection<?> c) { return this.collection.removeAll(c); } @Override public boolean retainAll(Collection<?> c) { return this.collection.retainAll(c); } @Override public int size() { return this.collection.size(); } @Override public Object[] toArray() { return this.collection.toArray(); } @Override public <T> T[] toArray(T[] a) { return this.collection.toArray(a); } public E get(int index) { if (collection instanceof List) { return (E) ((List) collection).get(index); } if (index < 0) { throw new IndexOutOfBoundsException(); } Iterator<E> iterator = iterator(); int i = 0; while (iterator.hasNext()) { if (index == i) { return iterator.next(); } iterator.next(); } throw new IndexOutOfBoundsException(); } }
package com.rekoe.msg; /** * @author 科技㊣²º¹³ * Feb 16, 2013 2:35:33 PM * http://www.rekoe.com * QQ:5382211 */ public enum MessageExecuteState { INITIALIZED, CANCELED, EXECUTED, EXECUTING_FIRST_STEP, EXECUTING_LAST_STEP, EXECUTING_IO_STEP; }
package com.aki.redis.service; import com.aki.redis.po.UserRedis; import java.util.List; public interface IRedisGsonService { void add(String key, UserRedis user, Long time); void addList(String key, List<UserRedis> users, Long time); UserRedis get(String key); List<UserRedis> getUserList(String key); void delete(String key); }
//Predicate.java // //This library is free software; you can redistribute it and/or //modify it under the terms of the GNU Lesser General Public //License as published by the Free Software Foundation; either //version 2.1 of the License, or (at your option) any later version. // //This library is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU //Lesser General Public License for more details. package rtree.join; import rtree.*; import java.util.List; /** This class works with "sweepline" algo. For the actual binary predicate between MBRs, this interface should help. We will have an implementing class for "intersects","contains","meet". @author Prachuryya Barua */ public abstract class Predicate { protected Pair p = new PairElmt();//this is always PairElmt public Predicate(){} // public Predicate(Pair p) // { // if(p == null) // throw new NullPointerException(" Argument null"); // this.p = p; // } /** * Do the appropriate rtree operation. * @param event the <code>Element</code> at which the event took place. * @param from the index from which <code>others</code> start. * @param others the <code>Element[]</code> to compare with <code>event</code> * @param pairs a <code>List</code> value where the output pairs would put. * @param evtSide tells whether <code>event</code> is from left tree or right tree. * @param p a <code>Pair</code> value which specifies the kind of output required. */ public abstract void relate(Element event, int from, Element[] others, List pairs, int evtSide); /** * This one is specifically for the case where one tree is longer then the other. * It may be noted that both the elements can be leaf as well. * @param nlElmt the non-leaf <code>Element</code> * @param lfElmt the leaf <code>Element</code> * @param side The side of <code>nlElmt</code> element. * @return a <code>boolean</code> value */ public abstract boolean relateMismatch(Element nlElmt, Element lfElmt, int side); /** Returns the <code>Pair</code> which tells the type of output required. */ public Pair getPair() { return p; } }
package net.d4rk.inventorychef.constants; public class Constants { public static final String[] INGREDIENT_SUGGESTIONS = new String[] { // Netto "Paprika", "Karotten", "Knoblauch", "Zwiebeln", "Maiskolben", "Broccoli", "Blumenkohl", "Kürbis", "Maiskolben", "Tomaten", "Kohlrabi", "Gurken", "Radieschen", "Zuckererbsen", "Pilze", "Kartoffel", "Süßkartoffeln", "Rote Beete", "Stangenbohnen", "Salat", "Rucola", "Ingwer", "Avocado", "Zucchini", "Suppengrün", "grüner Spargel", "Apfel", "Trauben", "Erdbeeren", "Himbeeren", "Bananen", "Kirschen", "Wassermelone", "Passionsfrucht", "Zitrone", "Physalis", "Kiwi", "Aprikosen", "Rhabarber", "Mango", "Heidelbeeren", "Nekarinen", "Ananas", "Clementinen", "Pomelo", "Saft", "Smoothie", "Kopierpapier", "Versandtaschen", "Briefumschläge", "Müllbeutel", "Biomüllbeutel", "Kosmetikbeutel", "Taschentücher", "Deo", "Waschmittel", "Weichspüler", "Anti-Kalk", "Spülmaschinenpulver", "Klarspüler", "Spezialsalz", "Badreiniger", "Essigreiniger", "Seife", "Klopapier", "Zewa", "Wischtücher", "Schwammtuch", "Salz", "Pesto", "Suppennudeln", "Buchstabennudeln", "Mehl", "Vollkornmehl", "Haselnüsse", "Mandeln", "gem. Haselnüsse", "gem. Mandeln", "Zucker", "Rohrzucker", "Puderzucker", "Gelierzucker", "Schokoladenpudding", "Vanillepudding", "Vanillinzucker", "Kakao", "Kuchenglasur", "Speisestärke", "Blockschokolade", "Backpulver", "Rum-Aroma", "Linsen", "Milchbrötchen", "Kaba", "Kaffee", "Kaffeepads", "Cappuchino", "haltb. Sahne", "Schokocreme", "Toast", "Honig", "Sanella", "Joghurt", "Fruchtjoghurt", "Skyr", "Saure Sahne", "Creme Fraiche", "Mascarpone", "Quark", "Butter", "ges. Butter", "Käseaufschnitt", "Cheddar", "ger. Käse", "herzh. Käse", "Weichkäse", "Frischkäse", "Mozzarella", "Ofenkäse", "Grillkäse", "Babybel", "Tortelloni", "Schupfnudeln", "Hirtenkäse", "Parmesan", "Gouda", "gef. Pepperoni", "Ketchup", "Mayonaise", "Hefe", "Seelachsschnitzel", "Pizzateig", "Senf", "Salami", "Schinken", "Baconstreifen", "Schinkenwürfel", "Hackfleisch", "Minutensteaks", "Grillfackeln", "Weißwurst", "Kokosmilch", "Ajvar", "Laugenstangen", "Laugenbrezen", "Tiefkühlkräuter", "Pommes Frites", "Fischstäbchen", "Backfisch", "Seelachs", "Apfelmus", "Ananasscheiben", "Pfirsiche", "Mandarinen", "Kidneybohnen", "Baked Beans", // alle Bohnen "...bohnen", "", "Kichererbsen", "Gemüsemais", "passierte Tomaten", "Tomatenwürfel", "Maiskölbchen", "Cornichons", "Eis", "Sonnenblumenöl", "Keimöl", "Essig", "Balsamicoessig", "Balsamicoessig weiß", "Wein", "Milch", "Cornflakes", "Müsli", "Haferflocken fein", "Haferflocken grob", "Dinkelknusper", "Porridge", "Wraps", "Chiasamen", "Walnüsse", "Cashewkerne", "Pistazien", "Cantuccini", "Snyders", "Chips", "Pombär Chips", "Hafercookies", "Vitalgebäck", "Amarettini", "Grissini", "Minichoc", "Karamalz", "Hefeweizen", "Radler", "Gummibären", "Schokolade", "Nippon", "BallaSticks", "Toffifee", "Zwieback", "Knäckebrot", // LIDL "Wok-Gemüse", "Italienische Haselnüsse", "Paranüsse", // dm "Bulgur", "Couscous", "Hirse", "Quinoa", "Polenta", "Lankornreis", "Parboiled Reis", "Risottoreis", "Milchreis", "...reis", // weitere Reissorten "Vollkornmehl", "Dinkelvollkornmehl", "Magnesium", "Calcium", "Honigwaffeln", "Erdnussmus", "Nussmus", // denn's "Gemüsebrühe", "Farfalle", "Spaghetti", "Lasagneplatten" }; public static final String[] LOCATION_SUGGESTIONS = { "Küche", "Küchenschrank", "Kühlschrank", "Kühltruhe", "Gefrierschrank", "Vorratskammer", "Arbeitsfläche", "Keller" }; }
package com.example.structural.proxy; /** * Copyright (C), 2020 * FileName: Beauty * * @author: xieyufeng * @date: 2020/10/27 11:02 * @description: */ public class Beauty implements Girl { @Override public void eat() { System.out.println(Thread.currentThread().getId() + "-今天一起去吃个饭-" + getClass()); this.shopping(); } @Override public void shopping() { System.out.println(Thread.currentThread().getId() + "-吃完饭后出去shopping啊-" + getClass()); } }
package com.mxf.course.dao; import com.mxf.course.config.CommMapper; import com.mxf.course.entity.ClassEntity; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import java.util.List; /** * Created by baimao * Time:2021/5/17 */ @Mapper public interface ClassMapper extends CommMapper<ClassEntity> { @Select("<script>" + "select * from yz_jxgl_class where id != -1 " + "<if test=\"classname !=null and classname != ''\">" + " and classname like concat('%',#{classname},'%')" + "</if>" + "<if test=\"sketch !=null and sketch != ''\">" + " and sketch like concat('%',#{sketch},'%')" + "</if>" + "order by creatdate desc" + "</script>") List<ClassEntity> selectClassByConditions(@Param("classname")String classname, @Param("sketch")String sketch); @Select("select * from yz_jxgl_class where schoolid = #{schoolId}") List<ClassEntity> selectClassBySchoolId(@Param("schoolId")int schoolId); @Select("select * from yz_jxgl_class where gradeid = #{id}") List<ClassEntity> selectClassByGradeId(@Param("id") int id); @Select("select count(0) from yz_jxgl_class where gradeid = #{gradeid}") Integer selectClassCountByGradeId(@Param("gradeid")int gradeid); @Select("select count(0) from yz_jxgl_class where schoolid = #{schoolid}") Integer selectClassCountBySchoolId(@Param("schoolid")int schoolid); }
import java.util.Arrays; import java.util.List; /** * * How to validate image file extension with regular expression * */ public class RegexDemo { public static void main(String[] args) { List<String> validIPList = Arrays.asList("1.1.1.1", "255.255.255.255", "192.168.1.2", "10.10.1.1", "132.253.111.10", "26.10.2.10", "127.0.0.1"); IPAddressValidator ipAddressValidator = new IPAddressValidator(); validIPList.stream().forEach(ip -> System.out.println( ip + " is Valid? = " + ipAddressValidator.validate(ip))); System.out.println("--------------------------------------"); List<String> inValidIPList = Arrays.asList("10.10.10", "222.222.2.999", "10.0.0.a"); inValidIPList.stream().forEach(ip -> System.out.println( ip + " is Valid? = " + ipAddressValidator.validate(ip))); } }
package com.teaman.data.authorization; import com.parse.ParseException; /** * <h1> [Insert class name here] </h1> * <p> * [Insert class description here] * </p> * <p> * [Insert additional information here (links, code snippets, etc.)] * </p> * * @author Aaron Weaver * Team Andronerds * waaronl@okstate.edu * @version 1.0 * @since 2/23/16 */ public interface SignupAdapter { boolean signUp(String email, String firstName, String lastName, String password) throws ParseException; void signUpAsync(SignupCallback callback, String email, String firstName, String lastName, String password); }