text
stringlengths 10
2.72M
|
|---|
package com.ulman.currencyrate.preference;
import android.content.SharedPreferences;
import com.ulman.currencyrate.CurrencyRateApplication;
import com.ulman.currencyrate.CurrencyRateConstant;
public class CurrencyRatePreference {
private SharedPreferences sharedPreferences;
public CurrencyRatePreference() {
sharedPreferences = CurrencyRateApplication.getSharedPreference();
}
/*
today rate preference methods
*/
public void saveUsdRate(String usdRate) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(CurrencyRateConstant.NEXT_RATE_USD_KEY, usdRate);
editor.apply();
}
public void saveEurRate(String eurRate) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(CurrencyRateConstant.NEXT_RATE_EUR_KEY, eurRate);
editor.apply();
}
public String loadUsdRate() {
return sharedPreferences.getString(CurrencyRateConstant.NEXT_RATE_USD_KEY, "0.0");
}
public String loadEurRate() {
return sharedPreferences.getString(CurrencyRateConstant.NEXT_RATE_EUR_KEY, "0.0");
}
/*
next day preference methods
*/
public void saveRateNextDate(String nextDate) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(CurrencyRateConstant.RATE_NEXT_DAY_KEY, nextDate);
editor.apply();
}
public String loadRateNextDate() {
return sharedPreferences.getString(CurrencyRateConstant.RATE_NEXT_DAY_KEY, "01.01.1970");
}
/*
previous difference rate preference methods
*/
public void savePreviousDifferenceInUsdRate(String difference) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(CurrencyRateConstant.PREVIOUS_DIFFERENCE_IN_RATE_USD_KEY, difference);
editor.apply();
}
public void savePreviousDifferenceInEurRate(String difference) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(CurrencyRateConstant.PREVIOUS_DIFFERENCE_IN_RATE_EUR_KEY, difference);
editor.apply();
}
public String loadPreviousDifferenceInUsdRate() {
return sharedPreferences.getString(CurrencyRateConstant.PREVIOUS_DIFFERENCE_IN_RATE_USD_KEY, "");
}
public String loadPreviousDifferenceInEurRate() {
return sharedPreferences.getString(CurrencyRateConstant.PREVIOUS_DIFFERENCE_IN_RATE_EUR_KEY, "");
}
/*
next difference rate preference methods
*/
public void saveNextDifferenceInUsdRate(String difference) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(CurrencyRateConstant.NEXT_DIFFERENCE_IN_RATE_USD_KEY, difference);
editor.apply();
}
public void saveNextDifferenceInEurRate(String difference) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(CurrencyRateConstant.NEXT_DIFFERENCE_IN_RATE_EUR_KEY, difference);
editor.apply();
}
public String loadNextDifferenceInUsdRate() {
return sharedPreferences.getString(CurrencyRateConstant.NEXT_DIFFERENCE_IN_RATE_USD_KEY, "");
}
public String loadNextDifferenceInEurRate() {
return sharedPreferences.getString(CurrencyRateConstant.NEXT_DIFFERENCE_IN_RATE_EUR_KEY, "");
}
/*
previous rate preference methods
*/
public void saveUsdPreviousRate(String previousUsdRate) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(CurrencyRateConstant.PREVIOUS_RATE_USD_KEY, previousUsdRate);
editor.apply();
}
public void saveEurPreviousRate(String previousEurRate) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(CurrencyRateConstant.PREVIOUS_RATE_EUR_KEY, previousEurRate);
editor.apply();
}
public String loadUsdPreviousRate() {
return sharedPreferences.getString(CurrencyRateConstant.PREVIOUS_RATE_USD_KEY, "0.0");
}
public String loadEurPreviousRate() {
return sharedPreferences.getString(CurrencyRateConstant.PREVIOUS_RATE_EUR_KEY, "0.0");
}
/*
previous day preference methods
*/
public void saveRatePreviousDate(String previousDate) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(CurrencyRateConstant.RATE_PREVIOUS_DAY_KEY, previousDate);
editor.apply();
}
public String loadRatePreviousDate() {
return sharedPreferences.getString(CurrencyRateConstant.RATE_PREVIOUS_DAY_KEY, "01.01.1970");
}
/*
settings preferences
*/
public void saveTransparency(int value) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(CurrencyRateConstant.SETTINGS_TRANSPARENCY_VALUE_KEY, value);
editor.apply();
}
public int loadTransparency() {
return sharedPreferences.getInt(CurrencyRateConstant.SETTINGS_TRANSPARENCY_VALUE_KEY, CurrencyRateConstant.SEEKBAR_HALF_VALUE);
}
}
|
package avatar.com.mymvptestone.java.mvp.base;
import java.lang.ref.WeakReference;
/**
* $desc$
*
* @author Frank
* email xiong.fu@avatarmind.com
* created 19-4-4 下午1:26.
*/
public abstract class BasePresenter<M extends Model, V extends View> implements Presenter<V,M> {
protected M model;
protected WeakReference<V> wrfView;
@Override
public void registerModel(M model) {
this.model = model;
}
@Override
public void registerView(V view) {
this.wrfView = new WeakReference<V>(view);
}
@Override
public V getView() {
return wrfView == null? null : wrfView.get();
}
@Override
public void destroy() {
if (wrfView != null){
wrfView.clear();
wrfView = null;
}
onViewDestroy();
}
public abstract void onViewDestroy();
}
|
package memoryPlay.GCAndMalloc;
public class FinalizeEscapeGC {
public static FinalizeEscapeGC SAVE_HOOK=null;
public void isAlive(){
System.out.println("I am still alive");
}
protected void finalize() throws Throwable{
super.finalize();
System.out.println("finalize method executed!");
FinalizeEscapeGC.SAVE_HOOK=this;
}
/**
* @param args
* @throws Throwable
*/
public static void main(String[] args) throws Throwable {
SAVE_HOOK=new FinalizeEscapeGC();
SAVE_HOOK=null;
System.gc();
Thread.sleep(600);
if(SAVE_HOOK!=null){
SAVE_HOOK.isAlive();
// SAVE_HOOK.finalize();
// SAVE_HOOK.finalize();
}
else
System.out.println("I am collected back");
SAVE_HOOK=null;
System.gc();
Thread.sleep(600);
if(SAVE_HOOK!=null){
SAVE_HOOK.isAlive();
// SAVE_HOOK.finalize();
// SAVE_HOOK.finalize();
}
else
System.out.println("I am collected back");
}
}
|
package controllers.mappers;
/**
* Mapper for participation JSON
*/
public class ParticipationJSON {
private int id;
private String role;
public int getId() {
return id;
}
public String getRole() {
return role;
}
}
|
package avex.models;
public class AthleteWINS {
private String wins;
private String wins48;
public String getWins48() {
return wins48;
}
public void setWins48(String wins48) {
this.wins48 = wins48;
}
public String getWins() {
return wins;
}
public void setWins(String wins) {
this.wins = wins;
}
}
|
import java.util.*;
public class Tree<v> {
Node<v> root;
public Tree() {
root = new Node<v>();
}
public Tree(ArrayList<Pair<v>> pairsIn) {
root = new Node<v>();
for (int i = 0; i < pairsIn.size(); i++) {
insert(pairsIn.get(i).key, pairsIn.get(i).val);
}
}
public void insert(Integer keyIn, v valIn) {
if (root.val == null) {
root.setKey(keyIn);
root.setValue(valIn);
} else {
root.insert(keyIn, valIn);
}
}
public void printTree() {
root.printSubtree();
}
public Integer size() {
return root.size();
}
public Boolean includesValue(v valIn) {
return root.includesValue(valIn);
}
public Boolean includesKey(Integer keyIn) {
return root.includesKey(keyIn);
}
public v getValueAt(Integer keyIn) {
return root.getValueAt(keyIn);
}
public class Node<v> {
Integer key = 0;
v val = null;
Node<v> left = null;
Node<v> right = null;
public Node() {};
public Node(Integer keyIn, v valIn) {
key = keyIn;
val = valIn;
}
public void setKey(Integer keyIn) {
key = keyIn;
}
public void setValue(v valIn) {
val = valIn;
}
public void insert(Integer keyIn, v valIn) {
if (key == keyIn) {
return;
}
else if (keyIn < key) {
if (left == null) {
left = new Node<v>(keyIn, valIn);
}
else {
left.insert(keyIn, valIn);
}
}
else {
if (right == null) {
right = new Node<v>(keyIn, valIn);
}
else {
right.insert(keyIn, valIn);
}
}
}
public Integer size() {
Integer localSize = 1;
if (left != null) {
localSize += left.size();
}
if (right != null) {
localSize += right.size();
}
return localSize;
}
public boolean includesValue(v valIn) {
if (val == valIn) {
return true;
}
else if (left != null && left.includesValue(valIn)) {
return true;
}
else if (right != null && right.includesValue(valIn)) {
return true;
}
return false;
}
public boolean includesKey(Integer keyIn) {
if (key == keyIn) {
return true;
}
else if (key > keyIn) {
return (left != null && left.includesKey(keyIn));
}
else {
return (right != null && right.includesKey(keyIn));
}
}
public v getValueAt(Integer keyIn) {
if (key == keyIn) {
return val;
}
else if (key > keyIn) {
if (left != null) {
return left.getValueAt(keyIn);
}
else {
return null;
}
}
else {
if (right != null) {
return right.getValueAt(keyIn);
}
else {
return null;
}
}
}
public void printSubtree() {
if (left != null) {
left.printSubtree();
}
System.out.println(val);
if (right != null) {
right.printSubtree();
}
}
}
}
|
/*
* Copyright (C) 2011-2014 Aestas/IT
*
* 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.aestasit.markdown.slidery.configuration;
import java.io.File;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import com.google.common.base.Preconditions;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.google.common.collect.Ordering;
/**
* Straight-forward in-memory implementation of the {@link Configuration}
* interface.
*
* @author Andrey Adamovich
*
*/
public class SimpleConfiguration implements Configuration {
private File templateFile;
private final Collection<File> inputFiles = new LinkedHashSet<File>();
private Charset inputEncoding = Charset.forName("UTF-8");
private final Multimap<String, File> staticFiles = HashMultimap.create();
private final Map<String, String> options = new HashMap<String, String>();
private File outputFile;
private String author;
private String company;
private String title;
private String description;
private Date date;
private File logo;
private String theme;
private String font;
private URL fontLink;
private final Map<String, String> colors = new HashMap<String, String>();
private final Multimap<String, String> transitionRules = HashMultimap.create();
private final Multimap<String, String> stylingRules = HashMultimap.create();
private boolean notesIncluded = true;
private boolean listIncremented = true;
private boolean splitOutput = false;
private boolean stripHtml = true;
public SimpleConfiguration() {
super();
}
public SimpleConfiguration(final Configuration config) {
super();
configuration(config);
}
@Override
public ConfigurationBuilder configuration(final ConfigurationReader config) {
author(config.getAuthor());
backgroundColor(config.getBackgroundColor());
// TODO: config.getColor(name)
// TODO: color(ref, color)
company(config.getCompany());
if (config.getDate() != null) {
date(config.getDate());
}
description(config.getDescription());
if (config.getInputEncoding() != null) {
encoding(config.getInputEncoding());
}
// TODO: font(name)
// TODO: font(name, link)
fontColor(config.getFontColor());
includeNotes(config.notesIncluded());
incrementalLists(config.listsIncremented());
if (config.getInputFiles() != null) {
inputFiles(config.getInputFiles());
}
logo(config.getLogo());
// TODO: option(name, value)
outputFile(config.getOutputFile());
splitOutput(config.isSplitOutput());
// TODO: staticFile(staticFile)
// TODO: stylingRule(selector, rule)
templateFile(config.getTemplateFile());
theme(config.getTheme());
title(config.getTitle());
// TODO: transitionRule(selector, rule)
return this;
}
@Override
public ConfigurationBuilder clear() {
clearInputFiles();
clearStaticFiles();
clearTemplateFiles();
clearSnippets();
return this;
}
@Override
public ConfigurationBuilder clearInputFiles() {
inputFiles.clear();
return this;
}
@Override
public ConfigurationBuilder clearStaticFiles() {
staticFiles.clear();
return this;
}
@Override
public ConfigurationBuilder clearTemplateFiles() {
templateFile = null;
return this;
}
@Override
public ConfigurationBuilder clearSnippets() {
// TODO Auto-generated method stub
return this;
}
@Override
public SimpleConfiguration inputFile(final File inputFile) {
inputFiles.add(inputFile);
return this;
}
@Override
public SimpleConfiguration inputFiles(final Collection<File> inputFiles) {
this.inputFiles.addAll(Ordering.from(fileNames()).sortedCopy(inputFiles));
return this;
}
@Override
public SimpleConfiguration staticFile(final File staticFile) {
staticFiles.put(".", staticFile);
return this;
}
@Override
public SimpleConfiguration staticFiles(final Collection<File> staticFiles) {
this.staticFiles.putAll(".", staticFiles);
return this;
}
@Override
public SimpleConfiguration staticFile(final String relativePath, final File staticFile) {
staticFiles.put(relativePath, staticFile);
return this;
}
@Override
public SimpleConfiguration staticFiles(final String relativePath, final Collection<File> staticFiles) {
this.staticFiles.putAll(relativePath, staticFiles);
return this;
}
@Override
public SimpleConfiguration outputFile(final File outputFile) {
this.outputFile = outputFile;
return this;
}
@Override
public SimpleConfiguration templateFile(final File templateFile) {
this.templateFile = templateFile;
return this;
}
@Override
public SimpleConfiguration encoding(final String encoding) {
Preconditions.checkArgument(Charset.isSupported(encoding), "Charset is not supported!");
inputEncoding = Charset.forName(encoding);
return this;
}
@Override
public SimpleConfiguration encoding(final Charset encoding) {
Preconditions.checkNotNull(encoding, "Charset is null!");
Preconditions.checkArgument(Charset.isSupported(encoding.name()), "Charset is not supported!");
inputEncoding = encoding;
return this;
}
@Override
public SimpleConfiguration option(final String name, final String value) {
options.put(name, value);
return this;
}
@Override
public void validate() {
Preconditions.checkState(inputFiles.size() > 0, "No input files given!");
Preconditions.checkState(outputFile != null, "Output file is not specified!");
Preconditions.checkState(templateFile != null && templateFile.exists(), "Template file does not exist!");
}
@Override
public Collection<File> getInputFiles() {
return Collections.unmodifiableCollection(inputFiles);
}
@Override
public Multimap<String, File> getStaticFiles() {
return Multimaps.unmodifiableMultimap(staticFiles);
}
@Override
public File getTemplateFile() {
return templateFile;
}
@Override
public File getOutputFile() {
return outputFile;
}
@Override
public Charset getInputEncoding() {
return inputEncoding;
}
@Override
public String getOption(final String name) {
return options.get(name);
}
@Override
public ConfigurationBuilder author(final String name) {
author = name;
return this;
}
@Override
public String getAuthor() {
return author;
}
@Override
public ConfigurationBuilder company(final String name) {
company = name;
return this;
}
@Override
public String getCompany() {
return company;
}
@Override
public ConfigurationBuilder title(final String title) {
this.title = title;
return this;
}
@Override
public String getTitle() {
return title;
}
@Override
public ConfigurationBuilder description(final String description) {
this.description = description;
return this;
}
@Override
public String getDescription() {
return description;
}
@Override
public ConfigurationBuilder date(final Date date) {
this.date = new Date(date.getTime());
return this;
}
@Override
public ConfigurationBuilder currentDate() {
date = new Date();
return this;
}
@Override
public Date getDate() {
if (date == null) {
currentDate();
}
return new Date(date.getTime());
}
@Override
public ConfigurationBuilder logo(final File file) {
logo = file;
return this;
}
@Override
public File getLogo() {
return logo;
}
@Override
public boolean listsIncremented() {
return listIncremented;
}
@Override
public ConfigurationBuilder incrementalLists() {
listIncremented = true;
return this;
}
@Override
public ConfigurationBuilder incrementalLists(final boolean state) {
listIncremented = state;
return this;
}
@Override
public ConfigurationBuilder includeNotes() {
notesIncluded = true;
return this;
}
@Override
public ConfigurationBuilder includeNotes(final boolean state) {
notesIncluded = state;
return this;
}
@Override
public ConfigurationBuilder excludeNotes() {
notesIncluded = false;
return this;
}
@Override
public boolean notesIncluded() {
return notesIncluded;
}
@Override
public ConfigurationBuilder theme(final String name) {
theme = name;
return this;
}
@Override
public String getTheme() {
return theme;
}
@Override
public ConfigurationBuilder font(final String name, final URL link) {
font = name;
fontLink = link;
return this;
}
@Override
public ConfigurationBuilder font(final String name) {
font = name;
fontLink = null;
return this;
}
@Override
public String getFontName() {
return font;
}
@Override
public URL getFontLink() {
return fontLink;
}
@Override
public ConfigurationBuilder backgroundColor(final String color) {
colors.put("background", color);
return this;
}
@Override
public ConfigurationBuilder fontColor(final String color) {
colors.put("font", color);
return this;
}
@Override
public ConfigurationBuilder color(final String ref, final String color) {
colors.put(ref, color);
return this;
}
@Override
public String getBackgroundColor() {
return colors.get("background");
}
@Override
public String getFontColor() {
return colors.get("font");
}
@Override
public String getColor(final String ref) {
return colors.get(ref);
}
@Override
public ConfigurationBuilder transitionRule(final String selector, final String rule) {
transitionRules.put(selector, rule);
return this;
}
@Override
public ConfigurationBuilder stylingRule(final String selector, final String rule) {
stylingRules.put(selector, rule);
return this;
}
@Override
public Multimap<String, String> getTransitionRules() {
return Multimaps.unmodifiableMultimap(transitionRules);
}
@Override
public Multimap<String, String> getStylingRules() {
return Multimaps.unmodifiableMultimap(stylingRules);
}
@Override
public boolean isSplitOutput() {
return splitOutput;
}
@Override
public ConfigurationBuilder splitOutput() {
splitOutput = true;
return this;
}
@Override
public ConfigurationBuilder splitOutput(final boolean state) {
splitOutput = state;
return this;
}
@Override
public ConfigurationBuilder stripHtml() {
stripHtml = true;
return this;
}
@Override
public ConfigurationBuilder stripHtml(boolean state) {
stripHtml = state;
return this;
}
@Override
public boolean htmlStripped() {
return stripHtml;
}
@Override
public ConfigurationBuilder inputFile(final File inputFile, final Transition transition) {
// TODO Auto-generated method stub
return null;
}
@Override
public ConfigurationBuilder inputFile(final File inputFile, final Styling styling) {
// TODO Auto-generated method stub
return null;
}
@Override
public ConfigurationBuilder inputFile(final File inputFile, final Transition transition, final Styling styling) {
// TODO Auto-generated method stub
return null;
}
@Override
public ConfigurationBuilder snippet(final Location location, final String snippet) {
// TODO Auto-generated method stub
return null;
}
@Override
public ConfigurationBuilder defaultTransition(final Transition transition) {
// TODO Auto-generated method stub
return null;
}
@Override
public ConfigurationBuilder defaultStyling(final Styling styling) {
// TODO Auto-generated method stub
return null;
}
@Override
public ConfigurationBuilder templateFile(final String targetName, final File templateFile) {
// TODO Auto-generated method stub
return null;
}
@Override
public ConfigurationBuilder templateFiles(final Collection<File> templateFile) {
// TODO Auto-generated method stub
return null;
}
@Override
public ConfigurationBuilder verbose() {
// TODO Auto-generated method stub
return null;
}
@Override
public ConfigurationBuilder verbose(final boolean state) {
// TODO Auto-generated method stub
return null;
}
@Override
public Transition getTransition(final File inputFile) {
// TODO Auto-generated method stub
return null;
}
@Override
public Styling getStyling(final File inputFile) {
// TODO Auto-generated method stub
return null;
}
@Override
public Map<String, String> getOptions() {
// TODO Auto-generated method stub
return null;
}
private static FileNameComparator fileNames() {
return new FileNameComparator();
}
private final static class FileNameComparator implements Comparator<File> {
@Override
public int compare(final File o1, final File o2) {
return o1.getName().compareTo(o2.getName());
}
}
}
|
package com.qcwp.carmanager.enumeration;
/**
* Created by qyh on 2017/6/6.
*/
public enum LoadDataTypeEnum {
dataTypedrive (0),
dataTypeTijian (1),
dataTypeTest (2),
dataTypeClearErr (3),
dataTypeReConnection (100),
dataTypeDisConnected (-1);
private final int value;
LoadDataTypeEnum(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
|
// **********************************************************************
// This file was generated by a TAF parser!
// TAF version 3.2.1.6 by WSRD Tencent.
// Generated from `/data/jcetool/taf//upload/kesenhu/AppPituWnsInterface.jce'
// **********************************************************************
package PituClientInterface;
import com.qq.component.json.JSON;
import com.qq.component.json.JSONException;
public final class stMusicMaterial extends com.qq.taf.jce.JceStruct
{
public String id = "";
public String name = "";
public String singer = "";
public String tags = "";
public String packageUrl = "";
public String songUrl = "";
public int timestamp = 0;
public int songId = 0;
public int richFlag = 0;
public int mask = 0;
public String thumbUrl = "";
public stMusicMaterial()
{
}
public stMusicMaterial(String id, String name, String singer, String tags, String packageUrl, String songUrl, int timestamp, int songId, int richFlag, int mask, String thumbUrl)
{
this.id = id;
this.name = name;
this.singer = singer;
this.tags = tags;
this.packageUrl = packageUrl;
this.songUrl = songUrl;
this.timestamp = timestamp;
this.songId = songId;
this.richFlag = richFlag;
this.mask = mask;
this.thumbUrl = thumbUrl;
}
public void writeTo(com.qq.taf.jce.JceOutputStream _os)
{
_os.write(id, 0);
_os.write(name, 1);
_os.write(singer, 2);
_os.write(tags, 3);
_os.write(packageUrl, 4);
_os.write(songUrl, 5);
_os.write(timestamp, 6);
_os.write(songId, 7);
_os.write(richFlag, 8);
_os.write(mask, 9);
_os.write(thumbUrl, 10);
}
public void readFrom(com.qq.taf.jce.JceInputStream _is)
{
this.id = _is.readString(0, true);
this.name = _is.readString(1, true);
this.singer = _is.readString(2, true);
this.tags = _is.readString(3, true);
this.packageUrl = _is.readString(4, true);
this.songUrl = _is.readString(5, true);
this.timestamp = (int) _is.read(timestamp, 6, true);
this.songId = (int) _is.read(songId, 7, true);
this.richFlag = (int) _is.read(richFlag, 8, true);
this.mask = (int) _is.read(mask, 9, true);
this.thumbUrl = _is.readString(10, true);
}
public String writeToJsonString() throws JSONException
{
return JSON.toJSONString(this);
}
public void readFromJsonString(String text) throws JSONException
{
stMusicMaterial temp = JSON.parseObject(text, stMusicMaterial.class);
this.id = temp.id;
this.name = temp.name;
this.singer = temp.singer;
this.tags = temp.tags;
this.packageUrl = temp.packageUrl;
this.songUrl = temp.songUrl;
this.timestamp = temp.timestamp;
this.songId = temp.songId;
this.richFlag = temp.richFlag;
this.mask = temp.mask;
this.thumbUrl = temp.thumbUrl;
}
}
|
package com.hqb.patshop.mbg.model;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
* pms_product_category
* @author
*/
@Data
public class PmsProductCategory implements Serializable {
/**
* 分类id
*/
private Long id;
/**
* 创建日期
*/
private Date gmtCreate;
/**
* 修改日期
*/
private Date gmtModified;
/**
* 分类名称
*/
private String categoryName;
/**
* 商品分级
*/
private Integer level;
/**
* 上机分类的编号:0表示一级分类
*/
private Long parentId;
/**
* 商品单位
*/
private String productUnit;
/**
* 是否显示在导航栏:0->不显示;1->显示
*/
private Integer navStatus;
/**
* 展示状态
*/
private Integer showStatus;
/**
* 图标
*/
private String icon;
/**
* 关键字
*/
private String keywords;
private static final long serialVersionUID = 1L;
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (that == null) {
return false;
}
if (getClass() != that.getClass()) {
return false;
}
PmsProductCategory other = (PmsProductCategory) that;
return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId()))
&& (this.getGmtCreate() == null ? other.getGmtCreate() == null : this.getGmtCreate().equals(other.getGmtCreate()))
&& (this.getGmtModified() == null ? other.getGmtModified() == null : this.getGmtModified().equals(other.getGmtModified()))
&& (this.getCategoryName() == null ? other.getCategoryName() == null : this.getCategoryName().equals(other.getCategoryName()))
&& (this.getLevel() == null ? other.getLevel() == null : this.getLevel().equals(other.getLevel()))
&& (this.getParentId() == null ? other.getParentId() == null : this.getParentId().equals(other.getParentId()))
&& (this.getProductUnit() == null ? other.getProductUnit() == null : this.getProductUnit().equals(other.getProductUnit()))
&& (this.getNavStatus() == null ? other.getNavStatus() == null : this.getNavStatus().equals(other.getNavStatus()))
&& (this.getShowStatus() == null ? other.getShowStatus() == null : this.getShowStatus().equals(other.getShowStatus()))
&& (this.getIcon() == null ? other.getIcon() == null : this.getIcon().equals(other.getIcon()))
&& (this.getKeywords() == null ? other.getKeywords() == null : this.getKeywords().equals(other.getKeywords()));
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
result = prime * result + ((getGmtCreate() == null) ? 0 : getGmtCreate().hashCode());
result = prime * result + ((getGmtModified() == null) ? 0 : getGmtModified().hashCode());
result = prime * result + ((getCategoryName() == null) ? 0 : getCategoryName().hashCode());
result = prime * result + ((getLevel() == null) ? 0 : getLevel().hashCode());
result = prime * result + ((getParentId() == null) ? 0 : getParentId().hashCode());
result = prime * result + ((getProductUnit() == null) ? 0 : getProductUnit().hashCode());
result = prime * result + ((getNavStatus() == null) ? 0 : getNavStatus().hashCode());
result = prime * result + ((getShowStatus() == null) ? 0 : getShowStatus().hashCode());
result = prime * result + ((getIcon() == null) ? 0 : getIcon().hashCode());
result = prime * result + ((getKeywords() == null) ? 0 : getKeywords().hashCode());
return result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", gmtCreate=").append(gmtCreate);
sb.append(", gmtModified=").append(gmtModified);
sb.append(", categoryName=").append(categoryName);
sb.append(", level=").append(level);
sb.append(", parentId=").append(parentId);
sb.append(", productUnit=").append(productUnit);
sb.append(", navStatus=").append(navStatus);
sb.append(", showStatus=").append(showStatus);
sb.append(", icon=").append(icon);
sb.append(", keywords=").append(keywords);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
package cn.ehanmy.hospital.di.component;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.di.scope.ActivityScope;
import cn.ehanmy.hospital.di.module.HGoodsConfirmModule;
import cn.ehanmy.hospital.mvp.ui.activity.HGoodsConfirmActivity;
import dagger.Component;
@ActivityScope
@Component(modules = HGoodsConfirmModule.class, dependencies = AppComponent.class)
public interface HGoodsConfirmComponent {
void inject(HGoodsConfirmActivity activity);
}
|
package br.com.allerp.allbanks.view.cadastros.panels;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.spring.injection.annot.SpringBean;
import br.com.allerp.allbanks.service.GenericService;
import br.com.allerp.allbanks.view.Util;
public class ExcluirPanel<T> extends Util<T> {
private static final long serialVersionUID = -5809832993758487928L;
@SpringBean(name = "service")
private GenericService<T> service;
public ExcluirPanel(String id, final T object, String titulo, String message) {
super(id);
add(new Label("confirma", "Exclusão de " + titulo + "!"));
add(new Label("exMsg", message));
add(new AjaxLink<T>("btn-confirma") {
private static final long serialVersionUID = -6737235094619280702L;
@Override
public void onClick(AjaxRequestTarget target) {
service.delete(object);
atualizaAoModificar(target, object);
}
});
add(new AjaxLink<T>("btn-cancelar") {
private static final long serialVersionUID = -2299143403487701927L;
@Override
public void onClick(AjaxRequestTarget target) {
atualizaAoModificar(target, object);
}
});
}
public void setService(GenericService<T> service) {
this.service = service;
}
}
|
package org.team3128.common.util.enums;
/**
* Direction enum used for turns.
* @author Jamie
*
*/
public enum Direction
{
RIGHT,
LEFT;
}
|
package components;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import library.Dc;
public class Label extends StackPane {
private Dc pos;
public Label(String text, Color color, int fontSize, int x, int y) {
pos = new Dc(x, y);
Text textComponent = new Text(pos.x(), pos.y(), text);
textComponent.setFill(color);
textComponent.setFont(Font.font("ARIAL BLACK", fontSize));
getChildren().addAll(textComponent);
}
}
|
/*
* LumaQQ - Java QQ Client
*
* Copyright (C) 2004 luma <stubma@163.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.tsinghua.lumaqq.widgets;
import static edu.tsinghua.lumaqq.resource.Messages.*;
import org.eclipse.swt.graphics.Image;
import edu.tsinghua.lumaqq.resource.Resources;
/**
* 头像图片提供器,用来为图片选择窗口提供头像选择的能力
*
* @author luma
*/
public class HeadImageAdvisor implements IImageSelectorAdvisor {
private static final int SIZE = 40;
private static final int MARGIN = 3;
private static final int GRID = MARGIN * 2 + SIZE;
private static final int ROW = 5;
private static final int COL = 8;
private static final int[][] headMap = new int[][] {
// 注意序号从0开始
// 男士头像
{
4, 6, 9, 13, 14, 15, 16, 27,
35, 36, 42, 43, 45, 49, 51, 52,
53, 59, 60, 62, 67, 71, 73, 76,
78, 79, 81, 84, 93, 94
},
// 女士头像
{
5, 8, 11, 19, 28, 29, 33, 37,
39, 44, 46, 48, 50, 54, 56, 57,
61, 66, 69, 74, 77, 80, 82, 83,
85, 86, 87, 88, 89
},
// 宠物头像
{
0, 1, 2, 3, 7, 10, 12, 16,
17, 18, 20, 21, 22, 23, 24, 25,
30, 31, 32, 34, 38, 40, 41, 47,
55, 58, 63, 64, 65, 68, 70, 72,
75, 90, 91, 92
},
// QQ堂头像
{
95, 96, 97, 98, 99
}
};
/* (non-Javadoc)
* @see edu.tsinghua.lumaqq.ui.IImageProvider#getGroupCount()
*/
public int getGroupCount() {
return 4;
}
/* (non-Javadoc)
* @see edu.tsinghua.lumaqq.ui.IImageProvider#getImageCount(int)
*/
public int getImageCount(int group) {
return headMap[group].length;
}
/* (non-Javadoc)
* @see edu.tsinghua.lumaqq.ui.IImageProvider#getGroupName(int)
*/
public String getGroupName(int group) {
switch(group) {
case 0:
return image_group_man;
case 1:
return image_group_woman;
case 2:
return image_group_pet;
case 3:
return image_group_qqtang;
default:
return "";
}
}
/* (non-Javadoc)
* @see edu.tsinghua.lumaqq.ui.IImageProvider#getImage(int, int)
*/
public Image getImage(int group, int sequence) {
if(sequence < 0 || sequence >= headMap[group].length)
return null;
int code = headMap[group][sequence] * 3;
return Resources.getInstance().getHead(code);
}
/* (non-Javadoc)
* @see edu.tsinghua.lumaqq.ui.IImageProvider#getImageCode(int, int)
*/
public int getImageCode(int group, int sequence) {
if(sequence < 0 || sequence >= headMap[group].length)
return -1;
return headMap[group][sequence] * 3;
}
/* (non-Javadoc)
* @see edu.tsinghua.lumaqq.ui.IImageProvider#canPagination(int)
*/
public boolean canPagination(int group) {
return false;
}
/* (non-Javadoc)
* @see edu.tsinghua.lumaqq.ui.IImageProvider#canNext(int, int)
*/
public boolean canNext(int group, int currentPage) {
return false;
}
/* (non-Javadoc)
* @see edu.tsinghua.lumaqq.ui.IImageProvider#canPrevious(int, int)
*/
public boolean canPrevious(int group, int currentPage) {
return false;
}
/* (non-Javadoc)
* @see edu.tsinghua.lumaqq.widgets.IImageSelectorAdvisor#isAuxiliaryLinkVisible()
*/
public boolean isAuxiliaryLinkVisible() {
return false;
}
/* (non-Javadoc)
* @see edu.tsinghua.lumaqq.ui.IImageProvider#doLink(edu.tsinghua.lumaqq.ui.FaceSelectShell)
*/
public void doLink(ImageSelector fss) {
}
/* (non-Javadoc)
* @see edu.tsinghua.lumaqq.ui.IImageProvider#getLinkLabel()
*/
public String getLinkLabel() {
return "";
}
/* (non-Javadoc)
* @see edu.tsinghua.lumaqq.ui.IImageProvider#getGridSize()
*/
public int getGridSize() {
return GRID;
}
/* (non-Javadoc)
* @see edu.tsinghua.lumaqq.ui.IImageProvider#getImageSize()
*/
public int getImageSize() {
return SIZE;
}
/* (non-Javadoc)
* @see edu.tsinghua.lumaqq.ui.IImageProvider#getRow()
*/
public int getRow() {
return ROW;
}
/* (non-Javadoc)
* @see edu.tsinghua.lumaqq.ui.IImageProvider#getCol()
*/
public int getCol() {
return COL;
}
/* (non-Javadoc)
* @see edu.tsinghua.lumaqq.ui.IImageProvider#getMargin()
*/
public int getMargin() {
return MARGIN;
}
}
|
package com.elepy.dao;
import com.elepy.Resource;
import com.elepy.exceptions.ElepyException;
import com.elepy.http.HttpContext;
import com.elepy.http.Request;
import com.elepy.http.Response;
import com.elepy.models.FieldType;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class FiltersTest {
@Test
void testProperTestSetup() {
Map<String, String> map = new HashMap<>();
map.put("hi", "ryan");
Request request = mockedContextWithQueryMap(map).request();
assertEquals("ryan", request.queryParams("hi"));
}
@Test
void testCanFindProperFilter() {
assertThat(FilterType.getForFieldType(FieldType.NUMBER))
.containsExactly(
FilterType.GREATER_THAN,
FilterType.GREATER_THAN_OR_EQUALS,
FilterType.LESSER_THAN,
FilterType.LESSER_THAN_OR_EQUALS,
FilterType.EQUALS,
FilterType.NOT_EQUALS);
assertThat(FilterType.getForFieldType(FieldType.TEXT))
.containsExactly(
FilterType.CONTAINS,
FilterType.EQUALS,
FilterType.NOT_EQUALS);
}
@Test
void testCreateProperFilter() {
Class<Resource> resourceClass = Resource.class;
Map<String, String> map = new HashMap<>();
map.put("id_equals", "1234");
Request request = mockedContextWithQueryMap(map).request();
List<Filter> filterQueries = request.filtersForModel(resourceClass);
assertEquals(1, filterQueries.size());
assertEquals("id", filterQueries.get(0).getFilterableField().getName());
assertEquals("1234", filterQueries.get(0).getFilterValue());
assertEquals(FilterType.EQUALS, filterQueries.get(0).getFilterType());
}
@Test
void testMongoQuery() {
Class<Resource> resourceClass = Resource.class;
Map<String, String> map = new HashMap<>();
map.put("id_equals", "1234");
Request request = mockedContextWithQueryMap(map).request();
List<Filter> filterQueries = request.filtersForModel(resourceClass);
assertEquals(1, filterQueries.size());
}
@Test
void testFilterDoesntTryToCreateWithWrongParam() {
Class<Resource> resourceClass = Resource.class;
Map<String, String> map = new HashMap<>();
map.put("id_quals", "1234");
Request request = mockedContextWithQueryMap(map).request();
List<Filter> filterQueries = request.filtersForModel(resourceClass);
assertEquals(0, filterQueries.size());
}
@Test
void testThrowExceptionWithInvalidPropName() {
Class<Resource> resourceClass = Resource.class;
Map<String, String> map = new HashMap<>();
map.put("id33_Ee_equals", "1234");
Request request = mockedContextWithQueryMap(map).request();
ElepyException elepyException = assertThrows(ElepyException.class, () -> request.filtersForModel(resourceClass));
assertTrue(elepyException.getMessage().contains("id33_Ee"));
}
private HttpContext mockedContextWithQueryMap(Map<String, String> map) {
HttpContext mockedContext = mockedContext();
when(mockedContext.request().queryParams()).thenReturn(map.keySet());
when(mockedContext.request().queryParams(anyString())).thenAnswer(invocationOnMock -> map.get(invocationOnMock.getArgument(0)));
when(mockedContext.request().filtersForModel(any())).thenCallRealMethod();
return mockedContext;
}
private HttpContext mockedContext() {
HttpContext context = mock(HttpContext.class);
Request request = mock(Request.class);
Response response = mock(Response.class);
when(context.response()).thenReturn(response);
when(context.request()).thenReturn(request);
return context;
}
}
|
package com.example.userportal.configuration;
import com.example.userportal.security.CustomUserDetailsService;
import com.example.userportal.security.jwt.JwtAuthenticationEntryPoint;
import com.example.userportal.security.jwt.JwtAuthenticationFilter;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.BeanIds;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.zalando.problem.spring.web.advice.security.SecurityProblemSupport;
@Configuration
@EnableJpaRepositories("com.example.userportal.repository")
@EnableJpaAuditing(auditorAwareRef = "springSecurityAuditorAware")
@EnableTransactionManagement
@EnableWebSecurity
@Import(SecurityProblemSupport.class)
@RequiredArgsConstructor
@EnableGlobalMethodSecurity(
securedEnabled = true,
jsr250Enabled = true,
prePostEnabled = true
)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
final private SecurityProblemSupport problemSupport;
final private CustomUserDetailsService customUserDetailsService;
final private JwtAuthenticationEntryPoint unauthorizedHandler;
@Bean
public JwtAuthenticationFilter jwtAuthenticationFilter() {
return new JwtAuthenticationFilter();
}
@Override
public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder
.userDetailsService(customUserDetailsService)
.passwordEncoder(passwordEncoder());
}
@Bean(BeanIds.AUTHENTICATION_MANAGER)
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf()
.disable()
.exceptionHandling()
.authenticationEntryPoint(unauthorizedHandler)
.accessDeniedHandler(problemSupport)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/",
"/favicon.ico",
"/**/*.png",
"/**/*.gif",
"/**/*.svg",
"/**/*.jpg",
"/**/*.html",
"/**/*.css",
"/**/*.js")
.permitAll()
.antMatchers("/auth/**",
"/menu/**",
"/products/**",
"/payment/payu/notify",
"/configuration/ui",
"/webjars/**",
"/swagger-ui.html",
"/swagger-resources",
"/swagger-resources/**",
"/configuration/security",
"/v2/api-docs",
"/shops/**")
.permitAll()
.anyRequest()
.authenticated();
http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedHeader("*");
config.addAllowedOrigin("*");
config.addAllowedMethod("OPTIONS");
config.addAllowedMethod("GET");
config.addAllowedMethod("POST");
config.addAllowedMethod("PUT");
config.addAllowedMethod("DELETE");
config.setMaxAge(3600L);
config.setAllowCredentials(true);
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2000-2016 hybris AG
* All rights reserved.
*
* This software is the confidential and proprietary information of hybris
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with hybris.
*
*
*/
package com.cnk.travelogix.common.core.payment.strategies;
/**
* Strategy for retrieving the correct URL for payment submission.
*/
public interface CnkPaymentFormActionUrlStrategy
{
/**
* Gets the URI of the Hosted Order Page. This method read the HOP URL using the configuration service, as such the
* URL has to be defined in a property file on the class path.
*
* @return a URL to the HOP server.
*/
String getHopRequestUrl(String cardType);
/**
* Gets the URI of the Silent Order Post. By default this method will utilize a config property to define the SOP
* URL. An extension may implement this method to call an external service (e.g., CIS) to get the correct SOP URL.
*
* @param clientRef
* unique identifier representing the client in a call to external services.
*
* @return a URL to the SOP server.
*/
String getSopRequestUrl(String clientRef);
}
|
package org.sagebionetworks.object.snapshot.worker.utils;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.sagebionetworks.asynchronous.workers.sqs.MessageUtils;
import org.sagebionetworks.audit.dao.ObjectRecordDAO;
import org.sagebionetworks.audit.utils.ObjectRecordBuilderUtils;
import org.sagebionetworks.common.util.progress.ProgressCallback;
import org.sagebionetworks.repo.model.ObjectType;
import org.sagebionetworks.repo.model.audit.FileHandleSnapshot;
import org.sagebionetworks.repo.model.audit.ObjectRecord;
import org.sagebionetworks.repo.model.dbo.file.FileHandleDao;
import org.sagebionetworks.repo.model.file.ExternalFileHandle;
import org.sagebionetworks.repo.model.file.ExternalObjectStoreFileHandle;
import org.sagebionetworks.repo.model.file.FileHandle;
import org.sagebionetworks.repo.model.file.GoogleCloudFileHandle;
import org.sagebionetworks.repo.model.file.ProxyFileHandle;
import org.sagebionetworks.repo.model.file.S3FileHandle;
import org.sagebionetworks.repo.model.message.ChangeMessage;
import org.sagebionetworks.repo.model.message.ChangeType;
import com.amazonaws.services.sqs.model.Message;
@ExtendWith(MockitoExtension.class)
public class FileHandleSnapshotRecordWriterTest {
@Mock
private FileHandleDao mockFileHandleDao;
@Mock
private ObjectRecordDAO mockObjectRecordDao;
@Mock
private ProgressCallback mockCallback;
@InjectMocks
private FileHandleSnapshotRecordWriter writer;
private String id = "123";
@Test
public void deleteFileMessageTest() throws IOException {
Message message = MessageUtils.buildMessage(ChangeType.DELETE, id, ObjectType.FILE, "etag", System.currentTimeMillis());
ChangeMessage changeMessage = MessageUtils.extractMessageBody(message);
writer.buildAndWriteRecords(mockCallback, Arrays.asList(changeMessage));
verify(mockObjectRecordDao, never()).saveBatch(anyList(), anyString());
}
@Test
public void invalidChangeMessageTest() throws IOException {
Message message = MessageUtils.buildMessage(ChangeType.UPDATE, id, ObjectType.PRINCIPAL, "etag", System.currentTimeMillis());
ChangeMessage changeMessage = MessageUtils.extractMessageBody(message);
assertThrows(IllegalArgumentException.class, () -> writer.buildAndWriteRecords(mockCallback, Arrays.asList(changeMessage)));
}
@Test
public void validChangeMessageTest() throws IOException {
FileHandle fileHandle = new S3FileHandle();
fileHandle.setEtag("etag");
when(mockFileHandleDao.get(id)).thenReturn(fileHandle);
Message message = MessageUtils.buildMessage(ChangeType.UPDATE, id, ObjectType.FILE, "etag", System.currentTimeMillis());
ChangeMessage changeMessage = MessageUtils.extractMessageBody(message);
FileHandleSnapshot record = FileHandleSnapshotRecordWriter.buildFileHandleSnapshot(fileHandle);
ObjectRecord expected = ObjectRecordBuilderUtils.buildObjectRecord(record, changeMessage.getTimestamp().getTime());
writer.buildAndWriteRecords(mockCallback, Arrays.asList(changeMessage, changeMessage));
verify(mockFileHandleDao, times(2)).get(id);
verify(mockObjectRecordDao).saveBatch(eq(Arrays.asList(expected, expected)), eq(expected.getJsonClassName()));
}
@Test
public void testBuildFileHandleSnapshotWithS3FileHandle() {
S3FileHandle s3FH = new S3FileHandle();
s3FH.setBucketName("bucket");
s3FH.setConcreteType(S3FileHandle.class.getName());
s3FH.setContentMd5("md5");
s3FH.setContentSize(1L);
s3FH.setCreatedBy("998");
s3FH.setCreatedOn(new Date());
s3FH.setFileName("fileName");
s3FH.setId("555");
s3FH.setKey("key");
s3FH.setStorageLocationId(900L);
FileHandleSnapshot snapshot = FileHandleSnapshotRecordWriter.buildFileHandleSnapshot(s3FH);
assertEquals(s3FH.getBucketName(), snapshot.getBucket());
assertEquals(s3FH.getConcreteType(), snapshot.getConcreteType());
assertEquals(s3FH.getContentMd5(), snapshot.getContentMd5());
assertEquals(s3FH.getContentSize(), snapshot.getContentSize());
assertEquals(s3FH.getCreatedBy(), snapshot.getCreatedBy());
assertEquals(s3FH.getCreatedOn(), snapshot.getCreatedOn());
assertEquals(s3FH.getFileName(), snapshot.getFileName());
assertEquals(s3FH.getId(), snapshot.getId());
assertEquals(s3FH.getKey(), snapshot.getKey());
assertEquals(s3FH.getStorageLocationId(), snapshot.getStorageLocationId());
}
@Test
public void testBuildFileHandleSnapshotWithGoogleCloudFileHandle() {
GoogleCloudFileHandle googleCloudFileHandle = new GoogleCloudFileHandle();
googleCloudFileHandle.setBucketName("bucket");
googleCloudFileHandle.setConcreteType(S3FileHandle.class.getName());
googleCloudFileHandle.setContentMd5("md5");
googleCloudFileHandle.setContentSize(1L);
googleCloudFileHandle.setCreatedBy("998");
googleCloudFileHandle.setCreatedOn(new Date());
googleCloudFileHandle.setFileName("fileName");
googleCloudFileHandle.setId("555");
googleCloudFileHandle.setKey("key");
googleCloudFileHandle.setStorageLocationId(900L);
FileHandleSnapshot snapshot = FileHandleSnapshotRecordWriter.buildFileHandleSnapshot(googleCloudFileHandle);
assertEquals(googleCloudFileHandle.getBucketName(), snapshot.getBucket());
assertEquals(googleCloudFileHandle.getConcreteType(), snapshot.getConcreteType());
assertEquals(googleCloudFileHandle.getContentMd5(), snapshot.getContentMd5());
assertEquals(googleCloudFileHandle.getContentSize(), snapshot.getContentSize());
assertEquals(googleCloudFileHandle.getCreatedBy(), snapshot.getCreatedBy());
assertEquals(googleCloudFileHandle.getCreatedOn(), snapshot.getCreatedOn());
assertEquals(googleCloudFileHandle.getFileName(), snapshot.getFileName());
assertEquals(googleCloudFileHandle.getId(), snapshot.getId());
assertEquals(googleCloudFileHandle.getKey(), snapshot.getKey());
assertEquals(googleCloudFileHandle.getStorageLocationId(), snapshot.getStorageLocationId());
}
@Test
public void testBuildFileHandleSnapshotWithExternalFileHandle() {
ExternalFileHandle externalFH = new ExternalFileHandle();
externalFH.setConcreteType(S3FileHandle.class.getName());
externalFH.setContentMd5("md5");
externalFH.setContentSize(1L);
externalFH.setCreatedBy("998");
externalFH.setCreatedOn(new Date());
externalFH.setFileName("fileName");
externalFH.setId("555");
externalFH.setExternalURL("externalURL");
externalFH.setStorageLocationId(900L);
FileHandleSnapshot snapshot = FileHandleSnapshotRecordWriter.buildFileHandleSnapshot(externalFH);
assertNull(snapshot.getBucket());
assertEquals(externalFH.getConcreteType(), snapshot.getConcreteType());
assertEquals(externalFH.getContentMd5(), snapshot.getContentMd5());
assertEquals(externalFH.getContentSize(), snapshot.getContentSize());
assertEquals(externalFH.getCreatedBy(), snapshot.getCreatedBy());
assertEquals(externalFH.getCreatedOn(), snapshot.getCreatedOn());
assertEquals(externalFH.getFileName(), snapshot.getFileName());
assertEquals(externalFH.getId(), snapshot.getId());
assertEquals(externalFH.getExternalURL(), snapshot.getKey());
assertEquals(externalFH.getStorageLocationId(), snapshot.getStorageLocationId());
}
@Test
public void testBuildFileHandleSnapshotWithProxyFileHandle() {
ProxyFileHandle proxyFH = new ProxyFileHandle();
proxyFH.setConcreteType(ProxyFileHandle.class.getName());
proxyFH.setContentMd5("md5");
proxyFH.setContentSize(1L);
proxyFH.setCreatedBy("998");
proxyFH.setCreatedOn(new Date());
proxyFH.setFileName("fileName");
proxyFH.setId("555");
proxyFH.setFilePath("filePath");
proxyFH.setStorageLocationId(900L);
FileHandleSnapshot snapshot = FileHandleSnapshotRecordWriter.buildFileHandleSnapshot(proxyFH);
assertNull(snapshot.getBucket());
assertEquals(proxyFH.getConcreteType(), snapshot.getConcreteType());
assertEquals(proxyFH.getContentMd5(), snapshot.getContentMd5());
assertEquals(proxyFH.getContentSize(), snapshot.getContentSize());
assertEquals(proxyFH.getCreatedBy(), snapshot.getCreatedBy());
assertEquals(proxyFH.getCreatedOn(), snapshot.getCreatedOn());
assertEquals(proxyFH.getFileName(), snapshot.getFileName());
assertEquals(proxyFH.getId(), snapshot.getId());
assertEquals(proxyFH.getFilePath(), snapshot.getKey());
assertEquals(proxyFH.getStorageLocationId(), snapshot.getStorageLocationId());
}
@Test
public void testBuildFileHandleSnapshotWithExternalObjectStoreFileHandle() {
ExternalObjectStoreFileHandle externalObjectStoreFileHandle = new ExternalObjectStoreFileHandle();
externalObjectStoreFileHandle.setConcreteType(ExternalObjectStoreFileHandle.class.getName());
externalObjectStoreFileHandle.setContentMd5("md5");
externalObjectStoreFileHandle.setContentSize(1L);
externalObjectStoreFileHandle.setCreatedBy("998");
externalObjectStoreFileHandle.setCreatedOn(new Date());
externalObjectStoreFileHandle.setFileName("fileName");
externalObjectStoreFileHandle.setId("555");
externalObjectStoreFileHandle.setFileKey("key");
externalObjectStoreFileHandle.setStorageLocationId(900L);
FileHandleSnapshot snapshot = FileHandleSnapshotRecordWriter.buildFileHandleSnapshot(externalObjectStoreFileHandle);
assertNull(snapshot.getBucket());
assertEquals(externalObjectStoreFileHandle.getConcreteType(), snapshot.getConcreteType());
assertEquals(externalObjectStoreFileHandle.getContentMd5(), snapshot.getContentMd5());
assertEquals(externalObjectStoreFileHandle.getContentSize(), snapshot.getContentSize());
assertEquals(externalObjectStoreFileHandle.getCreatedBy(), snapshot.getCreatedBy());
assertEquals(externalObjectStoreFileHandle.getCreatedOn(), snapshot.getCreatedOn());
assertEquals(externalObjectStoreFileHandle.getFileName(), snapshot.getFileName());
assertEquals(externalObjectStoreFileHandle.getId(), snapshot.getId());
assertEquals(externalObjectStoreFileHandle.getFileKey(), snapshot.getKey());
assertEquals(externalObjectStoreFileHandle.getStorageLocationId(), snapshot.getStorageLocationId());
}
}
|
package com.sage.rpg.component;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import com.sage.rpg.Game;
public class MenuButton extends Component {
private Interface parent;
private int x, y;
private int width, height;
private String text;
private int confirmId;
public MenuButton(final Game game, int id, Interface parent, String text, int x, int y, int width, int height) {
super(game, id, x + parent.getX(), y + parent.getY(), width, height);
this.parent = parent;
this.text = text;
this.x = x + parent.getX();
this.y = y + parent.getY();
this.width = width;
this.height = height;
}
public void render(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
if (getHovered())
g.setColor(Color.LIGHT_GRAY);
else if (isDisabled()) {
g.setColor(Color.RED);
text = "Disabled";
} else
g.setColor(parent.getBackgroundColor());
g.fillRect(x, y, width, height);
g2d.setStroke(new BasicStroke(parent.getOutlineThickness()));
g.setColor(parent.getOutlineColor());
g.drawRect(x, y, width, height);
if (text != null) {
if (parent.getFont() != null)
g.setFont(parent.getFont());
FontMetrics fm = g2d.getFontMetrics();
Rectangle2D r = fm.getStringBounds(text, g2d);
int textX = x + (width - (int) r.getWidth()) / 2;
int textY = y + (height - (int) r.getHeight()) / 2 + fm.getAscent();
g.drawString(text, textX, textY);
}
}
public int getConfirmId() {
return confirmId;
}
public void setConfirmId(int confirmId) {
this.confirmId = confirmId;
}
}
|
package com.tencent.mm.plugin.nearby.ui;
import android.view.View;
import com.tencent.mm.ui.base.MMSlideDelView.c;
class NearbySayHiListUI$7 implements c {
final /* synthetic */ NearbySayHiListUI lCB;
NearbySayHiListUI$7(NearbySayHiListUI nearbySayHiListUI) {
this.lCB = nearbySayHiListUI;
}
public final int cl(View view) {
return NearbySayHiListUI.d(this.lCB).getPositionForView(view);
}
}
|
import java.io.*;
import java.util.*;
class Node
{
Node next;
int data;
public void setData(int data)
{
this.data=data;
}
public int getData()
{
return data;
}
public boolean append(Node node)
{
if(node != null)
{
next= node;
return true;
}
else
return false;
}
}
public class LList
{
public Node head;
public static BufferedReader br;
public static void main(String args[]) throws IOException
{
br = new BufferedReader(new InputStreamReader(System.in));
int n=0;
while(n!=-1)
{
System.out.println("Enter number of nodes\n");
n = Integer.parseInt(br.readLine());
LList list = new LList();
list.createList(n);
list.printList();
list.removeDuplicates2();
list.printList();
}
}
public void createList(int n)
{
head = new Node();
Node trav = head;
Random rg = new Random();
int limit = n;
head.setData(rg.nextInt(limit));
for(int i=1;i<n;i++)
{
Node temp = new Node();
temp.setData(rg.nextInt(limit));
trav.append(temp);
trav=temp;
}
}
public void printList()
{
Node trav = head;
while(trav!=null)
{
System.out.print(trav.getData()+", ");
trav =trav.next;
}
System.out.println("");
}
public void removeDuplicates() //O(n^2) algo to delete duplicates in an unsorted linked list
{
Node trav1=head;
while(trav1 !=null)
{
Node trav2=trav1.next; //always begin at the sublist..all elements behind are unique
Node prev=trav1;
while(trav2 != null)
{
if(trav2.getData()== trav1.getData()) //delete duplicate element
{
prev.next=trav2.next;
trav2.next=null;
trav2=prev.next;
}
else //don't forget this..go to next element
{
prev=trav2;
trav2=trav2.next;
}
}
trav1=trav1.next;
}
}
public void removeDuplicates2() //O(n^2) algo to delete duplicates in an unsorted linked list
{
Node trav1=head;
HashMap<Integer,Boolean> hmap= new HashMap<Integer,Boolean>();//use boolean instead of references ..makes it easier
while(trav1!=null)
{
int key=trav1.getData();
hmap.put(key,false); //set this to false..because entry exists in map we know this element exists in the list
//while removing duplicates, it's set to true when element is encountered for the first time
//for remaining occurences, when the hashmap value is retrieved as true, that element is deleted
trav1=trav1.next;
}
trav1=head;
Node prev=head;
do
{
/*
use do while so that trav1 will go ahead of prev after first pass ..else this creates problems with a list with first 2 elements as
duplicates..i.e. 4,4,5,6....
*/
int key=trav1.getData();
if(hmap.get(key)==false)
{
//element has been encountered for the first time..delete all remaining occurrences on later on in the list
hmap.put(key,true);
prev=trav1;
trav1=trav1.next;
}
else
{
//element is duplicate since key-value has already been set to true in hashmap..therefore delete it
prev.next=trav1.next;
trav1.next=null;
trav1=prev.next;
}
}while(trav1!=null);
}
}
|
package com.thoughtworks.tw101.exercises.exercise9;
import java.util.List;
import java.util.ArrayList;
// If a node has a left node, check left node
// If left node has a left node check
// If child of left node has a left node check
// If child of let node has a right node check
// Else, if there are no children, return name
// If left node has a right node check
public class Node {
public String name;
private Node leftChild;
private Node rightChild;
private List<String> alphaList = new ArrayList<String>();
public Node(String name) {
this.name = name;
}
public void add(String nameOfNewNode) {
if (nameOfNewNode.compareTo(this.name) <= 0 ){
if (leftChild == null) {
leftChild = new Node(nameOfNewNode);
}
else{
leftChild.add(nameOfNewNode);
}
}
else if(nameOfNewNode.compareTo(this.name) > 0){
if (rightChild == null){
rightChild = new Node(nameOfNewNode);
}
else{
rightChild.add(nameOfNewNode);
}
}
}
public List<String> names() {
//
//if no children, add node
if(leftChild == null && rightChild == null){
alphaList.add(name);
}
//if children
else{
//if left child exists
if(leftChild != null){
//call names on left child and push to array
alphaList.addAll(leftChild.names());
}
//add root
alphaList.add(name);
if(rightChild != null){
alphaList.addAll(rightChild.names());
}
}
return alphaList;
}
}
|
package com.smxknife.java3._01_runtimecreateobject;
/**
* @author smxknife
* 2019/12/24
*/
public class _01_Cglib_Demo {
}
|
package ship.section;
import ship.ammunition.Ammunition;
import ship.hardpoint.*;
import ship.hardpoint.weapon.Weapon;
import java.util.ArrayList;
// hardpoint sections are sections which store weapons and contain ammunition for those weapons
public class HardpointSection extends Section{
// hardpoint structures (currently only weapons)
Hardpoint [] hardpoints;
// ammunition for weapons
Ammunition [] ammunitions;
// maximum ammunition storage
private int max_ammo;
// constructor
public HardpointSection(Hardpoint[] hardpoints, Ammunition[] ammunitions, int max_ammo, float mass) {
super(mass);
this.hardpoints = hardpoints;
this.ammunitions = ammunitions;
this.max_ammo = max_ammo;
}
//TODO: IMPLEMENT
public ArrayList<Weapon> getWeapons(){
ArrayList<Weapon> weapons = new ArrayList<>();
for (Hardpoint h : this.hardpoints){
if (h instanceof Weapon){
weapons.add((Weapon) h);
}
}
return weapons;
}
//TODO: CONFIGURE FOR MISSILE RANGES TOO
// get all the weapon ranges by looping over weapons
public ArrayList<Float> getMaxWeaponRange(){
ArrayList<Float> ranges = new ArrayList<>();
for (Hardpoint h : hardpoints){
if (h instanceof Weapon){
ranges.add(((Weapon) h).getRange());
}
}
return ranges;
}
}
|
package demo;
import java.util.Comparator;
import java.util.TreeSet;
public class TreeSetDemo2 {
public static void main(String[] args) {
TreeSet t= new TreeSet(new MyComparator());
t.add(10);
t.add(0);
t.add(15);
t.add(5);
t.add(20);
t.add(20);
System.out.println(t);
}
}
class MyComparator implements Comparator{
@Override
public int compare(Object o1, Object o2) {
Integer I1= (Integer) o1;
Integer I2= (Integer) o2;
return I2.compareTo(I1);
}
}
|
package com.thomaster.ourcloud.auth;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;
import java.util.stream.Collectors;
public class ReqBodyToUsernamePwd {
public static final String USERNAME_KEY = "username";
public static final String PASSWORD_KEY = "password";
private String parsedUsername;
private String parsedPassword;
public ReqBodyToUsernamePwd(HttpServletRequest loginAttemptRequest)
{
String requestBody = null;
try {
requestBody = loginAttemptRequest.getReader().lines().collect(Collectors.joining());
} catch (IOException e) {
e.printStackTrace();
}
if(requestBody != null) {
try {
Map<String, String> parsedLoginRequestBody = new ObjectMapper().readValue(requestBody, Map.class);
parsedUsername = parsedLoginRequestBody.get(USERNAME_KEY);
parsedPassword = parsedLoginRequestBody.get(PASSWORD_KEY);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
}
public String getParsedUsername() {
return parsedUsername;
}
public String getParsedPassword() {
return parsedPassword;
}
}
|
package com.sda.javagdy5.quiz;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) throws IOException {
Path category = getCategory();
List<Question> questions = readQuestions(category);
Collections.shuffle(questions);
for (int i = 0; i < 10; i++) {
Question question = questions.get(i);
List<String> answers = question.getAnswers();
String rightAnswer = answers.get(0);
Collections.shuffle(answers);
}
}
private static List<Question> readQuestions(Path category) throws IOException {
try (Scanner scanner = new Scanner(category)) {
List<Question> allQuestions = new ArrayList<>();
while (scanner.hasNext()) {
String content = scanner.nextLine();
int answersCount = Integer.parseInt(scanner.nextLine());
List<String> answers = new ArrayList<>(answersCount);
for (int i = 0; i < answersCount; i++) {
answers.add(scanner.nextLine());
}
allQuestions.add(new Question(content, answers));
}
return allQuestions;
}
}
private static Path getCategory() throws IOException {
Path dir = Paths.get("src", "main", "resources", "quiz");
List<Path> categoryFiles = Files
.list(dir)
.collect(Collectors.toList());
System.out.println("Wybierz kategorię:");
int i = 1;
for (Path categoryFile : categoryFiles) {
System.out.println(i + ") " + categoryFile.getFileName()
.toString()
.replace(".txt", "")
.replaceAll("_", " "));
i = i + 1;
}
try (Scanner scanner = new Scanner(System.in)) {
return categoryFiles.get(scanner.nextInt() - 1);
}
}
}
|
/*
* Copyright (C) 2013 Square, Inc.
*
* 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.squareup.rack;
import com.google.common.collect.ForwardingMap;
import java.io.Closeable;
import java.io.IOException;
import java.util.Map;
/**
* The HTTP request environment consumed by a {@link RackApplication}.
*
* @see <a href="http://rack.rubyforge.org/doc/SPEC.html">The Rack Specification</a>
* @see com.squareup.rack.servlet.RackEnvironmentBuilder
*/
public class RackEnvironment extends ForwardingMap<String, Object> {
public static final String REQUEST_METHOD = "REQUEST_METHOD";
public static final String SCRIPT_NAME = "SCRIPT_NAME";
public static final String PATH_INFO = "PATH_INFO";
public static final String QUERY_STRING = "QUERY_STRING";
public static final String SERVER_NAME = "SERVER_NAME";
public static final String SERVER_PORT = "SERVER_PORT";
public static final String CONTENT_LENGTH = "CONTENT_LENGTH";
public static final String CONTENT_TYPE = "CONTENT_TYPE";
public static final String HTTP_HEADER_PREFIX = "HTTP_";
public static final String RACK_VERSION = "rack.version";
public static final String RACK_URL_SCHEME = "rack.url_scheme";
public static final String RACK_INPUT = "rack.input";
public static final String RACK_ERRORS = "rack.errors";
public static final String RACK_LOGGER = "rack.logger";
public static final String RACK_MULTITHREAD = "rack.multithread";
public static final String RACK_MULTIPROCESS = "rack.multiprocess";
public static final String RACK_RUN_ONCE = "rack.run_once";
public static final String RACK_HIJACK = "rack.hijack?";
public static final String MINECART_HTTP_SERVLET_REQUEST = "minecart.http_servlet_request";
private final Map<String, Object> contents;
/**
* Creates a {@link RackEnvironment} with the given contents.
*
* @see com.squareup.rack.servlet.RackEnvironmentBuilder
* @param contents
*/
public RackEnvironment(Map<String, Object> contents) {
this.contents = contents;
}
/**
* Closes the rack.input stream.
*
* @throws IOException
*/
public void closeRackInput() throws IOException {
((Closeable) contents.get(RACK_INPUT)).close();
}
@Override protected Map<String, Object> delegate() {
return contents;
}
}
|
import java.util.Vector;
import java.util.Set;
public class MemoryConsumer {
//private static float CAP = 0.8f; // 80%
private static float CAP = 0.7f; // 70%
private static int ONE_MB = 1024 * 1024;
private static long SLEEP_TIME=2000;
private static Vector cache = new Vector();
public static void main(String[] args) throws Exception {
System.out.println("Sleep");
//getThreadInfo();
Thread.sleep(SLEEP_TIME);
System.out.println("Sleep end");
System.out.println();
Runtime rt = Runtime.getRuntime();
long maxMemBytes = rt.maxMemory();
long usedMemBytes = rt.totalMemory() - rt.freeMemory();
long freeMemBytes = rt.maxMemory() - usedMemBytes;
int allocBytes = Math.round(freeMemBytes * CAP);
System.out.println("== Read Values ==");
System.out.println("Max memory: " + rt.maxMemory()/ONE_MB + "MB");
System.out.println("Total memory: " + rt.totalMemory()/ONE_MB + "MB");
System.out.println("Free memory: " + rt.freeMemory()/ONE_MB + "MB");
System.out.println("== Calculated ==");
System.out.println("Max memory: " + maxMemBytes/ONE_MB + "MB");
System.out.println("Initial free memory: " + freeMemBytes/ONE_MB + "MB");
System.out.println("Reserve (80% of free): " + allocBytes/ONE_MB + "MB");
long start = System.currentTimeMillis();
for (int i = 0; i < allocBytes / ONE_MB; i++){
cache.add(new byte[ONE_MB]);
System.out.print("."+i);
}
System.out.println();
long end = System.currentTimeMillis();
usedMemBytes = rt.totalMemory() - rt.freeMemory();
freeMemBytes = rt.maxMemory() - usedMemBytes;
System.out.println("== after allocation-loop ==");
System.out.println("Free memory: " + freeMemBytes/ONE_MB + "MB");
System.out.println("Total memory: " + rt.totalMemory()/ONE_MB + "MB");
System.out.println("alloc loop duration " + (end - start)/1000);
System.out.println("Everything is OK, final sleep");
System.out.println();
Thread.sleep(SLEEP_TIME);
//getThreadInfo();
System.out.println("Finish");
}
public static void getThreadInfo() {
Set<Thread> threads = Thread.getAllStackTraces().keySet();
for (Thread t : threads) {
String name = t.getName();
Thread.State state = t.getState();
int priority = t.getPriority();
String type = t.isDaemon() ? "Daemon" : "Normal";
System.out.printf("%-20s \t %s \t %d \t %s\n", name, state, priority, type);
}
}
}
|
package com.youthchina.service.recommendation;
import com.youthchina.dao.jinhao.RecommendMapper;
import com.youthchina.domain.jinhao.BriefReview;
import com.youthchina.domain.jinhao.Label;
import com.youthchina.domain.jinhao.Question;
import com.youthchina.domain.qingyang.Company;
import com.youthchina.domain.qingyang.Job;
import com.youthchina.domain.tianjian.ComEssay;
import com.youthchina.domain.zhongyang.User;
import com.youthchina.exception.zhongyang.exception.NotFoundException;
import com.youthchina.service.application.CompanyCURDService;
import com.youthchina.service.application.JobService;
import com.youthchina.service.community.BriefReviewService;
import com.youthchina.service.community.EssayService;
import com.youthchina.service.community.QuestionService;
import com.youthchina.service.user.UserService;
import com.youthchina.util.dictionary.TagTargetType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.*;
@Service
public class RecommendServiceImpl implements RecommendService {
@Resource
RecommendMapper recommendMapper;
@Resource
BriefReviewService briefReviewService;
@Resource
EssayService essayService;
@Resource
QuestionService questionService;
@Resource
JobService jobService;
@Resource
CompanyCURDService companyCURDService;
@Resource
UserService userService;
@Override
@Transactional
public void addTag(String labelCode, int targetType, int targetId) throws NotFoundException {
//check whether targetId exist
switch (targetType) {
case TagTargetType.QUESTION: {
questionService.get(targetId);
break;
}
case TagTargetType.ARTICLE: {
essayService.get(targetId);
break;
}
case TagTargetType.EDITORIAL: {
briefReviewService.get(targetId);
break;
}
case TagTargetType.COMPANY: {
companyCURDService.get(targetId);
break;
}
case TagTargetType.JOB: {
jobService.get(targetId);
break;
}
case TagTargetType.USER: {
userService.exist(targetId);
break;
}
default:
throw new NotFoundException(4040, 404, "The target type does not exist!");
}
recommendMapper.addTag(labelCode, targetType, targetId);
}
@Override
@Transactional
public void deleteTag(String labelCode, int targetType, int targetId) throws NotFoundException {
String id = recommendMapper.isTagExist(labelCode, targetType, targetId);
if (id == null) throw new NotFoundException(404, 404, "This label does not exist and cannot be deleted");
recommendMapper.deleteTag(labelCode, targetType, targetId);
}
public boolean isTagExist(String labelCode, int targetType, int targetId) {
return recommendMapper.isTagExist(labelCode, targetType, targetId) != null;
}
@Override
public List<Label> getLabels(int targetType, int targetId) {
List<String> labelCodes = recommendMapper.getLabelCode(targetType, targetId);
List<Label> labels = new ArrayList<>();
if (labelCodes.size() == 0) return labels;
labels = recommendMapper.getLabel(labelCodes);
return labels;
}
@Override
@Transactional
public List<User> getRecommendUser(int userId) throws NotFoundException {
List<String> userLabels = recommendMapper.getUserLabel(userId);
if (userLabels.size() == 0) {
throw new NotFoundException(404, 404, "User do not have any labels");
}
List<Integer> userIds = recommendMapper.getRecommendUser(userLabels);
Set<Integer> nonRepeatIds = new HashSet<>(userIds);
List<User> users = new LinkedList<>();
for (Integer id : nonRepeatIds) {
if (id == userId) continue;
try {
users.add(userService.get(id));
} catch (NotFoundException e) {
e.printStackTrace();
}
}
return users;
}
@Override
@Transactional
public List<Company> getRecommendCompany(int userId) throws NotFoundException {
List<String> userLabels = recommendMapper.getUserLabel(userId);
if (userLabels.size() == 0) {
throw new NotFoundException(404, 404, "User do not have any labels");
}
List<Integer> ids = recommendMapper.getRecommendCompany(userLabels);
Set<Integer> reduceRepeat = new HashSet<>(ids);
ids = new ArrayList<>(reduceRepeat);
return companyCURDService.get(ids);
}
@Override
@Transactional
public List<ComEssay> getRecommendEssay(int userId) throws NotFoundException {
List<String> userLabels = recommendMapper.getUserLabel(userId);
if (userLabels.size() == 0) {
throw new NotFoundException(404, 404, "User do not have any labels");
}
List<Integer> ids = recommendMapper.getRecommendEassy(userLabels);
Set<Integer> reduceRepeat = new HashSet<>(ids);
ids = new ArrayList<>(reduceRepeat);
return essayService.get(ids);
}
@Override
public List<Question> getRecommendQuestion(int userId) throws NotFoundException {
List<String> userLabels = recommendMapper.getUserLabel(userId);
if (userLabels.size() == 0) {
throw new NotFoundException(404, 404, "User do not have any labels");
}
List<Integer> ids = recommendMapper.getRecommendQuestion(userLabels);
Set<Integer> reduceRepeat = new HashSet<>(ids);
ids = new ArrayList<>(reduceRepeat);
return questionService.get(ids);
}
@Override
public List<Job> getRecommendJob(int userId) throws NotFoundException {
List<String> userLabels = recommendMapper.getUserLabel(userId);
if (userLabels.size() == 0) {
throw new NotFoundException(404, 404, "User do not have any labels");
}
List<Integer> ids = recommendMapper.getRecommendJob(userLabels);
Set<Integer> reduceRepeat = new HashSet<>(ids);
ids = new ArrayList<>(reduceRepeat);
return jobService.get(ids);
}
@Override
public List<BriefReview> getRecommendBriefReview(int userId) throws NotFoundException {
List<String> userLabels = recommendMapper.getUserLabel(userId);
if (userLabels.size() == 0) {
throw new NotFoundException(404, 404, "User do not have any labels");
}
List<Integer> ids = recommendMapper.getRecommendBriefReview(userLabels);
Set<Integer> reduceRepeat = new HashSet<>(ids);
ids = new ArrayList<>(reduceRepeat);
return briefReviewService.get(ids);
}
}
|
package com.tencent.mm.ui.voicesearch;
class a$a {
public CharSequence nickName;
final /* synthetic */ a uFB;
public CharSequence uop;
public CharSequence uoq;
public int uor;
private a$a(a aVar) {
this.uFB = aVar;
}
/* synthetic */ a$a(a aVar, byte b) {
this(aVar);
}
}
|
package entity;
public class Kullanici {
private int kul_id;
private String kul_adi;
private String kul_sifre;
private String eski_sifre;
public Kullanici() {
}
public Kullanici(int kul_id, String kul_adi, String kul_sifre) {
this.kul_id = kul_id;
this.kul_adi = kul_adi;
this.kul_sifre = kul_sifre;
}
public void yazdir(){
System.out.println(this.kul_id);
}
public String getKul_adi() {
return kul_adi;
}
public void setKul_adi(String kul_adi) {
this.kul_adi = kul_adi;
}
public String getKul_sifre() {
return kul_sifre;
}
public void setKul_sifre(String kul_sifre) {
this.kul_sifre = kul_sifre;
}
public int getKul_id() {
return kul_id;
}
public void setKul_id(int kul_id) {
this.kul_id = kul_id;
}
public String getEski_sifre() {
return eski_sifre;
}
public void setEski_sifre(String eski_sifre) {
this.eski_sifre = eski_sifre;
}
@Override
public String toString() {
return "Kullanici{" + "kul_id=" + kul_id + ", kul_adi=" + kul_adi + ", kul_sifre=" + kul_sifre + ", eski_sifre=" + eski_sifre + '}';
}
}
|
package controllers;
import dao.ProfesionDAO;
import entity.Personal;
import entity.Profesion;
import services.serviceImpl.PersonalServiceImpl;
import services.serviceInterface.PersonalService;
import transaction.TransactionManager;
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 java.io.IOException;
@WebServlet(name = "MyServlet",urlPatterns = "/MyServlet")
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String login = req.getParameter("username");
String password= req.getParameter("password");
Personal personal;
PersonalService service = (PersonalServiceImpl)getServletContext().getAttribute("service");
personal=service.getPersonal(1);
if(personal.getLogin().equals(login)&&personal.getPassword().equals(password)){
resp.sendRedirect("jsp/cabinet.jsp");
}
}
}
|
import java.util.ArrayList;
/**
* Created by tmjon on 6/20/2017.
*/
public abstract class Exercise {
double mets;
private double caloriesBurned;
int durationMinutes;
int intensity;
int reps;
ArrayList<String> name = new ArrayList<String>();
public int getDuration() {
return durationMinutes;
}
public int getIntensity() {
return intensity;
}
public abstract void setMets();
public double getMets() {
return mets;
}
public void burnCalories(double weight) {
caloriesBurned = 0.0175 * mets * weight * durationMinutes;
}
public double getCaloriesBurned() {
return caloriesBurned;
}
}
|
package ro.ase.cts.clase;
public class MedicamentAdapter implements IMedicament{
private Medicament medicament;
public MedicamentAdapter(Medicament medicament) {
super();
this.medicament = medicament;
}
@Override
public void vindeMedicament() {
this.medicament.achizitioneazaMedicament();
}
}
|
package com.zhowin.miyou.recommend.adapter;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.zhowin.miyou.R;
import java.util.List;
/**
* author : zho
* date :2020/9/19
* desc : 贡献榜单 / 魅力榜单 的 信息
*/
public class CharmInformationAdapter extends BaseQuickAdapter<String, BaseViewHolder> {
public CharmInformationAdapter(@Nullable List<String> data) {
super( R.layout.include_charm_information_item_view, data);
}
@Override
protected void convert(@NonNull BaseViewHolder helper, String item) {
}
}
|
package MMediator;
public class MediatorTest {
public static void main(String[] args) {
DispatcherMediator dispatcher = new ConcreteDispatcherMediator();
Aircraft lightA = new LightAirplane("Sesna", 4000, dispatcher);
Aircraft lightB = new LightAirplane("An-2", 8000, dispatcher);
Aircraft lightC = new LightAirplane("An-3", 13000, dispatcher);
Aircraft commersA = new CommercialAirplane("An-148", 20000, dispatcher);
Aircraft commersB = new CommercialAirplane("An-158", 80000, dispatcher);
Aircraft commersC = new CommercialAirplane("An-178", 15000, dispatcher);
Aircraft personA = new PersonalJet("An-77", 34000, dispatcher);
Aircraft personB = new PersonalJet("A-300", 34000, dispatcher);
Aircraft personC = new PersonalJet("Boeing-737", 28000, dispatcher);
lightB.sendCurrentAltitude(lightB);
commersA.sendCurrentAltitude(commersA);
personC.sendCurrentAltitude(personC);
lightC.sendCurrentAltitude(lightC);
lightA.sendCurrentAltitude(lightA);
personB.sendCurrentAltitude(personB);
commersC.sendCurrentAltitude(commersC);
personA.sendCurrentAltitude(personA);
commersB.sendCurrentAltitude(commersB);
((ConcreteDispatcherMediator) dispatcher).printAllAircrafts();
}
}
|
package br.com.lucasfaria.comuns.enums;
import android.support.annotation.NonNull;
import java.util.ArrayList;
import java.util.List;
public enum DiasDaSemana {
DOMINGO("Domingo"),
SEGUNDA("Segunda-feira"),
TERCA("Terça-feira"),
QUARTA("Quarta-feira"),
QUINTA("Quinta-feira"),
SEXTA("Sexta-feira"),
SABADO("Sábado");
private static List<String> lista = null;
private String descricao;
DiasDaSemana(String descricao) {
this.descricao = descricao;
}
public static List<String> getNomes() {
if (lista == null) {
lista = new ArrayList<>();
for (DiasDaSemana tipo : DiasDaSemana.values()) {
lista.add(tipo.getDescricao());
}
}
return lista;
}
public static DiasDaSemana getByName(@NonNull final String name) {
for (DiasDaSemana tc : values()) {
if (name.equals(tc.getDescricao())) {
return tc;
}
}
return null;
}
public String toString() {
return descricao;
}
public String getDescricao() {
return descricao;
}
}
|
package com.takshine.wxcrm.controller;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.takshine.core.service.CRMService;
import com.takshine.wxcrm.base.util.FTPUtil;
import com.takshine.wxcrm.base.util.Get32Primarykey;
import com.takshine.wxcrm.base.util.OSSUtil;
import com.takshine.wxcrm.base.util.PropertiesUtil;
import com.takshine.wxcrm.base.util.StringUtils;
import com.takshine.wxcrm.base.util.WxUtil;
import com.takshine.wxcrm.domain.MessagesExt;
/**
* 资料 页面控制器
*
*
*/
@Controller
@RequestMapping("/files")
public class FilesController
{
// 日志
protected static Logger logger = Logger.getLogger(FilesController.class
.getName());
@Autowired
@Qualifier("cRMService")
private CRMService cRMService;
/**
* 从策信服务器下载文件
*
* @param request
* @param response
* @return
*/
@RequestMapping("/down4wx")
@ResponseBody
public String down4wx(HttpServletRequest request,
HttpServletResponse response) throws Exception
{
logger.info("FilesController-->in down4wx");
String serverids = request.getParameter("serverids");
String filetype = request.getParameter("filetype");
String relaid = request.getParameter("relaid");
String relatype = request.getParameter("relatype");
logger.info("FilesController-->serverids == " + serverids);
logger.info("FilesController-->filetype == " + filetype);
logger.info("FilesController-->relaid == " + relaid);
logger.info("FilesController-->relatype == " + relatype);
//如果上传是图片信息
if("img".equals(filetype)){
//下载图片信息
if(StringUtils.isNotNullOrEmptyStr(serverids)){
String[] serids = serverids.split(",");
for (String serid : serids) {
String filename = downloadWXImgToOss(serid);
logger.info("-------------filename-------"+filename);
MessagesExt me = new MessagesExt();
me.setFilename(filename);
me.setSource_filename(filename);
me.setRelaid(relaid);
me.setFiletype(filetype);
me.setRelatype(relatype);
cRMService.getDbService().getMessagesExtService().addObj(me);
}
}else{
return "nodata";
}
}else{
return "unknown";
}
logger.info("FilesController-->out down4wx");
return "success";
}
@RequestMapping("/down4wxToOss")
@ResponseBody
public String down4wxToOss(HttpServletRequest request,
HttpServletResponse response) throws Exception {
logger.info("FilesController-->in down4wxToOss");
String serverids = request.getParameter("serverids");
String filetype = request.getParameter("filetype");
String relaid = request.getParameter("relaid");
String relatype = request.getParameter("relatype");
logger.info("FilesController-->serverids == " + serverids);
logger.info("FilesController-->filetype == " + filetype);
logger.info("FilesController-->relaid == " + relaid);
logger.info("FilesController-->relatype == " + relatype);
//如果上传是图片信息
String filename="";
if("img".equals(filetype)){
//下载图片信息
if(StringUtils.isNotNullOrEmptyStr(serverids)){
serverids =serverids.replaceAll("'", "");
String[] serids = serverids.split(",");
for (String serid : serids) {
filename += downloadWXImgToOss(serid)+",";
logger.info("-------------filename-------"+filename);
}
}else{
return "unknown";
}
}else{
return "unknown";
}
logger.info("FilesController-->out down4wx");
return filename;
}
/**
* 从策信服务器下载文件
*
* @param request
* @param response
* @return
*/
@RequestMapping("/calendarDown4wx")
@ResponseBody
public String calendarDown4wx(HttpServletRequest request,
HttpServletResponse response) throws Exception {
logger.info("FilesController-->in down4wx");
String serverids = request.getParameter("serverids");
String filetype = request.getParameter("filetype");
String relaid = request.getParameter("relaid");
String relatype = request.getParameter("relatype");
logger.info("FilesController-->serverids == " + serverids);
logger.info("FilesController-->filetype == " + filetype);
logger.info("FilesController-->relaid == " + relaid);
logger.info("FilesController-->relatype == " + relatype);
//如果上传是图片信息
if("img".equals(filetype)){
//下载图片信息
if(StringUtils.isNotNullOrEmptyStr(serverids)){
String[] serids = serverids.split(",");
String filename=null;
int i=0;
for (String serid : serids) {
if(StringUtils.isNotNullOrEmptyStr(serid)){
if(serid.indexOf("source")==-1){
filename = downloadWXImgToOss(serid);
}else{
filename =serid;
}
}
logger.info("-------------filename-------"+filename);
MessagesExt me = new MessagesExt();
me.setFilename(filename);
me.setSource_filename(filename);
me.setRelaid(relaid);
me.setFiletype(filetype);
me.setRelatype(relatype);
if(i==0){
cRMService.getDbService().getMessagesExtService().delMessagesExt(me);
}
i++;
cRMService.getDbService().getMessagesExtService().addObj(me);
}
}else{
return "nodata";
}
}else{
return "unknown";
}
logger.info("FilesController-->out down4wx");
return "success";
}
/**
* 从微信上下载图片
* @param serverId
* @return
*/
private String downloadWXImg (String serverId) throws Exception{
byte[] data = WxUtil.downloadMedia(serverId);
ByteArrayInputStream is = new ByteArrayInputStream(data);
String pre_filename = PropertiesUtil.getAppContext("app.publicId")+"_"+Get32Primarykey.getRandom32PK();
//上传到FTP服务器
String fileName = "source_"+pre_filename+"_wx.jpeg";
FTPUtil fu = new FTPUtil();
FTPClient ftp = fu.getConnectionFTP(PropertiesUtil.getAppContext("file.service"),Integer.parseInt(PropertiesUtil.getAppContext("file.service.port")), PropertiesUtil.getAppContext("file.service.uid"), PropertiesUtil.getAppContext("file.service.pwd"));
if(fu.uploadFile(ftp, PropertiesUtil.getAppContext("file.service.userpath"), fileName, is)){
fu.closeFTP(ftp);
Image src = javax.imageio.ImageIO.read(new ByteArrayInputStream(data)); //构造Image对象
/*
//按比例压缩图片
int width = src.getWidth(null);
int height = src.getHeight(null);
if (96 >= width)
{
if (96 < height)
{
width = (int) (width * 96 / height);
height = 96;
}
}
else
{
if (96 >= height)
{
height = (int) (height * 96 / width);
width = 96;
}
else
{
if (height > width)
{
width = (int) (width * 96 / height);
height = 96;
}
else
{
height = (int) (height * 96 / width);
width = 96;
}
}
}
//end
*/
BufferedImage tag = new BufferedImage(96,96,BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(src,0,0,96,96,null); //绘制缩小后的图
//将生成的缩略成转换成流
ByteArrayOutputStream bs =new ByteArrayOutputStream();
ImageOutputStream imOut =ImageIO.createImageOutputStream(bs);
ImageIO.write(tag,"jpeg",imOut);
InputStream iss =new ByteArrayInputStream(bs.toByteArray());
fileName = pre_filename+"_wx.jpeg";
ftp = fu.getConnectionFTP(PropertiesUtil.getAppContext("file.service"),Integer.parseInt(PropertiesUtil.getAppContext("file.service.port")), PropertiesUtil.getAppContext("file.service.uid"), PropertiesUtil.getAppContext("file.service.pwd"));
fu.uploadFile(ftp, PropertiesUtil.getAppContext("file.service.userpath"), fileName, iss);
fu.closeFTP(ftp);
return fileName;
}else{
fu.closeFTP(ftp);
logger.info("ContactController upload method -1 上传失败!");
return null;
}
}
private String downloadWXImgToOss (String serverId) throws Exception{
byte[] data = WxUtil.downloadMedia(serverId);
InputStream is = new ByteArrayInputStream(data);
String pre_filename = PropertiesUtil.getAppContext("app.publicId")+"_"+Get32Primarykey.getRandom32PK();
String fileName = "source_"+pre_filename+"_wx.jpeg";
String key = OSSUtil.uploadFile(OSSUtil.BUCKET_PIC,fileName,is);
if (StringUtils.isNotNullOrEmptyStr(key)){
logger.info("downloadWXImgToOss 上传成功 : 文件名--> "+fileName);
return key;
}else {
logger.info("downloadWXImgToOss 上传失败! -1 ");
return null;
}
}
}
|
package pl.edu.agh.iosr.controller;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import pl.edu.agh.iosr.stockquote.StockQuote;
import pl.edu.agh.iosr.stockquote.StockQuoteListenerImpl;
@Controller
public class HomeController {
@Autowired AmqpTemplate amqpTemplate;
StockQuoteListenerImpl stockQuoteListener = new StockQuoteListenerImpl();
@RequestMapping(value = "/")
public String home(Model model) {
model.addAttribute(new Message());
model.addAttribute(new Key());
return "home";
}
@RequestMapping(value = "/publish", method=RequestMethod.POST)
public String publish(Model model, Message message) {
// Send a message to the "messages" queue
System.out.println("["+message.getKey()+"]["+message.getValue()+"]");
stockQuoteListener.setAmqpTemplate(amqpTemplate);
StockQuote stockQuote = new StockQuote(message.getKey(), new Date(), Double.parseDouble(message.getValue()));
stockQuoteListener.newStockQuote(stockQuote);
//amqpTemplate.convertAndSend(message.getKey(), message.getValue());
model.addAttribute("published", true);
return home(model);
}
@RequestMapping(value = "/get", method=RequestMethod.POST)
public String get(Model model, Key key) {
// Receive a message from the "messages" queue
System.out.println("["+key.getValue()+"]");
String message = (String)amqpTemplate.receiveAndConvert(key.getValue());
if (message != null)
model.addAttribute("got", message);
else
model.addAttribute("got_queue_empty", true);
return home(model);
}
@RequestMapping(value = "/test/{nums}", method=RequestMethod.GET)
public String performanceTest(Model model, @PathVariable String nums) {
List<TestResult> results = new ArrayList<TestResult>();
AmqpPerformanceTest tester = new AmqpPerformanceTest(amqpTemplate);
for(String num : nums.split(","))
results.add(tester.testNum(Integer.parseInt(num)));
model.addAttribute("results", results);
return "testResults";
}
}
|
package io.summer;
import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* Servlet implementation class SimpleServlet using Annotations
*/
/*
base URL (web-application name) with matching urlPattern - makes tomcat run this class
Default method - doGet
*/
@WebServlet(description = "A simple servlet Using Annotations", urlPatterns = { "/SimpleServletPath" })
public class SimpleServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public SimpleServlet() {}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("A simple servlet Using Annotations : Hello from doGet");
// TODO Auto-generated method stub
// response.getWriter().append("Served at: ").append(request.getContextPath());
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.println("<h3>Hello From</h3><h1>doGet</h1><p>A simple servlet Using Annotations</p>");
}
}
|
/**
* Created by dietaschuelter on 4/13/16.
*/
public class TestString {
public static void main(String[] args) {
int myInt = 7;
String myText = "grizzliwutz";
System.out.println(myText);
}
}
|
package exer;
import java.util.Scanner;
/**
* @author menglanyingfei
* @date 2017-7-18
*/
public class Main12_Divide {
/**
* @param args
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
boolean flag = true;
int temp = n;
for (int i = 2; i <= temp; ++i) {
while (i != n) {
if (temp % i == 0) {
if (flag) {
System.out.printf("%d=%d", n, i);
flag = false;
} else
System.out.printf("x%d", i);
temp /= i;
} else
break;
}
}
if (flag)
System.out.printf("%d=%d", n, n);
}
}
|
package com.tencent.mm.plugin.fav.ui;
import com.tencent.mm.plugin.fav.ui.a.a;
class FavBaseUI$8 implements Runnable {
final /* synthetic */ FavBaseUI iYp;
FavBaseUI$8(FavBaseUI favBaseUI) {
this.iYp = favBaseUI;
}
public final void run() {
a aMc = this.iYp.aMc();
aMc.aMD();
aMc.aME();
this.iYp.aMg();
}
}
|
package MiddleClass;
import facing.KMP;
/**
* @author renyujie518
* @version 1.0.0
* @ClassName xuanZhuanCi.java
* @Description
*
*如果一个字符串为str, 把字符串str前面任意的部分挪到后面形成的字符串叫 作str的旋转词。
* 比如str="12345", str的旋转词有"12345"、 "23451 " 、 "34512"、 "45123"和"51234"。
* 给定两个字符串a和b, 请判断a和b是否互为旋转 词。
* 比如: a="cdab", b="abcd", 返回true。
* a="1ab2", b="ab12", 返回false。
* a="2ab1", b="ab12", 返回true。
*
* 思路:
* 复制一遍紧接着后面 比如abcd复制完就是abcdabcd,那么这个大字符串中每个长度为4的子字符串都是旋转词
* 怎么判断互为旋转词 可以看是不是大字符串的子串 判断子串 优先想到KMP
*
* @createTime 2021年07月29日 16:18:00
*/
public class xuanZhuanCi {
public static boolean isRotation(String a, String b) {
if (a == null || b == null || a.length() != b.length()) {
return false;
}
String b2 = b + b;
//KMP算法解决的问题字符串str1和str2,str1是否包含str2,如果包含 返回str2在str1中开始的位置。 如果不包含返回-1
return KMP.getIndexOf(b2, a) != -1;
}
public static void main(String[] args) {
String str1 = "cdab";
String str2 = "abcd";
System.out.println(isRotation(str1, str2));
}
}
|
package app.controllers;
import app.algorithm.Move;
import app.election.ElectionData;
import app.enums.Metric;
import app.enums.Parties;
import app.enums.Property;
import app.json.PropertiesManager;
import app.state.District;
import app.state.Precinct;
import app.state.State;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import java.util.*;
@Service
@Scope(value = "prototype")
public abstract class Algorithm{
@Autowired
SocketHandler handler;
protected State state;
protected volatile boolean running;
protected volatile boolean paused;
private ArrayDeque<Move> listOfMoves;
private Thread algoThread;
protected double functionValue;
private HashMap<Metric, Double> weights;
protected long systemStartTime;
protected final long MAX_RUN_TIME;
protected long remainingRunTime;
private final int ONE = 1;
private final int ZERO = 0;
protected final String endMessage = "{\"enable_reset\": 1, \"console_log\" : \"Algo ended\"}";
protected String variant = "";
protected Set<Precinct> precinctSeeds;
protected Set<District> districtSeeds;
protected Set<District> districtExcluded;
public Algorithm(){
running = false;
paused = false;
listOfMoves = new ArrayDeque<>();
weights = new HashMap<>();
MAX_RUN_TIME = Integer.parseInt(PropertiesManager.get(Property.MAX_RUNTIME));
precinctSeeds = new HashSet<>();
districtSeeds = new HashSet<>();
districtExcluded = new HashSet<>();
}
public void resetPrecinctSeeds(Set<Precinct> seeds){
precinctSeeds.clear();
precinctSeeds.addAll(seeds);
}
public void resetDistrictExcluded(Set<District> excludes){
districtExcluded.clear();
districtExcluded.addAll(excludes);
}
public void resetDistrictSeeds(Set<District> seeds){
districtSeeds.clear();
districtSeeds.addAll(seeds);
}
protected Precinct getManualPrecinctSeed(District district){
for (Precinct seed : precinctSeeds) { // check for manually set seed
Precinct precinct = district.getPrecinct(seed.getID());
if (precinct != null) {
return precinct;
}
}
return null;
}
public Set<District> removeExcludedDistricts(Collection<District> districts){
Set<District> notExcluded = new HashSet<>();
for(District d: districts){
if(!districtExcluded.contains(d)){
notExcluded.add(d);
}
}
return notExcluded;
}
public Set<Precinct> removeExcludedPrecincts(Collection<Precinct> precincts){
Set<Precinct> notExcludedPrecincts = new HashSet<>();
for(Precinct p: precincts){
if(!districtExcluded.contains(p.getDistrict())){
notExcludedPrecincts.add(p);
}
}
return notExcludedPrecincts;
}
public void start(){
if( running ){
stop();
}
//systemStartTime = System.currentTimeMillis();
remainingRunTime = MAX_RUN_TIME;
algoThread = new Thread(()->{
running = true;
run();
running = false;
handler.send(endMessage);
});
algoThread.start();
}
public void stop(){
running = false;
paused = false;
algoThread.interrupt();
}
public void pause(boolean pause){
if(running) {
paused = pause;
System.out.println("Pause click");
}
}
public void addToMoveStack(Move move){
listOfMoves.push(move);
}
public void setState(State state){
this.state = state;
}
public boolean isRunning(){
return running;
}
public void setMetricWeights(double partisanFairness, double compactness, double populationEquality){
weights.put(Metric.PARTISAN_FAIRNESS, partisanFairness);
weights.put(Metric.COMPACTNESS, compactness);
weights.put(Metric.POPULATION_EQUALITY, populationEquality);
}
public HashMap<Metric, Double> getWeights(){
return weights;
}
public boolean isBetter(double newValue, double oldValue){
return true;
}
public double calculateFunctionValue(){
double populationEqualityValue = ONE - computeAveragePercentError();
calculateVoteTotal();
double partisanFairnessValue = ONE - computePartisanFairness();
double compactnessValue = computeCompactness();
return weights.get(Metric.POPULATION_EQUALITY) * populationEqualityValue +
weights.get(Metric.PARTISAN_FAIRNESS) * partisanFairnessValue + weights.get(Metric.COMPACTNESS) *
compactnessValue;
}
public void setInitialObjFunctionValue(double value){
functionValue = value;
}
public double computeAveragePercentError(){
int idealPopulation = state.getIdealPopulation();
double percentError = ZERO;
for(app.state.District district : state.getAllDistricts()){
percentError += Math.abs((double)(district.getPopulation() - idealPopulation)/idealPopulation);
}
return percentError/state.getDistrictMap().size();
}
public double computeCompactness(){
double totalCompactness = ZERO;
for(District district : state.getAllDistricts()){
totalCompactness += district.computePolsby();
}
return totalCompactness/state.getDistrictMap().size();
}
public double computePartisanFairness(){
int totalVotes = ZERO;
int democraticWastedVotes = ZERO;
int republicanWastedVotes = ZERO;
for(District district : state.getAllDistricts()){
totalVotes += district.getTotalVotes();
HashMap<Parties, Integer> map = district.retrieveWastedVotes();
democraticWastedVotes += map.get(Parties.DEMOCRATIC);
republicanWastedVotes += map.get(Parties.REPUBLICAN);
}
return Math.abs(((double)(democraticWastedVotes - republicanWastedVotes)/totalVotes));
}
public void calculateVoteTotal(){
for(District district : state.getAllDistricts()){
for(Precinct precinct : district.getAllPrecincts()){
ElectionData ed = precinct.getElectionData();
HashMap<Parties, Integer> voterDistribution = ed.getVoterDistribution();
if(voterDistribution.containsKey(Parties.DEMOCRATIC)){
district.addVotes(Parties.DEMOCRATIC, voterDistribution.get(Parties.DEMOCRATIC));
}
if(voterDistribution.containsKey(Parties.REPUBLICAN)){
district.addVotes(Parties.REPUBLICAN, voterDistribution.get(Parties.REPUBLICAN));
}
}
}
}
public double computeFunctionDistrict(District d){
double idealPopulation = state.getIdealPopulation();
double percentError = Math.abs((double)(d.getPopulation() - idealPopulation)/idealPopulation);
double popEqualityValue = ONE - percentError;
int totalVotes = d.getTotalVotes();
HashMap<Parties, Integer> map = d.retrieveWastedVotes();
int democraticWastedVotes = map.get(Parties.DEMOCRATIC);
int republicanWastedVotes = map.get(Parties.REPUBLICAN);
double partisanFairness = Math.abs(((double)(democraticWastedVotes-republicanWastedVotes)/totalVotes));
double compactness = d.computePolsby();
return weights.get(Metric.POPULATION_EQUALITY) * popEqualityValue +
weights.get(Metric.PARTISAN_FAIRNESS) * partisanFairness+ weights.get(Metric.COMPACTNESS) *
compactness;
}
public void setVariant(String variant){this.variant = variant;}
public static double normalize(double number){
return ((number/3) * 1 + 0);
}
abstract void run();
}
|
package be.spring.app.service;
import be.spring.app.form.AccountProfileForm;
import be.spring.app.form.ActivateAccountForm;
import be.spring.app.model.Account;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.Errors;
import java.util.List;
import java.util.Locale;
public interface AccountService {
Account registerAccount(Account account, String password);
Account updateAccount(Account account, AccountProfileForm form);
@Transactional
Account saveAccount(Account account);
@Transactional
Account activateAccount(ActivateAccountForm form, Locale locale, Errors errors);
void validateUsername(String email, Errors errors);
void validateUsernameExcludeCurrentId(String email, Long id, Errors errors);
@Transactional(readOnly = false)
void setPasswordFor(Account account, String password);
@Transactional(readOnly = false)
boolean checkOldPassword(Account account, String password);
@Transactional(readOnly = true)
boolean passwordIsNullOrEmpty(Account account);
@Transactional(readOnly = true)
List<Account> getAll();
@Transactional(readOnly = true)
List<Account> getAllActivateAccounts();
@Transactional(readOnly = true)
Account getAccount(String id);
Account getAccount(Long id);
Account getActiveAccountByEmail(String email);
Account getActiveAccountById(String id);
List<Account> getAccountsByActivationStatus(boolean status);
List<Account> getAccountsWithActivationCode();
}
|
import java.util.ArrayList;
import java.util.Scanner;
/**
* sub-class for the pawn piece
*/
public class Pawn extends Piece{
/**
* constructor for the pawn object based on the location of the piece and the player's number
* @param locationToInsert tuple of x and y spots
* @param givenPlayerNumber enum which is the player's side
*/
public Pawn(Pair locationToInsert, PlayerSpecifier givenPlayerNumber)
{
this.typeOfPiece = PieceType.PAWN;
this.currentLocation = locationToInsert;
this.playerNumber = givenPlayerNumber;
}
/**
* override method which calculates the possible moves of the pawn piece according to the current
* state of the game
* @param gameBoard board object which includes the game board set up
* @return array list of all the possible moves
*/
@Override
public ArrayList<Pair> possiblePieceMoves(Board gameBoard)
{
ArrayList<Pair> listOfAllPossibleMoves = new ArrayList<>();
int leftCoordinate = this.currentLocation.getLeft();
int rightCoordinate = this.currentLocation.getRight();
if (this.playerNumber == PlayerSpecifier.FIRST)
{
if (leftCoordinate == 6)
{
Piece locationCheck = gameBoard.getPieceFromLocation(new Pair(leftCoordinate - 2, rightCoordinate));
if (locationCheck == null)
{
listOfAllPossibleMoves.add(new Pair(leftCoordinate - 2, rightCoordinate));
}
}
if ((leftCoordinate - 1 >= 0) && (rightCoordinate + 1 <= 7))
{
Piece locationCheck = gameBoard.getPieceFromLocation(new Pair(leftCoordinate - 1, rightCoordinate + 1));
if (locationCheck != null)
{
if (locationCheck.getPlayerNumber() != this.getPlayerNumber())
{
listOfAllPossibleMoves.add(new Pair(leftCoordinate - 1, rightCoordinate + 1));
}
}
}
if ((leftCoordinate - 1 >= 0) && (rightCoordinate - 1 >= 0))
{
Piece locationCheck = gameBoard.getPieceFromLocation(new Pair(leftCoordinate - 1, rightCoordinate - 1));
if (locationCheck != null)
{
if (locationCheck.getPlayerNumber() != this.getPlayerNumber())
{
listOfAllPossibleMoves.add(new Pair(leftCoordinate - 1, rightCoordinate - 1));
}
}
}
if (leftCoordinate - 1 >= 0)
{
Piece locationCheck = gameBoard.getPieceFromLocation(new Pair(leftCoordinate - 1, rightCoordinate));
if (locationCheck == null)
{
listOfAllPossibleMoves.add(new Pair(leftCoordinate - 1, rightCoordinate));
}
}
}
else
{
if (leftCoordinate == 1)
{
Piece locationCheck = gameBoard.getPieceFromLocation(new Pair(leftCoordinate + 2, rightCoordinate));
if (locationCheck == null)
{
listOfAllPossibleMoves.add(new Pair(leftCoordinate + 2, rightCoordinate));
}
}
if ((leftCoordinate + 1 >= 0) && (rightCoordinate + 1 <= 7))
{
Piece locationCheck = gameBoard.getPieceFromLocation(new Pair(leftCoordinate + 1, rightCoordinate + 1));
if (locationCheck != null)
{
if (locationCheck.getPlayerNumber() != this.getPlayerNumber())
{
listOfAllPossibleMoves.add(new Pair(leftCoordinate + 1, rightCoordinate + 1));
}
}
}
if ((leftCoordinate + 1 <= 7) && (rightCoordinate - 1 >= 0))
{
Piece locationCheck = gameBoard.getPieceFromLocation(new Pair(leftCoordinate + 1, rightCoordinate - 1));
if (locationCheck != null)
{
if (locationCheck.getPlayerNumber() != this.getPlayerNumber())
{
listOfAllPossibleMoves.add(new Pair(leftCoordinate + 1, rightCoordinate + 1));
}
}
}
if (leftCoordinate + 1 >= 0)
{
Piece locationCheck = gameBoard.getPieceFromLocation(new Pair(leftCoordinate + 1, rightCoordinate));
if (locationCheck == null)
{
listOfAllPossibleMoves.add(new Pair(leftCoordinate + 1, rightCoordinate));
}
}
}
return listOfAllPossibleMoves;
}
/**
* override method that implements the movement mechanics of the pawn piece
* @param newLocation location to move
* @param gameBoard board object which includes the game board set up
* @param playerNumber enum which is the player's side
* @return true if the piece moved successfully, false otherwise
*/
@Override
public boolean movePiece(Pair newLocation, Board gameBoard, PlayerSpecifier playerNumber)
{
boolean isPieceMoved = false;
ArrayList<Pair> allPossibleMoves = this.possiblePieceMoves(gameBoard);
for (Pair allPossibleMove : allPossibleMoves) {
if (allPossibleMove.isIdenticalPair(newLocation)) {
Piece pieceAtLocation = gameBoard.getPieceFromLocation(newLocation);
if (pieceAtLocation != null) {
gameBoard.removeFromPieceList(pieceAtLocation, playerNumber);
}
gameBoard.putNull(this.currentLocation);
gameBoard.putPiece(newLocation, this, playerNumber);
isPieceMoved = true;
this.currentLocation = newLocation;
break;
}
}
Pair pawnLocation = this.currentLocation;
if (this.currentLocation.getLeft() == 0 || this.currentLocation.getLeft() == 7)
{
char newPiece = 'O';
while (newPiece == 'O')
{
System.out.println("Choose new Piece: R-Rook, K-Knight, B-Bishop, Q-Queen");
Scanner newPieceScanner = new Scanner(System.in);
newPiece = newPieceScanner.next().charAt(0);
}
if (newPiece == 'R')
{
gameBoard.removeOldPiece(pawnLocation, this, playerNumber);
gameBoard.addNewPiece(pawnLocation, new Rook(pawnLocation, playerNumber), playerNumber);
}
if (newPiece == 'K')
{
gameBoard.removeOldPiece(pawnLocation, this, playerNumber);
gameBoard.addNewPiece(pawnLocation, new Knight(pawnLocation, playerNumber), playerNumber);
}
if (newPiece == 'B')
{
gameBoard.removeOldPiece(pawnLocation, this, playerNumber);
gameBoard.addNewPiece(pawnLocation, new Bishop(pawnLocation, playerNumber), playerNumber);
}
if (newPiece == 'Q')
{
gameBoard.removeOldPiece(pawnLocation, this, playerNumber);
gameBoard.addNewPiece(pawnLocation, new Queen(pawnLocation, playerNumber), playerNumber);
}
}
return isPieceMoved;
}
}
|
package com.example.shop_app.controller;
import com.example.shop_app.domain.Purchase;
import com.example.shop_app.repo.PurchaseRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("list_view")
public class ListController {
private PurchaseRepo purchaseRepo;
@Autowired
public ListController(PurchaseRepo purchaseRepo) {
this.purchaseRepo = purchaseRepo;
}
@GetMapping
public List<Purchase> getActualList(Purchase purchase) {
return purchaseRepo.findAllActualPurchase();
}
}
|
package com.espendwise.manta.web.tags;
import org.apache.log4j.Logger;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.tagext.TagSupport;
public class TabRowTag extends TagSupport {
private static final Logger logger = Logger.getLogger(TabRowTag.class);
private TabTag ancestor;
@Override
public int doStartTag() throws JspException {
TabTag ancestorTag = (TabTag) findAncestorWithClass(this, TabTag.class);
logger.debug("doStartTag()=> ancestorTag: " + ancestorTag);
if (ancestorTag == null) {
String message = "Tag must be nested within a TabTag tag.";
logger.error(message, new Exception(message));
return (SKIP_PAGE);
}
setAncestor(ancestorTag);
getAncestor().addRow();
return BodyTagSupport.EVAL_PAGE;
}
public void setAncestor(TabTag ancestor) {
this.ancestor = ancestor;
}
public TabTag getAncestor() {
return ancestor;
}
@Override
public void release() {
super.release();
this.ancestor = null;
}
}
|
package com.uptc.prg.maze.model.data.mazegraphlist;
import com.uptc.prg.maze.model.data.graphlist.EdgeType;
import com.uptc.prg.maze.model.data.graphlist.list.LinkedList;
import java.awt.*;
public class MazeGraph extends LinkedList<MazeVertex> {
public MazeGraph(MazeVertex startMazeVertex) {
super(startMazeVertex);
}
public MazeGraph() {
}
/*====================================== PUBLIC METHODS ======================================*/
public final MazeVertex getAnyUncheckedVertex() {
Node<MazeVertex> uncheckedVertexNode = this.getHead();
while (uncheckedVertexNode != null) {
if (!uncheckedVertexNode.getData().isChecked()) {
return uncheckedVertexNode.getData();
}
uncheckedVertexNode = uncheckedVertexNode.getNext();
}
return null;
}
public final MazeVertex addVertex(MazeVertex mazeVertex) {
if (this.searchMazeVertex(mazeVertex) == null) {
this.addToList(mazeVertex);
return mazeVertex;
} else {
return this.searchMazeVertex(mazeVertex);
}
}
public final void addPath(MazePath path) {
MazeVertex startMazeVertex = this.addVertex(new MazeVertex(path.getStartVertexPosition()));
MazeVertex endMazeVertex = this.addVertex(new MazeVertex(path.getEndVertexPosition()));
if (path.getEdgeType() == EdgeType.DIRECTED) {
this.addDirectedPaths(startMazeVertex, endMazeVertex, path.getEdgeWeight());
} else {
this.addUndirectedPath(startMazeVertex, endMazeVertex, path.getEdgeWeight());
}
}
public final void addDirectedPaths(MazeVertex startMazeVertex, MazeVertex endMazeVertex, int pathWeight) {
startMazeVertex.addEdge(new MazeEdge(endMazeVertex, pathWeight, EdgeType.DIRECTED));
}
public final void addUndirectedPath(MazeVertex startMazeVertex, MazeVertex endMazeVertex, int pathWeight) {
startMazeVertex.addEdge(new MazeEdge(endMazeVertex, pathWeight, EdgeType.UNDIRECTED));
endMazeVertex.addEdge(new MazeEdge(startMazeVertex, pathWeight, EdgeType.DIRECTED));
}
/**
* Try to find on the graph the parameter {@link MazeVertex}, if is found the {@link MazeVertex} from
* the graph is returned, else, returns {@literal null}.
*
* @param mazeVertex The {@link MazeVertex} to search on the graph.
* @return The found {@link MazeVertex} from the graph, {@literal null} otherwise.
*/
public final MazeVertex searchMazeVertex(MazeVertex mazeVertex) {
Node<MazeVertex> foundNode = this.getHead();
while (foundNode != null) {
if (foundNode.getData().getVertexPosition().equals(mazeVertex.getVertexPosition())) {
return foundNode.getData();
} else {
foundNode = foundNode.getNext();
}
}
return null;
}
public final MazeVertex searchApproximateMazeVertex(MazeVertex vertexToSearch, int threshold) {
Node<MazeVertex> foundNode = this.getHead();
while (foundNode != null && vertexToSearch.getVertexPosition() != null) {
if (this.isOnPositionWithThreshold(
foundNode.getData().getVertexPosition(),
vertexToSearch.getVertexPosition(),
threshold)) {
return foundNode.getData();
} else {
foundNode = foundNode.getNext();
}
}
return null;
}
public final boolean hasVertex(MazeVertex mazeVertex) {
return this.searchMazeVertex(mazeVertex) != null;
}
public final void uncheckAllVertices() {
MazeVertex currentVertex;
Node<MazeVertex> currentNodeVertex = this.getHead();
while (currentNodeVertex != null) {
currentVertex = currentNodeVertex.getData();
currentVertex.uncheckVertex();
currentNodeVertex = currentNodeVertex.getNext();
}
}
public final void checkAllVertices() {
MazeVertex currentVertex;
Node<MazeVertex> currentNodeVertex = this.getHead();
while (currentNodeVertex != null) {
currentVertex = currentNodeVertex.getData();
currentVertex.checkVertex();
currentNodeVertex = currentNodeVertex.getNext();
}
}
public final void resetVerticesDistances() {
MazeVertex currentVertex;
Node<MazeVertex> currentNodeVertex = this.getHead();
while (currentNodeVertex != null) {
currentVertex = currentNodeVertex.getData();
currentVertex.setVertexDistance(Integer.MAX_VALUE);
currentNodeVertex = currentNodeVertex.getNext();
}
}
public final int size() {
int vertexCount = 0;
Node<MazeVertex> currentNodeVertex = this.getHead();
while (currentNodeVertex != null) {
vertexCount++;
currentNodeVertex = currentNodeVertex.getNext();
}
return vertexCount;
}
/*====================================== PRIVATE METHODS =====================================*/
private boolean isOnPositionWithThreshold(Point pointOnGraph, Point searchingPosition, int threshold) {
if (searchingPosition.x > pointOnGraph.x - threshold && searchingPosition.x < pointOnGraph.x + threshold) {
return searchingPosition.y > pointOnGraph.y - threshold && searchingPosition.y < pointOnGraph.y + threshold;
}
return false;
}
}
|
package hackerrank;
import java.util.Arrays;
public class BubbleSortSimplyDemo {
public static int[] bubbleSort (int[] array) {
boolean isSorted = false;
// int lastUnsorted = array.length - 1;
while(!isSorted) {
isSorted = true;
for(int i = 0; i < array.length - 1; i++) {
if (array[i] > array[i + 1]) {
swap(array, i, i + 1);
isSorted = false;
}
}
// lastUnsorted--;
}
return array;
}
public static void swap(int[] array, int i, int j) {
int tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
public static void main(String[] args) {
int[] array = {3,6,1,2,5,6,7,8,-5,-2};
long[] times = new long[100];
for (int i = 0; i < 100; i++) {
long start = System.nanoTime();
System.out.println(Arrays.toString(bubbleSort(array)));
times[i] = System.nanoTime() - start;
System.out.println(times[i]);
}
long sum = 0;
for (int i = 1; i < 100; i++) {
sum += times[i];
}
long average = sum/20;
System.out.println("============");
System.out.println(average);
}
}
|
package jpamock.reflection;
public interface PropertyCallBack {
void propertyCallBack(PropertyDescription propertyDescription);
}
|
package sellwin.gui;
import javax.swing.*;
import sellwin.domain.*;
import sellwin.utils.*;
// SellWin http://sourceforge.net/projects/sellwincrm
//Contact support@open-app.com for commercial help with SellWin
//This software is provided "AS IS", without a warranty of any kind.
/**
* this class implements a pop up dialog to show a
* user's alarms...after which, the user can elect
* to forget the alarm or be reminded of the alarm
* later on
*/
public class AlarmDialog extends javax.swing.JDialog implements GUIChars {
private Activity act;
private Whiteboard wb=null;
/**
* Creates new form AlarmDialog
* @param parent the parent frame for this dialog
* @param modal is this dialog to be modal or not
* @param act the Activity to display on this dialog
*/
public AlarmDialog(java.awt.Frame parent, boolean modal, Activity act) {
super(parent, modal);
this.act = act;
wb = MainWindow.getWhiteboard();
initComponents();
setActivity(act);
setColors();
setFonts();
setLang();
setSize(300, 150);
}
/**
* set this dialog's Activity to display
* @param a the Activity to display
*/
private final void setActivity(Activity a) {
activityLabel.setText(a.getSubject());
startDateLabel.setText(Prefs.dateTimeFormat.format(a.getStartDate()));
byLabel.setText(a.getModifiedBy());
}
/**
* This method is called from within the constructor to
* initialize the form.
*/
private final void initComponents() {
buttonPanel = new JPanel();
remindButton = new JButton();
forgetButton = new JButton();
mainPanel = new JPanel();
jLabel1 = new JLabel();
jLabel2 = new JLabel();
jLabel3 = new JLabel();
activityLabel = new JLabel();
startDateLabel = new JLabel();
byLabel = new JLabel();
setTitle("Alarm Details");
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
closeDialog(evt);
}
});
remindButton.setText("Remind Later");
remindButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
remindAction(evt);
}
});
buttonPanel.add(remindButton);
forgetButton.setText("Forget");
forgetButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
forgetAction(evt);
}
});
buttonPanel.add(forgetButton);
getContentPane().add(buttonPanel, java.awt.BorderLayout.SOUTH);
mainPanel.setLayout(new java.awt.GridBagLayout());
java.awt.GridBagConstraints gridBagConstraints1;
mainPanel.setBorder(new javax.swing.border.EtchedBorder());
jLabel1.setText("Activity");
gridBagConstraints1 = new java.awt.GridBagConstraints();
gridBagConstraints1.ipadx = 10;
gridBagConstraints1.ipady = 10;
gridBagConstraints1.anchor = java.awt.GridBagConstraints.EAST;
mainPanel.add(jLabel1, gridBagConstraints1);
jLabel2.setText("Alarm Date");
gridBagConstraints1 = new java.awt.GridBagConstraints();
gridBagConstraints1.gridx = 0;
gridBagConstraints1.gridy = 1;
gridBagConstraints1.ipadx = 10;
gridBagConstraints1.ipady = 10;
gridBagConstraints1.anchor = java.awt.GridBagConstraints.EAST;
mainPanel.add(jLabel2, gridBagConstraints1);
jLabel3.setText("By");
gridBagConstraints1 = new java.awt.GridBagConstraints();
gridBagConstraints1.gridx = 0;
gridBagConstraints1.gridy = 2;
gridBagConstraints1.ipadx = 10;
gridBagConstraints1.ipady = 10;
gridBagConstraints1.anchor = java.awt.GridBagConstraints.EAST;
mainPanel.add(jLabel3, gridBagConstraints1);
activityLabel.setText("activityLabel");
gridBagConstraints1 = new java.awt.GridBagConstraints();
gridBagConstraints1.gridx = 1;
gridBagConstraints1.gridy = 0;
gridBagConstraints1.anchor = java.awt.GridBagConstraints.WEST;
mainPanel.add(activityLabel, gridBagConstraints1);
startDateLabel.setText("startDateLabel");
gridBagConstraints1 = new java.awt.GridBagConstraints();
gridBagConstraints1.gridx = 1;
gridBagConstraints1.gridy = 1;
gridBagConstraints1.anchor = java.awt.GridBagConstraints.WEST;
mainPanel.add(startDateLabel, gridBagConstraints1);
byLabel.setText("byLabel");
gridBagConstraints1 = new java.awt.GridBagConstraints();
gridBagConstraints1.gridx = 1;
gridBagConstraints1.gridy = 2;
gridBagConstraints1.anchor = java.awt.GridBagConstraints.WEST;
mainPanel.add(byLabel, gridBagConstraints1);
getContentPane().add(mainPanel, java.awt.BorderLayout.CENTER);
pack();
}
/**
* the action that gets called when the 'forget' button is
* pressed
* @param evt the ActionEvent that gets called
*/
private void forgetAction(java.awt.event.ActionEvent evt) {
// Add your handling code here:
act.setAlarmAck(true);
try {
wb.updateActivity(wb.getCurrentOpportunity().getPK(), act);
hide();
} catch (Exception e) {
ErrorHandler.show(this, e);
}
}
/**
* called when the 'remind' button is pressed
* @evt the ActionEvent that we receive by our friend "mr java"
*/
private void remindAction(java.awt.event.ActionEvent evt) {
setVisible(false);
dispose();
}
/**
* Closes the dialog
* @param evt the WindowEvent we get
*/
private final void closeDialog(java.awt.event.WindowEvent evt) {
setVisible(false);
dispose();
}
/**
* set the screen's colors
*/
public final void setColors() {
jLabel1.setForeground(MainWindow.LETTERS);
jLabel2.setForeground(MainWindow.LETTERS);
jLabel3.setForeground(MainWindow.LETTERS);
activityLabel.setForeground(MainWindow.LETTERS);
startDateLabel.setForeground(MainWindow.LETTERS);
byLabel.setForeground(MainWindow.LETTERS);
}
/**
* set the screen's fonts
*/
public final void setFonts() {
jLabel1.setFont(MainWindow.LABEL_FONT);
jLabel2.setFont(MainWindow.LABEL_FONT);
jLabel3.setFont(MainWindow.LABEL_FONT);
remindButton.setFont(MainWindow.LABEL_FONT);
forgetButton.setFont(MainWindow.LABEL_FONT);
activityLabel.setFont(MainWindow.FIELD_FONT);
startDateLabel.setFont(MainWindow.FIELD_FONT);
byLabel.setFont(MainWindow.FIELD_FONT);
};
/**
* set the dialog's language
*/
public final void setLang() {
setTitle(wb.getLang().getString("alarmInfo"));
jLabel1.setText(wb.getLang().getString("activity"));
jLabel2.setText(wb.getLang().getString("startDate"));
jLabel3.setText(wb.getLang().getString("by"));
remindButton.setText(wb.getLang().getString("remind"));
forgetButton.setText(wb.getLang().getString("forget"));
}
private JPanel buttonPanel;
private JButton remindButton;
private JButton forgetButton;
private JPanel mainPanel;
private JLabel jLabel1;
private JLabel jLabel2;
private JLabel jLabel3;
private JLabel activityLabel;
private JLabel startDateLabel;
private JLabel byLabel;
}
|
package com.hpg.demo.service.impl;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.hpg.demo.bean.Merchant;
import com.hpg.demo.dao.MerchantMapper;
import com.hpg.demo.service.MerchantService;
@Service("merchantServiceImpl")
public class MerchantServiceImpl implements MerchantService{
@Resource(name = "merchantMapper")
private MerchantMapper merchantMapper;
public void insertMerchant(Merchant merchant) throws Exception{
merchantMapper.save(merchant);
}
public List<Merchant> getMerchant() {
return merchantMapper.getMerchant();
}
public List<Merchant> getMerchantByLastId(int lastId) {
return merchantMapper.getMerchantByLastId(lastId);
}
}
|
package com.passing.spring.service.impl;
import java.util.ArrayList;
import java.util.List;
import com.passing.spring.service.SearchJpToCn;
import com.passing.hibernate.beans.Jpword;
import com.passing.hibernate.dao.JPwordDao;
public class SearchJpToCnBean implements SearchJpToCn {
private JPwordDao jpwordDao;
public JPwordDao getJpwordDao() {
return jpwordDao;
}
public void setJpwordDao(JPwordDao jpwordDao) {
this.jpwordDao = jpwordDao;
}
public List<Jpword> doJpToCn(String searchStr){
List<Jpword> resultList = getJpwordDao().getWordListByWord(searchStr);
if(resultList.size() < 1){
return getJpwordDao().getWordListByKana(searchStr);
}else{
return resultList;
}
}
public List<Jpword> doJpToCn_like(String searchStr){
List<Jpword> wordList = new ArrayList<Jpword>();
if(searchStr.length() > 1){
List<Jpword> right1List = getJpwordDao().getWordListByKana_right_like(searchStr);
List<Jpword> right2List = getJpwordDao().getWordListByKana_two_right_like(searchStr);
List<Jpword> left1List = getJpwordDao().getWordListByKana_left_like(searchStr);
wordList = right1List;
wordList.addAll(right2List);
wordList.addAll(left1List);
}
return wordList;
}
}
|
package com.fleet.axis2.services.service;
import com.fleet.axis2.services.entity.User;
/**
* @author April Han
*/
public interface UserService {
User get(Long id);
String getName(Long id);
}
|
package entity.particle;
import entity.minion.Minion;
import entity.particle.base.Bullet;
import gui.Sprite;
import logic.DamageType;
import logic.Vector2;
/**
* The CannonBullet class represents {@link Bullet Bullets} fired from {@link entity.tower.CannonTower Cannon Towers}.
*/
public class CannonBullet extends Bullet {
/**
* The constructor for the CannonBullet class.
* Instantiates the bullet with {@link Bullet#Bullet(Vector2, double, Minion, int, double) Bullet()} constructor.
* @param position The starting position of the bullet.
* @param rotation The starting rotation of the bullet.
* @param target The target of the bullet.
* @param damage The damage the bullet will deal if it reaches its target.
*/
public CannonBullet(Vector2 position, double rotation, Minion target, double damage) {
super(position, rotation, target, Sprite.CANNON_BULLET, damage);
}
/**
* The implementation of the method {@link Bullet#hit(Minion) hit} of the {@link Bullet} class.
* It deals damage to the {@link Minion} when it reaches its target.
* @param target The target of the bullet.
*/
@Override
public void hit(Minion target) {
target.takeDamage(this.damage, DamageType.Cannon);
}
}
|
package com.grability.test.dlmontano.grabilitytest.model;
/**
* Created by Diego Montano on 02/06/2016.
*/
public class Artist extends CommonData {
private long appId;
private String href;
public Artist() {
}
public Artist(long appId, String label, String href) {
this.appId = appId;
this.label = label;
this.href = href;
}
public long getAppId() { return appId; }
public void setAppId(long appId) { this.appId = appId; }
public String getHref() {
return href;
}
public void setHref(String href) {
this.href = href;
}
}
|
package com.hawk.application.web;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration("FunctionTest-config.xml")
@ActiveProfiles("dev")
public class RegisterViewTest {
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(
this.webApplicationContext).build();
}
@Test
public void registerPage() throws Exception {
ResultActions actions = this.mockMvc.perform(post("/register.html")
.param("email", "test@abc").param("password", "123")
.param("confirmPassword", "123").accept(MediaType.TEXT_HTML));
actions.andDo(print()); // action is logged into the console
actions.andExpect(status().isFound());
actions.andExpect(view().name("redirect:/"));
}
}
|
package com.example.windows10now.muathe24h.model;
/**
* Created by Windows 10 Now on 11/14/2017.
*/
public class Card {
private String namePrice;
private int price;
public Card() {
}
public Card(String namePrice, int price) {
this.namePrice = namePrice;
this.price = price;
}
public Card(String namePrice, int price, String nameHomeNetWork, int imgLogo) {
this.namePrice = namePrice;
this.price = price;
}
public String getNamePrice() {
return namePrice;
}
public void setNamePrice(String namePrice) {
this.namePrice = namePrice;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
|
package com.programacion.movil.estemanp.androidmvcapplication.View;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.programacion.movil.estemanp.androidmvcapplication.Controller.ApplicationController;
import com.programacion.movil.estemanp.androidmvcapplication.Domain.User;
import com.programacion.movil.estemanp.androidmvcapplication.OptionActivity;
import com.programacion.movil.estemanp.androidmvcapplication.R;
public class LoginActivity extends AppCompatActivity
{
EditText userName;
EditText password;
ApplicationController appController;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_login);
appController =(ApplicationController)getApplication();
userName=(android.widget.EditText) this.findViewById(R.id.editUsername);
password=(android.widget.EditText) this.findViewById(R.id.editPassword);
}
public void login(View view) {
if(appController.isValidUser(userName.getText().toString(),password.getText().toString())) {
User logUser = appController.getUser(userName.getText().toString());
Intent intent;
if (logUser.getRol().equals("admin")) {
intent = new Intent(this, AdminActivity.class);
}else{
intent = new Intent(this, OptionActivity.class);
}
startActivity(intent);
}else{
Toast.makeText(this, "El usuario y contraseña no coinciden", Toast.LENGTH_SHORT).show();
}
}
}
|
package com.pkjiao.friends.mm.adapter;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.pkjiao.friends.mm.R;
import com.pkjiao.friends.mm.MarrySocialApplication;
import com.pkjiao.friends.mm.activity.ContactsInfoActivity;
import com.pkjiao.friends.mm.base.AsyncHeadPicBitmapLoader;
import com.pkjiao.friends.mm.base.ContactsInfo;
import com.pkjiao.friends.mm.database.MarrySocialDBHelper;
public class ContactsListAdapter extends BaseAdapter {
@SuppressWarnings("unused")
private static final String TAG = "ContactsListAdapter";
private Context mContext;
private LayoutInflater mInflater;
private ArrayList<ContactsInfo> mData;
private AsyncHeadPicBitmapLoader mHeadPicBitmapLoader;
private MarrySocialDBHelper mDBHelper;
public ContactsListAdapter(Context context) {
mContext = context;
mInflater = LayoutInflater.from(mContext);
mHeadPicBitmapLoader = new AsyncHeadPicBitmapLoader(mContext);
mDBHelper = MarrySocialDBHelper.newInstance(mContext);
}
public void setDataSource(ArrayList<ContactsInfo> source) {
mData = source;
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Object getItem(int position) {
return mData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.contacts_list_item_layout,
parent, false);
holder = new ViewHolder();
holder.contacts_item_entry = (RelativeLayout) convertView
.findViewById(R.id.contacts_item_entry);
holder.person_pic = (ImageView) convertView
.findViewById(R.id.contacts_person_pic);
holder.person_name = (TextView) convertView
.findViewById(R.id.contacts_person_name);
holder.person_description = (TextView) convertView
.findViewById(R.id.contacts_person_description);
holder.person_description_more = (CheckBox) convertView
.findViewById(R.id.contacts_person_description_more);
holder.new_contact_icon = (ImageView) convertView
.findViewById(R.id.contacts_new_icon);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final int pos = position;
holder.contacts_item_entry
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
startToViewContactsInfo(mData.get(pos).getUid());
}
});
holder.person_name.setText(mData.get(position).getNickName());
mHeadPicBitmapLoader.loadImageBitmap(holder.person_pic,
mData.get(position).getUid());
holder.person_description.setText(String.format(mContext.getResources()
.getString(R.string.contacts_detail_more), mData.get(position)
.getFirstDirectFriend()));
holder.person_description_more.setChecked(false);
final ViewHolder holder_temp = holder;
final String description = (mData.get(position).getFirstDirectFriend());
final String description_more = mData.get(position).getDirectFriends();
holder.person_description_more
.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (holder_temp.person_description_more.isChecked()) {
holder_temp.person_description.setText(String
.format(mContext.getResources().getString(
R.string.contacts_detail_more),
description_more));
} else {
holder_temp.person_description.setText(String
.format(mContext.getResources().getString(
R.string.contacts_detail_more),
description));
}
}
});
if (mData.get(position).isNewContact()) {
holder.new_contact_icon.setVisibility(View.VISIBLE);
} else {
holder.new_contact_icon.setVisibility(View.INVISIBLE);
}
return convertView;
}
class ViewHolder {
RelativeLayout contacts_item_entry;
ImageView person_pic;
TextView person_name;
TextView person_description;
CheckBox person_description_more;
ImageView new_contact_icon;
}
private void startToViewContactsInfo(String uid) {
Intent intent = new Intent(mContext, ContactsInfoActivity.class);
intent.putExtra(MarrySocialDBHelper.KEY_UID, uid);
mContext.startActivity(intent);
deleteNewContactsFlagFromContactsDB(uid);
}
private void deleteNewContactsFlagFromContactsDB(String uid) {
ContentValues insertValues = new ContentValues();
insertValues.put(MarrySocialDBHelper.KEY_IS_NEW, MarrySocialDBHelper.HAS_NO_MSG);
String whereClause = MarrySocialDBHelper.KEY_UID + " = "
+ uid;
try{
mDBHelper.update(MarrySocialDBHelper.DATABASE_CONTACTS_TABLE,
insertValues, whereClause, null);
} catch (Exception exp) {
exp.printStackTrace();
}
}
// private String transArray2String(String[] friends) {
// String friend = "";
// for (String str : friends) {
// friend = friend + str + ", ";
// }
//
// friend = friend.substring(0, friend.length() - 2);
// return friend;
// }
}
|
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Main {
public static void main(String[] args) throws IOException {
String origin = "music.mp3";
String dest = "copy-music.mp3";
File file = new File(origin);
File destFile = new File(dest);
destFile.createNewFile();
FileOutputStream f = new FileOutputStream(file);
ThreadMaker threadMaker = new ThreadMaker();
threadMaker.copy(origin, dest,file.length());
}
}
|
package com.javakc.ssm.modules.system.home.entity;
import com.javakc.ssm.base.entity.BaseEntity;
public class HomeEntity extends BaseEntity<HomeEntity>{
}
|
/*
* File Name :InitServlet.java
* Create Date:2012-11-6 上午12:06:17
* Author :woden
*/
package com.riversoft.nami;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import com.riversoft.core.cache.RedisClient;
import com.riversoft.vote.VoteManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.riversoft.core.BeanFactory;
/**
* 初始化Servlet容器.
*/
@WebServlet(loadOnStartup = 0, urlPatterns = "/InitServlet", name = "InitServlet", displayName = "InitServlet", description = "用于NAMI WEB容器启动初始化")
@SuppressWarnings("serial")
public class InitServlet extends HttpServlet {
static Logger logger = LoggerFactory.getLogger(InitServlet.class);
public void init(ServletConfig config) throws ServletException {
logger.info("========== NAMI 平台安全初始化 开始 ==========");
Platform.init();
logger.info("========== NAMI 平台安全初始化 结束 ==========");
logger.info("========== NAMI Spring容器初始化 开始 ==========");
BeanFactory.init("classpath:applicationContext.xml");
logger.info("========== NAMI Spring容器初始化 结束 ==========");
logger.info("========== NAMI Redis连接初始化 开始 ==========");
RedisClient.init();
logger.info("========== NAMI Redis连接初始化 结束 ==========");
VoteManager.INSTANCE.init();
}
// @Override
// public void destroy() {
// super.destroy();
// VoteManager.INSTANCE.saveToDB();
// }
}
|
/*
* 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 jframework.ui.student;
import static data.Constants.*;
import data.db.DBPerson;
import data.core.api.ApiDate;
import data.core.api.ApiFile;
import data.core.api.ApiGui;
import data.core.api.ApiValidate;
import data.core.interfaces.UIDefaults;
import data.core.interfaces.UIForm;
import data.core.ui.swing.SwingList;
import data.db.DBPerson_person;
import java.util.HashMap;
import javax.swing.ButtonGroup;
import javax.swing.JOptionPane;
/**
*
* @author Ryno Laptop
*/
public class AddStudentPopup extends javax.swing.JFrame implements UIForm{
int id;
int row;
SwingList studentList = null;
HashMap<String, String> student;
HashMap<String, String> parent;
DBPerson db;
/**
* Creates new form AddNew
*/
public AddStudentPopup(SwingList studentList) {
this.studentList = studentList;
initComponents();
setComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
nameField = new javax.swing.JTextField();
surnameField = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
guardianNameField = new javax.swing.JTextField();
guardianSurnameField = new javax.swing.JTextField();
guardianContactNumberField = new javax.swing.JTextField();
jLabel9 = new javax.swing.JLabel();
guardianEmailField = new javax.swing.JTextField();
emailLabel = new javax.swing.JLabel();
genderLabel = new javax.swing.JLabel();
maleRadio = new javax.swing.JRadioButton();
femaleRadio = new javax.swing.JRadioButton();
jSeparator1 = new javax.swing.JSeparator();
formCemisNr = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setResizable(false);
jButton1.setText("Save");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel2.setText("Surname");
jLabel1.setText("Name");
jLabel5.setText("Student Details");
jLabel6.setText("Guardian Details");
jLabel8.setText("Name");
jLabel7.setText("Surname");
jLabel9.setText("Contact #");
emailLabel.setText("Email");
genderLabel.setText("Gender");
maleRadio.setText("Male");
maleRadio.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
maleRadioActionPerformed(evt);
}
});
femaleRadio.setText("Female");
formCemisNr.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
formCemisNrActionPerformed(evt);
}
});
jLabel3.setText("Cemis Nr");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(genderLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(maleRadio)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(femaleRadio))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jLabel1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(nameField, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(surnameField, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel8)
.addComponent(jLabel7)
.addComponent(jLabel9)
.addComponent(emailLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(guardianNameField, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(guardianSurnameField, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(guardianContactNumberField, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(guardianEmailField, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jSeparator1)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(formCemisNr, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel6)
.addComponent(jLabel5))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(nameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(surnameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(formCemisNr, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(genderLabel)
.addComponent(maleRadio)
.addComponent(femaleRadio))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(4, 4, 4)
.addComponent(jLabel6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(guardianNameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel8, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(guardianSurnameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel9)
.addComponent(guardianContactNumberField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(emailLabel)
.addComponent(guardianEmailField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButton1)
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
if(validateFields()){
//create student
this.student.put("per_firstname", nameField.getText());
this.student.put("per_lastname", surnameField.getText());
this.student.put("per_cemis_nr", formCemisNr.getText());
this.student.put("per_name", surnameField.getText() + ", " + nameField.getText());
this.student.put("per_type", "0");
this.student.put("per_date_created", ApiDate.getDate());
int student_id = this.db.insert(this.student);
//create guardian
this.parent.put("per_firstname", guardianNameField.getText());
this.parent.put("per_lastname", guardianSurnameField.getText());
this.parent.put("per_cemis_nr", "");
this.parent.put("per_name", guardianSurnameField.getText() + ", " + guardianNameField.getText());
this.parent.put("per_email", guardianEmailField.getText());
this.parent.put("per_telnr", guardianContactNumberField.getText());
this.parent.put("per_type", "1");
this.parent.put("per_date_created", ApiDate.getDate());
int guardian_id = this.db.insert(this.parent);
new DBPerson_person().create(student_id, guardian_id);
this.dispose();
addTableRow();
}
}//GEN-LAST:event_jButton1ActionPerformed
private void maleRadioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_maleRadioActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_maleRadioActionPerformed
private void formCemisNrActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_formCemisNrActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_formCemisNrActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Windows".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(AddStudentPopup.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(AddStudentPopup.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(AddStudentPopup.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(AddStudentPopup.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel emailLabel;
private javax.swing.JRadioButton femaleRadio;
private javax.swing.JTextField formCemisNr;
private javax.swing.JLabel genderLabel;
private javax.swing.JTextField guardianContactNumberField;
private javax.swing.JTextField guardianEmailField;
private javax.swing.JTextField guardianNameField;
private javax.swing.JTextField guardianSurnameField;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JRadioButton maleRadio;
private javax.swing.JTextField nameField;
private javax.swing.JTextField surnameField;
// End of variables declaration//GEN-END:variables
//----------------------------------------------------------------------------------------------------------
private void addTableRow(){
// ListStudent.jTable1.setModel(ListStudent.refreshTable());
// ListStudent.hideColumn(0);
}
//----------------------------------------------------------------------------------------------------------
@Override
public void actions() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
//----------------------------------------------------------------------------------------------------------
@Override
public final void setComponents() {
this.setTitle("Add new Student");
this.setIconImage(ApiFile.getImageIcon(ICON_ADD_16).getImage());
jPanel1.setBackground(ApiGui.getPanelColor());
this.db = new DBPerson();
this.student = this.db.get_fromdefault();
this.parent = this.db.get_fromdefault();
ButtonGroup genderGroup = new ButtonGroup();
genderGroup.add(maleRadio);
genderGroup.add(femaleRadio);
}
//----------------------------------------------------------------------------------------------------------
@Override
public boolean validateFields() {
ApiValidate validate = new ApiValidate();
validate.addComponent(nameField, "Student name");
validate.addComponent(surnameField, "Student surname");
validate.addComponent(guardianNameField, "Parent name");
validate.addComponent(guardianSurnameField, "Parent surname");
return validate.validateComponents();
}
//----------------------------------------------------------------------------------------------------------
}
|
/*
* Copyright (C) 2023 Hedera Hashgraph, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hedera.mirror.importer.repository;
import static org.assertj.core.api.Assertions.assertThat;
import lombok.RequiredArgsConstructor;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
class EntityTransactionRepositoryTest extends AbstractRepositoryTest {
private final EntityTransactionRepository repository;
@Test
void prune() {
var entityTransaction1 = domainBuilder.entityTransaction().persist();
var entityTransaction2 = domainBuilder.entityTransaction().persist();
var entityTransaction3 = domainBuilder.entityTransaction().persist();
repository.prune(entityTransaction1.getConsensusTimestamp());
assertThat(repository.findAll()).containsExactlyInAnyOrder(entityTransaction2, entityTransaction3);
repository.prune(entityTransaction2.getConsensusTimestamp());
assertThat(repository.findAll()).containsExactly(entityTransaction3);
}
@Test
void save() {
var entityTransaction = domainBuilder.entityTransaction().get();
repository.save(entityTransaction);
assertThat(repository.findById(entityTransaction.getId())).contains(entityTransaction);
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author win10
*/
public interface Pizza {
float checkCrust();
float hasVegetable();
//float hasCheese();
float hasTopping();
String cookongTime();
//float calDiscount();
float totalCost();
}
|
package com.kingbbode.bot.common.base.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
/**
* Created by YG on 2016-10-10.
*/
@Configuration
public class RedisConfig {
@Bean
public JedisConnectionFactory jedisConnectionFactory() {
JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
jedisConnectionFactory.setHostName("192.168.183.158");
jedisConnectionFactory.setPort(6379);
jedisConnectionFactory.setTimeout(0);
jedisConnectionFactory.setUsePool(true);
return jedisConnectionFactory;
}
@Bean
public StringRedisTemplate redisTemplate(JedisConnectionFactory jedisConnectionFactory) {
StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
stringRedisTemplate.setConnectionFactory(jedisConnectionFactory);
return stringRedisTemplate;
}
}
|
package gisviewer;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EtchedBorder;
/**
* top-level frame that contains a map and a panel with the coordinates of the
* mouse cursor
*
* @author haunert
*/
public class MapFrame extends JFrame {
/**
* the map displayed in this frame
*/
private Map myMap;
/**
* the label displaying the x-coordinate
*/
private JLabel xLabel;
/**
* the label displaying the y-coordinate
*/
private JLabel yLabel;
private static final long serialVersionUID = 1L;
/**
* constructor for crating an empty MapFrame
*
* @param title: the title displayed in the upper left corner of the
* frame
* @param isMainWindow: if set to true, the application will terminate if the
* frame is closed
*/
public MapFrame(String title, boolean isMainWindow) {
super(title);
setLayout(new BorderLayout());
// labels showing the world coordinates of the mouse pointer
xLabel = new JLabel();
yLabel = new JLabel();
myMap = new Map(this);
// when fitting the content to the map extend, use some empty space at the
// boundary
myMap.setFrameRatio(0.1);
JPanel myPanel = new JPanel();
myPanel.setLayout(new GridLayout(2, 1));
myPanel.add(xLabel);
myPanel.add(yLabel);
myPanel.setBorder(BorderFactory.createTitledBorder(new EtchedBorder(), "Map Coordinates", 0, 0));
// some GUI attributes
myMap.fitMapToDisplay();
myPanel.setMinimumSize(new Dimension(200, 80));
myPanel.setPreferredSize(new Dimension(200, 80));
this.add(BorderLayout.NORTH, myPanel);
this.add(BorderLayout.CENTER, myMap);
// end program if the main window is closed
if (isMainWindow) {
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
};
});
}
}
/**
* setter method used to update the coordinates displayed as text
*
* @param x: the x-coordinate that is displayed
* @param y: the y-coordinate that is displayed
*/
public void setXYLabelText(double x, double y) {
xLabel.setText(" x = " + x);
xLabel.repaint();
yLabel.setText(" y = " + y);
yLabel.repaint();
}
/**
* the map displayed in this frame
*
* @return the map
*/
public Map getMap() {
return myMap;
}
}
|
package es.uma.sportjump.sjs.service.services;
import java.util.List;
import es.uma.sportjump.sjs.model.entities.Coach;
import es.uma.sportjump.sjs.model.entities.ExerciseBlock;
import es.uma.sportjump.sjs.model.entities.Training;
public interface TrainingService {
/**
* Creates a new training with the data given by parameters;
* @param name Name of training.
* @param type type of training.
* @param description description and comments of exercise block.
* @param exerciseBlockList list with the exerciseblock belong to training.
* @param coach coach that owns the current exercise block.
* @return the new Exercise block created with his new id.
*/
public Training setNewTraining(String name, String type, String description, List<ExerciseBlock> exerciseBlockList, Coach coach);
/**
* Update an training given by parameter
* @param training the exerciseblock to update in database
*/
public void updateTraining(Training training);
/**
* find a training without exercises blockby its id given by parameter
* @param idTraining
* @return the training with the id.
*/
public Training findTrainingLight(Long idTraining);
/**
* find a complete training with exercises blocks by its id given by parameter
* @param idTraining
* @return the training with the id.
*/
public Training findTraining(Long idTraining);
/**
* find an training by its name and the coach in charge given by parameter
* @param idTraining
* @return the training with the id.
*/
public Training findTrainingByNameAndCoach(String name, Coach coach);
/**
* Deletes the training given by parameter from database
* @param training the exercise block to delete
*/
public void removeTraining(Training training);
/**
* Find all training from a coach given by parameter
* @param coach
* @return list with all training
*/
public List<Training> findAllTraining(Coach coach);
}
|
/**
* This code illustrates use of Stack
* @author java
*
*/
import java.util.Stack;
public class StackTest {
public static void main(String[] args) {
Stack<String> stack = new Stack<>();
stack.push("hello");
stack.push("Toroto");
stack.push("Ontario");
stack.push("Canada");
while (!stack.isEmpty()){
System.out.println(stack.pop());
}
}
}
|
package com.jiw.dudu;
import com.jiw.dudu.service.user.UserRegisterService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
/**
* @Description LogRecordTest
* @Author pangh
* @Date 2022年11月23日
* @Version v1.0.0
*/
@SpringBootTest(classes = {DuduApplication.class})
@RunWith(SpringRunner.class)
public class ApplicationListenerTest {
@Resource
private UserRegisterService userRegisterService;
@Test
public void testUserRegisterFireMsg(){
userRegisterService.registerUser("嘟嘟");
}
}
|
package com.samsung.object;
/**
* Created by SamSunger on 5/14/2015.
*/
public class Dealer {
private String PKID;
private String DealerName;
private String Distric;
private String City;
private String Adress;
private String Latitud;
private String LongGitude;
private String Status;
private String NameZone;
private String PhoneNumber;
public Dealer(String PKID, String dealerName, String distric, String city, String adress, String latitud, String longGitude, String status, String nameZone, String phoneNumber) {
if (dealerName == null) {
dealerName = "";
}
if (distric == null) {
distric = "";
}
if (city == null) {
city = "";
}
if (adress == null) {
adress = "";
}
if (latitud == null) {
latitud = "";
}
if (longGitude == null) {
longGitude = "";
}
if (status == null) {
status = "";
}
if (nameZone == null) {
nameZone = "";
}
if (phoneNumber == null) {
phoneNumber = "";
}
DealerName = dealerName;
Distric = distric;
City = city;
Adress = adress;
Latitud = latitud;
LongGitude = longGitude;
Status = status;
NameZone = nameZone;
PhoneNumber = phoneNumber;
this.PKID=PKID;
}
public String getDealerName() {
return DealerName;
}
public void setDealerName(String dealerName) {
DealerName = dealerName;
}
public String getDistric() {
return Distric;
}
public void setDistric(String distric) {
Distric = distric;
}
public String getCity() {
return City;
}
public void setCity(String city) {
City = city;
}
public String getAdress() {
return Adress;
}
public void setAdress(String adress) {
Adress = adress;
}
public String getLatitud() {
return Latitud;
}
public void setLatitud(String latitud) {
Latitud = latitud;
}
public String getLongGitude() {
return LongGitude;
}
public void setLongGitude(String longGitude) {
LongGitude = longGitude;
}
public String getStatus() {
return Status;
}
public void setStatus(String status) {
Status = status;
}
public String getNameZone() {
return NameZone;
}
public void setNameZone(String nameZone) {
NameZone = nameZone;
}
public String getPhoneNumber() {
return PhoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
PhoneNumber = phoneNumber;
}
public String getPKID() {
return PKID;
}
public void setPKID(String PKID) {
this.PKID = PKID;
}
@Override
public String toString() {
return PKID+" : "+DealerName+" : "+Latitud +" : " +LongGitude;
}
}
|
package org.webmaple.admin.controller;
import org.webmaple.admin.service.SpiderManageService;
import org.webmaple.admin.view.JDSpiderView;
import org.webmaple.common.model.Result;
import org.webmaple.common.model.SpiderDTO;
import org.webmaple.common.util.UrlUtil;
import org.webmaple.common.view.SpiderView;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import java.util.ArrayList;
/**
* @author lyifee
* on 2021/2/9
*/
@Controller
public class TestController {
private static final String BASE_URL = "https://search.jd.com/Search?";
@Resource
private SpiderManageService spiderManageService;
@GetMapping("/testGet")
@ResponseBody
public Result<Void> testGet(@RequestParam String testStr) {
Result<Void> result = new Result<>();
return result.success("success! " + testStr);
}
@PostMapping("/testPost")
@ResponseBody
public Result<Void> testPost(SpiderView spiderView) {
Result<Void> result = new Result<>();
System.out.println(spiderView);
return result.success("success! ");
}
@PostMapping("/JDSpider")
@ResponseBody
public Result<Void> jdSpider(JDSpiderView fields) {
SpiderDTO spiderDTO = new SpiderDTO();
spiderDTO.setWorker(fields.getWorker());
spiderDTO.setThreadNum(Integer.parseInt(fields.getThreadNum()));
spiderDTO.setUuid("jd.com");
spiderDTO.setProcessor("com.ecspider.common.processor.JDProcessor");
spiderDTO.setDownloader("com.ecspider.common.downloader.SeleniumDownloader");
spiderDTO.setPipeline("com.ecspider.common.pipeline.JDPipeline");
ArrayList<String> urls = new ArrayList<>();
urls.add(getRootUrl(fields.getKeyword(), Integer.parseInt(fields.getStartPage())));
spiderDTO.setUrls(urls);
return spiderManageService.createSpider(spiderDTO);
}
private String getRootUrl(String keyword, int startPage) {
String url;
url = UrlUtil.addParamToUrl(BASE_URL, "keyword", keyword);
url = UrlUtil.addParamToUrl(url, "wq", keyword);
url = UrlUtil.addParamToUrl(url, "page", String.valueOf(startPage * 2 - 1));
if (startPage == 1) {
url = UrlUtil.addParamToUrl(url, "s", String.valueOf(1));
} else {
url = UrlUtil.addParamToUrl(url, "s", String.valueOf(56 + 60 * (startPage - 2)));
}
url = UrlUtil.addParamToUrl(url, "click", "0");
return url;
}
}
|
package com.example.fibonacci;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
LinearLayout scrollRes;
int fibCalc = 1;
int fibAct=1;
int fibAnt=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scrollRes = findViewById(R.id.linearLayout);
fibCalc = Integer.valueOf(getIntent().getStringExtra("limite"));
for ( int i = 0; i<fibCalc; i++)
{
/*String actual = (String) resultados.getText();*/
TextView nuevo = new TextView(getBaseContext());
fibAct = fibAct + fibAnt;
fibAnt = fibAct - fibAnt;
nuevo.setText("" + fibAct);
//resultados.setText(actual);
scrollRes.addView(nuevo);
}
}
}
|
package com.zitiger.plugin.xdkt.setter.generator;
import com.intellij.psi.PsiVariable;
import org.jetbrains.annotations.NotNull;
public interface SetterGenerator {
void generate(@NotNull PsiVariable element);
}
|
package views;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.border.BevelBorder;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
public class HighScoreFrame implements ActionListener {
/** Frame d'affichage. */
private static JFrame frame;
/** Liste des noms des colonnes du tableau. */
@SuppressWarnings("unused")
private static String[] names;
/** Tableau contenant tous les meilleurs scores. */
private Object[][] data;
/** Le nombre de scores enregistres. (entre 0 et 5). */
private int nbHightScore;
/** Le fichier d'acces du fichier des meilleurs */
private final static String nomFichier = "best-scores.txt";
/** La colonne d'insertion d'un nouveau score. */
private int colNewScore;
/** La ligne d'insertion d'un nouveau score. */
private int ligneNewScore;
/** Le score a sauvegarder. */
private int score;
/** Le niveau atteint. */
private int niveau;
/** Le nombre de lignes. */
private int ligne;
/** La ligne d'insertion. */
private int ligneInsertion;
/**
* Surcharge du constructeur. Utilise pour inserer un score dans la table.
* param score Le score que l'on va inserer. param niveau Le niveau atteint
* par le joueur param ligne Le nombre de lignes remplies.
*/
public HighScoreFrame() {
/* Declaration de la fenetre. */
frame = new JFrame("Meilleurs scores");
frame.setSize(582, 267);
/* Gestion de la croix de fermeture de la frame. */
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
frame.dispose();
}
});
/* Aucun score enregistre pour le moment. */
nbHightScore = 0;
/*
* Initialisation des donnees a partir d'un fichier. Remplissage du
* tableau.
*/
final String[] names = { "Rang", "Nom", "Score", "Ligne", "Niveau" };
data = new Object[5][5];
initData();
/* On teste si le score merite d'etre enregistre dans la table. */
ligneInsertion = testScore(score);
/* Creation d'un modele pour la base. */
TableModel dataModel = new AbstractTableModel() {
/**
*
*/
private static final long serialVersionUID = 1L;
/* Surcharge obligatoire des methodes de la TableModel. */
public int getColumnCount() { // Renvoie le nombre de colonnes.
return names.length;
}
public int getRowCount() { // Renvoie le nombre de lignes.
return data.length;
}
public Object getValueAt(int row, int col) { // Renvoie une valeur
// de la table.
return data[row][col];
}
/* Surcharge d'autres methodes. */
public String getColumnName(int column) { // Renvoie le nom d'une
// colonne.
return names[column];
}
public Class<? extends Object> getColumnClass(int c) { // Renvoie la
// class
// d'un
// objet
// d'une
// colonne.
return getValueAt(0, c).getClass();
}
public boolean isCellEditable(int row, int col) { // Indique si on
// peut ecrire
// dans la
// table.
return false; // Ici on ne peut pas...
}
public void setValueAt(Object aValue, int row, int column) { // Insertion
// d'une
// valeur.
data[row][column] = aValue;
saveFichier(); // Sauvegarde du nouveau tableau dans un fichier.
}
};
/* Creation de la table. */
JTable tableView = new JTable(dataModel);
tableView.editCellAt(1, 3);
/* Ecrit le score en rouge. */
TableColumn numbersColumn = tableView.getColumn("Score");
DefaultTableCellRenderer numberColumnRenderer = new DefaultTableCellRenderer() {
/**
*
*/
private static final long serialVersionUID = 1L;
public void setValue(Object value) {
@SuppressWarnings("unused")
int cellValue = (value instanceof Number) ? ((Number) value)
.intValue() : 0;
setForeground(Color.red);
setText((value == null) ? "" : value.toString());
}
};
numberColumnRenderer.setHorizontalAlignment(JLabel.CENTER);
numbersColumn.setCellRenderer(numberColumnRenderer);
numbersColumn.sizeWidthToFit();
/* Insertion du tout dans un panel. */
JScrollPane scrollpane = new JScrollPane(tableView);
scrollpane.setBorder(new BevelBorder(BevelBorder.LOWERED));
scrollpane.setBounds(61, 65, 430, 105);
/* Insertion du tout dans un panel. */
JPanel panel = new JPanel();
panel.setLayout(null);
panel.setBackground(new java.awt.Color(189, 211, 211));
panel.add(scrollpane);
/* Creation d'un label. */
JLabel label = new JLabel("MEILLEURS SCORES : ");
label.setBounds(122, 15, 333, 27);
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setForeground(Color.red);
label.setFont(new Font("dialog", 1, 18));
panel.add(label);
/* Creation d'un bouton. */
JButton boutonOk = new JButton("Ok !!");
boutonOk.setBounds(242, 190, 98, 25);
panel.add(boutonOk);
boutonOk.addActionListener(this);
/* On place le tout dans la fenetre. */
frame.getContentPane().add(panel);
frame.setVisible(true);
}
/**
* Surcharge du constructeur.
* <P>
* Utilise pour inserer un score dans la table.
*
* @param score
* Le score que l'on va inserer.
* @param niveau
* Le niveau atteint par le joueur
* @param ligne
* Le nombre de lignes remplies.
*/
public HighScoreFrame(int score, int niveau, int ligne) {
this.score = score;
this.niveau = niveau;
this.ligne = ligne;
/* Declaration de la fenetre. */
frame = new JFrame("Meilleurs scores");
frame.setSize(582, 267);
/* Gestion de la croix de fermeture de la frame. */
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
frame.dispose();
}
});
/* Aucun score enregistre pour le moment. */
nbHightScore = 0;
/*
* Initialisation des donnees a partir d'un fichier. Remplissage du
* tableau.
*/
final String[] names = { "Rang", "Nom", "Score", "Ligne", "Niveau" };
data = new Object[5][5];
initData();
/* On teste si le score merite d'etre enregistre dans la table. */
ligneInsertion = testScore(score);
/* Creation d'un modele pour la base. */
TableModel dataModel = new AbstractTableModel() {
/**
*
*/
private static final long serialVersionUID = 1L;
/* Surcharge obligatoire des methodes de la TableModel. */
public int getColumnCount() { // Renvoie le nombre de colonnes.
return names.length;
}
public int getRowCount() { // Renvoie le nombre de lignes.
return data.length;
}
public Object getValueAt(int row, int col) { // Renvoie une valeur
// de la table.
return data[row][col];
}
/* Surcharge d'autres methodes. */
public String getColumnName(int column) { // Renvoie le nom d'une
// colonne.
return names[column];
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public Class getColumnClass(int c) { // Renvoie la class d'un objet
// d'une colonne.
return getValueAt(0, c).getClass();
}
public boolean isCellEditable(int row, int col) { // Indique si on
// peut ecrire
// dans la
// table.
// On est sur le nom de la nouvelle personne enregistree.
// Donc on peut ecrire
// Dans tous les autres cas, non.
return (row == getLigneInsertion()) && (col == 1);
}
public void setValueAt(Object aValue, int row, int column) { // Insertion
// d'une
// valeur.
data[row][column] = aValue;
saveFichier(); // Sauvegarde du nouveau tableau dans un fichier.
}
};
/* Creation de la table. */
JTable tableView = new JTable(dataModel);
tableView.editCellAt(1, 3);
/* Ecrit le score en rouge. */
TableColumn numbersColumn = tableView.getColumn("Score");
DefaultTableCellRenderer numberColumnRenderer = new DefaultTableCellRenderer() {
/**
*
*/
private static final long serialVersionUID = 1L;
public void setValue(Object value) {
@SuppressWarnings("unused")
int cellValue = (value instanceof Number) ? ((Number) value)
.intValue() : 0;
setForeground(Color.red);
setText((value == null) ? "" : value.toString());
}
};
numberColumnRenderer.setHorizontalAlignment(JLabel.CENTER);
numbersColumn.setCellRenderer(numberColumnRenderer);
numbersColumn.sizeWidthToFit();
/* Insertion du tout dans un panel. */
JScrollPane scrollpane = new JScrollPane(tableView);
scrollpane.setBorder(new BevelBorder(BevelBorder.LOWERED));
scrollpane.setBounds(61, 65, 430, 105);
/* Insertion du tout dans un panel. */
JPanel panel = new JPanel();
panel.setLayout(null);
panel.setBackground(new java.awt.Color(189, 211, 211));
panel.add(scrollpane);
/* Creation d'un label. */
JLabel label = new JLabel("MEILLEURS SCORES : ");
label.setBounds(122, 15, 333, 27);
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setForeground(Color.red);
label.setFont(new Font("dialog", 1, 18));
panel.add(label);
/* Creation d'un bouton. */
JButton boutonOk = new JButton("Ok");
boutonOk.setBounds(242, 190, 98, 25);
panel.add(boutonOk);
boutonOk.addActionListener(this);
/* On place le tout dans la fenetre. */
frame.getContentPane().add(panel);
frame.setVisible(true);
}
/**
* Ecouteur du bouton Ok.
*
* @param e
* Evenement genere par le bouton Ok.
* @see java.awt.event.ActionListener#actionPerformed(ActionEvent)
*/
public void actionPerformed(ActionEvent e) {
frame.dispose(); // On ferme la fenetre.
}
/**
* Renvoie la colonne ou doit se faire l'insertion.
*
* @return La colonne d'insertion.
*/
public int getColNewScore() {
return colNewScore;
}
/**
* Renvoie la ligne ou doit se faire l'insertion.
*
* @return La ligne d'insertion.
*/
public int getLigneInsertion() {
return ligneInsertion;
}
/**
* Renvoie la ligne du nouveau score.
*
* @return La ligne du nouveau score.
*/
public int getLigneNewScore() {
return ligneNewScore;
}
/**
* Initialisation du tableau de la table a partir d'un fichier.
*/
public void initData() {
FileReader fic = null; // Le fichier de lecture.
String sentence; // La phrase lue dans le fichier.
BufferedReader br = null;
@SuppressWarnings("unused")
String f = null;
try { // Lecture du fichier.
fic = new FileReader(nomFichier);
} catch (IOException e) {
try {
FileWriter fw = new FileWriter(nomFichier);
PrintWriter pw = new PrintWriter(fw);
pw.print("");
pw.close();
fic = new FileReader(nomFichier);
} catch (IOException error) {
System.err.println("Erreur d'ouverture de fichier. ");
}
}
try {
/* On bufferise le flux de lecture. */
br = new BufferedReader(fic);
// On essaie de lire une premiere ligne. */
sentence = br.readLine();
} catch (IOException e) {
sentence = null;
}
while (sentence != null) { // La phrase n'est pas nulle : on peut la
// traiter...
StringTokenizer st = new StringTokenizer(sentence, " "); // On
// cherche
// les
// espaces.
for (int i = 0; i < 5; i++) {
data[nbHightScore][i] = st.nextToken(); // Le premier jeton.
}
nbHightScore++; // Il y a une ligne de plus...
try { // On essaie de lire une autre ligne.
sentence = br.readLine();
} catch (IOException e) {
sentence = null;
}
}
try { // On ferme le fichier.
br.close();
} catch (IOException e) {
System.out
.println("Impossible de fermer le fichier est déjà ouvert");
}
}
/**
* Sauvegarde des donnees dans un fichier.
*/
public void saveFichier() {
FileWriter fw = null;
boolean finFichier = false;
PrintWriter pw = null;
try { // On ouvre le fichier en ecriture.
fw = new FileWriter(nomFichier);
/* On formate le flux d'ecriture. */
pw = new PrintWriter(fw);
} catch (IOException e) {
System.out.println("Ecriture impossible");
}
/* On remplit le fichier. */
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (data[i][j] != null) {
pw.print(data[i][j] + " ");
} else {
finFichier = true;
}
}
if (finFichier == false) {
pw.println("1 System 0 0 0");
}
}
/* On ferme le fichier. */
try {
fw.close();
} catch (IOException e) {
System.out.println("Erreur lors de la fermeture du fichier.");
}
}
/**
* Teste si un score merite d'etre sauvegarder ie est dans les 5 premiers.
*
* @param score
* Le score qu'il faut inserer.
* @return -1 si le score n'est pas enregistre.
*/
public int testScore(int score) {
for (int i = 0; i < 4; i++) { // Pour chaque ligne,
String scoreTeste = (String) data[i][2];
/* On compare le score enregistre avec le score teste. */
if ((scoreTeste == null)
|| (new Integer(scoreTeste).intValue() < score)) { // Un
// best
// Score
// !!
/* On decale le tableau. */
for (int j = 4; j > i; j--) {
for (int k = 0; k < 5; k++) {
if ((k == 0) && (data[j - 1][0] != null)) {
int rang = new Integer((String) data[j - 1][0])
.intValue() + 1;
data[j][k] = new String("" + rang);
} else {
data[j][k] = data[j - 1][k];
}
}
}
int rang = i + 1;
/* On initialise la ligne nouvellement creee. */
data[i][0] = new String("" + rang);
data[i][1] = new String("?NOM?");
data[i][2] = new String("" + score);
data[i][3] = new String("" + ligne);
data[i][4] = new String("" + niveau);
return i; // La ligne d'insertion.
}
}
return -1; // Pas d'insertion.
}
}
|
package com.wapa5pow.freettsplugin;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.text.TextUtils;
import android.util.Log;
import com.unity3d.player.UnityPlayer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
class TtsManager implements TextToSpeech.OnInitListener {
private final String TAG = "TtsManager";
private static final TtsManager instance = new TtsManager();
private TextToSpeech tts;
static TtsManager getInstance() {
return instance;
}
void initialize(Context context) {
tts = new TextToSpeech(context, this);
tts.setOnUtteranceProgressListener(new UtteranceProgressListener()
{
@Override
public void onStart(String utteranceId)
{
Log.d(TAG, "progress on Start " + utteranceId);
UnityPlayer.UnitySendMessage("FreeTtsManager", "OnCallBack", "start");
}
@Override
public void onDone(String utteranceId)
{
Log.d(TAG, "progress on Done " + utteranceId);
UnityPlayer.UnitySendMessage("FreeTtsManager", "OnCallBack", "finish");
}
@Override
public void onError(String utteranceId)
{
Log.d(TAG, "progress on Error " + utteranceId);
UnityPlayer.UnitySendMessage("FreeTtsManager", "OnCallBack", "finish");
}
@Override
public void onStop(String utteranceId, boolean interrupted)
{
Log.d(TAG, "progress on Stop " + utteranceId);
UnityPlayer.UnitySendMessage("FreeTtsManager", "OnCallBack", "cancel");
}
});
}
@Override
public void onInit(int status) {
if (TextToSpeech.SUCCESS == status) {
List<String> languages = new ArrayList<>();
for (Locale locale : Locale.getAvailableLocales()) {
if (tts.isLanguageAvailable(locale) > 0) {
languages.add(toBcp47Language(locale));
}
}
Collections.sort(languages);
UnityPlayer.UnitySendMessage(
"TtsForm", "AddLanguageButtons", TextUtils.join(",", languages));
} else {
Log.d(TAG, "Error init");
}
}
void speechText(String text, String language, float rate, float pitch) {
if (0 < text.length()) {
tts.setSpeechRate(rate);
tts.setPitch(pitch);
tts.setLanguage(getLocal(language));
if (tts.isSpeaking()) {
tts.stop();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ttsGreater21(text);
} else {
ttsUnder20(text);
}
}
}
void stop() {
tts.stop();
}
private Locale getLocal(String local) {
Locale locale;
try {
String[] localStrings = local.split("-");
locale = new Locale(localStrings[0], localStrings[1]);
} catch (Exception e) {
locale = new Locale("en", "US");
}
return locale;
}
@SuppressWarnings("deprecation")
private void ttsUnder20(String text) {
String utteranceId = this.hashCode() + "";
HashMap<String, String> params = new HashMap<>();
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, utteranceId);
tts.speak(text, TextToSpeech.QUEUE_FLUSH, params);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void ttsGreater21(String text) {
String utteranceId = this.hashCode() + "";
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, utteranceId);
}
/**
* Modified from:
* https://github.com/apache/cordova-plugin-globalization/blob/master/src/android/Globalization.java
*
* Returns a well-formed ITEF BCP 47 language tag representing this locale string
* identifier for the client's current locale
*
* @return String: The BCP 47 language tag for the current locale
*/
public static String toBcp47Language(Locale loc) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
return loc.toLanguageTag();
}
// we will use a dash as per BCP 47
final char SEP = '-';
String language = loc.getLanguage();
String region = loc.getCountry();
String variant = loc.getVariant();
// special case for Norwegian Nynorsk since "NY" cannot be a variant as per BCP 47
// this goes before the string matching since "NY" wont pass the variant checks
if (language.equals("no") && region.equals("NO") && variant.equals("NY")) {
language = "nn";
region = "NO";
variant = "";
}
if (language.isEmpty() || !language.matches("\\p{Alpha}{2,8}")) {
language = "und"; // Follow the Locale#toLanguageTag() implementation
// which says to return "und" for Undetermined
} else if (language.equals("iw")) {
language = "he"; // correct deprecated "Hebrew"
} else if (language.equals("in")) {
language = "id"; // correct deprecated "Indonesian"
} else if (language.equals("ji")) {
language = "yi"; // correct deprecated "Yiddish"
}
// ensure valid country code, if not well formed, it's omitted
if (!region.matches("\\p{Alpha}{2}|\\p{Digit}{3}")) {
region = "";
}
// variant subtags that begin with a letter must be at least 5 characters long
if (!variant.matches("\\p{Alnum}{5,8}|\\p{Digit}\\p{Alnum}{3}")) {
variant = "";
}
StringBuilder bcp47Tag = new StringBuilder(language);
if (!region.isEmpty()) {
bcp47Tag.append(SEP).append(region);
}
if (!variant.isEmpty()) {
bcp47Tag.append(SEP).append(variant);
}
return bcp47Tag.toString();
}
}
|
package com.supconit.kqfx.web.service.data;
import hc.business.dic.services.DataDictionaryService;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.tempuri.dag_xsd.Service_wsdl.ServiceLocator;
import org.tempuri.dag_xsd.Service_wsdl.ServiceStub;
import com.supconit.kqfx.web.fxzf.search.entities.Fxzf;
import com.supconit.kqfx.web.fxzf.search.services.FxzfSearchService;
import com.supconit.kqfx.web.fxzf.warn.entities.Config;
import com.supconit.kqfx.web.fxzf.warn.services.ConfigService;
import com.supconit.kqfx.web.util.DictionaryUtil;
import com.supconit.kqfx.web.util.SysConstants;
@Component("KQFX_DATA_TRASPORT")
public class DataTransportThread implements Runnable {
private static final Logger logger = LoggerFactory.getLogger(DataTransportThread.class);
@Autowired
private FxzfSearchService fxzfSearchService;
@Autowired
private DataWebServiceImpl dataWebServiceImpl;
@Autowired
private DataDictionaryService dataDictionaryService;
@Autowired
private ConfigService configService;
@Value("${WebService.data}")
private String url;
@Override
public void run() {
while (true){
try{
List<Fxzf> Fxzfs = fxzfSearchService.getFxzfToTransport();
HashMap<String, String> stationMap = DictionaryUtil.dictionary("STATIONNAME",dataDictionaryService);
if(Fxzfs.size()>0){
/**
* 获取长宽高
*/
Double length = configService.getByCode(SysConstants.LENGTH).getValue();
Double width = configService.getByCode(SysConstants.WIDTH).getValue();
Double height = configService.getByCode(SysConstants.HEIGHT).getValue();
ServiceLocator serviceLocator = new ServiceLocator();
java.net.URL wsdl= new java.net.URL(url);
ServiceStub serviceStub = new ServiceStub(wsdl,serviceLocator);
for(Fxzf fxzf : Fxzfs){
logger.info("================有数据需要被传送================");
if(dataWebServiceImpl.tranferData(fxzf,serviceStub,stationMap,length,width,height)){
fxzf.setTransport(1);
fxzf.setTransportTime(new Date());
fxzfSearchService.upDateFxzftransport(fxzf);
}
}
}else{
Thread.sleep(5000);
}
}catch(Exception e){
e.printStackTrace();
}
}
}
}
|
package Building;
public interface Floor {
public int getNumberOfSpaces();
public int getNumberRoomsOfSpaces();
public double getTotalArea();
public Space[] getSpacesArray();
public Space getSpaceByNum(int number);
public void changeSpace(int number, Space newSpace);
public void addNewSpace(int number);
public void deleteSpace(int number);
public Space getBestSpace();
public void addFitSpace(int number, Space newSpace);
java.util.Iterator iterator();
public Object clone();
}
|
package com.gabriel.paiva.cursomc.cursomc.services;
import com.gabriel.paiva.cursomc.cursomc.domains.*;
import com.gabriel.paiva.cursomc.cursomc.enums.EstadoPagamento;
import com.gabriel.paiva.cursomc.cursomc.exceptions.AuthorizationException;
import com.gabriel.paiva.cursomc.cursomc.exceptions.ObjectNotFoundException;
import com.gabriel.paiva.cursomc.cursomc.repositories.ItemPedidoRepository;
import com.gabriel.paiva.cursomc.cursomc.repositories.PagamentoRepository;
import com.gabriel.paiva.cursomc.cursomc.repositories.PedidoRepository;
import com.gabriel.paiva.cursomc.cursomc.security.UserSS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.Optional;
@Service
public class PedidoService {
@Autowired
private PedidoRepository pedidoRepository;
@Autowired
private ProdutoService produtoService;
@Autowired
private PagamentoRepository pagamentoRepository;
@Autowired
private BoletoService boletoService;
@Autowired
private ItemPedidoRepository itemPedidoRepository;
@Autowired
private ClienteService clienteService;
public Pedido buscar (Integer id){
Optional<Pedido> pedido = pedidoRepository.findById(id);
return pedido.orElseThrow(() ->
new ObjectNotFoundException("Objeto com ID (" + id + ") não encontrado.")
);
}
@Transactional
public Pedido insert(Pedido pedido){
pedido.setId(null);
pedido.setInstante(new Date());
pedido.getPagamento().setPedido(pedido);
pedido.getPagamento().setEstadoPagamento(EstadoPagamento.PENDENTE);
if(pedido.getPagamento() instanceof PagamentoComBoleto){
PagamentoComBoleto pagamentoComBoleto = (PagamentoComBoleto) pedido.getPagamento();
boletoService.preencherPagamentoComBoleto(pagamentoComBoleto, pedido.getInstante());
}
pedido = pedidoRepository.save(pedido);
pagamentoRepository.save(pedido.getPagamento());
//inserir os itens
for(ItemPedido itemPedido : pedido.getItens()) {
itemPedido.setDesconto(0d);
itemPedido.setPedido(pedido);
itemPedido.setPreco(produtoService.buscar(itemPedido.getProduto().getId()).getPreco());
}
itemPedidoRepository.saveAll(pedido.getItens());
return pedido;
}
public Page<Pedido> findPage(UserSS userSS, Integer page, Integer linesPerPage, String orderBy, String direction){
if(userSS == null){
throw new AuthorizationException("Access denied");
}
Cliente cliente = clienteService.find(userSS.getId());
PageRequest pageRequest = PageRequest.of(page,linesPerPage, Sort.Direction.valueOf(direction),orderBy);
return pedidoRepository.findByCliente(cliente,pageRequest);
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.cmsfacades.restrictions.populator.data;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.when;
import de.hybris.bootstrap.annotations.UnitTest;
import de.hybris.platform.catalog.model.CatalogVersionModel;
import de.hybris.platform.cms2.model.restrictions.AbstractRestrictionModel;
import de.hybris.platform.cms2.servicelayer.services.admin.CMSAdminSiteService;
import de.hybris.platform.core.model.ItemModel;
import de.hybris.platform.core.model.type.ComposedTypeModel;
import de.hybris.platform.servicelayer.type.TypeService;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
@UnitTest
@RunWith(MockitoJUnitRunner.class)
public class RestrictionSearchByNamedQueryDataPopulatorTest
{
private static final String TEST_TYPECODE = "TestTypeCode";
@InjectMocks
private RestrictionSearchByNamedQueryDataPopulator populator;
@Mock
private TypeService typeService;
@Mock
private CMSAdminSiteService adminSiteService;
@Mock
private CatalogVersionModel catalogVersion;
@Mock
private ComposedTypeModel composedTypeModel;
@Before
public void setUp()
{
when(adminSiteService.getActiveCatalogVersion()).thenReturn(catalogVersion);
when(typeService.getComposedTypeForCode(TEST_TYPECODE)).thenReturn(composedTypeModel);
doThrow(new IllegalArgumentException()).when(typeService).getComposedTypeForCode(null);
}
@Test
public void shouldConvertParameters()
{
final Map<String, ?> map = populator.convertParameters("name:help,typeCode:TestTypeCode");
assertThat(map.get(AbstractRestrictionModel.CATALOGVERSION), equalTo(catalogVersion));
assertThat(map.get(AbstractRestrictionModel.NAME), equalTo("%help%"));
assertThat(map.get(ItemModel.ITEMTYPE), equalTo(composedTypeModel));
}
@Test
public void shouldConvertParametersWithEmptyNameValue()
{
final Map<String, ?> map = populator.convertParameters("name:,typeCode:TestTypeCode");
assertThat(map.get(AbstractRestrictionModel.CATALOGVERSION), equalTo(catalogVersion));
assertThat(map.get(AbstractRestrictionModel.NAME), equalTo("%%"));
assertThat(map.get(ItemModel.ITEMTYPE), equalTo(composedTypeModel));
}
@Test(expected = IllegalArgumentException.class)
public void shouldConvertParametersWithEmptyParams()
{
// typeCode cannot be null
populator.convertParameters("");
}
}
|
package com.companyname.bank;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
String killedKenny = Util.killChar("Kenny");
String testKill = "A meteor comes crashing from the heavens, impacting on Kenny's head!";
assertTrue( testKill.equals(killedKenny) );
}
}
|
package com.uwetrottmann.trakt5.entities;
import com.uwetrottmann.trakt5.enums.Rating;
import org.threeten.bp.OffsetDateTime;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.List;
public class SyncSeason {
public Integer number;
public List<SyncEpisode> episodes;
public OffsetDateTime collected_at;
public OffsetDateTime watched_at;
public OffsetDateTime rated_at;
public Rating rating;
@Nonnull
public SyncSeason number(int number) {
this.number = number;
return this;
}
@Nonnull
public SyncSeason episodes(List<SyncEpisode> episodes) {
this.episodes = episodes;
return this;
}
@Nonnull
public SyncSeason episodes(SyncEpisode episode) {
ArrayList<SyncEpisode> list = new ArrayList<>(1);
list.add(episode);
return episodes(list);
}
@Nonnull
public SyncSeason collectedAt(OffsetDateTime collectedAt) {
this.collected_at = collectedAt;
return this;
}
@Nonnull
public SyncSeason watchedAt(OffsetDateTime watchedAt) {
this.watched_at = watchedAt;
return this;
}
@Nonnull
public SyncSeason ratedAt(OffsetDateTime ratedAt) {
this.rated_at = ratedAt;
return this;
}
@Nonnull
public SyncSeason rating(Rating rating) {
this.rating = rating;
return this;
}
}
|
package com.jokeit.domain;
import javax.persistence.*;
@Entity
@Table(name = "feedback")
public class Feedback {
@Id
@GeneratedValue
private Integer id;
@Column(name = "assessment")
private Integer assessment;
@Column(name = "comment")
private String comment;
@ManyToOne
@JoinColumn(name = "joke_id", referencedColumnName = "id")
private Joke joke;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getAssessment() {
return assessment;
}
public void setAssessment(Integer assessment) {
this.assessment = assessment;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public Joke getJoke() {
return joke;
}
public void setJoke(Joke joke) {
this.joke = joke;
}
}
|
import java.util.LinkedList;
import java.util.Queue;
public class TestQueueException {
public static void main(String[] args) throws IllegalStateException {
Queue<Integer> queue = new LinkedList<>();
queue.add(753434);
queue.add(435343);
queue.add(2147483647);
try{
queue.add(10);
}
catch(Exception e){
System.out.println("Exception: " + e);
}
System.out.println("Queue: " + queue);
}
}
|
package Tests;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import dataStructures.*;
class StackTest {
private Stack<Integer> stack;
private void setupEscenario() {
stack = new Stack<Integer>();
Node q1 = new Node(1);
Node q2 = new Node(2);
Node q3 = new Node(3);
stack.push(q1);
stack.push(q2);
stack.push(q3);
}
private void setupEscenario1() {
stack = new Stack<Integer>();
}
private void setupEscenario2() {
stack = new Stack<Integer>();
Node q1 = new Node(1);
stack.push(q1);
}
//------------------------------------------------------------------------------------------------------------
@Test
void test() {
setupEscenario();
assertEquals(stack.peek().getInfo(),3);
}
@Test
void testPeek() {
setupEscenario1();
assertEquals(stack.peek(),null);
}
@Test
void testPeek1() {
setupEscenario2();
assertEquals(stack.peek().getInfo(),1);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
@Test
void testPopStack() {
setupEscenario();
stack.pop();
assertEquals(stack.peek().getInfo(),2);
}
@Test
void testPopStack1() {
setupEscenario1();
stack.pop();
assertEquals(stack.peek(),null);
}
@Test
void testPopStack2() {
setupEscenario2();
stack.pop();
assertEquals(stack.peek(),null);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
@Test
void testIsEmpty(){
setupEscenario1();
assertTrue(stack.isEmpty(),"Esta lleno");
}
@Test
void testIsEmpty1() {
setupEscenario();
assertFalse(stack.isEmpty(),"Esta vacio");
}
@Test
void testIsEmpty2() {
setupEscenario2();
assertFalse(stack.isEmpty(),"Esta vacio");
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
@Test
void testPushStack() {
setupEscenario();
Node q1 = new Node(5);
stack.push(q1);
assertEquals(stack.peek().getInfo(),5);
}
@Test
void testPushStack1() {
setupEscenario1();
Node q1 = new Node(1);
stack.push(q1);
assertEquals(stack.peek().getInfo(),1);
}
@Test
void testPushStack2() {
setupEscenario2();
Node q1 = new Node(2);
stack.push(q1);
assertEquals(stack.peek().getInfo(),2);
}
//------------------------------------------------------------------------------------------------------------
}
|
package ru.ermakovis.simpleStorage.client;
import io.netty.handler.codec.serialization.ObjectDecoderInputStream;
import io.netty.handler.codec.serialization.ObjectEncoderOutputStream;
import java.io.IOException;
import java.net.Socket;
public class Network {
private final Socket socket;
private final ObjectEncoderOutputStream output;
private final ObjectDecoderInputStream input;
public Network(String serverAddress, int port) throws IOException {
socket = new Socket(serverAddress, port);
output = new ObjectEncoderOutputStream(socket.getOutputStream());
input = new ObjectDecoderInputStream(socket.getInputStream());
}
public void sendMessage(Object msg) throws IOException {
output.writeObject(msg);
}
public Object receiveMessage() throws IOException, ClassNotFoundException {
return input.readObject();
}
public void stop() {
try {
output.close();
input.close();
socket.close();
} catch (Exception ignored) {
}
}
}
|
package com.jlgproject.model;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.List;
/**
* Created by sunbeibei on 2017/6/27.
*/
public class Share_Informations implements Serializable {
/**
* state : ok
* message : 查询股权成功
* data : {"pageNum":1,"total":1,"items":[{"@id":"1","createUser":null,"updateUser":null,"createTime":1498622129836,"updateTime":1498622129836,"isDeleted":false,"deleteReason":0,"unAuth":false,"zid":1,"userId":1192,"shareholderName":"杨洋洋","shareholderCode":"258159988494","address":"北京","amount":580884976495,"proportion":"20","registeredCapital":"50000","actualCapital":"800000","id":1715}]}
*/
private String state;
private String message;
private DataBean data;
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public DataBean getData() {
return data;
}
public void setData(DataBean data) {
this.data = data;
}
public static class DataBean {
/**
* pageNum : 1
* total : 1
* items : [{"@id":"1","createUser":null,"updateUser":null,"createTime":1498622129836,"updateTime":1498622129836,"isDeleted":false,"deleteReason":0,"unAuth":false,"zid":1,"userId":1192,"shareholderName":"杨洋洋","shareholderCode":"258159988494","address":"北京","amount":580884976495,"proportion":"20","registeredCapital":"50000","actualCapital":"800000","id":1715}]
*/
private int pageNum;
private int total;
private List<ItemsBean> items;
public int getPageNum() {
return pageNum;
}
public void setPageNum(int pageNum) {
this.pageNum = pageNum;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public List<ItemsBean> getItems() {
return items;
}
public void setItems(List<ItemsBean> items) {
this.items = items;
}
public static class ItemsBean {
@SerializedName("@id")
private String _$Id196; // FIXME check this code
private Object createUser;
private Object updateUser;
private long createTime;
private long updateTime;
private boolean isDeleted;
private int deleteReason;
private boolean unAuth;
private int zid;
private int userId;
private String shareholderName;
private String shareholderCode;
private String address;
private long amount;
private String proportion;
private String registeredCapital;
private String actualCapital;
private int id;
public String get_$Id196() {
return _$Id196;
}
public void set_$Id196(String _$Id196) {
this._$Id196 = _$Id196;
}
public Object getCreateUser() {
return createUser;
}
public void setCreateUser(Object createUser) {
this.createUser = createUser;
}
public Object getUpdateUser() {
return updateUser;
}
public void setUpdateUser(Object updateUser) {
this.updateUser = updateUser;
}
public long getCreateTime() {
return createTime;
}
public void setCreateTime(long createTime) {
this.createTime = createTime;
}
public long getUpdateTime() {
return updateTime;
}
public void setUpdateTime(long updateTime) {
this.updateTime = updateTime;
}
public boolean isIsDeleted() {
return isDeleted;
}
public void setIsDeleted(boolean isDeleted) {
this.isDeleted = isDeleted;
}
public int getDeleteReason() {
return deleteReason;
}
public void setDeleteReason(int deleteReason) {
this.deleteReason = deleteReason;
}
public boolean isUnAuth() {
return unAuth;
}
public void setUnAuth(boolean unAuth) {
this.unAuth = unAuth;
}
public int getZid() {
return zid;
}
public void setZid(int zid) {
this.zid = zid;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getShareholderName() {
return shareholderName;
}
public void setShareholderName(String shareholderName) {
this.shareholderName = shareholderName;
}
public String getShareholderCode() {
return shareholderCode;
}
public void setShareholderCode(String shareholderCode) {
this.shareholderCode = shareholderCode;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public long getAmount() {
return amount;
}
public void setAmount(long amount) {
this.amount = amount;
}
public String getProportion() {
return proportion;
}
public void setProportion(String proportion) {
this.proportion = proportion;
}
public String getRegisteredCapital() {
return registeredCapital;
}
public void setRegisteredCapital(String registeredCapital) {
this.registeredCapital = registeredCapital;
}
public String getActualCapital() {
return actualCapital;
}
public void setActualCapital(String actualCapital) {
this.actualCapital = actualCapital;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
}
}
|
package com.gtfs.service.impl;
import java.io.Serializable;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import com.gtfs.bean.DesignationMst;
import com.gtfs.dao.interfaces.DesignationMstDao;
import com.gtfs.service.interfaces.DesignationMstService;
@Service
public class DesignationMstServiceImpl implements DesignationMstService,Serializable{
@Autowired
private DesignationMstDao designationMstDao;
public List<DesignationMst> findAllActiveFromDesignationMst() {
return designationMstDao.findAllActiveFromDesignationMst();
}
public DesignationMst findById(Long designationId){
return designationMstDao.findById(designationId);
}
}
|
package com.io.spring;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection="student")
public class Student {
@Id
private int id;
private String age;
private String name;
private String phoneNo;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
@Override
public String toString() {
return "Student [id=" + id + ", age=" + age + ", name=" + name + ", phoneNo=" + phoneNo + "]";
}
public Student(int id, String age, String name, String phoneNo) {
super();
this.id = id;
this.age = age;
this.name = name;
this.phoneNo = phoneNo;
}
}
|
package edu.mayo.cts2.framework.webapp.rest.controller;
import java.util.Map;
public interface UrlTemplateBinder<R> {
public Map<String,String> getPathValues(R resource);
}
|
package com.yorkwang.model;
import com.jfinal.plugin.activerecord.Model;
public class UploadImage extends Model<UploadImage>{
public static final UploadImage dao = new UploadImage().dao();
public static final int TYPE_COMPANY_INFO = 1;
public static final int TYPE_TEMP = -1;
private boolean selected = false;
public boolean getSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
|
package com.design.pattern.observer;
/**
* @author zhangbingquan
* @desc 观察者接口
* @time 2019-09-14 18:53
*/
public interface Observer {
void update();
}
|
package org.sagebionetworks.table.cluster.search;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.sagebionetworks.table.query.util.ColumnTypeListMappings;
import org.sagebionetworks.util.ValidateArgument;
import org.springframework.stereotype.Component;
@Component
public class SimpleRowSearchProcessor implements RowSearchProcessor {
private static final String SEPARATOR = " ";
@Override
public String process(List<TypedCellValue> data) {
ValidateArgument.required(data, "data");
StringBuilder output = new StringBuilder();
for (TypedCellValue rawValue : data) {
String value = rawValue.getRawValue();
if (StringUtils.isBlank(value)) {
continue;
}
if (ColumnTypeListMappings.isList(rawValue.getColumnType())) {
List<String> multiValues = new JSONArray(value).toList().stream()
.map(obj -> obj == null ? null : obj.toString().trim())
.filter(str -> !StringUtils.isBlank(str))
.collect(Collectors.toList());
output.append(String.join(SEPARATOR, multiValues)).append(SEPARATOR);
} else {
output.append(value.trim()).append(SEPARATOR);
}
}
return StringUtils.trimToNull(output.toString());
}
}
|
package pl.edu.agh.to.lab4.searching;
import pl.edu.agh.to.lab4.suspects.Suspect;
public interface SearchStrategy {
boolean filter(Suspect suspect);
}
|
package com.lec.ex1_inputStreamOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
//1. stream객체 생성(inputStream,outputStream) 2.읽고쓰기(반복) 3.stream닫기
public class Ex05_fileCopyStep1 {
public static void main(String[] args) {
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream("txtFile\\mamamoo.jpg"); // \만하면 해석하기 시작.기능의미 따라서 \\ //입력
os = new FileOutputStream("txtFile/mamamoo_copy.jpg"); // d:/big/ //출력
int cnt = 0; // 뒤 "번 반목문 실행 후 파일 복사 성공"를 위해 변수 선언
while (true) {
++cnt; // 반복문 실행
int i = is.read(); // 1byte
if (i == -1)
break;
os.write(i);
}
System.out.println(cnt + "번 반목문 실행 후 파일 복사 성공");
} catch (FileNotFoundException e) {
System.out.println("파일 이나 폴더 못 찾음" + e.getMessage());
} catch (IOException e) {
System.out.println("일고 쓸 때 예외남" + e.getMessage());
} finally {
try {
if (is != null)
is.close();
if (os != null)
os.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}// main
}// class
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.