text
stringlengths 10
2.72M
|
|---|
package com.amodtech.meshdisplaycontroller;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class AboutMeshControllerActivity extends Activity {
/*
* This class is provides user help for the application
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about_mesh_controller);
//Display the About image
ImageView mainMenuImageView;
mainMenuImageView = (ImageView) findViewById(R.id.aboutMeshControllerImage);
int imageResID = getResources().getIdentifier("controller_menu_image", "drawable", getPackageName());
if (imageResID != 0) {
mainMenuImageView.setImageResource(imageResID);
}
//Set the back button listener
final Button backButton = (Button) findViewById(R.id.aboutMeshDisplayBackButton);
backButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
}
|
/*
* Copyright 2002-2019 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.servlet.view.script;
import java.nio.charset.Charset;
import java.util.function.Supplier;
import javax.script.Bindings;
import javax.script.ScriptEngine;
import org.springframework.lang.Nullable;
/**
* Interface to be implemented by objects that configure and manage a
* JSR-223 {@link ScriptEngine} for automatic lookup in a web environment.
* Detected and used by {@link ScriptTemplateView}.
*
* @author Sebastien Deleuze
* @since 4.2
*/
public interface ScriptTemplateConfig {
/**
* Return the {@link ScriptEngine} to use by the views.
*/
@Nullable
ScriptEngine getEngine();
/**
* Return the engine supplier that will be used to instantiate the {@link ScriptEngine}.
* @since 5.2
*/
@Nullable
Supplier<ScriptEngine> getEngineSupplier();
/**
* Return the engine name that will be used to instantiate the {@link ScriptEngine}.
*/
@Nullable
String getEngineName();
/**
* Return whether to use a shared engine for all threads or whether to create
* thread-local engine instances for each thread.
*/
@Nullable
Boolean isSharedEngine();
/**
* Return the scripts to be loaded by the script engine (library or user provided).
*/
@Nullable
String[] getScripts();
/**
* Return the object where the render function belongs (optional).
*/
@Nullable
String getRenderObject();
/**
* Return the render function name (optional). If not specified, the script templates
* will be evaluated with {@link ScriptEngine#eval(String, Bindings)}.
*/
@Nullable
String getRenderFunction();
/**
* Return the content type to use for the response.
* @since 4.2.1
*/
@Nullable
String getContentType();
/**
* Return the charset used to read script and template files.
*/
@Nullable
Charset getCharset();
/**
* Return the resource loader path(s) via a Spring resource location.
*/
@Nullable
String getResourceLoaderPath();
}
|
package org.example.Week7.dao.impl;
public class OrderDaoImpl {
}
|
package book;
/**
* TextBook class
* Book child class
*/
public class TextBook extends Book{
private String field;
private double discount;
private double actualPrice;
/**
* constructor
*
* @param title
* @param price
* @param field
* @param discount
*/
public TextBook(String title, double price, String field, double discount){
super(title, price);
this.field = field;
this.discount = discount;
}
/**
* checks if two textbooks are equal
*
* @param other
* @return
*/
public boolean equals (Object other){
if(other instanceof TextBook){
TextBook t1 = (TextBook) other;
if(super.equals(t1) && this.field.equals(t1.getField())){
return true;
}else{
return false;
}
}else{
return false;
}}
/**
* outputs all the information of a textbook
* @return
*/
public String toString(){
String out = super.toString();
out += "\n\tField: " + this.getField() + "\n\tDiscount: " +
this.getDiscount()+ "%" + "\n\tActual price: " + this.applyDiscount() +"$";
return out;
}
//setters
public void setField(String field){
this.field = field;
}
public void setDiscount(double discount){
this.discount = discount;
}
//getters
public String getField(){
return field;
}
public double getDiscount(){
return discount;
}
//apply discount to a textbook
public double applyDiscount(){
this.setDiscount(discount);
actualPrice = super.getPrice() - super.getPrice() * discount/100;
super.setPrice(actualPrice);
return actualPrice;
}
}
|
package com.blockgame.crash.model;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.validation.constraints.NotBlank;
import org.hibernate.annotations.CreationTimestamp;
import lombok.*;
@Data
@Entity(name="member")
public class MemberVo {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long mbrNo;
@Column(unique = true)
@NotBlank(message = "아이디를 입력해주세요.")
private String id;
@Column(unique = true)
@NotBlank(message = "이름을 입력해주세요.")
private String name;
@NotBlank(message = "비밀번호를 입력해주세요.")
private String password;
private String role;
@CreationTimestamp
private Date createDate;
@OneToMany(mappedBy = "member", cascade = CascadeType.ALL, orphanRemoval = true)
private List<RecordVo> records = new ArrayList<>();
}
|
package api.provincia;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping({"provincia"})
public class RestControladorProvincia {
@Autowired
private ServicioProvincia servicioProvincia;
/**
* Este método corresponde al RF20. Adicionar Año Docente.
*
* @param provincia
* @return {@link EntidadProvincia}
*/
@PostMapping
public EntidadProvincia adicionarProvincia(@RequestBody EntidadProvincia provincia) {
return servicioProvincia.guardar(provincia);
}
/**
* Este método corresponde al RF21. Mostrar año docente.
*
* @param id
* @return {@link EntidadProvincia}
*/
@GetMapping(path = {"{id}"})
public ResponseEntity<EntidadProvincia> mostrarProvincia(@PathVariable int id) {
return servicioProvincia.obtenerPorId(id)
.map(record -> ResponseEntity.ok(record))
.orElse(ResponseEntity.notFound().build());
}
/**
* Este método corresponde al RF22. Editar año docente
*
* @param
* @param provincia
* @return {@link EntidadProvincia}
*/
@PutMapping(path = "{id}")
public ResponseEntity<EntidadProvincia> editarProvincia(@PathVariable int id, @RequestBody EntidadProvincia provincia) {
return servicioProvincia.actualizar(id, provincia)
.map(record -> ResponseEntity.ok(record))
.orElse(ResponseEntity.notFound().build());
}
/**
* Este método corresponde al RF23. Eliminar año docente
*
* @param id
* @return {@link EntidadProvincia}
*/
@DeleteMapping(path = "{id}")
public ResponseEntity<EntidadProvincia> eliminarProvincia(@PathVariable int id) {
return servicioProvincia.eliminar(id)
.map(record -> ResponseEntity.ok(record))
.orElse(ResponseEntity.notFound().build());
}
/**
* Este método corresponde al RF24. Mostrar listado de años docentes
*
* @return
*/
@GetMapping
public List<EntidadProvincia> mostrarProvincia() {
return servicioProvincia.listarTodos();
}
}
|
/*
* 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.messaginghub.pooled.jms.util;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.Collections;
import jakarta.jms.JMSException;
import jakarta.jms.MessageFormatException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Timeout;
/**
* Test for the JMS Message Property support class
*/
@Timeout(20)
public class JMSMessagePropertySupportTest {
//----- convertPropertyTo tests ------------------------------------------//
@Test
public void testConvertPropertyToNullBooleanTarget() throws JMSException {
assertFalse(JMSMessagePropertySupport.convertPropertyTo("timeout", null, Boolean.class));
}
@Test
public void testConvertPropertyToNullFloatTarget() throws JMSException {
assertThrows(NullPointerException.class, () -> {
JMSMessagePropertySupport.convertPropertyTo("float", null, Float.class);
});
}
@Test
public void testConvertPropertyToNullDoubleTarget() throws JMSException {
assertThrows(NullPointerException.class, () -> {
JMSMessagePropertySupport.convertPropertyTo("double", null, Double.class);
});
}
@Test
public void testConvertPropertyToNullShortTarget() throws JMSException {
assertThrows(NumberFormatException.class, () -> {
JMSMessagePropertySupport.convertPropertyTo("number", null, Short.class);
});
}
@Test
public void testConvertPropertyToNullIntegerTarget() throws JMSException {
assertThrows(NumberFormatException.class, () -> {
JMSMessagePropertySupport.convertPropertyTo("number", null, Integer.class);
});
}
@Test
public void testConvertPropertyToNullLongTarget() throws JMSException {
assertThrows(NumberFormatException.class, () -> {
JMSMessagePropertySupport.convertPropertyTo("number", null, Long.class);
});
}
@Test
public void testConvertPropertyToNullStringTarget() throws JMSException {
assertNull(JMSMessagePropertySupport.convertPropertyTo("string", null, String.class));
}
//----- checkPropertyNameIsValid tests -----------------------------------//
@Test
public void testCheckPropertyNameIsValidWithNullName() throws JMSException {
assertThrows(IllegalArgumentException.class, () -> {
JMSMessagePropertySupport.checkPropertyNameIsValid(null, true);
});
}
@Test
public void testCheckPropertyNameIsValidWithEmptyName() throws JMSException {
assertThrows(IllegalArgumentException.class, () -> {
JMSMessagePropertySupport.checkPropertyNameIsValid("", true);
});
}
@Test
public void testCheckPropertyNameWithLogicOperatorValidationDisabled() throws JMSException {
JMSMessagePropertySupport.checkPropertyNameIsValid("OR", false);
}
//----- checkIdentifierIsntLogicOperator tests ---------------------------//
@Test
public void testCheckIdentifierIsntLogicOperatorOr() throws JMSException {
assertThrows(IllegalArgumentException.class, () -> {
JMSMessagePropertySupport.checkIdentifierIsntLogicOperator("OR");
});
}
@Test
public void testCheckIdentifierIsntLogicOperatorAnd() throws JMSException {
assertThrows(IllegalArgumentException.class, () -> {
JMSMessagePropertySupport.checkIdentifierIsntLogicOperator("AND");
});
}
@Test
public void testCheckIdentifierIsntLogicOperatorNot() throws JMSException {
assertThrows(IllegalArgumentException.class, () -> {
JMSMessagePropertySupport.checkIdentifierIsntLogicOperator("NOT");
});
}
@Test
public void testCheckIdentifierIsntLogicOperatorBetween() throws JMSException {
assertThrows(IllegalArgumentException.class, () -> {
JMSMessagePropertySupport.checkIdentifierIsntLogicOperator("BETWEEN");
});
}
@Test
public void testCheckIdentifierIsntLogicOperatorIn() throws JMSException {
assertThrows(IllegalArgumentException.class, () -> {
JMSMessagePropertySupport.checkIdentifierIsntLogicOperator("IN");
});
}
@Test
public void testCheckIdentifierIsntLogicOperatorLike() throws JMSException {
assertThrows(IllegalArgumentException.class, () -> {
JMSMessagePropertySupport.checkIdentifierIsntLogicOperator("LIKE");
});
}
@Test
public void testCheckIdentifierIsntLogicOperatorIs() throws JMSException {
assertThrows(IllegalArgumentException.class, () -> {
JMSMessagePropertySupport.checkIdentifierIsntLogicOperator("IS");
});
}
@Test
public void testCheckIdentifierIsntLogicOperatorEscape() throws JMSException {
assertThrows(IllegalArgumentException.class, () -> {
JMSMessagePropertySupport.checkIdentifierIsntLogicOperator("ESCAPE");
});
}
//----- checkIdentifierIsntNullTrueFalse tests ---------------------------//
@Test
public void testCheckIdentifierIsntNullTrueFalseFalse() throws JMSException {
assertThrows(IllegalArgumentException.class, () -> {
JMSMessagePropertySupport.checkIdentifierIsntNullTrueFalse("FALSE");
});
}
@Test
public void testCheckIdentifierIsntNullTrueFalseNull() throws JMSException {
assertThrows(IllegalArgumentException.class, () -> {
JMSMessagePropertySupport.checkIdentifierIsntNullTrueFalse("NULL");
});
}
@Test
public void testCheckIdentifierIsntNullTrueFalseTrue() throws JMSException {
assertThrows(IllegalArgumentException.class, () -> {
JMSMessagePropertySupport.checkIdentifierIsntNullTrueFalse("TRUE");
});
}
//----- checkIdentifierLetterAndDigitRequirements ------------------------//
@Test
public void testCheckIdentifierLetterAndDigitRequirementsValid() throws JMSException {
JMSMessagePropertySupport.checkIdentifierLetterAndDigitRequirements("test");
}
@Test
public void testCheckIdentifierLetterAndDigitRequirementsStartWithNumber() throws JMSException {
assertThrows(IllegalArgumentException.class, () -> {
JMSMessagePropertySupport.checkIdentifierLetterAndDigitRequirements("1");
});
}
@Test
public void testCheckIdentifierLetterAndDigitRequirementsContainsColon() throws JMSException {
assertThrows(IllegalArgumentException.class, () -> {
JMSMessagePropertySupport.checkIdentifierLetterAndDigitRequirements("a:b");
});
}
@Test
public void testCheckIdentifierLetterAndDigitRequirementsContainsEndWithColon() throws JMSException {
assertThrows(IllegalArgumentException.class, () -> {
JMSMessagePropertySupport.checkIdentifierLetterAndDigitRequirements("a:b");
});
}
//----- checkValidObject -------------------------------------------------//
@Test
public void testCheckValidObjectBoolean() throws JMSException {
JMSMessagePropertySupport.checkValidObject(Boolean.TRUE);
}
@Test
public void testCheckValidObjectByte() throws JMSException {
JMSMessagePropertySupport.checkValidObject(Byte.MAX_VALUE);
}
@Test
public void testCheckValidObjectShort() throws JMSException {
JMSMessagePropertySupport.checkValidObject(Short.MAX_VALUE);
}
@Test
public void testCheckValidObjectInteger() throws JMSException {
JMSMessagePropertySupport.checkValidObject(Integer.MAX_VALUE);
}
@Test
public void testCheckValidObjectLong() throws JMSException {
JMSMessagePropertySupport.checkValidObject(Long.MAX_VALUE);
}
@Test
public void testCheckValidObjectFloat() throws JMSException {
JMSMessagePropertySupport.checkValidObject(Float.MAX_VALUE);
}
@Test
public void testCheckValidObjectDouble() throws JMSException {
JMSMessagePropertySupport.checkValidObject(Double.MAX_VALUE);
}
@Test
public void testCheckValidObjectCharacter() throws JMSException {
JMSMessagePropertySupport.checkValidObject(Character.MAX_VALUE);
}
@Test
public void testCheckValidObjectString() throws JMSException {
JMSMessagePropertySupport.checkValidObject("");
}
@Test
public void testCheckValidObjectNull() throws JMSException {
JMSMessagePropertySupport.checkValidObject(null);
}
@Test
public void testCheckValidObjectList() throws JMSException {
assertThrows(MessageFormatException.class, () -> {
JMSMessagePropertySupport.checkValidObject(Collections.EMPTY_LIST);
});
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tot.gather;
import tot.bean.DataField;
import tot.dao.DaoFactory;
import tot.util.UrlUtil;
import tot.util.StringUtils;
import tot.util.HtmlParse;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
*
* @author Administrator
*/
public class ScheduledGatherThread implements Runnable {
private static Log log = LogFactory.getLog(ScheduledGatherThread.class);
private int taskId = 0;
private int count = 0;
/** Creates a new instance of GatherThread */
public ScheduledGatherThread(int taskid) {
this.taskId = taskid;
}
public void run() {
count++;
log.debug("start scheduled gather task:" + taskId + " for " + count + " times");
if (taskId > 0) {
DataField df = DaoFactory.getGatherDAO().getGather(taskId);
if (df != null) {
int ReplaceUrl = Integer.parseInt(df.getFieldValue("ReplaceUrl"));
String UrlFrom = df.getFieldValue("UrlFrom");
String UrlTo = df.getFieldValue("UrlTo");
String ReplaceStr = df.getFieldValue("ReplaceStr");
String ListLabelStart = df.getFieldValue("ListLabelStart");
String ListLabelEnd = df.getFieldValue("ListLabelEnd");
String content = UrlUtil.getHtml(df.getFieldValue("Url"), df.getFieldValue("Encode"));
if (content != null) {
String links = StringUtils.subStr(content, ListLabelStart, ListLabelEnd);
if (ReplaceUrl == 1) {
links = StringUtils.replaceString(links, UrlFrom, UrlTo);
}
if (ReplaceStr != null && ReplaceStr.length() > 0) {
links = StringUtils.replaceString(links, ReplaceStr, "");
}
String[] linkArr = HtmlParse.getUrls(links);
GatherTask task = new GatherTask(linkArr, df);
try {
task.start();
} catch (IOException e) {
log.debug(e);
} finally {
try{
task.shutdown();
}catch (Exception e) {
}
}
}
}
}
}
}
|
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 17. 电话号码的字母组合
* 给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
* 给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number
*
*
* 解法: 采用回溯的思想,加上深度优先搜索,只不过是全不查询
*/
public class LC0009 {
public List<String> letterCombinations(String digits) {
//存放结果集
List<String> list = new ArrayList<>();
if (digits == null || digits.length()==0) return list;
Map<Character,String> hashmap = new HashMap<>();
hashmap.put('2',"abc");
hashmap.put('3',"def");
hashmap.put('4',"ghi");
hashmap.put('5',"jkl");
hashmap.put('6',"mno");
hashmap.put('7',"pqrs");
hashmap.put('8',"tuv");
hashmap.put('9',"wxyz");
StringBuilder sb = new StringBuilder();
domethod(digits,0,hashmap,list,sb); // 入口
return list;
}
private void domethod(String digits, int index, Map<Character, String> hashmap, List<String> list, StringBuilder sb) {
if (index == digits.length()){ //当长度符合条件时,将结果存进结果容器中
list.add(String.valueOf(sb));
}else {
String s = hashmap.get(digits.charAt(index));
for (int i = 0;i < s.length();i++){ //深度搜索的变形,对每一层的几个选项(节点)进行遍历
sb.append(s.charAt(i));
domethod(digits,index+1,hashmap,list,sb); //递归进行深搜
sb.deleteCharAt(index); //回溯操作
}
}
}
}
|
package com.culturaloffers.maps.services;
import com.culturaloffers.maps.model.GeoLocation;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.PageRequest;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import javax.transaction.Transactional;
import java.util.List;
import static com.culturaloffers.maps.constants.GeoLocationConstants.*;
import static org.junit.Assert.*;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.*;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestPropertySource("classpath:test-user-geo.properties")
public class GeoLocationServiceIntegrationTest {
@Autowired
private GeoLocationService geoLocationService;
@Test
public void testGetByAddress() {
GeoLocation geoLocation = geoLocationService.getByAddress(DB_GEO_LOCATION_ADDRESS);
assertEquals(DB_GEO_LOCATION_ADDRESS, geoLocation.getAddress());
}
@Test
public void testGetByWrongAddress() {
GeoLocation geoLocation = geoLocationService.getByAddress(NEW_GEO_LOCATION_ADDRESS);
assertNull(geoLocation);
}
@Test
public void testGetByLatitudeAndLongitude() {
GeoLocation geoLocation = geoLocationService.getByLatitudeAndLongitude(
DB_GEO_LOCATION_LATITUDE, DB_GEO_LOCATION_LONGITUDE);
assertEquals(DB_GEO_LOCATION_LATITUDE, geoLocation.getLatitude(), DELTA);
assertEquals(DB_GEO_LOCATION_LONGITUDE, geoLocation.getLongitude(), DELTA);
}
@Test
public void testGetByLatitudeAndLongitudeWrong() {
GeoLocation geoLocation = geoLocationService.getByLatitudeAndLongitude(
DB_GEO_LOCATION_LATITUDE, NEW_GEO_LOCATION_LONGITUDE);
assertNull(geoLocation);
}
@Test
public void testGetAllGeoLocations() {
List<GeoLocation> geoLocations = geoLocationService.getAllGeoLocations();
assertEquals(DB_GEO_ALL, geoLocations.size());
}
@Test
public void testGetGeoLocationsFirstPage() {
List<GeoLocation> geoLocations = geoLocationService.getGeoLocations(
PageRequest.of(DB_GEO_PAGE, DB_GEO_SIZE)).getContent();
assertEquals(DB_GEO_SIZE, geoLocations.size());
}
@Test
public void testGetGeoLocationsSecondPage() {
List<GeoLocation> geoLocations = geoLocationService.getGeoLocations(
PageRequest.of(DB_GEO_PAGE_TWO, DB_GEO_SIZE)).getContent();
assertEquals(DB_GEO_EXPECTED_TWO, geoLocations.size());
}
@Test
@Transactional
@Rollback(true)
public void testDeleteByAddress() {
boolean deleted = geoLocationService.delete(DB_GEO_LOCATION_ADDRESS);
assertTrue(deleted);
}
@Test
@Transactional
@Rollback(true)
public void testDeleteByLatitudeAndLongitude() {
boolean deleted = geoLocationService.delete(DB_GEO_LOCATION_LATITUDE, DB_GEO_LOCATION_LONGITUDE);
assertTrue(deleted);
}
@Test
@Transactional
@Rollback(true)
public void testDeleteById() {
boolean deleted = geoLocationService.delete(DB_GEO_LOCATION_ID);
assertTrue(deleted);
}
@Test
@Transactional
@Rollback(true)
public void testInsert() {
GeoLocation geoLocation = new GeoLocation(
NEW_GEO_LOCATION_LATITUDE,
NEW_GEO_LOCATION_LONGITUDE,
NEW_GEO_LOCATION_ADDRESS
);
GeoLocation created = geoLocationService.insert(geoLocation);
assertEquals(NEW_GEO_LOCATION_ADDRESS, created.getAddress());
assertEquals(NEW_GEO_LOCATION_LATITUDE, created.getLatitude(), DELTA);
assertEquals(NEW_GEO_LOCATION_LONGITUDE, created.getLongitude(), DELTA);
}
@Test
@Transactional
@Rollback(true)
public void testUpdate() {
GeoLocation geoLocation = new GeoLocation(
NEW_GEO_LOCATION_LATITUDE,
NEW_GEO_LOCATION_LONGITUDE,
NEW_GEO_LOCATION_ADDRESS
);
GeoLocation updated = geoLocationService.update(DB_GEO_LOCATION_ID, geoLocation);
assertEquals(NEW_GEO_LOCATION_ADDRESS, updated.getAddress());
assertEquals(NEW_GEO_LOCATION_LATITUDE, updated.getLatitude(), DELTA);
assertEquals(NEW_GEO_LOCATION_LONGITUDE, updated.getLongitude(), DELTA);
}
}
|
package controller;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.DaoException;
import dao.StudenteDao;
import entity.Studente;
/**
* Servlet implementation class RegServletCM
*/
@WebServlet("/RegServletCM")
public class RegServletCM extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String nome = request.getParameter("nome");
String cognome = request.getParameter("cognome");
String username = request.getParameter("username");
String password = request.getParameter("password");
String confermaPass = request.getParameter("confermaPass");
Studente nuovoUtente=new Studente();
nuovoUtente.setNome(nome);
nuovoUtente.setCognome(cognome);
nuovoUtente.setUsername(username);
nuovoUtente.setPassword(password);
// registrazione utente
try {
StudenteDao ud = new StudenteDao();
ArrayList<Studente> u = ud.getBy(username); // cerco username nuovo ut nel db
if (!(u.isEmpty()) ) { // se
request.setAttribute("errorMsg3", "Username giÓ presente!");
getServletContext().getRequestDispatcher("/registrazioneCM.jsp").forward(request, response);
} else {
if (password.equals(confermaPass)) {
if (password.equals("")|| nome.equals("") || cognome.equals("") || username.equals("")) {
if(password.equals(""))
{request.setAttribute("errorMsg4", " campo obbligatorio vuoto!");};
if(nome.equals(""))
{request.setAttribute("errorMsg5", " campo obbligatorio vuoto!");};
if(cognome.equals(""))
{request.setAttribute("errorMsg6", " campo obbligatorio vuoto!");};
if(username.equals(""))
{request.setAttribute("errorMsg7", " campo obbligatorio vuoto!");};
getServletContext().getRequestDispatcher("/registrazioneCM.jsp").forward(request, response);
} else {
request.setAttribute("username", request.getParameter("username"));
ud.add(nuovoUtente);
request.setAttribute("nome", nome);
request.setAttribute("cognome", cognome);
getServletContext().getRequestDispatcher("/pagPersCM.jsp").forward(request, response);
}
} else {
request.setAttribute("errorMsg8", "password errata!");
getServletContext().getRequestDispatcher("/registrazioneCM.jsp").forward(request, response);
}
}
}catch (DaoException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package easyinvest.com.myapplication;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.NumberPicker;
import android.widget.TextView;
import android.widget.Toast;
public class BuySellActivity extends AppCompatActivity {
private TextView priceCalculation;
private NumberPicker numberPickerFraction;
private NumberPicker numberPickerInteger;
private TextView balanceValue;
private Stock stock;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_buy_sell);
priceCalculation = (TextView) findViewById(R.id.textView_price_calculation);
numberPickerFraction = (NumberPicker) findViewById(R.id.numberPicker_fraction);
numberPickerInteger = (NumberPicker) findViewById(R.id.numberPicker_integer);
balanceValue = (TextView) findViewById(R.id.textView_balance_value);
Button buttonHome = (Button) findViewById(R.id.button_home);
buttonHome.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(BuySellActivity.this, FindStocksActivity.class);
startActivity(intent);
}
});
String[] fractions = new String[10];
String[] integers = new String[10];
for (int i = 0; i < 10; i++) {
fractions[i] = "0." + i;
integers[i] = "" + i;
}
initializeNumberPicker(numberPickerFraction, fractions);
initializeNumberPicker(numberPickerInteger, integers);
if (State.getIndex() != Index.DOW) {
numberPickerFraction.setVisibility(View.INVISIBLE);
}
}
@Override
protected void onResume() {
super.onResume();
stock = State.getStock();
balanceValue.setText("" + State.getPortfolio().getBalance());
TextView sharePriceTextView = (TextView) findViewById(R.id.textView_share_price);
sharePriceTextView.setText("" + stock.price);
TextView companyName = (TextView) findViewById(R.id.textView_company_name);
companyName.setText(stock.name);
TextView ticker = (TextView) findViewById(R.id.textView_ticker);
ticker.setText("NASDAQ: " + stock.ticker);
Button viewPortfolio = (Button) findViewById(R.id.button_portfolio);
viewPortfolio.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(BuySellActivity.this, PortfolioActivity.class);
startActivity(intent);
}
});
Button buy = (Button) findViewById(R.id.button_buy);
buy.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Portfolio portfolio = State.getPortfolio();
double quantity = getQuantity();
if (portfolio.canBuy(stock, quantity)) {
portfolio.buy(stock, quantity);
Toast.makeText(getApplicationContext(), quantity + " shares of " + stock.ticker + " bought", Toast.LENGTH_LONG).show();
balanceValue.setText("" + portfolio.getBalance());
Intent intent = new Intent(BuySellActivity.this, PortfolioActivity.class);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Not Enough Funds", Toast.LENGTH_LONG).show();
}
}
});
Button sell = (Button) findViewById(R.id.button_sell);
sell.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Portfolio portfolio = State.getPortfolio();
double quantity = getQuantity();
if (!portfolio.getStocks().contains(stock)) {
Toast.makeText(getApplicationContext(), "You do not own the stock", Toast.LENGTH_LONG).show();
} else {
if (quantity > portfolio.getQuantity(stock)) {
quantity = portfolio.getQuantity(stock);
}
Toast.makeText(getApplicationContext(), quantity + " shares of " + stock.ticker + " sold", Toast.LENGTH_LONG).show();
portfolio.sell(stock, quantity);
balanceValue.setText("" + portfolio.getBalance());
Intent intent = new Intent(BuySellActivity.this, PortfolioActivity.class);
startActivity(intent);
}
}
});
setPriceCalculationText();
}
private void initializeNumberPicker(final NumberPicker numberPicker, String[] values) {
numberPicker.setDisplayedValues(values);
numberPicker.setMaxValue(9);
numberPicker.setMinValue(0);
numberPicker.setWrapSelectorWheel(false);
numberPicker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
setPriceCalculationText();
}
});
}
private void setPriceCalculationText() {
String text = "";
double quantity = getQuantity();
text += quantity + " @ " + stock.price + " = " + Math.round(stock.price * quantity);
priceCalculation.setText(text);
}
private double getQuantity() {
return Double.parseDouble(numberPickerInteger.getDisplayedValues()[numberPickerInteger.getValue()])
+ Double.parseDouble(numberPickerFraction.getDisplayedValues()[numberPickerFraction.getValue()]);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_buy_sell, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
package br.com.fiap.bean;
import java.util.Calendar;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import br.com.fiap.dao.BebidaDAO;
import br.com.fiap.dao.impl.BebidaDAOImpl;
import br.com.fiap.entity.Bebida;
import br.com.fiap.exception.DBException;
import br.com.fiap.singleton.EntityManagerFactorySingleton;
@ManagedBean(name="bebidaMB")
@RequestScoped
public class BebidaMB {
private Bebida bebida;
private BebidaDAO dao;
private List<Bebida> lista;
@PostConstruct
private void init() {
EntityManager em = EntityManagerFactorySingleton.getInstance().createEntityManager();
dao = new BebidaDAOImpl(em);
bebida = new Bebida();
bebida.setDataValidade(Calendar.getInstance());
lista = dao.listar();
}
public void cadastrar() {
FacesMessage msg;
try {
dao.cadastrar(bebida);
msg = new FacesMessage("Cadastrado!");
} catch (DBException e) {
e.printStackTrace();
msg = new FacesMessage("Erro");
}
FacesContext.getCurrentInstance().addMessage(null, msg);
lista = dao.listar(); // Atualizar a lista
}
public Bebida getBebida() {
return bebida;
}
public void setBebida(Bebida bebida) {
this.bebida = bebida;
}
public List<Bebida> getLista() {
return lista;
}
public void setLista(List<Bebida> lista) {
this.lista = lista;
}
}
|
package server.sport.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import server.sport.exception.EntityCannotBeProcessedExecption;
import server.sport.exception.ResourceNotFoundException;
import server.sport.model.*;
import server.sport.repository.*;
import java.util.*;
@Service
public class UserService {
@Autowired
UserRepository userRepository;
@Autowired
UserTypeRepository userTypeRepository;
@Autowired
TeamRepository teamRepository;
@Autowired
ActivityRepository activityRepository;
@Autowired
ResponsibilityRepository responsibilityRepository;
@Autowired
UserResponsibilityRepository userResponsibilityRepository;
@Autowired
UserStatusRepository userStatusRepository;
@Autowired
ActivityStatusRepository activityStatusRepository;
private Sort.Direction getSortDirection(String direction){
if(direction.equals("asc")){
return Sort.Direction.ASC;
}
return Sort.Direction.DESC;
}
public ResponseEntity<User> addUser(User user) {
userTypeRepository.findById(user.getUserType().getUserTypeId())
.orElseThrow(() -> new ResourceNotFoundException("User type with id " + user.getUserType().getUserTypeId() + " not found."));
teamRepository.findById(user.getTeam().getTeamId())
.orElseThrow(() -> new ResourceNotFoundException("Team with id " + user.getTeam().getTeamId() + " not found."));
return new ResponseEntity<>(userRepository.save(user), HttpStatus.OK);
}
private boolean sortCriteriaCheck(String sort){
return sort.equals("firstName") || sort.equals("lastName") || sort.equals("userId");
}
public ResponseEntity<Map<String, Object>> getTeamMembers(int teamId, String[] sort, int page, int size){
List<Sort.Order> orders= new ArrayList<>();
if(sort[0].contains(",")){
for(String sortOrders: sort){
String[] _sort = sortOrders.split(",");
if (!sortCriteriaCheck(_sort[0])) throw new IllegalArgumentException("Can't sort according to: " + _sort[0]);
orders.add(new Sort.Order(getSortDirection(_sort[1]), _sort[0]));
}
} else {
if (!sortCriteriaCheck(sort[0])) throw new IllegalArgumentException("Can't sort according to: " + sort[0]);
orders.add(new Sort.Order(getSortDirection(sort[1]),sort[0]));
}
Pageable pagingSort = PageRequest.of(page, size,Sort.by(orders));
Page<User> pageUsers = userRepository.findAllByTeamTeamId(teamId, pagingSort);
if (pageUsers.getContent().isEmpty()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
List<BasicUser> basicUsers = new ArrayList<>();
for (User user: pageUsers.getContent()) {
Team tempTeam = user.getTeam();
Sport tempSport = tempTeam.getSport();
basicUsers.add(new BasicUser(user.getUserId(),user.getFirstName(),user.getLastName(),user.getEmail(),
new Team(tempTeam.getTeamId(),tempTeam.getTeamName(),
new Sport(tempSport.getSportId(),tempSport.getSportName(), tempSport.getResponsibilities())))
);
}
Map<String,Object> response = new HashMap<>();
response.put("users", basicUsers);
response.put("currentPage", pageUsers.getNumber());
response.put("totalItems", pageUsers.getTotalElements());
response.put("totalPages", pageUsers.getTotalPages());
return new ResponseEntity<>(response, HttpStatus.OK);
}
public ResponseEntity<Integer> updateStatusInActivity (int userId, int activityId, String status){
Activity activity = activityRepository.findById(activityId).orElseThrow(
() -> new org.springframework.data.rest.webmvc.ResourceNotFoundException("Not found activity with activity id = " + activityId));
UserStatus userStatus = userStatusRepository.findByStatusName(status);
if (userStatus.equals(null))
new org.springframework.data.rest.webmvc.ResourceNotFoundException("Not found status with user status name = " + status);
User user = userRepository.findById(userId).orElseThrow(
() -> new org.springframework.data.rest.webmvc.ResourceNotFoundException("Not found user with user id = " + userId));
/*List <ActivityStatus> activityStatuses1 = activity.getActivityStatuses().stream().filter
(activityStatus1 -> activityStatus1.getUserId()==userId).collect(Collectors.toList());
ActivityStatus activityStatus = null;
if (activityStatuses1.size() == 1){
activityStatus = new ActivityStatus(userId, activityId, userStatus, user, activity);
}else if (activityStatuses1.size() > 1 ){
new ErrorMessage(403, new Date(), "Too many activityStauses for one users", "Found more than one record of activity status for one user");
}else {
activityStatus = activityStatuses1.get(0);
activityStatus.setUserStatus(userStatus);
}
*/
return new ResponseEntity<>(activityStatusRepository.saveNewActivityStatus(userStatus.getStatusId(),activityId, userId), HttpStatus.OK);
}
public ResponseEntity<Activity> getActivity(int userId,int activityId) {
Activity activity = activityRepository.findById(activityId)
.orElseThrow(() -> new ResourceNotFoundException("Did not find activity with id = " + activityId));
return new ResponseEntity<>(activity, HttpStatus.OK);
}
public ResponseEntity<UserResponsibility> assignUserResponsibility(Integer userId, int activityId, int responsibility){
Activity activity = activityRepository.findById(activityId)
.orElseThrow(() -> new ResourceNotFoundException("Did not find activity with id = " + activityId));
User user = userRepository.findById(userId)
.orElseThrow(() -> new ResourceNotFoundException("Did not find user with id = " + userId));
if (!activity.getTeam().getUsers().contains(user)){
throw new EntityCannotBeProcessedExecption("Cannot assign responsibility to user from another team. Activity id = " + activityId + " User id = " + userId);
}
responsibilityRepository.findById(responsibility)
.orElseThrow(() -> new ResourceNotFoundException("Did not find responsibility with id = " + responsibility));
UserResponsibility userResponsibility = userResponsibilityRepository.findById(new UserResponsibilityPK(responsibility,activityId))
.orElseThrow(() -> new ResourceNotFoundException("Did not find activity with id = " + activityId + " and assigned responsibility with id " + responsibility));
userResponsibility.setUser(user);
return new ResponseEntity<>(userResponsibilityRepository.save(userResponsibility), HttpStatus.OK);
}
public ResponseEntity<User> getUser(int userId) {
User user = userRepository.findById(userId)
.orElseThrow(() -> new ResourceNotFoundException("Did not find User with id = " + userId));
return new ResponseEntity<>(user, HttpStatus.OK);
}
public ResponseEntity<User> getUserByEmail(String email){
User user = userRepository.getUserByEmail(email)
.orElseThrow(() -> new ResourceNotFoundException("Did not find User with email = " + email));
Team team = teamRepository.findTeamByUsersContaining(user);
user.setTeam(team);
return new ResponseEntity<>(user, HttpStatus.OK);
}
public ResponseEntity<HttpStatus> deleteUser (int userId){
userRepository.deleteByUserId(userId).
orElseThrow(() -> new ResourceNotFoundException("Did not find User with id = " + userId));
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
public ResponseEntity<User> updateUser(User user, int userId) {
User _user = userRepository.findById(userId)
.orElseThrow(() -> new ResourceNotFoundException("Did not find user with id = " + userId));
_user.setUserId(userId);
_user.setFirstName(user.getFirstName());
_user.setLastName(user.getLastName());
_user.setEmail(user.getEmail());
_user.setGender(user.getGender());
_user.setPhone(user.getPhone());
_user.setEmail(user.getEmail());
UserType userType= userTypeRepository.findById(user.getUserType().getUserTypeId())
.orElseThrow(() -> new ResourceNotFoundException("Did not find user type with id = " + user.getUserType().getUserTypeId()));
_user.setUserType(userType);
Team team = teamRepository.findById(user.getTeam().getTeamId())
.orElseThrow(() -> new ResourceNotFoundException("Did not find team with id = " + user.getTeam().getTeamId()));
_user.setTeam(team);
_user.setTeam(user.getTeam());
return new ResponseEntity<>(userRepository.save(_user), HttpStatus.OK);
}
}
|
package com.example.kazi.testapplication.model;
/**
* Created by Kazi on 5/12/2017.
*/
public interface AdapterRefresher {
void refresh();
}
|
package view;
import controller.ImageProcessingController;
import controller.ProcessingController;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileNameExtensionFilter;
import layeredimage.ViewModel;
import layeredimage.blend.AbstractBlend;
/**
* Represents a GUI interface that allows a user to perform all supported functionality for editing
* a layered image, and see a preview of their work as they make changes.
*/
public class GraphicalView extends JFrame implements View, ActionListener {
private final ImageProcessingController controller;
private ViewModel display;
private String currentImageName;
private String currentLayerName;
private JPanel mainPanel;
private ImageIcon imagePanel;
private JPanel layerSelectors;
private JMenu layerMenu;
private JMenuItem newLayer;
private JMenuItem loadLayer;
private JMenuItem saveCurrentLayer;
private ButtonGroup layers;
private JPanel layerMoveUppers;
private JPanel layerMoveDowners;
private JPanel layerCopiers;
private JPanel layerShowers;
private JPanel layerHiders;
private JMenu tabs;
/**
* Constructs a new graphical view - initializes all unchanging JFrame components as well as the
* overall framework of the GUI, and creates a new controller which references this as it's view
* and which will actually hold and edit a model.
*/
public GraphicalView() {
super();
setTitle("Image Processing Interactive Interface");
setSize(750, 750);
mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
JScrollPane mainScrollPane = new JScrollPane(mainPanel);
JMenuBar menuBar = new JMenuBar();
menuBar.setName("Menus");
JMenu file = new JMenu("File");
JMenuItem load = new JMenuItem("Load");
load.setActionCommand("Load File");
load.addActionListener(this);
file.add(load);
JMenuItem save = new JMenuItem("Save");
save.setActionCommand("Save File");
save.addActionListener(this);
file.add(save);
JMenuItem exportMenuItem = new JMenuItem("Export");
exportMenuItem.setActionCommand("Export as Image");
exportMenuItem.addActionListener(this);
file.add(exportMenuItem);
JMenuItem executeMenuItem = new JMenuItem("Execute");
executeMenuItem.setActionCommand("Execute Script");
executeMenuItem.addActionListener(this);
file.add(executeMenuItem);
menuBar.add(file);
JMenu edit = new JMenu("Edit");
JMenu applyMutator = new JMenu("Apply Mutator");
JMenuItem applyBlur = new JMenuItem("Blur");
applyBlur.setActionCommand("Blur");
applyBlur.addActionListener(this);
applyMutator.add(applyBlur);
JMenuItem applySharpen = new JMenuItem("Sharpen");
applySharpen.setActionCommand("Sharpen");
applySharpen.addActionListener(this);
applyMutator.add(applySharpen);
JMenuItem applyGreyscale = new JMenuItem("Greyscale");
applyGreyscale.setActionCommand("Greyscale");
applyGreyscale.addActionListener(this);
applyMutator.add(applyGreyscale);
JMenuItem applySepia = new JMenuItem("Sepia");
applySepia.setActionCommand("Sepia");
applySepia.addActionListener(this);
applyMutator.add(applySepia);
edit.add(applyMutator);
menuBar.add(edit);
layerMenu = new JMenu("Layer");
newLayer = new JMenuItem("New Layer");
newLayer.setActionCommand("Add New Layer");
newLayer.addActionListener(this);
layerMenu.add(newLayer);
loadLayer = new JMenuItem("Load Image");
loadLayer.setActionCommand("Load Image As Layer");
loadLayer.addActionListener(this);
layerMenu.add(loadLayer);
saveCurrentLayer = new JMenuItem("Save Current Layer");
saveCurrentLayer.setActionCommand("Save Current Layer");
saveCurrentLayer.addActionListener(this);
layerMenu.add(saveCurrentLayer);
menuBar.add(layerMenu);
tabs = new JMenu("Current Images");
menuBar.add(tabs);
imagePanel = new ImageIcon();
JLabel imageHolder = new JLabel();
imageHolder.setLayout(new BorderLayout());
imageHolder.setIcon(imagePanel);
JScrollPane imageScrollPane = new JScrollPane(imageHolder);
JPanel leftPanel = new JPanel();
leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.PAGE_AXIS));
JButton blur = new JButton("Blur");
blur.setActionCommand("Blur");
blur.addActionListener(this);
leftPanel.add(blur);
JButton sharpen = new JButton("Sharpen");
sharpen.setActionCommand("Sharpen");
sharpen.addActionListener(this);
leftPanel.add(sharpen);
JButton greyscale = new JButton("Greyscale");
greyscale.setActionCommand("Greyscale");
greyscale.addActionListener(this);
leftPanel.add(greyscale);
JButton sepia = new JButton("Sepia");
sepia.setActionCommand("Sepia");
sepia.addActionListener(this);
leftPanel.add(sepia);
JScrollPane leftScrollPane = new JScrollPane(leftPanel);
JPanel rightPanel = new JPanel();
rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.PAGE_AXIS));
JPanel addLoadLayer = new JPanel();
addLoadLayer.setLayout(new BoxLayout(addLoadLayer, BoxLayout.LINE_AXIS));
JButton addNewLayer = new JButton("New Layer");
addNewLayer.setActionCommand("Add New Layer");
addNewLayer.addActionListener(this);
addLoadLayer.add(addNewLayer);
JButton loadLayer = new JButton("Load Image");
loadLayer.setActionCommand("Load Image As Layer");
loadLayer.addActionListener(this);
addLoadLayer.add(loadLayer);
JButton saveLayer = new JButton("Save Current");
saveLayer.setActionCommand("Save Current Layer");
saveLayer.addActionListener(this);
addLoadLayer.add(saveLayer);
rightPanel.add(addLoadLayer);
JPanel layerInterface = new JPanel();
layerInterface.setLayout(new BoxLayout(layerInterface, BoxLayout.LINE_AXIS));
layerSelectors = new JPanel();
layerSelectors.setLayout(new BoxLayout(layerSelectors, BoxLayout.PAGE_AXIS));
layerInterface.add(layerSelectors);
layers = new ButtonGroup();
layerMoveUppers = new JPanel();
layerMoveUppers.setLayout(new BoxLayout(layerMoveUppers, BoxLayout.PAGE_AXIS));
layerInterface.add(layerMoveUppers);
layerMoveDowners = new JPanel();
layerMoveDowners.setLayout(new BoxLayout(layerMoveDowners, BoxLayout.PAGE_AXIS));
layerInterface.add(layerMoveDowners);
layerCopiers = new JPanel();
layerCopiers.setLayout(new BoxLayout(layerCopiers, BoxLayout.PAGE_AXIS));
layerInterface.add(layerCopiers);
layerShowers = new JPanel();
layerShowers.setLayout(new BoxLayout(layerShowers, BoxLayout.PAGE_AXIS));
layerInterface.add(layerShowers);
layerHiders = new JPanel();
layerHiders.setLayout(new BoxLayout(layerHiders, BoxLayout.PAGE_AXIS));
layerInterface.add(layerHiders);
rightPanel.add(layerInterface);
JScrollPane rightScrollPane = new JScrollPane(rightPanel);
mainPanel.add(imageScrollPane, BorderLayout.CENTER);
mainPanel.add(rightScrollPane, BorderLayout.EAST);
mainPanel.add(leftScrollPane, BorderLayout.WEST);
mainPanel.add(menuBar, BorderLayout.NORTH);
add(mainScrollPane);
this.controller = new ProcessingController(this);
}
@Override
public void renderException(String message) throws IllegalArgumentException {
if (message == null) {
throw new IllegalArgumentException("Null Message");
}
JOptionPane.showMessageDialog(GraphicalView.this, message, "Error", JOptionPane.ERROR_MESSAGE);
}
@Override
public void showView() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
/**
* Handles a user request to load a layered image file as a new image accessible by the view.
*/
private void handleLoadFile() {
final JFileChooser fChooser = new JFileChooser(".");
fChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int retValue = fChooser.showOpenDialog(GraphicalView.this);
if (retValue == JFileChooser.APPROVE_OPTION) {
File f = fChooser.getSelectedFile();
String commandToExecute =
"create-layered-image " + f.getName() + " " + f.getPath().replaceAll(" ", ">");
this.controller.runCommands(commandToExecute);
try {
this.display = controller.getReferenceToImage(f.getName());
} catch (IllegalArgumentException exception) {
this.renderException(exception.getMessage());
}
this.currentImageName = f.getName();
this.currentLayerName = null;
this.imagePanel.setImage(this.display.getImageRepresentation());
this.updateLayerButtons();
this.updateTabs();
SwingUtilities.updateComponentTreeUI(mainPanel);
}
}
/**
* Handles a user request to blur the currently selected layer of the currently selected image.
*/
private void handleBlur() {
if (!(this.currentImageName == null || this.currentLayerName == null)) {
String commandToExecute =
"apply-mutator blur " + this.currentImageName + " " + this.currentLayerName;
this.controller.runCommands(commandToExecute);
this.imagePanel.setImage(this.display.getImageRepresentation());
SwingUtilities.updateComponentTreeUI(mainPanel);
}
}
/**
* Handles a user request to sharpen the currently selected layer of the currently selected
* image.
*/
private void handleSharpen() {
if (!(this.currentImageName == null || this.currentLayerName == null)) {
String commandToExecute =
"apply-mutator sharpen " + this.currentImageName + " " + this.currentLayerName;
this.controller.runCommands(commandToExecute);
this.imagePanel.setImage(this.display.getImageRepresentation());
SwingUtilities.updateComponentTreeUI(mainPanel);
}
}
/**
* Handles a user request to apply a greyscale filter to the currently selected layer of the
* currently selected image.
*/
private void handleGreyscale() {
if (!(this.currentImageName == null || this.currentLayerName == null)) {
String commandToExecute =
"apply-mutator greyscale " + this.currentImageName + " " + this.currentLayerName;
this.controller.runCommands(commandToExecute);
this.imagePanel.setImage(this.display.getImageRepresentation());
SwingUtilities.updateComponentTreeUI(mainPanel);
}
}
/**
* Handles a user request to apply a sepia filter to the currently selected layer of the currently
* selected image.
*/
private void handleSepia() {
if (!(this.currentImageName == null || this.currentLayerName == null)) {
String commandToExecute =
"apply-mutator sepia " + this.currentImageName + " " + this.currentLayerName;
this.controller.runCommands(commandToExecute);
this.imagePanel.setImage(this.display.getImageRepresentation());
SwingUtilities.updateComponentTreeUI(mainPanel);
}
}
/**
* Handles a user request to save the currently selected layer as an image file.
*/
private void handleSaveCurrentLayer() {
if (!(this.currentImageName == null || this.currentLayerName == null)) {
final JFileChooser fChooser = new JFileChooser(".");
int retValue = fChooser.showSaveDialog(GraphicalView.this);
if (retValue == JFileChooser.APPROVE_OPTION) {
File f = fChooser.getSelectedFile();
String commandToExecute =
"save " + this.currentImageName + " " + this.currentLayerName + " "
+ f.getName().substring(f.getName().lastIndexOf(".") + 1) + " "
+ f.getPath().replaceAll(" ", ">").substring(0, f.getPath().lastIndexOf("."));
this.controller.runCommands(commandToExecute);
this.updateLayerButtons();
SwingUtilities.updateComponentTreeUI(mainPanel);
}
}
}
/**
* Handles a user request to add a new layer to the currently selected image.
*/
private void handleAddNewLayer() {
String newLayer = JOptionPane.showInputDialog("Enter the name of the new layer");
String commandToExecute = "add-layer " + this.currentImageName + " " + newLayer;
this.controller.runCommands(commandToExecute);
this.updateLayerButtons();
SwingUtilities.updateComponentTreeUI(mainPanel);
}
/**
* Handles a user request to load an existing image file as a new layer of the currently selected
* image.
*/
private void handleLoadImageAsLayer() {
final JFileChooser fChooser = new JFileChooser(".");
//NOTE: NO FILTER AS VIEW SHOULD NOT BE COUPLED TO WHAT TYPES OF FILES ARE SUPPORTED.
int retValue = fChooser.showOpenDialog(GraphicalView.this);
if (retValue == JFileChooser.APPROVE_OPTION) {
File f = fChooser.getSelectedFile();
String newLayer = JOptionPane.showInputDialog("Enter the name of the new layer");
String commandToExecute =
"add-image-as-layer " + this.currentImageName + " " + newLayer + " "
+ f.getPath().replaceAll(" ", ">");
this.controller.runCommands(commandToExecute);
this.imagePanel.setImage(this.display.getImageRepresentation());
this.updateLayerButtons();
SwingUtilities.updateComponentTreeUI(mainPanel);
}
}
/**
* Handles a user request to save the current layered image as a layered image file.
*/
private void handleSaveFile() {
if (this.currentImageName != null) {
final JFileChooser fChooser = new JFileChooser(".");
int retValue = fChooser.showSaveDialog(GraphicalView.this);
if (retValue == JFileChooser.APPROVE_OPTION) {
File f = fChooser.getSelectedFile();
String commandToExecute =
"save-layered " + this.currentImageName + " " + f.getPath().replaceAll(" ", ">");
this.controller.runCommands(commandToExecute);
this.updateLayerButtons();
SwingUtilities.updateComponentTreeUI(mainPanel);
}
}
}
/**
* Handles a user request to export the currently selected image as an image file.
*/
private void handleExportAsImage() {
if (this.currentImageName != null) {
String[] allBlendTypes = AbstractBlend.getBlendTypes();
String blendType = allBlendTypes[JOptionPane.showOptionDialog(this, "Choose Blend Type",
"Blend Choices", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null,
allBlendTypes, allBlendTypes[0])];
final JFileChooser fChooser = new JFileChooser(".");
int retValue = fChooser.showSaveDialog(GraphicalView.this);
if (retValue == JFileChooser.APPROVE_OPTION) {
File f = fChooser.getSelectedFile();
String commandToExecute =
"save-as-image " + this.currentImageName + " "
+ blendType + " "
+ f.getName().substring(f.getName().lastIndexOf(".") + 1) + " "
+ f.getPath().replaceAll(" ", ">").substring(0, f.getPath().lastIndexOf("."));
this.controller.runCommands(commandToExecute);
this.updateLayerButtons();
SwingUtilities.updateComponentTreeUI(mainPanel);
}
}
}
/**
* Handles a user request to run an external script, and see the results.
*/
private void handleExecuteScript() {
final JFileChooser fChooser = new JFileChooser(".");
FileNameExtensionFilter filter = new FileNameExtensionFilter("Text Files", "txt");
fChooser.setFileFilter(filter);
int retValue = fChooser.showOpenDialog(GraphicalView.this);
if (retValue == JFileChooser.APPROVE_OPTION) {
File f = fChooser.getSelectedFile();
FileReader newRead;
try {
newRead = new FileReader(f);
} catch (IOException fileError) {
this.renderException(fileError.getMessage());
return;
}
Scanner scanner = new Scanner(newRead);
StringBuilder commandToExecute = new StringBuilder();
while (scanner.hasNextLine()) {
commandToExecute.append(scanner.nextLine()).append("\n");
}
System.out.println(commandToExecute);
this.controller.runCommands(commandToExecute.toString());
if (controller.getLayeredImageNames().size() != 0) {
this.currentImageName = (controller.getLayeredImageNames().get(0));
this.display = controller.getReferenceToImage(currentImageName);
this.imagePanel.setImage(this.display.getImageRepresentation());
}
this.updateLayerButtons();
this.updateTabs();
SwingUtilities.updateComponentTreeUI(mainPanel);
}
}
@Override
public void actionPerformed(ActionEvent e) {
if (e == null) {
throw new IllegalArgumentException("Null action");
}
switch (e.getActionCommand()) {
case "Load File":
this.handleLoadFile();
break;
case "Blur":
this.handleBlur();
break;
case "Sharpen":
this.handleSharpen();
break;
case "Greyscale":
this.handleGreyscale();
break;
case "Sepia":
this.handleSepia();
break;
case "Save Current Layer":
this.handleSaveCurrentLayer();
break;
case "Add New Layer":
this.handleAddNewLayer();
break;
case "Load Image As Layer":
this.handleLoadImageAsLayer();
break;
case "Save File":
this.handleSaveFile();
break;
case "Export as Image":
this.handleExportAsImage();
break;
case "Execute Script":
this.handleExecuteScript();
break;
default:
this.handleLayerCommand(e);
this.handleTabCommand(e);
}
}
/**
* Given an action event, will process it as a dynamic tab-selecting action: if it begins with
* "Change Tab ", and then the name of a image currently existing within the model, this will set
* the image currently being edited to that image and refresh layer buttons and menu items.
*
* @param e The action event to be handled
*/
private void handleTabCommand(ActionEvent e) {
if (e.getActionCommand().startsWith("Change Tab ")) {
String commandSecondPart;
try {
commandSecondPart = e.getActionCommand().split(" ")[2];
} catch (IndexOutOfBoundsException exception) {
return;
}
for (String imageName : this.controller.getLayeredImageNames()) {
if (commandSecondPart.equals(imageName)) {
this.currentImageName = imageName;
try {
this.display = controller.getReferenceToImage(imageName);
} catch (IllegalArgumentException exception) {
this.renderException(exception.getMessage());
}
this.currentLayerName = null;
this.imagePanel.setImage(this.display.getImageRepresentation());
this.updateLayerButtons();
SwingUtilities.updateComponentTreeUI(mainPanel);
return;
}
}
}
}
/**
* Given an action event, will process it as a dynamic method that does something to a currently
* existing layer. Currently handles selecting layers, moving them up or down, copying a
* particular layer, and showing or hiding individual layers.
*
* @param e The action event to be processed
*/
private void handleLayerCommand(ActionEvent e) {
if (e.getActionCommand().startsWith("Select ")) {
String commandSecondPart;
try {
commandSecondPart = e.getActionCommand().split(" ")[1];
} catch (IndexOutOfBoundsException exception) {
return;
}
for (String layerName : display.getLayerNames()) {
if (commandSecondPart.equals(layerName)) {
this.currentLayerName = layerName;
this.imagePanel.setImage(this.display.getImageRepresentation());
SwingUtilities.updateComponentTreeUI(mainPanel);
return;
}
}
}
if (e.getActionCommand().startsWith("Move Up ")) {
String commandSecondPart;
try {
commandSecondPart = e.getActionCommand().split(" ")[2];
} catch (IndexOutOfBoundsException exception) {
return;
}
int counter = 0;
for (String layerName : display.getLayerNames()) {
if (commandSecondPart.equals(layerName)) {
if (counter != 0) {
String commandToExecute =
"move-layer " + this.currentImageName + " " + layerName + " " + (counter - 1);
this.controller.runCommands(commandToExecute);
this.updateLayerButtons();
this.imagePanel.setImage(this.display.getImageRepresentation());
SwingUtilities.updateComponentTreeUI(mainPanel);
return;
}
}
counter += 1;
}
}
if (e.getActionCommand().startsWith("Move Down ")) {
String commandSecondPart;
try {
commandSecondPart = e.getActionCommand().split(" ")[2];
} catch (IndexOutOfBoundsException exception) {
return;
}
int counter = 0;
for (String layerName : display.getLayerNames()) {
if (commandSecondPart.equals(layerName)) {
if (counter != display.getLayerNames().size() - 1) {
String commandToExecute =
"move-layer " + this.currentImageName + " " + layerName + " " + (counter + 1);
this.controller.runCommands(commandToExecute);
this.updateLayerButtons();
this.imagePanel.setImage(this.display.getImageRepresentation());
SwingUtilities.updateComponentTreeUI(mainPanel);
return;
}
}
counter += 1;
}
}
if (e.getActionCommand().startsWith("Copy ")) {
String commandSecondPart;
try {
commandSecondPart = e.getActionCommand().split(" ")[1];
} catch (IndexOutOfBoundsException exception) {
return;
}
for (String layerName : display.getLayerNames()) {
if (commandSecondPart.equals(layerName)) {
String newLayer = JOptionPane.showInputDialog("Enter the name of the new layer");
if (newLayer == null) {
return;
}
String commandToExecute =
"copy-layer " + this.currentImageName + " " + newLayer + " " + layerName;
this.controller.runCommands(commandToExecute);
this.updateLayerButtons();
this.imagePanel.setImage(this.display.getImageRepresentation());
SwingUtilities.updateComponentTreeUI(mainPanel);
return;
}
}
}
if (e.getActionCommand().startsWith("Show ")) {
String commandSecondPart;
try {
commandSecondPart = e.getActionCommand().split(" ")[1];
} catch (IndexOutOfBoundsException exception) {
return;
}
for (String layerName : display.getLayerNames()) {
if (commandSecondPart.equals(layerName)) {
String commandToExecute =
"update-visibility " + this.currentImageName + " " + layerName + " true";
this.controller.runCommands(commandToExecute);
this.updateLayerButtons();
this.imagePanel.setImage(this.display.getImageRepresentation());
SwingUtilities.updateComponentTreeUI(mainPanel);
return;
}
}
}
if (e.getActionCommand().startsWith("Hide ")) {
String commandSecondPart;
try {
commandSecondPart = e.getActionCommand().split(" ")[1];
} catch (IndexOutOfBoundsException exception) {
return;
}
for (String layerName : display.getLayerNames()) {
if (commandSecondPart.equals(layerName)) {
String commandToExecute =
"update-visibility " + this.currentImageName + " " + layerName + " false";
this.controller.runCommands(commandToExecute);
this.updateLayerButtons();
this.imagePanel.setImage(this.display.getImageRepresentation());
SwingUtilities.updateComponentTreeUI(mainPanel);
return;
}
}
}
}
/**
* Refreshes the currently available layer menu buttons and freestanding buttons, so that they
* match the currently existing layers of the currently displaying image.
*/
private void updateLayerButtons() {
this.layerSelectors.removeAll();
this.layers = new ButtonGroup();
this.layerMoveUppers.removeAll();
this.layerMoveDowners.removeAll();
this.layerShowers.removeAll();
this.layerHiders.removeAll();
this.layerCopiers.removeAll();
this.layerMenu.removeAll();
layerMenu.add(newLayer);
layerMenu.add(loadLayer);
layerMenu.add(saveCurrentLayer);
for (String layerName : this.display.getLayerNames()) {
JMenu nextLayerMenu = new JMenu(layerName);
JMenuItem nextSetAsCurrent = new JMenuItem("Set as current");
nextSetAsCurrent.setActionCommand("Select " + layerName);
nextSetAsCurrent.addActionListener(this);
nextLayerMenu.add(nextSetAsCurrent);
JMenuItem nextMoveUp = new JMenuItem("Move Up");
nextMoveUp.setActionCommand("Move Up " + layerName);
nextMoveUp.addActionListener(this);
nextLayerMenu.add(nextMoveUp);
JMenuItem nextMoveDown = new JMenuItem("Move Down");
nextMoveDown.setActionCommand("Move Down " + layerName);
nextMoveDown.addActionListener(this);
nextLayerMenu.add(nextMoveDown);
JMenuItem nextCopy = new JMenuItem("Copy");
nextCopy.setActionCommand("Copy " + layerName);
nextCopy.addActionListener(this);
nextLayerMenu.add(nextCopy);
JMenuItem nextShow = new JMenuItem("Show");
nextShow.setActionCommand("Show " + layerName);
nextShow.addActionListener(this);
nextLayerMenu.add(nextShow);
JMenuItem nextHide = new JMenuItem("Hide");
nextHide.setActionCommand("Hide " + layerName);
nextHide.addActionListener(this);
nextLayerMenu.add(nextHide);
layerMenu.add(nextLayerMenu);
JRadioButton nextLayerSelector = new JRadioButton(layerName);
nextLayerSelector.setActionCommand("Select " + layerName);
nextLayerSelector.addActionListener(this);
layers.add(nextLayerSelector);
layerSelectors.add(nextLayerSelector);
JButton nextMoveUpper = new JButton("↑");
nextMoveUpper.setActionCommand("Move Up " + layerName);
nextMoveUpper.addActionListener(this);
layerMoveUppers.add(nextMoveUpper);
JButton nextMoveDowner = new JButton("↓");
nextMoveDowner.setActionCommand("Move Down " + layerName);
nextMoveDowner.addActionListener(this);
layerMoveDowners.add(nextMoveDowner);
JButton nextCopier = new JButton("Copy");
nextCopier.setActionCommand("Copy " + layerName);
nextCopier.addActionListener(this);
layerCopiers.add(nextCopier);
JButton nextShower = new JButton("Show");
nextShower.setActionCommand("Show " + layerName);
nextShower.addActionListener(this);
layerShowers.add(nextShower);
JButton nextHider = new JButton("Hide");
nextHider.setActionCommand("Hide " + layerName);
nextHider.addActionListener(this);
layerHiders.add(nextHider);
}
}
/**
* Updates the image selection buttons so that they accurately represent the existing models
* within the controller.
*/
private void updateTabs() {
this.tabs.removeAll();
for (String imageName : this.controller.getLayeredImageNames()) {
JMenuItem nextName = new JMenuItem(imageName);
nextName.setActionCommand("Change Tab " + imageName);
nextName.addActionListener(this);
tabs.add(nextName);
}
}
}
|
package com.proxiad.games.extranet.utils;
import java.io.File;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import lombok.Getter;
public class PeopleReferentialGenerator {
private static final String SURNAME_FILE = "bdd_noms.txt";
private static final String FIRSTNAME_FILE = "bdd_prenoms.txt";
public static final String SURNAME_REFERENTIAL = "src/main/resources/referentiel_noms.txt";
public static final String FIRSTNAME_REFERENTIAL = "src/main/resources/referentiel_prenoms.txt";
public static void main(String[] args) {
generateFirstNameReferential();
generateSurnameReferential();
}
private static void generateSurnameReferential() {
PeopleReferentialGenerator generator = new PeopleReferentialGenerator();
List<SurnamePeople> nomMap = generator.extractSurnamesFromFile();
File prenomFile = new File(SURNAME_REFERENTIAL);
List<String> prenoms = nomMap.stream()
.map(personPrenom -> personPrenom.getName() + "\t" + personPrenom.getNombre())
.collect(Collectors.toList());
FileUtils.writeInFile(prenomFile, prenoms);
}
private static void generateFirstNameReferential() {
PeopleReferentialGenerator generator = new PeopleReferentialGenerator();
Map<Integer, List<FirstNamePeople>> prenomMap = generator.extractFirstNamesFromFile();
File prenomFile = new File(FIRSTNAME_REFERENTIAL);
List<String> prenoms = prenomMap.keySet().stream().map(sex -> prenomMap.get(sex).stream()
.map(personPrenom -> personPrenom.getSex() + "\t" + personPrenom.getName() + "\t" + personPrenom.getNombre())
.collect(Collectors.toList()))
.flatMap(List::stream)
.collect(Collectors.toList());
FileUtils.writeInFile(prenomFile, prenoms);
}
private List<SurnamePeople> extractSurnamesFromFile() {
List<String> lines = getFileContent(SURNAME_FILE);
return lines.stream()
.map(SurnamePeople::new)
.filter(people -> people.getNombre() >= 600)
.collect(Collectors.toList());
}
private Map<Integer, List<FirstNamePeople>> extractFirstNamesFromFile() {
List<String> lines = getFileContent(FIRSTNAME_FILE);
return lines.stream()
.map(FirstNamePeople::new)
.filter(people -> people.getNombre() >= 300)
.sorted(Comparator.comparing(FirstNamePeople::getName))
.distinct()
.collect(Collectors.groupingBy(FirstNamePeople::getSex, Collectors.toList()));
}
private List<String> getFileContent(String nameFile) {
File file = getFile(nameFile);
List<String> lines = FileUtils.readFile(file);
lines.remove(0);
return lines;
}
private File getFile(String nameFile) {
//Get file from resources folder
ClassLoader classLoader = getClass().getClassLoader();
return new File(classLoader.getResource(nameFile).getFile());
}
private class FirstNamePeople {
@Getter
private Integer sex;
@Getter
private String name;
@Getter
private Integer nombre;
FirstNamePeople(String line) {
this.sex = Integer.valueOf(line.split("\t")[0].trim());
this.name = line.split("\t")[1].trim();
this.nombre = Integer.valueOf(line.split("\t")[3].trim());
}
@Override
public boolean equals(Object o) {
return name.equals(((FirstNamePeople) o).getName());
}
@Override
public int hashCode() {
return this.getName().hashCode();
}
}
private class SurnamePeople {
@Getter
private String name;
@Getter
private Integer nombre;
SurnamePeople(String line) {
this.name = line.split("\t")[0].trim();
this.nombre = Integer.valueOf(line.split("\t")[11].trim());
}
@Override
public boolean equals(Object o) {
return name.equals(((SurnamePeople) o).getName());
}
@Override
public int hashCode() {
return this.getName().hashCode();
}
}
}
|
package cn.edu.nju.software.timemachine.test.service;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import cn.edu.nju.software.timemachine.entity.*;
import cn.edu.nju.software.timemachine.service.*;
public class Init {
public static void initDatabase(IAlbumService<Album> albumService,ICategoryService<Category> categoryService,
ICommentService<SimpleComment> commentService,IFriendService<Friend> friendService,
IMessageService<Message> messageService,IPictureService<Picture> pictureService,IUserService<User> userService,IRoleService<Role> roleService){
Role userRole = new Role();
userRole.setDateCreated(new Date());
userRole.setName("user");
roleService.addRole(userRole);
Role adminRole = new Role();
adminRole.setDateCreated(new Date());
adminRole.setName("admin");
roleService.addRole(adminRole);
Friend friend = new Friend();
friend.setCategory(userService.getUser(1).getCategoryList().get(0));
friend.setDateCreated(new Date());
friend.setNikename("ljj");
friend.setUser(userService.getUser(2));
friendService.addFriend(friend, userService.getUser(2).getCategoryList().get(0));
Friend friend2 = new Friend();
friend2.setCategory(userService.getUser(1).getCategoryList().get(0));
friend2.setDateCreated(new Date());
friend2.setNikename("ljj");
friend2.setUser(userService.getUser(3));
friendService.addFriend(friend2, userService.getUser(3).getCategoryList().get(0));
/*
User user1=new User();
user1.setEmail("a@gmail.com");
user1.setName("ljj");
user1.setPassword("123456");
Calendar c=new GregorianCalendar();
c.set(2000, 0, 1);
user1.getUserMeta().setBirthday(c);
user1.getUserMeta().setCity("nanjing");
userService.addUser(user1);
User user2= new User();
user2.setEmail("b@gmail.com");
user2.setName("lhh");
user1.setPassword("234");
userService.addUser(user2);
Friend friend1 =new Friend();
friend1.setCategory(userService.getUser(1).getCategoryList().get(0));
friend1.setNikename("xiaohh");
friend1.setUser(userService.getUser(2));
friendService.addFriend(friend1,userService.getUser(2).getCategoryList().get(0));
Album album = new Album();
album.setName("MyAlbum");
album.setOwner(userService.getUser(1));
albumService.addAlbum(album);
Picture picture = new Picture();
picture.setAlbum(album);
//添加了用户lhh
addUserTest(userService,"利好换","dingli886@sina.com","123456",new GregorianCalendar(1991, 8, 30), "Changsha", "China", "male", "I'm lhh");
//添加与lhh相同用户名用户lhh_same_usrname
addUserTest(userService,"lhh","suck@sina.com","123456",new GregorianCalendar(1991, 8, 20), "Shanghai", "China", "female", "I'm not lhh");
//添加与lhh相同邮箱用户lhh_same_email
addUserTest(userService,"lgl","dingli886@sina.com","1234567",new GregorianCalendar(1992, 8, 20), "Beijing", "China", "male", "I'm not lhh too!");
//添加了用户LJJ
addUserTest(userService,"ljj", "ljj@gmail.com", "ljj213", new GregorianCalendar(1990, 10, 22), "Zhongshan", "China", "male", "I love SSH!");
addUserTest(userService,"qc", "qc@gmail.com", "ljj213", new GregorianCalendar(1993, 10, 22), "Zhongshan", "China", "male", "I love SSH!");
//根据邮箱查找用户
searchUserByEmailTest(userService, "dingli886@sina.com");
//根据用户名查找用户
User lhh=searchUserByNameTest(userService, "lhh").get(0);
Role userRole = new Role();
userRole.setDateCreated(new Date());
userRole.setName("user");
roleService.addRole(userRole);
Role adminRole = new Role();
adminRole.setDateCreated(new Date());
adminRole.setName("admin");
roleService.addRole(adminRole);
User user1=new User();
user1.setEmail("a@gmail.com");
user1.setName("ljj");
user1.setPassword("123456");
Calendar c=new GregorianCalendar();
c.set(2000, 0, 1);
user1.getUserMeta().setBirthday(c);
user1.getUserMeta().setCity("nanjing");
userService.addUser(user1);
User user2= new User();
user2.setEmail("b@gmail.com");
user2.setName("lhh");
user1.setPassword("234");
userService.addUser(user2);
Category category = new Category();
category.setName("default");
category.setOwner(userService.getUser(1));
categoryService.addCategory(category);
Category category2 = new Category();
category2.setName("default");
User u = userService.getUser(2);
category2.setOwner(u);
categoryService.addCategory(category2);
Friend friend1 =new Friend();
friend1.setCategory(userService.getUser(1).getCategoryList().get(0));
friend1.setNikename("xiaohh");
friend1.setUser(userService.getUser(2));
friendService.addFriend(friend1, userService.getUser(2).getCategoryList().get(0));
System.out.println(friend1.getCategory().getOwner().getId()+" "+friend1.getUser().getId());
//随机产生15个用户
for(int i=1;i<16;i++){
addUserTest(userService,"lhh"+String.valueOf(i),"user"+String.valueOf(i)+"@sina.com","user"+String.valueOf(i),new GregorianCalendar(1991, 8, i), "City"+String.valueOf(i%5), "Country"+String.valueOf(i%3), i%2==0?"male":"female", "I'm user"+String.valueOf("i"));
}
//System.out.println("执行第"+times+"次");
//每个用户添加一个相册
for(int j=1;j<16;j++){
addAlbumTest(albumService,userService.getUser(j),"Album"+String.valueOf(j));
}
//每个用户添加若干个好友分组
for(int k=1;k<16;k++){
if(k%2==0) addCategoryTest(categoryService, userService.getUser(k), "classmates");
if(k%3==0) addCategoryTest(categoryService, userService.getUser(k), "teachers");
if(k%5==0) addCategoryTest(categoryService, userService.getUser(k), "colleagues");
}
addFriendToRandomGroupTest(friendService, userService.getUser(12), userService.getUser(14),
userService.getUser(12).getName()+"'s Friend No."+String.valueOf(14));
//for(int i=0;i<userService.getUser(15).getCategoryList().size();i++)
// System.out.println("lhh15: 分组"+userService.getUser(15).getCategoryList().get(i).getName());
for(int m=1;m<16;m++){
int random=(int)(Math.random()*16);
System.out.println("rashjasj"+random);
for(int index=1;index<5;index++)
addFriendToRandomGroupTest(friendService, userService.getUser(m), userService.getUser((int)(Math.random()*13)), userService.getUser(m).getName()+"'s Friend No."+String.valueOf(index));
}
//添加了用户lhh
addUserTest(userService,"lhh","dingli886@sina.com","123456",new GregorianCalendar(1991, 8, 30), "Changsha", "China", "male", "I'm lhh");
//添加与lhh相同用户名用户lhh_same_usrname
addUserTest(userService,"lhh","suck@sina.com","123456",new GregorianCalendar(1991, 8, 20), "Shanghai", "China", "female", "I'm not lhh");
//添加与lhh相同邮箱用户lhh_same_email
addUserTest(userService,"lgl","dingli886@sina.com","1234567",new GregorianCalendar(1992, 8, 20), "Beijing", "China", "male", "I'm not lhh too!");
//添加了用户LJJ
addUserTest(userService,"ljj", "ljj@gmail.com", "ljj213", new GregorianCalendar(1990, 10, 22), "Zhongshan", "China", "male", "I love SSH!");
//根据邮箱查找用户
searchUserByEmailTest(userService, "dingli886@sina.com");
//根据用户名查找用户
User lhh=searchUserByNameTest(userService, "lhh").get(0);
*/
}
/*
private static List<User> searchUserByEmailTest(IUserService<User> userService,String email){
List<User> user_list=(List<User>) userService.searchUserByEmail(email);
for(int i=0;i<user_list.size();i++){
System.out.print(user_list.get(i).getName());
}
System.out.println();
return user_list;
}
private static List<User> searchUserByNameTest(IUserService<User> userService,String name){
List<User> user_list=userService.searchUserByName("lhh");
for(int i=0;i<user_list.size();i++){
System.out.print(user_list.get(i).getEmail());
}
System.out.println();
return user_list;
}
private static boolean addUserTest(IUserService<User> userService,String username, String email, String password,
Calendar birthday, String city, String country, String sex,
String otherstuff) {
User lhh = new User();
lhh.setEmail(email);
lhh.setName(username);
lhh.setPassword(password);
lhh.getUserMeta().setBirthday(birthday);
lhh.getUserMeta().setCity(city);
lhh.getUserMeta().setCountry(country);
lhh.getUserMeta().setSex(sex);
lhh.getUserMeta().setOtherStuff(otherstuff);
boolean flag=userService.addUser(lhh);
if(flag) System.out.println("添加用户"+lhh.getName()+"/"+lhh.getEmail()+" 成功!");
else System.out.println("添加用户"+lhh.getName()+"/"+lhh.getEmail()+" 失败!");
return flag;
}
private static boolean addAlbumTest(IAlbumService<Album> albumService,User user,String name){
boolean flag=false;
Album album = new Album();
album.setName(name);
album.setOwner(user);
flag=albumService.addAlbum(album);
System.out.println("用户"+user.getName()+"添加相册"+album.getName()+new String(flag?"成功!":"失败!"));
return flag;
}
private static boolean addCategoryTest(ICategoryService<Category> categoryService,User user,String cate_name){
boolean flag=false;
Category cater=new Category();
cater.setName(cate_name);
cater.setOwner(user);
flag=categoryService.addCategory(cater);
System.out.println(user.getName()+"添加分组:"+cater.getName()+new String(flag?"成功!":"失败!"));
return flag;
}
private static boolean addFriendToRandomGroupTest(IFriendService<Friend> friendService,User invitor,User invitee,String nickname){
boolean flag=false;
Friend friend=new Friend();
int num_of_groups=invitor.getCategoryList().size();
friend.setCategory(invitor.getCategoryList().get(0));
friend.setNikename(nickname);
friend.setUser(invitee);
Category category2 = new Category();
category2.setName("default");
User u = userService.getUser(2);
category2.setOwner(u);
categoryService.addCategory(category2);
//flag=friendService.addFriend(friend, invitee.getCategoryList().get(0));
System.out.println(invitor.getName()+"添加好友:"+invitee.getName()+new String(flag?"成功!":"失败!"));
return flag;
}*/
}
|
package com.example.idp4;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
public class BluetoothConnectionServ
{
private BluetoothAdapter bluetoothAdapter ;
private Set<BluetoothDevice> pairedDevices;
private String[] addr ;
private static final UUID MY_UUID =
UUID.fromString("00001101-0000-1000-8000-00805f9b34fb") ;
private String mac ;
private BluetoothDevice remoteDevice ;
private BluetoothSocket mmSocket ;
private String name ;
/**
* Initializes a Bluetooth connection and add the paired devices to a
* spinner (given as parameter). The spinner item selected by the user
* will be the paired device to connect to.
* <p>
* If a Bluetooth connection is impossible (for reasons such as : no
* Bluetooth adapter are available, the user didn't enable Bluetooth,
* etc.) an exception will be thrown.
*
* @param a the activity in which context the Bluetooth connection
* has to be held.
* @param spin a spinner to which this constructor will add the
* paired devices.
* @throws BluetoothException
*/
BluetoothConnectionServ(String name) throws BluetoothException
{
this.name = name ;
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter() ;
if (bluetoothAdapter == null)
throw new BluetoothException
("No bluetooth adapter has been found!") ;
else
{
if(!bluetoothAdapter.isEnabled())
{
throw new BluetoothException
("Bluetooth must be enabled!") ;
}
}
pairedDevices = bluetoothAdapter.getBondedDevices() ;
List<String> list = new ArrayList<String>() ;
int nbPairedDevices = pairedDevices.size() ;
if (nbPairedDevices > 0)
{
addr = new String[pairedDevices.size()] ;
int k = 0 ;
for (BluetoothDevice device : pairedDevices)
{
addr[k] = device.getAddress() ;
list.add(device.getName()) ;
k++ ;
}
}
else
throw new BluetoothException("No paired devices") ;
mac = addr[list.indexOf(name)] ;
}
public BluetoothSocket getBluetoothSocket() throws BluetoothException
{
try
{
remoteDevice = bluetoothAdapter.getRemoteDevice(mac);
}
catch (IllegalArgumentException e0)
{
throw new BluetoothException("Not a valid MAC address!");
}
try
{
mmSocket = remoteDevice.createRfcommSocketToServiceRecord(MY_UUID);
return mmSocket ;
}
catch(IOException e)
{
throw new BluetoothException(e.toString()) ;
}
}
}
|
package juniorandkarlson;
public class Play implements Group {
private final Human[] notfamily1 = new Human[10];
private final Human[] family1 = new Human[10];
private int notfamily = 0;
private int countfamily1 = 0;
private int love = 0;
public void addnotfamily(Human var1){
notfamily1[notfamily] = var1;
notfamily += 1;
}
public void addfamily(Human var1){
family1[countfamily1] = var1;
countfamily1 += 1;
}
public void play(){
Parent[] parents = makeparents();
Child[] children = makechildren();
for (int i = 0; i < 2; i++){
if (parents[i].getActivity()){
for (int j = 0; j < countfamily1; j++) {
if (((family1[j].hashCode() > 2000) && (family1[j].getGender() != family1[i].getGender())) || ((family1[j].getStatus() == Status.CHILD) && (family1[j].getPersonality() == Personality.GOOD))) {
love += 1;
}
}
parents[i].laugh();
System.out.println(ifthen(parents[i]));
break;
}
}
for (Child child : children) {
if (child.getActivity()) {
Child couple = findcouple(child);
System.out.print(talk(couple, child) + child.thoughts());
enumerate(child);
child.husbandWife();
break;
}
}
}
public Child[] makechildren() {
int countparents = 0;
Child[] makechildren = new Child [10];
for (int i = 0; i< countfamily1; i++){
if (family1[i].getStatus() == Status.CHILD) {
makechildren[countparents] = (Child) family1[i];
countparents ++;
}
}
return makechildren;
}
public Parent[] makeparents() {
int countparents = 0;
Parent[] makeparents = new Parent [2];
for (int i = 0; i< countfamily1; i++){
if (family1[i].hashCode() > 2000){
makeparents[countparents] = (Parent) family1[i];
countparents ++;
}
}
return makeparents;
}
public String ifthen(Parent parent) {
String s = "";
if (parent.getActivity()) {
switch (love) {
case 1:
s = "ты меня любишь, значит я ";
s += parent.good();
break;
case 2:
s = "вы оба меня любите, значит я ";
s += parent.good();
break;
case 0:
s = "никто меня не любит, значит я ";
s += parent.bad();
break;
default:
s = "много людей меня любят, значит я ";
s += parent.good();
break;
}
}
return s;
}
public String talk(Child couple, Child themain){
String s = "";
if (couple == null) {
s = themain.sigh();
} else {
s += sighelse(couple, themain) + themain.pause() + themain.think() + themain.doubt() + " будет не очень приятно жить вместе с " + couple.toString() + reason(couple);
}
return s;
}
public String reason(Child couple) {
String s = "";
if (couple.getPersonality() == Personality.BAD) {
if (couple.getGender() == Gender.FEMALE) {
s += ", потому что с ней трудно ладить. ";
} else {
s += ", потому что с ним трудно ладить. ";
}
} else {
if (couple.getGender() == Gender.FEMALE) {
s += ", хотя с ней и дружу. ";
} else {
s += ", хотя с ним и дружу. ";
}
}
return s;
}
public Child findcouple(Human h){
Child abstract_human = null;
for (int i = 0; i < notfamily; i++){
if (notfamily1[i].getGender() != h.getGender()){
abstract_human = (Child) notfamily1[i];
break;
}
}
return abstract_human;
}
public String sighelse(Child couple, Child themain){
if (themain.getGender() == Gender.MALE) {
return "Ну, тогда я женюсь на " + couple.toString() + ", - вздохнул " + themain.toString() + ". – Ведь надо же мне будет на ком-нибудь жениться!\n";
}else{
return "Ну, тогда я выйду замуж за " + couple.toString() + ", - вздохнула " + themain.toString() + ". – Ведь надо же мне будет выйти замуж за кого-нибудь!\n";
}
}
public void enumerate(Human h){
Human[] l = new Human[countfamily1];
int k = 0;
// Список всех, кого надо перечислить
for (int j = 0; j < countfamily1; j++){
if (!h.equals(family1[j])){
l[k] = family1[j];
k += 1;
}
}
//Само перечисление
if (k > 1) {
for (int j = 0; j < k - 2; j++) {
System.out.print(l[j].toString());
System.out.print(", ");
}
System.out.print(l[k-2].toString() + " и " + l[k-1].toString());
}else{
System.out.println(l[0].toString());
}
}
}
|
package com.zaozuo.zmall.order.controller;
import com.zaozuo.zmall.api.IUserController;
import com.zaozuo.zmall.common.entity.Order;
import com.zaozuo.zmall.common.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.UUID;
/**
* @author fengqi
*/
@RequestMapping("/zmall/order")
@RestController
public class OrderController {
@Autowired
IUserController userService;
@RequestMapping("/{id}")
public Order getOrder(@PathVariable String id) {
User user = userService.getUser(id);
Order order = new Order();
order.setId(id);
if (user != null) {
order.setUserId(user.getId());
order.setUser(user);
}
order.setOrderSn(UUID.randomUUID().toString());
return order;
}
}
|
package org.isokissa.sananmuunnos;
import java.util.List;
public class SananmuunnosService {
public static String muunna(String inputWords) {
List<String> tokens = Splitter.splitToTokens(inputWords);
if (tokens.size() < 2) {
return inputWords;
}
StringBuilder result = new StringBuilder();
int currentToken = 0;
boolean isFirstTokenSpace = isSpaceToken(tokens.get(currentToken));
if (isFirstTokenSpace) {
result.append(tokens.get(currentToken++));
}
while (currentToken < tokens.size() - 1) {
Splitter.WordParts firstWord = Splitter.splitWord(tokens.get(currentToken++));
Splitter.WordParts secondWord = Splitter.splitWord(tokens.get(currentToken++));
result.append(secondWord.getBeginning());
result.append(firstWord.getRest());
result.append(firstWord.getBeginning());
result.append(secondWord.getRest());
}
while (currentToken < tokens.size()) {
result.append(tokens.get(currentToken++));
}
return result.toString();
}
private static boolean isSpaceToken(String token) {
return token.charAt(0) == ' ';
}
}
|
/*
* CombineGenotypeTable
*/
package net.maizegenetics.dna.snp;
import net.maizegenetics.dna.snp.bit.BitStorage;
import net.maizegenetics.dna.snp.depth.AlleleDepth;
import net.maizegenetics.dna.snp.genotypecall.GenotypeCallTable;
import net.maizegenetics.dna.map.Chromosome;
import net.maizegenetics.dna.map.PositionList;
import net.maizegenetics.taxa.TaxaList;
import net.maizegenetics.taxa.TaxaListUtils;
import net.maizegenetics.util.BitSet;
import java.util.*;
/**
* Combines multiple GenotypeTables together.
*
* @author Terry Casstevens
*/
public class CombineGenotypeTable implements GenotypeTable {
private static final long serialVersionUID = -5197800047652332969L;
private final GenotypeTable[] myAlignments;
private final int[] mySiteOffsets;
private final Map<Chromosome, GenotypeTable> myChromosomes = new HashMap<>();
private Chromosome[] myChromosomesList;
private int[] myChromosomesOffsets;
private final TaxaList myTaxaList;
private String[][] myAlleleStates;
private CombineGenotypeTable(TaxaList taxaList, GenotypeTable[] genoTables) {
myTaxaList = taxaList;
myAlignments = genoTables;
mySiteOffsets = new int[genoTables.length + 1];
mySiteOffsets[0] = 0;
int count = 0;
for (int i = 0; i < genoTables.length; i++) {
count = genoTables[i].numberOfSites() + count;
mySiteOffsets[i + 1] = count;
Chromosome[] chromosomes = genoTables[i].chromosomes();
for (int j = 0; j < chromosomes.length; j++) {
myChromosomes.put(chromosomes[j], genoTables[i]);
}
}
initChromosomes();
}
/**
* This factory method combines given genoTables. If only one genotypeTable,
* then it is returned unchanged. Otherwise, this requires that each
* genotypeTable has the same Taxa in the same order.
*
* @param genoTables
* @return
*/
public static GenotypeTable getInstance(GenotypeTable[] genoTables) {
if ((genoTables == null) || (genoTables.length == 0)) {
throw new IllegalArgumentException("CombineAlignment: getInstance: must provide genoTables.");
}
if (genoTables.length == 1) {
return genoTables[0];
}
TaxaList firstGroup = genoTables[0].taxa();
for (int i = 1; i < genoTables.length; i++) {
if (!areTaxaListsEqual(firstGroup, genoTables[i].taxa())) {
throw new IllegalArgumentException("CombineAlignment: getInstance: TaxaLists do not match.");
}
}
return new CombineGenotypeTable(firstGroup, genoTables);
}
/**
* This factory method combines given genoTables. If only one genotypeTable,
* then it is returned unchanged. If isUnion equals true, a union join of
* the Identifiers will be used to construct the combination. Any genotypeTable
* not containing one of the Identifiers will return unknown value for those
* locations. If isUnion equals false, a intersect join of the Identifiers
* will be used.
*
* @param genoTables genoTables to combine
* @param isUnion whether to union or intersect join
* @return
*/
public static GenotypeTable getInstance(GenotypeTable[] genoTables, boolean isUnion) {
if ((genoTables == null) || (genoTables.length == 0)) {
throw new IllegalArgumentException("CombineAlignment: getInstance: must provide genoTables.");
}
if (genoTables.length == 1) {
return genoTables[0];
}
TaxaList[] groups = new TaxaList[genoTables.length];
for (int i = 0; i < genoTables.length; i++) {
groups[i] = genoTables[i].taxa();
}
TaxaList newTaxa = null;
if (isUnion) {
newTaxa = TaxaListUtils.getAllTaxa(groups);
} else {
newTaxa = TaxaListUtils.getCommonTaxa(groups);
}
GenotypeTable[] newAlignmentNews = new GenotypeTable[genoTables.length];
for (int i = 0; i < genoTables.length; i++) {
newAlignmentNews[i] = FilterGenotypeTable.getInstance(genoTables[i], newTaxa);
}
return new CombineGenotypeTable(newTaxa, newAlignmentNews);
}
private static boolean areTaxaListsEqual(TaxaList first, TaxaList second) {
if (first.numberOfTaxa() != second.numberOfTaxa()) {
return false;
}
for (int i = 0, n = first.numberOfTaxa(); i < n; i++) {
if (!first.get(i).equals(second.get(i))) {
return false;
}
}
return true;
}
private void initChromosomes() {
List<Integer> offsets = new ArrayList<>();
List<Chromosome> chromosomes = new ArrayList<>();
for (int i = 0; i < myAlignments.length; i++) {
chromosomes.addAll(Arrays.asList(myAlignments[i].chromosomes()));
int[] tempOffsets = myAlignments[i].chromosomesOffsets();
for (int j = 0; j < tempOffsets.length; j++) {
offsets.add(tempOffsets[j] + mySiteOffsets[i]);
}
}
myChromosomesList = new Chromosome[chromosomes.size()];
myChromosomesList = chromosomes.toArray(myChromosomesList);
myChromosomesOffsets = new int[offsets.size()];
for (int i = 0; i < offsets.size(); i++) {
myChromosomesOffsets[i] = (Integer) offsets.get(i);
}
if (myChromosomesOffsets.length != myChromosomesList.length) {
throw new IllegalStateException("CombineAlignment: initChromosomes: number chromosomes offsets should equal number of chromosomes.");
}
}
public byte genotype(int taxon, int site) {
int translate = translateSite(site);
return myAlignments[translate].genotype(taxon, site - mySiteOffsets[translate]);
}
@Override
public byte[] genotypeRange(int taxon, int startSite, int endSite) {
byte[] result = new byte[endSite - startSite];
int count = 0;
int firstAlign = translateSite(startSite);
int secondAlign = translateSite(endSite);
for (int i = firstAlign; i <= secondAlign; i++) {
int firstSite = 0;
if (i == firstAlign) {
firstSite = startSite - mySiteOffsets[firstAlign];
}
int secondSite = 0;
if (firstAlign == secondAlign) {
secondSite = endSite - mySiteOffsets[firstAlign];
} else if (i != secondAlign) {
secondSite = myAlignments[i].numberOfSites();
} else {
secondSite = endSite - mySiteOffsets[secondAlign];
}
for (int s = firstSite; s < secondSite; s++) {
result[count++] = myAlignments[i].genotype(taxon, s);
}
}
return result;
}
@Override
public byte genotype(int taxon, Chromosome locus, int physicalPosition) {
int site = siteOfPhysicalPosition(physicalPosition, locus);
int translate = translateSite(site);
return myAlignments[translate].genotype(taxon, site - mySiteOffsets[translate]);
}
/**
* Returns which genotypeTable to use.
*
* @param site
* @return genotypeTable index.
*/
public int translateSite(int site) {
for (int i = 1; i < mySiteOffsets.length; i++) {
if (mySiteOffsets[i] > site) {
return i - 1;
}
}
throw new IndexOutOfBoundsException("CombineAlignment: translateSite: index out of range: " + site);
}
@Override
public boolean hasReference() {
for (int i = 0; i < myAlignments.length; i++) {
if (!myAlignments[i].hasReference()) {
return false;
}
}
return true;
}
@Override
public String siteName(int site) {
int translate = translateSite(site);
return myAlignments[translate].siteName(site - mySiteOffsets[translate]);
}
@Override
public int numberOfSites() {
return mySiteOffsets[mySiteOffsets.length - 1];
}
@Override
public int chromosomeSiteCount(Chromosome locus) {
return ((GenotypeTable) myChromosomes.get(locus)).chromosomeSiteCount(locus);
}
@Override
public int chromosomalPosition(int site) {
int translate = translateSite(site);
return myAlignments[translate].chromosomalPosition(site - mySiteOffsets[translate]);
}
@Override
public int siteOfPhysicalPosition(int physicalPosition, Chromosome locus) {
GenotypeTable align = ((GenotypeTable) myChromosomes.get(locus));
int i = -1;
for (int j = 0; j < myAlignments.length; j++) {
if (myAlignments[j] == align) {
i = j;
break;
}
}
if (i == -1) {
return -1;
}
return mySiteOffsets[i] + align.siteOfPhysicalPosition(physicalPosition, locus);
}
@Override
public int siteOfPhysicalPosition(int physicalPosition, Chromosome locus, String snpName) {
GenotypeTable align = ((GenotypeTable) myChromosomes.get(locus));
int i = -1;
for (int j = 0; j < myAlignments.length; j++) {
if (myAlignments[j] == align) {
i = j;
break;
}
}
if (i == -1) {
return -1;
}
return mySiteOffsets[i] + align.siteOfPhysicalPosition(physicalPosition, locus, snpName);
}
@Override
public Chromosome chromosome(int site) {
int translate = translateSite(site);
return myAlignments[translate].chromosome(site - mySiteOffsets[translate]);
}
@Override
public Chromosome[] chromosomes() {
return myChromosomesList;
}
@Override
public int numChromosomes() {
if (myChromosomesList == null) {
return 0;
} else {
return myChromosomesList.length;
}
}
@Override
public float[][] siteScores() {
if (!hasSiteScores()) {
return null;
}
int numSeqs = numberOfTaxa();
float[][] result = new float[numSeqs][numberOfSites()];
for (int a = 0, n = myAlignments.length; a < n; a++) {
if (myAlignments[a].hasSiteScores()) {
for (int s = 0, m = myAlignments[a].numberOfSites(); s < m; s++) {
for (int t = 0; t < numSeqs; t++) {
result[t][mySiteOffsets[a] + s] = myAlignments[a].siteScore(t, s);
}
}
}
}
return result;
}
@Override
public float siteScore(int taxon, int site) {
int translate = translateSite(site);
return myAlignments[translate].siteScore(taxon, site - mySiteOffsets[translate]);
}
@Override
public boolean hasSiteScores() {
for (GenotypeTable align : myAlignments) {
if (align.hasSiteScores()) {
return true;
}
}
return false;
}
@Override
public int indelSize(int site) {
int translate = translateSite(site);
return myAlignments[translate].indelSize(site - mySiteOffsets[translate]);
}
@Override
public boolean isIndel(int site) {
int translate = translateSite(site);
return myAlignments[translate].isIndel(site - mySiteOffsets[translate]);
}
@Override
public byte referenceAllele(int site) {
int translate = translateSite(site);
return myAlignments[translate].referenceAllele(site - mySiteOffsets[translate]);
}
@Override
public GenotypeTable[] compositeAlignments() {
return myAlignments;
}
@Override
public byte majorAllele(int site) {
int translate = translateSite(site);
return myAlignments[translate].majorAllele(site - mySiteOffsets[translate]);
}
@Override
public byte minorAllele(int site) {
int translate = translateSite(site);
return myAlignments[translate].minorAllele(site - mySiteOffsets[translate]);
}
@Override
public byte[] minorAlleles(int site) {
int translate = translateSite(site);
return myAlignments[translate].minorAlleles(site - mySiteOffsets[translate]);
}
@Override
public byte[] alleles(int site) {
int translate = translateSite(site);
return myAlignments[translate].alleles(site - mySiteOffsets[translate]);
}
@Override
public double minorAlleleFrequency(int site) {
int translate = translateSite(site);
return myAlignments[translate].minorAlleleFrequency(site - mySiteOffsets[translate]);
}
@Override
public int[][] allelesSortedByFrequency(int site) {
int translate = translateSite(site);
return myAlignments[translate].allelesSortedByFrequency(site - mySiteOffsets[translate]);
}
@Override
public byte[] genotypeArray(int taxon, int site) {
int translate = translateSite(site);
return myAlignments[translate].genotypeArray(taxon, site - mySiteOffsets[translate]);
}
@Override
public byte[] genotypeAllTaxa(int site) {
byte[] result = new byte[numberOfTaxa()];
int offset=0;
for (int i = 0; i < myAlignments.length; i++) {
byte[] current = myAlignments[i].genotypeAllTaxa(site);
System.arraycopy(current, 0, result, offset, current.length);
offset+=current.length;
}
return result;
}
@Override
public byte[] genotypeAllSites(int taxon) {
byte[] result = new byte[numberOfSites()];
for (int i = 0; i < myAlignments.length; i++) {
byte[] current = myAlignments[i].genotypeAllSites(taxon);
System.arraycopy(current, 0, result, myChromosomesOffsets[i], current.length);
}
return result;
}
@Override
public BitSet allelePresenceForAllSites(int taxon, WHICH_ALLELE allele) {
throw new UnsupportedOperationException("CombineAlignment: getAllelePresenceForAllSites: This operation isn't possible as it spans multiple GenotypeTables.");
}
@Override
public long[] allelePresenceForSitesBlock(int taxon, WHICH_ALLELE allele, int startBlock, int endBlock) {
throw new UnsupportedOperationException("CombineAlignment: getAllelePresenceForSitesBlock: This operation isn't possible as it spans multiple GenotypeTables.");
}
@Override
public String genotypeAsString(int taxon, int site) {
int translate = translateSite(site);
return myAlignments[translate].genotypeAsString(taxon, site - mySiteOffsets[translate]);
}
@Override
public String[] genotypeAsStringArray(int taxon, int site) {
int translate = translateSite(site);
return myAlignments[translate].genotypeAsStringArray(taxon, site - mySiteOffsets[translate]);
}
@Override
public byte[] referenceAlleles(int startSite, int endSite) {
int numSites = endSite - startSite;
byte[] result = new byte[numSites];
for (int i = 0; i < numSites; i++) {
result[i] = referenceAllele(startSite + i);
}
return result;
}
@Override
public byte[] referenceAlleleForAllSites() {
for (int i = 0; i < myAlignments.length; i++) {
if (!myAlignments[i].hasReference()) {
return null;
}
}
byte[] result = new byte[numberOfSites()];
int count = 0;
for (int i = 0; i < myAlignments.length; i++) {
byte[] current = myAlignments[i].referenceAlleleForAllSites();
for (int j = 0; j < current.length; j++) {
result[count++] = current[j];
}
}
return result;
}
@Override
public boolean isHeterozygous(int taxon, int site) {
int translate = translateSite(site);
return myAlignments[translate].isHeterozygous(taxon, site - mySiteOffsets[translate]);
}
@Override
public int[] physicalPositions() {
boolean allNull = true;
for (int i = 0; i < myAlignments.length; i++) {
int[] current = myAlignments[0].physicalPositions();
if ((current != null) && (current.length != 0)) {
allNull = false;
break;
}
}
if (allNull) {
return null;
} else {
int[] result = new int[numberOfSites()];
int count = 0;
for (int i = 0; i < myAlignments.length; i++) {
int[] current = myAlignments[i].physicalPositions();
for (int j = 0; j < current.length; j++) {
result[count++] = current[j];
}
}
return result;
}
}
@Override
public String chromosomeName(int site) {
int translate = translateSite(site);
return myAlignments[translate].chromosomeName(site - mySiteOffsets[translate]);
}
@Override
public int[] chromosomesOffsets() {
return myChromosomesOffsets;
}
@Override
public SITE_SCORE_TYPE siteScoreType() {
SITE_SCORE_TYPE first = myAlignments[0].siteScoreType();
for (int i = 1; i < myAlignments.length; i++) {
if (first != myAlignments[i].siteScoreType()) {
return SITE_SCORE_TYPE.MixedScoreTypes;
}
}
return first;
}
@Override
public boolean isAllPolymorphic() {
for (int i = 0; i < myAlignments.length; i++) {
if (!myAlignments[i].isAllPolymorphic()) {
return false;
}
}
return true;
}
@Override
public boolean isPolymorphic(int site) {
int translate = translateSite(site);
return myAlignments[translate].isPolymorphic(site - mySiteOffsets[translate]);
}
@Override
public double majorAlleleFrequency(int site) {
int translate = translateSite(site);
return myAlignments[translate].majorAlleleFrequency(site - mySiteOffsets[translate]);
}
@Override
public String genomeVersion() {
String first = myAlignments[0].genomeVersion();
if (first == null) {
return null;
}
for (int i = 1; i < myAlignments.length; i++) {
String current = myAlignments[i].genomeVersion();
if ((current != null) && (!first.equals(current))) {
return null;
}
}
return first;
}
@Override
public boolean isPositiveStrand(int site) {
int translate = translateSite(site);
return myAlignments[translate].isPositiveStrand(site - mySiteOffsets[translate]);
}
@Override
public boolean isPhased() {
for (int i = 0; i < myAlignments.length; i++) {
if (myAlignments[i].isPhased() == false) {
return false;
}
}
return true;
}
@Override
public boolean retainsRareAlleles() {
for (int i = 0; i < myAlignments.length; i++) {
if (myAlignments[i].retainsRareAlleles() == false) {
return false;
}
}
return true;
}
@Override
public String[][] alleleDefinitions() {
if (myAlleleStates != null) {
return myAlleleStates;
}
boolean allTheSame = true;
String[][] encodings = myAlignments[0].alleleDefinitions();
if (encodings.length == 1) {
for (int i = 1; i < myAlignments.length; i++) {
String[][] current = myAlignments[i].alleleDefinitions();
if ((current.length == 1) && (encodings[0].length == current[0].length)) {
for (int j = 0; j < encodings[0].length; j++) {
if (!current[0][j].equals(encodings[0][j])) {
allTheSame = false;
break;
}
}
} else {
allTheSame = false;
break;
}
if (!allTheSame) {
break;
}
}
} else {
allTheSame = false;
}
if (allTheSame) {
myAlleleStates = encodings;
} else {
String[][] result = new String[numberOfSites()][];
int count = 0;
for (int i = 0; i < myAlignments.length; i++) {
for (int j = 0, n = myAlignments[i].numberOfSites(); j < n; j++) {
result[count++] = myAlignments[i].alleleDefinitions(j);
}
}
myAlleleStates = result;
}
return myAlleleStates;
}
@Override
public String[] alleleDefinitions(int site) {
int translate = translateSite(site);
return myAlignments[translate].alleleDefinitions(site - mySiteOffsets[translate]);
}
@Override
public String genotypeAsString(int site, byte value) {
int translate = translateSite(site);
return myAlignments[translate].genotypeAsString(site - mySiteOffsets[translate], value);
}
@Override
public int maxNumAlleles() {
int result = 999999;
for (int i = 0; i < myAlignments.length; i++) {
if (myAlignments[i].maxNumAlleles() < result) {
result = myAlignments[i].maxNumAlleles();
}
}
return result;
}
@Override
public int totalGametesNonMissingForSite(int site) {
int translate = translateSite(site);
return myAlignments[translate].totalGametesNonMissingForSite(site - mySiteOffsets[translate]);
}
@Override
public int heterozygousCount(int site) {
int translate = translateSite(site);
return myAlignments[translate].heterozygousCount(site - mySiteOffsets[translate]);
}
@Override
public int minorAlleleCount(int site) {
int translate = translateSite(site);
return myAlignments[translate].minorAlleleCount(site - mySiteOffsets[translate]);
}
@Override
public int majorAlleleCount(int site) {
int translate = translateSite(site);
return myAlignments[translate].majorAlleleCount(site - mySiteOffsets[translate]);
}
@Override
public Object[][] genosSortedByFrequency(int site) {
int translate = translateSite(site);
return myAlignments[translate].genosSortedByFrequency(site - mySiteOffsets[translate]);
}
@Override
public byte[] allelesBySortType(ALLELE_SORT_TYPE scope, int site) {
int translate = translateSite(site);
return myAlignments[translate].allelesBySortType(scope, site - mySiteOffsets[translate]);
}
@Override
public BitSet allelePresenceForAllTaxa(int site, WHICH_ALLELE allele) {
int translate = translateSite(site);
return myAlignments[translate].allelePresenceForAllTaxa(site - mySiteOffsets[translate], allele);
}
@Override
public BitSet haplotypeAllelePresenceForAllSites(int taxon, boolean firstParent, WHICH_ALLELE allele) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public BitSet haplotypeAllelePresenceForAllTaxa(int site, boolean firstParent, WHICH_ALLELE allele) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public long[] haplotypeAllelePresenceForSitesBlock(int taxon, boolean firstParent, WHICH_ALLELE allele, int startBlock, int endBlock) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String genotypeAsStringRange(int taxon, int startSite, int endSite) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String genotypeAsStringRow(int taxon) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int[] firstLastSiteOfChromosome(Chromosome chromosome) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int numberOfTaxa() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Chromosome chromosome(String name) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String majorAlleleAsString(int site) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String minorAlleleAsString(int site) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public TaxaList taxa() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String taxaName(int index) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String diploidAsString(int site, byte value) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int totalNonMissingForSite(int site) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Object[][] genoCounts() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Object[][] majorMinorCounts() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int totalGametesNonMissingForTaxon(int taxon) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int heterozygousCountForTaxon(int taxon) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int totalNonMissingForTaxon(int taxon) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean hasDepth() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public AlleleDepth depth() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int[] depthForAlleles(int taxon, int site) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public BitStorage bitStorage(WHICH_ALLELE allele) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public PositionList positions() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public GenotypeCallTable genotypeMatrix() {
throw new UnsupportedOperationException("Not supported yet.");
}
}
|
package com.bear.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* This is a web page redirect Controller
*
* Created by nick on 2017/5/26.
*/
@Controller
public class WebPageController {
@RequestMapping(path = "/index")
public String index(){
return "index";
}
@RequestMapping(path = "/welcome")
public String welcome(){
return "welcome";
}
}
|
package day07;
public class Rectangle01 extends Shape01{
@Override
void draw() {
// TODO Auto-generated method stub
System.out.println("Draw rectangle is called");
}
}
|
package com.stk123.task.strategy;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import com.stk123.model.Index;
import com.stk123.model.K;
public class Strategy19 extends Strategy {
public Strategy19(){
this(null,null,false,true);
}
public Strategy19(String dataSourceName, List<Index> indexs, boolean sendMail, boolean logToDB){
super(dataSourceName, indexs, sendMail, logToDB);
}
@Override
public void run(Connection conn, String today) throws Exception {
List<Index> results = new ArrayList<Index>();
for(Index index : indexs){
if(index.isStop(today))continue;
List<List<K>> list1 = index.isBreakOutTrendLine3(today, 10, 2, 0);
if(list1.size() > 0 || index.isBreakOutShortTrendLine(today)){
results.add(index);
}
List<List<K>> list2 = index.isBreakOutTrendLine3(today, 60, 5, 0);
if(list2.size() > 0 || index.isBreakOutTrendLine2(today,60,6,0.05)){
results.add(index);
}
}
if(results.size() > 0){
super.logStrategy(conn, today, "丁垂19-往它宅找阿", results);
}
}
}
|
package com.rharo.jpastreamer.model;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import lombok.Getter;
import lombok.Setter;
@Entity
@Getter
@Setter
public class Car {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String color;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "brand_id")
private Brand brand;
private String model;
}
|
package com.zareca.decorator;
/**
* @Auther: ly
* @Date: 2020/10/19 22:27
* @Description:
*/
public class SausageDecorator extends BattercakeDecorator {
@Override
public void doSomething() {
}
public SausageDecorator(Battercake battercake) {
super(battercake);
}
@Override
protected String getMsg() {
return super.getMsg() + "+1根香肠";
}
@Override
protected int getPrice() {
return super.getPrice() + 2;
}
}
|
package xtrus.ex.mci.test;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelConfig;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.junit.Before;
import org.junit.Test;
import xtrus.ex.mci.ExMciException;
import xtrus.ex.mci.Utils;
import xtrus.ex.mci.message.MciMessage;
public class MciClientTest {
private void startServer(int port) throws Exception {
// Configure the server.
ServerBootstrap bootstrap = new ServerBootstrap(
new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));
// Set up the pipeline factory.
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
public ChannelPipeline getPipeline() {
ChannelPipeline p = Channels.pipeline(
new MciFrameDecoder("SERVER-"),
new MciServerMessageHandler());
return p;
}
});
bootstrap.setOption("child.tcpNoDelay", true);
bootstrap.setOption("child.keepAlive", true);
bootstrap.bind(new InetSocketAddress(port));
}
@Before
public void init() throws Exception {
// startServer(9999);
System.out.println("Server started.");
}
@Test
public void send() throws Exception {
ClientBootstrap bootstrap = new ClientBootstrap(
new NioClientSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));
try {
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
public ChannelPipeline getPipeline() {
return Channels.pipeline(
new MciFrameDecoder("CLIENT-"),
new MciMessageHandler());
}
});
bootstrap.setOption("tcpNoDelay", true);
bootstrap.setOption("receiveBufferSize", 1048576);
bootstrap.setOption("sendBufferSize", 1048576);
ChannelFuture connectFuture = bootstrap.connect(new InetSocketAddress("localhost", 9200));
connectFuture.sync();
// send message
Channel channel = connectFuture.getChannel();
sendMessage(0, channel);
// Close the connection.
channel.close().sync();
} finally {
// Shutdown all thread pools to exit.
bootstrap.releaseExternalResources();
}
}
private void sendMessage(int idx, Channel channel) throws Exception, ExMciException,
InterruptedException {
// send to server.
StringBuffer buffer = new StringBuffer();
buffer.append(createHeader());
buffer.append(createData());
buffer.append("@@");
int size = buffer.length();
buffer.insert(0, Utils.writeToNumeric(String.valueOf(size), 8));
byte[] sendingData = buffer.toString().getBytes();
MciMessageHandler handler = channel.getPipeline().get(MciMessageHandler.class);
MciMessage responseMessage = handler.sendMessage(sendingData);
System.out.println("["+idx+"] CLIENT RECEIVED : "+new String(responseMessage.unmarshal()));
}
private String createHeader() throws Exception {
StringBuffer header = new StringBuffer();
// 글로벌 ID 정보
header.append("0000"); // 시스템코드
header.append(" "); // 근무일자
header.append(" "); // 근무번호
header.append(Utils.writeToNumeric("15123001", 8)); // 일련번호
header.append(Utils.writeToNumeric("15123001", 8)); // 전송연번
// 시스템 정보
header.append("111100"); //송신지 시스템 코드
header.append("222200"); // 수신지 시스템 코드
header.append("0001"); // 전송 식별번호
// 정보처리 정보
header.append("M"); // 거래구분(M/F)
header.append("S"); // 요청응답구분(S/R)
header.append("S"); // 동기화 구분
header.append("20151230085600000"); // 요청 일시
// 서비스 정보
header.append("CS10000010 "); // 요청 서비스 코드
header.append(" "); // 결과 수신 서비스 코드
// 응답결과 정보
header.append(Utils.writeToString(" ", 17)); // 응답일시
header.append(Utils.writeToString(" ", 1)); // 처리결과코드
header.append(Utils.writeToString(" ", 1)); // 응답전문유형코드
header.append(Utils.writeToString(" ", 3)); // 연속일련번호
// 장애 정보
header.append(Utils.writeToString(" ", 3)); // 장애시스템코드
header.append(Utils.writeToString(" ", 10)); // 표준전문오류코드
// 파일 정보
header.append(Utils.writeToString(" ", 16));
header.append(Utils.writeToString(" ", 8));
header.append(Utils.writeToString(" ", 12));
header.append(Utils.writeToString(" ", 12));
header.append(Utils.writeToString(" ", 4));
return header.toString();
}
private String createData() throws Exception {
StringBuffer data = new StringBuffer();
data.append(Utils.writeToString(" ", 1000));
return data.toString();
}
}
|
package org.maia.mvc.gerenciadorOfertas.services.impl;
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.maia.mvc.gerenciadorOfertas.domain.SocialMetaTag;
import org.maia.mvc.gerenciadorOfertas.services.SocialMetaTagServices;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
@Service
public class SocialMetaTagServiceImpl implements SocialMetaTagServices{
private static Logger log = LoggerFactory.getLogger(SocialMetaTagServiceImpl.class);
@Override
public SocialMetaTag getSocialMetaTag(String url) {
SocialMetaTag tagsTwitter = getTwitterCardByUrl(url);
if(!isEmpty(tagsTwitter)) {
return tagsTwitter;
}
SocialMetaTag tagsOpenGraph = getOpenGraphByUrl(url);
if(!isEmpty(tagsOpenGraph)) {
return tagsOpenGraph;
}
SocialMetaTag tagsItemprop = getItempropByUrl(url);
if(!isEmpty(tagsItemprop)) {
return tagsItemprop;
}
return null;
}
//recuperando os dados ta meta tag da pagina html com openGraph
private SocialMetaTag getOpenGraphByUrl(String url) {
log.info("Iniciando getOpenGraphByUrl para a url >" + url);
SocialMetaTag tag = new SocialMetaTag();
try {
Document document = Jsoup.connect(url).get(); //recuperando os dados ta meta tag da pagina html ex: https://www.udemy.com/course/dax-e-pbi/
tag.setTitle(document.head().select("meta[property=og:title]").attr("content") ); //<meta property="og:title" content="Power BI & DAX Avançado - Guia Completo para Análises Reais">
tag.setSite(document.head().select("meta[property=og:site_name]").attr("content") ); //<meta property="og:site_name" content="Udemy">
tag.setImage(document.head().select("meta[property=og:image]").attr("content") ); //<meta property="og:image" content="https://img-b.udemycdn.com/course/480x270/1491672_846d_10.jpg?secure=0oQrfvUUfzwvuyOR16s5tA%3D%3D%2C1602954423">
tag.setUrl(document.head().select("meta[property=og:url]").attr("content") ); //<meta property="og:url" content="https://www.udemy.com/course/dax-e-pbi/">
} catch (IOException e) {
//e.printStackTrace();
log.error(e.getMessage(), e.getCause());
}
return tag;
}
//recuperando os dados ta meta tag da pagina html com TwitterCard
private SocialMetaTag getTwitterCardByUrl(String url) {
log.info("Iniciando getTwitterCardByUrl para a url >" + url);
SocialMetaTag tag = new SocialMetaTag();
try {
Document document = Jsoup.connect(url).get(); //recuperando os dados ta meta tag da pagina html ex: https://www.udemy.com/course/dax-e-pbi/
tag.setTitle(document.head().select("meta[name=twitter:title]").attr("content") ); //<meta property="twitter:title" content="Power BI & DAX Avançado - Guia Completo para Análises Reais">
tag.setSite(document.head().select("meta[name=twitter:site]").attr("content") ); //<meta property="twitter:site_name" content="Udemy">
tag.setImage(document.head().select("meta[name=twitter:image]").attr("content") ); //<meta property="twitter:image" content="https://img-b.udemycdn.com/course/480x270/1491672_846d_10.jpg?secure=0oQrfvUUfzwvuyOR16s5tA%3D%3D%2C1602954423">
tag.setUrl(document.head().select("meta[name=twitter:url]").attr("content") ); //<meta property="twitter:url" content="https://www.udemy.com/course/dax-e-pbi/">
log.info("tag >" + tag);
} catch (IOException e) {
//e.printStackTrace();
log.error(e.getMessage(), e.getCause());
}
return tag;
}
//recuperando os dados ta meta tag da pagina html com itemprop
private SocialMetaTag getItempropByUrl(String url) {
log.info("Iniciando getItempropByUrl para a url >" + url);
SocialMetaTag tag = new SocialMetaTag();
try {
Document document = Jsoup.connect(url).get();
tag.setTitle(document.select("meta[itemprop=name]").attr("content") ); //<meta itemprop="name" content="Power BI & DAX Avançado - Guia Completo para Análises Reais">
tag.setDescricao(document.select("meta[itemprop=description]").attr("content") );
tag.setImage(document.select("meta[itemprop=image]").attr("content") );
tag.setUrl(document.select("meta[itemprop=url]").attr("content") );
} catch (IOException e) {
//e.printStackTrace();
log.error(e.getMessage(), e.getCause());
}
return tag;
}
private boolean isEmpty(SocialMetaTag tag) {
if (tag.getImage().isEmpty() ) return true;
if (tag.getTitle().isEmpty() ) return true;
if (tag.getSite().isEmpty() ) return true;
return false;
}
}
|
package ro.microservices.checkout.entities;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.math.BigDecimal;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Entity
public class OrderItem {
@Id
@GeneratedValue
private Long id;
private String code;
private Integer quantity;
private Long orderId;
}
|
package org.isc.certanalysis.web.error;
public class X509ExistsException extends RuntimeException {
public X509ExistsException(String msg) {
super(msg);
}
}
|
package com.cit360projectmark4.controller;
import com.cit360projectmark4.service.BaseService;
import com.cit360projectmark4.service.BaseServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class LogoutController extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.sendRedirect("login.jsp");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
String username = (String) session.getAttribute("username");
System.out.println("LogoutController: doPost: starting. SID: " + request.getSession().getId());
String page = "login.jsp";
System.out.println("LogoutController: doPost: sending request dispatcher");
request.getRequestDispatcher(page).include(request, response);
session.invalidate();
System.out.println("LogoutController: doPost: " + username + " has logged out");
}
}
|
package com.kodilla.good.patterns.flights;
import java.time.LocalDateTime;
import java.time.Month;
import java.util.HashMap;
import java.util.Map;
public class FlightDatabase {
public Map<Flight, Integer> createFlightDatabase() {
Flight flightGdnWro = new Flight("Gdansk","Wroclaw", LocalDateTime.of(2018, Month.OCTOBER, 2, 20, 0,0), LocalDateTime.of(2018, Month.OCTOBER, 2, 21, 0, 0));
Flight flightGdnRze = new Flight("Gdansk","Rzeszow", LocalDateTime.of(2018, Month.OCTOBER, 2, 18, 0,0), LocalDateTime.of(2018, Month.OCTOBER, 2, 20, 0, 0));
Flight flightWroGdn = new Flight("Wroclaw", "Gdansk", LocalDateTime.of(2018, Month.OCTOBER, 3, 9, 0,0), LocalDateTime.of(2018, Month.OCTOBER, 3, 10, 0, 0));
Flight flightRzeGdn = new Flight("Rzeszow", "Gdansk", LocalDateTime.of(2018, Month.OCTOBER, 4, 12, 0,0), LocalDateTime.of(2018, Month.OCTOBER, 4, 14, 0, 0));
Flight flightGdnPoz = new Flight("Gdansk", "Poznan", LocalDateTime.of(2018, Month.OCTOBER, 5, 9, 0,0), LocalDateTime.of(2018, Month.OCTOBER, 5, 10, 0, 0));
Flight flightPozRze = new Flight("Poznan", "Rzeszow", LocalDateTime.of(2018, Month.OCTOBER, 5, 11, 0,0), LocalDateTime.of(2018, Month.OCTOBER, 5, 12, 0, 0));
Flight flightPozWro = new Flight("Poznan", "Wroclaw", LocalDateTime.of(2018, Month.OCTOBER, 6, 9, 0,0), LocalDateTime.of(2018, Month.OCTOBER, 6, 10, 0, 0));
Flight flightPozGdn = new Flight("Poznan", "Gdansk", LocalDateTime.of(2018, Month.OCTOBER, 6, 9, 0,0), LocalDateTime.of(2018, Month.OCTOBER, 6, 10, 0, 0));
Map<Flight, Integer> flightDatabase = new HashMap<>();
flightDatabase.put(flightGdnWro, 1);
flightDatabase.put(flightGdnRze, 2);
flightDatabase.put(flightWroGdn, 3);
flightDatabase.put(flightRzeGdn, 4);
flightDatabase.put(flightGdnPoz, 5);
flightDatabase.put(flightPozRze, 6);
flightDatabase.put(flightPozWro, 7);
flightDatabase.put(flightPozGdn, 8);
return flightDatabase;
}
}
|
package com.heihei.adapter;
import java.util.List;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.heihei.cell.ListCell;
import com.heihei.model.User;
import com.wmlives.heihei.R;
public class UserAdapter extends BaseAdapter<User>{
public UserAdapter(List<User> data) {
super(data);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null)
{
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.cell_user, null);
}
ListCell lc = (ListCell) convertView;
lc.setData(getItem(position), position, this);
return convertView;
}
}
|
package it.unical.dimes.processmining.core;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* @author flupia
*
* Created on Apr 22, 2013 5:48:35 PM
*/
public class ConstraintParser extends DefaultHandler {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ConstraintParser cp = new ConstraintParser("C:\\Users\\flupia\\Desktop\\Constraints.xml");
cp.run();
}
private final LinkedList<Constraint> constraints;
private String tempVal;
// to maintain context
private Constraint tempConstraint;
private final String pathToConstraints;
public ConstraintParser(String pathToConstraints) {
// TODO Auto-generated constructor stub
this.pathToConstraints = pathToConstraints;
constraints = new LinkedList<Constraint>();
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
tempVal = new String(ch, start, length);
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (qName.equalsIgnoreCase("Constraint")) {
// add it to the list
constraints.add(tempConstraint);
} else if (qName.equalsIgnoreCase("Head")) {
tempConstraint.setHead(tempVal);
} else if (qName.equalsIgnoreCase("Body")) {
tempConstraint.addBody(tempVal);
}
}
public LinkedList<Constraint> getConstraints() {
return constraints;
}
private void parseDocument() {
// get a factory
SAXParserFactory spf = SAXParserFactory.newInstance();
try {
// get a new instance of parser
SAXParser sp = spf.newSAXParser();
// parse the file and also register this class for call backs
sp.parse(pathToConstraints, this);
} catch (SAXException se) {
se.printStackTrace();
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (IOException ie) {
ie.printStackTrace();
}
}
/**
* Iterate through the list and print the contents
*/
private void printData() {
System.out.println("No of Constraints '" + constraints.size() + "'.");
Iterator<Constraint> it = constraints.iterator();
while (it.hasNext()) {
System.out.println(it.next().toString());
}
}
public void run() {
parseDocument();
printData();
}
// Event Handlers
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// reset
tempVal = "";
if (qName.equalsIgnoreCase("Constraint")) {
// create a new instance of employee
tempConstraint = new Constraint();
String type = attributes.getValue("type");
if (type.equalsIgnoreCase("edge")) {
tempConstraint.setPathConstraint(false);
tempConstraint.setConstraintType(true);
} else if (type.equalsIgnoreCase("notEdge")) {
tempConstraint.setPathConstraint(false);
tempConstraint.setConstraintType(false);
} else if (type.equalsIgnoreCase("path")) {
tempConstraint.setPathConstraint(true);
tempConstraint.setConstraintType(true);
} else if (type.equalsIgnoreCase("notPath")) {
tempConstraint.setPathConstraint(true);
tempConstraint.setConstraintType(false);
}
}
}
}
|
package br.com.saltypub.web.beer.hue;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class BeerHue {
@Id
private Long id;
private String srmOrLovibond;
private String color;
private String colorHex;
private String example;
private Integer ebc;
public BeerHue() { }
public BeerHue(Long id, String srmOrLovibond, String color, String colorHex, String example, Integer ebc) {
this.id = id;
this.srmOrLovibond = srmOrLovibond;
this.color = color;
this.colorHex = colorHex;
this.example = example;
this.ebc = ebc;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getSrmOrLovibond() {
return srmOrLovibond;
}
public void setSrmOrLovibond(String srmOrLovibond) {
this.srmOrLovibond = srmOrLovibond;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getColorHex() {
return colorHex;
}
public void setColorHex(String colorHex) {
this.colorHex = colorHex;
}
public String getExample() {
return example;
}
public void setExample(String example) {
this.example = example;
}
public Integer getEbc() {
return ebc;
}
public void setEbc(Integer ebc) {
this.ebc = ebc;
}
}
|
package org.vanilladb.comm.protocols.zabelection;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.vanilladb.comm.process.ProcessList;
import org.vanilladb.comm.process.ProcessState;
import org.vanilladb.comm.protocols.events.ProcessListInit;
import org.vanilladb.comm.protocols.tcpfd.FailureDetected;
import org.vanilladb.comm.protocols.tcpfd.ProcessConnected;
import net.sf.appia.core.AppiaEventException;
import net.sf.appia.core.Channel;
import net.sf.appia.core.Event;
import net.sf.appia.core.Layer;
import net.sf.appia.core.Session;
public class ZabElectionSession extends Session {
private static Logger logger = Logger.getLogger(ZabElectionSession.class.getName());
private ProcessList processList;
private int defaultLeaderId;
private int leaderId;
private int epochId = 0;
ZabElectionSession(Layer layer, int defaultLeaderId) {
super(layer);
this.defaultLeaderId = defaultLeaderId;
}
@Override
public void handle(Event event) {
if (event instanceof ProcessListInit)
handleProcessListInit((ProcessListInit) event);
else if (event instanceof ProcessConnected)
handleProcessConnected((ProcessConnected) event);
else if (event instanceof FailureDetected)
handleFailureDetected((FailureDetected) event);
}
private void handleProcessListInit(ProcessListInit event) {
if (logger.isLoggable(Level.FINE))
logger.fine("Received ProcessListInit");
// Save the list
this.processList = event.copyProcessList();
// Let the event continue
try {
event.go();
} catch (AppiaEventException e) {
e.printStackTrace();
}
}
private void handleProcessConnected(ProcessConnected event) {
if (logger.isLoggable(Level.FINE))
logger.fine("Received ProcessConnected");
// Let the event continue
try {
event.go();
} catch (AppiaEventException e) {
e.printStackTrace();
}
// Set the connected process ready
processList.getProcess(event.getConnectedProcessId())
.setState(ProcessState.CORRECT);
// Initialize when all processes are ready
if (processList.areAllCorrect())
setFirstLeader(event.getChannel());
}
private void handleFailureDetected(FailureDetected event) {
if (logger.isLoggable(Level.FINE))
logger.fine("Received FailureDetected (failed id = " +
event.getFailedProcessId() + ")");
// Set the process state as failed
processList.getProcess(event.getFailedProcessId()).setState(ProcessState.FAILED);
// Let the event continue
try {
event.go();
} catch (AppiaEventException e) {
e.printStackTrace();
}
// If it is the leader, choose a new one.
if (leaderId == event.getFailedProcessId()) {
electNewLeader();
try {
LeaderChanged change = new LeaderChanged(event.getChannel(), this,
leaderId, epochId);
change.init();
change.go();
} catch (AppiaEventException e) {
e.printStackTrace();
}
}
}
private void setFirstLeader(Channel channel) {
// Set the first leader
leaderId = defaultLeaderId;
if (logger.isLoggable(Level.FINE))
logger.fine("Initialize with leaderId = " + leaderId);
// Send a leader init event
try {
LeaderInit init = new LeaderInit(channel, this, leaderId);
init.init();
init.go();
} catch (AppiaEventException e) {
e.printStackTrace();
}
}
private void electNewLeader() {
// A deterministic algorithm
// Only works when there are no two processes failed at the same time
for (int i = processList.getSize() - 1; i >= 0; i--) {
if (processList.getProcess(i).isCorrect()) {
leaderId = i;
break;
}
}
epochId++;
if (logger.isLoggable(Level.INFO))
logger.info("Elected a new leader: Process " + leaderId +
" (epoch: " + epochId + ")");
}
}
|
package com.trump.auction.reactor.bid;
import java.util.concurrent.TimeUnit;
import org.springframework.stereotype.Component;
import com.trump.auction.reactor.api.exception.BidException;
import com.trump.auction.reactor.api.model.AuctionContext;
import com.trump.auction.reactor.api.model.Bid;
import com.trump.auction.reactor.api.model.BidRequest;
import com.trump.auction.reactor.api.model.BidResponse;
import com.trump.auction.reactor.api.model.BidType;
import com.trump.auction.reactor.bid.rule.BidHitRule;
import com.trump.auction.reactor.bid.support.AttemptHitEvent;
import com.trump.auction.reactor.bid.support.AutoBidEvent;
import com.trump.auction.reactor.util.lock.DistributedLock;
import lombok.extern.slf4j.Slf4j;
/**
* 默认单次出价处理
*
* @author Owen
* @since 2018/1/16
*/
@Slf4j
@Component
public class DefaultBidHandle extends AbstractBidHandler implements BidHandler {
@Override
public boolean support(BidRequest bidRequest) {
return BidType.DEFAULT.equals(bidRequest.getBidType());
}
@Override
public BidResponse handleRequest(BidRequest bidRequest) {
DistributedLock lock = null;
AuctionContext context = null;
try {
lock = lockFactory.getBidLock(bidRequest.getAuctionNo());
lock.acquire();
context = contextFactory.create(bidRequest.getAuctionNo());
return handleRequest0(bidRequest, context);
} catch (Throwable e) {
return handleException(bidRequest, context, e);
} finally {
if (lock != null) {
lock.release();
}
}
}
protected BidResponse handleException(BidRequest bidRequest, AuctionContext context, Throwable e) {
if (BidException.support(e)) {
log.warn("[bid error] code:{}, request:{}, context:{},", e.getMessage(), bidRequest, context);
} else {
log.error("[bid error] request:{}, context:{}, error:{}", bidRequest, context, e);
}
return onError(bidRequest, context, e);
}
protected BidResponse handleRequest0(BidRequest bidRequest, AuctionContext context) {
Bid bid = getBid(bidRequest);
// 检查竞拍状态
checkBid(bid, context);
// 出价
context.onBid(bid);
bidRepository.saveContext(context);
// 判断竞拍成功的前置条件
if (isHittable(context)) {
AttemptHitEvent event = new AttemptHitEvent(context);
timer.add(event, context.getBidCountDown(), TimeUnit.SECONDS);
} else {
AutoBidEvent event = new AutoBidEvent(context);
timer.add(event, config.nextAutoBidDelayTime(context.getBidCountDown()));
}
return onSuccess(bidRequest, context);
}
private Bid getBid(BidRequest bidRequest) {
return beanMapper.map(bidRequest, Bid.class);
}
protected void checkBid(Bid bid, AuctionContext context) {
context.checkBiddable(bid.getBidder());
// 判断是否有未完成的出价
if (bidQueueHandler.remainBid(context.getAuctionNo(), bid.getBidder())) {
throw BidException.bidderQueued();
}
}
/**
* 判断是否满足拍中的前置条件
*/
private boolean isHittable(AuctionContext context) {
boolean bidHit = false;
for (BidHitRule hitRule : hitRules) {
bidHit = hitRule.check(context);
if (!bidHit) {
break;
}
}
return bidHit;
}
}
|
package pl.basistam.zad1.books;
import pl.basistam.AbstractBooksInput;
public class Main {
public static void main(String[] args) {
AbstractBooksInput input = new BooksInput(new XmlBuilderImpl());
input.add();
}
}
|
package fr.ucbl.disp.vfos.util.file;
public enum EIOFileType {
WRITE,
READ
}
|
package com.framgia.fsalon.screen.homestylist;
/**
* Listens to user actions from the UI ({@link HomeStylistActivity}), retrieves the data and updates
* the UI as required.
*/
public class HomeStylistPresenter implements HomeStylistContract.Presenter {
private static final String TAG = HomeStylistPresenter.class.getName();
private final HomeStylistContract.ViewModel mViewModel;
public HomeStylistPresenter(HomeStylistContract.ViewModel viewModel) {
mViewModel = viewModel;
}
@Override
public void onStart() {
}
@Override
public void onStop() {
}
}
|
package com.example.van.baotuan.VP.user.login;
import com.example.van.baotuan.model.user.UserBiz;
import com.example.van.baotuan.util.stringUtil.MD5Util;
/**
* 登录的Presenter
* Created by Van on 2016/11/06.
*/
public class LoginPresenter implements LoginContract.Presenter {
private final LoginContract.View mLogInView;
private UserBiz userBiz;
public LoginPresenter(LoginContract.View mLogInView) {
this.mLogInView = mLogInView;
mLogInView.setPresenter(this);
userBiz = new UserBiz(this);
}
@Override
public void start() {
}
/**
* 登录
* @param userName
* @param password
*/
@Override
public void logIn(String userName, String password) {
if (userName.isEmpty()||password.isEmpty()){
mLogInView.onFailure("用户名或密码不能为空");
}
password = encrypt(password);
userBiz.logIn(userName,password);
}
@Override
public void signIn() {
}
@Override
public void forgetPassword() {
}
@Override
public void cancelLogIn() {
}
@Override
public void onSuccess() {
mLogInView.onSuccess("登录成功");
}
@Override
public void onFailure(String msg) {
mLogInView.onError(msg);
}
@Override
public void onError(String msg) {
mLogInView.onError(msg);
}
private String encrypt(String plain){
return MD5Util.MD5(plain);
}
}
|
package com.example.oodlesdemoproject.model.repo;
import com.example.oodlesdemoproject.model.countrydetails.CountryDetailsResponse;
import java.io.Serializable;
import java.util.ArrayList;
public class CountryListResponse implements Serializable {
private ArrayList<CountryDetailsResponse> countryLists;
public ArrayList<CountryDetailsResponse> getCountryLists() {
return countryLists;
}
public void setProfiles(ArrayList<CountryDetailsResponse> countryLists) {
this.countryLists = countryLists;
}
}
|
package com.vkoval.addressbook.entity.address;
import com.vkoval.addressbook.entity.category.Category;
import lombok.Data;
import javax.persistence.*;
@Data
@Entity
public class AddressData {
@Id
@GeneratedValue
private Long id;
@Column
private String name;
@Column
private String secondName;
@Column
private String patronymic;
@Embedded
private Address address;
@Column
private String phoneNumber;
@ManyToOne
private Category category;
}
|
import java.time.LocalDateTime;
public class QuoteTimer implements ITime, Runnable {
private QuoteObserver observer;
private boolean run;
private LocalDateTime time;
public QuoteTimer(QuoteObserver obs, boolean runNow)
{
observer = obs;
run = runNow;
}
public void run()
{
try {
Tick();
}
catch(InterruptedException i) {}//Ignore
}
public void Start()
{
run = true;
}
public void Tick() throws InterruptedException
{
while(run)
{
SendCallBack();
Thread.sleep(10);
}
}
public void Stop()
{
run = false;
}
public void SendCallBack() {
observer.OnChange();
}
}
|
package com.ipincloud.iotbj.srv.domain;
import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.Time;
import java.sql.Date;
import java.sql.Timestamp;
import com.alibaba.fastjson.annotation.JSONField;
//(SyncVehicle)
//generate by redcloud,2020-07-24 19:59:20
public class SyncVehicle implements Serializable {
private static final long serialVersionUID = 69L;
// 车辆ID(最大长度64)
private String vehicleId ;
// 车牌号码(最大长度64)
private String plateNo ;
// 是否关联人员
private String isBandPerson ;
// 人员ID(最大长度64)
private String personId ;
// 车主姓名(最大长度64) 车辆是否和人员绑定,带有人员信息
private String personName ;
// 车主联系电话(最大长度64)
private String phoneNo ;
// 车牌类型
private String plateType ;
// 车牌颜色
private String plateColor ;
// 车辆类型
private String vehicleType ;
// 车辆颜色
private String vehicleColor ;
// 车辆描述
private String mark ;
public String getVehicleId() {
return vehicleId ;
}
public void setVehicleId(String vehicleId) {
this.vehicleId = vehicleId;
}
public String getPlateNo() {
return plateNo ;
}
public void setPlateNo(String plateNo) {
this.plateNo = plateNo;
}
public String getIsBandPerson() {
return isBandPerson ;
}
public void setIsBandPerson(String isBandPerson) {
this.isBandPerson = isBandPerson;
}
public String getPersonId() {
return personId ;
}
public void setPersonId(String personId) {
this.personId = personId;
}
public String getPersonName() {
return personName ;
}
public void setPersonName(String personName) {
this.personName = personName;
}
public String getPhoneNo() {
return phoneNo ;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
public String getPlateType() {
return plateType ;
}
public void setPlateType(String plateType) {
this.plateType = plateType;
}
public String getPlateColor() {
return plateColor ;
}
public void setPlateColor(String plateColor) {
this.plateColor = plateColor;
}
public String getVehicleType() {
return vehicleType ;
}
public void setVehicleType(String vehicleType) {
this.vehicleType = vehicleType;
}
public String getVehicleColor() {
return vehicleColor ;
}
public void setVehicleColor(String vehicleColor) {
this.vehicleColor = vehicleColor;
}
public String getMark() {
return mark ;
}
public void setMark(String mark) {
this.mark = mark;
}
}
|
package com.example.lorand.assr.model;
class Injury {
private int id;
private String cause;
private String injuredUntil;
private String injuredFrom; // date + game
}
|
package com.noveogroup.marchenko.device;
/**
* This interface represents a Device for sorting algorithms.
*/
public interface Device extends Comparable<Device> {
int getPrice();
}
|
package Problem_16496;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
public class Main {
static class data implements Comparable<data>{
String str;
data(String str) {
this.str = str;
}
@Override
public int compareTo(data d) {
// TODO Auto-generated method stub
String com1 = this.str + d.str;
String com2 = d.str + this.str;
return com1.compareTo(com2)*(-1);
}
}
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
String[] arr = br.readLine().split(" ");
StringBuilder sb = new StringBuilder();
ArrayList<data> str = new ArrayList<data>();
for(int i = 0; i< arr.length;i++)str.add(new data(arr[i]));
Collections.sort(str);
for(data d : str) {
sb.append(d.str);
}
if(sb.toString().charAt(0) == '0') System.out.println('0');
else System.out.println(sb.toString());
}
}
|
/*
* 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.payment;
import com.forgerock.sapi.gateway.ob.uk.common.datamodel.converter.common.FRRiskConverter;
import com.forgerock.sapi.gateway.ob.uk.common.datamodel.payment.FRWriteDataDomesticScheduled;
import com.forgerock.sapi.gateway.ob.uk.common.datamodel.payment.FRWriteDomesticScheduled;
import uk.org.openbanking.datamodel.payment.*;
import static com.forgerock.sapi.gateway.ob.uk.common.datamodel.converter.payment.FRWriteDomesticScheduledConsentConverter.*;
public class FRWriteDomesticScheduledConverter {
//OB to FR
public static FRWriteDomesticScheduled toFRWriteDomesticScheduled(OBWriteDomesticScheduled1 obWriteDomesticScheduled1) {
return obWriteDomesticScheduled1 == null ? null : FRWriteDomesticScheduled.builder()
.data(toFRWriteDataDomesticScheduled(obWriteDomesticScheduled1.getData()))
.risk(FRRiskConverter.toFRPaymentRisk(obWriteDomesticScheduled1.getRisk()))
.build();
}
public static FRWriteDomesticScheduled toFRWriteDomesticScheduled(OBWriteDomesticScheduled2 obWriteDomesticScheduled2) {
return obWriteDomesticScheduled2 == null ? null : FRWriteDomesticScheduled.builder()
.data(toFRWriteDataDomesticScheduled(obWriteDomesticScheduled2.getData()))
.risk(FRRiskConverter.toFRPaymentRisk(obWriteDomesticScheduled2.getRisk()))
.build();
}
public static FRWriteDataDomesticScheduled toFRWriteDataDomesticScheduled(OBWriteDataDomesticScheduled1 data) {
return data == null ? null : FRWriteDataDomesticScheduled.builder()
.consentId(data.getConsentId())
.initiation(toFRWriteDomesticScheduledDataInitiation(data.getInitiation()))
.build();
}
public static FRWriteDataDomesticScheduled toFRWriteDataDomesticScheduled(OBWriteDataDomesticScheduled2 data) {
return data == null ? null : FRWriteDataDomesticScheduled.builder()
.consentId(data.getConsentId())
.initiation(toFRWriteDomesticScheduledDataInitiation(data.getInitiation()))
.build();
}
public static FRWriteDataDomesticScheduled toFRWriteDataDomesticScheduled(OBWriteDomesticScheduled2Data data) {
return data == null ? null : FRWriteDataDomesticScheduled.builder()
.consentId(data.getConsentId())
.initiation(toFRWriteDomesticScheduledDataInitiation(data.getInitiation()))
.build();
}
// FR to OB
public static OBWriteDomesticScheduled2 toOBWriteDomesticScheduled2(FRWriteDomesticScheduled domesticScheduledPayment) {
return domesticScheduledPayment == null ? null : new OBWriteDomesticScheduled2()
.data(toOBWriteDomesticScheduled2Data(domesticScheduledPayment.getData()))
.risk(FRRiskConverter.toOBRisk1(domesticScheduledPayment.getRisk()));
}
public static OBWriteDataDomesticScheduled2 toOBWriteDataDomesticScheduled2(FRWriteDataDomesticScheduled data) {
return data == null ? null : new OBWriteDataDomesticScheduled2()
.consentId(data.getConsentId())
.initiation(toOBDomesticScheduled2(data.getInitiation()));
}
public static OBWriteDomesticScheduled2Data toOBWriteDomesticScheduled2Data(FRWriteDataDomesticScheduled data) {
return data == null ? null : new OBWriteDomesticScheduled2Data()
.consentId(data.getConsentId())
.initiation(toOBWriteDomesticScheduled2DataInitiation(data.getInitiation()));
}
}
|
package com.soa.soap;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for bowType.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="bowType">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="BAD"/>
* <enumeration value="MIDDLE"/>
* <enumeration value="GOOD"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "bowType")
@XmlEnum
public enum BowType {
BAD,
MIDDLE,
GOOD;
public String value() {
return name();
}
public static BowType fromValue(String v) {
return valueOf(v);
}
}
|
package com.codegym.repository;
import com.codegym.model.Customer;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface ICustomerRepository extends JpaRepository<Customer, Long> {
}
|
/*
* 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 agh.musicapplication.mappdao.interfaces;
import agh.musicapplication.mappdao.Crudable;
import agh.musicapplication.mappmodel.MAlbum;
import agh.musicapplication.mappmodel.MAlbumSong;
import agh.musicapplication.mappmodel.MSong;
import java.util.List;
/**
*
* @author Agata
*/
public interface MAlbumSongRepositoryInterface extends Crudable<MAlbumSong> {
public MAlbumSong getMAlbumSongWithSomeAlbumNameAndSongName(MAlbum a, MSong s);
public List<MSong> getAllSongsOfSomeAlbum(MAlbum a);
}
|
package pl.kkowalewski.activeflap;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.IBinder;
import android.os.PowerManager;
import android.provider.Settings;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
import static pl.kkowalewski.activeflap.MainActivity.ADD_ADMIN_PRIVILEGES;
import static pl.kkowalewski.activeflap.MainActivity.EXTRA_KEY_COMPONENT_NAME;
import static pl.kkowalewski.activeflap.MainActivity.PROXIMITY_THRESHOLD;
import static pl.kkowalewski.activeflap.MainActivity.SYSTEM_SCREEN_OFF_TIMEOUT;
public class ActiveFlapService extends Service implements SensorEventListener {
/*------------------------ FIELDS REGION ------------------------*/
public static final int NOTIFICATION_ID = 1;
public static final String NOTIFICATION_CHANNEL_ID = "Channel_Id";
public static final String NOTIFICATION_CHANNEL_NAME = "Channel_Name";
public static final String WAKE_LOCK_TAG = ":TAG";
public static final String SERVICE_RUNNING_IN_BACKGROUND = "Service is running background";
private DevicePolicyManager devicePolicyManager;
private ComponentName componentName;
private SensorManager sensorManager;
private Sensor proximitySensor;
/*------------------------ METHODS REGION ------------------------*/
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
devicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
componentName = (ComponentName) intent.getExtras().get(EXTRA_KEY_COMPONENT_NAME);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
proximitySensor = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
sensorManager.registerListener(this, proximitySensor,
SensorManager.SENSOR_DELAY_FASTEST);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundForNewDevices();
} else {
startForegroundForOldDevices();
}
return super.onStartCommand(intent, flags, startId);
}
@RequiresApi(api = Build.VERSION_CODES.O)
private void startForegroundForNewDevices() {
NotificationChannel channel = new NotificationChannel(
NOTIFICATION_CHANNEL_ID,
NOTIFICATION_CHANNEL_NAME,
NotificationManager.IMPORTANCE_NONE
);
channel.setLightColor(Color.BLUE);
channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(channel);
NotificationCompat.Builder notificationBuilder = new NotificationCompat
.Builder(this, NOTIFICATION_CHANNEL_ID);
startForeground(NOTIFICATION_ID, notificationBuilder
.setOngoing(true)
.setContentTitle(SERVICE_RUNNING_IN_BACKGROUND)
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build());
}
private void startForegroundForOldDevices() {
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent
.getActivity(this, 0, notificationIntent, 0);
startForeground(NOTIFICATION_ID, new NotificationCompat.Builder(this,
NOTIFICATION_CHANNEL_ID)
.setOngoing(true)
.setContentTitle(getString(R.string.app_name))
.setContentText("Service is running background")
.setContentIntent(pendingIntent)
.build());
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_PROXIMITY
&& devicePolicyManager.isAdminActive(componentName)) {
final float distance = event.values[0];
if (distance <= PROXIMITY_THRESHOLD) {
devicePolicyManager.lockNow();
} else {
PowerManager powerManager = (PowerManager) getApplicationContext()
.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = powerManager
.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK
| PowerManager.FULL_WAKE_LOCK
| PowerManager.ACQUIRE_CAUSES_WAKEUP
), WAKE_LOCK_TAG);
try {
final int screenOffTimeout = Settings.System.getInt(getContentResolver(),
Settings.System.SCREEN_OFF_TIMEOUT);
wakeLock.acquire((long) (screenOffTimeout * 0.25));
} catch (Settings.SettingNotFoundException e) {
Toast.makeText(getApplicationContext(),
SYSTEM_SCREEN_OFF_TIMEOUT, Toast.LENGTH_SHORT).show();
}
}
} else {
Toast.makeText(getApplicationContext(),
ADD_ADMIN_PRIVILEGES, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
|
package com.paragon.utils.logger;
import android.util.Log;
/**
* Created by Rupesh Saxena
*/
public class Logger {
private static final boolean ENABLED = true;
private static final boolean DISABLED = false;
private static final boolean LOG_STATUS = ENABLED;
private static final String LOG_PREFIX = " :-> ";
private static final String LOG_CAT = "Logger";
public static final String EXCEPTION_MSG = "Some Exception while printing logger :->";
public static void e(String prefixP, String textToLog) {
try {
String prefix = prefixP + LOG_PREFIX;
if (LOG_STATUS == ENABLED) {
Log.e(LOG_CAT, prefix + textToLog);
}
} catch (Exception e) {
Log.e(LOG_CAT, EXCEPTION_MSG + e.toString());
}
}
public static void v(String prefixP, String textToLog) {
try {
String prefix = prefixP + LOG_PREFIX;
if (LOG_STATUS == ENABLED) {
Log.v(LOG_CAT, prefix + textToLog);
}
} catch (Exception e) {
Log.v(LOG_CAT, EXCEPTION_MSG + e.toString());
}
}
public static void d(String prefixP, String textToLog) {
try {
String prefix = prefixP + LOG_PREFIX;
if (LOG_STATUS == ENABLED) {
Log.d(LOG_CAT, prefix + textToLog);
}
} catch (Exception e) {
Log.d(LOG_CAT, EXCEPTION_MSG + e.toString());
}
}
public static void i(String prefixP, String textToLog) {
try {
String prefix = prefixP + LOG_PREFIX;
if (LOG_STATUS == ENABLED) {
Log.e(LOG_CAT, prefix + textToLog);
}
} catch (Exception e) {
Log.i(LOG_CAT, EXCEPTION_MSG + e.toString());
}
}
public static void w(String prefixP, String textToLog) {
try {
String prefix = prefixP + LOG_PREFIX;
if (LOG_STATUS == ENABLED) {
Log.w(LOG_CAT, prefix + textToLog);
}
} catch (Exception e) {
Log.w(LOG_CAT, EXCEPTION_MSG + e.toString());
}
}
}
|
package dev.nowalk.repositories;
import java.util.List;
import dev.nowalk.models.Award;
public interface AwardRepo {
public void addAward(Award a);
public List<Award> getAllAwards();
public Award getAward(int id);
public Award updateAward(Award change);
public Award deleteAward(Award a);
}
|
package com.letscrawl.base.bean.job;
import java.io.Serializable;
import org.bson.types.ObjectId;
import com.letscrawl.base.bean.Document;
public class ExtractJob implements Serializable {
private static final long serialVersionUID = 1L;
private ObjectId id;
private ObjectId crawlerId;
private Document document;
public static final String QUEUE_KEY = "extractJobQueue";
public static final String BACKUP_QUEUE_KEY = "extractJobBackupQueue";
public static final String BACKUP_TIME_KEY = "backupTime";
public static final long BACKUP_TIMEOUT_MILLISECOND = 30 * 1000;
public static final String BACKUP_LOCK_KEY = "backupLockKey";
private ExtractJob() {
id = new ObjectId();
}
public ExtractJob(ObjectId crawlerId, Document document) {
this();
this.crawlerId = crawlerId;
this.document = document;
}
public ObjectId getId() {
return id;
}
public ObjectId getCrawlerId() {
return crawlerId;
}
public Document getDocument() {
return document;
}
}
|
package lab.nnverify.platform.verifyplatform.models;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.HashMap;
import java.util.Map;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ResponseEntity {
private int status;
private String msg;
private Map<String, Object> data = new HashMap<>();
}
|
package pm9.trackingserver.constants;
import pm9.trackingserver.rest.response.GenericResponse;
/**
* Enum of common responses returned by the API.
*/
public enum EnumResponse {
WORKING(100l, "Working"),
SUCCESS(200l, "Success"),
WRONG_API_KEY(500l, "Wrong API KEY"),
DEVICE_REGISTER_FAILURE(510l, "Device not registered"),
DEVICE_NOT_FOUND(520l, "Device not found"),
DEVICE_UNREGISTER_FAILURE(530l, "Device not unregistered"),
DEVICE_ALREADY_REGISTERED(540l, "Device already registered");
/// Used to identify the response.
private Long id;
/// Contains details of the response.
private String message;
EnumResponse(Long id, String message) {
this.id = id;
this.message = message;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
/**
* This function returns a GenericResponse which contains the information of EnumResponse object.
* @param enumResponse EnumResponse which needs to returned.
* @return Packs EnumResponse as GenericResponse.
*/
public static GenericResponse getGenericResponse(EnumResponse enumResponse){
GenericResponse genericResponse = new GenericResponse();
genericResponse.setStatus(enumResponse.getId());
genericResponse.setMessage(enumResponse.getMessage());
return genericResponse;
}
}
|
/*
* Copyright (c) 2004 Steve Northover and Mike Wilson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
package part2;
import org.eclipse.swt.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.graphics.*;
/**
* Draws a 5-pointed star, then saves it in a a jpeg file.
*
* @author mcq
*/
public class SavePoly {
static final int points = 5;
static final String filename = "Star.jpeg";
public static void main(String[] args) {
// Make the shape
int[] radial = new int[points * 2];
Rectangle bounds = new Rectangle(0, 0, 200, 200);
Point center = new Point(100, 100);
int pos = 0;
for (int i = 0; i < points; ++i) {
double r = Math.PI * 2 * pos / points;
radial[i * 2] = (int) ((1 + Math.cos(r)) * center.x);
radial[i * 2 + 1] = (int) ((1 + Math.sin(r)) * center.y);
pos = (pos + points / 2) % points;
}
// Draw it
Display display = new Display();
Color yellow = display.getSystemColor(SWT.COLOR_YELLOW);
Color blue = display.getSystemColor(SWT.COLOR_BLUE);
Image image = new Image(display, bounds);
GC gc = new GC(image);
gc.setForeground(blue);
gc.setBackground(yellow);
gc.fillPolygon(radial);
gc.drawPolygon(radial);
gc.dispose();
// Write it out
ImageLoader loader = new ImageLoader();
loader.data = new ImageData[] {image.getImageData()};
loader.save(filename, SWT.IMAGE_JPEG);
// Clean up
image.dispose();
blue.dispose();
yellow.dispose();
display.dispose();
}
}
|
package com.lzx.xiuxian.Adapter;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.lzx.xiuxian.R;
import com.lzx.xiuxian.Vo.User;
import java.util.List;
public class FriendsAdapter extends RecyclerView.Adapter<FriendsAdapter.ViewHolder> {
private List<User> mUserList;
static class ViewHolder extends RecyclerView.ViewHolder{
ImageView ItemImage;
TextView ItemName;
public ViewHolder(View view){
super(view);
ItemImage = (ImageView)view.findViewById(R.id.item_image);
ItemName = (TextView) view.findViewById(R.id.item_name);
}
}
public FriendsAdapter(List<User> itemList){
mUserList = itemList;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item,parent,false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) {
User user = mUserList.get(i);
viewHolder.ItemName.setText(user.getName()+"\n"+user.getPhone()+"\n"+"修行"+user.getScore()+"分钟");
}
public int getItemCount() {
return mUserList.size();
}
}
|
package com.csc.capturetool.myapplication;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import com.uuzuche.lib_zxing.activity.ZXingLibrary;
/**
* Created by SirdarYangK on 2018/11/2
* des:
*/
public class CscApplication extends Application {
private static CscApplication mContext;
private static String PREF_NAME = "csc_capture_pref";
@Override
public void onCreate() {
super.onCreate();
mContext = this;
ZXingLibrary.initDisplayOpinion(this);//二维码三方框架
//自动适配设置
// AutoLayoutConifg.getInstance().useDeviceSize();
}
public static CscApplication getApplication() {
return mContext;
}
public static SharedPreferences getPreferences() {
SharedPreferences pref = mContext.getSharedPreferences(PREF_NAME,
Context.MODE_PRIVATE);
return pref;
}
}
|
package FactoryMethodPattern02.example.factory.concreteFactory;
import FactoryMethodPattern02.example.factory.LoggerFactory;
import FactoryMethodPattern02.example.product.concreteProduct.FileLogger;
import FactoryMethodPattern02.example.product.Logger;
public class FileLoggerFactory extends LoggerFactory {
@Override
public Logger createLogger() {
//创建文件相关的信息....
//对文件进行一些预处理方面的工作....
//创建文件日志的实例对象....
return new FileLogger();
}
}
|
package com.beike.service.impl.common;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.beike.common.exception.BaseException;
import com.beike.dao.common.SmsDao;
import com.beike.entity.common.Sms;
import com.beike.entity.common.SmsQuene;
import com.beike.form.SmsInfo;
import com.beike.service.common.EmailService;
import com.beike.service.common.SmsService;
/**
* Copyright: Copyright (c)2010 Company: YeePay.com Description:
*
* @author: wenhua.cheng
* @version: 1.0 Create at: 2011-4-20
*/
@Service("smsService")
public class SmsServiceImpl implements SmsService {
private static Log log = LogFactory.getLog(SmsServiceImpl.class);
@Autowired
private SmsUtils smsUtils;
public static Map<String, Sms> smsMap = new java.util.concurrent.ConcurrentHashMap<String, Sms>();
public SmsUtils getSmsUtils() {
return smsUtils;
}
public void setSmsUtils(SmsUtils smsUtils) {
this.smsUtils = smsUtils;
}
@Override
public Sms getSmsByTitle(String title) throws BaseException {
Sms sms = smsMap.get(title);
if (sms == null) {
sms = smsDao.getSmsByTitle(title);
}
if (sms == null) {
throw new BaseException(BaseException.SMSTEMPLATE_NOT_FOUNT);
}
smsMap.put(title, sms);
return sms;
}
@Autowired
private SmsDao smsDao;
@Autowired
private EmailService emailService;
private static ResourceBundle rb = ResourceBundle.getBundle("smsconfig");
private static final String operId = rb.getString("operId");
private static final String operPass = rb.getString("operPass");
private static final String sendUrl = rb.getString("smsSend");
private static final String smsAutoSendCount = rb
.getString("smsAutoSendCount");
private static final String sender = rb.getString("sender");
private static final String toEmail = rb.getString("toer");
/**
* 参数类型进行了绑定。有点耦合
*
* @param url
* @param sourceBean
* @return
*/
@SuppressWarnings("unchecked")
@Override
public Map sendSms(SmsInfo sourceBean) {
log.info("sendSms " + sourceBean);
if(sourceBean.getDesMobile().startsWith("10000")){ //如果手机号是10000打头侧不入库.add by wenhua.cheng
return null;
}
Map<String, String> sendMap = new HashMap<String, String>();
sendMap.put("OperID", operId);
sendMap.put("OperPass", operPass);
// 暂时无用。执空
sendMap.put("SendTime", "");
sendMap.put("ValidTime", "");
sendMap.put("AppendID", sourceBean.getAppendID());
sendMap.put("DesMobile", sourceBean.getDesMobile());
sendMap.put("Content", sourceBean.getContent());
sendMap.put("ContentType", sourceBean.getContentType());
//List<String> resultList = new ArrayList<String>();
try {
//Long begin = new Date().getTime();
// resultList = HttpUtils.URLGet(sendUrl, sendMap);
/*
* SmsSendThread smsThread = new SmsSendThread(sendMap);
* smsThread.start(); Long end = new Date().getTime();
* log.info("times=" + (end - begin)+",map="+sendMap);
*/
// 短信保存至数据库,定时批量发送 add by qiaowb 2011-11-4
smsDao.saveSmsInfo(sourceBean);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
// Map<String, String> smsMap = null;
// SmsQuene smsQuene = new SmsQuene();
// smsQuene.setId(1L);
// smsQuene.setMobile("13581974941");
// smsQuene.setSmscontent("121213242342_" + new
// java.util.Date().getTime());
// // try {
// // System.out.print(URLEncoder.encode("用户提交到企信s通平台的状态报告错ss误码abc",
// // "GBK"));
// // } catch (UnsupportedEncodingException e) {
// // e.printStackTrace();
// // }
// for (int i = 0; i < 10; i++) {
// smsQuene.setSmscontent("121213242" + i + "342_"
// + new java.util.Date().getTime());
// String code = SmsUtils.sendSms(smsQuene);
// }
String content = "您在千品网购买的“久久丫100元储值卡:”服务密码为qh200926703mm764024有效期至2012-07-06【千品网】";
Pattern p = Pattern.compile("服务密码为qh[0-9]{9}mm[0-9]{6}");
Matcher m = p.matcher(content);
if (m.find()) {
content = content.replace("服务密码为qh", "优惠券序号").replace("mm", ",密码");
}
System.out.println(content);
}
public SmsDao getSmsDao() {
return smsDao;
}
public void setSmsDao(SmsDao smsDao) {
this.smsDao = smsDao;
}
/*
* (non-Javadoc)
*
* @see com.beike.service.common.SmsService#sendSmsInfo()
*/
@Override
public String sendSmsInfo() {
List<SmsQuene> smsList = smsDao.getSmsInfoList(smsAutoSendCount);
StringBuffer returnStr = new StringBuffer("");
if (smsList != null && smsList.size() > 0) {
for (SmsQuene smsQuene : smsList) {
String content = smsQuene.getSmscontent();
Pattern p = Pattern.compile("服务密码为qh[0-9]{9}mm[0-9]{6}");
Matcher m = p.matcher(content);
if (m.find()) {
content = content.replace("服务密码为qh", "优惠券序号").replace("mm",
",密码");
}
smsQuene.setSmscontent(content);
String sendResult = SmsUtils.sendSms(smsQuene);
if ("1".equals(sendResult)) {
returnStr.append(smsQuene.getId()).append(",");
smsDao.updateSmsInfo(sendResult, operId, operPass, sendUrl,
smsQuene);
} else {
// 两种通道 都不好用发邮件通知
sendErrorEmail("两种通道短信发送失败.." + smsQuene);
}
}
}
return returnStr.toString();
}
private void sendErrorEmail(String content) {
if (toEmail != null) {
String[] emails = toEmail.split(",");
if (emails != null && emails.length > 0) {
for (String string : emails) {
try {
emailService.sendMail(string, sender, content,
"系统短信发送失败");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
public EmailService getEmailService() {
return emailService;
}
public void setEmailService(EmailService emailService) {
this.emailService = emailService;
}
}
|
package com.postpc.Sheed.makeMatches;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.imageview.ShapeableImageView;
import com.postpc.Sheed.MatchMakerEngine;
import com.postpc.Sheed.R;
import com.postpc.Sheed.SheedApp;
import com.postpc.Sheed.SheedUser;
import com.postpc.Sheed.database.SheedUsersDB;
import com.squareup.picasso.Picasso;
import java.util.List;
import static com.postpc.Sheed.Utils.USER_INTENT_SERIALIZABLE_KEY;
public class MatchActivity extends AppCompatActivity {
SheedUser currentUser;
SheedUsersDB db;
TextView rhsNameView;
TextView lhsNameView;
ShapeableImageView rhsImage;
ShapeableImageView lhsImage;
ImageButton acceptMatchFab;
ImageButton declineMatchFab;
TextView headerView;
View swipeDetector;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_match);
final Intent sheedUserIntent = getIntent();
if (sheedUserIntent != null)
{
currentUser = (SheedUser) sheedUserIntent.getSerializableExtra(USER_INTENT_SERIALIZABLE_KEY);
}
// if (currentUser == null)
// {
// return;
// }
// load views
rhsNameView = findViewById(R.id.rhs_name);
lhsNameView = findViewById(R.id.lhs_name);
rhsImage = findViewById(R.id.rhs_img);
lhsImage = findViewById(R.id.lhs_img);
acceptMatchFab = findViewById(R.id.make_match);
declineMatchFab = findViewById(R.id.not_make_match);
headerView = findViewById(R.id.header_title);
swipeDetector = findViewById(R.id.swipe_detector);
db = SheedApp.getDB();
matchLoopExecutorHelper();
acceptMatchFab.setOnClickListener(v -> onAcceptMatchAction());
declineMatchFab.setOnClickListener(v -> onDeclineMatchAction());
acceptMatchFab.bringToFront();
declineMatchFab.bringToFront();
swipeDetector.setOnTouchListener(new OnSwipeTouchListener(this) {
@Override
public void onSwipeRight() {
onAcceptMatchAction();
}
@Override
public void onSwipeLeft() {
onDeclineMatchAction();
}
});
}
void fillRhsUser(SheedUser sheedUser)
{
rhsNameView.setText(sheedUser.firstName);
Picasso.with(this).load(sheedUser.imageUrl).into(rhsImage);
rhsImage.animate().rotationBy(360f).alpha(1 / 0.3f).setDuration(500L).
setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
rhsImage.setVisibility(View.VISIBLE);
}
}).start();
rhsNameView.animate().rotationBy(360f).alpha(1 / 0.3f).setDuration(500L).
setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
rhsNameView.setVisibility(View.VISIBLE);
}
}).start();
}
void fillLhsUser(SheedUser sheedUser)
{
lhsNameView.setText(sheedUser.firstName);
Picasso.with(this).load(sheedUser.imageUrl).into(lhsImage);
lhsImage.animate().rotationBy(360f).alpha(1 / 0.3f).setDuration(500L).
setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
lhsImage.setVisibility(View.VISIBLE);
}
}).start();
lhsNameView.animate().rotationBy(360f).alpha(1 / 0.3f).setDuration(500L).
setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
lhsNameView.setVisibility(View.VISIBLE);
}
}).start();
}
void matchLoopExecutorHelper(){
// List<String> matchFound = MatchMaker.makeMatch(currentUser.community);
//List<String> matchFound = MatchMakerEngine.makeMatch();
// assert matchFound.size() == 2; // Assert that two users retrieved from MatchMaker
// db.downloadUserAndDo(matchFound.get(0), this::fillLhsUser);
// db.downloadUserAndDo(matchFound.get(1), this::fillRhsUser);
// headerView.setText("We think it's a great match !");
// headerView.setVisibility(View.VISIBLE);
}
void onAcceptMatchAction() {
// Can add animations
// Update DB to let users know they have been matched
headerView.setText("Love is in the air !"); // I added this just to see that the listeners indeed work
roundEndRoutine();
}
void onDeclineMatchAction() {
// Can add animations
// Update DB for matching algorithm improvement
headerView.setText("Better luck next time"); // I added this just to see that the listeners indeed work
roundEndRoutine();
}
void matchLoopExecutor(Integer x){
Handler handler = new Handler();
handler.postDelayed(this::matchLoopExecutorHelper, x*1000);
}
void roundEndRoutine(){
rhsNameView.animate().rotationBy(360f).alpha(1 / 0.3f).setDuration(500L).
setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
rhsNameView.setVisibility(View.GONE);
}
}).start();
rhsImage.animate().rotationBy(360f).alpha(1 / 0.3f).setDuration(500L).
setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
rhsImage.setVisibility(View.GONE);
}
}).start();
lhsNameView.animate().rotationBy(360f).alpha(1 / 0.3f).setDuration(500L).
setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
lhsNameView.setVisibility(View.GONE);
}
}).start();
lhsImage.animate().rotationBy(360f).alpha(1 / 0.3f).setDuration(500L).
setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
lhsImage.setVisibility(View.GONE);
}
}).start();
headerView.setVisibility(View.GONE);
matchLoopExecutor(1);
}
}
|
/*
* 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 scheduledexecutor;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* @author blaszczyk
*/
public class HostsList {
List<Host> list = new ArrayList();
private Date lastCheck;
public Date getLastCheck() {
return lastCheck;
}
public void setLastCheck(Date lastCheck) {
this.lastCheck = lastCheck;
}
public void add(Host host)
{
list.add(host);
}
public void clear()
{
list.clear();
}
public int reachableHostsCount()
{
int i = 0;
for(Host host : list)
{
if(host.isReachable())
{
i++;
}
}
return i;
}
}
|
import java.util.Date;
public class MyThread extends Thread {
// public boolean isStart = true;
public void run() {
int i = 0;
while (!isInterrupted()){
try {
Thread.sleep(1000);
} catch (InterruptedException e){
System.out.println("Разбудили, суки!");
return;
};
System.out.println("новый поток i = " + i);
i++;
}
}
}
|
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class test {
public static void main(String[] args) throws Exception {
encrypt("edwin","password");
decrypt("2Jj3Bt0nCnsBaRDFkwGz76AlyeNLSmlmGxqCskX7UY0=");
}
private static void encrypt(String username, String password) throws Exception {
byte[] keyData = (username+password).getBytes();
SecretKeySpec secretKeySpec = new SecretKeySpec(keyData, "Blowfish");
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] hasil = cipher.doFinal(password.getBytes());
System.out.println(Base64.getEncoder().encodeToString(hasil));
}
private static void decrypt(String string) throws Exception {
byte[] keyData = ("flag{this_is_fake_flag}").getBytes();
SecretKeySpec secretKeySpec = new SecretKeySpec(keyData, "Blowfish");
Cipher cipher = Cipher.getInstance("Blowfish/ECB/PKCS5Padding");
cipher.init(2, secretKeySpec);
byte[] hasil = cipher.doFinal(Base64.getDecoder().decode(string));
System.out.println(new String(hasil));
}
}
|
package com.pooyaco.gazelle.entity;
import com.pooyaco.gazelle.entity.interceptor.AuditableEntityListener;
import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;
/**
* Created by s.taefi on 2015/03/04.
*/
@MappedSuperclass
@EntityListeners(AuditableEntityListener.class)
public abstract class BaseEntity implements Entity{
}
|
package com.google.firebase.codelab.mlkit;
import android.support.v4.content.FileProvider;
/**
* Created by Abin.Thomas on 24-05-2018.
*/
public class GenericFileProvider extends FileProvider {
}
|
package guillaumeagis.perk4you.cards;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import guillaumeagis.perk4you.R;
/**
*
* Chat card
*/
public final class HumanCard implements ICard{
private String text;
/**
* constructor
* get the venue by the given position in parameter
*/
public HumanCard(final String msg) {
this.text = msg;
}
@Override
public eCardType getType() {
return eCardType.HUMAN;
}
public static class itemAdapter extends GenericCardAdapter.ViewHolder {
private TextView _tvtText;
private LinearLayout llContent;
public itemAdapter(View v) {
super(v);
this._tvtText = (TextView)v.findViewById(R.id.tvText);
this.llContent = (LinearLayout) v.findViewById(R.id.llContent);
}
}
/***
* Update the view
* @param holder current placeHolder
*/
@Override
public void updateView(final GenericCardAdapter.ViewHolder holder) {
((itemAdapter)holder)._tvtText.setText(text);
((itemAdapter)holder).llContent.setBackgroundResource(R.drawable.btn_radius_blue);
((itemAdapter)holder)._tvtText.setTextColor(Color.WHITE);
alignRight((itemAdapter) holder);
}
/**
* Align the messages of the user on the right side
* @param holder current holder
*/
public void alignRight(final itemAdapter holder)
{
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)holder.llContent.getLayoutParams();
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
holder.llContent.setLayoutParams(params);
}
/** Inflate the view related to the venue
* @param parent parent
* @return view inflated
*/
public static View getView(ViewGroup parent) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_chat, parent, false);
return v;
}
}
|
import proxy.ServiceProxyCglib;
import proxy.ServiceProxyJdk;
import service.IHelloService;
import service.impl.HelloServiceImpl;
public class Main {
public static void main(String[] args) {
ServiceProxyJdk serviceProxyJdk = new ServiceProxyJdk();
IHelloService proxyJdk = (IHelloService) serviceProxyJdk.bind(new HelloServiceImpl());
proxyJdk.sayHello("Arvin");
ServiceProxyCglib serviceProxyCglib = new ServiceProxyCglib();
IHelloService proxyCglib = (IHelloService) serviceProxyCglib.getInstance(new HelloServiceImpl());
proxyCglib.sayHello("Arvin");
}
}
|
import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.hadoop.mapreduce.*;
import org.apache.hadoop.io.*;
import java.util.*;
public class WordCountMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
///Replacing all digits and punctuation with an empty string
String line = value.toString().replaceAll("\\p{Punct}|\\d", "").toLowerCase();
//Extracting the words
//StringTokenizer record = new StringTokenizer(line);
//Emitting each word as a key and one as its value
//while (record.hasMoreTokens())
//context.write(new Text(record.nextToken()), new IntWritable(1));
String[] record = line.split("\\s");
String coWord;
for(int i=0; i<record.length-1; i++) {
int j = i+1;
if(record[i].matches(".*\\w.*") && record[j].matches(".*\\w.*")) {
coWord = record[i] + " " + record[j];
context.write(new Text(coWord), new IntWritable(1));
}
}
}
}
|
package com.meetingapp.android.ui;
import android.content.Context;
import android.content.res.TypedArray;
import android.support.v7.widget.AppCompatEditText;
import android.util.AttributeSet;
import android.util.Log;
import com.meetingapp.android.R;
import com.meetingapp.android.util.TextUtils;
import com.meetingapp.android.util.TypeFaceUtils;
public class CustomEditText extends AppCompatEditText {
public CustomEditText(Context context) {
super(context);
}
public CustomEditText(Context context, AttributeSet attrs) {
super(context, attrs);
applyTypeFace(context, attrs, 0);
}
public CustomEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
applyTypeFace(context, attrs, defStyleAttr);
}
private void applyTypeFace(Context context, AttributeSet attrs, int defStyle) {
try {
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.font);
String str = a.getString(R.styleable.font_fonttype);
Log.e("Typeface", "" + str);
if (TextUtils.isNullOrEmpty(str)) {
str = "0";
}
setTypeface(TypeFaceUtils.getTypeFace(context, Integer.parseInt(str)));
a.recycle();
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package com.gy.service;
import com.gy.util.ResultObject;
import org.springframework.stereotype.Service;
/**
* @Author: liumin
* @Description:
* @Date: Created in 2018/4/9 9:47
*/
@Service
public interface WorkOrderService {
public ResultObject workOrder(String id,String installPlace,String carNo,String problem,String token);
public ResultObject list(String tyreId,String carNo);
public ResultObject deal(String id,String result,String token);
}
|
package es.codeurjc.gameweb;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class GamewebApplicationTests {
//esto es un push de prueba
@Test
void contextLoads() {
}
}
|
package Lec_03_ConditionalStatements;
import java.util.Scanner;
public class Lab_03_04_Number_1_9ToText {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Въведи цяло число от 1 до 9 вкл: ");
int inputNum = Integer.parseInt(scanner.nextLine());
if (1 == inputNum){
System.out.println("one");
} else if (2 == inputNum) {
System.out.println("two");
} else if (3 == inputNum){
System.out.println("three");
} else if (4 == inputNum){
System.out.println("four");
} else if (5 == inputNum){
System.out.println("five");
} else if (6 == inputNum){
System.out.println("six");
} else if (7 == inputNum){
System.out.println("seven");
} else if (8 == inputNum){
System.out.println("eight");
} else if (9 == inputNum){
System.out.println("nine");
} else {
System.out.println("number too big");
}
}
}
|
package org.apidesign.gate.timing;
import java.util.Timer;
import java.util.TimerTask;
import net.java.html.json.Model;
import net.java.html.json.ModelOperation;
import net.java.html.json.Property;
@Model(className="Current", instance = true, properties = {
@Property(name = "millis", type = long.class)
})
final class CurrentModel {
private static final Timer MILLIS = new Timer("Millis");
private PingMillis task;
@ModelOperation
void start(Current model) {
if (task == null) {
task = new PingMillis(model);
MILLIS.scheduleAtFixedRate(task, 100, 251);
}
}
@ModelOperation
void stop(Current model) {
if (task != null) {
task.cancel();
task = null;
}
}
@ModelOperation
void updateTime(Current model) {
model.setMillis(System.currentTimeMillis());
}
private static final class PingMillis extends TimerTask {
private final Current model;
PingMillis(Current model) {
this.model = model;
}
@Override
public void run() {
this.model.updateTime();
}
}
}
|
package hadoop.sort.secondary;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.io.WritableComparator;
public class YearGroupComparator extends WritableComparator {
public YearGroupComparator() {
super(Combinekey.class,true);
}
@Override
public int compare(WritableComparable a, WritableComparable b) {
Combinekey k1 = (Combinekey) a;
Combinekey k2 = (Combinekey) b;
return k1.getYear()-k2.getYear();
}
}
|
package lv.qaguru.qa2.core;
import org.apache.log4j.Logger;
/**
* Created by user on 2017.05.21..
*/
public class MainPage {
BaseFunctions baseFunctions;
private static final Logger LOGGER = Logger.getLogger(MainPage.class);
public static final String URL = "http://qaguru.lv:8080/qa2/";
public MainPage(BaseFunctions baseFunctions) {
this.baseFunctions = baseFunctions;
}
}
|
package decemberChallenge2017;
import java.util.Scanner;
public class ChefAndHisCake {
public static void main(String[] args) {
Scanner scan= new Scanner(System.in);
int t=scan.nextInt();
for(int i=0;i<t;i++)
{
int n=scan.nextInt();
int m=scan.nextInt();
scan.nextLine();
char a[][]= new char [n][m];
for(int j=0; j<n ; j++) {
String str=scan.nextLine();
a[j]=str.toCharArray();
}
//if column 'm' are even, then cost will always be same after starting from either red or green
int rCount =0, gCount =0;
int rRowCount[]= new int[n];
int gRowCount[]= new int[n];
for(int j=0; j<n ; j++)
{
rCount =0;
gCount =0;
char first=a[j][0];
char second = (first=='R') ? 'G' : 'R';
// System.out.println("first "+ first + " second "+ second);
for(int k=1; k<m;k++)
{
if(k%2!=0 && a[j][k]!=second)
{
if(second=='R')
rCount++;
else
gCount++;
}
else if(k%2==0 && a[j][k]!=first)
{
if(first=='R')
rCount++;
else
gCount++;
}
}
rRowCount[j]=rCount;
gRowCount[j]=gCount;
}
// reverse logic (i.e. count from back cost of R and G)
int rCountRev =0, gCountRev =0;
int rRowCountRev[]= new int[n];
int gRowCountRev[]= new int[n];
for(int j=0; j<n ; j++)
{
rCountRev =0;
gCountRev =0;
char last=a[j][m-1];
char secondLast = (last=='R') ? 'G' : 'R';
// System.out.println("last "+ last + " secondLast "+ secondLast);
for(int k=m-1; k>=0;k--)
{
if(k%2!=0 && a[j][k]!=secondLast)
{
if(secondLast=='R')
rCountRev++;
else
gCountRev++;
}
else if(k%2==0 && a[j][k]!=last)
{
if(last=='R')
rCountRev++;
else
gCountRev++;
}
}
rRowCountRev[j]=rCountRev;
gRowCountRev[j]=gCountRev;
}
int finalRCount=0;
for(int g=0;g<n;g++)
{
finalRCount = (rRowCount[g]<=rRowCountRev[g]) ? finalRCount + rRowCount[g] : finalRCount + rRowCountRev[g];
}
int finalGCount=0;
for(int g=0;g<n;g++)
{
finalGCount = (gRowCount[g]<=gRowCountRev[g]) ? finalGCount + gRowCount[g] : finalGCount + gRowCountRev[g];
}
System.out.println(finalRCount*3 + finalGCount*5);
}
}
}
|
/**
* Kenny Akers
* Mr. Paige
* Homework #22
* 4/20/18
*/
public class GraphProperties {
private final SymbolGraph graph; // The graph
private int diameter; // Definition: Maximum eccentricity of a graph
private int radius; // Definition: Minimum eccentricity of a graph
private int wienerIndex; // Definition: The sum of the lengths of the shortest paths between all pairs of vertices
private SymbolGraph.Vertex center; // Definition: A vertex whose eccentricity is the radius
private final int numComponents; // The number of components in this graph
private boolean[] visited;
private int[] eccentricities;
public GraphProperties(SymbolGraph graph) {
this.graph = graph;
this.visited = new boolean[graph.vertices()];
this.eccentricities = new int[graph.vertices()];
this.numComponents = this.countComponents();
if (!this.computeEccentricities()) { // If the graph is not connected, return.
return;
}
this.diameter = this.computeDiameter();
this.radius = this.computeRadius();
this.center = this.computeCenter();
this.wienerIndex = this.computeWienerIndex();
}
private boolean computeEccentricities() {
for (int i = 0; i < this.graph.vertices(); i++) {
BreadthFirstPaths bfp = new BreadthFirstPaths(this.graph, this.graph.get(i));
if (!bfp.isConnected()) {
System.out.println("Graph is not connected");
return false;
}
int eccentricity = 0;
for (int h = 0; h < this.graph.vertices(); h++) {
if (bfp.hasPathTo(this.graph.get(h)) && bfp.distTo(this.graph.get(h)) > eccentricity) {
eccentricity = bfp.distTo(this.graph.get(h));
}
}
this.eccentricities[i] = eccentricity;
}
return true;
}
private int computeWienerIndex() {
for (int vertex = 0; vertex < graph.vertices(); vertex++) {
BreadthFirstPaths breadthFirstPaths = new BreadthFirstPaths(graph, this.graph.get(vertex));
for (int otherVertex = 0; otherVertex < graph.vertices(); otherVertex++) {
if (otherVertex != vertex) {
this.wienerIndex += breadthFirstPaths.distTo(this.graph.get(otherVertex));
}
}
}
return this.wienerIndex;
}
private int countComponents() {
int count = 0;
for (int v = 0; v < this.graph.vertices(); v++) {
if (!this.visited[v]) {
this.DFS(this.graph.get(v));
count++;
}
}
return count;
}
private void DFS(SymbolGraph.Vertex start) {
if (!this.visited[start.index()]) {
this.visited[start.index()] = true;
for (SymbolGraph.Vertex v : start.neighbors()) {
this.DFS(v);
}
}
}
private int computeDiameter() {
int diam = this.eccentricities[0];
for (int i = 1; i < this.eccentricities.length; i++) {
if (this.eccentricities[i] > diam) {
diam = this.eccentricities[i];
}
}
return diam;
}
private int computeRadius() {
int rad = this.eccentricities[0];
for (int i = 1; i < this.eccentricities.length; i++) {
if (this.eccentricities[i] < rad) {
rad = this.eccentricities[i];
}
}
return rad;
}
private SymbolGraph.Vertex computeCenter() {
for (int i = 0; i < this.eccentricities.length; i++) {
if (this.radius == this.eccentricities[i]) {
return this.graph.get(i);
}
}
return null;
}
public int diameter() {
return this.diameter;
}
public int radius() {
return this.radius;
}
public SymbolGraph.Vertex center() {
return this.center;
}
public int wienerIndex() {
return this.wienerIndex;
}
public int numberComponents() {
return this.numComponents;
}
}
|
package de.hdm.softwarepraktikum.shared.bo;
/*
* Neben get und set Name/Unit wurden keine weiteren Methoden deklariert, da die Articleklasse von ihrer
* Superklasse BusinessObject erbt, in der die nötigen Methoden bereits implementiert sind.
*/
public class Item extends BusinessObject {
private static final long serialVersionUID = 1L;
// Name des Items
private String name;
// Globale Sichtbarkeit des Items
private boolean isGlobal;
// Id des Erstellers des Items
private int ownerID;
// Favorite Status des
private boolean isFavorite;
/**
* **************************************************************************************
* ABSCHNITT Anfang: Getter und Setter der Attribute
* **************************************************************************************
*/
/*
* Auslesen des Namens des Items
* @return name wird zurückgegeben
*/
public String getName() {
return name;
}
/*
* Setzen des Namens des Items
* @param value
*/
public void setName(String value) {
this.name = value;
}
/*
* Auslesen des FavoritenStatus des Items
* @return isFavorite;
*/
public Boolean getIsFavorite() {
return isFavorite;
}
/*
* Setzen des FavoriteStatus des Items
* @param isFavorite
*/
public void setFavorite(Boolean isFavorite) {
this.isFavorite = isFavorite;
}
/*
* Auslesen der globalen Sichtbarkeit des ITems
* @return isGlobal
*/
public boolean getIsGlobal() {
return isGlobal;
}
/*
* Setzen der globalen Sichtbarkeit des Items
* @param value
*/
public void setIsGlobal(boolean value) {
this.isGlobal = value;
}
/*
* Auslesen der ID des Erstellers
* @return ownerID
*/
public int getOwnerID() {
return ownerID;
}
/*
* Setzen der ID des Erstellers
* @üaram ownerID
*/
public void setOwnerID(int ownerID) {
this.ownerID = ownerID;
}
/**
* **************************************************************************************
* ABSCHNITT Ende: Getter und Setter der Attribute
* **************************************************************************************
*/
}
|
package com.restcode.restcode.resource;
import com.restcode.restcode.domain.model.User;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class SaveConsultantResource extends User{
private String linkedln;
public String getLinkedln() {
return linkedln;
}
public void setLinkedln(String linkedln) {
this.linkedln = linkedln;
}
}
|
package de.tu_darmstadt.elc.olw.api.constant;
public class ProductName {
private static class MP4_Lecturer_360p {
private static final String id = "1";
private static final String extension = "mp4";
}
/**
* mp4 848x480 16:9
*
* @author hungtu
*
*/
private static class MP4_Lecturer_480p {
private static final String id = "2";
private static final String extension = "mp4";
}
/**
* mp4 1280x720 16:9
*
* @author hungtu
*
*/
private static class MP4_Lecturer_720p {
private static final String id = "3";
private static final String extension = "mp4";
}
/**
* mp4 320x240 4:3
*
* @author hungtu
*
*/
private static class MP4_Lecturer_Mobile {
private static final String id = "4";
private static final String extension = "mp4";
}
/**
* flv 480x360 4:3
*
* @author hungtu
*
*/
private static class FLV_Lecturer_360p {
private static final String id = "5";
private static final String extension = "flv";
}
/**
* flv 848x480 4:3
*
* @author hungtu
*
*/
private static class FLV_Lecturer_480p {
private static final String id = "6";
private static final String extension = "flv";
}
private static class MP3_128k {
private static final String id = "7";
private static final String extension = "mp3";
}
private static class OGG_128k {
private static final String id = "8";
private static final String extension = "ogg";
}
/*
private static class AAC_128k {
private static final String id = "8";
private static final String extension = "aac";
}
*/
private static class MP4_Presentation_480p {
private static final String id = "9";
private static final String extension = "mp4";
}
private static class MP4_Presentation_Mobile {
private static final String id = "90";
private static final String extension = "mp4";
}
private static class FZIP_Lecturnity_Slide {
private static final String id = "10";
private static final String extension = "zip";
}
private static class XML_Presentation {
private static final String id = "presentation";
private static final String extension="xml";
}
private static class XML_Lecturnity_Slide_Info {
private static final String id = "100";
private static final String extension = "xml";
}
private static class Document_Image_Folder {
private static final String id = "11";
}
private static class Document_Meta_Folder {
private static final String id = "12";
}
private static class PDF_Document {
private static final String id = "13";
private static final String extension = "pdf";
}
private static class XML_Document_Info {
private static final String id = "110";
private static final String extension = "xml";
}
/**
* flv 480x360 4:3
*
* @author hungtu
*
*/
private static class FLV_Presentation_360p {
private static final String id = "25";
private static final String extension = "flv";
}
/**
* flv 848x480 4:3
*
* @author hungtu
*
*/
private static class FLV_Presentation_480p {
private static final String id = "26";
private static final String extension = "flv";
}
private static class WEBM_Lecturer_360p {
private static final String id = "105";
private static final String extension = "webm";
}
private static class WEBM_Lecturer_480p {
private static final String id = "106";
private static final String extension = "webm";
}
private static class WEBM_Presentation_360P {
private static final String id = "205";
private static final String extension = "webm";
}
private static class WEBM_Presentation_480P {
private static final String id = "206";
private static final String extension = "webm";
}
public static String getWEBM_Lecturer_360pName() {
return WEBM_Lecturer_360p.id + "." + WEBM_Lecturer_360p.extension;
}
public static String getWEBM_Lecturer_480pName() {
return WEBM_Lecturer_480p.id + "." + WEBM_Lecturer_480p.extension;
}
public static String getWEBM_Presentation_360pName() {
return WEBM_Presentation_360P.id + "." + WEBM_Presentation_360P.extension;
}
public static String getWEBM_Presenation_480pName() {
return WEBM_Presentation_480P.id + "." + WEBM_Presentation_480P.extension;
}
public static String getMP4_Lecturer_360pName() {
return MP4_Lecturer_360p.id + "." + MP4_Lecturer_360p.extension;
}
public static String getMP4_Lecturer_480pName() {
return MP4_Lecturer_480p.id + "." + MP4_Lecturer_480p.extension;
}
public static String getMP4_Lecturer_720pName() {
return MP4_Lecturer_720p.id + "." + MP4_Lecturer_720p.extension;
}
public static String getMP3_128kName() {
return MP3_128k.id + "." + MP3_128k.extension;
}
public static String getOGG_128kName() {
return OGG_128k.id + "." + OGG_128k.extension;
}
public static String getFLV_Audio_128kName() {
return MP3_128k.id + "." + FLV_Lecturer_360p.extension;
}
/*
public static String getAAC_128kName() {
return AAC_128k.id + "." + AAC_128k.extension;
}
*/
public static String getMP4_Lecturer_MobileName() {
return MP4_Lecturer_Mobile.id + "." + MP4_Lecturer_Mobile.extension;
}
public static String getFLV_Lecturer_360pName() {
return FLV_Lecturer_360p.id + "." + FLV_Lecturer_360p.extension;
}
public static String getFLV_Lecturer_480pName() {
return FLV_Lecturer_480p.id + "." + FLV_Lecturer_480p.extension;
}
public static String getMP4_Presentation_480pName() {
return MP4_Presentation_480p.id + "." + MP4_Presentation_480p.extension;
}
public static String getMP4_Presentation_MobileName() {
return MP4_Presentation_Mobile.id + "."
+ MP4_Presentation_Mobile.extension;
}
public static String getFZIP_Lecturnity_SlideName() {
return FZIP_Lecturnity_Slide.id + "." + FZIP_Lecturnity_Slide.extension;
}
public static String getXML_Lecturnity_Slide_InfoName() {
return XML_Lecturnity_Slide_Info.id + "."
+ XML_Lecturnity_Slide_Info.extension;
}
public static String getPDF_DocumentName() {
return PDF_Document.id + "." + PDF_Document.extension;
}
public static String getDocument_Image_FolderName() {
return Document_Image_Folder.id;
}
public static String getDocument_Meta_FolderName() {
return Document_Meta_Folder.id;
}
public static String getXML_Document_InfoName() {
return XML_Document_Info.id + "." + XML_Document_Info.extension;
}
public static String getFLV_Presentation_360pName() {
return FLV_Presentation_360p.id + "." + FLV_Presentation_360p.extension;
}
public static String getFLV_Presentation_480pName() {
return FLV_Presentation_480p.id + "." + FLV_Presentation_480p.extension;
}
public static String getXML_PresentationName() {
return XML_Presentation.id + "." + XML_Presentation.extension;
}
public static String getRAW_Material_Name() {
return "30.zip";
}
public static String getProductName (int i) {
switch (i) {
case 1: return getMP4_Lecturer_360pName();
case 2: return getMP4_Lecturer_480pName();
case 3: return getMP4_Lecturer_720pName();
case 4: return getMP4_Lecturer_MobileName();
case 5: return getFLV_Lecturer_360pName();
case 6: return getFLV_Lecturer_480pName();
case 7: return getMP3_128kName();
//case 8: return getAAC_128kName();
case 8: return getOGG_128kName();
case 9: return getMP4_Presentation_480pName();
case 90: return getMP4_Presentation_MobileName();
case 10: return getFZIP_Lecturnity_SlideName();
case 100: return getXML_Lecturnity_Slide_InfoName();
case 11: return getDocument_Image_FolderName();
case 12: return getDocument_Meta_FolderName();
case 110: return getXML_Document_InfoName();
case 25: return getFLV_Presentation_360pName();
case 26: return getFLV_Presentation_480pName();
case 105: return getWEBM_Lecturer_360pName();
case 106: return getWEBM_Lecturer_480pName();
case 205: return getWEBM_Presentation_360pName();
case 206: return getWEBM_Presenation_480pName();
}
return "unknown";
}
}
|
package sample.model;
// Generated May 21, 2012 11:05:32 PM by Hibernate Tools 3.2.1.GA
/**
* Information generated by hbm2java
*/
public class Information implements java.io.Serializable {
private Integer id;
private String name;
private String slogan;
private String aboutWhoWeAre;
private String servicesWhatWeOffer;
private String servicesImage;
private String email;
private String contactInformation;
public Information() {
}
public Information(String name, String slogan, String aboutWhoWeAre, String servicesWhatWeOffer, String servicesImage, String email, String contactInformation) {
this.name = name;
this.slogan = slogan;
this.aboutWhoWeAre = aboutWhoWeAre;
this.servicesWhatWeOffer = servicesWhatWeOffer;
this.servicesImage = servicesImage;
this.email = email;
this.contactInformation = contactInformation;
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getSlogan() {
return this.slogan;
}
public void setSlogan(String slogan) {
this.slogan = slogan;
}
public String getAboutWhoWeAre() {
return this.aboutWhoWeAre;
}
public void setAboutWhoWeAre(String aboutWhoWeAre) {
this.aboutWhoWeAre = aboutWhoWeAre;
}
public String getServicesWhatWeOffer() {
return this.servicesWhatWeOffer;
}
public void setServicesWhatWeOffer(String servicesWhatWeOffer) {
this.servicesWhatWeOffer = servicesWhatWeOffer;
}
public String getServicesImage() {
return this.servicesImage;
}
public void setServicesImage(String servicesImage) {
this.servicesImage = servicesImage;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getContactInformation() {
return this.contactInformation;
}
public void setContactInformation(String contactInformation) {
this.contactInformation = contactInformation;
}
}
|
package com.cuisine.survey;
import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.tiles.TilesContainer;
import org.apache.tiles.access.TilesAccess;
@WebServlet("/survey/result")
public class MemberSurveyResult extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
HttpSession session = request.getSession();
String idtest = (String) session.getAttribute("idTest");
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://dev.notepubs.com:9898/cuisine?allowPublicKeyRetrieval=true&useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=UTC";
Connection connection = DriverManager.getConnection(url, "cuisine", "12345");
Statement statement = connection.createStatement();
String sql = "SELECT editorId,matchRate FROM member where id=" + idtest;
response.setCharacterEncoding("UTF-8");
response.setContentType("text/; charset=UTF-8");
ResultSet resultSet = statement.executeQuery(sql);
resultSet.next();
request.setAttribute("editorId", resultSet.getString(1));
request.setAttribute("matchRate", resultSet.getString(2));
String x = (String)resultSet.getString(1);
Class.forName("com.mysql.cj.jdbc.Driver");
String url2 = "jdbc:mysql://dev.notepubs.com:9898/cuisine?allowPublicKeyRetrieval=true&useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=UTC";
Connection connection2 = DriverManager.getConnection(url2, "cuisine", "12345");
Statement statement2 = connection2.createStatement();
String sql2 = "SELECT name,description from editor where id =" + x;
ResultSet resultSet2 = statement2.executeQuery(sql2);
resultSet2.next();
request.setAttribute("name", resultSet2.getString(1));
request.setAttribute("descroption", resultSet2.getString(2));
String idTest = (String)session.getAttribute("idTest");
CallableStatement callableStatement = connection.prepareCall("{call getMatchRate(?)}");
callableStatement.setInt(1, Integer.parseInt(idTest));
ResultSet resultSet3 = callableStatement.executeQuery();
resultSet3.next();
request.setAttribute("char1Id", resultSet3.getString(1));
request.setAttribute("char1Name", resultSet3.getString(2));
request.setAttribute("char1MatchRate", resultSet3.getString(3));
resultSet3.next();
System.out.println(resultSet3.getString(1));
request.setAttribute("char2Id", resultSet3.getString(1));
request.setAttribute("char2Name", resultSet3.getString(2));
request.setAttribute("char2MatchRate", resultSet3.getString(3));
resultSet3.next();
request.setAttribute("char3Id", resultSet3.getString(1));
request.setAttribute("char3Name", resultSet3.getString(2));
request.setAttribute("char3MatchRate", resultSet3.getString(3));
resultSet3.next();
request.setAttribute("char4Id", resultSet3.getString(1));
request.setAttribute("char4Name", resultSet3.getString(2));
request.setAttribute("char4MatchRate", resultSet3.getString(3));
resultSet3.next();
request.setAttribute("char5Id", resultSet3.getString(1));
request.setAttribute("char5Name", resultSet3.getString(2));
request.setAttribute("char5MatchRate", resultSet3.getString(3));
// String xTest = (String)resultSet3.getString(2);
// System.out.println(xTest);
// String yTest = (String)resultSet3.getString(3);
// System.out.println(yTest);
// resultSet3.next();
// String x2Test = (String)resultSet3.getString(2);
// System.out.println(x2Test);
// String y2Test = (String)resultSet3.getString(3);
// System.out.println(y2Test);
// resultSet3.next();
// request.setAttribute("char1Name", resultSet.getString(2));
// request.setAttribute("char1MatchRate", resultSet.getString(3));
// resultSet.next();
// request.setAttribute("char2Name", resultSet.getString(2));
// request.setAttribute("char2MatchRate", resultSet.getString(3));
// Class.forName("com.mysql.cj.jdbc.Driver");
// String url2 = "jdbc:mysql://dev.notepubs.com:9898/cuisine?allowPublicKeyRetrieval=true&useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=UTC";
// Connection connection2 = DriverManager.getConnection(url, "cuisine", "12345");
// Statement statement2 = connection.createStatement();
// String sql2 = "SELECT editorId,matchRate FROM member where id="+ idtest;
// request.getRequestDispatcher("/WEB-INF/view/cuisine/test.jsp").forward(request,
// response);
// response.sendRedirect(""); // ٲٴ ο ΰ
} catch (SQLException e) {
System.out.println("SQLException: " + e);
} catch (ClassNotFoundException e) {
System.out.println("ClassNotFoundException: " + e);
}
TilesContainer container = TilesAccess.getContainer(request.getSession().getServletContext());
container.render("survey.result", request, response);
}
public class Data {
int memberId;
int surveyId;
int result;
public int getMemberId() {
return memberId;
}
public void setMemberId(int memberId) {
this.memberId = memberId;
}
public int getSurveyId() {
return surveyId;
}
public void setSurveyId(int surveyId) {
this.surveyId = surveyId;
}
public int getResult() {
return result;
}
public void setResult(int result) {
this.result = result;
}
}
}
|
/**
Java Programming lab 6
File I/O, practice with reading input files and writing to output files
Throw exceptions when needed
Process for program:
1. Take in input file from Hotel Expenses, display error if input file is not found
2. Read file line by line, keeping a total for each kind of service provided
3. Then display total amount of each service category, and write to a output file
Use fileNotFoundException
Use a delimiter in.useDemiliter(";"); to tokenize each input line based on semi-colons.
*/
import java.util.NoSuchElementException;
import java.lang.*;
import java.util.Scanner;
import java.io.*;
public class ProgrammingLab6
{
public static void main(String[] args)
{
try{
String inFileName = " ";
String outFileName = " ";
inFileName = userInFile(inFileName); //Set input file equal to input file name
outFileName = userOutFile(outFileName); //Set output file equal to output file name
File inputFile = new File(inFileName); //Open input file
Scanner in = new Scanner(inputFile); //Use in for scanner objects within the inputfile
PrintWriter out = new PrintWriter(outFileName); //Print writer to print to output file
double lodgingTotal = 0;
double conferenceTotal = 0;
double roomServiceTotal = 0;
double dinnerTotal = 0;
double spaTotal = 0;
while(in.hasNextLine()) //While the input file has another line of content
{
String line = in.nextLine();
Scanner reader = new Scanner(line); //Use this scanner for each line in the input file
reader.useDelimiter(";"); //Instead of white space, use semi-colon to mark the end of a word
String name = reader.next(); //Reads first word before semicolon
String type= reader.next();//Reads second word before semicolon
double cost = reader.nextDouble(); //Save cost of the double
String date = reader.next();
if(type.equals("Lodging"))//if the cost was from lodging
{lodgingTotal = lodgingTotal + cost;}
if(type.equals("Conference"))//if the cost was from conferences
{conferenceTotal = conferenceTotal + cost;}
if(type.equals("Room Service"))//if the cost was from room service
{roomServiceTotal = roomServiceTotal + cost;}
if(type.equals("Dinner"))//if the cost was from dinners
{dinnerTotal = dinnerTotal + cost;}
if(type.equals("Spa"))//if the cost was from the spa
{spaTotal = spaTotal + cost;}
}
displayResult(lodgingTotal, conferenceTotal, roomServiceTotal, dinnerTotal, spaTotal, out);//Calls for method to calculate and display results
in.close();//close input file
out.close();// close output file
}
catch (FileNotFoundException exception)
{System.out.println("The input file was not found!");}
catch (NoSuchElementException exception)
{System.out.println("The format of the input is invaild!");}
}
/**
Asks for user to enter in the name and location of the input file
@param is the string inFileName
@return the inputted name of the input file
*/
public static String userInFile(String inFileName) throws FileNotFoundException
{
Scanner console = new Scanner(System.in);
System.out.print("Enter Input File: ");
inFileName = console.next();
return inFileName;
}
/**
Asks for user to enter name of the output file they wish to create
@param is the string outFileName
@return the inputted name of the output file
*/
public static String userOutFile(String outFileName)
{
Scanner console = new Scanner(System.in);
System.out.println("If you do not have a output file then it will create one for you automatically!");
System.out.print("Enter Output File: ");
outFileName = console.next();
return outFileName;
}
/**
Displays the total cost of each type of cost in the hotel in the compiler and into the output file
@param is the printwriter, total of lodging cost, total of conference cost, total of room service costs, total of dinner cost, total of spa cost
@return is nothing because the method is void
*/
public static void displayResult(double lodgingTotal,double conferenceTotal,double roomServiceTotal,double dinnerTotal,double spaTotal,PrintWriter out)
{
System.out.printf("Lodging: %10.2f\n", lodgingTotal);//Displays to compiler
System.out.printf("Conference: %10.2f\n", conferenceTotal);
System.out.printf("Room Service: %10.2f\n", roomServiceTotal);
System.out.printf("Dinner: %10.2f\n", dinnerTotal);
System.out.printf("Spa: %10.2f\n", spaTotal);
out.printf("Lodging: %10.2f\n", lodgingTotal);//Displays to output files
out.printf("Conference: %10.2f\n", conferenceTotal);
out.printf("Room Service: %10.2f\n", roomServiceTotal);
out.printf("Dinner: %10.2f\n", dinnerTotal);
out.printf("Spa: %10.2f\n", spaTotal);
}
}
|
package br.com.softplan.services;
import java.util.HashSet;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import br.com.softplan.domain.User;
import br.com.softplan.domain.enums.UserType;
import br.com.softplan.repositories.UserRepository;
import br.com.softplan.security.UserSpringSecurity;
@Service
public class UserDetailServiceImpl implements UserDetailsService{
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException {
User user = userRepository.findByLoginUser(login);
if (user == null) {
throw new UsernameNotFoundException(login);
}
Set<UserType> profile = new HashSet<UserType>();
profile.add(UserType.toEnum(user.getTypeUser()));
return new UserSpringSecurity(
user.getId(),
user.getLoginUser(),
user.getPassword(),
profile);
}
}
|
package project1;
public class SquareMethod {
public static int square(int a) {
int b=a*a;
return b;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int a=9;
double result=square(a);
System.out.println(result);
}
}
|
package kr.ac.kopo.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class JdbcTest {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("oracle.jdbc.driver.OracleDriver");
String serverName = "192.168.119.119";
String portNumber = "1521";
String sid = "dink";
String url = "jdbc:oracle:thin:@" + serverName + ":" + portNumber + ":" + sid;
String username = "scott";
String password = "tiger";
Connection conn = DriverManager.getConnection(url, username, password);
String sql = "SELECT DEPTNO,SAL*12 AS ANNUAL_SAL,ENAME,JOB,HIREDATE FROM EMP ORDER BY DEPTNO";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
ArrayList<String> list = new ArrayList<String>();
while (rs.next()) {
String current = rs.getString("ENAME");
current = current + "\t" + rs.getString("SAL");
current = current + "\t" + rs.getString("COMM");
current = current + "\t" + rs.getString("DEPTNO");
current = current + "\t" + rs.getString("JOB");
list.add(current);
}
System.out.println("ENAME" + "\t" + "SAL" + "\t" + "COMM" + "\t" + "DEPTNO" + "\t" + "JOB");
System.out.println("");
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
}
|
package restaurant;
public class Table {
int numberOfTable;
boolean isOccupied;
Order order;
public Table() {}
public Table(int numberOfTable, boolean isOccupied, Order order) {
super();
this.numberOfTable = numberOfTable;
this.isOccupied = isOccupied;
this.order = order;
}
public int getNumberOfTable() {
return numberOfTable;
}
public void setNumberOfTable(int numberOfTable) {
this.numberOfTable = numberOfTable;
}
public boolean isOccupied() {
return isOccupied;
}
public void setOccupied(boolean isOccupied) {
this.isOccupied = isOccupied;
}
public Order getOrder() {
return order;
}
public void setOrder(Order order) {
this.order = order;
}
}
|
package com.jgw.supercodeplatform.trace.dto.template.query;
import com.jgw.supercodeplatform.trace.common.model.page.DaoSearch;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* 溯源功能-查询追溯模板
*/
@ApiModel(value = "溯源功能-查询追溯模板")
public class TraceFunTemplateconfigListParam extends DaoSearch {
@ApiModelProperty(value = "主键id")
private Long id;
@ApiModelProperty(value = "溯源模板号")
private String traceTemplateId;//溯源模板号
@ApiModelProperty(value = "溯源模板名称")
private String traceTemplateName;//溯源模板名称
@ApiModelProperty(value = "组织id",hidden = true)
private String organizationId;//组织id
@ApiModelProperty(value = "节点数量")
private Integer nodeCount;//节点数
@ApiModelProperty(value = "使用批次数量")
private String traceBatchNum;//使用批次数量
@ApiModelProperty(value = "创建人")
private String createMan;//创建人
@ApiModelProperty(value = "创建时间")
private String createTime;//创建时间
@ApiModelProperty(value = "业务类型")
private String businessType; //业务类型 1、自动节点 2、手动节点 3、默认节点
@ApiModelProperty(value = "功能ID号")
private String nodeFunctionId; //功能ID号
@ApiModelProperty(value = "功能名称")
private String nodeFunctionName; //功能名称
@ApiModelProperty(value = "节点顺序")
private Integer nodeWeight; //节点顺序
public TraceFunTemplateconfigListParam() {
}
public TraceFunTemplateconfigListParam(Long id, String traceTemplateId, String traceTemplateName, String organizationId, Integer nodeCount, String traceBatchNum, String createMan, String createTime, String businessType, String nodeFunctionId, String nodeFunctionName, Integer nodeWeight) {
this.id = id;
this.traceTemplateId = traceTemplateId;
this.traceTemplateName = traceTemplateName;
this.organizationId = organizationId;
this.nodeCount = nodeCount;
this.traceBatchNum = traceBatchNum;
this.createMan = createMan;
this.createTime = createTime;
this.businessType = businessType;
this.nodeFunctionId = nodeFunctionId;
this.nodeFunctionName = nodeFunctionName;
this.nodeWeight = nodeWeight;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTraceTemplateId() {
return traceTemplateId;
}
public void setTraceTemplateId(String traceTemplateId) {
this.traceTemplateId = traceTemplateId;
}
public String getTraceTemplateName() {
return traceTemplateName;
}
public void setTraceTemplateName(String traceTemplateName) {
this.traceTemplateName = traceTemplateName;
}
public String getOrganizationId() {
return organizationId;
}
public void setOrganizationId(String organizationId) {
this.organizationId = organizationId;
}
public Integer getNodeCount() {
return nodeCount;
}
public void setNodeCount(Integer nodeCount) {
this.nodeCount = nodeCount;
}
public String getTraceBatchNum() {
return traceBatchNum;
}
public void setTraceBatchNum(String traceBatchNum) {
this.traceBatchNum = traceBatchNum;
}
public String getCreateMan() {
return createMan;
}
public void setCreateMan(String createMan) {
this.createMan = createMan;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public String getNodeFunctionId() {
return nodeFunctionId;
}
public void setNodeFunctionId(String nodeFunctionId) {
this.nodeFunctionId = nodeFunctionId;
}
public String getNodeFunctionName() {
return nodeFunctionName;
}
public void setNodeFunctionName(String nodeFunctionName) {
this.nodeFunctionName = nodeFunctionName;
}
public Integer getNodeWeight() {
return nodeWeight;
}
public void setNodeWeight(Integer nodeWeight) {
this.nodeWeight = nodeWeight;
}
}
|
package services;
import java.util.ArrayList;
import java.util.Collection;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import repositories.FloatEntityRepository;
import security.LoginService;
import datatype.Url;
import domain.Actor;
import domain.Brotherhood;
import domain.FloatEntity;
import domain.Parade;
@Service
@Transactional
public class FloatEntityService {
@Autowired
private FloatEntityRepository floatRepository;
@Autowired
private ActorService actorService;
@Autowired
private ParadeService paradeService;
@Autowired
private BrotherhoodService brotherhoodService;
@Autowired
private Validator validator;
public FloatEntity reconstruct(final FloatEntity f, final BindingResult binding) {
FloatEntity result;
if (f.getId() == 0) {
result = f;
this.validator.validate(f, binding);
} else {
result = this.floatRepository.findOne(f.getId());
f.setBrotherhood(result.getBrotherhood());
f.setVersion(result.getVersion());
result = f;
this.validator.validate(f, binding);
}
return result;
}
public FloatEntity create() {
FloatEntity res;
res = new FloatEntity();
res.setPictures(new ArrayList<Url>());
return res;
}
public Collection<FloatEntity> findAll() {
Collection<FloatEntity> res;
res = this.floatRepository.findAll();
return res;
}
public FloatEntity findOne(final int floatEntityId) {
FloatEntity res;
res = this.floatRepository.findOne(floatEntityId);
return res;
}
public FloatEntity save(final FloatEntity floatEntity) {
FloatEntity res;
Assert.notNull(floatEntity);
Assert.isTrue(this.actorService.getActorLogged().getUserAccount().getAuthorities().iterator().next().getAuthority().equals("BROTHERHOOD"));
final Actor user = this.actorService.findByUsername(LoginService.getPrincipal().getUsername());
final Brotherhood b = this.brotherhoodService.findOne(user.getId());
if (floatEntity.getId() == 0) {
floatEntity.setBrotherhood(b);
res = this.floatRepository.save(floatEntity);
} else {
Assert.isTrue(floatEntity.getBrotherhood().equals(b));
res = this.floatRepository.save(floatEntity);
}
return res;
}
public void delete(final FloatEntity floatEntity) {
Assert.notNull(floatEntity);
Assert.isTrue(this.actorService.getActorLogged().getUserAccount().getAuthorities().iterator().next().getAuthority().equals("BROTHERHOOD"));
Collection<Parade> parades;
parades = this.paradeService.findAll();
for (final Parade p : parades) {
Collection<FloatEntity> floats;
floats = p.getFloats();
if (floats.contains(floatEntity)) {
floats.remove(floatEntity);
p.setFloats(floats);
}
}
this.floatRepository.delete(floatEntity);
}
public Collection<FloatEntity> getFloatsByBrotherhood(final Brotherhood b) {
Collection<FloatEntity> result;
result = this.floatRepository.getFloatsByBrotherhood(b);
return result;
}
}
|
package org.team16.team16week5;
import static org.junit.Assert.*;
import org.junit.Test;
public class PrintExpectedBillTest {
private PrintExpectedBill printExpectedBill;
private DetailedCost detailedCost;
private User user;
private Gold gold = new Gold();
private Silver silver = new Silver();
@Test
public void testNoAdditionalCost(){
this.user = new User(silver,1,490);
detailedCost = new DetailedCost(this.user);
printExpectedBill = new PrintExpectedBill(this.detailedCost);
assertEquals("29.95" , ""+this.printExpectedBill.printTotalCostEvaluation());
assertEquals(null , this.printExpectedBill.printOverExcessMinutesCostEvaluation());
assertEquals(null , this.printExpectedBill.printAdditionalLineCostEvaluation());
}
@Test
public void testOverExcessMinutes(){
this.user = new User(gold,1,1123);
detailedCost = new DetailedCost(this.user);
printExpectedBill = new PrintExpectedBill(this.detailedCost);
assertEquals("49.95 + (123*0.45) = 105.30" , ""+this.printExpectedBill.printTotalCostEvaluation());
assertEquals(" + (123*0.45)" , this.printExpectedBill.printOverExcessMinutesCostEvaluation());
assertEquals(null , this.printExpectedBill.printAdditionalLineCostEvaluation());
}
@Test
public void testHaveFamilyDiscountThreeAdditionalLine(){
this.user = new User(silver,4,459);
detailedCost = new DetailedCost(this.user);
printExpectedBill = new PrintExpectedBill(this.detailedCost);
assertEquals("29.95 + (2*21.5) + 5.0 = 77.95" , ""+this.printExpectedBill.printTotalCostEvaluation());
assertEquals(null , this.printExpectedBill.printOverExcessMinutesCostEvaluation());
assertEquals(" + (2*21.5) + 5.0" , this.printExpectedBill.printAdditionalLineCostEvaluation());
}
@Test
public void testHaveFamilyDiscountOverThreeAdditionalLine(){
this.user = new User(gold,5,981);
detailedCost = new DetailedCost(this.user);
printExpectedBill = new PrintExpectedBill(this.detailedCost);
assertEquals("49.95 + (2*14.5) + (2*5.0) = 88.95" , ""+this.printExpectedBill.printTotalCostEvaluation());
assertEquals(null , this.printExpectedBill.printOverExcessMinutesCostEvaluation());
assertEquals(" + (2*14.5) + (2*5.0)" , this.printExpectedBill.printAdditionalLineCostEvaluation());
}
@Test
public void testNoFamilyDiscountOneAdditionalLine(){
this.user = new User(silver,2,354);
detailedCost = new DetailedCost(this.user);
printExpectedBill = new PrintExpectedBill(this.detailedCost);
assertEquals("29.95 + 21.5 = 51.45" , ""+this.printExpectedBill.printTotalCostEvaluation());
assertEquals(null , this.printExpectedBill.printOverExcessMinutesCostEvaluation());
assertEquals(" + 21.5" , this.printExpectedBill.printAdditionalLineCostEvaluation());
}
@Test
public void testNoFamilyDiscountTwoAdditionalLine(){
this.user = new User(gold,3,885);
detailedCost = new DetailedCost(this.user);
printExpectedBill = new PrintExpectedBill(this.detailedCost);
assertEquals("49.95 + (2*14.5) = 78.95" , ""+this.printExpectedBill.printTotalCostEvaluation());
assertEquals(null , this.printExpectedBill.printOverExcessMinutesCostEvaluation());
assertEquals(" + (2*14.5)" , this.printExpectedBill.printAdditionalLineCostEvaluation());
}
}
|
package com.easyclean.easyclean;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.io.Serializable;
public class OrderActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
RadioButton radioRegular;
RadioButton radioExpress;
CheckBox checkBox_laundryBag;
CheckBox checkBox_bedSheet;
CheckBox checkBox_bedCover;
TextView increase_laundryBag;
TextView increase_bedSheet;
TextView increase_bedCover;
TextView decrease_laundryBag;
TextView decrease_bedSheet;
TextView decrease_bedCover;
TextView count_laundryBag;
TextView count_bedSheet;
TextView count_bedCover;
TextView text_total;
int countLaundryBag = 0;
int countBedSheet = 0;
int countBedCover = 0;
int total = 0;
boolean regular = true;
boolean express = false;
boolean laundryBag = false;
boolean bedSheet = false;
boolean bedCover = false;
DatabaseReference transactionReference;
Transaction transaction;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order);
Toolbar myToolbar = findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
radioRegular = findViewById(R.id.radio_regular);
radioExpress = findViewById(R.id.radio_express);
checkBox_laundryBag = findViewById(R.id.checkBox_laundryBag);
checkBox_bedSheet = findViewById(R.id.checkBox_bedSheet);
checkBox_bedCover = findViewById(R.id.checkBox_bedCover);
increase_laundryBag = findViewById(R.id.increase_laundryBag);
increase_bedSheet = findViewById(R.id.increase_bedSheet);
increase_bedCover = findViewById(R.id.increase_bedCover);
decrease_laundryBag = findViewById(R.id.decrease_laundryBag);
decrease_bedSheet = findViewById(R.id.decrease_bedSheet);
decrease_bedCover = findViewById(R.id.decrease_bedCover);
count_laundryBag = findViewById(R.id.count_laundryBag);
count_bedSheet = findViewById(R.id.count_bedSheet);
count_bedCover = findViewById(R.id.count_bedCover);
text_total = findViewById(R.id.total);
mAuth = FirebaseAuth.getInstance();
transactionReference = FirebaseDatabase.getInstance().getReference("Transactions");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_logout:
mAuth.signOut();
startActivity(new Intent(this, LoginActivity.class));
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void onClick(View view){
switch (view.getId()){
case R.id.increase_laundryBag:
countLaundryBag++;
changeLaundryBag();
hitung();
break;
case R.id.increase_bedSheet:
countBedSheet++;
changeBedSheet();
hitung();
break;
case R.id.increase_bedCover:
countBedCover++;
changeBedCover();
hitung();
break;
case R.id.decrease_laundryBag:
if (countLaundryBag>0){
countLaundryBag--;
changeLaundryBag();
hitung();
}
break;
case R.id.decrease_bedSheet:
if (countBedSheet >0){
countBedSheet--;
changeBedSheet();
hitung();
}
break;
case R.id.decrease_bedCover:
if (countBedCover>0){
countBedCover--;
changeBedCover();
hitung();
}
break;
case R.id.button_back:
finish();
break;
case R.id.button_next:
save();
break;
default:
break;
}
}
private void save() {
if (text_total.getText().toString().equals("0")){
Toast.makeText(this, "Choose Service.",
Toast.LENGTH_SHORT).show();
return;
}
String transId = transactionReference.push().getKey();
String uid = mAuth.getCurrentUser().getUid();
String type;
if (regular) {
type = "regular";
} else {
type = "express";
}
transaction = new Transaction(transId, uid, type);
if (laundryBag) {
transaction.setLaundryBag(String.valueOf(countLaundryBag));
}
if (bedSheet) {
transaction.setBedSheet(String.valueOf(countBedSheet));
}
if (bedCover) {
transaction.setBedCover(String.valueOf(countBedCover));
}
transaction.total = String.valueOf(total);
Intent intent = new Intent(this, LocationActivity.class);
intent.putExtra("transaction", transaction);
startActivity(intent);
}
public void changeLaundryBag(){
count_laundryBag.setText(countLaundryBag+"");
}
public void changeBedSheet(){
count_bedSheet.setText(countBedSheet +"");
}
public void changeBedCover(){
count_bedCover.setText(countBedCover +"");
}
public void onRadioButtonClicked(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch(view.getId()) {
case R.id.radio_regular:
if (checked) {
regular = true;
express = false;
hitung();
}
break;
case R.id.radio_express:
if (checked){
regular = false;
express = true;
hitung();
}
break;
}
}
public void onCheckboxClicked(View view) {
boolean checked = ((CheckBox) view).isChecked();
switch(view.getId()) {
case R.id.checkBox_laundryBag:
laundryBag = checked;
hitung();
break;
case R.id.checkBox_bedSheet:
bedSheet = checked;
hitung();
break;
case R.id.checkBox_bedCover:
bedCover = checked;
hitung();
break;
}
}
public void hitung(){
int total = 0;
int laundryBagCost = 41000;
int bedSheetCost = 25000;
int bedCoverCost = 50000;
int expressCost = 20000;
if (laundryBag){
if (express){
total+=(laundryBagCost+expressCost)*countLaundryBag;
}else{
total+=laundryBagCost*countLaundryBag;
}
}
if (bedSheet){
if (express){
total+=(bedSheetCost+expressCost)*countBedSheet;
}else{
total+=bedSheetCost*countBedSheet;
}
}
if (bedCover){
if (express){
total+=(bedCoverCost+expressCost)*countBedCover;
}else{
total+=bedCoverCost*countBedCover;
}
}
this.total = total;
text_total.setText(this.total+"");
}
}
|
/**
*
*/
package gaydadsProject1;
/**
* @author David Gayda
* Instructor: Prof. Bachman
* CSE 283, Section B
*
* This BattleshipBoard contains methods to create and maintain
* a simple battleship game. This is to be used with the server
* and client class of the Project 1 Program.
*
* MAX_GUESSES can be changed in this class to limit the length of the game.
*
* All aspects of this program with the exception of a few
* noted pieces provided by Prof. Bachman
*
*/
public class BattleshipBoard {
//These ints are used to keep track of the codes needed to be used often.
static final int MAX_GUESSES = 25;
static final int BLANK = 1;
static final int MISS = 2;
static final int DESTROYER = 3;
static final int CRUISER = 4;
static final int BATTLESHIP = 5;
static final int HIT = 6;
static final int MISS_CODE = 10;
static final int HIT_CODE = 20;
static final int SINK_CODE = 30;
static final int ILLEGAL_MOVE_CODE = 40;
static final int GAME_CONTINUES = 10;
static final int CLIENT_WON = 20;
static final int SERVER_WON = 30;
static final int ILLEGAL_MOVE_GAME_OVER = 40;
Boolean isIllegalMoveTriggered;
//This int is used to track how many guesses the user has and compare with the max allowed.
int guessesCount;
//These ints are used to determine random ship placements
int randomRow;
int randomCol;
int randomAxis;
//This array is used to track information on the board.
int [] [] boardArray;
//These ints track how many hits each ship has taken on.
int destroyerCount;
int cruiserCount;
int battleshipCount;
/**
* This is the constructor for the BattleshipBoard Object
*/
public BattleshipBoard() {
this.isIllegalMoveTriggered = false;
this.destroyerCount = 2;
this.cruiserCount = 3;
this.battleshipCount = 4;
this.boardArray = createBoard();
}
/**
* This method is a shortcut to place all ships with one method
*/
protected void placeShips() {
placeDestroyer(this.boardArray);
placeCruiser(this.boardArray);
placeBattleship(this.boardArray);
}
/**
* This method creates an array of arrays containing
* 1 (BLANK) the value for a blank space
* @return
*/
private int [][] createBoard() {
int rows = 10;
int cols = 10;
int board[][] = new int[rows][cols];
for (int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++) {
board[i][j] = 1;
}
}
return board;
}
/**
* This method takes in the board array and prints out
* the corresponding board to the console.
* @param board
*/
protected void printBoard() {
//Taken from Example Code
for (int r = 0; r < this.boardArray.length; r++) {
System.out.print("|");
for (int c = 0; c < this.boardArray[r].length; c++) {
if (this.boardArray[r][c] == BLANK ) {
System.out.print(" _ |");
}
else if (this.boardArray[r][c] == MISS ) {
System.out.print(" M |");
}
else if (this.boardArray[r][c] == DESTROYER ) {
System.out.print(" D |");
}
else if (this.boardArray[r][c] == CRUISER ) {
System.out.print(" C |");
}
else if (this.boardArray[r][c] == BATTLESHIP ) {
System.out.print(" B |");
}
else {
System.out.print(" H |");
}
}
System.out.println();
}
}
/**
* This method checks compares the player's move and the current board.
* It returns an int specifying what has occurred (10, 20, 30, 40)
* @param row
* @param col
* @return
*/
protected int checkMoveStatus(int row, int col) {
if (row > 9 || row < 0 || col > 9 || col < 0) {
isIllegalMoveTriggered = true;
return ILLEGAL_MOVE_CODE;
}
guessesCount++;
if (this.boardArray[row][col] == DESTROYER ) {
destroyerCount--;
if (destroyerCount == 0) {
return SINK_CODE;
}
else {
return HIT_CODE;
}
}
else if (this.boardArray[row][col] == CRUISER ) {
cruiserCount--;
if (cruiserCount == 0) {
return SINK_CODE;
}
else {
return HIT_CODE;
}
}
else if (this.boardArray[row][col] == BATTLESHIP ) {
battleshipCount--;
if (battleshipCount == 0) {
return SINK_CODE;
}
else {
return HIT_CODE;
}
}
else {
return MISS_CODE;
}
}
/**
* This method checks the game status based on the current move and returns
* an int (10,20,30,40) determining if the game should end, who won, or if it continues.
* @return
*/
protected int checkGameStatus() {
if (guessesCount == MAX_GUESSES ) {
return SERVER_WON;
}
else if(destroyerCount == 0 && cruiserCount == 0 && battleshipCount == 0) {
return CLIENT_WON;
}
else if (this.isIllegalMoveTriggered == true) {
return ILLEGAL_MOVE_GAME_OVER;
}
else {
return GAME_CONTINUES;
}
}
/**
* This method places a "Destroyer" ship to the board.
* A "Destroyer" is a boat that is 2 spaces in length.
* No need to check for other ships on the board, only if out of bounds.
* @param board
*/
private void placeDestroyer(int board [][]) {
//Choose Random Position and Axis between 1-9 to account for boundaries issues
randomRow = (int) ((Math.random() * 9) + 1);
randomCol = (int) ((Math.random() * 9) + 1);
randomAxis = (int) (Math.random() * 2);
//If randomAxis == 1 try to place Vertically
if (randomAxis == 1) {
board [randomRow][randomCol] = DESTROYER;
board [randomRow - 1][randomCol] = DESTROYER;
}
else {
board [randomRow][randomCol] = DESTROYER;
board [randomRow][randomCol - 1] = DESTROYER;
}
}
/**
*This method places a "Cruiser" ship to the board.
* A "Cruiser" is a boat that is 3 spaces in length.
* If the ship is overlapping another, I just choose another random number.
* Given that only 3 ships are on the board at any time, there is no need to check
* for a full board or lack of positions.
* @param board
*/
private void placeCruiser(int board [][]) {
//Choose Random Position and Axis between 2-8 to account for boundaries issues
randomRow = (int) ((Math.random() * 8) + 2);
randomCol = (int) ((Math.random() * 8) + 2);
randomAxis = (int) (Math.random() * 2);
//If randomAxis == 1 try to place Vertically
if (randomAxis == 1) {
while (board [randomRow][randomCol] != BLANK
|| board [randomRow - 1][randomCol] != BLANK
|| board [randomRow - 2][randomCol] != BLANK) {
randomRow = (int) ((Math.random() * 8) + 2);
randomCol = (int) ((Math.random() * 8) + 2);
}
board [randomRow][randomCol] = CRUISER;
board [randomRow - 1][randomCol] = CRUISER;
board [randomRow - 2][randomCol] = CRUISER;
}
else {
while (board [randomRow][randomCol] != BLANK
|| board [randomRow - 1][randomCol] != BLANK
|| board [randomRow - 2][randomCol] != BLANK) {
randomRow = (int) ((Math.random() * 8) + 2);
randomCol = (int) ((Math.random() * 8) + 2);
}
board [randomRow][randomCol] = CRUISER;
board [randomRow][randomCol - 1] = CRUISER;
board [randomRow][randomCol - 2] = CRUISER;
}
}
/**
*This method places a "Battleship" ship to the board.
* A "Battleship" is a boat that is 4 spaces in length.
* Given that only 3 ships are on the board at any time, there is no need to check
* for a full board or lack of positions.
* @param board
*/
private void placeBattleship(int board [][]) {
//Choose Random Position and Axis between 4-7 to account for boundaries issues
randomRow = (int) ((Math.random() * 7) + 3);
randomCol = (int) ((Math.random() * 7) + 3);
randomAxis = (int) (Math.random() * 2);
//If randomAxis == 1 try to place Vertically
if (randomAxis == 1) {
//If any part of the ship is overlapping, try new spot
while (board [randomRow][randomCol] != BLANK
|| board [randomRow - 1][randomCol] != BLANK
|| board [randomRow - 2][randomCol] != BLANK
|| board [randomRow - 3][randomCol] != BLANK) {
randomRow = (int) ((Math.random() * 7) + 3);
randomCol = (int) ((Math.random() * 7) + 3);
}
board [randomRow ][randomCol] = BATTLESHIP;
board [randomRow - 1][randomCol] = BATTLESHIP;
board [randomRow - 2][randomCol] = BATTLESHIP;
board [randomRow - 3][randomCol] = BATTLESHIP;
}
else {
//If any part of the ship is overlapping, try new spot
while (board [randomRow][randomCol] != BLANK
|| board [randomRow][randomCol - 1] != BLANK
|| board [randomRow][randomCol - 2] != BLANK
|| board [randomRow][randomCol - 3] != BLANK) {
randomRow = (int) ((Math.random() * 7) + 3);
randomCol = (int) ((Math.random() * 7) + 3);
}
board [randomRow ][randomCol] = BATTLESHIP;
board [randomRow][randomCol - 1] = BATTLESHIP;
board [randomRow][randomCol - 2] = BATTLESHIP;
board [randomRow][randomCol - 3] = BATTLESHIP;
}
}
/**
* This is the main method for this class,
* only used for testing and development purposes.
* @param args
*/
}
|
package decisao;
import javax.swing.JOptionPane;
public class DecisaoEncadeada {
public static void main(String[] args) {
// TODO Auto-generated method stub
String materia = JOptionPane.showInputDialog("Materia");
float faltas = Float.parseFloat(JOptionPane.showInputDialog("faltas"));
if (faltas >= 20 ) {
System.out.println("REPROVADO POR NUMERO DE FALTAS");
} else {
float nota1 = Float.parseFloat(JOptionPane.showInputDialog("nota1"));
float nota2 = Float.parseFloat(JOptionPane.showInputDialog("nota2"));
float media = (nota1 + nota2) /2;
if (media >= 6 ) {
System.out.println("APROVADO");
} else if (media < 4 ) {
System.out.println("REPROVADO");
} else {
System.out.println("EXAME");
}
System.out.println("Media: " + media);
System.out.println("Faltas: " + faltas);
}
}
}
|
package nl.tue.win.dbt.data;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
public class LabeledVertex<V, L> implements Serializable {
private final V data;
private final Set<L> labels;
public LabeledVertex(V data, Collection<? extends L> labels) {
this.data = data;
this.labels = new HashSet<>(labels);
}
public LabeledVertex(V data) {
this.data = data;
this.labels = new HashSet<>();
}
public V getData() {
return data;
}
public Set<L> getLabels() {
return labels;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
LabeledVertex<?, ?> that = (LabeledVertex<?, ?>) o;
if (data != null ? !data.equals(that.data) : that.data != null) return false;
return labels != null ? labels.equals(that.labels) : that.labels == null;
}
@Override
public int hashCode() {
int result = data != null ? data.hashCode() : 0;
result = 31 * result + (labels != null ? labels.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "LabeledVertex{" +
"data=" + data +
", labels=" + labels +
'}';
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.