text stringlengths 10 2.72M |
|---|
package Strings;
import java.util.Stack;
/*Objective is to reduce a string with condition like
* 1. we can delete any pair of adjacent letters with same value.
* For example, string "aabcc" would become either "aab" or "bcc"
* after operation.
* 2. If the final string is empty, print Empty String.
*
* Original String : aaabccddd
Reduced string : abd
Reduced string : abd
Original String: bccb
Reduced string : Empty String
Reduced string : Empty String
There are 2 methods to solve.
* */
public class StringSuperReduced {
//method 1
public static void reducedStringUsingStack(String string)
{
Stack<Character> stack = new Stack<>();
int h = 0; //height of stack
for (int i=0; i<string.length(); i++) {
if (!stack.isEmpty() && stack.peek().equals(string.charAt(i))) {
stack.pop(); //throw away
h--;
} else {
stack.push(string.charAt(i));
h++;
}
}
if (h == 0) {
System.out.println("Empty String");
}
else
{
char[] c = new char[h];
for (int i=h-1; i>=0; i--) {
c[i] = stack.pop();
}
System.out.println(new String(c));
}
}
//method 2
public static void reducedString(String string)
{
StringBuilder s = new StringBuilder(string);
for(int i = 1; i < s.length(); i++) {
if(s.charAt(i) == s.charAt(i-1)) {
s.delete(i-1, i+1);
i = 0;
}
}
if(s.length() == 0) System.out.println("Empty String");
else System.out.println(s);
}
public static void main(String[] args)
{
String string = "aaabccddd";
System.out.println("Original String : " + string);
System.out.print("Reduced string : ");
reducedStringUsingStack(string);
System.out.print("Reduced string : ");
reducedString(string);
string = "bccb";
System.out.println();
System.out.println("Original String: " + string);
System.out.print("Reduced string : ");
reducedStringUsingStack(string);
System.out.print("Reduced string : ");
reducedString(string);
}
}
|
/*
* Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.webui.common;
import com.vaadin.shared.ui.MarginInfo;
import com.vaadin.ui.AbstractSplitPanel;
import com.vaadin.ui.Component;
import com.vaadin.ui.HorizontalSplitPanel;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.VerticalSplitPanel;
/**
* Places the whole contents in container with margins.
* The content is divided with the {@link VerticalSplitPanel} or {@link HorizontalSplitPanel}.
* The two content components are placed in two split panels, with only one margin set, the one next to split bar.
* The size is set to full.
* @author K. Benedyczak
*/
public class CompositeSplitPanel extends VerticalLayout
{
private VerticalLayout vl1;
private VerticalLayout vl2;
public CompositeSplitPanel(boolean vertical, boolean needsMargin, int firstSpacePercent)
{
AbstractSplitPanel split;
vl1 = new VerticalLayout();
vl1.setSizeFull();
vl2 = new VerticalLayout();
vl2.setSizeFull();
if (vertical)
{
split = new VerticalSplitPanel();
vl1.setMargin(new MarginInfo(false, false, true, false));
vl2.setMargin(new MarginInfo(true, false, false, false));
} else
{
split = new HorizontalSplitPanel();
vl1.setMargin(new MarginInfo(false, true, false, false));
vl2.setMargin(new MarginInfo(false, false, false, true));
}
split.setFirstComponent(vl1);
split.setSecondComponent(vl2);
split.setSizeFull();
split.setSplitPosition(firstSpacePercent, Unit.PERCENTAGE);
addComponent(split);
setMargin(needsMargin);
setSizeFull();
}
public CompositeSplitPanel(boolean vertical, boolean needsMargin,
Component first, Component second, int firstSpacePercent)
{
this(vertical, needsMargin, firstSpacePercent);
setFirstComponent(first);
setSecondComponent(second);
}
public void setFirstComponent(Component first)
{
vl1.removeAllComponents();
vl1.addComponent(first);
}
public void setSecondComponent(Component second)
{
vl2.removeAllComponents();
vl2.addComponent(second);
}
}
|
package com.example.phonebook;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class Adapter extends BaseAdapter {
private Context context;
private List<Contact> listes;
private LayoutInflater inflater;
public Adapter(Context context,List<Contact> liste){
this.context = context;
this.listes = liste;
this.inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return listes.size();
}
@Override
public Contact getItem(int position) {
return listes.get(position);
}
@Override
public long getItemId(int position) {
return listes.get(position).getId();
}
//pour personnalisé chaque element/*
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = inflater.inflate(R.layout.adapter_layout,null);
// get infos about item
Contact currentContact = getItem(position);
Integer itemId = currentContact.getId();
String itemFirstName = currentContact.getFirstName();
String itemLastName = currentContact.getLastName();
String itemEmail = currentContact.getEmail();
String itemTel = currentContact.getPhone();
String itemProf = currentContact.getJob();
// get item name view
TextView itemIdView = convertView.findViewById(R.id.id);
itemIdView.setText(String.valueOf(itemId));
TextView itemNameView = convertView.findViewById(R.id.nom);
itemNameView.setText(itemLastName);
TextView itemFirstNameView = convertView.findViewById(R.id.prenom);
itemFirstNameView.setText(itemFirstName);
TextView itemEmailView = convertView.findViewById(R.id.email);
itemEmailView.setText(itemEmail);
TextView itemTelView = convertView.findViewById(R.id.tel);
itemTelView.setText(itemTel);
TextView itemProfView = convertView.findViewById(R.id.prof);
itemProfView.setText(itemProf);
return convertView;
}
}
|
/*
* 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 window.java;
import driver.DriverClass;
import driver.DriverFlight;
import java.sql.SQLException;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Rectangle2D;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.DateCell;
import javafx.scene.control.DatePicker;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.Spinner;
import javafx.scene.control.SpinnerValueFactory;
import javafx.scene.control.ToggleGroup;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Text;
import javafx.stage.Screen;
import javafx.stage.Stage;
/**
*
* @author Rohan
*/
public class Window extends Application {
//Decalration of fields
public RadioButton one_trip_btn,round_trip_btn;
public ToggleGroup trip_tg;
public ComboBox from_city_list,to_city_list,class_list;
public DatePicker depart_date,return_date;
public Spinner<Integer> adult_no,child_no,infant_no;
public Button search_btn, sign_in_btn, sign_up_btn, sign_out_btn;
public Scene scene;
public Image logo;
public GridPane page_1;
public Label hello_user_lbl;
private DriverFlight df = new DriverFlight();
private Traveller t = new Traveller();
private Flights fs = new Flights();
private User u =new User();
private AllDetails ad = new AllDetails();
@Override
public void start(Stage primaryStage) {
DriverClass dc = new DriverClass();
Login_scene ls = new Login_scene();
//setting full screen
//primaryStage.setFullScreen(true);
//Setting gridPane as layout for the page
page_1 = new GridPane();
//making gridlines visible
//page_1.setGridLinesVisible(true);
//css effects for page_1 i.e. gridpane
page_1.setId("page");
//setting gaps between rows and columns of grid
page_1.setHgap(10);
page_1.setVgap(10);
//padding of gridpane in scene
page_1.setPadding(new Insets(50,50,50,50));
//Logo Image
logo = new Image(Window.class.getResourceAsStream("air-logo.png"));
ImageView logo_view = new ImageView(logo);
//adding logo image to gridpane
page_1.add(logo_view,0,0);
//setting size of image logo
logo_view.setFitHeight(150);
logo_view.setFitWidth(200);
//scenetitle
Label scenetitle = new Label("Welcome To AeroSwing Flights...");
//adding css effects to label welcome-label
scenetitle.setId("welcome-label");
page_1.add(scenetitle, 1,0,4,2);
//Radio Buttons
one_trip_btn = new RadioButton("One Way Trip");
round_trip_btn = new RadioButton("Round Trip");
//ToggleGroup to select any one option for RadioButtons
trip_tg = new ToggleGroup();
one_trip_btn.setToggleGroup(trip_tg);
round_trip_btn.setToggleGroup(trip_tg);
//Setting Title for radioButtons
Text select_trip_text = new Text("Select Your Trip");
select_trip_text.setId("text");
//adding trip text and radio buttons to page
page_1.add(select_trip_text, 0,3,2,1);
page_1.add(one_trip_btn,0,4);
page_1.add(round_trip_btn,0,5);
//Journeydetails-text
Text jour_detail_text = new Text("Enter Your Journey Details");
jour_detail_text.setId("text");
page_1.add(jour_detail_text,0,7,2,1);
//Text for From:
Text from_state_text = new Text("Journey From :");
page_1.add(from_state_text,0,9);
//ComboBox for Source States
from_city_list = new ComboBox();
from_city_list.getItems().addAll("Mumbai","New Delhi","Bengaluru","Chennai");
from_city_list.setPromptText("---------select city---------");
from_city_list.setMaxSize(300,50);
page_1.add(from_city_list,1,9);
//css effects for combobox from_state_list
from_city_list.setId("combobox");
//departure date
depart_date = new DatePicker();
depart_date.setPromptText("Departure Date");
depart_date.setEditable(false);
page_1.add(depart_date,2,9);
//return date
return_date = new DatePicker();
return_date.setPromptText("Return Date");
return_date.setEditable(false);
page_1.add(return_date,2,11);
//disabling dates before toady's date and dates after 1 year
depart_date.setDayCellFactory(picker -> new DateCell(){
@Override
public void updateItem(LocalDate date, boolean empty){
super.updateItem(date, empty);
LocalDate today = LocalDate.now();
if(return_date.getValue()==null)
setDisable(empty || date.compareTo(today)<0 || date.isAfter(today.plusYears(1)));
else if(return_date.getValue()!=null)
setDisable(empty || date.compareTo(return_date.getValue())>0 || date.compareTo(today)<0 || date.isAfter(return_date.getValue().plusYears(1)));
}
});
//text for To:
Text to_state_text = new Text("To Destination:");
page_1.add(to_state_text,0,11);
//ComboBox for Destination Cities
to_city_list = new ComboBox();
to_city_list.getItems().addAll("Mumbai","New Delhi","Bengaluru","Chennai");
to_city_list.setPromptText("---------select city---------");
to_city_list.setMaxSize(300,50);
page_1.add(to_city_list,1,11);
//css effects for comobox to_state_list
to_city_list.setId("combobox");
//disabling dates before departure date and dates after 1 year
return_date.setDayCellFactory(picker -> new DateCell(){
@Override
public void updateItem(LocalDate date, boolean empty){
super.updateItem(date, empty);
LocalDate today = LocalDate.now();
if(depart_date.getValue()!=null)
setDisable(empty || date.compareTo(depart_date.getValue())<0 || date.isAfter(depart_date.getValue().plusYears(1)));
else if(depart_date.getValue()==null)
setDisable(empty || date.compareTo(today)<0 || date.isAfter(today.plusYears(1)));
}
});
//enabling return date if only round trip is selected
return_date.setDisable(true);
//if one way trip selected then disabling return date
one_trip_btn.setOnAction(e -> {
return_date.setDisable(true);
});
//if round trip selected then enabling return date
round_trip_btn.setOnAction(e -> {
return_date.setDisable(false);
});
//Text for Class
Text select_class = new Text("Select Class :");
page_1.add(select_class,0,14);
//ComboBox for selecting Class
class_list = new ComboBox();
class_list.getItems().addAll("Economy","Business","First");
class_list.setMaxSize(300,50);
page_1.add(class_list,1,14,1,1);
//css effects for comobox class_list
class_list.setId("combobox");
class_list.setPromptText("--------select class--------");
// class_list.setMinSize(to_city_list.getWidth(),to_city_list.getHeight());
//Text for travellers
Text travellers_txt = new Text("Traveller(s) :");
travellers_txt.setId("text");
page_1.add(travellers_txt,0,15,2,1);
//css effects for comobox travellers
//travellers_txt.setId("combobox");
//
Text adult_txt = new Text("Adult(above 15 yrs) :");
page_1.add(adult_txt,0,16);
adult_no = new Spinner<>();
//value_factory for adult i.e. setting range of values for no. of adults
adult_no.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(0,4,0));
page_1.add(adult_no, 0, 17);
Text child_txt = new Text("Child(2-15 yrs) :");
page_1.add(child_txt,1,16);
child_no = new Spinner<>();
//value_factory for child i.e. setting range of values for no. of child
child_no.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(0,4,0));
page_1.add(child_no, 1, 17);
Text infant_txt = new Text("Infant(Under 2 yrs) :");
page_1.add(infant_txt,2,16);
infant_no = new Spinner<>();
//value_factory for infant i.e. setting range of values for no. of infants
infant_no.setValueFactory(new SpinnerValueFactory.IntegerSpinnerValueFactory(0,4,0));
page_1.add(infant_no, 2, 17);
//signIn button actionevent
sign_in_btn = new Button("Sign in");
page_1.add(sign_in_btn, 0,26);
sign_in_btn.setOnAction(e ->{
Stage loginStage = new Stage();
ls.start(loginStage);
//primaryStage.close();
//SignIn button of login scene
ls.signin_btn.setOnAction(f -> {
if(ls.username_tf.getText().isEmpty() || ls.passwd_pf.getText().isEmpty())
{
Alert warning = new Alert(Alert.AlertType.WARNING);
warning.setTitle("Warning");
warning.setContentText("Both fields are mandatory");
warning.show();
}
else{
try {
u.setUserId(ls.username_tf.getText());
u.setPassword(ls.passwd_pf.getText());
dc.setUserData(u);
int flag=dc.checkCredentials();
switch (flag) {
case 0:
{
Alert warning = new Alert(Alert.AlertType.WARNING);
warning.setTitle("Warning");
warning.setContentText("Username or Password is Incorrect");
warning.show();
break;
}
case -1:
{
Alert warning = new Alert(Alert.AlertType.WARNING);
warning.setTitle("Warning");
warning.setContentText("Account does not exists");
warning.show();
break;
}
case 1:
{
primaryStage.show();
page_1.setVisible(true);
sign_in_btn.setVisible(false);
sign_in_btn.setDisable(true);
sign_out_btn.setVisible(true);
sign_out_btn.setDisable(false);
hello_user_lbl.setText("Hello "+dc.getUserData().getFirstName()+"!");
hello_user_lbl.setVisible(true);
hello_user_lbl.setDisable(false);
loginStage.close();
break;
}
default:
break;
}
} catch (SQLException ex) {
Logger.getLogger(Window.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
});
//
RadioButton trip = (RadioButton)trip_tg.getSelectedToggle();
sign_up_btn = new Button("Sign up");
page_1.add(sign_up_btn, 2, 26);
GridPane.setHalignment(sign_up_btn, HPos.RIGHT);
//signUp btn actionEvent
sign_up_btn.setOnAction(e->{
Stage sign_up_page = new Stage();
Sign_Up_Window spw = new Sign_Up_Window();
spw.start(sign_up_page);
});
search_btn = new Button("Search");
search_btn.setMaxSize(250, 50);
page_1.add(search_btn,1,23,2,1);
//search button ActionEvent
search_btn.setOnAction(e->{
if(trip_tg.getSelectedToggle()==null || from_city_list.getValue()==null || to_city_list.getValue()==null || class_list.getValue()==null)
{System.out.println("toogle");
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Incomplete Details");
alert.setContentText("Please fill all the required Fields");
alert.show();
}
else if(adult_no.getValue()==0 && child_no.getValue()==0 && infant_no.getValue()==0)
{System.out.println("no. of trav");
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Incomplete Details");
alert.setContentText("Please fill all the required Fields");
alert.show();
}
else if(((RadioButton)trip_tg.getSelectedToggle()).getText().equals("One Way Trip") && depart_date.getValue()==null)
{
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Incomplete Details");
alert.setContentText("Please fill all the required Fields");
alert.show();
}
else if(((RadioButton)trip_tg.getSelectedToggle()).getText().equals("Round Trip") && (depart_date.getValue()==null || return_date.getValue()==null))
{
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Incomplete Details");
alert.setContentText("Please fill all the required Fields");
alert.show();
}
else if(from_city_list.getValue().equals(to_city_list.getValue()))
{
Alert error = new Alert(Alert.AlertType.ERROR);
error.setTitle("Error");
error.setContentText("Choose a different Source or Destination");
error.show();
}
else
{
fs.trip = getFlightDetails().getTrip();
fs.src = getFlightDetails().getFromCity();
fs.dest = getFlightDetails().getToCity();
fs.adults = getFlightDetails().getAdults();
fs.childs = getFlightDetails().getChilds();
fs.infants = getFlightDetails().getInfants();
fs.depart_date = getFlightDetails().getDepartDate();
fs.return_date = getFlightDetails().getReturnDate();
df.setTravellerData(getFlightDetails());
try {
fs.setFlightData(df.getFlightRecords());
} catch (SQLException ex) {
Logger.getLogger(Window.class.getName()).log(Level.SEVERE, null, ex);
}
if(((RadioButton)trip_tg.getSelectedToggle()).getText().equals("Round Trip"))
{
try {
fs.setRoundFlightData(df.getRoundFlightRecord());
} catch (SQLException ex) {
Logger.getLogger(Window.class.getName()).log(Level.SEVERE, null, ex);
}
}
Stage flightSearchStage = new Stage();
try {
fs.start(flightSearchStage);
} catch (ParseException ex) {
Logger.getLogger(Window.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
sign_out_btn = new Button("Sign Out");
//sign_out btn actionEvent
sign_out_btn.setOnAction(e->{
hello_user_lbl.setVisible(false);
sign_out_btn.setVisible(false);
sign_out_btn.setDisable(true);
sign_in_btn.setDisable(false);
sign_in_btn.setVisible(true);
});
page_1.add(sign_out_btn, 0, 26);
sign_out_btn.setVisible(false);
sign_out_btn.setDisable(true);
hello_user_lbl = new Label();
hello_user_lbl.setStyle("-fx-font-size: 25px; -fx-text-fill: green");
page_1.add(hello_user_lbl, 0, 27);
hello_user_lbl.setVisible(false);
hello_user_lbl.setDisable(true);
ScrollPane rootPane = new ScrollPane();
rootPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
rootPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.ALWAYS);
rootPane.setFitToHeight(true);
rootPane.setFitToWidth(true);
//rootPane.setVmax(2);
//rootPane.setHmax(2);
//rootPane.setVvalue(20);
rootPane.setContent(page_1);
//instantiating scene
scene = new Scene(rootPane, 1000, 600);
scene.getStylesheets().add(Window.class.getResource("Window.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.setTitle("AeroSwing National Flights");
//primaryStage.setResizable(false);
//setting primaryStage to the size of screen of pc
Rectangle2D primaryScreenBounds = Screen.getPrimary().getVisualBounds();
//MinX and MinY are upper left corner of primaryStage
primaryStage.setX(primaryScreenBounds.getMinX());
primaryStage.setY(primaryScreenBounds.getMinY());
//setting width of stage to width of screen
primaryStage.setWidth(primaryScreenBounds.getWidth());
//setting height of stage to height of screen
primaryStage.setHeight(primaryScreenBounds.getHeight());
//primaryStage.initStyle(StageStyle.TRANSPARENT);
//show Stage
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
public Traveller getFlightDetails()
{
RadioButton trip = (RadioButton)trip_tg.getSelectedToggle();
t.setTrip(trip.getText());
t.setFromCity(from_city_list.getValue().toString());
t.setToCity(to_city_list.getValue().toString());
t.setClassType(class_list.getValue().toString());
t.setDepartDate(depart_date.getValue().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
if(((RadioButton)trip_tg.getSelectedToggle()).getText().equals("Round Trip"))
{
t.setReturnDate(return_date.getValue().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
}
t.setAdults(adult_no.getValue().toString());
t.setChilds(child_no.getValue().toString());
t.setInfants(infant_no.getValue().toString());
return t;
}
}
|
package haw.ci.lib.nodes;
import haw.ci.lib.SymbolTable;
import haw.ci.lib.descriptor.Descriptor;
public class ProcedureBodyNode extends AbstractNode {
private static final long serialVersionUID = -7312376636705994625L;
private StatementSequenceNode statementSequence;
private DeclarationNode declaration;
public ProcedureBodyNode(DeclarationNode declaration,
StatementSequenceNode statementSequence) {
this.declaration = declaration;
this.statementSequence = statementSequence;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((declaration == null) ? 0 : declaration.hashCode());
result = prime
* result
+ ((statementSequence == null) ? 0 : statementSequence
.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;
ProcedureBodyNode other = (ProcedureBodyNode) obj;
if (declaration == null) {
if (other.declaration != null)
return false;
} else if (!declaration.equals(other.declaration))
return false;
if (statementSequence == null) {
if (other.statementSequence != null)
return false;
} else if (!statementSequence.equals(other.statementSequence))
return false;
return true;
}
@Override
public String toString(int indentation) {
String result = toString(indentation, this.getClass().getName() + "\n");
if(statementSequence != null) {
result += statementSequence.toString() + "\n";
}
if(declaration != null) {
result += declaration.toString() + "\n";
}
return result;
}
@Override
public Descriptor compile(SymbolTable symbolTable){
declaration.compile(symbolTable);
statementSequence.compile(symbolTable);
return null;
}
}
|
import java.util.ArrayList;
import java.util.List;
public class Secretary {
List<General> savedGenerals;
List<General> livingGenerals;
Secretary(List<General> generals) {
this.livingGenerals = generals;
savedGenerals=new ArrayList<>();
for(General general: livingGenerals) {
savedGenerals.add((General) general.clone());
}
}
String getChanges() {
StringBuilder str=new StringBuilder();
for(int i=0;i<savedGenerals.size();i++) {
str.append("------------------------------------------------------\nZMIANY U GENERALA: ");
str.append(savedGenerals.get(i).getName());
str.append("\n");
String[] savedGeneralState=savedGenerals.get(i).toString().split("\n");
String[] livingGeneralState=livingGenerals.get(i).toString().split("\n");
for(int j=0; j<livingGeneralState.length; j++) {
if(j>=savedGeneralState.length) {
str.append("AFTER: ");
str.append(livingGeneralState[j]);
str.append("\n");
}
else
{
if(!savedGeneralState[j].equals(livingGeneralState[j])) {
str.append("BEFORE: ");
str.append(savedGeneralState[j]);
str.append("\n");
str.append("AFTER: ");
str.append(livingGeneralState[j]);
str.append("\n");
}
}
}
str.append("\n\nPODJĘTE DZIALANIA OD POCZĄTKU:\n");
str.append(livingGenerals.get(i).getAction());
str.append("\n------------------------------------------------------\n\n");
}
savedGenerals=new ArrayList<>();
for(General general: livingGenerals) {
savedGenerals.add((General) general.clone());
}
return str.toString();
}
}
|
package cn.partner.leetcode;
/**
* 两数之和
*
* 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
*
* 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
*
* 示例:
*
* 给定 nums = [2, 7, 11, 15], target = 9
*
* 因为 nums[0] + nums[1] = 2 + 7 = 9
* 所以返回 [0, 1]
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/two-sum
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
// LeetCode begin
class Solution {
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
return new int[] {i, j};
}
}
}
return null;
}
}
/**
* ↓参照大神用HashMap的写法,快很多
*/
//class Solution {
// static int r[] = new int[2];
// Map<Integer, Integer> map = new HashMap<Integer, Integer>();
// public int[] twoSum(int[] nums, int target) {
// for (int i = 0; i < nums.length; i++) {
// Integer v = map.get(nums[i]);
// if (v != null) {
// r[0] = v;
// r[1] = i;
// return r;
// }
// map.put(target - nums[i], i);
// }
// return null;
// }
//}
// LeetCode end
//Test
public class No_0001_Alg_0001_Two_Sum {
public static void main(String[] args) {
int[] result = new Solution().twoSum(new int[]{2, 7, 11, 15}, 9);
if (result != null)
System.out.println(String.format("[%d, %d]", result[0], result[1]));
}
}
/**
* Output:
* [0, 1]
*/
|
/*
BaseConverter -- converts one base to another for the Cellular Automaton Explorer.
Copyright (C) 2005 David B. Bahr (http://academic.regis.edu/dbahr/)
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package cellularAutomata.util.math;
import java.math.BigInteger;
/**
* Converts numbers from one base to another.
*
* @author David Bahr
*/
public class BaseConverter
{
private BaseConverter()
{
super();
}
/**
* Converts the given number in base 10 to a number in the base given by the
* radix. For example, if radix = 2, and num = 6, then this will return the
* string "1 1 0". All the digits are given as number. So hexadecimal
* numbers use the symbols 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
* 15 rather than the letters a, b, c, d, e. Each digit in the number is
* separated by a space.
*
* @param num
* The base 10 number that will be converted.
* @param radix
* The new base.
*
* @return A representation of num in the base given by radix.
*/
public static String convertBase(BigInteger num, int radix)
{
BigInteger bigIntRadix = BigInteger.valueOf(radix);
if(num.compareTo(bigIntRadix) < 0)
{
return new String("" + num);
}
else
{
return convertBase(num.divide(bigIntRadix), radix)
+ new String(" " + (num.mod(bigIntRadix)));
}
}
/**
* Converts the given number in base 10 to a number in the base given by the
* radix. For example, if radix = 2, and num = 6, then this will return the
* string "1 1 0". All the digits are given as number. So hexadecimal
* numbers use the symbols 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
* 15 rather than the letters a, b, c, d, e. Each digit in the number is
* separated by a space.
*
* @param num
* The base 10 number that will be converted.
* @param radix
* The new base.
*
* @return A representation of num in the base given by radix.
*/
public static String convertBase(int num, int radix)
{
if(num < radix)
{
return new String("" + num);
}
else
{
return convertBase(num / radix, radix)
+ new String(" " + (num % radix));
}
}
/**
* Converts the given number in base 10 to a number in the base given by the
* radix. For example, if radix = 2, and num = 6, then this will return the
* string "1 1 0". All the digits are given as number. So hexadecimal
* numbers use the symbols 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
* 15 rather than the letters a, b, c, d, e.
*
* @param num
* The base 10 number that will be converted.
* @param radix
* The new base.
*
* @return A representation of num in the base given by radix. Each digit of
* the number is in a separate array element. The 0th element
* contains the lowest order digit.
*/
public static int[] convertFromBaseTen(BigInteger num, int radix)
{
String newNumber = convertBase(num, radix);
String[] tokens = newNumber.split("\\s");
int[] digits = new int[tokens.length];
for(int i = 0; i < tokens.length; i++)
{
digits[i] = Integer.parseInt(tokens[tokens.length - 1 - i]);
}
return digits;
}
/**
* Converts the given number in base 10 to a number in the base given by the
* radix. For example, if radix = 2, and num = 6, then this will return the
* string "1 1 0". All the digits are given as number. So hexadecimal
* numbers use the symbols 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
* 15 rather than the letters a, b, c, d, e.
*
* @param num
* The base 10 number that will be converted.
* @param radix
* The new base.
*
* @return A representation of num in the base given by radix. Each digit of
* the number is in a separate array element. The 0th element
* contains the lowest order digit.
*/
public static int[] convertFromBaseTen(int num, int radix)
{
String newNumber = convertBase(num, radix);
String[] tokens = newNumber.split("\\s");
int[] digits = new int[tokens.length];
for(int i = 0; i < tokens.length; i++)
{
digits[i] = Integer.parseInt(tokens[tokens.length - 1 - i]);
}
return digits;
}
/**
* Converts a string (in the base given by radix) to a base 10 integer. The
* radix may be 2 to 36. Each digit in the string is given by 0...9 or a...z
* (or equivalently A...Z). This code uses the constructor
* BigInteger(string, radix), and additional details may be found there.
*
* @param theNumber
* The number represented as a string. May only contain digits
* 0...9 and a...z (or equivalently A...Z).
* @param radix
* The base of the number (for example, 2 is binary). The base
* may be between 2 and 36.
*
* @return The corresponding number in base 10. If the corresponding number
* is bigger than a long, then the output is not guaranteed or
* specified. See BigInteger for details.
*/
public static long convertToBaseTen(String theNumber, int radix)
{
BigInteger theInteger = new BigInteger(theNumber, radix);
return theInteger.longValue();
}
}
|
/*
* Copyright (C) 2020 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 android.net.vcn;
import static java.util.Objects.requireNonNull;
import android.annotation.NonNull;
import android.annotation.RequiresPermission;
import android.annotation.SystemService;
import android.content.Context;
import android.net.LinkProperties;
import android.net.NetworkCapabilities;
import android.os.ParcelUuid;
import android.os.RemoteException;
import android.os.ServiceSpecificException;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.annotations.VisibleForTesting.Visibility;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
/**
* VcnManager publishes APIs for applications to configure and manage Virtual Carrier Networks.
*
* <p>A VCN creates a virtualization layer to allow MVNOs to aggregate heterogeneous physical
* networks, unifying them as a single carrier network. This enables infrastructure flexibility on
* the part of MVNOs without impacting user connectivity, abstracting the physical network
* technologies as an implementation detail of their public network.
*
* <p>Each VCN virtualizes an Carrier's network by building tunnels to a carrier's core network over
* carrier-managed physical links and supports a IP mobility layer to ensure seamless transitions
* between the underlying networks. Each VCN is configured based on a Subscription Group (see {@link
* android.telephony.SubscriptionManager}) and aggregates all networks that are brought up based on
* a profile or suggestion in the specified Subscription Group.
*
* <p>The VCN can be configured to expose one or more {@link android.net.Network}(s), each with
* different capabilities, allowing for APN virtualization.
*
* <p>If a tunnel fails to connect, or otherwise encounters a fatal error, the VCN will attempt to
* reestablish the connection. If the tunnel still has not reconnected after a system-determined
* timeout, the VCN Safe Mode (see below) will be entered.
*
* <p>The VCN Safe Mode ensures that users (and carriers) have a fallback to restore system
* connectivity to update profiles, diagnose issues, contact support, or perform other remediation
* tasks. In Safe Mode, the system will allow underlying cellular networks to be used as default.
* Additionally, during Safe Mode, the VCN will continue to retry the connections, and will
* automatically exit Safe Mode if all active tunnels connect successfully.
*
* @hide
*/
@SystemService(Context.VCN_MANAGEMENT_SERVICE)
public class VcnManager {
@NonNull private static final String TAG = VcnManager.class.getSimpleName();
private static final Map<
VcnUnderlyingNetworkPolicyListener, VcnUnderlyingNetworkPolicyListenerBinder>
REGISTERED_POLICY_LISTENERS = new ConcurrentHashMap<>();
@NonNull private final Context mContext;
@NonNull private final IVcnManagementService mService;
/**
* Construct an instance of VcnManager within an application context.
*
* @param ctx the application context for this manager
* @param service the VcnManagementService binder backing this manager
*
* @hide
*/
public VcnManager(@NonNull Context ctx, @NonNull IVcnManagementService service) {
mContext = requireNonNull(ctx, "missing context");
mService = requireNonNull(service, "missing service");
}
/**
* Get all currently registered VcnUnderlyingNetworkPolicyListeners for testing purposes.
*
* @hide
*/
@VisibleForTesting(visibility = Visibility.PRIVATE)
@NonNull
public static Map<VcnUnderlyingNetworkPolicyListener, VcnUnderlyingNetworkPolicyListenerBinder>
getAllPolicyListeners() {
return Collections.unmodifiableMap(REGISTERED_POLICY_LISTENERS);
}
// TODO: Make setVcnConfig(), clearVcnConfig() Public API
/**
* Sets the VCN configuration for a given subscription group.
*
* <p>An app that has carrier privileges for any of the subscriptions in the given group may set
* a VCN configuration. If a configuration already exists for the given subscription group, it
* will be overridden. Any active VCN(s) may be forced to restart to use the new configuration.
*
* <p>This API is ONLY permitted for callers running as the primary user.
*
* @param subscriptionGroup the subscription group that the configuration should be applied to
* @param config the configuration parameters for the VCN
* @throws SecurityException if the caller does not have carrier privileges, or is not running
* as the primary user
* @throws IOException if the configuration failed to be persisted. A caller encountering this
* exception should attempt to retry (possibly after a delay).
* @hide
*/
@RequiresPermission("carrier privileges") // TODO (b/72967236): Define a system-wide constant
public void setVcnConfig(@NonNull ParcelUuid subscriptionGroup, @NonNull VcnConfig config)
throws IOException {
requireNonNull(subscriptionGroup, "subscriptionGroup was null");
requireNonNull(config, "config was null");
try {
mService.setVcnConfig(subscriptionGroup, config, mContext.getOpPackageName());
} catch (ServiceSpecificException e) {
throw new IOException(e);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
// TODO: Make setVcnConfig(), clearVcnConfig() Public API
/**
* Clears the VCN configuration for a given subscription group.
*
* <p>An app that has carrier privileges for any of the subscriptions in the given group may
* clear a VCN configuration. This API is ONLY permitted for callers running as the primary
* user. Any active VCN will be torn down.
*
* @param subscriptionGroup the subscription group that the configuration should be applied to
* @throws SecurityException if the caller does not have carrier privileges, or is not running
* as the primary user
* @throws IOException if the configuration failed to be cleared. A caller encountering this
* exception should attempt to retry (possibly after a delay).
* @hide
*/
@RequiresPermission("carrier privileges") // TODO (b/72967236): Define a system-wide constant
public void clearVcnConfig(@NonNull ParcelUuid subscriptionGroup) throws IOException {
requireNonNull(subscriptionGroup, "subscriptionGroup was null");
try {
mService.clearVcnConfig(subscriptionGroup);
} catch (ServiceSpecificException e) {
throw new IOException(e);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
// TODO: make VcnUnderlyingNetworkPolicyListener @SystemApi
/**
* VcnUnderlyingNetworkPolicyListener is the interface through which internal system components
* can register to receive updates for VCN-underlying Network policies from the System Server.
*
* @hide
*/
public interface VcnUnderlyingNetworkPolicyListener {
/**
* Notifies the implementation that the VCN's underlying Network policy has changed.
*
* <p>After receiving this callback, implementations MUST poll VcnManager for the updated
* VcnUnderlyingNetworkPolicy via VcnManager#getUnderlyingNetworkPolicy.
*/
void onPolicyChanged();
}
/**
* Add a listener for VCN-underlying network policy updates.
*
* @param executor the Executor that will be used for invoking all calls to the specified
* Listener
* @param listener the VcnUnderlyingNetworkPolicyListener to be added
* @throws SecurityException if the caller does not have permission NETWORK_FACTORY
* @throws IllegalArgumentException if the specified VcnUnderlyingNetworkPolicyListener is
* already registered
* @hide
*/
@RequiresPermission(android.Manifest.permission.NETWORK_FACTORY)
public void addVcnUnderlyingNetworkPolicyListener(
@NonNull Executor executor, @NonNull VcnUnderlyingNetworkPolicyListener listener) {
requireNonNull(executor, "executor must not be null");
requireNonNull(listener, "listener must not be null");
VcnUnderlyingNetworkPolicyListenerBinder binder =
new VcnUnderlyingNetworkPolicyListenerBinder(executor, listener);
if (REGISTERED_POLICY_LISTENERS.putIfAbsent(listener, binder) != null) {
throw new IllegalArgumentException(
"Attempting to add a listener that is already in use");
}
try {
mService.addVcnUnderlyingNetworkPolicyListener(binder);
} catch (RemoteException e) {
REGISTERED_POLICY_LISTENERS.remove(listener);
throw e.rethrowFromSystemServer();
}
}
/**
* Remove the specified VcnUnderlyingNetworkPolicyListener from VcnManager.
*
* <p>If the specified listener is not currently registered, this is a no-op.
*
* @param listener the VcnUnderlyingNetworkPolicyListener that will be removed
* @hide
*/
public void removeVcnUnderlyingNetworkPolicyListener(
@NonNull VcnUnderlyingNetworkPolicyListener listener) {
requireNonNull(listener, "listener must not be null");
VcnUnderlyingNetworkPolicyListenerBinder binder =
REGISTERED_POLICY_LISTENERS.remove(listener);
if (binder == null) {
return;
}
try {
mService.removeVcnUnderlyingNetworkPolicyListener(binder);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
/**
* Queries the underlying network policy for a network with the given parameters.
*
* <p>Prior to a new NetworkAgent being registered, or upon notification that Carrier VCN policy
* may have changed via {@link VcnUnderlyingNetworkPolicyListener#onPolicyChanged()}, a Network
* Provider MUST poll for the updated Network policy based on that Network's capabilities and
* properties.
*
* @param networkCapabilities the NetworkCapabilities to be used in determining the Network
* policy for this Network.
* @param linkProperties the LinkProperties to be used in determining the Network policy for
* this Network.
* @throws SecurityException if the caller does not have permission NETWORK_FACTORY
* @return the VcnUnderlyingNetworkPolicy to be used for this Network.
* @hide
*/
@NonNull
@RequiresPermission(android.Manifest.permission.NETWORK_FACTORY)
public VcnUnderlyingNetworkPolicy getUnderlyingNetworkPolicy(
@NonNull NetworkCapabilities networkCapabilities,
@NonNull LinkProperties linkProperties) {
requireNonNull(networkCapabilities, "networkCapabilities must not be null");
requireNonNull(linkProperties, "linkProperties must not be null");
try {
return mService.getUnderlyingNetworkPolicy(networkCapabilities, linkProperties);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
/**
* Binder wrapper for added VcnUnderlyingNetworkPolicyListeners to receive signals from System
* Server.
*
* @hide
*/
private static class VcnUnderlyingNetworkPolicyListenerBinder
extends IVcnUnderlyingNetworkPolicyListener.Stub {
@NonNull private final Executor mExecutor;
@NonNull private final VcnUnderlyingNetworkPolicyListener mListener;
private VcnUnderlyingNetworkPolicyListenerBinder(
Executor executor, VcnUnderlyingNetworkPolicyListener listener) {
mExecutor = executor;
mListener = listener;
}
@Override
public void onPolicyChanged() {
mExecutor.execute(() -> mListener.onPolicyChanged());
}
}
}
|
package com.cqut.util.timeTask;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class TaskListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent sce) {
new TimerManager();
}
public void contextDestroyed(ServletContextEvent sce) {
}
}
|
package pp.model.comparators;
import pp.model.Trnm;
public class CapableGladsComparator implements java.util.Comparator<pp.model.Trnm> {
@Override
public int compare(Trnm o1, Trnm o2) {
return Double.compare(o2.getGladsCapacity(), o1.getGladsCapacity());
}
}
|
import java.util.Scanner;
public class main{
public void calcular(int x,int y,int z){
if((x<y)&&(x>z)){
System.out.println("El numero de enmedio es: "+x);
}else{
if((y<x)&&(y>z)){
System.out.println("El numero de enmedio es: "+y);
}else{
if((z<y)&&(z>x)){
System.out.println("El numero de enmedio es: "+z);
}
}
}
}
public static void main(String []args){
Scanner sc=new Scanner(System.in);
main o=new main();
int x,y,z;
System.out.println("Dime un numero");
x=sc.nextInt();
System.out.println("Dime un numero");
y=sc.nextInt();
System.out.println("Dime un numero");
z=sc.nextInt();
o.calcular(x, y, z);
}
} |
package com.cg.project.main;
public class AppMain {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Hello World");
int value=10;
value+=20;
System.out.println(value);
}
}
|
package com.SearchHouse.service;
import java.util.List;
import com.SearchHouse.pojo.BedRoom;
public interface BedRoomService {
//增加
public void addBedRoom(BedRoom bedroom);
//删除
public void deleteRoom(int bedroomId);
//更新
public void updateRoom(BedRoom bedroom);
//查询单个
public BedRoom getRoomById(int bedroomId);
//查询
public List<BedRoom> queryAllRoom();
}
|
package com.isg.ifrend.core.model.mli.dto;
public class AccountClosureDTO {
}
|
/**
*
*/
package com.smartech.course.racing.vehicle.payload;
/**
* Simple payload carried by a truck or a car trailer
* @author Alexey Solomatin
*
*/
public class SimplePayload implements PayloadCarriable {
private double maxPayloadWeight;
private double payloadWeight;
/**
*
*/
public SimplePayload(double maxPayloadWeight, double payloadWeight) {
this.maxPayloadWeight = maxPayloadWeight;
this.payloadWeight = payloadWeight;
}
/* (non-Javadoc)
* @see com.smartech.course.racing.vehicle.PayloadCarriable#getMaxPayloadWeight()
*/
@Override
public double getMaxPayloadWeight() {
return maxPayloadWeight;
}
/* (non-Javadoc)
* @see com.smartech.course.racing.vehicle.PayloadCarriable#getPayloadWeight()
*/
@Override
public double getPayloadWeight() {
return payloadWeight;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "SimplePayload [maxPayloadWeight=" + maxPayloadWeight + ", payloadWeight=" + payloadWeight + "]";
}
}
|
package com.twofactorauth.boundary.impl;
import com.twofactorauth.boundary.UserServiceI;
import com.twofactorauth.entity.MessageModel;
import com.twofactorauth.entity.UserModel;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
@Stateless
public class UserServiceImpl extends AbstractBeanImpl<UserModel,Long> implements UserServiceI{
@PersistenceContext(unitName = "pu")
EntityManager em;
public UserServiceImpl() {
super(UserModel.class);
}
@Override
protected EntityManager getEntityManager() {
return em;
}
@Override
public MessageModel getUser(String userName, String pwd) {
Query q= em.createQuery("FROM UserModel u WHERE u.username=:username AND u.pwd=:pwd",UserModel.class);
q.setParameter("username",userName);
q.setParameter("pwd",pwd);
UserModel userModel= (UserModel) q.getSingleResult();
return new MessageModel(
userModel!=null?true:false,
"Done",
userModel
);
}
@Override
public MessageModel updateToken(Long id, String token) {
Query q=em.createQuery("UPDATE UserModel u set u.oneSignalToken=:token WHERE u.id=:id");
q.setParameter("token",token);
q.setParameter("id",id);
q.executeUpdate();
return new MessageModel(
true,
"Done"
);
}
@Override
public MessageModel updateAccess(Long id, boolean isAllowed) {
Query q=em.createQuery("UPDATE UserModel u set u.isAllowed=:isAllowed,u.requestStatus=1 WHERE u.id=:id");
q.setParameter("isAllowed",isAllowed);
q.setParameter("id",id);
q.executeUpdate();
return new MessageModel(
true,
"Done"
);
}
@Override
public MessageModel requestStatus(Long id) throws Exception{
Query q= em.createQuery("SELECT u.requestStatus AS rs,u.isAllowed AS al FROM UserModel u WHERE u.id=:id");
q.setParameter("id",id);
// Boolean b= (Boolean) q.getSingleResult();
Object map=q.getSingleResult();
return new MessageModel(
true,
"Done",
map
);
}
/**
* Send request here
* @param id
* @param token
* @return
*/
@Override
public MessageModel iniate2FA(Long id, String token) {
// write code here
//set isAllowed to false, then send notification
updateAccess(id,false);
sendRequest(id,token);
return new MessageModel(
true,
"Done"
);
}
@Override
public MessageModel getDefault() {
return new MessageModel(
false,
"No data found"
);
}
/**
*
* @param id
* @param token
*/
private void sendRequest(Long id,String token){
try {
String jsonResponse;
URL url = new URL("https://onesignal.com/api/v1/notifications");
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setUseCaches(false);
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setRequestMethod("POST");
String strJsonBody = "{"
+ "\"app_id\": \"768b0275-4652-4d4f-b6bb-b31438dda180\","
+ "\"include_player_ids\": [\""+token+"\"],"
+ "\"data\": {\"id\": \""+id+"\"},"
+ "\"contents\": {"
+ "\"en\": \"2FA Action required\""
+ "},"
+ "\"headings\": {"
+ "\"en\": \"Hi There\""
+ "}"
+ "}";
System.out.println("strJsonBody:\n" + strJsonBody);
byte[] sendBytes = strJsonBody.getBytes("UTF-8");
con.setFixedLengthStreamingMode(sendBytes.length);
OutputStream outputStream = con.getOutputStream();
outputStream.write(sendBytes);
int httpResponse = con.getResponseCode();
System.out.println("httpResponse: " + httpResponse);
Scanner scanner;
if ( httpResponse >= HttpURLConnection.HTTP_OK
&& httpResponse < HttpURLConnection.HTTP_BAD_REQUEST) {
scanner = new Scanner(con.getInputStream(), "UTF-8");
}
else {
scanner = new Scanner(con.getErrorStream(), "UTF-8");
}
jsonResponse = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
scanner.close();
System.out.println("jsonResponse:\n" + jsonResponse);
} catch(Throwable t) {
t.printStackTrace();
}
}
}
|
package com.ubuntu4u.ubuntu4u.ubuntu4u_client.state;
/**
* Created by Q. Engelbrecht on 2017-06-16.
*/
public class AppState {
public String DeviceToken;
public String TokenStatus;
public int UserID;
public String DisplayName;
public String MobileNumber;
public String ProfilePicture;
}
|
package com.mindtree.runner;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.testng.Assert;
import org.testng.ITestResult;
import org.testng.TestRunner;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.markuputils.ExtentColor;
import com.aventstack.extentreports.markuputils.MarkupHelper;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
import com.mindtree.reusablecomponents.ReusableComponents;
import com.mindtree.reusablecomponents.ReusableMethods;
import com.mindtree.uistore.HomePageUI;
import com.mindtree.utility.Log;
import com.mindtree.utility.PropertyFileReader;
public class Runner{
private Logger log = (Logger) Log.logger(TestRunner.class.getName());
WebDriver driver;
public Runner() throws IOException {
System.out.println("working");
driver = ReusableComponents.loadDriver();
}
@BeforeTest
public void homePage() throws IOException {
driver.manage().window().maximize();
ReusableMethods.loadURL(driver);
}
@Test (priority = 0)
public void Login() {
ReusableMethods.hover(HomePageUI.header_profile, driver);
ReusableMethods.click(HomePageUI.Login, driver);
log.info("opened login page");
}
@Test (priority = 1,dataProvider="getSearchData")
public void search(String name) throws IOException {
ReusableMethods.sendKeys(HomePageUI.search_bar, name, driver);
ReusableMethods.click(HomePageUI.search_button, driver);
System.out.println(driver.getTitle());
log.info("searched for item and verified it");
}
@Test (priority = 2)
public void subscribe() throws InterruptedException {
ReusableMethods.sendKeys(HomePageUI.subscribe_input, "random@gmail.com", driver);
ReusableMethods.click(HomePageUI.subscribe_btn, driver);
System.out.print(ReusableMethods.getText(HomePageUI.subscribe_success, driver));
log.info("searched for item and verified it");
}
@Test (priority = 3)
public void Google_playapp() throws InterruptedException {
ReusableMethods.click(HomePageUI.playapp, driver);
System.out.println(driver.getTitle());
}
@Test (priority = 4)
public void iOS_app() throws InterruptedException {
ReusableMethods.click(HomePageUI.iOSapp, driver);
System.out.println(driver.getTitle());
}
@Test(priority=5)
public void insta() {
ReusableMethods.click(HomePageUI.insta, driver);
System.out.println(driver.getTitle());
}
@Test (priority = 6)
public void payment_methods(String method) throws InterruptedException {
List<WebElement> pay = ReusableMethods.getElements(HomePageUI.payment_method, driver);
boolean found = false;
for(int i=0;i<pay.size();i++) {
if(pay.get(i).getAttribute("alt").toLowerCase().contains(method)) {
found = true;
break;
}
}
assertTrue(found);
}
@Test (priority = 7)
public void offers_bar() throws InterruptedException {
String size =new Integer(ReusableMethods.getElements(HomePageUI.n_offers, driver).size()).toString();
assertEquals(size,"2");
}
@Test (priority = 8)
public void head_alert() throws InterruptedException {
assertTrue(ReusableMethods.getElement(HomePageUI.header_profile, driver));
}
@Test (priority = 9)
public void count_furniture() {
String size =new Integer(ReusableMethods.getElements(HomePageUI.n_item_furniture, driver).size()).toString();
assertEquals(size,21);
}
}
|
/*
* Copyright 2002-2022 the original author or authors.
*
* 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
*
* https://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.springframework.aot.hint.annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.junit.jupiter.api.Test;
import org.springframework.aot.hint.ExecutableMode;
import org.springframework.aot.hint.ReflectionHints;
import org.springframework.aot.hint.TypeReference;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link SimpleReflectiveProcessor}.
*
* @author Stephane Nicoll
*/
class SimpleReflectiveProcessorTests {
private final SimpleReflectiveProcessor processor = new SimpleReflectiveProcessor();
private final ReflectionHints hints = new ReflectionHints();
@Test
void registerReflectiveHintsForClass() {
processor.registerReflectionHints(hints, SampleBean.class);
assertThat(hints.typeHints()).singleElement().satisfies(typeHint -> {
assertThat(typeHint.getType()).isEqualTo(TypeReference.of(SampleBean.class));
assertThat(typeHint.getMemberCategories()).isEmpty();
assertThat(typeHint.constructors()).isEmpty();
assertThat(typeHint.fields()).isEmpty();
assertThat(typeHint.methods()).isEmpty();
});
}
@Test
void registerReflectiveHintsForConstructor() {
Constructor<?> constructor = SampleBean.class.getDeclaredConstructors()[0];
processor.registerReflectionHints(hints, constructor);
assertThat(hints.typeHints()).singleElement().satisfies(typeHint -> {
assertThat(typeHint.getType()).isEqualTo(TypeReference.of(SampleBean.class));
assertThat(typeHint.getMemberCategories()).isEmpty();
assertThat(typeHint.constructors()).singleElement().satisfies(constructorHint -> {
assertThat(constructorHint.getName()).isEqualTo("<init>");
assertThat(constructorHint.getMode()).isEqualTo(ExecutableMode.INVOKE);
assertThat(constructorHint.getParameterTypes()).containsExactly(TypeReference.of(String.class));
});
assertThat(typeHint.fields()).isEmpty();
assertThat(typeHint.methods()).isEmpty();
});
}
@Test
void registerReflectiveHintsForField() throws NoSuchFieldException {
Field field = SampleBean.class.getDeclaredField("name");
processor.registerReflectionHints(hints, field);
assertThat(hints.typeHints()).singleElement().satisfies(typeHint -> {
assertThat(typeHint.getType()).isEqualTo(TypeReference.of(SampleBean.class));
assertThat(typeHint.getMemberCategories()).isEmpty();
assertThat(typeHint.constructors()).isEmpty();
assertThat(typeHint.fields()).singleElement().satisfies(fieldHint ->
assertThat(fieldHint.getName()).isEqualTo("name"));
assertThat(typeHint.methods()).isEmpty();
});
}
@Test
void registerReflectiveHintsForMethod() throws NoSuchMethodException {
Method method = SampleBean.class.getDeclaredMethod("setName", String.class);
processor.registerReflectionHints(hints, method);
assertThat(hints.typeHints()).singleElement().satisfies(typeHint -> {
assertThat(typeHint.getType()).isEqualTo(TypeReference.of(SampleBean.class));
assertThat(typeHint.getMemberCategories()).isEmpty();
assertThat(typeHint.constructors()).isEmpty();
assertThat(typeHint.fields()).isEmpty();
assertThat(typeHint.methods()).singleElement().satisfies(methodHint -> {
assertThat(methodHint.getName()).isEqualTo("setName");
assertThat(methodHint.getMode()).isEqualTo(ExecutableMode.INVOKE);
assertThat(methodHint.getParameterTypes()).containsExactly(TypeReference.of(String.class));
});
});
}
static class SampleBean {
@SuppressWarnings("unused")
private String name;
SampleBean(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
}
}
|
package com.arch.dependencyrule.application;
import com.arch.dependencyrule.presentation.StudentViewModelPOJO;
public interface InputBoundary {
StudentViewModelPOJO saveAndPresentStudent(StudentInputPOJO pojo);
}
|
package br.com.mixfiscal.prodspedxnfe.domain.enums;
import br.com.mixfiscal.prodspedxnfe.domain.ex.EnumDesconhecidoException;
public enum ETipoICMS {
ICMS00((byte)0),
ICMS10((byte)2),
ICMS20((byte)3),
ICMS30((byte)4),
ICMS40((byte)5),
ICMS41((byte)6),
ICMS50((byte)7),
ICMS51((byte)8),
ICMS60((byte)9),
ICMS70((byte)10),
ICMS90((byte)11);
private final byte codICMS;
private ETipoICMS(byte codICMS) {
this.codICMS = codICMS;
}
public byte getCodICMS() {
return codICMS;
}
public static ETipoICMS deCodigo(String codigo) throws EnumDesconhecidoException, NumberFormatException {
int iCodigo = Integer.parseInt(codigo);
return deCodigo(iCodigo);
}
public static ETipoICMS deCodigo(int codigo) throws EnumDesconhecidoException {
for (ETipoICMS tipoItem : ETipoICMS.values()) {
if (tipoItem.getCodICMS() == codigo)
return tipoItem;
}
throw new EnumDesconhecidoException();
}
}
|
package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
public class UpdateDAO {
//更新SQL update(ユーザーID、更新する項目のlist)
public static void update(String userid,ArrayList<String> list){
Connection con = null;
PreparedStatement pstmt = null;
@SuppressWarnings("unused")
int rs = 0;
try{
int j = 0;
for(int i=0;i<list.size()/2;i++){
String[] array1 = list.get(j).split(",");
/*array1[0] = 更新前の収入 or 収支
*array1[1] = 更新前の内容
*array1[2] = 更新前のコスト
*/
String[] array2 = list.get(j+1).split(",");
/*array2[0] = 更新後の収入 or 収支
*array2[1] = 更新後の内容
*array2[2] = 更新後のコスト
*/
j=j+2;
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/motonote?useSSL=false",
"adminuser",
"password");
String sql = "UPDATE book set RE = ?, content = ?, price = ? WHERE userid = ? AND RE = ? AND content = ? AND price = ? LIMIT 1;";
pstmt = con.prepareStatement(sql);
pstmt.setInt(1, Integer.parseInt(array2[0]));
pstmt.setString(2, array2[1]);
pstmt.setInt(3, Integer.parseInt(array2[2]));
pstmt.setString(4, userid);
pstmt.setInt(5, Integer.parseInt(array1[0]));
pstmt.setString(6, array1[1]);
pstmt.setInt(7, Integer.parseInt(array1[2]));
rs = pstmt.executeUpdate();
con.close();
}
} catch (SQLException e){
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
|
package jdk8.lamda;
import java.util.List;
import java.util.function.IntFunction;
import java.util.function.ToIntFunction;
import com.google.common.collect.Lists;
public class HelloFunction {
public static void main(String[] args) {
// 准备测试对象
IntFunction<Integer> addFun = addNum(3, items -> {
// 利用reduce进行求值
return items.stream().reduce(0, (x, y) -> x + y);
});
// 方法调用还很生硬,有个莫名其妙的函数名apply,可能会引起业务的误解
addFun.apply(1);
addFun.apply(2);
addFun.apply(3);
// 超过了数量不求值
int result = addFun.apply(4);
// 1+2+3 = 6
//assertThat(result, IsEqual.equalTo(6));
}
/**
* 输入一定数量的参数,然后统一求值,这个函数是个高阶函数
* @param size 需要求值的个数
* @param fn 求值函数
* @return 函数对象
* 从函数的定义就可以看出,Java函数编程的内在思想还是面向对象
*/
public static IntFunction<Integer> addNum(int size, ToIntFunction<List<Integer>> fn) {
// 声明局部变量,用于存储传入参数
final List<Integer> args = Lists.newArrayList();
return (value) -> {
int result = -1;
if(args.size() == size) {
result = fn.applyAsInt(args);
} else {
args.add(value);
}
// 返回结果
return result;
};
// return new IntFunction<Integer>() {
//
// @Override
// public Integer apply(int value) {
// // 没有达到定义的数量之前,不求值
// int result = -1;
// if(args.size() == size) {
// result = fn.applyAsInt(args);
// } else {
// args.add(value);
// }
// // 返回结果
// return result;
// }
//
// };
}
}
|
package 构建者模式.v1;
/**
* 电脑对象的实际构建者实现
* @author ethan
*/
public class ComputerActualBuilder implements Builder {
private Computer computer = new Computer();
@Override
public void buildDisplay(String display) {
computer.setDisplay(display);
}
@Override
public void buildHost(String host) {
computer.setHost(host);
}
@Override
public void buildOs(String os) {
computer.setOs(os);
}
@Override
public Computer build() {
return computer;
}
}
|
package com.forever.serviceimpl;
import com.forever.service.IHelloService;
/**
* @Description:
* @Author: zhang
* @Date: 2019/6/18
*/
public class HelloServiceImpl implements IHelloService {
public String hello(String name) {
return "hello " + name;
}
}
|
public class testmahasiswa {
public static void main(String[] args) {
mahasiswa mhs = new mahasiswa("nurul dwi ariyanti",20);
mhs.tampilkanbiodata();
System.out.println();
mhs.setOld (25);
mhs.tampilkanbiodata();
}
} |
package ioc.Demo1;
/**
* Created by Yingjie.Lu on 2018/8/2.
*/
public class HelloWorld {
public void say(){
System.out.println("spring ioc");
}
}
|
package ru.alexside.dto;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Alex on 25.03.2018.
*/
@Data
public class ContactFull {
private Long id;
private String type;
private String name;
private String companyName;
private String description;
private List<String> contacts = new ArrayList<>();
}
|
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package JavaTeacherLib;
import JavaTeacherLib.LlkContext;
import JavaTeacherLib.Node;
import JavaTeacherLib.TableNode;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Iterator;
import java.util.LinkedList;
public class MyLang {
private int axioma;
private boolean create;
private int LLK;
private LinkedList<Node> language;
private LinkedList<TableNode> lexemaTable;
private int[] terminals;
private int[] nonterminals;
private int[] epsilonNerminals;
private LlkContext[] termLanguarge;
private LlkContext[] firstK;
private LlkContext[] followK;
private LinkedList<LlkContext>[] LocalkContext;
private int[][] uprTable;
private int siz=0; //размер массива нетерминалов которые нам подходят
private static final int Cons = 1522;
// public boolean lab() {
// int[] nonterm = this.getNonTerminals();
// LlkContext[] firstContext = this.getFirstK();
// if(firstContext != null) {
// for(int j = 0; j < nonterm.length; ++j) {
// System.out.println("FirstK-контекст для нетермінала: " + this.getLexemaText(nonterm[j]));
// LlkContext tmp = firstContext[j];
//
// for(int ii = 0; ii < tmp.calcWords(); ++ii) {
// int[] word = tmp.getWord(ii);
// if(word.length == 0) {
// System.out.print("Е-слово");
// } else {
// for(int ii1 = 0; ii1 < word.length; ++ii1) {
// System.out.print(this.getLexemaText(word[ii1]) + " ");
// }
// }
//
// System.out.println();
// }
// }
//
// }
// int[] napr=new int[Cons];
// Iterator i$ = this.language.iterator();
//
// while(i$.hasNext()) {
// Node tmp = (Node)i$.next();
// int[] roole = tmp.getRoole();
//// if ()
// for(int ii = 0; ii < roole.length; ++ii) {
//
// System.out.print(this.getLexemaText(roole[ii]) + " ! ");
// if(roole.length == 1) {
// System.out.print(" -> ");
// }
// }
//
// System.out.println("");
// }
//
// }
//
public MyLang(String fileLang, int llk1) {
this.LLK = llk1;
this.create = false;
this.language = new LinkedList();
this.lexemaTable = new LinkedList();
this.readGrammat(fileLang);
if(this.create) {
Iterator i$ = this.language.iterator();
if(i$.hasNext()) {
Node tmp = (Node)i$.next();
int[] ii = tmp.getRoole();
this.axioma = ii[0];
}
this.terminals = this.createTerminals();
this.nonterminals = this.createNonterminals();
this.termLanguarge = this.createTerminalLang();
}
}
public boolean isCreate() {
return this.create;
}
public void setLocalkContext(LinkedList<LlkContext>[] localK) {
this.LocalkContext = localK;
}
public LinkedList<LlkContext>[] getLocalkContext() {
return this.LocalkContext;
}
public void leftRecusionTrace() {
LinkedList lang = this.getLanguarge();
int[] term = this.getTerminals();
int[] epsilon = this.getEpsilonNonterminals();
Iterator count = lang.iterator();
while(count.hasNext()) {
Node i$ = (Node)count.next();
int[] tmp = i$.getRoole();
if(tmp.length == 1) {
i$.setTeg(1);
} else if(i$.getRoole()[1] > 0) {
i$.setTeg(1);
} else {
i$.setTeg(0);
}
}
int var12 = 0;
boolean isRecurtion = false;
Iterator var13 = lang.iterator();
while(true) {
while(true) {
Node var14;
do {
if(!var13.hasNext()) {
if(!isRecurtion) {
System.out.println("В граматиці ліворекурсивні нетермінали відсутні ");
}
return;
}
var14 = (Node)var13.next();
++var12;
} while(var14.getTeg() == 1);
int[] role = var14.getRoole();
for(int ii = 1; ii < role.length && role[ii] <= 0; ++ii) {
MyLang.TmpList tree = new MyLang.TmpList((MyLang.TmpList)null, var14, ii);
if(tree.searchLeftRecursion(this)) {
tree.destroy();
isRecurtion = true;
break;
}
tree.destroy();
int ii1;
for(ii1 = 0; ii1 < epsilon.length && epsilon[ii1] != role[ii]; ++ii1) {
;
}
if(ii1 == epsilon.length) {
break;
}
}
}
}
}
public void rigthRecusionTrace() {
LinkedList lang = this.getLanguarge();
int[] term = this.getTerminals();
int[] epsilon = this.getEpsilonNonterminals();
boolean count = false;
Iterator i$ = lang.iterator();
Node tmp2;
int[] role;
while(i$.hasNext()) {
tmp2 = (Node)i$.next();
role = tmp2.getRoole();
if(role.length == 1) {
tmp2.setTeg(1);
} else if(role[role.length - 1] > 0) {
tmp2.setTeg(1);
} else {
tmp2.setTeg(0);
}
}
int var12 = 0;
boolean isRecurtion = false;
i$ = lang.iterator();
while(true) {
while(true) {
do {
if(!i$.hasNext()) {
if(!isRecurtion) {
System.out.println("В граматиці праворекурсивні нетермінали відсутні ");
}
return;
}
tmp2 = (Node)i$.next();
++var12;
} while(tmp2.getTeg() == 1);
role = tmp2.getRoole();
for(int ii = role.length - 1; ii > 0 && role[ii] <= 0; --ii) {
MyLang.TmpList tree = new MyLang.TmpList((MyLang.TmpList)null, tmp2, ii);
if(tree.searchRigthRecursion(this)) {
tree.destroy();
isRecurtion = true;
break;
}
tree.destroy();
int ii1;
for(ii1 = 0; ii1 < epsilon.length && epsilon[ii1] != role[ii]; ++ii1) {
;
}
if(ii1 == epsilon.length) {
break;
}
}
}
}
}
public LinkedList<LlkContext>[] createLocalK() {
LinkedList[] localK = null;
LlkContext[] termLang = this.getLlkTrmContext();
LlkContext[] first = this.getFirstK();
int[] term = this.getTerminals();
int[] nonterm = this.getNonTerminals();
localK = new LinkedList[nonterm.length];
LlkContext[] tmpLlk = new LlkContext[40];
int[] mult = new int[40];
int[] maxmult = new int[40];
int ii;
for(ii = 0; ii < nonterm.length; ++ii) {
localK[ii] = null;
}
for(ii = 0; ii < nonterm.length && nonterm[ii] != this.axioma; ++ii) {
;
}
LlkContext rezult = new LlkContext();
rezult.addWord(new int[0]);
localK[ii] = new LinkedList();
localK[ii].add(rezult);
int iter = 0;
boolean count;
do {
++iter;
System.out.println("Побудова множини Local: ітерація " + iter);
count = false;
label151:
for(ii = 0; ii < nonterm.length; ++ii) {
int nomrole = 0;
Iterator i$ = this.language.iterator();
while(true) {
int ii1;
Node tmp;
do {
if(!i$.hasNext()) {
continue label151;
}
tmp = (Node)i$.next();
++nomrole;
for(ii1 = 0; ii1 < nonterm.length && nonterm[ii1] != tmp.getRoole()[0]; ++ii1) {
;
}
} while(localK[ii1] == null);
int indexLeft = ii1;
int[] role = tmp.getRoole();
for(ii1 = 1; ii1 < role.length; ++ii1) {
if(role[ii1] == nonterm[ii]) {
int multcount = 0;
int j1;
for(int j = ii1 + 1; j < role.length; ++j) {
if(role[j] >= 0) {
for(j1 = 0; j1 < term.length && term[j1] != role[j]; ++j1) {
;
}
tmpLlk[multcount++] = termLang[j1];
} else {
for(j1 = 0; j1 < nonterm.length && nonterm[j1] != role[j]; ++j1) {
;
}
tmpLlk[multcount++] = first[j1];
}
}
Iterator i$1 = localK[indexLeft].iterator();
while(i$1.hasNext()) {
LlkContext tmp1 = (LlkContext)i$1.next();
tmpLlk[multcount] = tmp1;
for(j1 = 0; j1 < multcount + 1; ++j1) {
mult[j1] = 0;
maxmult[j1] = tmpLlk[j1].calcWords();
}
int realCalc = 0;
for(j1 = 0; j1 < multcount + 1; ++j1) {
if(j1 == 0) {
realCalc = tmpLlk[j1].minLengthWord();
} else {
int minLength = tmpLlk[j1].minLengthWord();
if(realCalc >= this.getLlkConst()) {
break;
}
realCalc += minLength;
}
}
realCalc = j1;
rezult = new LlkContext();
do {
int[] llkWord = this.newWord(this.getLlkConst(), tmpLlk, mult, realCalc);
rezult.addWord(llkWord);
} while(this.newCalcIndex(mult, maxmult, realCalc));
if(localK[ii] == null) {
localK[ii] = new LinkedList();
localK[ii].add(rezult);
count = true;
} else if(!this.belongToLlkContext(localK[ii], rezult)) {
localK[ii].add(rezult);
count = true;
}
}
}
}
}
}
} while(count);
return localK;
}
public void printLocalk() {
LinkedList[] localK = this.getLocalkContext();
int[] term = this.getTerminals();
int[] nonterm = this.getNonTerminals();
for(int ii = 0; ii < nonterm.length; ++ii) {
System.out.println("Контекст Local для нетермінала " + this.getLexemaText(nonterm[ii]));
Iterator i$ = localK[ii].iterator();
while(i$.hasNext()) {
LlkContext tmp = (LlkContext)i$.next();
int count = tmp.calcWords();
System.out.println("{ ");
for(int ii1 = 0; ii1 < tmp.calcWords(); ++ii1) {
int[] word = tmp.getWord(ii1);
if(word.length == 0) {
System.out.print("Е-слово");
} else {
for(int ii2 = 0; ii2 < word.length; ++ii2) {
System.out.print(this.getLexemaText(word[ii2]) + " ");
}
}
System.out.println();
}
System.out.println("} ");
}
}
}
public boolean llkCondition() {
boolean upr = true;
int count = 0;
LinkedList[] localK = this.getLocalkContext();
LlkContext[] firstTerm = this.getLlkTrmContext();
LlkContext[] firstNonterm = this.getFirstK();
int[] term = this.getTerminals();
int[] nonterm = this.getNonTerminals();
LlkContext[] tmpLlk = new LlkContext[40];
int[] mult = new int[40];
int[] maxmult = new int[40];
Iterator i$ = this.getLanguarge().iterator();
label219:
while(i$.hasNext()) {
Node tmp = (Node)i$.next();
++count;
int[] role = tmp.getRoole();
int count1 = 0;
Iterator i$1 = this.getLanguarge().iterator();
label217:
while(true) {
int[] role1;
do {
if(!i$1.hasNext()) {
continue label219;
}
Node tmp1 = (Node)i$1.next();
++count1;
if(tmp == tmp1) {
continue label219;
}
role1 = tmp1.getRoole();
} while(role[0] != role1[0]);
int ii;
for(ii = 0; ii < nonterm.length && role[0] != nonterm[ii]; ++ii) {
;
}
Iterator i$2 = localK[ii].iterator();
while(true) {
while(true) {
if(!i$2.hasNext()) {
continue label217;
}
LlkContext loctmp = (LlkContext)i$2.next();
int counMult = 0;
int j1;
int j2;
for(j1 = 1; j1 < role.length; ++j1) {
if(role[j1] > 0) {
for(j2 = 0; j2 < term.length && term[j2] != role[j1]; ++j2) {
;
}
tmpLlk[counMult++] = firstTerm[j2];
} else {
for(j2 = 0; j2 < nonterm.length && nonterm[j2] != role[j1]; ++j2) {
;
}
tmpLlk[counMult++] = firstNonterm[j2];
}
}
tmpLlk[counMult++] = loctmp;
for(j1 = 0; j1 < counMult; ++j1) {
mult[j1] = 0;
maxmult[j1] = tmpLlk[j1].calcWords();
}
int realCalc = 0;
int minLength;
for(j1 = 0; j1 < counMult; ++j1) {
if(j1 == 0) {
realCalc = tmpLlk[j1].minLengthWord();
} else {
minLength = tmpLlk[j1].minLengthWord();
if(realCalc >= this.getLlkConst()) {
break;
}
realCalc += minLength;
}
}
realCalc = j1;
LlkContext result = new LlkContext();
int[] llkWord;
do {
llkWord = this.newWord(this.getLlkConst(), tmpLlk, mult, realCalc);
result.addWord(llkWord);
} while(this.newCalcIndex(mult, maxmult, realCalc));
counMult = 0;
for(j1 = 1; j1 < role1.length; ++j1) {
if(role1[j1] > 0) {
for(j2 = 0; j2 < term.length && term[j2] != role1[j1]; ++j2) {
;
}
tmpLlk[counMult++] = firstTerm[j2];
} else {
for(j2 = 0; j2 < nonterm.length && nonterm[j2] != role1[j1]; ++j2) {
;
}
tmpLlk[counMult++] = firstNonterm[j2];
}
}
tmpLlk[counMult++] = loctmp;
for(j1 = 0; j1 < counMult; ++j1) {
mult[j1] = 0;
maxmult[j1] = tmpLlk[j1].calcWords();
}
realCalc = 0;
for(j1 = 0; j1 < counMult; ++j1) {
if(j1 == 0) {
realCalc = tmpLlk[j1].minLengthWord();
} else {
minLength = tmpLlk[j1].minLengthWord();
if(realCalc >= this.getLlkConst()) {
break;
}
realCalc += minLength;
}
}
realCalc = j1;
LlkContext result1 = new LlkContext();
do {
llkWord = this.newWord(this.getLlkConst(), tmpLlk, mult, realCalc);
result1.addWord(llkWord);
} while(this.newCalcIndex(mult, maxmult, realCalc));
for(j1 = 0; j1 < result.calcWords(); ++j1) {
if(result1.wordInContext(result.getWord(j1))) {
System.out.println("Пара правил (" + count + "," + count1 + ") не задовільняють LL(" + this.getLlkConst() + ")- умові");
upr = false;
break;
}
}
}
}
}
}
if(upr) {
System.out.println("Граматика задовільняює LL(" + this.getLlkConst() + ")- умові");
}
return upr;
}
private boolean belongToLlkContext(LinkedList<LlkContext> list, LlkContext llk) {
int llkCount = llk.calcWords();
Iterator i$ = list.iterator();
int ii;
do {
LlkContext tmp;
do {
if(!i$.hasNext()) {
return false;
}
tmp = (LlkContext)i$.next();
} while(llkCount != tmp.calcWords());
int tmpCount = tmp.calcWords();
for(ii = 0; ii < llkCount && tmp.wordInContext(llk.getWord(ii)); ++ii) {
;
}
} while(ii != llkCount);
return true;
}
public int indexNonterminal(int ssItem) {
for(int ii = 0; ii < this.nonterminals.length; ++ii) {
if(ssItem == this.nonterminals[ii]) {
return ii;
}
}
return 0;
}
public int indexTerminal(int ssItem) {
for(int ii = 0; ii < this.terminals.length; ++ii) {
if(ssItem == this.terminals[ii]) {
return ii;
}
}
return 0;
}
public int getLexemaCode(byte[] lexema, int lexemaLen, int lexemaClass) {
Iterator i$ = this.lexemaTable.iterator();
String ss;
int ii;
TableNode tmp;
do {
do {
if(!i$.hasNext()) {
return -1;
}
tmp = (TableNode)i$.next();
ss = tmp.getLexemaText();
} while(ss.length() != lexemaLen);
for(ii = 0; ii < ss.length() && ss.charAt(ii) == (char)lexema[ii]; ++ii) {
;
}
} while(ii != ss.length());
return tmp.getLexemaCode();
}
public void printTerminals() {
System.out.println("СПИСОК ТЕРМІНАЛІВ:");
if(this.terminals != null) {
for(int ii = 0; ii < this.terminals.length; ++ii) {
System.out.println("" + (ii + 1) + " " + this.terminals[ii] + "\t " + this.getLexemaText(this.terminals[ii]));
}
}
}
public void printNonterminals() {
System.out.println("СПИСОК НЕТЕРМІНАЛІВ:");
if(this.nonterminals != null) {
for(int ii = 0; ii < this.nonterminals.length; ++ii) {
System.out.println("" + (ii + 1) + " " + this.nonterminals[ii] + "\t " + this.getLexemaText(this.nonterminals[ii]));
}
}
}
public int[][] getUprTable() {
return this.uprTable;
}
public void setUprTable(int[][] upr) {
this.uprTable = upr;
}
public LlkContext[] getFirstK() {
return this.firstK;
}
public void setFirstK(LlkContext[] first) {
this.firstK = first;
}
public LlkContext[] getFollowK() {
return this.followK;
}
public void setFollowK(LlkContext[] follow) {
this.followK = follow;
}
public void prpintRoole(Node nod) {
int[] role = nod.getRoole();
for(int ii = 0; ii < role.length; ++ii) {
if(ii == 0) {
System.out.print(this.getLexemaText(role[ii]) + " -> ");
} else {
System.out.print(" " + this.getLexemaText(role[ii]));
}
}
System.out.println();
}
public boolean createNonProdRools() {
if(this.getNonTerminals().length == 0) {
return true;
} else {
int[] prodtmp = new int[this.getNonTerminals().length];
int count = 0;
Iterator i$ = this.language.iterator();
Node tmp;
while(i$.hasNext()) {
tmp = (Node)i$.next();
tmp.setTeg(0);
}
int ii;
boolean upr;
int[] rool1;
label117:
do {
upr = false;
i$ = this.language.iterator();
while(true) {
int ii1;
do {
do {
if(!i$.hasNext()) {
continue label117;
}
tmp = (Node)i$.next();
rool1 = tmp.getRoole();
} while(tmp.getTeg() == 1);
for(ii = 1; ii < rool1.length; ++ii) {
if(rool1[ii] <= 0) {
for(ii1 = 0; ii1 < count && prodtmp[ii1] != rool1[ii]; ++ii1) {
;
}
if(ii1 == count) {
break;
}
}
}
} while(ii != rool1.length);
for(ii1 = 0; ii1 < count && prodtmp[ii1] != rool1[0]; ++ii1) {
;
}
if(ii1 == count) {
prodtmp[count++] = rool1[0];
}
tmp.setTeg(1);
upr = true;
}
} while(upr);
if(count == prodtmp.length) {
System.out.print("В граматиці непродуктивні правила відсутні\n");
return true;
} else {
System.out.print("Непродуктивні правила: \n");
i$ = this.language.iterator();
while(true) {
do {
if(!i$.hasNext()) {
return false;
}
tmp = (Node)i$.next();
} while(tmp.getTeg() == 1);
rool1 = tmp.getRoole();
for(ii = 0; ii < rool1.length; ++ii) {
if(ii == 1) {
System.out.print(" ::= ");
}
System.out.print(this.getLexemaText(rool1[ii]) + " ");
if(rool1.length == 1) {
System.out.print(" ::= ");
}
}
System.out.println("");
}
}
}
}
public boolean createNonDosNeterminals() {
int[] nonTerminals = this.getNonTerminals();
int[] dosnerminals = new int[nonTerminals.length];
int count = 0;
boolean iter = false;
if(nonTerminals == null) {
return true;
} else {
Iterator i$ = this.language.iterator();
Node tmp;
if(i$.hasNext()) {
tmp = (Node)i$.next();
dosnerminals[0] = tmp.getRoole()[0];
count = 1;
}
boolean upr;
int ii;
int ii1;
label109:
do {
upr = false;
i$ = this.language.iterator();
while(true) {
int[] rool1;
do {
if(!i$.hasNext()) {
continue label109;
}
tmp = (Node)i$.next();
rool1 = tmp.getRoole();
for(ii = 0; ii < count && dosnerminals[ii] != rool1[0]; ++ii) {
;
}
} while(ii == count);
for(ii = 1; ii < rool1.length; ++ii) {
if(rool1[ii] < 0) {
for(ii1 = 0; ii1 < count && dosnerminals[ii1] != rool1[ii]; ++ii1) {
;
}
if(ii1 == count) {
dosnerminals[count] = rool1[ii];
upr = true;
++count;
}
}
}
}
} while(upr);
int var12 = nonTerminals.length - count;
if(var12 == 0) {
System.out.println("В граматиці недосяжних нетерміналів немає");
return true;
} else {
int[] nonDosNeterminals = new int[var12];
var12 = 0;
for(ii = 0; ii < nonTerminals.length; ++ii) {
for(ii1 = 0; ii1 < count && nonTerminals[ii] != dosnerminals[ii1]; ++ii1) {
;
}
if(ii1 == count) {
nonDosNeterminals[var12++] = nonTerminals[ii];
}
}
for(ii = 0; ii < nonDosNeterminals.length; ++ii) {
System.out.println("Недосяжний нетермінал: " + this.getLexemaText(nonDosNeterminals[ii]) + "\n ");
}
return false;
}
}
}
public boolean leftRecursNonnerminal() {
int[] controlSet = new int[this.getNonTerminals().length];
int[] nontrm = this.getNonTerminals();
int[] eps = this.getEpsilonNonterminals();
boolean upr = false;
boolean upr1 = false;
for(int ii = 0; ii < nontrm.length; ++ii) {
int count = 0;
int count1 = 1;
upr = false;
controlSet[count] = nontrm[ii];
do {
Iterator i$ = this.language.iterator();
label94:
while(true) {
int[] rool1;
do {
if(!i$.hasNext()) {
break label94;
}
Node tmp = (Node)i$.next();
rool1 = tmp.getRoole();
} while(rool1[0] != controlSet[count]);
int ii1;
for(ii1 = 1; ii1 < rool1.length && rool1[ii1] <= 0 && rool1[ii1] != controlSet[0]; ++ii1) {
int ii2;
for(ii2 = 0; ii2 < count1 && rool1[ii1] != controlSet[ii2]; ++ii2) {
;
}
if(ii2 == count1) {
controlSet[count1++] = rool1[ii1];
}
if(eps == null) {
break;
}
for(ii2 = 0; ii2 < eps.length && rool1[ii1] != eps[ii2]; ++ii2) {
;
}
if(ii2 == eps.length) {
break;
}
}
if(ii1 != rool1.length && rool1[ii1] == controlSet[0]) {
System.out.print("Нетермінал: " + this.getLexemaText(controlSet[0]) + " ліворекурсивний \n");
upr = true;
upr1 = true;
break;
}
}
if(upr) {
break;
}
++count;
} while(count < count1);
}
if(!upr1) {
System.out.print("В граматиці відсутні ліворекурсивні нетермінали \n");
return false;
} else {
return true;
}
}
public boolean rightRecursNonnerminal() {
int[] controlSet = new int[this.getNonTerminals().length];
int[] nontrm = this.getNonTerminals();
int[] eps = this.getEpsilonNonterminals();
boolean upr = false;
boolean upr1 = false;
for(int ii = 0; ii < nontrm.length; ++ii) {
int count = 0;
int count1 = 1;
upr = false;
controlSet[count] = nontrm[ii];
do {
Iterator i$ = this.language.iterator();
label94:
while(true) {
int[] rool1;
do {
if(!i$.hasNext()) {
break label94;
}
Node tmp = (Node)i$.next();
rool1 = tmp.getRoole();
} while(rool1[0] != controlSet[count]);
int ii1;
for(ii1 = rool1.length - 1; ii1 > 0 && rool1[ii1] <= 0 && rool1[ii1] != controlSet[0]; --ii1) {
int ii2;
for(ii2 = 0; ii2 < count1 && rool1[ii1] != controlSet[ii2]; ++ii2) {
;
}
if(ii2 == count1) {
controlSet[count1++] = rool1[ii1];
}
if(eps == null) {
break;
}
for(ii2 = 0; ii2 < eps.length && rool1[ii1] != eps[ii2]; ++ii2) {
;
}
if(ii2 == eps.length) {
break;
}
}
if(ii1 != 0 && rool1[ii1] == controlSet[0]) {
System.out.print("Нетермінал: " + this.getLexemaText(controlSet[0]) + " праворекурсивний \n");
upr = true;
upr1 = true;
break;
}
}
if(upr) {
break;
}
++count;
} while(count < count1);
}
if(!upr1) {
System.out.print("В граматиці відсутні праворекурсивні нетермінали \n");
return false;
} else {
return true;
}
}
public LlkContext[] firstK() {
int[] llkWord = new int[10];
boolean upr = false;
int[] term = this.getTerminals();
int[] nonterm = this.getNonTerminals();
LlkContext[] llkTrmContext = this.getLlkTrmContext();
LlkContext[] rezult = new LlkContext[nonterm.length];
LlkContext[] tmpLlk = new LlkContext[40];
int[] mult = new int[40];
int[] maxmult = new int[40];
int iter = 0;
int ii;
for(ii = 0; ii < rezult.length; ++ii) {
rezult[ii] = new LlkContext();
}
label125:
do {
upr = false;
boolean prav = false;
PrintStream var10000 = System.out;
StringBuilder var10001 = (new StringBuilder()).append("Ітерація пошуку множини FirstK ");
++iter;
var10000.println(var10001.append(iter).toString());
Iterator i$ = this.language.iterator();
while(true) {
while(true) {
if(!i$.hasNext()) {
continue label125;
}
Node tmp = (Node)i$.next();
int[] tmprole = tmp.getRoole();
for(ii = 0; ii < nonterm.length && tmprole[0] != nonterm[ii]; ++ii) {
;
}
if(tmprole.length == 1) {
if(rezult[ii].addWord(new int[0])) {
upr = true;
}
} else {
int ii0;
int ii1;
for(ii0 = 1; ii0 < tmprole.length; ++ii0) {
if(tmprole[ii0] > 0) {
for(ii1 = 0; ii1 < term.length && term[ii1] != tmprole[ii0]; ++ii1) {
;
}
tmpLlk[ii0 - 1] = llkTrmContext[ii1];
} else {
for(ii1 = 0; ii1 < nonterm.length && nonterm[ii1] != tmprole[ii0]; ++ii1) {
;
}
if(rezult[ii1].calcWords() == 0) {
break;
}
tmpLlk[ii0 - 1] = rezult[ii1];
}
}
if(ii0 == tmprole.length) {
int multCount = tmprole.length - 1;
for(ii1 = 0; ii1 < multCount; ++ii1) {
mult[ii1] = 0;
maxmult[ii1] = tmpLlk[ii1].calcWords();
}
int realCalc = 0;
for(ii1 = 0; ii1 < multCount; ++ii1) {
if(ii1 == 0) {
realCalc = tmpLlk[ii1].minLengthWord();
} else {
int minLength = tmpLlk[ii1].minLengthWord();
if(realCalc >= this.getLlkConst()) {
break;
}
realCalc += minLength;
}
}
realCalc = ii1;
while(true) {
llkWord = this.newWord(this.getLlkConst(), tmpLlk, mult, realCalc);
if(rezult[ii].addWord(llkWord)) {
upr = true;
}
if(!this.newCalcIndex(mult, maxmult, realCalc)) {
break;
}
}
}
}
}
}
} while(upr);
System.out.println("Кінець пошуку множин FIRSTk");
return rezult;
}
public LlkContext[] followK() {
LinkedList lan = this.getLanguarge();
LlkContext[] firstK = this.getFirstK();
int[] term = this.getTerminals();
int[] nonterm = this.getNonTerminals();
LlkContext[] llkTrmContext = this.getLlkTrmContext();
LlkContext[] rezult = new LlkContext[nonterm.length];
LlkContext[] tmpLlk = new LlkContext[40];
int[] mult = new int[40];
int[] maxmult = new int[40];
int iter = 0;
int ii;
for(ii = 0; ii < rezult.length; ++ii) {
rezult[ii] = new LlkContext();
}
int aaxioma = this.getAxioma();
for(ii = 0; ii < nonterm.length && nonterm[ii] != aaxioma; ++ii) {
;
}
rezult[ii].addWord(new int[0]);
boolean upr;
label149:
do {
upr = false;
boolean prav = false;
PrintStream var10000 = System.out;
StringBuilder var10001 = (new StringBuilder()).append("Ітерація побудово множини FollowK ");
++iter;
var10000.println(var10001.append(iter).toString());
Iterator i$ = lan.iterator();
while(true) {
int[] tmprole;
do {
if(!i$.hasNext()) {
continue label149;
}
Node tmp = (Node)i$.next();
tmprole = tmp.getRoole();
for(ii = 0; ii < nonterm.length && tmprole[0] != nonterm[ii]; ++ii) {
;
}
if(ii == nonterm.length) {
return null;
}
} while(rezult[ii].calcWords() == 0);
int leftItem = ii;
for(int jj = 1; jj < tmprole.length; ++jj) {
if(tmprole[jj] <= 0) {
int multCount = 0;
int ii1;
for(int ii0 = jj + 1; ii0 < tmprole.length; ++ii0) {
if(tmprole[ii0] > 0) {
for(ii1 = 0; ii1 < term.length && term[ii1] != tmprole[ii0]; ++ii1) {
;
}
tmpLlk[multCount++] = llkTrmContext[ii1];
} else {
for(ii1 = 0; ii1 < nonterm.length && nonterm[ii1] != tmprole[ii0]; ++ii1) {
;
}
tmpLlk[multCount++] = firstK[ii1];
}
}
tmpLlk[multCount++] = rezult[leftItem];
for(ii1 = 0; ii1 < multCount; ++ii1) {
mult[ii1] = 0;
maxmult[ii1] = tmpLlk[ii1].calcWords();
}
int realCalc = 0;
for(ii1 = 0; ii1 < multCount; ++ii1) {
if(ii1 == 0) {
realCalc = tmpLlk[ii1].minLengthWord();
} else {
int minLength = tmpLlk[ii1].minLengthWord();
if(realCalc >= this.getLlkConst()) {
break;
}
realCalc += minLength;
}
}
realCalc = ii1;
for(ii1 = 0; ii1 < nonterm.length && nonterm[ii1] != tmprole[jj]; ++ii1) {
;
}
while(true) {
int[] llkWord = this.newWord(this.getLlkConst(), tmpLlk, mult, realCalc);
if(rezult[ii1].addWord(llkWord)) {
upr = true;
}
if(!this.newCalcIndex(mult, maxmult, realCalc)) {
break;
}
}
}
}
}
} while(upr);
System.out.println("Кінець пошуку множин FollowK");
return rezult;
}
public void firstFollowK() {
int[] term = this.getTerminals();
int[] nonterm = this.getNonTerminals();
LlkContext[] llkTrmContext = this.getLlkTrmContext();
LlkContext[] tmpLlk = new LlkContext[40];
int[] mult = new int[40];
int[] maxmult = new int[40];
int roleNumb = 0;
Iterator i$ = this.getLanguarge().iterator();
while(i$.hasNext()) {
Node tmp = (Node)i$.next();
++roleNumb;
int[] tmprole = tmp.getRoole();
int multCount = 0;
int ii1;
for(int ii = 1; ii < tmprole.length; ++ii) {
if(tmprole[ii] > 0) {
for(ii1 = 0; ii1 < term.length && term[ii1] != tmprole[ii]; ++ii1) {
;
}
tmpLlk[multCount] = llkTrmContext[ii1];
} else {
for(ii1 = 0; ii1 < nonterm.length && nonterm[ii1] != tmprole[ii]; ++ii1) {
;
}
tmpLlk[multCount] = this.firstK[ii1];
}
++multCount;
}
for(ii1 = 0; ii1 < nonterm.length && nonterm[ii1] != tmprole[0]; ++ii1) {
;
}
tmpLlk[multCount++] = this.followK[ii1];
for(ii1 = 0; ii1 < multCount; ++ii1) {
mult[ii1] = 0;
maxmult[ii1] = tmpLlk[ii1].calcWords();
}
int realCalc = 0;
for(ii1 = 0; ii1 < multCount; ++ii1) {
if(ii1 == 0) {
realCalc = tmpLlk[ii1].minLengthWord();
} else {
int minLength = tmpLlk[ii1].minLengthWord();
if(realCalc >= this.getLlkConst()) {
break;
}
realCalc += minLength;
}
}
realCalc = ii1;
LlkContext rezult = new LlkContext();
do {
int[] llkWord = this.newWord(this.getLlkConst(), tmpLlk, mult, realCalc);
rezult.addWord(llkWord);
} while(this.newCalcIndex(mult, maxmult, realCalc));
tmp.addFirstFollowK(rezult);
}
System.out.println("Множини FirstK(w)+ FollowK(A): А->w побудовані ");
}
public void printFirstkContext() {
int[] nonterm = this.getNonTerminals();
LlkContext[] firstContext = this.getFirstK();
if(firstContext != null) {
for(int j = 0; j < nonterm.length; ++j) {
System.out.println("FirstK-контекст для нетермінала: " + this.getLexemaText(nonterm[j]));
LlkContext tmp = firstContext[j];
for(int ii = 0; ii < tmp.calcWords(); ++ii) {
int[] word = tmp.getWord(ii);
if(word.length == 0) {
System.out.print("Е-слово");
} else {
for(int ii1 = 0; ii1 < word.length; ++ii1) {
System.out.print(this.getLexemaText(word[ii1]) + " ");
}
}
System.out.println();
}
}
}
}
public void printFollowkContext() {
int[] nonterm = this.getNonTerminals();
LlkContext[] followContext = this.getFollowK();
for(int j = 0; j < nonterm.length; ++j) {
System.out.println("FollowK-контекст для нетермінала: " + this.getLexemaText(nonterm[j]));
LlkContext tmp = followContext[j];
for(int ii = 0; ii < tmp.calcWords(); ++ii) {
int[] word = tmp.getWord(ii);
if(word.length == 0) {
System.out.print("Е-слово");
} else {
for(int ii1 = 0; ii1 < word.length; ++ii1) {
System.out.print(this.getLexemaText(word[ii1]) + " ");
}
}
System.out.println();
}
}
}
public void printFirstFollowK() {
int count = 0;
Iterator i$ = this.getLanguarge().iterator();
while(i$.hasNext()) {
Node tmp = (Node)i$.next();
++count;
System.out.print("Правило №" + count + " ");
this.prpintRoole(tmp);
LlkContext loc = tmp.getFirstFollowK();
for(int ii1 = 0; ii1 < loc.calcWords(); ++ii1) {
int[] word = loc.getWord(ii1);
if(word.length == 0) {
System.out.print("Е-слово");
} else {
for(int ii2 = 0; ii2 < word.length; ++ii2) {
System.out.print(this.getLexemaText(word[ii2]) + " ");
}
}
System.out.println();
}
}
}
public void printFirstFollowForRoole() {
boolean count = false;
byte[] readline = new byte[80];
int rooleNumber = 0;
while(true) {
while(true) {
System.out.println("Введіть номер правила або end");
try {
int textLen = System.in.read(readline);
String StrTmp = new String(readline, 0, textLen, "ISO-8859-1");
if(StrTmp.trim().equals("end")) {
return;
}
rooleNumber = (new Integer(StrTmp.trim())).intValue();
} catch (Exception var12) {
System.out.println("Невірний код дії, повторіть: ");
}
int var13 = 0;
Iterator i$ = this.getLanguarge().iterator();
while(i$.hasNext()) {
Node tmp = (Node)i$.next();
++var13;
if(var13 == rooleNumber) {
this.prpintRoole(tmp);
LlkContext loc = tmp.getFirstFollowK();
for(int ii1 = 0; ii1 < loc.calcWords(); ++ii1) {
int[] word = loc.getWord(ii1);
if(word.length == 0) {
System.out.print("Е-слово");
} else {
for(int ii2 = 0; ii2 < word.length; ++ii2) {
System.out.print(this.getLexemaText(word[ii2]) + " ");
}
}
System.out.println();
}
break;
}
}
}
}
}
public boolean strongLlkCondition() {
boolean upr = true;
int count = 0;
Iterator i$ = this.getLanguarge().iterator();
label46:
while(i$.hasNext()) {
Node tmp = (Node)i$.next();
++count;
int[] role = tmp.getRoole();
LlkContext cont = tmp.getFirstFollowK();
int count1 = 0;
Iterator i$1 = this.getLanguarge().iterator();
while(true) {
while(true) {
Node tmp1;
int[] role1;
do {
if(!i$1.hasNext()) {
continue label46;
}
tmp1 = (Node)i$1.next();
++count1;
if(tmp == tmp1) {
continue label46;
}
role1 = tmp1.getRoole();
} while(role[0] != role1[0]);
LlkContext cont1 = tmp1.getFirstFollowK();
for(int ii = 0; ii < cont.calcWords(); ++ii) {
if(cont1.wordInContext(cont.getWord(ii))) {
System.out.println("" + role[0] + " " + this.getLexemaText(role[0]) + " -пара правил (" + count + "," + count1 + ") не задовольняють сильній LL(" + this.getLlkConst() + ")- умові");
upr = false;
break;
}
}
}
}
}
if(upr) {
System.out.println("Граматика задовільняює сильній LL(" + this.getLlkConst() + ")- умові");
}
return upr;
}
public int[][] createUprTable() {
int[] term = this.getTerminals();
int[] nonterm = this.getNonTerminals();
if(this.LLK != 1) {
System.out.println("Спроба побудувати таблицю управління для k=" + this.LLK);
return (int[][])null;
} else {
int[][] upr = new int[nonterm.length][term.length + 1];
int ii;
for(int ii1 = 0; ii1 < nonterm.length; ++ii1) {
for(ii = 0; ii < term.length + 1; ++ii) {
upr[ii1][ii] = 0;
}
}
int rowline = 0;
Iterator i$ = this.getLanguarge().iterator();
while(i$.hasNext()) {
Node tmp = (Node)i$.next();
++rowline;
int[] role = tmp.getRoole();
int rowindex = this.indexNonterminal(role[0]);
LlkContext cont = tmp.getFirstFollowK();
for(ii = 0; ii < cont.calcWords(); ++ii) {
int[] word = cont.getWord(ii);
int colindex;
if(word.length == 0) {
colindex = this.getTerminals().length;
} else {
colindex = this.indexTerminal(word[0]);
}
if(upr[rowindex][colindex] != 0) {
System.out.println("При побудові таблиці управління для нетермінала " + this.getLexemaText(nonterm[rowindex]) + " порушшено LL(1)-властивість");
return (int[][])null;
}
upr[rowindex][colindex] = rowline;
}
}
System.out.println("Таблиця управління LL(1)-аналізу побудована ");
return upr;
}
}
public int[][] createUprTableWithCollision() {
int[] term = this.getTerminals();
int[] nonterm = this.getNonTerminals();
if(this.LLK != 1) {
System.out.println("Спроба побудувати таблицю управління для k=" + this.LLK);
return (int[][])null;
} else {
int[][] upr = new int[nonterm.length][term.length + 1];
int ii;
for(int ii1 = 0; ii1 < nonterm.length; ++ii1) {
for(ii = 0; ii < term.length + 1; ++ii) {
upr[ii1][ii] = 0;
}
}
int rowline = 0;
Iterator i$ = this.getLanguarge().iterator();
while(i$.hasNext()) {
Node tmp = (Node)i$.next();
++rowline;
int[] role = tmp.getRoole();
int rowindex = this.indexNonterminal(role[0]);
LlkContext cont = tmp.getFirstFollowK();
for(ii = 0; ii < cont.calcWords(); ++ii) {
int[] word = cont.getWord(ii);
boolean colindex = false;
int var16;
if(word.length == 0) {
var16 = this.getTerminals().length;
} else {
var16 = this.indexTerminal(word[0]);
}
if(upr[rowindex][var16] != 0) {
upr[rowindex][var16] = -1;
} else {
upr[rowindex][var16] = rowline;
}
}
}
System.out.println("Таблиця управління LL(1)-аналізу побудована ");
return upr;
}
}
private boolean newCalcIndex(int[] mult, int[] maxmult, int realCalc) {
for(int ii = realCalc - 1; ii >= 0; --ii) {
if(mult[ii] + 1 != maxmult[ii]) {
++mult[ii];
return true;
}
mult[ii] = 0;
}
return false;
}
private int[] newWord(int LLK, LlkContext[] tmp, int[] mult, int realCalc) {
int[] word = new int[LLK];
int llkTmp = 0;
int ii;
for(ii = 0; ii < realCalc; ++ii) {
int[] wordtmp = tmp[ii].getWord(mult[ii]);
for(int word1 = 0; word1 < wordtmp.length && llkTmp != LLK; ++word1) {
word[llkTmp++] = wordtmp[word1];
}
if(llkTmp == LLK) {
break;
}
}
int[] var10 = new int[llkTmp];
for(ii = 0; ii < llkTmp; ++ii) {
var10[ii] = word[ii];
}
return var10;
}
public int getLlkConst() {
return this.LLK;
}
private int getLexemaCode(String lexema, int lexemaClass) {
Iterator i$ = this.lexemaTable.iterator();
TableNode tmp;
do {
if(!i$.hasNext()) {
return 0;
}
tmp = (TableNode)i$.next();
} while(!tmp.getLexemaText().equals(lexema) || (tmp.getLexemaCode() & -16777216) != lexemaClass);
return tmp.getLexemaCode();
}
public LlkContext[] getLlkTrmContext() {
return this.termLanguarge;
}
private LlkContext[] createTerminalLang() {
LlkContext[] cont = new LlkContext[this.terminals.length];
for(int ii = 0; ii < this.terminals.length; ++ii) {
int[] trmWord = new int[]{this.terminals[ii]};
cont[ii] = new LlkContext();
cont[ii].addWord(trmWord);
}
return cont;
}
public String getLexemaText(int code) {
Iterator i$ = this.lexemaTable.iterator();
TableNode tmp;
do {
if(!i$.hasNext()) {
return null;
}
tmp = (TableNode)i$.next();
} while(tmp.getLexemaCode() != code);
return tmp.getLexemaText();
}
public int[] getTerminals() {
return this.terminals;
}
public int[] getNonTerminals() {
return this.nonterminals;
}
public int[] getEpsilonNonterminals() {
return this.epsilonNerminals;
}
public LinkedList<Node> getLanguarge() {
return this.language;
}
public void printEpsilonNonterminals() {
System.out.println("СПИСОК E-терміналів:");
if(this.epsilonNerminals != null) {
for(int ii = 0; ii < this.epsilonNerminals.length; ++ii) {
System.out.println("" + this.epsilonNerminals[ii] + "\t" + this.getLexemaText(this.epsilonNerminals[ii]));
}
}
}
public void setEpsilonNonterminals(int[] eps) {
this.epsilonNerminals = eps;
}
public int[] createEpsilonNonterminals() {
int[] terminal = new int[this.nonterminals.length];
int count = 0;
Iterator rezult = this.language.iterator();
Node tmp;
while(rezult.hasNext()) {
tmp = (Node)rezult.next();
tmp.setTeg(0);
}
boolean upr;
int ii;
label78:
do {
upr = false;
rezult = this.language.iterator();
while(true) {
int[] role;
do {
if(!rezult.hasNext()) {
continue label78;
}
tmp = (Node)rezult.next();
role = tmp.getRoole();
for(ii = 1; ii < role.length && role[ii] <= 0; ++ii) {
int ii1;
for(ii1 = 0; ii1 < count && terminal[ii1] != role[ii]; ++ii1) {
;
}
if(ii1 == count) {
break;
}
}
} while(ii != role.length);
int ii2;
for(ii2 = 0; ii2 < count && terminal[ii2] != role[0]; ++ii2) {
;
}
if(ii2 == count) {
terminal[count++] = role[0];
upr = true;
}
}
} while(upr);
int[] var10 = new int[count];
for(ii = 0; ii < count; ++ii) {
var10[ii] = terminal[ii];
}
return var10;
}
public void printGramma() {
int count = 0;
Iterator i$ = this.language.iterator();
while(i$.hasNext()) {
Node tmp = (Node)i$.next();
int[] roole = tmp.getRoole();
++count;
System.out.print("" + count + " ");
for(int ii = 0; ii < roole.length; ++ii) {
if(ii == 1) {
System.out.print(" -> ");
}
System.out.print(this.getLexemaText(roole[ii]) + " ! ");
if(roole.length == 1) {
System.out.print(" -> ");
}
}
System.out.println("");
}
}
private int[] createTerminals() {
int count = 0;
Iterator i$ = this.lexemaTable.iterator();
TableNode tmp;
while(i$.hasNext()) {
tmp = (TableNode)i$.next();
if(tmp.getLexemaCode() > 0) {
++count;
}
}
int[] terminal = new int[count];
count = 0;
i$ = this.lexemaTable.iterator();
while(i$.hasNext()) {
tmp = (TableNode)i$.next();
if(tmp.getLexemaCode() > 0) {
terminal[count] = tmp.getLexemaCode();
++count;
}
}
return terminal;
}
private int[] createNonterminals() {
int count = 0;
Iterator i$ = this.lexemaTable.iterator();
TableNode tmp;
while(i$.hasNext()) {
tmp = (TableNode)i$.next();
if(tmp.getLexemaCode() < 0) {
++count;
}
}
int[] nonterminal = new int[count];
count = 0;
i$ = this.lexemaTable.iterator();
while(i$.hasNext()) {
tmp = (TableNode)i$.next();
if(tmp.getLexemaCode() < 0) {
nonterminal[count] = tmp.getLexemaCode();
++count;
}
}
return nonterminal;
}
private void setAxioma(int axiom0) {
this.axioma = axiom0;
}
public int getAxioma() {
return this.axioma;
}
private void readGrammat(String fname) {
char[] lexema = new char[180];
int[] roole = new int[80];
BufferedReader s;
try {
s = new BufferedReader(new FileReader(fname.trim()));
} catch (FileNotFoundException var24) {
System.out.print("Файл:" + fname.trim() + " не відкрито\n");
this.create = false;
return;
}
for(int pravilo = 0; pravilo < lexema.length; ++pravilo) {
lexema[pravilo] = 0;
}
int[] var27 = new int[80];
int line;
for(line = 0; line < var27.length; ++line) {
var27[line] = 0;
}
int pos = 0;
boolean poslex = false;
byte q = 0;
boolean leftLexema = false;
int posRoole = 0;
line = 0;
String readline = null;
int readpos = 0;
int readlen = 0;
try {
int newLexemaCode;
TableNode nodeTmp;
Node nod;
while(s.ready()) {
if(readline == null || readpos >= readlen) {
readline = s.readLine();
if(line == 0 && readline.charAt(0) == '\ufeff') {
readline = readline.substring(1);
}
readlen = readline.length();
++line;
}
for(readpos = 0; readpos < readlen; ++readpos) {
char litera = readline.charAt(readpos);
String e;
boolean strTmp;
Iterator ii;
TableNode i$;
switch(q) {
case 0:
if(litera == 32 || litera == 9 || litera == 13 || litera == 10 || litera == 8) {
break;
}
if(readpos == 0 && posRoole > 0 && (litera == 33 || litera == 35)) {
nod = new Node(roole, posRoole);
this.language.add(nod);
if(litera == 33) {
posRoole = 1;
break;
}
posRoole = 0;
}
byte var26 = 0;
pos = var26 + 1;
lexema[var26] = litera;
if(litera == 35) {
q = 1;
} else if(litera == 92) {
--pos;
q = 3;
} else {
q = 2;
}
break;
case 1:
lexema[pos++] = litera;
if(litera != 35 && readpos != 0) {
break;
}
e = new String(lexema, 0, pos);
nodeTmp = new TableNode(e, -2147483648);
strTmp = true;
ii = this.lexemaTable.iterator();
while(ii.hasNext()) {
i$ = (TableNode)ii.next();
if(nodeTmp.equals(i$)) {
strTmp = false;
break;
}
}
if(strTmp) {
this.lexemaTable.add(nodeTmp);
}
newLexemaCode = this.getLexemaCode(e, -2147483648);
roole[posRoole++] = newLexemaCode;
pos = 0;
q = 0;
break;
case 2:
if(litera == 92) {
--pos;
q = 3;
} else {
if(litera != 32 && readpos != 0 && litera != 35 && litera != 13 && litera != 9) {
lexema[pos++] = litera;
continue;
}
e = new String(lexema, 0, pos);
nodeTmp = new TableNode(e, 268435456);
strTmp = true;
ii = this.lexemaTable.iterator();
while(ii.hasNext()) {
i$ = (TableNode)ii.next();
if(nodeTmp.equals(i$)) {
strTmp = false;
break;
}
}
if(strTmp) {
this.lexemaTable.add(nodeTmp);
}
newLexemaCode = this.getLexemaCode(e, 268435456);
roole[posRoole++] = newLexemaCode;
pos = 0;
q = 0;
--readpos;
}
break;
case 3:
lexema[pos++] = litera;
q = 2;
}
}
}
if(pos != 0) {
int var29;
if(q == 1) {
var29 = -2147483648;
} else {
var29 = 268435456;
}
String var31 = new String(lexema, 0, pos);
nodeTmp = new TableNode(var31, var29);
boolean var30 = true;
Iterator var32 = this.lexemaTable.iterator();
while(var32.hasNext()) {
TableNode tmp = (TableNode)var32.next();
if(nodeTmp.equals(tmp)) {
var30 = false;
break;
}
}
if(var30) {
this.lexemaTable.add(nodeTmp);
}
newLexemaCode = this.getLexemaCode(var31, var29);
roole[posRoole++] = newLexemaCode;
}
if(posRoole > 0) {
nod = new Node(roole, posRoole);
this.language.add(nod);
}
this.create = true;
} catch (IOException var25) {
System.out.println(var25.toString());
this.create = false;
}
}
private class TmpList {
MyLang.TmpList treeFather;
Node treeNode;
int treePos;
private TmpList(MyLang.TmpList tmpFather, Node tmpNode, int tmpPos) {
this.treeFather = tmpFather;
this.treeNode = tmpNode;
this.treePos = tmpPos;
}
private void destroy() {
this.treeFather = null;
this.treeNode = null;
this.treePos = 0;
}
private boolean roleInTree(Node tmp) {
MyLang.TmpList tmpLst = null;
for(tmpLst = this; tmpLst != null; tmpLst = tmpLst.treeFather) {
if(tmpLst.treeNode.getRoole()[0] == tmp.getRoole()[0]) {
return true;
}
}
return false;
}
private boolean searchLeftRecursion(MyLang lang) {
int[] epsilon = lang.getEpsilonNonterminals();
MyLang.TmpList tmpLst = null;
for(tmpLst = this; tmpLst.treeFather != null; tmpLst = tmpLst.treeFather) {
;
}
Node root = tmpLst.treeNode;
if(root.getRoole()[0] == this.treeNode.getRoole()[this.treePos]) {
System.out.println("Ліворекурсивний вивод");
this.printLeftRecurion(lang);
return true;
} else {
int count = 0;
Iterator i$ = lang.getLanguarge().iterator();
while(true) {
Node tmp;
int[] role;
do {
do {
do {
if(!i$.hasNext()) {
return false;
}
tmp = (Node)i$.next();
++count;
} while(tmp.getTeg() == 1);
} while(this.roleInTree(tmp));
role = tmp.getRoole();
} while(role[0] != this.treeNode.getRoole()[this.treePos]);
for(int ii = 1; ii < role.length && role[ii] <= 0; ++ii) {
MyLang.TmpList tree1 = MyLang.this.new TmpList(this, tmp, ii);
if(tree1.searchLeftRecursion(lang)) {
tree1.destroy();
return true;
}
tree1.destroy();
int ii1;
for(ii1 = 0; ii1 < epsilon.length && epsilon[ii1] != role[ii]; ++ii1) {
;
}
if(ii1 == epsilon.length) {
break;
}
}
}
}
}
private void printLeftRecurion(MyLang lang) {
if(this.treeFather != null) {
MyLang.TmpList tmp = this.treeFather;
tmp.printLeftRecurion(lang);
}
int[] tmpRole = this.treeNode.getRoole();
int ii;
for(ii = 0; ii < tmpRole.length; ++ii) {
if(ii == 0) {
System.out.print(lang.getLexemaText(tmpRole[ii]) + " -> ");
} else {
System.out.print(lang.getLexemaText(tmpRole[ii]) + " ");
}
}
System.out.println();
for(ii = 1; ii < this.treePos; ++ii) {
System.out.println(lang.getLexemaText(tmpRole[ii]) + " =>* epsilon");
}
}
private boolean searchRigthRecursion(MyLang lang) {
int[] epsilon = lang.getEpsilonNonterminals();
MyLang.TmpList tmpLst;
for(tmpLst = this; tmpLst.treeFather != null; tmpLst = tmpLst.treeFather) {
;
}
Node root = tmpLst.treeNode;
if(root.getRoole()[0] == this.treeNode.getRoole()[this.treePos]) {
System.out.println("\nПраворекурсивний вивод:");
this.printRigthRecurion(lang);
return true;
} else {
int count = 0;
Iterator i$ = lang.getLanguarge().iterator();
while(true) {
Node tmp;
int[] role;
do {
do {
do {
do {
do {
if(!i$.hasNext()) {
return false;
}
tmp = (Node)i$.next();
++count;
} while(tmp.getTeg() == 1);
} while(this.roleInTree(tmp));
role = tmp.getRoole();
} while(role.length <= 1);
} while(role[role.length - 1] > 0);
} while(role[0] != this.treeNode.getRoole()[this.treePos]);
for(int ii = role.length - 1; ii > 0 && role[ii] <= 0; --ii) {
MyLang.TmpList tree1 = MyLang.this.new TmpList(this, tmp, ii);
if(tree1.searchRigthRecursion(lang)) {
tree1.destroy();
return true;
}
tree1.destroy();
int ii1;
for(ii1 = 0; ii1 < epsilon.length && epsilon[ii1] != role[ii]; ++ii1) {
;
}
if(ii1 == epsilon.length) {
break;
}
}
}
}
}
private void printRigthRecurion(MyLang lang) {
if(this.treeFather != null) {
MyLang.TmpList tmp = this.treeFather;
tmp.printRigthRecurion(lang);
}
int[] tmpRole = this.treeNode.getRoole();
int ii;
for(ii = 0; ii < tmpRole.length; ++ii) {
if(ii == 0) {
System.out.print(lang.getLexemaText(tmpRole[ii]) + " -> ");
} else {
System.out.print(lang.getLexemaText(tmpRole[ii]) + " ");
}
}
System.out.println();
for(ii = tmpRole.length - 1; ii > this.treePos; --ii) {
System.out.println(lang.getLexemaText(tmpRole[ii]) + " =>* epsilon");
}
}
}
}
|
package com.lxl;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Created by xiaolu on 15/5/5.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath*:*.xml","classpath:*.xml"})
public class BaseTest {
}
|
package com.ywd.blog.service;
import java.util.List;
import com.ywd.blog.entity.LotteryList;
public interface LotteryListService {
public Integer add(LotteryList lotteryList);
public Integer deleteById(Long id);
public Integer deleteAll();
public List<LotteryList> findByRank(Integer rank);
}
|
package leetcode.solution;
import leetcode.struct.ListNode;
/**
* 剑指 Offer 24. 反转链表
* <p>
* https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/
* <p>
* 定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
* <p>
* 输入: 1->2->3->4->5->NULL
* 输出: 5->4->3->2->1->NULL
* <p>
* <p>
* Solution: 设置两个指针,每次后指针指向前指针,然后移动两个指针,以后指针为空作为判断条件。
* <p>
* ps:注意初始前指针不能指向后指针,以防出现环。
*
* @author mingkai
*/
public class SolutionJianzhi24 {
public ListNode reverseList(ListNode head) {
//前指针
ListNode p = null;
//后指针
ListNode q = head;
while (q != null) {
ListNode n = q.next;
q.next = p;
//前指针移动
p = q;
//后指针移动
q = n;
}
return p;
}
public static void main(String[] args) {
ListNode a = ListNode.create(1, 2, 3, 4, 5);
SolutionJianzhi24 solutionJianzhi24 = new SolutionJianzhi24();
solutionJianzhi24.reverseList(a).print();
}
}
|
package com.meskat.save_life;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class AddProfile extends Activity implements OnClickListener{
Button addinfo;
EditText name,bloodgroup,etLd,eaddress,etTD,etPhone,etarea;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_profile);
Button addInfo =(Button) findViewById(R.id.btnAdded);
addInfo.setOnClickListener(this);
name = (EditText) findViewById(R.id.name);
name.setOnClickListener(this);
bloodgroup= (EditText) findViewById(R.id.bloodgroup);
bloodgroup.setOnClickListener(this);
eaddress = (EditText)findViewById(R.id.etaddress);
eaddress.setOnClickListener(this);
etLd = (EditText) findViewById(R.id.etLd);
etLd.setOnClickListener(this);
etTD= (EditText) findViewById(R.id.etTD);
etTD.setOnClickListener(this);
etPhone = (EditText) findViewById(R.id.etPhone);
etPhone.setOnClickListener(this);
etarea = (EditText) findViewById(R.id.etarea);
etarea.setOnClickListener(this);
}
public AddProfile() {
// TODO Auto-generated constructor stub
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch(arg0.getId()) {
case R.id.btnAdded:
boolean workornot= true;
try{
String name1 =name.getText().toString();
String bloodgroup1 =bloodgroup.getText().toString();
String eaddress1 =eaddress.getText().toString();
String etLd1 =etLd.getText().toString();
String etTD1 = etTD.getText().toString();
String etPhone1 =etPhone.getText().toString();
String etarea1 =etarea.getText().toString();
db entry = new db(AddProfile.this);
entry.open();
entry.createEntry(name1,bloodgroup1,eaddress1,etarea1,etPhone1,etTD1,etLd1);
entry.close();
}
catch(Exception e){
workornot = false;
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("Ohh no...");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
}
finally{
if(workornot){
Dialog d = new Dialog(this);
d.setTitle("Works");
TextView tv = new TextView(this);
tv.setText("Success");
d.setContentView(tv);
d.show();
}
}
break;
case R.id.btnhome:
Intent i = new Intent(AddProfile.this,MainActivity.class);
startActivity(i);
break;
}
}
}
|
/*
* Copyright 2002-2022 the original author or authors.
*
* 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
*
* https://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.springframework.test.context.aot;
import java.lang.annotation.Annotation;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Stream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.platform.engine.support.descriptor.ClassSource;
import org.junit.platform.launcher.Launcher;
import org.junit.platform.launcher.LauncherDiscoveryRequest;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.launcher.TestPlan;
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
import org.junit.platform.launcher.core.LauncherFactory;
import org.springframework.core.annotation.MergedAnnotation;
import org.springframework.core.annotation.MergedAnnotations;
import org.springframework.test.context.BootstrapWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import static org.junit.platform.engine.discovery.DiscoverySelectors.selectClasspathRoots;
import static org.junit.platform.engine.discovery.PackageNameFilter.includePackageNames;
import static org.springframework.core.annotation.MergedAnnotation.VALUE;
import static org.springframework.core.annotation.MergedAnnotations.SearchStrategy.INHERITED_ANNOTATIONS;
import static org.springframework.core.annotation.MergedAnnotations.SearchStrategy.TYPE_HIERARCHY;
/**
* {@code TestClassScanner} scans provided classpath roots for Spring integration
* test classes using the JUnit Platform {@link Launcher} API which allows all
* registered {@link org.junit.platform.engine.TestEngine TestEngines} to discover
* tests according to their own rules.
*
* <p>The scanner currently detects the following categories of Spring integration
* test classes.
*
* <ul>
* <li>JUnit Jupiter: classes that register the {@code SpringExtension} via
* {@code @ExtendWith}.</li>
* <li>JUnit 4: classes that register the {@code SpringJUnit4ClassRunner} or
* {@code SpringRunner} via {@code @RunWith}.</li>
* <li>Generic: classes that are annotated with {@code @ContextConfiguration} or
* {@code @BootstrapWith}.</li>
* </ul>
*
* <p>The scanner has been tested with the following
* {@link org.junit.platform.engine.TestEngine TestEngines}.
*
* <ul>
* <li>JUnit Jupiter</li>
* <li>JUnit Vintage</li>
* <li>JUnit Platform Suite Engine</li>
* <li>TestNG Engine for the JUnit Platform</li>
* </ul>
*
* @author Sam Brannen
* @since 6.0
*/
class TestClassScanner {
// JUnit Jupiter
private static final String EXTEND_WITH_ANNOTATION_NAME = "org.junit.jupiter.api.extension.ExtendWith";
private static final String SPRING_EXTENSION_NAME = "org.springframework.test.context.junit.jupiter.SpringExtension";
// JUnit 4
private static final String RUN_WITH_ANNOTATION_NAME = "org.junit.runner.RunWith";
private static final String SPRING_JUNIT4_CLASS_RUNNER_NAME = "org.springframework.test.context.junit4.SpringJUnit4ClassRunner";
private static final String SPRING_RUNNER_NAME = "org.springframework.test.context.junit4.SpringRunner";
private final Log logger = LogFactory.getLog(TestClassScanner.class);
private final Set<Path> classpathRoots;
/**
* Create a {@code TestClassScanner} for the given classpath roots.
* <p>For example, in a Gradle project that only supports Java-based tests,
* the supplied set would contain a single {@link Path} representing the
* absolute path to the project's {@code build/classes/java/test} folder.
* @param classpathRoots the classpath roots to scan
*/
TestClassScanner(Set<Path> classpathRoots) {
this.classpathRoots = assertPreconditions(classpathRoots);
}
/**
* Scan the configured classpath roots for Spring integration test classes.
*/
Stream<Class<?>> scan() {
return scan(new String[0]);
}
/**
* Scan the configured classpath roots for Spring integration test classes
* in the given packages.
* <p>This method is currently only intended to be used within our own test
* suite to validate the behavior of this scanner with a limited scope. In
* production scenarios one should invoke {@link #scan()} to scan all packages
* in the configured classpath roots.
*/
Stream<Class<?>> scan(String... packageNames) {
Assert.noNullElements(packageNames, "'packageNames' must not contain null elements");
if (logger.isInfoEnabled()) {
if (packageNames.length > 0) {
logger.info("Scanning for Spring test classes in packages %s in classpath roots %s"
.formatted(Arrays.toString(packageNames), this.classpathRoots));
}
else {
logger.info("Scanning for Spring test classes in all packages in classpath roots %s"
.formatted(this.classpathRoots));
}
}
LauncherDiscoveryRequestBuilder builder = LauncherDiscoveryRequestBuilder.request();
builder.selectors(selectClasspathRoots(this.classpathRoots));
if (packageNames.length > 0) {
builder.filters(includePackageNames(packageNames));
}
LauncherDiscoveryRequest request = builder.build();
Launcher launcher = LauncherFactory.create();
TestPlan testPlan = launcher.discover(request);
return testPlan.getRoots().stream()
.map(testPlan::getDescendants)
.flatMap(Set::stream)
.map(TestIdentifier::getSource)
.flatMap(Optional::stream)
.filter(ClassSource.class::isInstance)
.map(ClassSource.class::cast)
.map(this::getJavaClass)
.flatMap(Optional::stream)
.filter(this::isSpringTestClass)
.distinct()
.sorted(Comparator.comparing(Class::getName));
}
private Optional<Class<?>> getJavaClass(ClassSource classSource) {
try {
return Optional.of(classSource.getJavaClass());
}
catch (Exception ex) {
// ignore exception
return Optional.empty();
}
}
private boolean isSpringTestClass(Class<?> clazz) {
boolean isSpringTestClass = (isJupiterSpringTestClass(clazz) || isJUnit4SpringTestClass(clazz) ||
isGenericSpringTestClass(clazz));
if (isSpringTestClass && logger.isTraceEnabled()) {
logger.trace("Found Spring test class: " + clazz.getName());
}
return isSpringTestClass;
}
private static boolean isJupiterSpringTestClass(Class<?> clazz) {
return MergedAnnotations.search(TYPE_HIERARCHY)
.withEnclosingClasses(ClassUtils::isInnerClass)
.from(clazz)
.stream(EXTEND_WITH_ANNOTATION_NAME)
.map(annotation -> annotation.getClassArray(VALUE))
.flatMap(Arrays::stream)
.map(Class::getName)
.anyMatch(SPRING_EXTENSION_NAME::equals);
}
private static boolean isJUnit4SpringTestClass(Class<?> clazz) {
MergedAnnotation<Annotation> mergedAnnotation =
MergedAnnotations.from(clazz, INHERITED_ANNOTATIONS).get(RUN_WITH_ANNOTATION_NAME);
if (mergedAnnotation.isPresent()) {
String name = mergedAnnotation.getClass(VALUE).getName();
return (SPRING_JUNIT4_CLASS_RUNNER_NAME.equals(name) || SPRING_RUNNER_NAME.equals(name));
}
return false;
}
private static boolean isGenericSpringTestClass(Class<?> clazz) {
MergedAnnotations mergedAnnotations = MergedAnnotations.from(clazz, TYPE_HIERARCHY);
return (mergedAnnotations.isPresent(ContextConfiguration.class) ||
mergedAnnotations.isPresent(BootstrapWith.class));
}
private static Set<Path> assertPreconditions(Set<Path> classpathRoots) {
Assert.notEmpty(classpathRoots, "'classpathRoots' must not be null or empty");
Assert.noNullElements(classpathRoots, "'classpathRoots' must not contain null elements");
classpathRoots.forEach(classpathRoot -> Assert.isTrue(Files.exists(classpathRoot),
() -> "Classpath root [%s] does not exist".formatted(classpathRoot)));
return classpathRoots;
}
}
|
import java.util.Scanner;
/*
* 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.
*/
/**
*
* @author sinanulug
*/
public class ConsoleApp implements DLManager{
Scanner oku=new Scanner(System.in);
public ConsoleApp() {
new Core(this);
}
public static void main(String[] args) {
ConsoleApp ca=new ConsoleApp();
}
public String getDownloadURL() {
System.out.println("İndirilecek dosyanın URLsi: ");
String yol=oku.next();
return yol;
}
public String getSavedFilePath() {
System.out.println("Kaydedilecek Yer :");
String yol=oku.next();
return yol;
//https://www.textnow.com/
}
public void showPercent(double percent, double total, double downloaded) {
System.out.printf("%% %.2f [%f ∕ %f]\n",percent,downloaded,total);
}
public void showCompleted() {
System.out.println("Dosya indirme tamamlandı.");
}
public void showError() {
System.out.println("Dosya indirme işlemi tamamlanamadı.");
}
}
|
package algorithms.graph.process;
import java.util.ArrayList;
import java.util.List;
import algorithms.context.AbstractContextTest;
import algorithms.graph.Graph;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.junit.Assert;
import org.junit.Test;
@Slf4j
public abstract class AbstractCycleDetectionTest extends AbstractContextTest {
abstract Graph getCycleGraph();
abstract Graph getAcyclicGraph();
abstract CycleDetection getCycleDetection();
@Test
public void hasCycleTest() {
CycleDetection cycleDetection = getCycleDetection();
cycleDetection.init(getCycleGraph());
boolean hasCycle = cycleDetection.hasCycle();
Assert.assertEquals(true, hasCycle);
List<Integer> path = new ArrayList<>();
for (Integer v : cycleDetection.cycle()) {
path.add(v);
}
log.info("has cycle :{} , cycle: {}", hasCycle, StringUtils.join(path, "->"));
}
@Test
public void noCycleTest() {
CycleDetection cycleDetection = getCycleDetection();
getCycleDetection().init(getAcyclicGraph());
boolean hasCycle = cycleDetection.hasCycle();
Assert.assertEquals(false, hasCycle);
log.info("has cycle :{}", hasCycle);
}
}
|
/*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2011 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: proactive@ow2.org or contact@activeeon.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; version 3 of
* the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s): ActiveEon Team - http://www.activeeon.com
*
* ################################################################
* $$ACTIVEEON_CONTRIBUTOR$$
*/
package org.ow2.proactive.scheduler.task.internal;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.persistence.Column;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.MappedSuperclass;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlTransient;
import org.hibernate.annotations.AccessType;
import org.hibernate.annotations.Any;
import org.hibernate.annotations.AnyMetaDef;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import org.hibernate.annotations.ManyToAny;
import org.hibernate.annotations.MetaValue;
import org.hibernate.annotations.Proxy;
import org.hibernate.collection.AbstractPersistentCollection;
import org.objectweb.proactive.ActiveObjectCreationException;
import org.objectweb.proactive.core.node.Node;
import org.objectweb.proactive.core.node.NodeException;
import org.objectweb.proactive.core.util.converter.MakeDeepCopy;
import org.objectweb.proactive.core.util.log.ProActiveLogger;
import org.ow2.proactive.db.annotation.Unloadable;
import org.ow2.proactive.scheduler.common.exception.ExecutableCreationException;
import org.ow2.proactive.scheduler.common.job.JobId;
import org.ow2.proactive.scheduler.common.job.JobInfo;
import org.ow2.proactive.scheduler.common.task.Task;
import org.ow2.proactive.scheduler.common.task.TaskId;
import org.ow2.proactive.scheduler.common.task.TaskInfo;
import org.ow2.proactive.scheduler.common.task.TaskState;
import org.ow2.proactive.scheduler.common.task.TaskStatus;
import org.ow2.proactive.scheduler.common.task.flow.FlowAction;
import org.ow2.proactive.scheduler.common.task.flow.FlowActionType;
import org.ow2.proactive.scheduler.common.task.flow.FlowBlock;
import org.ow2.proactive.scheduler.common.util.SchedulerLoggers;
import org.ow2.proactive.scheduler.core.annotation.TransientInSerialization;
import org.ow2.proactive.scheduler.core.db.DatabaseManager;
import org.ow2.proactive.scheduler.core.properties.PASchedulerProperties;
import org.ow2.proactive.scheduler.job.InternalJob;
import org.ow2.proactive.scheduler.task.ExecutableContainer;
import org.ow2.proactive.scheduler.task.ForkedJavaExecutableContainer;
import org.ow2.proactive.scheduler.task.JavaExecutableContainer;
import org.ow2.proactive.scheduler.task.NativeExecutableContainer;
import org.ow2.proactive.scheduler.task.TaskIdImpl;
import org.ow2.proactive.scheduler.task.TaskInfoImpl;
import org.ow2.proactive.scheduler.task.launcher.TaskLauncher;
import org.ow2.proactive.scheduler.task.launcher.TaskLauncherInitializer;
import org.ow2.proactive.utils.NodeSet;
/**
* Internal and global description of a task.
* This class contains all informations about the task to launch.
* It also provides methods to create its own launcher and manage the content regarding the scheduling order.<br/>
* Specific internal task may extend this abstract class.
*
* @author The ProActive Team
* @since ProActive Scheduling 0.9
*/
@MappedSuperclass
@Table(name = "INTERNAL_TASK")
@AccessType("field")
@Proxy(lazy = false)
@XmlAccessorType(XmlAccessType.FIELD)
public abstract class InternalTask extends TaskState {
/** */
private static final long serialVersionUID = 31L;
/** Parents list : null if no dependences */
// WARNING #writeObject() refers to this field's name as a String
@ManyToAny(metaColumn = @Column(name = "ITASK_TYPE", length = 5))
@AnyMetaDef(idType = "long", metaType = "string", metaValues = {
@MetaValue(targetEntity = InternalJavaTask.class, value = "IJT"),
@MetaValue(targetEntity = InternalNativeTask.class, value = "INT"),
@MetaValue(targetEntity = InternalForkedJavaTask.class, value = "IFJT") })
@JoinTable(joinColumns = @JoinColumn(name = "ITASK_ID"), inverseJoinColumns = @JoinColumn(name = "DEPEND_ID"))
@LazyCollection(value = LazyCollectionOption.FALSE)
@Cascade(CascadeType.ALL)
@XmlTransient
private List<InternalTask> ideps = null;
/** Informations about the launcher and node */
//These informations are not required during task process
@Transient
@TransientInSerialization
private ExecuterInformations executerInformations;
/** Task information : this is the informations that can change during process. */
@Cascade(CascadeType.ALL)
@OneToOne(fetch = FetchType.EAGER, targetEntity = TaskInfoImpl.class)
private TaskInfoImpl taskInfo = new TaskInfoImpl();
/** Node exclusion for this task if desired */
@Transient
@TransientInSerialization
@XmlTransient
private NodeSet nodeExclusion = null;
/** Contains the user executable */
@Unloadable
@Any(fetch = FetchType.LAZY, metaColumn = @Column(name = "EXEC_CONTAINER_TYPE", updatable = false, length = 5))
@AnyMetaDef(idType = "long", metaType = "string", metaValues = {
@MetaValue(targetEntity = JavaExecutableContainer.class, value = "JEC"),
@MetaValue(targetEntity = NativeExecutableContainer.class, value = "NEC"),
@MetaValue(targetEntity = ForkedJavaExecutableContainer.class, value = "FJEC") })
@JoinColumn(name = "EXEC_CONTAINER_ID", updatable = false)
@Cascade(CascadeType.ALL)
@TransientInSerialization
@XmlTransient
protected ExecutableContainer executableContainer = null;
/** Maximum number of execution for this task in case of failure (node down) */
@Column(name = "MAX_EXEC_ON_FAILURE")
private int maxNumberOfExecutionOnFailure = PASchedulerProperties.NUMBER_OF_EXECUTION_ON_FAILURE
.getValueAsInt();
/** iteration number if the task was replicated by a IF control flow action */
@Column(name = "ITERATION")
private int iteration = 0;
/** replication number if the task was replicated by a REPLICATE control flow action */
@Column(name = "REPLICATION")
private int replication = 0;
/** If this{@link #getFlowBlock()} != {@link FlowBlock#NONE},
* each start block has a matching end block and vice versa */
@Column(name = "MATCH_BLOCK")
private String matchingBlock = null;
/** if this task is the JOIN task of a {@link FlowActionType#IF} action,
* this list contains the 2 end-points (tagged {@link FlowBlock#END}) of the
* IF and ELSE branches */
@ManyToAny(metaColumn = @Column(name = "ITASK_TYPE", length = 5))
@AnyMetaDef(idType = "long", metaType = "string", metaValues = {
@MetaValue(targetEntity = InternalJavaTask.class, value = "IJT"),
@MetaValue(targetEntity = InternalNativeTask.class, value = "INT"),
@MetaValue(targetEntity = InternalForkedJavaTask.class, value = "IFJT") })
@JoinTable(joinColumns = @JoinColumn(name = "ITASK_ID"), inverseJoinColumns = @JoinColumn(name = "DEPEND_ID"))
@LazyCollection(value = LazyCollectionOption.FALSE)
@Cascade(CascadeType.ALL)
@TransientInSerialization
@XmlTransient
@Column(name = "JOIN_BRANCH")
private List<InternalTask> joinedBranches = null;
/** if this task is the IF or ELSE task of a {@link FlowActionType#IF} action,
* this fields points to the task performing the corresponding IF action */
@Any(fetch = FetchType.LAZY, metaColumn = @Column(name = "ITASK_TYPE", updatable = false, length = 5))
@AnyMetaDef(idType = "long", metaType = "string", metaValues = {
@MetaValue(targetEntity = InternalJavaTask.class, value = "IJT"),
@MetaValue(targetEntity = InternalNativeTask.class, value = "INT"),
@MetaValue(targetEntity = InternalForkedJavaTask.class, value = "IFJT") })
@JoinColumn(name = "ITASK_ID", updatable = false)
@Cascade(CascadeType.ALL)
@TransientInSerialization
@XmlTransient
private InternalTask ifBranch = null;
/** If unsure, always leave this to false
* when true, {@link #ideps} should not be included in the serialization of this object.
* setting this flag just before serialization prevents large object graphs from being
* serialized when dependencies are not wanted.
*/
@TransientInSerialization
@XmlTransient
private boolean skipIdepsInSerialization = false;
/**
* List of non-static fields that don't have the
* {@link TransientInSerialization} annotation
**/
private static final List<Field> fieldsToSerialize = getFieldsToSerialize();
/**
* {@inheritDoc}
*/
@Override
public TaskState replicate() throws ExecutableCreationException {
/* this implementation deep copies everything using serialization.
* however the new InternalTask cannot be strictly identical and
* we have to handle the following special cases:
*
* - ExecutableContainer is transient and not copied during serialization.
* It needs to be manually copied, and added to the InternalTask replica
*
* - Using the TaskInfo of _this_ gives us a FINISHED task, need to explicitely
* create a new clean one.
*
* - InternalTask dependencies need to be nulled as they contain references
* to other InternalTasks, and will be rewritten later anyway
*
* - Most of the objects down the object graph contain Hibernate @Id fields.
* If all those fields are not set to 0 when inserting the object in DB,
* insertion will fail.
*
* - Collections are mapped to specific Hibernate internal collections at runtime,
* which contain references to the @Id fields mentionned above. They need to be
* reset too.
*/
try {
DatabaseManager.getInstance().load(this);
} catch (NoClassDefFoundError e) {
// only the scheduler core needs to persist InternalTask in DB
// clients may need to call this method nonetheless
} catch (Throwable t) {
// if this happens on the core, you might want to fix it.
// clients that do not use hibernate can ignore this,
ProActiveLogger.getLogger(SchedulerLoggers.DATABASE).debug("Failed to init DB", t);
}
InternalTask replicatedTask = null;
// SCHEDULING-1373 remains, but not replicating the container make the core hangs,
// while replicating it "only" loses tasks args in db...
ExecutableContainer replicatedContainer = null;
try {
this.skipIdepsInSerialization = true;
// Deep copy of the InternalTask using serialization
replicatedTask = (InternalTask) MakeDeepCopy.WithProActiveObjectStream.makeDeepCopy(this);
replicatedContainer = (ExecutableContainer) MakeDeepCopy.WithProActiveObjectStream
.makeDeepCopy(this.executableContainer);
} catch (Throwable t) {
throw new ExecutableCreationException("Failed to serialize task", t);
} finally {
this.skipIdepsInSerialization = false;
}
// ExecutableContainer is transient and non serializable but only given once at construction
// it needs to be explicitely added
replicatedTask.setExecutableContainer(replicatedContainer);
// ideps contain references to other InternalTasks, it needs to be removed.
// anyway, dependecies for the new task will not be the same as the original
replicatedTask.ideps = null;
// the taskinfo needs to be cleaned so that we don't tag this task as finished
TaskId repId = replicatedTask.taskInfo.getTaskId();
replicatedTask.taskInfo = new TaskInfoImpl();
replicatedTask.taskInfo.setTaskId(repId); // we only need this id for the HashSet comparisons...
replicatedTask.taskInfo.setNumberOfExecutionLeft(getMaxNumberOfExecution());
replicatedTask.taskInfo.setNumberOfExecutionOnFailureLeft(getMaxNumberOfExecutionOnFailure());
ArrayList<Object> acc = new ArrayList<Object>();
acc.add(replicatedTask);
try {
// serialization copied everything, including hibernate ids
// these ids need to be set to 0 before DB insertion
resetIds(replicatedTask, acc);
} catch (Throwable e1) {
throw new ExecutableCreationException("Failed to reset hibernate ids in replica", e1);
}
/* uncomment this to have a close look at the serialized graph
* you will need to add some jars (http://xstream.codehaus.org/) to the classpath
XStream x = new XStream();
String sx = x.toXML(replicatedTask);
System.out.println("----------");
System.out.println(sx);
System.out.println("----------");
*/
// We cannot register the newly created InternalTask for DB insertion now,
// since it only makes sense to hibernate once it's added to the parent InternalJob
// The next DB.update(InternalJob) will take care of it
return replicatedTask;
}
/**
* Recursively walks the object graph of the parameter
* to reset any hibernate id encountered
*
* @param obj the root object to walk, may be null
* @param acc the set of all objects walked during the recursive call, to avoid cycles
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
void resetIds(Object obj, List<Object> acc) throws IllegalArgumentException, IllegalAccessException {
if (obj == null)
return;
Class<?> clazz = obj.getClass();
LinkedList<Field> fields = new LinkedList<Field>();
while (clazz != null) {
for (Field f : clazz.getDeclaredFields()) {
if (!Modifier.isStatic(f.getModifiers())) {
fields.addLast(f);
}
}
clazz = clazz.getSuperclass();
}
fields: for (Field f : fields) {
boolean accessible = f.isAccessible();
f.setAccessible(true);
Object value = f.get(obj);
for (Annotation a : f.getAnnotations()) {
// reset unique Hibernate identifiers
if (Id.class.isAssignableFrom(a.annotationType()) ||
GeneratedValue.class.isAssignableFrom(a.annotationType())) {
f.set(obj, 0);
continue fields;
}
}
// every persisted Java Collection is translated at runtime as an Hibernate AbstractPersistentCollection.
// This collection references the parent @Id, so we have to zero it too
if (AbstractPersistentCollection.class.isAssignableFrom(obj.getClass())) {
if (f.getName().equals("key")) {
// the id is a Long name 'key' declared as Serializable
try {
f.set(obj, new Long(0));
} catch (Throwable t) {
ProActiveLogger.getLogger(SchedulerLoggers.DATABASE).debug(
"Failed to reset AbstractPersistentCollection key", t);
}
} else if (f.getName().equals("role")) {
try {
f.set(obj, null);
} catch (Throwable t) {
ProActiveLogger.getLogger(SchedulerLoggers.DATABASE).debug(
"Failed to reset AbstractPersistentCollection role", t);
}
}
}
//boolean contains = acc.contains(value);
boolean contains = false;
for (Object o : acc) {
if (o == value) {
contains = true;
break;
}
}
if (contains) {
continue;
} else {
// this hibernate PersistentMap is nuts: it contains itself twice as a Map
// and Serializable field... this forces me to remove it from the cycle detection
if (!(value != null && AbstractPersistentCollection.class.isAssignableFrom(value.getClass())))
acc.add(value);
}
// arrays do not have regular fields in the java reflect api
if (f.getType().isArray() && value != null && !f.getType().getComponentType().isPrimitive()) {
for (int i = 0; i < Array.getLength(value); i++) {
resetIds(Array.get(value, i), acc);
}
}
// plain string cannot contain ids
else if (value instanceof java.lang.String) {
continue;
}
// go deeper if not string, array or primitive
if (!f.getType().isPrimitive()) {
resetIds(f.get(obj), acc);
}
f.setAccessible(accessible);
}
}
/**
* Accumulates in <code>acc</code> replications of all the tasks that recursively
* depend on <code>this</code> until <code>target</code> is met
*
* @param acc tasks accumulator
* @param target stopping condition
* @param loopAction true if the action performed is a LOOP, false is it is a replicate
* @param dupIndex replication index threshold if <code>ifAction == true</code>
* replication index to set to the old tasks if <code>ifAction == false</code>
* @param itIndex iteration index threshold it <code>ifAction == true</code>
*
* @throws ExecutableCreationException one task could not be replicated
*/
public void replicateTree(Map<TaskId, InternalTask> acc, TaskId target, boolean loopAction, int dupIndex,
int itIndex) throws ExecutableCreationException {
Map<TaskId, InternalTask> tmp = new HashMap<TaskId, InternalTask>();
// replicate the tasks
internalReplicateTree(tmp, target, loopAction, dupIndex, itIndex);
// remove replicates from nested LOOP action
Map<String, Entry<TaskId, InternalTask>> map = new HashMap<String, Entry<TaskId, InternalTask>>();
for (Entry<TaskId, InternalTask> it : tmp.entrySet()) {
String name = it.getValue().getAmbiguousName();
if (map.containsKey(name)) {
Entry<TaskId, InternalTask> cur = map.get(name);
if (it.getValue().getIterationIndex() < cur.getValue().getIterationIndex()) {
map.put(name, it);
}
} else {
map.put(name, it);
}
}
for (Entry<TaskId, InternalTask> it : map.values()) {
acc.put(it.getKey(), it.getValue());
}
// reconstruct the dependencies
internalReconstructTree(acc, target, loopAction, dupIndex, itIndex);
}
/**
* Internal recursive delegate of {@link #replicateTree(Map, TaskId)} for task replication
*
* @param acc accumulator
* @param target end condition
* @param loopAction true if the action performed is a LOOP, false is it is a replicate
* @param initDupIndex replication index threshold if <code>ifAction == true</code>
* replication index to set to the old tasks if <code>ifAction == false</code>
* @param itIndex iteration index threshold it <code>ifAction == true</code>
*
* @throws ExecutableCreationException one task could not be replicated
*/
private void internalReplicateTree(Map<TaskId, InternalTask> acc, TaskId target, boolean loopAction,
int dupIndex, int itIndex) throws ExecutableCreationException {
InternalTask nt = null;
if (!acc.containsKey(this.getId())) {
nt = (InternalTask) this.replicate();
// when nesting REPLICATE actions, the replication index of the original tasks will change
if (!loopAction) {
this.setReplicationIndex(dupIndex);
} else {
nt.setIterationIndex(this.getIterationIndex() + 1);
}
acc.put(this.getTaskInfo().getTaskId(), nt);
// recursive call
if (!this.getTaskInfo().getTaskId().equals(target)) {
if (this.getIDependences() != null) {
Map<String, InternalTask> deps = new HashMap<String, InternalTask>();
for (InternalTask parent : this.getIDependences()) {
// filter out replicated tasks
if (deps.containsKey(parent.getAmbiguousName())) {
InternalTask dep = deps.get(parent.getAmbiguousName());
if (dep.getReplicationIndex() > parent.getReplicationIndex()) {
deps.put(parent.getAmbiguousName(), parent);
}
} else {
deps.put(parent.getAmbiguousName(), parent);
}
}
for (InternalTask parent : deps.values()) {
parent.internalReplicateTree(acc, target, loopAction, dupIndex, itIndex);
}
}
if (this.getJoinedBranches() != null) {
for (InternalTask parent : this.getJoinedBranches()) {
parent.internalReplicateTree(acc, target, loopAction, dupIndex, itIndex);
}
}
if (this.getIfBranch() != null) {
this.getIfBranch().internalReplicateTree(acc, target, loopAction, dupIndex, itIndex);
}
}
}
}
/**
* Internal recursive delegate of {@link #replicateTree(Map, TaskId)} for dependence replication
*
* @param acc accumulator
* @param target end condition
* @param loopAction true if the action performed is an if, false is it is a replicate
* @param initDupIndex replication index threshold if <code>ifAction == true</code>
* replication index to set to the old tasks if <code>ifAction == false</code>
* @param itIndex iteration index threshold it <code>ifAction == true</code>
*
* @throws Exception instantiation error
*/
private void internalReconstructTree(Map<TaskId, InternalTask> acc, TaskId target, boolean loopAction,
int dupIndex, int itIndex) {
if (target.equals(this.getId())) {
return;
}
InternalTask nt = acc.get(this.getId());
Map<String, InternalTask> ideps = new HashMap<String, InternalTask>();
int deptype = 0;
if (this.getIfBranch() != null) {
deptype = 1;
ideps.put(this.getIfBranch().getAmbiguousName(), this.getIfBranch());
} else if (this.getJoinedBranches() != null && this.getJoinedBranches().size() == 2) {
deptype = 2;
ideps.put(this.getJoinedBranches().get(0).getAmbiguousName(), this.getJoinedBranches().get(0));
ideps.put(this.getJoinedBranches().get(1).getAmbiguousName(), this.getJoinedBranches().get(1));
} else if (this.hasDependences()) {
// hard dependency check has to be exclusive and AFTER if branch checks :
// if an FlowAction#IF was executed, we should have both weak and hard dependencies,
// although only the weak one should be copied on the replicated task
// ideps.addAll(this.getIDependences());
for (InternalTask parent : this.getIDependences()) {
// filter out replicated tasks
if (ideps.containsKey(parent.getAmbiguousName())) {
InternalTask dep = ideps.get(parent.getAmbiguousName());
if (dep.getReplicationIndex() > parent.getReplicationIndex()) {
ideps.put(parent.getAmbiguousName(), parent);
}
} else {
ideps.put(parent.getAmbiguousName(), parent);
}
}
}
if (ideps.size() == 0) {
return;
}
for (InternalTask parent : ideps.values()) {
if (acc.get(parent.getId()) == null && nt != null) {
// tasks are skipped to prevent nested LOOP
while (acc.get(parent.getId()) == null) {
InternalTask np = parent.getIDependences().get(0);
if (np == null) {
if (parent.getIfBranch() != null) {
np = parent.getIfBranch();
} else if (parent.getJoinedBranches() != null) {
np = parent.getJoinedBranches().get(0);
}
}
parent = np;
}
InternalTask tg = acc.get(parent.getId());
nt.addDependence(tg);
} else if (nt != null) {
InternalTask tg = acc.get(parent.getId());
boolean hasit = false;
switch (deptype) {
case 0:
if (nt.hasDependences()) {
for (InternalTask it : nt.getIDependences()) {
// do NOT use contains(): relies on getId() which is null
if (it.getName().equals(tg.getName())) {
hasit = true;
}
}
}
if (!hasit) {
nt.addDependence(tg);
}
break;
case 1:
nt.setIfBranch(tg);
break;
case 2:
if (nt.getJoinedBranches() == null) {
List<InternalTask> jb = new ArrayList<InternalTask>();
nt.setJoinedBranches(jb);
}
for (InternalTask it : nt.getJoinedBranches()) {
if (it.getName().equals(tg.getName())) {
hasit = true;
}
}
if (!hasit) {
nt.getJoinedBranches().add(tg);
}
break;
}
}
if (!parent.getTaskInfo().getTaskId().equals(target)) {
parent.internalReconstructTree(acc, target, loopAction, dupIndex, itIndex);
}
}
}
/**
* Recursively checks if this is a dependence,
* direct or indirect, of <code>parent</code>
* <p>
* Direct dependence means through {@link Task#getDependencesList()},
* indirect dependence means through weak dependences induced by
* {@link FlowActionType#IF}, materialized by
* {@link InternalTask#getIfBranch()} and {@link InternalTask#getJoinedBranches()}.
*
* @param parent the dependence to find
* @return true if this depends on <code>parent</code>
*/
public boolean dependsOn(InternalTask parent) {
return internalDependsOn(parent, 0);
}
private boolean internalDependsOn(InternalTask parent, int depth) {
if (this.getId().equals(parent.getId())) {
return (depth >= 0);
}
if (this.getIDependences() == null && this.getJoinedBranches() == null && this.getIfBranch() == null) {
return false;
}
if (this.joinedBranches != null) {
for (InternalTask it : this.getJoinedBranches()) {
if (!it.internalDependsOn(parent, depth - 1)) {
return false;
}
}
} else if (this.getIfBranch() != null) {
if (!this.getIfBranch().internalDependsOn(parent, depth + 1)) {
return false;
}
} else if (this.getIDependences() != null) {
for (InternalTask it : this.getIDependences()) {
if (!it.internalDependsOn(parent, depth)) {
return false;
}
}
}
return true;
}
public void setExecutableContainer(ExecutableContainer e) {
this.executableContainer = e;
}
/** Hibernate default constructor */
public InternalTask() {
}
/**
* Create the launcher for this taskDescriptor.
*
* @param node the node on which to create the launcher.
* @param job the job on which to create the launcher.
* @return the created launcher as an activeObject.
*/
public abstract TaskLauncher createLauncher(InternalJob job, Node node)
throws ActiveObjectCreationException, NodeException;
/**
* Return true if this task can handle parent results arguments in its executable
*
* @return true if this task can handle parent results arguments in its executable, false if not.
*/
public abstract boolean handleResultsArguments();
/**
* Return a container for the user executable represented by this task descriptor.
*
* @return the user executable represented by this task descriptor.
*/
public ExecutableContainer getExecutableContainer() {
return this.executableContainer;
}
/**
* Add a dependence to the list of dependences for this taskDescriptor.
* The tasks in this list represents the tasks that the current task have to wait for before starting.
*
* @param task a super task of this task.
*/
public void addDependence(InternalTask task) {
if (ideps == null) {
ideps = new ArrayList<InternalTask>();
}
ideps.add(task);
}
public boolean removeDependence(InternalTask task) {
if (ideps != null) {
return ideps.remove(task);
}
return false;
}
/**
* Return true if this task has dependencies.
* It means the first eligible tasks in case of TASK_FLOW job type.
*
* @return true if this task has dependencies, false otherwise.
*/
public boolean hasDependences() {
return (ideps != null && ideps.size() > 0);
}
/**
* @see org.ow2.proactive.scheduler.common.task.TaskState#getTaskInfo()
*/
@Override
public TaskInfo getTaskInfo() {
return taskInfo;
}
/**
* @see org.ow2.proactive.scheduler.common.task.TaskState#update(org.ow2.proactive.scheduler.common.task.TaskInfo)
*/
@Override
public synchronized void update(TaskInfo taskInfo) {
if (!getId().equals(taskInfo.getTaskId())) {
throw new IllegalArgumentException(
"This task info is not applicable for this task. (expected id is '" + getId() +
"' but was '" + taskInfo.getTaskId() + "'");
}
this.taskInfo = (TaskInfoImpl) taskInfo;
}
/**
* @see org.ow2.proactive.scheduler.common.task.CommonAttribute#setMaxNumberOfExecution(int)
*/
@Override
public void setMaxNumberOfExecution(int numberOfExecution) {
super.setMaxNumberOfExecution(numberOfExecution);
this.taskInfo.setNumberOfExecutionLeft(numberOfExecution);
this.taskInfo.setNumberOfExecutionOnFailureLeft(maxNumberOfExecutionOnFailure);
}
/**
* To set the finishedTime
*
* @param finishedTime the finishedTime to set
*/
public void setFinishedTime(long finishedTime) {
taskInfo.setFinishedTime(finishedTime);
//set max progress if task is finished
if (finishedTime > 0) {
taskInfo.setProgress(100);
}
}
/**
* To set the jobId
*
* @param id the jobId to set
*/
public void setJobId(JobId id) {
taskInfo.setJobId(id);
}
/**
* To set the startTime
*
* @param startTime the startTime to set
*/
public void setStartTime(long startTime) {
taskInfo.setStartTime(startTime);
}
/**
* To set the taskId
*
* @param taskId the taskId to set
*/
public void setId(TaskId taskId) {
taskInfo.setTaskId(taskId);
}
/**
* Set the job info to this task.
*
* @param jobInfo a job info containing job id and others informations
*/
public void setJobInfo(JobInfo jobInfo) {
taskInfo.setJobInfo(jobInfo);
}
/**
* To set the status
*
* @param taskStatus the status to set
*/
public void setStatus(TaskStatus taskStatus) {
taskInfo.setStatus(taskStatus);
}
/**
* Set the real execution duration for the task.
*
* @param duration the real duration of the execution of the task
*/
public void setExecutionDuration(long duration) {
taskInfo.setExecutionDuration(duration);
}
/**
* To get the dependences of this task as internal tasks.
* Return null if this task has no dependence.
*
* @return the dependences
*/
public List<InternalTask> getIDependences() {
//set to null if needed
if (ideps != null && ideps.size() == 0) {
ideps = null;
}
return ideps;
}
/**
* {@inheritDoc}
*/
@Override
@XmlTransient
public List<TaskState> getDependences() {
//set to null if needed
if (ideps == null || ideps.size() == 0) {
ideps = null;
return null;
}
List<TaskState> tmp = new ArrayList<TaskState>(ideps.size());
for (TaskState ts : ideps) {
tmp.add(ts);
}
return tmp;
}
/**
* To set the executionHostName
*
* @param executionHostName the executionHostName to set
*/
public void setExecutionHostName(String executionHostName) {
taskInfo.setExecutionHostName(executionHostName);
}
/**
* To get the executer informations
*
* @return the executerInformations
*/
public ExecuterInformations getExecuterInformations() {
return executerInformations;
}
/**
* To set the executer informations.
*
* @param executerInformations the executerInformations to set
*/
public void setExecuterInformations(ExecuterInformations executerInformations) {
this.executerInformations = executerInformations;
}
/**
* Returns the node Exclusion group.
*
* @return the node Exclusion group.
*/
public NodeSet getNodeExclusion() {
return nodeExclusion;
}
/**
* Sets the nodes Exclusion to the given nodeExclusion value.
*
* @param nodeExclusion the nodeExclusion to set.
*/
public void setNodeExclusion(NodeSet nodeExclusion) {
this.nodeExclusion = nodeExclusion;
}
/**
* Decrease the number of re-run left.
*/
public void decreaseNumberOfExecutionLeft() {
taskInfo.decreaseNumberOfExecutionLeft();
}
/**
* Decrease the number of execution on failure left.
*/
public void decreaseNumberOfExecutionOnFailureLeft() {
taskInfo.decreaseNumberOfExecutionOnFailureLeft();
}
/**
* @see org.ow2.proactive.scheduler.common.task.TaskState#getMaxNumberOfExecutionOnFailure()
*/
@Override
public int getMaxNumberOfExecutionOnFailure() {
return maxNumberOfExecutionOnFailure;
}
/**
* Set the current progress of the task
*
* @param progress the current progress of the task
*/
public void setProgress(Integer progress) {
taskInfo.setProgress(progress);
}
/**
* To set the name of this task.
* <p>
* The provided String will be appended the iteration and replication index
* if > 0, so that: <br>
* <code>name = name [iterationSeparator iteration] [replicationSeparator replication]</code>
*
* @param newName
* the name to set.
*/
public void setName(String newName) {
if (newName == null) {
return;
}
int i = -1;
if ((i = newName.indexOf(TaskId.iterationSeparator)) != -1) {
newName = newName.substring(0, i);
} else if ((i = newName.indexOf(TaskId.replicationSeparator)) != -1) {
newName = newName.substring(0, i);
}
String n = this.getTaskNameSuffix();
if (newName.length() + n.length() > 255) {
throw new IllegalArgumentException("The name is too long, it must have 255 chars length max : " +
newName + n);
}
super.setName(newName + n);
if (this.getId() != null) {
((TaskIdImpl) this.getId()).setReadableName(newName + n);
}
// update matching block name if it exists
// start/end block tasks should always have the same iteration & replication
if (this.matchingBlock != null && this.matchingBlock.length() > 0) {
String m = getInitialName(this.matchingBlock);
this.setMatchingBlock(m + getTaskNameSuffix());
}
// update target name if this task performs a LOOP action
// same as the matching block name : indexes should match as LOOP initiator and
// target share the same block scope
if (this.getFlowScript() != null &&
this.getFlowScript().getActionType().equals(FlowActionType.LOOP.toString())) {
String t = getInitialName(this.getFlowScript().getActionTarget());
this.getFlowScript().setActionTarget(t + getTaskNameSuffix());
}
// same stuff with IF
if (this.getFlowScript() != null &&
this.getFlowScript().getActionType().equals(FlowActionType.IF.toString())) {
String ifBranch = getInitialName(this.getFlowScript().getActionTarget());
String elseBranch = getInitialName(this.getFlowScript().getActionTargetElse());
this.getFlowScript().setActionTarget(ifBranch + getTaskNameSuffix());
this.getFlowScript().setActionTargetElse(elseBranch + getTaskNameSuffix());
if (this.getFlowScript().getActionContinuation() != null) {
String join = getInitialName(this.getFlowScript().getActionContinuation());
this.getFlowScript().setActionContinuation(join + getTaskNameSuffix());
}
}
}
/**
* Constructs the suffix to append to a task name so that is
* can be unique among replicated tasks in complex taskflows with loops/replications
*
* @return the String suffix to append to a replicated task so that
* it can be distinguished from the original
*/
private String getTaskNameSuffix() {
String n = "";
if (this.iteration > 0) {
n += TaskId.iterationSeparator + this.iteration;
}
if (this.replication > 0) {
n += TaskId.replicationSeparator + this.replication;
}
return n;
}
/**
* Extracts the original task name if it was added a suffix to
* make it unique among replicated tasks
* <p>
* <b>This methods returns an ambiguous name: several tasks can share this name;
* it cannot be used as an identifier.
* </b>
* @return the original task name, without the added suffixes for iteration and replication
*/
private String getAmbiguousName() {
return getInitialName(this.getName());
}
/**
* Extracts the original task name if it was added a suffix to
* make it unique among replicated tasks
* <p>
* <b>This methods returns an ambiguous name: several tasks can share this name;
* it cannot be used as an identifier.
* </b>
* @param fullTaskName name with the iteration and replication suffixes
* @return the original task name, without the added suffixes for iteration and replication
*/
public static String getInitialName(String fullTaskname) {
String taskName = null;
String[] str = new String[] { "^(.*)[" + TaskId.iterationSeparator + "].*$",
"^(.*)[" + TaskId.replicationSeparator + "].*$", "^(.*)$" };
Matcher matcher = null;
for (String regex : str) {
Pattern pat = Pattern.compile(regex);
matcher = pat.matcher(fullTaskname);
if (matcher.find()) {
taskName = matcher.group(1);
return taskName;
}
}
throw new RuntimeException("Could not extract task name: " + fullTaskname);
}
/**
* Extracts the replication index from a non ambiguous name:
* <p>ie: getReplicationIndexFromName("task1*3") returns 3.
*
* @param name non ambiguous task name
* @return the replication index contained in the name
*/
public static int getReplicationIndexFromName(String name) {
if (name.indexOf(TaskId.replicationSeparator) == -1) {
return 0;
} else {
return Integer.parseInt(name.split("[" + TaskId.replicationSeparator + "]")[1]);
}
}
/**
* Extracts the iteration index from a non ambiguous name:
* <p>ie: getIterationIndexFromName("task1#3") returns 3.
*
* @param name non ambiguous task name
* @return the replication index contained in the name
*/
public static int getIterationIndexFromName(String name) {
if (name.indexOf(TaskId.iterationSeparator) == -1) {
return 0;
} else {
String suffix = name.split("[" + TaskId.iterationSeparator + "]")[1];
return Integer.parseInt(suffix.split("[" + TaskId.replicationSeparator + "]")[0]);
}
}
/**
* Set the iteration number of this task if it was replicated by a IF flow operations
* <p>
* Updates the Task's name consequently, see {@link Task#setName(String)}
*
* @param it iteration number, must be >= 0
*/
public void setIterationIndex(int it) {
if (it < 0) {
throw new IllegalArgumentException("Cannot set negative iteration index: " + it);
}
String taskName = getInitialName(this.getName());
this.iteration = it;
this.setName(taskName);
}
/**
* @return the iteration number of this task if it was replicated by a LOOP flow operations (>= 0)
*/
@Override
public int getIterationIndex() {
return this.iteration;
}
/**
* Set the replication number of this task if it was replicated by a REPLICATE flow operations
*
* @param it iteration number, must be >= 0
*/
public void setReplicationIndex(int it) {
if (it < 0) {
throw new IllegalArgumentException("Cannot set negative replication index: " + it);
}
String taskName = getInitialName(this.getName());
this.replication = it;
this.setName(taskName);
}
/**
* @return the replication number of this task if it was replicated by a REPLICATE flow operations (>= 0)
*/
@Override
public int getReplicationIndex() {
return this.replication;
}
/**
* Control Flow Blocks are formed with pairs of {@link FlowBlock#START} and {@link FlowBlock#END}
* on tasks. The Matching Block of a Task represents the corresponding
* {@link FlowBlock#START} of a Task tagged {@link FlowBlock#END}, and vice-versa.
*
* @return the name of the Task matching the block started or ended in this task, or null
*/
public String getMatchingBlock() {
return this.matchingBlock;
}
/**
* Control Flow Blocks are formed with pairs of {@link FlowBlock#START} and {@link FlowBlock#END}
* on tasks. The Matching Block of a Task represents the corresponding
* {@link FlowBlock#START} of a Task tagged {@link FlowBlock#END}, and vice-versa.
*
* @param s the name of the Task matching the block started or ended in this task
*/
public void setMatchingBlock(String s) {
this.matchingBlock = s;
}
/**
* If a {@link FlowActionType#IF} {@link FlowAction} is performed in a TaskFlow,
* there exist no hard dependency between the initiator of the action and the IF or ELSE
* branch. Similarly, there exist no dependency between the IF or ELSE branches
* and the JOIN task.
* This method provides an easy way to check if this task joins an IF/ELSE action
*
* @return a List of String containing the end-points of the IF and ELSE branches
* joined by this task, or null if it does not merge anything.
*/
public List<InternalTask> getJoinedBranches() {
return this.joinedBranches;
}
/**
* If a {@link FlowActionType#IF} {@link FlowAction} is performed in a TaskFlow,
* there exist no hard dependency between the initiator of the action and the IF or ELSE
* branch. Similarly, there exist no dependency between the IF or ELSE branches
* and the JOIN task.
*
* @param branches sets the List of String containing the end-points
* of the IF and ELSE branches joined by this task
*/
public void setJoinedBranches(List<InternalTask> branches) {
this.joinedBranches = branches;
}
/**
* If a {@link FlowActionType#IF} {@link FlowAction} is performed in a TaskFlow,
* there exist no hard dependency between the initiator of the action and the IF or ELSE
* branch. Similarly, there exist no dependency between the IF or ELSE branches
* and the JOIN task.
* This method provides an easy way to check if this task is an IF/ELSE branch.
*
* @return the name of the initiator of the IF action that this task is a branch of
*/
public InternalTask getIfBranch() {
return this.ifBranch;
}
/**
* If a {@link FlowActionType#IF} {@link FlowAction} is performed in a TaskFlow,
* there exist no hard dependency between the initiator of the action and the IF or ELSE
* branch. Similarly, there exist no dependency between the IF or ELSE branches
* and the JOIN task.
*
* @return the name of the initiator of the IF action that this task is a branch of
*/
public void setIfBranch(InternalTask branch) {
this.ifBranch = branch;
}
/**
* Prepare and return the default task launcher initializer (ie the one that works for every launcher)<br>
* Concrete launcher may have to add values to the created initializer to bring more information to the launcher.
*
* @return the default created task launcher initializer
*/
protected TaskLauncherInitializer getDefaultTaskLauncherInitializer(InternalJob job) {
TaskLauncherInitializer tli = new TaskLauncherInitializer();
tli.setOwner(job.getOwner());
tli.setTaskId(getId());
tli.setPreScript(getPreScript());
tli.setPostScript(getPostScript());
tli.setControlFlowScript(getFlowScript());
tli.setTaskInputFiles(getInputFilesList());
tli.setTaskOutputFiles(getOutputFilesList());
tli.setNamingServiceUrl(job.getJobDataSpaceApplication().getNamingServiceURL());
tli.setIterationIndex(getIterationIndex());
tli.setReplicationIndex(getReplicationIndex());
if (isWallTimeSet()) {
tli.setWalltime(wallTime);
}
tli.setPreciousLogs(isPreciousLogs());
return tli;
}
/**
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (InternalTask.class.isAssignableFrom(obj.getClass())) {
return ((InternalTask) obj).getId().equals(getId());
}
return false;
}
//********************************************************************
//************************* SERIALIZATION ****************************
//********************************************************************
/**
* Serialize this instance. Include only the fields contained in the
* {@link #fieldsToSerialize}. <br/>
*
* If {@link #skipIdepsInSerialization} is true when this method is called,
* {@link #ideps} will not be included in the serialized object.
*/
private void writeObject(ObjectOutputStream out) throws IOException {
try {
Map<String, Object> toSerialize = new HashMap<String, Object>();
for (Field f : fieldsToSerialize) {
// skip the "ideps" field if the skipIdepsInSerialization flag is set
if (!(this.skipIdepsInSerialization && (f.getName() == "ideps"))) {
toSerialize.put(f.getName(), f.get(this));
}
}
out.writeObject(toSerialize);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings("unchecked")
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
try {
Map<String, Object> map = (Map<String, Object>) in.readObject();
for (Entry<String, Object> e : map.entrySet()) {
InternalTask.class.getDeclaredField(e.getKey()).set(this, e.getValue());
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Create a list of non-static fields without
* {@link TransientInSerialization} annotation for later use by the
* {@link #writeObject} method. <br/>
*
* Note that {@link TransientInSerialization} is used to annotate the fields
* of this class that should not be serialized by Java serialization. <br/>
*
* Also note that <b>transient</b> modifier cannot be used instead of
* {@link TransientInSerialization} because, for performance reasons, some
* fields must be Java-transient but not Hibernate-transient; such fields
* can have neither the {@link Transient} annotation nor the
* <b>transient</b> modifier.
*
*/
private static List<Field> getFieldsToSerialize() {
List<Field> fieldsToSerialize = new ArrayList<Field>();
Field[] fields = InternalTask.class.getDeclaredFields();
for (Field f : fields) {
if (!f.isAnnotationPresent(TransientInSerialization.class) &&
!Modifier.isStatic(f.getModifiers())) {
fieldsToSerialize.add(f);
}
}
return fieldsToSerialize;
}
}
|
package util;
import javafx.scene.control.Alert;
import model.Appointment;
import java.text.ParseException;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.WeekFields;
import java.util.Date;
import java.util.List;
import java.util.Locale;
public class TimeConverter {
/**
* gets current system local time
* @return
*/
public String getLocalTime() {
return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
}
/**
* gets current UTC time
* @return
*/
public String getUtcTime() {
return LocalDateTime.now(ZoneId.of("UTC")).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
}
/**
* converts system time to UTC
* @param time
* @return
*/
public String convertDefaultToUtc(String time) {
return ZonedDateTime
.parse(time, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault()))
.toOffsetDateTime()
.atZoneSameInstant(ZoneId.of("UTC"))
.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
}
/**
* converts UTC to system time
* @param time
* @return
*/
public String convertUtcToDefault(String time) {
return ZonedDateTime
.parse(time, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneOffset.UTC))
.toOffsetDateTime()
.atZoneSameInstant(ZoneId.systemDefault())
.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
}
/**
* checks if date is in a valid form
* @param validate
* @throws DateTimeParseException
*/
public void isValidDate(String validate) throws DateTimeParseException {
try {
LocalDateTime.parse(validate, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
} catch (DateTimeParseException e) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Invalid Time String");
alert.setHeaderText("Start/End Times Must Be In: yyyy-MM-dd hh:mm:ss");
alert.setContentText("Please enter a valid time and try again");
alert.showAndWait();
}
}
/**
* checks if time is within busines hours
* @param validate
* @throws Exception
*/
public void isBusinessHours(String validate) throws Exception {
int compare = Integer.parseInt(LocalDateTime.parse(validate, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).format(DateTimeFormatter.ofPattern("HH")));
int opening = Integer.parseInt(LocalTime.parse("09:00:00", DateTimeFormatter.ofPattern("HH:mm:ss")).format(DateTimeFormatter.ofPattern("HH")));
int closing = Integer.parseInt(LocalTime.parse("17:00:00", DateTimeFormatter.ofPattern("HH:mm:ss")).format(DateTimeFormatter.ofPattern("HH")));
if (compare < opening || compare > closing){
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Outside of Business Hours");
alert.setHeaderText("Start/End Times Must Be Between the hours of: 09:00:00 - 17:00:00");
alert.setContentText("Please enter a valid time and try again");
alert.showAndWait();
throw new Exception("Outside of Business Hours");
}
}
/**
* checks if date within the current month
* @param validate
* @return
*/
public boolean isCurrentMonth(String validate) {
String newValidate = LocalDateTime.parse(validate, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).format(DateTimeFormatter.ofPattern("yyyy-MM"));
String localDate = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM"));
return localDate.equals(newValidate);
}
/**
* checks if date is witnin current week
* @param validate
* @return
*/
public boolean isCurrentWeek(String validate) {
int day, month, year; // comparing dates
int cDay, cMonth, cYear; // current dates
String currentDate = getLocalTime();
year = Integer.parseInt(validate.substring(0,4));
month = Integer.parseInt(validate.substring(5,7));
day = Integer.parseInt(validate.substring(8,10));
cYear = Integer.parseInt(currentDate.substring(0,4));
cMonth = Integer.parseInt(currentDate.substring(5,7));
cDay = Integer.parseInt(currentDate.substring(8,10));
Locale userLocale = Locale.getDefault();
WeekFields weekNumbering = WeekFields.of(userLocale);
LocalDate date = LocalDate.of(year, month, day);
LocalDate cDate = LocalDate.of(cYear, cMonth, cDay);
int compWeek = date.get(weekNumbering.weekOfWeekBasedYear());
int currentWeek = cDate.get(weekNumbering.weekOfWeekBasedYear());
return compWeek == currentWeek;
}
/**
* converts date and time into ZoneDateTime object
* @param time
* @return
* @throws ParseException
*/
public ZonedDateTime dateConverter(String time) throws ParseException {
return ZonedDateTime.parse(time, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault()));
}
/**
* uses converted date time ZoneDateTime object to see if time overlaps
* @param time1Start
* @param time1End
* @param time2Start
* @param time2End
* @throws ParseException
* @throws CustomException
*/
public void isOverlap(String time1Start, String time1End, String time2Start, String time2End) throws ParseException, CustomException {
ZonedDateTime date1;
ZonedDateTime date2;
ZonedDateTime date3;
ZonedDateTime date4;
date1 = dateConverter(time1Start);
date2 = dateConverter(time1End);
date3 = dateConverter(time2Start);
date4 = dateConverter(time2End);
if(date1.isBefore(date4) && date3.isBefore(date2))
throw(new CustomException("OVERLAPPING TIME"));
}
public void loginCheck(List<Appointment> appointment) {
String currentDayHour;
String currentTime = getUtcTime();
String minute = currentTime.substring(14,16);
currentDayHour = currentTime.substring(0,13);
int minuteMin = Integer.parseInt(minute);
int minuteMax = minuteMin + 15;
appointment.forEach(x -> {
String appointmentMinute = x.getStartTime().substring(14,16);
int appointmentMin = Integer.parseInt(appointmentMinute);
System.out.println(minuteMin + " < = " + appointmentMin + " > = " + minuteMax + " AND " + x.getStartTime().substring(0,13));
if (x.getStartTime().substring(0,13).equals(currentDayHour) && (
minuteMin <= appointmentMin && minuteMax >= appointmentMin
) ){
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Upcoming Appointment Within 15 Minutes");
alert.setHeaderText("You have an appointment starting in 15 minutes");
alert.setContentText("Did I mention that an appointment will start within 15 minutes?");
alert.showAndWait();
}
});
System.out.println(minuteMin + " - " + minuteMax);
System.out.println(currentDayHour);
System.out.println(getUtcTime());
}
}
|
package com.netcracker.folktaxi;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Activity {
public void getActiveDriver() {
try {
Connection con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/folktaxi",
"postgres",
"root"
);
//PreparedStatement stmt = con.prepareStatement(" SELECT current_database();");
PreparedStatement stmt = con.prepareStatement(
" SELECT J.driver_id " +
"FROM JOURNEY J" +
"GROUP BY J.driver_id" +
"HAVING COUNT(J.journey_id)=(SELECT MAX(VAL) FROM" +
"(SELECT COUNT(J1.journey_id)AS VAL " +
"FROM JOURNEY J1" +
"GROUP BY J1.driver_id)K);"
);
ResultSet rs = stmt.executeQuery();
while (rs.next())
System.out.println(rs.getString(1));
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
|
package com.jgw.supercodeplatform.trace.pojo;
/**
* 企业功能路由关系表
* @author czm
*
*/
public class TraceOrgFunRoute {
private Integer id; //序列Id
private String organizationId; //组织Id
private String functionId; //功能ID号(节点Id)
private String databaseAddress; //数据库地址
private String tableName; //表名
private String traceTemplateId; //溯源模板号
public TraceOrgFunRoute() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getOrganizationId() {
return organizationId;
}
public String getTraceTemplateId() {
return traceTemplateId;
}
public void setTraceTemplateId(String traceTemplateId) {
this.traceTemplateId = traceTemplateId;
}
public void setOrganizationId(String organizationId) {
this.organizationId = organizationId;
}
public String getFunctionId() {
return functionId;
}
public void setFunctionId(String functionId) {
this.functionId = functionId;
}
public String getDatabaseAddress() {
return databaseAddress;
}
public void setDatabaseAddress(String databaseAddress) {
this.databaseAddress = databaseAddress;
}
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
}
|
package uzduotis10;
import java.io.*;
/*
Iš duomenų failo nustatyti kokie skaičiai yra lyginiai
ir išvesti į rezultatų failą skaičių ir ar jis lyginis.
Pvz: 1 - nelyginis
2 – lyginis
*/
public class uzduotis10 {
public static void main(String[] args) {
String file = "C:\\TestineRep\\HelloWorld\\src\\uzduotis10\\Duomenys.txt";
String fileRasymui = "C:\\TestineRep\\HelloWorld\\src\\uzduotis10\\Atsakymai.txt";
try {
String nuskaitytiSkaiciai = Skaityti(file);
// \\W+ pasalina viskas kas ne zodziai
String[] skaiciuMasyvasString = nuskaitytiSkaiciai.split("\\W+");
Integer[] skaiciuMasyvas = GautiSkaiciuMasyva(skaiciuMasyvasString);
Rasyti(fileRasymui, skaiciuMasyvas);
} catch (IOException e) {
e.printStackTrace();
}
}
public static Integer[] GautiSkaiciuMasyva(String[] skaiciai) {
Integer[] skaiciuMasyvas = new Integer[skaiciai.length];
for (int i = 0; i < skaiciai.length; i++) {
skaiciuMasyvas[i] = Integer.parseInt(skaiciai[i]);
}
return skaiciuMasyvas;
}
public static String Skaityti(String failas) throws IOException {
String visosEilutes = "";
BufferedReader br = new BufferedReader(new FileReader(failas));
try {
String line = br.readLine();
while (line != null) {
visosEilutes += line + " ";
line = br.readLine();
}
} catch (FileNotFoundException ex) {
System.out.println("Failas nerastas");
} finally {
br.close();
}
return visosEilutes;
}
public static void Rasyti(String failas, Integer[] skaiciuMasyvas) throws IOException {
BufferedWriter output = null;
try {
output = new BufferedWriter(new FileWriter(failas));
for(int i = 0; i < skaiciuMasyvas.length; i++) {
if (skaiciuMasyvas[i] % 2 == 0) {
output.write(skaiciuMasyvas[i] + " - Skaicius yra lyginis" + "\n");
} else {
output.write(skaiciuMasyvas[i] + " - Skaicius yra nera lyginis" + "\n");
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (output != null) {
output.close();
}
}
}
}
|
package com.trump.auction.reactor.common.repository;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import java.util.*;
/**
* Base class of redis repository
*
* @author Owen
* @since 2018/1/22
*/
public abstract class AbstractRedisRepository {
public static final String KEY_PREFIX = "auction.reactor";
protected <T> T convertToBean(String json, Class<T> clazz) {
return JSON.parseObject(json, clazz);
}
protected <T> List<T> convertToBean(List<String> list, Class<T> clazz) {
if (CollectionUtils.isEmpty(list)) {
return Collections.EMPTY_LIST;
}
return Lists.transform(list, (json) -> JSON.parseObject(json, clazz));
}
protected <V> Map<String, V> convertToBean(Map<Object, Object> src, Class<V> clazz) {
if (CollectionUtils.isEmpty(src)) {
return Collections.EMPTY_MAP;
}
Map<String, V> result = new HashMap<>();
for (Map.Entry<Object, Object> entry : src.entrySet()) {
result.put(entry.getKey().toString(), JSON.parseObject(entry.getValue().toString(), clazz));
}
return result;
}
protected String makeKey(String auctionNo, String... keyNames) {
Assert.notNull(auctionNo, "[auctionNo]");
Assert.notNull(keyNames, "[keyNames]");
StringBuilder result = new StringBuilder(makeKey0(keyNames));
result.append(".{").append(auctionNo).append("}");
return result.toString();
}
protected String makeKey0(String... keyNames) {
Assert.notNull(keyNames, "[keyNames]");
StringBuilder result = new StringBuilder(KEY_PREFIX);
for (String keyName : keyNames) {
result.append(".").append(keyName);
}
return result.toString();
}
}
|
package com.onightperson.hearken.launchmode.singletask;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.onightperson.hearken.R;
import com.onightperson.hearken.base.BaseActivity;
/**
* Created by liubaozhu on 17/6/14.
*/
public class SingleTaskBActivity extends BaseActivity implements View.OnClickListener {
private Button mLaunchSingleTaskA;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_singletask_b_layout);
initViews();
}
private void initViews() {
mLaunchSingleTaskA = (Button) findViewById(R.id.launch_a_activity);
mLaunchSingleTaskA.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Intent intent = null;
if (v == mLaunchSingleTaskA) {
intent = new Intent(this, SingleTaskAActivity.class);
}
if (intent != null) {
startActivity(intent);
}
}
}
|
package com.example.weather.db;
import org.litepal.crud.DataSupport;
/**
* 存放城市的数据
* LitePal的每个实体类必须继承DataSupport
* Created by Administrator on 2018/10/14.
*/
public class City extends DataSupport {
private int id;
private String cityName;
private int cityCode;
private int privateId;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public int getCityCode() {
return cityCode;
}
public void setCityCode(int cityCode) {
this.cityCode = cityCode;
}
public int getPrivateId() {
return privateId;
}
public void setPrivateId(int privateId) {
this.privateId = privateId;
}
}
|
package pl.dkiszka.bank.services;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import pl.dkiszka.bank.models.User;
import pl.dkiszka.bank.repositories.UserRepository;
/**
* @author Dominik Kiszka {dominikk19}
* @project bank-application
* @date 25.04.2021
*/
@Service(value = "userService")
@RequiredArgsConstructor
public class UserService implements UserDetailsService {
private final UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return userRepository.findAllByUsername(username)
.map(this::convertToUserDetails)
.orElseThrow(() -> new UsernameNotFoundException("Incorrect Username / Password supplied!"));
}
private UserDetails convertToUserDetails(User user) {
var account = user.getAccount();
return org.springframework.security.core.userdetails.User
.withUsername(account.getUsername())
.password(account.getPassword())
.authorities(account.getRoles())
.accountExpired(false)
.accountLocked(false)
.credentialsExpired(false)
.disabled(false)
.build();
}
}
|
package com.allmsi.plugin.file.dao;
import java.util.List;
import java.util.Map;
import com.allmsi.plugin.file.model.FilePo;
public interface FileMapper {
int deleteByPrimaryKey(String id);
int insert(FilePo record);
FilePo selectByPrimaryKey(String id);
List<FilePo> selectByMD5(Map<String, Object> map);
int update(FilePo file);
int deleteFlag(String id);
List<FilePo> selectByIds(List<String> reseourcesId);
} |
import info.gridworld.actor.Actor;
import info.gridworld.actor.ActorWorld;
import info.gridworld.actor.Rock;
import info.gridworld.grid.Grid;
import info.gridworld.grid.BoundedGrid;
import info.gridworld.grid.Location;
import info.gridworld.grid.AbstractGrid;
import java.util.ArrayList;
/**
* Game of Life starter code. Demonstrates how to create and populate the game using the GridWorld framework.
* Also demonstrates how to provide accessor methods to make the class testable by unit tests.
*
* @author @gcschmit
* @version 18 July 2014
*/
public class GameOfLife
{
// the world comprised of the grid that displays the graphics for the game
private ActorWorld world;
// the game board will have 5 rows and 5 columns
private final int ROWS = 50;
private final int COLS = 50;
/**
* Default constructor for objects of class GameOfLife
*
* @post the game will be initialized and populated with the initial state of cells
*
*/
public GameOfLife()
{
// create the grid, of the specified size, that contains Actors
BoundedGrid<Actor> grid = new BoundedGrid<Actor>(ROWS, COLS);
// create a world based on the grid
world = new ActorWorld(grid);
// populate the game
populateGame();
// display the newly constructed and populated world
world.show();
}
/**
* Creates the actors and inserts them into their initial starting positions in the grid
*
* @pre the grid has been created
* @post all actors that comprise the initial state of the game have been added to the grid
*
*/
public void populateGame()
{
// constants for the location of the three cells initially alive
// the grid of Actors that maintains the state of the game
// (alive cells contains actors; dead cells do not)
Grid<Actor> grid = world.getGrid();
// create and add rocks (a type of Actor) to the three intial locations
//***********ROW 21****************
Rock rock21_20 = new Rock();
Location loc21_20 = new Location(21,20);
grid.put(loc21_20,rock21_20);
Rock rock21_21 = new Rock();
Location loc21_21 = new Location(21,21);
grid.put(loc21_21,rock21_21);
Rock rock21_22 = new Rock();
Location loc21_22 = new Location(21,22);
grid.put(loc21_22,rock21_22);
Rock rock21_23 = new Rock();
Location loc21_23 = new Location(21,23);
grid.put(loc21_23,rock21_23);
Rock rock21_24 = new Rock();
Location loc21_24 = new Location(21,24);
grid.put(loc21_24,rock21_24);
Rock rock21_25 = new Rock();
Location loc21_25 = new Location(21,25);
grid.put(loc21_25,rock21_25);
Rock rock21_26 = new Rock();
Location loc21_26 = new Location(21,26);
grid.put(loc21_26,rock21_26);
Rock rock21_27 = new Rock();
Location loc21_27 = new Location(21,27);
grid.put(loc21_27,rock21_27);
Rock rock21_28 = new Rock();
Location loc21_28 = new Location(21,28);
grid.put(loc21_28,rock21_28);
Rock rock21_29 = new Rock();
Location loc21_29 = new Location(21,29);
grid.put(loc21_29,rock21_29);
//***********Row 23*********
Rock rock3_2 = new Rock();
Location loc3_2 = new Location(23, 22);
grid.put(loc3_2, rock3_2);
Rock rock3_3 = new Rock();
Location loc3_3 = new Location(23, 23);
grid.put(loc3_3, rock3_3);
Rock rock3_4 = new Rock();
Location loc3_4 = new Location(23, 24);
grid.put(loc3_4, rock3_4);
Rock rock3_5 = new Rock();
Location loc3_5 = new Location(23, 25);
grid.put(loc3_5, rock3_5);
Rock rock3_6 = new Rock();
Location loc3_6 = new Location(23, 26);
grid.put(loc3_6, rock3_6);
Rock rock3_7 = new Rock();
Location loc3_7 = new Location(23, 27);
grid.put(loc3_7, rock3_7);
//*******************ROW 24*******************************
Rock rock4_2 = new Rock();
Location loc4_2 = new Location(24, 22);
grid.put(loc4_2, rock4_2);
Rock rock4_3 = new Rock();
Location loc4_3 = new Location(24, 23);
grid.put(loc4_3, rock4_3);
Rock rock4_6 = new Rock();
Location loc4_6 = new Location(24, 26);
grid.put(loc4_6, rock4_6);
Rock rock4_7 = new Rock();
Location loc4_7 = new Location(24, 27);
grid.put(loc4_7, rock4_7);
//**********************COL 19********************
Rock rock21_19 = new Rock();
Location loc21_19 = new Location(21,19);
grid.put(loc21_19,rock21_19);
Rock rock22_19 = new Rock();
Location loc22_19 = new Location(22,19);
grid.put(loc22_19,rock22_19);
Rock rock23_19 = new Rock();
Location loc23_19 = new Location(23,19);
grid.put(loc23_19,rock23_19);
Rock rock24_19 = new Rock();
Location loc24_19 = new Location(24,19);
grid.put(loc24_19,rock24_19);
Rock rock25_19 = new Rock();
Location loc25_19 = new Location(25,19);
grid.put(loc25_19,rock25_19);
Rock rock26_19 = new Rock();
Location loc26_19 = new Location(26,19);
grid.put(loc26_19,rock26_19);
Rock rock27_19 = new Rock();
Location loc27_19 = new Location(27,19);
grid.put(loc27_19,rock27_19);
Rock rock28_19 = new Rock();
Location loc28_19 = new Location(28,19);
grid.put(loc28_19,rock28_19);
Rock rock29_19 = new Rock();
Location loc29_19 = new Location(29,19);
grid.put(loc29_19,rock29_19);
//*********************COL 30***************
Rock rock21_30 = new Rock();
Location loc21_30 = new Location(21,30);
grid.put(loc21_30,rock21_30);
Rock rock22_30 = new Rock();
Location loc22_30 = new Location(22,30);
grid.put(loc22_30,rock22_30);
Rock rock23_30 = new Rock();
Location loc23_30 = new Location(23,30);
grid.put(loc23_30,rock23_30);
Rock rock24_30 = new Rock();
Location loc24_30 = new Location(24,30);
grid.put(loc24_30,rock24_30);
Rock rock25_30 = new Rock();
Location loc25_30 = new Location(25,30);
grid.put(loc25_30,rock25_30);
Rock rock26_30 = new Rock();
Location loc26_30 = new Location(26,30);
grid.put(loc26_30,rock26_30);
Rock rock27_30 = new Rock();
Location loc27_30 = new Location(27,30);
grid.put(loc27_30,rock27_30);
Rock rock28_30 = new Rock();
Location loc28_30 = new Location(28,30);
grid.put(loc28_30,rock28_30);
Rock rock29_30 = new Rock();
Location loc29_30 = new Location(29,30);
grid.put(loc29_30,rock29_30);
//*****************ROW 25************************************
Rock rock5_1 = new Rock();
Location loc5_1 = new Location(25, 21);
grid.put(loc5_1, rock5_1);
Rock rock5_8 = new Rock();
Location loc5_8 = new Location(25, 28);
grid.put(loc5_8, rock5_1);
//******************ROW 26*********************************
Rock rock6_2 = new Rock();
Location loc6_2 = new Location(26, 22);
grid.put(loc6_2, rock6_2);
Rock rock6_3 = new Rock();
Location loc6_3 = new Location(26, 23);
grid.put(loc6_3, rock6_3);
Rock rock6_6 = new Rock();
Location loc6_6 = new Location(26, 26);
grid.put(loc6_6, rock6_6);
Rock rock6_7 = new Rock();
Location loc6_7 = new Location(26, 27);
grid.put(loc6_7, rock6_7);
//************************ROW 27***************************
Rock rock7_2 = new Rock();
Location loc7_2 = new Location(27, 22);
grid.put(loc7_2, rock7_2);
Rock rock7_3 = new Rock();
Location loc7_3 = new Location(27, 23);
grid.put(loc7_3, rock7_3);
Rock rock7_4 = new Rock();
Location loc7_4 = new Location(27, 24);
grid.put(loc7_4, rock7_4);
Rock rock7_5 = new Rock();
Location loc7_5 = new Location(27, 25);
grid.put(loc7_5, rock7_5);
Rock rock7_6 = new Rock();
Location loc7_6 = new Location(27, 26);
grid.put(loc7_6, rock7_6);
Rock rock7_7 = new Rock();
Location loc7_7 = new Location(27, 27);
grid.put(loc7_7, rock7_7);
//*****************ROW 30*******************
Rock rock30_20 = new Rock();
Location loc30_20 = new Location(30,20);
grid.put(loc30_20,rock30_20);
Rock rock30_21 = new Rock();
Location loc30_21 = new Location(30,21);
grid.put(loc30_21,rock30_21);
Rock rock30_22 = new Rock();
Location loc30_22 = new Location(30,22);
grid.put(loc30_22,rock30_22);
Rock rock30_23 = new Rock();
Location loc30_23 = new Location(30,23);
grid.put(loc30_23,rock30_23);
Rock rock30_24 = new Rock();
Location loc30_24 = new Location(30,24);
grid.put(loc30_24,rock30_24);
Rock rock30_25 = new Rock();
Location loc30_25 = new Location(30,25);
grid.put(loc30_25,rock30_25);
Rock rock30_26 = new Rock();
Location loc30_26 = new Location(30,26);
grid.put(loc30_26,rock30_26);
Rock rock30_27 = new Rock();
Location loc30_27 = new Location(30,27);
grid.put(loc30_27,rock30_27);
Rock rock30_28 = new Rock();
Location loc30_28 = new Location(30,28);
grid.put(loc30_28,rock30_28);
Rock rock30_29 = new Rock();
Location loc30_29 = new Location(30,29);
grid.put(loc30_29,rock30_29);
}
/**
* Generates the next generation based on the rules of the Game of Life and updates the grid
* associated with the world
*
* @pre the game has been initialized
* @post the world has been populated with a new grid containing the next generation
*
*/
public void createNextGeneration()
{
/** You will need to read the documentation for the World, Grid, and Location classes
* in order to implement the Game of Life algorithm and leverage the GridWorld framework.
*/
// create the grid, of the specified size, that contains Actors
Grid<Actor> grid = world.getGrid();
BoundedGrid<Actor> newGrid = new BoundedGrid<Actor>(this.ROWS, this.COLS);
world.setGrid(newGrid);
for (int row = 0; row < ROWS - 1; row++)
{
for (int col = 0; col < COLS - 1; col++)
{
Location loc = new Location(row, col);
ArrayList num = grid.getOccupiedAdjacentLocations(loc);
if ((num.size() < 2) && (grid.get(loc) != null))
{
newGrid.remove(loc);
}
else if ((num.size() < 4) && (grid.get(loc) != null))
{
Rock rock = new Rock();
newGrid.put(loc, rock);
}
else if ((num.size() > 3) && (grid.get(loc) != null))
{
newGrid.remove(loc);
}
else if ((num.size() == 3) && (grid.get(loc) == null))
{
Rock rock = new Rock();
newGrid.put(loc, rock);
}
world.show();
}
}
}
/**
* Returns the actor at the specified row and column. Intended to be used for unit testing.
*
* @param row the row (zero-based index) of the actor to return
* @param col the column (zero-based index) of the actor to return
* @pre the grid has been created
* @return the actor at the specified row and column
*/
public Actor getActor(int row, int col)
{
Location loc = new Location(row, col);
Actor actor = world.getGrid().get(loc);
return actor;
}
/**
* Returns the number of rows in the game board
*
* @return the number of rows in the game board
*/
public int getNumRows()
{
return ROWS;
}
/**
* Returns the number of columns in the game board
*
* @return the number of columns in the game board
*/
public int getNumCols()
{
return COLS;
}
/**
* Creates an instance of this class. Provides convenient execution.
*
*/
public static void main(String[] args)throws InterruptedException
{
GameOfLife game = new GameOfLife();
for(int i = 0;i < 101;i++)
{
game.createNextGeneration();
if(i == 44)
{
System.out.println("This robot is cool, So as the maker of the grid I will let him last longer!!");
Thread.sleep(4700);
}
Thread.sleep(300);
}
}
}
|
package HakerRank.MergeSortCountingInversions;
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
// Complete the countInversions function below.
// 2
// 5
// 1 1 1 2 2
// 5
// 2 1 3 1 2
//out
// 0
// 4
static long countInversions(int[] arr) {
long result = 0;
result = mergeSort(arr, 0, arr.length -1);
return result;
}
private static long mergeSort(int[] arr,int startIdx, int endIdx) {
if(startIdx == endIdx) {
return 0;
}
int middle = (startIdx + endIdx) /2;
//왼쪽
long elapsedCount1 = mergeSort(arr, startIdx, middle);
//오른쪽
long elapsedCount2 = mergeSort(arr, middle+1, endIdx);
//합쳐서 정렬
long elapsedCount3 = mergeAndCount(arr, startIdx, endIdx, middle);
return elapsedCount1 + elapsedCount2 + elapsedCount3;
}
private static long mergeAndCount(int[] arr, int startIdx, int endIdx, int middle) {
int[] tmpArr = new int[endIdx - startIdx + 1 ];
long count = 0;
int left = startIdx;
int right = middle + 1;
int curIdx = 0;
while(left < middle +1 && right < endIdx + 1 ) {
if(arr[left] > arr[right]) {
tmpArr[curIdx++] = arr[right++];
count += middle - left + 1;
} else {
tmpArr[curIdx++] = arr[left++];
}
}
while(left < middle + 1) {
tmpArr[curIdx++] = arr[left++];
}
while(right < endIdx + 1) {
tmpArr[curIdx++] = arr[right++];
}
System.arraycopy(tmpArr, 0, arr, startIdx, endIdx - startIdx + 1);
// for(int i = startIdx; i < endIdx+1; i++) {
// arr[i] = tmpArr[i];
// }
return count;
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
// BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int t = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int tItr = 0; tItr < t; tItr++) {
int n = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
int[] arr = new int[n];
String[] arrItems = scanner.nextLine().split(" ");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int i = 0; i < n; i++) {
int arrItem = Integer.parseInt(arrItems[i]);
arr[i] = arrItem;
}
long result = countInversions(arr);
System.out.println(result);
// bufferedWriter.write(String.valueOf(result));
// bufferedWriter.newLine();
}
// bufferedWriter.close();
scanner.close();
}
} |
package kinshik.hadoop.demo;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
public class Launcher {
public static void main(String[] args) throws Exception {
if (args.length < 2) {
throw new IllegalArgumentException("Required 2 arguments: IN and OUT!");
}
Path hdfsFile = new Path(args[0]);
Path hdfsFile2 = new Path(args[1]);
Configuration conf = new Configuration();
// conf.set("textinputformat.record.delimiter","]");
Job job = Job.getInstance(conf);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(LongWritable.class);
job.setOutputKeyClass(NullWritable.class);
job.setOutputValueClass(Text.class);
job.setMapperClass(MyMapper.class);
job.setReducerClass(MyReducer.class);
job.setInputFormatClass(TextInputFormat.class);
job.setOutputFormatClass(TextOutputFormat.class);
FileInputFormat.setInputPaths(job, hdfsFile);
FileOutputFormat.setOutputPath(job, hdfsFile2);
job.setJarByClass(Launcher.class);
job.setJobName("Word count");
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
} |
package com.abd.rest.restsecurity.repositories;
import com.abd.rest.restsecurity.model.Role;
import org.springframework.data.repository.CrudRepository;
public interface RoleRepository extends CrudRepository<Role, Long> {
Role findByRole(String role);
}
|
package cartas;
import excepciones.TengoTodasLasPartesDeExodiaException;
import juego.RecolectorDePartesDeExodia;
public class CabezaExodia extends Exodia {
public CabezaExodia() {
super();
this.puntosDeAtaque = new Puntos(1000);
this.puntosDeDefensa = new Puntos(1000);
this.nivel = 3;
this.nombre = "Exodia - Cabeza";
this.colocarImagenEnCartaDesdeArchivoDeRuta("resources/images/carta_CabezaExodia.png");
}
@Override
public void serRecolectadaPorElRecolectorDePartesDeExodia(RecolectorDePartesDeExodia recolectorDePartesDeExodia) throws TengoTodasLasPartesDeExodiaException {
recolectorDePartesDeExodia.recolectarCabeza(this);
}
}
|
package ir.sadeghzadeh.mozhdeh.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import ir.sadeghzadeh.mozhdeh.R;
import ir.sadeghzadeh.mozhdeh.dialog.OnOneItemSelectedInDialog;
import ir.sadeghzadeh.mozhdeh.entity.KeyValuePair;
/**
* Created by reza on 11/11/16.
*/
public class KeyValuePairsAdapter extends ArrayAdapter<KeyValuePair> {
List<KeyValuePair> items;
LayoutInflater layoutInflater;
OnOneItemSelectedInDialog callback;
List<KeyValuePair> selected = new ArrayList<>();
boolean selectMultiple;
public KeyValuePairsAdapter(Context context, int resource, List<KeyValuePair> items, boolean selectMultiple, OnOneItemSelectedInDialog callback) {
super(context, resource, items);
this.items = items;
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.callback = callback;
this.selectMultiple = selectMultiple;
}
public int getCount() {
if (items == null) {
return 0;
}
return items.size();
}
public KeyValuePair getItem(int index) {
return items.get(index);
}
public View getView(int position, View paramView, ViewGroup paramViewGroup) {
Holder holder = new Holder();
KeyValuePair item = items.get(position);
View rowView;
if( paramView == null){
//TODO if selectMultipe is the view should be check box else radiobox
rowView= layoutInflater.inflate(R.layout.key_value_pair_row_item, null);
}else {
rowView = paramView;
}
holder.value= (TextView) rowView.findViewById(R.id.value);
rowView.setTag(item.key+ "," + item.value);
//set values
holder.value.setText(item.value);
holder.checkbox = (CheckBox) rowView.findViewById(R.id.checkbox);
holder.checkbox.setTag(item.key+ "," + item.value);
if(selected.contains(item)){
holder.checkbox.setChecked(true);
} else {
holder.checkbox.setChecked(false);
}
/* for (KeyValuePair selectedRow : selected) {
if (selectedRow.key.equals(item.key)) {
holder.checkbox.setChecked(true);
} else {
holder.checkbox.setChecked(false);
}
}*/
holder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton checkbox, boolean isChecked) {
String[] rowValues = checkbox.getTag().toString().split(",");
if(isChecked){
selected.add(new KeyValuePair(rowValues[0],rowValues[1]));
checkbox.setChecked(true);
}else {
for(int i=0;i< selected.size();i++){
if(selected.get(i).key.equals(rowValues[0])){
selected.remove(i);
checkbox.setChecked(false);
break;
}
}
}
callback.onItemSelected(selected);
}
});
return rowView;
}
public class Holder {
TextView value;
CheckBox checkbox;
public Holder() {
}
}
}
|
package heylichen.alg.graph.tasks;
import heylichen.alg.graph.structure.Graph;
import heylichen.test.AppTestContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
@Slf4j
public class DfsCCTest extends AppTestContext {
@Autowired
private Graph tinyUndirectedGraph;
@Autowired
private Graph mediumUndirectedGraph;
@Test
public void testCC() {
testCC(tinyUndirectedGraph);
}
@Test
public void testDisplay() {
CC cc = new DfsCC(mediumUndirectedGraph);
display(cc, mediumUndirectedGraph);
}
private void testCC(Graph graph) {
CC cc = new DfsCC(graph);
Assert.assertEquals("there are 3 connected components", 3, cc.getComponentsCount());
Assert.assertTrue(cc.connected(1, 4));
Assert.assertTrue(cc.connected(7, 8));
Assert.assertTrue(cc.connected(9, 12));
Assert.assertFalse(cc.connected(9, 1));
}
private void display(CC cc, Graph graph) {
List<List<Integer>> ll = new ArrayList<>(cc.getComponentsCount());
for (int i = 0; i < cc.getComponentsCount(); i++) {
ll.add(new LinkedList<>());
}
for (int i = 0; i < graph.getVertexCount(); i++) {
int componentId = cc.getComponentId(i);
ll.get(componentId).add(i);
}
log.info("{} connected components", ll.size());
for (int i = 0; i < ll.size(); i++) {
log.info("componentId={} : {}", i, StringUtils.join(ll.get(i)));
}
}
} |
/*
* Copyright (c) 2015 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.webui.forms.reg;
import pl.edu.icm.unity.exceptions.IllegalFormContentsException;
import pl.edu.icm.unity.exceptions.WrongArgumentException;
import pl.edu.icm.unity.server.api.AttributesManagement;
import pl.edu.icm.unity.server.api.AuthenticationManagement;
import pl.edu.icm.unity.server.api.GroupsManagement;
import pl.edu.icm.unity.server.api.RegistrationsManagement;
import pl.edu.icm.unity.server.api.internal.IdPLoginController;
import pl.edu.icm.unity.server.authn.remote.RemotelyAuthenticatedContext;
import pl.edu.icm.unity.server.utils.UnityMessageSource;
import pl.edu.icm.unity.server.utils.UnityServerConfiguration;
import pl.edu.icm.unity.types.registration.RegistrationContext;
import pl.edu.icm.unity.types.registration.RegistrationContext.TriggeringMode;
import pl.edu.icm.unity.types.registration.RegistrationForm;
import pl.edu.icm.unity.types.registration.RegistrationRequest;
import pl.edu.icm.unity.webui.authn.LocaleChoiceComponent;
import pl.edu.icm.unity.webui.common.ConfirmationComponent;
import pl.edu.icm.unity.webui.common.ErrorComponent;
import pl.edu.icm.unity.webui.common.Images;
import pl.edu.icm.unity.webui.common.NotificationPopup;
import pl.edu.icm.unity.webui.common.Styles;
import pl.edu.icm.unity.webui.common.attributes.AttributeHandlerRegistry;
import pl.edu.icm.unity.webui.common.credentials.CredentialEditorRegistry;
import pl.edu.icm.unity.webui.common.identities.IdentityEditorRegistry;
import pl.edu.icm.unity.webui.forms.PostFormFillingHandler;
import pl.edu.icm.unity.webui.forms.reg.RequestEditorCreator.RequestEditorCreatedCallback;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent;
import com.vaadin.server.Resource;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.VerticalLayout;
/**
* Used to display a standalone (not within a dialog) registration form.
*
* @author K. Benedyczak
*/
public class StandaloneRegistrationView extends CustomComponent implements View
{
private RegistrationForm form;
private RegistrationsManagement regMan;
private IdentityEditorRegistry identityEditorRegistry;
private CredentialEditorRegistry credentialEditorRegistry;
private AttributeHandlerRegistry attributeHandlerRegistry;
private AttributesManagement attrsMan;
private AuthenticationManagement authnMan;
private GroupsManagement groupsMan;
private UnityMessageSource msg;
private UnityServerConfiguration cfg;
private IdPLoginController idpLoginController;
private VerticalLayout main;
public StandaloneRegistrationView(RegistrationForm form, UnityMessageSource msg,
RegistrationsManagement regMan,
IdentityEditorRegistry identityEditorRegistry,
CredentialEditorRegistry credentialEditorRegistry,
AttributeHandlerRegistry attributeHandlerRegistry,
AttributesManagement attrsMan,
AuthenticationManagement authnMan,
GroupsManagement groupsMan,
UnityServerConfiguration cfg, IdPLoginController idpLoginController)
{
this.form = form;
this.msg = msg;
this.regMan = regMan;
this.identityEditorRegistry = identityEditorRegistry;
this.credentialEditorRegistry = credentialEditorRegistry;
this.attributeHandlerRegistry = attributeHandlerRegistry;
this.attrsMan = attrsMan;
this.authnMan = authnMan;
this.groupsMan = groupsMan;
this.cfg = cfg;
this.idpLoginController = idpLoginController;
}
@Override
public void enter(ViewChangeEvent changeEvent)
{
initUIBase();
RequestEditorCreator editorCreator = new RequestEditorCreator(msg, form,
RemotelyAuthenticatedContext.getLocalContext(),
identityEditorRegistry, credentialEditorRegistry, attributeHandlerRegistry,
regMan, attrsMan, groupsMan, authnMan);
editorCreator.invoke(new RequestEditorCreatedCallback()
{
@Override
public void onCreationError(Exception e)
{
handleError(e);
}
@Override
public void onCreated(RegistrationRequestEditor editor)
{
editorCreated(editor);
}
@Override
public void onCancel()
{
//nop
}
});
}
private void initUIBase()
{
main = new VerticalLayout();
main.setMargin(true);
main.setSpacing(true);
addStyleName("u-standalone-public-form");
setCompositionRoot(main);
setWidth(100, Unit.PERCENTAGE);
}
private void editorCreated(RegistrationRequestEditor editor)
{
LocaleChoiceComponent localeChoice = new LocaleChoiceComponent(cfg, msg);
main.addComponent(localeChoice);
main.setComponentAlignment(localeChoice, Alignment.TOP_RIGHT);
main.addComponent(editor);
editor.setWidth(100, Unit.PERCENTAGE);
main.setComponentAlignment(editor, Alignment.MIDDLE_CENTER);
HorizontalLayout buttons = new HorizontalLayout();
Button ok = new Button(msg.getMessage("RegistrationRequestEditorDialog.submitRequest"));
ok.addStyleName(Styles.vButtonPrimary.toString());
ok.addClickListener(event -> {
accept(editor);
});
Button cancel = new Button(msg.getMessage("cancel"));
cancel.addClickListener(event -> {
RegistrationContext context = new RegistrationContext(false,
idpLoginController.isLoginInProgress(),
TriggeringMode.manualStandalone);
new PostFormFillingHandler(idpLoginController, form, msg, regMan.getProfileInstance(form))
.cancelled(true, context);
showConfirm(Images.error32.getResource(),
msg.getMessage("StandalonePublicFormView.requestCancelled"));
});
buttons.addComponents(cancel, ok);
buttons.setSpacing(true);
main.addComponent(buttons);
main.setComponentAlignment(buttons, Alignment.MIDDLE_CENTER);
}
private void handleError(Exception e)
{
if (e instanceof IllegalArgumentException)
{
ErrorComponent ec = new ErrorComponent();
ec.setError(e.getMessage());
setCompositionRoot(ec);
} else
{
ErrorComponent ec = new ErrorComponent();
ec.setError("Can not open registration editor", e);
setCompositionRoot(ec);
}
}
private void accept(RegistrationRequestEditor editor)
{
RegistrationContext context = new RegistrationContext(true,
idpLoginController.isLoginInProgress(),
TriggeringMode.manualStandalone);
RegistrationRequest request;
try
{
request = editor.getRequest();
} catch (Exception e)
{
NotificationPopup.showError(msg, msg.getMessage("Generic.formError"), e);
return;
}
try
{
String requestId = regMan.submitRegistrationRequest(request, context);
new PostFormFillingHandler(idpLoginController, form, msg, regMan.getProfileInstance(form))
.submittedRegistrationRequest(requestId, regMan, request, context);
showConfirm(Images.ok32.getResource(),
msg.getMessage("StandalonePublicFormView.requestSubmitted"));
} catch (WrongArgumentException e)
{
if (e instanceof IllegalFormContentsException)
editor.markErrorsFromException((IllegalFormContentsException) e);
NotificationPopup.showError(msg, msg.getMessage("Generic.formError"), e);
return;
} catch (Exception e)
{
new PostFormFillingHandler(idpLoginController, form, msg, regMan.getProfileInstance(form))
.submissionError(e, context);
showConfirm(Images.error32.getResource(),
msg.getMessage("StandalonePublicFormView.submissionFailed"));
}
}
private void showConfirm(Resource icon, String message)
{
VerticalLayout wrapper = new VerticalLayout();
ConfirmationComponent confirmation = new ConfirmationComponent(icon, message);
wrapper.addComponent(confirmation);
wrapper.setComponentAlignment(confirmation, Alignment.MIDDLE_CENTER);
wrapper.setSizeFull();
setSizeFull();
setCompositionRoot(wrapper);
}
}
|
package gameBoard;
public class Difficult extends Board {
private Difficult(int h, int w) {
super(h, w);
createFinalMaze(1, 1, 1);
// TODO Auto-generated constructor stub
}
private static Board instance = new Difficult(70,70);
public static Board getInstance(){
return instance;
}
}
|
package com.esum.web.ims.smail.vo;
/**
* table: SMAIL_OUT_PARTNER_INFO
*
* Copyright(c) eSum Technologies., Inc. All rights reserved.
*/
public class SmailOutPartnerInfo {
// primary key
private String smailPartnerId;
// fields
private String useOutbound;
private String partnerMail;
private String partnerTpId;
private String contentType;
private String regDate; // "yyyyMMddHHmmss"
private String modDate; // "yyyyMMddHHmmss"
public String getSmailPartnerId() {
return smailPartnerId;
}
public void setSmailPartnerId(String smailPartnerId) {
this.smailPartnerId = smailPartnerId;
}
public String getPartnerMail() {
return partnerMail;
}
public void setPartnerMail(String partnerMail) {
this.partnerMail = partnerMail;
}
public String getUseOutbound() {
return useOutbound;
}
public void setUseOutbound(String useOutbound) {
this.useOutbound = useOutbound;
}
public String getPartnerTpId() {
return partnerTpId;
}
public void setPartnerTpId(String partnerTpId) {
this.partnerTpId = partnerTpId;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public String getRegDate() {
return regDate;
}
public void setRegDate(String regDate) {
this.regDate = regDate;
}
public String getModDate() {
return modDate;
}
public void setModDate(String modDate) {
this.modDate = modDate;
}
}
|
package com.test;
import java.util.PriorityQueue;
import com.test.base.Solution;
public class SolutionA implements Solution{
public int nthUglyNumber(int n) {
if (n == 1) {
return 1;
}
PriorityQueue<Long> queue = new PriorityQueue<Long>(n * 2);
queue.add((long) 2);
queue.add((long) 3);
queue.add((long) 5);
long last = 1;
for (int i = 1; i < n; i++) {
long value = queue.poll();
// 重复的值
while (last == value) {
value = queue.poll();
}
last = value;
queue.add(last * 2);
queue.add(last * 3);
queue.add(last * 5);
}
return (int)last;
}
}
|
package com.riversoft.weixin.mp.event.card;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlCData;
import com.riversoft.weixin.common.event.EventRequest;
public class UserConsumeCardEvent extends EventRequest {
@JsonProperty("CardId")
@JacksonXmlCData
private String cardId;
@JsonProperty("UserCardCode")
@JacksonXmlCData
private String userCardCode;
@JsonProperty("ConsumeSource")
@JacksonXmlCData
private String consumeSource;
@JsonProperty("LocationName")
@JacksonXmlCData
private String locationName;
@JsonProperty("StaffOpenId")
@JacksonXmlCData
private String staffOpenId;
@JsonProperty("OuterStr")
@JacksonXmlCData
private String outerStr;
@JsonProperty("VerifyCode")
@JacksonXmlCData
private String verifyCode;
@JsonProperty("RemarkAmount")
@JacksonXmlCData
private String remarkAmount;
public String getCardId() {
return cardId;
}
public void setCardId(String cardId) {
this.cardId = cardId;
}
public String getUserCardCode() {
return userCardCode;
}
public void setUserCardCode(String userCardCode) {
this.userCardCode = userCardCode;
}
public String getOuterStr() {
return outerStr;
}
public void setOuterStr(String outerStr) {
this.outerStr = outerStr;
}
public String getConsumeSource() {
return consumeSource;
}
public void setConsumeSource(String consumeSource) {
this.consumeSource = consumeSource;
}
public String getLocationName() {
return locationName;
}
public void setLocationName(String locationName) {
this.locationName = locationName;
}
public String getStaffOpenId() {
return staffOpenId;
}
public void setStaffOpenId(String staffOpenId) {
this.staffOpenId = staffOpenId;
}
public String getVerifyCode() {
return verifyCode;
}
public void setVerifyCode(String verifyCode) {
this.verifyCode = verifyCode;
}
public String getRemarkAmount() {
return remarkAmount;
}
public void setRemarkAmount(String remarkAmount) {
this.remarkAmount = remarkAmount;
}
}
|
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import com.itextpdf.text.DocumentException;
import xml.Dias;
import xml.Escala;
import xml.Mes;
public class EscalaOrganista {
private static final String RESOURCES_DIR = "organistas//src//main//resources//";
private static final String OUTPUT_DIR = "organistas//src//main//resources//output//";
private static final String SEGUNDA = "-2";
private static final String QUINTA = "-5";
private static final String DOMINGO = "-D";
public static void main(String[] args){
String nomeEscala = "Escala de Organistas";
int qntMes = 4;
List<String> namesSeq1 = Arrays.asList("Cecilia", "Daniela", "Any", "Camila", "Ester", "Cibele", "Maria","Cristiane", "Fernanda", "Jessica");
List<String> namesSeq2 = Arrays.asList("Daniela", "Any", "Cecilia", "Ester", "Cibele", "Camila", "Maria","Cristiane", "Fernanda", "Jessica");
List<String> namesSeq3 = Arrays.asList("Any", "Cecilia", "Daniela", "Cibele", "Camila", "Ester", "Cristiane", "Fernanda", "Jessica");
List<String> nomes = joinNames(namesSeq1, namesSeq2, namesSeq3);
Class[] classes = {Escala.class, Mes.class, Dias.class};
String xml = Utils.generateXml(getEscala(nomeEscala, nomes, qntMes), classes);
String xsl = RESOURCES_DIR+ "template.xsl";
ByteArrayOutputStream btOs = PdfGeneration.generatePDF(xml, xsl);
String fundo = RESOURCES_DIR+ "fundo.pdf";
String destPDF = OUTPUT_DIR + "newMergedDest.pdf";
try {
ApplyTemplate.apply(btOs, fundo, destPDF);
} catch (IOException | DocumentException e) {
e.printStackTrace();
}
}
private static List<String> joinNames(List<String> namesSeq1, List<String> namesSeq2, List<String> namesSeq3) {
List<String> nomes = new ArrayList<>();
for (int i = 0; i <= 3; i++ ){
nomes.addAll(namesSeq1);
nomes.addAll(namesSeq2);
nomes.addAll(namesSeq3);
}
return nomes;
}
private static Escala getEscala(String nomeEscala, List<String> names, int qntMes) {
int year = Calendar.getInstance().get(Calendar.YEAR);
int month = Calendar.getInstance().get(Calendar.MONTH) + 1;
Calendar cal = new GregorianCalendar(year, month, 1);
Nomes nomes = new Nomes(names);
Escala escala = new Escala();
escala.setNome(nomeEscala);
for (int i = 1; i <= qntMes; i++) {
Mes mes = new Mes();
Locale ptBR = new Locale("pt","br");
mes.setNomeMes(cal.getDisplayName(Calendar.MONTH, Calendar.SHORT, ptBR).toUpperCase() + " / " + (year % 2000));
Dias dias = new Dias();
setDays(month, cal, nomes, dias);
mes.addDias(dias);
escala.addMes(mes);
month++;
}
return escala;
}
private static void setDays(int month, Calendar cal, Nomes nomes, Dias dias) {
do {
// get the day of the week for the current day
// check if it is a Saturday or Sunday
isDay(cal, nomes, dias, Calendar.MONDAY, SEGUNDA);
isDay(cal, nomes, dias, Calendar.THURSDAY, QUINTA);
isDay(cal, nomes, dias, Calendar.SUNDAY, DOMINGO);
// advance to the next day
cal.add(Calendar.DAY_OF_YEAR, 1);
} while (cal.get(Calendar.MONTH) == month);
}
private static void isDay(Calendar cal, Nomes nomes, Dias dias, int dayOfWeek, String refDayOfWeek) {
int day = cal.get(Calendar.DAY_OF_WEEK);
if (day == dayOfWeek) {
// print the day - but you could add them to a list or whatever
String dayOfMonth = String.valueOf(cal.get(Calendar.DAY_OF_MONTH));
dias.joinDiaEscalada(dayOfMonth + refDayOfWeek, nomes.getNames().get(nomes.getSequencia()));
if (nomes.getSequencia() == nomes.getNames().size() - 1) {
nomes.setSequencia(0);
} else {
nomes.setSequencia(nomes.getSequencia() + 1);
}
}
}
public static String getField(String str, String regex, int field){
List<String> list = Arrays.asList(str.split(regex));
return list.get(field);
}
}
|
package Project;
import java.util.*;
import java.io.*;
public class Admin extends User implements Function {
//default constructor
public Admin() {
super();
}
//constructor
public Admin(String un, String pw, String fn, String ln) {
super(un, pw, fn, ln);
}
//Print all courses
public void printAllCourse(ArrayList<Course> AC) {
for(Course c:AC)
System.out.println(c);
}
//Print all courses that are full
public void printMatchCourse(ArrayList<Course> AC) {
for(Course c:AC) {
if (c.ifFull())
System.out.println(c);
}
}
//Write a file for the list of courses that are Full
public void writeFullCourse(ArrayList<Course> AC) {
String fileName = "CoursesFull.txt";
try{
FileWriter fileWriter = new FileWriter(fileName);
BufferedWriter bw = new BufferedWriter(fileWriter);
for(Course c:AC) {
if (c.ifFull()) {
bw.write(c.toString());
bw.newLine();
}
}
bw.close();
}
catch (IOException exk) {
System.out.println( "Error writing file '" + fileName + "'");
exk.printStackTrace();
}
}
//Print names of students in a course
public void printStudentInCourse(ArrayList<Course> cList, String cID) {
boolean found = false;
Course selectC = new Course();
for(Course c:cList) {
if (cID.equals(c.getCID())) {
found = true;
selectC = c;
}
}
if (found) {
for(String rsName:selectC.getCRS())
System.out.println(rsName);
} else
System.out.println("Cannot find the course.");
}
//Print the list of courses a given student is being registered on
public void printAllCoursesOfStudent(ArrayList<Student> sList, String fName, String lName) {
boolean found = false;
Student selectS = new Student();
for(Student s:sList) {
if (fName.equals(s.getFN()) && lName.equals(s.getLN())) {
found = true;
selectS = s;
}
}
if (found) {
for(Course cInfo:selectS.getRC())
System.out.println(cInfo);
} else
System.out.println("Cannot find the Student.");
}
//sort
public void sortCourse(ArrayList<Course> cList) {
Collections.sort(cList);
}
}
|
package com.siciarek.fractals.line;
import com.siciarek.fractals.common.Drawable;
import com.siciarek.fractals.common.Fractal;
import com.siciarek.fractals.common.Utils;
public class KochCurve extends Fractal {
public KochCurve(Drawable canvas) {
super(canvas);
this.name = "Koch Curve";
this.x1 = 0f;
this.y1 = canvas.getHeight();
this.x2 = canvas.getWidth();
this.y2 = canvas.getHeight();
this.miny = canvas.getHeight();
this.setPosition(iterations - 1, x1, y1, x2, y2);
}
protected void setPosition(int iter, float sx, float sy, float ex, float ey) {
this.countPosition(iter, sx, sy, ex, ey);
this.y1 = (canvas.getHeight() + (canvas.getHeight() - this.miny)) * 0.5f;
this.y2 = this.y1;
}
protected void countPosition(int iter, float sx, float sy, float ex, float ey) {
if (iter > 0) {
float xoffset = (ex - sx) / 3.0f;
float yoffset = (ey - sy) / 3.0f;
float x1 = sx;
float y1 = sy;
float x2 = sx + xoffset;
float y2 = sy + yoffset;
float angle = (float) -Math.PI / 3;
float[] temp = Utils.rotatePoint(angle, x2, y2, ex - xoffset, ey - yoffset);
float x3 = temp[0];
float y3 = temp[1];
float x4 = ex - xoffset;
float y4 = ey - yoffset;
float x5 = ex;
float y5 = ey;
this.countPosition(iter - 1, x1, y1, x2, y2);
this.countPosition(iter - 1, x2, y2, x3, y3);
this.countPosition(iter - 1, x3, y3, x4, y4);
this.countPosition(iter - 1, x4, y4, x5, y5);
} else {
if(ey < this.miny) {
this.miny = ey;
}
}
}
protected void render(int iter, float sx, float sy, float ex, float ey) {
if (iter > 0) {
float xoffset = (ex - sx) / 3.0f;
float yoffset = (ey - sy) / 3.0f;
float x1 = sx;
float y1 = sy;
float x2 = sx + xoffset;
float y2 = sy + yoffset;
float angle = (float) -Math.PI / 3;
float[] temp = Utils.rotatePoint(angle, x2, y2, ex - xoffset, ey - yoffset);
float x3 = temp[0];
float y3 = temp[1];
float x4 = ex - xoffset;
float y4 = ey - yoffset;
float x5 = ex;
float y5 = ey;
render(iter - 1, x1, y1, x2, y2);
render(iter - 1, x2, y2, x3, y3);
render(iter - 1, x3, y3, x4, y4);
render(iter - 1, x4, y4, x5, y5);
} else {
canvas.lineTo(ex, ey);
}
}
}
|
package sockets;
import java.io.*;
/**
*
* @author kei98
*/
public class Servidor extends Conexion {
private DataInputStream in;
private BufferedReader input;
private DataOutputStream out;
private int num;
private int cantIntentos = 5;
private boolean acierto = false;
public Servidor() throws IOException {
super("servidor");
// Inicializa el servidor
try {
num = (int) (Math.random()*200) +1;
System.out.println("Servidor inicializado");
System.out.println("Esperando al cliente ...");
socketCliente = socketServer.accept();
System.out.println("Cliente aceptado");
System.out.println("El número es: " + num);
// Recibe los mensajes desde el cliente
in = new DataInputStream(
new BufferedInputStream(socketCliente.getInputStream()));
// Lee los mensajes del teclado
input = new BufferedReader(new InputStreamReader(System.in));
// Envía los mensajes al cliente
out = new DataOutputStream(socketCliente.getOutputStream());
out.writeUTF("Bienvenido. Adivina el número entre 1 y 200.\n Tienes 5 "
+ "intentos. Introduce un número para comenzar");
String line;
String s;
// Lee los mensajes del cliente. El programa finaliza cuando la cantidad de
// intentos sea igual a 0 o que ya el cliente haya acertado
while (cantIntentos > 0 && !acierto) {
try {
line = in.readUTF();
System.out.println("Cliente: " + line);
try{
s = calcular(Integer.parseInt(line));
out.writeUTF(s);
}catch(NumberFormatException e){
out.writeUTF("Debe ingresar solo números " + e);
}
} catch (IOException i) {
System.out.println(i);
}
}
System.out.println("Cerrando conexiones");
// Cerrando conexiones
socketCliente.close();
socketServer.close();
in.close();
out.close();
} catch (IOException i) {
System.out.println(i);
}
}
/**
*
* @param n: número digitado por el cliente
* @return
* String que contiene cuál es la relación del número introducido con el autogenerado
*/
private String calcular(int n){
String s = "";
cantIntentos--;
String cantI = cantIntentos == 1 ? " Te queda " + cantIntentos + " intento" : " Te quedan " + cantIntentos + " intentos";
String cantZ = "\n Te has quedado sin intentos. El número generado fue: " + this.num;
if(n > 0 && n < 201){
if(n > this.num){
s += "El número es menor.";
}else if(n < this.num){
s += "El número es mayor.";
}else{
s += "Acertaste. Adiós";
acierto = true;
}
}else{
s += "Número fuera de rango.";
}
if(!s.contains("Acertaste")){
s += cantIntentos != 0 ? cantI: cantZ;
}
return s;
}
public static void main(String args[]) throws IOException {
Servidor server = new Servidor();
}
} |
public class Main {
public static void main(String[] args) {
boolean xys = PlayingCat.isCatPlaying(false,35);
System.out.println(xys);
}
}
|
package app.akeorcist.deviceinformation.event;
/**
* Created by Akexorcist on 3/11/15 AD.
*/
public class ViewEvent {
public static final String EVENT_VIEW_SHOW_UP = "view_show_up";
public static final String EVENT_MENU_SELECTED = "menu_selected";
public static final String EVENT_REFRESH_LIST = "refresh_list";
private String eventState;
public ViewEvent(String eventState) {
this.eventState = eventState;
}
public String getEventState() {
return eventState;
}
public void setEventState(String eventState) {
this.eventState = eventState;
}
}
|
package gromcode.main.lesson30.task1;
import java.util.Date;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;
public class UkrainianBankSystem implements BankSystem {
private Set<Transaction> transactions = new TreeSet<>();
@Override
public void withdraw(User user, int amount) {
//проверить лимит
//проверить достаточно ли денег
if(!checkUser(user) || !checkWithdraw(user, amount))
return;
user.setBalance(user.getBalance() - amount - amount * user.getBank().getCommission(amount));
createAndSaveTransaction(new Date(), TransactionType.WITHDRAWAL, amount, "sdfsd");
}
@Override
public void fund(User user, int amount) {
//проверить amount >= 0
//проверить лимит
if(!checkUser(user) || !checkFundLimits(user, amount))
return;
user.setBalance(user.getBalance() + amount);
createAndSaveTransaction(new Date(), TransactionType.FUNDING, amount, "sdfsd");
}
@Override
public void transferMoney(User fromUser, User toUser, int amount) {
//снимаем деньги
//пополняем с fromUser - ToUser
if(!checkUser(fromUser) || !checkWithdraw(fromUser, amount))
return;
if(!checkUser(toUser) || !checkFundLimits(toUser, amount))
return;
if(fromUser.getBank().getCurrency() != toUser.getBank().getCurrency()){
System.err.println("Cant send money "+ amount + " from user: different currency");
return;
}
withdraw(fromUser, amount);
fund(toUser, amount);
createAndSaveTransaction(new Date(), TransactionType.TRANSFER, amount, "sdfsd");
}
@Override
public void paySalary(User user) {
if(!checkUser(user)){
paySallaryErrorMsg();
return;
}
//зачислить к зп
fund(user, user.getSalary());
createAndSaveTransaction(new Date(), TransactionType.SALARY_INCOME, user.getSalary(), "sdfsd");
}
private void withdrawalErrorMsg(User user, int amount){
if(user == null)
System.err.println("Cant withdraw money "+ amount);
System.err.println("Cant withdraw money "+ amount + " from user" + user.toString());
}
private void fundingErrorMsg(User user, int amount){
if(user == null)
System.err.println("Cant fund money "+ amount);
System.err.println("Cant fund money "+ amount + " to user" + user.toString());
}
private void paySallaryErrorMsg(){
System.err.println("Cant pay salary");
}
private boolean checkWithdraw(User user, int amount){
return checkWithdrawLimits(user, amount, user.getBank().getLimitOfWithdrawal())
&& checkWithdrawLimits(user, amount, user.getBalance());
}
private boolean checkWithdrawLimits(User user, int amount, double limit){
if(amount <= 0 || amount + user.getBank().getCommission(amount) > limit) {
withdrawalErrorMsg(user, amount);
return false;
}
return true;
}
private boolean checkFundLimits(User user, int amount){
if(amount <= 0 || amount > user.getBank().getLimitOfFunding()){
fundingErrorMsg(user, amount);
return false;
}
return true;
}
private boolean checkUser(User user){
if(user == null || user.getBank() == null)
return false;
return true;
}
private Transaction createAndSaveTransaction(Date dateCreated, TransactionType type, int amount, String descr){
Random random = new Random();
Transaction tr = new Transaction(random.nextLong(), dateCreated, null, type, amount, descr);
transactions.add(tr);
return tr;
}
public Set<Transaction> getTransactions() {
return transactions;
}
}
|
package gui;
import cliente.Cliente;
import com.cloudgarden.layout.AnchorConstraint;
import com.cloudgarden.layout.AnchorLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.WindowConstants;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileNameExtensionFilter;
/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class RecibirMercaderia extends javax.swing.JFrame {
private JLabel lblRuta;
private JTextField txtRuta;
private JButton btnExplorar;
private JButton btnAnalizarRemito;
private JPanel pnlReporte;
private JTextField txtResponsable;
private JLabel lblResponsable;
private JTextField txtReporte;
private JScrollPane scrollPane1;
private JButton btnCerrar;
{
//Set Look & Feel
try {
javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel");
} catch(Exception e) {
e.printStackTrace();
}
}
public RecibirMercaderia(Cliente cliente) {
super();
initGUI(cliente);
}
private void initGUI(final Cliente cliente) {
try {
AnchorLayout thisLayout = new AnchorLayout();
getContentPane().setLayout(thisLayout);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
this.setPreferredSize(new java.awt.Dimension(582, 289));
this.setTitle("Recepcion de Mercaderia");
{
txtResponsable = new JTextField();
getContentPane().add(txtResponsable, new AnchorConstraint(181, 786, 257, 143, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
txtResponsable.setPreferredSize(new java.awt.Dimension(369, 20));
}
{
lblResponsable = new JLabel();
getContentPane().add(lblResponsable, new AnchorConstraint(192, 136, 246, 18, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
lblResponsable.setText("Responsable: ");
lblResponsable.setPreferredSize(new java.awt.Dimension(68, 14));
}
{
pnlReporte = new JPanel();
getContentPane().add(pnlReporte, new AnchorConstraint(322, 917, 788, 82, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
pnlReporte.setPreferredSize(new java.awt.Dimension(479, 122));
pnlReporte.setBorder(BorderFactory.createTitledBorder("Reporte del analisis"));
{
scrollPane1 = new JScrollPane();
scrollPane1.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
pnlReporte.add(scrollPane1);
scrollPane1.setPreferredSize(new java.awt.Dimension(468, 95));
{
txtReporte = new JTextField();
scrollPane1.setViewportView(txtReporte);
txtReporte.setPreferredSize(new java.awt.Dimension(444, 94));
}
}
}
{
btnAnalizarRemito = new JButton();
getContentPane().add(btnAnalizarRemito, new AnchorConstraint(840, 983, 950, 793, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
btnAnalizarRemito.setText("Analizar Remito");
btnAnalizarRemito.setPreferredSize(new java.awt.Dimension(109, 23));
btnAnalizarRemito.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if(!txtResponsable.getText().equals("")){
File f = new File(txtRuta.getText());
txtReporte.setText(cliente.recibirMercaderia(f, txtResponsable.getText()));
}else{
JOptionPane.showMessageDialog(null, "Datos Incompletos. LLene el responsable de la recepcion de la mercaderia", "Advertencia", JOptionPane.WARNING_MESSAGE);}
}
});
}
{
btnCerrar = new JButton();
getContentPane().add(btnCerrar, new AnchorConstraint(840, 131, 950, 18, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
btnCerrar.setText("Cerrar");
btnCerrar.setPreferredSize(new java.awt.Dimension(65, 23));
btnCerrar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
dispose();
}
});
}
{
btnExplorar = new JButton();
getContentPane().add(btnExplorar, new AnchorConstraint(51, 966, 135, 835, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
btnExplorar.setText("Explorar");
btnExplorar.setPreferredSize(new java.awt.Dimension(75, 22));
btnExplorar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//Crear un objeto FileChooser
JFileChooser fc = new JFileChooser();
//Filtro para archivos xml
FileNameExtensionFilter filtro = new FileNameExtensionFilter("Archivos XML", "xml");
fc.setFileFilter(filtro);
//Mostrar la ventana para abrir archivo y recoger la respuesta
//En el parámetro del showOpenDialog se indica la ventana
// al que estará asociado. Con el valor this se asocia a la
// ventana que la abre.
int respuesta = fc.showOpenDialog(btnExplorar);
//Comprobar si se ha pulsado Aceptar
if (respuesta == JFileChooser.APPROVE_OPTION)
{
txtRuta.setText(fc.getSelectedFile().getPath());
}
}
});
}
{
txtRuta = new JTextField();
getContentPane().add(txtRuta, new AnchorConstraint(55, 786, 135, 82, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
txtRuta.setPreferredSize(new java.awt.Dimension(404, 21));
txtRuta.setText("Coloque la ruta del remito");
txtRuta.setEnabled(false);
}
{
lblRuta = new JLabel();
getContentPane().add(lblRuta, new AnchorConstraint(59, 70, 135, 18, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL, AnchorConstraint.ANCHOR_REL));
lblRuta.setText("Ruta: ");
lblRuta.setPreferredSize(new java.awt.Dimension(30, 16));
}
pack();
this.setSize(582, 289);
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
/*
* Dado um vetor de números reais, fazer um programa que imprima o menor
* elemento do vetor
*/
package Lista4;
import java.util.Scanner;
public class Exercicio4 {
static Scanner input = new Scanner(System.in);
static double menor(double vetor[]){
double menor=vetor[0];
for(int i=0;i<vetor.length;i++){
if(vetor[i]<menor){
menor=vetor[i];
}
}
return menor;
}
public static void main(String[] args) {
System.out.print("Escreva o tamanho do vetor: ");
int tamanho=input.nextInt();
double vetor[] = Exercicio2.vetor(tamanho);
vetor=Exercicio2.populaVetor(vetor);
double menor=menor(vetor);
System.out.println("Menor número= "+menor);
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* 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
*
* https://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.springframework.web.socket.server.support;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.web.socket.AbstractHttpRequestTests;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
/**
* Tests for {@link HandshakeInterceptorChain}.
*
* @author Rossen Stoyanchev
* @author Sam Brannen
*/
class HandshakeInterceptorChainTests extends AbstractHttpRequestTests {
private Map<String, Object> attributes = new HashMap<>();
private HandshakeInterceptor i1 = mock();
private HandshakeInterceptor i2 = mock();
private HandshakeInterceptor i3 = mock();
private WebSocketHandler wsHandler = mock();
private HandshakeInterceptorChain chain = new HandshakeInterceptorChain(List.of(i1, i2, i3), wsHandler);
@Test
void success() throws Exception {
given(i1.beforeHandshake(request, response, wsHandler, attributes)).willReturn(true);
given(i2.beforeHandshake(request, response, wsHandler, attributes)).willReturn(true);
given(i3.beforeHandshake(request, response, wsHandler, attributes)).willReturn(true);
chain.applyBeforeHandshake(request, response, attributes);
verify(i1).beforeHandshake(request, response, wsHandler, attributes);
verify(i2).beforeHandshake(request, response, wsHandler, attributes);
verify(i3).beforeHandshake(request, response, wsHandler, attributes);
verifyNoMoreInteractions(i1, i2, i3);
}
@Test
void applyBeforeHandshakeWithFalseReturnValue() throws Exception {
given(i1.beforeHandshake(request, response, wsHandler, attributes)).willReturn(true);
given(i2.beforeHandshake(request, response, wsHandler, attributes)).willReturn(false);
chain.applyBeforeHandshake(request, response, attributes);
verify(i1).beforeHandshake(request, response, wsHandler, attributes);
verify(i1).afterHandshake(request, response, wsHandler, null);
verify(i2).beforeHandshake(request, response, wsHandler, attributes);
verifyNoMoreInteractions(i1, i2, i3);
}
@Test
void applyAfterHandshakeOnly() {
chain.applyAfterHandshake(request, response, null);
verifyNoMoreInteractions(i1, i2, i3);
}
}
|
package com.wirelesscar.dynafleet.api.types;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for getElapsedTimeFromStatus complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="getElapsedTimeFromStatus">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Api_OrderGetElapsedTimeFromStatusTO_1" type="{http://wirelesscar.com/dynafleet/api/types}Api_OrderGetElapsedTimeFromStatusTO"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "getElapsedTimeFromStatus", propOrder = {
"apiOrderGetElapsedTimeFromStatusTO1"
})
public class GetElapsedTimeFromStatus {
@XmlElement(name = "Api_OrderGetElapsedTimeFromStatusTO_1", required = true, nillable = true)
protected ApiOrderGetElapsedTimeFromStatusTO apiOrderGetElapsedTimeFromStatusTO1;
/**
* Gets the value of the apiOrderGetElapsedTimeFromStatusTO1 property.
*
* @return
* possible object is
* {@link ApiOrderGetElapsedTimeFromStatusTO }
*
*/
public ApiOrderGetElapsedTimeFromStatusTO getApiOrderGetElapsedTimeFromStatusTO1() {
return apiOrderGetElapsedTimeFromStatusTO1;
}
/**
* Sets the value of the apiOrderGetElapsedTimeFromStatusTO1 property.
*
* @param value
* allowed object is
* {@link ApiOrderGetElapsedTimeFromStatusTO }
*
*/
public void setApiOrderGetElapsedTimeFromStatusTO1(ApiOrderGetElapsedTimeFromStatusTO value) {
this.apiOrderGetElapsedTimeFromStatusTO1 = value;
}
}
|
package gameVoiceHandler.intents.handlers;
import com.amazon.speech.slu.Intent;
import com.amazon.speech.slu.Slot;
import com.amazon.speech.speechlet.SpeechletResponse;
import gameData.GameDataInstance;
import gameData.GameManager;
import gameData.StateManager;
import gameData.enums.TurnState;
import gameVoiceHandler.intents.handlers.Utils.BadIntentUtil;
import gameVoiceHandler.intents.HandlerInterface;
import gameVoiceHandler.intents.handlers.Utils.GameFireUtil;
import gameVoiceHandler.intents.speeches.Speeches;
import gameVoiceHandler.intents.speeches.SpeechesGenerator;
import org.apache.commons.lang3.math.NumberUtils;
/**
* Created by corentinl on 2/22/16.
*/
//TODO: Combine this class with HandleOneFirePositionGiven
public class HandleTwoFirePositionsGiven implements HandlerInterface {
private static final String LINE_SLOT = "line";
private static final String COLUMN_SLOT = "column";
private static final String LINE_LETTER_SLOT = "lineLetter";
private static final String COLUMN_NUMBER_SLOT = "columnNumber";
@Override
public SpeechletResponse handleIntent(Intent intent, GameDataInstance gameDataInstance) {
if (!isIntentExpected(gameDataInstance)) {
return BadIntentUtil.fireUnexpected();
}
StateManager stateManager = gameDataInstance.getStateManager();
if (stateManager.getTurnState().equals(TurnState.PLAYER)) {
String speechOutput = "";
GameManager gameManager = gameDataInstance.getGameManager();
parseFireCoordinates(intent, gameManager);
if (gameDataInstance.getGameManager().getLastPlayerAttackXCoordinate() == -1
|| gameDataInstance.getGameManager().getLastPlayerAttackYCoordinate() == -1) {
speechOutput = Speeches.IM_SORRY + Speeches.INCORRECT_NUMBER;
} else {
speechOutput += GameFireUtil.fire(gameDataInstance);
}
if (gameManager.gameIsOver()) {
return SpeechesGenerator.newTellResponse(speechOutput);
} else {
return SpeechesGenerator.newAskResponse(speechOutput, false, speechOutput, false);//TODO: Check the reprompt
}
} else {
String speechOutput = Speeches.NOT_YOUR_TURN + stateManager.getLastQuestionAsked();
return SpeechesGenerator.newAskResponse(speechOutput, false, stateManager.getLastQuestionAsked(), false);
}
}
private boolean isIntentExpected(GameDataInstance gameDataInstance) {
return gameDataInstance.getStateManager().isGamesStarted();
}
private static void parseFireCoordinates(Intent intent, GameManager gameManager) {
Slot lineSlot = intent.getSlot(LINE_SLOT);
Slot columnSlot = intent.getSlot(COLUMN_SLOT);
Slot lineLetterSlot = intent.getSlot(LINE_LETTER_SLOT);
Slot columnNumberSlot = intent.getSlot(COLUMN_NUMBER_SLOT);
int x = -1;
int y = -1;
if (lineSlot != null && columnSlot != null) {
String lineSlotValue = lineSlot.getValue();
String columnSlotValue = columnSlot.getValue();
if (NumberUtils.isNumber(lineSlotValue) && NumberUtils.isNumber(columnSlotValue))
x = Integer.parseInt(lineSlotValue);
y = Integer.parseInt(columnSlotValue);
} else if (lineLetterSlot != null && columnNumberSlot != null) {
String lineLetterSlotValue = lineLetterSlot.getValue();
String columnNumberSlotValue = columnNumberSlot.getValue();
x = lineLetterSlotValue.toLowerCase().toCharArray()[0] - 'a' + 1;
if (NumberUtils.isNumber(columnNumberSlotValue))
y = Integer.parseInt(columnNumberSlotValue);
}
gameManager.setLastPlayerAttackXCoordinate(x);
gameManager.setLastPlayerAttackYCoordinate(y);
}
}
|
package ALIXAR.U7_COLLECTIONS.T1.A8;
import java.util.*;
public class Actividad8 {
public static void main(String[] args) {
Scanner teclado = new Scanner(System.in);
List<String> lista = new ArrayList<>();
System.out.println("Introduzca una palabra: ");
}
}
|
package com.mycontacts.controller;
import android.content.Context;
import android.content.res.Resources;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.mycontacts.R;
import com.mycontacts.model.M_ContactFAV;
import java.util.ArrayList;
public class ContactFavAdapter extends RecyclerView.Adapter<ContactFavAdapter.MyHolder> {
Context context;
ArrayList<M_ContactFAV> mContacts;
public ContactFavAdapter(Context context, ArrayList<M_ContactFAV> mContacts) {
this.context = context;
this.mContacts = mContacts;
}
@Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.contact_fav_row, parent, false);
return new MyHolder(view);
}
@Override
public void onBindViewHolder(final MyHolder holder, final int position) {
try {
M_ContactFAV contact = mContacts.get(position);
String imagePath = contact.getContact_Image_uri();
String contact_status = contact.getContact_Status();
holder.name.setText(contact.getContact_Name());
if (imagePath != null) {
Glide.with(context).load(imagePath).into(holder.img_photo);
} else {
holder.img_photo.setImageDrawable(context.getResources().getDrawable(R.drawable.th));
}
} catch (Resources.NotFoundException e) {
e.printStackTrace();
}
}
@Override
public int getItemCount() {
return mContacts.size();
}
public class MyHolder extends RecyclerView.ViewHolder {
ImageView img_photo;
TextView name;
public MyHolder(View itemView) {
super(itemView);
img_photo = (ImageView) itemView.findViewById(R.id.img_photo);
name = (TextView) itemView.findViewById(R.id.txt_name);
}
}
}
|
package com.bakerystudios.tools;
import java.awt.Graphics;
import com.bakerystudios.game.Screen;
public class Text {
public static void drawCentralizedText(Graphics g, String str, int y) {
g.drawString(str, Screen.WIDTH / 2 - g.getFontMetrics().stringWidth(str) / 2, y);
}
}
|
package com.soy.seckill.enums;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.omg.CORBA.UNKNOWN;
/**
* 执行秒杀后状态(数据字典)
* Created by Soy on 2016/12/12.
*/
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum StateEnum {
SUCCESS(1,"秒杀成功"),
END(0,"秒杀结束"),
REPEAT_KILL(-1,"重复秒杀"),
INNER_ERROR(-2,"系统异常"),
DATA_REWRITE(-3,"数据篡改");
private int state;
private String stateInfo;
StateEnum(int state, String stateInfo) {
this.state = state;
this.stateInfo = stateInfo;
}
public int getState() {
return state;
}
public String getStateInfo() {
return stateInfo;
}
public static StateEnum stateOf(int state){
for(StateEnum stateEnum : values()){
if(stateEnum.getState() == state){
return stateEnum;
}
}
return null;
}
}
|
//------------------------------------------------------------------------------
// Copyright (c) 2012 Microsoft Corporation. All rights reserved.
//
// Description: See the class level JavaDoc comments.
//------------------------------------------------------------------------------
package com.microsoft.live;
/**
* Represents errors that occur when making requests to the Representational State Transfer
* (REST) API.
*/
public class LiveOperationException extends Exception {
private static final long serialVersionUID = 4630383031651156731L;
LiveOperationException(String message) {
super(message);
}
LiveOperationException(String message, Throwable e) {
super(message, e);
}
}
|
/**
* This class is generated by jOOQ
*/
package schema.tables;
import java.util.Arrays;
import java.util.List;
import javax.annotation.Generated;
import org.jooq.Field;
import org.jooq.ForeignKey;
import org.jooq.Identity;
import org.jooq.Schema;
import org.jooq.Table;
import org.jooq.TableField;
import org.jooq.UniqueKey;
import org.jooq.impl.TableImpl;
import schema.BitnamiEdx;
import schema.Keys;
import schema.tables.records.OauthProviderConsumerRecord;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.8.4"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class OauthProviderConsumer extends TableImpl<OauthProviderConsumerRecord> {
private static final long serialVersionUID = -1677741574;
/**
* The reference instance of <code>bitnami_edx.oauth_provider_consumer</code>
*/
public static final OauthProviderConsumer OAUTH_PROVIDER_CONSUMER = new OauthProviderConsumer();
/**
* The class holding records for this type
*/
@Override
public Class<OauthProviderConsumerRecord> getRecordType() {
return OauthProviderConsumerRecord.class;
}
/**
* The column <code>bitnami_edx.oauth_provider_consumer.id</code>.
*/
public final TableField<OauthProviderConsumerRecord, Integer> ID = createField("id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "");
/**
* The column <code>bitnami_edx.oauth_provider_consumer.name</code>.
*/
public final TableField<OauthProviderConsumerRecord, String> NAME = createField("name", org.jooq.impl.SQLDataType.VARCHAR.length(255).nullable(false), this, "");
/**
* The column <code>bitnami_edx.oauth_provider_consumer.description</code>.
*/
public final TableField<OauthProviderConsumerRecord, String> DESCRIPTION = createField("description", org.jooq.impl.SQLDataType.CLOB.nullable(false), this, "");
/**
* The column <code>bitnami_edx.oauth_provider_consumer.key</code>.
*/
public final TableField<OauthProviderConsumerRecord, String> KEY = createField("key", org.jooq.impl.SQLDataType.VARCHAR.length(256).nullable(false), this, "");
/**
* The column <code>bitnami_edx.oauth_provider_consumer.secret</code>.
*/
public final TableField<OauthProviderConsumerRecord, String> SECRET = createField("secret", org.jooq.impl.SQLDataType.VARCHAR.length(16).nullable(false), this, "");
/**
* The column <code>bitnami_edx.oauth_provider_consumer.status</code>.
*/
public final TableField<OauthProviderConsumerRecord, Short> STATUS = createField("status", org.jooq.impl.SQLDataType.SMALLINT.nullable(false), this, "");
/**
* The column <code>bitnami_edx.oauth_provider_consumer.xauth_allowed</code>.
*/
public final TableField<OauthProviderConsumerRecord, Byte> XAUTH_ALLOWED = createField("xauth_allowed", org.jooq.impl.SQLDataType.TINYINT.nullable(false), this, "");
/**
* The column <code>bitnami_edx.oauth_provider_consumer.user_id</code>.
*/
public final TableField<OauthProviderConsumerRecord, Integer> USER_ID = createField("user_id", org.jooq.impl.SQLDataType.INTEGER, this, "");
/**
* Create a <code>bitnami_edx.oauth_provider_consumer</code> table reference
*/
public OauthProviderConsumer() {
this("oauth_provider_consumer", null);
}
/**
* Create an aliased <code>bitnami_edx.oauth_provider_consumer</code> table reference
*/
public OauthProviderConsumer(String alias) {
this(alias, OAUTH_PROVIDER_CONSUMER);
}
private OauthProviderConsumer(String alias, Table<OauthProviderConsumerRecord> aliased) {
this(alias, aliased, null);
}
private OauthProviderConsumer(String alias, Table<OauthProviderConsumerRecord> aliased, Field<?>[] parameters) {
super(alias, null, aliased, parameters, "");
}
/**
* {@inheritDoc}
*/
@Override
public Schema getSchema() {
return BitnamiEdx.BITNAMI_EDX;
}
/**
* {@inheritDoc}
*/
@Override
public Identity<OauthProviderConsumerRecord, Integer> getIdentity() {
return Keys.IDENTITY_OAUTH_PROVIDER_CONSUMER;
}
/**
* {@inheritDoc}
*/
@Override
public UniqueKey<OauthProviderConsumerRecord> getPrimaryKey() {
return Keys.KEY_OAUTH_PROVIDER_CONSUMER_PRIMARY;
}
/**
* {@inheritDoc}
*/
@Override
public List<UniqueKey<OauthProviderConsumerRecord>> getKeys() {
return Arrays.<UniqueKey<OauthProviderConsumerRecord>>asList(Keys.KEY_OAUTH_PROVIDER_CONSUMER_PRIMARY);
}
/**
* {@inheritDoc}
*/
@Override
public List<ForeignKey<OauthProviderConsumerRecord, ?>> getReferences() {
return Arrays.<ForeignKey<OauthProviderConsumerRecord, ?>>asList(Keys.OAUTH_PROVIDER_CONSUMER_USER_ID_4F22B60D2B258006_FK_AUTH_USER_ID);
}
/**
* {@inheritDoc}
*/
@Override
public OauthProviderConsumer as(String alias) {
return new OauthProviderConsumer(alias, this);
}
/**
* Rename this table
*/
public OauthProviderConsumer rename(String name) {
return new OauthProviderConsumer(name, null);
}
}
|
package series03Part1;
import java.awt.FlowLayout;
import javax.swing.JFrame;
public class MyFrameA extends JFrame {
private static final long serialVersionUID = 1L;
MyFrameA(int title) {
this(Integer.toString(title));
}
MyFrameA(String title) {
setTitle(title);
setSize(200, 200);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
}
|
/*
* (C) Mississippi State University 2009
*
* The WebTOP employs two licenses for its source code, based on the intended use. The core license for WebTOP applications is
* a Creative Commons GNU General Public License as described in http://*creativecommons.org/licenses/GPL/2.0/. WebTOP libraries
* and wapplets are licensed under the Creative Commons GNU Lesser General Public License as described in
* http://creativecommons.org/licenses/*LGPL/2.1/. Additionally, WebTOP uses the same licenses as the licenses used by Xj3D in
* all of its implementations of Xj3D. Those terms are available at http://www.xj3d.org/licenses/license.html.
*/
//WTMath.java
//Defines math routines of general interest to WebTOP
//Compiled by Davis Herring
//Created March 2 2002
//Updated July 8 2004
//Version 0.48
package org.webtop.util;
import java.util.Random;
public final class WTMath
{
public static final Random random=new Random();
//=====================
// PRINCIPAL FUNCTIONS
//=====================
//These are different from a%b in that -5%2.4 = -0.2 (remainder), but
//fmod(-5,2.4) = 2.2.
public static float mod(final float a,final float b)
{return a-b*(float)Math.floor(a/b);}
public static double mod(final double a,final double b)
{return a-b*Math.floor(a/b);}
public static float toRads(final float degs)
{return degs*(float)Math.PI/180;}
public static double toRads(final double degs)
{return degs*Math.PI/180;}
public static float toDegs(final float rads)
{return rads*180/(float)Math.PI;}
public static double toDegs(final double rads)
{return rads*180/Math.PI;}
public static float sinh(final float x)
{return (float)(Math.exp(x) - Math.exp(-x)) / 2;}
public static double sinh(final double x)
{return (Math.exp(x) - Math.exp(-x)) / 2;}
public static float cosh(final float x)
{return (float)(Math.exp(x) + Math.exp(-x)) / 2;}
public static double cosh(final double x)
{return (Math.exp(x) + Math.exp(-x)) / 2;}
public static float tanh(final float x)
{return sinh(x) / cosh(x);}
public static double tanh(final double x)
{return sinh(x) / cosh(x);}
public static int bound(final int x,final int min,final int max) {
if(max<min)
throw new IllegalArgumentException("invalid interval ["+max+','+min+']');
return x>max?max:x<min?min:x;
}
public static float bound(final float x,final float min,final float max) {
if(max<min)
throw new IllegalArgumentException("invalid interval ["+max+','+min+']');
return x>max?max:x<min?min:x;
}
public static double bound(final double x,
final double min,final double max) {
if(max<min)
throw new IllegalArgumentException("invalid interval ["+max+','+min+']');
return x>max?max:x<min?min:x;
}
//==================
// BESSEL FUNCTIONS
//==================
/////////////////////////////////////////////////////////////////////////
//Bessel functions copied from Numerical Recipes. They probably need to
//have a bit of code-cleanup.
//Returns the Bessel function J0(x) for any real x.
public static double j0(final double x) {
final double ax,z;
final double xx,y,ans,ans1,ans2;
if((ax=Math.abs(x))<8) {
y=x*x;
ans1 = 57568490574d + y*(-13362590354d+y*(651619640.7
+ y*(-11214424.18 + y*(77392.33017 + y*(-184.9052456)))));
ans2 = 57568490411d + y*(1029532985d + y*(9494680.718
+ y*(59272.64853 + y*(267.8532712 + y*1))));
ans = ans1/ans2;
} else {
z = 8/ax;
y = z*z;
xx = ax-0.785398164;
ans1 = 1 + y*(-0.1098628627e-2 + y*(0.2734510407e-4
+ y*(-0.2073370639e-5 + y*0.2093887211e-6)));
ans2 = -0.1562499995e-1 + y*(0.1430488765e-3
+ y*(-0.6911147651e-5 + y*(0.7621095161e-6
- y*0.934935152e-7)));
ans = Math.sqrt(0.636619772/ax)*(Math.cos(xx)*ans1-z*Math.sin(xx)*ans2);
}
return ans;
}
//Returns the Bessel function J1(x) for any real x.
public static double j1(final double x) {
double ax,z;
double xx,y,ans,ans1,ans2;
if((ax=Math.abs(x))<8) {
y = x*x;
ans1 = x*(72362614232d + y*(-7895059235d + y*(242396853.1
+y*(-2972611.439 + y*(15704.48260 + y*(-30.16036606))))));
ans2 = 144725228442d+y*(2300535178d+y*(18583304.74
+ y*(99447.43394 + y*(376.9991397 + y*1))));
ans = ans1/ans2;
} else {
z = 8/ax;
y = z*z;
xx = ax-2.356194491;
ans1 = 1 + y*(0.183105e-2 + y*(-0.3516396496e-4
+ y*(0.2457520174e-5 + y*(-0.240337019e-6))));
ans2 = 0.04687499995 + y*(-0.2002690873e-3
+ y*(0.8449199096e-5 + y*(-0.88228987e-6
+ y*0.105787412e-6)));
ans = Math.sqrt(0.636619772/ax)*(Math.cos(xx)*ans1 - z*Math.sin(xx)*ans2);
if(x<0) ans = -ans;
}
return ans;
}
//adapted by way of Leigh Brookshaw:
static public double jn(final int n,final double x) {
int j,m;
double ax,bj,bjm,bjp,sum,tox,ans;
boolean jsum;
final double ACC = 40;
final double BIGNO = 1e+10;
final double BIGNI = 1e-10;
if(n == 0) return j0(x);
if(n == 1) return j1(x);
if(n<0) return Math.pow(-1,-n)*jn(-n,x); //Changed to allow for funcions of negative order [Matt]
//if(n<0) throw new IllegalArgumentException("Bessel functions of negative order not implemented.");
if((ax=Math.abs(x)) == 0) return 0;
else
if(ax>n) {
tox=2/ax;
bjm=j0(ax);
bj=j1(ax);
for(j=1;j<n;j++) {
bjp=j*tox*bj-bjm;
bjm=bj;
bj=bjp;
}
ans=bj;
} else {
tox=2/ax;
m=2*((n+(int)Math.sqrt(ACC*n))/2);
jsum=false;
bjp=ans=sum=0;
bj=1;
for(j=m;j>0;j--) {
bjm=j*tox*bj-bjp;
bjp=bj;
bj=bjm;
if(Math.abs(bj)>BIGNO) {
bj *= BIGNI;
bjp *= BIGNI;
ans *= BIGNI;
sum *= BIGNI;
}
if(jsum) sum += bj;
jsum=!jsum;
if(j == n) ans=bjp;
}
sum=2*sum-bj;
ans /= sum;
}
return x<0 && n%2 == 1 ? -ans : ans;
}
//Returns the Bessel function Y0(x) for positive x.
public static double y0(final double x) {
double z;
double xx,y,ans,ans1,ans2;
if(x<8) {
y = x*x;
ans1 = -2957821389d + y*(7062834065d + y*(-512359803.6
+ y*(10879881.29 + y*(-86327.92757 + y*228.4622733))));
ans2 = 40076544269d + y*(745249964.8 + y*(7189466.438
+ y*(47447.26470 + y*(226.1030244 + y*1))));
ans = (ans1/ans2) + 0.636619772*j0(x)*Math.log(x);
} else {
z = 8/x;
y = z*z;
xx = x-0.785398164;
ans1 = 1 + y*(-0.1098628627e-2 + y*(0.2734510407e-4
+ y*(-0.2073370639e-5 + y*0.2093887211e-6)));
ans2 = -0.1562499995e-1 + y*(0.1430488765e-3
+ y*(-0.6911147651e-5 + y*(0.7621095161e-6
+ y*(-0.934945152e-7))));
ans = Math.sqrt(0.636619772/x)*(Math.sin(xx)*ans1 + z*Math.cos(xx)*ans2);
}
return ans;
}
//Returns the Bessel function Y1(x) for positive x.
public static double y1(final double x) {
double z;
double xx,y,ans,ans1,ans2;
if(x<8) {
y = x*x;
ans1 = x*(-0.4900604943e13 + y*(0.1275274390e13
+ y*(-0.5153438139e11 + y*(0.7349264551e9
+ y*(-0.4237922726e7 + y*0.8511937935e4)))));
ans2 = 0.2499580570e14 + y*(0.4244419664e12
+ y*(0.3733650367e10 + y*(0.2245904002e8
+ y*(0.1020426050e6 + y*(0.3549632885e3 + y)))));
ans = (ans1/ans2) + 0.636619772*(j1(x)*Math.log(x) - 1/x);
} else {
z = 8/x;
y = z*z;
xx = x-2.356194491;
ans1 = 1 + y*(0.183105e-2 + y*(-0.3516396496e-4
+ y*(0.2457520174e-5 + y*(-0.240337019e-6))));
ans2 = 0.04687499995 + y*(-0.2002690873e-3
+ y*(0.8449199096e-5 + y*(-0.88228987e-6
+ y*0.105787412e-6)));
ans = Math.sqrt(0.636619772/x)*(Math.sin(xx)*ans1 + z*Math.cos(xx)*ans2);
}
return ans;
}
//Returns the Bessel function I0(x) for any real x
public static double i0(final double x) {
double ax,ans,y;
if((ax=Math.abs(x))<3.75) {
y=x/3.75;
y*=y;
ans=1.0+y*(3.5156229+y*(3.0899424+y*(1.2067492+y*(0.2659732+y*(0.360768e-1+y*0.45813e-2)))));
} else {
y=3.75/ax;
ans=(Math.exp(ax)/Math.sqrt(ax))*(0.39894228+y*(0.1328592e-1+y*(0.225319e-2+y*(-0.157565e-2+y*(0.916281e-2+y*(-0.2057706e-1+y*(0.2635537e-1+y*(-0.1647633e-1+y*0.392377e-2))))))));
}
return ans;
}
//Returns the Bessel function I1(x) for any real x
public static double i1(final double x) {
double ax,ans,y;
if((ax=Math.abs(x))< 3.75) {
y=x/3.75;
y*=y;
ans=ax*(0.5+y*(0.87890594+y*(0.51498869+y*(0.15084934+y*(0.2658733e-1+y*(0.301532e-2+y*0.32411e-3))))));
} else {
y=3.75/ax;
ans=0.2282967e-1+y*(-0.2895312e-1+y*(0.1787654e-1-y*0.420059e-2));
ans=0.39894228+y*(-.3988024e-2+y*(-0.362018e-2+y*(0.163801e-2+y*(-0.1031555e-1+y*ans))));
}
return x < 0.0 ? -ans : ans;
}
//Returns the Bessel function K0(x) for positive x
public static double k0(final double x) {
double y,ans;
if(x <= 2.0) {
y=x*x/4.0;
ans=(-1.0*Math.log(x/2.0)*i0(x))+(-0.57721566+y*(0.42278420+y*(0.23069765+y*(0.3488590e-1+y*(0.262698e-2+y*(0.10750e-3+y*0.74e-5))))));
} else {
y=2.0/x;
ans=(Math.exp(-x)/Math.sqrt(x))*(1.25331414+y*(-0.7832358e-1+y*(0.2189568e-1+y*(-0.1062446e-1+y*(0.587872e-2+y*(-0.251540e-2+y*0.53208e-3))))));
}
return ans;
}
//Returns the Bessel function K1(x) for positive x
public static double k1(final double x) {
double y,ans;
if(x <= 2.0) {
y=x*x/4.0;
ans=(Math.log(x/2.0)*i1(x))+(1.0/x)*(1.0+y*(0.15443144+y*(-.67278579+y*(-0.18156897+y*(-0.1919402e-1+y*(-0.110404e-2+y*(-0.4686e-4)))))));
} else {
y=2.0/x;
ans=(Math.exp(-x)/Math.sqrt(x))*(1.25331414+y*(0.23498619+y*(-0.3655620e-1+y*(0.1504268e-1+y*(-0.780353e-2+y*(0.325614e-2+y*(-0.68245e-3)))))));
}
return ans;
}
//Returns the Bessel function Kn(x) for positive x
public static double kn(final int n,final double x) {
int j;
double bk,bkm,bkp,tox;
tox=2.0/x;
bkm=k0(x);
bk=k1(x);
if(n == 0) return k0(x);
if(n == 1) return k1(x);
if(n<0) throw new IllegalArgumentException("Bessel functions of negative order not implemented.");
for(j=1; j<n; j++) {
bkp=bkm+j*tox*bk;
bkm=bk;
bk=bkp;
}
return bk;
}
//=================
// COLOR FUNCTIONS
//=================
//This is the color function from the Circular Module. Eventually it should
//get a home in some other class (possibly its own); also, any modules using
//this color model should refer to this copy, and any using another color
//model should either change to use this one or have their model moved to a
//similar global location. [Davis]
//empirical constants for hue()
private static final float BLUE_WAVE =410; //some use 400
private static final float RED_WAVE =625; //some use 630
private static final float HUE_SCALE =240;
public static final float SATURATION = 1; //we always use saturated colors
private static final int RED=0,GREEN=1,BLUE=2;
public static float hue(final float wavelength) {
final float hue=(wavelength - BLUE_WAVE) / (RED_WAVE - BLUE_WAVE);
return HUE_SCALE*(1-bound(hue,0,1));
}
//Fills the first three elements of the array rgb (which must be non-null
//and have length >= 3) with the red, green, and blue components of the
//color whose hue is h, whose luminosity is l, and whose saturation is s.
//All values are on [0,1] except for h, which is on [0,360].
public static void hls2rgb(final float[] rgb,
final float h,final float l,final float s) {
final float m2=(l<=0.5f) ? l*(1+s) : l+s-l*s,m1=2*l-m2;
if(s==0) // special case for efficiency
rgb[RED]=rgb[GREEN]=rgb[BLUE]=l;
else {
rgb[RED]=component(m1,m2,h+120);
rgb[GREEN]=component(m1,m2,h);
rgb[BLUE]=component(m1,m2,h-120);
}
//Clamp color values
if(rgb[RED]>1) rgb[RED]=1;
if(rgb[GREEN]>1) rgb[GREEN]=1;
if(rgb[BLUE]>1) rgb[BLUE]=1;
}
//Helper function for HLS
private static float component(final float n1,final float n2,float h) {
while(h<0) h+=360;
while(h>360) h-=360;
if(h<60) return n1+(n2-n1)*h/60;
else if(h<180) return n2;
else if(h<240) return n1+(n2-n1)*(240-h)/60;
else return n1;
}
//Stores into an array RGB values (on [0,1]) for a given hue, saturation,
//and value; VERY similar to java.awt.Color's HSB -> RGB color
//functions... thus, is it needed?
//Apparently, only NSlit uses this at the moment.
public static void hsv2rgb(final float[] rgb,
float hue,final float sat,final float val) {
if(sat==0) {
rgb[RED]=rgb[GREEN]=rgb[BLUE]=val;
} else {
hue=mod(hue,360)/60;
final int hue_range=(int)Math.floor(hue); //integer part of hue/60
final float hue_offset=hue-hue_range; //fractional part
final float f4=val*(1-sat),
f5=val*(1-sat*hue_offset),
f6=val*(1-sat*(1-hue_offset));
switch (hue_range) {
case 0:
rgb[RED] = val;
rgb[GREEN] = f6;
rgb[BLUE] = f4;
break;
case 1:
rgb[RED] = f5;
rgb[GREEN] = val;
rgb[BLUE] = f4;
break;
case 2:
rgb[RED] = f4;
rgb[GREEN] = val;
rgb[BLUE] = f6;
break;
case 3:
rgb[RED] = f4;
rgb[GREEN] = f5;
rgb[BLUE] = val;
break;
case 4:
rgb[RED] = f6;
rgb[GREEN] = f4;
rgb[BLUE] = val;
break;
case 5:
rgb[RED] = val;
rgb[GREEN] = f4;
rgb[BLUE] = f5;
break;
}
}
}
private WTMath() {}
}
|
/*
* 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 utilidades;
import java.io.Serializable;
import java.util.ArrayList;
/**
*
* @author Ignacio Brenes
*/
public class Empresa implements Serializable{
private String nombre;
private ArrayList <Proyecto> listProyecto;
private ArrayList <Departamento> departamentos;
private ArrayList<Empleado> listaEmpleados;
private int cedulaJuridica;
public Recursos recursos;
public Departamento departamento;
public static Empresa singletonObj;
/*
Se declara la empresa como un objeto singleton para asi tener acceso a sus datos en todas las clases
*/
public static synchronized Empresa getProyecto(){
if(singletonObj == null){
singletonObj = new Empresa();
}
return singletonObj;
}
public void setData(String nombre, ArrayList<Proyecto> listProyecto, int cedulaJuridica, ArrayList<Departamento> departamentos){
this.nombre = nombre;
this.listProyecto = listProyecto;
this.cedulaJuridica = cedulaJuridica;
this.departamentos = departamentos;
this.listaEmpleados = new ArrayList<>();
}
//
// public Empresa(String nombre, ArrayList<Proyecto> listProyecto, int cedulaJuridica, ArrayList<Departamento> departamentos) {
// this.nombre = nombre;
// this.listProyecto = listProyecto;
// this.cedulaJuridica = cedulaJuridica;
// this.departamentos = departamentos;
// }
public void addEmpleado(Empleado e){
listaEmpleados.add(e);
}
public ArrayList<Empleado> getEmpleados(){
return listaEmpleados;
}
public Empleado buscarEmpleado(Empleado e){
if(listaEmpleados.isEmpty()){
return null;
}
if(listaEmpleados.contains(e)){
return e;
}
return null;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public ArrayList<Proyecto> getListProyecto() {
return listProyecto;
}
public void setListProyecto(ArrayList<Proyecto> listProyecto) {
this.listProyecto = listProyecto;
}
public int getCedulaJuridica() {
return cedulaJuridica;
}
public void setCedulaJuridica(int cedulaJuridica) {
this.cedulaJuridica = cedulaJuridica;
}
public ArrayList<Departamento> getDepartamentos() {
return departamentos;
}
public void setDepartamentos(ArrayList<Departamento> departamentos) {
this.departamentos = departamentos;
}
}
|
/*
* Copyright (C) 2014 Vasilis Vryniotis <bbriniotis at datumbox.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.datumbox.framework.machinelearning.featureselection.continuous;
import com.datumbox.common.dataobjects.Dataset;
import com.datumbox.common.dataobjects.Record;
import com.datumbox.configuration.MemoryConfiguration;
import com.datumbox.configuration.TestConfiguration;
import java.util.Iterator;
import java.util.Map;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Vasilis Vryniotis <bbriniotis at datumbox.com>
*/
public class PCATest {
public PCATest() {
}
/**
* Test of estimateModelParameters method, of class PCA.
*/
@Test
public void testCalculateParameters() {
System.out.println("calculateParameters");
Dataset originaldata = new Dataset();
originaldata.add(Record.<Double>newDataVector(new Double[]{1.0, 2.0, 3.0}, null));
originaldata.add(Record.<Double>newDataVector(new Double[]{0.0, 5.0, 6.0}, null));
originaldata.add(Record.<Double>newDataVector(new Double[]{7.0, 8.0, 0.0}, null));
originaldata.add(Record.<Double>newDataVector(new Double[]{10.0, 0.0, 12.0}, null));
originaldata.add(Record.<Double>newDataVector(new Double[]{13.0, 14.0, 15.0}, null));
MemoryConfiguration memoryConfiguration = new MemoryConfiguration();
String dbName = "JUnitPCAdimred";
PCA instance = new PCA(dbName);
PCA.TrainingParameters param = instance.getEmptyTrainingParametersObject();
param.setMaxDimensions(null);
instance.initializeTrainingConfiguration(memoryConfiguration, param);
instance.evaluateFeatures(originaldata);
instance=null;
Dataset newdata = originaldata;
instance = new PCA(dbName);
instance.setMemoryConfiguration(memoryConfiguration);
Dataset expResult = new Dataset();
expResult.add(Record.<Double>newDataVector(new Double[]{-3.4438, 0.0799, -1.4607}, null));
expResult.add(Record.<Double>newDataVector(new Double[]{-6.0641, 1.0143, -4.8165}, null));
expResult.add(Record.<Double>newDataVector(new Double[]{-7.7270, 6.7253, 2.8399}, null));
expResult.add(Record.<Double>newDataVector(new Double[]{-14.1401, -6.4677, 1.4920}, null));
expResult.add(Record.<Double>newDataVector(new Double[]{-23.8837, 3.7408, -2.3614}, null));
instance.clearFeatures(newdata);
assertEquals(newdata.size(), expResult.size());
Iterator<Record> itResult = newdata.iterator();
Iterator<Record> itExpectedResult = expResult.iterator();
while(itResult.hasNext()) {
Record r=itResult.next();
Record r2 = itExpectedResult.next();
for(Map.Entry<Object, Object> entry : r.getX().entrySet()) {
Object feature = entry.getKey();
Double value = Dataset.toDouble(entry.getValue());
assertEquals(Dataset.toDouble(r2.getX().get(feature)), value, TestConfiguration.DOUBLE_ACCURACY_MEDIUM);
}
}
instance.erase(true);
}
}
|
package com.meehoo.biz.core.basic.vo.security;
import com.meehoo.biz.core.basic.domain.security.AdminToRole;
import com.meehoo.biz.core.basic.vo.BaseEntityVO;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* @author zc
* @date 2019-04-25
*/
@EqualsAndHashCode(callSuper = true)
@Data
public class AdminToRoleVO extends BaseEntityVO {
private String adminId;
private String adminName;
private String roleId;
private String roleName;
public AdminToRoleVO(AdminToRole adminToRole) {
this.adminId = adminToRole.getAdmin().getId();
this.adminName = adminToRole.getAdmin().getUserName();
this.roleId = adminToRole.getRole().getId();
this.roleName = adminToRole.getRole().getName();
}
}
|
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
BazaZapytania bazazapytania;
Scanner in = new Scanner(System.in);
Student student;
int idUzyt = 0, idPrzedmiotu, opcja;
boolean powrot = false;
while(true)
{
powrot = false;
System.out.println("\n");
System.out.println("****************************************");
System.out.println(" WIRTUALNY DZIEKANAT ");
System.out.println("****************************************");
System.out.println("\nLogowanie");
System.out.println("1. Dla prowadzacyh");
System.out.println("2. Dla studentow");
System.out.println("3. Dla pracowników dziekanatu");
System.out.println("4. Wyjście");
int zmienna = Integer.parseInt(in.nextLine());
if(zmienna==1)
{
String login = "";
String haslo = "";
while (login.equals(""))
{
System.out.println("Podaj login");
login = in.nextLine();
}
while (haslo.equals(""))
{
System.out.println("Podaj haslo");
haslo = in.nextLine();
}
Prowadzacy prowadzacy = new Prowadzacy(login, haslo);
idUzyt = prowadzacy.Zaloguj();
while ((idUzyt == 0) && (powrot == false))
{
System.out.println("Naciśnij:\n 1. Jeśli chcesz spróbować ponownie,\n 2. Jeśli chcesz zmienić hasło,\n 3. Wyjście!");
zmienna = Integer.parseInt(in.nextLine());
if (zmienna == 1) {
login = "";
haslo = "";
while (login.equals("")) {
System.out.println("Podaj login");
login = in.nextLine();
}
while (haslo.equals("")) {
System.out.println("Podaj haslo");
haslo = in.nextLine();
}
prowadzacy = new Prowadzacy(login, haslo);
}
else if (zmienna == 3)
powrot = true;
else if (zmienna == 2) {
prowadzacy.ZmienHaslo();
}
else
System.out.println("Brak opcji");
idUzyt = prowadzacy.Zaloguj();
}
bazazapytania = new BazaZapytania();
bazazapytania.wczytajPrzedmioty(idUzyt);
while (powrot == false) {
System.out.println();
System.out.println("********************************************");
System.out.println("Prowadzący id=" + idUzyt + "\n");
System.out.println("1. Zobacz swoje dane \n2. Zobacz liste przedmiotów \n3. Wyloguj");
System.out.print("Podaj opcje: ");
opcja = in.nextInt();
switch (opcja) {
case 1:
System.out.println(prowadzacy.toString(2));
break;
case 2:
while (!powrot)
{
System.out.println();
System.out.println("********************************************");
for (Przedmiot przedmiot: bazazapytania.przedmioty) {
System.out.println(przedmiot.toString());
}
bazazapytania.przedmioty.toString();
System.out.println("1. Sprawdź Liste studentów z przedmiotu");
System.out.print("2. Powrot \nPodaj opcje:");
opcja = in.nextInt();
switch (opcja) {
case 1:
System.out.print("Podaj id przedmiotu: ");
idPrzedmiotu = in.nextInt();
bazazapytania.wczytajStudentowPoIdPrzedmiotu(idPrzedmiotu);
while (!powrot)
{
System.out.println();
System.out.println("********************************************");
System.out.println("1. Sprawdź oceny studenta z przedmiotu");
System.out.println("2. Sprawdź średnia studenta z przedmiotu");
System.out.println("3. Wstaw nową ocene");
System.out.print("4. Powrot \nPodaj opcje:");
opcja = in.nextInt();
switch (opcja) {
case 1:
System.out.print("Podaj id studenta: ");
opcja = in.nextInt();
bazazapytania.wczytajOcenyStudentaZPrzedmiotu(opcja, idPrzedmiotu);
break;
case 2:
System.out.print("Podaj id studenta: ");
opcja = in.nextInt();
bazazapytania.podajSredniaStudenta(opcja, idPrzedmiotu);
break;
case 3:
double ocena;
int waga;
int id;
String name;
System.out.print("Podaj id studenta: ");
id = in.nextInt();
System.out.print("Podaj ocene: ");
ocena = in.nextDouble();
System.out.print("Podaj wage oceny: ");
waga = in.nextInt();
in.nextLine();
System.out.print("Podaj nazwę: ");
name = in.nextLine();
bazazapytania.dodajOcene(id,idPrzedmiotu,ocena,waga,name);
break;
case 4:
powrot = true;
break;
default:
System.out.println("Błędna opcja");
}
}
powrot = false;
break;
case 2:
powrot = true;
break;
default:
System.out.println("Błędna opcja");
}
}
powrot = false;
break;
case 3:
in.nextLine();
powrot = true;
break;
default:
System.out.println("Błędna opcja");
}
}
}
//###############################################################################################################333
else if(zmienna==2)
{
powrot = false;
String login="";
String haslo="";
while (login.equals(""))
{
System.out.println("Podaj login");
login = in.nextLine();
}
while (haslo.equals(""))
{
System.out.println("Podaj haslo");
haslo = in.nextLine();
}
student=new Student(login,haslo);
idUzyt = student.Zaloguj();
while((idUzyt == 0) && (powrot == false))
{
System.out.println("Naciśnij:\n 1 Jeśli chcesz spróbować ponownie,\n 2. Dla zmiany hasła,\n 3. Wyjście!");
zmienna = Integer.parseInt(in.nextLine());
if (zmienna == 1)
{
login = "";
haslo = "";
while (login.equals(""))
{
System.out.println("Podaj login");
login = in.nextLine();
}
while (haslo.equals(""))
{
System.out.println("Podaj haslo");
haslo = in.nextLine();
}
student = new Student(login, haslo);
}
else if (zmienna == 3)
{
powrot = true;
}
else if (zmienna == 2)
{
student.ZmienHaslo();
}
else
System.out.println("Brak opcji");
idUzyt = student.Zaloguj();
}
bazazapytania = new BazaZapytania();
System.out.println(idUzyt);
bazazapytania.wczytajPrzedmiotyDlaStudenta(1);
while(powrot == false)
{
System.out.println();
System.out.println("********************************************");
System.out.println("STUDENT id=" + idUzyt + "\n");
System.out.println("1. Zobacz swoje dane \n2. Zobacz liste przedmiotów \n3. Wyloguj");
System.out.print("Podaj opcje: ");
opcja = in.nextInt();
switch (opcja)
{
case 1:
System.out.println(student.toString(2));
break;
case 2:
while(!powrot)
{
System.out.println();
System.out.println("********************************************");
for (Przedmiot przedmiot: bazazapytania.przedmioty)
{
System.out.println(przedmiot.toString());
}
System.out.println("1. Sprawdź oceny z przedmiotu");
System.out.println("2. Sprawdź srednią z przedmiotu");
System.out.print("3. Powrot \nPodaj opcje:");
opcja = in.nextInt();
switch (opcja)
{
case 1:
System.out.print("Podaj id przedmiotu: ");
idPrzedmiotu = in.nextInt();
bazazapytania.wczytajOcenyStudentaZPrzedmiotu(idUzyt, idPrzedmiotu);
break;
case 2:
System.out.print("Podaj id przedmiotu: ");
idPrzedmiotu = in.nextInt();
bazazapytania.podajSredniaStudenta(idUzyt, idPrzedmiotu);
break;
case 3:
powrot = true;
break;
default:
System.out.println("Błędna opcja");
}
}
powrot = false;
break;
case 3:
in.nextLine();
powrot = true;
break;
default:
System.out.println("Błędna opcja");
}
}
}
else if (zmienna == 3)
{
bazazapytania= new BazaZapytania();
while (powrot == false) {
System.out.println();
System.out.println("********************************************");
System.out.println("Pracownik dziekantu\n");
System.out.println("1. Pokaż liste użytkowników");
System.out.println("2. Pokaż liste prowadzących");
System.out.println("3. Pokaż liste studentów");
System.out.println("4. Pokaż liste przedmitów");
System.out.println("5. Pokaż liste ocen");
System.out.println("6. Rejestracja nowego studenta");
System.out.println("7. Wyloguj");
System.out.print("Podaj opcje: ");
opcja = in.nextInt();
switch (opcja)
{
case 1:
bazazapytania.wypiszWszystkichProwadzacych();
bazazapytania.wypiszWszystkichStudentow();
break;
case 2:
bazazapytania.wypiszWszystkichProwadzacych();
break;
case 3:
bazazapytania.wypiszWszystkichStudentow();
break;
case 4:
bazazapytania.wypiszWszystkiePrzedmioty();
break;
case 5:
bazazapytania.wypiszWszystkieOceny();
break;
case 6:
in.nextLine();
List<String> dane = new ArrayList<String>();
System.out.println("Podaj login");
dane.add(in.nextLine());
System.out.println("Podaj haslo");
dane.add(in.nextLine());
System.out.println("Podaj pesel");
dane.add(in.nextLine());
System.out.println("Podaj imie");
dane.add(in.nextLine());
System.out.println("Podaj nazwisko");
dane.add(in.nextLine());
System.out.println("Podaj wydzial");
dane.add(in.nextLine());
System.out.println("Podaj kierunek");
dane.add(in.nextLine());
System.out.println("Podaj stopien studiow");
dane.add(in.nextLine());
System.out.println("Podaj nr semestru");
dane.add(in.nextLine());
student= new Student(dane.get(0), dane.get(1));
student.ustawDane(Integer.parseInt(dane.get(2)), dane.get(3), dane.get(4), dane.get(5), dane.get(6), Integer.parseInt(dane.get(7)), Integer.parseInt(dane.get(8)));
student.dodajPrzedmiot(1);student.dodajPrzedmiot(2);
student.dodajOcene(1);student.dodajOcene(2);student.dodajOcene(3);student.dodajOcene(4);
bazazapytania = new BazaZapytania();
bazazapytania.dodajStudenta(student);
break;
case 7:
powrot = true;
in.nextLine();
break;
default:
System.out.println("z opcja");
}
}
}
else
System.exit(0);
}
}
}
|
package com.example.ppolova.defender;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
public class GamePanel extends SurfaceView implements SurfaceHolder.Callback {
private MainThread thread;
private static GamePanel INSTANCE;
//rectangle to draw GAME OVER text into
private Rect r = new Rect();
private Player player;
private Point playerPoint;
private EnemyManager enemyManager;
private ScoreManager scoreManager;
private List<Star> stars = new ArrayList<Star>();
private List<Shot> shots = new ArrayList<Shot>();
private List<EnemyShot> enemyShots = new ArrayList<EnemyShot>();
//determines if user is moving the player
private boolean movingPlayer = false;
private boolean gameOver = false;
private long gameOverTime;
public String playerName;
public int difficulty;
public GamePanel(Context context) {
super(context);
INSTANCE = this;
getHolder().addCallback(this);
//sets current context
Constants.CURRENT_CONTEXT = context;
thread = new MainThread(getHolder(), this);
//spawn a player at the beginning and move it to proper location
player = new Player(new Rect(100, 100, 100+Player.WIDTH, 100+Player.HEIGHT), Color.rgb(96, 128, 145));
playerPoint = new Point(Constants.SCREEN_WIDTH/4, Constants.SCREEN_HEIGHT/2);
player.update(playerPoint);
enemyManager = new EnemyManager();
scoreManager = new ScoreManager(context);
// get user's name and selected difficulty
Preferencies preferencies = new Preferencies(context);
this.playerName = preferencies.getPlayerName();
this.difficulty = preferencies.getDifficulty();
// spawn stars
int numberOfStars = 100;
for (int i = 0; i < numberOfStars; i++) {
stars.add(new Star());
}
setFocusable(true);
}
public void gameOver() {
gameOver = true;
// if score is greater than 0, save it
if (player.getScore() > 0) {scoreManager.addData(playerName, player.getScore());}
gameOverTime = System.currentTimeMillis();
}
//reset the game after GAME OVER
public void reset() {
if (!gameOver) return;
enemyManager = new EnemyManager();
movingPlayer = false;
player.reset();
playerPoint = new Point(Constants.SCREEN_WIDTH/4, Constants.SCREEN_HEIGHT/2);
player.update(playerPoint);
shots.clear();
enemyShots.clear();
gameOver = false;
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
thread = new MainThread(getHolder(), this);
thread.setRunning(true);
thread.start();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
while(retry) {
try {
thread.setRunning(false);
thread.join();
} catch (Exception e) {
e.printStackTrace();
}
retry = false;
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
//game is running and user touched the Player
if (!gameOver && player.getTouchRectangle().contains((int)event.getX(), (int)event.getY())) {
movingPlayer = true;
} else if (!gameOver && (event.getX() > Constants.SCREEN_WIDTH/2)) {
Shot newShot = new Shot(player.getRectangle().right, player.getRectangle().centerY());
this.shots.add(newShot);
}
//game is over and 2 seconds passed
if (gameOver && System.currentTimeMillis() - gameOverTime >= 2000) {
reset();
}
break;
case MotionEvent.ACTION_MOVE:
if (!gameOver && movingPlayer)
if (event.getY() < 200) {
playerPoint.set(Constants.SCREEN_WIDTH/4, 200);
} else if (event.getY() > 9*(Constants.SCREEN_HEIGHT/10)) {
} else {
playerPoint.set(Constants.SCREEN_WIDTH / 4, (int) event.getY());
}
break;
case MotionEvent.ACTION_UP:
movingPlayer = false;
break;
}
return true;
}
public void update() {
if (!gameOver) {
for (Star star : stars) {
star.update();
}
for (Shot shot : shots) {
if (!shot.toBeDeleted) shot.update();
}
for (EnemyShot shot : enemyShots) {
if (!shot.toBeDeleted) shot.update();
}
if (player.getHealth() <= 0) {
gameOver();
}
// safely remove shots
ListIterator<Shot> iter = shots.listIterator();
while(iter.hasNext()){
if(iter.next().toBeDeleted){
iter.remove();
}
}
// safely remove enemy shots
ListIterator<EnemyShot> iter2 = enemyShots.listIterator();
while(iter2.hasNext()){
if(iter2.next().toBeDeleted){
iter2.remove();
}
}
player.update(playerPoint);
// if enemy collided with player, game is over
enemyManager.update();
if (enemyManager.playerCollision(player)) {
player.setHealth(0);
gameOver();
}
}
}
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
canvas.drawColor(Color.BLACK);
for (Star star : stars) {
star.draw(canvas);
}
for (Shot shot : shots) {
if (!shot.toBeDeleted) shot.draw(canvas);
}
for (EnemyShot shot : enemyShots) {
if (!shot.toBeDeleted) shot.draw(canvas);
}
player.draw(canvas);
enemyManager.draw(canvas);
if(gameOver) {
Paint paint = new Paint();
paint.setTextSize(100);
paint.setColor(Color.MAGENTA);
drawCenterText(canvas, paint, "GAME OVER");
paint.setTextSize(70);
drawBottomText(canvas, paint, "TAP OR SHAKE TO START AGAIN");
}
//draw score
Paint paint = new Paint();
paint.setTextSize(80);
paint.setColor(Color.MAGENTA);
canvas.drawText("Score: " + player.getScore(), 50, 50 + paint.descent() - paint.ascent(), paint);
canvas.drawText("Health: " + player.getHealth(), 700, 50 + paint.descent() - paint.ascent(), paint);
}
//draw text in the center of screen
private void drawCenterText(Canvas canvas, Paint paint, String text) {
paint.setTextAlign(Paint.Align.LEFT);
canvas.getClipBounds(r);
int cHeight = r.height();
int cWidth = r.width();
paint.getTextBounds(text, 0, text.length(), r);
float x = cWidth / 2f - r.width() / 2f - r.left;
float y = cHeight / 2f + r.height() / 2f - r.bottom;
canvas.drawText(text, x, y, paint);
}
private void drawBottomText(Canvas canvas, Paint paint, String text) {
paint.setTextAlign(Paint.Align.LEFT);
canvas.getClipBounds(r);
int cHeight = r.height();
int cWidth = r.width();
paint.getTextBounds(text, 0, text.length(), r);
float x = cWidth / 2f - r.width() / 2f - r.left;
float y = cHeight / 2f + r.height() / 2f - r.bottom + 150;
canvas.drawText(text, x, y, paint);
}
public EnemyManager getEnemyManager() {
return enemyManager;
}
public static GamePanel getInstance() {
return INSTANCE;
}
public Player getPlayer() {
return player;
}
public List<Shot> getShots() {
return shots;
}
public MainThread getThread() {
return thread;
}
public int getDifficulty() {
return this.difficulty;
}
public List<EnemyShot> getEnemyShots() {
return enemyShots;
}
}
|
package com.example.administrator.panda_channel_app.MVP_Framework.module.home.adapter;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.example.administrator.panda_channel_app.MVP_Framework.app.App;
import com.example.administrator.panda_channel_app.MVP_Framework.modle.biz.BaseModle;
import com.example.administrator.panda_channel_app.MVP_Framework.modle.entity.HomeDataBean;
import com.example.administrator.panda_channel_app.MVP_Framework.modle.entity.HomeData_viedeoBean;
import com.example.administrator.panda_channel_app.MVP_Framework.modle.entity.HomeLightChinaBean;
import com.example.administrator.panda_channel_app.MVP_Framework.network.callback.MyNetWorkCallback;
import com.example.administrator.panda_channel_app.MVP_Framework.utlis.ACache;
import com.example.administrator.panda_channel_app.R;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import static com.example.administrator.panda_channel_app.R.layout.home_fragment_item_interactive;
/**
* Created by Administrator on 2017/7/12 0012.
*/
public class HomeXrecyclerAdapter extends RecyclerView.Adapter implements ViewPager.OnPageChangeListener {
public interface setOnClickListener{
void setViwpagerListener(HomeDataBean.DataBean.BigImgBean imgbean);
void setWonderfulListener(HomeDataBean.DataBean.AreaBean.ListscrollBean wonderbean);
void setPandaeyeVideoListener(HomeData_viedeoBean.ListBean pandaeyebean);
void setPandaeyeoneListener(HomeDataBean.DataBean.PandaeyeBean.ItemsBean pandaeyebean);
void setPandaeyetwoListener(HomeDataBean.DataBean.PandaeyeBean.ItemsBean pandaeyebean);
void setPandaliveListener(HomeDataBean.DataBean.PandaliveBean.ListBean pandabean);
void setPangtwallliveListener(HomeDataBean.DataBean.WallliveBean.ListBeanX wallbean);
void setChinaliveListener(HomeDataBean.DataBean.ChinaliveBean.ListBeanXX bean);
void setInteractliveListener(HomeDataBean.DataBean.InteractiveBean.InteractiveoneBean interbean);
void setCctvliveListener(Home_CCTVBean.ListBean cctvbean);
void setLightChinaListener(HomeLightChinaBean.ListBean lightbean);
}
private setOnClickListener OnClickListener;
public void setOnClickListener(setOnClickListener OnClickListener){
this.OnClickListener=OnClickListener;
}
private ArrayList<Object> list;
private ArrayList<HomeDataBean> listdata;
private Context context;
private Timer timer;
private ViewPager viewPager;
private LinearLayout point_ratio;
private static final int layout_viewpager = 1,
layout_Wonderful = 2,
layout_report = 3,
layout_homePandalive = 4,
layout_homegtwalllive = 5,
layout_homechinalive = 6,
layout_interactive = 7,
layout_CCTVrecycler = 8,
layout_lightchina = 9;
private ArrayList<HomeData_viedeoBean.ListBean> listvideodata;
private ArrayList<HomeDataBean.DataBean.AreaBean.ListscrollBean> wonderful_list = new ArrayList<>();//精彩直播
private ArrayList<View> views = new ArrayList<>();//轮播视图
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 888:
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
break;
}
}
};
public HomeXrecyclerAdapter(ArrayList<Object> list, ArrayList<HomeData_viedeoBean.ListBean> listvideodata,ArrayList<HomeDataBean> listdata, Context context) {
this.list = list;
this.listvideodata = listvideodata;
this.context = context;
this.listdata=listdata;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder holder = null;
switch (viewType) {
case 1:
View viewapgerview = LayoutInflater.from(context).inflate(R.layout.home_fragment_item_viewpager, null);
holder=new ViewpagerViewHolder(viewapgerview);
break;
case 2:
View Wonderfulview = LayoutInflater.from(context).inflate(R.layout.home_fragment_item_wonderful, null);
holder=new WonderfulViewHolder(Wonderfulview);
break;
case 3:
View reportview = LayoutInflater.from(context).inflate(R.layout.home_fragment_item_report, null);
holder=new ReportViewHolder(reportview);
break;
case 4:
View pandaliveview = LayoutInflater.from(context).inflate(R.layout.home_fragment_item_pandalive, null);
holder=new PandaliveViewHolder(pandaliveview);
break;
case 5:
View gtwallliveview = LayoutInflater.from(context).inflate(R.layout.home_fragment_item_gtwalllive, null);
holder=new WallliveViewHolder(gtwallliveview);
break;
case 6:
View chinaliveview = LayoutInflater.from(context).inflate(R.layout.home_fragment_item_chinalive, null);
holder=new ChinaliveViewHolder(chinaliveview);
break;
case 7:
View interactiveview = LayoutInflater.from(context).inflate(home_fragment_item_interactive, null);
holder=new InteractiveViewHolder(interactiveview);
break;
case 8:
View cctvview = LayoutInflater.from(context).inflate(R.layout.home_fragment_item_cctv, null);
holder=new CCTVrecyclerViewHolder(cctvview);
break;
case 9:
View lightchinaview = LayoutInflater.from(context).inflate(R.layout.home_fragment_item_lightchina, null);
holder=new LightchinaViewHolder(lightchinaview);
break;
}
return holder;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
int type =getItemViewType(position);
switch (type){
case layout_viewpager:
ViewpagerViewHolder viewpagerViewHolder= (ViewpagerViewHolder) holder;
initviewpager(listdata.get(0).getData(),viewPager.getCurrentItem());
break;
case layout_Wonderful:
WonderfulViewHolder wondeholder= (WonderfulViewHolder) holder;
initWonderful(wondeholder);
break;
case layout_report:
ReportViewHolder reportholer = (ReportViewHolder) holder;
initreport(reportholer);
break;
case layout_homePandalive:
PandaliveViewHolder pandaliveholer= (PandaliveViewHolder) holder;
inithomePandalive(pandaliveholer,position);
break;
case layout_homegtwalllive:
WallliveViewHolder wallholder = (WallliveViewHolder) holder;
inithomegtwalllive(wallholder,position);
break;
case layout_homechinalive:
ChinaliveViewHolder chinaholder= (ChinaliveViewHolder) holder;
inithomechinalive(chinaholder,position);
break;
case layout_interactive:
InteractiveViewHolder interaholder= (InteractiveViewHolder) holder;
initinteractive(interaholder,position);
break;
case layout_CCTVrecycler:
CCTVrecyclerViewHolder cctvholder= (CCTVrecyclerViewHolder) holder;
initCCTVrecycler(cctvholder,position);
break;
case layout_lightchina:
LightchinaViewHolder lightholder= (LightchinaViewHolder) holder;
initlightchina(lightholder,position);
break;
}
}
private ArrayList<HomeLightChinaBean.ListBean> listlight=new ArrayList<>();
private void initlightchina(final LightchinaViewHolder viewHolder,int position) {
viewHolder.home_lightchina_name.setText(listdata.get(0).getData().getList().get(0).getTitle());
String url=listdata.get(0).getData().getList().get(0).getListUrl();
BaseModle.iHttp.get(url, null, new MyNetWorkCallback<HomeLightChinaBean>() {
@Override
public void Success(HomeLightChinaBean homeLightChinaBean) {
listlight.clear();
listlight.addAll(homeLightChinaBean.getList());
App.context.runOnUiThread(new Runnable() {
@Override
public void run() {
viewHolder.home_lightchina_recyclerview.setLayoutManager(new LinearLayoutManager(context));
Home_LightChina_RecyclerAdapter adapter =new Home_LightChina_RecyclerAdapter(listlight,context);
viewHolder.home_lightchina_recyclerview.setAdapter(adapter);
adapter.setOnClickListener(new Home_LightChina_RecyclerAdapter.setOnClickListener() {
@Override
public void setOnClickListener(View v, int position) {
OnClickListener.setLightChinaListener(listlight.get(position));
}
});
}
});
ACache aCacha=ACache.get(App.context);
aCacha.put(homeLightChinaBean.getClass().getSimpleName(),homeLightChinaBean);
}
@Override
public void onError(String errormsg) {
ACache aCache=ACache.get(App.context);
HomeLightChinaBean homeLightChinaBean = (HomeLightChinaBean) aCache.getAsObject("HomeLightChinaBean");
listlight.clear();
listlight.addAll(homeLightChinaBean.getList());
App.context.runOnUiThread(new Runnable() {
@Override
public void run() {
viewHolder.home_lightchina_recyclerview.setLayoutManager(new LinearLayoutManager(context));
Home_LightChina_RecyclerAdapter adapter =new Home_LightChina_RecyclerAdapter(listlight,context);
viewHolder.home_lightchina_recyclerview.setAdapter(adapter);
adapter.setOnClickListener(new Home_LightChina_RecyclerAdapter.setOnClickListener() {
@Override
public void setOnClickListener(View v, int position) {
OnClickListener.setLightChinaListener(listlight.get(position));
}
});
}
});
}
});
}
private ArrayList<Home_CCTVBean.ListBean> listcctv=new ArrayList<>();
private void initCCTVrecycler(final CCTVrecyclerViewHolder viewHolder,int position) {
BaseModle.iHttp.get(listdata.get(0).getData().getCctv().getListurl(), null, new MyNetWorkCallback<Home_CCTVBean>() {
@Override
public void Success(Home_CCTVBean home_cctvBean) {
listcctv.clear();
listcctv.addAll(home_cctvBean.getList());
App.context.runOnUiThread(new Runnable() {
@Override
public void run() {
viewHolder.home_cctv_name.setText(listdata.get(0).getData().getCctv().getTitle());
Home_CCTVrecyclerAdapter adapter =new Home_CCTVrecyclerAdapter(listcctv,context);
viewHolder.home_cctv_recyclerview.setLayoutManager(new GridLayoutManager(context,2));
viewHolder.home_cctv_recyclerview.setAdapter(adapter);
adapter.setOnClickListener(new Home_CCTVrecyclerAdapter.setOnClickListener() {
@Override
public void setOnClickListener(View v, int position) {
OnClickListener.setCctvliveListener(listcctv.get(position));
}
});
}
});
ACache aCacha=ACache.get(App.context);
aCacha.put(home_cctvBean.getClass().getSimpleName(), home_cctvBean);
}
@Override
public void onError(String errormsg) {
ACache aCache=ACache.get(App.context);
Home_CCTVBean home_cctvBean = (Home_CCTVBean) aCache.getAsObject("Home_CCTVBean");
listcctv.clear();
listcctv.addAll(home_cctvBean.getList());
App.context.runOnUiThread(new Runnable() {
@Override
public void run() {
viewHolder.home_cctv_name.setText(listdata.get(0).getData().getCctv().getTitle());
Home_CCTVrecyclerAdapter adapter =new Home_CCTVrecyclerAdapter(listcctv,context);
viewHolder.home_cctv_recyclerview.setLayoutManager(new GridLayoutManager(context,2));
viewHolder.home_cctv_recyclerview.setAdapter(adapter);
adapter.setOnClickListener(new Home_CCTVrecyclerAdapter.setOnClickListener() {
@Override
public void setOnClickListener(View v, int position) {
OnClickListener.setCctvliveListener(listcctv.get(position));
}
});
}
});
}
});
}
private void initinteractive(InteractiveViewHolder viewHolder, final int position) {
viewHolder.home_interactive_linear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
OnClickListener.setInteractliveListener(listdata.get(0).getData().getInteractive().getInteractiveone().get(0));
}
});
viewHolder.home_interactive_name.setText(listdata.get(0).getData().getInteractive().getTitle());
viewHolder.home_interactive_title.setText
(listdata.get(0).getData().getInteractive().getInteractiveone().get(0).getTitle());
Glide.with(context).load(listdata.get(0).getData().getInteractive().getInteractiveone().get(0).getImage()).into(viewHolder.home_interactive_img);
}
private void inithomechinalive(ChinaliveViewHolder viewHolder,int position) {
ArrayList<HomeDataBean.DataBean.ChinaliveBean.ListBeanXX> listBeen=new ArrayList<>();
listBeen.clear();
listBeen.addAll(listdata.get(0).getData().getChinalive().getList());
Homechinalive_recyclerAdapter adapter =new Homechinalive_recyclerAdapter(listBeen,context);
viewHolder.home_chinalive_recycler.setLayoutManager(new GridLayoutManager(context,3));
viewHolder.home_chinalive_recycler.setAdapter(adapter);
adapter.setOnClickListener(new Homechinalive_recyclerAdapter.setOnClickListener() {
@Override
public void setOnClickListener(View v, int position) {
OnClickListener.setChinaliveListener(listdata.get(0).getData().getChinalive().getList().get(position));
}
});
}
private void inithomegtwalllive(WallliveViewHolder viewHolder,int position) {
ArrayList<HomeDataBean.DataBean.WallliveBean.ListBeanX> listBeen=new ArrayList<>();
listBeen.clear();
listBeen.addAll(listdata.get(0).getData().getWalllive().getList());
Homegtwalllive_recyclerAdapter adapter =new Homegtwalllive_recyclerAdapter(listBeen,context);
viewHolder.home_gtwalllive_recycler.setLayoutManager(new GridLayoutManager(context,3));
viewHolder.home_gtwalllive_recycler.setAdapter(adapter);
adapter.setOnClickListener(new Homegtwalllive_recyclerAdapter.setOnClickListener() {
@Override
public void setOnClickListener(View v, int position) {
OnClickListener.setPangtwallliveListener(listdata.get(0).getData().getWalllive().getList().get(position));
}
});
}
private void inithomePandalive(PandaliveViewHolder viewHolder,int position) {
ArrayList<HomeDataBean.DataBean.PandaliveBean.ListBean> listBeen=new ArrayList<>();
listBeen.clear();
listBeen.addAll(listdata.get(0).getData().getPandalive().getList());
HomePandalive_recyclerAdapter adapter =new HomePandalive_recyclerAdapter(listBeen,context);
viewHolder.home_Pandalive_recycler.setLayoutManager(new GridLayoutManager(context,3));
viewHolder.home_Pandalive_recycler.setAdapter(adapter);
adapter.setOnClickListener(new HomePandalive_recyclerAdapter.setOnClickListener() {
@Override
public void setOnClickListener(View v, int position) {
OnClickListener.setPandaliveListener(listdata.get(0).getData().getPandalive().getList().get(position));
}
});
}
private void initvideorecycler(ReportViewHolder viewHolder) {
Home_panda_eye_videorecyclerAdapter adapter =new Home_panda_eye_videorecyclerAdapter(context,listvideodata);
viewHolder.home_panda_eye_videorecycler.setLayoutManager(new LinearLayoutManager(context));
viewHolder.home_panda_eye_videorecycler.setAdapter(adapter);
adapter.setOnClickListener(new Home_panda_eye_videorecyclerAdapter.setOnClickListener() {
@Override
public void setOnClickListener(View v, int position) {
OnClickListener.setPandaeyeVideoListener(listvideodata.get(position));
}
});
}
private void initWonderful(WonderfulViewHolder viewHolder) {
viewHolder.home_wonderful_recommend.setText(listdata.get(0).getData().getArea().getTitle());
Glide.with(context).load(listdata.get(0).getData().getArea().getImage()).into(viewHolder.home_wonderful_img);
LinearLayoutManager manager =new LinearLayoutManager(context);
manager.setOrientation(LinearLayoutManager.HORIZONTAL);
viewHolder.home_wonderful_recyclerview.setLayoutManager(manager);
Home_wonderful_recyclerviewAdapter adapter =new Home_wonderful_recyclerviewAdapter(wonderful_list,context);
adapter.setOnClickListener(new Home_wonderful_recyclerviewAdapter.setOnClickListener() {
@Override
public void setOnClickListener(View v, int position) {
OnClickListener.setWonderfulListener(listdata.get(0).getData().getArea().getListscroll().get(position));
}
});
viewHolder.home_wonderful_recyclerview.setAdapter(adapter);
}
private void initreport(ReportViewHolder viewHolder) {
wonderful_list.clear();
wonderful_list.addAll(listdata.get(0).getData().getArea().getListscroll());
viewHolder. home_report_onetx.setText(listdata.get(0).getData().getPandaeye().getItems().get(0).getBrief());
viewHolder.home_report_onecontent.setText(listdata.get(0).getData().getPandaeye().getItems().get(0).getTitle());
viewHolder.home_report_twotx.setText(listdata.get(0).getData().getPandaeye().getItems().get(1).getBrief());
viewHolder.home_report_twocontent.setText(listdata.get(0).getData().getPandaeye().getItems().get(1).getTitle());
viewHolder.tab_report.setText(listdata.get(0).getData().getPandaeye().getTitle());
Glide.with(context).load(listdata.get(0).getData().getPandaeye().getPandaeyelogo()).into(viewHolder.home_report_img);
initvideorecycler(viewHolder);
viewHolder.home_report_onecontent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
OnClickListener.setPandaeyeoneListener(listdata.get(0).getData().getPandaeye().getItems().get(0));
}
});
viewHolder.home_report_twocontent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
OnClickListener.setPandaeyetwoListener(listdata.get(0).getData().getPandaeye().getItems().get(1));
}
});
}
@Override
public int getItemCount() {
int num= list.size();
return num;
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
int newPosition = position % views.size();
for (int i = 0; i < listdata.get(0).getData().getBigImg().size(); i++) {
if (i == newPosition) {
// 就将i对应的点设置为选中状态,其他的点都设置成未选中状态
point_ratio.getChildAt(i).setBackgroundResource(
R.drawable.rotation_point_black);
} else {
point_ratio.getChildAt(i).setBackgroundResource(
R.drawable.rotation_point_white);
}
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
class ViewpagerViewHolder extends RecyclerView.ViewHolder{
public ViewpagerViewHolder(View itemView) {
super(itemView);
viewPager= (ViewPager) itemView.findViewById(R.id.home_viewpager);
point_ratio= (LinearLayout) itemView.findViewById(R.id.point_ratio);
}
}
class WonderfulViewHolder extends RecyclerView.ViewHolder{
RecyclerView home_wonderful_recyclerview;
TextView home_wonderful_recommend;
ImageView home_wonderful_img;
public WonderfulViewHolder(View itemView) {
super(itemView);
home_wonderful_recyclerview= (RecyclerView) itemView.findViewById(R.id.home_wonderful_recyclerview);
home_wonderful_img= (ImageView) itemView.findViewById(R.id.home_wonderful_img);
home_wonderful_recommend= (TextView) itemView.findViewById(R.id.home_wonderful_recommend);
}
}
class ReportViewHolder extends RecyclerView.ViewHolder{
TextView home_report_onetx,
home_report_onecontent,
home_report_twotx,
home_report_twocontent,
tab_report;
RecyclerView home_panda_eye_videorecycler;
ImageView home_report_img;
public ReportViewHolder(View itemView) {
super(itemView);
home_panda_eye_videorecycler= (RecyclerView) itemView.findViewById(R.id.home_panda_eye_videorecycler);
home_report_img= (ImageView) itemView.findViewById(R.id.home_report_img);
home_report_onetx= (TextView) itemView.findViewById(R.id.home_report_onetx);
home_report_onecontent= (TextView) itemView.findViewById(R.id.home_report_onecontent);
home_report_twotx= (TextView) itemView.findViewById(R.id.home_report_twotx);
home_report_twocontent= (TextView) itemView.findViewById(R.id.home_report_twocontent);
tab_report= (TextView) itemView.findViewById(R.id.tab_report);
}
}
class PandaliveViewHolder extends RecyclerView.ViewHolder{
RecyclerView home_Pandalive_recycler ;
TextView home_Pandalive_tv;
public PandaliveViewHolder(View itemView) {
super(itemView);
home_Pandalive_tv=(TextView) itemView.findViewById(R.id.home_Pandalive_tv);
home_Pandalive_recycler =(RecyclerView) itemView.findViewById(R.id.home_Pandalive_recycler);
}
}
class WallliveViewHolder extends RecyclerView.ViewHolder{
RecyclerView home_gtwalllive_recycler;
TextView home_gtwalllive_tv;
public WallliveViewHolder(View itemView) {
super(itemView);
home_gtwalllive_recycler=(RecyclerView) itemView.findViewById(R.id.home_gtwalllive_recycler);
home_gtwalllive_tv=(TextView) itemView.findViewById(R.id.home_gtwalllive_tv);
}
}
class ChinaliveViewHolder extends RecyclerView.ViewHolder{
RecyclerView home_chinalive_recycler;
TextView home_chinalive_tv;
public ChinaliveViewHolder(View itemView) {
super(itemView);
home_chinalive_recycler=(RecyclerView) itemView.findViewById(R.id.home_chinalive_recycler);
home_chinalive_tv=(TextView) itemView.findViewById(R.id.home_chinalive_tv);
}
}
class InteractiveViewHolder extends RecyclerView.ViewHolder{
LinearLayout home_interactive_linear;
TextView home_interactive_name,
home_interactive_title;
ImageView home_interactive_img;
public InteractiveViewHolder(View itemView) {
super(itemView);
home_interactive_linear= (LinearLayout) itemView.findViewById(R.id.home_interactive_linear);
home_interactive_img=(ImageView) itemView.findViewById(R.id.home_interactive_img);
home_interactive_name=(TextView) itemView.findViewById(R.id.home_interactive_name);
home_interactive_title=(TextView) itemView.findViewById(R.id.home_interactive_title);
}
}
class CCTVrecyclerViewHolder extends RecyclerView.ViewHolder{
RecyclerView home_cctv_recyclerview;
TextView home_cctv_name;
public CCTVrecyclerViewHolder(View itemView) {
super(itemView);
home_cctv_name= (TextView) itemView.findViewById(R.id.home_cctv_name);
home_cctv_recyclerview= (RecyclerView) itemView.findViewById(R.id.home_cctv_recyclerview);
}
}
class LightchinaViewHolder extends RecyclerView.ViewHolder{
RecyclerView home_lightchina_recyclerview;
TextView home_lightchina_name;
public LightchinaViewHolder(View itemView) {
super(itemView);
home_lightchina_recyclerview= (RecyclerView) itemView.findViewById(R.id.home_lightchina_recyclerview);
home_lightchina_name= (TextView) itemView.findViewById(R.id.home_lightchina_name);
}
}
private boolean flag=false;
private void initviewpager(final HomeDataBean.DataBean bean, final int position) {
Home_viewpager_Adapter home_viewpager_adapter =new Home_viewpager_Adapter(views);
viewPager.setAdapter(home_viewpager_adapter);
viewPager.setOnPageChangeListener(this);
views.clear();
point_ratio.removeAllViews();
for (int i=0;i<listdata.get(0).getData().getBigImg().size();i++){
View point_item =LayoutInflater.from(context).inflate(R.layout.point_item,null);
ImageView img = (ImageView) point_item.findViewById(R.id.point_img);
final int finalI = i;
img.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
OnClickListener.setViwpagerListener(bean.getBigImg().get(finalI));
}
});
TextView text= (TextView) point_item.findViewById(R.id.home_point_item_text);
text.setText(listdata.get(0).getData().getBigImg().get(i).getTitle());
Glide.with(context).load(listdata.get(0).getData().getBigImg().get(i).getImage()).into(img);
views.add(point_item);
View view_point=new View(context);
view_point.setBackgroundResource(R.drawable.rotation_point_black);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(20, 20);
lp.setMargins(20, 0, 0, 0);
point_ratio.addView(view_point, lp);
}
viewPager.setCurrentItem(10000);
if(timer==null) {
timer = new Timer();
}
if(task==null) {
task=new TimerTask() {
@Override
public void run() {
handler.sendEmptyMessage(888);
}
};
}
if(flag==false) {
timer.schedule(task, 4000, 4000);
flag=true;
}
}
private TimerTask task;
@Override
public int getItemViewType(int position) {
Object o =list.get(position);
if(o instanceof HomeDataBean.DataBean.BigImgBean) {
return 1;
}
else if(o instanceof HomeDataBean.DataBean.AreaBean) {
return 2;
}
else if(o instanceof HomeDataBean.DataBean.PandaeyeBean) {
return 3;
}
else if(o instanceof HomeDataBean.DataBean.PandaliveBean) {
return 4;
}
else if(o instanceof HomeDataBean.DataBean.WallliveBean) {
return 5;
}
else if(o instanceof HomeDataBean.DataBean.ChinaliveBean) {
return 6;
}
else if(o instanceof HomeDataBean.DataBean.InteractiveBean) {
return 7;
}
else if(o instanceof HomeDataBean.DataBean.CctvBean) {
return 8;
}
else if(o instanceof HomeDataBean.DataBean.ListBeanXXX) {
return 9;
}
return -1;
}
}
|
package com.example.vijaygarg.delagain.Activities;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import com.example.vijaygarg.delagain.Adapters.DisplayDeviceAdapter;
import com.example.vijaygarg.delagain.Model.DisplayModel;
import com.example.vijaygarg.delagain.Model.ObjectModel;
import com.example.vijaygarg.delagain.R;
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.ValueEventListener;
import java.util.ArrayList;
public class DisplayDevices extends AppCompatActivity {
RecyclerView rv;
ArrayList<DisplayModel>arr;
DatabaseReference databaseReference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_devices);
arr=new ArrayList<>();
rv=findViewById(R.id.displaydevice);
final DisplayDeviceAdapter displayDeviceAdapter=new DisplayDeviceAdapter(this,arr);
rv.setLayoutManager(new LinearLayoutManager(this));
rv.setAdapter(displayDeviceAdapter);
databaseReference= FirebaseDatabase.getInstance().getReference().child("display_request");
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dataSnapshot1:dataSnapshot.getChildren()){
DisplayModel displayModel=dataSnapshot1.getValue(DisplayModel.class);
if(displayModel.getRequest_result().equals("accept")&& displayModel.getIs_sold_out()==false){
arr.add(displayModel);
}
}
displayDeviceAdapter.notifyDataSetChanged();
databaseReference.removeEventListener(this);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
//todo databasereference work is pending
}
}
|
package com.appirio.api.member.util;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.IOUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;
import com.appirio.api.member.config.MemberConfiguration;
import com.appirio.api.member.model.User;
import com.appirio.automation.api.DefaultRequestProcessor;
import com.appirio.automation.api.DefaultResponse;
import com.appirio.automation.api.config.EnvironmentConfiguration;
import com.appirio.automation.api.exception.AutomationException;
import com.appirio.automation.api.exception.InvalidRequestException;
import com.appirio.automation.api.model.UserInfo;
import com.appirio.automation.api.service.AuthenticationService;
import com.appirio.automation.api.service.UserService;
import com.appirio.automation.api.util.ApiUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.NullNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
public class MemberUtil {
AuthenticationService authService = new AuthenticationService();
String jwtToken ="";
final static Logger logger = Logger.getLogger(MemberUtil.class);
UserService userService = new UserService();
/**
* Gets and loads json data file
* @param fileName
* @return jsonContents
*/
public String getFile(String fileName) {
String jsonContents = "";
ClassLoader classLoader = getClass().getClassLoader();
try {
jsonContents = IOUtils.toString(classLoader.getResourceAsStream(fileName));
} catch (IOException e) {
throw new AutomationException("Some error occurred while reading member.json "
+ e.getLocalizedMessage());
}
return jsonContents;
}
/**
* Generate jwt token(v3)
* @return headers
*/
public List<NameValuePair> getHeader()
{
authService = new AuthenticationService();
//Get v3 token
jwtToken=authService.getV3JWTToken();
List<NameValuePair> headers = new ArrayList<NameValuePair>();
headers.add(new BasicNameValuePair("Content-Type", "application/json"));
headers.add(new BasicNameValuePair("Authorization", "Bearer "+ jwtToken));
return headers;
}
/**
* Generate jwt token(v3) of specific user
* @param username
* @param password
* @return headers
*/
public List<NameValuePair> getHeader(String username,String password)
{
authService = new AuthenticationService();
//Get v3 token
jwtToken=authService.getV3JWTToken(username,password);
List<NameValuePair> headers = new ArrayList<NameValuePair>();
headers.add(new BasicNameValuePair("Content-Type", "application/json"));
headers.add(new BasicNameValuePair("Authorization", "Bearer "+ jwtToken));
return headers;
}
/**
* Generate jwt token(v2) of specific user
* @param username
* @param password
* @return headers
*/
public List<NameValuePair> getHeaderV2(String username,String password)
{
authService = new AuthenticationService();
//Get v3 token
jwtToken=authService.getAuth0JWTToken(username,password);
List<NameValuePair> headers = new ArrayList<NameValuePair>();
headers.add(new BasicNameValuePair("Content-Type", "application/json"));
headers.add(new BasicNameValuePair("Authorization", "Bearer "+ jwtToken));
return headers;
}
/**
* Generate jwt token(v2)
* @return headers
*/
public List<NameValuePair> getHeaderV2()
{
authService = new AuthenticationService();
//Get v3 token
jwtToken=authService.getAuth0JWTToken();
List<NameValuePair> headers = new ArrayList<NameValuePair>();
headers.add(new BasicNameValuePair("Content-Type", "application/json"));
headers.add(new BasicNameValuePair("Authorization", "Bearer "+ jwtToken));
return headers;
}
/**
* Get token from photo url in the response content.
* @param jsonObject
* @return token
*/
public String getTokenFromPhotoUrl(JsonNode jsonObject){
String token ="";
String jsonContentValue = jsonObject.path("result").path("content").textValue();
token = jsonContentValue.substring(jsonContentValue.indexOf("profile/"), jsonContentValue.indexOf(".jp"));
token=token.substring(token.lastIndexOf("-")+1);
return token;
}
/**
* Gets the profile of a specific member
* @param handle
* @param headers
* @return responseMetadata
*/
public DefaultResponse retrieveMemberProfile(String handle,List<NameValuePair> headers){
String retrieveMemberProfile = EnvironmentConfiguration.getBaseUrl()+MemberConfiguration.getRetrieveMemberProfileEndPoint();
retrieveMemberProfile = ApiUtil.replaceToken(retrieveMemberProfile,"@handle",handle);
DefaultResponse responseMetadata=DefaultRequestProcessor.getRequest(retrieveMemberProfile, null, headers);
return responseMetadata;
}
/**
* Updates the profile of a member using UserInfo object contain member data
* @param userInfo
* @param memberUpdateNode
* @return
*/
public DefaultResponse updateMemberProfile(UserInfo userInfo,JsonNode memberUpdateNode){
JsonNode memberNode = memberUpdateNode.get("param");
((ObjectNode)memberNode).put("firstName",userInfo.getfirstName());
((ObjectNode)memberNode).put("lastName",userInfo.getLastName());
((ObjectNode)memberNode).put("handle",userInfo.getUserName());
((ObjectNode)memberNode).put("email",userInfo.getEmail());
List<NameValuePair> headers = getHeader(userInfo.getUserName(),userInfo.getPassword());
String putMemberProfile = EnvironmentConfiguration.getBaseUrl()+MemberConfiguration.getMemberPutProfileEndPoint();
putMemberProfile= ApiUtil.replaceToken(putMemberProfile,"@handle",userInfo.getUserName());
DefaultResponse responseMetadata = DefaultRequestProcessor.putRequest(putMemberProfile, null, headers,memberUpdateNode.toString());
return responseMetadata;
}
/**
* Updates the profile of a member with specified data
* @param userDetails
* @param memberUpdateNode
* @return memberUpdateNode
* json object containing all the updated member details
*/
public JsonNode addUpdatedFieldsToMemberObj(JsonNode userDetails,JsonNode memberUpdateNode){
JsonNode memberNode = memberUpdateNode.path("param");
String userId = userDetails.path("param").path("userId").textValue();
String photoURL = userDetails.path("param").path("photoURL").textValue();
String firstName = userDetails.path("param").path("firstName").textValue();
String lastName = userDetails.path("param").path("lastName").textValue();
String handle = userDetails.path("param").path("handle").textValue();
String email = userDetails.path("param").path("email").textValue();
String otherLangName = userDetails.path("param").path("otherLangName").textValue();
String quote = userDetails.path("param").path("quote").textValue();
((ObjectNode)memberNode).put("userId",userId);
((ObjectNode)memberNode).put("firstName",firstName);
((ObjectNode)memberNode).put("lastName",lastName);
((ObjectNode)memberNode).put("handle",handle);
((ObjectNode)memberNode).put("email",email);
((ObjectNode)memberNode).put("otherLangName",otherLangName);
((ObjectNode)memberNode).put("quote",quote);
((ObjectNode)memberNode).put("photoURL",photoURL);
return memberUpdateNode;
}
/**
* Asserts the fields in member skill set got in the response contents
* @param skills
* @param handle
* @return result
*/
public boolean assertFieldsInMemberSkillSet(JsonNode skills,String handle){
Iterator<JsonNode> skillset = skills.elements();
boolean result = false;
while(skillset.hasNext()) {
JsonNode temp = skillset.next();
Iterator<String> skillTags =temp.fieldNames();
JsonNode field = null;
while(skillTags.hasNext()) {
String nodeFieldName = skillTags.next();
if(nodeFieldName.equalsIgnoreCase("tagName")){
field = temp.get(nodeFieldName);
if(!field.equals(NullNode.getInstance())){
result = true;
}
else{
logger.error("MemberUtil:assertFieldsInMemberSkillSet:Skills for member '"+handle+"' does not contain field 'tagName'");
return false;
}
}
else if(nodeFieldName.equalsIgnoreCase("sources")){
field = temp.get(nodeFieldName);
if(!field.equals(NullNode.getInstance())){
result = true;
}
else{
logger.error("MemberUtil:assertFieldsInMemberSkillSet:Skills for member '"+handle+"' does not contain field 'sources'");
return false;
}
}
else if(nodeFieldName.equalsIgnoreCase("score")){
field = temp.get(nodeFieldName);
if(!field.equals(NullNode.getInstance())){
result = true;
}
else{
logger.error("MemberUtil:assertFieldsInMemberSkillSet:Skills for member '"+handle+"' does not contain field 'score'");
return false;
}
}
else if(nodeFieldName.equalsIgnoreCase("hidden")){
field = temp.get(nodeFieldName);
if(!field.equals(NullNode.getInstance())){
result = true;
}
else{
logger.error("MemberUtil:assertFieldsInMemberSkillSet:Skills for member '"+handle+"' does not contain field 'hidden'");
return false;
}
}
}
}
return result;
}
/**
* Adds a node containing tagId and its value for 'hidden' field, to the skillset node
* @param skillsSet
* @param tagId
* @param hidden
* @return skillsSet
*/
public JsonNode addSkillTagIds(ObjectNode skillsSet,String tagId,String hidden) {
ObjectMapper mapper = new ObjectMapper();
ObjectNode hidden2 = mapper.createObjectNode();;
hidden2.put("hidden", hidden);
skillsSet.put(tagId,hidden2);
return skillsSet;
}
/**
* Constructs url parameters for member api endpoints where filter values are field names
* @param requestObject
* json object cointaining field names to used as filter parameters
* @return urlParameters
* List<NameValuePair> type object containing all parameters
*/
public List<NameValuePair> constructParameters(JsonNode requestObject) {
Iterator<String> fieldNames = requestObject.fieldNames();
List<NameValuePair> urlParameters=new ArrayList<NameValuePair>();
while(fieldNames.hasNext()) {
String filterValues="";
String fieldName = fieldNames.next();
if(fieldName.equalsIgnoreCase("fields"))
{
JsonNode jsonFilter=requestObject.get(fieldName);
Iterator<String> filterfieldNames = jsonFilter.fieldNames();
while(filterfieldNames.hasNext()) {
String filterFieldName=filterfieldNames.next();
filterValues=filterValues+filterFieldName+",";
}
filterValues=filterValues.substring(0, filterValues.lastIndexOf(","));
urlParameters.add(new BasicNameValuePair("fields",filterValues));
}
}
return urlParameters;
}
/**
* Checks if the response contents are as per the filter values and contain the specified field
* @param response
* response obtained by executing the query
* @param filterFieldName
* field name to be checked in the response contents
* @return
*/
public boolean assertFieldsAsFilterParams(DefaultResponse response,String filterFieldName){
JsonNode responseData = null;
List<JsonNode> responseContents = new ArrayList<JsonNode>();
String nodeFieldName;
if(response.getResponseContents()==null){
responseData=response.getResponseData();
responseContents.add(responseData.path("result").path("content"));
}
else
responseContents = response.getResponseContents();
for (JsonNode jsonNode : responseContents) {
Iterator<String> elements =jsonNode.fieldNames();
while(elements.hasNext()) {
nodeFieldName = elements.next();
if(nodeFieldName.equalsIgnoreCase(filterFieldName))
return true;
else
continue;
}
}
return false;
}
public Map<String,User> getUsers(JsonNode users) {
Map<String,User> usersMap = new HashMap<String,User>();
JsonNode existingUserNode = null;
Iterator<JsonNode> elements = users.elements();
while(elements.hasNext()) {
existingUserNode = elements.next();
JsonNode paramNode = existingUserNode.path("param");
User u = new User(paramNode.path("userId").textValue(),paramNode.path("username").textValue(),
paramNode.path("password").textValue());
usersMap.put(u.getUsername(),u);
}
return usersMap;
}
/**
* Creates test users
* @param usersNode
* @return newUsersMap
*/
public Map<String,UserInfo> createUsers(JsonNode usersNode) {
Iterator<JsonNode> iter = usersNode.elements();
JsonNode usersObject = null;
ArrayList<UserInfo> usersList = new ArrayList<UserInfo>();
Map<String,UserInfo> newUsersMap = new HashMap<String,UserInfo>();
while(iter.hasNext()) {
usersObject = iter.next();
UserInfo userInfo = userService.createAnActivatedUser(usersObject);
logger.debug("MemberTest:setUp:createUsers:User with Id " + userInfo.getUserId() + " created");
usersList.add(userInfo);
newUsersMap.put(userInfo.getUserName(), userInfo);
}
logger.debug("MemberUtil:createUsers: " + usersList.size() + " Users created!");
return newUsersMap;
}
/**
* Gets External Links Data of a specific member
* @param handle
* @return responseMetadata
*/
public List<JsonNode> getMemberExternalLinksData(String handle){
String getExternalLinksDataUrl = EnvironmentConfiguration.getBaseUrl()+MemberConfiguration.getMemberGetExternalLinksData();
getExternalLinksDataUrl = ApiUtil.replaceToken(getExternalLinksDataUrl,"@handle@",handle);
DefaultResponse responseMetadata=DefaultRequestProcessor.getRequest(getExternalLinksDataUrl, null, null);
return responseMetadata.getResponseContents();
}
/**
* Update External Link of a specific member
* @param handle
* @return responseMetadata
*/
public JsonNode updateMemberExternalLinksData(String handle,List<NameValuePair> headers, String payload){
String updateMemberExternalLinkUrl = EnvironmentConfiguration.getBaseUrl()+MemberConfiguration.getMemberUpdateExternalLink();
updateMemberExternalLinkUrl = ApiUtil.replaceToken(updateMemberExternalLinkUrl,"@handle@",handle);
DefaultResponse responseMetadata= DefaultRequestProcessor.postRequest(updateMemberExternalLinkUrl,null,headers,payload);
return responseMetadata.getResponseData();
}
/**
* Delete External Link of a specific member
* @param handle
* @return responseMetadata
*/
public JsonNode deleteMemberExternalLinksData(String handle,List<NameValuePair> headers, String externalLinkId){
String deleteMemberExternalLinkUrl = EnvironmentConfiguration.getBaseUrl()+MemberConfiguration.getMemberDeleteExternalLink();
deleteMemberExternalLinkUrl = ApiUtil.replaceToken(deleteMemberExternalLinkUrl,"@handle@",handle);
deleteMemberExternalLinkUrl = ApiUtil.replaceToken(deleteMemberExternalLinkUrl,"@externalLinkId@",externalLinkId);
DefaultResponse responseMetadata= DefaultRequestProcessor.deleteRequest(deleteMemberExternalLinkUrl, null, headers);
return responseMetadata.getResponseData();
}
}
|
package java.com.kaizenmax.taikinys_icl.pojo;
public class FarmerDetailsPojo {
public static final String FARMERDETAILS_TABLE_NAME = "farmerdetails";
public static final String FARMERDETAILS_COLUMN_ID = "id";
public static final String FARMERDETAILS_COLUMN_FARMER_NAME = "farmername";
public static final String FARMERDETAILS_COLUMN_FARMER_LAND = "farmerland";
public static final String FARMERDETAILS_COLUMN_FARMER_MOBILE = "farmermobile";
public static final String FARMERDETAILS_COLUMN_PROMO_FM_ID = "promofmid";
public static final String FARMERDETAILS_COLUMN_PROMO_DEMOL3Serial_ID = "demol3serialid";
private String farmerName;
private String farmerLand;
private String farmerMobile;
public String getFarmerName() {
return farmerName;
}
public void setFarmerName(String farmerName) {
this.farmerName = farmerName;
}
public String getFarmerLand() {
return farmerLand;
}
public void setFarmerLand(String farmerLand) {
this.farmerLand = farmerLand;
}
public String getFarmerMobile() {
return farmerMobile;
}
public void setFarmerMobile(String farmerMobile) {
this.farmerMobile = farmerMobile;
}
}
|
/*
* 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 caro;
import static caro.co.bcwidth;
import java.util.ArrayList;
import java.util.Random;
/**
*
* @author Admin-s
*/
public class Minimax1 {
int[] mangdiemtc = {0,3,24,192,1536,12288,98304};
int[] mangdiempn = {0,1,9,81,729,6561,59049};
// Hàm kiểm tra xem ô nào có thể đi được
public ArrayList<VT> cotheMoves(co c) {
int[][] o = c.getO();
ArrayList<VT> a = new ArrayList<VT>();
for (int i = 0; i < co.bcheight; i++) {
for (int j = 0; j < co.bcwidth; j++) {
if (o[i][j] == 0) {
VT click = new VT();
click.setHeight(i);
click.setWidth(j);
a.add(click);
}
}
}
return a;
}
//hàm kiểm tra win
public Boolean Find_Win(int[][] o, int player)
{
for (int i = 0; i < co.bcheight; i++)
{
for (int j = 0; j < co.bcwidth; j++)
{
//xét hàng ngang
try{
if (o[i][j] == player && o[i+1][j] == player && o[i+2][j] == player && o[i+3][j] == player && o[i+4][j] == player)
{
return true;
}
}catch(Exception e){
}
//xét hàng dọc
try{
if (o[i][j] == player && o[i][j+1] == player && o[i][j+2] == player && o[i][j+3] == player && o[i][j+4] == player)
{
return true;
}
}catch(Exception e){
}
//chéo từ trên xuống qua bên phải
try{
if (o[i][j] == player && o[i+1][j+1] == player && o[i+2][j+2] == player && o[i+3][j+3] == player && o[i+4][j+4] == player)
{
return true;
}
}catch(Exception e){
}
//chéo từ trên xuống qua bên trái
try{
if (o[i][j] == player && o[i-1][j+1] == player && o[i-2][j+2] == player && o[i-3][j+3] == player && o[i-4][j+4] == player)
{
return true;
}
}catch(Exception e){
}
}
}
return false;
}
//Hàm minimax
public int[] minimax(co c,int player,int[] vt) {
int DiemMax = 0;
int DiemPhongNgu = 0;
int DiemTanCong = 0;
VT vtbest = new VT();
//lưu lại bàn cờ
int[][] oco = c.getO();
if(player==2)
{
//lượt đi đầu tiên
if(!checktt(oco,player))
{
//nếu nước đi của người nằm viền 3 ô bên ngoài thì đánh ở giữa ngược lại đánh random xung quanh nước đi của người
if(vt[0]>3 && vt[0] < co.bcheight-3)
{
if(vt[1]>3 && vt[1] < co.bcwidth-3)
{
int[] ran = {-1,0,1};
Random r = new Random();
vtbest.setHeight(vt[0]+r.nextInt(ran.length)-1);
vtbest.setWidth(vt[1]+r.nextInt(ran.length)-1);
}
}
else
{
vtbest.setHeight(co.bcheight/2);
vtbest.setWidth(co.bcwidth/2);
}
} else
{
//tìm điểm cao nhất (Minimax)
for (int i = 0; i < co.bcheight; i++) {
for (int j = 0; j < co.bcwidth; j++) {
VT vitri = new VT();
vitri.setHeight(i);
vitri.setWidth(j);
//nếu nước cờ chưa có ai đánh và không bị cắt tỉa thì mới xét giá trị MinMax
if (oco[i][j] == 0 && !catTia(vitri,oco))
{
int DiemTam;
//nếu xung quanh nhiều quân ta thì điểm tấn công cao nếu nhiều quân địch điểm phòng ngự cao
DiemTanCong = duyetTC_Ngang(vitri,oco) + duyetTC_Doc(vitri,oco) + duyetTC_Sac(vitri,oco) + duyetTC_Huyen(vitri,oco);
DiemPhongNgu = duyetPN_Ngang(vitri,oco) + duyetPN_Doc(vitri,oco) + duyetPN_Sac(vitri,oco) + duyetPN_Huyen(vitri,oco);
if (DiemPhongNgu > DiemTanCong)
{
DiemTam = DiemPhongNgu;
}
else
{
DiemTam = DiemTanCong;
}
if (DiemMax < DiemTam)
{
DiemMax = DiemTam;
vtbest=vitri;
}
}
}
}
}
}
return new int[]{vtbest.getHeight(), vtbest.getWidth()};
}
//kiểm tra xem đã đánh ô nào chưa
public boolean checktt(int[][] o,int p){
for (int i = 0; i < co.bcheight; i++) {
for (int j = 0; j < co.bcwidth; j++) {
if(o[i][j]==p)
return true;
}
}
return false;
}
//cho bàn cờ về như ban đầu
public void resertma(int[][] o,int[][] ro){
for (int j = 0; j < co.bcheight; j++) {
for (int k = 0; k < co.bcwidth; k++) {
o[j][k] = ro[j][k];
}
}
}
// <editor-fold defaultstate="collapsed" desc=" Cắt tỉa Alpha betal ">
Boolean catTia(VT oCo,int[][] o)
{
//nếu cả 4 hướng đều không có nước cờ thì cắt tỉa
if (catTiaNgang(oCo,o) && catTiaDoc(oCo,o) && catTiaSac(oCo,o) && catTiaHuyen(oCo,o))
return true;
//chạy đến đây thì 1 trong 4 hướng vẫn có nước cờ thì không được cắt tỉa
return false;
}
Boolean catTiaNgang(VT oCo,int[][] o)
{
//duyệt bên phải
if (oCo.width <= co.bcwidth - 5)
for (int i = 1; i <= 4; i++)
if (o[oCo.height][oCo.width + i] != 0)//nếu có nước cờ thì không cắt tỉa
return false;
//duyệt bên trái
if (oCo.width >= 4)
for (int i = 1; i <= 4; i++)
if (o[oCo.height][oCo.width - i] != 0)//nếu có nước cờ thì không cắt tỉa
return false;
//nếu chạy đến đây tức duyệt 2 bên đều không có nước đánh thì cắt tỉa
return true;
}
Boolean catTiaDoc(VT oCo,int[][] o)
{
//duyệt phía giưới
if (oCo.height <= co.bcheight - 5)
for (int i = 1; i <= 4; i++)
if (o[oCo.height + i][oCo.width] != 0)//nếu có nước cờ thì không cắt tỉa
return false;
//duyệt phía trên
if (oCo.height >= 4)
for (int i = 1; i <= 4; i++)
if (o[oCo.height - i][oCo.width] != 0)//nếu có nước cờ thì không cắt tỉa
return false;
//nếu chạy đến đây tức duyệt 2 bên đều không có nước đánh thì cắt tỉa
return true;
}
Boolean catTiaSac(VT oCo,int[][] o)
{
//duyệt từ trên xuống
if (oCo.height <= co.bcheight - 5 && oCo.width >= 4)
for (int i = 1; i <= 4; i++)
if (o[oCo.height + i][oCo.width - i] != 0)//nếu có nước cờ thì không cắt tỉa
return false;
//duyệt từ giưới lên
if (oCo.width <= co.bcwidth - 5 && oCo.height >= 4)
for (int i = 1; i <= 4; i++)
if (o[oCo.height - i][oCo.width + i] != 0)//nếu có nước cờ thì không cắt tỉa
return false;
//nếu chạy đến đây tức duyệt 2 bên đều không có nước đánh thì cắt tỉa
return true;
}
Boolean catTiaHuyen(VT oCo,int[][] o)
{
//duyệt từ trên xuống
if (oCo.height <= co.bcheight - 5 && oCo.width <= co.bcwidth - 5)
for (int i = 1; i <= 4; i++)
if (o[oCo.height + i][oCo.width + i] != 0)//nếu có nước cờ thì không cắt tỉa
return false;
//duyệt từ giưới lên
if (oCo.width >= 4 && oCo.height >= 4)
for (int i = 1; i <= 4; i++)
if (o[oCo.height - i][oCo.width - i] != 0)//nếu có nước cờ thì không cắt tỉa
return false;
//nếu chạy đến đây tức duyệt 2 bên đều không có nước đánh thì cắt tỉa
return true;
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc=" Điểm tấn công ">
public int duyetTC_Ngang(VT oCo,int[][] o)
{
int DiemTanCong = 0;
int SoQuanTa = 0;
int SoQuanDichPhai = 0;
int SoQuanDichTrai = 0;
//đếm số khoản chống xung quanh có đủ để đánh thắng
int KhoangChong = 0;
//bên phải
for (int dem = 1; dem <= 4 && oCo.width < co.bcwidth - 5; dem++)
{
//nếu là quân ta cộng thêm vô quân ta và khoảng chống
if (o[oCo.height][oCo.width + dem] == 2)
{
//nếu là ô kế bên cộng thêm 37 vào điểm tấn công
if (dem == 1)
DiemTanCong += 37;
SoQuanTa++;
KhoangChong++;
}
else
//nếu là quân địch thì cộng cho quân địch và ngược lại cộng cho khoảng chống
if (o[oCo.height][oCo.width + dem] == 1)
{
SoQuanDichPhai++;
break;
}
else KhoangChong++;
}
//bên trái
for (int dem = 1; dem <= 4 && oCo.width > 4; dem++)
{
if (o[oCo.height][oCo.width - dem] == 2)
{
if (dem == 1)
DiemTanCong += 37;
SoQuanTa++;
KhoangChong++;
}
else
if (o[oCo.height][oCo.width - dem] == 1)
{
SoQuanDichTrai++;
break;
}
else KhoangChong++;
}
//khoảng chống không đủ tạo thành 5 nước thì không cộng điểm
if (SoQuanDichPhai > 0 && SoQuanDichTrai > 0 && KhoangChong < 4)
return 0;
DiemTanCong -= mangdiempn[SoQuanDichPhai + SoQuanDichTrai];
DiemTanCong += mangdiemtc[SoQuanTa];
return DiemTanCong;
}
//duyệt dọc
public int duyetTC_Doc(VT oCo,int[][] o)
{
int DiemTanCong = 0;
int SoQuanTa = 0;
int SoQuanDichTren = 0;
int SoQuanDichDuoi = 0;
int KhoangChong = 0;
//bên trên
for (int dem = 1; dem <= 4 && oCo.height > 4; dem++)
{
if (o[oCo.height - dem][oCo.width] == 2)
{
if (dem == 1)
DiemTanCong += 37;
SoQuanTa++;
KhoangChong++;
}
else
if (o[oCo.height - dem][oCo.width] == 1)
{
SoQuanDichTren++;
break;
}
else KhoangChong++;
}
//bên dưới
for (int dem = 1; dem <= 4 && oCo.height < co.bcheight - 5; dem++)
{
if (o[oCo.height + dem][oCo.width] == 2)
{
if (dem == 1)
DiemTanCong += 37;
SoQuanTa++;
KhoangChong++;
}
else
if (o[oCo.height + dem][oCo.width] == 1)
{
SoQuanDichDuoi++;
break;
}
else KhoangChong++;
}
//bị chặn 2 đầu khoảng chống không đủ tạo thành 5 nước
if (SoQuanDichTren > 0 && SoQuanDichDuoi > 0 && KhoangChong < 4)
return 0;
DiemTanCong -= mangdiempn[SoQuanDichTren + SoQuanDichDuoi];
DiemTanCong += mangdiemtc[SoQuanTa];
return DiemTanCong;
}
//sắc
public int duyetTC_Sac(VT oCo,int[][] o)
{
int DiemTanCong = 1;
int SoQuanTa = 0;
int SoQuanDichCheoTren = 0;
int SoQuanDichCheoDuoi = 0;
int KhoangChong = 0;
//sắc xuống
for (int dem = 1; dem <= 4 && oCo.width < co.bcwidth - 5 && oCo.height < co.bcheight - 5; dem++)
{
if (o[oCo.height + dem][oCo.width + dem] == 2)
{
if (dem == 1)
DiemTanCong += 37;
SoQuanTa++;
KhoangChong++;
}
else
if (o[oCo.height + dem][oCo.width + dem] == 1)
{
SoQuanDichCheoTren++;
break;
}
else KhoangChong++;
}
//sắc lên
for (int dem = 1; dem <= 4 && oCo.height > 4 && oCo.width > 4; dem++)
{
if (o[oCo.height - dem][oCo.width - dem] == 2)
{
if (dem == 1)
DiemTanCong += 37;
SoQuanTa++;
KhoangChong++;
}
else
if (o[oCo.height - dem][oCo.width - dem] == 1)
{
SoQuanDichCheoDuoi++;
break;
}
else KhoangChong++;
}
//bị chặn 2 đầu khoảng chống không đủ tạo thành 5 nước
if (SoQuanDichCheoTren > 0 && SoQuanDichCheoDuoi > 0 && KhoangChong < 4)
return 0;
DiemTanCong -= mangdiempn[SoQuanDichCheoTren + SoQuanDichCheoDuoi];
DiemTanCong += mangdiemtc[SoQuanTa];
return DiemTanCong;
}
//huyền
public int duyetTC_Huyen(VT oCo,int[][] o)
{
int DiemTanCong = 0;
int SoQuanTa = 0;
int SoQuanDichCheoTren = 0;
int SoQuanDichCheoDuoi = 0;
int KhoangChong = 0;
//huyền lên
for (int dem = 1; dem <= 4 && oCo.width < co.bcwidth - 5 && oCo.height > 4; dem++)
{
if (o[oCo.height - dem][oCo.width + dem] == 2)
{
if (dem == 1)
DiemTanCong += 37;
SoQuanTa++;
KhoangChong++;
}
else
if (o[oCo.height - dem][oCo.width + dem] == 1)
{
SoQuanDichCheoTren++;
break;
}
else KhoangChong++;
}
//huyền xuống
for (int dem = 1; dem <= 4 && oCo.width > 4 && oCo.height < co.bcheight - 5; dem++)
{
if (o[oCo.height + dem][oCo.width - dem] == 2)
{
if (dem == 1)
DiemTanCong += 37;
SoQuanTa++;
KhoangChong++;
}
else
if (o[oCo.height + dem][oCo.width - dem] == 1)
{
SoQuanDichCheoDuoi++;
break;
}
else KhoangChong++;
}
//bị chặn 2 đầu khoảng chống không đủ tạo thành 5 nước
if (SoQuanDichCheoTren > 0 && SoQuanDichCheoDuoi > 0 && KhoangChong < 4)
return 0;
DiemTanCong -= mangdiempn[SoQuanDichCheoTren + SoQuanDichCheoDuoi];
DiemTanCong += mangdiemtc[SoQuanTa];
return DiemTanCong;
}
// </editor-fold>
// <editor-fold defaultstate="collapsed" desc=" Điểm phòng ngự ">
public int duyetPN_Ngang(VT oCo,int[][] o)
{
int DiemPhongNgu = 0;
int SoQuanTaTrai = 0;
int SoQuanTaPhai = 0;
int SoQuanDich = 0;
int KhoangChongPhai = 0;
int KhoangChongTrai = 0;
Boolean ok = false;
for (int dem = 1; dem <= 4 && oCo.width < co.bcwidth - 5; dem++)
{
if (o[oCo.height][oCo.width + dem] == 1)
{
//nếu quân địch kế bên thì cộng thêm 9 điểm phòng ngự
if (dem == 1)
DiemPhongNgu += 9;
SoQuanDich++;
}
else
if (o[oCo.height][oCo.width + dem] == 2)
{
//nếu quân ta ở quá xa trừ 170
if (dem == 4)
DiemPhongNgu -= 170;
SoQuanTaTrai++;
break;
}
else
{
if (dem == 1)
ok = true;
KhoangChongPhai++;
}
}
//nếu quân địch có 3 đường liên tiếp mà chưa bị chặn - 200
if (SoQuanDich == 3 && KhoangChongPhai == 1 && ok)
DiemPhongNgu -= 200;
ok = false;
for (int dem = 1; dem <= 4 && oCo.width > 4; dem++)
{
if (o[oCo.height][oCo.width - dem] == 1)
{
if (dem == 1)
DiemPhongNgu += 9;
SoQuanDich++;
}
else
if (o[oCo.height][oCo.width - dem] == 2)
{
if (dem == 4)
DiemPhongNgu -= 170;
SoQuanTaPhai++;
break;
}
else
{
if (dem == 1)
ok = true;
KhoangChongTrai++;
}
}
if (SoQuanDich == 3 && KhoangChongTrai == 1 && ok)
DiemPhongNgu -= 200;
//nếu không đủ chỗ đánh thì trả về 0
if (SoQuanTaPhai > 0 && SoQuanTaTrai > 0 && (KhoangChongTrai + KhoangChongPhai + SoQuanDich) < 4)
return 0;
DiemPhongNgu -= mangdiemtc[SoQuanTaTrai + SoQuanTaPhai];
DiemPhongNgu += mangdiempn[SoQuanDich];
return DiemPhongNgu;
}
public int duyetPN_Doc(VT oCo,int[][] o)
{
int DiemPhongNgu = 0;
int SoQuanTaTrai = 0;
int SoQuanTaPhai = 0;
int SoQuanDich = 0;
int KhoangChongTren = 0;
int KhoangChongDuoi = 0;
Boolean ok = false;
//lên
for (int dem = 1; dem <= 4 && oCo.height > 4; dem++)
{
if (o[oCo.height - dem][oCo.width ] == 1)
{
if (dem == 1)
DiemPhongNgu += 9;
SoQuanDich++;
}
else
if (o[oCo.height - dem][oCo.width ] == 2)
{
if (dem == 4)
DiemPhongNgu -= 170;
SoQuanTaPhai++;
break;
}
else
{
if (dem == 1)
ok = true;
KhoangChongTren++;
}
}
if (SoQuanDich == 3 && KhoangChongTren == 1 && ok)
DiemPhongNgu -= 200;
ok = false;
//xuống
for (int dem = 1; dem <= 4 && oCo.height < co.bcheight - 5; dem++)
{
//gặp quân địch
if (o[oCo.height + dem][oCo.width ] == 1)
{
if (dem == 1)
DiemPhongNgu += 9;
SoQuanDich++;
}
else
if (o[oCo.height + dem][oCo.width ] == 2)
{
if (dem == 4)
DiemPhongNgu -= 170;
SoQuanTaTrai++;
break;
}
else
{
if (dem == 1)
ok = true;
KhoangChongDuoi++;
}
}
if (SoQuanDich == 3 && KhoangChongDuoi == 1 && ok)
DiemPhongNgu -= 200;
if (SoQuanTaPhai > 0 && SoQuanTaTrai > 0 && (KhoangChongTren + KhoangChongDuoi + SoQuanDich) < 4)
return 0;
DiemPhongNgu -= mangdiemtc[SoQuanTaTrai + SoQuanTaPhai];
DiemPhongNgu += mangdiempn[SoQuanDich];
return DiemPhongNgu;
}
public int duyetPN_Sac(VT oCo,int[][] o)
{
int DiemPhongNgu = 0;
int SoQuanTaTrai = 0;
int SoQuanTaPhai = 0;
int SoQuanDich = 0;
int KhoangChongTren = 0;
int KhoangChongDuoi = 0;
Boolean ok = false;
//lên
for (int dem = 1; dem <= 4 && oCo.height < co.bcheight - 5 && oCo.width < co.bcwidth - 5; dem++)
{
if (o[oCo.height + dem][oCo.width + dem] == 1)
{
if (dem == 1)
DiemPhongNgu += 9;
SoQuanDich++;
}
else
if (o[oCo.height + dem][oCo.width + dem] == 2)
{
if (dem == 4)
DiemPhongNgu -= 170;
SoQuanTaPhai++;
break;
}
else
{
if (dem == 1)
ok = true;
KhoangChongTren++;
}
}
if (SoQuanDich == 3 && KhoangChongTren == 1 && ok)
DiemPhongNgu -= 200;
ok = false;
//xuống
for (int dem = 1; dem <= 4 && oCo.height > 4 && oCo.width > 4; dem++)
{
if (o[oCo.height - dem][oCo.width - dem] == 1)
{
if (dem == 1)
DiemPhongNgu += 9;
SoQuanDich++;
}
else
if (o[oCo.height - dem][oCo.width - dem] == 2)
{
if (dem == 4)
DiemPhongNgu -= 170;
SoQuanTaTrai++;
break;
}
else
{
if (dem == 1)
ok = true;
KhoangChongDuoi++;
}
}
if (SoQuanDich == 3 && KhoangChongDuoi == 1 && ok)
DiemPhongNgu -= 200;
if (SoQuanTaPhai > 0 && SoQuanTaTrai > 0 && (KhoangChongTren + KhoangChongDuoi + SoQuanDich) < 4)
return 0;
DiemPhongNgu -= mangdiemtc[SoQuanTaPhai + SoQuanTaTrai];
DiemPhongNgu += mangdiempn[SoQuanDich];
return DiemPhongNgu;
}
public int duyetPN_Huyen(VT oCo,int[][] o)
{
int DiemPhongNgu = 0;
int SoQuanTaTrai = 0;
int SoQuanTaPhai = 0;
int SoQuanDich = 0;
int KhoangChongTren = 0;
int KhoangChongDuoi = 0;
Boolean ok = false;
//lên
for (int dem = 1; dem <= 4 && oCo.height > 4 && oCo.width < co.bcwidth - 5; dem++)
{
if (o[oCo.height - dem][oCo.width + dem] == 1)
{
if (dem == 1)
DiemPhongNgu += 9;
SoQuanDich++;
}
else
if (o[oCo.height - dem][oCo.width + dem] == 2)
{
if (dem == 4)
DiemPhongNgu -= 170;
SoQuanTaPhai++;
break;
}
else
{
if (dem == 1)
ok = true;
KhoangChongTren++;
}
}
if (SoQuanDich == 3 && KhoangChongTren == 1 && ok)
DiemPhongNgu -= 200;
ok = false;
//xuống
for (int dem = 1; dem <= 4 && oCo.height < co.bcheight - 5 && oCo.width > 4; dem++)
{
if (o[oCo.height + dem][oCo.width - dem] == 1)
{
if (dem == 1)
DiemPhongNgu += 9;
SoQuanDich++;
}
else
if (o[oCo.height + dem][oCo.width - dem] == 2)
{
if (dem == 4)
DiemPhongNgu -= 170;
SoQuanTaTrai++;
break;
}
else
{
if (dem == 1)
ok = true;
KhoangChongDuoi++;
}
}
if (SoQuanDich == 3 && KhoangChongDuoi == 1 && ok)
DiemPhongNgu -= 200;
if (SoQuanTaPhai > 0 && SoQuanTaTrai > 0 && (KhoangChongTren + KhoangChongDuoi + SoQuanDich) < 4)
return 0;
DiemPhongNgu -= mangdiemtc[SoQuanTaTrai + SoQuanTaPhai];
DiemPhongNgu += mangdiempn[SoQuanDich];
return DiemPhongNgu;
}
// </editor-fold>
}
|
package com.crud.mvc.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import com.crud.mvc.models.Emp;
public class EmployeeDao {
JdbcTemplate template;
public void setTemplate(JdbcTemplate template) {
this.template = template;
}
public void addEmployee(Emp employee) {
String sqlQuery = "insert into Employee(ID,name,salary,designation) " + "values("
+ Integer.valueOf(employee.getId()) + ",'" + employee.getName() + "',"
+ Integer.valueOf(employee.getSalary()) + ", '" + employee.getDesignation() + "')";
template.update(sqlQuery);
}
public List<Emp> getEmployees() {
return template.query("select * from Employee", new RowMapper<Emp>() {
public Emp mapRow(ResultSet rs, int row) throws SQLException {
Emp e = new Emp();
e.setId(Integer.toString(rs.getInt(1)));
e.setName(rs.getString(2));
e.setSalary(Float.toString(rs.getFloat(3)));
e.setDesignation(rs.getString(4));
return e;
}
});
}
public int delete(int id) {
String sqlQuery = "delete from Employee where id=" + id + "";
return template.update(sqlQuery);
}
public Emp getEmpById(int id) {
String sql = "select * from Employee where id=?";
return template.queryForObject(sql, new Object[] { id }, new BeanPropertyRowMapper<Emp>(Emp.class));
}
public int update(Emp employee) {
String sqlQuery = "update Employee set name='" + employee.getName() + "', salary=" + employee.getSalary()
+ ",designation='" + employee.getDesignation() + "' where id=" + employee.getId();
return template.update(sqlQuery);
}
}
|
package com.example.administrator.mytechnologyproject.model.parser;
import com.example.administrator.mytechnologyproject.model.BaseEntity;
import com.example.administrator.mytechnologyproject.model.PasswordRecover;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
/**
* Created by Administrator on 2016/9/26.
*/
public class ParserPasswordRecover {
public static PasswordRecover getPassword(String json) {
Gson gson = new Gson();
Type type = new TypeToken<BaseEntity<PasswordRecover>>() {
}.getType();
BaseEntity<PasswordRecover> entity = gson.fromJson(json, type);
return entity.getData();
}
}
|
package edu.kmi.primejavaC.JWC.View.Form;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.BoxLayout;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import java.awt.Color;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import com.sun.glass.events.WindowEvent;
import edu.kmi.primejavaC.JWC.Controller.FrontController;
import edu.kmi.primejavaC.JWC.Controller.Event.IdCheckEvent;
import edu.kmi.primejavaC.JWC.Controller.Event.SignUpEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class SignUp_Form extends Parent_Form{
private JTextField txtId;
private JPasswordField txtPwd;
private JPasswordField txtPwd_chk;
private Boolean Id_chk;
private Boolean Pw_chk;
/**
* Create the application.
*/
public SignUp_Form(FrontController control) {
super(550, 400, control);
setTitle("SignUpPage");
Id_chk = false;
Pw_chk = false;
//------------------컴포넌트 구성-------------------------------
JPanel signup_panel = new JPanel();
getContentPane().add(signup_panel, BorderLayout.CENTER);
signup_panel.setLayout(null);
JLabel lblNewLabel = new JLabel("Please fill out the details below!");
lblNewLabel.setBounds(96, 49, 332, 31);
lblNewLabel.setFont(new Font("Yu Gothic", Font.BOLD, 20));
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
signup_panel.add(lblNewLabel);
JLabel lblId = new JLabel("ID");
lblId.setHorizontalAlignment(SwingConstants.CENTER);
lblId.setFont(new Font("Yu Gothic UI Semilight", Font.PLAIN, 17));
lblId.setBounds(134, 128, 47, 24);
signup_panel.add(lblId);
JLabel lblPwd = new JLabel("PASSWORD");
lblPwd.setHorizontalAlignment(SwingConstants.CENTER);
lblPwd.setFont(new Font("Yu Gothic UI Semilight", Font.PLAIN, 17));
lblPwd.setBounds(77, 164, 104, 24);
signup_panel.add(lblPwd);
JLabel lblChk = new JLabel("PASSWORD_CHECK");
lblChk.setHorizontalAlignment(SwingConstants.CENTER);
lblChk.setFont(new Font("Yu Gothic UI Semilight", Font.PLAIN, 17));
lblChk.setBounds(27, 200, 154, 24);
signup_panel.add(lblChk);
txtId = new JTextField();
txtId.setFont(new Font("맑은 고딕", Font.PLAIN, 17));
txtId.setBounds(195, 128, 159, 24);
signup_panel.add(txtId);
txtId.setColumns(10);
txtPwd = new JPasswordField();
txtPwd.setFont(new Font("맑은 고딕", Font.PLAIN, 17));
txtPwd.setBounds(195, 164, 159, 24);
signup_panel.add(txtPwd);
txtPwd_chk = new JPasswordField();
txtPwd_chk.setFont(new Font("맑은 고딕", Font.PLAIN, 17));
txtPwd_chk.setBounds(195, 202, 159, 24);
signup_panel.add(txtPwd_chk);
JButton txtChk = new JButton("ID Check");
txtChk.setBounds(379, 129, 105, 27);
signup_panel.add(txtChk);
JTextArea txtPwdChk = new JTextArea();
txtPwdChk.setLineWrap(true);
txtPwdChk.setRows(3);
txtPwdChk.setFont(new Font("굴림", Font.PLAIN, 15));
txtPwdChk.setBackground(UIManager.getColor("Label.background"));
txtPwdChk.setEditable(false);
txtPwdChk.setForeground(new Color(255, 0, 0));
txtPwdChk.setText("Please enter your password.");
txtPwdChk.setBounds(368, 167, 127, 60);
signup_panel.add(txtPwdChk);
JButton btnSignUp = new JButton("SignUp");
btnSignUp.setEnabled(false);
btnSignUp.setBounds(219, 256, 105, 27);
signup_panel.add(btnSignUp);
//-------------컴포넌트 구성 end----------------------
//-------------이벤트 등록------------------------
//id 중복체크
IdCheckEvent id_chk = new IdCheckEvent(this);
txtChk.addActionListener(id_chk);
//id textBox 입력 시, id 중복 체크 리스너의 id 필드 초기화하는 이벤트
txtId.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void keyPressed(KeyEvent e) {}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
id_chk.setId(txtId.getText());
}
});
//입력된 비밀번호가 같은지 확인하는 이벤트
txtPwd.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void keyPressed(KeyEvent e) {}
@Override
public void keyReleased(KeyEvent e) {
String pwd = new String(txtPwd.getPassword(), 0, txtPwd.getPassword().length);
String pwd_2 = new String(txtPwd_chk.getPassword(), 0, txtPwd_chk.getPassword().length);
if(pwd.length() == 0 && pwd_2.length() == 0){
txtPwdChk.setForeground(new Color(255, 0, 0));
txtPwdChk.setText("Please enter your password.");
Pw_chk = false;
btnSignUp.setEnabled(false);
}
else if(!(pwd.equals(pwd_2))){
txtPwdChk.setForeground(new Color(255, 0, 0));
txtPwdChk.setText("Passwords do not match.");
Pw_chk = false;
btnSignUp.setEnabled(false);
}
else{
txtPwdChk.setForeground(new Color(0, 0, 255));
txtPwdChk.setText("Password available.");
Pw_chk = true;
if(Id_chk == true && Pw_chk == true){
btnSignUp.setEnabled(true);
}
}
}
});
//입력된 비밀번호가 같은지 확인하는 이벤트
txtPwd_chk.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void keyPressed(KeyEvent e) {}
@Override
public void keyReleased(KeyEvent e) {
String pwd = new String(txtPwd.getPassword(), 0, txtPwd.getPassword().length);
String pwd_2 = new String(txtPwd_chk.getPassword(), 0, txtPwd_chk.getPassword().length);
if(pwd.length() == 0 && pwd_2.length() == 0){
txtPwdChk.setForeground(new Color(255, 0, 0));
txtPwdChk.setText("Please enter your password.");
Pw_chk = false;
btnSignUp.setEnabled(false);
}
else if(!(pwd.equals(pwd_2))){
txtPwdChk.setForeground(new Color(255, 0, 0));
txtPwdChk.setText("Passwords do not match.");
Pw_chk = false;
btnSignUp.setEnabled(false);
}
else{
txtPwdChk.setForeground(new Color(0, 0, 255));
txtPwdChk.setText("Password available.");
Pw_chk = true;
if(Id_chk == true && Pw_chk == true){
btnSignUp.setEnabled(true);
}
}
}
});
//회원 가입 버튼
btnSignUp.addActionListener(new SignUpEvent(this));
//--------------이벤트 등록 end----------------------
}
public void setId_chk(Boolean id_chk) {
Id_chk = id_chk;
}
//입력된 id와 pw를 반환하는 함수
//회원 가입 버튼 클릭 시 호출되는 함수 use ( SignUpEvent.class )
public String[] join(){
String info[] = {new String(txtId.getText()), new String(txtPwd.getPassword(), 0, txtPwd.getPassword().length)};
return info;
}
}
|
package com.durgam.guerra.servicio;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.LockModeType;
import javax.persistence.PersistenceContext;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.StaleObjectStateException;
import org.hibernate.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import com.durgam.guerra.dominio.GestionRequisito;
import com.durgam.guerra.dominio.Proyecto;
import com.durgam.guerra.dominio.Requisito;
import com.durgam.guerra.repositorio.RepositorioGestionRequisito;
//import com.durgam.guerra.dominio.RequisitoCompuesto;
//import com.durgam.guerra.dominio.RequisitoSimple;
import com.durgam.guerra.repositorio.RepositorioProyecto;
@Service
@Repository
public class ServicioProyecto {
@Autowired
private RepositorioProyecto repositorioProyecto;
@Autowired
private ServicioGestionRequisito servicioGestionRequisito;
@PostConstruct // La anotación PostConstruct se utiliza en un método que
// debe ejecutarse tras una inyección de dependencia para
// efectuar cualquier inicialización
@Transactional
public void populate() {
// GestionRequisito app= GestionRequisito.getSistema();
// System.out.println("Creando Proyectos en la Base de Datos");
// Proyecto proyecto1 = new Proyecto ("Proyecto 1", "Cambio de version
// de BBDD");
// Proyecto proyecto2 = new Proyecto ("Proyecto 2", "Proyecto
// Semaforos");
// Proyecto proyecto3 = new Proyecto ("Proyecto 3", "Sistema Contable");
// proyecto1.agregarRequisito(new RequisitoSimple(0,
// "Req1Proy1","Tensión Arterial","Media","Deshidratación", null));
// proyecto1.agregarRequisito(new RequisitoSimple(0, "Req2Proy1","Cierre
// Automatico de Puertas","Alta","Suministro Electrico Interrumpido",
// null));
// proyecto2.agregarRequisito(new RequisitoSimple(0,
// "Req1Proy2","Despachar Cajero Automatico","Media","Seguridad de
// Cierre", null));
// proyecto2.agregarRequisito(new RequisitoSimple(0,
// "Req2Proy2","Desemcriptar Llave Bancaria","Alta","Sobrecarga
// Algoritmica", null));
// proyecto3.agregarRequisito(new RequisitoSimple(0, "Req1Proy3","Mayor
// Productividad","Alta","Costo de Oportunidad", null));
// proyecto3.agregarRequisito(new RequisitoSimple(0, "Req2Proy3","Menor
// tiempo de Respuesta","Media","Latencia ente request", null));
// app.agregarProyecto(proyecto1);
// app.agregarProyecto(proyecto2);
// app.agregarProyecto(proyecto3);
// RequisitoSimple req1 = new RequisitoSimple(0, "Req1","Mantener
// Cartera Clientes","Alta","Costo de Oportunidad", null);
// RequisitoSimple req2 = new RequisitoSimple(0, "Req2","Minimizar
// tiempo de respusta de atencion","Media","Fidelidad del Cliente",
// null);
// RequisitoSimple req3 = new RequisitoSimple(0, "Req3","Movimientos de
// Expedientes","Baja","Costos de Papeleo", null);
// RequisitoSimple req4 = new RequisitoSimple(0, "Req4","Provision de
// Medicamentos","Alta","Alta disponibilidad de entrega", null);
// Proyecto proyecto4 = new Proyecto ("Proyecto 4", "Cambio de version
// de BBDD");
// proyecto4.agregarRequisito(req1);
// proyecto4.agregarRequisito(req2);
// proyecto4.agregarRequisito(req3);
// proyecto4.agregarRequisito(req4);
// proyecto4.agregarRequisito(new RequisitoSimple(0,
// "Req1Proy1","Tensión Arterial","Media","Deshidratación", null));
// proyecto4.agregarRequisito(new RequisitoSimple(0, "Req2Proy1","Cierre
// Automatico de Puertas","Alta","Suministro Electrico Interrumpido",
// null));
// RequisitoSimple reqComp1= new RequisitoSimple(0,
// "ReqSimple1Compu1","Reducir Tiempo de Entrega","Alta","Nueva
// Tecnologia", null);
// RequisitoSimple reqComp2= new RequisitoSimple(0,
// "ReqSimple2Compu1","Reubicacion de Personal","Media","Profesionales
// Capacitados", null);
// RequisitoSimple reqComp3= new RequisitoSimple(0,
// "ReqSimple3Compu1","Mayor Cartera de Clientes","Alta","Inversores de
// Corto plazo", null);
// RequisitoCompuesto compuesto1= new RequisitoCompuesto(0,
// "ComReq1","Reducir tiempo de Desarrollo","Muy Alta","Comunicación
// Insuficiente",null);
// compuesto1.agregar(reqComp1);
// compuesto1.agregar(reqComp2);
// compuesto1.agregar(reqComp3);
// proyecto4.agregarRequisito(compuesto1);
// app.agregarProyecto(proyecto4);
}
@Transactional
public List<Proyecto> obtenerTodosLosProyectos() {
return repositorioProyecto.findAll();
}
@Transactional
public void borrarProyecto(Proyecto proyecto) {
GestionRequisito gestionRequisito = (servicioGestionRequisito.buscarGestionRequisitoPorId((long) 1));
gestionRequisito=servicioGestionRequisito.removerProyecto(gestionRequisito, proyecto);
}
@Transactional
public void borrarProyectoId(Long id) {
Proyecto proyecto=this.buscarProyectoPorId(id);
this.borrarProyecto(proyecto);
}
@Transactional
public void grabarProyecto(Proyecto proyecto) {
// Graba un proyecto nuevo y actualizar uno existente
// busca el proyecto, si existe lo actualiza
// si no existe lo crea
GestionRequisito gestionRequisito = (servicioGestionRequisito.buscarGestionRequisitoPorId((long) 1));
if (proyecto.getId()==null){
gestionRequisito=servicioGestionRequisito.agregarProyecto(gestionRequisito, proyecto);
}else {
if (repositorioProyecto.exists(proyecto.getId())) {
Proyecto proyectoExistente = repositorioProyecto.findOne(proyecto.getId());
proyectoExistente=this.actualizarProyecto(proyectoExistente, proyecto);
//Para probar la concurrencia
for (int i=0;i<100000;i++){
System.out.println(i);
}
}
}
servicioGestionRequisito.GrabarGestionRequisito(gestionRequisito);
}
@Transactional
public Proyecto NuevoProyecto() {
return new Proyecto();
}
@Transactional
public Proyecto buscarProyectoPorId(Long id) {
return repositorioProyecto.findOne(id);
}
@Transactional
public Proyecto actualizarProyecto(Proyecto proyecto, Proyecto proyectoActual){
proyecto.setNombreProyecto(proyectoActual.getNombreProyecto());
proyecto.setDescripcionProyecto(proyectoActual.getDescripcionProyecto());
return proyecto;
}
@Transactional
public void agregarRequisito(Proyecto proyecto, Requisito requisito) {
proyecto.getRequisitos().add(requisito);
requisito.setProyecto(proyecto);
}
}
|
package org.sealoflove.zero.three;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.sealoflove.Task;
public class Task033 implements Task {
Map<Integer, Set<Integer>> mulToDiv = new HashMap<>();
int limit;
private void populateMaps(int limit) {
for (int i = 1; i < limit; i++) {
for (int j = i; j < limit; j++) {
if (i * j < limit) {
if (!mulToDiv.containsKey(i * j)) {
mulToDiv.put(i * j, new HashSet<>());
}
mulToDiv.get(i * j).add(i);
mulToDiv.get(i * j).add(j);
}
}
}
}
int findLargestCommonDenominator(int a, int b) {
Set<Integer> denominators = new HashSet<>();
if (a > 100 || b > 100) {
//do it the stupid, old-fashioned way
for (int i = 1; i <= a; i++) {
if ((a % i == 0) && (b % i == 0))
denominators.add(i);
}
} else {
for (Integer den : mulToDiv.get(a)) {
if (mulToDiv.get(b).contains(den)) {
denominators.add(den);
}
}
}
int max = 0;
for (Integer den : denominators) {
if (den > max)
max = den;
}
return max;
}
class Fraction implements Comparable<Fraction>{
final Integer num;
final Integer den;
Fraction prod(Fraction o) {
return new Fraction(num * o.num, den * o.den);
}
Fraction simplified() {
int commonDen = findLargestCommonDenominator(num, den);
return new Fraction(num / commonDen, den / commonDen);
}
public Fraction(String input) {
this.num = Integer.parseInt(input.substring(0, input.indexOf('/')));
this.den = Integer.parseInt(input.substring(input.indexOf('/') + 1));
}
//stupid simplify: 14/48 would become 1/8
Fraction stupid() {
int[] numbers = new int[10];
numbers[num % 10]++;
numbers[num / 10]++;
numbers[den % 10]++;
numbers[den / 10]++;
for (char i = '0'; i <= '9'; i++) {
if (numbers[i - '0'] == 2) {
String newfr = this.toString().replaceAll("" + i, "");
return new Fraction(newfr);
}
}
return this;
}
public Fraction(int num, int den) {
if (den == 0)
throw new ArithmeticException("division by 0");
this.num = num;
this.den = den;
}
@Override
public int compareTo(Fraction o) {
return num * o.den - o.num * den;
}
@Override
public boolean equals(Object o) {
return this.compareTo((Fraction)o) == 0;
}
@Override
public String toString() {
return String.format("%d/%d", num, den);
}
}
private int generateCombos() {
Fraction prod = new Fraction(1, 1);
for (int i = 10; i < 99; i++) {
for (int j = i + 1; j <= 99; j++) {
Fraction fr = new Fraction(i, j);
try {
if (fr.stupid().equals(fr) && fr.stupid().toString().length() < fr.toString().length()
&& (fr.den * fr.num % 100 != 0)) {
System.out.println(fr + "|" + fr.stupid());
prod = prod.prod(fr);
}
} catch (NumberFormatException exc) {
//for cases like 11/22 -> too much hassle to exclude those cases, just catch the exc
}
}
}
System.out.println(prod);
return prod.simplified().den;
}
@Override
public String getResult() {
this.limit = 100;
populateMaps(limit);
return String.format("%d", generateCombos());
}
} |
package com.epam.university.spring.model;
import com.epam.university.spring.domain.Show;
import com.epam.university.spring.domain.User;
public class BirthdayDiscountStrategy implements DiscountStrategy {
public Long execute(User user, Show entry) {
int showDay = entry.getTime().getDayOfMonth();
int birthDay = user.getBirthday().getDate();
int showMonth = entry.getTime().getMonthOfYear();
int birthMonth = user.getBirthday().getMonth() + 1;
if (showDay == birthDay && showMonth == birthMonth) {
return 5L;
} else {
return 0L;
}
}
}
|
package com.netcracker.app.domain.info.services.contacts;
import com.netcracker.app.domain.info.entities.contacts.ContactsImpl;
import com.netcracker.app.domain.info.repositories.contacts.ContactsImplRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class ContactsServiceImpl extends AbstractContactsService<ContactsImpl> {
private ContactsImplRepository repository;
@Autowired
public ContactsServiceImpl(ContactsImplRepository repository) {
super(repository);
this.repository = repository;
}
public void updateAddress(String address, int id) throws Exception {
if (repository.existsById(id) && address != null) {
ContactsImpl companyInfo = repository.getOne(id);
companyInfo.setAddress(address);
repository.saveAndFlush(companyInfo);
}
}
public void updatePhone(String phone, int id) {
if (repository.existsById(id) && phone != null) {
ContactsImpl companyInfo = repository.getOne(id);
companyInfo.setPhone(phone);
repository.saveAndFlush(companyInfo);
}
}
public void updateWorkHours(String workHours, int id) {
if (repository.existsById(id) && workHours != null) {
ContactsImpl companyInfo = repository.getOne(id);
companyInfo.setWorkHours(workHours);
repository.saveAndFlush(companyInfo);
}
}
}
|
package com.pisen.ott.launcher.widget.slide;
import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.LinearLayout;
import com.pisen.ott.launcher.base.OttBaseActivity;
/**
* 自动收缩菜单栏
*
* @author yangyp
* @version 1.0, 2015年1月22日 下午4:51:25
*/
public abstract class MenuLayout extends LinearLayout implements OnFocusChangeListener, OnClickListener {
private int enterAnim;
private int exitAnim;
public MenuLayout(Context context, AttributeSet attrs, int enter, int exit) {
super(context, attrs);
this.enterAnim = enter;
this.exitAnim = exit;
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
setDefaultFocusedChild(this);
}
protected void setDefaultFocusedChild(View view) {
if (view.isShown()){
if (view instanceof ViewGroup) {
ViewGroup layout = (ViewGroup) view;
for (int i = 0, N = layout.getChildCount(); i < N; i++) {
View child = layout.getChildAt(i);
setDefaultFocusedChild(child);
}
} else {
if (view.isFocusable()) {
view.setOnFocusChangeListener(this);
view.setOnClickListener(this);
}
}
}
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
return executeKeyEvent(event) || super.dispatchKeyEvent(event);
}
public boolean executeKeyEvent(KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (event.getKeyCode()) {
case KeyEvent.KEYCODE_BACK:
hideMenu();
break;
}
}
return false;
}
/**
* 是否显示
*
* @return
*/
public boolean isVisible() {
return getVisibility() == View.VISIBLE;
}
public Boolean toggleMenu() {
if (isVisible()) {
hideMenu();
return false;
} else {
showMenu();
return true;
}
}
/**
* 显示菜单
*/
public void showMenu() {
if (isEnabled()) {
if (getVisibility() != View.VISIBLE) {
setVisibility(View.VISIBLE);
requestFocus();
startAnimation(AnimationUtils.loadAnimation(getContext(), enterAnim));
}
}
}
/**
* 隐藏菜单
*/
public void hideMenu() {
if (getVisibility() == View.VISIBLE) {
Context context = getContext();
if (context instanceof OttBaseActivity) {
((OttBaseActivity) context).requestContentFocus();
}
setVisibility(View.GONE);
startAnimation(AnimationUtils.loadAnimation(getContext(), exitAnim));
}
}
/**
* 隐藏菜单(不带动画)
*/
public void hideMenuWithOutAnimation() {
if (getVisibility() == View.VISIBLE) {
Context context = getContext();
if (context instanceof OttBaseActivity) {
((OttBaseActivity) context).requestContentFocus();
}
setVisibility(View.GONE);
}
}
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
if (findFocus() == null) {
// hideMenu();
}
}
}
@Override
public void onClick(View v) {
onItemClick(v);
}
public void onItemClick(View v) {
}
}
|
package br.com.zolp.estudozolp.configuration;
//
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.context.annotation.PropertySource;
//import org.springframework.core.env.Environment;
//import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
//import org.springframework.jndi.JndiTemplate;
//import org.springframework.orm.jpa.JpaTransactionManager;
//import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
//import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
//import org.springframework.transaction.PlatformTransactionManager;
//import org.springframework.transaction.annotation.EnableTransactionManagement;
//
//import javax.naming.NamingException;
//import javax.sql.DataSource;
//import java.util.Properties;
//
///**
// * Classe responsavel por efetuar a configuracao do repositorio.
// *
// * @author mamede
// * @version 0.0.1-SNAPSHOT
// */
//@Configuration
//@EnableTransactionManagement
//@EnableJpaRepositories(
// basePackages = "br.com.zolp.estudozolp.repository",
// entityManagerFactoryRef = "repositoryZolpEntityManager",
// transactionManagerRef = "repositoryZolpTransactionManager"
//)
//@PropertySource({"classpath:database.properties"})
public class RepositoryZolpConfig {
// @Autowired
// private Environment env;
//
// /**
// * Efetua a configuração do DataSource com base no \"Jndi Name\" configurado no
// * servidor de aplicações. A implementação do método deverá ser anotada como
// * \"@Bean\" para que o mesmo possa ser inicializado pelo Spring.
// *
// * Caso seja necessário utilizar multiplos repositórios (dataSources), a
// * implementação deste método deverá ser anotada ao menos em uma implementação,
// * com a anotação \"@Primary\".
// *
// * @return
// * @throws NamingException
// */
// @Bean(name = "repositoryZolpDataSource", destroyMethod = "")
// public DataSource repositoryZolpDataSource() throws NamingException {
//
// final JndiTemplate jndi = new JndiTemplate();
// final DataSource dataSource = jndi.lookup(env.getRequiredProperty("hibernate.connection.datasource"),
// DataSource.class);
// return dataSource;
//
// }
//
// /**
// * Efetua a configuração do entityManger. Caso seja necessário utilizar
// * multiplos repositórios (dataSources), a implementação deste método deverá ser
// * anotada ao menos em uma implementação, com a anotação \"@Primary\".
// *
// * @return
// * @throws NamingException
// */
// @Bean
// public LocalContainerEntityManagerFactoryBean repositoryZolpEntityManager() throws NamingException {
//
// final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
//
// em.setDataSource(this.repositoryZolpDataSource());
// em.setPackagesToScan(new String[] {"br.com.zolp.estudozolp.entity"});
// em.setPersistenceUnitName("repositoryZolpJpaPersistenceUnit");
//
// final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
// em.setJpaVendorAdapter(vendorAdapter);
//
// em.setJpaProperties(hibernateProperties());
//
// return em;
// }
//
// /**
// * Efetua a configuração do transactionManager Caso seja necessário utilizar
// * multiplos repositórios (dataSources), a implementação deste método deverá ser
// * anotada ao menos em uma implementação, com a anotação \"@Primary\".
// *
// * @return
// * @throws NamingException
// */
// @Bean
// public PlatformTransactionManager repositoryZolpTransactionManager() throws NamingException {
//
// final JpaTransactionManager transactionManager = new JpaTransactionManager();
//
// transactionManager.setEntityManagerFactory(repositoryZolpEntityManager().getObject());
//
// return transactionManager;
// }
//
// /**
// * Preenche as propriedades utilizadas no hibernate com base no arquivo de
// * configurações da aplicação.
// *
// * @return
// */
// private Properties hibernateProperties() {
//
// final Properties properties = new Properties();
//
// properties.put("hibernate.dialect", env.getRequiredProperty("hibernate.dialect"));
// properties.put("hibernate.show_sql", env.getRequiredProperty("hibernate.show_sql"));
// properties.put("hibernate.format_sql", env.getRequiredProperty("hibernate.format_sql"));
//
// return properties;
// }
}
|
package com.it.inv;
public class Department
{
int DEPT_ID;
String DEPT_NAME;
public Department(int dEPT_ID, String dEPT_NAME) {
super();
DEPT_ID = dEPT_ID;
DEPT_NAME = dEPT_NAME;
}
public int getDEPT_ID() {
return DEPT_ID;
}
public void setDEPT_ID(int dEPT_ID) {
DEPT_ID = dEPT_ID;
}
public String getDEPT_NAME() {
return DEPT_NAME;
}
public void setDEPT_NAME(String dEPT_NAME) {
DEPT_NAME = dEPT_NAME;
}
}
|
package com.weathair.security;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.Properties;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseCookie;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JwtAuthorizationFilter extends UsernamePasswordAuthenticationFilter {
// The time in milli-second before your session expire, here 3600 Seconds, so 1 hour
//private final static long EXPIRATION_TIME = 3600000L;
// a secret Key to avoid password hack by dictionary for exemple
// private final static String SECRET_KEY = "869EOKLMPHI32389JDC23E389CDKJ32443";
private final AuthenticationManager authenticationManager;
public JwtAuthorizationFilter (AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
// Show the root for login, we didn't get control for authentication so we make root here.
setFilterProcessesUrl("/login");
}
/**
* We try to authenticate here,
* We read our informations in our pojo class and then we map it with RequestBody
* We return autehntication Manager, where we got a new object with an user name, a password
* and an arraylist empty where you will found the roles
*
*/
@Override
public Authentication attemptAuthentication (HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException {
try {
InputStream requestBody = request.getInputStream();
AuthenticationPojo authenticationInfo = new ObjectMapper().readValue(requestBody, AuthenticationPojo.class);
return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(authenticationInfo.getUsername(),
authenticationInfo.getPassword(), new ArrayList<>()));
} catch (IOException e) {
System.err.println("Request body is empty.");
throw new AuthenticationCredentialsNotFoundException("Request body is empty.");
}
}
/**
* If your authentication is successfull so this function will put on , then
* we create a JWT Token, we put him expiration date and we sign it with
* HMAC512 method,
* Every token must began with "beared ", that's why we writed it on the response
*/
@Override
protected void successfulAuthentication (HttpServletRequest request, HttpServletResponse response, FilterChain chain,
Authentication authenticationResult) throws IOException, ServletException {
Properties properties = new Properties();
try {
properties.load(new FileInputStream("src/main/resources/application.properties"));
} catch (IOException e) {
System.err.println(e.getMessage());
}
String SECRET_KEY = properties.getProperty("jwt.secret_key");
String TOKEN_COOKIE = properties.getProperty("jwt.auth_name");
Long EXPIRATION_TIME = Long.parseLong(properties.getProperty("jwt.expiration_time"));
Boolean COOKIE_SECURE = Boolean.parseBoolean(properties.getProperty("jwt.cookie_secure"));
String token = JWT.create().withSubject(authenticationResult.getName())
.withExpiresAt(new Date(System.currentTimeMillis() + EXPIRATION_TIME*1000))
.sign(Algorithm.HMAC512(SECRET_KEY));
response.addHeader("Authorization", "Bearer " + token);
ResponseCookie responseCookie = ResponseCookie.from(TOKEN_COOKIE, token).httpOnly(true).maxAge(EXPIRATION_TIME*1000)
.path("/").sameSite("lax").secure(COOKIE_SECURE).build();
response.setHeader(HttpHeaders.SET_COOKIE, responseCookie.toString());
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.