text
stringlengths
10
2.72M
/** * */ package com.isg.iloan.controller.functions.dataEntry; import java.util.Collection; import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.util.GenericForwardComposer; import org.zkoss.zul.Checkbox; import org.zkoss.zul.Groupbox; import org.zkoss.zul.Textbox; import com.isg.iloan.commons.IDs; /** * @author augusto.marte * */ public class SaveAndSwipeViewCtrl extends GenericForwardComposer { private Checkbox pledgeNo; private Checkbox pledgeYes; private Textbox deposiorBranchOpened_txtbox; private Textbox deposiorAccntNum_txtbox; private Groupbox depositor_grpbox; private Checkbox metrobankDepositorNo; private Checkbox metrobankDepositorYes; /** * * */ @Override public void doAfterCompose(Component comp) throws Exception { super.doAfterCompose(comp); // TODO Auto-generated method stub //---initial values ---------- metrobankDepositorNo.setChecked(true); metrobankDepositorYes.setChecked(false); pledgeNo.setChecked(true); pledgeYes.setChecked(false); } public void onCheck$metrobankDepositorYes(){ depositor_grpbox.setVisible(metrobankDepositorYes.isChecked()); metrobankDepositorNo.setChecked(!metrobankDepositorYes.isChecked()); } public void onCheck$metrobankDepositorNo(){ depositor_grpbox.setVisible(!metrobankDepositorNo.isChecked()); metrobankDepositorYes.setChecked(!metrobankDepositorNo.isChecked()); } public void onCheck$pledgeYes(){ pledgeNo.setChecked(!pledgeYes.isChecked()); Collection<Component> comps = this.getPage().getDesktop().getComponents(); for(Component comp:comps){ if(IDs.DOA_WINDOW.equals(comp.getId())){ // Collection<Component> fellows = comp.getFellows(); // for(Component fellow:fellows){ // if(IDs.DOA_PLEDGE_DIV.equals(fellow.getId())){ // fellow.setVisible(pledgeYes.isChecked()); // break; // } // } comp.getFellow(IDs.DOA_PLEDGE_DIV).setVisible(pledgeYes.isChecked()); break; } } } public void onCheck$pledgeNo(){ pledgeYes.setChecked(!pledgeNo.isChecked()); Collection<Component> comps = this.getPage().getDesktop().getComponents(); for(Component comp:comps){ if(IDs.DOA_WINDOW.equals(comp.getId())){ // Collection<Component> fellows = comp.getFellows(); // for(Component fellow:fellows){ // if(IDs.DOA_PLEDGE_DIV.equals(fellow.getId())){ // fellow.setVisible(!pledgeNo.isChecked()); // break; // } // } comp.getFellow(IDs.DOA_PLEDGE_DIV).setVisible(!pledgeNo.isChecked()); break; } } } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.helmidev.entities; import java.io.Serializable; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; /** * * @author Helmi Omrane */ @Entity @Table(name = "tbl_customer") public class Customer implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @NotNull(message = "Vorname kann nicht NULL sein") @Size(min = 2, max = 55, message = "Vorname darf nicht kürzer als 2 zeichen oder länger als 55 Zeichen sein") @Column(name = "customer_First_Name") private String first_name; @Size(min = 2, max = 55, message = "Nachname darf nicht kürzer als 2 zeichen oder länger als 55 Zeichen sein") @NotNull(message = "Nachname kann nicht NULL sein ") @Column(name = "customer_Last_Name") private String last_name; @NotNull(message = "Email Adresse kann nicht NULL sein") @Pattern(regexp = "(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])", message = "Bitte geben Sie eine gültige Email Adresse") @Column(name = "customer_Email", unique = true) private String email; @Column(name = "customer_Account") private double account; @OneToMany(mappedBy = "Customer",fetch = FetchType.EAGER) private List<Shopping> listOfShopping; @OneToMany(mappedBy = "Customer",fetch = FetchType.EAGER) private List<Billing> listOfBilling; public List<Shopping> getListOfShopping() { return listOfShopping; } public void setListOfShopping(List<Shopping> listOfShopping) { this.listOfShopping = listOfShopping; } public List<Billing> getListOfBilling() { return listOfBilling; } public void setListOfBilling(List<Billing> listOfBilling) { this.listOfBilling = listOfBilling; } public String getFirst_name() { return first_name; } public void setFirst_name(String first_name) { this.first_name = first_name; } public String getLast_name() { return last_name; } public void setLast_name(String last_name) { this.last_name = last_name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public double getAccount() { return account; } public void setAccount(double account) { this.account = account; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Customer)) { return false; } Customer other = (Customer) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } public String getFullName(){ return first_name +" "+last_name; } @Override public String toString() { return "Model.Entities.Customer[ id=" + id + " ]"; } }
package bis.project.controllers; import java.util.Set; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import bis.project.model.Currency; import bis.project.model.DailyAccountBalance; import bis.project.services.CredentialsServices; import bis.project.services.CurrencyServices; import bis.project.services.DailyAccountBalanceServices; import bis.project.validators.CurrencyValidator; import bis.project.validators.ValidationException; @RestController public class DailyAccountBalanceController { @Autowired private DailyAccountBalanceServices dabServices; @Autowired private CredentialsServices services; @RequestMapping(value = "/api/dailyAccountBalances", method = RequestMethod.GET) public Set<DailyAccountBalance> getAllDailyAccountBalances(@RequestHeader(value="BankId") Integer bankId) { Set<DailyAccountBalance> dds = dabServices.getAllDailyAccountBalances(); if(bankId != null){ dds = dds.stream().filter(x -> x.getAccount().getBank().getId().equals(bankId)).collect(Collectors.toSet()); } return dds; } @RequestMapping(value = "/api/dailyAccountBalances/{id}", method = RequestMethod.GET) public ResponseEntity<DailyAccountBalance> getDailyAccountBalance(@PathVariable("id") Integer id) { DailyAccountBalance ddd = dabServices.getDailyAccountBalance(id); if(ddd != null) { return new ResponseEntity<DailyAccountBalance>(ddd, HttpStatus.OK); } return new ResponseEntity<DailyAccountBalance>(HttpStatus.NOT_FOUND); } }
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.identity.captcha.connector; import org.wso2.carbon.identity.captcha.exception.CaptchaException; import org.wso2.carbon.identity.governance.IdentityGovernanceService; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; /** * Captcha Connector. */ public interface CaptchaConnector { void init(IdentityGovernanceService identityGovernanceService); int getPriority(); boolean canHandle(ServletRequest servletRequest, ServletResponse servletResponse) throws CaptchaException; CaptchaPreValidationResponse preValidate(ServletRequest servletRequest, ServletResponse servletResponse) throws CaptchaException; boolean verifyCaptcha(ServletRequest servletRequest, ServletResponse servletResponse) throws CaptchaException; CaptchaPostValidationResponse postValidate(ServletRequest servletRequest, ServletResponse servletResponse) throws CaptchaException; }
package com.cninnovatel.ev.contact; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import android.annotation.TargetApi; import android.content.Context; import android.os.Build; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.cninnovatel.ev.App; import com.cninnovatel.ev.R; import com.cninnovatel.ev.api.ApiClient; import com.cninnovatel.ev.api.model.RestContact; import com.cninnovatel.ev.api.model.RestContactReq; import com.cninnovatel.ev.type.User; import com.cninnovatel.ev.utils.AvatarLoader; import com.cninnovatel.ev.utils.NetworkUtil; import com.cninnovatel.ev.utils.Utils; @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public class SystemUserAdapter extends ArrayAdapter<User> { private int resource; private List<User> users; private List<Integer> userIds = new ArrayList<Integer>(); private static Logger log = Logger.getLogger(SystemUserAdapter.class); public SystemUserAdapter(Context context, int textViewResourceId, List<User> objects, List<Integer> ids) { super(context, textViewResourceId, objects); resource = textViewResourceId; users = objects; userIds = ids; } private class ViewHolder { public ImageView avatar; public TextView display_name; public LinearLayout add; public LinearLayout added; } @Override public View getView(int position, View convertView, ViewGroup parent) { final User user = users.get(position); ViewHolder holder = null; if (convertView == null) { holder = new ViewHolder(); convertView = LayoutInflater.from(getContext()).inflate(resource, null); holder.avatar = (ImageView) convertView.findViewById(R.id.avatar); holder.display_name = (TextView) convertView.findViewById(R.id.display_name); holder.add = (LinearLayout) convertView.findViewById(R.id.add); holder.added = (LinearLayout) convertView.findViewById(R.id.added); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } AvatarLoader.load(user.getImageUrl(), holder.avatar); if (StringUtils.isNotEmpty(user.getDisplayName())) { holder.display_name.setText(user.getDisplayName()); } else { holder.display_name.setText(user.getUserName()); } if (userIds.contains(user.getId())) { holder.add.setVisibility(View.GONE); holder.added.setVisibility(View.VISIBLE); } else { holder.add.setVisibility(View.VISIBLE); holder.add.setBackgroundResource(R.drawable.btn_add); holder.add.setClickable(true); holder.added.setVisibility(View.GONE); } holder.add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!NetworkUtil.isNetConnected(App.getContext())) { Utils.showToast(App.getContext(), R.string.server_unavailable); return; } RestContactReq restContactReq = new RestContactReq(); restContactReq.setUserId(user.getId()); v.setBackgroundResource(R.drawable.btn_gray); v.setClickable(false); ApiClient.addContact(restContactReq, new Callback<RestContact>() { @Override public void onResponse(Call<RestContact> call, Response<RestContact> response) { if (response.isSuccessful()) { if (userIds == null) { userIds = new ArrayList<Integer>(); } userIds.add(user.getId()); notifyDataSetChanged(); } else { log.error("add contact failure!"); Utils.showToast(App.getContext(), R.string.action_fail); } } @Override public void onFailure(Call<RestContact> call, Throwable e) { } }); } }); return convertView; } }
package com.ctt.web.filter; import org.springframework.stereotype.Component; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import java.io.IOException; /** * @Description * @auther Administrator * @create 2020-03-25 上午 11:14 */ @Component public class AuthFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest re = (HttpServletRequest) servletRequest; String token = re.getHeader("token"); filterChain.doFilter(servletRequest,servletResponse); } @Override public void destroy() { } }
package com.example.register; public class User { String name; String email; String phone; public User(String name, String email, String phone) { this.name = name; this.email = email; this.phone = phone; } static User[] users = new User[]{}; }
/* * Created Thu Dec 02 15:54:49 CST 2004 by MyEclipse Hibernate Tool. */ package com.aof.component.helpdesk; import java.io.Serializable; /** * A class that represents a row in the 'Call_Type' table. * This class may be customized as it is never re-generated * after being created. */ public class CallType extends AbstractCallType implements Serializable { /** * Simple constructor of CallType instances. */ public CallType() { } /** * Constructor of CallType instances given a simple primary key. * @param type */ public CallType(java.lang.String type) { super(type); } /* Add customized code below */ }
package ui; import java.util.Arrays; import java.util.List; import javax.swing.JOptionPane; import domain.*; public class QuizTestApp { public static void main(String[] args) { // maak een quiz met een aantal randomvragen uit de opdrachtendatabase String aantalVragen = JOptionPane.showInputDialog(null,"typ aantal gewenste vragen voor de quiz","Maak een quiz",JOptionPane.QUESTION_MESSAGE); Quiz quiz = new Quiz(Integer.parseInt(aantalVragen)); // toon de aangemaakte quiz JOptionPane.showMessageDialog(null, quiz, "Dit is de quiz",JOptionPane.INFORMATION_MESSAGE); // geef de namen van de deelnemers aan de test String deelnemers = JOptionPane.showInputDialog(null,"typ namen van de deelnemers gescheiden door een komma","Maak een deelnemer groep",JOptionPane.QUESTION_MESSAGE); List <String> deelnemerLijst = Arrays.asList(deelnemers.split(",")); // maak een deelnemergroep DeelnemerGroep groep = new DeelnemerGroep(deelnemerLijst); //maak een test Test test = new Test(groep,quiz); //start test //alle deelnemers beantwoorden vraag 1, vervolgens beurteling vraag 2, ... while (!test.isVoorbij()){ String vraagAanBeurt = test.getVolgendeVraag(); //Elke deelnemer beantwoord de vraag die aan de beurt is for (int i = 0; i < test.getAantalDeelnemers();i++){ String deelnemerAanBeurt = test.getDeelnemerAanBeurt(); //System.out.println(test.getDeelnemerAanBeurt()); String antwoord = JOptionPane.showInputDialog(null,vraagAanBeurt,"Typ antwoord voor deelnemer "+deelnemerAanBeurt ,JOptionPane.QUESTION_MESSAGE); //het antwoord van de speler aan beurt wordt geregistreerd test.speel(antwoord); } } //de resultaten van de test worden getoond per deelnemer en per vraag JOptionPane.showMessageDialog(null, test.getScoresDeelnemers(), "Overzicht van de scores per deelnemer/vraag",JOptionPane.INFORMATION_MESSAGE); //de winnaar(s) van de test worden getoond JOptionPane.showMessageDialog(null, test.getWinnaars(), "Overzicht van de winnaar(s) van de test",JOptionPane.INFORMATION_MESSAGE); //de totale score per deelnemer wordt getoond, geordend van de deelnemer met de hoogste score naar de deelnemer met de laagste score JOptionPane.showMessageDialog(null, groep.getPuntenOverzicht(), "Overzicht van de totale score per deelnemer",JOptionPane.INFORMATION_MESSAGE); } }
package io.swagger.server.api.verticle; import io.vertx.core.AbstractVerticle; import io.vertx.core.json.Json; import io.vertx.core.json.JsonObject; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import io.swagger.server.api.model.Pet; import io.swagger.server.api.model.ModelApiResponse; import java.io.File; import java.util.List; import java.util.Map; public class PetApiVerticle extends AbstractVerticle { final static Logger LOGGER = LoggerFactory.getLogger(PetApiVerticle.class); final static String POST_PET_SERVICE_ID = "POST_pet"; final static String DELETE_PET_PETID_SERVICE_ID = "DELETE_pet_petId"; final static String GET_PET_FINDBYSTATUS_SERVICE_ID = "GET_pet_findByStatus"; final static String GET_PET_FINDBYTAGS_SERVICE_ID = "GET_pet_findByTags"; final static String GET_PET_PETID_SERVICE_ID = "GET_pet_petId"; final static String PUT_PET_SERVICE_ID = "PUT_pet"; final static String POST_PET_PETID_SERVICE_ID = "POST_pet_petId"; final static String POST_PET_PETID_UPLOADIMAGE_SERVICE_ID = "POST_pet_petId_uploadImage"; //TODO : create Implementation PetApi service = new PetApiImpl(); @Override public void start() throws Exception { //Consumer for POST_pet vertx.eventBus().<JsonObject> consumer(POST_PET_SERVICE_ID).handler(message -> { try { Pet body = Json.mapper.readValue(message.body().getJsonObject("body").encode(), Pet.class); //TODO: call implementation service.addPet(body); message.reply(null); } catch (Exception e) { //TODO : replace magic number (101) message.fail(101, e.getLocalizedMessage()); } }); //Consumer for DELETE_pet_petId vertx.eventBus().<JsonObject> consumer(DELETE_PET_PETID_SERVICE_ID).handler(message -> { try { Long petId = Json.mapper.readValue(message.body().getJsonObject("petId").encode(), Long.class); String apiKey = Json.mapper.readValue(message.body().getJsonObject("apiKey").encode(), String.class); //TODO: call implementation service.deletePet(petId, apiKey); message.reply(null); } catch (Exception e) { //TODO : replace magic number (101) message.fail(101, e.getLocalizedMessage()); } }); //Consumer for GET_pet_findByStatus vertx.eventBus().<JsonObject> consumer(GET_PET_FINDBYSTATUS_SERVICE_ID).handler(message -> { try { List<String> status = Json.mapper.readValue(message.body().getJsonArray("status").encode(), Json.mapper.getTypeFactory().constructCollectionType(List.class, String.class)); //TODO: call implementation List<Pet> result = service.findPetsByStatus(status); message.reply(new JsonObject(Json.encode(result))); } catch (Exception e) { //TODO : replace magic number (101) message.fail(101, e.getLocalizedMessage()); } }); //Consumer for GET_pet_findByTags vertx.eventBus().<JsonObject> consumer(GET_PET_FINDBYTAGS_SERVICE_ID).handler(message -> { try { List<String> tags = Json.mapper.readValue(message.body().getJsonArray("tags").encode(), Json.mapper.getTypeFactory().constructCollectionType(List.class, String.class)); //TODO: call implementation List<Pet> result = service.findPetsByTags(tags); message.reply(new JsonObject(Json.encode(result))); } catch (Exception e) { //TODO : replace magic number (101) message.fail(101, e.getLocalizedMessage()); } }); //Consumer for GET_pet_petId vertx.eventBus().<JsonObject> consumer(GET_PET_PETID_SERVICE_ID).handler(message -> { try { Long petId = Json.mapper.readValue(message.body().getJsonObject("petId").encode(), Long.class); //TODO: call implementation Pet result = service.getPetById(petId); message.reply(new JsonObject(Json.encode(result))); } catch (Exception e) { //TODO : replace magic number (101) message.fail(101, e.getLocalizedMessage()); } }); //Consumer for PUT_pet vertx.eventBus().<JsonObject> consumer(PUT_PET_SERVICE_ID).handler(message -> { try { Pet body = Json.mapper.readValue(message.body().getJsonObject("body").encode(), Pet.class); //TODO: call implementation service.updatePet(body); message.reply(null); } catch (Exception e) { //TODO : replace magic number (101) message.fail(101, e.getLocalizedMessage()); } }); //Consumer for POST_pet_petId vertx.eventBus().<JsonObject> consumer(POST_PET_PETID_SERVICE_ID).handler(message -> { try { Long petId = Json.mapper.readValue(message.body().getJsonObject("petId").encode(), Long.class); String name = Json.mapper.readValue(message.body().getJsonObject("name").encode(), String.class); String status = Json.mapper.readValue(message.body().getJsonObject("status").encode(), String.class); //TODO: call implementation service.updatePetWithForm(petId, name, status); message.reply(null); } catch (Exception e) { //TODO : replace magic number (101) message.fail(101, e.getLocalizedMessage()); } }); //Consumer for POST_pet_petId_uploadImage vertx.eventBus().<JsonObject> consumer(POST_PET_PETID_UPLOADIMAGE_SERVICE_ID).handler(message -> { try { Long petId = Json.mapper.readValue(message.body().getJsonObject("petId").encode(), Long.class); String additionalMetadata = Json.mapper.readValue(message.body().getJsonObject("additionalMetadata").encode(), String.class); File file = Json.mapper.readValue(message.body().getJsonObject("file").encode(), File.class); //TODO: call implementation ModelApiResponse result = service.uploadFile(petId, additionalMetadata, file); message.reply(new JsonObject(Json.encode(result))); } catch (Exception e) { //TODO : replace magic number (101) message.fail(101, e.getLocalizedMessage()); } }); } }
package com.flowedu.dto; import lombok.Data; /** * Created by jihoan on 2017. 8. 11.. */ @Data public class LectureStudentRelDto { // 아이디 private Long lectureRelId; // 강의 정보 아이디 private Long lectureId; // 학생 아이디 private Long studentId; // 생성일 private String createDate; private boolean addYn; private String studentName; private String schoolName; private Integer paymentPrice; private boolean paymentYn; private String paymentDate; public LectureStudentRelDto() {} public LectureStudentRelDto(Long lectureId, Long studentId) { this.lectureId = lectureId; this.studentId = studentId; } }
/* * Created by Angel Leon (@gubatron), Alden Torres (aldenml) * Copyright (c) 2011-2014, FrostWire(R). All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.limegroup.gnutella.gui.search; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Font; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.HashMap; import java.util.Map; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JTable; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableCellRenderer; import com.frostwire.gui.theme.ThemeMediator; import com.frostwire.uxstats.UXAction; import com.frostwire.uxstats.UXStats; import com.limegroup.gnutella.gui.GUIMediator; /** * * @author gubatron * @author aldenml * */ public class SourceRenderer extends DefaultTableCellRenderer implements TableCellRenderer { private static final Map<String, ImageIcon> sourceIcons = new HashMap<String, ImageIcon>(); static { try { sourceIcons.put("soundcloud", GUIMediator.getThemeImage("soundcloud_off")); sourceIcons.put("youtube", GUIMediator.getThemeImage("youtube_on")); sourceIcons.put("archive.org", GUIMediator.getThemeImage("archive_source")); sourceIcons.put("isohunt", GUIMediator.getThemeImage("isohunt_source")); sourceIcons.put("clearbits", GUIMediator.getThemeImage("clearbits_source")); sourceIcons.put("extratorrent", GUIMediator.getThemeImage("extratorrent_source")); sourceIcons.put("kat", GUIMediator.getThemeImage("kat_source")); sourceIcons.put("mininova", GUIMediator.getThemeImage("mininova_source")); sourceIcons.put("monova", GUIMediator.getThemeImage("monova_source")); sourceIcons.put("tpb", GUIMediator.getThemeImage("tpb_source")); sourceIcons.put("bitsnoop", GUIMediator.getThemeImage("bitsnoop_off")); sourceIcons.put("torlock", GUIMediator.getThemeImage("torlock_off")); sourceIcons.put("eztv", GUIMediator.getThemeImage("eztv_off")); sourceIcons.put("default", GUIMediator.getThemeImage("seeding_small")); } catch (Throwable e) { // just print it e.printStackTrace(); } } private SourceHolder sourceHolder; public SourceRenderer() { setCursor(new Cursor(Cursor.HAND_CURSOR)); initMouseListener(); } @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int columns) { setOpaque(true); setEnabled(true); if (isSelected) { setBackground(ThemeMediator.TABLE_SELECTED_BACKGROUND_ROW_COLOR); } else { setBackground(row % 2 == 1 ? ThemeMediator.TABLE_ALTERNATE_ROW_COLOR : Color.WHITE); } updateUI((SourceHolder) value, table, row); return super.getTableCellRendererComponent(table, getText(), isSelected, hasFocus, row, columns); } private void initMouseListener() { MouseAdapter mouseAdapter = new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (sourceHolder != null) { sourceHolder.getUISearchResult().showDetails(true); e.consume(); UXStats.instance().log(UXAction.SEARCH_RESULT_SOURCE_VIEW); } } }; addMouseListener(mouseAdapter); } private void updateUI(SourceHolder value, JTable table, int row) { sourceHolder = value; updateIcon(); updateLinkLabel(table); } private void updateIcon() { if (sourceHolder != null) { String sourceName = sourceHolder.getSourceName().toLowerCase(); if (sourceName.contains("-")) { sourceName = sourceName.substring(0, sourceName.indexOf("-")).trim(); } ImageIcon icon = sourceIcons.get(sourceName); if (icon != null) { setIcon(icon); } else { setIcon(sourceIcons.get("default")); } } } private void updateLinkLabel(JTable table) { if (sourceHolder != null) { setText(sourceHolder.getSourceNameHTML()); syncFont(table, this); } } private void syncFont(JTable table, JComponent c) { Font tableFont = table.getFont(); if (tableFont != null && !tableFont.equals(c.getFont())) { c.setFont(tableFont); } } }
package org.springframework.build.shadow; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import org.gradle.api.DefaultTask; import org.gradle.api.artifacts.Configuration; import org.gradle.api.artifacts.component.ModuleComponentSelector; import org.gradle.api.artifacts.query.ArtifactResolutionQuery; import org.gradle.api.artifacts.result.ArtifactResolutionResult; import org.gradle.api.artifacts.result.ComponentArtifactsResult; import org.gradle.api.artifacts.result.DependencyResult; import org.gradle.api.artifacts.result.ResolutionResult; import org.gradle.api.artifacts.result.ResolvedArtifactResult; import org.gradle.api.file.DirectoryProperty; import org.gradle.api.file.FileCopyDetails; import org.gradle.api.file.FileTree; import org.gradle.api.tasks.Classpath; import org.gradle.api.tasks.Input; import org.gradle.api.tasks.Nested; import org.gradle.api.tasks.Optional; import org.gradle.api.tasks.OutputDirectory; import org.gradle.api.tasks.TaskAction; import org.gradle.jvm.JvmLibrary; import org.gradle.language.base.artifact.SourcesArtifact; /** * Gradle task to add source from shadowed jars into our own source jars. * * @author Phillip Webb * @author Andy Wilkinson */ public class ShadowSource extends DefaultTask { private final DirectoryProperty outputDirectory = getProject().getObjects().directoryProperty(); private List<Configuration> configurations = new ArrayList<>(); private final List<Relocation> relocations = new ArrayList<>(); @Classpath @Optional public List<Configuration> getConfigurations() { return this.configurations; } public void setConfigurations(List<Configuration> configurations) { this.configurations = configurations; } @Nested public List<Relocation> getRelocations() { return this.relocations; } public void relocate(String pattern, String destination) { this.relocations.add(new Relocation(pattern, destination)); } @OutputDirectory DirectoryProperty getOutputDirectory() { return this.outputDirectory; } @TaskAction void syncSourceJarFiles() { sync(getSourceJarFiles()); } private List<File> getSourceJarFiles() { List<File> sourceJarFiles = new ArrayList<>(); for (Configuration configuration : this.configurations) { ResolutionResult resolutionResult = configuration.getIncoming().getResolutionResult(); resolutionResult.getRootComponent().get().getDependencies().forEach(dependency -> { Set<ComponentArtifactsResult> artifactsResults = resolveSourceArtifacts(dependency); for (ComponentArtifactsResult artifactResult : artifactsResults) { artifactResult.getArtifacts(SourcesArtifact.class).forEach(sourceArtifact -> { sourceJarFiles.add(((ResolvedArtifactResult) sourceArtifact).getFile()); }); } }); } return Collections.unmodifiableList(sourceJarFiles); } private Set<ComponentArtifactsResult> resolveSourceArtifacts(DependencyResult dependency) { ModuleComponentSelector componentSelector = (ModuleComponentSelector) dependency.getRequested(); ArtifactResolutionQuery query = getProject().getDependencies().createArtifactResolutionQuery() .forModule(componentSelector.getGroup(), componentSelector.getModule(), componentSelector.getVersion()); return executeQuery(query).getResolvedComponents(); } @SuppressWarnings("unchecked") private ArtifactResolutionResult executeQuery(ArtifactResolutionQuery query) { return query.withArtifacts(JvmLibrary.class, SourcesArtifact.class).execute(); } private void sync(List<File> sourceJarFiles) { getProject().sync(spec -> { spec.into(this.outputDirectory); spec.eachFile(this::relocateFile); spec.filter(this::transformContent); spec.exclude("META-INF/**"); spec.setIncludeEmptyDirs(false); sourceJarFiles.forEach(sourceJar -> spec.from(zipTree(sourceJar))); }); } private void relocateFile(FileCopyDetails details) { String path = details.getPath(); for (Relocation relocation : this.relocations) { path = relocation.relocatePath(path); } details.setPath(path); } private String transformContent(String content) { for (Relocation relocation : this.relocations) { content = relocation.transformContent(content); } return content; } private FileTree zipTree(File sourceJar) { return getProject().zipTree(sourceJar); } /** * A single relocation. */ static class Relocation { private final String pattern; private final String pathPattern; private final String destination; private final String pathDestination; Relocation(String pattern, String destination) { this.pattern = pattern; this.pathPattern = pattern.replace('.', '/'); this.destination = destination; this.pathDestination = destination.replace('.', '/'); } @Input public String getPattern() { return this.pattern; } @Input public String getDestination() { return this.destination; } String relocatePath(String path) { return path.replace(this.pathPattern, this.pathDestination); } public String transformContent(String content) { return content.replaceAll("\\b" + this.pattern, this.destination); } } }
package mobi.app.redis.netty.command; import mobi.app.redis.netty.reply.Reply; import mobi.app.redis.transcoders.Transcoder; import java.util.List; import java.util.concurrent.Future; /** * User: thor * Date: 12-12-20 * Time: 上午10:18 */ public interface Command<T> { List<byte[]> getArgs(); String getName(); void setTranscoder(Transcoder transcoder); Transcoder getTranscoder(); void setResult(Reply reply); // boolean decodeBySelf(); // T decode(Reply reply); Future<T> getReply(); }
package com.anz.demo.dto; import lombok.Builder; import lombok.Data; import lombok.Value; import java.math.BigDecimal; import java.time.LocalDate; @Builder @Data public class Transaction { private Long accountNumber; private String accountName; private LocalDate valueDate; private Currency currency; private BigDecimal debitAmount; private BigDecimal creditAmount; private CreditType debitCredit; private String transactionNarrative; }
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.util.*; public class Screen extends Actor implements IScreen { private int x, y; public static ArrayList<IScreen> screenTwoComponents=null; World pw =null; public Screen(int X, int Y) { this.x = X; this.y = Y; } public Screen(World w) { pw = w; screenTwoComponents = new ArrayList(); } public void act() {} public void addToWorld(){ Iterator<IScreen> screenIterator = screenTwoComponents.iterator(); while(screenIterator.hasNext()){ IScreen screen = screenIterator.next(); Actor actor = (Actor)screen; //System.out.println(" *** " + actor + " : " + screen.getXCoordinate() + " : " + screen.getYCoordinate()); pw.addObject(actor, screen.getXCoordinate(), screen.getYCoordinate()); } } public void AddComponents(IScreen screen){ screenTwoComponents.add(screen); //System.out.println("kal ArrayList :: " + screenTwoComponents.size() + " " + screenTwoComponents ); } public void RemoveComponents(IScreen screen){ pw.removeObject((Actor)screen); } public int getXCoordinate(){ return x; } public int getYCoordinate(){ return y; } }
package c01.todoteamname.project.SPORTCRED; import java.io.IOException; import org.json.JSONException; import org.json.JSONObject; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; public class SearchRadar implements HttpHandler { Neo4JDB nb = Neo4JDB.createInstanceOfDatabase(); public SearchRadar() {} @Override public void handle(HttpExchange r) { try { if (r.getRequestMethod().equals("POST")) { r.getResponseHeaders().add("Access-Control-Allow-Origin", "*"); handlePut(r); } } catch (Exception e) { try { r.sendResponseHeaders(500, -1); } catch (IOException e1) { } } } public void handlePut(HttpExchange r) throws IOException, JSONException { String body = Utils.convert(r.getRequestBody()); JSONObject deserialized = new JSONObject(body); String searchedUser; String username; if (deserialized.has("searchedUser") && deserialized.has("username")) { searchedUser = deserialized.getString("searchedUser"); username = deserialized.getString("username"); boolean ableToAdd = false; if (!(username.equals(searchedUser))) { ableToAdd = this.nb.searchRadar(r, username, searchedUser); if (ableToAdd) { r.sendResponseHeaders(200, -1); } else { r.sendResponseHeaders(201, -1); } } else { r.sendResponseHeaders(202, -1); } } else { r.sendResponseHeaders(400, -1); } } }
package com.example.reminiscence; import android.net.Uri; import androidx.lifecycle.LiveData; import androidx.room.Dao; import androidx.room.Delete; import androidx.room.Insert; import androidx.room.OnConflictStrategy; import androidx.room.Query; import androidx.room.Update; import java.net.URI; import java.util.List; @Dao public interface PhotoNameDao { @Insert void insert(PhotoName photoName); @Query("SELECT * FROM photo_table") LiveData<List<PhotoName>> getAllPhotos(); }
//OR Gate public class OR implements LogicOperation { public boolean logicOP(boolean A, boolean B){ return A|B; } }
package l6; import java.util.Arrays; public class AnyTypesArray { private Object[] ar; public AnyTypesArray() { ar = new Object[0]; } public void addObject(Object o) { ar = Arrays.copyOf(ar, ar.length + 1); ar[ar.length - 1] = o; } public Object getObject(int Index) { if (Index < ar.length && Index >= 0) return ar[Index]; else return null; } }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.reactive.function.client; import java.util.List; import java.util.function.Consumer; import org.springframework.http.codec.ClientCodecConfigurer; import org.springframework.http.codec.HttpMessageReader; import org.springframework.http.codec.HttpMessageWriter; /** * Default implementation of {@link ExchangeStrategies.Builder}. * * @author Arjen Poutsma * @author Brian Clozel * @since 5.0 */ final class DefaultExchangeStrategiesBuilder implements ExchangeStrategies.Builder { final static ExchangeStrategies DEFAULT_EXCHANGE_STRATEGIES; static { DefaultExchangeStrategiesBuilder builder = new DefaultExchangeStrategiesBuilder(); builder.defaultConfiguration(); DEFAULT_EXCHANGE_STRATEGIES = builder.build(); } private final ClientCodecConfigurer codecConfigurer; public DefaultExchangeStrategiesBuilder() { this.codecConfigurer = ClientCodecConfigurer.create(); this.codecConfigurer.registerDefaults(false); } private DefaultExchangeStrategiesBuilder(DefaultExchangeStrategies other) { this.codecConfigurer = other.codecConfigurer.clone(); } public void defaultConfiguration() { this.codecConfigurer.registerDefaults(true); } @Override public ExchangeStrategies.Builder codecs(Consumer<ClientCodecConfigurer> consumer) { consumer.accept(this.codecConfigurer); return this; } @Override public ExchangeStrategies build() { return new DefaultExchangeStrategies(this.codecConfigurer); } private static class DefaultExchangeStrategies implements ExchangeStrategies { private final ClientCodecConfigurer codecConfigurer; private final List<HttpMessageReader<?>> readers; private final List<HttpMessageWriter<?>> writers; public DefaultExchangeStrategies(ClientCodecConfigurer codecConfigurer) { this.codecConfigurer = codecConfigurer; this.readers = List.copyOf(this.codecConfigurer.getReaders()); this.writers = List.copyOf(this.codecConfigurer.getWriters()); } @Override public List<HttpMessageReader<?>> messageReaders() { return this.readers; } @Override public List<HttpMessageWriter<?>> messageWriters() { return this.writers; } @Override public Builder mutate() { return new DefaultExchangeStrategiesBuilder(this); } } }
package com.jfronny.raut.gui; import io.github.cottonmc.cotton.gui.client.CottonInventoryScreen; import net.minecraft.entity.player.PlayerEntity; public class BackpackScreen extends CottonInventoryScreen<BackpackController> { public BackpackScreen(BackpackController container, PlayerEntity player) { super(container, player); } }
package shopFind.model; import org.springframework.hateoas.ResourceSupport; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; /* * Class that maps ShopDetailsResponse */ @JsonInclude(Include.NON_NULL) public class ShopDetailsResponse extends ResourceSupport { private String shopName; private ShopAddress shopAddress; private double latitiude; private double longitude; private Response response; public Response getResponse() { return response; } public void setResponse(Response response) { this.response = response; } public String getShopName() { return shopName; } public void setShopName(String shopName) { this.shopName = shopName; } public ShopAddress getShopAddress() { return shopAddress; } public void setShopAddress(ShopAddress shopAddress) { this.shopAddress = shopAddress; } public double getLatitiude() { return latitiude; } public void setLatitiude(double d) { this.latitiude = d; } public double getLongitude() { return longitude; } public void setLongitude(double longitude) { this.longitude = longitude; } }
package utilities; import static constants.Constants.JS_AXIS_LEFT_STICK_X; import java.net.Inet4Address; import java.net.UnknownHostException; import drivetrain.DriveIO; import edu.wpi.first.wpilibj.PowerDistributionPanel; import edu.wpi.first.wpilibj.networktables.NetworkTable; public class RobotTable { //not currently in use private static NetworkTable table; public static void init() { table = NetworkTable.getTable("dashboard"); table.putString("Position", "default"); table.putString("Obstacle", "default"); table.putString("ShooterSetting", "default"); } public static void update() { RobotTable.getInstance().putNumber("getYaw", DriveIO.getInstance().getYaw()); RobotTable.getInstance().putNumber("getPitch", DriveIO.getInstance().getPitch()); RobotTable.getInstance().putNumber("getRoll", DriveIO.getInstance().getRoll()); } public static NetworkTable getInstance() { if(table == null) { init(); } return table; } public static String getAutonPosition(){ return table.getString("Position", ""); } public static String getAutonObstacle(){ return table.getString("Obstacle", ""); } public static String getAutonShooterSetting() { return table.getString("ShooterSetting", ""); } }
package com.justcode.hxl.viewutil.recycleview_util.layoutmanager.chipslayoutmanager.gravity; import android.graphics.Rect; import com.justcode.hxl.viewutil.recycleview_util.layoutmanager.chipslayoutmanager.layouter.AbstractLayouter; import com.justcode.hxl.viewutil.recycleview_util.layoutmanager.chipslayoutmanager.layouter.Item; import java.util.List; class LTRRowFillSpaceCenterDenseStrategy implements IRowStrategy { @Override public void applyStrategy(AbstractLayouter abstractLayouter, List<Item> row) { int difference = GravityUtil.getHorizontalDifference(abstractLayouter) / 2; for (Item item : row) { Rect childRect = item.getViewRect(); childRect.left += difference; childRect.right += difference; } } }
package com.unionfind; public class Test { @org.junit.Test public void test1() { int n=10000; UnionFind_1 u = new UnionFind_1(n); long start = System.currentTimeMillis(); for(int i=0;i<n;i++) { int a= (int) (Math.random()*n); int b= (int) (Math.random()*n); u.unionElement(a, b); } for(int i=0;i<n;i++) { int a= (int) (Math.random()*n); int b= (int) (Math.random()*n); u.isConnected(a, b); } long end= System.currentTimeMillis(); System.out.println(end-start+"ms"); } @org.junit.Test public void test2() { int n=100000; UnionFind_2 u = new UnionFind_2(n); long start = System.currentTimeMillis(); for(int i=0;i<n;i++) { int a= (int) (Math.random()*n); int b= (int) (Math.random()*n); u.unionElement(a, b); } for(int i=0;i<n;i++) { int a= (int) (Math.random()*n); int b= (int) (Math.random()*n); u.isConnected(a, b); } long end= System.currentTimeMillis(); System.out.println(end-start+"ms"); } @org.junit.Test public void test3() { int n=1000000; UnionFind_3 u = new UnionFind_3(n); long start = System.currentTimeMillis(); for(int i=0;i<n;i++) { int a= (int) (Math.random()*n); int b= (int) (Math.random()*n); u.unionElement(a, b); } for(int i=0;i<n;i++) { int a= (int) (Math.random()*n); int b= (int) (Math.random()*n); u.isConnected(a, b); } long end= System.currentTimeMillis(); System.out.println(end-start+"ms"); } @org.junit.Test public void test4() { int n=1000000; UnionFind_4 u = new UnionFind_4(n); long start = System.currentTimeMillis(); for(int i=0;i<n;i++) { int a= (int) (Math.random()*n); int b= (int) (Math.random()*n); u.unionElement(a, b); } for(int i=0;i<n;i++) { int a= (int) (Math.random()*n); int b= (int) (Math.random()*n); u.isConnected(a, b); } long end= System.currentTimeMillis(); System.out.println(end-start+"ms"); } @org.junit.Test public void test5() { int n=1000000; UnionFind_5 u = new UnionFind_5(n); long start = System.currentTimeMillis(); for(int i=0;i<n;i++) { int a= (int) (Math.random()*n); int b= (int) (Math.random()*n); u.unionElement(a, b); } for(int i=0;i<n;i++) { int a= (int) (Math.random()*n); int b= (int) (Math.random()*n); u.isConnected(a, b); } long end= System.currentTimeMillis(); System.out.println(end-start+"ms"); } }
/* * Copyright (c) 2005 Einar Pehrson <einar@pehrson.nu>. * * This file is part of * CleanSheets - a spreadsheet application for the Java platform. * * CleanSheets is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * CleanSheets is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with CleanSheets; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.yurkiss.antlr.eval; import org.yurkiss.antlr.eval.functions.If; import org.yurkiss.antlr.eval.functions.NumericFunction; import org.yurkiss.antlr.eval.functions.Or; import org.yurkiss.antlr.eval.functions.Sum; import org.yurkiss.antlr.eval.operators.*; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * A factory for creating certain types of language elements. * * @author Einar Pehrson */ public class Language { /** * The singleton instance */ private static final Language instance = new Language(); /** * The name of the file in which language properties are stored */ private static final String PROPERTIES_FILENAME = "res/language.props"; /** * The unary operators that are supported by the language */ private List<UnaryOperator> unaryOperators = new ArrayList<UnaryOperator>(); /** * The binary operators that are supported by the language */ private List<BinaryOperator> binaryOperators = new ArrayList<BinaryOperator>(); /** * The functions that are supported by the language */ private List<Function> functions = new ArrayList<Function>(); /** * Creates a new language. */ private Language() { List<Class<? extends BinaryOperator>> binClasses = Arrays.asList( Adder.class, Subtracter.class, Multiplier.class, Divider.class, LessThan.class, GreaterThan.class, GreaterThanOrEqual.class, LessThanOrEqual.class, Equal.class, Equal2.class, NotEqual.class, Exponentiator.class ); List<Class<? extends Function>> funcClasses = Arrays.asList( Sum.class, If.class, Or.class ); try { for (Class<? extends BinaryOperator> clazz : binClasses) { BinaryOperator instance = clazz.newInstance(); binaryOperators.add(instance); } for (Class<? extends Function> clazz : funcClasses) { Function instance = clazz.newInstance(); functions.add(instance); } } catch (InstantiationException | IllegalAccessException e) { e.printStackTrace(); } // Loads static methods from java.lang.Math that use double precision for (Method method : Math.class.getMethods()) if (Modifier.isStatic(method.getModifiers()) && method.getReturnType() == Double.TYPE) functions.add(new NumericFunction(method)); } /** * Returns the singleton instance. * * @return the singleton instance */ public static Language getInstance() { return instance; } /** * Returns the unary operator with the given identifier. * @return the unary operator with the given identifier */ // public UnaryOperator getUnaryOperator(String identifier) throws UnknownElementException { // for (UnaryOperator operator : unaryOperators) // if (identifier.equalsIgnoreCase(operator.getIdentifier())) // return operator; // .clone() // throw new UnknownElementException(identifier); // } /** * Returns the binary operator with the given identifier. * * @return the binary operator with the given identifier */ public BinaryOperator getBinaryOperator(String identifier) throws UnknownElementException { for (BinaryOperator operator : binaryOperators) if (identifier.equalsIgnoreCase(operator.getIdentifier())) return operator; // .clone() throw new UnknownElementException(identifier); } /** * Returns the function with the given identifier. * * @return the function with the given identifier */ public Function getFunction(String identifier) throws UnknownElementException { for (Function function : functions) if (identifier.equalsIgnoreCase(function.getIdentifier())) return function; // .clone() throw new UnknownElementException(identifier); } /** * Returns whether there is a function with the given identifier. * * @return whether there is a function with the given identifier */ public boolean hasFunction(String identifier) { try { return getFunction(identifier) != null; } catch (UnknownElementException e) { return false; } } /** * Returns the functions that are supported by the syntax. * * @return the functions that are supported by the syntax */ public Function[] getFunctions() { return functions.toArray(new Function[functions.size()]); } }
import com.spart.io.Model.Employee; import com.spart.io.Model.Regex; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class RegexTest { @Test public void prefix() { String[] data = {"1", "Mr3535.", "Halil", "C", "Kale", "M", "Halilcankale98@gmail.com", "7/17/1998", "6/19/2021", "50000"}; Employee empTest = new Employee(); Assertions.assertFalse(Regex.RegexCall(data, empTest)); } @Test public void firstName(){ String[]data={"1","Mr.","Hal3553il","C","Kale","M","Halilcankale98@gmail.com","7/7/1998","6/9/2021","50000"}; Employee empTest= new Employee(); Assertions.assertFalse(Regex.RegexCall(data,empTest)); } @Test public void midInitial(){ String[]data={"1","Mr.","Halil","CFG","Kale","M","Halilcankale98@gmail.com","7/7/1998","6/9/2021","50000"}; Employee empTest= new Employee(); Assertions.assertFalse(Regex.RegexCall(data,empTest)); } @Test public void lastName(){ String[]data={"1","Mr.","Halil","C","Kal56e","M","Halilcankale98@gmail.com","7/7/1998","6/9/2021","50000"}; Employee empTest= new Employee(); Assertions.assertFalse(Regex.RegexCall(data,empTest)); } @Test public void Gender() { String[] data = {"1", "MR.", "Halil", "C", "Kale", "35", "Halilcankale98@gmail.com", "7/7/1998", "6/9/2021", "50000"}; Employee empTest = new Employee(); Assertions.assertFalse(Regex.RegexCall(data, empTest)); } @Test public void Email(){ String[]data={"1","Mr.","Halil","C","Kale","M","546","7/7/1998","6/9/2021","50000"}; Employee empTest= new Employee(); Assertions.assertFalse(Regex.RegexCall(data,empTest)); } }
package com.cst.web.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class TestController { private static final Logger logger = LoggerFactory.getLogger(TestController.class); @RequestMapping(value="/test/userinfo/{userId}") @ResponseBody public String getUserInfo(@PathVariable(value="userId") String userId){ logger.info("userId :{}",userId); return "{\"2\":\"3\"}"; } public String addUser() { System.out.println("测试方法"); return ""; } }
package com.itobuz.android.awesomechat.profile; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.widget.Toolbar; import com.itobuz.android.awesomechat.BaseActivity; import com.itobuz.android.awesomechat.Dependencies; import com.itobuz.android.awesomechat.R; import com.itobuz.android.awesomechat.navigation.AndroidProfileNavigator; import com.itobuz.android.awesomechat.profile.presenter.ProfilePresenter; import com.itobuz.android.awesomechat.profile.view.ProfileDisplayer; import de.hdodenhof.circleimageview.CircleImageView; /** * Created by Debasis on 19/12/16. */ public class ProfileActivity extends BaseActivity { private ProfilePresenter presenter; private AndroidProfileNavigator navigator; private CircleImageView profileImageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); setSupportActionBar((Toolbar) findViewById(R.id.toolbar)); getSupportActionBar().setTitle(R.string.profile_toolbar_title); ProfileDisplayer profileDisplayer = (ProfileDisplayer) findViewById(R.id.profileView); profileImageView = (CircleImageView) findViewById(R.id.profileImageView); navigator = new AndroidProfileNavigator(this); presenter = new ProfilePresenter( Dependencies.INSTANCE.getLoginService(), Dependencies.INSTANCE.getUserService(), Dependencies.INSTANCE.getProfileService(), Dependencies.INSTANCE.getStorageService(), profileDisplayer, navigator); if (ContextCompat.checkSelfPermission(ProfileActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { profileImageView.setEnabled(false); ActivityCompat.requestPermissions(ProfileActivity.this, new String[] { Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (!navigator.onActivityResult(requestCode, resultCode, data)) { super.onActivityResult(requestCode, resultCode, data); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == 0) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) { profileImageView.setEnabled(true); } } } @Override protected void onStart() { super.onStart(); presenter.startPresenting(); } @Override protected void onDestroy() { super.onDestroy(); presenter.stopPresenting(); } }
package org.ananas.extension.example.transform.sql; import org.ananas.runner.core.TransformerStepRunner; import org.ananas.runner.core.model.Step; import org.apache.beam.sdk.extensions.sql.SqlTransform; public class StepRunner extends TransformerStepRunner { protected StepRunner(Step step, org.ananas.runner.core.StepRunner previous) { super(step, previous); } @Override public void build() { String statement = (String) this.step.config.get("sql"); this.output = previous .getOutput() .apply( "simple sql transform", SqlTransform.query(statement)); } }
package com.si.ha.vaadin; public abstract class PushEvent implements Runnable{ }
package lab5; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class ContaIDTest { @Test void getCPF() { } @Test void getFornecedor() { } @Test void testHashCode() { } @Test void equals() { } }
import com.flipkart.dart.Batch; import com.flipkart.dart.BatchIngestor; import com.flipkart.dart.IngestionSuspendedException; import com.flipkart.dart.UploadResponse; import com.flipkart.dart.data.validation.ValidationException; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.log4j.Logger; import java.io.IOException; import java.io.StringWriter; import java.util.HashMap; import java.util.Iterator; import java.util.List; /** * Created by shukad on 09/12/15. */ public class BulkIngestorTask implements Runnable { private String ids; private static Logger logger = Logger.getLogger(BulkIngestorTask.class); private static String entityUrl = "fkint/apl/finance_reporting/invoice"; public BulkIngestorTask(String ids){ this.ids = ids; } public void run() { try { ingestForIds(); } catch (Exception e) { logger.error(ExceptionUtils.getStackTrace(e)); logger.error("Unable to ingest for the ids, Error: " + e.getMessage()); } } private void ingestForIds() throws Exception { logger.info("Getting batch ingestor object"); BatchIngestor batchIngestor = BatchIngestorFactory.INSTANCE.getBatchIngestor(); logger.info("Got batch ingestor object"); DataMerger merger = new DataMerger(); Jsonizer jsonizer = new Jsonizer(); BulkIngestorConnector bulkIngestorConnector = new BulkIngestorConnector(); InvoiceConnector connector = new InvoiceConnector(); connector.getTransformer().populateTransformationColumnsForAccruals(); Long timeBegin = System.currentTimeMillis(); List<HashMap> invoicesToIngest = merger.mergeAll(connector.getInvoices(ids), connector.getInvoiceItems(ids), connector.getInvoiceSubItems(ids)); Gson gson = new GsonBuilder().serializeNulls().create(); logger.info("******* printing json *********" ); logger.info(gson.toJson(invoicesToIngest)); Iterator<HashMap> invoiceIterator = invoicesToIngest.iterator(); String batchId = "INVOICE_".concat(String.valueOf(System.currentTimeMillis())). concat("_").concat(Util.getTimeBasedIncrementalNumber(5).toString()); logger.info("Time taken to extract and merge is " + (System.currentTimeMillis() - timeBegin) + "ms"); Long prepareBatchBegin = System.currentTimeMillis(); logger.info("Getting batch ingestor new batch object" + batchIngestor); Batch batch = batchIngestor.newBatch(batchId, entityUrl); logger.info("Got batch ingestor new batch object"); while(invoiceIterator.hasNext()){ HashMap invoice = invoiceIterator.next(); StringWriter invoiceJson = jsonizer.serialize(invoice); batch.add(invoiceJson.toString()); } logger.info("Time taken to prepare batch is " + (System.currentTimeMillis() - prepareBatchBegin) + "ms"); Long batchCommitBegin = System.currentTimeMillis(); UploadResponse uploadResponse = batch.commit(); logger.info("Time taken to commit batch is " + (System.currentTimeMillis() - batchCommitBegin) + "ms"); bulkIngestorConnector.markIdsAsIngested(ids, uploadResponse.getLocation().get(0)); logger.info("Time taken to ingest batch - " + batchId + " of size " + invoicesToIngest.size() + " is " + (System.currentTimeMillis() - timeBegin) + "ms"); connector.shutdown(); bulkIngestorConnector.shutdown(); } }
package edu.duke.ra.core.operator; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import edu.duke.ra.core.db.DB; public class Project extends RAXNode { protected String _columns; public Project(String columns, RAXNode input) { super(new ArrayList<RAXNode>(Arrays.asList(input))); _columns = columns; } public String genViewDef(DB db) throws SQLException { return "SELECT DISTINCT " + _columns + " FROM " + getChild(0).getViewName(); } public String toPrintString() { return "\\project_{" + _columns + "}"; } }
package homework1; public interface ICommunicationPrinter { public String welcome(String name); }
package com.aiwac.constant; /** * * @author HC * @date 2017年11月14日 * */ public class EmotionConstant { public static final int ACTIVATE_CONVERSATION_THRESHOLD = -1; public static final int FACE_IMAGE_EMOTION_SOURCE = 1; public static final int VOICE_EMOTION_SOURCE = 2; public static final int TEXT_EMOTION_SOURCE = 3; public static final int THERMAL_IMAGE_EMOTION_SOURCE = 4; public static final int BAIDU_NEGATIVE_EMOTION = -1; public static final int BAIDU_CALM_EMOTION = 0; public static final int BAIDU_POSITIVE_EMOTION = 1; public static final int BAIDU_EMOTION_TYPES = 3; public static final String BAIDU_CALM_EMOTION_TYPE = "6"; public static final String BAIDU_HAPPY_EMOTION_TYPE = "3"; public static final String BAIDU_SAD_EMOTION_TYPE = "4"; public static final int AIWAC_EMOTION_TYPES = 7; public static final String AIWAC_ANGRY_EMOTION_TYPE = "0"; public static final String AIWAC_DISGUST_EMOTION_TYPE = "1"; public static final String AIWAC_FEAR_EMOTION_TYPE = "2"; public static final String AIWAC_HAPPY_EMOTION_TYPE = "3"; public static final String AIWAC_SAD_EMOTION_TYPE = "4"; public static final String AIWAC_SURPRISE_EMOTION_TYPE = "5"; public static final String AIWAC_NEUTRAL_EMOTION_TYPE = "6"; // emotion bits, 7 '_' represent 7 kinds of emotion type public static final String EMOTION_BIT = "_______"; public static final String CONTENT_GROUP_DEFAULT_EMOTION = "2222222"; public static final String[] EMOTION_TYPES = {"Angry", "Disgust", "Fear", "Happy", "Sad", "Surprise", "Neutral"}; }
package com.micHon.adapter; public class UKToEuroAdapter implements EuroDevice { UKDevice device; public UKToEuroAdapter(UKDevice device) { this.device = device; } public void on() { device.powerOn(); } }
package com.ozeeesoftware.realestate.controller; import com.ozeeesoftware.realestate.model.Property; import com.ozeeesoftware.realestate.service.PropertyServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Map; @RestController @RequestMapping("/api/v1/properties") @CrossOrigin(origins = "http://localhost:4200") public class PropertyController { @Autowired private PropertyServiceImpl propertyServiceImpl; @GetMapping public ResponseEntity<List<Property>> getAllAds(){ return propertyServiceImpl.getAllAds(); } @PostMapping public ResponseEntity<Property> createAd(@RequestBody Property property){ return propertyServiceImpl.createAd(property); } @GetMapping("/{id}") public ResponseEntity<Property> getAdById(@PathVariable Long id){ return propertyServiceImpl.getAdById(id); } @PutMapping("/{id}") public ResponseEntity<Property> updateAd(@PathVariable Long id, @RequestBody Property property){ return propertyServiceImpl.updateAd(id, property); } @DeleteMapping("/{id}") public ResponseEntity<Map<String,Boolean>> deleteAd(@PathVariable Long id){ return propertyServiceImpl.deleteAd(id); } }
package com.mx.cdmx.cacho; @FunctionalInterface public interface FuncInterface { public abstract Integer doOperation(int i); }
package com.reagent.android.testproject; import com.reagent.android.testproject.nativelistview.GitHubRepoCommetDeatilActivity; import com.reagent.android.testproject.weblistview.GitHubRepoCommetDeatilWebViewActivity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; /** * This Activity used for select Native or Webview list Activity * @author Sandeep_PC * */ public class ListSelecterActivity extends BaseActivity implements OnClickListener{ private Context mContext; private View view; private LayoutInflater inflater; private Button btnNativeList,btnWebViewList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initialize(); setListener(); } /** * Initialize view & objects */ private void initialize (){ mContext = this; inflater = LayoutInflater.from(mContext); view = inflater.inflate(R.layout.layout_activitylist, getMiddleContent()); setModuleTitle(getString(R.string.module_title)); btnNativeList = (Button)view.findViewById(R.id.btnNativView); btnWebViewList = (Button)view.findViewById(R.id.btnWebView); } /** * Set Activity object Listener */ private void setListener(){ btnNativeList.setOnClickListener(this); btnWebViewList.setOnClickListener(this); } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.btnNativView: startActivity(new Intent(mContext, GitHubRepoCommetDeatilActivity.class)); break; case R.id.btnWebView: startActivity(new Intent(mContext, GitHubRepoCommetDeatilWebViewActivity.class)); break; default: break; } } }
package io.github.satr.aws.lambda.bookstore.constants; // Copyright © 2020, github.com/satr, MIT License public final class IntentName { public static String SearchBookByTitle = "SearchBookByTitleIntent"; public static String SelectBook = "SelectBookIntent"; public static String ShowBookSearchResult = "ShowBookSearchResultIntent"; public static String AddBookToBasket = "AddBookToBasketIntent"; public static String ShowBasket = "ShowBasketIntent"; public static String Introduction = "IntroductionIntent"; public static String CompleteOrder = "CompleteOrderIntent"; public static String RemoveBookFromBasket = "RemoveBookFromBasketIntent"; }
package com.openclassrooms.apisafetynet.controller; import java.net.URI; import java.sql.Date; import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.repository.query.Param; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity.BodyBuilder; import org.springframework.http.ResponseEntity.HeadersBuilder; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.server.ResponseStatusException; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import com.openclassrooms.apisafetynet.exceptions.UnfindablePersonException; import com.openclassrooms.apisafetynet.model.ChildAlertAndFamily; import com.openclassrooms.apisafetynet.model.MedicalRecord; import com.openclassrooms.apisafetynet.model.Person; import com.openclassrooms.apisafetynet.projection.ChildAlert; import com.openclassrooms.apisafetynet.projection.Email; import com.openclassrooms.apisafetynet.projection.PersonInfo; import com.openclassrooms.apisafetynet.projection.PhoneAlert; import com.openclassrooms.apisafetynet.service.PersonService; @RestController public class PersonController { @Autowired private PersonService personService; private ResponseEntity<Void> response; //---------- Méthodes de base -------- @DeleteMapping("/person/{id_bd}") public ResponseEntity<String> deletePerson(@PathVariable("id_bd") String idDb) throws UnfindablePersonException{ personService.deletePerson(idDb); return ResponseEntity.ok().body("Person deleted"); } @GetMapping("/persons") public ResponseEntity<Iterable<Person>> getPersons() { return ResponseEntity.ok().body(personService.getPersons()); } /* @PostMapping("/person") public ResponseEntity<Void> createPerson(@RequestBody Person person) { Person p = personService.savePerson(person); // Possibilité 2 de gérer une exception if (p == null) return ResponseEntity.noContent().build(); URI location = ServletUriComponentsBuilder .fromCurrentRequest() .path("/{id_Db}") .buildAndExpand(person.getIdDb()) .toUri(); return ResponseEntity.created(location).build(); } @PostMapping("/persons") public Iterable<Person> createPerson(@RequestBody Iterable<Person> persons) { return personService.savePersons(persons); } */ // trouver quelle response entity renvoyer pour plusieurs enregsiremens @PostMapping("/person") public ResponseEntity<Person> createPerson(@RequestBody Person person) { Person p = personService.savePerson(person); /*//Fonctionne mais je veux tester autre chose return ResponseEntity.created(location).build(); */ URI location = ServletUriComponentsBuilder .fromCurrentRequest() .path("/{id_Db}") .buildAndExpand(person.getIdDb()) .toUri(); return ResponseEntity.created(location) .header("jhyuhuih","uihyug") // juste pour savoir ce que ça fait .body(p); } @PostMapping("/persons") public ResponseEntity<Void> createPersons(@RequestBody Iterable<Person> persons) { Iterable<Person> p = personService.savePersons(persons); if (p == null) return ResponseEntity.noContent().build(); URI location = ServletUriComponentsBuilder .fromCurrentRequest().path("/packdeperson").build(false).toUri(); return ResponseEntity.created(location).build(); } @PutMapping("/person/{id_db}") public Person updatePerson(@PathVariable("id_db") String idDb, @RequestBody Person person) { return personService.updatePerson(idDb,person); } //---------- Méthodes personalisées -------- @GetMapping("/childAlert") public Iterable<ChildAlertAndFamily> getChildAlert(@RequestParam("address") String address){ return personService.getChildAlert(address); } @GetMapping("/phoneAlert") public Iterable<PhoneAlert> getPhones(@RequestParam("firestation") int station){ return personService.getPhones(station); } @GetMapping(value = "/personInfo") public Iterable<PersonInfo> getPersonInfo(@RequestParam("firstName") String firstName, @RequestParam("lastName") String lastName){ return personService.getPersonInfo(firstName, lastName); } @GetMapping(value = "/communityEmail") public Iterable<Email> getEmail(@RequestParam("city") String city){ return personService.getEmail(city); } /* * */ }
public class KeyIndexedCounting { public void keyIndexedCounting(int [] a) { int [] counting = new int[R + 1]; int [] aux = new int[a.length]; for (int i = 0; i < a.length; i++) { count[a[i]]++; } for (int i = 1; i < R; i++) { count[i + 1] += count[i]; } for (int i = 0; i < a.length; i++) { aux[count[a[i]]++] = a[i]; } for (int i = 0; i < a.length; i++) { a[i] = aux[i]; } } }
package annotation.codegener;/** * Created by DELL on 2018/10/18. */ import java.util.function.IntBinaryOperator; /** * user is lwb **/ public class Bar { @Adapt(IntBinaryOperator.class) public static int add(int a,int b){ return a + b; } }
package interview.meituan.D; import java.util.*; public class Main { // 保存原始字符串集合 private static List<String> list = new ArrayList<>(); // 保存字符串多重集合 private static Map<String, Integer> map = new HashMap<>(); public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); // 操作次数 int k = sc.nextInt(); // 初始字符串个数 sc.nextLine(); for(int i = 0; i < k; i++) { String tmp = sc.nextLine(); list.add(tmp); map.put(tmp, 1); } // n次操作 for(int i = 0; i < n; i++) { String op = sc.nextLine(); if(op.charAt(0)=='?') { int res = query(op.substring(1, op.length())); System.out.println(res); } else if(op.charAt(0)=='+') add(Integer.parseInt(op.substring(1, op.length())) - 1); else delete(Integer.parseInt(op.substring(1, op.length())) - 1); } } // 查询操作 public static int query(String s) { int cnt = 0; for (Map.Entry<String, Integer> entry : map.entrySet()) { // 求每个子串在母串中出现了多少次 if(entry.getValue() == 0) continue; cnt += cal(entry.getKey(), s); } return cnt; } public static int cal(String key, String s) { int cnt = 0; while(s.indexOf(key) != -1) { int index = s.indexOf(key); cnt++; s = s.substring(index + 1, s.length()); } return cnt; } // 增加操作 public static void add(int index) { String s = list.get(index); if(map.containsKey(s)) { int cnt = map.get(s); map.put(s, cnt + 1); } else map.put(s, 1); } // 删除操作 public static void delete(int index) { String s = list.get(index); int cnt = map.get(s); if(cnt > 1) map.remove(s); else map.remove(s); } } /* public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n=sc.nextInt(); int k=sc.nextInt(); String s[]=new String[k+1]; boolean de[]=new boolean[k+1]; for(int i=1;i<=k;i++){ s[i]=sc.next(); } String str=""; LinkedList<Integer> sum = new LinkedList<>(); for(int kkk=0;kkk<n;kkk++){ str=sc.next(); if(str.charAt(0)=='-'){ de[Integer.parseInt(str.substring(1,str.length()))]=true; } else if(str.charAt(0)=='+'){ de[Integer.parseInt(str.substring(1,str.length()))]=false; } else{ int ans=0; String mo = str.substring(1, str.length()); for(int i=1;i<=k;i++){ if(de[i])continue; int index=0; while(true){ int tmp=mo.indexOf(s[i],index); //System.out.println(tmp); if(tmp==-1)break; index=tmp+1; ans++; } } sum.add(ans); } } for (Integer integer : sum) { System.out.println(integer); } } }*/
package abstracto; public class Victor extends Professor{ public Victor() { this.Modulo = "M4"; Mn = 2; Edad = "36"; } @Override public void examen() { // TODO Auto-generated method stub System.out.println("Examen de M4"); } @Override public String toString() { // TODO Auto-generated method stub return "Clase meme"; } }
package symapMultiAlign; import java.awt.Color; import java.awt.Component; import java.awt.Point; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import symapQuery.SyMAPQueryFrame; public class AlignmentViewPanel extends JPanel { private static final long serialVersionUID = -2090028995232770402L; public AlignmentViewPanel(SyMAPQueryFrame parentFrame, String [] names, String [] sequences, String fileName) { theParentFrame = parentFrame; setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); setBackground(Color.WHITE); buildMultiAlignments(names, sequences, fileName); } private void buildMultiAlignments(String [] names, String [] sequences, String fileName) { final String [] theNames = names; final String [] theSequences = sequences; final String theFilename = fileName; if(theThread == null) { theThread = new Thread(new Runnable() { public void run() { try { bRunThread = true; setStatus(); //Load sequences from the database setMultiSequenceData(theNames, theSequences, theFilename); createButtonPanel(); createMainPanel(); showStatus(false); add(buttonPanel); add(scroller); updateExportButton(); } catch (Exception e) { e.printStackTrace(); } } }); theThread.setPriority(Thread.MIN_PRIORITY); theThread.start(); } } private void setStatus() { progressField = new JTextField(100); progressField.setEditable(false); progressField.setMaximumSize(progressField.getPreferredSize()); progressField.setBackground(Color.WHITE); progressField.setBorder(BorderFactory.createEmptyBorder()); btnCancel = new JButton("Cancel Alignment"); btnCancel.setBackground(Color.WHITE); btnCancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { stopThread(); } }); add(progressField); add(Box.createVerticalStrut(10)); add(btnCancel); } private void showStatus(boolean show) { btnCancel.setVisible(show); progressField.setVisible(show); } private void updateStatus(String status) { progressField.setText(status); } private void stopThread() { if(theThread != null) { bRunThread = false; } } private void setMultiSequenceData(String [] names, String [] sequences, String fileName) { theMultiAlignmentData = new MultiAlignmentData(fileName); for(int x=0; x<names.length; x++) theMultiAlignmentData.addSequence(names[x], sequences[x]); updateStatus("Aligning sequences please wait.."); theMultiAlignmentData.alignSequences(); createMultiAlignPanels(); } private void createButtonPanel() { buttonPanel = new JPanel(); buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.PAGE_AXIS)); buttonPanel.setBackground(Color.WHITE); add(Box.createVerticalStrut(10)); add(getButtonRow1()); add(Box.createVerticalStrut(10)); add(getMultiButtonRow()); buttonPanel.setAlignmentX(LEFT_ALIGNMENT); } private JPanel getButtonRow1() { JPanel theRow = new JPanel(); theRow.setLayout(new BoxLayout(theRow, BoxLayout.LINE_AXIS)); theRow.setAlignmentX(LEFT_ALIGNMENT); theRow.setBackground(Color.WHITE); menuHorzRatio = new JComboBox (); //menuHorzRatio.setPreferredSize( dim2 ); //menuHorzRatio.setMaximumSize ( dim2 ); menuHorzRatio.addItem( new MenuMapper ( "Horz. Ratio = 1:1", 1 ) ); menuHorzRatio.addItem( new MenuMapper ( "Horz. Ratio = 1:2", 2 ) ); menuHorzRatio.addItem( new MenuMapper ( "Horz. Ratio = 1:3", 3 ) ); menuHorzRatio.addItem( new MenuMapper ( "Horz. Ratio = 1:4", 4 ) ); menuHorzRatio.addItem( new MenuMapper ( "Horz. Ratio = 1:5", 5 ) ); menuHorzRatio.addItem( new MenuMapper ( "Horz. Ratio = 1:6", 6 ) ); menuHorzRatio.addItem( new MenuMapper ( "Horz. Ratio = 1:7", 7 ) ); menuHorzRatio.addItem( new MenuMapper ( "Horz. Ratio = 1:8", 8 ) ); menuHorzRatio.addItem( new MenuMapper ( "Horz. Ratio = 1:9", 9 ) ); menuHorzRatio.addItem( new MenuMapper ( "Horz. Ratio = 1:10", 10 ) ); menuHorzRatio.setBackground(Color.WHITE); menuHorzRatio.setSelectedIndex(0); menuHorzRatio.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { refreshPanels(); } }); btnShowType = new JButton("Show Sequences"); btnShowType.setBackground(Color.WHITE); btnShowType.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if(btnShowType.getText().equals("Show Graphic")) { btnShowType.setText("Show Sequences"); menuHorzRatio.setEnabled(true); } else { btnShowType.setText("Show Graphic"); menuHorzRatio.setEnabled(false); } refreshPanels(); } }); theRow.add(menuHorzRatio); theRow.add(Box.createHorizontalStrut(10)); theRow.add(btnShowType); btnExport = new JButton("Export"); btnExport.setBackground(Color.WHITE); btnExport.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if(theMultiPanel != null) { String filename = ""; filename = JOptionPane.showInputDialog("Enter file name"); if(filename != null && filename.length() > 0) { if(!filename.endsWith(".fasta")) filename += ".fasta"; theMultiAlignmentData.writeMuscleCache(filename); } } } }); theRow.add(Box.createHorizontalStrut(10)); theRow.add(btnExport); theRow.setMaximumSize(theRow.getPreferredSize()); return theRow; } private void updateExportButton() { if(theMultiAlignmentData != null && theMultiAlignmentData.hasFilename()) btnExport.setEnabled(true); else btnExport.setEnabled(false); } private JPanel getMultiButtonRow() { JPanel theRow = new JPanel(); theRow.setLayout(new BoxLayout(theRow, BoxLayout.LINE_AXIS)); theRow.setBackground(Color.WHITE); theRow.setAlignmentX(LEFT_ALIGNMENT); btnCopySeq = new JButton("Copy Sequence"); btnCopySeq.setEnabled(false); btnCopySeq.setBackground(Color.WHITE); btnCopySeq.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard(); cb.setContents(new StringSelection(theMultiPanel.getSelectedSequence()), null); } }); theRow.add(btnCopySeq); theRow.setMaximumSize(theRow.getPreferredSize()); return theRow; } private void refreshPanels() { refreshMultiPanels(); } private void refreshMultiButtons() { if(theMultiPanel.getNumSequencesSelected() == 1) btnCopySeq.setEnabled(true); else btnCopySeq.setEnabled(false); } private void refreshMultiPanels() { mainPanel.removeAll(); try { boolean showText = btnShowType.getText().equals("Show Sequences"); MenuMapper ratioSelection = (MenuMapper) menuHorzRatio.getSelectedItem(); int ratio = ratioSelection.asInt(); if(theMultiPanel != null) { theMultiPanel.setBorderColor(Color.BLACK); theMultiPanel.setBasesPerPixel(ratio); if(showText) theMultiPanel.setDrawMode(AlignmentPanelBase.GRAPHICMODE); else theMultiPanel.setDrawMode(AlignmentPanelBase.TEXTMODE); mainPanel.add(theMultiPanel); mainPanel.add(Box.createVerticalStrut(40)); LegendPanel lPanel = new LegendPanel(); lPanel.setIsPair(true); mainPanel.add(lPanel); } else { mainPanel.add(new JLabel("No Sequences")); } mainPanel.revalidate(); mainPanel.repaint(); } catch (Exception e) { e.printStackTrace(); } } private void createMultiAlignPanels() { theMultiPanel = new MultipleAlignmentPanel(theParentFrame, theMultiAlignmentData, 10, 10, 10, 10); theMultiPanel.setAlignmentY(Component.LEFT_ALIGNMENT); } private void createMainPanel() { scroller = new JScrollPane ( ); scroller.setHorizontalScrollBarPolicy( JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED ); scroller.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED ); scroller.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { handleClick(e); } }); mainPanel = new JPanel(); mainPanel.setLayout( new BoxLayout ( mainPanel, BoxLayout.Y_AXIS ) ); mainPanel.setBackground( Color.WHITE ); mainPanel.setAlignmentX(LEFT_ALIGNMENT); scroller.setViewportView( mainPanel ); refreshPanels(); } private void handleClick(MouseEvent e) { handleClickForMultiple(e); } private void handleClickForMultiple(MouseEvent e) { if(theMultiPanel != null) { // Convert to view relative coordinates int viewX = (int) (e.getX() + scroller.getViewport().getViewPosition().getX()); int viewY = (int) (e.getY() + scroller.getViewport().getViewPosition().getY()); // Get the panel and convert to panel relative coordinates int nPanelX = viewX - theMultiPanel.getX(); int nPanelY = viewY - theMultiPanel.getY(); if ( theMultiPanel.contains( nPanelX, nPanelY ) ) // Click is in current panel, let the object handle it theMultiPanel.handleClick( e, new Point( nPanelX, nPanelY ) ); else // Clear all selections in the panel unless shift or control are down if ( !e.isShiftDown() && !e.isControlDown() ) { theMultiPanel.selectNoRows(); theMultiPanel.selectNoColumns(); } refreshMultiButtons(); } } private SyMAPQueryFrame theParentFrame = null; //Display panels private JScrollPane scroller = null; //Main panels for the tab private JPanel buttonPanel = null; private JPanel mainPanel = null; //UI controls for the button panel private JComboBox menuHorzRatio = null; private JButton btnShowType = null; private JButton btnCopySeq = null; private JButton btnShowAll = null; private JButton btnShowAllPairs = null; private JButton btnShowOnlyPairs = null; private JButton btnShowHelp = null; private JButton btnExport = null; //Controls for progress/cancelling action private JTextField progressField = null; private JButton btnCancel = null; //Thread used for building the sequence data private Thread theThread = null; private boolean bRunThread = false; //Multiple alignment dataholders private MultiAlignmentData theMultiAlignmentData = null; private MultipleAlignmentPanel theMultiPanel = null; }
package springBoot; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; @Entity public class MovieRatings { @Id @GeneratedValue private long id; @NotNull @Size(min=1, max=150) private String movieTitle; @NotNull private int rating; @NotNull @Size(min=1, max=150) private String userName; @NotNull private String dateTime; public MovieRatings() { id = 0; movieTitle = null; rating = 0; userName = null; dateTime = null; } public MovieRatings(long id, String movieTitle, int rating, String userName, String dateTime) { super(); this.id = id; this.movieTitle = movieTitle; this.rating = rating; this.userName = userName; this.dateTime = dateTime; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getMovieTitle() { return movieTitle; } public void setMovieTitle(String movieTitle) { this.movieTitle = movieTitle; } public int getRating() { return rating; } public void setRating(int rating) { this.rating = rating; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getDateTime() { return dateTime; } public void setDateTime(String dateTime) { this.dateTime = dateTime; } }
package Event; import java.awt.Color; import java.awt.Graphics; import java.awt.event.KeyEvent; import Cards.Player; import Gamesetup.Game; public class PickStarters extends Event{ private int step; private int pick; private Player p1; private Player p2; private boolean finished; public PickStarters(Game game, Player p1, Player p2) { super(game); this.p1 = p1; this.p2 = p2; step = 1; pick = 0; finished = false; } public boolean finished() { return finished; } public void render(Graphics g) { g.setColor(Color.RED); if(step == 1) { g.drawRect(90+pick*120, 515, 100, 120); g.drawRect(90+pick*120+1, 516, 98, 118); g.drawRect(90+pick*120+2, 517, 96, 116); g.drawRect(90+pick*120+3, 518, 94, 114); }else if(step == 2){ g.drawRect(90+pick*120, 25, 100, 120); g.drawRect(90+pick*120+1, 26, 98, 118); g.drawRect(90+pick*120+2, 27, 96, 116); g.drawRect(90+pick*120+3, 28, 94, 114); } } public void update() { if(game.getKBC().checkIfKeyPAR(KeyEvent.VK_LEFT) && pick > 0) { pick--; } else if(game.getKBC().checkIfKeyPAR(KeyEvent.VK_RIGHT) && pick < 4) { pick++; } else if(game.getKBC().checkIfKeyPAR(KeyEvent.VK_ENTER)) { if(step == 1) { p1.playMCard(pick, 0); step++; pick = 0; }else if(step == 2){ p2.playMCard(pick, 0); finished = true; } } } }
package com.alibaba.druid.bvt.pool; import junit.framework.TestCase; import org.junit.Assert; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.util.JdbcUtils; public class TimeBetweenLogStatsMillisTest2 extends TestCase { private DruidDataSource dataSource; protected void setUp() throws Exception { System.setProperty("druid.timeBetweenLogStatsMillis", "1000"); dataSource = new DruidDataSource(); dataSource.setUrl("jdbc:mock:xxx"); } protected void tearDown() throws Exception { JdbcUtils.close(dataSource); System.clearProperty("druid.timeBetweenLogStatsMillis"); } public void test_0() throws Exception { dataSource.init(); Assert.assertEquals(1000, dataSource.getTimeBetweenLogStatsMillis()); } }
package com.sullbrothers.crypto.mancer; import java.util.List; import com.sullbrothers.crypto.database.CurrencyValuesDAO; import com.sullbrothers.crypto.database.RateHistoryDAO; /** * MancerState */ public class MancerState { public CurrencyValuesDAO currencyValues; public RateHistoryDAO.RateHistory currentRates; public List<RateHistoryDAO.RateHistory> historicalRates; public MancerState (CurrencyValuesDAO cv, RateHistoryDAO.RateHistory cr, List<RateHistoryDAO.RateHistory> hr) { this.currencyValues = cv; this.currentRates = cr; this.historicalRates = hr; } public double checkAgainst(MancerState other){ return this.getTotalValue() - other.getTotalValue(); } public double getTotalValue(){ double toReturn = 0; for(String s : this.currencyValues.getCurrencies()){ toReturn += this.currencyValues.getValueForCurrency(s)*(1/this.currentRates.getRates().getExchangeRateByCurrency(s).getPrice()); } return toReturn; } public void setCurrentRatePosition(int i){ if(i >= 0 && i < historicalRates.size()){ this.currentRates = historicalRates.get(i); } } public String toString(){ return "\"STATE\": {" + currencyValues + ", \"CURRENT_RATES\": " + currentRates + "}"; } }
package com.handler; import com.model.Author; import com.service.AuthorService; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.stereotype.Component; import org.springframework.web.reactive.function.server.ServerRequest; import org.springframework.web.reactive.function.server.ServerResponse; import reactor.core.publisher.Mono; import static org.springframework.web.reactive.function.BodyInserters.fromValue; @Component public class AuthorHandler { private final AuthorService authorService; public AuthorHandler(AuthorService authorService) { this.authorService = authorService; } public Mono<ServerResponse> findByName(ServerRequest serverRequest) { String name = serverRequest.queryParam("name").orElse(null); return ServerResponse.ok() .contentType(MediaType.APPLICATION_JSON) .body(authorService.findByName(name), Author.class); } public Mono<ServerResponse> findById(ServerRequest serverRequest) { Mono<Author> authorMono = authorService.findAuthorById( serverRequest.pathVariable("id")); return authorMono.flatMap(author -> ServerResponse.ok() .body(fromValue(author))) .switchIfEmpty(ServerResponse.notFound().build()); } public Mono<ServerResponse> save(ServerRequest serverRequest) { Mono<Author> authorMono = serverRequest.bodyToMono(Author.class); return authorMono.flatMap(author -> ServerResponse.status(HttpStatus.OK) .contentType(MediaType.APPLICATION_JSON) .body(authorService.save(author), Author.class)); } public Mono<ServerResponse> update(ServerRequest serverRequest) { final String authorId = serverRequest.pathVariable("id"); Mono<Author> authorMono = serverRequest.bodyToMono(Author.class); return authorMono.flatMap(author -> ServerResponse.status(HttpStatus.OK) .contentType(MediaType.APPLICATION_JSON) .body(authorService.update(authorId, author), Author.class)); } public Mono<ServerResponse> delete(ServerRequest serverRequest) { String authorId = serverRequest.pathVariable("id"); return authorService .findAuthorById(authorId) .flatMap(author -> ServerResponse.noContent().build(authorService.delete(author))) .switchIfEmpty(ServerResponse.notFound().build()); } }
/* * Copyright (c) 2016, WSO2 Inc. (http://wso2.com) All Rights Reserved. * * 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.wso2.msf4j.util; import java.util.HashMap; import java.util.Map; import java.util.Properties; /** * A utility which allows reading variables from the environment or System properties. * If the variable in available in the environment as well as a System property, the System property takes * precedence. */ public class SystemVariableUtil { private static final String VARIABLE_PREFIX = "CUSTOM_"; public static String getValue(String variableName, String defaultValue) { String value; if (System.getProperty(variableName) != null) { value = System.getProperty(variableName); } else if (System.getenv(variableName) != null) { value = System.getenv(variableName); } else { value = defaultValue; } return value; } public static Map<String, String> getArbitraryAttributes() { Map<String, String> arbitraryAttributes = new HashMap<>(); Map<String, String> environmentVariables = System.getenv(); environmentVariables.keySet().stream().filter(key -> key.startsWith(VARIABLE_PREFIX)).forEach(key -> { arbitraryAttributes.put(key, environmentVariables.get(key)); }); Properties properties = System.getProperties(); properties.keySet().stream().filter(key -> ((String) key).startsWith(VARIABLE_PREFIX)).forEach((Object key) -> { arbitraryAttributes.put((String) key, properties.getProperty((String) key)); }); return arbitraryAttributes; } }
package com.dirmod.cotizacionrestapi; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class CotizacionRestApiApplication { public static void main(String[] args) { SpringApplication.run(CotizacionRestApiApplication.class, args); } }
/* * Copyright 2018 nghiatc. * * 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.ntc.jedis; import com.ntc.configer.NConfig; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import redis.clients.jedis.JedisPoolConfig; import redis.clients.jedis.JedisShardInfo; import redis.clients.jedis.ShardedJedis; import redis.clients.jedis.ShardedJedisPool; /** * * @author nghiatc * @since Mar 7, 2018 */ public class JedisShardPoolClient { private static final Logger logger = LoggerFactory.getLogger(JedisShardPoolClient.class); private static final ConcurrentHashMap<String, JedisShardPoolClient> mapInstance = new ConcurrentHashMap<String, JedisShardPoolClient>(16, 0.9f, 16); private static Lock lock = new ReentrantLock(); private ShardedJedisPool pool; private List<JedisShardInfo> listShards = new ArrayList<>(); private JedisShardPoolClient(String prefix) { JedisPoolConfig cfg = new JedisPoolConfig(); cfg.setTestOnBorrow(true); cfg.setMaxTotal(100); // DEFAULT_MAX_TOTAL = 8 ==> the number instance in pool. // "127.0.0.1:1111:;127.0.0.2:2222;127.0.0.3:3333:cccc" | host:port:password String shards = NConfig.getConfig().getString(prefix + ".shards", "127.0.0.1:6379"); System.out.println("shards: " + shards); if (shards != null && !shards.isEmpty()) { String[] arrShards = shards.split(";"); System.out.println("arrShards: " + Arrays.asList(arrShards)); for (String shard : arrShards) { String[] sh = shard.split(":"); System.out.println("sh: " + Arrays.asList(sh)); if (sh.length == 2) { String host = sh[0]; int port = Integer.valueOf(sh[1]); JedisShardInfo jsi = new JedisShardInfo(host, port); listShards.add(jsi); } else if (sh.length == 3) { String host = sh[0]; int port = Integer.valueOf(sh[1]); String password = sh[2]; JedisShardInfo jsi = new JedisShardInfo(host, port); jsi.setPassword(password); listShards.add(jsi); } } } pool = new ShardedJedisPool(cfg, listShards); } public static JedisShardPoolClient getInstance(String prefix) { JedisShardPoolClient instance = mapInstance.get(prefix); if (instance == null) { lock.lock(); try { instance = mapInstance.get(prefix); if (instance == null) { instance = new JedisShardPoolClient(prefix); mapInstance.put(prefix, instance); } } finally { lock.unlock(); } } return instance; } public ShardedJedisPool getPool() { return pool; } public List<JedisShardInfo> getListShards() { return listShards; } public ShardedJedis borrowJedis() { ShardedJedis jedis = null; try { jedis = pool.getResource(); } catch (Exception e) { logger.error("borrowJedis: ", e); } return jedis; } public static void returnJedis(ShardedJedis jedis) { try { if (jedis != null) { jedis.close(); } } catch (Exception e) { logger.error("returnJedis: ", e); } } }
/* * Copyright 2018 Mike Neilson. * * 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 lan.capstone.uwins.model.simulation.uwins.testmodel; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.ejb.ActivationConfigProperty; import javax.ejb.EJBException; import javax.ejb.MessageDriven; import javax.ejb.MessageDrivenBean; import javax.ejb.MessageDrivenContext; import javax.ejb.Stateless; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.TextMessage; /** * * @author Mike Neilson */ @MessageDriven( activationConfig = { @ActivationConfigProperty(propertyName = "destinationLookup" , propertyValue ="uwinsl:/jms/computations/rc"), @ActivationConfigProperty(propertyName = "useJndi", propertyValue ="true") }) public class RCTestRainSummer implements MessageListener, MessageDrivenBean{ MessageDrivenContext ctx; @PostConstruct public void hello(){ System.err.println("Computation Bean ready"); } public RCTestRainSummer(){ super(); System.err.println("Computation Bean constructing"); } @Override public void onMessage(Message message) { TextMessage tm = (TextMessage)message; try { System.err.println(tm.getText()); } catch (JMSException ex) { System.err.println(ex); ex.printStackTrace(System.err); Logger.getLogger(RCTestRainSummer.class.getName()).log(Level.SEVERE, null, ex); } } @Override public void setMessageDrivenContext(MessageDrivenContext ctx) throws EJBException { this.ctx = ctx; } @Override public void ejbRemove() throws EJBException { } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.lol.ivyconvertpom; import java.io.File; import java.net.MalformedURLException; import java.text.ParseException; import org.apache.ivy.core.settings.IvySettings; import org.apache.ivy.core.module.descriptor.ModuleDescriptor; import org.apache.ivy.plugins.parser.m2.PomModuleDescriptorParser; import org.apache.ivy.plugins.repository.url.URLResource; /** * Convert a pom to an ivy file */ public class IvyConvertPom { public static void convert(final IvySettings ivySettings, final File pomFile, final File ivyFile) { try { if (pomFile == null) { throw new RuntimeException("source pom file is required for convertpom task"); } if (ivyFile == null) { throw new RuntimeException("destination ivy file is required for convertpom task"); } ModuleDescriptor md = PomModuleDescriptorParser.getInstance().parseDescriptor( ivySettings, pomFile.toURI().toURL(), false); PomModuleDescriptorParser.getInstance().toIvyFile(pomFile.toURI().toURL().openStream(), new URLResource(pomFile.toURI().toURL()), ivyFile, md); } catch (MalformedURLException e) { throw new RuntimeException("unable to convert given pom file to url: " + pomFile + ": " + e, e); } catch (ParseException e) { System.out.println(e.getMessage()); throw new RuntimeException("syntax errors in pom file " + pomFile + ": " + e, e); } catch (Exception e) { throw new RuntimeException("impossible convert given pom file to ivy file: " + e + " from=" + pomFile + " to=" + ivyFile, e); } } }
package com.automationui.framework.pages.components; import com.automationui.framework.BasePage; import com.automationui.framework.WebLocators; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.ui.ExpectedConditions; public class MenuComponent extends BasePage { public MenuComponent(WebDriver pDriver) { super(pDriver); } public void clickOnMenuAndSelect( String menuItem) { // We can use another approach if we've more items. getLogger(MenuComponent.getClassName(this)).info("Click on menu item: " + menuItem); if ("logout".equals(menuItem)) { wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(WebLocators.CSS_MENU))); driver.findElement((By.cssSelector(WebLocators.CSS_MENU))).click(); wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(WebLocators.CSS_LOGOUT))); driver.findElement(By.cssSelector(WebLocators.CSS_LOGOUT)).click(); } else if ("documents".equals(menuItem)) { wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(WebLocators.CSS_MENU))); driver.findElement((By.cssSelector(WebLocators.CSS_MENU))).click(); wait.until( ExpectedConditions.elementToBeClickable(By.cssSelector(WebLocators.CSS_DOCUMENTS))); driver.findElement(By.cssSelector(WebLocators.CSS_DOCUMENTS)).click(); } } }
import java.awt.BorderLayout; import java.awt.Component; import java.awt.Frame; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import java.awt.image.BufferedImage; import java.awt.image.DataBufferByte; import java.awt.image.Raster; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.util.ArrayList; import java.util.List; import javax.imageio.ImageIO; import javax.media.opengl.GL; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLCanvas; import javax.media.opengl.GLEventListener; import com.sun.opengl.util.Animator; import com.sun.opengl.util.GLUT; public class Project_ssalansk extends Frame implements GLEventListener { private static GL gl; // interface to OpenGL private static GLCanvas canvas; // drawable in a frame private static Animator animator; // drive display() in a loop private static GLUT glut; // only needed for putting text on the screen private static int HEIGHT = 800, WIDTH = 800; private static InputListener inputListener; // to capture user input private static Viewport view; private static final int POOL_BALL_ROWS = 5; // be reasonable private static final int NUM_POOL_BALLS = POOL_BALL_ROWS*(POOL_BALL_ROWS+1)/2; private static final int BALL_TEXTURE_COUNT = Math.min(16, NUM_POOL_BALLS+1); private static final double SPHERE_RADIUS = 0.05; private static final double SPHERE_SPACING = 0.005; private static final double DRAG_COEF = 0.95; private static final double PUSH_FORCE = 0.005; private static final int SPHERE_SUBDIVISIONS = 2; private static final float SPHERE_VDATA[][] = { { 1.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f }, { -1.0f, 0.0f, 0.0f }, { 0.0f, -1.0f, 0.0f }, { 0.0f, 0.0f, -1.0f } }; private static final float LIGHT_POSITION[] = { 2.0f, 2.0f, 2.0f, 1.0f }; private static final float BLACK[] = { 0.0f, 0.0f, 0.0f, 1.0f }; private static final float WHITE[] = { 1.0f, 1.0f, 1.0f, 1.0f }; private static final float RED[] = { 1.0f, 0.0f, 0.0f, 1.0f }; private static final float WHITEISH[] = { 0.8f, 0.8f, 0.7f, 1.0f }; private static final float DARK_GREY[] = { 0.1f, 0.1f, 0.1f, 1.0f }; private static final int[] POOL_BALL_TEX = new int[BALL_TEXTURE_COUNT]; private static final int[] POOL_TABLE_TEX = new int[1]; private static final double TABLE_LENGTH = 1; private static final double TABLE_WIDTH = 0.6; private Sphere playerSphere; private List<Sphere> sceneSpheres; private Light lightSource; private Project_ssalansk() { // 1. specify a drawable: canvas canvas = new GLCanvas(); // 2. listen to the events related to canvas: init, reshape, display, and displayChanged canvas.addGLEventListener(this); // 3. add the canvas to fill the Frame container this.add(canvas, BorderLayout.CENTER); // 4. interface to GLUT glut = new GLUT(); Point sphereCenter = new Point(0.453125, 0, 0, 0,0,0); playerSphere = new Sphere(sphereCenter, SPHERE_RADIUS); view = fromPositionLookingAt(new Point(0,0,-6), sphereCenter); view.zoom = 0.0005f; Point lightSourceLocation = new Point(0, 0, 0); lightSource = new Light(lightSourceLocation); sceneSpheres = setupSpheres(); } private class InputListener implements KeyListener, MouseListener, MouseMotionListener, MouseWheelListener, Runnable { private boolean keyUp, keyDown, keyLeft, keyRight; private Viewport view; private int mousePosX; private int mousePosY; public InputListener(GLAutoDrawable gLAutoDrawable, Viewport view) { ((Component) gLAutoDrawable).addKeyListener(this); ((Component) gLAutoDrawable).addMouseListener(this); ((Component) gLAutoDrawable).addMouseMotionListener(this); ((Component) gLAutoDrawable).addMouseWheelListener(this); this.view = view; this.keyUp = false; this.keyDown = false; this.keyLeft = false; this.keyRight = false; } @Override public void run() { while (true) { if (this.keyUp) { Vector d = view.getDirection(); playerSphere.center.dx -= PUSH_FORCE*d.x; playerSphere.center.dz -= PUSH_FORCE*d.z; } if (this.keyDown) { Vector d = view.getDirection(); playerSphere.center.dx += PUSH_FORCE*d.x; playerSphere.center.dz += PUSH_FORCE*d.z; } if (this.keyLeft) { Vector d = view.getDirection(); playerSphere.center.dx -= PUSH_FORCE*d.z; playerSphere.center.dz += PUSH_FORCE*d.x; } if (this.keyRight) { Vector d = view.getDirection(); playerSphere.center.dx += PUSH_FORCE*d.z; playerSphere.center.dz -= PUSH_FORCE*d.x; } try { Thread.sleep(15); } catch (InterruptedException e) { } } } @Override public void keyPressed(KeyEvent e) { int keyCode = e.getKeyCode(); if (keyCode == KeyEvent.VK_ESCAPE) { System.exit(0); } if (keyCode == KeyEvent.VK_UP) { this.keyUp = true; } if (keyCode == KeyEvent.VK_DOWN) { this.keyDown = true; } if (keyCode == KeyEvent.VK_LEFT) { this.keyLeft = true; } if (keyCode == KeyEvent.VK_RIGHT) { this.keyRight = true; } if (keyCode == KeyEvent.VK_PLUS || keyCode == KeyEvent.VK_EQUALS) { if (lightSource.attenuation > 0) { lightSource.attenuation -= 0.2; } } if (keyCode == KeyEvent.VK_MINUS || keyCode == KeyEvent.VK_UNDERSCORE) { if (lightSource.attenuation < 5) { lightSource.attenuation += 0.2; } } } @Override public void keyReleased(KeyEvent e) { int keyCode = e.getKeyCode(); if (keyCode == KeyEvent.VK_UP) { this.keyUp = false; } if (keyCode == KeyEvent.VK_DOWN) { this.keyDown = false; } if (keyCode == KeyEvent.VK_LEFT) { this.keyLeft = false; } if (keyCode == KeyEvent.VK_RIGHT) { this.keyRight = false; } } @Override public void mouseDragged(MouseEvent e) { int dx = e.getX() - this.mousePosX; int dy = e.getY() - this.mousePosY; this.mousePosX = e.getX(); this.mousePosY = e.getY(); this.view.yaw += dx*0.1; this.view.pitch += dy*0.1; } @Override public void mouseClicked(MouseEvent e) { this.mousePosX = e.getX(); this.mousePosY = e.getY(); } @Override public void mousePressed(MouseEvent e) { this.mousePosX = e.getX(); this.mousePosY = e.getY(); } @Override public void mouseWheelMoved(MouseWheelEvent e) { view.zoom *= Math.pow(1.05, e.getWheelRotation()); } @Override public void mouseReleased(MouseEvent e) {} @Override public void mouseEntered(MouseEvent e) {} @Override public void mouseExited(MouseEvent e) {} @Override public void mouseMoved(MouseEvent e) {} @Override public void keyTyped(KeyEvent e) {} } private class Vector { double x, y, z; public Vector(double vx, double vy, double vz) { x = vx; y = vy; z = vz; } public Vector normalized() { double l = magnitude(); return scaled(1.0 / l); } public Vector scaled(double s) { return new Vector(x * s, y * s, z * s); } public double magnitudeSquared() { return this.dot(this); } public double magnitude() { return Math.sqrt(magnitudeSquared()); } public double dot(Vector v2) { return this.x * v2.x + this.y * v2.y + this.z * v2.z; } public Point getDestinationPointFrom(Point start) { return new Point(start.x + x, start.y + y, start.z + z); } public Vector minus(Vector v2) { return new Vector(x-v2.x, y-v2.y, z-v2.z); } public Vector plus(Vector v2) { return new Vector(x+v2.x, y+v2.y, z+v2.z); } } private class Point { public double x, y, z; public double dx, dy, dz; public Point(double px, double py, double pz) { x = px; y = py; z = pz; dx = 0; dy = 0; dz = 0; } public void setVelocity(Vector vel) { dx = vel.x; dy = vel.y; dz = vel.z; } public Vector getVelocity() { return new Vector(dx,dy,dz); } public Point(double px, double py, double pz, double delta_x, double delta_y, double delta_z) { x = px; y = py; z = pz; dx = delta_x; dy = delta_y; dz = delta_z; } public void step() { x += dx; y += dy; z += dz; } public Vector getVectorTo(Point other) { return new Vector(other.x - this.x, other.y - this.y, other.z - this.z); } } private class Sphere { public double radius; public Point center; public int ballNumber; public float[] orientation; public Sphere(Point c, double r) { radius = r; center = c; ballNumber = 0; // default orientation = theIdentityMatrix(); } public void step() { center.step(); center.dx *= DRAG_COEF; center.dy *= DRAG_COEF; center.dz *= DRAG_COEF; double dl = Math.sqrt(center.dx*center.dx+center.dz*center.dz); gl.glMatrixMode(GL.GL_MODELVIEW); gl.glPushMatrix(); gl.glLoadIdentity(); gl.glRotated(180/Math.PI*dl/SPHERE_RADIUS, center.dz, 0, -center.dx); gl.glMultMatrixf(FloatBuffer.wrap(orientation)); gl.glGetFloatv(GL.GL_MODELVIEW_MATRIX, FloatBuffer.wrap(orientation)); gl.glPopMatrix(); } public void bounceSides() { double eff_bound_x = TABLE_LENGTH - radius; double eff_bound_z = TABLE_WIDTH - radius; if (center.x < -eff_bound_x || center.x > eff_bound_x) { center.dx = Math.copySign(center.dx, -center.x); center.x = Math.copySign( TABLE_LENGTH-radius, center.x); } if (center.z < -eff_bound_z || center.z > eff_bound_z) { center.dz = Math.copySign(center.dz, -center.z); center.z = Math.copySign( TABLE_WIDTH-radius, center.z); } } public void transDraw() { gl.glPushMatrix(); gl.glTranslated(center.x, center.y, center.z); gl.glMultMatrixf(orientation,0); gl.glScaled(radius, radius, radius); gl.glBindTexture(GL.GL_TEXTURE_2D, POOL_BALL_TEX[ballNumber]); drawSphere(SPHERE_SUBDIVISIONS); gl.glPopMatrix(); } } private class Light { public Point location; public float attenuation; public Light(Point loc) { location = loc; attenuation = 2.0f; } public float[] getPos() { float[] pos = { (float) location.x, (float) location.y, (float) location.z, 1 }; return pos; } } private class Viewport { public float roll, pitch, yaw, zoom; public Vector cameraPos; public Viewport(Vector pos, float roll, float pitch, float yaw, float zoom) { this.roll = roll; this.yaw = yaw; this.pitch = pitch; this.zoom = zoom; this.cameraPos = pos; } public Vector getDirection() { double x = Math.sin(-yaw*Math.PI/180); double y = Math.cos(pitch*Math.PI/180); double z = Math.cos(-yaw*Math.PI/180); Vector v = new Vector(x, y, z); return (v).normalized(); } } private Viewport fromPositionLookingAt(Point camera, Point subject){ Vector pos = new Vector(camera.x, camera.y, camera.z); Vector direction = camera.getVectorTo(subject); float yaw = (float) Math.atan2(direction.x, direction.z); float pitch = (float) Math.atan2(direction.z,direction.y); float roll = 0; float fov = 3; return new Viewport(pos, roll, pitch, yaw, fov); } private void setupScene() { gl.glLoadIdentity(); gl.glColor3d(1, 1, 1); gl.glMaterialfv(GL.GL_FRONT, GL.GL_DIFFUSE, BLACK, 0); gl.glMaterialfv(GL.GL_FRONT, GL.GL_EMISSION, WHITEISH, 0); gl.glMaterialfv(GL.GL_FRONT, GL.GL_SPECULAR, BLACK, 1); gl.glMaterialfv(GL.GL_FRONT, GL.GL_AMBIENT, BLACK, 0); gl.glRasterPos3d(-0.9, 0.9, 0); glut.glutBitmapString(GLUT.BITMAP_HELVETICA_18, "Use the directional arrows to move the cue ball"); gl.glRasterPos3d(-0.9, 0.85, 0); glut.glutBitmapString(GLUT.BITMAP_HELVETICA_18, "Click and drag the mouse to change the camera angle"); gl.glFrustum(-view.zoom * WIDTH, view.zoom * WIDTH, -view.zoom * HEIGHT, view.zoom * HEIGHT, 1.0, 16.0); gl.glTranslated(view.cameraPos.x,view.cameraPos.y,view.cameraPos.z); gl.glRotated(view.pitch, 1, 0, 0); gl.glRotated(view.yaw, 0, 1, 0); gl.glRotated(view.roll, 0, 0, 1); } private void drawTable() { // just have the box be dimly emitting, rather than receive lighting gl.glMaterialfv(GL.GL_FRONT, GL.GL_AMBIENT, BLACK, 0); gl.glMaterialfv(GL.GL_FRONT, GL.GL_SPECULAR, BLACK, 0); gl.glMaterialfv(GL.GL_FRONT, GL.GL_DIFFUSE, BLACK, 0); gl.glMaterialfv(GL.GL_FRONT, GL.GL_EMISSION, WHITE, 0); gl.glBindTexture(GL.GL_TEXTURE_2D, POOL_TABLE_TEX[0]); gl.glLineWidth(1); gl.glBegin(GL.GL_QUADS); gl.glNormal3f(0, 1, 0); gl.glTexCoord2f(0, 0); gl.glVertex3d(-TABLE_LENGTH, -SPHERE_RADIUS, -TABLE_WIDTH); gl.glTexCoord2f(0, 1); gl.glVertex3d(-TABLE_LENGTH, -SPHERE_RADIUS, TABLE_WIDTH); gl.glTexCoord2f(1, 1); gl.glVertex3d(TABLE_LENGTH, -SPHERE_RADIUS, TABLE_WIDTH); gl.glTexCoord2f(1, 0); gl.glVertex3d(TABLE_LENGTH, -SPHERE_RADIUS, -TABLE_WIDTH); gl.glEnd(); } private void drawSphere(long depth) { subdivideSphere(SPHERE_VDATA[0], SPHERE_VDATA[1], SPHERE_VDATA[2], depth); subdivideSphere(SPHERE_VDATA[0], SPHERE_VDATA[2], SPHERE_VDATA[4], depth); subdivideSphere(SPHERE_VDATA[0], SPHERE_VDATA[4], SPHERE_VDATA[5], depth); subdivideSphere(SPHERE_VDATA[0], SPHERE_VDATA[5], SPHERE_VDATA[1], depth); subdivideSphere(SPHERE_VDATA[3], SPHERE_VDATA[1], SPHERE_VDATA[5], depth); subdivideSphere(SPHERE_VDATA[3], SPHERE_VDATA[5], SPHERE_VDATA[4], depth); subdivideSphere(SPHERE_VDATA[3], SPHERE_VDATA[4], SPHERE_VDATA[2], depth); subdivideSphere(SPHERE_VDATA[3], SPHERE_VDATA[2], SPHERE_VDATA[1], depth); } private void checkBounce(Sphere s1, Sphere s2) { Vector separation = s1.center.getVectorTo(s2.center); if( separation.magnitudeSquared() <= 4*SPHERE_RADIUS*SPHERE_RADIUS ) { Vector n = separation.normalized(); Vector s1v = s1.center.getVelocity(); Vector s2v = s2.center.getVelocity(); Point middle = separation.scaled(0.5).getDestinationPointFrom(s1.center); s1.center = n.scaled(-(SPHERE_RADIUS+SPHERE_SPACING)).getDestinationPointFrom(middle); s2.center = n.scaled((SPHERE_RADIUS+SPHERE_SPACING)).getDestinationPointFrom(middle); Vector exchange = n.scaled(n.dot(s2v)).minus(n.scaled(n.dot(s1v))); s1.center.setVelocity(s1v.plus(exchange)); s2.center.setVelocity(s2v.minus(exchange)); } } private List<Sphere> setupSpheres() { ArrayList<Sphere> spheres = new ArrayList<>(10); Point corner = new Point(0, 0, 0); Vector cross = new Vector(-0.5, 0, Math.sqrt(3)/2).scaled(2*SPHERE_RADIUS + SPHERE_SPACING); Vector diag = new Vector(0.5,0,Math.sqrt(3)/2).scaled(2*SPHERE_RADIUS + SPHERE_SPACING); int n = 1; for(int i=0;i<POOL_BALL_ROWS;i++) { for(int j=0;j+i<POOL_BALL_ROWS;j++) { Vector offset = cross.scaled(i).plus(diag.scaled(j)); Point p = offset.getDestinationPointFrom(corner); Sphere s = new Sphere(p, SPHERE_RADIUS); s.ballNumber = n++%16; spheres.add(s); } } return spheres; } private void subdivideSphere(float v1[], float v2[], float v3[], long depth) { if (depth == 0) { drawSphereTriangle(v1, v2, v3); return; } float v12[] = new float[3]; float v23[] = new float[3]; float v31[] = new float[3]; int i; for (i = 0; i < 3; i++) { v12[i] = v1[i] + v2[i]; v23[i] = v2[i] + v3[i]; v31[i] = v3[i] + v1[i]; } normalize(v12); normalize(v23); normalize(v31); subdivideSphere(v1, v12, v31, depth - 1); subdivideSphere(v2, v23, v12, depth - 1); subdivideSphere(v3, v31, v23, depth - 1); subdivideSphere(v12, v23, v31, depth - 1); } private void drawSphereTriangle(float v1[], float v2[], float v3[]) { float[] uv1 = texCoord(v1); float[] uv2 = texCoord(v2); float[] uv3 = texCoord(v3); gl.glBegin(GL.GL_TRIANGLES); gl.glTexCoord2f(uv1[0], uv1[1]); gl.glNormal3fv(v1,0); gl.glVertex3fv(v1,0); gl.glTexCoord2f(uv2[0], uv2[1]); gl.glNormal3fv(v2,0); gl.glVertex3fv(v2,0); gl.glTexCoord2f(uv3[0], uv3[1]); gl.glNormal3fv(v3,0); gl.glVertex3fv(v3,0); gl.glEnd(); } private void normalize(float[] vector) { float d = (float) Math.sqrt(vector[0] * vector[0] + vector[1] * vector[1] + vector[2] * vector[2]); if (d == 0) { System.err.println("0 length vector: normalize()."); return; } vector[0] /= d; vector[1] /= d; vector[2] /= d; } private float[] theIdentityMatrix() { float[] f = new float[16]; for (int i = 0; i < 4; i++) { f[i * 5] = 1.0f; } return f; } private float[] texCoord(float v[]) { float[] uv = new float[2]; uv[0] = (float) ((Math.atan2(-v[2],v[0])+Math.PI)/(Math.PI*2)); uv[1] = (float) (Math.acos(v[1])/Math.PI); return uv; } private void initializePoolBallTexture(int n) { gl.glBindTexture(GL.GL_TEXTURE_2D, POOL_BALL_TEX[n]); gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR); gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR); readImageAndGlTexImage2D("textures/small_PoolBalluv"+n+".jpg"); } private void readImageAndGlTexImage2D(String fileName) { File f = new File(fileName); BufferedImage bufimg; try { // read the image into BufferredImage structure bufimg = ImageIO.read(f); int imgW = bufimg.getWidth(); int imgH = bufimg.getHeight(); int imgType = bufimg.getType(); System.out.println(fileName+" -- BufferedImage WIDTH&HEIGHT: "+imgW+", "+imgH); System.out.println("BufferedImage type TYPE_3BYTE_BGR 5; GRAY 10: "+imgType); //TYPE_BYTE_GRAY 10 //TYPE_3BYTE_BGR 5 // retrieve the pixel array in raster's databuffer Raster raster = bufimg.getData(); DataBufferByte dataBufByte = (DataBufferByte)raster. getDataBuffer(); System.out.println("Image data's type TYPE_BYTE 0: "+ dataBufByte.getDataType()); // TYPE_BYTE 0 gl.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGB8, imgW, imgH, 0, GL.GL_BGR, GL.GL_UNSIGNED_BYTE, ByteBuffer.wrap(dataBufByte.getData())); } catch (IOException ex) { System.exit(1); } } @Override public void init(GLAutoDrawable drawable) { gl = drawable.getGL(); // 2. clear the background to black gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f); gl.glClear(GL.GL_COLOR_BUFFER_BIT); // 3. drive the display() in a loop animator = new Animator(canvas); animator.start(); // start animator thread gl.glDrawBuffer(GL.GL_BACK); gl.glEnable(GL.GL_DEPTH_TEST); gl.glDepthFunc(GL.GL_LEQUAL); gl.glEnable(GL.GL_TEXTURE_2D); gl.glHint(GL.GL_PERSPECTIVE_CORRECTION_HINT, GL.GL_NICEST); // Perspective correction gl.glEnable(GL.GL_BLEND); gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA); gl.glEnable(GL.GL_LIGHTING); gl.glEnable(GL.GL_NORMALIZE); gl.glEnable(GL.GL_LIGHT1); gl.glLightfv(GL.GL_LIGHT1, GL.GL_POSITION, LIGHT_POSITION, 0); gl.glLightfv(GL.GL_LIGHT1, GL.GL_DIFFUSE, WHITE, 0); gl.glEnable(GL.GL_LIGHT2); gl.glLightfv(GL.GL_LIGHT2, GL.GL_POSITION, lightSource.getPos(), 0); gl.glLightfv(GL.GL_LIGHT2, GL.GL_DIFFUSE, RED, 0); // initialize EARTH texture obj gl.glGenTextures(BALL_TEXTURE_COUNT, IntBuffer.wrap(POOL_BALL_TEX)); for(int n=0;n<BALL_TEXTURE_COUNT;n++) { initializePoolBallTexture(n); } gl.glGenTextures(1, IntBuffer.wrap(POOL_TABLE_TEX)); gl.glBindTexture(GL.GL_TEXTURE_2D, POOL_TABLE_TEX[0]); gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR); gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR); readImageAndGlTexImage2D("textures/table.jpg"); inputListener = new InputListener(canvas, view); new Thread(inputListener).start(); } @Override public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { WIDTH = width; HEIGHT = height; gl.glViewport(0, 0, WIDTH, HEIGHT); } @Override public void display(GLAutoDrawable drawable) { gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); setupScene(); // draw the box within which the shapes will bounce //drawBox(); drawTable(); // update light source positions gl.glLightfv(GL.GL_LIGHT1, GL.GL_POSITION, LIGHT_POSITION, 0); gl.glLightfv(GL.GL_LIGHT2, GL.GL_POSITION, lightSource.getPos(), 0); // set material lighting properties for objects gl.glMaterialfv(GL.GL_FRONT, GL.GL_DIFFUSE, WHITEISH, 0); gl.glMaterialfv(GL.GL_FRONT, GL.GL_EMISSION, BLACK, 0); gl.glMaterialfv(GL.GL_FRONT, GL.GL_SPECULAR, WHITEISH, 1); gl.glMaterialfv(GL.GL_FRONT, GL.GL_AMBIENT, DARK_GREY, 0); playerSphere.bounceSides(); for (Sphere s : sceneSpheres) { s.bounceSides(); } for (int i = 0; i < sceneSpheres.size(); i++) { checkBounce(sceneSpheres.get(i),playerSphere); for (int j = 0; j < i; j++) { checkBounce(sceneSpheres.get(i),sceneSpheres.get(j)); } } playerSphere.transDraw(); for (Sphere s : sceneSpheres) { s.transDraw(); } playerSphere.step(); for (Sphere s : sceneSpheres) { s.step(); } try { Thread.sleep(20); } catch (Exception ignore) { } } @Override public void displayChanged(GLAutoDrawable arg0, boolean arg1, boolean arg2) { // TODO Auto-generated method stub } public static void main(String[] args) { Project_ssalansk f = new Project_ssalansk(); f.setTitle("JOGL Project_ssalansk"); f.setSize(WIDTH, HEIGHT); f.setVisible(true); } }
/* * IntValidator * * Version: 1.0 * * 08.07.2019 * * Shamshur Aliaksandr * */ package z2.validators; public class IntValidator { //-- return true if a>0 public static boolean isNatural(int a) { return (a > 0) ? true:false; } }
package com.example.onenprofessor.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import org.json.JSONObject; import android.os.Environment; import android.os.Handler; import com.example.onenprofessor.ConstantValue; public class FileUtils { /** * 根据参数创建文件 * @param is 文件输入流 * @param json 另一端socket传来的msg * @param hanlder 更新界面 */ public static void reciveFile(InputStream is,JSONObject json,Handler handler){ try { String fileName = json.getString("filename"); String fileSzie = json.getString("filesize"); String path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+com.example.onenprofessor.ConstantValue.DIR_NAME; File file = new File(path+"/"+fileName); if(!file.exists()){ file.createNewFile(); } FileOutputStream fos = new FileOutputStream(file); //更新界面 handler.sendEmptyMessage(ConstantValue.ON_READ); int intfileSzie = Integer.parseInt(fileSzie); byte[] buffer = new byte[intfileSzie]; int length = 0; int size = 0; //向另一端socket发送正在接受状态 while(size < intfileSzie){ length = is.read(buffer); size += length; fos.write(buffer,0,length); } /* }*/ fos.flush(); fos.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static InputStream getFileInputStream(String fileName) throws FileNotFoundException{ File file = new File(fileName); FileInputStream fis; fis = new FileInputStream(file); return fis; } public static long getFileSize(String fileName) throws IOException{ File file = new File(fileName); FileInputStream fis = new FileInputStream(file); return fis.getChannel().size(); } }
// https://leetcode.com/problems/find-k-closest-elements/solution/ // https://leetcode.com/problems/find-k-closest-elements/discuss/106426/JavaC%2B%2BPython-Binary-Search-O(log(N-K)-%2B-K) class Solution { public List<Integer> findClosestElements(int[] arr, int k, int x) { int n = arr.length; if (x <= arr[0]) return Arrays.stream(arr, 0, k).boxed().collect(Collectors.toList()); else if (arr[n - 1] <= x) return Arrays.stream(arr, n - k, n).boxed().collect(Collectors.toList()); else { int left = 0, right = arr.length - k; while (left < right) { int mid = (left + right) / 2; if (x - arr[mid] > arr[mid + k] - x) left = mid + 1; else right = mid; } return Arrays.stream(arr, left, left + k).boxed().collect(Collectors.toList()); } } }
package com.kevin.cloud.commons.platform.service.fallback; import com.kevin.cloud.commons.platform.dto.FallBackResult; /** * @program: kevin-cloud-dubbo2.0 * @description: * @author: kevin * @create: 2020-01-11 20:48 **/ public abstract class BaseFallBack implements IBaseFallBack { private static final int errorLength = 230; public static FallBackResult fallBackError(FallBackResult fallBackResult, Throwable throwable) { FallBackResult fallBackResultEnd = null; if (fallBackResult == null) { fallBackResultEnd = new FallBackResult(); } fallBackResultEnd.setStatus(false); if(throwable.toString().length() >= errorLength){ fallBackResultEnd.setFallbackReason(throwable.toString().substring(0, errorLength)); }else{ fallBackResultEnd.setFallbackReason(throwable.toString()); } return fallBackResultEnd; } public static FallBackResult fallBackError(Throwable throwable) { return fallBackError(null, throwable); } }
package com.stackroute.recommend; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.stereotype.Component; @Component @EnableEurekaClient @SpringBootApplication public class RecommendApplication { public static void main(String[] args) { SpringApplication.run(RecommendApplication.class, args); } }
/* * Copyright © 2020-2022 ForgeRock AS (obst@forgerock.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.forgerock.sapi.gateway.ob.uk.common.datamodel.converter.account; import com.forgerock.sapi.gateway.ob.uk.common.datamodel.account.FRPartyData; import com.forgerock.sapi.gateway.ob.uk.common.datamodel.converter.common.FRPostalAddressConverter; import uk.org.openbanking.datamodel.account.*; public class FRPartyConverter { // FR to OB public static OBParty1 toOBParty1(FRPartyData party) { return party == null ? null : new OBParty1() .partyId(party.getPartyId()) .partyNumber(party.getPartyNumber()) .partyType(toOBExternalPartyType1Code(party.getPartyType())) .name(party.getName()) .emailAddress(party.getEmailAddress()) .phone(party.getPhone()) .mobile(party.getMobile()) .address(FRPostalAddressConverter.toOBPostalAddress8List(party.getAddresses())); } public static OBParty2 toOBParty2(FRPartyData party) { return party == null ? null : new OBParty2() .partyId(party.getPartyId()) .partyNumber(party.getPartyNumber()) .partyType(toOBExternalPartyType1Code(party.getPartyType())) .name(party.getName()) .fullLegalName(party.getFullLegalName()) .legalStructure(party.getLegalStructure()) .beneficialOwnership(party.getBeneficialOwnership()) .accountRole(party.getAccountRole()) .emailAddress(party.getEmailAddress()) .phone(party.getPhone()) .mobile(party.getMobile()) .relationships(toOBPartyRelationships1(party.getRelationship())) .address(FRPostalAddressConverter.toOBParty2AddressList(party.getAddresses())); } public static OBExternalPartyType1Code toOBExternalPartyType1Code(FRPartyData.FRPartyType partyType) { return partyType == null ? null : OBExternalPartyType1Code.valueOf(partyType.name()); } public static OBPartyRelationships1 toOBPartyRelationships1(FRPartyData.FRRelationship relationship) { return relationship == null ? null : new OBPartyRelationships1() .account(new OBPartyRelationships1Account() .related(relationship.getRelated()) .id(relationship.getId())); } // OB to FR public static FRPartyData toFRPartyData(OBParty2 party) { return party == null ? null : FRPartyData.builder() .partyId(party.getPartyId()) .partyNumber(party.getPartyNumber()) .partyType(toFRPartyType(party.getPartyType())) .name(party.getName()) .fullLegalName(party.getFullLegalName()) .legalStructure(party.getLegalStructure()) //.beneficialOwnership(party.isBeneficialOwnership()) .accountRole(party.getAccountRole()) .emailAddress(party.getEmailAddress()) .phone(party.getPhone()) .mobile(party.getMobile()) .relationship(toFRRelationship(party.getRelationships())) .addresses(FRPostalAddressConverter.toFRPostalAddressList(party.getAddress())) .build(); } public static FRPartyData.FRPartyType toFRPartyType(OBExternalPartyType1Code partyType) { return partyType == null ? null : FRPartyData.FRPartyType.valueOf(partyType.name()); } public static FRPartyData.FRRelationship toFRRelationship(OBPartyRelationships1 relationship) { return relationship == null || relationship.getAccount() == null ? null : FRPartyData.FRRelationship.builder() .related(relationship.getAccount().getRelated()) .id(relationship.getAccount().getId()) .build(); } }
package unisinos.tradutores.antlr.main.listener; import lombok.Getter; import org.antlr.v4.runtime.tree.TerminalNodeImpl; import unisinos.tradutores.antlr.main.domain.Method; import unisinos.tradutores.antlr.main.gramatica.Java8BaseListener; import unisinos.tradutores.antlr.main.gramatica.Java8Parser; import java.util.ArrayList; import java.util.List; import static java.util.Objects.nonNull; @Getter public class JavaBaseListenerImpl extends Java8BaseListener { private final List<Method> methods; private Method.MethodBuilder currentMethod; public JavaBaseListenerImpl() { methods = new ArrayList<>(); } @Override public void enterMethodDeclarator(Java8Parser.MethodDeclaratorContext ctx) { if (nonNull(currentMethod)) { methods.add(currentMethod.build()); } if (nonNull(ctx.Identifier())) { currentMethod = Method.builder().name(ctx.Identifier().getText()); } } @Override public void enterMethodInvocation(Java8Parser.MethodInvocationContext ctx) { if (nonNull(currentMethod) && ctx.children.size() > 0) { StringBuilder method = new StringBuilder(ctx.children.get(0).getText()); for (int i = 1; i < ctx.children.size(); i++) { if (ctx.children.get(i) instanceof TerminalNodeImpl) { method.append(ctx.children.get(i).getText()); continue; } if (ctx.children.get(i) instanceof Java8Parser.ArgumentListContext) { method.append("param"); } } currentMethod.methodsCall(method.toString()); } } @Override public void enterMethodInvocation_lf_primary(Java8Parser.MethodInvocation_lf_primaryContext ctx) { if (nonNull(currentMethod) && ctx.children.size() > 0) { StringBuilder method = new StringBuilder(ctx.children.get(0).getText()); for (int i = 1; i < ctx.children.size(); i++) { if (ctx.children.get(i) instanceof TerminalNodeImpl) { method.append(ctx.children.get(i).getText()); continue; } if (ctx.children.get(i) instanceof Java8Parser.ArgumentListContext) { method.append("param"); } } currentMethod.methodsCall(method.toString()); } } @Override public void enterMethodInvocation_lfno_primary(Java8Parser.MethodInvocation_lfno_primaryContext ctx) { if (nonNull(currentMethod) && ctx.children.size() > 0) { StringBuilder method = new StringBuilder(ctx.children.get(0).getText()); for (int i = 1; i < ctx.children.size(); i++) { if (ctx.children.get(i) instanceof TerminalNodeImpl) { method.append(ctx.children.get(i).getText()); continue; } if (ctx.children.get(i) instanceof Java8Parser.ArgumentListContext) { method.append("param"); } } currentMethod.methodsCall(method.toString()); } } @Override public void enterBlockStatements(Java8Parser.BlockStatementsContext ctx) { if (nonNull(currentMethod)) { currentMethod.blockStatement(ctx.getText()); } } @Override public void enterForStatement(Java8Parser.ForStatementContext ctx) { if (ctx.children.size() < 2) { return; } if (nonNull(currentMethod)) { currentMethod.command(ctx.children.get(0).getText()); } } @Override public void enterForStatementNoShortIf(Java8Parser.ForStatementNoShortIfContext ctx) { if (ctx.children.size() < 2) { return; } if (nonNull(currentMethod)) { currentMethod.command(ctx.children.get(0).getText()); } } @Override public void enterWhileStatement(Java8Parser.WhileStatementContext ctx) { if (ctx.children.size() < 2) { return; } if (nonNull(currentMethod)) { currentMethod.command(ctx.children.get(0).getText()); } } @Override public void enterWhileStatementNoShortIf(Java8Parser.WhileStatementNoShortIfContext ctx) { if (ctx.children.size() < 2) { return; } if (nonNull(currentMethod)) { currentMethod.command(ctx.children.get(0).getText()); } } @Override public void enterDoStatement(Java8Parser.DoStatementContext ctx) { if (ctx.children.size() < 2) { return; } if (nonNull(currentMethod)) { currentMethod.command(ctx.children.get(0).getText()); } } @Override public void enterIfThenStatement(Java8Parser.IfThenStatementContext ctx) { if (ctx.children.size() < 2) { return; } if (nonNull(currentMethod)) { currentMethod.command(ctx.children.get(0).getText()); } } @Override public void enterIfThenElseStatement(Java8Parser.IfThenElseStatementContext ctx) { if (ctx.children.size() < 2) { return; } if (nonNull(currentMethod)) { currentMethod.command(ctx.children.get(0).getText()); } } @Override public void enterIfThenElseStatementNoShortIf(Java8Parser.IfThenElseStatementNoShortIfContext ctx) { if (ctx.children.size() < 2) { return; } if (nonNull(currentMethod)) { currentMethod.command(ctx.children.get(0).getText()); } } @Override public void enterCatches(Java8Parser.CatchesContext ctx) { if (ctx.children.size() < 2) { return; } if (nonNull(currentMethod)) { currentMethod.command(ctx.children.get(0).getText()); } } @Override public void enterConditionalExpression(Java8Parser.ConditionalExpressionContext ctx) { if (ctx.children.size() < 2) { return; } if (nonNull(currentMethod)) { currentMethod.command(ctx.children.get(0).getText()); } } @Override public void enterSwitchLabel(Java8Parser.SwitchLabelContext ctx) { if (ctx.children.size() < 2) { return; } if (nonNull(currentMethod)) { currentMethod.command(ctx.children.get(0).getText()); } } public List<Method> result() { methods.add(currentMethod.build()); return methods; } }
/* * 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 pkcs11; import iaik.pkcs.pkcs11.Module; import iaik.pkcs.pkcs11.Session; import iaik.pkcs.pkcs11.Slot; import iaik.pkcs.pkcs11.Token; import iaik.pkcs.pkcs11.TokenException; import iaik.pkcs.pkcs11.TokenInfo; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** * Handle all the PKCS11 related operations in the program. * * @author Raphaël Cohen */ public class TokenManager { private Module pkcs11Module; private Token token; public TokenManager() { } /** * Get the available token slots * * @return Array of the token slots availables * @throws TokenException */ public Slot[] getTokenSlots() throws TokenException { return pkcs11Module.getSlotList(Module.SlotRequirement.TOKEN_PRESENT); } /** * Load the token to use. For now the token in the first available slot is * used * * @return Succes of the operation * @throws TokenException */ protected boolean loadToken() throws TokenException { Slot[] slots = this.getTokenSlots(); if (slots.length == 0) { //No tokens connected System.out.println("Couldn't find any token."); return false; } System.out.println(slots.length + " slot(s) available."); this.token = slots[0].getToken(); System.out.println("Connected to token"); return true; } /** * Initialize the token manager: * <ul> * <li>Initialize the PKCS#11 module</li> * <li>Set the Token to use</li> * </ul> * @param librarayPath * @return success of the operation */ public boolean initialize(String librarayPath) { try { return initializePkcs11Module(librarayPath) && this.loadToken(); } catch (TokenException ex) { Logger.getLogger(SmartCardPinChanger.class.getName()).log(Level.SEVERE, null, ex); System.out.println("Impossible to initialize the token manager, exiting"); System.exit(0); } return false; } /** * Initialize the PKCS#11 module * * @param librarayPath Path to the cryptoki DLL * @return Success of the operation * @throws TokenException */ protected boolean initializePkcs11Module(String librarayPath) throws TokenException { System.out.println("Initializing PKCS11 module ..."); try { pkcs11Module = Module.getInstance(librarayPath); pkcs11Module.initialize(null); return true; } catch (IOException ex) { Logger.getLogger(SmartCardPinChanger.class.getName()).log(Level.SEVERE, null, ex); System.out.println("Impossible to initialize the PKCS11 module: " + ex.getMessage()); return false; } } /** * Release context */ public void release() { System.out.println("Releasing token context"); try { this.token.closeAllSessions(); pkcs11Module.finalize(null); } catch (TokenException ex) { Logger.getLogger(SmartCardPinChanger.class.getName()).log(Level.SEVERE, null, ex); System.out.println("Error while releasing context"); } } /** * Perform the change PIN operation * * @param oldPin * @param newPin * @return Success of the operation */ public boolean changeTokenPin(String oldPin, String newPin) { Session openedSession = this.openSession(); if (openedSession == null) { return false; } if (!this.loginToToken(openedSession, oldPin)) { this.closeSession(openedSession); return false; } return this.setPin(openedSession, oldPin, newPin); } /** * Set the new PIN * * @param openedSession An opened Session * @param oldPin The actual Pin * @param newPin The new Pin * @return Success of the operation */ protected boolean setPin(Session openedSession, String oldPin, String newPin) { try { openedSession.setPIN(oldPin.toCharArray(), newPin.toCharArray()); System.out.println("PIN changed."); this.closeSession(openedSession); return true; } catch (TokenException ex) { Logger.getLogger(SmartCardPinChanger.class.getName()).log(Level.SEVERE, null, ex); System.out.println("Impossible to set the new PIN"); return false; } } /** * Open a new session on the token * * @return The opened session */ protected Session openSession() { Session session; try { session = this.token.openSession( Token.SessionType.SERIAL_SESSION, Token.SessionReadWriteBehavior.RW_SESSION, null, null ); } catch (TokenException ex) { Logger.getLogger(SmartCardPinChanger.class.getName()).log(Level.SEVERE, null, ex); System.out.println("Impossible to open a session on the token"); return null; } return session; } /** * Close the given session * * @param session */ protected void closeSession(Session session) { try { session.closeSession(); } catch (TokenException ex) { Logger.getLogger(SmartCardPinChanger.class.getName()).log(Level.SEVERE, null, ex); } } /** * Log-in to the given session * * @param session Session to log to * @param userPINString PIN to access the token * @return Succes of the log-in */ protected boolean loginToToken(Session session, String userPINString) { TokenInfo tokenInfo; try { tokenInfo = this.token.getTokenInfo(); if (!tokenInfo.isLoginRequired()) { return true; } if (tokenInfo.isProtectedAuthenticationPath()) { System.out.println("Please enter the user PIN at the PIN-pad of your reader."); session.login(Session.UserType.USER, null); // the token prompts the PIN by other means; e.g. PIN-pad return true; } session.login(Session.UserType.USER, userPINString.toCharArray()); return true; } catch (TokenException ex) { Logger.getLogger(SmartCardPinChanger.class.getName()).log(Level.SEVERE, null, ex); System.out.println("Impossible to log-in the token. The PIN code may be wrong ..."); return false; } } }
package kr.or.ddit.global; public interface GlobalConstant { // temp에 files폴더에 파일을 저장 public String FILE_PATH = "C:\\Users\\JeaSeok\\Desktop\\Programming\\Server File\\FinalProject"; }
/** * Copyright ${license.git.copyrightYears} the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ibatis.reflection; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * Mybatis提供的ReflectorFactory的默认实现,唯一实现。 * 我们可以在mybatis-config.xml中配置自定义的ReflectorFactory实现类,从而实现功能上的拓展。 * Mybatis初始化流程时,会涉及该拓展点 */ public class DefaultReflectorFactory implements ReflectorFactory { /** * 该字段决定是否开启对Reflector对象的缓存 */ private boolean classCacheEnabled = true; /** * 使用ConcurrentMap集合实现对Reflector对象的缓存 */ private final ConcurrentMap<Class<?>, Reflector> reflectorMap = new ConcurrentHashMap<>(); public DefaultReflectorFactory() { } @Override public boolean isClassCacheEnabled() { return classCacheEnabled; } @Override public void setClassCacheEnabled(boolean classCacheEnabled) { this.classCacheEnabled = classCacheEnabled; } @Override public Reflector findForClass(Class<?> type) { // 检测是否开启缓存 if (classCacheEnabled) { // synchronized (type) removed see issue #461 // 已删除同步(类型) - 问题参见 issue #461 // Java8中可以通过"::"关键字访问类的构造方法,对象的方法,静态方法。 // Reflector::new等同于new Reflector() // #todo:我们需要的是new Reflector(type),Reflector::new是否等同于?参数是否有传入? // do:我们并不需要new Reflector(type)。computeIfAbsent()方法第一个参数是key,第二个参数是使用第一个参数计算value的方法(并不是value)。 // 故type会自动的传入Reflector::new计算value。再将key和计算好的value存入集合中 // 构建Reflector对象,添加缓存,并返回 return reflectorMap.computeIfAbsent(type, Reflector::new); } else { // 构建Reflector对象,直接返回 return new Reflector(type); } } }
package com.lovi.twr.common.model; import org.springframework.data.annotation.Id; public abstract class EntityBase{ public static final short STATUS_INACTIVE = 0; public static final short STATUS_ACTIVE = 1; public static final short STATUS_DELETED = 2; @Id private Integer id; public EntityBase() { } public EntityBase(Integer id) { this.id = id; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { if (!(object instanceof EntityBase)) { return false; } EntityBase other = (EntityBase) object; return !((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))); } @Override public String toString() { return "EntityBase{" + "id=" + id + '}'; } }
package fr.ul.miage.m1.projetreseau; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.util.Hashtable; public class HTTPServer extends Thread { // Répertoire racine du projet private final File root; // Objet effectuant le lien entre notre serveur (java) et le navigateur, il attend // les requetes et envoie les infos au navigateur quand il faut private final ServerSocket serverSocket; // Nom du serveur public static final String VERSION = "NotreSereurHTTP"; // MIME TYPES reconnus par notre serveur public static final Hashtable<String, String> MIME_TYPES = new Hashtable<>(); // Ajouts des différents MIME_TYPES reconnus par notre serveur static { MIME_TYPES.put(".gif", "images/gif"); MIME_TYPES.put(".jpg", "images/jpeg"); MIME_TYPES.put(".jpeg", "images/jpeg"); MIME_TYPES.put(".png", "images/png"); MIME_TYPES.put(".html", "text/html"); MIME_TYPES.put(".htm", "text/html"); MIME_TYPES.put(".txt", "text/plain"); MIME_TYPES.put(".css", "text/css"); MIME_TYPES.put(".js", "text/javascript"); MIME_TYPES.put(".woff", "font/woff"); MIME_TYPES.put(".woff2", "font/woff2"); MIME_TYPES.put(".ttf", "font/ttf"); MIME_TYPES.put(".ttf2", "font/ttf2"); MIME_TYPES.put(".ico", "image/x-icon"); } /** * Constructeur * * @param rootDir Repertoire racine du site qu'on doit lancer * @param port Port d'écoute * @param domaine nom de domaine du serveur * @throws IOException */ public HTTPServer(File rootDir, int port, String domaine) throws IOException { root = rootDir.getCanonicalFile(); if (!root.isDirectory()) throw new IOException("Le fichier spécifié n'est pas un répertoire"); InetAddress address = InetAddress.getByName(domaine); serverSocket = new ServerSocket(port, 50, address); System.out.println("Lancement du serveur :" + domaine + " sur le port :" + port); start(); } /** * Lance le serveur dans un thread */ public void run() { while (true) { try { // Ecoute une connexion à etablir avec ce socket et s'il y en a une, l'accepte Socket socket = serverSocket.accept(); // Lecture d'une requête envoyée par le navigateur (client) au serveur, analyse // et réponse : envoi d'une requête serveur vers navigateur (client) HTTPRequest requestThread = new HTTPRequest(socket, root,serverSocket.getInetAddress().getHostName()); requestThread.start(); } catch (IOException e) { System.exit(1); } } } /** * Fonction qui vérifie si un fichier est compressé via son nom * * @param file fichier où on souhaite savoir s'il ets compressé * @return true s'il est compressé, false sinon */ public static boolean estCompresse(java.io.File file) { String filename = file.getName(); String[] filenameParts = filename.split("."); for (int i = 0; i < filenameParts.length; i++) { if (filenameParts[i].equals("min")) { return true; } } return false; } /** * Fonction qui détermine l'extension d'un fichier * * @param file fichier où on souhaite récuperer l'extension * @return extension du fichier '.html' | '.css' ... */ public static String getExtension(java.io.File file) { String extension = ""; String filename = file.getName(); int dotPos = filename.lastIndexOf("."); if (dotPos >= 0) { extension = filename.substring(dotPos); } return extension.toLowerCase(); } }
/* * work_wx * wuhen 2020/1/16. * Copyright (c) 2020 jianfengwuhen@126.com All Rights Reserved. */ package com.work.wx.controller.modle; import com.work.wx.controller.modle.subChatItem.*; import java.util.Arrays; public class ChatModel extends BaseModel { private String corpId; private Long seq; private String msgtype; // 文本消息为:text。String类型 图片消息为:image。String类型 撤回消息为:revoke。String类型 // 同意消息为:agree,不同意消息为:disagree。String类型 语音消息为:voice。String类型 视频消息为:video。String类型 // 名片消息为:card。String类型 位置消息为:location。String类型 表情消息为:emotion。String类型 file。String类型 // 链接消息为:link。String类型 消息为:weapp。String类型 消息为:chatrecord。String类型 _todo。String类型 vote。String // 类型 collect。String类型 redpacket。String类型 meeting。String类型 消息id,消息的唯一标识,企业可以使用此字段进行消息去 // 重。 String类型 docmsg。String类型, 标识在线文档消息类型 markdown。String类型, 标识MarkDown消息类型 news String类 //型, 标识 图文消息类型 calendar。String类型, 标识日程消息类型 private String msgid; // 消息id,消息的唯一标识,企业可以使用此字段进行消息去重。String类型 private String action; // 消息动作,目前有send(发送消息)/recall(撤回消息)/switch(切换企业日志)三种类型。String类型 private String from; // 消息发送方id。同一企业内容为userid,非相同企业为external_userid。消息如果是机器人发出,也为external_userid。String类型 private String[] tolist; // 消息接收方列表,可能是多个,同一个企业内容为userid,非相同企业为external_userid。数组,内容为string类型 private String roomid; // 群聊消息的群id。如果是单聊则为空。String类型 private Long msgtime; // 消息发送时间戳,utc时间,ms单位。 private Boolean mark = false; // 是否已经同步了媒体数据 private ChatModelText text; //文本类型 private ChatModelImage image; //图片消息为 private ChatModelMedia voice; private ChatModelMedia video; private ChatModelFile file; private ChatModelLocation location; private ChatModelEmotion emotion; private ChatModelCard card; private ChatModelAgree agree; private ChatModelLink link; private ChatModeRecord chatrecord; private ChatModeVote vote; private ChatModeCollect collect; private ChatModelRedPacket redpacket; private ChatModelRevoke revoke; private ChatModelMetting meeting; private ChatModelDocMsg docmsg; private ChatModelNews news; private ChatModelCalendar calendar; public String getMsgtype() { return msgtype; } public void setMsgtype(String msgtype) { this.msgtype = msgtype; } public String getMsgid() { return msgid; } public void setMsgid(String msgid) { this.msgid = msgid; } public String getAction() { return action; } public void setAction(String action) { this.action = action; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String[] getTolist() { return tolist; } public void setTolist(String[] tolist) { this.tolist = tolist; } public String getRoomid() { return roomid; } public void setRoomid(String roomid) { this.roomid = roomid; } public Long getMsgtime() { return msgtime; } public void setMsgtime(Long msgtime) { this.msgtime = msgtime; } public String getCorpId() { return corpId; } public void setCorpId(String corpId) { this.corpId = corpId; } public Long getSeq() { return seq; } public void setSeq(Long seq) { this.seq = seq; } public Boolean isMark() { return mark; } public void setMark(Boolean mark) { this.mark = mark; } public ChatModel(String corpId) { this.corpId = corpId; } public ChatModel(String corpId, Long seq) { this.corpId = corpId; this.seq = seq; } public ChatModel() { } public ChatModel(String corpId, String from) { this.corpId = corpId; this.from = from; } public ChatModelText getText() { return text; } public void setText(ChatModelText text) { this.text = text; } public ChatModelImage getImage() { return image; } public void setImage(ChatModelImage image) { this.image = image; } public ChatModelMedia getVoice() { return voice; } public void setVoice(ChatModelMedia voice) { this.voice = voice; } public ChatModelMedia getVideo() { return video; } public void setVideo(ChatModelMedia video) { this.video = video; } public ChatModelLocation getLocation() { return location; } public void setLocation(ChatModelLocation location) { this.location = location; } public ChatModelEmotion getEmotion() { return emotion; } public void setEmotion(ChatModelEmotion emotion) { this.emotion = emotion; } public ChatModelCard getCard() { return card; } public void setCard(ChatModelCard card) { this.card = card; } public ChatModelAgree getAgree() { return agree; } public void setAgree(ChatModelAgree agree) { this.agree = agree; } public ChatModelLink getLink() { return link; } public void setLink(ChatModelLink link) { this.link = link; } public ChatModeRecord getChatrecord() { return chatrecord; } public void setChatrecord(ChatModeRecord chatrecord) { this.chatrecord = chatrecord; } public ChatModeVote getVote() { return vote; } public void setVote(ChatModeVote vote) { this.vote = vote; } public ChatModeCollect getCollect() { return collect; } public void setCollect(ChatModeCollect collect) { this.collect = collect; } public ChatModelRedPacket getRedpacket() { return redpacket; } public void setRedpacket(ChatModelRedPacket redpacket) { this.redpacket = redpacket; } public ChatModelRevoke getRevoke() { return revoke; } public void setRevoke(ChatModelRevoke revoke) { this.revoke = revoke; } public ChatModelMetting getMeeting() { return meeting; } public void setMeeting(ChatModelMetting meeting) { this.meeting = meeting; } public ChatModelDocMsg getDocmsg() { return docmsg; } public void setDocmsg(ChatModelDocMsg docmsg) { this.docmsg = docmsg; } public ChatModelNews getNews() { return news; } public void setNews(ChatModelNews news) { this.news = news; } public ChatModelCalendar getCalendar() { return calendar; } public void setCalendar(ChatModelCalendar calendar) { this.calendar = calendar; } public ChatModelFile getFile() { return file; } public void setFile(ChatModelFile file) { this.file = file; } @Override public String toString() { return "ChatModel{" + "corpId='" + corpId + '\'' + ", seq=" + seq + ", msgtype='" + msgtype + '\'' + ", msgid='" + msgid + '\'' + ", action='" + action + '\'' + ", from='" + from + '\'' + ", tolist=" + Arrays.toString(tolist) + ", roomid='" + roomid + '\'' + ", msgtime=" + msgtime + ", mark=" + mark + ", text=" + text + ", image=" + image + ", voice=" + voice + ", video=" + video + ", file=" + file + ", location=" + location + ", emotion=" + emotion + ", card=" + card + ", agree=" + agree + ", link=" + link + ", chatrecord=" + chatrecord + ", vote=" + vote + ", collect=" + collect + ", redpacket=" + redpacket + ", revoke=" + revoke + ", meeting=" + meeting + ", docmsg=" + docmsg + ", news=" + news + ", calendar=" + calendar + "} " + super.toString(); } }
/******************************************************************************* * Copyright 2014 Hyplink (solideclipse@gmail.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 hyplink.net.general; /** This file contains the task list that Hyplink's developers working on */ public class TODO { private TODO() {} /** @revision 5v1.4 */ // TODOne Change version name and version code // TODOne Add animation // TODOne Add best score attribute /** @revision 6v1.5 */ // TODOne Change version name and version code // TODOne Add dialog (win, lose, confirm new game) // TODOne Add expanding mode // TODOne Add sound effect // TODOne Add menu (New game, rate, about, enable sound, share) /** @revision 7v1.6 */ // TODOne Change version name and version code // TODOne Fix bug do not save sound setting // TODOne Remove about function in menu // TODOne Fix app_market and app_url link // TODOne Improve score tiles // TODOne Add v11, v14 styles // TODOne Add layout-land // TODOne Change icon // TODOne Add change orientation function /** @release */ // TODOne integrate StartApp ads // TODOne add license to each header of java file // TODOne logMode = false // TODOne Take screen shoots // TODOne Edit application information on publishing page // TODO Backup project // TODO delete unused files // TODO ProGuard // TODO Signed application and make the .APK file // TODO Upload application and screen shoots }
public class MergeSortedArray { public void merge(int[] nums1, int m, int[] nums2, int n) { if (nums1.length == 0 || nums2.length == 0 ) return; int i=0,j=0,k=0; int temp = 0; int s = m+n-1; while (i < s ) { if (nums1[i]<=nums2[j]) { if (nums1[i]==0) nums1[i]=temp; i++; } else { temp = nums1[i]; nums1[i]=nums2[j]; j++; i++; } } } public static void main(String[] args) { } }
package com.blackbird.camel.zone; import com.blackbird.model.zone.AdConfigContext; public interface AdConfigHandler { public void handle(AdConfigContext body); }
package com.esum.wp.as2.svcinfo.struts.action; import java.security.PrivateKey; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import com.esum.appcommon.resource.application.Config; import com.esum.appcommon.session.SessionMgr; import com.esum.appframework.exception.ApplicationException; import com.esum.appframework.struts.action.BaseDelegateAction; import com.esum.appframework.struts.actionform.BeanUtilForm; import com.esum.as2util.common.rsa.RSAUtil; import com.esum.framework.common.util.Base64; import com.esum.framework.security.crypto.digest.DigestUtil; import com.esum.wp.as2.svcinfo.SvcInfo; import com.esum.wp.as2.svcinfo.service.ISvcInfoService; import com.esum.wp.as2.tld.XtrusLangTag; public class SvcInfoAction extends BaseDelegateAction { protected ActionForward doService( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { if (method.equals("other method")) { /** * insert, update, delete, deleteList, select, selectList 이외의 서비스 처리 */ return null; } else if (method.equals("login")) { SvcInfo svcInfo = null; BeanUtilForm beanUtilForm = (BeanUtilForm) form; request.removeAttribute("inputObject"); request.removeAttribute("outputObject"); Object inputObject = null; if (beanUtilForm != null) { inputObject = beanUtilForm.getBean(); } else { beanUtilForm = new BeanUtilForm(); } if (inputObject == null) { svcInfo = new SvcInfo(); } else { svcInfo = (SvcInfo) inputObject; } SessionMgr sess = new SessionMgr(request); try { PrivateKey privateKey = (PrivateKey) sess.getObjValue("__rsaPrivateKey__"); sess.removeValue("__rsaPrivateKey__"); if (privateKey == null) { throw new Exception(XtrusLangTag.getMessage("error.rsa.private.key")); } String username = svcInfo.getUserId(); String password = RSAUtil.decryptRsa(privateKey, svcInfo.getPassword()); svcInfo.setPassword(Base64.encode(DigestUtil.SHA256(password.getBytes()), false)); svcInfo.setLoginResult(false); List loginResultList = (List) ((ISvcInfoService) iBaseService).login(svcInfo); if(loginResultList != null){ if (loginResultList.size() > 0) { svcInfo.setLoginResult(true); SvcInfo loginResultObj = (SvcInfo) loginResultList.get(0); String userauth = loginResultObj.getUserAuth(); // HttpSession sess.setValue("langType", svcInfo.getSvcIdLangtype()); sess.setValue("ctimezone", Integer.toString(-((new Date()).getTimezoneOffset()/60))); sess.setValue("svcid", username); //sess 체크용 sess.setValue("userid", username); sess.setValue("password", svcInfo.getPassword()); sess.setValue("dbType", Config.getString("Common","DB.TYPE")); sess.setValue("userauth", userauth); sess.setValue("recentSetting", "oneMin"); sess.setValue("autoRefresh", "N"); sess.setValue("autoRefreshValue", "60"); } } }catch (RuntimeException e) { String loginError = XtrusLangTag.getMessage("alert.db.not.connect"); ApplicationException ae = new ApplicationException(loginError); request.setAttribute("servletpath", request.getServletPath()); request.setAttribute("exception", ae); return mapping.findForward("failure"); } catch (Exception e) { String loginError = e.getMessage(); ApplicationException ae = new ApplicationException(loginError); request.setAttribute("servletpath", request.getServletPath()); request.setAttribute("exception", ae); return mapping.findForward("failure"); } beanUtilForm.setBean(svcInfo); request.setAttribute("inputObject", svcInfo); return mapping.findForward("success"); } else { return super.doService(mapping, form, request, response); } } }
package com.company; import ru.ifmo.se.pokemon.*; public class Main { public static void main (String[] args) { Battle b = new Battle(); b.addAlly(new Hawlucha ()); b.addAlly(new Numel()); b.addAlly(new Camerupt()); b.addFoe(new Starly()); b.addFoe(new Stravia()); b.addFoe(new Staraptor()); b.go(); } }
package com.example.bigasslayout.bigasslayout; import android.app.Activity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; /** * Created by demo on 12/22/14. */ public class GoatList extends ArrayAdapter<String> { private final Activity context; private final String xmlSpeed; private boolean fibonacciBool; private final String[] goatNames; private final boolean[] goatTrue; private final int[] goatPix; private final boolean lotsOfObjects; CheckBox rowCheck; public GoatList(Activity context, String xmlSpeed, Boolean fibonacciBool, String[] goatNames, int[] goatPix, boolean[] goatTrue, boolean lotsOfObjects) { super(context, R.layout.goatrow, goatNames); this.context = context; this.xmlSpeed = xmlSpeed; this.fibonacciBool = fibonacciBool; this.goatNames = goatNames; this.goatPix = goatPix; this.goatTrue = goatTrue; this.lotsOfObjects = lotsOfObjects; } @Override public View getView(int position, View view, ViewGroup parent) { LayoutInflater inflater = context.getLayoutInflater(); View rowView; if (xmlSpeed.matches(context.getResources().getString(R.string.slowestXml))) { //slow view is goatrow rowView = inflater.inflate(R.layout.goatrow, null, true); } else if (xmlSpeed.equals(context.getResources().getString(R.string.overdrawXml))) { //use view with as much overdraw removed as possible rowView = inflater.inflate(R.layout.nooverdrawgoatrow, null, true); } else if (xmlSpeed.equals(context.getResources().getString(R.string.removeLLoverdrawXml))) { //use view with as much overdraw removed as possible rowView = inflater.inflate(R.layout.nooverdrawgoatrow, null, true); } else if (xmlSpeed.equals(context.getResources().getString(R.string.RLfastXml))) { //use view with as much overdraw removed as possible //this also removes one layer of the goat row by using a relative layout rowView = inflater.inflate(R.layout.rlfastestgoatrow, null, true); } else if (xmlSpeed.matches(context.getResources().getString(R.string.myfast))) { //my fast view rowView = inflater.inflate(R.layout.my_optimize_goatrow, null, true); } else //fastest { rowView = inflater.inflate(R.layout.fastestgoatrow, null, true); } //add more objects - defaults to no if (!lotsOfObjects) { // we'll use the views initialized once at the top. TextView rowTxt = (TextView) rowView.findViewById(R.id.textView); ImageView rowImg = (ImageView) rowView.findViewById(R.id.imageView); rowCheck = (CheckBox) rowView.findViewById(R.id.checkBox); if (fibonacciBool) { int bigNumber; //confusion and delay -take the position, add 4, multiply by another number to (a BIG number) //find that member of the fibonacci sequence using recursion (which is slow) if (position == 5) { bigNumber = (position + 8) * 3;//will cause a jink scrolling up } else if (position == 10) { bigNumber = (position + 3) * 3;//will pause scrolling down } else { bigNumber = (position + 4) * 2; } int fibValue = fibonacci.fib(bigNumber); //wasted time! rowTxt.setText(goatNames[position] + "\nDelay Fibonacci #: " + fibValue); } else {//no crazy slowdown from fibonacci. rowTxt.setText(goatNames[position]); } rowImg.setImageResource(goatPix[position]); rowCheck.setChecked(goatTrue[position]); rowCheck.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CheckBox checkedBox = (CheckBox) v; //this all has to be inverse. If the user checks the box - it WAS unchecked if (!checkedBox.isChecked()) { //button WAS checked. User unchecked it //goat checkedBox.setChecked(true); Toast.makeText(context, "Correct! \nThis is a goat", Toast.LENGTH_SHORT).show(); } else { //button was not checked, and user checked it //not a goat checkedBox.setChecked(false); Toast.makeText(context, "Come on, \nThis is a NOT a goat", Toast.LENGTH_SHORT).show(); } } }); } else { //lotsOfObjects is true //let's create new views every interaction //hahahahah TextView rowTxt = (TextView) rowView.findViewById(R.id.textView); ImageView rowImg = (ImageView) rowView.findViewById(R.id.imageView); CheckBox rowCheckWaste = (CheckBox) rowView.findViewById(R.id.checkBox); //look a bunch of redundant objects created during rendering. How silly :) if (fibonacciBool) { //confusion and delay -take the position, add 4, multiply by another number to (a BIG number) //find that member of the fibonacci sequence using recursion (which is slow) int bigNumberWaste; if (position == 5) { bigNumberWaste = (position + 8) * 3;//will cause a jink scrolling up //}else if (position == 10) { // bigNumberWaste = (position+3)*3;//will pause scrolling down } else { bigNumberWaste = (position + 4) * 2; } int fibValue = fibonacci.fib(bigNumberWaste); //wasted time! rowTxt.setText(goatNames[position] + "\nDelay Fibonacci #: " + fibValue); } else {//no crazy slowdown. rowTxt.setText(goatNames[position]); } rowImg.setImageResource((goatPix[position])); rowCheckWaste.setChecked(goatTrue[position]); rowCheckWaste.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //add a new variable for the checkbox CheckBox checkedBox = (CheckBox) v; //this all has to be inverse. If the user checks the box - it WAS unchecked if (!checkedBox.isChecked()) { //button WAS checked. User unchecked it //goat checkedBox.setChecked(true); Toast.makeText(context, "Correct! \nThis is a goat", Toast.LENGTH_SHORT).show(); } else { //button was not checked, and user checked it //not a goat checkedBox.setChecked(false); Toast.makeText(context, "Come on, \nThis is a NOT a goat", Toast.LENGTH_SHORT).show(); } } }); } return rowView; } }
import java.io.*; import java.util.*; public class Main{ public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String exp = br.readLine(); //System.out.println(exp); System.out.println(infixEval(exp)); // code } public static int infixEval(String exp){ Stack<Integer> operands = new Stack<>(); Stack<Character> operators = new Stack<>(); for(int i=0; i< exp.length(); i++){ char ch = exp.charAt(i); if((ch >= '0' && ch <= '9')){ operands.push(ch - '0'); }else if(ch == '('){ operators.push(ch); }else if(ch == ')'){ while(operators.peek() != '('){ char optr = operators.pop(); int num2 = operands.pop(); int num1 = operands.pop(); int ans = solve(optr, num1, num2); operands.push(ans); } operators.pop(); }else if(ch== '+' || ch== '*' || ch=='/' || ch=='-'){ while(operators.size()!=0 && operators.peek()!='(' && precedence(ch) <= precedence(operators.peek())){ char optr = operators.pop(); int num2 = operands.pop(); int num1 = operands.pop(); int ans = solve(optr, num1, num2); operands.push(ans); } operators.push(ch); } } while(operators.size() != 0){ char optr = operators.pop(); int num2 = operands.pop(); int num1 = operands.pop(); int ans = solve(optr, num1, num2); operands.push(ans); } return operands.peek(); } public static int precedence(char ch){ if(ch == '*' || ch == '/'){ return 2; }else{ return 1; } } public static int solve(char op, int num1, int num2){ if(op == '*'){ return num1 * num2; }else if(op == '+'){ return num1 + num2; }else if(op == '/'){ return num1 / num2; }else{ return num1 - num2; } } }
package com.liyang.category.action; import com.liyang.category.entity.Category; import com.liyang.category.service.CategoryService; import com.liyang.commons.Page; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; /* *@author:李洋 *@date:2019/7/29 15:05 */ public class CategoryAction { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } private Page<Category> page; public Page<Category> getPage() { return page; } private Map<String,Object> map; public Map<String, Object> getMap() { return map; } public void setMap(Map<String, Object> map) { this.map = map; } public void setPage(Page<Category> page) { this.page = page; } public String addCategory(){ CategoryService cs = new CategoryService(); Category ca = new Category(); ca.setId(UUID.randomUUID().toString().replaceAll("-","")); ca.setName(name); cs.addCategory(ca); return "addSuccess"; } public String queryCategory(){ CategoryService cs = new CategoryService(); List<Category> data = cs.queryCategory(name); map = new HashMap<>(); map.put("cate",data); return "querySimpleSuccess"; } private int pageNumber; private int pageSize; public int getPageNumber() { return pageNumber; } public void setPageNumber(int pageNumber) { this.pageNumber = pageNumber; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public String querySomeCategory(){ CategoryService gs = new CategoryService(); page = new Page<>(); page.setPageNumber(pageNumber); page.setPageSize(pageSize); page.setTotal(gs.queryCount()); page.setRows(gs.querySomeCategory(page.getStart(),pageSize)); return "querySuccess"; } public String queryAllCategory(){ CategoryService gs = new CategoryService(); map = new HashMap<>(); map.put("cate",gs.queryAllCategory()); return "querySimpleSuccess"; } }
package br.com.zup.kafka.util; import org.apache.commons.lang3.StringUtils; import java.util.Collection; public final class Assert { private Assert() {} public static void notNull(Object object, String message) { if (object == null) { throw new IllegalArgumentException(message); } } public static void notNull(Object object) { notNull(object, "[Assertion failed] - this argument is required; it must not be null"); } public static void notNull(Object... objects) { for (Object o : objects) { notNull(o); } } public static void notEmpty(String string, String message) { if (StringUtils.isBlank(string)) { throw new IllegalArgumentException(message); } } public static void notEmpty(String string) { notEmpty(string, "[Assertion failed] - this String argument must have text; it must not be null, empty, or blank"); } public static void notEmpty(Collection<?> collection, String message) { if (collection == null || collection.isEmpty()) { throw new IllegalArgumentException(message); } } public static void notEmpty(Collection<?> collection) { notEmpty(collection, "[Assertion failed] - this Collection argument must not be empty"); } public static void greaterThan(Number number, Number minValue, String message) { if (number.longValue() <= minValue.longValue()) { throw new IllegalArgumentException(message); } } public static void greaterThan(Number number, Number minValue) { greaterThan(number, minValue, "[Assertion failed] - this number argument must greater than a min value"); } public static void greaterThanZero(Number... numbers) { for (Number n : numbers) { greaterThan(n, 0, "[Assertion failed] - this number argument must greater than zero"); } } public static void assertFalse(boolean assertion, String message) { if (assertion) { throw new IllegalArgumentException("[Assertion failed] - " + message); } } public static void assertTrue(boolean assertion, String message) { if (!assertion) { throw new IllegalArgumentException("[Assertion failed] - " + message); } } }
package com.beike.dao.trx.partner; import com.beike.entity.partner.PartnerReqId; /** * @ClassName: PartnerReqIdDao * @Description: TODO * @author yurenli * @date 2012-7-12 下午06:41:00 * @version V1.0 */ public interface PartnerReqIdDao { /** * @param partnerNo * @param requestId * @return */ public PartnerReqId findByPNoAndReqId(String partnerNo,String requestId); /** * @param partnerReqId */ public void addPartnerReqId(PartnerReqId partnerReqId) ; }
/* * Copyright © 2018 www.noark.xyz All Rights Reserved. * * 感谢您选择Noark框架,希望我们的努力能为您提供一个简单、易用、稳定的服务器端框架 ! * 除非符合Noark许可协议,否则不得使用该文件,您可以下载许可协议文件: * * http://www.noark.xyz/LICENSE * * 1.未经许可,任何公司及个人不得以任何方式或理由对本框架进行修改、使用和传播; * 2.禁止在本项目或任何子项目的基础上发展任何派生版本、修改版本或第三方版本; * 3.无论你对源代码做出任何修改和改进,版权都归Noark研发团队所有,我们保留所有权利; * 4.凡侵犯Noark版权等知识产权的,必依法追究其法律责任,特此郑重法律声明! */ package xyz.noark.log.pattern; import java.util.Objects; /** * 格式化信息 * * @author 小流氓[176543888@qq.com] * @since 3.4.3 */ final class FormattingInfo { private static final char[] SPACES = new char[]{' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '}; private static final FormattingInfo DEFAULT = new FormattingInfo(false, 0); /** * 最小长度 */ private final int minLength; /** * 左对齐 */ private final boolean leftAlign; private FormattingInfo(final boolean leftAlign, final int minLength) { this.leftAlign = leftAlign; this.minLength = minLength; } public static FormattingInfo getDefault() { return DEFAULT; } public static FormattingInfo getOrDefault(boolean leftAlign, int minLength) { if (leftAlign == DEFAULT.leftAlign && minLength == DEFAULT.minLength) { return DEFAULT; } else { return new FormattingInfo(leftAlign, minLength); } } /** * 根据指定的长度和对齐方式调整缓冲区的内容 * * @param startIndex 缓冲区起始位置 * @param buffer 缓冲区 */ public void format(final int startIndex, final StringBuilder buffer) { final int rawLength = buffer.length() - startIndex; if (rawLength < minLength) { if (leftAlign) { final int fieldEnd = buffer.length(); buffer.setLength(startIndex + minLength); for (int i = fieldEnd; i < buffer.length(); i++) { buffer.setCharAt(i, ' '); } } else { int padLength = minLength - rawLength; final char[] paddingArray = SPACES; for (; padLength > paddingArray.length; padLength -= paddingArray.length) { buffer.insert(startIndex, paddingArray); } buffer.insert(startIndex, paddingArray, 0, padLength); } } } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof FormattingInfo)) { return false; } FormattingInfo that = (FormattingInfo) o; return minLength == that.minLength && leftAlign == that.leftAlign; } @Override public int hashCode() { return Objects.hash(minLength, leftAlign); } @Override public String toString() { return "FormattingInfo" + "[leftAlign=" + leftAlign + ", minLength=" + minLength + ']'; } }
package com.stackroute.pe5; import java.util.HashMap; import java.util.Map; /* * Write a program where an array of strings is input and output is a Map<String,boolean> where * each different string is a key and its value is true if that string appears 2 or more times in the array. */ public class MapStrings { /* * this function checks for the number of occurrence of a string and returns the required boolean values along with * the string in a hash map. */ public Map<String,Boolean> mapperS(String[] S_in){ Map M_out = new HashMap(); for(String ss: S_in){ if(!M_out.containsKey(ss)){ M_out.put(ss,false); } else { M_out.put(ss,true); } } return M_out; } }
package com.metoo.module.app.manage.buyer.tool; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.metoo.foundation.domain.User; import com.metoo.foundation.service.ISysConfigService; @Component public class AppUserTools { @Autowired private ISysConfigService configService; public List get(List<User> users) { if (users.size() > 0) { List<Map> list = new ArrayList<Map>(); for (User user : users) { Map map = new HashMap(); map.put("user_id", user.getId()); map.put("user_name", user.getUserName()); map.put("user_email", user.getEmail()); map.put("user_sex", user.getSex()); if (user.getSex() == -1) { map.put("user_photo", this.configService.getSysConfig().getImageWebServer() + "/" + "resources" + "/" + "style" + "/" + "common" + "/" + "images" + "/" + "member.png"); } if (user.getSex() == 0) { map.put("user_photo", this.configService.getSysConfig().getImageWebServer() + "/" + "resources" + "/" + "style" + "/" + "common" + "/" + "images" + "/" + "member0.png"); } if (user.getSex() == 1) { map.put("user_photo", this.configService.getSysConfig().getImageWebServer() + "/" + "resources" + "/" + "style" + "/" + "common" + "/" + "images" + "/" + "member1.png"); } list.add(map); } return list; } return null; } public Map<String, Object> get(User user) { if (user != null) { Map<String, Object> map = new HashMap<String, Object>(); map.put("friend_id", user.getId()); map.put("user_name", user.getUserName()); map.put("user_email", user.getEmail()); map.put("user_sex", user.getSex()); if (user.getSex() == -1) { map.put("user_photo", this.configService.getSysConfig().getImageWebServer() + "/" + "resources" + "/" + "style" + "/" + "common" + "/" + "images" + "/" + "member.png"); } if (user.getSex() == 0) { map.put("user_photo", this.configService.getSysConfig().getImageWebServer() + "/" + "resources" + "/" + "style" + "/" + "common" + "/" + "images" + "/" + "member0.png"); } if (user.getSex() == 1) { map.put("user_photo", this.configService.getSysConfig().getImageWebServer() + "/" + "resources" + "/" + "style" + "/" + "common" + "/" + "images" + "/" + "member1.png"); } return map; } return null; } }
package com.feng.stream; import org.junit.Test; import java.util.List; import java.util.stream.Stream; public class StreamTest2 { @Test public void test1(){ List<Employee> employees = EmployeeData.getEmployees(); Stream<Employee> stream = employees.stream(); /* stream.filter(e -> e.getAge()>18).forEach(System.out::println); System.out.println("---------------"); employees.stream().limit(2).forEach(System.out::println); System.out.println("----------------"); employees.stream().skip(3).forEach(System.out::println); System.out.println("----------------");*/ employees.stream().distinct().forEach(System.out::println); } }
package com.example.zeal.greendaodemo; import android.app.Application; import org.litepal.LitePal; import org.litepal.LitePalApplication; /** * Created by liaowj on 2017/4/11. */ public class App extends LitePalApplication { /** A flag to show how easily you can switch from standard SQLite to the encrypted SQLCipher. */ public static final boolean ENCRYPTED = true; @Override public void onCreate() { super.onCreate(); LitePal.initialize(this); } }
package cshekhar.springboot.model; import org.bson.types.ObjectId; import org.mongodb.morphia.annotations.Entity; import org.mongodb.morphia.annotations.Indexed; import org.mongodb.morphia.annotations.Property; import org.mongodb.morphia.utils.IndexDirection; import org.springframework.data.annotation.Id; /** * Created by cshekhar on 7/5/17. */ @Entity("metrics") public class Metric { @Property("timeStamp") @Indexed(value= IndexDirection.ASC) private long timeStamp; public long getTimeStamp() { return timeStamp; } public void setTimeStamp(long timeStamp) { this.timeStamp = timeStamp; } @Property("value") private int value; public int getValue() { return value; } public void setValue(int value) { this.value = value; } @Override public String toString() { return "Metric [TimeStamp = " + timeStamp + ", " + "Value = " + value + "]"; } }
package com.legaoyi.protocol.upstream.messagebody; import java.util.List; import java.util.Map; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import com.fasterxml.jackson.annotation.JsonProperty; import com.legaoyi.protocol.message.MessageBody; /** * 采集记录仪状态信号配置信息(06H) * * @author <a href="mailto:shengbo.gao@gmail.com;78772895@qq.com">gaoshengbo</a> * @version 1.0.0 * @since 2019-05-20 */ @Scope("prototype") @Component(MessageBody.MESSAGE_BODY_BEAN_PREFIX + "0700_06H_2019" + MessageBody.MESSAGE_BODY_BEAN_SUFFIX) public class Jt808_2019_0700_06H_MessageBody extends Jt808_2019_0700_MessageBody { private static final long serialVersionUID = 3967333775572778460L; /** 记录仪当前时间 **/ @JsonProperty("realTime") private String realTime; /** 状态信号配置信息 **/ @JsonProperty("signal") private List<Map<String, Object>> signal; public final String getRealTime() { return realTime; } public final void setRealTime(String realTime) { this.realTime = realTime; } public final List<Map<String, Object>> getSignal() { return signal; } public final void setSignal(List<Map<String, Object>> signal) { this.signal = signal; } }
package com.dalmirdasilva.androidmessagingprotocol.device.message; import java.util.ArrayList; import java.util.List; public class DataMessage extends Message { public DataMessage() { super(Message.TYPE_DATA); } public DataMessage(Byte[] payload) { this(); this.payload = payload; } }
package com.v1_4.mydiaryapp.com; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONObject; import android.app.Dialog; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.Button; import android.widget.ImageButton; import android.widget.ListView; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; public class Screen_RSSReader extends Act_ActivityBase { public DownloadThread downloadThread; public ListView myListView; public ArrayList<Obj_RSSStory> menuItems; public Adapter_RSSStory menuItemAdapter; public int selectedIndex; //onCreate public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.act_global_list); //activity name thisActivityName = "Screen_RSSReader"; //remote command remoteDataCommand = "rssFeedViewController"; //appDelegate holds current screen this.appDelegate = (AppDelegate) this.getApplication(); appGuid = appDelegate.currentApp.guid; appApiKey = appDelegate.currentApp.apiKey; screenGuid = appDelegate.currentScreen.screenGuid; saveAsFileName = appDelegate.currentScreen.screenGuid + "_rssFeed.txt"; //back button.. ImageButton btnBack = (ImageButton) findViewById(R.id.btnBack); btnBack.setOnClickListener(new OnClickListener() { public void onClick(View v) { finish(); } }); //info button.. ImageButton btnInfo = (ImageButton) findViewById(R.id.btnInfo); btnInfo.setOnClickListener(new OnClickListener() { public void onClick(View v) { showInfo(); } }); //title ((TextView)findViewById(R.id.myTitle)).setText(appDelegate.currentScreen.screenTitle); //init selected index selectedIndex = -1; //list view myListView = (ListView)findViewById(R.id.myList); //array of items menuItems = new ArrayList<Obj_RSSStory>(); //setup data adapter int resID = R.layout.list_rss_style_1; menuItemAdapter = new Adapter_RSSStory(this, resID, menuItems); myListView.setAdapter(menuItemAdapter); } //onStart @Override protected void onStart() { super.onStart(); //local or remote JSON text... if(appDelegate.fileExists(saveAsFileName)){ Log.i("ZZ", thisActivityName + ":onStart local data exists"); JSONData = appDelegate.getLocalText(saveAsFileName); parseData(JSONData); }else{ //parse called after when done Log.i("ZZ", thisActivityName + ":onStart downloading data"); downloadData(); } } //onStop @Override protected void onStop(){ super.onStop(); if(downloadThread != null){ boolean retry = true; downloadThread.setThreadRunning(false); while(retry){ try{ downloadThread.join(); retry = false; }catch (Exception je){ Log.i("ZZ", thisActivityName + ":onStop ERROR: " + je.getMessage()); } } } } //download data public void downloadData(){ //show progress showProgress("Loading...", "We'll save this to speed things up for next time."); //appDelegate.currentScreen.jsonScreenOptions holds variables for RSS feed try{ JSONObject raw = new JSONObject(appDelegate.currentScreen.jsonScreenOptions); //build URL String tmpURL = raw.getString("url"); tmpURL += "?appGuid=" + appGuid; tmpURL += "&appApiKey=" + appApiKey; tmpURL += "&screenGuid=" + screenGuid; tmpURL += "&command=" + remoteDataCommand; downloadThread = new DownloadThread(); downloadThread.setDownloadURL(tmpURL); downloadThread.setSaveAsFileName(saveAsFileName); downloadThread.setDownloadType("text"); downloadThread.setThreadRunning(true); downloadThread.start(); }catch (Exception je){ hideProgress(); showAlert("Download Error", "The data returned by the RSS Feed URL is not well formed."); Log.i("ZZ", thisActivityName + ":downloadData appDelegate.currentScreen.jsonScreenOptions is not well formed"); } } //parse data.. public void parseData(String theJSONString){ //parse JSON string //Log.i("ZZ", thisActivityName + ":parseData: " + theJSONString); //empty list view data adapter menuItemAdapter.clear(); myListView.invalidate(); try{ //empty data if previously filled... menuItems.clear(); //create json objects from data string... JSONObject raw = new JSONObject(theJSONString); JSONObject results = raw.getJSONObject("results"); JSONArray stories = results.getJSONArray("stories"); //loop int i = 0; for (i = 0; i < stories.length(); i++){ JSONObject tmpJson = stories.getJSONObject(i); //RSS Story Obj_RSSStory tmpItem = new Obj_RSSStory(); tmpItem.setTitle(tmpJson.getString("title")); tmpItem.setLink(tmpJson.getString("link")); tmpItem.setDescription(tmpJson.getString("description")); menuItems.add(i, tmpItem); }//end for //setup data adapter int resID = R.layout.list_rss_style_1; menuItemAdapter = new Adapter_RSSStory(this, resID, menuItems); myListView.setAdapter(menuItemAdapter); //setup list click listener final OnItemClickListener listItemClickHandler = new OnItemClickListener() { public void onItemClick(AdapterView parent, View v, int position, long id){ //clicked item Obj_RSSStory tmpStory = (Obj_RSSStory) menuItems.get(position); if(tmpStory.getLink().length() > 1){ //create an Obj_Screen from RSSStory data.. Obj_Screen tmpItem = new Obj_Screen("0000", "0000"); tmpItem.setScreenType("screen_url"); tmpItem.setScreenTitle(tmpStory.title); //create JSON from RSSStory data String tmpKeys = "{"; tmpKeys += "\"title\":\"" + tmpStory.title + "\","; tmpKeys += "\"url\":\"" + tmpStory.link + "\""; tmpKeys += "}"; tmpItem.setJsonScreenOptions(tmpKeys); //remember selected index to select this row on resume... selectedIndex = position; //fire menuClick (method in Act_ActivityBase) to launch Screen_CustomURL menuTap(tmpItem); }else{ showAlert("No URL?", "This RSS Story does not have a URL associated with it?"); } } }; myListView.setOnItemClickListener(listItemClickHandler); }catch (Exception je){ //showAlert("Data Format Error", "There was a problem reading data associated with this app."); } //hide progress hideProgress(); } ///////////////////////////////////////////////////// //done downloading data.. Handler downloadTextHandler = new Handler(){ @Override public void handleMessage(Message msg){ if(JSONData.length() < 1){ hideProgress(); showAlert("Error Downloading", "Please check your internet connection then try again."); }else{ parseData(JSONData); } } }; //download class in new thread / class public class DownloadThread extends Thread{ boolean threadRunning = false; String downloadURL = ""; String saveAsFileName = ""; String downloadType = ""; void setThreadRunning(boolean bolRunning){ threadRunning = bolRunning; } void setDownloadURL(String theURL){ downloadURL = theURL; } void setSaveAsFileName(String theFileName){ saveAsFileName = theFileName; } void setDownloadType(String imageOrText){ downloadType = imageOrText; } @Override public void run(){ if(downloadType == "text"){ JSONData = appDelegate.downloadText(downloadURL); appDelegate.saveText(saveAsFileName, JSONData); downloadTextHandler.sendMessage(downloadTextHandler.obtainMessage()); this.setThreadRunning(false); } } } ///////////////////////////////////////////////////// //options menu @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); //set up dialog final Dialog dialog = new Dialog(this); dialog.setContentView(R.layout.menu_refresh); dialog.setTitle("Screen Options"); //refresh .. Button btnRefresh = (Button) dialog.findViewById(R.id.btnRefresh); btnRefresh.setOnClickListener(new OnClickListener() { public void onClick(View v) { dialog.cancel(); downloadData(); } }); //cancel... Button button = (Button) dialog.findViewById(R.id.btnCancel); button.setOnClickListener(new OnClickListener(){ public void onClick(View v) { dialog.cancel(); } }); //show dialog.show(); return true; } //end menu ///////////////////////////////////////////////////// }
package test; public class Wrapper { private String v; @Override public String toString() { return v; } public static Wrapper of(String v) { Wrapper w = new Wrapper(); w.v = v; return w; } }
import cutter.THULACCutter; import org.apache.lucene.analysis.*; import org.apache.lucene.analysis.standard.StandardFilter; import org.apache.lucene.analysis.standard.StandardTokenizer; import token.CutterTokenizer; import token.SemanticExpandFilter; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import java.io.IOException; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; import java.util.List; public class NIR { private int TOPK = 3; private List<String> DISPLAYED_FIELDS = Arrays.asList("题名", "作者", "摘要", "单位"); private List<Document> lastQueryResult = new ArrayList<>(); private Searcher searcher; public NIR(Searcher searcher) { this.searcher = searcher; } private void cli() { Scanner input = new Scanner(System.in); System.out.print(">>"); while (input.hasNext()) { String line = input.nextLine(); if (line.startsWith("SET_TOP_K")) set_top_k(line); else if (line.startsWith("SET_DISPLAYED_FIELDS")) set_displayed_fields(line); else if (line.equalsIgnoreCase("QUIT")) break; else query(line); System.out.print(">>"); } } private void set_top_k(String line) { Scanner scanner = new Scanner(line); scanner.next("SET_TOP_K"); int top_k = scanner.nextInt(); System.out.println("Set new k:" + top_k); this.TOPK = top_k; } private void set_displayed_fields(String line) { Scanner scanner = new Scanner(line); scanner.next("SET_DISPLAYED_FIELDS"); List<String> displayed_fields = new ArrayList<>(); while (scanner.hasNext("\\S+")) { displayed_fields.add(scanner.next("\\S+")); } System.out.println("Set new displayed fields:" + displayed_fields); this.DISPLAYED_FIELDS = displayed_fields; } private void query(String line) { List<Document> documents = this.searcher.search(line, this.TOPK); for (Document document : documents) { System.out.println("{"); for (String field_name: this.DISPLAYED_FIELDS) { try { System.out.println("\t" + field_name + ":" + document.getField(field_name).stringValue()); } catch (NullPointerException e) { System.out.println("\t" + field_name + " not found."); } } System.out.println("}"); } } public static void main (String[] argv) throws IOException { // Directory directory = new RAMDirectory(); Analyzer basic_analyzer = new StandardAnalyzer(); Analyzer analyzer = new Analyzer() { @Override protected TokenStreamComponents createComponents(String s) { Tokenizer src = new CutterTokenizer(new THULACCutter()); // Tokenizer src = new StandardTokenizer(); TokenStream tok = new StandardFilter(src); tok = new LowerCaseFilter(tok); tok = new SemanticExpandFilter(tok); return new TokenStreamComponents(src, tok); } }; Directory directory = FSDirectory.open(Paths.get("index")); new IndexBuilder("data/CNKI_journal_v2.txt", directory, analyzer); Searcher searcher = new Searcher(directory, analyzer); new NIR(searcher).cli(); try { searcher.close(); directory.close(); } catch (IOException e) { e.printStackTrace(System.err); } } }
/* * 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 latihanmethodprosedur; /** * * @author ARIEN */ import javax.swing.JOptionPane; public class LatihanMethodProsedur { public static void main(String[] argas) { String nilai1String, nilai2String; int nilai1Int, nilai2Int; nilai1String = JOptionPane.showInputDialog("Masukan Bilangan Pertama : "); nilai1Int = Integer.parseInt(nilai1String); nilai2String = JOptionPane.showInputDialog("Masukan Bilangan Kedua : "); nilai2Int = Integer.parseInt(nilai2String); //memanggil method prosedur penjumlahan perkalian(nilai1Int, nilai2Int); } public static void perkalian(int nilaiPadaParameter1, int nilaiPadaParameter2) { int hasil = 0; hasil = nilaiPadaParameter1 * nilaiPadaParameter2; System.out.println("Hasil perkalian : " + hasil); } }
/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cglib.core; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.invoke.MethodHandles; import java.lang.reflect.Constructor; import java.lang.reflect.InaccessibleObjectException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.security.ProtectionDomain; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.BiConsumer; import java.util.function.Consumer; import org.springframework.asm.Type; /** * @version $Id: ReflectUtils.java,v 1.30 2009/01/11 19:47:49 herbyderby Exp $ */ @SuppressWarnings({"rawtypes", "unchecked"}) public class ReflectUtils { private ReflectUtils() { } private static final Map primitives = new HashMap(8); private static final Map transforms = new HashMap(8); private static final ClassLoader defaultLoader = ReflectUtils.class.getClassLoader(); private static final Method classLoaderDefineClassMethod; private static final Throwable THROWABLE; private static final ProtectionDomain PROTECTION_DOMAIN; private static final List<Method> OBJECT_METHODS = new ArrayList<>(); private static BiConsumer<String, byte[]> generatedClassHandler; private static Consumer<Class<?>> loadedClassHandler; // SPRING PATCH BEGIN static { // Resolve protected ClassLoader.defineClass method for fallback use // (even if JDK 9+ Lookup.defineClass is preferably used below) Method classLoaderDefineClass; Throwable throwable = null; try { classLoaderDefineClass = ClassLoader.class.getDeclaredMethod("defineClass", String.class, byte[].class, Integer.TYPE, Integer.TYPE, ProtectionDomain.class); } catch (Throwable t) { classLoaderDefineClass = null; throwable = t; } classLoaderDefineClassMethod = classLoaderDefineClass; THROWABLE = throwable; PROTECTION_DOMAIN = getProtectionDomain(ReflectUtils.class); for (Method method : Object.class.getDeclaredMethods()) { if ("finalize".equals(method.getName()) || (method.getModifiers() & (Modifier.FINAL | Modifier.STATIC)) > 0) { continue; } OBJECT_METHODS.add(method); } } // SPRING PATCH END private static final String[] CGLIB_PACKAGES = {"java.lang"}; static { primitives.put("byte", Byte.TYPE); primitives.put("char", Character.TYPE); primitives.put("double", Double.TYPE); primitives.put("float", Float.TYPE); primitives.put("int", Integer.TYPE); primitives.put("long", Long.TYPE); primitives.put("short", Short.TYPE); primitives.put("boolean", Boolean.TYPE); transforms.put("byte", "B"); transforms.put("char", "C"); transforms.put("double", "D"); transforms.put("float", "F"); transforms.put("int", "I"); transforms.put("long", "J"); transforms.put("short", "S"); transforms.put("boolean", "Z"); } public static ProtectionDomain getProtectionDomain(final Class source) { if (source == null) { return null; } return source.getProtectionDomain(); } public static Type[] getExceptionTypes(Member member) { if (member instanceof Method method) { return TypeUtils.getTypes(method.getExceptionTypes()); } else if (member instanceof Constructor<?> constructor) { return TypeUtils.getTypes(constructor.getExceptionTypes()); } else { throw new IllegalArgumentException("Cannot get exception types of a field"); } } public static Signature getSignature(Member member) { if (member instanceof Method method) { return new Signature(member.getName(), Type.getMethodDescriptor(method)); } else if (member instanceof Constructor<?> constructor) { Type[] types = TypeUtils.getTypes(constructor.getParameterTypes()); return new Signature(Constants.CONSTRUCTOR_NAME, Type.getMethodDescriptor(Type.VOID_TYPE, types)); } else { throw new IllegalArgumentException("Cannot get signature of a field"); } } public static Constructor findConstructor(String desc) { return findConstructor(desc, defaultLoader); } public static Constructor findConstructor(String desc, ClassLoader loader) { try { int lparen = desc.indexOf('('); String className = desc.substring(0, lparen).trim(); return getClass(className, loader).getConstructor(parseTypes(desc, loader)); } catch (ClassNotFoundException | NoSuchMethodException ex) { throw new CodeGenerationException(ex); } } public static Method findMethod(String desc) { return findMethod(desc, defaultLoader); } public static Method findMethod(String desc, ClassLoader loader) { try { int lparen = desc.indexOf('('); int dot = desc.lastIndexOf('.', lparen); String className = desc.substring(0, dot).trim(); String methodName = desc.substring(dot + 1, lparen).trim(); return getClass(className, loader).getDeclaredMethod(methodName, parseTypes(desc, loader)); } catch (ClassNotFoundException | NoSuchMethodException ex) { throw new CodeGenerationException(ex); } } private static Class[] parseTypes(String desc, ClassLoader loader) throws ClassNotFoundException { int lparen = desc.indexOf('('); int rparen = desc.indexOf(')', lparen); List params = new ArrayList(); int start = lparen + 1; for (; ; ) { int comma = desc.indexOf(',', start); if (comma < 0) { break; } params.add(desc.substring(start, comma).trim()); start = comma + 1; } if (start < rparen) { params.add(desc.substring(start, rparen).trim()); } Class[] types = new Class[params.size()]; for (int i = 0; i < types.length; i++) { types[i] = getClass((String) params.get(i), loader); } return types; } private static Class getClass(String className, ClassLoader loader) throws ClassNotFoundException { return getClass(className, loader, CGLIB_PACKAGES); } private static Class getClass(String className, ClassLoader loader, String[] packages) throws ClassNotFoundException { String save = className; int dimensions = 0; int index = 0; while ((index = className.indexOf("[]", index) + 1) > 0) { dimensions++; } StringBuilder brackets = new StringBuilder(className.length() - dimensions); for (int i = 0; i < dimensions; i++) { brackets.append('['); } className = className.substring(0, className.length() - 2 * dimensions); String prefix = (dimensions > 0) ? brackets + "L" : ""; String suffix = (dimensions > 0) ? ";" : ""; try { return Class.forName(prefix + className + suffix, false, loader); } catch (ClassNotFoundException ignore) { } for (String pkg : packages) { try { return Class.forName(prefix + pkg + '.' + className + suffix, false, loader); } catch (ClassNotFoundException ignore) { } } if (dimensions == 0) { Class c = (Class) primitives.get(className); if (c != null) { return c; } } else { String transform = (String) transforms.get(className); if (transform != null) { try { return Class.forName(brackets + transform, false, loader); } catch (ClassNotFoundException ignore) { } } } throw new ClassNotFoundException(save); } public static Object newInstance(Class type) { return newInstance(type, Constants.EMPTY_CLASS_ARRAY, null); } public static Object newInstance(Class type, Class[] parameterTypes, Object[] args) { return newInstance(getConstructor(type, parameterTypes), args); } @SuppressWarnings("deprecation") public static Object newInstance(final Constructor cstruct, final Object[] args) { boolean flag = cstruct.isAccessible(); try { if (!flag) { cstruct.setAccessible(true); } Object result = cstruct.newInstance(args); return result; } catch (InstantiationException | IllegalAccessException e) { throw new CodeGenerationException(e); } catch (InvocationTargetException e) { throw new CodeGenerationException(e.getTargetException()); } finally { if (!flag) { cstruct.setAccessible(flag); } } } public static Constructor getConstructor(Class type, Class[] parameterTypes) { try { Constructor constructor = type.getDeclaredConstructor(parameterTypes); constructor.setAccessible(true); return constructor; } catch (NoSuchMethodException e) { throw new CodeGenerationException(e); } } public static String[] getNames(Class[] classes) { if (classes == null) { return null; } String[] names = new String[classes.length]; for (int i = 0; i < names.length; i++) { names[i] = classes[i].getName(); } return names; } public static Class[] getClasses(Object[] objects) { Class[] classes = new Class[objects.length]; for (int i = 0; i < objects.length; i++) { classes[i] = objects[i].getClass(); } return classes; } public static Method findNewInstance(Class iface) { Method m = findInterfaceMethod(iface); if (!m.getName().equals("newInstance")) { throw new IllegalArgumentException(iface + " missing newInstance method"); } return m; } public static Method[] getPropertyMethods(PropertyDescriptor[] properties, boolean read, boolean write) { Set methods = new HashSet(); for (PropertyDescriptor pd : properties) { if (read) { methods.add(pd.getReadMethod()); } if (write) { methods.add(pd.getWriteMethod()); } } methods.remove(null); return (Method[]) methods.toArray(new Method[methods.size()]); } public static PropertyDescriptor[] getBeanProperties(Class type) { return getPropertiesHelper(type, true, true); } public static PropertyDescriptor[] getBeanGetters(Class type) { return getPropertiesHelper(type, true, false); } public static PropertyDescriptor[] getBeanSetters(Class type) { return getPropertiesHelper(type, false, true); } private static PropertyDescriptor[] getPropertiesHelper(Class type, boolean read, boolean write) { try { BeanInfo info = Introspector.getBeanInfo(type, Object.class); PropertyDescriptor[] all = info.getPropertyDescriptors(); if (read && write) { return all; } List properties = new ArrayList(all.length); for (PropertyDescriptor pd : all) { if ((read && pd.getReadMethod() != null) || (write && pd.getWriteMethod() != null)) { properties.add(pd); } } return (PropertyDescriptor[]) properties.toArray(new PropertyDescriptor[properties.size()]); } catch (IntrospectionException e) { throw new CodeGenerationException(e); } } public static Method findDeclaredMethod(final Class type, final String methodName, final Class[] parameterTypes) throws NoSuchMethodException { Class cl = type; while (cl != null) { try { return cl.getDeclaredMethod(methodName, parameterTypes); } catch (NoSuchMethodException e) { cl = cl.getSuperclass(); } } throw new NoSuchMethodException(methodName); } public static List addAllMethods(final Class type, final List list) { if (type == Object.class) { list.addAll(OBJECT_METHODS); } else { list.addAll(java.util.Arrays.asList(type.getDeclaredMethods())); } Class superclass = type.getSuperclass(); if (superclass != null) { addAllMethods(superclass, list); } Class[] interfaces = type.getInterfaces(); for (Class element : interfaces) { addAllMethods(element, list); } return list; } public static List addAllInterfaces(Class type, List list) { Class superclass = type.getSuperclass(); if (superclass != null) { list.addAll(Arrays.asList(type.getInterfaces())); addAllInterfaces(superclass, list); } return list; } public static Method findInterfaceMethod(Class iface) { if (!iface.isInterface()) { throw new IllegalArgumentException(iface + " is not an interface"); } Method[] methods = iface.getDeclaredMethods(); if (methods.length != 1) { throw new IllegalArgumentException("expecting exactly 1 method in " + iface); } return methods[0]; } // SPRING PATCH BEGIN public static void setGeneratedClassHandler(BiConsumer<String, byte[]> handler) { generatedClassHandler = handler; } public static Class defineClass(String className, byte[] b, ClassLoader loader) throws Exception { return defineClass(className, b, loader, null, null); } public static Class defineClass(String className, byte[] b, ClassLoader loader, ProtectionDomain protectionDomain) throws Exception { return defineClass(className, b, loader, protectionDomain, null); } @SuppressWarnings({"deprecation", "serial"}) public static Class defineClass(String className, byte[] b, ClassLoader loader, ProtectionDomain protectionDomain, Class<?> contextClass) throws Exception { Class c = null; Throwable t = THROWABLE; BiConsumer<String, byte[]> handlerToUse = generatedClassHandler; if (handlerToUse != null) { handlerToUse.accept(className, b); } // Preferred option: JDK 9+ Lookup.defineClass API if ClassLoader matches if (contextClass != null && contextClass.getClassLoader() == loader) { try { MethodHandles.Lookup lookup = MethodHandles.privateLookupIn(contextClass, MethodHandles.lookup()); c = lookup.defineClass(b); } catch (LinkageError | IllegalArgumentException ex) { // in case of plain LinkageError (class already defined) // or IllegalArgumentException (class in different package): // fall through to traditional ClassLoader.defineClass below t = ex; } catch (Throwable ex) { throw new CodeGenerationException(ex); } } // Direct defineClass attempt on the target Classloader if (c == null) { if (protectionDomain == null) { protectionDomain = PROTECTION_DOMAIN; } // Look for publicDefineClass(String name, byte[] b, ProtectionDomain protectionDomain) try { Method publicDefineClass = loader.getClass().getMethod( "publicDefineClass", String.class, byte[].class, ProtectionDomain.class); c = (Class) publicDefineClass.invoke(loader, className, b, protectionDomain); } catch (InvocationTargetException ex) { if (!(ex.getTargetException() instanceof UnsupportedOperationException)) { throw new CodeGenerationException(ex.getTargetException()); } // in case of UnsupportedOperationException, fall through t = ex.getTargetException(); } catch (Throwable ex) { // publicDefineClass method not available -> fall through t = ex; } // Classic option: protected ClassLoader.defineClass method if (c == null && classLoaderDefineClassMethod != null) { Object[] args = new Object[]{className, b, 0, b.length, protectionDomain}; try { if (!classLoaderDefineClassMethod.isAccessible()) { classLoaderDefineClassMethod.setAccessible(true); } c = (Class) classLoaderDefineClassMethod.invoke(loader, args); } catch (InvocationTargetException ex) { throw new CodeGenerationException(ex.getTargetException()); } catch (InaccessibleObjectException ex) { // setAccessible failed with JDK 9+ InaccessibleObjectException -> fall through // Avoid through JVM startup with --add-opens=java.base/java.lang=ALL-UNNAMED t = ex; } catch (Throwable ex) { throw new CodeGenerationException(ex); } } } // Fallback option: JDK 9+ Lookup.defineClass API even if ClassLoader does not match if (c == null && contextClass != null && contextClass.getClassLoader() != loader) { try { MethodHandles.Lookup lookup = MethodHandles.privateLookupIn(contextClass, MethodHandles.lookup()); c = lookup.defineClass(b); } catch (LinkageError | IllegalAccessException ex) { throw new CodeGenerationException(ex) { @Override public String getMessage() { return "ClassLoader mismatch for [" + contextClass.getName() + "]: JVM should be started with --add-opens=java.base/java.lang=ALL-UNNAMED " + "for ClassLoader.defineClass to be accessible on " + loader.getClass().getName() + "; consider co-locating the affected class in that target ClassLoader instead."; } }; } catch (Throwable ex) { throw new CodeGenerationException(ex); } } // No defineClass variant available at all? if (c == null) { throw new CodeGenerationException(t); } // Force static initializers to run. Class.forName(className, true, loader); return c; } public static void setLoadedClassHandler(Consumer<Class<?>> loadedClassHandler) { ReflectUtils.loadedClassHandler = loadedClassHandler; } public static Class<?> loadClass(String className, ClassLoader classLoader) throws ClassNotFoundException { // Force static initializers to run. Class<?> clazz = Class.forName(className, true, classLoader); Consumer<Class<?>> handlerToUse = loadedClassHandler; if (handlerToUse != null) { handlerToUse.accept(clazz); } return clazz; } // SPRING PATCH END public static int findPackageProtected(Class[] classes) { for (int i = 0; i < classes.length; i++) { if (!Modifier.isPublic(classes[i].getModifiers())) { return i; } } return 0; } public static MethodInfo getMethodInfo(final Member member, final int modifiers) { final Signature sig = getSignature(member); return new MethodInfo() { private ClassInfo ci; @Override public ClassInfo getClassInfo() { if (ci == null) { ci = ReflectUtils.getClassInfo(member.getDeclaringClass()); } return ci; } @Override public int getModifiers() { return modifiers; } @Override public Signature getSignature() { return sig; } @Override public Type[] getExceptionTypes() { return ReflectUtils.getExceptionTypes(member); } }; } public static MethodInfo getMethodInfo(Member member) { return getMethodInfo(member, member.getModifiers()); } public static ClassInfo getClassInfo(final Class clazz) { final Type type = Type.getType(clazz); final Type sc = (clazz.getSuperclass() == null) ? null : Type.getType(clazz.getSuperclass()); return new ClassInfo() { @Override public Type getType() { return type; } @Override public Type getSuperType() { return sc; } @Override public Type[] getInterfaces() { return TypeUtils.getTypes(clazz.getInterfaces()); } @Override public int getModifiers() { return clazz.getModifiers(); } }; } // used by MethodInterceptorGenerated generated code public static Method[] findMethods(String[] namesAndDescriptors, Method[] methods) { Map map = new HashMap(); for (Method method : methods) { map.put(method.getName() + Type.getMethodDescriptor(method), method); } Method[] result = new Method[namesAndDescriptors.length / 2]; for (int i = 0; i < result.length; i++) { result[i] = (Method) map.get(namesAndDescriptors[i * 2] + namesAndDescriptors[i * 2 + 1]); if (result[i] == null) { // TODO: error? } } return result; } }
package sr.hakrinbank.intranet.api.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.jpa.repository.Temporal; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import sr.hakrinbank.intranet.api.model.InterestSavingsAccount; import javax.persistence.TemporalType; import java.util.Date; import java.util.List; /** * Created by clint on 6/15/17. */ @Repository public interface InterestSavingsAccountRepository extends JpaRepository<InterestSavingsAccount, Long> { @Query("SELECT a FROM Interest a WHERE a.accountType = :name") InterestSavingsAccount findByName(@Param("name") String name); @Query("SELECT a FROM Interest a WHERE a.deleted = 0") List<InterestSavingsAccount> findActiveInterestSavingsAccount(); @Query("select a from Interest a where (a.accountType LIKE '%' || :qry || '%') AND a.deleted = 0") List<InterestSavingsAccount> findAllActiveInterestSavingsAccountBySearchQuery(@Param("qry") String qry); @Query("SELECT a FROM Interest a WHERE a.deleted = 0 ORDER BY a.date DESC") List<InterestSavingsAccount> findActiveInterestSavingsAccountOrderedByDate(); @Query("select a from Interest a where (a.accountType LIKE '%' || :characters || '%') AND (a.date BETWEEN :startOfDay AND :endOfDay) AND a.deleted = 0") List<InterestSavingsAccount> findAllActiveInterestSavingsAccountBySearchQueryAndDate(@Param("characters") String characters, @Param("startOfDay") Date startOfDay, @Param("endOfDay") Date endOfDay); @Query("select a from Interest a where (a.date BETWEEN :startOfDay AND :endOfDay) AND a.deleted = 0") List<InterestSavingsAccount> findAllActiveInterestSavingsAccountByDate(@Param("startOfDay") @Temporal(TemporalType.TIMESTAMP) Date startOfDay, @Param("endOfDay") @Temporal(TemporalType.TIMESTAMP) Date endOfDay); }
package cn.itcast.jdbc; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import cn.itcast.c3p0.UserService; public class TestService { @Test public void testDemo(){ ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml"); UserService servie = (UserService) context.getBean("userService"); servie.add(); } }
package com.training.apps; import javax.xml.ws.Response; import com.training.ifaces.BloodDonor; import com.training.ifaces.GetRequestResponse; import examples.webservices.async.DonationRequest; import examples.webservices.async.DonationRequestServiceService; public class MyClientApplication { public static void main(String[] args) { // TODO Auto-generated method stub /*CurrencyConverterImplService conv=new CurrencyConverterImplService(); CurrencyConverter proxy=conv.getCurrencyConverterImplPort(); System.out.println(proxy.dolorToRupees(100));*/ DonationRequestServiceService conv=new DonationRequestServiceService(); DonationRequest proxy=conv.getDonationRequestServicePort(); //System.out.println(proxy.getRequest("apos")); Response res=proxy.getRequestAsync("apos"); while(!res.isDone()) { try { System.out.println("Waiting"); //Thread.sleep(2000); Thread t=new Thread(){ public void run(){ for(int i=0;i<100;i++){ System.out.println(i); } } }; t.start(); t.join(1000); GetRequestResponse resp=(GetRequestResponse) res.get(); //BloodDonor b=resp.getReturn(); System.out.println(resp.getReturn()); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } // System.out.println("Waiting"); // while(!res.isDone()); // try { // // GetRequestResponse resp=(GetRequestResponse) res.get(); // //BloodDonor b=resp.getReturn(); // System.out.println(resp.getReturn()); // } catch (Exception e) { // // TODO: handle exception // e.printStackTrace(); // } } }
package net.edzard.kinetic; /** * An elliptical shape. * @author Ed */ public class Ellipse extends Shape { /** Protected default Ctor keeps GWT happy */ protected Ellipse() {} /** * Retrieve this ellipse's radius. * @return The radius (x and y component) */ public final native Vector2d getRadius() /*-{ return @net.edzard.kinetic.Vector2d::new(DD)(this.getRadius().x, this.getRadius().y); }-*/; /** * Assign the ellipse's radius. * @param radius The new radius value (x and y component) */ public final native void setRadius(Vector2d radius) /*-{ this.setRadius([radii.@net.edzard.kinetic.Vector2d::x, radii.@net.edzard.kinetic.Vector2d::y]); }-*/; /** * Animate a linear transition of this circle. * @param target Another circle shape - defines the characteristics that the current circle will have at the end of the animation * @param duration The time it will take for the animation to complete, in seconds * @return An object for controlling the transition. */ public final Transition transitionTo(Ellipse target, double duration) { return transitionTo(target, duration, null, null); } /** * Animate a transition of this circle. * @param target Another circle shape - defines the characteristics that the current circle will have at the end of the animation * @param duration The time it will take for the animation to complete, in seconds * @param ease An easing function that defines how the transition will take place * @param callback A function that will be called at the end of the animation * @return An object for controlling the transition. */ public final Transition transitionTo(Ellipse target, double duration, EasingFunction ease, Runnable callback) { StringBuffer sb = new StringBuffer(); if (this.getRadius() != target.getRadius()) sb.append("radius: {x:").append(target.getRadius().x).append(", y: ").append(target.getRadius().y).append("},"); return transitionToShape(target, sb, duration, ease, callback); } }