text stringlengths 10 2.72M |
|---|
package com.zihui.cwoa.system.service;
import com.zihui.cwoa.system.dao.sys_projectMapper;
import com.zihui.cwoa.system.pojo.sys_project;
import org.apache.ibatis.annotations.Param;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@CacheConfig(cacheNames = {"sys_projectServiceCache"})
@Service
public class sys_projectService {
@Resource
private sys_projectMapper projectMapper;
@CacheEvict(key="'projectListToSelect'")
public int deleteByPrimaryKey(Integer projectId){
return projectMapper.deleteByPrimaryKey(projectId);
};
@CacheEvict(key="'projectListToSelect'")
public int insertSelective(sys_project record){
return projectMapper.insertSelective(record);
};
public sys_project selectByPrimaryKey(Integer projectId){
return projectMapper.selectByPrimaryKey(projectId);
};
@CacheEvict(key="'projectListToSelect'")
public int updateByPrimaryKeySelective(sys_project record){
return projectMapper.updateByPrimaryKeySelective(record);
};
/**
* 查询根据条件查询所有项目
* @param record
* @return sys_project 返回所有对象
*/
public List<sys_project> selectProList(sys_project record,Integer page, Integer limit){
if(page==1){
page =0;
}else{
page = (page-1)*limit;
}
return projectMapper.selectProList(record,page,limit);
};
//分页查询总数
public Integer selectProListCount(@Param("sys_project") sys_project record){
return projectMapper.selectProListCount(record);
};
//用户展示项目下拉
@Cacheable(key="'projectListToSelect'")
public List<sys_project> projectListToSelect(){
return projectMapper.projectListToSelect();
}
}
|
package com.tencent.mm.plugin.aa.ui;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.vending.c.a;
import com.tencent.mm.vending.j.d;
import java.util.List;
class AAQueryListUI$6 implements a<Object, d<List, String, Boolean>> {
final /* synthetic */ AAQueryListUI eCd;
final /* synthetic */ boolean eCf;
AAQueryListUI$6(AAQueryListUI aAQueryListUI, boolean z) {
this.eCd = aAQueryListUI;
this.eCf = z;
}
public final /* synthetic */ Object call(Object obj) {
d dVar = (d) obj;
List list = (List) dVar.get(0);
x.i("MicroMsg.AAQueryListUI", "record list size: %s, h5Url: %s, lastFlag: %s", new Object[]{Integer.valueOf(list.size()), dVar.get(1), dVar.get(2)});
if (!bi.oW((String) dVar.get(1))) {
AAQueryListUI.a(this.eCd, (String) dVar.get(1));
}
if (this.eCf) {
AAQueryListUI.f(this.eCd).Wf();
}
b f = AAQueryListUI.f(this.eCd);
x.i("MicroMsg.AAQueryListAdapter", "addNewRecord: %s", new Object[]{list});
if (list != null && list.size() > 0) {
x.i("MicroMsg.AAQueryListAdapter", "addNewRecord size: %s", new Object[]{Integer.valueOf(list.size())});
f.dataList.addAll(list);
f.notifyDataSetChanged();
}
if (AAQueryListUI.g(this.eCd) != null) {
AAQueryListUI.g(this.eCd).dismiss();
AAQueryListUI.h(this.eCd);
}
if (AAQueryListUI.a(this.eCd).getVisibility() != 0) {
AAQueryListUI.a(this.eCd).setVisibility(0);
}
AAQueryListUI.i(this.eCd);
if (!((Boolean) dVar.get(2)).booleanValue()) {
AAQueryListUI.j(this.eCd);
}
if (AAQueryListUI.a(this.eCd).getFooterViewsCount() > 0) {
AAQueryListUI.a(this.eCd).removeFooterView(AAQueryListUI.d(this.eCd));
}
if (AAQueryListUI.b(this.eCd)) {
AAQueryListUI.k(this.eCd);
if (AAQueryListUI.l(this.eCd).getVisibility() == 0) {
AAQueryListUI.a(this.eCd).addFooterView(AAQueryListUI.l(this.eCd), null, false);
}
}
return uQG;
}
}
|
//Omar Mustafa Dalal 1180171
import java.io.File;
import java.util.ArrayList;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.ScrollPane.ScrollBarPolicy;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.FileChooser;
import javafx.stage.FileChooser.ExtensionFilter;
import javafx.stage.Screen;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(String[] args) {
launch();
}
//Variables for interface elements and other data
private final String BOX_STYLE = "-fx-background-color:#fff;-fx-background-radius:10px;-fx-effect: dropshadow(three-pass-box, rgba(0,0,0,0.16), 25px, 0, 0, 0);";
private UCS ucs;
private AStar astar;
private Map map;
private City[] citiesArr;
private double windowHeight = 900;
private double windowWidth = 1300;
private Stage window;
//Start method to run the program
@Override
public void start(Stage pS) throws Exception {
Pane bgPane = new Pane();
HBox root = new HBox(25);
adjustHeight(bgPane);
bgPane.getChildren().addAll(root);
Scene scene = new Scene(bgPane, windowWidth, windowHeight);
map = new Map(srcCB, destCB, scene);
VBox right = getRightSide();
root.getChildren().addAll(map, right);
window = pS;
pS.setScene(scene);
pS.setResizable(false);
pS.setTitle("Maps");
pS.show();
}
private ComboBox<String> srcCB = new ComboBox<>();
private ComboBox<String> destCB = new ComboBox<>();
private int[] complexity;
private Button runBtn;
private Button clearBtn;
private Button drawAllBtn;
private FlowPane routePane;
//Setting up the interface
public VBox getRightSide() {
VBox root = new VBox(15);
root.setAlignment(Pos.CENTER);
root.setStyle("-fx-font-size: 20px;");
Label bigTitleLbl = new Label("Palestine Map");
bigTitleLbl.setPadding(new Insets(0,0,15,0));
bigTitleLbl.setStyle("-fx-font-weight:bold;-fx-font-size:35px");
HBox topBox = new HBox(15);
VBox fileBox = getFileBox();
HBox columnsBox = new HBox(15);
VBox columnOne = new VBox(20);
columnOne.setPadding(new Insets(0, 0, 0, 15));
columnOne.setAlignment(Pos.TOP_CENTER);
VBox selectBox = getSelectPathBox();
VBox routeBox = getRouteBox();
routePane = new FlowPane();
routePane.setVgap(15);
ScrollPane routeScrollPane = getRouteScroll();
routeScrollPane.setContent(routePane);
routeBox.getChildren().addAll(routeScrollPane);
VBox btnsBox = getBtnsBox();
VBox complexityBox = getComplexityBox();
columnOne.getChildren().addAll(selectBox, complexityBox);
VBox columnTwo = new VBox(20);
columnTwo.setAlignment(Pos.TOP_CENTER);
columnTwo.getChildren().addAll(routeBox);
topBox.getChildren().addAll(fileBox, btnsBox);
topBox.setAlignment(Pos.CENTER);
columnsBox.getChildren().addAll(columnOne, columnTwo);
root.getChildren().addAll(bigTitleLbl, topBox, columnsBox);
return root;
}
//Setting up the select file box
private File citiesFile;
private File roadsFile;
private VBox getFileBox() {
VBox root = new VBox(15);
root.setPadding(new Insets(15));
root.setAlignment(Pos.CENTER);
root.setStyle(BOX_STYLE);
root.setPrefWidth(610);
Label titleLbl = new Label("Select Files");
titleLbl.setStyle("-fx-font-size: 25px;-fx-font-weight:bold;");
HBox citiesRow = new HBox(10);
citiesRow.setAlignment(Pos.CENTER);
Label citiesLbl = new Label("Towns File");
TextField citiesField = new TextField();
citiesField.setPrefWidth(350);
citiesField.setDisable(true);
citiesField.setPromptText("Towns File Location");
Button cityBtn = new Button("Browse");
cityBtn.setOnAction(e->{
FileChooser chooser = new FileChooser();
chooser.getExtensionFilters().add(new ExtensionFilter("Text File", "*.csv"));
citiesFile = chooser.showOpenDialog(window);
if (citiesFile!=null) {
citiesField.setText(citiesFile.getAbsolutePath());
} else {
citiesField.setText("");
}
});
citiesRow.getChildren().addAll(citiesLbl, citiesField, cityBtn);
HBox roadsRow = new HBox(10);
roadsRow.setAlignment(Pos.CENTER);
Label roadsLbl = new Label("Roads File");
TextField roadsField = new TextField();
roadsField.setPrefWidth(350);
roadsField.setDisable(true);
roadsField.setPromptText("Roads File Location");
Button roadsBtn = new Button("Browse");
roadsBtn.setOnAction(e->{
FileChooser chooser = new FileChooser();
chooser.getExtensionFilters().add(new ExtensionFilter("Text File", "*.csv"));
roadsFile = chooser.showOpenDialog(window);
if (roadsFile!=null) {
roadsField.setText(roadsFile.getAbsolutePath());
} else {
roadsField.setText("");
}
});
roadsRow.getChildren().addAll(roadsLbl, roadsField, roadsBtn);
Button readyBtn = new Button("Ready");
readyBtn.setOnAction(e-> {
try {
citiesArr = ReadMethods.readFiles(citiesFile, roadsFile);
ucs = new UCS(citiesArr);
astar = new AStar(citiesArr);
map.drawCities(citiesArr);
for (int i=0; i<citiesArr.length; i++) {
destCB.getItems().add(citiesArr[i].getName());
srcCB.getItems().add(citiesArr[i].getName());
}
runBtn.setDisable(false);
clearBtn.setDisable(false);
drawAllBtn.setDisable(false);
readyBtn.setDisable(true);
cityBtn.setDisable(true);
roadsBtn.setDisable(true);
} catch (NullPointerException ex) {
alert("Enter both files first!");
roadsField.setText("");
citiesField.setText("");
citiesFile = null;
roadsFile = null;
} catch (Exception ex) {
alert("Enter valid files!");
roadsField.setText("");
citiesField.setText("");
citiesFile = null;
roadsFile = null;
}
});
root.getChildren().addAll(titleLbl, citiesRow, roadsRow, readyBtn);
return root;
}
private Label timeLbl;
private Label spaceLbl;
//Setting up the box containing time and space complexity
private VBox getComplexityBox() {
VBox root = new VBox (5);
root.setPadding(new Insets(15));
root.setStyle(BOX_STYLE);
root.setPrefSize(450, 100);
root.setMaxWidth(450);
VBox titleBox = new VBox();
titleBox.setAlignment(Pos.CENTER);
Label titleLbl = new Label("Complexity");
titleLbl.setStyle("-fx-font-size: 25px;-fx-font-weight:bold;");
titleBox.getChildren().add(titleLbl);
timeLbl = new Label("Time: ");
spaceLbl = new Label("Space: ");
root.getChildren().addAll(titleBox, timeLbl, spaceLbl);
return root;
}
//Styling the select path box
private VBox getSelectPathBox() {
VBox selectBox = new VBox(15);
selectBox.setAlignment(Pos.CENTER);
selectBox.setPadding(new Insets(15));
selectBox.setStyle(BOX_STYLE);
selectBox.setPrefWidth(450);
Label titleLbl = new Label("Find Route");
titleLbl.setStyle("-fx-font-size:30px; -fx-font-weight: bold;");
titleLbl.setAlignment(Pos.CENTER);
HBox srcBox = new HBox(15);
srcBox.setAlignment(Pos.CENTER);
Label srcLbl = new Label("Source City");
srcLbl.setPrefWidth(150);
srcCB.setValue("Select Source");
srcCB.setPrefWidth(250);
srcCB.setOnAction(e-> {
map.select(srcCB.getValue(), citiesArr, true);
});
srcBox.getChildren().addAll(srcLbl, srcCB);
HBox destBox = new HBox(15);
destBox.setAlignment(Pos.CENTER);
Label destLbl = new Label("Destination City");
destLbl.setPrefWidth(150);
destCB.setValue("Select Destination");
destCB.setPrefWidth(250);
destBox.getChildren().addAll(destLbl, destCB);
destCB.setOnAction(e-> {
map.select(destCB.getValue(), citiesArr, false);
});
HBox algorithmBox = new HBox(15);
algorithmBox.setAlignment(Pos.CENTER);
Label algorithmLbl = new Label("Algorithm");
algorithmLbl.setPadding(new Insets(0,30,0,0));
RadioButton ucsRB = new RadioButton("Uniform Cost Search");
ucsRB.setSelected(true);
ucsRB.setStyle("-fx-font-size:16px");
RadioButton aStarRB = new RadioButton("A Star");
aStarRB.setStyle("-fx-font-size:16px");
ToggleGroup algTG = new ToggleGroup();
ucsRB.setToggleGroup(algTG);
aStarRB.setToggleGroup(algTG);
algorithmBox.getChildren().addAll(algorithmLbl, ucsRB, aStarRB);
runBtn = new Button("Find Route");
runBtn.setDisable(true);
runBtn.setAlignment(Pos.CENTER);
runBtn.setOnAction(e->{
runClicked(ucsRB.isSelected());
});
selectBox.getChildren().addAll(titleLbl, srcBox, destBox, algorithmBox, runBtn);
return selectBox;
}
//Method called when find path is clicked
private void runClicked(boolean ucsSelected) {
try {
complexity = new int[2];
if (ucsSelected) {
map.clearAll(citiesArr, false);
int srcIndex = ucs.findCity(srcCB.getValue());
int destIndex = ucs.findCity(destCB.getValue());
ArrayList<City> route = new ArrayList<>();
float dist = ucs.findPath(srcIndex, destIndex, route, complexity);
distLbl.setText("Distance: "+String.format("%.2f", dist)+" Km");
demonstrateRoute(routePane, route);
timeLbl.setText("Time: "+complexity[0]+" (Rounds)");
spaceLbl.setText("Space: "+complexity[1]+" (Maximun Node Count in PQ)");
map.drawRoute(route);
} else {
map.clearAll(citiesArr, false);
int srcIndex = astar.findCity(srcCB.getValue());
int destIndex = astar.findCity(destCB.getValue());
ArrayList<City> route = new ArrayList<>();
float dist = astar.findPath(srcIndex, destIndex, route, complexity);
distLbl.setText("Distance: "+String.format("%.2f", dist)+" Km");
demonstrateRoute(routePane, route);
timeLbl.setText("Time: "+complexity[0]+" (Rounds)");
spaceLbl.setText("Space: "+complexity[1]+" (Maximun Node Count in PQ)");
map.drawRoute(route);
}
} catch (NullPointerException ex) {
alert("No routes connect "+srcCB.getValue()+" and "+destCB.getValue());
map.clearAll(citiesArr, true);
} catch (IndexOutOfBoundsException ex) {
alert("Select source and destination cities first!");
map.clearAll(citiesArr, true);
}
}
//Styling the scroll pane used to display the path
private ScrollPane getRouteScroll() {
ScrollPane routeScrollPane = new ScrollPane();
routeScrollPane.setHbarPolicy(ScrollBarPolicy.NEVER);
routeScrollPane.setVbarPolicy(ScrollBarPolicy.NEVER);
routeScrollPane.setStyle("-fx-background:#fff;-fx-background-color:#fff;-fx-border:none;");
return routeScrollPane;
}
//Styling the map box containing show all roads and clear buttons
private VBox getBtnsBox() {
VBox btnsBox = new VBox(15);
btnsBox.setAlignment(Pos.CENTER);
btnsBox.setStyle(BOX_STYLE);
btnsBox.setPrefSize(285, 125);
btnsBox.setAlignment(Pos.CENTER);
Label mapTitleLbl = new Label("Map");
mapTitleLbl.setAlignment(Pos.CENTER);
mapTitleLbl.setStyle("-fx-font-size:30px; -fx-font-weight: bold;");
clearBtn = new Button("Clear Map");
VBox.setMargin(clearBtn, new Insets(5,0,0,0));
clearBtn.setDisable(true);
clearBtn.setOnAction(e->{
map.clearAll(citiesArr, true);
routePane.getChildren().clear();
distLbl.setText("Distance: ");
timeLbl.setText("Time: ");
spaceLbl.setText("Space: ");
});
drawAllBtn = new Button("Show All Roads");
drawAllBtn.setDisable(true);
drawAllBtn.setOnAction(e->{
map.clearAll(citiesArr, false);
map.drawAllRoutes(citiesArr);
});
btnsBox.getChildren().addAll(mapTitleLbl, clearBtn, drawAllBtn);
return btnsBox;
}
//Route box which will be the content of the scroll pane to display path
private Label distLbl;
private VBox getRouteBox() {
VBox root = new VBox (5);
root.setAlignment(Pos.TOP_CENTER);
root.setPadding(new Insets(15));
root.setStyle(BOX_STYLE+"-fx-font-weight:bold;");
root.setMinHeight(452.5);
root.setMaxHeight(800);
root.setPrefWidth(450);
Label titleLbl = new Label("Route");
titleLbl.setStyle("-fx-font-size: 25px");
titleLbl.setAlignment(Pos.TOP_LEFT);
distLbl = new Label("Distance: ");
root.getChildren().addAll(titleLbl, distLbl);
return root;
}
//Method to display alert in case of errors
private void alert(String msg) {
Alert alert = new Alert(AlertType.ERROR, msg, ButtonType.OK);
alert.show();
}
//Method to adjust the height of the window for low resolution screens
private void adjustHeight(Pane bgPane) {
double screenHeight = Screen.getPrimary().getBounds().getHeight();
if (screenHeight<=900) {
windowHeight = 675;
windowWidth = 1000;
bgPane.setScaleX(0.75);
bgPane.setScaleY(0.75);
bgPane.setLayoutX(-(windowWidth-(windowWidth*0.75))/2);
bgPane.setLayoutY(-(windowHeight-(windowHeight*0.75))/2);
bgPane.setStyle("-fx-background-color:#fff");
}
}
//Add cities to the path and display them on screen
private void demonstrateRoute(FlowPane pane, ArrayList<City> route) {
pane.getChildren().clear();
for (int i=route.size()-1; i>=0; i--) {
StackPane rectPane = new StackPane();
Label lbl = new Label(route.get(i).getName());
lbl.setStyle("-fx-font-size:15px; -fx-font-weight:bold");
lbl.setTextFill(Color.WHITE);
Rectangle rect = new Rectangle(lbl.getText().length()*10, 40);
rect.setFill(Color.web("55bbaa"));
rect.setArcHeight(10);
rect.setArcWidth(10);
rectPane.getChildren().addAll(rect, lbl);
pane.getChildren().add(rectPane);
if (i!=0) {
Rectangle arrow = new Rectangle(20,3);
arrow.setFill(Color.web("55bbaa"));
pane.getChildren().add(arrow);
}
}
}
}
|
package com.semantyca.nb.core.env;
import com.semantyca.nb.localization.constants.LanguageCode;
import java.util.Arrays;
public class EnvConst {
public static final String SERVER_VERSION = "4.0.0";
public static final String SERVER_NAME = "nb4";
public static final String FRAMEWORK_LOGO = "nextbase_logo_small.png";
public static final String MAIN_PACKAGE = "com.semantyca";
public static final String[] DEFAULT_LANGS = {"ENG", "RUS", "KAZ"};
public static final String FSID_FIELD_NAME = "fsid";
public static final String TMP_DIR = System.getProperty("java.io.tmpdir");
public static int DEFAULT_PAGE_SIZE = 25;
public static String DEFAULT_DATE_FORMAT = "dd.MM.yyyy";
public static String DEFAULT_DATETIME_FORMAT = "dd.MM.yyyy kk:mm";
public static String DEFAULT_TIME_FORMAT = "kk:mm";
public static String APP_ID;
public static String DEFAULT_LANG = DEFAULT_LANGS[0];
public static String DEFAULT_TRANSLATOR_ENGINE = "yandex";
public static String DEFAULT_MAP_SERVICE_ENGINE = "google";
public static String DEFAULT_WEATHER_SERVICE_ENGINE = "openweather.org";
public static LanguageCode getDefaultLang() {
return LanguageCode.valueOf(EnvConst.DEFAULT_LANG);
}
public static final LanguageCode[] getDefaultLangs(){
return Arrays.stream(DEFAULT_LANGS).map((v)-> LanguageCode.valueOf(v)).toArray(LanguageCode[]::new);
}
} |
package com.infosys.bookingms.repository;
public interface BookingRepository {
}
|
package com.poly.duc.DucQuanLyQuanAO.controller;
import com.poly.duc.DucQuanLyQuanAO.model.Product;
import com.poly.duc.DucQuanLyQuanAO.sevice.ProductSevice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
@Controller
public class ProductWebController {
@Autowired
ProductSevice productSevice;
@RequestMapping({"/home"})
public String home(Model model){
List<Product> productList = productSevice.findAllProduct();
model.addAttribute("products",productList);
return "/home/products";
}
@RequestMapping({"/test"})
public String test(){
// List<Product> productList = productSevice.findAllProduct();
// model.addAttribute("products",productList);
return "/home/index";
}
}
|
package com.kobotan.android.Vshkole.database;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.kobotan.android.Vshkole.entities.Content;
import com.kobotan.android.Vshkole.entities.Entity;
import com.kobotan.android.Vshkole.entities.Image;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import java.util.ArrayList;
import java.util.List;
/**
* Created by sancho on 15.04.15.
*/
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
// name of the database file for your application -- change to something appropriate for your app
private static final String DATABASE_NAME = "VitaDB.sqlite";
// any time you make changes to your database objects, you may have to increase the database version
private static final int DATABASE_VERSION = 1;
// the DAO object we use to access the SimpleData table
private Dao<Entity, Integer> entityDao = null;
private Dao<Content, Integer> contentDao = null;
private Dao<Image, String> imageDao = null;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
try {
TableUtils.createTable(connectionSource, Entity.class);
TableUtils.createTable(connectionSource, Content.class);
TableUtils.createTable(connectionSource, Image.class);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), "Can't create database", e);
throw new RuntimeException(e);
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {
try {
List<String> allSql = new ArrayList<String>();
switch (oldVersion) {
case 1:
//allSql.add("alter table AdData add column `new_col` VARCHAR");
//allSql.add("alter table AdData add column `new_col2` VARCHAR");
}
for (String sql : allSql) {
db.execSQL(sql);
}
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), "exception during onUpgrade", e);
throw new RuntimeException(e);
}
}
public Dao<Entity, Integer> getEntityDao() {
if (null == entityDao) {
try {
entityDao = getDao(Entity.class);
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
}
return entityDao;
}
public Dao<Content, Integer> getContentDao() {
if (null == contentDao) {
try {
contentDao = getDao(Content.class);
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
}
return contentDao;
}
public Dao<Image, String> getImageDao() {
if (null == imageDao) {
try {
imageDao = getDao(Image.class);
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
}
return imageDao;
}
}
|
package com.tyss.cg.loanproject.services;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import com.tyss.cg.loanproject.beans.AdminInfoBean;
import com.tyss.cg.loanproject.beans.CustomerInfoBean;
public class ServicesImpl implements ServicesDeclaration {
Scanner scanner = new Scanner(System.in);
List<AdminInfoBean> adminlist = new ArrayList<AdminInfoBean>();
List<CustomerInfoBean> customerlist = new ArrayList<CustomerInfoBean>();
CustomerInfoBean customerInfoBean;
// AdminInfoBean adminInfoBean = new AdminInfoBean();
AdminInfoBean adminInfoBean;
@Override
public void addAdmin() {
// AdminInfoBean adminInfoBean;
System.out.println("Enter the number of entries: ");
int entry = scanner.nextInt();
scanner.nextLine();
for (int i = 0; i < entry; i++) {
System.out.println("Enter the details of Admin " + (i + 1));
System.out.println("Enter the AdminId: ");
int adminid = Integer.parseInt(scanner.nextLine());
// adminInfoBean.setAdminid(adminid);
System.out.println("Enter the Email: ");
String email = scanner.nextLine();
// adminInfoBean.setEmail(email);
System.out.println("Enter the Password: ");
String password = scanner.nextLine();
// adminInfoBean.setPassword(password);
System.out.println("Enter the Username: ");
String username = scanner.nextLine();
// adminInfoBean.setUsername(username);
System.out.println("Enter 10 digit Phone number: ");
int phonenumber = Integer.parseInt(scanner.nextLine());
// adminInfoBean.setPhonenumber(phonenumber);
System.out.println("Enter the First Name: ");
String firstname = scanner.nextLine();
// adminInfoBean.setFirstname(firstname);
System.out.println("Enter the Last Name: ");
String lastname = scanner.nextLine();
// adminInfoBean.setLastname(lastname);
adminInfoBean = new AdminInfoBean(adminid, email, password, username, firstname, lastname, phonenumber);
adminlist.add(adminInfoBean);
// adminlist.add(adminInfoBean);
// for (AdminInfoBean adminInfoBean2 : adminlist) {
// System.out.println(adminlist);
// }
}
}
@Override
public void displayAdmin() {
if (adminlist.isEmpty() != true) {
// for (AdminInfoBean adminInfoBean : adminlist) {
// System.out.println(adminInfoBean);
// }
for (int i = 0; i < adminlist.size(); i++) {
System.out.println(adminlist.get(i));
}
} else
System.out.println("no data found");
}
@Override
public void deleteAdmin() {
int count = 0;
System.out.println("Enter userid: ");
int adminid = scanner.nextInt();
scanner.nextLine();
if (adminlist.isEmpty() != true) {
for (AdminInfoBean adminInfoBean : adminlist) {
if (adminInfoBean.getAdminid() == adminid) {
System.out.println(adminInfoBean.getAdminid());
adminlist.remove(adminInfoBean);
count++;
break;
}
}
// for (int i = 0; i < adminlist.size(); i++) {
// adminlist.get(i);
// if(adminInfoBean.getAdminid()==adminid) {
// System.out.println(adminInfoBean.getAdminid());
// adminlist.remove(adminInfoBean);
// break;
// }
//
if (count > 0)
System.out.println("Admin removed");
else
System.out.println("Admin not found");
} else {
System.out.println("Empty list");
}
}
@Override
public void updateAdmin() {
System.out.println("enter the adminid of admin you want to updat: ");
int id = scanner.nextInt();
if (adminlist.isEmpty() != true) {
for (AdminInfoBean adminInfoBean : adminlist) {
if (adminInfoBean.getAdminid() == id) {
System.out.println("what do you want to update for this admin?");
System.out.println("1> AdminId");
System.out.println("2> Email");
System.out.println("3> Password");
System.out.println("4> Username");
System.out.println("5> PhoneNumber");
System.out.println("6> First Name");
System.out.println("7> Last Name");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println("enter the new id");
int adminid = scanner.nextInt();
adminInfoBean.setAdminid(adminid);
break;
case 2:
System.out.println("Enter the Email: ");
String email = scanner.nextLine();
adminInfoBean.setEmail(email);
break;
case 3:
System.out.println("Enter the Password: ");
String password = scanner.nextLine();
adminInfoBean.setPassword(password);
break;
case 4:
System.out.println("Enter the Username: ");
String username = scanner.nextLine();
adminInfoBean.setUsername(username);
break;
case 5:
System.out.println("Enter 10 digit Phone number: ");
int phonenumber = Integer.parseInt(scanner.nextLine());
adminInfoBean.setPhonenumber(phonenumber);
break;
case 6:
System.out.println("Enter the First Name: ");
String firstname = scanner.nextLine();
adminInfoBean.setFirstname(firstname);
break;
case 7:
System.out.println("Enter the Last Name: ");
String lastname = scanner.nextLine();
adminInfoBean.setLastname(lastname);
break;
default:
System.out.println("wrong choice");
break;
}
}
}
}
}
@Override
public void displayCustomer() {
if (customerlist.isEmpty() == false) {
for (int i = 0; i < customerlist.size(); i++) {
System.out.println(customerlist.get(i));
}
} else
System.out.println("no data found");
}
@Override
public void addCustomer() {
System.out.println("Please mention number of entries: ");
int entry = scanner.nextInt();
scanner.nextLine();
for (int i = 0; i < entry; i++) {
customerInfoBean = new CustomerInfoBean();
System.out.println("Enter the details of customer: " + (i + 1));
System.out.println("Enter the CustomerId: ");
int customerid = Integer.parseInt(scanner.nextLine());
customerInfoBean.setCustomerid(customerid);
System.out.println("Enter the Email: ");
String email = scanner.nextLine();
customerInfoBean.setEmail(email);
System.out.println("Enter the Password: ");
String password = scanner.nextLine();
customerInfoBean.setPassword(password);
System.out.println("Enter the Username: ");
String username = scanner.nextLine();
customerInfoBean.setUsername(username);
System.out.println("Enter the First Name: ");
String firstname = scanner.nextLine();
customerInfoBean.setFirstname(firstname);
System.out.println("Enter the Last Name: ");
String lastname = scanner.nextLine();
customerInfoBean.setLastname(lastname);
System.out.println("Enter the Open Date of birth: ");
String dateofbirth = scanner.nextLine();
customerInfoBean.setDateofbirth(dateofbirth);
System.out.println("Enter 10 digit Phone number: ");
int phone = Integer.parseInt(scanner.nextLine());
customerInfoBean.setPhonenumber(phone);
System.out.println("Enter the Bank Branch: ");
String bankbranch = scanner.nextLine();
customerInfoBean.setBankbranch(bankbranch);
System.out.println("Enter the Account number: ");
String accountnum = scanner.nextLine();
customerInfoBean.setAccountnum(accountnum);
System.out.println("Enter the Open Date: ");
String opendate = scanner.nextLine();
customerInfoBean.setOpendate(opendate);
customerlist.add(customerInfoBean);
}
}
@Override
public void deleteCustomer() {
System.out.println("enter the CustomerId: ");
int id = scanner.nextInt();
scanner.nextLine();
int count = 0;
if (customerlist.isEmpty() != true) {
for (CustomerInfoBean customerInfoBean : customerlist) {
if (customerInfoBean.getCustomerid() == id) {
System.out.println(customerInfoBean.getCustomerid());
customerlist.remove(customerInfoBean);
count++;
break;
}
}
if (count > 0) {
System.out.println("Customer removed");
} else
System.out.println("Customer not found");
} else
System.out.println("empty db");
}
@Override
public void updateCustomer() {
// TODO Auto-generated method stub
}
@Override
public void loginOperations() {
// TODO Auto-generated method stub
}
} |
package com.tfjybj.integral.provider.controller;
import com.dmsdbj.itoo.sso.utils.UserUtil;
import com.tfjybj.integral.model.UserHomeModel;
import com.dmsdbj.cloud.tool.business.IntegralResult;
import com.tfjybj.integral.model.UserHomeModel;
import com.tfjybj.integral.provider.service.HomeLoadingService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
@Api(tags = {"首页加载接口"})
@RequestMapping(value = "/homeloading")
@RestController
@Slf4j
public class HomeLoadingController{
@Resource
private HomeLoadingService homeLoadingService;
@ApiOperation(value = "根据用户id查询用户总积分、月积分、日积分以及绑定的插件")
@GetMapping(value = {"/queryPageContentByUserId"})
public IntegralResult<UserHomeModel> queryPageContentByUserId( ){
//获取token信息中的userId;
String userId = UserUtil.getCurrentUser().getUserId();
UserHomeModel userHomeModel= homeLoadingService.queryPageContentByUserId(userId);
return IntegralResult.build("0000","查询成功",userHomeModel);
}
@ApiOperation(value = "根据接受者id和消息状态查询条数")
@GetMapping(value = {"/queryUnreadMessage"})
public IntegralResult queryUnreadMessage( ){
//获取token信息中的userId;
String userId = UserUtil.getCurrentUser().getUserId();
Integer unreadMessageCount= homeLoadingService.queryUnreadMessage(userId);
return IntegralResult.build("0000","查询成功",unreadMessageCount);
}
@ApiOperation(value = "根据接受者id和消息状态查询红包条数")
@GetMapping(value = {"/queryUnreadRedMessage"})
public IntegralResult queryUnreadRedMessage( ){
//获取token信息中的userId;
String userId = UserUtil.getCurrentUser().getUserId();
Integer unreadMessageCount= homeLoadingService.queryUnreadRedMessage(userId);
return IntegralResult.build("0000","查询成功",unreadMessageCount);
}
}
|
package com.clienteapp.demo.service;
import com.clienteapp.demo.entity.Cliente;
import java.util.List;
public interface IClienteService {
public List<Cliente> listarClientes();
public void guardarCliente(Cliente cliente);
public Cliente buscarPorId(Long id);
public void eliminarCliente(Long id);
}
|
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Stroke;
import java.awt.BasicStroke;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class DrawPanel extends JPanel
{
private ArrayList<MyShape> shapes;
private int shapeCount;
private int shapeType;
private MyShape currentShape;
private Paint currentColor;
private boolean filledShape;
private JLabel statusLabel;
private Stroke currentStroke = new BasicStroke(getLineWidth(), BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
private int width;
private float [] dashes = new float[1];
public DrawPanel(JLabel status)
{
statusLabel = status;
shapes = new ArrayList<>(100);
shapeCount = 0;
shapeType = 0;
currentShape = null;
currentColor = Color.BLACK;
dashes[0] = 5;
width = 5;
setBackground(Color.WHITE);
mouseDrawing handler= new mouseDrawing();
addMouseListener(handler);
addMouseMotionListener(handler);
setLayout(new BorderLayout());
add(statusLabel, BorderLayout.SOUTH);
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2D = (Graphics2D) g;
for(int i = 0; i < shapes.size(); i++)
shapes.get(i).draw(g2D);
//draws the current Shape Object if it is not null
if (currentShape != null)
currentShape.draw(g2D);
shapeCount = shapes.size();
}
public void setShapeType(int shapeType)
{
this.shapeType = shapeType;
}
public void setPaint(Paint currentColor)
{
this.currentColor = currentColor;
}
public void setFilledShape(boolean filledShape)
{
this.filledShape = filledShape;
}
public void setCurrentStroke(Stroke currentStroke)
{
this.currentStroke = currentStroke;
}
public void setWidth(int width)
{
this.width = width;
}
public void setDash(float[] dashes)
{
this.dashes = dashes;
}
public void clearLastShape()
{
if(!shapes.isEmpty())
shapes.remove(shapeCount - 1);
repaint();
}
public void clearDrawing()
{
if (!shapes.isEmpty())
{
shapes.clear();
repaint();
}
}
public int getLineWidth()
{
return width;
}
private class mouseDrawing extends MouseAdapter implements MouseMotionListener
{
@Override
public void mousePressed(MouseEvent event)
{
if(shapeType == 0)
currentShape = new MyLine(event.getX(), event.getY(), event.getX(), event.getY(), currentColor, currentStroke);
else if(shapeType == 1)
currentShape = new MyRectangle(event.getX(), event.getY(), event.getX(), event.getY(), currentColor, filledShape, currentStroke);
else if(shapeType == 2)
currentShape = new MyOval(event.getX(), event.getY(), event.getX(), event.getY(), currentColor, filledShape, currentStroke);
currentShape.setX1(event.getX());
currentShape.setY1(event.getY());
currentShape.setPaint(currentColor);
}
@Override
public void mouseReleased(MouseEvent event)
{
if(currentShape != null)
{
currentShape.setX2(event.getX());
currentShape.setY2(event.getY());
shapes.add(currentShape);
currentShape = null;
repaint();
}
}
@Override
public void mouseMoved(MouseEvent event)
{
statusLabel.setText("("+event.getX()+","+event.getY()+")");
}
@Override
public void mouseDragged(MouseEvent event)
{
currentShape.setX2(event.getX());
currentShape.setY2(event.getY());
statusLabel.setText(String.format("(%d, %d)",event.getX(),event.getY()));
repaint();
}
}
} |
package collections;
import java.util.Vector;
public class VectorExample {
public static void main(String[] args) {
// TODO Auto-generated method stub//is same as Array List.Vector methods are synchronized.Thread safety.
Vector <String> names = new Vector <String> ( );
names.add ("cherry");
names.add ("apple");
names.add ("banana");
names.add ("kiwi");
names.add ("apple");
System.out.println (names);
}
}
|
import org.junit.Assert;
import org.junit.Test;
import java.io.*;
/**
* Created by Benedikt on 27.10.2016.
*/
public class ETest {
private static final InputStream sIn = System.in;
public static final PrintStream sOut = System.out;
static void inputOutput(String input, String output) {
try {
InputStream inputStream = new ByteArrayInputStream(input.getBytes("UTF-8"));
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
System.setOut(new PrintStream(outputStream));
System.setIn(inputStream);
main(new String[1]);
System.out.flush();
System.setIn(sIn);
System.setOut(sOut);
String[] shouldOut = outputStream.toString("UTF-8").trim().split("\n");
for (int i = 0; i < shouldOut.length; i++) {
shouldOut[i] = shouldOut[i].trim();
}
String[] isOut = output.split("\n");
for (int i = 0; i < isOut.length; i++) {
isOut[i] = isOut[i].trim();
}
Assert.assertArrayEquals(shouldOut, isOut);
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void firstGivenTest() throws IOException {
String input = "";
String shouldOutput = "";
inputOutput(input, shouldOutput);
}
@Test
public void secondGivenTest() throws IOException {
String input = "";
String shouldOutput = "";
inputOutput(input, shouldOutput);
}
// @Test
// public void Test() throws IOException {
// String input = "";
// String shouldOutput = "";
// inputOutput(input, shouldOutput);
// }
}
|
package org.ah.minecraft.armour.mobs;
import java.util.ArrayList;
import java.util.List;
import org.ah.minecraft.armour.MoonPhases;
import org.ah.minecraft.armour.Plugin;
import org.bukkit.EntityEffect;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Silverfish;
import org.bukkit.inventory.ItemStack;
public class BloodBatController extends CustomEntityController {
public BloodBatController(int weight) {
super(weight);
}
@Override
public void update(LivingEntity e) {
e.playEffect(EntityEffect.HURT);
if ((Plugin.day(e.getWorld())) || (Plugin.getMoonPhase(e.getWorld()) != MoonPhases.NEW)) {
e.getWorld().playEffect(e.getLocation(), org.bukkit.Effect.STEP_SOUND, Material.WEB, 10);
e.remove();
}
}
@Override
public boolean isOne(LivingEntity e) {
return ((e instanceof Silverfish)) && ("Blood Rat".equals(e.getCustomName()));
}
@Override
public LivingEntity spawn(Location loc) {
Silverfish b = (Silverfish) loc.getWorld().spawnEntity(loc, EntityType.SILVERFISH);
b.setCustomName("Blood Rat");
return b;
}
@Override
public List<ItemStack> getDrops() {
List<ItemStack> drops = new ArrayList();
return drops;
}
}
|
package com.tencent.mm.d;
import com.tencent.mm.d.e.a;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.t.c;
class e$a$1 implements Runnable {
final /* synthetic */ a bCC;
e$a$1(a aVar) {
this.bCC = aVar;
}
public final void run() {
x.d("MicroMsg.EmojiAndTextArtist", "cancel focus!");
if (this.bCC.bCB.vG() != null) {
c ys = ((com.tencent.mm.cache.c) this.bCC.bCB.vG()).ys();
if (ys != null && ys.dnN) {
ys.setSelected(false);
a.a(this.bCC).aH(false);
a.a(this.bCC).vO();
}
}
}
}
|
package com.zs.service.impl;
import com.zs.dao.AreaDao;
import com.zs.entity.Area;
import com.zs.service.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @Created by IDEA
* @author:LiuYiBo(小博)
* @Date:2018/7/24
* @Time:16:22
*/
@Service
public class AreaServiceImpl implements AreaService {
@Autowired
private AreaDao areaDao;
@Override
public List<Area> getAreaList() {
return areaDao.queryArea();
}
}
|
import java.awt.Color;
public class Tiger extends Critter
{
private Color color;
private boolean usedScissorsLast = false;
private int direction;
private int stepsToTake;
private int stepsTaken;
public Tiger(Color color)
{
this.color = color;
stepsTaken = 0;
stepsToTake = 5;
direction = SOUTH;
}
public int fight(String opponent)
{
if(usedScissorsLast)
{
usedScissorsLast = false;
return PAPER;
}
else
{
usedScissorsLast = true;
return SCISSORS;
}
}
public Color getColor()
{
return this.color;
}
public int getMove(CritterInfo info)
{
if(stepsTaken == stepsToTake)
{
stepsTaken = 0;
direction = getNewDirection();
}
stepsTaken++;
return direction;
}
public String toString()
{
return "T";
}
private int getNewDirection()
{
switch(direction)
{
case SOUTH:
{
return WEST;
}
case WEST:
{
return NORTH;
}
case NORTH:
{
return EAST;
}
case EAST:
{
return SOUTH;
}
default:
{
//should never happen
return CENTER;
}
}
}
}
|
package framework.commands;
import framework.dto.ReportDTO;
import framework.services.ReportService;
public class ReportCommand implements Command {
private ReportService service;
private ReportDTO dto;
private String reportResult;
public ReportCommand(ReportService service, ReportDTO dto){
this.service = service;
this.dto = dto;
}
@Override
public void execute() {
reportResult = service.getReport(dto);
}
public String getReportResult() {
return reportResult;
}
}
|
package com.tencent.mm.plugin.wenote.model.nativenote.spans;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.FontMetricsInt;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.graphics.Path.Direction;
import android.text.Layout;
import android.text.Spanned;
import android.text.style.LeadingMarginSpan;
public final class d implements LeadingMarginSpan, f<Boolean>, g<Boolean> {
private static Path qsO = null;
private final int qsP;
public boolean qsQ;
public final /* synthetic */ f caH() {
return new d(this.qsP, this.qsQ);
}
public final /* bridge */ /* synthetic */ Object getValue() {
return Boolean.TRUE;
}
public d(int i, boolean z, boolean z2, boolean z3) {
this.qsP = i;
boolean z4 = z && z3 && !z2;
this.qsQ = z4;
if (qsO == null) {
qsO = new Path();
}
}
private d(int i, boolean z) {
this.qsP = i;
this.qsQ = z;
}
public final int getLeadingMargin(boolean z) {
return this.qsQ ? 0 : this.qsP;
}
public final void drawLeadingMargin(Canvas canvas, Paint paint, int i, int i2, int i3, int i4, int i5, CharSequence charSequence, int i6, int i7, boolean z, Layout layout) {
Spanned spanned = (Spanned) charSequence;
if (!this.qsQ && spanned.getSpanStart(this) == i6) {
Style style = paint.getStyle();
paint.setStyle(Style.FILL);
qsO.reset();
qsO.addCircle(0.0f, 0.0f, 6.0f, Direction.CW);
FontMetricsInt fontMetricsInt = paint.getFontMetricsInt();
int i8 = (fontMetricsInt.ascent + ((fontMetricsInt.descent + i4) + i4)) / 2;
canvas.save();
canvas.translate((float) ((i2 * 6) + i), (float) i8);
canvas.drawPath(qsO, paint);
canvas.restore();
paint.setStyle(style);
}
}
}
|
public class OverridingDeviceKeys extends BaseGameActivity {
// ====================================================
// CONSTANTS
// ====================================================
public static int WIDTH = 800;
public static int HEIGHT = 480;
// ====================================================
// VARIABLES
// ====================================================
private Scene mScene;
private Camera mCamera;
// Each rectangle imitates a different scene in our game
Rectangle screenOne;
Rectangle screenTwo;
Rectangle screenThree;
Rectangle screenFour;
// ====================================================
// CREATE ENGINE OPTIONS
// ====================================================
@Override
public EngineOptions onCreateEngineOptions() {
mCamera = new Camera(0, 0, WIDTH, HEIGHT);
EngineOptions engineOptions = new EngineOptions(true,
ScreenOrientation.LANDSCAPE_FIXED, new FillResolutionPolicy(),
mCamera);
return engineOptions;
}
// ====================================================
// CREATE RESOURCES
// ====================================================
@Override
public void onCreateResources(
OnCreateResourcesCallback pOnCreateResourcesCallback) {
pOnCreateResourcesCallback.onCreateResourcesFinished();
}
// ====================================================
// CREATE SCENE
// ====================================================
@Override
public void onCreateScene(OnCreateSceneCallback pOnCreateSceneCallback) {
mScene = new Scene();
pOnCreateSceneCallback.onCreateSceneFinished(mScene);
}
// ====================================================
// POPULATE SCENE
// ====================================================
@Override
public void onPopulateScene(Scene pScene,
OnPopulateSceneCallback pOnPopulateSceneCallback) {
// Create each rectangle which takes up the screen width and height.
// Each rectangle is a different color in order to represent a different
// scene
screenOne = new Rectangle(0, 0, WIDTH, HEIGHT,
mEngine.getVertexBufferObjectManager());
mScene.attachChild(screenOne);
screenOne.setColor(Color.GREEN);
screenTwo = new Rectangle(0, 0, WIDTH, HEIGHT,
mEngine.getVertexBufferObjectManager());
mScene.attachChild(screenTwo);
screenTwo.setColor(Color.BLUE);
screenThree = new Rectangle(0, 0, WIDTH, HEIGHT,
mEngine.getVertexBufferObjectManager());
mScene.attachChild(screenThree);
screenThree.setColor(Color.PINK);
screenFour = new Rectangle(0, 0, WIDTH, HEIGHT,
mEngine.getVertexBufferObjectManager());
mScene.attachChild(screenFour);
screenFour.setColor(Color.CYAN);
pOnPopulateSceneCallback.onPopulateSceneFinished();
}
// Override Android's responses for the physical device 'buttons'
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// On the event that the 'back' key is pressed
if (keyCode == KeyEvent.KEYCODE_BACK) {
// Loop through the rectangles/"scenes" starting from the last attached
for (int i = mScene.getChildCount() - 1; i >= 0; i--) {
// Get the current entity
Entity entity = (Entity) mScene.getChildByIndex(i);
// If the rectangle is still visible
if (entity.isVisible()) {
// Set the current rectangle to invisible
entity.setVisible(false);
// Return false so that a single rectangle is removed for each
// touch of the 'back' key
return false;
}
}
// The code below is only executed after all rectangles are no
// longer visible
// Dialogs must be executed on the UI Thread!
runOnUiThread(new Runnable() {
@Override
public void run() {
// Create a dialog box which asks if we'd like to quit
AlertDialog dialog = new AlertDialog.Builder(
OverridingDeviceKeys.this).create();
// Set the dialog's title text
dialog.setTitle("Quit Game?");
// Set the dialogs message text
dialog.setMessage("Are you sure you want to quit?");
// Create a button for the dialog box, titled "YES"
dialog.setButton("YES",
new DialogInterface.OnClickListener() {
// Override the click event of this specific button
@Override
public void onClick(DialogInterface arg0,
int arg1) {
// If the "YES" button is clicked, close the activity
OverridingDeviceKeys.this.finish();
}
});
// Create a second button which allows the app to keep running
dialog.setButton2("NO",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
// We can leave this listener blank, simply closing the dialog
// and resuming our game
}
});
// We must call show() on the dialog in order to display it
dialog.show();
}
});
// Return false, disallowing the 'back' key to close our activity
// since we're handling that ourselves
return false;
}
// This call will execute Android's native response. We can return false
// if we'd like to handle every type of event ourselves or if we'd like to
// disable all device keys
return super.onKeyDown(keyCode, event);
}
} |
package com.example.kostas.myapplication;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.journeyapps.barcodescanner.BarcodeEncoder;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class QRWallet extends AppCompatActivity {
ImageView image;
String text2Qr;
static ImageView vol;
String x;
TextView mTextViewResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qrwallet);
x = LogIn.e_mail.toUpperCase();
ImageView img = (ImageView) findViewById(R.id.imageView2) ;
if(MkoChoose_Ewallet.current.equals("wwf"))
img.setImageResource(R.drawable.wwf);
else if(MkoChoose_Ewallet.current.equals("line"))
img.setImageResource(R.drawable.health);
else if(MkoChoose_Ewallet.current.equals("unicef"))
img.setImageResource(R.drawable.unicef);
else if(MkoChoose_Ewallet.current.equals("med"))
img.setImageResource(R.drawable.ed);
else if(MkoChoose_Ewallet.current.equals("smile"))
img.setImageResource(R.drawable.smile);
else
img.setImageResource(R.drawable.actionade);
mTextViewResult = findViewById(R.id.textViewEv3);
OkHttpClient client = new OkHttpClient();
String url = "http://192.168.0.104:3000/api/queries/selectCommoditiesByOwner?owner="+x+"";
Request request = new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
final String myResponse = response.body().string();
Log.d("Coins : ",myResponse);/
QRWallet.this.runOnUiThread(new Runnable() {
@Override
public void run() {
mTextViewResult.setText(myResponse);
}
});
}
}
});
image = (ImageView)findViewById(R.id.QRImage);
text2Qr = x;
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
try{
BitMatrix bitMatrix = multiFormatWriter.encode(text2Qr , BarcodeFormat.QR_CODE, 200 , 200);
BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
Bitmap bitmap = barcodeEncoder.createBitmap(bitMatrix);
image.setImageBitmap(bitmap);
}
catch (WriterException e){
e.printStackTrace();
}
}
}
|
package br.com.recife.vacina.vacinarecife.mvp.vacinas;
import java.util.List;
import br.com.recife.vacina.vacinarecife.model.Record;
/**
* Created by morae on 06/01/2018.
*/
public interface IVacinasInteractor {
interface OnLoadVacinasFinish {
void onLoadVacinasSuccess(List<Record> records);
void onLoadVacinasError(int message);
}
void loadVacinas(OnLoadVacinasFinish listener);
}
|
package com.aacademy.bike_station.repository;
import com.aacademy.bike_station.model.Type;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface TypeRepository extends JpaRepository<Type, Long> {
Optional<Type> findByType(String type);
}
|
package com.lingnet.vocs.dao.jcsj;
import java.util.HashMap;
import java.util.List;
import com.lingnet.common.dao.BaseDao;
import com.lingnet.qxgl.entity.QxLog;
import com.lingnet.util.Pager;
/**
*
* @ClassName: LogDao
* @Description: 日志管理dao
* @author 姜平豹
* @date 2014-3-26 上午10:07:02
*
*/
public interface LogDao extends BaseDao<QxLog,String> {
@SuppressWarnings("rawtypes")
public List<HashMap> search(Pager pager, HashMap<String, String> searchMap);
/**
*
* @Title: Operate
* @param djType单据类型
* @param czType操作类型:增加,修改,删除,审核,查看
* @return
* String
* @author 姜平豹
* @since 2014-3-26 V 1.0
*/
public String Operate(String djType,String czType);
}
|
/*
Displays list of user's taken masechtos and allows user to choose one and open 'CompletedMasechta' activity
to then be able to change status to completed
*/
package com.example.mna.mishnapals;
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.os.Bundle;
//import android.support.v7.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Period;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
/**
* Created by MNA on 8/13/2017.
*/
public class MyMishnayos extends AppCompatActivity {
public void onCreate(Bundle savedInstance)
{
super.onCreate(savedInstance);
setContentView(R.layout.my_mishnayos);
final ListView listMishnayos = findViewById(R.id.listMishnayos);
final ArrayList<CaseTakenInfo> cases = new ArrayList<>();
final ListAdapter listAdapter = new ListAdapter(getBaseContext() , R.layout.my_masechta, cases);
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
/*
Populate 'cases' arraylist from user's branch in db with the cases this user participates in
*/
Query currUser = ref.child("users").orderByChild("userEmail").equalTo(user.getEmail());//.getRef().child("cases");
Log.d("curr", user.getEmail());
currUser.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
cases.clear();
for(DataSnapshot ds : dataSnapshot.getChildren()){
dataSnapshot = ds.child("cases");}
for(DataSnapshot userCase : dataSnapshot.getChildren()){
CaseTakenInfo caseTaken = userCase.getValue(CaseTakenInfo.class);
Log.d("curr6", caseTaken.getMasechtaTaken()+" "+caseTaken.isFinished());
cases.add(caseTaken);
}
listMishnayos.setAdapter(listAdapter);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
/*
If user selects an unfinished masechta, open the 'CompletedMasechta' activity to enable user to change status to completed
*/
listMishnayos.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(!cases.get(position).isFinished()) {
Intent intent = new Intent(getBaseContext(), CompletedMasechta.class);
CaseTakenInfo caseTakenInfo = cases.get(position);
intent.putExtra("caseId", cases.get(position).getCaseId());
intent.putExtra("masechta", cases.get(position).getMasechtaTaken());
startActivity(intent);
//TODO maybe change to manually update the listitem instead of ending activity and then resarting
MyMishnayos.this.finish();
}
}
});
}
/*
Create the list of masechtos
*/
private class ListAdapter extends ArrayAdapter<CaseTakenInfo>
{
DatabaseReference dbref = FirebaseDatabase.getInstance().getReference().child("cases");
public ListAdapter(Context context, int textViewResourceId){
super(context, textViewResourceId);
}
public ListAdapter(Context context, int textViewResourceId, List<CaseTakenInfo> casesTaken){
super(context, textViewResourceId, casesTaken);
}
/*
Fills in the fields of each masechta in the list with masechta name, date to complete, etc
*/
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
View v = convertView;
if (v == null) {
LayoutInflater li;
li = LayoutInflater.from(getContext());
v = li.inflate(R.layout.my_masechta, null);
holder = new ViewHolder();
holder.masechta = v.findViewById(R.id.masechtaName);
v.setTag(holder);
}
else {
holder = (ViewHolder)v.getTag();
}
final CaseTakenInfo caseTaken = getItem(position);
Log.d("aaaaa", "" + caseTaken.getMasechtaTaken());
if (caseTaken != null) {
holder.masechta.setText("Masechta: "+caseTaken.getMasechtaTaken());
final TextView completionStatus = (TextView) v.findViewById(R.id.completionStatus);
final TextView nameNiftar = (TextView) v.findViewById(R.id.nameNiftar);
DatabaseReference dref = dbref.child(caseTaken.getCaseId());
dref = dref.child("firstName");
dref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
nameNiftar.setText("Name of Niftar: "+((String)dataSnapshot.getValue()));
completionStatus.setText("Status: "+(caseTaken.isFinished()?"Completed":"Not Completed"));
Log.d("curr6", "resetStat "+caseTaken.getMasechtaTaken());
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
/*
Retreive date niftar from db and fill it in
*/
final TextView dateNiftar = (TextView) v.findViewById(R.id.dateNiftar);
final TextView timeRemaining = (TextView) v.findViewById(R.id.timeRemaining);
final ColorStateList textViewDefaultColor = dateNiftar.getTextColors();
dref = dbref.child(caseTaken.getCaseId()).child("date");
dref.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Integer[] dayMonthYear = new Integer[4];
String date = "";
int counter=0;
for (DataSnapshot sp : dataSnapshot.getChildren()) {
counter++;
dayMonthYear[counter] = sp.getValue(Integer.class);
Log.d("aaaa", "" + sp.getValue(Integer.class));
date += sp.getValue(Integer.class)+(counter<3 ? "/":"");
}
//Log.d("aaaa", ""+dataSnapshot.getValue(List<>.class));
// dateNiftar.setText(dataSnapshot.child("0").getValue(Integer.class));
dateNiftar.setText("End Date: "+date);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
LocalDate localDate = LocalDate.of(dayMonthYear[3], dayMonthYear[1], dayMonthYear[2]);
LocalDate today = LocalDate.now();
Period p = Period.between(localDate, today);
timeRemaining.setText("ft"+p.getDays());
}else{
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy");
try {
Date formattedDate = simpleDateFormat.parse(date);
Date currDate = Calendar.getInstance().getTime();
long diff = formattedDate.getTime() - currDate.getTime();
int days = (int)Math.ceil((double)diff/(double)(24*60*60*1000));
if(days>0){
timeRemaining.setTextColor(textViewDefaultColor);
timeRemaining.setText("Time Remaining: "+ days + " days");}
else if(days == 0){
timeRemaining.setTextColor(Color.RED);
timeRemaining.setText("Time Remaining: ENDS TODAY");}
else if(days < 0){
timeRemaining.setTextColor(Color.LTGRAY);
timeRemaining.setText("Time Remaining: Ended "+ Math.abs(days) + " days ago");
}
} catch (ParseException e) {
e.printStackTrace();
timeRemaining.setText("Error Calculating Time");
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
return v;
}
}
static class ViewHolder{
TextView masechta;
}
}
|
package com.tencent.mm.g.c;
import android.content.ContentValues;
import android.database.Cursor;
import com.tencent.mm.protocal.c.wl;
import com.tencent.mm.sdk.e.c;
import com.tencent.mm.sdk.platformtools.x;
import java.io.IOException;
public abstract class di extends c {
private static final int cKQ = "oriMsgId".hashCode();
private static final int cKR = "dataProto".hashCode();
private static final int cKS = "favFrom".hashCode();
public static final String[] ciG = new String[0];
private static final int ciO = "msgId".hashCode();
private static final int ciP = "rowid".hashCode();
private static final int ciV = "status".hashCode();
private static final int cke = "type".hashCode();
private static final int cnf = "title".hashCode();
private static final int cws = "desc".hashCode();
private static final int cxT = "localId".hashCode();
private static final int cyp = "toUser".hashCode();
private boolean cKN = true;
private boolean cKO = true;
private boolean cKP = true;
private boolean ciK = true;
private boolean ciS = true;
private boolean cjI = true;
private boolean cnb = true;
private boolean cwo = true;
private boolean cxR = true;
private boolean cyb = true;
public wl field_dataProto;
public String field_desc;
public String field_favFrom;
public int field_localId;
public long field_msgId;
public long field_oriMsgId;
public int field_status;
public String field_title;
public String field_toUser;
public int field_type;
public final void d(Cursor cursor) {
String[] columnNames = cursor.getColumnNames();
if (columnNames != null) {
int length = columnNames.length;
for (int i = 0; i < length; i++) {
int hashCode = columnNames[i].hashCode();
if (cxT == hashCode) {
this.field_localId = cursor.getInt(i);
this.cxR = true;
} else if (ciO == hashCode) {
this.field_msgId = cursor.getLong(i);
} else if (cKQ == hashCode) {
this.field_oriMsgId = cursor.getLong(i);
} else if (cyp == hashCode) {
this.field_toUser = cursor.getString(i);
} else if (cnf == hashCode) {
this.field_title = cursor.getString(i);
} else if (cws == hashCode) {
this.field_desc = cursor.getString(i);
} else if (cKR == hashCode) {
try {
byte[] blob = cursor.getBlob(i);
if (blob != null && blob.length > 0) {
this.field_dataProto = (wl) new wl().aG(blob);
}
} catch (IOException e) {
x.e("MicroMsg.SDK.BaseRecordMessageInfo", e.getMessage());
}
} else if (cke == hashCode) {
this.field_type = cursor.getInt(i);
} else if (ciV == hashCode) {
this.field_status = cursor.getInt(i);
} else if (cKS == hashCode) {
this.field_favFrom = cursor.getString(i);
} else if (ciP == hashCode) {
this.sKx = cursor.getLong(i);
}
}
}
}
public final ContentValues wH() {
ContentValues contentValues = new ContentValues();
if (this.cxR) {
contentValues.put("localId", Integer.valueOf(this.field_localId));
}
if (this.ciK) {
contentValues.put("msgId", Long.valueOf(this.field_msgId));
}
if (this.cKN) {
contentValues.put("oriMsgId", Long.valueOf(this.field_oriMsgId));
}
if (this.field_toUser == null) {
this.field_toUser = "";
}
if (this.cyb) {
contentValues.put("toUser", this.field_toUser);
}
if (this.cnb) {
contentValues.put("title", this.field_title);
}
if (this.cwo) {
contentValues.put("desc", this.field_desc);
}
if (this.cKO && this.field_dataProto != null) {
try {
contentValues.put("dataProto", this.field_dataProto.toByteArray());
} catch (IOException e) {
x.e("MicroMsg.SDK.BaseRecordMessageInfo", e.getMessage());
}
}
if (this.cjI) {
contentValues.put("type", Integer.valueOf(this.field_type));
}
if (this.ciS) {
contentValues.put("status", Integer.valueOf(this.field_status));
}
if (this.cKP) {
contentValues.put("favFrom", this.field_favFrom);
}
if (this.sKx > 0) {
contentValues.put("rowid", Long.valueOf(this.sKx));
}
return contentValues;
}
}
|
package org.apache.commons.net.ftp.parser;
import java.text.ParseException;
import java.util.List;
import java.util.ListIterator;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
public class UnixFTPEntryParser extends ConfigurableFTPFileEntryParserImpl {
static final String DEFAULT_DATE_FORMAT = "MMM d yyyy";
static final String DEFAULT_RECENT_DATE_FORMAT = "MMM d HH:mm";
static final String NUMERIC_DATE_FORMAT = "yyyy-MM-dd HH:mm";
private static final String JA_MONTH = "月";
private static final String JA_DAY = "日";
private static final String JA_YEAR = "年";
private static final String DEFAULT_DATE_FORMAT_JA = "M'月' d'日' yyyy'年'";
private static final String DEFAULT_RECENT_DATE_FORMAT_JA = "M'月' d'日' HH:mm";
public static final FTPClientConfig NUMERIC_DATE_CONFIG = new FTPClientConfig(
"UNIX",
"yyyy-MM-dd HH:mm",
null);
private static final String REGEX = "([bcdelfmpSs-])(((r|-)(w|-)([xsStTL-]))((r|-)(w|-)([xsStTL-]))((r|-)(w|-)([xsStTL-])))\\+?\\s*(\\d+)\\s+(?:(\\S+(?:\\s\\S+)*?)\\s+)?(?:(\\S+(?:\\s\\S+)*)\\s+)?(\\d+(?:,\\s*\\d+)?)\\s+((?:\\d+[-/]\\d+[-/]\\d+)|(?:\\S{3}\\s+\\d{1,2})|(?:\\d{1,2}\\s+\\S{3})|(?:\\d{1,2}月\\s+\\d{1,2}日))\\s+((?:\\d+(?::\\d+)?)|(?:\\d{4}年))\\s(.*)";
final boolean trimLeadingSpaces;
public UnixFTPEntryParser() {
this((FTPClientConfig)null);
}
public UnixFTPEntryParser(FTPClientConfig config) {
this(config, false);
}
public UnixFTPEntryParser(FTPClientConfig config, boolean trimLeadingSpaces) {
super("([bcdelfmpSs-])(((r|-)(w|-)([xsStTL-]))((r|-)(w|-)([xsStTL-]))((r|-)(w|-)([xsStTL-])))\\+?\\s*(\\d+)\\s+(?:(\\S+(?:\\s\\S+)*?)\\s+)?(?:(\\S+(?:\\s\\S+)*)\\s+)?(\\d+(?:,\\s*\\d+)?)\\s+((?:\\d+[-/]\\d+[-/]\\d+)|(?:\\S{3}\\s+\\d{1,2})|(?:\\d{1,2}\\s+\\S{3})|(?:\\d{1,2}月\\s+\\d{1,2}日))\\s+((?:\\d+(?::\\d+)?)|(?:\\d{4}年))\\s(.*)");
configure(config);
this.trimLeadingSpaces = trimLeadingSpaces;
}
public List<String> preParse(List<String> original) {
ListIterator<String> iter = original.listIterator();
while (iter.hasNext()) {
String entry = iter.next();
if (entry.matches("^total \\d+$"))
iter.remove();
}
return original;
}
public FTPFile parseFTPEntry(String entry) {
FTPFile file = new FTPFile();
file.setRawListing(entry);
boolean isDevice = false;
if (matches(entry)) {
int type;
String typeStr = group(1);
String hardLinkCount = group(15);
String usr = group(16);
String grp = group(17);
String filesize = group(18);
String datestr = String.valueOf(group(19)) + " " + group(20);
String name = group(21);
if (this.trimLeadingSpaces)
name = name.replaceFirst("^\\s+", "");
try {
if (group(19).contains("月")) {
FTPTimestampParserImpl jaParser = new FTPTimestampParserImpl();
jaParser.configure(new FTPClientConfig(
"UNIX", "M'月' d'日' yyyy'年'", "M'月' d'日' HH:mm"));
file.setTimestamp(jaParser.parseTimestamp(datestr));
} else {
file.setTimestamp(parseTimestamp(datestr));
}
} catch (ParseException parseException) {}
switch (typeStr.charAt(0)) {
case 'd':
type = 1;
break;
case 'e':
type = 2;
break;
case 'l':
type = 2;
break;
case 'b':
case 'c':
isDevice = true;
type = 0;
break;
case '-':
case 'f':
type = 0;
break;
default:
type = 3;
break;
}
file.setType(type);
int g = 4;
for (int access = 0; access < 3; access++, g += 4) {
file.setPermission(access, 0,
!group(g).equals("-"));
file.setPermission(access, 1,
!group(g + 1).equals("-"));
String execPerm = group(g + 2);
if (!execPerm.equals("-") && !Character.isUpperCase(execPerm.charAt(0))) {
file.setPermission(access, 2, true);
} else {
file.setPermission(access, 2, false);
}
}
if (!isDevice)
try {
file.setHardLinkCount(Integer.parseInt(hardLinkCount));
} catch (NumberFormatException numberFormatException) {}
file.setUser(usr);
file.setGroup(grp);
try {
file.setSize(Long.parseLong(filesize));
} catch (NumberFormatException numberFormatException) {}
if (type == 2) {
int end = name.indexOf(" -> ");
if (end == -1) {
file.setName(name);
} else {
file.setName(name.substring(0, end));
file.setLink(name.substring(end + 4));
}
} else {
file.setName(name);
}
return file;
}
return null;
}
protected FTPClientConfig getDefaultConfiguration() {
return new FTPClientConfig(
"UNIX",
"MMM d yyyy",
"MMM d HH:mm");
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\org\apache\commons\net\ftp\parser\UnixFTPEntryParser.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/ |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.iotdb.db.writelog.replay;
import java.util.List;
import org.apache.iotdb.db.engine.filenode.FileNodeManager;
import org.apache.iotdb.db.exception.FileNodeManagerException;
import org.apache.iotdb.db.exception.PathErrorException;
import org.apache.iotdb.db.exception.ProcessorException;
import org.apache.iotdb.db.metadata.MManager;
import org.apache.iotdb.db.qp.physical.PhysicalPlan;
import org.apache.iotdb.db.qp.physical.crud.DeletePlan;
import org.apache.iotdb.db.qp.physical.crud.InsertPlan;
import org.apache.iotdb.db.qp.physical.crud.UpdatePlan;
import org.apache.iotdb.tsfile.file.metadata.enums.TSDataType;
import org.apache.iotdb.tsfile.read.common.Path;
import org.apache.iotdb.tsfile.utils.Pair;
import org.apache.iotdb.tsfile.write.record.TSRecord;
import org.apache.iotdb.tsfile.write.record.datapoint.DataPoint;
public class ConcreteLogReplayer implements LogReplayer {
/**
* replay operation log (PhysicalPlan).
*
* @param plan PhysicalPlan
* @throws ProcessorException ProcessorException
*/
@Override
public void replay(PhysicalPlan plan, boolean isOverflow) throws ProcessorException {
try {
if (plan instanceof InsertPlan) {
InsertPlan insertPlan = (InsertPlan) plan;
multiInsert(insertPlan);
} else if (plan instanceof UpdatePlan) {
UpdatePlan updatePlan = (UpdatePlan) plan;
update(updatePlan);
} else if (plan instanceof DeletePlan) {
DeletePlan deletePlan = (DeletePlan) plan;
delete(deletePlan, isOverflow);
}
} catch (Exception e) {
throw new ProcessorException(
String.format("Cannot replay log %s", plan.toString()), e);
}
}
private void multiInsert(InsertPlan insertPlan)
throws PathErrorException, FileNodeManagerException {
String deviceId = insertPlan.getDeviceId();
long insertTime = insertPlan.getTime();
String[] measurementList = insertPlan.getMeasurements();
String[] insertValues = insertPlan.getValues();
TSRecord tsRecord = new TSRecord(insertTime, deviceId);
for (int i = 0; i < measurementList.length; i++) {
String pathKey = deviceId + "." + measurementList[i];
TSDataType dataType = MManager.getInstance().getSeriesType(pathKey);
String value = insertValues[i];
DataPoint dataPoint = DataPoint.getDataPoint(dataType, measurementList[i], value);
tsRecord.addTuple(dataPoint);
}
FileNodeManager.getInstance().insert(tsRecord, true);
}
private void update(UpdatePlan updatePlan) throws FileNodeManagerException, PathErrorException {
TSDataType dataType = MManager.getInstance().getSeriesType(updatePlan.getPath().getFullPath());
for (Pair<Long, Long> timePair : updatePlan.getIntervals()) {
FileNodeManager.getInstance().update(updatePlan.getPath().getDevice(),
updatePlan.getPath().getMeasurement(), timePair.left, timePair.right, dataType,
updatePlan.getValue());
}
}
private void delete(DeletePlan deletePlan, boolean isOverflow) throws FileNodeManagerException {
for (Path path : deletePlan.getPaths()) {
if (isOverflow) {
FileNodeManager.getInstance().deleteOverflow(path.getDevice(), path.getMeasurement(),
deletePlan.getDeleteTime());
} else {
FileNodeManager.getInstance().deleteBufferWrite(path.getDevice(), path.getMeasurement(),
deletePlan.getDeleteTime());
}
}
}
}
|
package ua.solomenko.inputoutput;
import java.io.*;
public class FileAnalyzer {
// Написать программу FileAnalyzer, которая в консоли принимает 2 параметра:
// 1) путь к файлу
// 2) слово
// Usage:
// java FileAnalyzer C:/test/story.txt duck
// Выводит:
// 1) Кол-во вхождений искомого слова в файле
// 2) Все предложения содержащие искомое слово
// (предложение заканчивается символами ".", "?", "!"), каждое преждложение с новой строки.
public static void main(String[] args) throws IOException {
String path = "resources/story.txt";
String word = "duck";
if (args.length > 0) {
path = args[0];
word = args[1];
}
System.out.println("Amount of coincidences the search word in the text: " +countDuplicates(path, word));
printSentences(path, word);
}
static int countDuplicates(String path, String word) throws IOException {
validatePath(path);
File root = new File(path);
char[] text;
try (FileReader file = new FileReader(path)) {
text = new char[(int) root.length()];
file.read(text);
}
int counter = 0;
String[] words = new String(text).split(" ");
for (String wd : words) {
if (wd.equalsIgnoreCase(word)) {
counter++;
}
}
return counter;
}
static void printSentences(String path, String word) throws IOException {
validatePath(path);
String[] sentences = findSentences(path, word);
for (String sentence : sentences){
if (sentence != null){
System.out.println(sentence);
}
}
}
static String[] findSentences(String path, String word) throws IOException {
validatePath(path);
File fileLength = new File(path);
char[] text;
try (FileReader file = new FileReader(path)) {
text = new char[(int) fileLength.length()];
file.read(text);
}
String[] sentences = new String(text).split("\\.|\\?|\\!");
String[] temp = new String[sentences.length];
for (int i = 0; i<sentences.length; i++){
String[] words = sentences[i].split(" ");
for (String wd : words){
if(wd.equalsIgnoreCase(word)){
temp[i] = sentences[i];
}
}
}
return temp;
}
static private void validatePath(String path) throws IOException{
File file = new File(path);
if(!file.exists()){
throw new IOException("File does not exist.");
}
}
} |
package tv;
/**
*
* @author Adriana
*/
public class Main1 {
public static void main(String[] args) {
Tv tv1 = new Tv();
Tv tv2 = new Tv();
tv1.encender();
tv1.subirVolumen();
tv1.subirVolumen();
tv1.subirVolumen();
tv1.subirVolumen();
tv2 = tv1;
tv1.subirVolumen();
tv2.subirVolumen();
System.out.println("Tv1 volumen: " + tv1.volumen);
System.out.println("Tv2 volumen: " + tv2.volumen);
}
}
|
package com.mes.old.meta;
// Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.Set;
/**
* JbpmIdUser generated by hbm2java
*/
public class JbpmIdUser implements java.io.Serializable {
private BigDecimal id;
private char class_;
private String name;
private String email;
private String password;
private Set jbpmIdMemberships = new HashSet(0);
public JbpmIdUser() {
}
public JbpmIdUser(BigDecimal id, char class_) {
this.id = id;
this.class_ = class_;
}
public JbpmIdUser(BigDecimal id, char class_, String name, String email, String password, Set jbpmIdMemberships) {
this.id = id;
this.class_ = class_;
this.name = name;
this.email = email;
this.password = password;
this.jbpmIdMemberships = jbpmIdMemberships;
}
public BigDecimal getId() {
return this.id;
}
public void setId(BigDecimal id) {
this.id = id;
}
public char getClass_() {
return this.class_;
}
public void setClass_(char class_) {
this.class_ = class_;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public Set getJbpmIdMemberships() {
return this.jbpmIdMemberships;
}
public void setJbpmIdMemberships(Set jbpmIdMemberships) {
this.jbpmIdMemberships = jbpmIdMemberships;
}
}
|
package com.zpjr.cunguan.presenter.impl.fragment;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import com.zpjr.cunguan.R;
import com.zpjr.cunguan.action.action.investment.IInvestmentAction;
import com.zpjr.cunguan.action.impl.investment.InvestmentActionImpl;
import com.zpjr.cunguan.common.base.BasePresenterImpl;
import com.zpjr.cunguan.common.utils.CommonUtils;
import com.zpjr.cunguan.common.utils.Constants;
import com.zpjr.cunguan.common.views.WDTabPageIndicator;
import com.zpjr.cunguan.presenter.presenter.fragment.IInvestFragmentPresenter;
import com.zpjr.cunguan.ui.activity.investment.ProductListFragment;
import com.zpjr.cunguan.ui.activity.main.MainActivity;
import com.zpjr.cunguan.ui.fragment.InvestFragment;
import com.zpjr.cunguan.view.fragment.IInvestFragmnetView;
import com.zpjr.cunguan.view.investment.IInvestmentListView;
import java.util.ArrayList;
import java.util.List;
/**
* Description: 产品列表FragmentActivity的presenter
* Autour: LF
* Date: 2017/7/17 14:18
*/
public class InvestFragmentPresenterImpl extends BasePresenterImpl implements IInvestFragmentPresenter {
private BasePagerAdapter mAdapter;
private Fragment mShortFragment;
private Fragment mMediumFragment;
private Fragment mLongFragment;
private List<Fragment> mProductList = new ArrayList<>();
private IInvestFragmnetView mView;
public InvestFragmentPresenterImpl(IInvestFragmnetView view) {
this.mView = view;
}
@Override
public void initFragment(ViewPager viewPager, WDTabPageIndicator indicator) {
viewPager.setOffscreenPageLimit(1);
if (mProductList.size() > 0) {
mProductList.clear();
}
mShortFragment = new ProductListFragment();
Bundle bundle = new Bundle();
bundle.putString("product_type", Constants.ASY);
mShortFragment.setArguments(bundle);
mProductList.add(mShortFragment);
mMediumFragment = new ProductListFragment();
bundle = new Bundle();
bundle.putString("product_type", Constants.PYY);
mMediumFragment.setArguments(bundle);
mProductList.add(mMediumFragment);
mLongFragment = new ProductListFragment();
bundle = new Bundle();
bundle.putString("product_type", Constants.AWY);
mLongFragment.setArguments(bundle);
mProductList.add(mLongFragment);
mAdapter = new BasePagerAdapter(((MainActivity) mView.getContext()).getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
indicator.setViewPager(viewPager);
setTabPagerIndicator(indicator);
}
public void setTabPagerIndicator(WDTabPageIndicator indicator) {
indicator.setIndicatorMode(WDTabPageIndicator.IndicatorMode.MODE_WEIGHT_NOEXPAND_NOSAME);// 设置模式,一定要先设置模式
indicator.setDividerColor(Color.parseColor("#00ffffff"));// 设置分割线的颜色
indicator.setDividerPadding(CommonUtils.dip2px(mView.getContext().getApplicationContext(), 30));
indicator.setIndicatorColor(Color.parseColor("#ff9d49"));// 设置底部导航线的颜色
indicator.setTextColorSelected(Color.WHITE);// 设置tab标题选中的颜色
indicator.setTextColor(Color.parseColor("#e5e5e5"));// 设置tab标题未被选中的颜色
indicator.setTextSize(CommonUtils.sp2px(mView.getContext().getApplicationContext(), 14));// 设置字体大小
indicator.setTextSizeSelected(CommonUtils.sp2px(mView.getContext().getApplicationContext(), 16));//设置tab标题被选中的大小
indicator.setIndicatorHeight(CommonUtils.dip2px(mView.getContext().getApplicationContext(), 4));
}
/**
* viewpager适配器
*/
class BasePagerAdapter extends FragmentPagerAdapter {
String[] titles;
public BasePagerAdapter(FragmentManager fm) {
super(fm);
this.titles = CommonUtils.getStringArray(R.array.product_list_titles);
}
@Override
public android.support.v4.app.Fragment getItem(int position) {
return mProductList.get(position);
}
@Override
public int getCount() {
return titles.length;
}
@Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
}
}
|
package com.lito.fupin.meta.paper.entity;
import lombok.Data;
import java.util.Date;
@Data
public class Paper {
private Integer ids;
private String paperId;
private String title;
private String content;
private Date uploadTime;
private String uploadUserId;
private String status;
private String approveRemark;
private Date approveTime;
private String categoryId;
private String isPublic;
private String imgUrl;
private String fileUrl;
private String approveUserId;
private String author;
private Integer views;
private String organizeId;
private String organizeName;
}
|
package com.tencent.wecall.talkroom.model;
import com.tencent.wecall.talkroom.model.g.a;
class g$16 implements Runnable {
final /* synthetic */ g vyO;
g$16(g gVar) {
this.vyO = gVar;
}
public final void run() {
synchronized (this.vyO.cWy) {
for (a bgu : this.vyO.cWy) {
bgu.bgu();
}
}
}
}
|
package com.qf.Algorithm;
public class ListCode {
public static void main(String[] args) {
ListNode node = new ListNode(1);
node.next = new ListNode(2);
node.next.next = new ListNode(3);
node.next.next.next = new ListNode(4);
node.next.next.next.next = new ListNode(5);
removeNthFromEnd(node, 3);
while (node!=null) {
System.out.print(node.val + "\t");
node = node.next;
}
}
public static ListNode removeNthFromEnd(ListNode head, int n) {
ListNode first = new ListNode(0);
first.next = head;
ListNode node1 = first;
ListNode node2 = first;
int i = 0;
while (i<n) {
node1 = node1.next;
i++;
}
while (node1.next!=null) {
node1 = node1.next;
node2 = node2.next;
}
node2.next = node2.next.next;
return first.next;
}
public static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
}
|
package datastructures.interfaces;
import misc.exceptions.NoSuchKeyException;
/**
* Represents a data structure that contains a bunch of key-value mappings. Each key must be unique.
*/
public interface IDictionary<K, V> {
/**
* Returns the value corresponding to the given key.
*
* @throws NoSuchKeyException if the dictionary does not contain the given key.
*/
public V get(K key);
/**
* Returns the value corresponding to the given key, if the key exists in the map.
*
* If the key does *not* contain the given key, returns the default value.
*
* Note: This method does not modify the map in any way. The interface also
* provides a default implementation, but you may optionally override
* it with a more efficient version.
*/
public default V getOrDefault(K key, V defaultValue) {
if (this.containsKey(key)) {
return this.get(key);
} else {
return defaultValue;
}
}
/**
* Adds the key-value pair to the dictionary. If the key already exists in the dictionary,
* replace its value with the given one.
*/
public void put(K key, V value);
/**
* Remove the key-value pair corresponding to the given key from the dictionary.
*
* @throws NoSuchKeyException if the dictionary does not contain the given key.
*/
public V remove(K key);
/**
* Returns 'true' if the dictionary contains the given key and 'false' otherwise.
*/
public boolean containsKey(K key);
/**
* Returns the number of key-value pairs stored in this dictionary.
*/
public int size();
/**
* Returns 'true' if this dictionary is empty and 'false' otherwise.
*/
public default boolean isEmpty() {
return this.size() == 0;
}
}
|
package kodlamaio.hrms.dataAccess.abstacts;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import kodlamaio.hrms.entities.concretes.ConfirmationCode;
public interface ConfirmationDao extends JpaRepository<ConfirmationCode, Integer> {
ConfirmationCode getByConfirmationCode(String confirmationCode);
List<ConfirmationCode> getByIsConfirmed(boolean isConfirmed);
ConfirmationCode getByUserIdAndId(int userId, int id);
}
|
package pl.finsys.beanscopes.services;
/**
* @author jarek@finsys.pl
*/
public class ServiceTwoImpl implements ServiceTwo {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
|
package android.support.v7.widget;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
class p implements q {
final RectF Nx = new RectF();
p() {
}
public void eN() {
af.Ts = new af$a() {
public final void a(Canvas canvas, RectF rectF, float f, Paint paint) {
float f2 = 2.0f * f;
float width = (rectF.width() - f2) - 1.0f;
float height = (rectF.height() - f2) - 1.0f;
if (f >= 1.0f) {
float f3 = f + 0.5f;
p.this.Nx.set(-f3, -f3, f3, f3);
int save = canvas.save();
canvas.translate(rectF.left + f3, rectF.top + f3);
canvas.drawArc(p.this.Nx, 180.0f, 90.0f, true, paint);
canvas.translate(width, 0.0f);
canvas.rotate(90.0f);
canvas.drawArc(p.this.Nx, 180.0f, 90.0f, true, paint);
canvas.translate(height, 0.0f);
canvas.rotate(90.0f);
canvas.drawArc(p.this.Nx, 180.0f, 90.0f, true, paint);
canvas.translate(width, 0.0f);
canvas.rotate(90.0f);
canvas.drawArc(p.this.Nx, 180.0f, 90.0f, true, paint);
canvas.restoreToCount(save);
canvas.drawRect((rectF.left + f3) - 1.0f, rectF.top, 1.0f + (rectF.right - f3), rectF.top + f3, paint);
canvas.drawRect((rectF.left + f3) - 1.0f, 1.0f + (rectF.bottom - f3), 1.0f + (rectF.right - f3), rectF.bottom, paint);
}
canvas.drawRect(rectF.left, Math.max(0.0f, f - 1.0f) + rectF.top, rectF.right, 1.0f + (rectF.bottom - f), paint);
}
};
}
public final void a(o oVar, Context context, int i, float f, float f2, float f3) {
af afVar = new af(context.getResources(), i, f, f2, f3);
afVar.U(oVar.getPreventCornerOverlap());
oVar.setBackgroundDrawable(afVar);
h(oVar);
}
private void h(o oVar) {
Rect rect = new Rect();
i(oVar).getPadding(rect);
oVar.E((int) Math.ceil((double) b(oVar)), (int) Math.ceil((double) c(oVar)));
oVar.d(rect.left, rect.top, rect.right, rect.bottom);
}
public final void f(o oVar) {
}
public final void g(o oVar) {
i(oVar).U(oVar.getPreventCornerOverlap());
h(oVar);
}
public final void a(o oVar, int i) {
af i2 = i(oVar);
i2.cN.setColor(i);
i2.invalidateSelf();
}
public final void a(o oVar, float f) {
af i = i(oVar);
if (f < 0.0f) {
throw new IllegalArgumentException("Invalid radius " + f + ". Must be >= 0");
}
float f2 = (float) ((int) (0.5f + f));
if (i.go != f2) {
i.go = f2;
i.gu = true;
i.invalidateSelf();
}
h(oVar);
}
public final float d(o oVar) {
return i(oVar).go;
}
public final void c(o oVar, float f) {
af i = i(oVar);
i.o(f, i.gr);
}
public final float e(o oVar) {
return i(oVar).gt;
}
public final void b(o oVar, float f) {
af i = i(oVar);
i.o(i.gt, f);
h(oVar);
}
public final float a(o oVar) {
return i(oVar).gr;
}
public final float b(o oVar) {
af i = i(oVar);
return ((((float) i.Tr) + i.gr) * 2.0f) + (Math.max(i.gr, (i.go + ((float) i.Tr)) + (i.gr / 2.0f)) * 2.0f);
}
public final float c(o oVar) {
af i = i(oVar);
return ((((float) i.Tr) + (i.gr * 1.5f)) * 2.0f) + (Math.max(i.gr, (i.go + ((float) i.Tr)) + ((i.gr * 1.5f) / 2.0f)) * 2.0f);
}
private static af i(o oVar) {
return (af) oVar.getBackground();
}
}
|
package com.crivano.swaggerservlet;
public interface IHTTP {
<T extends ISwaggerResponse> T fetch(String authorization, String url,
String method, ISwaggerRequest req, Class<T> clazzResp)
throws Exception;
}
|
package com.example.android.navigation_test;
import android.support.v4.app.Fragment;
import android.view.View;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.ViewGroup;
/**
* Created by Krishnendu Mukherjee on 12/12/16.
*The main purpose of this fragment is to inflate (connect) the fragment_facilities xml file,
*thereby providing the various educational and research facilities provided by the department.
*/
public class Facilities extends Fragment{
View myView;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.fragment_facilities, container, false);
return myView;
}
}
|
package com.travel.models;
import javax.persistence.*;
import java.util.Set;
@Entity
@Table(name="amenities")
public class Amenity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private String description;
@OneToMany(mappedBy = "amenity")
private Set<AmenityItem> amenityItems;
public long getId() {
return this.id;
}
public String getDescription() {
return description;
}
public String getName() {
return this.name;
}
public Set<AmenityItem> getAmenityItems() {
return this.amenityItems;
}
public void setName(String name) {
this.name = name;
}
public void setDescription(String description) {
this.description = description;
}
public void setAmenityItems(Set<AmenityItem> amenityItems) {
this.amenityItems = amenityItems;
}
} |
package com.umasuo.authentication;
import org.springframework.util.Assert;
/**
* This provider provide an tool to check the authentication of the token.
* default policy provider.
*/
public interface AuthPolicyProvider {
/**
* check the authentication of the token
*
* @param token token input.
*/
default void checkToken(String token) {
Assert.notNull(token);
// TODO: 17/8/28 check token
}
}
|
package pl.mgd.util;
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
/*Java Singleton Singleton pattern restricts the instantiation of a class and ensures
* that only one instance of the class exists in the java virtual machine.
* The singleton class must provide a global access point to get the instance of the class.
* Singleton pattern is used for logging, drivers objects, caching and thread pool.
* Singleton design pattern is also used in other design patterns like
* Abstract Factory, Builder, Prototype, Facade etc.
* Singleton design pattern is used in core java classes also, for example java.lang.Runtime, java.awt.Desktop.
*
*Implement Private constructor to restrict instantiation of the class from other classes.
* Private static variable of the same class that is the only instance of the class.
* Public static method that returns the instance of the class,
* this is the global access point for outer world to get the instance of the singleton class.
*/
public class ConnectionProvider {
public static DataSource dataSource;
public static Connection getConnection() throws SQLException {
return getDSInstance().getConnection();
}
private static DataSource getDSInstance() {
if(dataSource == null) {
try {
Context initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:comp/env");
dataSource = (DataSource) envContext.lookup("jdbc/library");
} catch (NamingException e) {
e.printStackTrace();
}
}
return dataSource;
}
}
|
package problem13;
/**
* @author Jackid
* JDK-version:1.8
* Problem:牛客网-剑指offer《机器人的运动范围》
* Result:已通过了所有的测试用例
*/
/*题目描述:
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,
每一次只能向左,右,上,下四个方向移动一格,
但是不能进入行坐标和列坐标的数位之和大于k的格子。
例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。
请问该机器人能够达到多少个格子?
*/
public class Solution {
static int visited[][];//标记已经被访问的格子,由1或0表示
static int[] x = { 1, 0, -1, 0 };// 右、下、左、上
static int[] y = { 0, 1, 0, -1 };// 右、下、左、上
public int movingCount(int threshold, int rows, int cols)// threshold指的是题目中的k,rows为m,cols为n
{
visited = new int[rows][cols];//初始化数组
if (threshold < 0)//k小于0,则地图上所有点都不符合题意,返回0
return 0;
else
return find(threshold, rows, cols, 0, 0);//初始化并开始寻找
}
//find(...)是搜索函数,用来搜索地图中的格子
public static int find(int threshold, int rows, int cols, int current_row, int current_col) {
int road = 1;//能进入到该函数的都是新的格子,所以格子数为1
visited[current_row][current_col] = 1;//将该格子标记为已访问
for (int i = 0; i < 4; i++) {//四个方向分别搜索
if (judge(threshold, rows, cols, current_row + y[i], current_col + x[i]))
//符合要求时,进入下一个格子的搜索
road += find(threshold, rows, cols, current_row + y[i], current_col + x[i]);//向四个方向收集符合要求的格子的数量
}
return road;//返回搜索得到的格子数
}
//judge(...)是判断函数,用来判断当前格子是否合法。
public static boolean judge(int threshold, int rows, int cols, int current_row, int current_col) {
if (current_row >= rows || current_row < 0 || current_col >= cols || current_col < 0)//判断是否超出地图界限
return false;
if (visited[current_row][current_col] == 1)//判断格子是否被访问过
return false;
//以下是判断行坐标和列坐标的数位之和是否大于k
int sum = 0;
String string_current_row = String.valueOf(current_row);
String string_current_col = String.valueOf(current_col);
for (int i = 0; i < string_current_row.length(); i++)
sum += Integer.valueOf(string_current_row.substring(i, i + 1));
for (int i = 0; i < string_current_col.length(); i++)
sum += Integer.valueOf(string_current_col.substring(i, i + 1));
if (sum > threshold)
return false;
//以上判断均通过则返回true
return true;
}
}
|
package com.tencent.mm.plugin.appbrand.f;
import com.tencent.mm.plugin.appbrand.appusage.k;
import com.tencent.mm.plugin.fts.a.a.a;
import com.tencent.mm.plugin.fts.a.c;
import com.tencent.mm.plugin.fts.a.d;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
class b$b extends a {
final /* synthetic */ b fyH;
private String id;
private String name;
public b$b(b bVar, String str) {
this.fyH = bVar;
this.id = str;
}
public final boolean execute() {
this.fyH.fyF.beginTransaction();
this.fyH.fyF.b(c.jqg, this.id);
k sK = i.sK(this.id);
if (sK != null) {
long currentTimeMillis = System.currentTimeMillis();
String oV = bi.oV(sK.dfX);
int hashCode = oV.hashCode();
this.fyH.fyF.a(393216, 1, (long) hashCode, oV, currentTimeMillis, sK.appName);
this.fyH.fyF.a(393216, 2, (long) hashCode, oV, currentTimeMillis, d.av(sK.appName, false));
this.fyH.fyF.a(393216, 3, (long) hashCode, oV, currentTimeMillis, d.av(sK.appName, true));
this.name = sK.appName;
x.i("MicroMsg.FTS.FTS5SearchWeAppLogic", "inserted we app info id = %s", new Object[]{oV});
}
this.fyH.fyF.commit();
return true;
}
public final String getName() {
return "InsertWeAppTask";
}
public final String afC() {
return String.format("{name: %s id: %s}", new Object[]{this.name, this.id});
}
}
|
package com.huangyifei.android.androidexample.savestate;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import com.huangyifei.android.androidexample.BaseActivity;
import com.huangyifei.android.androidexample.R;
/**
* Created by huangyifei on 16/10/13.
*/
public class ActivityThree extends BaseActivity {
private static final boolean ENABLE_SAVE_STATE = true;
private TextFragment mFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_container_layout);
if (ENABLE_SAVE_STATE && savedInstanceState != null) {
mFragment = (TextFragment) getSupportFragmentManager().findFragmentByTag("text_fragment");
} else {
mFragment = (TextFragment) Fragment.instantiate(this, TextFragment.class.getName());
getSupportFragmentManager().beginTransaction().add(R.id.content, mFragment, "text_fragment").commit();
}
}
public static void launch(Activity activity) {
activity.startActivity(new Intent(activity, ActivityThree.class));
}
} |
package server.rest.controllers;
import static org.junit.jupiter.api.Assertions.*;
class SkillsControllerTest {
} |
package com.tencent.mm.plugin.welab.d;
import android.text.TextUtils;
import com.tencent.mm.kernel.g;
import com.tencent.mm.s.c;
import com.tencent.mm.sdk.platformtools.ad;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.aa.a;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public final class b {
private static final b qnt = new b();
public Map<String, Integer> qmR = new HashMap();
public String tag = "";
public static b bYX() {
return qnt;
}
private b() {
bYM();
}
private void bYM() {
this.tag = (String) g.Ei().DT().get(a.sXi, null);
x.i("WeLabRedPointMgr", "load red tag " + this.tag);
if (!TextUtils.isEmpty(this.tag)) {
for (Object obj : this.tag.split("&")) {
if (!TextUtils.isEmpty(obj)) {
String[] split = obj.split("=");
if (split != null && split.length == 2) {
this.qmR.put(split[0], Integer.valueOf(bi.WU(split[1])));
}
}
}
}
}
public final boolean e(com.tencent.mm.plugin.welab.c.a.a aVar) {
if (aVar.field_RedPoint != 1) {
return false;
}
boolean z = aVar.bTJ() || aVar.field_Switch == 3;
if (z || Sc(aVar.field_LabsAppId)) {
return false;
}
return true;
}
private boolean Sc(String str) {
return this.qmR.containsKey(str) && ((Integer) this.qmR.get(str)).intValue() == 1;
}
public final void f(com.tencent.mm.plugin.welab.c.a.a aVar) {
if (aVar.field_RedPoint == 1 && !Sc(aVar.field_LabsAppId) && aVar.bYT()) {
c.Cp().v(266267, true);
}
}
public static void bYY() {
Object obj;
List<com.tencent.mm.plugin.welab.c.a.a> bYJ = com.tencent.mm.plugin.welab.b.bYI().bYJ();
if (bYJ == null || bYJ.isEmpty()) {
} else {
}
for (com.tencent.mm.plugin.welab.c.a.a aVar : bYJ) {
if (aVar != null && qnt.e(aVar)) {
obj = null;
break;
}
}
int obj2 = 1;
if (obj2 != null) {
c.Cp().aV(266267, 266241);
}
}
public static boolean bYZ() {
return c.Cp().aU(266267, 266241);
}
public static boolean bZa() {
return ad.chZ().getBoolean("key_has_enter_welab", false);
}
}
|
/*]
*/
package com.cleverfishsoftware.loadgenerator.payload.air;
import static com.cleverfishsoftware.loadgenerator.payload.air.AirlineDataPayloadGenerator.removeBadChars;
import java.util.UUID;
/**
*
* @author peter
*/
public class AirlineDataFormatterCSV implements AirlineDataFormatter {
private static final String COMMA = ",";
@Override
public String format(Airline airline, Airport from, Airport to, int depHr, int depMin, int arrHr, int arrMin, String price, String currency, String type, int size) {
StringBuilder record = new StringBuilder()
.append(UUID.randomUUID().toString())
.append(COMMA)
.append(removeBadChars(airline.code))
.append(COMMA)
.append(removeBadChars(airline.name))
.append(COMMA)
.append(removeBadChars(airline.country))
.append(COMMA)
.append(removeBadChars(from.code))
.append(COMMA)
.append(removeBadChars(from.name))
.append(COMMA)
.append(removeBadChars(from.city))
.append(COMMA)
.append(removeBadChars(from.country))
.append(COMMA)
.append(removeBadChars(to.code))
.append(COMMA)
.append(removeBadChars(to.name))
.append(COMMA)
.append(removeBadChars(to.city))
.append(COMMA)
.append(removeBadChars(to.country))
.append(COMMA)
.append(String.format("%02d", depHr).concat(":").concat(String.format("%02d", depMin)))
.append(COMMA)
.append(String.format("%02d", arrHr).concat(":").concat(String.format("%02d", arrMin)))
.append(COMMA)
.append(price)
.append(COMMA)
.append(currency)
.append(COMMA)
.append(type);
if (record.length() + 2 < size) {
record.append(COMMA);
while (record.length() < size) { // add padding to match the desired message size, need at least one character after the comma
if (record.length() % 2 == 0) {
record.append("0");
} else {
record.append("1");
}
}
}
return record.toString();
}
}
|
package com.mo.serilanumber;
import com.mo.serialnumber.Application;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringJUnit4ClassRunner.class) // SpringJUnit支持,由此引入Spring-Test框架支持!
@SpringApplicationConfiguration(classes = Application.class) // 指定我们SpringBoot工程的Application启动类
@WebAppConfiguration
public class BaseTest {
@Test
public void test(){
}
}
|
package com.anibal.educational.rest_service.comps.service.mail;
public interface MailService {
public void sendMail(MailContent content, MailConfigurator configurator) throws MailServiceException;
}
|
package com.kh.efp.band.model.service;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.springframework.social.google.api.plus.Activity.Article;
import com.kh.efp.band.model.vo.Board;
import com.kh.efp.band.model.vo.Member_Band;
public interface BoardMemberService {
List<Member_Band> boardMemberList();
}
|
package com.amit.indiehooddemo;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.amit.indiehooddemo.adapter.ListAdapter;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.function.Consumer;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private static final String DATA_URL = "https://ui-test-dot-indihood-dev-in.appspot.com/records";
private static final String SCHEMA_URL = "https://ui-test-dot-indihood-dev-in.appspot.com/schema";
RequestQueue requestQueue;
private ListAdapter adapter;
private ListView listView;
private ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = findViewById(R.id.progressBar);
requestQueue = Volley.newRequestQueue(this);
listView = findViewById(R.id.root_list_view);
loadSchema();
}
private void loadSchema(){
//getting the progressbar
//making the progressbar visible
progressBar.setVisibility(View.VISIBLE);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, SCHEMA_URL, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
loadData(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
//creating a request queue
//adding the string request to request queue
requestQueue.add(jsonObjectRequest);
}
private void loadData(final JSONObject schemaJson){
//getting the progressbar
final ProgressBar progressBar = findViewById(R.id.progressBar);
//making the progressbar visible
progressBar.setVisibility(View.VISIBLE);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, DATA_URL, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
processData(schemaJson, response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
progressBar.setVisibility(View.INVISIBLE);
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
//creating a request queue
//adding the string request to request queue
requestQueue.add(jsonObjectRequest);
}
@SuppressLint("NewApi")
private void processData(final JSONObject schemaJson, final JSONObject dataJson){
try {
final ArrayList<String> dataList = new ArrayList<>();
dataJson.keys().forEachRemaining(new Consumer<String>() {
@Override
public void accept(String key) {
Object keyvalue = null;
try {
keyvalue = dataJson.get(key);
dataList.add(key);
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("key: " + key + " value: " + keyvalue);
}
});
progressBar.setVisibility(View.INVISIBLE);
ListAdapter listAdapter = new ListAdapter(this, dataList, schemaJson, dataJson);
listView.setAdapter(listAdapter);
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package com.khachik.explore.Activities;
import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.khachik.explore.Configs.Config;
import com.khachik.explore.Models.Image;
import com.khachik.explore.Fragments.SlideshowDialogFragment;
import com.khachik.explore.Adapters.GalleryAdapter;
import com.khachik.explore.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.util.ArrayList;
public class GalleryActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private static final String endpoint = "https://api.androidhive.info/json/glide.json";
private ArrayList<Image> images;
private ProgressDialog pDialog;
private GalleryAdapter mAdapter;
private RecyclerView recyclerView;
private com.android.volley.RequestQueue queue;
private String title;
private String images_folder;
private Config config;
private String host;
private int port;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
this.title = null;
this.images_folder = null;
} else {
this.title = extras.getString("title");
this.images_folder = extras.getString("images_folder");
}
} else {
this.title = (String) savedInstanceState.getSerializable("title");
this.images_folder = (String) savedInstanceState.getSerializable("images_folder");
}
this.config = new Config();
this.host = config.getHost();
this.port = config.getPort();
recyclerView = (RecyclerView) findViewById(R.id.gallery_recycler_view);
this.queue = Volley.newRequestQueue(this);
pDialog = new ProgressDialog(this);
images = new ArrayList<>();
mAdapter = new GalleryAdapter(getApplicationContext(), images);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getApplicationContext(), 2);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
recyclerView.addOnItemTouchListener(new GalleryAdapter.RecyclerTouchListener(getApplicationContext(), recyclerView, new GalleryAdapter.ClickListener() {
@Override
public void onClick(View view, int position) {
Bundle bundle = new Bundle();
bundle.putSerializable("images", images);
bundle.putInt("position", position);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
SlideshowDialogFragment newFragment = SlideshowDialogFragment.newInstance();
newFragment.setArguments(bundle);
newFragment.show(ft, "slideshow");
}
@Override
public void onLongClick(View view, int position) {
}
}));
fetchImages();
}
@Nullable
public File[] getExternalStorageFiles() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET)
== PackageManager.PERMISSION_GRANTED) {
final File externalStorage = Environment.getExternalStorageDirectory();
if (externalStorage != null) {
return externalStorage.listFiles();
}
}
return null;
}
private void fetchImages() {
pDialog.setMessage("In progress ...");
pDialog.show();
String url;
if (this.images_folder != "" && this.images_folder != null){
url = "http://" + this.host + ":" + this.port + "/images?dirName=" + this.images_folder;
} else {
url = "http://" + this.host + ":" + this.port + "/wallpapers";
}
System.out.println("request - - - " + url);
JsonArrayRequest req = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
pDialog.hide();
images.clear();
for (int i = 0; i < response.length(); i++) {
try {
JSONObject object = response.getJSONObject(i);
Image image = new Image();
image.setName(title);
JSONObject url = object.getJSONObject("url");
image.setSmall(url.getString("small"));
image.setMedium(url.getString("medium"));
image.setLarge(url.getString("large"));
image.setTimestamp(object.getString("timestamp"));
images.add(image);
} catch (JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
}
}
mAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error: " + error.getMessage());
pDialog.hide();
}
});
// Adding request to request queue
//appController.addToRequestQueue(req);
this.queue.add(req);
}
}
|
package old;
import org.junit.Assert;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class TestCSS {
@Test
public void main() throws InterruptedException {
String baseUrl = "https://www.facebook.com/login/identify?ctx=recover";
WebDriver driver = DriverUtils.getDriver();
driver.get(baseUrl);
Thread.sleep(5000);
driver.findElement(By.cssSelector("a[title=\"Go to Facebook home\"]"))
.click();
Thread.sleep(5000);
Assert.assertEquals("same title", "Facebook - log in or sign up" ,driver.getTitle());
driver.close();
}
}
|
package com.jessematty.myapplication;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.InputType;
import android.text.Layout;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.ArrayList;
public class AreaConversions extends Activity {
TextView squareFeet;
TextView squareMiles;
TextView squareMeters;
TextView squareKilometers;
TextView acres;
TextView hectare;
TextView squareInches;
TextView squareMillimeters;
TextView squareCentimeters;
EditText numberField;
Spinner valuesList;
String valueChoice;
Button convert;
double squareFeetNumber;
double squareMilesNumber;
double squareMetersNumber;
double squareKilometersNumber;
double acresNumber;
double hectacreNumber;
double squareInchesNumber;
double squareMillimetersNumber;
double squareCentimetersNumber;
public AreaConversions() {
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
createLayout();
}
public void createLayout(){
squareFeet=new TextView(this);
squareMiles=new TextView(this);
squareMeters=new TextView(this);
squareKilometers=new TextView(this);
acres=new TextView(this);
hectare= new TextView(this);
squareInches= new TextView(this);
squareMillimeters= new TextView(this);
squareCentimeters= new TextView(this);
LinearLayout mainLayout= new LinearLayout(this);
mainLayout.setOrientation(LinearLayout.VERTICAL);
valuesList= new Spinner(this);
ArrayList<String> values= new ArrayList<>();
values.add("Square Inches");
values.add("Square Feet");
values.add("Square Miles");
values.add("Square Millimeters");
values.add("Square Centimeters");
values.add("Square Meters");
values.add("Square Kilometers" );
values.add("Acres");
values.add("Hectacres");
ArrayAdapter<String> adapter= new ArrayAdapter(this, R.layout.textview);
adapter.addAll(values);
valuesList.setAdapter(adapter);
valuesList.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
valueChoice= (String) parent.getItemAtPosition(position);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
convert= new Button(this);
convert.setText("Convert");
convert.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (valueChoice.equals("Square Kilometers")){
setTextViewKilometers();
}
else if (valueChoice.equals("Square Meters")){
setTextViewMeters();
}
else if (valueChoice.equals("Square Centimeters")){
setTextViewCentimeters();
}
else if (valueChoice.equals("Square Millimeters")){
setTextViewMillimeters();
}
else if (valueChoice.equals("Square Miles")){
setTextViewMiles();
}
else if (valueChoice.equals("Square Feet")){
setTextViewFeet();
}
else if (valueChoice.equals("Acres")){
setTextViewAcres();
}
else if (valueChoice.equals("Hectacres")){
setTextViewHectacres();
}
else if (valueChoice.equals("Square Inches")){
setTextViewInches();
}
}
});
numberField= new EditText(this);
numberField.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_CLASS_NUMBER);
LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,100);
LinearLayout enterText= new LinearLayout(this);
enterText.setOrientation(LinearLayout.HORIZONTAL);
enterText.addView(numberField);
enterText.addView(valuesList);
enterText.addView(convert);
mainLayout.addView(enterText);
TextView english= new TextView(this);
english.setText("English Measurements");
english.setTextSize(30);
english.setTextColor(Color.RED);
english.setLayoutParams(params);
english.setGravity(Gravity.CENTER);
mainLayout.addView(english);
squareInches.setLayoutParams(params);
squareInches.setGravity(Gravity.CENTER);
mainLayout.addView(squareInches);
squareFeet.setLayoutParams(params);
squareFeet.setGravity(Gravity.CENTER);
mainLayout.addView(squareFeet);
squareMiles.setLayoutParams(params);
squareMiles.setGravity(Gravity.CENTER);
mainLayout.addView(squareMiles);
acres.setLayoutParams(params);
acres.setGravity(Gravity.CENTER);
mainLayout.addView(acres);
TextView metric= new TextView(this);
metric.setText("Metric Measurements");
metric.setTextSize(30);
metric.setTextColor(Color.GREEN);
metric.setLayoutParams(params);
metric.setGravity(Gravity.CENTER);
mainLayout.addView(metric);
squareMillimeters.setLayoutParams(params);
squareMillimeters.setGravity(Gravity.CENTER);
mainLayout.addView(squareMillimeters);
squareCentimeters.setLayoutParams(params);
squareCentimeters.setGravity(Gravity.CENTER);
mainLayout.addView(squareCentimeters);
squareMeters.setLayoutParams(params);
squareMeters.setGravity(Gravity.CENTER);
mainLayout.addView(squareMeters);
squareKilometers.setLayoutParams(params);
squareKilometers.setGravity(Gravity.CENTER);
mainLayout.addView(squareKilometers);
hectare.setLayoutParams(params);
hectare.setGravity(Gravity.CENTER);
mainLayout.addView(hectare);
ScrollView mainView= new ScrollView(this);
mainView.addView(mainLayout);
setContentView(mainView);
}
public void setTextViewAcres(){
String text =String.valueOf(numberField.getText());
if(text!=null && !text.isEmpty()) {
acresNumber = Double.valueOf(text);
}
else {
acresNumber = 1;
}
squareKilometersNumber=acresNumber*.00404686;
squareFeetNumber=acresNumber*43560;
squareMilesNumber=acresNumber*0.0015625;
squareMetersNumber=acresNumber*4046.86;
hectacreNumber=acresNumber*0.404686;
squareMeters.setText( "Meters: "+ String.valueOf(squareMetersNumber));
squareFeet.setText("Square Feet: "+ String.valueOf(squareFeetNumber));
squareMiles.setText("Square Miles: "+String.valueOf(squareMilesNumber));
hectare.setText("Hectacres: "+String.valueOf(hectacreNumber));
acres.setText("Acres: "+String.valueOf(acresNumber));
squareKilometers.setText(" Square Kilometers: "+String.valueOf(squareKilometersNumber));
squareCentimeters.setText("n/a");
squareInches.setText("n/a");
squareMillimeters.setText("n/a");
}
public void setTextViewKilometers(){
String text =String.valueOf(numberField.getText());
if(text!=null && !text.isEmpty()) {
squareKilometersNumber = Double.valueOf(text);
}
else {
squareKilometersNumber = 1;
}
acresNumber=squareKilometersNumber*247.105;
squareFeetNumber=squareKilometersNumber*1.076e+7;
squareMilesNumber=squareKilometersNumber*0.386102;
squareMetersNumber=squareKilometersNumber*1000000;
hectacreNumber=squareKilometersNumber*100;
squareMeters.setText( "Meters: "+ String.valueOf(squareMetersNumber));
squareFeet.setText("Square Feet: "+ String.valueOf(squareFeetNumber));
squareMiles.setText("SquareMiles: "+String.valueOf(squareMilesNumber));
hectare.setText("Hectacres: "+String.valueOf(hectacreNumber));
acres.setText("Acres: "+String.valueOf(acresNumber));
squareKilometers.setText(" Square Kilometers: "+String.valueOf(squareKilometersNumber));
squareCentimeters.setText("n/a");
squareInches.setText("n/a");
squareMillimeters.setText("n/a");
}
public void setTextViewMiles(){
String text =String.valueOf(numberField.getText());
if(text!=null && !text.isEmpty()) {
squareMilesNumber = Double.valueOf(text);
}
else {
squareMilesNumber = 1;
}
squareKilometersNumber=squareMilesNumber*2.58999;
squareFeetNumber=squareMilesNumber*2.788e+7;
acresNumber=squareMilesNumber*640;
squareMetersNumber=squareMilesNumber*2.59e+6;
hectacreNumber=squareMilesNumber*258.999;
squareMeters.setText( "Meters: "+ String.valueOf(squareMetersNumber));
squareKilometers.setText(" Square Kilometers: "+String.valueOf(squareKilometersNumber));
squareFeet.setText("Square Feet: "+ String.valueOf(squareFeetNumber));
squareMiles.setText("SquareMiles: "+String.valueOf(squareMilesNumber));
hectare.setText("Hectacres: "+String.valueOf(hectacreNumber));
acres.setText("Acres: "+String.valueOf(acresNumber));
squareCentimeters.setText("n/a");
squareInches.setText("n/a");
squareMillimeters.setText("n/a");
}
public void setTextViewFeet(){
String text =String.valueOf(numberField.getText());
if(text!=null && !text.isEmpty()) {
squareFeetNumber = Double.valueOf(text);
}
else {
squareFeetNumber = 1;
}
squareKilometersNumber=squareFeetNumber*9.2903e-8;
squareMilesNumber=squareFeetNumber*3.58701e-8;
acresNumber=squareFeetNumber*2.29568e-5;
squareMetersNumber=squareFeetNumber*0.092903;
hectacreNumber=squareFeetNumber*9.2903e-6;
squareMeters.setText( "Meters: "+ String.valueOf(squareMetersNumber));
squareKilometers.setText(" Square Kilometers: "+String.valueOf(squareKilometersNumber));
squareFeet.setText("Square Feet: "+ String.valueOf(squareFeetNumber));
squareMiles.setText("SquareMiles: "+String.valueOf(squareMilesNumber));
hectare.setText("Hectacres: "+String.valueOf(hectacreNumber));
acres.setText("Acres: "+String.valueOf(acresNumber));
}
public void setTextViewMeters(){
String text =String.valueOf(numberField.getText());
if(text!=null && !text.isEmpty()) {
squareMetersNumber = Double.valueOf(text);
}
else {
squareMetersNumber = 1;
}
squareKilometersNumber=squareMetersNumber*1e-6;
squareFeetNumber=squareMetersNumber*10.7639;
acresNumber=squareMetersNumber*0.000247105;
squareMilesNumber=squareMetersNumber*3.86102e-7;
hectacreNumber=squareMetersNumber*0.0001;
squareMeters.setText( "Meters: "+ String.valueOf(squareMetersNumber));
squareKilometers.setText(" Square Kilometers: "+String.valueOf(squareKilometersNumber));
squareFeet.setText("Square Feet: "+ String.valueOf(squareFeetNumber));
squareMiles.setText("SquareMiles: "+String.valueOf(squareMilesNumber));
hectare.setText("Hectacres: "+String.valueOf(hectacreNumber));
acres.setText("Acres: "+String.valueOf(acresNumber));
}
public void setTextViewHectacres(){
String text =String.valueOf(numberField.getText());
if(text!=null && !text.isEmpty()) {
hectacreNumber = Double.valueOf(text);
}
else {
hectacreNumber = 1;
}
squareKilometersNumber=hectacreNumber*0.01;
squareFeetNumber=hectacreNumber*107639;
squareMetersNumber=hectacreNumber*10000;
acresNumber=hectacreNumber*2.47105;
squareMilesNumber=hectacreNumber*0.00386102;
squareMeters.setText( "Meters: "+ String.valueOf(squareMetersNumber));
squareKilometers.setText(" Square Kilometers: "+String.valueOf(squareKilometersNumber));
squareFeet.setText("Square Feet: "+ String.valueOf(squareFeetNumber));
squareMiles.setText("SquareMiles: "+String.valueOf(squareMilesNumber));
hectare.setText("Hectacres: "+String.valueOf(hectacreNumber));
acres.setText("Acres: "+String.valueOf(acresNumber));
squareCentimeters.setText("n/a");
squareInches.setText("n/a");
squareMillimeters.setText("n/a");
}
public void setTextViewInches(){
String text =String.valueOf(numberField.getText());
if(text!=null && !text.isEmpty()) {
squareInchesNumber = Double.valueOf(text);
}
else {
squareInchesNumber = 1;
}
squareFeetNumber=squareInchesNumber*0.00694444;
squareMillimetersNumber=squareInchesNumber*645.16;
squareCentimetersNumber=squareInchesNumber*6.4516;
squareMetersNumber=squareInchesNumber*0.00064516;
squareFeet.setText("Square Feet: "+ String.valueOf(squareFeetNumber));
squareMillimeters.setText("Square Millimeters: "+String.valueOf(squareMillimetersNumber));
squareCentimeters.setText("Square Centimeters: "+String.valueOf(squareCentimetersNumber));
squareMeters.setText("Square Meters: "+ String.valueOf(squareMetersNumber));
squareInches.setText("Square Inches: "+String.valueOf(squareInchesNumber));
squareMiles.setText("n/a");
acres.setText("n/a");
hectare.setText("n/a");
squareKilometers.setText("n/a");
}
public void setTextViewMillimeters(){
String text =String.valueOf(numberField.getText());
if(text!=null && !text.isEmpty()) {
squareMillimetersNumber = Double.valueOf(text);
}
else {
squareMillimetersNumber = 1;
}
squareFeetNumber=squareMillimetersNumber*1.07639e-5;
squareCentimetersNumber=squareMillimetersNumber*0.01;
squareInchesNumber=squareMillimetersNumber*0.00155;
squareMetersNumber=squareMillimetersNumber*1e-6;
squareFeet.setText("Square Feet: "+ String.valueOf(squareFeetNumber));
squareMillimeters.setText("Square Millimeters: "+String.valueOf(squareMillimetersNumber));
squareCentimeters.setText("Square Centimeters: "+String.valueOf(squareCentimetersNumber));
squareMeters.setText("Square Meters: "+ String.valueOf(squareMetersNumber));
squareInches.setText("Square Inches: "+String.valueOf(squareInchesNumber));
squareMiles.setText("n/a");
acres.setText("n/a");
hectare.setText("n/a");
squareKilometers.setText("n/a");
}
public void setTextViewCentimeters(){
String text =String.valueOf(numberField.getText());
if(text!=null && !text.isEmpty()) {
squareCentimetersNumber = Double.valueOf(text);
}
else {
squareCentimetersNumber = 1;
}
squareFeetNumber=squareCentimetersNumber*0.00107639;
squareMillimetersNumber=squareCentimetersNumber*100;
squareInchesNumber=squareCentimetersNumber*0.155;
squareMetersNumber=squareCentimetersNumber*0.0001;
squareFeet.setText("Square Feet: "+ String.valueOf(squareFeetNumber));
squareMillimeters.setText("Square Millimeters: "+String.valueOf(squareMillimetersNumber));
squareCentimeters.setText("Square Centimeters: "+String.valueOf(squareCentimetersNumber));
squareMeters.setText("Square Meters: "+ String.valueOf(squareMetersNumber));
squareInches.setText("Square Inches: "+String.valueOf(squareInchesNumber));
squareMiles.setText("n/a");
acres.setText("n/a");
hectare.setText("n/a");
squareKilometers.setText("n/a");
}
}
|
package com.service.employee.dao;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import com.service.employee.domain.EmployeeExperienceDetails;
public interface IEmployeeExperienceDao extends JpaRepository<EmployeeExperienceDetails, Long> {
@Query("SELECT t FROM EmployeeExperienceDetails t WHERE t.employee.empId = ?1 Order by t.joiningDate desc")
List<EmployeeExperienceDetails> findAllByEmpId(long empId);
}
|
/*
* 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 com.github.somi92.seecsk.model.tables.trening;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
/**
*
* @author milos
*/
public class PrisustvaTableRenderer extends DefaultTableCellRenderer {
private JCheckBox jchbPrisutan;
private JPanel panel;
public PrisustvaTableRenderer() {
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
panel = new JPanel(new BorderLayout());
jchbPrisutan = new JCheckBox();
panel.setBackground(Color.white);
jchbPrisutan.setSelected((boolean) value);
jchbPrisutan.setBackground(Color.white);
JLabel lbl1 = new JLabel(" ");
panel.add(lbl1, BorderLayout.WEST);
panel.add(jchbPrisutan, BorderLayout.CENTER);
return panel;
}
}
|
import jdk.javadoc.internal.tool.resources.javadoc;
/*
* @lc app=leetcode id=70 lang=java
*
* [70] Climbing Stairs
*/
// @lc code=start
class Solution {
public int climbStairs(int n) {
// int[] memo = new int[n];
// return countStepsMemo(0, n, memo);
return countSteps(n);
}
public int countStepsMemo(int currentStep, int destinationStep, int[] memo){
if (currentStep > destinationStep){
return 0;
} else if (currentStep == destinationStep) {
return 1;
} else if (memo[currentStep] == 0) {
memo[currentStep] = countStepsMemo(currentStep + 1, destinationStep, memo) + countStepsMemo(currentStep + 2, destinationStep, memo);
}
return memo[currentStep];
}
public int countSteps(int destinationStep){
if (destinationStep == 1){
return 1;
}
int[] table = new int[destinationStep + 1];
table[0] = 0;
table[1] = 1;
table[2] = 2;
for (int i = 3; i <= destinationStep; ++i) {
table[i] = table[i -1] + table[i -2];
}
return table[destinationStep];
}
}
// @lc code=end
|
package com.tuanhk.splashscreen;
import android.support.annotation.Nullable;
import com.tuanhk.ui.activity.BaseActivity;
import com.tuanhk.ui.fragment.BaseFragment;
public class SplashScreenActivity extends BaseActivity {
@Nullable
@Override
protected BaseFragment getFragmentToHost() {
return SplashScreenFragment.newInstance(getIntent().getExtras());
}
}
|
package vn.m2m.common.models.forms;
public class SearchConditionForm { //ho tro view
private String fieldName;
private String fieldType; // Date, Int, String
private String fieldValue;
private String compQueryOp; // eq, ne, gt, lt, gte , lte, like, nlike
public SearchConditionForm() {
this.fieldName = "";
this.fieldType = "";
this.fieldValue = "";
this.compQueryOp = "";
}
public String getFieldName() {
return fieldName;
}
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
public String getFieldType() {
return fieldType;
}
public void setFieldType(String fieldType) {
this.fieldType = fieldType;
}
public String getFieldValue() {
return fieldValue;
}
public void setFieldValue(String fieldValue) {
this.fieldValue = fieldValue;
}
public String getCompQueryOp() {
return compQueryOp;
}
public void setCompQueryOp(String compQueryOp) {
this.compQueryOp = compQueryOp;
}
}
|
package com.jvmless.threecardgame.domain.shuffle;
import com.jvmless.threecardgame.domain.game.GameId;
public interface GameMovesRepository {
GameMoves findByGameId(GameId gameId);
void save(GameMoves gameMoves);
}
|
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.tiles.readers;
import androidx.annotation.NonNull;
import androidx.annotation.RestrictTo;
import androidx.annotation.RestrictTo.Scope;
import androidx.wear.tiles.TileAddEventData;
import androidx.wear.tiles.TileEnterEventData;
import androidx.wear.tiles.TileLeaveEventData;
import androidx.wear.tiles.TileRemoveEventData;
import androidx.wear.tiles.proto.EventProto;
import androidx.wear.tiles.protobuf.ExtensionRegistryLite;
import androidx.wear.tiles.protobuf.InvalidProtocolBufferException;
/** Event readers for androidx.wear.tiles' Parcelable classes. */
public class EventReaders {
private EventReaders() {}
/** Reader for Tile add event parameters. */
public static class TileAddEvent {
@SuppressWarnings("unused")
private final EventProto.TileAddEvent mProto;
private TileAddEvent(@NonNull EventProto.TileAddEvent proto) {
this.mProto = proto;
}
/**
* Create an instance of this reader from a given {@link TileAddEventData} instance.
*
* @hide
*/
@RestrictTo(Scope.LIBRARY)
@NonNull
public static TileAddEvent fromParcelable(@NonNull TileAddEventData parcelable) {
try {
return new TileAddEvent(
EventProto.TileAddEvent.parseFrom(
parcelable.getContents(),
ExtensionRegistryLite.getEmptyRegistry()));
} catch (InvalidProtocolBufferException ex) {
throw new IllegalArgumentException(
"Passed TileAddEventData did not contain a valid proto payload", ex);
}
}
}
/** Reader for Tile remove event parameters. */
public static class TileRemoveEvent {
@SuppressWarnings("unused")
private final EventProto.TileRemoveEvent mProto;
private TileRemoveEvent(@NonNull EventProto.TileRemoveEvent proto) {
this.mProto = proto;
}
/**
* Create an instance of this reader from a given {@link TileRemoveEventData} instance.
*
* @hide
*/
@RestrictTo(Scope.LIBRARY)
@NonNull
public static TileRemoveEvent fromParcelable(@NonNull TileRemoveEventData parcelable) {
try {
return new TileRemoveEvent(
EventProto.TileRemoveEvent.parseFrom(
parcelable.getContents(),
ExtensionRegistryLite.getEmptyRegistry()));
} catch (InvalidProtocolBufferException ex) {
throw new IllegalArgumentException(
"Passed TileRemoveEventData did not contain a valid proto payload", ex);
}
}
}
/** Reader for Tile enter event parameters. */
public static class TileEnterEvent {
@SuppressWarnings("unused")
private final EventProto.TileEnterEvent mProto;
private TileEnterEvent(@NonNull EventProto.TileEnterEvent proto) {
this.mProto = proto;
}
/**
* Create an instance of this reader from a given {@link TileEnterEventData} instance.
*
* @hide
*/
@RestrictTo(Scope.LIBRARY)
@NonNull
public static TileEnterEvent fromParcelable(@NonNull TileEnterEventData parcelable) {
try {
return new TileEnterEvent(
EventProto.TileEnterEvent.parseFrom(
parcelable.getContents(),
ExtensionRegistryLite.getEmptyRegistry()));
} catch (InvalidProtocolBufferException ex) {
throw new IllegalArgumentException(
"Passed TileEnterEventData did not contain a valid proto payload", ex);
}
}
}
/** Reader for a Tile leave event parameters. */
public static class TileLeaveEvent {
@SuppressWarnings("unused")
private final EventProto.TileLeaveEvent mProto;
private TileLeaveEvent(@NonNull EventProto.TileLeaveEvent proto) {
this.mProto = proto;
}
/**
* Create an instance of this reader from a given {@link TileLeaveEventData} instance.
*
* @hide
*/
@RestrictTo(Scope.LIBRARY)
@NonNull
public static TileLeaveEvent fromParcelable(@NonNull TileLeaveEventData parcelable) {
try {
return new TileLeaveEvent(
EventProto.TileLeaveEvent.parseFrom(
parcelable.getContents(),
ExtensionRegistryLite.getEmptyRegistry()));
} catch (InvalidProtocolBufferException ex) {
throw new IllegalArgumentException(
"Passed TileLeaveEventData did not contain a valid proto payload", ex);
}
}
}
}
|
package com.pybeta.daymatter.tool;
import android.graphics.Bitmap;
import android.graphics.Matrix;
public class ImageTool {
/**
* 修改Bitmap为制定宽高的Bitmap
* @param bitmap
* @param newWidth
* @param newHeight
* @return
*/
public static Bitmap getScaleImg(Bitmap bitmap, int newWidth, int newHeight) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
// 计算缩放比例
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// 取得想要缩放的matrix参数
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
// 得到新的图片
Bitmap resultBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix,true);
bitmap.recycle();
bitmap = null;
return resultBitmap;
}
}
|
package net.helpscout.sample.beacon;
import android.annotation.SuppressLint;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import com.helpscout.beacon.Beacon;
import com.helpscout.beacon.internal.core.model.BeaconConfigOverrides;
import com.helpscout.beacon.internal.core.model.PreFilledForm;
import com.helpscout.beacon.ui.BeaconActivity;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.helpscout.sample.beacon.customisation.R;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class CustomisationActivity extends AppCompatActivity {
//for sample this is hardcoded to a single user. But in your code these details would be on per user basis.
private static final String secureModeUserEmail = "beacon_secure@scottyab.com";
private static final String secureModeUserSignature = "8235545a15c6f41b64e3c47e5c94d3cfb6c6d297e87af88dec953a73042a7b92";
// Replace this list with max five article string ids from your docs
private static final List<String> articleSuggestionsOverride = new ArrayList<>();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_customisation);
//typically this should be set after successfully logging on to your service
Beacon.login(secureModeUserEmail);
addPreFilledData();
addUserAttributes();
addArticlesSuggestionOverride();
findViewById(R.id.action_open_beacon).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
setColorOverrides(false);
openBeaconInSecureMode();
}
});
findViewById(R.id.action_open_beacon_color).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
setColorOverrides(true);
openBeaconInBasicMode();
}
});
}
private void setColorOverrides(boolean enabled) {
if (enabled) {
@SuppressLint("ResourceType") String colorHexString = getResources().getString(R.color.primary);
Beacon.setConfigOverrides(new BeaconConfigOverrides(null, null, null, null, colorHexString));
} else {
Beacon.setConfigOverrides(new BeaconConfigOverrides(null, null, null, null, null));
}
}
private void openBeaconInBasicMode() {
BeaconActivity.open(this);
}
private void openBeaconInSecureMode() {
BeaconActivity.openInSecureMode(this, secureModeUserSignature);
}
/**
* Illustrates how to use the user attributes
*/
private void addUserAttributes() {
Beacon.addAttributeWithKey("App version", getAppVersion());
Beacon.addAttributeWithKey("OS version", Build.VERSION.RELEASE);
Beacon.addAttributeWithKey("Device", Build.MANUFACTURER + " " + Build.MODEL);
}
/**
* Pre-fill the Contact us form
*/
private void addPreFilledData() {
Map<Integer, String> prePopulatedCustomFields = new HashMap<>();
prePopulatedCustomFields.put(123, "TEST");
Beacon.addPreFilledForm(new PreFilledForm(
"My Secure user Scott",
"Bug report for app",
"Please include steps to reproduce the issue",
prePopulatedCustomFields
));
}
/**
* Add suggested articles
*/
private void addArticlesSuggestionOverride() {
Beacon.setOverrideSuggestedArticles(articleSuggestionsOverride);
}
private String getAppVersion() {
try {
PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
return pInfo.versionName;
} catch (PackageManager.NameNotFoundException e) {
throw new RuntimeException(e);
}
}
}
|
package myproject1;
public class HelloWorld {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Hello world 123");
System.out.println("Hello user");
}
}
|
package by.dt.web.controller;
import by.dt.entity.Category;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping(path = "/user-storage/v1", produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public class CategoryController {
@ApiOperation(value = "Запрос на получение всех категорий", notes = "Возвращает список всех категорий", produces = MediaType.APPLICATION_JSON_VALUE
, consumes = MediaType.APPLICATION_JSON_VALUE)
@RequestMapping(path = "/categories", method = RequestMethod.GET)
public List<Category> getAllCategories() {
//TODO : Implement logic for getAllCategories
return null;
}
@ApiOperation(value = "Запрос на получение всех главных категорий", notes = "Возвращает список всех главных категорий", produces = MediaType.APPLICATION_JSON_VALUE
, consumes = MediaType.APPLICATION_JSON_VALUE)
@RequestMapping(path = "/mainCategories", method = RequestMethod.GET)
public List<Category> getMainCategories() {
//TODO : Implement logic for getMainCategories
return null;
}
}
|
package com.avogine.junkyard.util;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import org.lwjgl.BufferUtils;
import org.lwjgl.assimp.AIFile;
import org.lwjgl.assimp.AIFileIO;
import org.lwjgl.system.MemoryUtil;
public class JarFile extends AIFile {
private static AtomicInteger nextId = new AtomicInteger(1);
private static Map<String, JarFile> fileMap = new HashMap<>();
private String id;
private String path;
private ByteBuffer buf;
private OutputStream out;
public JarFile(String path) {
super(BufferUtils.createByteBuffer(SIZEOF));
this.path = path;
ReadProc(JarFile::read);
WriteProc(JarFile::write);
TellProc(JarFile::tell);
FileSizeProc(JarFile::fileSize);
SeekProc(JarFile::seek);
FlushProc(JarFile::flush);
id = Integer.toString(nextId.getAndIncrement());
fileMap.put(id, this);
UserData(MemoryUtil.memAddress(MemoryUtil.memUTF8(id, true)));
try {
byte[] bytes = ClassLoader.getSystemResourceAsStream(this.path).readAllBytes();
buf = MemoryUtil.memAlloc(bytes.length).put(bytes).flip();
} catch (Exception ex) {
throw new RuntimeException("Error trying to read " + path, ex);
}
}
@Override
public String toString() {
return String.format("id: %s, path: %s", id, path);
}
@Override
public void close() {
if (out != null) {
try {
out.close(); out = null;
} catch (IOException ex) {
ex.printStackTrace();
}
}
fileMap.remove(id);
MemoryUtil.memFree(buf);
super.close();
}
private static JarFile lookup(long pFile) {
AIFile aiFile = AIFile.create(pFile);
String idStr = MemoryUtil.memUTF8(aiFile.UserData());
return fileMap.get(idStr);
}
private static long read(long pFile, long pBuffer, long size, long count) {
JarFile jarFile = lookup(pFile);
System.out.printf("READ { size: %d, count: %d }\n", size, count);
try {
long numBytesToRead = size * count;
int i = 0;
ByteBuffer buf = jarFile.buf;
while (i < numBytesToRead && buf.hasRemaining()) {
MemoryUtil.memPutByte(pBuffer + i, buf.get());
i++;
}
System.out.printf("%d bytes read\n", i);
return i;
} catch (Exception ex) {
ex.printStackTrace();
return 0;
}
}
private static long tell(long pFile) {
JarFile jarFile = lookup(pFile);
System.out.printf("TELL { curPos: %d }\n", jarFile.buf.position());
// Apparently "tell" means report the current byte position
return jarFile.buf.position();
}
private static long fileSize(long pFile) {
JarFile jarFile = lookup(pFile);
System.out.printf("SIZE { size: %d }\n", jarFile.buf.limit());
return jarFile.buf.limit();
}
private static int seek(long pFile, long offset, int origin) {
JarFile jarFile = lookup(pFile);
System.out.printf("SEEK { offset: %d, origin: %d }\n", offset, origin);
jarFile.buf.position((int)offset);
return 0; // 0 means success, -1 means failure
}
// Write operations are not supported for jar files so these are noops
private static long write(long pFile, long pBuffer, long memB, long count) {
System.out.printf("WRITE { memB: %d, count %d }\n", memB, count);
// Return the count to pretend like we wrote the bytes
return count;
}
private static void flush(long pFile) {
System.out.println("FLUSH");
}
private static class JarFileIO extends AIFileIO {
public JarFileIO() {
super(BufferUtils.createByteBuffer(SIZEOF));
OpenProc(JarFileIO::open);
CloseProc(JarFileIO::close);
}
private static long open(long pFileIO, long fileName, long openMode) {
String name = MemoryUtil.memUTF8(fileName);
String mode = MemoryUtil.memUTF8(openMode);
JarFile jarFile = new JarFile(name);
System.out.printf("OPEN(%s) { mode: %s }\n", jarFile, mode);
return jarFile.address();
}
private static void close(long pFileIO, long pFile) {
JarFile jarFile = lookup(pFile);
System.out.printf("CLOSE(%s)\n", jarFile);
jarFile.close();
}
}
public static AIFileIO createFileIO() {
return new JarFileIO();
}
}
|
package com.mrice.txl.appthree.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.mrice.txl.appthree.R;
import com.mrice.txl.appthree.ui.me.PageOne;
import java.util.List;
/**
* Created by app on 2017/10/11.
*/
public class FOneAdapter extends BaseAdapter {
private Context context;
private List<PageOne> list;
private int[] arrs = new int[]{R.drawable.d10, R.drawable.d9, R.drawable.d8, R.drawable.d7, R.drawable.d6, R.drawable.d5, R.drawable.d4, R.drawable.d3, R.drawable.d2, R.drawable.d};
ViewHolder viewHolder;
public FOneAdapter(Context context, List<PageOne> list) {
this.context = context;
this.list = list;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int i) {
return list.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null) {
view = LayoutInflater.from(context).inflate(R.layout.f_one_item, null);
viewHolder = new ViewHolder();
viewHolder.img = (ImageView) view.findViewById(R.id.img);
viewHolder.title = (TextView) view.findViewById(R.id.title);
viewHolder.time = (TextView) view.findViewById(R.id.time);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.img.setImageResource(arrs[i]);
viewHolder.title.setText(list.get(i).getTitle());
viewHolder.time.setText(list.get(i).getTime());
return view;
}
public final class ViewHolder {
ImageView img;
TextView title;
TextView content;
TextView time;
TextView source;
}
}
|
package com.demo.withdrawal.util;
import java.util.LinkedHashMap;
import java.util.Map;
public class LruCache<K,V> extends LinkedHashMap<K,V>{
public static final int CACHE_SIZE = 300;
public LruCache(int initialCapacity, float loadFactor, boolean accessOrder) {
super(initialCapacity, loadFactor, accessOrder);
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > CACHE_SIZE;
}
public static <K, V> LruCache<K, V> newInstance() {
return new LruCache<K, V>(CACHE_SIZE, 0.75f, true);
}
}
|
package net.thumbtack.asurovenko.trainee;
import net.thumbtack.asurovenko.trainee.exceptions.TraineeException;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class TraineeTest {
@Test
public void testTraineeEmpty() throws TraineeException {
Trainee trainee = new Trainee();
assertEquals("name", trainee.getName());
assertEquals("surname", trainee.getSurname());
assertEquals(1, trainee.getVal());
}
@Test
public void testTrainee() throws TraineeException {
Trainee trainee = new Trainee("Alexey", "Surovenko", 4);
assertEquals("Alexey", trainee.getName());
assertEquals("Surovenko", trainee.getSurname());
assertEquals(4, trainee.getVal());
}
@Test(expected = TraineeException.class)
public void testTraineeExceptionString1() throws TraineeException {
new Trainee("AbcRe", new String(""), 4);
}
@Test(expected = TraineeException.class)
public void testTraineeExceptionString2() throws TraineeException {
new Trainee(" ", "Qweas", 4);
}
@Test(expected = TraineeException.class)
public void testTraineeExceptionNullString() throws TraineeException {
new Trainee(null, "Qweas", 4);
}
@Test(expected = TraineeException.class)
public void testTraineeExceptionInt() throws TraineeException {
new Trainee("AbcRe", "IthfYd", 6);
}
// 4.18
@Test
public void testJSON() throws TraineeException {
Trainee trainee = new Trainee("name", "surname", 4);
String jsonTraineeString = trainee.toJson();
Trainee trainee2 = Trainee.fromJson(jsonTraineeString);
assertEquals(trainee2, trainee);
assertEquals("{\"name\":\"name\",\"surname\":\"surname\",\"val\":4}", jsonTraineeString);
}
} |
package com.ng.ngcommon.ui.activity;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import com.ng.ngcommon.bean.event.MessageEvent;
import com.ng.ngcommon.ui.BaseAppManager;
import com.ng.ngcommon.util.LogUtils;
import com.ng.ngcommon.widget.loading.VaryViewHelperController;
import com.ng.ngcommon.widget.net.NetChangeObserver;
import com.ng.ngcommon.widget.net.NetStateReceiver;
import com.ng.ngcommon.widget.net.NetUtils;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import butterknife.ButterKnife;
/**
* Created by jiangzn on 16/11/23.
*/
public abstract class BaseFragmentActivity extends FragmentActivity {
/**
* 屏幕参数
*/
protected int mScreenWidth = 0;
protected int mScreenHeight = 0;
protected float mScreenDensity = 0.0f;
/**
* 上下文
*/
protected Context mContext = null;
/**
* 联网状态
*/
protected NetChangeObserver mNetChangeObserver = null;
/**
* 加载视图控制器
* loading view controller
*/
protected VaryViewHelperController mVaryViewHelperController = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//设置沉浸式标题栏
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// getWindow().addFlags(
// WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// getWindow().addFlags(
// WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
// }
BaseAppManager.getInstance().addActivity(this);
init();
}
private void init() {
BaseAppManager.getInstance().addActivity(this);
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
mScreenDensity = displayMetrics.density;
mScreenHeight = displayMetrics.heightPixels;
mScreenWidth = displayMetrics.widthPixels;
if (getContentViewLayoutID() != 0) {
setContentView(getContentViewLayoutID());
} else {
throw new IllegalArgumentException("You must return a right contentView layout resource Id");
}
mNetChangeObserver = new NetChangeObserver() {
@Override
public void onNetConnected(NetUtils.NetType type) {
super.onNetConnected(type);
if (isNetWorkConnected == false) {
onNetworkConnected(type);
} else {
if (!NetUtils.isNetworkConnected(BaseFragmentActivity.this)) {
judgeNetwork();
}
}
}
@Override
public void onNetDisConnect() {
super.onNetDisConnect();
if (isNetWorkConnected == true) {
onNetworkDisConnected();
} else {
if (NetUtils.isNetworkConnected(BaseFragmentActivity.this)) {
judgeNetwork();
}
}
}
};
NetStateReceiver.registerObserver(mNetChangeObserver);
//判断网络情况
judgeNetwork();
}
private void judgeNetwork() {
if (NetUtils.isNetworkConnected(this)) {
isNetWorkConnected = true;
//LogUtils.d("now_isNetWorkConnected:" + isNetWorkConnected);
initViewsAndEvents();
} else {
isNetWorkConnected = false;
//LogUtils.d("now_isNetWorkConnected:" + isNetWorkConnected);
onNetworkDisConnected();
}
}
/**
* network connected
*/
protected void onNetworkConnected(NetUtils.NetType type) {
LogUtils.d("onNetworkConnected");
if (getRootView() != null) {
toggleNetworkError(false, null);
toggleShowLoading(false, null);
initViewsAndEvents();
}
}
private static boolean isNetWorkConnected = false;
/**
* network disconnected
*/
protected void onNetworkDisConnected() {
LogUtils.d("onNetworkDisConnected");
if (getRootView() != null) {
getRootView().setVisibility(View.VISIBLE);
toggleNetworkError(true, new View.OnClickListener() {
@Override
public void onClick(View v) {
judgeNetwork();
}
});
}
}
@Override
public void setContentView(int layoutResID) {
super.setContentView(layoutResID);
ButterKnife.bind(this);
if (null != getLoadingTargetView()) {
mVaryViewHelperController = new VaryViewHelperController(getLoadingTargetView());
} else if (null != getRootView()) {
mVaryViewHelperController = new VaryViewHelperController(getRootView());
}
}
/**
* 得到视图高度
*
* @param v
* @return
*/
protected int getViewHeight(View v) {
int intw = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
int inth = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
v.measure(intw, inth);
return v.getMeasuredHeight();
}
/**
* bind layout resource file
*
* @return id of layout resource
*/
protected abstract int getContentViewLayoutID();
/**
* 用于Butterknife 的onclick方法绑定
*
* @param view
*/
protected abstract void onClick(View view);
/**
* is bind eventBus
*
* @return
*/
protected abstract boolean isBindEventBusHere();
/**
* init all views and add events
*/
protected abstract void initViewsAndEvents();
protected abstract View getLoadingTargetView();
@Override
protected void onDestroy() {
super.onDestroy();
ButterKnife.unbind(this);
NetStateReceiver.removeRegisterObserver(mNetChangeObserver);
if (isBindEventBusHere()) {
EventBus.getDefault().unregister(this);
}
}
/**
* toggle show loading
*
* @param toggle
*/
protected void toggleShowLoading(boolean toggle, String msg) {
if (null == mVaryViewHelperController) {
throw new IllegalArgumentException("You must return a right target view for loading");
}
if (toggle) {
mVaryViewHelperController.showLoading(msg);
} else {
mVaryViewHelperController.restore();
}
}
/**
* toggle show empty
*
* @param toggle
*/
protected void toggleShowEmpty(boolean toggle, String msg, View.OnClickListener onClickListener) {
if (null == mVaryViewHelperController) {
throw new IllegalArgumentException("You must return a right target view for loading");
}
if (toggle) {
mVaryViewHelperController.showEmpty(msg, onClickListener);
} else {
mVaryViewHelperController.restore();
}
}
/**
* toggle show error
*
* @param toggle
*/
protected void toggleShowError(boolean toggle, String msg, View.OnClickListener onClickListener) {
if (null == mVaryViewHelperController) {
throw new IllegalArgumentException("You must return a right target view for loading");
}
if (toggle) {
mVaryViewHelperController.showError(msg, onClickListener);
} else {
mVaryViewHelperController.restore();
}
}
/**
* toggle show network error
*
* @param toggle
*/
protected void toggleNetworkError(boolean toggle, View.OnClickListener onClickListener) {
if (null == mVaryViewHelperController) {
throw new IllegalArgumentException("You must return a right target view for loading");
}
if (toggle) {
mVaryViewHelperController.showNetworkError(onClickListener);
} else {
mVaryViewHelperController.restore();
}
}
protected View getRootView() {
View group = ((ViewGroup) this.findViewById(android.R.id.content)).getChildAt(0);
//LogUtil.d(this,"----"+group.getClass().getSimpleName());
return group;
}
/**
* 隐藏软键盘
*/
public void hideKeyboard() {
if (getWindow().getAttributes(). softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN ) {
InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE );
if (getCurrentFocus() != null)
manager.hideSoftInputFromWindow(getCurrentFocus()
.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS );
}
}
public void onResume() {
super.onResume();
}
public void onPause() {
super.onPause();
}
@Override
protected void onStart() {
if (!EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().register(this);
}
super.onStart();
}
@Subscribe
public void onMessageEvent(MessageEvent event) {
LogUtils.d("BaseAty收到了");
onGetEvent(event);
}
protected abstract void onGetEvent(MessageEvent event);
}
|
package com.jk.jkproject.ui.adapter;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.facebook.drawee.view.SimpleDraweeView;
import com.jk.jkproject.R;
import com.jk.jkproject.ui.activity.TeamDetailsActivity;
import com.jk.jkproject.ui.entity.TeamCenterInfo;
import com.jk.jkproject.ui.widget.recyclerview.BaseWrapperRecyclerAdapter;
import com.jk.jkproject.ui.widget.recyclerview.ClickableViewHolder;
import com.jk.jkproject.ui.widget.recyclerview.OnRecyclerItemClickListener;
import com.jk.jkproject.utils.FuncUtils;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
public class TeamSearchListAdapter extends BaseWrapperRecyclerAdapter<TeamCenterInfo.DataBean, TeamSearchListAdapter.ItemViewHolder> implements OnRecyclerItemClickListener {
private Context context;
private List<TeamCenterInfo.DataBean> list = new ArrayList<TeamCenterInfo.DataBean>();
private LayoutInflater mLayoutInflater;
public TeamSearchListAdapter(Context paramContext, List<TeamCenterInfo.DataBean> paramList) {
this.context = paramContext;
this.mLayoutInflater = LayoutInflater.from(paramContext);
appendToList(paramList);
}
public void onBindItemViewHolder(ItemViewHolder paramItemViewHolder, int paramInt) {
this.list = getList();
if (this.list.size() > 0) {
final TeamCenterInfo.DataBean dataBean = this.list.get(paramInt);
if (dataBean != null) {
if (!TextUtils.isEmpty(dataBean.getTm_name())) {
paramItemViewHolder.tvTeamName.setText(dataBean.getTm_name());
} else {
paramItemViewHolder.tvTeamName.setText("--");
}
if (dataBean.getTm_count() != 0) {
paramInt = dataBean.getTm_count();
TextView textView = paramItemViewHolder.tvMembers;
StringBuilder stringBuilder1 = new StringBuilder();
stringBuilder1.append("成员");
stringBuilder1.append(String.valueOf(paramInt));
textView.setText(stringBuilder1.toString());
} else {
paramItemViewHolder.tvMembers.setText("0");
}
if (!TextUtils.isEmpty(dataBean.getCaptain_name())) {
StringBuilder stringBuilder1 = new StringBuilder();
stringBuilder1.append(dataBean.getCaptain_name());
stringBuilder1.append("");
String str = stringBuilder1.toString();
paramItemViewHolder.tvUserName.setText(str);
} else {
paramItemViewHolder.tvUserName.setText("--");
}
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(dataBean.getId());
stringBuilder.append("");
if (!TextUtils.isEmpty(stringBuilder.toString())) {
stringBuilder = new StringBuilder();
stringBuilder.append(dataBean.getId());
stringBuilder.append("");
String str = stringBuilder.toString();
TextView textView = paramItemViewHolder.tvId;
stringBuilder = new StringBuilder();
stringBuilder.append("ID");
stringBuilder.append(str);
textView.setText(stringBuilder.toString());
} else {
paramItemViewHolder.tvId.setText("--");
}
stringBuilder = new StringBuilder();
stringBuilder.append(dataBean.getTm_msg());
stringBuilder.append("");
if (!TextUtils.isEmpty(stringBuilder.toString())) {
stringBuilder = new StringBuilder();
stringBuilder.append(dataBean.getTm_msg());
stringBuilder.append("");
String str = stringBuilder.toString();
paramItemViewHolder.tvInstructions.setText(str);
} else {
paramItemViewHolder.tvInstructions.setText("--");
}
paramItemViewHolder.sdvLeftHeader.setImageURI(dataBean.getTm_url());
paramItemViewHolder.llTeamList.setOnClickListener(new View.OnClickListener() {
public void onClick(View param1View) {
if (FuncUtils.isFastDoubleClick())
return;
Intent intent = new Intent(TeamSearchListAdapter.this.context, TeamDetailsActivity.class);
intent.putExtra("data", (Serializable) dataBean);
TeamSearchListAdapter.this.context.startActivity(intent);
}
});
}
}
}
public void onClick(View paramView, int paramInt) {
if (FuncUtils.isFastDoubleClick())
return;
}
public ItemViewHolder onCreateItemViewHolder(ViewGroup paramViewGroup, int paramInt) {
return new ItemViewHolder(this.mLayoutInflater.inflate(R.layout.team_search_list, paramViewGroup, false));
}
public class ItemViewHolder extends ClickableViewHolder {
@BindView(R.id.sdv_left_header)
SimpleDraweeView sdvLeftHeader;
@BindView(R.id.tv_user_name)
TextView tvUserName;
@BindView(R.id.tv_join)
TextView tvJoin;
@BindView(R.id.tv_instructions)
TextView tvInstructions;
@BindView(R.id.tv_team_name)
TextView tvTeamName;
@BindView(R.id.tv_members)
TextView tvMembers;
@BindView(R.id.tv_id)
TextView tvId;
@BindView(R.id.ll_team_list)
LinearLayout llTeamList;
public ItemViewHolder(View param1View) {
super(param1View);
addOnItemViewClickListener();
addOnViewClickListener(param1View);
}
}
}
/* Location: E:\BaiduNetdiskDownload\111\afby\jar\classes2-dex2jar.jar!\com\jk\jkprojec\\ui\adapter\TeamSearchListAdapter.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/ |
package ba.bitcamp.LabS02D03;
public class SlobodanPadSOdredjeneVisine {
public static void main(String[] args) {
/*Korisnik unosi vrijeme pada u sekundama i distancu u metrima
* code ispisuje
*/
System.out.print("Unesite vrijeme pada u sekundama: ");
double vrijeme = TextIO.getlnDouble();
System.out.print("Unesite distancu pada: ");
double distanca = TextIO.getlnDouble();
double g = 9.81;
double pad = (g * (vrijeme * vrijeme)) / 2;
if (pad > distanca) {
System.out.println("Objekt ce za dato vrijeme pasti na tlo");
}else{
System.out.println("Objekt nece za dato vrijeme pasti na tlo.");
double ostatak = distanca - pad;
double extraVrijeme = Math.sqrt((2 * ostatak) / g);
System.out.println("Objekt bi trebao putovati jos " + extraVrijeme + " sekundi dok bi pao na tlo.");
//uglove kroz cosinus
}
}
}
|
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class AddMusicUI {
public JFrame frame;
private LoginControl control;
private AddMusicControl aControl;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
/**
* Create the application.
*/
public AddMusicUI(DataManager dm, LoginControl control) {
this.control = control;
this.aControl = new AddMusicControl(dm);
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setTitle("Add Music");
frame.setBounds(100, 100, 450, 300);
frame.getContentPane().setLayout(null);
JLabel lblMusicTitle = new JLabel("Music Title:");
lblMusicTitle.setBounds(80, 62, 83, 16);
frame.getContentPane().add(lblMusicTitle);
JLabel lblArtist = new JLabel("Artist:");
lblArtist.setBounds(80, 92, 45, 16);
frame.getContentPane().add(lblArtist);
JLabel lblExternalLink = new JLabel("External Link:");
lblExternalLink.setBounds(80, 120, 93, 16);
frame.getContentPane().add(lblExternalLink);
JLabel lblNewLabel = new JLabel("");
lblNewLabel.setBounds(68, 245, 312, 16);
frame.getContentPane().add(lblNewLabel);
textField_1 = new JTextField();
textField_1.setBounds(235, 57, 130, 26);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
textField_2 = new JTextField();
textField_2.setBounds(235, 87, 130, 26);
frame.getContentPane().add(textField_2);
textField_2.setColumns(10);
textField_3 = new JTextField();
textField_3.setBounds(235, 115, 130, 26);
frame.getContentPane().add(textField_3);
textField_3.setColumns(10);
JButton btnAddMusic = new JButton("Add Music");
btnAddMusic.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(control.getAdmin()!=null) {
aControl.handleAddMusic(textField_1.getText(), textField_2.getText(), textField_3.getText());
lblNewLabel.setText("Music Successfully Added to the List.");
}
else
lblNewLabel.setText("Admin Not Logged in.");
}
});
btnAddMusic.setBounds(292, 163, 117, 29);
frame.getContentPane().add(btnAddMusic);
}
}
|
package com.javarush.task.pro.task13.task1313;
public class StringsLinkedList {
private Node first = new Node();
private Node last = new Node();
private Node newNode;
public void printAll() {
Node currentElement = first.next;
while ((currentElement) != null) {
System.out.println(currentElement.value);
currentElement = currentElement.next;
}
}
public void add(String value) {
newNode = new Node();
newNode.value = value;
if (first.next == null && last.prev == null) {
first.next = newNode;
last.prev = newNode;
return;
}
Node currentElement = first.next;
while ((currentElement) != null) {
Node next = currentElement.next;
if (next == null) {
currentElement.next = newNode;
last.prev = newNode;
newNode.prev = currentElement;
return;
}
currentElement = currentElement.next;
}
}
public static class Node {
private Node prev;
private String value;
private Node next;
}
}
|
package com.sosagabriel.net.service;
import java.io.IOException;
import us.monoid.web.Resty;
public class Updater {
private String latestIp = null;
private String updateUrl = null;
public static String CHECK_IP_ENDPOINT = "https://indiana.nodolujan.com.ar/ip.php";
public Updater(String updateUrl) {
this.updateUrl = updateUrl;
}
public void setLatestIp(String latestIp) {
this.latestIp = latestIp;
}
public String getLatestIp(boolean force) {
if (latestIp == null || force == true) {
latestIp = retrieveIp();
}
return latestIp;
}
public String getLatestIp() {
return getLatestIp(false);
}
public String retrieveIp() {
Resty resty = new Resty();
String raw = "";
try {
raw = resty.text(CHECK_IP_ENDPOINT).toString();
} catch (IOException e) {
// nothing to do
}
return raw.trim();
}
public boolean updateIp() {
boolean result = false;
String liveIp = retrieveIp();
if (latestIp == null || latestIp.equals(liveIp) == false) {
setLatestIp(liveIp);
System.out.println("ip changed updating...");
Resty resty = new Resty();
try {
resty.text(updateUrl).toString();
result = true;
} catch (IOException e) {
// nothing to do
System.out.println("exception while updating ip to service");
}
}
return result;
}
}
|
package sforum.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import sforum.model.Role;
@Repository
public interface RoleRepository extends JpaRepository<Role, Long> {
Role findOneByCode(String code);
}
|
package entities;
import creatures.BasicEnemy;
import creatures.Enemy;
import creatures.Player;
import game.Handler;
import statics.Boost;
import statics.Spawner;
import java.awt.*;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
public class EntityManager {
private Handler handler;
private Player player;
private ArrayList<Entity> entities;
private ArrayList<Enemy> enemies;
private ArrayList<Spawner> spawners;
private ArrayList<Coin> coins;
private Comparator<Entity> renderSorter = new Comparator<Entity>() {
@Override
public int compare(Entity a, Entity b) {
if (a.getY() + a.getHeight() < b.getY() + b.getHeight())
return -1;
return 1;
}
};
public EntityManager(Handler pHandler, Player pPlayer){
handler = pHandler;
player = pPlayer;
entities = new ArrayList<Entity>();
enemies = new ArrayList<Enemy>();
spawners = new ArrayList<Spawner>();
coins = new ArrayList<Coin>();
addEntity(player);
}
public void tick(){
for (int i = 0; i < entities.size(); i++){
Entity e = entities.get(i);
e.tick();
}
//entities.sort(renderSorter);
Enemy killedEnemy = null;
for (Enemy e: enemies) {
if (e.isDead())
killedEnemy = e;
}
if (killedEnemy != null){
Coin c = new Coin(handler, killedEnemy.x, killedEnemy.y, killedEnemy.width, killedEnemy.height);
addEntity(c);
//added
coins.add(c);
enemies.remove(killedEnemy);
entities.remove(killedEnemy);
handler.getWorld().addDefeatedEnemy();
}
Iterator itr = entities.iterator();
while (itr.hasNext()){
Entity e = (Entity) itr.next();
if (e instanceof Coin){
if(((Coin) e).isDestroyed()){
//added because of dog
coins.remove(e);
itr.remove();
}
}
if (e instanceof Boost){
if (((Boost) e).isDestroyed())
itr.remove();
}
}
}
public void render(Graphics g){
for (Entity e : entities){
e.render(g);
}
}
public void addEntity(Entity e){
entities.add(e);
}
public void addEntity(Entity e, int index){
entities.add(index, e);
}
//getters and setter
public Handler getHandler() {
return handler;
}
public void setHandler(Handler handler) {
this.handler = handler;
}
public Player getPlayer() {
return player;
}
public void setPlayer(Player player) {
this.player = player;
}
public ArrayList<Entity> getEntities() {
return entities;
}
public void setEntities(ArrayList<Entity> entities) {
this.entities = entities;
}
public ArrayList<Enemy> getEnemies() {
return enemies;
}
public void setEnemies(ArrayList<Enemy> enemies) {
this.enemies = enemies;
}
public ArrayList<Spawner> getSpawners() {
return spawners;
}
public ArrayList<Coin> getCoins() {
return coins;
}
}
|
package com.rgsj3.sebbs.repository;
import com.rgsj3.sebbs.domain.File;
import org.springframework.data.jpa.repository.JpaRepository;
public interface FileRepository extends JpaRepository<File, Integer> {
}
|
package com.smxknife.java.ex32;
/**
* @author smxknife
* 2021/1/14
*/
public class ExcepTest {
public static void main(String[] args) {
int i = 0;
try {
System.out.println();
} catch (Exception e) {
throw e;
}
}
}
|
package Erbauer;
// Reifenbreite, Reifengröße, Gewicht des Rahmens, Farbe des Rahmens, Anzahl der Gänge
public abstract class AbstractBike{
protected String name;
protected ITire tires;
protected IFrame frame;
protected IGearShift gearShift;
public void setTires(ITire tires) {
this.tires = tires;
}
public void setFrame(IFrame frame) {
this.frame = frame;
}
public void setGearShift(IGearShift gear) {
this.gearShift = gear;
}
public ITire getTires() {
return tires;
}
public IFrame getFrame() {
return frame;
}
public IGearShift getGearShift() {
return gearShift;
}
public String toString() {
return this.name+" mit einem Rahmen in "+frame.getColor()+", der "+frame.getWeight()+"kg wiegt; Räder mit einem Durchmesser von "+tires.getDiameter()+" und einer Stärke von "+tires.getStrength()+"; Gangschältung mit "+gearShift.getGearCount()+" Gängen";
}
public String getName() {
return this.name;
}
}
|
package Liftoff.launchcode.onlinebookstore.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class BookController {
@GetMapping("book")
public String displaybooks(Model model){
return "book/book";
}
}
|
/*
* 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 ProductPack;
import Entities.Contractor;
import Entities.Product;
import computersales.ConnectionClass;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
/**
*
* @author Sasha
*/
public class NewProduct extends javax.swing.JDialog {
Product editEntity;
List<Contractor> list;
ConnectionClass c = new ConnectionClass();
/**
* Creates new form NewProduct
*/
public NewProduct(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
combos();
}
public NewProduct(java.awt.Frame parent, boolean modal, Product u) {
super(parent, modal);
initComponents();
editEntity = u;
combos();
fillFields();
}
private void combos() {
list = new ArrayList<>();
list = c.getContractors();
contractor.setModel(new DefaultComboBoxModel(list.toArray()));
}
private void fillFields() {
name.setText(editEntity.getName());
price.setText(editEntity.getPrice()+"");
quantity.setText(editEntity.getQuantity()+"");
contractor.setSelectedItem(-1);
for (Contractor s : list) {
if (s.getId() == editEntity.getContractor_id()) {
contractor.setSelectedItem((s));
}
}
}
public boolean check() {
if ("".equals(name.getText())) {
JOptionPane.showMessageDialog(new JFrame(), "name cannot be empty");
return false;
}
if ("".equals(price.getText())) {
JOptionPane.showMessageDialog(new JFrame(), "price cannot be empty");
return false;
}
if ("".equals(quantity.getText())) {
JOptionPane.showMessageDialog(new JFrame(), "quantity cannot be empty");
return false;
}
return true;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
name = new javax.swing.JTextField();
price = new javax.swing.JTextField();
quantity = new javax.swing.JTextField();
contractor = new javax.swing.JComboBox<>();
jButton1 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
contractor.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jButton1.setText("OK");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel1.setText("Наименование");
jLabel2.setText("Цена");
jLabel3.setText("Количество");
jLabel4.setText("Контрагент");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(108, 108, 108)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel1)
.addComponent(jLabel2)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(jLabel4))
.addComponent(jLabel3))))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(name, javax.swing.GroupLayout.DEFAULT_SIZE, 263, Short.MAX_VALUE)
.addComponent(price)
.addComponent(quantity)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jButton1)
.addComponent(contractor, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(108, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(27, 27, 27)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(price, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(quantity, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(contractor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 29, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(24, 24, 24))
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
if (!check()) {
return;
}
if (editEntity == null) {
Product newOne = new Product(-1, name.getText(),Integer.parseInt(price.getText()),
Integer.parseInt(quantity.getText()),((Contractor)contractor.getSelectedItem()).getId());
c.addProduct(newOne);
} else {
editEntity.setName(name.getText());
editEntity.setPrice(Integer.parseInt(price.getText()));
editEntity.setQuantity(Integer.parseInt(quantity.getText()));
editEntity.setContractor_id(((Contractor)contractor.getSelectedItem()).getId());
c.editProduct(editEntity);
}
dispose();
}//GEN-LAST:event_jButton1ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JComboBox<String> contractor;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JTextField name;
private javax.swing.JTextField price;
private javax.swing.JTextField quantity;
// End of variables declaration//GEN-END:variables
}
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
static int [] SIZE = new int[367];
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
for (int i = 0; i < n; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
int start = Integer.parseInt(st.nextToken());
int end = Integer.parseInt(st.nextToken());
for (int j = start; j <= end; j++) {
SIZE[j]++;
}
}
int len = 0;
int max = 0;
int result = 0;
for (int i = 1; i < SIZE.length; i++) {
if (SIZE[i] == 0) {
result += (len * max);
len = 0;
max = 0;
}
if (SIZE[i] != 0) {
max = Math.max(max, SIZE[i]);
len++;
}
}
System.out.println(result);
}
}
|
package com.revature.models;
public class Phone {
private int id;
private String modelName;
private String brand;
private String serviceProvider;
private OS nokiaOS;
private String phoneNumber;
public int getId() {
return id;
}
public void setId(int id) {
System.out.println("set id");
this.id = id;
}
public String getModelName() {
return modelName;
}
public void setModelName(String modelName) {
System.out.println("set model name");
this.modelName = modelName;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
System.out.println("set brand: " + brand);
this.brand = brand;
}
public String getServiceProvider() {
return serviceProvider;
}
public void setServiceProvider(String serviceProvider) {
System.out.println("set service provider");
this.serviceProvider = serviceProvider;
}
public OS getNokiaOS() {
return nokiaOS;
}
public void setNokiaOS(OS os) {
System.out.println("set OS");
this.nokiaOS = os;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
System.out.println("set phone number");
this.phoneNumber = phoneNumber;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((brand == null) ? 0 : brand.hashCode());
result = prime * result + id;
result = prime * result + ((modelName == null) ? 0 : modelName.hashCode());
result = prime * result + ((nokiaOS == null) ? 0 : nokiaOS.hashCode());
result = prime * result + ((phoneNumber == null) ? 0 : phoneNumber.hashCode());
result = prime * result + ((serviceProvider == null) ? 0 : serviceProvider.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Phone other = (Phone) obj;
if (brand == null) {
if (other.brand != null)
return false;
} else if (!brand.equals(other.brand))
return false;
if (id != other.id)
return false;
if (modelName == null) {
if (other.modelName != null)
return false;
} else if (!modelName.equals(other.modelName))
return false;
if (nokiaOS == null) {
if (other.nokiaOS != null)
return false;
} else if (!nokiaOS.equals(other.nokiaOS))
return false;
if (phoneNumber == null) {
if (other.phoneNumber != null)
return false;
} else if (!phoneNumber.equals(other.phoneNumber))
return false;
if (serviceProvider == null) {
if (other.serviceProvider != null)
return false;
} else if (!serviceProvider.equals(other.serviceProvider))
return false;
return true;
}
@Override
public String toString() {
return "Phone [id=" + id + ", modelName=" + modelName + ", brand=" + brand + ", serviceProvider="
+ serviceProvider + ", os=" + nokiaOS + ", phoneNumber=" + phoneNumber + "]";
}
public Phone(int id, String modelName, String brand, String serviceProvider, OS os, String phoneNumber) {
System.out.println("args phone");
this.id = id;
this.modelName = modelName;
this.brand = brand;
this.serviceProvider = serviceProvider;
this.nokiaOS = os;
this.phoneNumber = phoneNumber;
}
public Phone() {
System.out.println("no args phone");
}
}
|
package day5;
class Car {
private int yearOfManufacture;
private String color;
private String model;
public void setYearOfManufacture(int yearOfManufacture) {
this.yearOfManufacture = yearOfManufacture;
}
public int getYearOfManufacture() {
return yearOfManufacture;
}
public void setColor(String color) {
this.color = color;
}
public String getColor() {
return color;
}
public void setModel(String model) {
this.model = model;
}
public String getModel() {
return model;
}
}
|
package View.GUIMain;
import Model.SistemaDeUsuario.Usuarios;
import View.GUISistemaDeAutenticacion.GUISistemaDeAutenticacion;
import View.GUISistemaDeCarrito.GUISistemaDeCarrito;
import View.GUISistemaDeInventario.GUISistemaDeInventario;
import View.GUISistemaDeMenu.GUISistemaDeMenu;
import View.GUISistemaDeOrdenes.GUISistemaDeOrdenes;
import View.GUISistemaDeReservacion.GUISistemaDeReservacion;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class GUIMain {
public GUIMain(){
}
public static void inicio() throws IOException, ClassNotFoundException {
clearScreen();
GUISistemaDeAutenticacion guiA = new GUISistemaDeAutenticacion();
System.out.println("\t= = RESTAURANTE ``DONDE SIEMPRE´´ = =");
// Que se identifique el usuario
// se manda a si respectivo menú
Usuarios usr;
usr = null;
boolean flag = true;
while(flag){ // El "login" deberia estar en un while
// - - - - - - - -
System.out.println(" Escoja una opcion:");
System.out.println("\n\t1. Cliente" +
"\n\t2. Gerente" +
"\n\t3. Chef" +
"\n\t0. Salir ");
int ir_a_menu = ingresoDatosInt(); // dependoendo el tipo de usuario lo manda a su respectivo menu
// - - - - - - - -
switch (ir_a_menu){
case 1:
clearScreen();
usr = guiA.menuCliente();
if (usr != null) {
menuClientes(usr);
}
else {
System.out.println("Contraseña incorrecta");;
}
break;
case 2:
clearScreen();
if (guiA.menuGerente()) {
menuGerente();
}
break;
case 3:
clearScreen();
if (guiA.menuChef()) {
menuChef();
}
break;
case 0: // 0 para salir
flag = false;
break;
default:
System.out.println("\tERROR: USUARIO NO VALIDO");
}
}
}
private static void menuClientes(Usuarios usr) throws IOException, ClassNotFoundException {
int opcion = 0;
Boolean activo = true;
clearScreen();
while(activo) {
System.out.println("\n\t= = Menu Principal = = ");
System.out.println("\nIngrese la opción deseada\n" +
"\n\t1. Menu del Restaurante" +
"\n\t2. Mi carrito" +
"\n\t3. Mis Reservaciones" +
"\n\t0. Cerrar Sesion");
opcion = ingresoDatosInt();
clearScreen(); // limpia la pantalla
switch (opcion) {
case 0:
activo = false;
break;
case 1:
GUISistemaDeMenu guiM = new GUISistemaDeMenu();
guiM.menuClientes();
break;
case 2:
GUISistemaDeCarrito menuCarrito = new GUISistemaDeCarrito();
menuCarrito.menuCarrito(usr);
break;
case 3:
GUISistemaDeReservacion menuReservaciones = new GUISistemaDeReservacion();
menuReservaciones.menuClienteReservaciones(usr);
break;
default:
System.out.println("\nEscoja una opcion valida.");
}
clearScreen();
}
}
private static void menuChef() throws IOException, FileNotFoundException, ClassNotFoundException {
int opcion = 0;
Boolean activo = true;
clearScreen();
while(activo) {
System.out.println("\n\t= = Menu Chef = = ");
System.out.println("\nIngrese la opción deseada\n" +
"\n\t1. Editar Menu del Restaurante" +
"\n\t2. Administrar ordenes" +
"\n\t0. Cerrar Sesion");
opcion = ingresoDatosInt();
clearScreen(); // limpia la pantalla
switch (opcion) {
case 0:
activo = false;
break;
case 1:
GUISistemaDeMenu guiM = new GUISistemaDeMenu();
guiM.menuChef();
break;
case 2:
GUISistemaDeOrdenes menuOrdenes = new GUISistemaDeOrdenes();
menuOrdenes.menuOrdenesChef();
break;
default:
System.out.println("\nEscoja una opcion valida.");
}
clearScreen();
}
}
private static void menuGerente() throws IOException, ClassNotFoundException {
int opcion = 0;
Boolean activo = true;
clearScreen();
while(activo) {
System.out.println("\n\t= = Menu Gerente = = ");
System.out.println("\nIngrese la opción deseada\n" +
"\n\t1. Administrar Inventario" +
"\n\t2. Administrador de reservaciones" +
"\n\t0. Cerrar Sesion");
opcion = ingresoDatosInt();
clearScreen(); // limpia la pantalla
switch (opcion) {
case 0:
activo = false;
break;
case 1:
GUISistemaDeInventario menuInv = new GUISistemaDeInventario();
menuInv.menuAdministradorInventario();
break;
case 2:
GUISistemaDeReservacion menuReservaciones = new GUISistemaDeReservacion();
menuReservaciones.menuAdminReservaciones();
break;
default:
System.out.println("\nEscoja una opcion valida.");
}
clearScreen();
}
}
// U T I L I D A D E S
private static String ingresoDatosString() {
Scanner scan = new Scanner(System.in);
while (true) {
try {
return scan.next();
} catch (Exception e) {
System.out.println("Ingresa un valor valido");
scan.nextLine();
}
}
}
private static int ingresoDatosInt() {
Scanner scan = new Scanner(System.in);
while (true) {
try {
return scan.nextInt();
} catch (Exception e) {
System.out.println("Ingresa un Numero");
scan.nextLine();
}
}
}
public static void pressAnyKeyToContinue() {
String seguir;
Scanner teclado = new Scanner(System.in);
System.out.println("\nPress Enter key to continue...");
try
{
seguir = teclado.nextLine();
}
catch(Exception ignored) {}
}
public static void clearScreen() {
System.out.print("\033[H\033[2J");
System.out.flush();
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.openwebbeans.slf4j;
import org.slf4j.spi.LocationAwareLogger;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.logging.Filter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
// mainly from cxf
class Slf4jLogger extends Logger
{
private static final String FQN = System.getProperty("org.apache.openwebbeans.slf4j.fqn", Slf4jLogger.class.getName());
private final org.slf4j.Logger logger;
private final LocationAwareLogger locationAwareLogger;
Slf4jLogger(final String name, final String resourceBundleName)
{
super(name, resourceBundleName);
logger = org.slf4j.LoggerFactory.getLogger(name);
if (LocationAwareLogger.class.isInstance(logger))
{
locationAwareLogger = LocationAwareLogger.class.cast(logger);
}
else
{
locationAwareLogger = null;
}
}
@Override
public void log(final LogRecord record)
{
if (isLoggable(record.getLevel()))
{
doLog(record);
}
}
@Override
public void log(final Level level, final String msg)
{
if (isLoggable(level))
{
doLog(new LogRecord(level, msg));
}
}
@Override
public void log(final Level level, final String msg, final Object param1)
{
if (isLoggable(level))
{
final LogRecord lr = new LogRecord(level, msg);
lr.setParameters(new Object[]{param1});
doLog(lr);
}
}
@Override
public void log(final Level level, final String msg, final Object[] params)
{
if (isLoggable(level))
{
final LogRecord lr = new LogRecord(level, msg);
lr.setParameters(params);
doLog(lr);
}
}
@Override
public void log(final Level level, final String msg, final Throwable thrown)
{
if (isLoggable(level))
{
final LogRecord lr = new LogRecord(level, msg);
lr.setThrown(thrown);
doLog(lr);
}
}
@Override
public void logp(final Level level, final String sourceClass, final String sourceMethod, final String msg)
{
if (isLoggable(level))
{
final LogRecord lr = new LogRecord(level, msg);
lr.setSourceClassName(sourceClass);
lr.setSourceMethodName(sourceMethod);
doLog(lr);
}
}
@Override
public void logp(final Level level, final String sourceClass, final String sourceMethod, final String msg, final Object param1)
{
if (isLoggable(level))
{
final LogRecord lr = new LogRecord(level, msg);
lr.setSourceClassName(sourceClass);
lr.setSourceMethodName(sourceMethod);
lr.setParameters(new Object[]{param1});
doLog(lr);
}
}
@Override
public void logp(final Level level, final String sourceClass, final String sourceMethod, final String msg, Object[] params)
{
if (isLoggable(level))
{
final LogRecord lr = new LogRecord(level, msg);
lr.setSourceClassName(sourceClass);
lr.setSourceMethodName(sourceMethod);
lr.setParameters(params);
doLog(lr);
}
}
@Override
public void logp(final Level level, final String sourceClass, final String sourceMethod, final String msg, final Throwable thrown)
{
if (isLoggable(level))
{
final LogRecord lr = new LogRecord(level, msg);
lr.setSourceClassName(sourceClass);
lr.setSourceMethodName(sourceMethod);
lr.setThrown(thrown);
doLog(lr);
}
}
@Override
public void logrb(final Level level, final String sourceClass, final String sourceMethod, final String bundleName, final String msg)
{
if (isLoggable(level))
{
final LogRecord lr = new LogRecord(level, msg);
lr.setSourceClassName(sourceClass);
lr.setSourceMethodName(sourceMethod);
doLog(lr, bundleName);
}
}
@Override
public void logrb(final Level level, final String sourceClass, final String sourceMethod,
final String bundleName, final String msg, final Object param1)
{
if (isLoggable(level))
{
final LogRecord lr = new LogRecord(level, msg);
lr.setSourceClassName(sourceClass);
lr.setSourceMethodName(sourceMethod);
lr.setParameters(new Object[]{param1});
doLog(lr, bundleName);
}
}
@Override
public void logrb(final Level level, final String sourceClass, final String sourceMethod,
final String bundleName, final String msg, Object[] params)
{
if (isLoggable(level))
{
final LogRecord lr = new LogRecord(level, msg);
lr.setSourceClassName(sourceClass);
lr.setSourceMethodName(sourceMethod);
lr.setParameters(params);
doLog(lr, bundleName);
}
}
@Override
public void logrb(final Level level, final String sourceClass, final String sourceMethod,
final String bundleName, final String msg, final Throwable thrown)
{
if (isLoggable(level))
{
final LogRecord lr = new LogRecord(level, msg);
lr.setSourceClassName(sourceClass);
lr.setSourceMethodName(sourceMethod);
lr.setThrown(thrown);
doLog(lr, bundleName);
}
}
@Override
public void entering(final String sourceClass, final String sourceMethod)
{
if (isLoggable(Level.FINER))
{
logp(Level.FINER, sourceClass, sourceMethod, "ENTRY");
}
}
@Override
public void entering(final String sourceClass, final String sourceMethod, final Object param1)
{
if (isLoggable(Level.FINER))
{
logp(Level.FINER, sourceClass, sourceMethod, "ENTRY {0}", param1);
}
}
@Override
public void entering(final String sourceClass, final String sourceMethod, final Object[] params)
{
if (isLoggable(Level.FINER))
{
final String msg = "ENTRY";
if (params == null)
{
logp(Level.FINER, sourceClass, sourceMethod, msg);
return;
}
final StringBuilder builder = new StringBuilder(msg);
for (int i = 0; i < params.length; i++)
{
builder.append(" {");
builder.append(i);
builder.append('}');
}
logp(Level.FINER, sourceClass, sourceMethod, builder.toString(), params);
}
}
@Override
public void exiting(final String sourceClass, final String sourceMethod)
{
if (isLoggable(Level.FINER))
{
logp(Level.FINER, sourceClass, sourceMethod, "RETURN");
}
}
@Override
public void exiting(final String sourceClass, final String sourceMethod, final Object result)
{
if (isLoggable(Level.FINER))
{
logp(Level.FINER, sourceClass, sourceMethod, "RETURN {0}", result);
}
}
@Override
public void throwing(final String sourceClass, final String sourceMethod, final Throwable thrown)
{
if (isLoggable(Level.FINER))
{
final LogRecord lr = new LogRecord(Level.FINER, "THROW");
lr.setSourceClassName(sourceClass);
lr.setSourceMethodName(sourceMethod);
lr.setThrown(thrown);
doLog(lr);
}
}
@Override
public void severe(final String msg)
{
if (isLoggable(Level.SEVERE))
{
doLog(new LogRecord(Level.SEVERE, msg));
}
}
@Override
public void warning(final String msg)
{
if (isLoggable(Level.WARNING))
{
doLog(new LogRecord(Level.WARNING, msg));
}
}
@Override
public void info(final String msg)
{
if (isLoggable(Level.INFO))
{
doLog(new LogRecord(Level.INFO, msg));
}
}
@Override
public void config(final String msg)
{
if (isLoggable(Level.CONFIG))
{
doLog(new LogRecord(Level.CONFIG, msg));
}
}
@Override
public void fine(final String msg)
{
if (isLoggable(Level.FINE))
{
doLog(new LogRecord(Level.FINE, msg));
}
}
@Override
public void finer(final String msg)
{
if (isLoggable(Level.FINER))
{
doLog(new LogRecord(Level.FINER, msg));
}
}
@Override
public void finest(final String msg)
{
if (isLoggable(Level.FINEST))
{
doLog(new LogRecord(Level.FINEST, msg));
}
}
@Override
public void setLevel(final Level newLevel)
{
// no-op
}
private void doLog(final LogRecord lr)
{
lr.setLoggerName(getName());
final String rbname = getResourceBundleName();
if (rbname != null)
{
lr.setResourceBundleName(rbname);
lr.setResourceBundle(getResourceBundle());
}
internalLog(lr);
}
private void doLog(final LogRecord lr, final String rbname)
{
lr.setLoggerName(getName());
if (rbname != null)
{
lr.setResourceBundleName(rbname);
lr.setResourceBundle(loadResourceBundle(rbname));
}
internalLog(lr);
}
private void internalLog(final LogRecord record)
{
final Filter filter = getFilter();
if (filter != null && !filter.isLoggable(record))
{
return;
}
final String msg = formatMessage(record);
internalLogFormatted(msg, record);
}
private String formatMessage(final LogRecord record)
{
final ResourceBundle catalog = record.getResourceBundle();
String format = record.getMessage();
if (catalog != null)
{
try
{
format = catalog.getString(record.getMessage());
}
catch (MissingResourceException ex)
{
format = record.getMessage();
}
}
try
{
final Object[] parameters = record.getParameters();
if (parameters == null || parameters.length == 0)
{
return format;
}
if (format.contains("{0") || format.contains("{1")
|| format.contains("{2") || format.contains("{3"))
{
return java.text.MessageFormat.format(format, parameters);
}
return format;
}
catch (final Exception ex)
{
return format;
}
}
private static ResourceBundle loadResourceBundle(final String resourceBundleName)
{
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (null != cl)
{
try
{
return ResourceBundle.getBundle(resourceBundleName, Locale.getDefault(), cl);
}
catch (final MissingResourceException e)
{
// no-op
}
}
cl = ClassLoader.getSystemClassLoader();
if (null != cl)
{
try
{
return ResourceBundle.getBundle(resourceBundleName, Locale.getDefault(), cl);
}
catch (final MissingResourceException e)
{
// no-op
}
}
return null;
}
@Override
public Level getLevel()
{
if (logger.isTraceEnabled())
{
return Level.FINEST;
}
else if (logger.isDebugEnabled())
{
return Level.FINER;
}
else if (logger.isInfoEnabled())
{
return Level.INFO;
}
else if (logger.isWarnEnabled())
{
return Level.WARNING;
}
else if (logger.isErrorEnabled())
{
return Level.SEVERE;
}
return Level.OFF;
}
@Override
public boolean isLoggable(final Level level)
{
final int i = level.intValue();
if (i == Level.OFF.intValue())
{
return false;
}
else if (i >= Level.SEVERE.intValue())
{
return logger.isErrorEnabled();
}
else if (i >= Level.WARNING.intValue())
{
return logger.isWarnEnabled();
}
else if (i >= Level.INFO.intValue())
{
return logger.isInfoEnabled();
}
else if (i >= Level.FINER.intValue())
{
return logger.isDebugEnabled();
}
return logger.isTraceEnabled();
}
private void internalLogFormatted(final String msg, final LogRecord record)
{
final Level level = record.getLevel();
final Throwable t = record.getThrown();
final Handler[] targets = getHandlers();
if (targets != null)
{
for (Handler h : targets)
{
h.publish(record);
}
}
if (!getUseParentHandlers())
{
return;
}
if (Level.FINE.equals(level))
{
if (locationAwareLogger == null)
{
logger.debug(msg, t);
}
else
{
locationAwareLogger.log(null, FQN, LocationAwareLogger.DEBUG_INT, msg, null, t);
}
}
else if (Level.INFO.equals(level))
{
if (locationAwareLogger == null)
{
logger.info(msg, t);
}
else
{
locationAwareLogger.log(null, FQN, LocationAwareLogger.INFO_INT, msg, null, t);
}
}
else if (Level.WARNING.equals(level))
{
if (locationAwareLogger == null)
{
logger.warn(msg, t);
}
else
{
locationAwareLogger.log(null, FQN, LocationAwareLogger.WARN_INT, msg, null, t);
}
}
else if (Level.FINER.equals(level))
{
if (locationAwareLogger == null)
{
logger.trace(msg, t);
}
else
{
locationAwareLogger.log(null, FQN, LocationAwareLogger.DEBUG_INT, msg, null, t);
}
}
else if (Level.FINEST.equals(level))
{
if (locationAwareLogger == null)
{
logger.trace(msg, t);
}
else
{
locationAwareLogger.log(null, FQN, LocationAwareLogger.TRACE_INT, msg, null, t);
}
}
else if (Level.ALL.equals(level))
{
if (locationAwareLogger == null)
{
logger.error(msg, t);
}
else
{
locationAwareLogger.log(null, FQN, LocationAwareLogger.ERROR_INT, msg, null, t);
}
}
else if (Level.SEVERE.equals(level))
{
if (locationAwareLogger == null)
{
logger.error(msg, t);
}
else
{
locationAwareLogger.log(null, FQN, LocationAwareLogger.ERROR_INT, msg, null, t);
}
}
else if (Level.CONFIG.equals(level))
{
if (locationAwareLogger == null)
{
logger.debug(msg, t);
}
else
{
locationAwareLogger.log(null, FQN, LocationAwareLogger.DEBUG_INT, msg, null, t);
}
}
}
}
|
package com.salmito.engine.main;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ConfigurationInfo;
import android.os.Bundle;
import android.view.Window;
public class MainScreen extends Activity {
private MainView mainView;
private Renderer renderer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
mainView = new MainView(this);
final ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();
final boolean supportsEs2 = configurationInfo.reqGlEsVersion >= 0x20000;
if (supportsEs2) {
mainView.setEGLContextClientVersion(2);
renderer=new Renderer(mainView);
mainView.setRenderer(renderer);
} else {
return; //todo fallback
}
//mainView.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
setContentView(mainView);
}
@Override
protected void onResume() {
super.onResume();
mainView.onResume();
}
@Override
protected void onPause() {
super.onPause();
mainView.onPause();
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
}
}
|
/*
* Copyright (C), 2013-2014, 上海汽车集团股份有限公司
* FileName: AnnotationVo.java
* Author: baowenzhou
* Date: 2016年3月16日 下午14:44:03
* Description: //模块目的、功能描述
* History: //修改记录
* <author> <time> <version> <desc>
* 修改人姓名 修改时间 版本号 描述
*/
package com.xjf.wemall.api.entity.annotation;
import java.lang.annotation.Annotation;
/**
* 登录参数<br>
* 〈功能详细描述〉
*
* @author baowenzhou
* @see [相关类/方法](可选)
* @since [产品/模块版本] (可选)
*/
public class AnnotationVo {
// 参数值
private Object paramValue;
// 注解类
private Annotation annotation;
public Object getParamValue() {
return paramValue;
}
public void setParamValue(Object paramValue) {
this.paramValue = paramValue;
}
public Annotation getAnnotation() {
return annotation;
}
public void setAnnotation(Annotation annotation) {
this.annotation = annotation;
}
}
|
package com.example.hp.above;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import org.w3c.dom.Text;
public class BinarySearchTreeActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_binary_search_tree);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
public void search_bst(View view)
{
TextView previewText= (TextView) findViewById(R.id.bst_search);
previewText.setText("\n\n\n// C function to search a given key in a given BST\n" +
"struct node* search(struct node* root, int key)\n" +
"{\n" +
" // Base Cases: root is null or key is present at root\n" +
" if (root == NULL || root->key == key)\n" +
" return root;\n" +
" \n" +
" // Key is greater than root's key\n" +
" if (root->key < key)\n" +
" return search(root->right, key);\n" +
" \n" +
" // Key is smaller than root's key\n" +
" return search(root->left, key);\n" +
"}");
}
public void insert_bst(View view)
{
TextView previewText= (TextView) findViewById(R.id.bst_insert);
previewText.setText("\n\n 100 100\n" +
" / \\ Insert 40 / \\\n" +
" 20 500 ---------> 20 500 \n" +
" / \\ / \\ \n" +
" 10 30 10 30\n" +
" \\ \n" +
" 40" +
"\n\n\n// C program to demonstrate insert operation in binary search tree\n" +
"#include<stdio.h>\n" +
"#include<stdlib.h>\n" +
" \n" +
"struct node\n" +
"{\n" +
" int key;\n" +
" struct node *left, *right;\n" +
"};\n" +
" \n" +
"// A utility function to create a new BST node\n" +
"struct node *newNode(int item)\n" +
"{\n" +
" struct node *temp = (struct node *)malloc(sizeof(struct node));\n" +
" temp->key = item;\n" +
" temp->left = temp->right = NULL;\n" +
" return temp;\n" +
"}\n" +
" \n" +
"// A utility function to do inorder traversal of BST\n" +
"void inorder(struct node *root)\n" +
"{\n" +
" if (root != NULL)\n" +
" {\n" +
" inorder(root->left);\n" +
" printf(\"%d \\n\", root->key);\n" +
" inorder(root->right);\n" +
" }\n" +
"}\n" +
" \n" +
"/* A utility function to insert a new node with given key in BST */\n" +
"struct node* insert(struct node* node, int key)\n" +
"{\n" +
" /* If the tree is empty, return a new node */\n" +
" if (node == NULL) return newNode(key);\n" +
" \n" +
" /* Otherwise, recur down the tree */\n" +
" if (key < node->key)\n" +
" node->left = insert(node->left, key);\n" +
" else if (key > node->key)\n" +
" node->right = insert(node->right, key); \n" +
" \n" +
" /* return the (unchanged) node pointer */\n" +
" return node;\n" +
"}\n" +
" \n" +
"// Driver Program to test above functions\n" +
"int main()\n" +
"{\n" +
" /* Let us create following BST\n" +
" 50\n" +
" / \\\n" +
" 30 70\n" +
" / \\ / \\\n" +
" 20 40 60 80 */\n" +
" struct node *root = NULL;\n" +
" root = insert(root, 50);\n" +
" insert(root, 30);\n" +
" insert(root, 20);\n" +
" insert(root, 40);\n" +
" insert(root, 70);\n" +
" insert(root, 60);\n" +
" insert(root, 80);\n" +
" \n" +
" // print inoder traversal of the BST\n" +
" inorder(root);\n" +
" \n" +
" return 0;\n" +
"}" +
"\n\nOutput:\n" +
"20\n" +
"30\n" +
"40\n" +
"50\n" +
"60\n" +
"70\n" +
"80\n" +
"\n\nTime Complexity: The worst case time complexity of search and insert operations is O(h) where h is height of " +
"\n\nBinary Search Tree. In worst case, we may have to travel from root to the deepest leaf node." +
"\n\nThe height of a skewed tree may become n and the time complexity of search and insert operation may become O(n).");
}
public void delete_bst(View view)
{
TextView previewText= (TextView) findViewById(R.id.bst_delete);
previewText.setText("\n\n1) Node to be deleted is leaf: Simply remove from the tree.\n" +
" 50 50\n" +
" / \\ delete(20) / \\\n" +
" 30 70 ---------> 30 70 \n" +
" / \\ / \\ \\ / \\ \n" +
" 20 40 60 80 40 60 80\n" +
"\n\n2) Node to be deleted has only one child: Copy the child to the node and delete the child\n" +
" 50 50\n" +
" / \\ delete(30) / \\\n" +
" 30 70 ---------> 40 70 \n" +
" \\ / \\ / \\ \n" +
" 40 60 80 60 80\n" +
"\n\n3) Node to be deleted has two children: Find inorder successor of the node. Copy contents of the inorder successor to the node and delete the inorder successor. Note that inorder predecessor can also be used.\n" +
" 50 60\n" +
" / \\ delete(50) / \\\n" +
" 40 70 ---------> 40 70 \n" +
" / \\ \\ \n" +
" 60 80 80\n" +
"\n\nThe important thing to note is, inorder successor is needed only when right child is not empty. " +
"\n\nIn this particular case, inorder successor can be obtained by finding the minimum value in right child of the node." +
"\n\nCODE:\n\n// C program to demonstrate delete operation in binary search tree\n" +
"#include<stdio.h>\n" +
"#include<stdlib.h>\n" +
" \n" +
"struct node\n" +
"{\n" +
" int key;\n" +
" struct node *left, *right;\n" +
"};\n" +
" \n" +
"// A utility function to create a new BST node\n" +
"struct node *newNode(int item)\n" +
"{\n" +
" struct node *temp = (struct node *)malloc(sizeof(struct node));\n" +
" temp->key = item;\n" +
" temp->left = temp->right = NULL;\n" +
" return temp;\n" +
"}\n" +
" \n" +
"// A utility function to do inorder traversal of BST\n" +
"void inorder(struct node *root)\n" +
"{\n" +
" if (root != NULL)\n" +
" {\n" +
" inorder(root->left);\n" +
" printf(\"%d \", root->key);\n" +
" inorder(root->right);\n" +
" }\n" +
"}\n" +
" \n" +
"/* A utility function to insert a new node with given key in BST */\n" +
"struct node* insert(struct node* node, int key)\n" +
"{\n" +
" /* If the tree is empty, return a new node */\n" +
" if (node == NULL) return newNode(key);\n" +
" \n" +
" /* Otherwise, recur down the tree */\n" +
" if (key < node->key)\n" +
" node->left = insert(node->left, key);\n" +
" else\n" +
" node->right = insert(node->right, key);\n" +
" \n" +
" /* return the (unchanged) node pointer */\n" +
" return node;\n" +
"}\n" +
" \n" +
"/* Given a non-empty binary search tree, return the node with minimum\n" +
" key value found in that tree. Note that the entire tree does not\n" +
" need to be searched. */\n" +
"struct node * minValueNode(struct node* node)\n" +
"{\n" +
" struct node* current = node;\n" +
" \n" +
" /* loop down to find the leftmost leaf */\n" +
" while (current->left != NULL)\n" +
" current = current->left;\n" +
" \n" +
" return current;\n" +
"}\n" +
" \n" +
"/* Given a binary search tree and a key, this function deletes the key\n" +
" and returns the new root */\n" +
"struct node* deleteNode(struct node* root, int key)\n" +
"{\n" +
" // base case\n" +
" if (root == NULL) return root;\n" +
" \n" +
" // If the key to be deleted is smaller than the root's key,\n" +
" // then it lies in left subtree\n" +
" if (key < root->key)\n" +
" root->left = deleteNode(root->left, key);\n" +
" \n" +
" // If the key to be deleted is greater than the root's key,\n" +
" // then it lies in right subtree\n" +
" else if (key > root->key)\n" +
" root->right = deleteNode(root->right, key);\n" +
" \n" +
" // if key is same as root's key, then This is the node\n" +
" // to be deleted\n" +
" else\n" +
" {\n" +
" // node with only one child or no child\n" +
" if (root->left == NULL)\n" +
" {\n" +
" struct node *temp = root->right;\n" +
" free(root);\n" +
" return temp;\n" +
" }\n" +
" else if (root->right == NULL)\n" +
" {\n" +
" struct node *temp = root->left;\n" +
" free(root);\n" +
" return temp;\n" +
" }\n" +
" \n" +
" // node with two children: Get the inorder successor (smallest\n" +
" // in the right subtree)\n" +
" struct node* temp = minValueNode(root->right);\n" +
" \n" +
" // Copy the inorder successor's content to this node\n" +
" root->key = temp->key;\n" +
" \n" +
" // Delete the inorder successor\n" +
" root->right = deleteNode(root->right, temp->key);\n" +
" }\n" +
" return root;\n" +
"}\n" +
" \n" +
"// Driver Program to test above functions\n" +
"int main()\n" +
"{\n" +
" /* Let us create following BST\n" +
" 50\n" +
" / \\\n" +
" 30 70\n" +
" / \\ / \\\n" +
" 20 40 60 80 */\n" +
" struct node *root = NULL;\n" +
" root = insert(root, 50);\n" +
" root = insert(root, 30);\n" +
" root = insert(root, 20);\n" +
" root = insert(root, 40);\n" +
" root = insert(root, 70);\n" +
" root = insert(root, 60);\n" +
" root = insert(root, 80);\n" +
" \n" +
" printf(\"Inorder traversal of the given tree \\n\");\n" +
" inorder(root);\n" +
" \n" +
" printf(\"\\nDelete 20\\n\");\n" +
" root = deleteNode(root, 20);\n" +
" printf(\"Inorder traversal of the modified tree \\n\");\n" +
" inorder(root);\n" +
" \n" +
" printf(\"\\nDelete 30\\n\");\n" +
" root = deleteNode(root, 30);\n" +
" printf(\"Inorder traversal of the modified tree \\n\");\n" +
" inorder(root);\n" +
" \n" +
" printf(\"\\nDelete 50\\n\");\n" +
" root = deleteNode(root, 50);\n" +
" printf(\"Inorder traversal of the modified tree \\n\");\n" +
" inorder(root);\n" +
" \n" +
" return 0;\n" +
"}" +
"\n\nOutput:\n" +
"\nInorder traversal of the given tree\n" +
"20 30 40 50 60 70 80\n" +
"\nDelete 20\n" +
"\nInorder traversal of the modified tree\n" +
"30 40 50 60 70 80\n" +
"\nDelete 30\n" +
"\nInorder traversal of the modified tree\n" +
"40 50 60 70 80\n" +
"\nDelete 50\n" +
"\nInorder traversal of the modified tree\n" +
"40 60 70 80\n" +
"\nTime Complexity: The worst case time complexity of delete operation is O(h) where h is height of Binary Search Tree. In worst case, we may have to travel from root to the deepest leaf node. The height of a skewed tree may become n and the time complexity of delete operation may become O(n)");
}
}
|
package fi.jjc.graphics.rendering.util;
import java.awt.geom.Rectangle2D;
import org.lwjgl.opengl.GL11;
import fi.jjc.graphics.image.Image2DData;
import fi.jjc.graphics.image.Texture2D;
import fi.jjc.graphics.image.TextureFilter;
import fi.jjc.graphics.image.TextureParameters;
import fi.jjc.graphics.image.TextureWrap;
import fi.jjc.graphics.matrix.MatrixHandler;
import fi.jjc.graphics.matrix.MatrixStack;
import fi.jjc.graphics.rendering.RenderCall;
/**
* Background rendering class, renders an image on the entire scene.
*
* @see fi.jjc.graphics.rendering.TextureRender
* @author Jens ┼kerblom
*/
public class BackgroundRender implements RenderCall
{
/**
* Texture storage.
*/
private final Texture2D bgTex;
/**
* Constructor.
*
* @param image
* image to be rendered.
*/
public BackgroundRender(Image2DData image)
{
this.bgTex = new Texture2D(image, new TextureParameters(TextureFilter.FILTER_LINEAR,
TextureFilter.FILTER_LINEAR,
TextureWrap.WRAP_CLAMP_TO_EDGE,
TextureWrap.WRAP_CLAMP_TO_EDGE));
}
/**
* Removes the image storage from memory, the renderer should not be used after this call.
*/
public void dispose()
{
this.bgTex.dispose();
}
/**
* @see fi.jjc.graphics.rendering.RenderCall#render()
*/
@Override
public void render()
{
this.bgTex.bind();
{
MatrixStack.MAT_MODELVIEW.push();
{
MatrixStack.MAT_MODELVIEW.loadId();
MatrixStack.MAT_PROJECTION.push();
{
MatrixStack.MAT_PROJECTION.loadId();
MatrixHandler.ortho2D(new Rectangle2D.Double(0.0, 0.0, 1.0, 1.0));
GL11.glBegin(GL11.GL_QUADS);
{
GL11.glTexCoord2d(0.0, 0.0);
GL11.glVertex2d(0.0, 0.0);
GL11.glTexCoord2d(1.0, 0.0);
GL11.glVertex2d(1.0, 0.0);
GL11.glTexCoord2d(1.0, 1.0);
GL11.glVertex2d(1.0, 1.0);
GL11.glTexCoord2d(0.0, 1.0);
GL11.glVertex2d(0.0, 1.0);
}
GL11.glEnd();
}
MatrixStack.MAT_PROJECTION.pop();
}
MatrixStack.MAT_MODELVIEW.pop();
}
this.bgTex.unbind();
}
} |
package com.tencent.mm.g.a;
import com.tencent.mm.sdk.b.b;
public final class sm extends b {
public a cdp;
public sm() {
this((byte) 0);
}
private sm(byte b) {
this.cdp = new a();
this.sFm = false;
this.bJX = null;
}
}
|
package cdn.shared.message;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import cdn.shared.GlobalLogger;
import cdn.shared.message.IMessage.MessageType;
public class MessageReader {
private final ByteBuffer bytes;
private int size = -1;
private MessageType type = null;
public static MessageReader fromSocketChannel(SocketChannel channel) throws IOException {
int totalBytesRead = 0;
ByteBuffer buf = ByteBuffer.allocate(4);
while (totalBytesRead < 4 && totalBytesRead >= 0) {
totalBytesRead += channel.read(buf);
}
if (totalBytesRead == -1) {
GlobalLogger.warning(MessageReader.class, "Had to close socket, need to re-initiate.");
channel.close();
} else {
buf.position(0);
int size = buf.getInt();
ByteBuffer buf2 = ByteBuffer.allocate(size + 4);
buf2.position(4);
if (safelyRead(channel, buf2, size)) {
buf2.put(buf.array());
return new MessageReader(buf2);
}
}
return null;
}
private static boolean safelyRead(SocketChannel sock, ByteBuffer buf, int size) {
try {
int totalBytesRead = 0;
int ret = 0;
Selector s = Selector.open();
while (totalBytesRead < size && ret >= 0) {
if (sock.isBlocking()) {
ret = sock.read(buf);
totalBytesRead += ret;
} else {
SelectionKey key = sock.register(s, SelectionKey.OP_READ);
s.select(2000);
if (s.selectedKeys().remove(key)) {
totalBytesRead += sock.read(buf);
}
}
}
if (ret < 0) {
if (ret == -1) {
GlobalLogger.debug(MessageReader.class, "EOS!!!!");
sock.close();
return false;
}
GlobalLogger.debug(MessageReader.class, "Error reading bytes.");
}
s.close();
buf.position(0);
} catch (IOException ex) {
ex.printStackTrace();
GlobalLogger.severe(MessageReader.class, "IOException throw while safely reading.");
return false;
}
return true;
}
public MessageReader(ByteBuffer bytes) {
this.bytes = bytes;
}
public MessageType getType() throws IOException {
if (type == null) {
bytes.position(4);
type = MessageType.fromOrdinal(bytes.getInt());
}
return type;
}
public int getSize() throws IOException {
if (size < 0) {
bytes.position(0);
size = bytes.getInt() - Integer.SIZE / 8;
}
return size;
}
public void readRemains(byte[] bytes) throws IOException {
this.bytes.position(8);
for (int i = 0; i < bytes.length; i++) {
bytes[i] = this.bytes.get();
}
}
}
|
package model;
import java.lang.reflect.Type;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class ReceiverLookupDocument implements StatusMessageObject
{
private final static Type typeOfMap = new TypeToken<ConcurrentHashMap<String, Long>>() {}.getType();
private final ConcurrentMap<String, Long> lookup;
private int tries = 0;
private Exception lastException = null;
public ReceiverLookupDocument()
{
lookup = new ConcurrentHashMap<String, Long>();
}
public ReceiverLookupDocument(final String json)
{
lookup = new Gson().fromJson(json, typeOfMap);
}
public boolean add(final long created, final String mailKey)
{
if (lookup.putIfAbsent(mailKey, created) != null)
{
return false;
}
return true;
}
public void remove(final String mailKey)
{
lookup.remove(mailKey);
}
public int size()
{
return lookup.size();
}
@Override
public String toString()
{
return toJSON();
}
public String toJSON()
{
Gson gson = new Gson();
return gson.toJson(lookup);
}
public static ReceiverLookupDocument fromJSON(final String value)
{
return new ReceiverLookupDocument(value);
}
@Override
public int getTries()
{
return tries;
}
@Override
public void incrementTries()
{
this.tries++;
}
@Override
public Exception getLastException()
{
return lastException;
}
@Override
public void setLastException(Exception lastException)
{
this.lastException = lastException;
}
@Override
public void resetStatus()
{
tries = 0;
lastException = null;
}
}
|
package Tugas;
public class Dosen extends Manusia{
@Override
public void makan(){
super.makan();
System.out.println("Porsi Dosen");
}
public void lembur(){
System.out.println("Dosen lembur");
}
public void infoDosen(){
System.out.println("Dosen");
System.out.println("==================");
this.bernafas();
this.makan();
this.lembur();
}
}
|
package me.the_red_freak.bptf.commands;
import org.bukkit.boss.BarColor;
import org.bukkit.boss.BarFlag;
import org.bukkit.boss.BarStyle;
import org.bukkit.boss.BossBar;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import me.the_red_freak.bptf.misc.BarCreator;
public class bar_command implements CommandExecutor {
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
Player p = null;
if(sender instanceof Player){
p = (Player) sender;
} else {
System.out.println("Only a player can execute this Command!");
return false;
}
String sentence = "";
for (String string : args) {
sentence = sentence + " " + string;
}
BossBar b = BarCreator.addBar(sentence, BarColor.GREEN, BarStyle.SEGMENTED_20, BarFlag.CREATE_FOG);
b.addPlayer(p);
return true;
}
}
|
package ncs.r4a118.rest;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Entity
@Table(name="users")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserInfo implements Serializable {
@Id
private int id;
private String name;
private String passwd;
@Column(name="registdate")
private String registDate;
@Column(name="updatedate")
private String updateDate;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.