text
stringlengths
10
2.72M
package com.espendwise.manta.web.controllers; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.propertyeditors.StringTrimmerEditor; import org.springframework.stereotype.Controller; import org.springframework.validation.DataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.context.request.WebRequest; import com.espendwise.manta.model.data.BusEntityData; import com.espendwise.manta.model.data.StoreMessageData; import com.espendwise.manta.service.AccountService; import com.espendwise.manta.service.StoreMessageService; import com.espendwise.manta.spi.AutoClean; import com.espendwise.manta.spi.SuccessMessage; import com.espendwise.manta.util.AppComparator; import com.espendwise.manta.util.Constants; import com.espendwise.manta.util.RefCodeNames; import com.espendwise.manta.util.SelectableObjects; import com.espendwise.manta.util.SelectableObjects.SelectableObject; import com.espendwise.manta.util.UpdateRequest; import com.espendwise.manta.util.Utility; import com.espendwise.manta.util.alert.ArgumentedMessage; import com.espendwise.manta.util.criteria.StoreAccountCriteria; import com.espendwise.manta.util.criteria.StoreMsgAccountConfigCriteria; import com.espendwise.manta.web.forms.SimpleConfigurationFilterForm; import com.espendwise.manta.web.forms.StoreMsgAccountconfigForm; import com.espendwise.manta.web.util.SessionKey; import com.espendwise.manta.web.util.WebAction; import com.espendwise.manta.web.util.WebErrors; import com.espendwise.manta.web.util.WebSort; @Controller @RequestMapping(UrlPathKey.STORE_MESSAGE.CONFIGURATION) @SessionAttributes({SessionKey.STORE_MESSAGE_CONFIGURATION, SessionKey.STORE_MESSAGE_CONFIGURATION_FILTER}) @AutoClean(SessionKey.STORE_MESSAGE_CONFIGURATION) public class StoreMessageConfigurationController extends BaseController { private static final Logger logger = Logger.getLogger(StoreMessageConfigurationController.class); private StoreMessageService storeMessageService; private AccountService accountService; @Autowired public StoreMessageConfigurationController(StoreMessageService storeMessageService, AccountService accountService) { this.storeMessageService = storeMessageService; this.accountService = accountService; } @InitBinder public void initBinder(DataBinder binder) { binder.registerCustomEditor(String.class, new StringTrimmerEditor(true)); } /*@RequestMapping(value = "/view", method = RequestMethod.GET) public String view(@ModelAttribute(SessionKey.STORE_MESSAGE_CONFIGURATION_FILTER) SimpleConfigurationFilterForm filterForm) { return "storeMessage/configuration"; }*/ @RequestMapping(value = "/view", method = RequestMethod.GET) public String view(WebRequest request, @PathVariable Long storeMessageId, @ModelAttribute(SessionKey.STORE_MESSAGE_CONFIGURATION) StoreMsgAccountconfigForm form, @ModelAttribute(SessionKey.STORE_MESSAGE_CONFIGURATION_FILTER) SimpleConfigurationFilterForm filterForm) throws Exception { if(storeMessageId > 0){ StoreMessageData message = storeMessageService.findStoreMessage(getStoreId(), storeMessageId); if (RefCodeNames.MESSAGE_MANAGED_BY.CUSTOMER.equals(message.getMessageManagedBy())){ return findAccounts(request, storeMessageId, form, filterForm); } } return "storeMessage/configuration"; } @RequestMapping(value = "/accounts", method = RequestMethod.GET) public String findAccounts(WebRequest request, @PathVariable Long storeMessageId, @ModelAttribute(SessionKey.STORE_MESSAGE_CONFIGURATION) StoreMsgAccountconfigForm form, @ModelAttribute(SessionKey.STORE_MESSAGE_CONFIGURATION_FILTER) SimpleConfigurationFilterForm filterForm) throws Exception { logger.info("findAccounts()=> BEGIN"); WebErrors webErrors = new WebErrors(request); if (!webErrors.isEmpty()) { return "storeMessage/configuration"; } List<? extends ArgumentedMessage> validationErrors = WebAction.validate(filterForm); if (!validationErrors.isEmpty()) { webErrors.putErrors(validationErrors); return "storeMessage/configuration"; } form.reset(); Long storeId = getStoreId(); Long userId = getUserId(); StoreMsgAccountConfigCriteria criteria = new StoreMsgAccountConfigCriteria(storeId, storeMessageId); StoreMessageData message = storeMessageService.findStoreMessage(getStoreId(), storeMessageId); boolean messageManagedByCustomer = RefCodeNames.MESSAGE_MANAGED_BY.CUSTOMER.equals(message.getMessageManagedBy()); form.setMessageManagedByCustomer(messageManagedByCustomer); logger.info("findAccounts()=> MessageManagedBy: " + message.getMessageManagedBy()); if (messageManagedByCustomer){ List<BusEntityData> configured = storeMessageService.findConfiguratedAccounts(criteria); SelectableObjects<BusEntityData> selableobj = new SelectableObjects<BusEntityData>( configured, configured, AppComparator.BUS_ENTITY_ID_COMPARATOR ); form.setAccounts(selableobj); logger.info("findAccounts()=> END."); return "storeMessage/configuration"; } criteria.setActiveOnly(!filterForm.getShowInactive()); criteria.setFilterType(filterForm.getFilterType()); criteria.setName(filterForm.getFilterValue()); if (filterForm.getShowConfiguredOnly()) { criteria.setLimit(Constants.FILTER_RESULT_LIMIT.STORE_MESSAGE_ACCOUNT); } logger.info("findAccounts()=> find store message accounts by criteria: " + criteria); logger.info("findAccounts()=> showConfiguredOnly: " + filterForm.getShowConfiguredOnly()); List<BusEntityData> configured = storeMessageService.findConfiguratedAccounts(criteria); StoreAccountCriteria accountCriteria = new StoreAccountCriteria(); accountCriteria.setStoreId(storeId); accountCriteria.setUserId(userId); accountCriteria.setActiveOnly(!filterForm.getShowInactive()); accountCriteria.setFilterType(filterForm.getFilterType()); accountCriteria.setName(filterForm.getFilterValue()); accountCriteria.setLimit(Constants.FILTER_RESULT_LIMIT.STORE_MESSAGE_ACCOUNT); List<BusEntityData> accounts = filterForm.getShowConfiguredOnly() ? new ArrayList<BusEntityData>(configured) : accountService.findStoreAccountBusDatas(accountCriteria); logger.info("findAccounts()=> accounts: " + accounts.size()); logger.info("findAccounts()=> configured: " + configured.size()); SelectableObjects<BusEntityData> selableobj = new SelectableObjects<BusEntityData>( accounts, configured, AppComparator.BUS_ENTITY_ID_COMPARATOR ); form.setAccounts(selableobj); WebSort.sort(form, BusEntityData.SHORT_DESC); logger.info("findAccounts()=> END."); return "storeMessage/configuration"; } @SuccessMessage @RequestMapping(value = "/accounts/update", method = RequestMethod.POST) public String update(@PathVariable Long storeMessageId, @ModelAttribute(SessionKey.STORE_MESSAGE_CONFIGURATION) StoreMsgAccountconfigForm form) throws Exception { logger.info("accounts/update()=> BEGIN"); Long storeId = getStoreId(); UpdateRequest<Long> updateRequest = new UpdateRequest<Long>(); List<Long> selectedIds = Utility.toIds(form.getAccounts().getNewlySelected()); List<Long> deselectedIds = Utility.toIds(form.getAccounts().getNewlyDeselected()); updateRequest.setToCreate(selectedIds); updateRequest.setToDelete(deselectedIds); logger.info("accounts/update()=> storeMessageId: " + storeMessageId); logger.info("accounts/update()=> storeId: " + storeId); logger.debug("accounts/update()=> updateRequest: " + updateRequest); storeMessageService.configureAccounts(storeId, storeMessageId, updateRequest); //MANTA-706 - update the form to reflect the creations/deletions Iterator<SelectableObject<BusEntityData>> accountIterator = form.getAccounts().getIterator(); while (accountIterator.hasNext()) { SelectableObject<BusEntityData> selectableObject = accountIterator.next(); Long accountId = selectableObject.getValue().getBusEntityId(); if (selectedIds.contains(accountId)) { selectableObject.setOriginallySelected(true); selectableObject.setSelected(true); } if (deselectedIds.contains(accountId)) { selectableObject.setOriginallySelected(false); selectableObject.setSelected(false); } } logger.info("accounts/update()=> END."); return "storeMessage/configuration"; } @SuccessMessage @RequestMapping(value = "/accounts/update/all", method = RequestMethod.POST) public String updateAll(@PathVariable Long storeMessageId) throws Exception { logger.info("accounts/updateAll()=> BEGIN"); Long storeId = getStoreId(); storeMessageService.configureAllAccounts(storeId, storeMessageId, false); logger.info("accounts/updateAll()=> END."); return "storeMessage/configuration"; } @ModelAttribute(SessionKey.STORE_MESSAGE_CONFIGURATION_FILTER) public SimpleConfigurationFilterForm initFilter(HttpSession session) { logger.info("initFilter()=> init...."); SimpleConfigurationFilterForm form = (SimpleConfigurationFilterForm) session.getAttribute(SessionKey.STORE_MESSAGE_CONFIGURATION_FILTER); if (form == null || !form.isInitialized()) { form = new SimpleConfigurationFilterForm() { public String getFilterKey() { return "admin.message.configuration.label.accounts"; } }; form.initialize(); } logger.info("initFilter()=> form: " + form); logger.info("initFilter()=> init.OK!"); return form; } @ModelAttribute(SessionKey.STORE_MESSAGE_CONFIGURATION) public StoreMsgAccountconfigForm init(HttpSession session, @PathVariable Long storeMessageId) { logger.info("init()=> init...."); StoreMsgAccountconfigForm form = (StoreMsgAccountconfigForm) session.getAttribute(SessionKey.STORE_MESSAGE_CONFIGURATION); logger.info("init()=> form: " + form); logger.info("init()=> storeMessageId: " + storeMessageId); if (form == null) { form = new StoreMsgAccountconfigForm(storeMessageId); } if (Utility.isSet(form.getAccounts())) { form.getAccounts().resetState(); } logger.info("init()=> init.OK!"); return form; } @RequestMapping(value = "/accounts/sortby/{field}", method = RequestMethod.GET) public String sort(@ModelAttribute(SessionKey.STORE_MESSAGE_CONFIGURATION) StoreMsgAccountconfigForm form, @PathVariable String field) throws Exception { WebSort.sort(form, field); return "storeMessage/configuration"; } }
package lookup; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.event.ForwardEvent; import org.zkoss.zk.ui.util.GenericForwardComposer; import org.zkoss.zul.Button; import org.zkoss.zul.Combobox; import org.zkoss.zul.Listbox; import org.zkoss.zul.Listcell; import org.zkoss.zul.Listitem; import org.zkoss.zul.Textbox; import org.zkoss.zul.Window; import services.GeneralService; import services.ManpowerService; import services.PersonnelService; import services.TrainingActivityService; import services.TravelExpenseService; public class LookupDocumentType extends GenericForwardComposer{ Window winLookupDocumentType; Listbox box; Textbox txCode,txType; Button btnSearch,btnCancel; List<Map<String, String>> fullMaps, searchMaps; public void doAfterCompose(Component win) throws Exception{ super.doAfterCompose(win); initMaps(); if (fullMaps == null || fullMaps.size() == 0) return; renderBoxLookup(); } private void initMaps() { //init all fullMaps = GeneralService.getDocumentTypeLookupList(); searchMaps = new ArrayList<Map<String,String>>(); for(Map<String,String> m: fullMaps){ searchMaps.add(m); } } private void renderBoxLookup() { Listitem item; Listcell cell; int i=1; box.getItems().clear(); for(Map<String,String> m: searchMaps){ item = new Listitem(); Button btnAdd = new Button("+"); btnAdd.addForward("onClick", winLookupDocumentType, "onAddType", m); cell = new Listcell(); btnAdd.setParent(cell); cell.setParent(item); cell = new Listcell(m.get("GCode")); cell.setParent(item); cell = new Listcell(m.get("Type")); cell.setParent(item); item.setParent(box); } } public void onAddType$winLookupDocumentType(ForwardEvent evt){ Map<String,String> map = (Map<String, String>) evt.getOrigin().getData(); onClose(map); } private void onClose(Map<String, String> map) { winLookupDocumentType.setAttribute("attrClose",true); if(map != null){ winLookupDocumentType.setAttribute("resultId",map.get("GCode")); winLookupDocumentType.setAttribute("resultDesc", map.get("Type")); } else{ winLookupDocumentType.setAttribute("resultId", ""); winLookupDocumentType.setAttribute("resultDesc", ""); } winLookupDocumentType.setVisible(false); } public void onClick$btnSearch(){ String code = txCode.getValue().toLowerCase(); String type = txType.getValue().toLowerCase(); searchMaps = new ArrayList<Map<String,String>>(); for(Map<String, String> m: fullMaps){ String mCode = m.get("GCode") != null ? m.get("GCode").toLowerCase() : ""; String mType = m.get("Type") != null ? m.get("Type").toLowerCase() : ""; if (mCode.contains(code) && mType.contains(type)){ searchMaps.add(m); } } renderBoxLookup(); } public void onClick$btnCancel(){ onClose(null); } public void onOK(){ onClick$btnSearch(); } }
package com.cannapaceus.grader; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.time.LocalDate; import java.util.ArrayList; import static org.junit.jupiter.api.Assertions.*; class CourseTest { private Course course; private Student student; private Assignment assignment; private Category category; private Grade grade; @BeforeEach void setUp() { course = new Course("Test Course", "TC 000", "Test Department"); } @Test void addAndGetStudent() { student = new Student("Test", "Student 0", "1234567890", "ts0000@test.edu"); course.addStudent(student); student = new Student("Test", "Student 1", "1234567891", "ts0001@test.edu"); course.addStudent(student); student = new Student("Test", "Student 2", "1234567892", "ts0002@test.edu"); course.addStudent(student); ArrayList<Student> lStudents = course.getlStudents(); assertEquals("Test", lStudents.get(0).getFirstMIName()); assertEquals("Test", lStudents.get(1).getFirstMIName()); assertEquals("Test", lStudents.get(2).getFirstMIName()); assertEquals("Student 0", lStudents.get(0).getLastName()); assertEquals("Student 1", lStudents.get(1).getLastName()); assertEquals("Student 2", lStudents.get(2).getLastName()); assertEquals("1234567890", lStudents.get(0).getStudentID()); assertEquals("1234567891", lStudents.get(1).getStudentID()); assertEquals("1234567892", lStudents.get(2).getStudentID()); assertEquals("ts0000@test.edu", lStudents.get(0).getStudentEmail()); assertEquals("ts0001@test.edu", lStudents.get(1).getStudentEmail()); assertEquals("ts0002@test.edu", lStudents.get(2).getStudentEmail()); } @Test void addAndGetAssignment() { assignment = new Assignment("Test Assignment 0", LocalDate.of(2019, 03, 25), LocalDate.of(2019, 03, 5), false, 100, new Category("Test Category 0", 1, 0), new Float(5)); course.addAssignment(assignment); assignment = new Assignment("Test Assignment 1", LocalDate.of(2020, 03, 25), LocalDate.of(2020, 03, 5), false, 101, new Category("Test Category 1", 1, 0), new Float(5)); course.addAssignment(assignment); ArrayList<Assignment> lAssignment = course.getlAssignments(); assertEquals("Test Assignment 0", lAssignment.get(0).getAssignmentName()); assertEquals("Test Assignment 1", lAssignment.get(1).getAssignmentName()); assertEquals(LocalDate.of(2019, 03, 25), lAssignment.get(0).getDueDate()); assertEquals(LocalDate.of(2020, 03, 25), lAssignment.get(1).getDueDate()); assertEquals(LocalDate.of(2019, 03, 5), lAssignment.get(0).getAssignedDate()); assertEquals(LocalDate.of(2020, 03, 5), lAssignment.get(1).getAssignedDate()); assertEquals(100, lAssignment.get(0).getMaxScore()); assertEquals(101, lAssignment.get(1).getMaxScore()); assertEquals("Test Category 0", lAssignment.get(0).getCategoryReference().getName()); assertEquals("Test Category 1", lAssignment.get(1).getCategoryReference().getName()); } @Test void addAndGetCategory() { category = new Category("Test Category 0", 10, 0); course.addCategory(category); category = new Category("Test Category 1", 20, 0); course.addCategory(category); ArrayList<Category> lCategory = course.getlCategories(); assertEquals("Test Category 0", lCategory.get(0).getName()); assertEquals("Test Category 1", lCategory.get(1).getName()); assertEquals(10, lCategory.get(0).getWeight()); assertEquals(20, lCategory.get(1).getWeight()); } @Test void addAndGetGrade() { student = new Student("Test", "Student 0", "1234567890", "ts0000@test.edu"); course.addStudent(student); assignment = new Assignment("Test Assignment 1", LocalDate.of(2020, 03, 25), LocalDate.of(2020, 03, 5), false, 101, new Category("Test Category 1", 1, 0), new Float(5)); course.addAssignment(assignment); grade = new Grade(10.5f, student, assignment); course.addGrade(grade); ArrayList<Grade> lGrades = course.getlGrades(); assertEquals(10.5f, lGrades.get(0).getGrade()); assertSame(assignment, lGrades.get(0).getAssignmentReference()); assertSame(student, lGrades.get(0).getStudentReference()); } @Test void removeStudentTest() { addAndGetStudent(); course.removeStudent(student); ArrayList<Student> lStudents = course.getlStudents(); assertEquals(2, lStudents.size()); } @Test void removeAssignmentTest() { addAndGetAssignment(); course.removeAssignment(assignment); ArrayList<Assignment> lAssignments = course.getlAssignments(); assertEquals(1, lAssignments.size()); } @Test void removeCategoryTest() { addAndGetCategory(); course.removeCategory(category); ArrayList<Category> lCategories = course.getlCategories(); assertEquals(1, lCategories.size()); } @Test void removeGradeTest() { addAndGetGrade(); course.removeGrade(grade); ArrayList<Grade> lGrades = course.getlGrades(); assertEquals(true, lGrades.isEmpty()); } @Test void archiveTest() { } @Test void populateAveragesTest() { } @Test void calculateStatsTest() { } @Test void getDBIDTest() { } @Test void getCourseNameTest() { } @Test void getCourseIDTest() { } @Test void getDepartmentTest() { } @Test void setDBIDTest() { } @Test void setCourseNameTest() { } @Test void setCourseIDTest() { } @Test void setDepartmentTest() { } @Test void compareTo() { } }
package mainModules; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.MenuItem; import javafx.stage.Stage; public class AboutController { @FXML private MenuItem closeMenu; @FXML private MenuItem mngDiseaseMenu; @FXML private MenuItem mngSolutionsMenu; @FXML private MenuItem diagDiseMenu; @FXML private MenuItem viewReportsMenu; @FXML private MenuItem viewGraphsMenu; @FXML private MenuItem aboutMenu; @FXML private Button backToMainBtn; /** * Function to handle events in the body of the UI * @param event * @throws Exception */ @FXML private void bodyOptionsHandler(ActionEvent event) throws Exception { if(backToMainBtn == event.getSource()) { Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("mainModules/GenerateReportUI.fxml")); Scene scene = new Scene(root); Stage stage = (Stage) backToMainBtn.getScene().getWindow(); stage.setTitle("Coconut Disease Image Scanner"); stage.setScene(scene); stage.show(); } } }
package com.ttcscn.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.ttcscn.dto.MenuDto; import com.ttcscn.entity.Menu; import com.ttcscn.entity.Message; import com.ttcscn.service.MenuService; @RestController public class MenuController { @Autowired MenuService menuService; @RequestMapping(value = "/menu/get", method = RequestMethod.POST) @ResponseBody public List<Menu> getAllListMenuPost() { List<Menu> arrMenu = menuService.getAllList(); return arrMenu; } @RequestMapping(value = "/menu/get", method = RequestMethod.GET) @ResponseBody public List<Menu> getAllListMenuGet() { List<Menu> arrMenu = menuService.getAllList(); return arrMenu; } @RequestMapping(value = "/menu/add", method = RequestMethod.POST) @ResponseBody public Message saveMenu(@RequestBody Menu menu) { Message mess = new Message(); Menu menufromData = menuService.findItemById(menu.getMaThucUong()); if(menufromData!=null) { mess.setMessage("Failse"); } else { String message = menuService.saveMenu(menu); mess.setMessage(message); } return mess; } @RequestMapping(value = "/menu/update", method = RequestMethod.POST) @ResponseBody public Message updateMenu(@RequestBody Menu menu) { Message mess = new Message(); Menu menufromData = menuService.findItemById(menu.getMaThucUong()); if(menufromData==null) { mess.setMessage("Failse"); } else { String message = menuService.updateMenu(menu); mess.setMessage(message); } return mess; } @RequestMapping(value = "/menu/delete", method = RequestMethod.POST) @ResponseBody public Message deleteMenu(@RequestBody Menu menu) { Message message = new Message(); Menu menufromData = menuService.findItemById(menu.getMaThucUong()); if(menufromData==null) { message.setMessage("Failse"); } else { String mess = menuService.deleteMenu(menufromData); message.setMessage("Success"); } return message; } @RequestMapping(value = "/menu/find", method = RequestMethod.GET) @ResponseBody public Menu findById(@RequestParam("maThucUong") String maThucUong) { Menu menu = menuService.findItemById(maThucUong); return menu; } //Test @RequestMapping(value = "/menu/test", method = RequestMethod.POST) @ResponseBody public MenuDto testList(@RequestBody List<Menu> menus) { MenuDto menuDto = new MenuDto(); menuDto.setMessage(menus.get(0).getTenThucUong()); menuDto.setStatus(menus.get(0).getHinhAnh()); return menuDto; } }
package com.slort.model; public class EntityBase { public EntityBase() { } public Object getNullValue() { return null; } }
package adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ImageButton; import android.widget.TextView; import java.util.ArrayList; import java.util.List; import grocerylist.sqlite.app.jsmtech.sqlitegrocerylist.R; import model.Grocery; import sqlite.DBAdapter; /** * Created by Sukriti on 6/16/16. */ public class GroceryAdapter extends RecyclerView.Adapter<GroceryAdapter.RV_ViewHolder> { private List<model.Grocery> listOfItems; private Context mContext; View itemView; private DBAdapter dbAdapter; public GroceryAdapter(Context context, ArrayList<Grocery> listOfGroceries) { this.mContext = context; this.listOfItems = listOfGroceries; dbAdapter = new DBAdapter(mContext); } @Override public RV_ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_grocery_item_view, parent, false); // link to xml return new RV_ViewHolder(itemView); } @Override public void onBindViewHolder(final RV_ViewHolder holder, int position) { final Grocery grocery = listOfItems.get(holder.getAdapterPosition()); holder.mItem.setText(grocery.getItem()); // Toast.makeText(mContext, isChecked + "", Toast.LENGTH_SHORT).show();; // holder.mChecked.setVisibility(View.GONE); if(!grocery.getIsVisited()) { grocery.setIsVisited(true); holder.mChecked.setChecked(false); holder.mChecked.setOnCheckedChangeListener(null); if(listOfItems.get(holder.getAdapterPosition()).getChecked() == 1) { holder.mChecked.setChecked(true); } else if(listOfItems.get(holder.getAdapterPosition()).getChecked() == 0) { holder.mChecked.setChecked(false); } holder.mChecked.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { Grocery c = listOfItems.get(holder.getAdapterPosition()); dbAdapter.open(); if(isChecked) { c.setChecked(1); } else { c.setChecked(0); } dbAdapter.updateGroceryItem(listOfItems.get(holder.getAdapterPosition()).getId(), c); dbAdapter.close(); } }); } else if(grocery.getIsVisited()) { if(listOfItems.get(holder.getAdapterPosition()).getChecked() == 1) { holder.mChecked.setChecked(true); } else if(listOfItems.get(holder.getAdapterPosition()).getChecked() == 0) { holder.mChecked.setChecked(false); } holder.mChecked.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { Grocery c = listOfItems.get(holder.getAdapterPosition()); dbAdapter.open(); if(isChecked) { c.setChecked(1); } else { c.setChecked(0); } dbAdapter.updateGroceryItem(listOfItems.get(holder.getAdapterPosition()).getId(), c); dbAdapter.close(); } }); } if(listOfItems.get(holder.getAdapterPosition()).getChecked() == 1) { holder.mChecked.setChecked(true); } else if(listOfItems.get(holder.getAdapterPosition()).getChecked() == 0) { holder.mChecked.setChecked(false); } holder.mDelete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dbAdapter.open(); dbAdapter.deleteGroceries(grocery.getId()); dbAdapter.close(); // We have deleted from the database! // We will also have to update the UI! listOfItems.remove(holder.getAdapterPosition()); notifyItemRemoved(holder.getAdapterPosition()); } }); // holder.mChecked.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { // @Override // public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // // Grocery c = listOfItems.get(holder.getAdapterPosition()); // // dbAdapter.open(); // if(isChecked) { // c.setChecked(1); // } // else { // c.setChecked(0); // } // dbAdapter.updateGroceryItem(listOfItems.get(holder.getAdapterPosition()).getId(), c); // // dbAdapter.close(); // // // } // }); } @Override public int getItemCount() { return listOfItems.size(); } @Override public long getItemId(int position) { return super.getItemId(position); } public class RV_ViewHolder extends RecyclerView.ViewHolder { protected TextView mItem; protected CheckBox mChecked; protected ImageButton mDelete; public RV_ViewHolder(View itemView) { super(itemView); mItem = (TextView) itemView.findViewById(R.id.name); mChecked = (CheckBox) itemView.findViewById(R.id.checked); mDelete = (ImageButton) itemView.findViewById(R.id.delete); } } }
package managedbean; import backingbean.reservation; import db.dbConnection; import javax.annotation.PostConstruct; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.context.FacesContext; import java.io.Serializable; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; @ManagedBean public class reservationBean implements Serializable { private reservation Reservation; private dbConnection db; @PostConstruct public void init(){ Reservation = new reservation(); db = new dbConnection(); } public reservation getReservation() { return Reservation; } public void setReservation(reservation reservation) { Reservation = reservation; } public String addReservation() { db.createRecord( Reservation.getArrival_Date(), Reservation.getNights(), Reservation.getAdults(), Reservation.getChildren(), Reservation.getRoom_type(), Reservation.getBed_type(), Reservation.getSmoking(), Reservation.getName(), Reservation.getEmail(), Reservation.getPhoneNumber() ); return "index"; } public List<reservation> getAllReservation(){ List<reservation> Resvation = new ArrayList<>(); ResultSet resultSet = db.displayRecords(); try { while(resultSet.next()) { reservation resv = new reservation(); resv.setId(resultSet.getInt("id")); resv.setArrival_Date(resultSet.getString("Arrival_date")); resv.setNights(resultSet.getInt("nights")); resv.setAdults(resultSet.getInt("adults")); resv.setChildren(resultSet.getInt("Children")); resv.setRoom_type(resultSet.getString("Room_type")); resv.setBed_type(resultSet.getString("Bed_type")); resv.setSmoking(resultSet.getString("Smoking")); resv.setName(resultSet.getString("Name")); resv.setEmail(resultSet.getString("Email")); resv.setPhoneNumber(resultSet.getInt("PhoneNumber")); Resvation.add(resv); } } catch (SQLException e) { e.printStackTrace(); } return Resvation; } public String deleteReservation(int id){ db.removeRecord(id); return "index"; } public String updateReservation(int reservationID,String Arrival_date, int nights, int adults, int children, String Room_type, String Bed_type, String Smoking, String Name, String Email, int phoneMumber) { Reservation.setArrival_Date(Arrival_date); Reservation.setNights(nights); Reservation.setAdults(adults); Reservation.setChildren(children); Reservation.setRoom_type(Room_type); Reservation.setBed_type(Bed_type); Reservation.setSmoking(Smoking); Reservation.setName(Name); Reservation.setEmail(Email); Reservation.setPhoneNumber(phoneMumber); db.updateRecord(reservationID,Reservation.getArrival_Date(), Reservation.getNights(), Reservation.getAdults(), Reservation.getChildren(), Reservation.getRoom_type(), Reservation.getBed_type(), Reservation.getSmoking(), Reservation.getName(), Reservation.getEmail(), Reservation.getPhoneNumber()); return "index"; } public List<reservation> getDataTable() { List<reservation> Resvation = new ArrayList<>(); if(Resvation == null) { Resvation = getAllReservation(); } return Resvation; } }
package com.koshcheyev.quadrangle.processing; /** * Created by Admin on 23.03.2017. */ public class SimpleIDCounter { private static int id = 0; public static int defineNewID(){ return id++; } }
package model; import com.jfinal.plugin.activerecord.Model; import java.util.List; /** * Created by reeco_000 on 2015/7/22. */ public class User extends Model<User>{ private int userid; private String username; private String password; private List<Article> articles; }
package com.willowtree.camera; import android.os.Bundle; import android.util.Log; import com.google.android.maps.*; import com.vividsolutions.jts.geom.Coordinate; import java.util.Iterator; /** * Created with IntelliJ IDEA. * User: Omar Lake * Date: 5/11/12 * Time: 9:58 AM * To change this template use File | Settings | File Templates. */ public class MapViewer extends MapActivity { private MapController mapController; private MyLocationOverlay myLocation; protected MainApp application; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mapview); application = (MainApp)getApplication(); // Log.d("Debug", "application is " + application) ; try { CameraStatus.coordinateList = application.getCoordinates(); } catch (Exception e) { e.printStackTrace(); } Iterator<Coordinate> iter = CameraStatus.coordinateList.iterator(); while(iter.hasNext()) { Coordinate coordinate = iter.next(); // android.util.Log.d("debug", "coordinate is " + coordinate.x +":" + coordinate.y + ":" + coordinate.z); } // Get Map at current location MapView mapView = (MapView) findViewById(R.id.map_view); mapController = mapView.getController(); mapController.setZoom(15); mapView.setBuiltInZoomControls(true); myLocation = new MyLocationOverlay(this, mapView); mapView.getOverlays().add(myLocation); myLocation.enableMyLocation(); myLocation.runOnFirstFix(new Runnable() { public void run() { mapController.animateTo(myLocation.getMyLocation()); } }); MapOverlay map_Overlay = new MapOverlay(); mapView.getOverlays().add(map_Overlay); } @Override protected void onResume() { super.onResume(); myLocation.enableMyLocation(); } @Override protected void onPause() { super.onPause(); myLocation.disableMyLocation(); } @Override protected boolean isRouteDisplayed() { return false; //To change body of implemented methods use File | Settings | File Templates. } }
package com.cs4125.bookingapp.services; import com.cs4125.bookingapp.model.entities.Route; import org.springframework.stereotype.Service; import java.sql.Timestamp; import java.util.List; @Service public interface RouteService { String findAllRoutes(String startNodeName, String endNodeName, String dateTime); String findAllRoutesFiltered(String startNodeName, String endNodeName, String filters, String dateTime); /* String searchRoute(int id); String searchRoute(String start_station, String end_station, Timestamp date_time); List<String> searchAllRoutes(String start_station, String end_station, Timestamp date_time); String addRoute(Route r); String updateRoute(Route r); String deleteRoute(Route r); */ }
package sort_algorithm; public class Challenging { public static void main(String[] args){ int[] intArray = {20, -1, 3, -4, 32, 21, -5, 425, 10, 452, 31, -353, -43}; String[] stringArray = {"bcdef", "dbaqc", "abcde", "omadd", "bbbbb"}; // insertionSortWithRecursive2(intArray, intArray.length); radixSort(stringArray, 5, 28); for(int i=0; i < stringArray.length; i++){ if(i == stringArray.length-1){ System.out.print(stringArray[i]); } else { System.out.print(stringArray[i] + ", "); } } } // 병합 정렬 Descending 순서로 구현 public static void mergeSort(int[] array, int start, int end){ if(end - start < 2) return; int mid = (start + end) / 2; mergeSort(array, start, mid); mergeSort(array, mid, end); merging(array, start,mid, end); } public static void merging(int[] array, int start, int mid, int end){ if(array[mid - 1] >= array[mid]) return; int i=start; int j=mid; int[] temp = new int[end - start + 1]; int tempIndex = 0; while(i < mid && j < end){ temp[tempIndex++] = array[i] < array[j] ? array[j++] : array[i++]; } System.arraycopy(array, i, array, start + tempIndex, mid - i); System.arraycopy(temp, 0, array, start, tempIndex); } // 삽입 정렬을 recursive로 변경해보기 public static void insertionSortWithRecursive(int[] array, int start){ if(start >= array.length || start <= 0) return; int tobeInserted = array[start]; int i=start; while(i > 0 && array[i-1] > tobeInserted){ array[i] = array[i-1]; i--; } array[i] = tobeInserted; insertionSortWithRecursive(array, start + 1); } // 다른 Recusive 삽입 정렬 public static void insertionSortWithRecursive2(int[] array, int itemNum){ if(itemNum < 2) return; insertionSortWithRecursive2(array, itemNum-1); int tobeInserted = array[itemNum-1]; int i; for(i=itemNum-1; i > 0 && array[i-1] > tobeInserted; i--){ array[i] = array[i-1]; } array[i] = tobeInserted; } // String value를 정렬하는 Radix 정렬 public static void radixSort(String[] array, int width, int radix){ for(int i=width-1; i >= 0; i--){ radixSingleSort(array, i, radix); } } public static void radixSingleSort(String[] array, int position, int radix){ int itemNum = array.length; int[] counting = new int[radix]; for(int i=0; i < itemNum; i++){ counting[radixGetChar(array[i], position)]++; } for(int i=1; i < counting.length; i++){ counting[i] += counting[i-1]; } String[] temp = new String[itemNum]; for(int i=itemNum-1; i >= 0; i--){ temp[--counting[radixGetChar(array[i], position)]] = array[i]; } for(int i=0; i < itemNum; i++){ array[i] = temp[i]; } } public static int radixGetChar(String value, int position){ return value.charAt(position) - 97; } public static void test(String value){ System.out.println(value.charAt(0)); System.out.println((int)value.charAt(0)); } }
import java.util.Scanner; public class PostNeg_Main { /** Main method */ public static void main(String[] args) { PostNegt result = new PostNegt(); result.setA(7); result.setB(-2); result.setNegative(true); boolean result1 = result.posNeg(result.getA(), result.getB(), result.isNegative()); System.out.println("The outcome of " +result.getA() + " and " +result.getB() + "" + " of boolean negative " + result.isNegative() + " is " +result1); } }
/* * 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 sigu.controller; import aplikasisigu.Home; import java.io.IOException; import sigu.model.modelBarang; import sigu.model.modelKategori; /** * * @author Luky Mulana */ public class controllerBarang { private modelBarang mB; private Home ho; public controllerBarang(Home ho) { this.ho = ho; } public void bersihBarang() { ho.getTfKodeBarangKategori().setText(""); ho.getTfNamaBarang().setText(""); ho.getCbKategoriBarang().setSelectedIndex(0); ho.getCbSupplierBarang().setSelectedIndex(0); ho.getTfStokBarang().setText(""); ho.getTfSatuanBarang().setText(""); } public void kontrolButton() { ho.getBtnTambahDataBarang().setEnabled(true); ho.getBtnHapusDataBarang().setEnabled(false); ho.getBtnEditDataBarang().setEnabled(false); ho.getBtnBatalDataBarang().setEnabled(true); } public void kontrolButtonDua() { ho.getBtnTambahDataBarang().setEnabled(false); ho.getBtnHapusDataBarang().setEnabled(true); ho.getBtnEditDataBarang().setEnabled(true); ho.getBtnBatalDataBarang().setEnabled(true); } public void simpanDataBarang() throws IOException { mB = new modelBarang(); mB.setKodeBarangModel(ho.getTfKodeBarang().getText()); mB.setNamaBarangModel(ho.getTfNamaBarang().getText()); mB.setKodeKategoriModel(ho.getTfKodeKategoriBarang().getText()); mB.setKodeSupplierModel(ho.getTfKodeSupplierBarang().getText()); mB.setStokModel(Integer.parseInt(ho.getTfStokBarang().getText())); mB.setSatuanModel(ho.getTfSatuanBarang().getText()); mB.simpanDataBarang(); bersihBarang(); kontrolButton(); } public void ubahDataBarang() throws IOException { mB = new modelBarang(); mB.setKodeBarangModel(ho.getTfKodeBarang().getText()); mB.setNamaBarangModel(ho.getTfNamaBarang().getText()); mB.setKodeKategoriModel(ho.getTfKodeKategoriBarang().getText()); mB.setKodeSupplierModel(ho.getTfKodeSupplierBarang().getText()); mB.setStokModel(Integer.parseInt(ho.getTfStokBarang().getText())); mB.setSatuanModel(ho.getTfSatuanBarang().getText()); mB.ubahDataBarang(); bersihBarang(); kontrolButton(); } public void hapusDataBarang() { mB = new modelBarang(); mB.setKodeBarangModel(ho.getTfKodeBarang().getText()); mB.hapusDataBarang(); bersihBarang(); kontrolButton(); } }
/* * Copyright 2008 Kjetil Valstadsve * * 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 vanadis.core.collections; import org.junit.Assert; import static org.junit.Assert.*; import org.junit.Test; import java.util.Collection; import java.util.Map; import java.util.Set; public class PropertyListMapTest { private static final String[] keys = {"a", "b", "c", "d", "e"}; @Test public void testGrowth() { PropertyListMap<String, Integer> plm = new PropertyListMap<String, Integer>(3, 65); assertEquals(3, plm.getCapacity()); plm.put("a", 1); assertEquals(3, plm.getCapacity()); plm.put("b", 2); assertEquals(6, plm.getCapacity()); assertEquals(2, plm.size()); assertEquals((Integer) 1, plm.get("a")); assertEquals((Integer) 2, plm.get("b")); assertEquals((Integer) 2, plm.remove("b")); assertEquals(3, plm.getCapacity()); assertEquals((Integer) 1, plm.get("a")); } @Test public void assertPutAll() { Map<String, Integer> map = create(); Map<String, Integer> source = fiveByTwo(); map.putAll(source); assertEquals(5, map.size()); assertKeySet(map.keySet()); assertValues(map.values()); assertPutGet(map); } @Test public void assertSize() { assertEquals(5, fiveByTwo().size()); assertEquals(0, create().size()); } @Test public void keySet() { assertKeySet(fiveByTwo().keySet()); } @Test public void values() { assertValues(fiveByTwo().values()); } @Test public void putGet() { assertPutGet(fiveByTwo()); } private static PropertyListMap<String, Integer> create() { return new PropertyListMap<String, Integer>(); } private static void assertKeySet(Set<String> map) { assertNotNull(map); assertEquals(5, map.size()); for (String key : keys) { Assert.assertTrue(map.contains(key)); } } private static void assertValues(Collection<Integer> map) { assertNotNull(map); assertEquals(5, map.size()); for (int i = 0; i < 5; i++) { Assert.assertTrue(map.contains(i + 1)); } } private static void assertPutGet(Map<String, Integer> map) { assertNull(map.get("dave")); assertEquals((Integer) 4, map.put("d", 0)); assertEquals((Integer) 0, map.get("d")); assertEquals((Integer) 0, map.remove("d")); assertNull(map.put("f", 7)); } private static Map<String, Integer> fiveByTwo() { PropertyListMap<String, Integer> map = new PropertyListMap<String, Integer>(5, 10); for (int i = 0; i < keys.length; i++) { assertNull(map.put(keys[i], i + 1)); } return map; } }
package bruteforcegen; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.Window; public class ComponentTools { public static void centerForm(Window window) { Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Dimension windowSize = window.getSize(); int x = (int) ((screenSize.getWidth() - windowSize.getWidth()) / 2); int y = (int) ((screenSize.getHeight() - windowSize.getHeight()) / 2); window.setLocation(x, y); } public static void setGrayColor(Component component) { Color backgroundColor = new Color(50, 50, 50); component.setBackground(backgroundColor); Color foregroundColor = new Color(175, 175, 175); component.setForeground(foregroundColor); } public static void setGrayColor(Component... components) { for (Component component : components) { Color backgroundColor = new Color(50, 50, 50); component.setBackground(backgroundColor); Color foregroundColor = new Color(175, 175, 175); component.setForeground(foregroundColor); } } }
package com.brainmentors.testengine.models.user; import org.springframework.stereotype.Component; @Component public class User { private String userid; private String password; private String name; private String address; private String phone; private String url; private String email; public String getUserid() { return userid; } public void setUserid(String userid) { this.userid = userid; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public String toString() { return "User [userid=" + userid + ", name=" + name + ", address=" + address + ", phone=" + phone + ", url=" + url + ", email=" + email + "]"; } }
package com.fang.dailytask.LinkList; import org.junit.Test; import static org.junit.Assert.*; /** * Author: fangxueshun * Description: 测试单链表 * Date: 2017/3/6 * Time: 18:25 */ public class LinkListTest { /*创建链表*/ @Test public final void TestLinkList(){ LinkList linkList = new LinkList(); linkList.add(1); linkList.add(2); linkList.add(3); linkList.add(4); assertEquals("LinkList:1 2 3 4 ",linkList.toString()); } }
package com.dinu; public class FindTargetInMountainArray { public static void main(String[] args) { int[] arr= {2,5,7,8,9,11,33,55,66,45,23,22,19,12,3,0}; int target=12; int peak=findPeak(arr); /* * System.out.println("peak : "+peak); * System.out.println(binarySearch(arr,target,0,8)); */ int index=binarySearch(arr,target,0,peak); if(index==-1) { index=binarySearch(arr,target,peak+1,arr.length-1); } System.out.println(index); } static int findPeak(int[] arr) { int start=0; int end=arr.length-1; while(start<end) { int mid=start+(end-start)/2; if(arr[mid]<arr[mid+1]) { start=mid+1; } else { end=mid; } } return start; } static int binarySearch(int arr[],int target,int start,int end) { boolean isAsc=arr[end]>arr[start]; while(start<=end) { int mid=start+(end-start)/2; if(arr[mid]==target) { return mid; } else { if(target<arr[mid]) { if(isAsc) { end=mid-1; } else { start=mid+1; } } else { if(isAsc) { start=mid+1; } else { end=mid-1; } } } } return -1; } }
package android.support.v7.view.menu; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Parcelable; import android.support.v4.view.d; import android.support.v4.view.m; import android.util.SparseArray; import android.view.ContextMenu.ContextMenuInfo; import android.view.KeyCharacterMap.KeyData; import android.view.KeyEvent; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; public class f implements android.support.v4.c.a.a { private static final int[] Id = new int[]{1, 4, 5, 3, 2, 0}; private boolean Ie; private boolean If; public a Ig; private ArrayList<h> Ih; private boolean Ii; public ArrayList<h> Ij; private ArrayList<h> Ik; private boolean Il; public int Im = 1; private ContextMenuInfo In; CharSequence Io; Drawable Ip; View Iq; private boolean Ir = false; private boolean Is = false; boolean It = false; private boolean Iu = false; private ArrayList<h> Iv = new ArrayList(); public CopyOnWriteArrayList<WeakReference<l>> Iw = new CopyOnWriteArrayList(); h Ix; public boolean Iy; ArrayList<h> bA; public final Context mContext; private final Resources mResources; public interface a { boolean a(f fVar, MenuItem menuItem); void b(f fVar); } public interface b { boolean f(h hVar); } public f(Context context) { boolean z = true; this.mContext = context; this.mResources = context.getResources(); this.bA = new ArrayList(); this.Ih = new ArrayList(); this.Ii = true; this.Ij = new ArrayList(); this.Ik = new ArrayList(); this.Il = true; if (this.mResources.getConfiguration().keyboard == 1 || !this.mResources.getBoolean(android.support.v7.a.a.b.abc_config_showMenuShortcutsWhenKeyboardPresent)) { z = false; } this.If = z; } public final void a(l lVar) { a(lVar, this.mContext); } public final void a(l lVar, Context context) { this.Iw.add(new WeakReference(lVar)); lVar.a(context, this); this.Il = true; } public final void b(l lVar) { Iterator it = this.Iw.iterator(); while (it.hasNext()) { WeakReference weakReference = (WeakReference) it.next(); l lVar2 = (l) weakReference.get(); if (lVar2 == null || lVar2 == lVar) { this.Iw.remove(weakReference); } } } public final void dispatchSaveInstanceState(Bundle bundle) { if (!this.Iw.isEmpty()) { SparseArray sparseArray = new SparseArray(); Iterator it = this.Iw.iterator(); while (it.hasNext()) { WeakReference weakReference = (WeakReference) it.next(); l lVar = (l) weakReference.get(); if (lVar == null) { this.Iw.remove(weakReference); } else { int id = lVar.getId(); if (id > 0) { Parcelable onSaveInstanceState = lVar.onSaveInstanceState(); if (onSaveInstanceState != null) { sparseArray.put(id, onSaveInstanceState); } } } } bundle.putSparseParcelableArray("android:menu:presenters", sparseArray); } } public final void c(Bundle bundle) { SparseArray sparseArray = null; int size = size(); int i = 0; while (i < size) { MenuItem item = getItem(i); View a = m.a(item); if (!(a == null || a.getId() == -1)) { if (sparseArray == null) { sparseArray = new SparseArray(); } a.saveHierarchyState(sparseArray); if (m.d(item)) { bundle.putInt("android:menu:expandedactionview", item.getItemId()); } } SparseArray sparseArray2 = sparseArray; if (item.hasSubMenu()) { ((p) item.getSubMenu()).c(bundle); } i++; sparseArray = sparseArray2; } if (sparseArray != null) { bundle.putSparseParcelableArray(dG(), sparseArray); } } public final void d(Bundle bundle) { if (bundle != null) { MenuItem item; SparseArray sparseParcelableArray = bundle.getSparseParcelableArray(dG()); int size = size(); for (int i = 0; i < size; i++) { item = getItem(i); View a = m.a(item); if (!(a == null || a.getId() == -1)) { a.restoreHierarchyState(sparseParcelableArray); } if (item.hasSubMenu()) { ((p) item.getSubMenu()).d(bundle); } } int i2 = bundle.getInt("android:menu:expandedactionview"); if (i2 > 0) { item = findItem(i2); if (item != null) { m.b(item); } } } } protected String dG() { return "android:menu:actionviewstates"; } public void a(a aVar) { this.Ig = aVar; } public final MenuItem a(int i, int i2, int i3, CharSequence charSequence) { int i4 = (-65536 & i3) >> 16; if (i4 < 0 || i4 >= Id.length) { throw new IllegalArgumentException("order does not contain a valid category."); } int i5 = (Id[i4] << 16) | (65535 & i3); MenuItem hVar = new h(this, i, i2, i3, i5, charSequence, this.Im); if (this.In != null) { hVar.IK = this.In; } this.bA.add(b(this.bA, i5), hVar); p(true); return hVar; } public MenuItem add(CharSequence charSequence) { return a(0, 0, 0, charSequence); } public MenuItem add(int i) { return a(0, 0, 0, this.mResources.getString(i)); } public MenuItem add(int i, int i2, int i3, CharSequence charSequence) { return a(i, i2, i3, charSequence); } public MenuItem add(int i, int i2, int i3, int i4) { return a(i, i2, i3, this.mResources.getString(i4)); } public SubMenu addSubMenu(CharSequence charSequence) { return addSubMenu(0, 0, 0, charSequence); } public SubMenu addSubMenu(int i) { return addSubMenu(0, 0, 0, this.mResources.getString(i)); } public SubMenu addSubMenu(int i, int i2, int i3, CharSequence charSequence) { h hVar = (h) a(i, i2, i3, charSequence); SubMenu pVar = new p(this.mContext, this, hVar); hVar.b(pVar); return pVar; } public SubMenu addSubMenu(int i, int i2, int i3, int i4) { return addSubMenu(i, i2, i3, this.mResources.getString(i4)); } public int addIntentOptions(int i, int i2, int i3, ComponentName componentName, Intent[] intentArr, Intent intent, int i4, MenuItem[] menuItemArr) { PackageManager packageManager = this.mContext.getPackageManager(); List queryIntentActivityOptions = packageManager.queryIntentActivityOptions(componentName, intentArr, intent, 0); int size = queryIntentActivityOptions != null ? queryIntentActivityOptions.size() : 0; if ((i4 & 1) == 0) { removeGroup(i); } for (int i5 = 0; i5 < size; i5++) { Intent intent2; ResolveInfo resolveInfo = (ResolveInfo) queryIntentActivityOptions.get(i5); if (resolveInfo.specificIndex < 0) { intent2 = intent; } else { intent2 = intentArr[resolveInfo.specificIndex]; } Intent intent3 = new Intent(intent2); intent3.setComponent(new ComponentName(resolveInfo.activityInfo.applicationInfo.packageName, resolveInfo.activityInfo.name)); MenuItem intent4 = add(i, i2, i3, resolveInfo.loadLabel(packageManager)).setIcon(resolveInfo.loadIcon(packageManager)).setIntent(intent3); if (menuItemArr != null && resolveInfo.specificIndex >= 0) { menuItemArr[resolveInfo.specificIndex] = intent4; } } return size; } public void removeItem(int i) { int i2; int size = size(); for (int i3 = 0; i3 < size; i3++) { if (((h) this.bA.get(i3)).getItemId() == i) { i2 = i3; break; } } i2 = -1; m(i2, true); } public void removeGroup(int i) { int i2; int size = size(); for (i2 = 0; i2 < size; i2++) { if (((h) this.bA.get(i2)).getGroupId() == i) { size = i2; break; } } size = -1; if (size >= 0) { int size2 = this.bA.size() - size; int i3 = 0; while (true) { i2 = i3 + 1; if (i3 >= size2 || ((h) this.bA.get(size)).getGroupId() != i) { p(true); } else { m(size, false); i3 = i2; } } p(true); } } private void m(int i, boolean z) { if (i >= 0 && i < this.bA.size()) { this.bA.remove(i); if (z) { p(true); } } } public void clear() { if (this.Ix != null) { h(this.Ix); } this.bA.clear(); p(true); } public void setGroupCheckable(int i, boolean z, boolean z2) { int size = this.bA.size(); for (int i2 = 0; i2 < size; i2++) { h hVar = (h) this.bA.get(i2); if (hVar.getGroupId() == i) { hVar.K(z2); hVar.setCheckable(z); } } } public void setGroupVisible(int i, boolean z) { int size = this.bA.size(); int i2 = 0; boolean z2 = false; while (i2 < size) { boolean z3; h hVar = (h) this.bA.get(i2); if (hVar.getGroupId() == i && hVar.M(z)) { z3 = true; } else { z3 = z2; } i2++; z2 = z3; } if (z2) { p(true); } } public void setGroupEnabled(int i, boolean z) { int size = this.bA.size(); for (int i2 = 0; i2 < size; i2++) { h hVar = (h) this.bA.get(i2); if (hVar.getGroupId() == i) { hVar.setEnabled(z); } } } public boolean hasVisibleItems() { if (this.Iy) { return true; } int size = size(); for (int i = 0; i < size; i++) { if (((h) this.bA.get(i)).isVisible()) { return true; } } return false; } public MenuItem findItem(int i) { int size = size(); for (int i2 = 0; i2 < size; i2++) { h hVar = (h) this.bA.get(i2); if (hVar.getItemId() == i) { return hVar; } if (hVar.hasSubMenu()) { MenuItem findItem = hVar.getSubMenu().findItem(i); if (findItem != null) { return findItem; } } } return null; } public int size() { return this.bA.size(); } public MenuItem getItem(int i) { return (MenuItem) this.bA.get(i); } public boolean isShortcutKey(int i, KeyEvent keyEvent) { return a(i, keyEvent) != null; } public void setQwertyMode(boolean z) { this.Ie = z; p(false); } boolean dH() { return this.Ie; } public boolean dI() { return this.If; } boolean b(f fVar, MenuItem menuItem) { return this.Ig != null && this.Ig.a(fVar, menuItem); } private static int b(ArrayList<h> arrayList, int i) { for (int size = arrayList.size() - 1; size >= 0; size--) { if (((h) arrayList.get(size)).Ho <= i) { return size + 1; } } return 0; } public boolean performShortcut(int i, KeyEvent keyEvent, int i2) { MenuItem a = a(i, keyEvent); boolean z = false; if (a != null) { z = a(a, null, i2); } if ((i2 & 2) != 0) { J(true); } return z; } private void a(List<h> list, int i, KeyEvent keyEvent) { boolean dH = dH(); int metaState = keyEvent.getMetaState(); KeyData keyData = new KeyData(); if (keyEvent.getKeyData(keyData) || i == 67) { int size = this.bA.size(); for (int i2 = 0; i2 < size; i2++) { h hVar = (h) this.bA.get(i2); if (hVar.hasSubMenu()) { ((f) hVar.getSubMenu()).a((List) list, i, keyEvent); } char alphabeticShortcut = dH ? hVar.getAlphabeticShortcut() : hVar.getNumericShortcut(); if ((metaState & 5) == 0 && alphabeticShortcut != 0 && ((alphabeticShortcut == keyData.meta[0] || alphabeticShortcut == keyData.meta[2] || (dH && alphabeticShortcut == 8 && i == 67)) && hVar.isEnabled())) { list.add(hVar); } } } } private h a(int i, KeyEvent keyEvent) { List list = this.Iv; list.clear(); a(list, i, keyEvent); if (list.isEmpty()) { return null; } int metaState = keyEvent.getMetaState(); KeyData keyData = new KeyData(); keyEvent.getKeyData(keyData); int size = list.size(); if (size == 1) { return (h) list.get(0); } boolean dH = dH(); for (int i2 = 0; i2 < size; i2++) { h hVar = (h) list.get(i2); char alphabeticShortcut = dH ? hVar.getAlphabeticShortcut() : hVar.getNumericShortcut(); if (alphabeticShortcut == keyData.meta[0] && (metaState & 2) == 0) { return hVar; } if (alphabeticShortcut == keyData.meta[2] && (metaState & 2) != 0) { return hVar; } if (dH && alphabeticShortcut == 8 && i == 67) { return hVar; } } return null; } public boolean performIdentifierAction(int i, int i2) { return a(findItem(i), null, i2); } public final boolean a(MenuItem menuItem, l lVar, int i) { boolean z = false; h hVar = (h) menuItem; if (hVar == null || !hVar.isEnabled()) { return false; } boolean z2; boolean dR = hVar.dR(); d dVar = hVar.IH; if (dVar == null || !dVar.hasSubMenu()) { z2 = false; } else { z2 = true; } boolean expandActionView; if (hVar.dY()) { expandActionView = hVar.expandActionView() | dR; if (!expandActionView) { return expandActionView; } J(true); return expandActionView; } else if (hVar.hasSubMenu() || z2) { J(false); if (!hVar.hasSubMenu()) { hVar.b(new p(this.mContext, this, hVar)); } p pVar = (p) hVar.getSubMenu(); if (z2) { dVar.onPrepareSubMenu(pVar); } if (!this.Iw.isEmpty()) { if (lVar != null) { z = lVar.a(pVar); } Iterator it = this.Iw.iterator(); boolean z3 = z; while (it.hasNext()) { WeakReference weakReference = (WeakReference) it.next(); l lVar2 = (l) weakReference.get(); if (lVar2 == null) { this.Iw.remove(weakReference); } else { if (z3) { z = z3; } else { z = lVar2.a(pVar); } z3 = z; } } z = z3; } expandActionView = dR | r2; if (expandActionView) { return expandActionView; } J(true); return expandActionView; } else { if ((i & 1) == 0) { J(true); } return dR; } } public final void J(boolean z) { if (!this.Iu) { this.Iu = true; Iterator it = this.Iw.iterator(); while (it.hasNext()) { WeakReference weakReference = (WeakReference) it.next(); l lVar = (l) weakReference.get(); if (lVar == null) { this.Iw.remove(weakReference); } else { lVar.a(this, z); } } this.Iu = false; } } public void close() { J(true); } public void p(boolean z) { if (this.Ir) { this.Is = true; return; } if (z) { this.Ii = true; this.Il = true; } if (!this.Iw.isEmpty()) { dJ(); Iterator it = this.Iw.iterator(); while (it.hasNext()) { WeakReference weakReference = (WeakReference) it.next(); l lVar = (l) weakReference.get(); if (lVar == null) { this.Iw.remove(weakReference); } else { lVar.n(z); } } dK(); } } public final void dJ() { if (!this.Ir) { this.Ir = true; this.Is = false; } } public final void dK() { this.Ir = false; if (this.Is) { this.Is = false; p(true); } } final void dL() { this.Ii = true; p(true); } final void dM() { this.Il = true; p(true); } public final ArrayList<h> dN() { if (!this.Ii) { return this.Ih; } this.Ih.clear(); int size = this.bA.size(); for (int i = 0; i < size; i++) { h hVar = (h) this.bA.get(i); if (hVar.isVisible()) { this.Ih.add(hVar); } } this.Ii = false; this.Il = true; return this.Ih; } public final void dO() { ArrayList dN = dN(); if (this.Il) { Iterator it = this.Iw.iterator(); int i = 0; while (it.hasNext()) { WeakReference weakReference = (WeakReference) it.next(); l lVar = (l) weakReference.get(); if (lVar == null) { this.Iw.remove(weakReference); } else { i = lVar.N() | i; } } if (i != 0) { this.Ij.clear(); this.Ik.clear(); i = dN.size(); for (int i2 = 0; i2 < i; i2++) { h hVar = (h) dN.get(i2); if (hVar.dV()) { this.Ij.add(hVar); } else { this.Ik.add(hVar); } } } else { this.Ij.clear(); this.Ik.clear(); this.Ik.addAll(dN()); } this.Il = false; } } public final ArrayList<h> dP() { dO(); return this.Ik; } public void clearHeader() { this.Ip = null; this.Io = null; this.Iq = null; p(false); } final void a(CharSequence charSequence, Drawable drawable, View view) { if (view != null) { this.Iq = view; this.Io = null; this.Ip = null; } else { if (charSequence != null) { this.Io = charSequence; } if (drawable != null) { this.Ip = drawable; } this.Iq = null; } p(false); } protected final f g(CharSequence charSequence) { a(charSequence, null, null); return this; } protected final f k(Drawable drawable) { a(null, drawable, null); return this; } public f dQ() { return this; } public boolean g(h hVar) { boolean z = false; if (!this.Iw.isEmpty()) { dJ(); Iterator it = this.Iw.iterator(); boolean z2 = false; while (it.hasNext()) { WeakReference weakReference = (WeakReference) it.next(); l lVar = (l) weakReference.get(); if (lVar == null) { this.Iw.remove(weakReference); } else { z = lVar.b(hVar); if (z) { break; } z2 = z; } } z = z2; dK(); if (z) { this.Ix = hVar; } } return z; } public boolean h(h hVar) { boolean z = false; if (!this.Iw.isEmpty() && this.Ix == hVar) { dJ(); Iterator it = this.Iw.iterator(); boolean z2 = false; while (it.hasNext()) { WeakReference weakReference = (WeakReference) it.next(); l lVar = (l) weakReference.get(); if (lVar == null) { this.Iw.remove(weakReference); } else { z = lVar.c(hVar); if (z) { break; } z2 = z; } } z = z2; dK(); if (z) { this.Ix = null; } } return z; } }
package JZOF; import java.util.ArrayList; /** * Created by yangqiao on 21/6/17. */ /* 输入n个整数,找出其中最小的K个数。 例如输入4,5,1,6,2,7,3,8这8个数字, 则最小的4个数字是1,2,3,4,。 */ public class MinKNumber { public static void main(String[] args) { int[] numbers = new int[]{1, 4, 2, 8, 15, 7, 9, 10}; ArrayList<Integer> result = new MinKNumber().GetLeastNumbers_Solution(numbers, 5); for (int i : result) { System.out.println(i); } } /* using quiksort partition function */ private int partition(int[] input, int start, int end) { int pivot = input[end]; int i = start - 1; for (int j = i + 1; j < end; j++) { if (input[j] < pivot) { i++; int temp = input[j]; input[j] = input[i]; input[i] = temp; } } int temp = input[end]; input[end] = input[i + 1]; input[i + 1] = temp; return i + 1; } public ArrayList<Integer> GetLeastNumbers_Solution(int[] input, int k) { ArrayList<Integer> result = new ArrayList<Integer>(); if (input != null && k != 0 && k <= input.length) { int pivot = partition(input, 0, input.length - 1); while (pivot != k - 1) { if (pivot > k - 1) { pivot = partition(input, 0, pivot - 1); } else if (pivot < k - 1) { pivot = partition(input, pivot + 1, input.length - 1); } } int index = 0; while (index < k) { result.add(input[index]); index++; } } return result; } } class MinKHeap{ public static void main(String[] args) { int[] numbers = new int[]{1, 4, 2, 8, 15, 7, 9, 10}; ArrayList<Integer> result = new MinKNumber().GetLeastNumbers_Solution(numbers, 5); for (int i : result) { System.out.println(i); } } public ArrayList<Integer> GetLeastNumbers_Solution(int[] input, int k) { ArrayList<Integer> result = new ArrayList<Integer>(); if (input != null && k != 0 && k <= input.length) { } return result; } }
package com.tencent.mm.plugin.ipcall.a.c; import android.os.Looper; import com.tencent.mm.plugin.ipcall.a.a.c; import com.tencent.mm.plugin.ipcall.a.i; import com.tencent.mm.plugin.voip.model.v2protocal; import com.tencent.mm.protocal.c.byy; import com.tencent.mm.protocal.c.cah; import com.tencent.mm.sdk.platformtools.ag; import com.tencent.mm.sdk.platformtools.x; public final class a { public boolean kqA = false; public boolean kqB = false; public a kqC = null; public v2protocal kqx = new v2protocal(this.kqy); private ag kqy = new 1(this, Looper.getMainLooper()); private boolean kqz = false; static /* synthetic */ void a(a aVar, int i) { x.d("MicroMsg.IPCallEngineManager", "channel connect failed!"); if (aVar.kqC != null) { aVar.kqC.rt(i); } } public final void aXJ() { x.d("MicroMsg.IPCallEngineManager", "setChannelActiveAfterAccept"); if (!this.kqA) { x.d("MicroMsg.IPCallEngineManager", "channel not connect now"); } this.kqx.setActive(); } public final void aXK() { if (this.kqz) { x.d("MicroMsg.IPCallEngineManager", "requestChannelConnect, already request channel connect"); return; } x.i("MicroMsg.IPCallEngineManager", "requestChannelConnect"); c cVar = i.aXp().koG; if (cVar != null) { if (cVar.gUH != null) { byy V = com.tencent.mm.plugin.ipcall.b.c.V(cVar.gUH); byy V2 = com.tencent.mm.plugin.ipcall.b.c.V(cVar.kpM); cah cah = new cah(); cah.swD = 0; cah.swE = 0; cah.swF = 0; cah.userName = ""; cah.eSH = ""; this.kqx.a(V, V, V2, cah); } x.d("MicroMsg.IPCallEngineManager", "finish set svr addr"); this.kqx.oOp = cVar.kpH; this.kqx.oPj = cVar.kpK; if (cVar.kpL != null) { this.kqx.oPk = cVar.kpL.toByteArray(); } if (cVar.kpI != null) { this.kqx.oOq = cVar.kpI.toByteArray(); } this.kqx.kpo = cVar.kpo; this.kqx.kpp = cVar.kpp; this.kqx.kpw = cVar.kpw; this.kqx.oOs = cVar.kpF; this.kqx.oOr = cVar.kpG; this.kqx.oOt = cVar.kpN; int configInfo = this.kqx.setConfigInfo(this.kqx.oOk, (long) this.kqx.kpo, this.kqx.kpw, this.kqx.kpp, this.kqx.field_peerId, 1, this.kqx.oOr, this.kqx.oOs, this.kqx.oOp, this.kqx.oOq == null ? 0 : this.kqx.oOq.length, this.kqx.oOq, this.kqx.oOt, 0, 0, this.kqx.oPj, this.kqx.oPk, 255, 0); x.d("MicroMsg.IPCallEngineManager", "setConfigInfo, ret: %d", Integer.valueOf(configInfo)); if (configInfo == 0) { configInfo = this.kqx.connectToPeer(); } if (configInfo < 0) { x.e("MicroMsg.IPCallEngineManager", "setConfigInfo failed, ret: %d", Integer.valueOf(configInfo)); if (this.kqC != null) { this.kqC.rt(21); } } this.kqz = true; } } public final void ry(int i) { if (this.kqA) { x.d("MicroMsg.IPCallEngineManager", "setDtmfPayloadType: %d", Integer.valueOf(i)); if (this.kqx.SetDTMFPayload(i) < 0) { x.i("MicroMsg.IPCallEngineManager", "setDtmfPayloadType failed, ret: %d", Integer.valueOf(this.kqx.SetDTMFPayload(i))); } } } public final void aXL() { this.kqA = false; this.kqz = false; this.kqB = false; } }
package com.sanfriend.android_next_pulltorefresh; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.Menu; import android.view.MenuItem; import android.webkit.WebView; import android.webkit.WebViewClient; import com.sanfriend.android_next_pulltorefresh.R; import com.sanfriend.ptr.OnRefreshListener; import com.sanfriend.ptr.PullToRefreshLayout; public class MainActivity extends AppCompatActivity { private WebView mWebView; private PullToRefreshLayout mPtr; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mPtr = (PullToRefreshLayout)findViewById(R.id.ptrLayout); mWebView = (WebView)findViewById(R.id.ptr_body); mWebView.loadUrl("https://sanfriend.com/ptr.html"); mWebView.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); if (mPtr != null && mPtr.isRefreshing()) mPtr.setRefreshing(false); } }); // first-time refresh mWebView.postDelayed(new Runnable() { @Override public void run() { mPtr.setRefreshing(true); } }, 10); mPtr.setOnRefreshListener(new OnRefreshListener() { @Override public void onRefresh() { mWebView.reload(); } }); } }
package backjun.silver; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.Arrays; import java.util.StringTokenizer; public class Main_2805_나무자르기 { static long max = 0; static int[] namu; static int N; static int M; static long minLen = Integer.MAX_VALUE; public static void main(String[] args) throws Exception { System.setIn(new FileInputStream("input.txt")); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); StringTokenizer st = new StringTokenizer(br.readLine()); N = Integer.parseInt(st.nextToken()); M = Integer.parseInt(st.nextToken()); namu = new int[N]; st = new StringTokenizer(br.readLine()); for (int i = 0; i < N; i++) { namu[i] = Integer.parseInt(st.nextToken()); } Arrays.sort(namu); bw.write(Bsearch(0, namu[namu.length - 1]) + "\n"); bw.flush(); bw.close(); } private static long Bsearch(long left, long right) { long sum = 0; long mid = (left + right) / 2; if (left > right) return max; for (int i : namu) { if (i < mid) continue; sum += i - mid; } if (sum >= M) { if (sum <= minLen) { minLen = sum; max = mid; } return Bsearch(mid + 1, right); } else { return Bsearch(left, mid - 1); } } }
package com.mmall.concurrency.example.singleton; import com.mmall.concurrency.annotation.Recommend; import com.mmall.concurrency.annotation.ThreadSafe; /** * @Auther: Mr.Dong * @Date: 2019/3/1 10:20 * @Description: 枚举模式:最安全 */ @ThreadSafe @Recommend public class SingletonExample7 { private SingletonExample7() { } public static SingletonExample7 getInstance() { return Singleton.INSTANCE.getInstance(); } private enum Singleton { INSTANCE; private SingletonExample7 singleton; // JVM保证这个方法只被调用一次 Singleton() { singleton = new SingletonExample7(); } public SingletonExample7 getInstance() { return singleton; } } }
package org.mge.ds.arrays; /** * Algorithm: * * Querying length of longest is fairly easy. Note that we are dealing with end * elements only. We need not to maintain all the lists. We can store the end * elements in an array. Discarding operation can be simulated with replacement, * and extending a list is analogous to adding more elements to array. * * We will use an auxiliary array to keep end elements. The maximum length of * this array is that of input. In the worst case the array divided into N lists * of size one (note that it does’t lead to worst case complexity). To discard * an element, we will trace ceil value of A[i] in auxiliary array (again * observe the end elements in your rough work), and replace ceil value with * A[i]. We extend a list by adding element to auxiliary array. We also maintain * a counter to keep track of auxiliary array length. * * 1. If A[i] is smallest among all end candidates of active lists, we will * start new active list of length 1. * * 2. If A[i] is largest among all end candidates of active lists, we will clone * the largest active list, and extend it by A[i]. * * 3. If A[i] is in between, we will find a list with largest end element that * is smaller than A[i]. Clone and extend this list by A[i]. We will discard all * other lists of same length as that of this modified list. **/ public class LongestIncreasingSubSequence { public static void main(String[] args) { int[] a = { 2, 5, 3, 7, 11, 8, 10, 13, 6 }; System.out.println("Length of Longest Increasing Subsequence is " + findLISLength(a)); } static int findLISLength(int a[]) { int n = a.length; int[] tailTable = new int[n]; int len = 1; tailTable[0] = a[0]; for (int i = 1; i < n; i++) { if (a[i] < tailTable[0]) { tailTable[0] = a[i]; } else if (a[i] > tailTable[len - 1]) { tailTable[len++] = a[i]; } else { int index = ceilIndex(tailTable, 0, len - 1, a[i]); tailTable[index] = a[i]; } } return len; } static int ceilIndex(int[] a, int l, int h, int key) { while ((h - l) > 1) { int m = (l + h) / 2; if (key > a[m]) { l = m + 1; } else { h = m - 1; } } return h; } }
/** * */ package org.opentosca.planbuilder.type.plugin.mysqldatabase; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.opentosca.planbuilder.model.tosca.AbstractDeploymentArtifact; import org.opentosca.planbuilder.model.tosca.AbstractImplementationArtifact; import org.opentosca.planbuilder.model.tosca.AbstractInterface; import org.opentosca.planbuilder.model.tosca.AbstractNodeTemplate; import org.opentosca.planbuilder.model.tosca.AbstractNodeType; import org.opentosca.planbuilder.model.tosca.AbstractNodeTypeImplementation; import org.opentosca.planbuilder.model.tosca.AbstractOperation; import org.opentosca.planbuilder.plugins.commons.Types; import org.opentosca.planbuilder.utils.Utils; /** * Copyright 2015 IAAS University of Stuttgart <br> * <br> * * @author Kalman Kepes - kepeskn@studi.informatik.uni-stuttgart.de * */ public class Util { public static boolean hasSqlScriptArtifact(List<AbstractDeploymentArtifact> das) { for (AbstractDeploymentArtifact da : das) { if (Util.isSqlScriptArtifact(da)) { return true; } } return false; } public static boolean isSqlScriptArtifact(AbstractDeploymentArtifact da) { if (da.getArtifactType().toString().equals(Constants.sqlScriptArtifactType.toString())) { return true; } return false; } public static List<AbstractImplementationArtifact> getIAsForInterfaces(List<AbstractImplementationArtifact> ias) { List<AbstractImplementationArtifact> iasForIfaces = new ArrayList<AbstractImplementationArtifact>(); for (AbstractImplementationArtifact ia : ias) { if ((ia.getOperationName() == null) || ia.getOperationName().equals("")) { iasForIfaces.add(ia); } } return iasForIfaces; } public static List<AbstractImplementationArtifact> getIAsForLifecycleInterface(List<AbstractImplementationArtifact> ias) { List<AbstractImplementationArtifact> iasForIfaces = new ArrayList<AbstractImplementationArtifact>(); for (AbstractImplementationArtifact ia : ias) { if (ia.getInterfaceName().equals("http://docs.oasis-open.org/tosca/ns/2011/12/interfaces/lifecycle")) { iasForIfaces.add(ia); } } return iasForIfaces; } public static List<AbstractImplementationArtifact> getIAsForOperations(List<AbstractImplementationArtifact> ias) { List<AbstractImplementationArtifact> iasForIfaces = new ArrayList<AbstractImplementationArtifact>(); for (AbstractImplementationArtifact ia : ias) { if ((ia.getOperationName() != null) && !ia.getOperationName().equals("")) { iasForIfaces.add(ia); } } return iasForIfaces; } /** * Checks whether there is some VM along the path from the given * nodeTemplate to the sinks of the Topology * * @param nodeTemplate an AbstractNodeTemplate * @return true iff there exists a path from the given NodeTemplate to a VM * Template in direction to the sinks */ public static boolean isConnectedToVM(AbstractNodeTemplate nodeTemplate) { List<AbstractNodeTemplate> nodes = new ArrayList<AbstractNodeTemplate>(); Utils.getNodesFromNodeToSink(nodeTemplate, nodes); for (AbstractNodeTemplate node : nodes) { if (Utils.checkForTypeInHierarchy(node, Types.vmNodeType) | Utils.checkForTypeInHierarchy(node, Types.ubuntu1310ServerNodeType)) { return true; } } return false; } /** * <p> * Searches for a NodeTypeImplementation which satisfies following * condition: <br> * - the nodeTypeImplementation has an IA for each operation of the TOSCA * lifecycle interface. <br> * * Note that the given nodeTemplate must define the TOSCA Lifecycle * interface so that the condition may be true * </p> * * @param nodeTemplate a NodeTemplate with a TOSCA Lifecycle interface * @return a NodeTypeImplementation which implements all operations of the * TOSCA Lifecycle interface of the given NodeTemplate, if not found * null */ public static AbstractNodeTypeImplementation selectLifecycleInterfaceNodeTypeImplementation(AbstractNodeTemplate nodeTemplate) { if (nodeTemplate == null) { return null; } AbstractNodeType nodeType = nodeTemplate.getType(); AbstractInterface usableIface = null; // check whether the nodeType contains any TOSCA interface for (AbstractInterface iface : nodeType.getInterfaces()) { if (iface.getName().equals("http://docs.oasis-open.org/tosca/ns/2011/12/interfaces/lifecycle")) { // check if we have operations to work with, e.g. install, // configure and start int toscaOperations = 0; for (AbstractOperation operation : iface.getOperations()) { switch (operation.getName()) { case "install": case "start": case "configure": toscaOperations++; break; default: break; } } if (toscaOperations != iface.getOperations().size()) { // we just accept pure TOSCA interfaces continue; } else { usableIface = iface; } } } for (AbstractNodeTypeImplementation nodeImpl : nodeTemplate.getImplementations()) { // check the IA's with the found interfaces, and if we found an IA // we // can use for one of the interfaces we'll use that List<AbstractImplementationArtifact> iasForInterfaces = Util.getIAsForLifecycleInterface(Util.getIAsForInterfaces(nodeImpl.getImplementationArtifacts())); List<AbstractImplementationArtifact> iasForOperations = Util.getIAsForLifecycleInterface(Util.getIAsForOperations(nodeImpl.getImplementationArtifacts())); // first check if we have an IA for a whole interface if (iasForInterfaces.size() == 1) { // found an implementation for the lifecycle interface -> // nodeTypeImpl will suffice return nodeImpl; } if (usableIface != null) { // check if operations in the interface are implementated by // single // ia's if (usableIface.getOperations().size() == iasForOperations.size()) { // TODO pretty vague check but should suffice return nodeImpl; } } else { // if the node doesn't have an interface basically no extra // operations will be executed, just upload of da's into the // right spots return nodeImpl; } } return null; } public static List<AbstractDeploymentArtifact> getSQLScriptArtifactDAs(List<AbstractDeploymentArtifact> das) { List<AbstractDeploymentArtifact> sqlDAs = new ArrayList<AbstractDeploymentArtifact>(); for (AbstractDeploymentArtifact da : das) { if (Util.isSqlScriptArtifact(da)) { sqlDAs.add(da); } } return sqlDAs; } /** * Removes duplicates from the given list * * @param das a List of DeploymentArtifacts * @return a possibly empty List of DeploymentArtifacts */ public static List<AbstractDeploymentArtifact> removeDuplicates(List<AbstractDeploymentArtifact> das) { if (das.size() == 0) { // list of size 0 has no duplicates return das; } AbstractDeploymentArtifact da = das.get(0); while (Collections.frequency(das, da) > 1 & das.size() > 0) { if (das.remove(da)) { da = das.get(0); } } return das; } /** * <p> * Searches for a NodeTypeImplementation with atleast one DA of type * {http://opentosca.org/types/declarative}SQLScriptArtifact * </p> * * @param nodeTemplate a NodeTemplate of type MySQLDatabase * @return a NodeTypeImplementation if found, else null */ public static AbstractNodeTypeImplementation selectSQLFileNodeTypeImplementation(AbstractNodeTemplate nodeTemplate) { if (nodeTemplate == null) { return null; } for (AbstractNodeTypeImplementation nodeImpl : nodeTemplate.getImplementations()) { // check if nodeImpl has SQL DA's if (Util.hasSqlScriptArtifact(nodeImpl.getDeploymentArtifacts())) { return nodeImpl; } } return null; } public static boolean canDeployNodeTemplate(AbstractNodeTemplate nodeTemplate) { if (Util.selectSQLFileNodeTypeImplementation(nodeTemplate) != null) { // the easiest implementation return true; } if (Util.selectLifecycleInterfaceNodeTypeImplementation(nodeTemplate) != null) { // "standard" lifecycle interface handling (deploy da's, deploy // ia's, execute ia/op's,..) return true; } // check nodeTemplate itself, you can attach DA's to nodeTemplates if (Util.hasSqlScriptArtifact(nodeTemplate.getDeploymentArtifacts())) { // this means we can use an SQL file to deploy the sql schema return true; } return false; } }
package com.mikronia.pixpaint.component.dialogs; import java.awt.BorderLayout; import java.awt.Desktop; import java.awt.event.WindowEvent; import java.io.File; import java.io.IOException; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JSeparator; import javax.swing.SwingConstants; import com.mikronia.pixpaint.component.PixDialog; import com.mikronia.pixpaint.locale.Language; import com.mikronia.pixpaint.application.Constants; import com.mikronia.pixpaint.application.Properties; /** * PixPaint settings dialog * * @since PixPaint 1.0.0 * @version 1.0 * * @author Thaynan M. Silva */ public class SettingsDialog extends PixDialog { private static final long serialVersionUID = 1L; private boolean restartRequired = false; public SettingsDialog() { super("dialog.settings.title", 340, 340); } @Override protected void createComponents() { JPanel controlPanel = new JPanel(null); add(controlPanel, BorderLayout.CENTER); ///////////////////// JLabel lbLanguage = new JLabel(getLanguage("dialog.settings.label.language")); lbLanguage.setBounds(10, 15, 150, 20); lbLanguage.setHorizontalAlignment(SwingConstants.RIGHT); controlPanel.add(lbLanguage); JComboBox<Language> cbLanguage = new JComboBox<Language>(Registry.getLanguages()); cbLanguage.setSelectedItem(Language.getCurrentLanguage()); cbLanguage.setBounds(170, 10, 160, 30); cbLanguage.addActionListener((e) -> { var selectedLanguage = Registry.getLanguageByIndex(cbLanguage.getSelectedIndex()); var selectedLanguageLocale = selectedLanguage.getLocale(); Properties.setProperty(Properties.CFG_LANGUAGE, selectedLanguageLocale); boolean propertyEffectivelyChanged = !Language.getCurrentLanguage(). equals(selectedLanguage); if (propertyEffectivelyChanged && !restartRequired) { restartRequired = true; } }); controlPanel.add(cbLanguage); JLabel lbAppearance = new JLabel(getLanguage("dialog.settings.label.appearance")); lbAppearance.setBounds(10, 55, 150, 20); lbAppearance.setHorizontalAlignment(SwingConstants.RIGHT); controlPanel.add(lbAppearance); JComboBox<String> cbLookAndFeel = new JComboBox<String>( LookAndFeelUtil.getInstalledLookAndFeelNames()); cbLookAndFeel.setSelectedItem(LookAndFeelUtil.getCurrentLookAndFeelName()); cbLookAndFeel.setBounds(170, 50, 160, 30); cbLookAndFeel.addActionListener((e) -> { String selectedLookAndFeelName = cbLookAndFeel.getSelectedItem().toString(); Properties.setProperty(Properties.CFG_LOOK, LookAndFeelUtil. getInstalledLookAndFeelClassNameByName(selectedLookAndFeelName)); boolean propertyEffectivelyChanged = !LookAndFeelUtil.getCurrentLookAndFeelName(). equals(selectedLookAndFeelName); if (propertyEffectivelyChanged && !restartRequired) { restartRequired = true; } }); controlPanel.add(cbLookAndFeel); ///////////////////// JSeparator separator1 = new JSeparator(JSeparator.HORIZONTAL); separator1.setBounds(40, 90, 240, 4); controlPanel.add(separator1); ///////////////////// JCheckBox cbEnableBackup = new JCheckBox(getLanguage("dialog.settings.enablebackup"), Properties.getProperty(Properties.CFG_BACKUP_ENABLE, Constants.backupEnabled)); cbEnableBackup.setBounds(20, 100, 300, 20); cbEnableBackup.addActionListener((e) -> Properties.setProperty( Properties.CFG_BACKUP_ENABLE, cbEnableBackup.isSelected())); controlPanel.add(cbEnableBackup); JCheckBox cbShowStatus = new JCheckBox(getLanguage("dialog.settings.showstatus"), Properties.getProperty(Properties.CFG_SHOW_STATUS, Constants.statusVisible)); cbShowStatus.setBounds(20, 125, 300, 20); cbShowStatus.addActionListener((e) -> Properties.setProperty( Properties.CFG_SHOW_STATUS, cbShowStatus.isSelected())); controlPanel.add(cbShowStatus); ///////////////////// JSeparator separator2 = new JSeparator(JSeparator.HORIZONTAL); separator2.setBounds(40, 155, 240, 4); controlPanel.add(separator2); ///////////////////// JButton btShowBackups = new JButton(getLanguage("dialog.settings.showbackups")); btShowBackups.setBounds(20, 165, 300, 30); btShowBackups.addActionListener((e) -> { try { Desktop.getDesktop().open(new File(Constants.backupsDirectory)); } catch (IOException ex) { ex.printStackTrace(); } }); controlPanel.add(btShowBackups); JButton btShowLogs = new JButton(getLanguage("dialog.settings.showlogs")); btShowLogs.setBounds(20, 200, 300, 30); btShowLogs.addActionListener((e) -> { try { Desktop.getDesktop().open(new File(Constants.logsDirectory)); } catch (IOException ex) { ex.printStackTrace(); } }); controlPanel.add(btShowLogs); JButton btShowPlugins = new JButton(getLanguage("dialog.settings.showplugins")); btShowPlugins.setBounds(20, 235, 300, 30); btShowPlugins.addActionListener((e) -> { try { Desktop.getDesktop().open(new File(Constants.pluginsDirectory)); } catch (IOException ex) { ex.printStackTrace(); } }); controlPanel.add(btShowPlugins); ///////////////////// JPanel bottomPanel = new JPanel(); add(bottomPanel, BorderLayout.SOUTH); JButton btClose = new JButton(getLanguage("dialog.settings.close")); btClose.addActionListener((e) -> dispose()); bottomPanel.add(btClose, BorderLayout.CENTER); } ///////////////////////// @Override public void windowClosing(WindowEvent e) { super.windowClosing(e); if (restartRequired) { JOptionPane.showMessageDialog(this, getLanguage("app.message.warning.restart"), getTitle(), JOptionPane.WARNING_MESSAGE); } } }
package com.tencent.mm.ac; import com.tencent.mm.ab.l; public interface p$a<T extends l> { void b(int i, int i2, String str, T t); }
/* * 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 javabankproject; /** * * @author Novin Pendar */ public class JavaBankProject { /** * @param args the command line arguments */ public static void main(String[] args) { JFrameSetAdminData jfarmeSetAdminData = new JFrameSetAdminData() ; jfarmeSetAdminData.setVisible(true) ; // JFrameMainMenu jframeMainMenu = new JFrameMainMenu() ; // jframeMainMenu.setVisible(true) ; } }
import java.util.Stack; class StockSpanner { static class Node { int price; int val; public Node(int price, int val) { this.price = price; this.val = val; } } Stack<Node> stack = new Stack<>(); public StockSpanner() { } public int next(int price) { int result = 1; while(!stack.isEmpty() && stack.peek().price <= price) { Node node = stack.pop(); result+=node.val; } stack.push(new Node(price, result)); return result; } public static void main(String[] args) { StockSpanner spanner = new StockSpanner(); System.out.println(spanner.next(100)); System.out.println(spanner.next(80)); System.out.println(spanner.next(60)); System.out.println(spanner.next(70)); System.out.println(spanner.next(60)); System.out.println(spanner.next(75)); System.out.println(spanner.next(85)); } }
package crawl; import model.*; import nlp.TagAnalyzer; import scorer.CommentScorer; import java.io.IOException; import java.time.LocalDateTime; import java.util.List; public class BasicCommentQueryer extends CommentQueryer { private TagAnalyzer analyzer; private CommentCrawler crawler; private CommentScorer scorer; public BasicCommentQueryer(Product product, TagAnalyzer analyzer, CommentCrawler crawler, CommentScorer scorer) { super(product); this.analyzer = analyzer; this.crawler = crawler; this.scorer = scorer; } @Override protected CommentQuery query() throws IOException { if (product.getComments().getQueries().isEmpty()) { List<Comment> comments = crawler.crawlAll(product.getId()); List<Tag> tags = analyzer.analyse(comments); LocalDateTime now = LocalDateTime.now(); return new CommentQuery(comments, tags, now); } else { List<CommentQuery> queries = product.getComments().getQueries(); LocalDateTime time = queries.get(queries.size() - 1).getTime(); List<Comment> comments = crawler.crawlFrom(product.getId(), time); List<Tag> tags = analyzer.analyse(comments); LocalDateTime now = LocalDateTime.now(); return new CommentQuery(comments, tags, now); } } @Override protected CommentSummary summary(List<CommentQuery> queries) { return scorer.evaluate(queries); } }
package hk.com.kycheungal.girlsfrontline; import android.content.ContentValues; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by fujitsu on 19/3/2017. */ public class DBHelper extends SQLiteOpenHelper { public static final String DB_NAME = "GirlsFrontLine.db"; public static final String Table_Name = "Girls_table"; public static final String Col_1 = "ID"; public static final String Col_2 = "Lv"; public static final String Col_3 = "No_Of_People"; public static final String Col_4 = "Skill_Lv"; public DBHelper(Context context) { super(context, DB_NAME, null, 1); } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { sqLiteDatabase.execSQL("create table " + Table_Name + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, Lv INTEGER, No_Of_People INTEGER, Skill_Lv INTEGER)"); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { sqLiteDatabase.execSQL("DROP TABLE IF EXIST " + Table_Name); onCreate(sqLiteDatabase); } public boolean insertData(int lv, int noOfPeople, int skillLv) { SQLiteDatabase sqLiteDatabase = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(Col_2, lv); contentValues.put(Col_3, noOfPeople); contentValues.put(Col_4, skillLv); Long result = sqLiteDatabase.insert(Table_Name, null, contentValues); if (result == -1) return false; else return true; } }
import java.util.ArrayList; import java.util.Scanner; public class paskaita9 { public static void main(String[] args) { ArrayList<String> listas = new ArrayList<>(); boolean tikrinimas = true; Scanner sc = new Scanner(System.in); String inputString; String didString = ""; while (listas.size() < 5) { System.out.println("áveskite ţodá!"); inputString = (sc.next()); listas.add(inputString); // if (listas.size() < 5) { // if(listas.contains(inputString)) { // System.out.println("kartojasi"); // } else { // listas.add(inputString); // // } // } // else { // System.out.println(listas); // listas.clear(); // listas.add(inputString); // } } // SHORT for each // for (String elm : listas) { // if (didString.length() < elm.length()) { // didString = elm; // }yug // } //// FOR EACH pilnas for (int i = 0; i < (listas.size()); i++) { if (didString.length() < listas.get(i).length()) { didString = listas.get(i); //jai reikia breako <----- // if (didString.length()>2) { // break; // } } } System.out.println(didString); sc.close(); } }
package cn.edu.nju.se.lawcase.util; import java.io.File; public class GeneralTest { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub File file = new File("F:\\法律大全-资料\\法条库\\宪法类\\中华人民共和国国务院组织法-(1982-12-10).txt"); System.out.println(file.getAbsolutePath()); } }
package com.box.androidsdk.content.models; import com.eclipsesource.json.JsonArray; import com.eclipsesource.json.JsonObject; import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; /** * A collection that contains a subset of items that are a part of a larger collection. The items within a partial collection begin at an offset within the full * collection and end at a specified limit. Note that the actual size of a partial collection may be less than its limit since the limit only specifies the * maximum size. For example, if there's a full collection with a size of 3, then a partial collection with offset 0 and limit 3 would be equal to a partial * collection with offset 0 and limit 100. * * @param <E> the type of elements in this partial collection. */ public abstract class BoxIterator<E extends BoxJsonObject> extends BoxJsonObject implements Iterable<E> { private static final long serialVersionUID = 8036181424029520417L; public static final String FIELD_ORDER = "order"; public static final String FIELD_TOTAL_COUNT = "total_count"; public static final String FIELD_ENTRIES = "entries"; public static final String FIELD_OFFSET = "offset"; public static final String FIELD_LIMIT = "limit"; public static final String FIELD_NEXT_MARKER = "next_marker"; public static final String FIELD_SORT = "sort"; public BoxIterator() { super(); } public BoxIterator(JsonObject jsonObject) { super(jsonObject); } @Override public void createFromJson(JsonObject object) { super.createFromJson(object); } /** * Gets the offset within the full collection where this collection's items begin. * * @return the offset within the full collection where this collection's items begin. */ public Long offset() { return getPropertyAsLong(FIELD_OFFSET); } /** * Gets the maximum number of items within the full collection that begin at {@link #offset}. * * @return the maximum number of items within the full collection that begin at the offset. */ public Long limit() { return getPropertyAsLong(FIELD_LIMIT); } /** * Gets the size of the full collection that this partial collection is based off of. * * @return the size of the full collection that this partial collection is based off of. */ public Long fullSize() { return getPropertyAsLong(FIELD_TOTAL_COUNT); } public int size() { if (getEntries() == null) { return 0; } else { return getEntries().size(); } } public ArrayList<E> getEntries(){ return getPropertyAsJsonObjectArray(getObjectCreator(), FIELD_ENTRIES); } public E get(int index) { return (E)getAs(getObjectCreator(), index); } protected abstract BoxJsonObjectCreator<E> getObjectCreator(); public E getAs(BoxJsonObjectCreator<E> creator, int index) { return getEntries().get(index); } public ArrayList<BoxOrder> getSortOrders() { return getPropertyAsJsonObjectArray(BoxJsonObject.getBoxJsonObjectCreator(BoxOrder.class), FIELD_ORDER); } public Iterator<E> iterator(){ return getEntries() == null ? Collections.<E>emptyList().iterator() : getEntries().iterator(); } /** * If using marker based paging returns the next marker if available. Returns null if no additional * items. * @return next marker if available or null if no items left. */ public String getNextMarker(){ return getPropertyAsString(FIELD_NEXT_MARKER); } }
package pl.luwi.series.distributed; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class TaskOrderedLine<P extends OrderedPoint> implements Serializable { public Integer RDPID; public Integer lineID; public List<P> points; private P start; private P end; private double dx; private double dy; private double sxey; private double exsy; private double length; public TaskOrderedLine(List<P> points, int RDPID, int lineID) { this.RDPID = RDPID; this.lineID = lineID; this.start = points.get(0); this.points = points; this.end = points.get(points.size() - 1); dx = start.getX() - end.getX(); dy = start.getY() - end.getY(); sxey = start.getX() * end.getY(); exsy = end.getX() * start.getY(); length = Math.sqrt(dx*dx + dy*dy); } private TaskOrderedLine(List<P> points, int RDPID){ this.RDPID = RDPID; this.start = points.get(0); this.points = points; this.end = points.get(points.size() - 1); dx = start.getX() - end.getX(); dy = start.getY() - end.getY(); sxey = start.getX() * end.getY(); exsy = end.getX() * start.getY(); length = Math.sqrt(dx*dx + dy*dy); } @SuppressWarnings("unchecked") public List<P> asList() { return Arrays.asList(start, end); } public double distance(OrderedPoint p) { return Math.abs(dy * p.getX() - dx * p.getY() + sxey - exsy) / length; } public P getStart() { return start; } public P getEnd() { return end; } public RDPresult<P> asResult(){ ArrayList<P> results = new ArrayList<>(2); results.add(getStart()); results.add(getEnd()); return new RDPresult<P>(null, results); } public RDPresult<P> asSplit(int index){ List<TaskOrderedLine<P>> lines = new ArrayList<>(); List<P> a = new ArrayList<P>(points.subList(0, index + 1)); lines.add(new TaskOrderedLine<P>(a, this.RDPID)); List<P> b = new ArrayList<P>(points.subList(index, points.size())); lines.add(new TaskOrderedLine<P>(b, this.RDPID)); return new RDPresult<P>(lines, null); } public class RDPresult<E extends OrderedPoint>{ List<TaskOrderedLine<E>> lines; List<E> points; public RDPresult(List<TaskOrderedLine<E>> lines, List<E> points){ this.lines = lines; this.points = points; } } }
/** * */ package com.trs.om.rbac.impl; import java.util.ArrayList; import java.util.List; import java.util.Properties; import org.apache.log4j.Logger; import org.springframework.transaction.annotation.Transactional; import com.trs.om.rbac.AuthorizationException; import com.trs.om.rbac.IAuthorization; import com.trs.om.rbac.IAuthorizationServer; import com.trs.om.rbac.IPermissionManager; import com.trs.om.rbac.IPrivilegeManager; import com.trs.om.rbac.IRoleManager; import com.trs.om.rbac.ISessionManager; import com.trs.om.bean.Permission; import com.trs.om.bean.Privilege; import com.trs.om.bean.Session; /** * @author Administrator * */ public class AuthorizationServer implements IAuthorizationServer { /** * */ private final static Logger logger = Logger.getLogger(AuthorizationServer.class); /** * */ private IPermissionManager permissionManager; /** * */ private IPrivilegeManager privilegeManager; /** * */ private IRoleManager roleManager; /** * */ private ISessionManager sessionManager; /** * @param managerServiceClass * @throws AuthorizationException */ public void start(String managerServiceClass,String daoServiceClass,Properties properties) throws AuthorizationException{ } /** * */ public void stop(){ } @Transactional public int canDoAsPrivilege(Long userId, String application, String object, String operation) throws AuthorizationException { if ( application == null || object == null || operation == null ){ throw new IllegalArgumentException("application|object|operation is null"); } Permission permission = permissionManager.getPermission(application,object,operation); if ( null == permission ) return IAuthorization.OPERATION_DENIED; List sessions = sessionManager.findSessionsByUser(userId); for ( int i = 0 ; i < sessions.size() ; i++ ){ Privilege previlige = privilegeManager.getPrivilege(permission.getId(),((Session)sessions.get(i)).getRoleId()); if ( previlige != null ){ return IAuthorization.OPERATION_ALLOWED; } } return IAuthorization.OPERATION_DENIED; } /* * (non-Javadoc) * @see com.trs.om.rbac.IAuthorizationServer#canDoAsPrevilige(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String) */ @Transactional public int canDoAsPrivilege(Long userId, String application, String object, String operation, String otherPermissions) throws AuthorizationException { return canDoAsPrivilege(userId,application,object,operation); } /* * (non-Javadoc) * @see com.trs.om.rbac.IAuthorizationServer#canDoAsPrevilige(java.lang.String, java.lang.String, java.lang.String) */ @Transactional public int canDoAsPrivilege(Long userId, String application, String permission) throws AuthorizationException { if ( permission == null ){ throw new IllegalArgumentException("application|object|operation is null"); } // int index = permission.indexOf(":"); String object = null,operation = null; if ( index > 0 ){ object = permission.substring(0, index); operation = permission.substring(index+1,permission.length()); } // return canDoAsPrivilege(userId,application,object,operation); } /* * (non-Javadoc) * @see com.trs.om.rbac.IAuthorizationServer#getOperations(java.lang.String, java.lang.String, java.lang.String) */ @Transactional public List getOperations(Long userId, String application, String object) throws AuthorizationException { if ( application == null || object == null ){ throw new IllegalArgumentException("application|object is null"); } // List operations = new ArrayList(); List sessions = sessionManager.findSessionsByUser(userId); for ( int i = 0 ; i < sessions.size() ; i++ ){ List previliges = privilegeManager.findPrivileges(null,((Session)sessions.get(i)).getRoleId()); for ( int j = 0 ; j < previliges.size() ; j++ ){ Permission permission = permissionManager.getPermission(((Privilege)previliges.get(j)).getPermissionId()); if ( permission == null ) continue; if ( application.equals(permission.getApplication()) && object.equals(permission.getObject()) ){ operations.add(permission.getOperation()); } } } // return operations; } /* * (non-Javadoc) * @see com.trs.om.rbac.IAuthorizationServer#getPermissions(java.lang.String, java.lang.String) */ @Transactional public List getPermissions(Long userId, String application) throws AuthorizationException { if ( application == null ){ throw new IllegalArgumentException("application is null"); } // List permissions = new ArrayList(); List sessions = sessionManager.findSessionsByUser(userId); for ( int i = 0 ; i < sessions.size() ; i++ ){ List previliges = privilegeManager.findPrivileges(null,((Session)sessions.get(i)).getRoleId()); for ( int j = 0 ; j < previliges.size() ; j++ ){ Permission permission = permissionManager.getPermission(((Privilege)previliges.get(j)).getPermissionId()); if ( permission == null ) continue; if ( application.equals(permission.getApplication()) ){ permissions.add(permission); } } } // return permissions; } /* * (non-Javadoc) * @see com.trs.om.rbac.IAuthorizationServer#registerPermission(java.lang.String, java.lang.String, java.lang.String) */ @Transactional public int registerPermission(String application, String object, String operation) throws AuthorizationException { Permission permission = permissionManager.getPermission(application, object, operation); if ( null != permission ){ permission.setApplication(application); permission.setObject(object); permission.setOperation(operation); permissionManager.updatePermission(permission); }else{ permissionManager.addNewPermission(application, object, operation); } return 0; } /* * (non-Javadoc) * @see com.trs.om.rbac.IAuthorizationServer#unregisterPermission(java.lang.String, java.lang.String, java.lang.String) */ @Transactional public int unregisterPermission(String application, String object, String operation) throws AuthorizationException { permissionManager.deletePermission(application,object,operation); return 0; } /** * */ @Transactional public int registerPrevilige(Long roleId, String application, String object, String operation) throws AuthorizationException { Permission permission = permissionManager.getPermission(application,object,operation); if ( null == permission ) { permission = permissionManager.addNewPermission(application, object, operation); privilegeManager.addNewPrivilege(roleId, permission.getId()); } return 0; } /** * */ @Transactional public int unregisterPrevilige(Long roleId, String application, String object, String operation) throws AuthorizationException { Permission permission = permissionManager.getPermission(application,object,operation); if ( null != permission ) { Privilege previlige = privilegeManager.getPrivilege(permission.getId(), roleId); privilegeManager.deletePrivilege(previlige.getId()); } return 0; } /* * (non-Javadoc) * @see com.trs.om.rbac.IAuthorizationServer#getRoles(java.lang.String) */ @Transactional public List getRoles(Long userId) throws AuthorizationException { List sessions = sessionManager.findSessionsByUser(userId); List roles = new ArrayList(); for ( int i = 0 ; i < sessions.size() ; i++ ){ roles.add(((Session)sessions.get(i)).getRoleId()); } return null; } /* * (non-Javadoc) * @see com.trs.om.rbac.IAuthorizationServer#registerSession(java.lang.String, java.lang.String) */ // public int registerSession(Long user, Long role) // throws AuthorizationException { // Session session = sessionManager.getSession(user,role); // if ( session == null ){ // sessionManager.addNewSession(role, user); // } // return 0; // } /** * */ @Transactional public int unregisterSession(Long userId, Long roleId) throws AuthorizationException { Session session = sessionManager.getSession(userId,roleId,null); if ( session != null ){ sessionManager.deleteSession(session.getId()); } return 0; } /** * */ public IPermissionManager getPermissionManager() { return this.permissionManager; } /** * */ public IPrivilegeManager getPrivilegeManager() { return this.privilegeManager; } /** * */ public IRoleManager getRoleManager() { return this.roleManager; } /** * */ public ISessionManager getSessionManager() { return this.sessionManager; } public void setPermissionManager(IPermissionManager permissionManager) { this.permissionManager = permissionManager; } public void setPrivilegeManager(IPrivilegeManager privilegeManager) { this.privilegeManager = privilegeManager; } public void setRoleManager(IRoleManager roleManager) { this.roleManager = roleManager; } public void setSessionManager(ISessionManager sessionManager) { this.sessionManager = sessionManager; } }
package org.fuserleer.console; import java.io.PrintStream; import java.time.Instant; import java.util.Collection; import java.util.Date; import java.util.stream.Collectors; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.fuserleer.Context; import org.fuserleer.apps.SimpleWallet; import org.fuserleer.crypto.ECPublicKey; import org.fuserleer.crypto.Identity; import org.fuserleer.ledger.atoms.Atom; import org.fuserleer.ledger.atoms.MessageParticle; import org.fuserleer.ledger.atoms.Particle.Spin; import org.fuserleer.serialization.Serialization; import org.fuserleer.serialization.DsonOutput.Output; import org.fuserleer.time.Time; public class Messages extends Function { private final static Options options = new Options().addOption(Option.builder("send").desc("Sends a message to an address").numberOfArgs(1).build()) .addOption("sent", false, "Lists sent messages") .addOption("inbox", false, "Lists received messages"); public Messages() { super("messages", options); } @Override public void execute(Context context, String[] arguments, PrintStream printStream) throws Exception { CommandLine commandLine = Function.parser.parse(options, arguments); SimpleWallet wallet = Wallet.get(context); if (wallet == null) throw new IllegalStateException("No wallet is open"); if (commandLine.hasOption("send") == true) { Identity receiver = Identity.from(commandLine.getOptionValue("send")); String message = commandLine.getArgList().stream().collect(Collectors.joining(" ")); MessageParticle messageParticle = new MessageParticle(message, wallet.getIdentity(), receiver, Time.getSystemTime()); wallet.sign(messageParticle); Atom atom = new Atom(messageParticle); wallet.submit(atom); printStream.println(Serialization.getInstance().toJson(atom, Output.API)); } else if (commandLine.hasOption("sent") == true) { Collection<MessageParticle> messages = wallet.get(MessageParticle.class, Spin.UP); for (MessageParticle message : messages) { if (message.getSender().equals(wallet.getIdentity()) == false) continue; printStream.println(message.getHash()+" "+Date.from(Instant.ofEpochMilli(message.getCreatedAt()))+" "+message.getRecipient()+" "+message.getMessage()); } } else if (commandLine.hasOption("inbox") == true) { Collection<MessageParticle> messages = wallet.get(MessageParticle.class, Spin.UP); for (MessageParticle message : messages) { if (message.getRecipient().equals(wallet.getIdentity()) == false) continue; printStream.println(message.getHash()+" "+Date.from(Instant.ofEpochMilli(message.getCreatedAt()))+" "+message.getSender()+" "+message.getMessage()); } } } }
package com.douane.dpworld.service; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Set; import java.util.stream.Collector; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import com.douane.config.ConstVar; import com.douane.dpworld.entities.Debarquement; import com.douane.dpworld.repository.DebarquementRepository; import com.douane.service.MessageDaoService; @Component public class DebarquementService { @Autowired private DebarquementRepository debarquementRepository; @Autowired private MarkedService markedService; @Autowired private MessageDaoService msgService; @Autowired private RestTemplate template; public int doFetch() { try { // fetch API and save response ResponseEntity<Debarquement[]> response = template.getForEntity(ConstVar.URL_debarquement,Debarquement[].class); // get body response Debarquement[] body = response.getBody(); // convert body to List with same argumant List<Debarquement> apiList = new ArrayList<Debarquement>(); apiList = Arrays.asList(body); System.out.println(apiList.size()); // getAll items saved in data base ArrayList<Debarquement> listDB = (ArrayList<Debarquement>) debarquementRepository.findAll(); System.out.println(listDB.size()); // get ids from DB list Set<Integer> ids = listDB.stream().map(Debarquement::getId).collect(Collectors.toSet()); // deffirence between tow list List<Debarquement> parentlist = apiList.stream() .filter(debarquement -> !ids.contains(debarquement.getId())).collect(Collectors.toList()); System.out.println(parentlist.size()); int count_save = parentlist.size(); parentlist.stream().forEach(item -> item.setAjoute(new Date())); // save deffirence in data base debarquementRepository.saveAll(parentlist) ; // marked items // logs details if(count_save>0) this.msgService.saveMessage("Debarquement", parentlist.get(0).getId(), parentlist.get(count_save-1).getId()); return count_save; }catch (Exception e) { return 0 ; } } }
package com.sunzequn.sdfs.socket.client; /** * Created by Sloriac on 2016/12/16. */ public class KeepAliveHandler extends Thread { private long lastTime; private SockClient client; public KeepAliveHandler(long lastTime, SockClient client) { this.lastTime = lastTime; this.client = client; } @Override public void run() { while (true) { try { if (System.currentTimeMillis() - lastTime > SockClient.getDELAY()) { client.sendAliveInfo(); lastTime = System.currentTimeMillis(); } else { Thread.sleep(SockClient.getDELAY()); } } catch (Exception e) { e.printStackTrace(); return; } } } }
package oop3; public class Calculator { int plus(int x, int y) { System.out.println("int+int의 합 계산"); int result = x+y; return result; } int plus(int x, int y, int z) { System.out.println("int+int+int의 합 계산"); int result = x+y+z; return result; } double plus(double x, double y) { System.out.println("double+double의 합 계산"); double result = x+y; return result; } long plus(long x, long y) { System.out.println("long+long의 합 계산"); long result = x+y; return result; } }
package main.form.strategy; import java.lang.reflect.Field; public class NativeLabelNamingStrategy implements LabelNamingStrategy { public String designName(Field field) { return field.getName(); } }
package org.a55889966.bleach.saran.tourguide; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import androidx.annotation.NonNull; import androidx.core.app.ActivityCompat; import androidx.core.content.FileProvider; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; import android.widget.ExpandableListView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; 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 com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; public class ProfileEventActivity extends AppCompatActivity implements CostAdapter.ClickListener { private DatabaseReference eventReference; private FirebaseAuth firebaseAuth; private DatabaseReference expenseReference; private DatabaseReference pictureRef; private String eventId; private String userId; private double eventBudget; //for expandable list View private ExpandableListView expandableListView; private ExpandableListAdapter adapter; private List<String> listDataHeader; private HashMap<String, List<String>> listDataChild; private ProgressBar progressBar; private TextView tourAreaTv,budgetStatusTv; private EventClass event; private androidx.appcompat.widget.Toolbar toolbar; private double budged; private double haveMoney; //firebase Stroage StorageReference firebaseStorage; private static final int STORAGE_REQUEST_CODE = 5; private static final int CAMERA_REQUEST_CODE = 6; String captureImagePath ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile_event); /***************Opening Activity***************/ toolbar = (androidx.appcompat.widget.Toolbar) findViewById(R.id.app_bar); progressBar = findViewById(R.id.amountProgress); tourAreaTv = findViewById(R.id.tourAreaTv); budgetStatusTv = findViewById(R.id.budgetStatusTv); expandableListView = findViewById(R.id.expandableListView); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); event = (EventClass) getIntent().getSerializableExtra("Event"); eventId = event.getEventId(); eventBudget = event.getBudget(); firebaseAuth = FirebaseAuth.getInstance(); userId = firebaseAuth.getCurrentUser().getUid(); //firebase Stroage firebaseStorage = FirebaseStorage.getInstance().getReference(); prepareListData(); adapter = new ExpandableListAdapter(this,listDataHeader,listDataChild); expandableListView.setAdapter(adapter); expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() { @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { //Expandable ListView Click Method onClickExpandableListView(groupPosition,childPosition); return false; } }); eventReference = FirebaseDatabase.getInstance().getReference("Event"); eventReference.keepSynced(true); expenseReference = FirebaseDatabase.getInstance().getReference("Event").child(userId).child(eventId); expenseReference.keepSynced(true); pictureRef = FirebaseDatabase.getInstance().getReference("Picture").child(userId).child(eventId); } // for adding expense thorough alert dialog private void addExpense(String costTittle, double costAmount, String finalDate) { String expenseId = expenseReference.push().getKey(); ExpenseClass expenseClass = new ExpenseClass(userId,eventId,expenseId,costAmount,costTittle,finalDate); expenseReference.child("Expense").child(expenseId).setValue(expenseClass).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()){ Toast.makeText(ProfileEventActivity.this, "data imported", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(ProfileEventActivity.this, "data not imported", Toast.LENGTH_SHORT).show(); } } }); } // get all basic info of this event private void showEventBasicInformation() { eventReference.child(userId).child(eventId).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot.getValue() != null){ EventClass eventClass = dataSnapshot.getValue(EventClass.class); String eventName = eventClass.getEventName(); String staringLocation = eventClass.getStartingLocation(); String destinationLocation = eventClass.getDestination(); budged = eventClass.getBudget(); toolbar.setTitle(eventName); tourAreaTv.setText(staringLocation+" To "+destinationLocation); ////////////Anoter method ////////// showProgressInProgressBer(budged); } else { Toast.makeText(ProfileEventActivity.this, "Value not gated", Toast.LENGTH_SHORT).show(); } } @Override public void onCancelled(DatabaseError databaseError) { Toast.makeText(ProfileEventActivity.this, ""+databaseError.getMessage(), Toast.LENGTH_SHORT).show(); } }); } // For Updating ProgressBer private void showProgressInProgressBer(final double budged) { expenseReference.child("Expense").addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot.getValue() != null){ // expense is already Added in Database double totalCost =0; for (DataSnapshot expens : dataSnapshot.getChildren()){ ExpenseClass expenseClass = expens.getValue(ExpenseClass.class); double newCost = expenseClass.getExpenseAmount(); totalCost+=newCost; } if (totalCost>0){ double progress = (100*totalCost)/budged; int progressInt = (int)progress; progressBar.setProgress(progressInt); haveMoney = budged -totalCost; String hMS = String.valueOf(haveMoney); budgetStatusTv.setText("You have "+hMS+" taka out of "+ budged +" taka"); } } else { // Expense is not Aready Added in Activity haveMoney = ProfileEventActivity.this.budged; budgetStatusTv.setText("You have "+ ProfileEventActivity.this.budged +" taka out of "+ ProfileEventActivity.this.budged +" taka"); } } @Override public void onCancelled(DatabaseError databaseError) { Toast.makeText(ProfileEventActivity.this, ""+databaseError.getMessage(), Toast.LENGTH_SHORT).show(); } }); } //Expandable ListView // Prepare Data For Expandable List View private void prepareListData() { listDataHeader = new ArrayList<String>(); listDataChild = new HashMap<String, List<String>>(); // Adding Head data listDataHeader.add("Expenditure"); listDataHeader.add("Moments"); listDataHeader.add("More on Event.."); // Adding child data List<String> expenditure = new ArrayList<String>(); expenditure.add("Add New Expense"); expenditure.add("View All Expense"); expenditure.add("Add more Budget"); List<String> moments = new ArrayList<String>(); moments.add("Take a Photo"); moments.add("Pick Image From Gallery"); moments.add("View All Moments"); List<String> moreOnEvent = new ArrayList<String>(); moreOnEvent.add("Edit Event"); moreOnEvent.add("Delete Event"); listDataChild.put(listDataHeader.get(0), expenditure); // Header, Child data listDataChild.put(listDataHeader.get(1), moments); listDataChild.put(listDataHeader.get(2), moreOnEvent); } //Expandable ListView Click Method // For get Spection Position Of item Click private void onClickExpandableListView(int groupPosition, int childPosition) { switch (groupPosition){ case 0: //Expenditure switch (childPosition){ case 0: //Add New Expense addNewExpense(); break; case 1: // View All Expense costItemList(); break; case 2: //Add More Budget addMoreBudget(); break; } break; case 1: //Moment switch (childPosition){ case 0: //Take Photo takePhoto(); break; case 1: //Pick Image From Gallery pickImageFromGallery(); break; case 2: //View All Moments viewAllMoments(); break; } break; case 2: switch (childPosition){ case 0: //Edit Event editEvent(); break; case 1: //Delete Event deleteEvent(); break; } break; } } private void viewAllMoments() { Intent intent = new Intent(this,MomentGalleryActivity.class); intent.putExtra("eventId",eventId); intent.putExtra("userId",userId); startActivity(intent); } public void takePhoto() { if(ActivityCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED){ ActivityCompat.requestPermissions(this,new String[]{android.Manifest.permission.CAMERA},101); return; } Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (takePictureIntent.resolveActivity(getPackageManager()) != null) { // Create the File where the photo should go File photoFile = null; try { photoFile = createImageFile(); } catch (IOException ex) { // Error occurred while creating the File } // Continue only if the File was successfully created if (photoFile != null) { Uri photoURI = FileProvider.getUriForFile(this, "org.a55889966.bleach.saran.tourguide.fileprovider", photoFile); takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI); startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE); } } } private File createImageFile() throws IOException { // Create an image file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = "JPEG_" + timeStamp + "_"; File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES); File image = File.createTempFile( imageFileName, /* prefix */ ".jpg", /* suffix */ storageDir /* directory */ ); // Save a file: path for use with ACTION_VIEW intents captureImagePath = image.getAbsolutePath(); return image; } private void pickImageFromGallery() { Intent intent = new Intent(Intent.ACTION_PICK); intent.setType("image/*"); startActivityForResult(intent,STORAGE_REQUEST_CODE); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == STORAGE_REQUEST_CODE && resultCode == RESULT_OK){ // FOR PICK IMAGE FORM GALLERY Uri uri = data.getData(); StorageReference path = firebaseStorage.child(userId).child(eventId).child("Photos").child(uri.getLastPathSegment()); path.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { Uri uri = taskSnapshot.getDownloadUrl(); String photoUri = String.valueOf(uri); String pictureId = pictureRef.push().getKey(); PictureClass picture = new PictureClass(userId,eventId,pictureId,photoUri); pictureRef.child(pictureId).setValue(picture).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()){ Toast.makeText(ProfileEventActivity.this, "Photo Uploded", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(ProfileEventActivity.this, "Not Uploaded", Toast.LENGTH_SHORT).show(); } } }); } }); } else if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK ){ // FOR PICK IMAGE FROM CAMERA /*Bundle extras = data.getExtras(); Log.e("photo", "onActivityResult: "+captureImagePath); */ Uri uri = Uri.fromFile(new File(captureImagePath)); StorageReference riversRef = firebaseStorage.child(userId).child(eventId).child("Photos/"+uri.getLastPathSegment()); riversRef.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { Uri uri = taskSnapshot.getDownloadUrl(); String photoUri = String.valueOf(uri); String pictureId = pictureRef.push().getKey(); PictureClass picture = new PictureClass(userId,eventId,pictureId,photoUri); pictureRef.child(pictureId).setValue(picture).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()){ Toast.makeText(ProfileEventActivity.this, "Photo Uploded", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(ProfileEventActivity.this, "Not Uploaded", Toast.LENGTH_SHORT).show(); } } }); } }); } else { Toast.makeText(this, "False", Toast.LENGTH_SHORT).show(); } } //Expandable ListView Click Method //Add New Expense //Show Alert Dialog And check is it emptay private void addNewExpense() { AlertDialog.Builder builder = new AlertDialog.Builder(this); LayoutInflater inflater =LayoutInflater.from(this); LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.expense_dialog,null,true); final EditText costTittleEt = layout.findViewById(R.id.costTittleEt); final EditText costAmountEt = layout.findViewById(R.id.costAmountEt); builder.setView(layout); builder.setPositiveButton("Add Expense", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //geting current Date Calendar calendar = Calendar.getInstance(); SimpleDateFormat format = new SimpleDateFormat("dd, MMM, yyyy 'at' HH:mm a"); String finalDate = format.format(calendar.getTime()); String costTittle =costTittleEt.getText().toString(); String costam = costAmountEt.getText().toString(); double costAmount = Double.parseDouble(costAmountEt.getText().toString()); if (!TextUtils.isEmpty(costTittle) && !TextUtils.isEmpty(costam)){ if (haveMoney>=costAmount){ // if alert dialog is filled up call addExpense(costTittle, costAmount,finalDate); } else { addMoreBudget(); } } } }); builder.setNegativeButton("Cancel",null); builder.show(); } //cost list Method private void costItemList() { expenseReference.child("Expense").addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { ArrayList<ExpenseClass>expenses = new ArrayList<>(); for (DataSnapshot costList : dataSnapshot.getChildren()){ ExpenseClass expenseClass = costList.getValue(ExpenseClass.class); expenses.add(expenseClass); } if (!expenses.isEmpty()){ AlertDialog.Builder builder = new AlertDialog.Builder(ProfileEventActivity.this); LayoutInflater inflater = LayoutInflater.from(ProfileEventActivity.this); View view = inflater.inflate(R.layout.cost_layout,null,true); final RecyclerView recyclerView = view.findViewById(R.id.costRv); builder.setView(view); String tost = expenses.get(0).getExpenseTittle(); Toast.makeText(ProfileEventActivity.this, ""+tost, Toast.LENGTH_SHORT).show(); CostAdapter costAdapter = new CostAdapter(ProfileEventActivity.this,expenses,ProfileEventActivity.this); RecyclerView.LayoutManager manager = new LinearLayoutManager(ProfileEventActivity.this, LinearLayoutManager.VERTICAL,false); recyclerView.setLayoutManager(manager); recyclerView.setAdapter(costAdapter); builder.setNegativeButton("Close",null); builder.show(); } else { Toast.makeText(ProfileEventActivity.this, "No Cost Added", Toast.LENGTH_SHORT).show(); } } @Override public void onCancelled(DatabaseError databaseError) { Toast.makeText(ProfileEventActivity.this, ""+databaseError.getMessage(), Toast.LENGTH_SHORT).show(); } }); } private void addMoreBudget() { AlertDialog.Builder builder = new AlertDialog.Builder(this); LayoutInflater inflater =LayoutInflater.from(this); LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.add_budget,null,true); final EditText newAmountEt = layout.findViewById(R.id.newAmmount); builder.setView(layout); builder.setPositiveButton("Add Budget", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { final String newAmount = newAmountEt.getText().toString(); double addedBudget = Double.valueOf(newAmountEt.getText().toString()); double newBudget = budged +addedBudget; if (!TextUtils.isEmpty(newAmount)){ eventReference.child(userId).child(eventId).child("budget").setValue(newBudget). addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()){ Toast.makeText(ProfileEventActivity.this, "Successful", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(ProfileEventActivity.this, ""+task.getException().getMessage(), Toast.LENGTH_SHORT).show(); } } }); } } }); builder.setCancelable(false); builder.setNegativeButton("Cancel",null); builder.show(); } private void deleteEvent() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Do you want to delete this event"); builder.setCancelable(false); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { eventReference.child(userId).child(eventId).removeValue().addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()){ Toast.makeText(ProfileEventActivity.this, "Deleted", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(ProfileEventActivity.this, "Error", Toast.LENGTH_SHORT).show(); } } }); Intent intent = new Intent(ProfileEventActivity.this,EventActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } }); builder.setNegativeButton("Cancel",null); builder.show(); } private void editEvent() { Intent intent = new Intent(ProfileEventActivity.this,AddEventActivity.class); intent.putExtra("userId",userId); intent.putExtra("eventId",eventId); startActivity(intent); } @Override public void onClickCostItem(ExpenseClass expenseClass) { } @Override public void onLogClickCostItem(ExpenseClass expenseClass) { final String costId = expenseClass.getExpenseId(); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Do you want to remove this cost ?"); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { expenseReference.child("Expense").child(costId).removeValue().addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if (task.isSuccessful()){ Toast.makeText(ProfileEventActivity.this, "Cost Deleted", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(ProfileEventActivity.this, ""+task.getException().getMessage(), Toast.LENGTH_SHORT).show(); } } }); } }); builder.setNegativeButton("No",null); builder.show(); } @Override protected void onStart() { super.onStart(); /*********Mehtod are running on start activity**********/ //showing event basic information showEventBasicInformation(); } }
package edu.uci.ics.sdcl.firefly.report.predictive.spectra; import java.util.Vector; import edu.uci.ics.sdcl.firefly.Answer; import edu.uci.ics.sdcl.firefly.Microtask; /** * Represents a line in the source code that under a fault localization investigation. * * @author adrianoc * */ public class Line extends Microtask{ /** Simplified version with only the data needed to write a Session Report */ public Line(String question, Integer ID, Vector<Answer> answerList, String fileName) { super(question,ID,answerList,fileName,0); this.answerList = answerList; this.ID = ID; this.question = question; this.fileName = fileName; } }
package com.zhouyi.business.core.service; import com.zhouyi.business.core.dao.LedenEquipmentParetsMapper; import com.zhouyi.business.core.model.LedenEquipmentParets; import com.zhouyi.business.core.model.PageData; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; /** * @author 李秸康 * @ClassNmae: LedenEquipmentParetsServiceImpl * @Description: TODO * @date 2019/6/25 10:18 * @Version 1.0 **/ @Service public class LedenEquipmentParetsServiceImpl implements LedenEquipmentParetsService { @Autowired private LedenEquipmentParetsMapper ledenEquipmentParetsMapper; /** * 获取分页对象 * @param conditions * @return */ @Override public PageData<LedenEquipmentParets> getLedenEquipmentParetsPage(Map<String, Object> conditions) { List<LedenEquipmentParets> list=ledenEquipmentParetsMapper.listLedenEquipmentParetesByConditions(conditions); Integer totalCount=ledenEquipmentParetsMapper.getLedenEquipmentParetsCountByConditions(conditions); PageData<LedenEquipmentParets> pageData=new PageData<>(list,totalCount,(int)conditions.get("pSize")); return pageData; } /** * 根据id获取配件信息 * @param id * @return */ @Override public LedenEquipmentParets getLedenEquipmentParetsById(Integer id) { return ledenEquipmentParetsMapper.selectByPrimaryKey(id.toString()); } /** * 添加配件信息 * * @param ledenEquipmentParets * @return */ @Override public Boolean addLedenEquipmentParets(LedenEquipmentParets ledenEquipmentParets) { return ledenEquipmentParetsMapper.insertSelective(ledenEquipmentParets)==1?true:false; } /** * 移除配件信息 * @param id * @return */ @Override public Boolean removeLedenEquipmentParetsById(Integer id) { return ledenEquipmentParetsMapper.deleteByPrimaryKey(id.toString())==1?true:false; } /** * 更新配件信息 * @param ledenEquipmentParets * @return */ @Override public Boolean updateLedenEquipmentParets(LedenEquipmentParets ledenEquipmentParets) { return ledenEquipmentParetsMapper.updateByPrimaryKeySelective(ledenEquipmentParets)==1?true:false; } }
package InterviewTasks_Saim_Numbers; import java.util.Arrays; public class FibonnaciBoth { public static void main(String[] args) { //fibon(8); fibonacci(10); } public static void fibon(int num){ int result = 0; int num1 =0; int num2 = 1; for (int i = 1; i < num; i++) { System.out.print(num1 + " "); result = num1 + num2; num1= num2; num2 = result; } } public static void fibonacci(int num) { int []arr = new int[num]; arr[0] = 0; arr[1] = 1; for (int i = 2; i < num ; i++) { arr[i] = arr[i-1] + arr[i - 2]; } System.out.println(Arrays.toString(arr)); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package legaltime.controller; import java.util.logging.Level; import java.util.logging.Logger; import legaltime.model.ClientAccountRegisterBean; import legaltime.model.ClientAccountRegisterManager; import legaltime.model.PaymentLogBean; import legaltime.model.PaymentLogManager; import legaltime.model.exception.DAOException; import legaltime.modelsafe.EasyLog; import legaltime.view.model.PaymentLogTableModel; /** * * @author bmartin */ public class ProcessControllerAccounting { public static final String RESULT_SUCCESS = "SUCCESS"; public static final String RESULT_ATTEMPTED = "ATTEMPTED"; private ClientAccountRegisterManager clientAccountRegisterManager; private PaymentLogManager paymentLogManager; private EasyLog easyLog; private static ProcessControllerAccounting instance; private PaymentLogBean paymentLogBean; protected ProcessControllerAccounting() { clientAccountRegisterManager = ClientAccountRegisterManager.getInstance(); paymentLogManager = PaymentLogManager.getInstance(); easyLog = EasyLog.getInstance(); } public static ProcessControllerAccounting getInstance(){ if(instance == null){ instance = new ProcessControllerAccounting(); } return instance; } public boolean savePaymentLogBean(PaymentLogBean paymentLogBean_) { boolean result = false; try { paymentLogManager.save(paymentLogBean_); ClientAccountRegisterBean clientAccountRegisterBean = clientAccountRegisterManager.createClientAccountRegisterBean(); clientAccountRegisterBean.isNew(false); clientAccountRegisterBean.setClientAccountRegisterId( paymentLogBean_.getClientAccountRegisterId()); clientAccountRegisterBean.setClientId(paymentLogBean_.getClientId()); clientAccountRegisterBean.setDescription(paymentLogBean_.getDescription()); clientAccountRegisterBean.setEffectiveDate(paymentLogBean_.getEffectiveDate()); clientAccountRegisterBean.setTranAmt(-1D*paymentLogBean_.getAmount()); clientAccountRegisterBean.setTranType("PAY"); clientAccountRegisterManager.save(clientAccountRegisterBean); result =true; } catch (DAOException ex) { Logger.getLogger(PaymentLogTableModel.class.getName()).log(Level.SEVERE, null, ex); easyLog.addEntry(EasyLog.SEVERE,"Error Updating Payment Log" ,getClass().getName(),ex); result = false; } return result ; } public boolean addPaymentLogBean(PaymentLogBean paymentLogBean_){ boolean result = false; ClientAccountRegisterBean clientAccountRegisterBean = clientAccountRegisterManager.createClientAccountRegisterBean(); clientAccountRegisterBean.setClientId(paymentLogBean_.getClientId()); clientAccountRegisterBean.setDescription(paymentLogBean_.getDescription()); clientAccountRegisterBean.setEffectiveDate(paymentLogBean_.getEffectiveDate()); clientAccountRegisterBean.setTranAmt(-1D*paymentLogBean_.getAmount()); clientAccountRegisterBean.setTranType("PAY"); try { clientAccountRegisterBean = clientAccountRegisterManager.save(clientAccountRegisterBean); paymentLogBean_.setClientAccountRegisterId(clientAccountRegisterBean.getClientAccountRegisterId()); paymentLogManager.save(paymentLogBean_); } catch (DAOException ex) { Logger.getLogger(PaymentLogTableModel.class.getName()).log(Level.SEVERE, null, ex); easyLog.addEntry(EasyLog.SEVERE,"Error Adding Payment Log Entry" ,getClass().getName(),ex); } return result; } public void reversePaymentLogById(int paymentLogId_){ try { paymentLogBean = paymentLogManager.loadByPrimaryKey(paymentLogId_); reversePaymentLog (paymentLogBean); } catch (DAOException ex) { Logger.getLogger(PaymentLogController.class.getName()).log(Level.SEVERE, null, ex); } } private void reversePaymentLog (PaymentLogBean paymentLogBean_){ try { paymentLogBean = paymentLogBean_; PaymentLogBean reversal = paymentLogManager.createPaymentLogBean(); reversal.copy(paymentLogBean); reversal.setAmount(-1D * paymentLogBean.getAmount()); reversal.setDescription(paymentLogBean.getDescription() +" Reversal"); reversal.setPaymentLogId(null); paymentLogManager.save(reversal); reversAccountRegisterTranById(paymentLogBean_.getClientAccountRegisterId(),"SYSTEM"); } catch (DAOException ex) { Logger.getLogger(PaymentLogController.class.getName()).log(Level.SEVERE, null, ex); } } public String reversAccountRegisterTranById(int accountRegisterId_, String SystemOrUser){ String result =RESULT_ATTEMPTED; try { ClientAccountRegisterBean bean = clientAccountRegisterManager.loadByPrimaryKey(accountRegisterId_); ClientAccountRegisterBean reversal = clientAccountRegisterManager.createClientAccountRegisterBean(); if(SystemOrUser.equals("USER") && bean.getTranType().equals("PAY")){ result = "Payments may only be reversed by reverseing thePayment."; easyLog.addEntry(EasyLog.INFO, "User attempted payment reversal on account register" , getClass().getName(), ""); return result; } reversal.copy(bean); reversal.setTranAmt(-1D* bean.getTranAmt()); reversal.setDescription(bean.getDescription() +" Reversal"); reversal.setClientAccountRegisterId(null); clientAccountRegisterManager.save(reversal); result =RESULT_SUCCESS; } catch (DAOException ex) { Logger.getLogger(ClientAccountRegisterController.class.getName()).log(Level.SEVERE, null, ex); easyLog.addEntry(EasyLog.SEVERE, "ERROR: DAO exception reversAccountRegisterTranById" , getClass().getName(), ex); } return result ; } }
package zhku.mvc.controller; import zhku.mvc.annotation.Autowired; import zhku.mvc.annotation.Controller; import zhku.mvc.annotation.RequestMapping; import zhku.mvc.service.MsgService; import java.io.PrintWriter; /** * Created by ipc on 2017/8/26. */ @Controller("msg") public class MsgController { @Autowired("msgService") MsgService msgService; @RequestMapping("msg") public void getMsg(){ String value = msgService.getMsgFromDB(); System.out.println("Controller方法getMsg"); } }
package com.deltastuido.user; import java.io.Serializable; import javax.persistence.*; import java.sql.Timestamp; /** * The persistent class for the user_sns database table. * */ @Entity @Table(name = "user_sns") @NamedQuery(name = "UserSns.findAll", query = "SELECT u FROM UserSns u") public class UserSns implements Serializable { private static final long serialVersionUID = 1L; public static enum SNS { WEIBO, WECHAT }; @EmbeddedId private UserSnsPK id; private String auth; @Column(name = "sns_profile") private String snsProfile; @Column(name = "time_created") private Timestamp timeCreated; @Column(name = "time_updated") private Timestamp timeUpdated; @Column(name = "time_auth_expired") private Timestamp timeAuthExpired; @Column(name = "sns_uid") private String snsUid; @Column(name = "avatar") private String avatar; @Column(name = "nickname") private String nickname; public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public UserSns() { } public UserSnsPK getId() { return this.id; } public void setId(UserSnsPK id) { this.id = id; } public String getAuth() { return this.auth; } public void setAuth(String auth) { this.auth = auth; } public String getSnsProfile() { return this.snsProfile; } public void setSnsProfile(String snsUser) { this.snsProfile = snsUser; } public Timestamp getTimeCreated() { return this.timeCreated; } public void setTimeCreated(Timestamp timeCreated) { this.timeCreated = timeCreated; } public Timestamp getTimeUpdated() { return this.timeUpdated; } public void setTimeUpdated(Timestamp timeUpdated) { this.timeUpdated = timeUpdated; } public Timestamp getTimeAuthExpired() { return timeAuthExpired; } public void setTimeAuthExpired(Timestamp timeAuthExpired) { this.timeAuthExpired = timeAuthExpired; } public String getSnsUid() { return snsUid; } public void setSnsUid(String snsUid) { this.snsUid = snsUid; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.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; UserSns other = (UserSns) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } @Override public String toString() { return "UserSns [id=" + id + ", auth=" + auth + ", snsProfile=" + snsProfile + ", timeCreated=" + timeCreated + ", timeUpdated=" + timeUpdated + ", timeAuthExpired=" + timeAuthExpired + ", snsUid=" + snsUid + ", nickname=" + nickname + "]"; } }
public class E27 { public static void main(String[] args) { String word = "Hello, World!"; int i = 0; while (i < 1) { word = word.replace("e", "u"); word = word.replace("o", "e"); word = word.replace("u", "o"); i++; } System.out.println(word); } }
import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class Writer implements Runnable { RWMonitor rwMonitor; int writeIntervalInSecs; public Writer(RWMonitor rwMonitor, int writeIntervalInSecs) { this.rwMonitor = rwMonitor; this.writeIntervalInSecs = writeIntervalInSecs; } @Override public void run() { while (true) { try { /*ENTRY*/ rwMonitor.writeMutex.acquire(); rwMonitor.writeCount++; if (rwMonitor.writeCount == 1) { rwMonitor.readTry.acquire(); } rwMonitor.writeMutex.release(); rwMonitor.resourceMutex.acquire(); /*CS*/ write(); /*EXIT*/ rwMonitor.resourceMutex.release(); rwMonitor.writeMutex.acquire(); rwMonitor.writeCount--; if (rwMonitor.writeCount == 0) { rwMonitor.readTry.release(); } rwMonitor.writeMutex.release(); Thread.sleep(writeIntervalInSecs * 1000); } catch (InterruptedException e) { e.printStackTrace(); } } } public void write() { System.out.println("Writing from writer on Thread ID: " + Thread.currentThread().getId()); try { BufferedWriter bufferedWriter = new BufferedWriter( new FileWriter(rwMonitor.sharedFile) ); String content = String.format( "Howdy! this is written by Thread ID: %d\n", Thread.currentThread().getId() ); bufferedWriter.write(content); bufferedWriter.close(); } catch (IOException e) { e.printStackTrace(); } } }
/** * Created by Jay Zhu, Jon Busa and Christian Murray * Ver. Feb. 29 2016 * * Jumper Questions * a. If there is a rock or flower two spaces ahead of the jumper * then it will not move, but turn by 90 degrees to the right. * * b. If the two spaces ahead does not exist, the jumper will not * move, but turn by 90 degrees to the right. * * c. The jumper should turn by 90 degrees to the right. * * d. The jumper should eat the actor that is sitting on the place * two in front of it if it is another bug. * * e. The jumper would eat the jumper that is in its path. * * f. We should still test some of the methods from the bug class * to make sure that the Jumper can do everything that a bug can do. * * Design * a. The Jumper should extend the Bug class. * * b. The BoxBug class is simular, but a BoxBug only moves one grid at * a time. * * c. Yes there should be a constructor for Jumper class, but it doesn't * take in any parameters. * * d. The canMove() method overrides the origin canMove() in the Bug class. * * e. The act() method was added only for Jumper class to move the bug two * grids at a time. * * f. We should write a Jumper tester, and test all the methods from the * Jumper class to see if all of them functions correctly. */ import info.gridworld.actor.Actor; import info.gridworld.actor.Bug; import info.gridworld.actor.Flower; import info.gridworld.actor.Rock; import info.gridworld.grid.Grid; import info.gridworld.grid.Location; public class Jumper extends Bug { Location nextJump; Grid grid; public Jumper() { } /** * The jumper will take two steps with every call to <code>act()</code> that is made. * Jumpers are very hungry, and will eat other bugs and jumpers that are on the grid. * Jumpers will not step on rocks or flowers but instead will jump over them or turn * to go around them. * When at the edge of a grid the jumper will turn 90 degrees until it can make a valid jump, and will * do the same if the space two paces in front of it is invalid. * */ public void act() { nextJump = getLocation().getAdjacentLocation(getDirection()).getAdjacentLocation(getDirection()); if(canMove()) { moveTo(nextJump); } else { turn(); turn(); } } /** * The <code>canMove()</code> method from the <code>Bug</code> class, changed so that it checks two spaces ahead * instead of one, and checks for rocks as well as flowers. * @return true if the bug can move and false if the bug cannot */ @Override public boolean canMove() { Grid<Actor> gr = getGrid(); //if the grid does not exist if (gr == null) return false; Location loc = getLocation(); //get the location that is two spaces in front of it instead of one Location next = loc.getAdjacentLocation(getDirection()).getAdjacentLocation(getDirection()); //if the location does not exist if (!gr.isValid(next)) return false; Actor neighbor = gr.get(next); if (neighbor == null) { return true; } else if (neighbor instanceof Rock || neighbor instanceof Flower) { return false; } return true; // ok to move into empty location or onto flower // not ok to move onto any other actor } }
/* * Copyright ApeHat.com * * 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 com.apehat.newyear.protocol.classpath; import java.io.IOException; import java.net.URL; import java.net.URLConnection; import java.net.URLStreamHandler; /** * @author hanpengfei * @since 1.0 */ public class Handler extends URLStreamHandler { @Override protected URLConnection openConnection(URL u) throws IOException { String path = u.getPath(); return new URL("file:" + path).openConnection(); } }
package Client; import Controllers.Controller; import Models.Usuario_model; import java.io.IOException; import java.io.ObjectInputStream; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; public class ReceiverClient implements Runnable { private ObjectInputStream entradaServidor; private Controller ctrl; public ReceiverClient(ObjectInputStream entrada) { entradaServidor = entrada; ctrl = new Controller(); } @Override public void run() { while(true) { try { ArrayList obj = (ArrayList) entradaServidor.readObject(); if(obj instanceof ArrayList) { if(!obj.isEmpty()) { String tipo = (String) obj.get(0); if(tipo.equals("usuario")) { String id = (String) obj.get(1); String nome = (String) obj.get(2); int trofeus = (int) obj.get(3); Usuario_model user = new Usuario_model(id, nome, trofeus, null); ctrl.setUser(user); ArrayList<Usuario_model> resultados = new ArrayList<>(); for(int i = 4; i < obj.size(); i++) { ArrayList u = (ArrayList) obj.get(i); String idU = (String) u.get(0); String nomeU = (String) u.get(1); int trofeusU = (int) u.get(2); if(!idU.equals(user.getId())) { Usuario_model usuario = new Usuario_model(idU, nomeU, trofeusU, null); resultados.add(usuario); } } ctrl.setResultados(resultados); ctrl.setInicioVisible(); } else if(tipo.equals("lista")){ ArrayList<Usuario_model> resultados = new ArrayList<>(); for(int i = 1; i < obj.size(); i++) { ArrayList u = (ArrayList) obj.get(i); String idU = (String) u.get(0); String nomeU = (String) u.get(1); int trofeusU = (int) u.get(2); if(!idU.equals(ctrl.getUser().getId())) { Usuario_model usuario = new Usuario_model(idU, nomeU, trofeusU, null); resultados.add(usuario); } } ctrl.setResultados(resultados); if(ctrl.getQualViewEstaAtiva() == 0) ctrl.setInicioVisible(); } else if(tipo.equals("comecar_jogo")){ int idDoJogo = (int) obj.get(1); String minhaPeca = (String) obj.get(2); String id = (String) obj.get(3); String nome = (String) obj.get(4); int trofeus = (int) obj.get(5); Usuario_model inimigo = new Usuario_model(id,nome,trofeus,null); ctrl.setInimigo(inimigo); ctrl.setJogoVisible(minhaPeca, idDoJogo); } else if(tipo.equals("atualizar_jogo")){ int quadrados[] = new int[9]; for(int j = 1; j < 10; j++) { int n = (int) obj.get(j); quadrados[j-1] = n; } ctrl.atualizarJogo(quadrados); } else if(tipo.equals("usuario_atualizar")){ String id = (String) obj.get(1); String nome = (String) obj.get(2); int trofeus = (int) obj.get(3); Usuario_model user = new Usuario_model(id, nome, trofeus, null); ctrl.setUser(user); } else if(tipo.equals("abandonou_partida")){ ctrl.setTag(0); ctrl.avisarQueInimigoAbandonou(); } } } Thread.sleep(100); } catch (InterruptedException ex) { Logger.getLogger(ReceiverClient.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(ReceiverClient.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(ReceiverClient.class.getName()).log(Level.SEVERE, null, ex); } } } }
package com.tencent.mm.protocal; final class c$ds extends c$g { c$ds() { super("launchApplication", "launchApplication", 260, true); } }
package com.littlecheesecake.redis.demo.repository; import com.google.common.collect.Lists; import com.sun.deploy.util.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.connection.RedisZSetCommands; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.stereotype.Repository; import java.util.Calendar; import java.util.List; import java.util.Set; @Repository public class RateDaoImpl implements RateDao { @Autowired RedisTemplate<String, Object> redisTemplate; /** * fixed window counter algorithm - used for second only * * Pros: * - easy to implement * - memory efficient * * Cons: * - allow burst of request at the edge of time window * * @param apiPath the api uri path e.g. /app/data * @param id the customer id e.g. access key * @param limit the rate limit * @return remaining api count in the given interval */ @Override public int limitRateFixedWindowCounter(String apiPath, String id, int interval, int limit) { // only allow per second interval to be applied if (interval != 1) { throw new RuntimeException("invalid interval provided: only allow value as 1 (per second)"); } long epochTime = System.currentTimeMillis() / 1000; //current time in second String key = StringUtils.join(Lists.newArrayList(apiPath, id, String.valueOf(interval)), ":"); RedisSerializer keyS = redisTemplate.getKeySerializer(); List<Object> results = redisTemplate.executePipelined((RedisCallback<Object>) redisConnection -> { redisConnection.incrBy(keyS.serialize(key), 1); redisConnection.expireAt(keyS.serialize(key), epochTime + 1); return null; }); int count = ((Long)results.get(0)).intValue(); return limit - count; } /** * rolling window log with sorted set (used for interval = 1|60, second and hourly) * * Pros: * - very accurate * - distributed safe * * Cons: * - memory intensive * * @param apiPath the api uri path e.g. /app/data * @param id the customer id e.g. access key * @param interval the time interval that the limit is applied to * @param limit the rate limit * @return remaining api count in the given interval */ @Override public int limitRateRollingWindowLog(String apiPath, String id, int interval, int limit) { if (interval != 1 && interval != 60) { throw new RuntimeException("invalid interval provided: only allow value of 1 or 60 (per second or per min)"); } long epochTimeMilli = System.currentTimeMillis(); String key = StringUtils.join(Lists.newArrayList(apiPath, id, String.valueOf(interval)), ":"); // get clear before time long clearBeforeTime = epochTimeMilli - interval * 1000; // get ttl time long ttl = interval; RedisSerializer keyS = redisTemplate.getKeySerializer(); RedisSerializer valueS = redisTemplate.getValueSerializer(); byte[] k = keyS.serialize(key); List<Object> results = redisTemplate.executePipelined((RedisCallback<Object>) redisConnection -> { // When a user attempts to perform an action, we first drop all elements of the set which occured before one interval ago. redisConnection.zRemRangeByScore(k, 0, clearBeforeTime); // We add the current timestamp to the set redisConnection.zAdd(k, epochTimeMilli, valueS.serialize(String.valueOf(epochTimeMilli))); // We fetch all elements of the set redisConnection.zRangeWithScores(k, 0, -1); // We set a TTL equal to the rate-limiting interval on the set (to save space) redisConnection.expire(k, ttl); return null; }); Set<RedisZSetCommands.Tuple> s = (Set<RedisZSetCommands.Tuple>) results.get(2); int count = s.size(); return limit - count; } /** * rolling window counter (apply to min, hour or day limit) * * Pros: * - memory efficient * * Cons: * - not accurate: According to experiments done by Cloudflare, only 0.003% of requests are wrongly allowed or rate limited * among 400 million requests: https://blog.cloudflare.com/counting-things-a-lot-of-different-things/ * * @param apiPath the api uri path e.g. /app/data * @param id the customer id e.g. access key * @param interval the time interval that the limit is applied to * @param limit the rate limit * @return remaining api count in the given interval */ @Override public int limitRateRollingWindowCounter(String apiPath, String id, int interval, int limit) { if (interval != 60 && interval != 3600 && interval != 3600 * 24) { throw new RuntimeException("invalid interval provided: only allow value of 1 or 60 (per second or per min)"); } // get time windows - start time of previous and current windows long currentTime = System.currentTimeMillis(); long currentWindow; long prevWindow; Calendar now = Calendar.getInstance(); now.set(Calendar.SECOND, 0); now.set(Calendar.MILLISECOND, 0); if (interval == 3600) { // get start of the hour now.set(Calendar.MINUTE, 0); } else if (interval == 3600 * 24) { // get start of the day now.set(Calendar.MINUTE, 0); now.set(Calendar.HOUR_OF_DAY, 0); } currentWindow = now.getTime().getTime(); prevWindow = currentWindow - interval * 1000; String keyPrev = StringUtils.join(Lists.newArrayList(apiPath, id, String.valueOf(interval), String.valueOf(prevWindow)), ":"); String keyCurrent = StringUtils.join(Lists.newArrayList(apiPath, id, String.valueOf(interval), String.valueOf(currentWindow)), ":"); RedisSerializer keyS = redisTemplate.getKeySerializer(); byte[] kPrev = keyS.serialize(keyPrev); byte[] kCurrent = keyS.serialize(keyCurrent); List<Object> results = redisTemplate.executePipelined((RedisCallback<Object>) redisConnection -> { // get prevWindow count redisConnection.get(kPrev); // add and get currentWindow count redisConnection.incrBy(kCurrent, 1); // add ttl: expires only after the next time window expires because the prev window needs to be retained // for count calculation redisConnection.expireAt(kCurrent, currentWindow / 1000 + 2 * interval); return null; }); long prevCount = results.get(0) == null ? 0L : Long.valueOf((String)results.get(0)); long currentCount = (long) results.get(1); // calculate the estimated count long count = (long)((1 - 1.0 * (currentTime - currentWindow) / (interval * 1000)) * prevCount) + currentCount; return (int)(limit - count); } }
package com.jt.manage.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import com.jt.common.mapper.SysMapper; import com.jt.manage.pojo.Item; public interface ItemMapper extends SysMapper<Item> { /** * 查询记录数 * @return */ int findCount(); /** * 分页查询 * @param start 起始位置 * @param rows 显示行数 * @return * 说明:Mybatis中不允许多值传参,可以将多值封装为单值 * 封装策略:1将数据封装为pojo * 2 将数据封装为Map集合map<key,value> * -->下面写注解主要是这个,底层实现封装为map集合 * 3 将数据封装为Array数组/List集合 */ List<Item> findItemByPage( @Param("start") int start, @Param("rows") int rows ); /** 查询商品分类的名字*/ @Select("select name from tb_item_cat where id=#{itemId}") String findItemCatNameById(Long itemId); void updateStatus(@Param("ids")Long[] ids,@Param("status")int status); }
package src; public class IfExprAST implements ExprAST { private ExprAST condExpr, thenExpr, elseExpr; public IfExprAST(ExprAST condExpr, ExprAST thenExpr, ExprAST elseExpr) { this.condExpr = condExpr; this.thenExpr = thenExpr; this.elseExpr = elseExpr; } public ExprAST getCond() { return condExpr; } public ExprAST getThen() { return thenExpr; } public ExprAST getElse() { return elseExpr; } public String toString() { return "cond = " + condExpr + ", then = " + thenExpr + ", else = " + elseExpr; } }
package org.study.regexp; import java.util.function.Function; import java.util.regex.MatchResult; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ReplaceFunction { public static String replace(String searchString, String patternString, Function<MatchResult, String> mapping) { Matcher matcher = Pattern.compile(patternString).matcher(searchString); StringBuffer sb = new StringBuffer(); while(matcher.find()){ MatchResult matchResult = matcher.toMatchResult(); matcher.appendReplacement(sb, mapping.apply(matchResult).replaceAll("\\$", "\\\\\\$")); } matcher.appendTail(sb); return sb.toString(); } }
package com.walkerwang.algorithm.bigcompany; import java.util.Scanner; /** * 算法基础-字符移位 * * 小Q最近遇到了一个难题:把一个字符串的大写字母放到字符串的后面,各个字符的相对位置不变,且不能申请额外的空间。 你能帮帮小Q吗? 输入描述: 输入数据有多组,每组包含一个字符串s,且保证:1<=s.length<=1000. 输出描述: 对于每组数据,输出移位后的字符串。 输入例子: AkleBiCeilD 输出例子: kleieilABCD * @author walkerwang * */ public class Tecent01 { public static void main(String[] args) { @SuppressWarnings("resource") Scanner scanner = new Scanner(System.in); while(scanner.hasNext()) { String str = scanner.nextLine(); // String str = "AEleBiCeilD"; bubbleSort(str); moveBack(str); } } /* * 改进的冒泡排序 */ public static void bubbleSort(String str) { char[] chs = str.toCharArray(); //从尾部开始需要第一个不是大写的字符 int i = chs.length-1; while(chs[i] >= 65 && chs[i] <= 90) { i--; } for(; i>=0; i--){ for(int j=1; j<=i; j++) { if((chs[j-1] >= 65 && chs[j-1] <= 90) && (chs[j] >= 97 && chs[j] <= 122)) { char tmp = chs[j-1]; chs[j-1] = chs[j]; chs[j] = tmp; } } } System.out.println(String.valueOf(chs)); } /* * 数组移位 * 运行时间: 35 ms 占用内存:279K */ public static void moveBack(String str) { boolean flag = false; //flag用于标记是否移动了 char[] chs = str.toCharArray(); int count = 0; //调整的大写字符个数,每调整一次,遍历的长度就减1 for(int i=0; i<chs.length-count; i++) { flag = false; if(chs[i] >=65 && chs[i] <= 90) { char tmp = chs[i]; for(int j=i+1; j<chs.length; j++) { //大写字符之后的字符前移 chs[j-1] = chs[j]; } chs[chs.length-1] = tmp; //该大写字符放到最后 flag = true; count++; if(flag == true) System.out.println(String.valueOf(chs)); i--; } } System.out.println(String.valueOf(chs)); } }
package com.ibeiliao.pay.api.provider; import java.util.Date; import java.util.List; import com.ibeiliao.pay.api.ApiResultBase; import com.ibeiliao.pay.api.dto.request.balance.OperateBalanceRequest; import com.ibeiliao.pay.api.dto.response.balance.SchoolBalanceLogResponse; import com.ibeiliao.pay.api.dto.response.balance.SchoolBalanceLogSingleResponse; import com.ibeiliao.pay.api.dto.response.balance.SchoolBalanceResponse; import com.ibeiliao.pay.api.dto.response.balance.SchoolIdsResponse; import com.ibeiliao.pay.api.dto.response.balance.StatSchoolIncomeResponse; import com.ibeiliao.pay.api.enums.BalanceType; /** * 余额服务 * @author linyi 2016/7/22. */ public interface BalanceServiceProvider { /** * 获取幼儿园的余额 * @param schoolId 幼儿园学校ID * @return 返回幼儿园的余额,包含可提现金额、冻结金额、待入账金额,如果没有余额,各个余额返回 0 */ SchoolBalanceResponse getSchoolBalance(long schoolId); /** * 统计幼儿园的收入,时间范围 [start, end]。 * 例如统计 2016 年 7 月收入:[2016-07-01 00:00:00, 2016-07-31 23:59:59] * @param schoolId 幼儿园学校ID * @param start 开始时间 * @param end 结束时间 * @return 返回统计结果 */ StatSchoolIncomeResponse statSchoolIncome(long schoolId, Date start, Date end); /** * 冻结可提现金额。 * 成功后,可提现金额减少相应的金额,冻结金额增加相应金额。 * * request.referenceId 请填上提现ID。 * * @param request 冻结资金的请求 * @return 返回 result.code=ApiCode.SUCCESS为成功,其他是失败 */ ApiResultBase blockWithdrawBalance(OperateBalanceRequest request); /** * 把冻结的金额转换可提现金额,用于提现驳回用户的请求。 * * 成功后,可提现金额增加相应的金额,冻结金额减少相应金额。 * * request.referenceId 请填上提现ID。 * * @param request 解除冻结提现金额的请求 * @return 返回 result.code=ApiCode.SUCCESS为成功,其他是失败 */ ApiResultBase unblockWithdrawBalance(OperateBalanceRequest request); /** * 批量把冻结的金额转换可提现金额,用于提现驳回用户的请求。 * * 成功后,可提现金额增加相应的金额,冻结金额减少相应金额。 * * request.referenceId 请填上提现ID。 * * @param requests 解除冻结提现金额的请求列表,不能为空 * @return 返回 result.code=ApiCode.SUCCESS为成功,其他是失败 */ ApiResultBase batchUnblockWithdrawBalance(List<OperateBalanceRequest> requests); /** * 批量冻结可提现金额 * * 成功后,可提现金额减少相应的金额,冻结金额增加相应金额。 * request.referenceId 请填上提现ID。 * * 如果有一个请求处理失败,所有请求都会失败,事务回滚,抛出 ServiceException。 * * @param requests 冻结资金的请求 * @return 返回 result.code=ApiCode.SUCCESS为成功,其他是失败 */ ApiResultBase batchBlockWithdrawBalance(List<OperateBalanceRequest> requests); /** * 批量扣除冻结金额。 * * 成功后,冻结金额减少相应的金额。 * 用于提现成功后的确认。 * * 如果有一个失败,那么所有操作都会失败,事务回滚,抛出 ServiceException。 * * @param requests 扣除冻结资金的请求 * @return 返回 result.code=ApiCode.SUCCESS为成功,其他是失败 */ ApiResultBase batchSubBlockBalance(List<OperateBalanceRequest> requests); /** * 封号,封禁成功后,学校不能申请提现,即可提现资金不能转为冻结资金,其他的功能不影响。 * 如果封号失败,学校的功能照旧。 * * @param schoolId 学校ID * @return 返回 ApiCode.SUCCESS=成功 */ ApiResultBase banSchoolBalanceAccount(long schoolId); /** * 解封,解封成功后,所有功能恢复正常 * * @param schoolId 学校ID * @return 返回 ApiCode.SUCCESS=成功 */ ApiResultBase unbanSchoolBalanceAccount(long schoolId); /** * 查询幼儿园的提现帐号的流水,按时间倒序排列 * @param schoolId 幼儿园学校ID * @param page 第几页,取值 [1, 1000] * @param pageSize 每页多少数据,取值 [10, 1000] * @return 成功返回列表,不会为 null。如果没有数据,返回size=0的 List */ SchoolBalanceLogResponse querySchoolWithdrawBalanceLog(long schoolId, int page, int pageSize); /** * 根据时间查询所有的提现流水, 按照流水id顺序排序 * @param startDate 开始时间,不能为空, 由 指定日期的 0点0分0秒0毫秒 开始 * @param endDate 结束时间,不能为空 由 指定日期的 23点59分59秒999毫秒结束 * @param page 页码,由1开始 * @param pageSize 分页大小, 取值 [10, 1000] * @return 成功返回列表,不会为 null。如果没有数据,返回size=0的 List */ SchoolBalanceLogResponse queryWithdrawBalanceLog(Date startDate, Date endDate, int page, int pageSize); /** * 查询特定日期[00:00:00,23:59:59]幼儿园的提现帐号的流水,按时间倒序排列。</br> * * 单个幼儿园一天的数据量不会太多,此处不支持分页 * * @param schoolId 幼儿园学校ID,不能为空 * @param date 查询日期,不能为空 * @return 成功返回列表,不会为 null。如果没有数据,返回size=0的 List */ SchoolBalanceLogResponse querySchoolBalanceLog(long schoolId, Date date); /** * 根据时间查询所有的流水, 按照流水id顺序排序 * * @param startDate 开始时间,不能为空, 由 指定日期的 0点0分0秒0毫秒 开始 * @param endDate 结束时间,不能为空 由 指定日期的 23点59分59秒999毫秒结束 * @param page 页码,由1开始 * @param pageSize 分页大小, 取值 [10, 1000] * @return 成功返回列表,不会为 null。如果没有数据,返回size=0的 List */ SchoolBalanceLogResponse queryBalanceLog(Date startDate, Date endDate, int page, int pageSize); /** * 根据 学校id, 账户类型, 时间 获取 该账户的最后的日志记录 * * @param balanceType 账户类型 * @param beforeDate 最后记录产生的之前时间 由 指定日期的 0点0分0秒0毫秒 开始 * @return 单条日志记录, 没有事返回空 */ SchoolBalanceLogSingleResponse queryLastBalanceLogBeforeDate(long schoolId, BalanceType balanceType, Date beforeDate); /** * 获取某个时间之后, 拥有余额账户的学校id, 默认排序 * @param beforeTime 时间, 传入的时间会自动转换为从 23时59分59秒999毫秒开始 * @return 学校id, 没有数据时返回空集合 */ SchoolIdsResponse queryAllSchoolIdOfBanlanceBeforeTime(Date beforeTime); }
package com.youthchina.controller; import com.fasterxml.jackson.databind.ObjectMapper; import com.youthchina.dao.tianjian.CommunityMapper; import com.youthchina.service.user.JwtService; import com.youthchina.util.AuthGenerator; import org.junit.After; import org.junit.Before; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.ClassPathResource; import org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import java.io.FileNotFoundException; import java.io.IOException; /** * Created by zhongyangwu on 4/9/19. */ public class BaseControllerTest { @Autowired protected WebApplicationContext context; @Autowired protected CommunityMapper communityMapper; @Autowired protected JwtService jwtService; @Value("${web.url.prefix}") protected String urlPrefix; @Value("${security.token.header}") protected String HEADER; protected AuthGenerator authGenerator = new AuthGenerator(); protected MockMvc mvc; @Before public void setup() { this.mvc = MockMvcBuilders.webAppContextSetup(context).apply(SecurityMockMvcConfigurers.springSecurity()).build(); } @After public void teardown() { } protected String readJson(String filepath) throws FileNotFoundException { ObjectMapper mapper = new ObjectMapper(); String jsonString = null; try { jsonString = mapper.writeValueAsString(mapper.readValue(new ClassPathResource(filepath).getFile(), Object.class)); } catch (IOException e) { throw new FileNotFoundException(); } return jsonString; } }
package com.awsp8.wizardry.Blocks; import com.awsp8.wizardry.Info; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.util.IIcon; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class MaztrixLog extends Block { public MaztrixLog(Material material) { super(material); } @SideOnly(Side.CLIENT) public static IIcon topIcon; @SideOnly(Side.CLIENT) public static IIcon sideIcon; @SideOnly(Side.CLIENT) public static IIcon bottomIcon; @Override @SideOnly(Side.CLIENT) public void registerBlockIcons(IIconRegister icon){ topIcon = icon.registerIcon(Info.NAME.toLowerCase() + ":logMaztrixTop"); sideIcon = icon.registerIcon(Info.NAME.toLowerCase() + ":logMaztrixSide"); bottomIcon = icon.registerIcon(Info.NAME.toLowerCase() + ":logMaztrixTop"); } @Override @SideOnly(Side.CLIENT) public IIcon getIcon(int side, int metadata){ if (side == 0){ return bottomIcon; }else if (side == 1){ return topIcon; }else { return sideIcon; } } }
package com.ToppInd; import java.io.IOException; public class Main { public static void main(String[] args) { try { // run AutoDimension.appref-ms and wait for process to finish var autoDimensionProcess = new ProcessBuilder("cmd.exe", "/c", "AutoDimension.appref-ms").start(); autoDimensionProcess.waitFor(); autoDimensionProcess.destroy(); // wait a few seconds - ProcessBuilder is not synchronized Thread.sleep(33_000); // run AutoBalloon (sw-test.appref-ms) and wait for process to finish var autoBalloonProcess = new ProcessBuilder("cmd.exe", "/c", "sw-test.appref-ms").start(); autoBalloonProcess.waitFor(); autoBalloonProcess.destroy(); // wait a few seconds Thread.sleep(6_000); // run AutoCenterMark var autoCenterMarkProcess = new ProcessBuilder("cmd.exe", "/c", "AutoCenterMark.appref-ms").start(); autoCenterMarkProcess.waitFor(); autoCenterMarkProcess.destroy(); } catch (IOException | InterruptedException e) { e.printStackTrace(); } } }
package com.tantransh.workshopapp.services; public class ServiceData { public static final String BASEURL = "http://ambspares.com/automobileworkshop/controller/"; public static final String CONTENTSERVICE = "ContentServiceInvoker.php"; public static final String JOBSERVICE = "JobServiceInvoker.php"; public static final String DATAURL = "DataManager.php"; public static final String AUTHURL = "auth.php"; public static final String BASEURL_2 = "http://ambspares.com/automobileworkshop/controller/"; }
package p4; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; public class ButtonListenerRimozioneApp implements ActionListener { private ButtonGroup group; private JFrame frame; private Sistema sistema; public ButtonListenerRimozioneApp(ButtonGroup group, JFrame frame, Sistema sistema) { this.group = group; this.frame = frame; this.sistema = sistema; } @Override public void actionPerformed(ActionEvent e) { JButton b = (JButton)e.getSource(); if(b.getText().equals("Ok")) { String action = group.getSelection().getActionCommand(); int indexApp = Integer.parseInt(action); sistema.rimozioneApp(indexApp); frame.dispose(); } else if(b.getText().equals("Annulla")) { //Chiudi fin frame.dispose(); } } }
package entity; public class Patient { private int id; private String name; private String epc; private String record=""; public Patient(String name, String epc) { this.id = -1; //-1:还没有id,这是非法id标识,只有当写入数据库的时候才会被创建 this.name = name; this.epc = epc; this.record=""; } public Patient(int id, String name, String epc, String record) { this.id = id; this.name = name; this.epc = epc; this.record=record; } public int getId() { return this.id; } public String getName() { return this.name; } public String getEpc(){ return this.epc; } public String getRecord() { return record; } public void setRecord(String record) { this.record = record; } }
/* * Sonar Codesize Plugin * Copyright (C) 2010 Matthijs Galesloot * dev@sonar.codehaus.org * * 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 org.sonar.plugins.codesize; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import org.apache.commons.configuration.PropertiesConfiguration; import org.junit.Before; import org.junit.Test; import org.mockito.Answers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.sonar.api.batch.DecoratorContext; import org.sonar.api.measures.Measure; import org.sonar.api.resources.Project; public class CodeSizeDecoratorTest { private Project project; @Before public void initMocks() { MockitoAnnotations.initMocks(this); Mockito.when(decoratorContext.getMeasure(CodesizeMetrics.CODE_COUNTERS)).thenReturn(null); Mockito.when(decoratorContext.getChildrenMeasures(CodesizeMetrics.CODE_COUNTERS)).thenAnswer(new Answer<List<Measure>>() { public List<Measure> answer(InvocationOnMock invocation) { List<Measure> measures = new ArrayList<Measure>(); Measure measure = new Measure(); measure.setData("java=10;css=5"); measures.add(measure); return measures; } }); project = new Project("test"); project.setConfiguration(new PropertiesConfiguration()); project.getConfiguration().setProperty(CodesizeConstants.SONAR_CODESIZE_ACTIVE, "True"); } @Mock(answer= Answers.RETURNS_DEEP_STUBS) private DecoratorContext decoratorContext; @Test public void decorate() { CodeSizeDecorator decorator = new CodeSizeDecorator(); assertTrue(decorator.shouldExecuteOnProject(project)); decorator.decorate(project, decoratorContext); Mockito.verify(decoratorContext).saveMeasure((Measure) Mockito.anyObject()); } @Test public void decorateExisting() { CodeSizeDecorator decorator = new CodeSizeDecorator(); final Measure projectMeasure = new Measure(CodesizeMetrics.CODE_COUNTERS, "java=15"); Mockito.when(decoratorContext.getMeasure(CodesizeMetrics.CODE_COUNTERS)).thenReturn(projectMeasure); decorator.decorate(project, decoratorContext); Mockito.verify(decoratorContext, Mockito.times(0)).saveMeasure((Measure) Mockito.anyObject()); } }
package sortimo.formularmanager.controller; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.google.gson.Gson; import sortimo.formularmanager.databaseoperations.FormEdit; import sortimo.formularmanager.databaseoperations.FormStatistics; import sortimo.formularmanager.global.ConfigMaps; import sortimo.formularmanager.storage.FormsStatisticsStorage; import sortimo.model.HelperFunctions; import sortimo.model.User; @WebServlet("/FormularManagerStatisticsController") public class FormularManagerStatisticsController extends HttpServlet { private static final long serialVersionUID = 1L; public FormularManagerStatisticsController() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HelperFunctions helper = new HelperFunctions(); if (helper.checkCookie(request)) { HttpSession session = request.getSession(); User userData = (User) session.getAttribute("userData"); User user = new User(); if (userData == null) { try { user.getUserAccount(helper.getUsername()); session.setAttribute("userData", user); } catch (Exception e) { e.printStackTrace(); } } else { user = (User) session.getAttribute("userData"); } String action = request.getParameter("action") != null ? request.getParameter("action") : "false"; String formId = request.getParameter("form_id") != null ? request.getParameter("form_id") : "false"; String responseId = request.getParameter("response_id") != null ? request.getParameter("response_id") : "false"; String country = request.getParameter("country") != null ? request.getParameter("country") : "DE"; request.setAttribute("user", user); request.setAttribute("formId", formId); FormStatistics stats = new FormStatistics(); ConfigMaps config = new ConfigMaps(); Gson gson = new Gson(); Map<Integer, FormsStatisticsStorage> statistics = null; Map<String, String> statisticsData = new HashMap<String, String>(); Map<String, String> formData = null; FormEdit form = new FormEdit(); FormsStatisticsStorage formStatistics = null; String formResponseStorageJson = null; String formDataJson = null; Map<String, String> meta = new HashMap<>(); meta.put("country", country); meta.put("formId", formId); String statesJson = gson.toJson(config.getStates()); String stateIconsJson = gson.toJson(config.getStateIcons()); switch(action) { case "getFormStatistics" : try { formStatistics = stats.getFormStatistics(responseId); formData = form.getFormData(formId); } catch (Exception e) { System.err.println("Statistik konnte nicht aus DB gelesen werden"); e.printStackTrace(); } formResponseStorageJson = gson.toJson(formStatistics); formDataJson = gson.toJson(formData); String userJson = gson.toJson(user); statisticsData.put("responseData", formResponseStorageJson); statisticsData.put("formData", formDataJson); statisticsData.put("user", userJson); statisticsData.put("states", statesJson); String json = gson.toJson(statisticsData); response.setContentType("text/plain"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(json); return; case "getChartStatistics" : Map<Integer, FormsStatisticsStorage> getChartStatistics = null; try { getChartStatistics = stats.getChartStatistics(formId); formData = form.getFormData(formId); } catch (Exception e) { System.err.println("Statistik konnte nicht aus DB gelesen werden"); e.printStackTrace(); } formResponseStorageJson = gson.toJson(getChartStatistics); formDataJson = gson.toJson(formData); String userInfoJson = gson.toJson(user); statisticsData.put("responseData", formResponseStorageJson); statisticsData.put("formData", formDataJson); statisticsData.put("user", userInfoJson); statisticsData.put("states", statesJson); String chartJson = gson.toJson(statisticsData); response.setContentType("text/plain"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(chartJson); return; case "getRespondedForms" : try { statistics = stats.getRespondedForms(formId, country); } catch (Exception e) { System.err.println("Responded Forms konnten nicht aus DB gelesen werden"); e.printStackTrace(); } formResponseStorageJson = gson.toJson(statistics); statisticsData.put("respondedForms", formResponseStorageJson); statisticsData.put("states", statesJson); statisticsData.put("stateIcons", stateIconsJson); String respondedFormsjson = gson.toJson(statisticsData); response.setContentType("text/plain"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(respondedFormsjson); return; case "saveProcessed" : try { stats.updateProcessState(request); } catch (Exception e) { System.err.println("Processed Status konnte nicht geändert werden"); e.printStackTrace(); } break; default : request.setAttribute("pageTitle", "Statistiken"); request.setAttribute("path", "formularmanager"); request.setAttribute("view", "statistics"); getServletContext().getRequestDispatcher("/layout.jsp").forward(request, response); break; } } else { response.sendRedirect("/sortimo/login"); return; } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
package deck; import card.*; import java.util.ArrayList; public interface Deck { /* Create the deck of cards */ public void create(int numberOfSuits, int numberOfRanks); /* Shuffle the deck */ public void shuffle(); /* deal a card from the deck */ public Card deal(); public ArrayList<Card> getDeck(); }
package DAO; import java.io.ByteArrayInputStream; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.time.LocalDate; import java.util.logging.Level; import java.util.logging.Logger; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.image.Image; import javax.imageio.ImageIO; import model.Categoria; import model.Conexion; import model.Producto; import model.Usuario; public class ProductoDAO { public ProductoDAO() { } public int guardar(Producto p, boolean accion){ String sql = null; if(!accion){ sql = "INSERT INTO producto (codigoproducto,nombreproducto,medida,imagen,fechaderegistro,idusuario,idcategoria) VALUES"; sql += "("; sql += " '"+p.getCodigoproducto()+"' , '"+p.getNombreproducto()+"' , '"+p.getMedida()+"' , ? , '"+LocalDate.now()+"' , "+model.Usuario.getInstanceUser(0, null, null, null).getIdusuario()+" , 5 "; sql += ")"; }else{ sql = "UPDATE producto SET codigoproducto='"+p.getCodigoproducto()+"', " + "nombreproducto='"+p.getNombreproducto()+"', " + "medida='"+p.getMedida()+"', " + "imagen=? WHERE idproducto="+p.getIdproducto(); } Conexion con = new Conexion(); try { PreparedStatement pst = con.getCon().prepareStatement(sql); pst.setBytes(1, p.getImagen()); int n = pst.executeUpdate(); return n; } catch (SQLException ex) { Logger.getLogger(ProductoDAO.class.getName()).log(Level.SEVERE, null, ex); util.Metodos.alert("Error", "Error al guardar el producto", null, Alert.AlertType.WARNING, ex, null); }finally{ con.CERRAR(); } return 0; } public int delete(Producto p){ Conexion con = new Conexion(); try { return con.GUARDAR("DELETE FROM producto WHERE idproducto="+p.getIdproducto()); } catch (SQLException ex) { util.Metodos.alert("Error", "Error al intentar eliminar el producto", null, Alert.AlertType.WARNING, ex, null); Logger.getLogger(ProductoDAO.class.getName()).log(Level.SEVERE, null, ex); }finally{ con.CERRAR(); } return 0; } public ObservableList<Producto> getProductos(){ ObservableList<Producto> productos = FXCollections.observableArrayList(); try { String sql = "SELECT u.nombreusuario, idproducto, codigoproducto, nombreproducto, medida, fechaderegistro, idcategoria\n" + " FROM producto p INNER JOIN usuario u ON u.idusuario=p.idusuario ORDER BY nombreproducto;"; Conexion con = new Conexion(); ResultSet rs = con.CONSULTAR(sql); while(rs.next()){ Producto p = new Producto(); p.setIdproducto(rs.getInt("idproducto")); p.setCodigoproducto(rs.getString("codigoproducto")); p.setNombreproducto(rs.getString("nombreproducto")); p.setMedida(rs.getString("medida")); p.setFechaderegistro(rs.getDate("fechaderegistro").toLocalDate()); p.setUsuario(new Usuario(rs.getString("nombreusuario"))); p.setSelected(false); productos.add(p); } con.CERRAR(); } catch (SQLException ex) { Logger.getLogger(ProductoDAO.class.getName()).log(Level.SEVERE, null, ex); } return productos; } public Image getImagen(int idproducto){ Image imagen = null; Conexion con = new Conexion(); ResultSet rs; try { rs = con.CONSULTAR("SELECT imagen FROM producto WHERE idproducto="+idproducto); if(rs.next()){ imagen = new Image(new ByteArrayInputStream(rs.getBytes("imagen")));//ImageIO.read(new ByteArrayInputStream(rs.getBytes("imagen"))); } } catch (SQLException ex) { Logger.getLogger(ProductoDAO.class.getName()).log(Level.SEVERE, null, ex); }finally{ con.CERRAR(); } return imagen; } }
package adp.group10.roomates.backend.model; import java.io.Serializable; /** * Created by calle on 2017-04-23. */ public class AvailableItem implements Serializable { private String Name; public AvailableItem(){ // Required for Firebase } public AvailableItem(String name){ this.Name = name; } public void setName(String name) { this.Name = name; } public String getName() { return Name; } }
package com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.builder; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.AbstractVerbundType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.DispositiveSperrListeType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.FertigungszustandType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.GeometrieType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.GewichtType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.IdentifikationType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.LagerInformationType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.MaterialFehlerListeType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.MaterialPraeferenzKzType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.MaterialTextListeType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.ProduktionswegType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.ProgrammierungType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.ReklamationType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.RestproduktionswegType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.StatusType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.TransportInformationType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.VerpackungArtType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.VersanddatenType; import java.io.StringWriter; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.namespace.QName; public class AbstractVerbundTypeBuilder { public static String marshal(AbstractVerbundType abstractVerbundType) throws JAXBException { JAXBElement<AbstractVerbundType> jaxbElement = new JAXBElement<>(new QName("TESTING"), AbstractVerbundType.class , abstractVerbundType); StringWriter stringWriter = new StringWriter(); return stringWriter.toString(); } private IdentifikationType identifikation; private FertigungszustandType fertigungszustand; private StatusType materialStatus; private ProduktionswegType produktionsweg; private MaterialPraeferenzKzType praeferenzKz; private ReklamationType reklamation; private LagerInformationType lagerInformation; private GewichtType gewicht; private GeometrieType geometrie; private VerpackungArtType verpackung; private ProgrammierungType programmierung; private DispositiveSperrListeType dispositiveSperrListe; private MaterialFehlerListeType materialFehlerListe; private TransportInformationType transportInformation; private MaterialTextListeType materialTextListe; private VersanddatenType versanddaten; private RestproduktionswegType restproduktionsweg; public AbstractVerbundTypeBuilder setIdentifikation(IdentifikationType value) { this.identifikation = value; return this; } public AbstractVerbundTypeBuilder setFertigungszustand(FertigungszustandType value) { this.fertigungszustand = value; return this; } public AbstractVerbundTypeBuilder setMaterialStatus(StatusType value) { this.materialStatus = value; return this; } public AbstractVerbundTypeBuilder setProduktionsweg(ProduktionswegType value) { this.produktionsweg = value; return this; } public AbstractVerbundTypeBuilder setPraeferenzKz(MaterialPraeferenzKzType value) { this.praeferenzKz = value; return this; } public AbstractVerbundTypeBuilder setReklamation(ReklamationType value) { this.reklamation = value; return this; } public AbstractVerbundTypeBuilder setLagerInformation(LagerInformationType value) { this.lagerInformation = value; return this; } public AbstractVerbundTypeBuilder setGewicht(GewichtType value) { this.gewicht = value; return this; } public AbstractVerbundTypeBuilder setGeometrie(GeometrieType value) { this.geometrie = value; return this; } public AbstractVerbundTypeBuilder setVerpackung(VerpackungArtType value) { this.verpackung = value; return this; } public AbstractVerbundTypeBuilder setProgrammierung(ProgrammierungType value) { this.programmierung = value; return this; } public AbstractVerbundTypeBuilder setDispositiveSperrListe(DispositiveSperrListeType value) { this.dispositiveSperrListe = value; return this; } public AbstractVerbundTypeBuilder setMaterialFehlerListe(MaterialFehlerListeType value) { this.materialFehlerListe = value; return this; } public AbstractVerbundTypeBuilder setTransportInformation(TransportInformationType value) { this.transportInformation = value; return this; } public AbstractVerbundTypeBuilder setMaterialTextListe(MaterialTextListeType value) { this.materialTextListe = value; return this; } public AbstractVerbundTypeBuilder setVersanddaten(VersanddatenType value) { this.versanddaten = value; return this; } public AbstractVerbundTypeBuilder setRestproduktionsweg(RestproduktionswegType value) { this.restproduktionsweg = value; return this; } public AbstractVerbundType build() { AbstractVerbundType result = new AbstractVerbundType(); result.setIdentifikation(identifikation); result.setFertigungszustand(fertigungszustand); result.setMaterialStatus(materialStatus); result.setProduktionsweg(produktionsweg); result.setPraeferenzKz(praeferenzKz); result.setReklamation(reklamation); result.setLagerInformation(lagerInformation); result.setGewicht(gewicht); result.setGeometrie(geometrie); result.setVerpackung(verpackung); result.setProgrammierung(programmierung); result.setDispositiveSperrListe(dispositiveSperrListe); result.setMaterialFehlerListe(materialFehlerListe); result.setTransportInformation(transportInformation); result.setMaterialTextListe(materialTextListe); result.setVersanddaten(versanddaten); result.setRestproduktionsweg(restproduktionsweg); return result; } }
package com.company.view; import com.company.controller.Controller; import com.company.model.MinesweeperCell; import com.company.model.MinesweeperModel; import javax.swing.*; import java.awt.*; public class GameField extends JPanel { private static final int CELL_SIZE = 16; private MinesweeperModel model; private Controller controller; private MinesweeperView view; private int rowCount; private int columCount; public GameField(MinesweeperModel model, Controller controller, MinesweeperView view) { this.model = model; this.controller = controller; this.view = view; this.addMouseMotionListener(controller); this.addMouseListener(controller); FieldInitialization(); } //Инициализация поля, используется для того,чтобы начать игру или при изменение уровня сложности public void FieldInitialization() { removeAll(); rowCount = model.getRowCount(); columCount = model.getColumCount(); setPreferredSize(new Dimension(CELL_SIZE * columCount, CELL_SIZE * rowCount)); } //Используется для синхронизации Модели и Представления(то есть Представление отрисовает состояние Модели) @Override public void paintComponent(Graphics g) { Graphics2D g2d = (Graphics2D) g; g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); for (int i = 0; i < rowCount; i++) { for (int j = 0; j < columCount; j++) { Image im = getImageForStateCell(i, j); g2d.drawImage(im, j * CELL_SIZE, i * CELL_SIZE, CELL_SIZE, CELL_SIZE, null); } } } //Псевдоавтомат, который по состоянию ячейки в Модели выдает определеную image public Image getImageForStateCell(int row, int colum) { MinesweeperCell cell = model.getCell(row, colum); if (cell.getState() == "closed") { if (model.isGameOver() && cell.isMined()) { return view.hashMapImage.get("StateBomb.png").getImage(); } if (model.isFinishGame() && cell.isMined()) { return view.hashMapImage.get("StateFlag.png").getImage(); } if (cell.isViewed()) { return view.hashMapImage.get("State0.png").getImage(); } return view.hashMapImage.get("StateClosed.png").getImage(); } else if (cell.getState() == "flagged") { if (!cell.isMined() && model.isGameOver()) { return view.hashMapImage.get("StateBombMistake.png").getImage(); } return view.hashMapImage.get("StateFlag.png").getImage(); } else if (cell.getState() == "question") { if (cell.isViewed()) { return view.hashMapImage.get("StateQuestionViewed.png").getImage(); } return view.hashMapImage.get("StateQuestion.png").getImage(); } else if (cell.getState() == "opened") { if (cell.isMined()) { return view.hashMapImage.get("StateBombThis.png").getImage(); } return view.hashMapImage.get("State" + cell.getCounter() + ".png").getImage(); } return null; } //Псевдоавтомат, который по позиции x и y, выдает номер ячейки в Модели public Point getPosition(int x, int y) { if (x >= 0 && x < getWidth() && y >= 0 && y < getHeight()) { return new Point(x / CELL_SIZE, y / CELL_SIZE); } return null; } }
package com.example.ta; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.ta.API.ApiClient; import com.example.ta.API.ApiInterface; import com.example.ta.API.SessionManager; import com.google.gson.JsonObject; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class LoginActivity extends AppCompatActivity { EditText et_username, et_password; Button bt_login; String Username, Password; ApiInterface apiInterface; SessionManager sessionManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); sessionManager = new SessionManager(LoginActivity.this); if (sessionManager.checkToken()){ Intent intent = new Intent(LoginActivity.this, MainActivity.class); startActivity(intent); finish(); } et_username = findViewById(R.id.et_username); et_password = findViewById(R.id.et_password); bt_login = findViewById(R.id.bt_login); final LoadingDialog loadingDialog = new LoadingDialog(LoginActivity.this); bt_login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { switch (v.getId()){ case R.id.bt_login: Username = et_username.getText().toString(); Password = et_password.getText().toString(); login(Username, Password); loadingDialog.startLoadingDialog(); break; } } }); } private void login(String username, String password) { apiInterface = ApiClient.getClient().create(ApiInterface.class); Call<ResponseBody> loginCall = apiInterface.loginResponse(username, password); loginCall.enqueue(new Callback<ResponseBody>(){ @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if (response.isSuccessful()) { JSONObject jsonRESULTS = null; try { jsonRESULTS = new JSONObject(response.body().string()); JSONObject jsonData = jsonRESULTS.getJSONObject("data"); Log.e("jsonData", jsonData.toString()); if (jsonData.length()!=0) { String token = jsonData.getString("token"); String name = jsonData.getString("name"); String nip = jsonData.getString("nip"); sessionManager.createLoginSession(token, name, nip); Toast.makeText(LoginActivity.this, name, Toast.LENGTH_SHORT).show(); Intent intent = new Intent(LoginActivity.this, MainActivity.class); startActivity(intent); finish(); } } catch (JSONException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }else { Toast.makeText(LoginActivity.this, "Gagal Login", Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { Log.e("error data", t.getMessage()); } }); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package unalcol.types.real.array; import unalcol.math.metric.MetricVectorSpace; import unalcol.math.metric.QuasiMetric; /** * @author jgomez */ public class MetricRealVectorSpace extends RealVectorSpace implements MetricVectorSpace<double[]> { protected QuasiMetric<double[]> metric; public MetricRealVectorSpace(QuasiMetric<double[]> metric) { this.metric = metric; } @Override public double apply(double[] x, double[] y) { return metric.apply(x, y); } }
package com.compulynx.droid.view.activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ProgressBar; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.DividerItemDecoration; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.compulynx.droid.R; import com.compulynx.droid.db.Transaction; import com.compulynx.droid.network.HttpApi; import com.compulynx.droid.view.adapter.TransactionAdapter; import com.compulynx.droid.view.util.ViewUtil; import com.google.gson.JsonObject; import butterknife.BindView; import butterknife.ButterKnife; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; public class StatementActivity extends AppCompatActivity { public static final String CUSTOMER_ID = "customerID"; @BindView(R.id.progress) ProgressBar progressBar; @BindView(R.id.recycler_view) RecyclerView recyclerView; @BindView(R.id.tv_bottom_right) TextView tvTotal; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_statement); ButterKnife.bind(this); recyclerView.setLayoutManager(new LinearLayoutManager(this)); recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL)); fetchTransactions(); } void fetchTransactions() { progressBar.setVisibility(View.VISIBLE); JsonObject body = new JsonObject(); body.addProperty("customerId", getIntent().getStringExtra(CUSTOMER_ID)); HttpApi.getInstance().fetchLast100Txns(body) .subscribeOn(Schedulers.io()) .observeOn(Schedulers.io()) .onErrorReturn(err -> { Log.e(getClass().getSimpleName(), err.toString()); return null; }) .observeOn(AndroidSchedulers.mainThread()) .doOnNext(resp -> { progressBar.setVisibility(View.GONE); //Log.w("resp", resp.toString()); if (resp != null) { //Type type = new TypeToken<ArrayList<Transaction>>(){}.getType(); double sum = 0; for (Transaction transaction : resp) sum += transaction.amount; recyclerView.setAdapter(new TransactionAdapter(resp)); tvTotal.setText(String.valueOf(sum)); } else ViewUtil.showToast(this, getString(R.string.sth_went_wrong), false); }).subscribe(); } }
package com.sinotao.business.dao.entity; import javax.persistence.Column; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; /** * 检查信息表 * @author 佟磊 */ @Table(name = "t_clinicar_check") public class ClinicarCheck { /** * 代理主键 */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; /** * 删除标记 */ private Boolean deleted; /** * 检查项目编号 */ @Column(name = "check_number") private String checkNumber; //其他字段没有用到,暂时没有加 /** * @return the id */ public Integer getId() { return id; } /** * @param id the id to set */ public void setId(Integer id) { this.id = id; } /** * @return the deleted */ public Boolean getDeleted() { return deleted; } /** * @param deleted the deleted to set */ public void setDeleted(Boolean deleted) { this.deleted = deleted; } /** * @return the checkNumber */ public String getCheckNumber() { return checkNumber; } /** * @param checkNumber the checkNumber to set */ public void setCheckNumber(String checkNumber) { this.checkNumber = checkNumber; } }
package com.akexorcist.myapplication; import android.os.Bundle; import android.support.annotation.NonNull; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.akexorcist.myapplication.common.BaseActivity; import com.akexorcist.myapplication.manager.DialogManager; import com.akexorcist.myapplication.utility.Utility; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; public class LoginActivity extends BaseActivity implements View.OnClickListener { private EditText etUsername; private EditText etPassword; private Button btnSignIn; private Button btnSignUp; private FirebaseAuth firebaseAuth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bindView(); setupView(); setupFirebaseAuth(); checkAlreadyLoggedIn(); } private void bindView() { etUsername = (EditText) findViewById(R.id.et_username); etPassword = (EditText) findViewById(R.id.et_password); btnSignIn = (Button) findViewById(R.id.btn_sign_in); btnSignUp = (Button) findViewById(R.id.btn_sign_up); } private void setupView() { btnSignIn.setOnClickListener(this); btnSignUp.setOnClickListener(this); } private void setupFirebaseAuth() { firebaseAuth = FirebaseAuth.getInstance(); } private void checkAlreadyLoggedIn() { FirebaseUser firebaseUser = firebaseAuth.getCurrentUser(); if (firebaseUser != null) { goToChatRoom(); } } @Override public void onClick(View view) { hideKeyboard(); if (view == btnSignIn) { String username = etUsername.getText().toString(); String password = etPassword.getText().toString(); signIn(username, password); } else if (view == btnSignUp) { String username = etUsername.getText().toString(); String password = etPassword.getText().toString(); signUp(username, password); } } private void signUp(@NonNull String username, @NonNull String password) { if (isUsernameAndPasswordValidated(username, password)) { showLoadingDialog(); firebaseAuth.createUserWithEmailAndPassword(username, password) .addOnSuccessListener(new OnSuccessListener<AuthResult>() { @Override public void onSuccess(AuthResult authResult) { FirebaseUser user = authResult.getUser(); if (user != null) { dismissLoadingDialog(); goToChatRoom(); } } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { dismissLoadingDialog(); showBottomMessage(e.getMessage()); } }); } } private void signIn(@NonNull String username, @NonNull String password) { if (isUsernameAndPasswordValidated(username, password)) { showLoadingDialog(); firebaseAuth.signInWithEmailAndPassword(username, password) .addOnSuccessListener(new OnSuccessListener<AuthResult>() { @Override public void onSuccess(AuthResult authResult) { FirebaseUser user = authResult.getUser(); if (user != null) { dismissLoadingDialog(); goToChatRoom(); } } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { dismissLoadingDialog(); showBottomMessage(e.getMessage()); } }); } } private void dismissLoadingDialog() { DialogManager.getInstance().dismissDialog(); } private void showLoadingDialog() { DialogManager.getInstance().showLoading(this); } private void goToChatRoom() { openActivity(ChatRoomActivity.class); } private boolean isUsernameAndPasswordValidated(String username, String password) { if (Utility.isUsernameAndPasswordEmpty(username, password)) { showBottomMessage(R.string.please_insert_username_password); return false; } if (Utility.isUsernameAndPasswordLessThan6Charactor(username, password)) { showBottomMessage(R.string.username_password_contain_at_least_6_characters); return false; } return true; } }
/* * 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 br.cwi.crescer.repositorio; import br.cwi.crescer.entity.Cidade; import br.cwi.crescer.entity.Cliente; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; /** * * @author Érico de Souza Loewe */ public class ClienteRepositorio extends RepositorioBase<Cliente> implements Repositorio<Cliente> { public void adicionar(Cliente cliente) { super.adicionar(cliente); } public void atualizar(Cliente cliente) { super.atualizar(cliente); } public void deletar(Long idCliente) { super.deletar(idCliente); } @Override public List<Cliente> listar() { return super.listar("Cliente"); } }
package com.dennistjahyadigotama.soaya.fcm; /** * Created by Denn on 7/21/2016. */ public class a { /* FirebaseMessaging.getInstance().subscribeToTopic("news"); Log.d(TAG, "Subscribed to news topic"); Log.d(TAG, "InstanceID token: " + FirebaseInstanceId.getInstance().getToken()); */ }
package database.entity; import javax.persistence.Entity; /** * Created by csvanefalk on 18/11/14. */ @Entity public class Category extends AbstractEntity { private String title; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }
/* * Copyright (C) 2021-2023 Hedera Hashgraph, LLC * * 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 com.hedera.mirror.importer.parser.record.entity; import static com.hederahashgraph.api.proto.java.ResponseCodeEnum.SUCCESS; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.from; import static org.junit.jupiter.api.Assertions.assertEquals; import com.google.protobuf.ByteString; import com.google.protobuf.UnknownFieldSet; import com.hedera.mirror.common.domain.entity.Entity; import com.hedera.mirror.common.domain.entity.EntityId; import com.hedera.mirror.common.domain.schedule.Schedule; import com.hedera.mirror.common.domain.transaction.RecordItem; import com.hedera.mirror.common.domain.transaction.TransactionSignature; import com.hedera.mirror.common.util.DomainUtils; import com.hedera.mirror.importer.TestUtils; import com.hedera.mirror.importer.repository.ScheduleRepository; import com.hedera.mirror.importer.repository.TransactionRepository; import com.hedera.mirror.importer.repository.TransactionSignatureRepository; import com.hederahashgraph.api.proto.java.AccountID; import com.hederahashgraph.api.proto.java.Key; import com.hederahashgraph.api.proto.java.ResponseCodeEnum; import com.hederahashgraph.api.proto.java.SchedulableTransactionBody; import com.hederahashgraph.api.proto.java.ScheduleCreateTransactionBody; import com.hederahashgraph.api.proto.java.ScheduleDeleteTransactionBody; import com.hederahashgraph.api.proto.java.ScheduleID; import com.hederahashgraph.api.proto.java.SignatureMap; import com.hederahashgraph.api.proto.java.SignaturePair; import com.hederahashgraph.api.proto.java.Transaction; import com.hederahashgraph.api.proto.java.TransactionBody; import com.hederahashgraph.api.proto.java.TransactionReceipt; import com.hederahashgraph.api.proto.java.TransactionRecord; import jakarta.annotation.Resource; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.commons.lang3.RandomStringUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; class EntityRecordItemListenerScheduleTest extends AbstractEntityRecordItemListenerTest { private static final long CREATE_TIMESTAMP = 1L; private static final long EXECUTE_TIMESTAMP = 500L; private static final String SCHEDULE_CREATE_MEMO = "ScheduleCreate memo"; private static final SchedulableTransactionBody SCHEDULED_TRANSACTION_BODY = SchedulableTransactionBody.getDefaultInstance(); private static final ScheduleID SCHEDULE_ID = ScheduleID.newBuilder() .setShardNum(0) .setRealmNum(0) .setScheduleNum(2) .build(); private static final Key SCHEDULE_REF_KEY = keyFromString(KEY); private static final long SIGN_TIMESTAMP = 10L; @Resource protected ScheduleRepository scheduleRepository; @Resource protected TransactionSignatureRepository transactionSignatureRepository; @Resource protected TransactionRepository transactionRepository; private List<TransactionSignature> defaultSignatureList; private static Stream<Arguments> provideScheduleCreatePayer() { return Stream.of( Arguments.of(null, PAYER, "no payer expect same as creator"), Arguments.of(PAYER, PAYER, "payer set to creator"), Arguments.of(PAYER2, PAYER2, "payer different than creator")); } @BeforeEach void before() { entityProperties.getPersist().setSchedules(true); defaultSignatureList = toTransactionSignatureList(CREATE_TIMESTAMP, SCHEDULE_ID, DEFAULT_SIG_MAP); } @ParameterizedTest(name = "{2}") @MethodSource("provideScheduleCreatePayer") void scheduleCreate(AccountID payer, AccountID expectedPayer, String name) { insertScheduleCreateTransaction(CREATE_TIMESTAMP, payer, SCHEDULE_ID); // verify entity count Entity expectedEntity = createEntity( EntityId.of(SCHEDULE_ID), SCHEDULE_REF_KEY, null, null, false, null, SCHEDULE_CREATE_MEMO, null, CREATE_TIMESTAMP, CREATE_TIMESTAMP); Schedule expectedSchedule = Schedule.builder() .consensusTimestamp(CREATE_TIMESTAMP) .creatorAccountId(EntityId.of(PAYER)) .payerAccountId(EntityId.of(expectedPayer)) .scheduleId(EntityId.of(SCHEDULE_ID).getId()) .transactionBody(SCHEDULED_TRANSACTION_BODY.toByteArray()) .build(); assertEquals(1, entityRepository.count()); assertEntity(expectedEntity); // verify schedule and signatures assertThat(scheduleRepository.findAll()).containsOnly(expectedSchedule); assertTransactionSignatureInRepository(defaultSignatureList); // verify transaction assertTransactionInRepository(CREATE_TIMESTAMP, false, SUCCESS); } @Test void scheduleCreateLongTermScheduledTransaction() { var expirationTime = recordItemBuilder.timestamp(); var pubKeyPrefix = recordItemBuilder.bytes(16); var signature = recordItemBuilder.bytes(32); var recordItem = recordItemBuilder .scheduleCreate() .receipt(r -> r.setScheduleID(SCHEDULE_ID)) .signatureMap(s -> s.clear() .addSigPair(SignaturePair.newBuilder() .setPubKeyPrefix(pubKeyPrefix) .setEd25519(signature))) .transactionBody(b -> b.setExpirationTime(expirationTime).setWaitForExpiry(true)) .build(); var scheduleCreate = recordItem.getTransactionBody().getScheduleCreate(); var timestamp = recordItem.getConsensusTimestamp(); var expectedEntity = createEntity( EntityId.of(SCHEDULE_ID), scheduleCreate.getAdminKey(), null, null, false, null, scheduleCreate.getMemo(), null, timestamp, timestamp); var expectedSchedule = Schedule.builder() .consensusTimestamp(recordItem.getConsensusTimestamp()) .creatorAccountId(recordItem.getPayerAccountId()) .expirationTime(DomainUtils.timestampInNanosMax(expirationTime)) .payerAccountId(EntityId.of(scheduleCreate.getPayerAccountID())) .scheduleId(SCHEDULE_ID.getScheduleNum()) .transactionBody(scheduleCreate.getScheduledTransactionBody().toByteArray()) .waitForExpiry(true) .build(); var expectedTransactionSignature = TransactionSignature.builder() .consensusTimestamp(timestamp) .entityId(EntityId.of(SCHEDULE_ID)) .publicKeyPrefix(DomainUtils.toBytes(pubKeyPrefix)) .signature(DomainUtils.toBytes(signature)) .type(SignaturePair.ED25519_FIELD_NUMBER) .build(); // when parseRecordItemAndCommit(recordItem); // then assertThat(entityRepository.findAll()).containsOnly(expectedEntity); assertThat(scheduleRepository.findAll()).containsOnly(expectedSchedule); assertThat(transactionSignatureRepository.findAll()).containsOnly(expectedTransactionSignature); assertTransactionInRepository(timestamp, false, SUCCESS); } @Test void scheduleDelete() { // given insertScheduleCreateTransaction(CREATE_TIMESTAMP, null, SCHEDULE_ID); // when long deletedTimestamp = CREATE_TIMESTAMP + 10; insertScheduleDeleteTransaction(deletedTimestamp, SCHEDULE_ID); // then Entity expected = createEntity( EntityId.of(SCHEDULE_ID), SCHEDULE_REF_KEY, null, null, true, null, SCHEDULE_CREATE_MEMO, null, CREATE_TIMESTAMP, deletedTimestamp); assertEquals(1, entityRepository.count()); assertEntity(expected); // verify schedule assertThat(scheduleRepository.count()).isOne(); assertScheduleInRepository(SCHEDULE_ID, CREATE_TIMESTAMP, PAYER, null); // verify transaction assertTransactionInRepository(deletedTimestamp, false, SUCCESS); } @Test void scheduleSign() { insertScheduleCreateTransaction(CREATE_TIMESTAMP, null, SCHEDULE_ID); // sign SignatureMap signatureMap = getSigMap(3, true); insertScheduleSign(SIGN_TIMESTAMP, signatureMap, SCHEDULE_ID); // verify entity count assertEquals(1, entityRepository.count()); // verify schedule assertThat(scheduleRepository.count()).isOne(); assertScheduleInRepository(SCHEDULE_ID, CREATE_TIMESTAMP, PAYER, null); // verify schedule signatures List<TransactionSignature> expectedTransactionSignatureList = new ArrayList<>(defaultSignatureList); expectedTransactionSignatureList.addAll(toTransactionSignatureList(SIGN_TIMESTAMP, SCHEDULE_ID, signatureMap)); assertTransactionSignatureInRepository(expectedTransactionSignatureList); // verify transaction assertTransactionInRepository(SIGN_TIMESTAMP, false, SUCCESS); } @Test void scheduleSignTwoBatches() { insertScheduleCreateTransaction(CREATE_TIMESTAMP, null, SCHEDULE_ID); // first sign SignatureMap firstSignatureMap = getSigMap(2, true); insertScheduleSign(SIGN_TIMESTAMP, firstSignatureMap, SCHEDULE_ID); // verify schedule signatures List<TransactionSignature> expectedTransactionSignatureList = new ArrayList<>(defaultSignatureList); expectedTransactionSignatureList.addAll( toTransactionSignatureList(SIGN_TIMESTAMP, SCHEDULE_ID, firstSignatureMap)); assertTransactionSignatureInRepository(expectedTransactionSignatureList); // second sign long timestamp = SIGN_TIMESTAMP + 10; SignatureMap secondSignatureMap = getSigMap(3, true); insertScheduleSign(timestamp, secondSignatureMap, SCHEDULE_ID); expectedTransactionSignatureList.addAll(toTransactionSignatureList(timestamp, SCHEDULE_ID, secondSignatureMap)); assertTransactionSignatureInRepository(expectedTransactionSignatureList); // verify entity count Entity expected = createEntity( EntityId.of(SCHEDULE_ID), SCHEDULE_REF_KEY, null, null, false, null, SCHEDULE_CREATE_MEMO, null, CREATE_TIMESTAMP, CREATE_TIMESTAMP); assertEquals(1, entityRepository.count()); assertEntity(expected); // verify schedule assertThat(scheduleRepository.count()).isOne(); assertScheduleInRepository(SCHEDULE_ID, CREATE_TIMESTAMP, PAYER, null); // verify transaction assertTransactionInRepository(SIGN_TIMESTAMP, false, SUCCESS); } @Test void scheduleSignDuplicateEd25519Signatures() { SignatureMap signatureMap = getSigMap(3, true); SignaturePair first = signatureMap.getSigPair(0); SignaturePair third = signatureMap.getSigPair(2); SignatureMap signatureMapWithDuplicate = signatureMap.toBuilder().addSigPair(first).addSigPair(third).build(); insertScheduleSign(SIGN_TIMESTAMP, signatureMapWithDuplicate, SCHEDULE_ID); // verify lack of schedule data and transaction assertTransactionSignatureInRepository(toTransactionSignatureList(SIGN_TIMESTAMP, SCHEDULE_ID, signatureMap)); assertThat(transactionRepository.count()).isEqualTo(1); } @Test void unknownSignatureType() { int unknownType = 999; ByteString sig = ByteString.copyFromUtf8("123"); UnknownFieldSet.Field unknownField = UnknownFieldSet.Field.newBuilder().addLengthDelimited(sig).build(); SignatureMap.Builder signatureMap = SignatureMap.newBuilder() .addSigPair(SignaturePair.newBuilder() .setPubKeyPrefix(byteString(8)) .setContract(sig) .build()) .addSigPair(SignaturePair.newBuilder() .setPubKeyPrefix(byteString(8)) .setECDSA384(sig) .build()) .addSigPair(SignaturePair.newBuilder() .setPubKeyPrefix(byteString(8)) .setECDSASecp256K1(sig) .build()) .addSigPair(SignaturePair.newBuilder() .setPubKeyPrefix(byteString(8)) .setEd25519(sig) .build()) .addSigPair(SignaturePair.newBuilder() .setPubKeyPrefix(byteString(8)) .setRSA3072(sig) .build()) .addSigPair(SignaturePair.newBuilder() .setPubKeyPrefix(byteString(8)) .setUnknownFields(UnknownFieldSet.newBuilder() .addField(unknownType, unknownField) .build()) .build()); insertScheduleSign(SIGN_TIMESTAMP, signatureMap.build(), SCHEDULE_ID); // verify assertThat(transactionRepository.count()).isEqualTo(1); assertThat(transactionSignatureRepository.findAll()) .isNotNull() .hasSize(signatureMap.getSigPairCount()) .allSatisfy(t -> assertThat(t) .returns(sig.toByteArray(), TransactionSignature::getSignature) .extracting(TransactionSignature::getPublicKeyPrefix) .isNotNull()) .extracting(TransactionSignature::getType) .containsExactlyInAnyOrder( SignaturePair.SignatureCase.CONTRACT.getNumber(), SignaturePair.SignatureCase.ECDSA_384.getNumber(), SignaturePair.SignatureCase.ECDSA_SECP256K1.getNumber(), SignaturePair.SignatureCase.ED25519.getNumber(), SignaturePair.SignatureCase.RSA_3072.getNumber(), unknownType); } @Test void unsupportedSignature() { SignatureMap signatureMap = SignatureMap.newBuilder() .addSigPair(SignaturePair.newBuilder().build()) .build(); insertScheduleSign(SIGN_TIMESTAMP, signatureMap, SCHEDULE_ID); // verify assertThat(transactionRepository.count()).isOne(); assertThat(transactionSignatureRepository.count()).isZero(); assertThat(scheduleRepository.count()).isZero(); assertTransactionInRepository(SIGN_TIMESTAMP, false, SUCCESS); } @Test void scheduleExecuteOnSuccess() { scheduleExecute(SUCCESS); } @Test void scheduleExecuteOnFailure() { scheduleExecute(ResponseCodeEnum.INVALID_CHUNK_TRANSACTION_ID); } private ByteString byteString(int length) { return ByteString.copyFrom(domainBuilder.bytes(length)); } void scheduleExecute(ResponseCodeEnum responseCodeEnum) { insertScheduleCreateTransaction(CREATE_TIMESTAMP, null, SCHEDULE_ID); // sign SignatureMap signatureMap = getSigMap(3, true); insertScheduleSign(SIGN_TIMESTAMP, signatureMap, SCHEDULE_ID); // scheduled transaction insertScheduledTransaction(EXECUTE_TIMESTAMP, SCHEDULE_ID, responseCodeEnum); // verify entity count Entity expected = createEntity( EntityId.of(SCHEDULE_ID), SCHEDULE_REF_KEY, null, null, false, null, SCHEDULE_CREATE_MEMO, null, CREATE_TIMESTAMP, CREATE_TIMESTAMP); assertEquals(1, entityRepository.count()); assertEntity(expected); // verify schedule assertScheduleInRepository(SCHEDULE_ID, CREATE_TIMESTAMP, PAYER, EXECUTE_TIMESTAMP); // verify schedule signatures List<TransactionSignature> expectedTransactionList = new ArrayList<>(defaultSignatureList); expectedTransactionList.addAll(toTransactionSignatureList(SIGN_TIMESTAMP, SCHEDULE_ID, signatureMap)); assertTransactionSignatureInRepository(expectedTransactionList); // verify transaction assertTransactionInRepository(EXECUTE_TIMESTAMP, true, responseCodeEnum); } private Transaction scheduleCreateTransaction(AccountID payer) { return buildTransaction(builder -> { ScheduleCreateTransactionBody.Builder scheduleCreateBuilder = builder.getScheduleCreateBuilder(); scheduleCreateBuilder .setAdminKey(SCHEDULE_REF_KEY) .setMemo(SCHEDULE_CREATE_MEMO) .setScheduledTransactionBody(SCHEDULED_TRANSACTION_BODY); if (payer != null) { scheduleCreateBuilder.setPayerAccountID(payer); } else { scheduleCreateBuilder.clearPayerAccountID(); } }); } private Transaction scheduleDeleteTransaction(ScheduleID scheduleId) { return buildTransaction(builder -> builder.setScheduleDelete( ScheduleDeleteTransactionBody.newBuilder().setScheduleID(scheduleId))); } private Transaction scheduleSignTransaction(ScheduleID scheduleID, SignatureMap signatureMap) { return buildTransaction(builder -> builder.getScheduleSignBuilder().setScheduleID(scheduleID), signatureMap); } private Transaction scheduledTransaction() { return buildTransaction(builder -> builder.getCryptoTransferBuilder() .getTransfersBuilder() .addAccountAmounts(accountAmount(PAYER.getAccountNum(), 1000)) .addAccountAmounts(accountAmount(NODE.getAccountNum(), 2000))); } private SignatureMap getSigMap(int signatureCount, boolean isEd25519) { SignatureMap.Builder builder = SignatureMap.newBuilder(); String salt = RandomStringUtils.randomAlphabetic(5); for (int i = 0; i < signatureCount; i++) { SignaturePair.Builder signaturePairBuilder = SignaturePair.newBuilder(); signaturePairBuilder.setPubKeyPrefix(ByteString.copyFromUtf8("PubKeyPrefix-" + i + salt)); ByteString byteString = ByteString.copyFromUtf8("Ed25519-" + i + salt); if (isEd25519) { signaturePairBuilder.setEd25519(byteString); } else { signaturePairBuilder.setRSA3072(byteString); } builder.addSigPair(signaturePairBuilder.build()); } return builder.build(); } private TransactionRecord createTransactionRecord( long consensusTimestamp, ScheduleID scheduleID, TransactionBody transactionBody, ResponseCodeEnum responseCode, boolean scheduledTransaction) { var receipt = TransactionReceipt.newBuilder().setStatus(responseCode).setScheduleID(scheduleID); return buildTransactionRecord( recordBuilder -> { recordBuilder.setReceipt(receipt).setConsensusTimestamp(TestUtils.toTimestamp(consensusTimestamp)); if (scheduledTransaction) { recordBuilder.setScheduleRef(scheduleID); } recordBuilder.getReceiptBuilder().setAccountID(PAYER); }, transactionBody, responseCode.getNumber()); } private void insertScheduleCreateTransaction(long createdTimestamp, AccountID payer, ScheduleID scheduleID) { Transaction createTransaction = scheduleCreateTransaction(payer); TransactionBody createTransactionBody = getTransactionBody(createTransaction); var createTransactionRecord = createTransactionRecord(createdTimestamp, scheduleID, createTransactionBody, SUCCESS, false); var recordItem = RecordItem.builder() .transactionRecord(createTransactionRecord) .transaction(createTransaction) .build(); parseRecordItemAndCommit(recordItem); } private void insertScheduleDeleteTransaction(long timestamp, ScheduleID scheduleId) { var transaction = scheduleDeleteTransaction(scheduleId); var transactionBody = getTransactionBody(transaction); var transactionRecord = createTransactionRecord(timestamp, scheduleId, transactionBody, SUCCESS, false); parseRecordItemAndCommit(RecordItem.builder() .transactionRecord(transactionRecord) .transaction(transaction) .build()); } private void insertScheduleSign(long signTimestamp, SignatureMap signatureMap, ScheduleID scheduleID) { Transaction signTransaction = scheduleSignTransaction(scheduleID, signatureMap); TransactionBody signTransactionBody = getTransactionBody(signTransaction); var signTransactionRecord = createTransactionRecord(signTimestamp, scheduleID, signTransactionBody, SUCCESS, false); var recordItem = RecordItem.builder() .transaction(signTransaction) .transactionRecord(signTransactionRecord) .build(); parseRecordItemAndCommit(recordItem); } private void insertScheduledTransaction( long signTimestamp, ScheduleID scheduleID, ResponseCodeEnum responseCodeEnum) { var transaction = scheduledTransaction(); var transactionBody = getTransactionBody(transaction); var record = createTransactionRecord(signTimestamp, scheduleID, transactionBody, responseCodeEnum, true); var recordItem = RecordItem.builder() .transactionRecord(record) .transaction(transaction) .build(); parseRecordItemAndCommit(recordItem); } private void assertScheduleInRepository( ScheduleID scheduleID, long createdTimestamp, AccountID payer, Long executedTimestamp) { Long scheduleEntityId = EntityId.of(scheduleID).getId(); assertThat(scheduleRepository.findById(scheduleEntityId)) .get() .returns(createdTimestamp, from(Schedule::getConsensusTimestamp)) .returns(executedTimestamp, from(Schedule::getExecutedTimestamp)) .returns(scheduleEntityId, from(Schedule::getScheduleId)) .returns(EntityId.of(PAYER), from(Schedule::getCreatorAccountId)) .returns(EntityId.of(payer), from(Schedule::getPayerAccountId)) .returns(SCHEDULED_TRANSACTION_BODY.toByteArray(), from(Schedule::getTransactionBody)); } private void assertTransactionSignatureInRepository(List<TransactionSignature> expected) { assertThat(transactionSignatureRepository.findAll()).isNotNull().hasSameElementsAs(expected); } private void assertTransactionInRepository( long consensusTimestamp, boolean scheduled, ResponseCodeEnum responseCode) { assertThat(transactionRepository.findById(consensusTimestamp)) .get() .returns(scheduled, from(com.hedera.mirror.common.domain.transaction.Transaction::isScheduled)) .returns( responseCode.getNumber(), from(com.hedera.mirror.common.domain.transaction.Transaction::getResult)); } private List<TransactionSignature> toTransactionSignatureList( long timestamp, ScheduleID scheduleId, SignatureMap signatureMap) { return signatureMap.getSigPairList().stream() .map(pair -> { TransactionSignature transactionSignature = new TransactionSignature(); transactionSignature.setConsensusTimestamp(timestamp); transactionSignature.setEntityId(EntityId.of(scheduleId)); transactionSignature.setPublicKeyPrefix( pair.getPubKeyPrefix().toByteArray()); transactionSignature.setSignature(pair.getEd25519().toByteArray()); transactionSignature.setType(SignaturePair.SignatureCase.ED25519.getNumber()); return transactionSignature; }) .collect(Collectors.toUnmodifiableList()); } }
package com.tt.miniapp.media; import com.tt.miniapp.media.base.MediaEditor; import com.tt.miniapp.media.impl.MediaEditImpl; public class ImplInjector { public static MediaEditor getMediaEditImpl() { return (MediaEditor)new MediaEditImpl(); } } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\media\ImplInjector.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package org.mge.general; import java.util.HashMap; public class KLengthMaNumber { public static void main(String[] args) { HashMap<String, Integer> map = new HashMap<String, Integer>(); map.put(null, 1); } }
package com.tomy.rest.store.logic; import com.tomy.rest.entity.User; import com.tomy.rest.store.UserStore; import org.springframework.stereotype.Repository; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @Repository public class UserStoreLogic implements UserStore { private Map<String, User> userMap; public UserStoreLogic(){ this.userMap = new HashMap<>(); } @Override public String create(User newUser) { this.userMap.put(newUser.getId(), newUser); return newUser.getId(); } @Override public void update(User newUser) { this.userMap.put(newUser.getId(), newUser); } @Override public void delete(String id) { this.userMap.remove(id); } @Override public User retrieve(String id) { return this.userMap.get(id); } @Override public List<User> retrieveAll() { return this.userMap.values().stream().collect(Collectors.toList()); } }
package com.smxknife.java2.thread.waitnotify; /** * @author smxknife * 2019/9/24 */ public class _Run_wait_notify { public static void main(String[] args) { Obj obj = new Obj(); new Thread(() -> obj.doWait(), "th-1").start(); new Thread(() -> obj.doNotify(), "th-2").start(); System.out.println("从输出日志来看,th-1先执行获得对象锁,执行doWait方法,这样th-2就排队等待对象锁而无法进入doNotify方法,\r\n" + "th-1在sleep的2秒内,th-2依然无法获得对象锁,但是当th-1执行wait()之后,th-2可以进入doNotify方法,th-1也没有退出doWait方法,\r\n" + "说明th-1暂时让出了对象锁,th-2可以继续执行了。当th-2调用notify方法之后,th-1可以执行了,但是由于对象锁被th-2持有\r\n," + "th-1就必须等待th-2执行完毕后才能继续执行"); } }
package com.tencent.mm.plugin.fts.ui; import android.view.View; import com.tencent.mm.plugin.fts.a.d.a.a; import com.tencent.mm.plugin.fts.a.d.e; import com.tencent.mm.plugin.fts.a.d.e.b; import com.tencent.mm.sdk.platformtools.ag; import java.util.HashSet; public final class l extends d implements b { private ag giD = new ag(); private boolean jww; private com.tencent.mm.plugin.fts.ui.d.l jxr; public l(e eVar, String str, int i) { super(eVar); this.jxr = new com.tencent.mm.plugin.fts.ui.d.l(eVar.getContext(), this, i); this.jxr.jsp = str; } protected final a qh(int i) { a qh = this.jxr.qh(i); if (qh != null) { qh.pageType = 3; } return qh; } protected final void aQx() { this.jww = false; this.jxr.a(this.bWm, this.giD, new HashSet()); } protected final boolean a(View view, a aVar, boolean z) { boolean a = this.jxr.a(view, aVar, z); if (aVar.jts && !this.jww) { this.jww = true; k.c(this.bWm, true, this.jxr.aQw(), -2); } if (a) { clearCache(); setCount(this.jxr.qg(0)); notifyDataSetChanged(); J(getCount(), true); } return a; } public final void a(e eVar, String str) { setCount(eVar.qg(0)); notifyDataSetChanged(); J(getCount(), true); } public final void finish() { super.finish(); if (!this.jww) { this.jww = true; k.c(this.bWm, false, this.jxr.aQw(), -2); } } protected final int aQg() { return this.jxr.aQw(); } }
package com.diozero.api; /*- * #%L * Organisation: diozero * Project: diozero - Core * Filename: SerialDeviceInterface.java * * This file is part of the diozero project. More information about this project * can be found at https://www.diozero.com/. * %% * Copyright (C) 2016 - 2023 diozero * %% * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * #L% */ /** * <a href="https://en.wikipedia.org/wiki/Serial_port">Serial Port Interface</a> */ public interface SerialDeviceInterface extends DeviceInterface { /** * Read a single byte returning error responses * * @return Signed integer representation of the data read, including error * responses (values &lt; 0) * @throws RuntimeIOException if an I/O error occurs */ int read() throws RuntimeIOException; /** * Read a single byte, throw an exception if unable to read any data * * @return The data read * @throws RuntimeIOException if an I/O error occurs */ byte readByte() throws RuntimeIOException; /** * Write a single byte, throw an exception if unable to write the data * * @param bVal The data to write * @throws RuntimeIOException if an I/O error occurs */ void writeByte(byte bVal) throws RuntimeIOException; /** * Attempt to read buffer.length bytes into the specified buffer, returning the * number of bytes actually read; throw a RuntimeIOException if an I/O error * occurs * * @param buffer The buffer to read into, the length of this buffer specifies * the number of bytes to read * @return The number of bytes read * @throws RuntimeIOException if an I/O error occurs */ int read(byte[] buffer) throws RuntimeIOException; /** * Write the byte buffer to the device * * @param data The data to write * @throws RuntimeIOException if an I/O error occurs */ void write(byte... data) throws RuntimeIOException; /** * Get the number of bytes that are available to be read * * @return The number of bytes that are available to read * @throws RuntimeIOException if an I/O error occurs */ int bytesAvailable() throws RuntimeIOException; }
package com.myblog.version3.entity.Form; import javax.validation.constraints.NotBlank; import javax.validation.constraints.Pattern; import java.io.Serializable; public class Register implements Serializable { @NotBlank(message = "电话号码不能为空") @Pattern(regexp = "^1(3|4|5|7|8)\\d{9}$", message = "请输入正确的手机号") private String phone; @NotBlank(message = "用户名不能为空") @Pattern(regexp = "^[a-zA-Z\\u4e00-\\u9fa50-9_]{3,15}$",message = "用户名不符合格式") private String userName; @NotBlank(message = "密码不能为空") @Pattern(regexp = "[0-9a-zA-z_]{6,15}" ,message = "密码不符合规范") private String Rpassword; @NotBlank(message = "请输入确认密码") private String Lpassword; @NotBlank(message = "验证码不能为空") private String verification; public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getRpassword() { return Rpassword; } public void setRpassword(String rpassword) { Rpassword = rpassword; } public String getLpassword() { return Lpassword; } public void setLpassword(String lpassword) { Lpassword = lpassword; } public String getVerification() { return verification; } public void setVerification(String verification) { this.verification = verification; } }
// $Id: strcat.java2.java,v 1.4 2001/01/31 03:38:54 doug Exp $ // http://www.bagley.org/~doug/shootout/ package com.harris.mobihoc; import java.io.*; import java.util.*; public class strcat implements Runnable{ private boolean contin = false; private int n = 10; public strcat(boolean contin, int n){ this.contin = contin; this.n = n; } @Override public void run(){ //int n = Integer.parseInt(args[0]); StringBuffer str = new StringBuffer(); for (int i=0; i<n; i++) { str.append("hello\n"); } System.out.println(str.length()); /* if(contin){ try{ Thread trial = new Thread(new wc(contin, n)); trial.start(); }catch(Exception e){ e.printStackTrace(); } } if(contin){ try{ Thread trial = new Thread(new sumcol(contin, n)); trial.start(); }catch(Exception e){ e.printStackTrace(); } } */ } }
interface X{ void foo(); } interface Z extends X{ void hoge(); } abstract class A implements Z{ public void foo(){ hoge(); } } class B extends A{ public void foo(){ System.out.println("A"); } public void hoge(){ System.out.println("B"); } } class Test{ public static void main(Sttring[] args){ X b = new B(); b.foo(); } }
import java.util.*; import java.io.*; public class cf496d{ public static void main(String [] args) throws IOException{ InputReader in = new InputReader("cf496d.in"); String s = in.next(); int [][] arr = new int[s.length() + 1][3]; for(int i = 0; i < s.length(); i++){ int num = s.charAt(i) - 48; int modded = (arr[i][1] + 2 * arr[i][2]) % 3; arr[i + 1][0] += arr[i][0]; if(num % 3 == 0){ arr[i + 1][0]++; continue; } else{ if((modded + num) % 3 == 0) arr[i + 1][0]++; else if(arr[i][3 - num % 3] > 0) arr[i + 1][0]++; else{ if(modded != 0) arr[i + 1][modded]++; arr[i + 1][num % 3]++; } } } System.out.println(arr[s.length()][0]); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(String s) { try{ reader = new BufferedReader(new FileReader(s), 32768); } catch (Exception e){ reader = new BufferedReader(new InputStreamReader(System.in), 32768); } tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
import java.util.*; import java.math.*; public class Main{ public static void main(String[] args){ Scanner lec = new Scanner(System.in); BigInteger aa = new BigInteger("100000000"); System.out.println("entro"); while(true){ System.out.println(aa); if(aa.isProbablePrime(10)){ System.out.println(aa); break; } aa = aa.add(BigInteger.ONE); } System.out.println("termino"); } }
package com.jiw.dudu; import com.jiw.dudu.design.optimization.*; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; /** * @Description ColaStrategyTest * @Author pangh * @Date 2023年07月13日 * @Version v1.0.0 */ @SpringBootTest(classes = {DuduApplication.class}) @RunWith(SpringRunner.class) public class ColaStrategyTest { @Test public void v3(){ PepsiCola colaHandler = (PepsiCola) ShareColaFactory.getColaStrategy(ColaTypeEnum.PEPSI_COLA); System.out.println(colaHandler.pepsiMethod(ColaTypeEnum.PEPSI_COLA.getDesc())); } }
package com.smartwerkz.bytecode; import static org.junit.Assert.*; import java.lang.reflect.Modifier; import javassist.ClassPool; import javassist.CtClass; import javassist.CtNewMethod; import org.junit.Test; import com.smartwerkz.bytecode.controlflow.FrameExit; import com.smartwerkz.bytecode.primitives.JavaObject; import com.smartwerkz.bytecode.vm.ByteArrayResourceLoader; import com.smartwerkz.bytecode.vm.Classpath; import com.smartwerkz.bytecode.vm.HostVMResourceLoader; import com.smartwerkz.bytecode.vm.VirtualMachine; public class ReflectionTest { @Test public void testReturnString() throws Exception { ClassPool cp = new ClassPool(true); CtClass cc = cp.makeClass("org.example.Test"); StringBuilder src = new StringBuilder(); src.append("public static boolean test() {"); src.append(" java.lang.Class paramClass1 = java.lang.ClassLoader.getSystemClassLoader().loadClass(\"sun.nio.cs.FastCharsetProvider\");"); src.append(" java.lang.Class paramClass2 = java.lang.ClassLoader.getSystemClassLoader().loadClass(\"sun.nio.cs.UTF_8\");"); src.append(" int modifiers = paramClass2.getModifiers();"); src.append(" return sun.reflect.Reflection.verifyMemberAccess(paramClass1, paramClass2, null, modifiers);"); src.append("}"); cc.addMethod(CtNewMethod.make(src.toString(), cc)); byte[] b = cc.toBytecode(); VirtualMachine vm = new VirtualMachine(); Classpath classpath = new Classpath(); classpath.addLoader(new ByteArrayResourceLoader(b)); classpath.addLoader(new HostVMResourceLoader()); vm.setClasspath(classpath); vm.start(); vm.initSunJDK(); FrameExit result = vm.execute("org/example/Test", "test", new JavaObject[0]); String asStringValue = result.getResult().asStringValue(); assertEquals("true", asStringValue); } @Test public void testReflectionInOracleJVM() throws Exception { Class paramClass1 = java.lang.ClassLoader.getSystemClassLoader().loadClass("sun.nio.cs.FastCharsetProvider"); Class paramClass2 = java.lang.ClassLoader.getSystemClassLoader().loadClass("sun.nio.cs.UTF_8"); Object paramObject = null; int paramClass2Modifiers = paramClass2.getModifiers(); boolean result = verifyMemberAccess(paramClass1, paramClass2, paramObject, paramClass2Modifiers); assertTrue(result); } private static int getClassAccessFlags(Class paramClass) { return paramClass.getModifiers(); } public static boolean verifyMemberAccess(Class paramClass1, Class paramClass2, Object paramObject, int paramInt) { int i = 0; boolean bool = false; if (paramClass1 == paramClass2) { return true; } if (!(Modifier.isPublic(getClassAccessFlags(paramClass2)))) { bool = isSameClassPackage(paramClass1, paramClass2); i = 1; if (!(bool)) { return false; } } if (Modifier.isPublic(paramInt)) { return true; } int j = 0; if ((Modifier.isProtected(paramInt)) && (isSubclassOf(paramClass1, paramClass2))) { j = 1; } if ((j == 0) && (!(Modifier.isPrivate(paramInt)))) { if (i == 0) { bool = isSameClassPackage(paramClass1, paramClass2); i = 1; } if (bool) { j = 1; } } if (j == 0) { return false; } if (Modifier.isProtected(paramInt)) { Class localClass = (paramObject == null) ? paramClass2 : paramObject.getClass(); if (localClass != paramClass1) { if (i == 0) { bool = isSameClassPackage(paramClass1, paramClass2); i = 1; } if ((!(bool)) && (!(isSubclassOf(localClass, paramClass1)))) { return false; } } } return true; } private static boolean isSameClassPackage(Class paramClass1, Class paramClass2) { return isSameClassPackage(paramClass1.getClassLoader(), paramClass1.getName(), paramClass2.getClassLoader(), paramClass2.getName()); } static boolean isSubclassOf(Class paramClass1, Class paramClass2) { while (paramClass1 != null) { if (paramClass1 == paramClass2) { return true; } paramClass1 = paramClass1.getSuperclass(); } return false; } private static boolean isSameClassPackage(ClassLoader paramClassLoader1, String paramString1, ClassLoader paramClassLoader2, String paramString2) { if (paramClassLoader1 != paramClassLoader2) { return false; } int i = paramString1.lastIndexOf(46); int j = paramString2.lastIndexOf(46); if ((i == -1) || (j == -1)) { return (i == j); } int k = 0; int l = 0; if (paramString1.charAt(k) == '[') { do ++k; while (paramString1.charAt(k) == '['); if (paramString1.charAt(k) != 'L') { throw new InternalError("Illegal class name " + paramString1); } } if (paramString2.charAt(l) == '[') { do ++l; while (paramString2.charAt(l) == '['); if (paramString2.charAt(l) != 'L') { throw new InternalError("Illegal class name " + paramString2); } } int i1 = i - k; int i2 = j - l; if (i1 != i2) { return false; } return paramString1.regionMatches(false, k, paramString2, l, i1); } }
package io.cobrowse.reactnative; import android.view.View; import com.facebook.react.uimanager.ThemedReactContext; import com.facebook.react.uimanager.ViewGroupManager; import java.util.WeakHashMap; import androidx.annotation.NonNull; public class RedactedViewManager extends ViewGroupManager<RedactedView> { static WeakHashMap<View, String> redactedViews = new WeakHashMap<>(); @Override @NonNull public String getName() { return "CBIOCobrowseRedacted"; } @NonNull @Override protected RedactedView createViewInstance(@NonNull ThemedReactContext reactContext) { RedactedView view = new RedactedView(reactContext); redactedViews.put(view, null); return view; } @Override public void onDropViewInstance(@NonNull RedactedView view) { super.onDropViewInstance(view); redactedViews.remove(view); } }
package com.hs.doubaobao.bean; /** * Created by zht on 2016/11/17. */ public class PhotoInfo { public String url; public int w; public int h; }