text stringlengths 10 2.72M |
|---|
package ChatClient;
import javafx.application.Application;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.stage.Modality;
import javafx.stage.Stage;
import java.io.IOException;
import java.util.List;
public class NetworkClient extends Application {
public static final List<String> USERS_TEST_DATA = List.of("Vasya", "Masha", "Boris");
private Stage primaryStage;
private Stage authStage;
private Network network;
private ChatController chatController;
@Override
public void start(Stage primaryStage) throws Exception {
this.primaryStage = primaryStage;
network = new Network();
if(!network.connect()) {
showErrorMessage("Problems with connection", " ", "Error of connection to server");
return; }
openAuthWindow(); // открыть окно авторизации
createMainChatWindow();
}
private void openAuthWindow() throws IOException {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(NetworkClient.class.getResource("authView.fxml")); // здесь свое видео окно на аутентификацию
Parent root = loader.load();
authStage = new Stage();
authStage.setTitle("Авторизация");
authStage.initModality(Modality.WINDOW_MODAL);
authStage.initOwner(primaryStage);
Scene scene = new Scene(root);
authStage.setScene(scene);
authStage.show();
authController authController = loader.getController();
authController.setNetwork(network);
authController.setNetworkClient(this);
}
public void createMainChatWindow() throws IOException {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(NetworkClient.class.getResource("sample.fxml")); // из лоадера достаем вьюху
Parent root = loader.load();
primaryStage.setTitle("Messenger");
primaryStage.setScene(new Scene(root,600,400));
//primaryStage.show(); окно не должно создаваться по умолчанию
chatController = loader.getController();
chatController.setNetwork(network);
primaryStage.setOnCloseRequest(windowEvent -> network.close());
}
public static void showErrorMessage(String title, String message, String errorMessage) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle(title);
alert.setHeaderText(message);
alert.setContentText(errorMessage);
alert.showAndWait();
}
public static void main(String[] args) {
launch(args);
}
public void openMainChatWindow() {
authStage.close();
primaryStage.show();
primaryStage.setTitle(network.getUsername());
chatController.setUsernameTitle(network.getUsername());
network.waitMessage(chatController);
}
}
|
package com.codicesoftware.plugins.hudson.util;
import hudson.Util;
import hudson.util.FormValidation;
import java.util.regex.Pattern;
public class FormChecker {
private static final Pattern WORKSPACE_REGEX = Pattern.compile("^[^@#/:]+$");
private static final Pattern SELECTOR_REGEX = Pattern.compile(
"^(\\s*(rep|repository)\\s+\"(.*)\"(\\s+mount\\s+\"(.*)\")?(\\s+path\\s+"
+ "\"(.*)\"(\\s+norecursive)?(\\s+((((((branch|br)\\s+\"(.*)\")(\\s+(revno\\s+"
+ "(\"\\d+\"|LAST|FIRST)|changeset\\s+\"\\S+\"))?(\\s+(label|lb)\\s+\"(.*)\")?)|"
+ "(label|lb)\\s+\"(.*)\")(\\s+(checkout|co)\\s+\"(.*\"))?)|(branchpertask\\s+"
+ "\"(.*)\"(\\s+baseline\\s+\"(.*)\")?)|(smartbranch\\s+\"(.*)\"))))+\\s*)+$",
Pattern.MULTILINE|Pattern.CASE_INSENSITIVE);
private static final String DEFAULT_SELECTOR =
"repository \"default\"\n path \"/\"\n br \"/main\"\n co \"/main\"";
private static FormValidation doRegexCheck(final Pattern regex, final String noMatchText,
final String nullText, String value) {
value = Util.fixEmpty(value);
if (value == null)
return FormValidation.error(nullText);
if (regex.matcher(value).matches())
return FormValidation.ok();
return FormValidation.error(noMatchText);
}
public static FormValidation doCheckWorkspaceName(String value) {
return doRegexCheck(WORKSPACE_REGEX, "Workspace name should not include @, #, / or :",
"Workspace name is mandatory", value);
}
public static FormValidation doCheckSelector(String value) {
return doRegexCheck(SELECTOR_REGEX, "Selector is not in valid format",
"Selector is mandatory", value);
}
public static String getDefaultSelector() {
return DEFAULT_SELECTOR;
}
}
|
package com.longlysmile.service.impl;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.longlysmile.entity.AttackRecord;
import com.longlysmile.mapper.AttackRecordMapper;
import com.longlysmile.service.AttackRecordService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* TODO
*
* @author wujie
* @version 1.0
* @date 2021/4/26 22:36
*/
@Service
public class AttackRecordServiceImpl extends ServiceImpl<AttackRecordMapper, AttackRecord> implements AttackRecordService {
@Resource
private MailService mailService;
@Resource
private AttackRecordMapper mapper;
@Override
public void saveAndSend(AttackRecord attackRecord) {
try {
attackRecord.setCreateTime(LocalDateTime.now());
save(attackRecord);
mailService.sendMail("[" + attackRecord.getType() + "][" +
DateUtil.format(localDateTimeToDate(attackRecord.getCreateTime()), DatePattern.NORM_DATETIME_PATTERN) + "]" + attackRecord.getContent());
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public List<Map<String, String>> statistics() {
return mapper.statistics();
}
/**
* LocalDateTime转Date
*
* @param localDateTime LocalDateTime
* @return Date
*/
public static Date localDateTimeToDate(LocalDateTime localDateTime) {
try {
ZoneId zoneId = ZoneId.systemDefault();
ZonedDateTime zdt = localDateTime.atZone(zoneId);
return Date.from(zdt.toInstant());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
|
package elementfactory;
import elementfactory.base.Element;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.pagefactory.ElementLocator;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ElementHandler implements InvocationHandler {
private final ElementLocator locator;
private final Class<?> wrappingType;
public ElementHandler(ElementLocator locator, Class<?> interfaceType) {
this.locator = locator;
if (!Element.class.isAssignableFrom(interfaceType)) {
throw new RuntimeException("Interface not assignable to element");
}
wrappingType = ImplementedByProcessor.getWrapperClass(interfaceType);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
WebElement element;
try {
element = locator.findElement();
} catch (NoSuchElementException e) {
// return false instead of throwing NoSuChElement exception if calling method is isDisplayed()
if ("isDisplayed".equals(method.getName()) && method.getDeclaringClass().isAssignableFrom(Element.class)) {
return false;
}
if ("clickIfPresent".equals(method.getName())) {
return false;
}
if ("toString".equals(method.getName())) {
return "Proxy element for: " + locator.toString();
}
throw e;
}
Constructor<?> cons = wrappingType.getDeclaredConstructor(WebElement.class);
cons.setAccessible(true);
Object thing = cons.newInstance(element);
try {
return method.invoke(wrappingType.cast(thing), args);
} catch (InvocationTargetException e) {
// Unwrap the underlying exception
throw e.getCause();
}
}
}
|
package com.cts.resources;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.cts.beans.Login;
import com.cts.service.LoginService;
@RestController
@RequestMapping("/info")
public class LoginController {
@Autowired
LoginService service;
@RequestMapping("/login")
Login getLogin() {
return service.getLogin();
}
@RequestMapping("/all")
List<Object> getAllLogins(){
return service.getAllLogins();
}
}
|
package com.sarf.service;
import java.util.List;
import com.sarf.vo.Qna_BoardVO;
import com.sarf.vo.SearchCriteria;
public interface Qna_BoardService {
// 게시물 작성
public void write(Qna_BoardVO boardVO) throws Exception;
// 게시물 목록 조회
public List<Qna_BoardVO> list(SearchCriteria scri) throws Exception;
// 게시물 조회
public Qna_BoardVO read(int bno) throws Exception;
}
|
package com.perhab.napalm.implementations.interfaceImplementation;
import java.util.concurrent.Callable;
public class AnonymousInnerClass implements InterfaceImplementation {
@Override
public Integer add(Integer a, Integer b) throws Exception {
Callable<Integer> callable = new Callable<Integer>() {
@Override
public Integer call() throws Exception {
return a + b;
}
};
return callable.call();
}
}
|
/**
* DNet eBusiness Suite
* Copyright: 2010-2013 Nan21 Electronics SRL. All rights reserved.
* Use is subject to license terms.
*/
package net.nan21.dnet.module.bd.presenter.impl.contact.qb;
import net.nan21.dnet.core.presenter.action.query.QueryBuilderWithJpql;
import net.nan21.dnet.module.bd.presenter.impl.contact.model.CommunicationMethodTypeLov_Ds;
import net.nan21.dnet.core.api.session.Session;
public class CommunicationMethodTypeLov_DsQb
extends
QueryBuilderWithJpql<CommunicationMethodTypeLov_Ds, CommunicationMethodTypeLov_Ds, Object> {
@Override
public void setFilter(CommunicationMethodTypeLov_Ds filter) {
if (filter.getTargetType() == null || filter.getTargetType().equals("")) {
filter.setTargetType("N/A");
}
super.setFilter(filter);
}
}
|
package com.joyfulmath.calculator.houseloan;
import java.util.ArrayList;
import com.joyfulmath.calculator.R;
import com.joyfulmath.calculator.Engine.CaculaterEngine;
import com.joyfulmath.calculator.Engine.CalculaterEngineListener;
import com.joyfulmath.calculator.Engine.CaculaterEngine.EngineParams;
import com.joyfulmath.calculator.Engine.CaculaterEngine.EngineResultParam;
import com.joyfulmath.calculator.Engine.GeneralEngineType.MonthLoanResult;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
public class RealEstatentResultActivity extends Activity implements CalculaterEngineListener {
public final static String ACTION = "android.intent.action.calculater.realestatent.result";
public final static String KEY_RESULT = "result";
public final static String KEY_PARAM = "param";
private static final String TAG = "SuperCalculater.RealEstatentResultActivity";
public EngineResultParam mResult = null;
public EngineParams mParam = null;
private ListView mListView = null;
private RealResultAdapter mAdapter = null;
private RealHandle handle = null;
private LinearLayout mTitleLayout =null;
private ArrayList<ViewHolder> mViewHolder = null;
private TextView mLoanTotalView = null;
private TextView mRepayTotalView = null;
private TextView mLoanMonthView = null;
private TextView mTotalInterestView = null;
private TextView mRateView = null;
private TextView mFirstPayView = null;
private TextView mRateTitleView = null;
private ProgressDialog mProdialog = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "[onCreate]");
setContentView(R.layout.activity_realestatent_result);
Intent intent = this.getIntent();
Bundle bundle = intent.getExtras();
mParam = (EngineParams) bundle.getParcelable(KEY_PARAM);
mListView = (ListView) this.findViewById(R.id.list_result);
mAdapter = new RealResultAdapter(mResult, this);
handle = new RealHandle();
mListView.setAdapter(mAdapter);
mTitleLayout = (LinearLayout) this.findViewById(R.id.result_title);
mProdialog = new ProgressDialog(this);
StartCalculate(mParam);
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.i(TAG, "[onDestroy]");
}
private class RealHandle extends Handler
{
@Override
public void handleMessage(Message msg) {
Log.i(TAG, "[handleMessage]");
dismissProdialog();
showTitleResult(mResult);
// mListView.invalidate();
mListView.setAdapter(mAdapter);
mListView.postInvalidate();
}
}
public void StartCalculate(EngineParams mParam )
{
Log.i(TAG, "[StartCalculate]");
CaculaterEngine.setListener(this);
CaculaterEngine.StartRealEstatentTransfer(mParam);
showProdialog();
}
public void showTitleResult(EngineResultParam result) {
// TODO Auto-generated method stubx
if(mViewHolder!=null && result!=null)
{
int total_loan = mParam.commercial_loan+mParam.gongjj_loan;
mLoanTotalView.setText(String.valueOf((total_loan)/10000)+"W");
double total_repay = total_loan+result.totalInterest;
total_repay = MonthLoanResult.transferDoubleWithByte(2, total_repay);
mRepayTotalView.setText(String.valueOf(total_repay));
mLoanMonthView.setText(String.valueOf(result.result.size()));
mTotalInterestView.setText(String.valueOf(result.totalInterest));
mFirstPayView.setText(String.valueOf(result.firstmonth));
double rate = 0;
if(mParam.commercial_loan!=0)
{
rate = mParam.commercial_rate*100;
mRateTitleView.setText(R.string.header_rate_commercial);
// mRateView.setText(String.valueOf(mParam.commercial_rate*100)+"%");
}
else
{
rate = mParam.gongjj_rate*100;
mRateTitleView.setText(R.string.header_rate_gongjj);
// mRateView.setText(String.valueOf(mParam.gongjj_rate*100)+"%");
}
rate = MonthLoanResult.transferDoubleWithByte(2, rate);
mRateView.setText(String.valueOf(rate)+"%");
mTitleLayout.setVisibility(View.VISIBLE);
}
}
@Override
public void onCalculaterResult(EngineResultParam calcResult) {
if(calcResult!=null)
{
Log.i(TAG, "[onCalculaterResult] calcResult:"+calcResult.totalInterest);
if(mViewHolder == null)
{
mViewHolder = new ArrayList<ViewHolder>(6);
mViewHolder.clear();
if(mTitleLayout!=null)
{
mLoanTotalView = (TextView) mTitleLayout.findViewById(R.id.text_header_loan_total_content);
mRepayTotalView = (TextView) mTitleLayout.findViewById(R.id.text_header_return_total_content);
mLoanMonthView = (TextView) mTitleLayout.findViewById(R.id.text_header_loan_month_content);
mTotalInterestView = (TextView) mTitleLayout.findViewById(R.id.text_header_total_interest_content);
mRateView = (TextView) mTitleLayout.findViewById(R.id.text_head_loan_rate_content);
mFirstPayView = (TextView) mTitleLayout.findViewById(R.id.text_header_repay_month_content);
mRateTitleView = (TextView) mTitleLayout.findViewById(R.id.text_head_loan_rate);
}
}
mAdapter.setResult(calcResult);
mResult = calcResult;
Message msg = handle.obtainMessage();
handle.sendMessage(msg);
}
}
public class ViewHolder{
public TextView startView;
public TextView endView;
}
public void showProdialog()
{
mProdialog.setMessage(this.getResources().getString(R.string.progress_dialog_title));
mProdialog.show();
}
public void dismissProdialog()
{
mProdialog.dismiss();
}
}
|
package com.beiyelin.projectportal.entity;
import com.beiyelin.addressservice.entity.EmbeddableAddress;
import com.beiyelin.commonsql.jpa.BaseDomainEntity;
import com.beiyelin.commonsql.jpa.MasterDataEntity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import static com.beiyelin.commonsql.constant.Repository.*;
/**
* @Description: 工种定义
* @Author: newmann
* @Date: Created in 14:43 2018-02-21
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper=true)
@Entity
@Table(name = WorkType.TABLE_NAME
// ,indexes ={@Index(name=Project.TABLE_NAME +"_code",columnList = "idCard",unique = true)}
)
public class WorkType extends MasterDataEntity {
public static final String TABLE_NAME="s_work_type";
private static final long serialVersionUID = 1L;
@Column(unique = true,length = CODE_LENGTH)
private String code;
@Column(unique = true,length = NAME_LENGTH)
private String name;
@Column(nullable = false)
private int checkType = 1; //考情类型,1代表按天,2代表按小时。
private int standardTimeLength; //标准工作时长,对应按小时核算的工种,比如一天10小时按一天核算,
// @Column(nullable = false)
// private int status = 1; //按主数据状态处理
}
|
package com.google.android.gms.c;
final class ba implements Cloneable {
static final bb bab = new bb();
boolean bac;
int[] bad;
bb[] bae;
int fi;
public ba() {
this(10);
}
private ba(int i) {
this.bac = false;
int ad = ad(i);
this.bad = new int[ad];
this.bae = new bb[ad];
this.fi = 0;
}
static int ad(int i) {
int i2 = i * 4;
for (int i3 = 4; i3 < 32; i3++) {
if (i2 <= (1 << i3) - 12) {
i2 = (1 << i3) - 12;
break;
}
}
return i2 / 4;
}
public final bb dM(int i) {
if (this.bac) {
gc();
}
return this.bae[i];
}
final int dN(int i) {
int i2 = 0;
int i3 = this.fi - 1;
while (i2 <= i3) {
int i4 = (i2 + i3) >>> 1;
int i5 = this.bad[i4];
if (i5 < i) {
i2 = i4 + 1;
} else if (i5 <= i) {
return i4;
} else {
i3 = i4 - 1;
}
}
return i2 ^ -1;
}
public final boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof ba)) {
return false;
}
ba baVar = (ba) obj;
if (size() != baVar.size()) {
return false;
}
int i;
boolean z;
int[] iArr = this.bad;
int[] iArr2 = baVar.bad;
int i2 = this.fi;
for (i = 0; i < i2; i++) {
if (iArr[i] != iArr2[i]) {
z = false;
break;
}
}
z = true;
if (z) {
bb[] bbVarArr = this.bae;
bb[] bbVarArr2 = baVar.bae;
i2 = this.fi;
for (i = 0; i < i2; i++) {
if (!bbVarArr[i].equals(bbVarArr2[i])) {
z = false;
break;
}
}
z = true;
if (z) {
return true;
}
}
return false;
}
final void gc() {
int i = this.fi;
int[] iArr = this.bad;
bb[] bbVarArr = this.bae;
int i2 = 0;
for (int i3 = 0; i3 < i; i3++) {
bb bbVar = bbVarArr[i3];
if (bbVar != bab) {
if (i3 != i2) {
iArr[i2] = iArr[i3];
bbVarArr[i2] = bbVar;
bbVarArr[i3] = null;
}
i2++;
}
}
this.bac = false;
this.fi = i2;
}
public final int hashCode() {
if (this.bac) {
gc();
}
int i = 17;
for (int i2 = 0; i2 < this.fi; i2++) {
i = (((i * 31) + this.bad[i2]) * 31) + this.bae[i2].hashCode();
}
return i;
}
public final boolean isEmpty() {
return size() == 0;
}
/* renamed from: qI */
public final ba clone() {
int i = 0;
int size = size();
ba baVar = new ba(size);
System.arraycopy(this.bad, 0, baVar.bad, 0, size);
while (i < size) {
if (this.bae[i] != null) {
baVar.bae[i] = this.bae[i].clone();
}
i++;
}
baVar.fi = size;
return baVar;
}
public final int size() {
if (this.bac) {
gc();
}
return this.fi;
}
}
|
package basic;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class Exercise09Test {
@Test
public void test_calPI(){
assertEquals(new Exercise09().calPI(), "3.141598");
}
}
|
package com.google.android.gms.analytics.internal;
import android.util.DisplayMetrics;
import com.google.android.gms.c.al;
import java.util.Locale;
public final class af extends o {
af(q qVar) {
super(qVar);
}
protected final void mE() {
}
public final al og() {
np();
DisplayMetrics displayMetrics = this.aFn.ns().mContext.getResources().getDisplayMetrics();
al alVar = new al();
alVar.aYE = k.c(Locale.getDefault());
alVar.aYG = displayMetrics.widthPixels;
alVar.aYH = displayMetrics.heightPixels;
return alVar;
}
}
|
package com.book.web;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.bookapp.dao.Book;
import com.bookapp.model.service.BookService;
public class Main {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
BookService bookService = (BookService) ctx.getBean("bookService");
List<Book> books = bookService.getAllBooks();
books.forEach(b -> System.out.println(b));
}
}
|
package com.stackroute.muzix.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
/*creates a table track with id, name, comment columns using @Entity @Id @Column annotation */
/*lombok annotations @Data @AllArgsConstructor @NoArgsConstructor are used for creating constructor, getter and setter*/
@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Track {
@Id
// @GeneratedValue(strategy= GenerationType.AUTO)
private int id;
@Column
private String name;
@Column
private String comment;
}
|
package net.minecraft.client.renderer.entity;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.model.ModelOcelot;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.passive.EntityOcelot;
import net.minecraft.util.ResourceLocation;
public class RenderOcelot extends RenderLiving<EntityOcelot> {
private static final ResourceLocation BLACK_OCELOT_TEXTURES = new ResourceLocation("textures/entity/cat/black.png");
private static final ResourceLocation OCELOT_TEXTURES = new ResourceLocation("textures/entity/cat/ocelot.png");
private static final ResourceLocation RED_OCELOT_TEXTURES = new ResourceLocation("textures/entity/cat/red.png");
private static final ResourceLocation SIAMESE_OCELOT_TEXTURES = new ResourceLocation("textures/entity/cat/siamese.png");
public RenderOcelot(RenderManager p_i47199_1_) {
super(p_i47199_1_, (ModelBase)new ModelOcelot(), 0.4F);
}
protected ResourceLocation getEntityTexture(EntityOcelot entity) {
switch (entity.getTameSkin()) {
default:
return OCELOT_TEXTURES;
case 1:
return BLACK_OCELOT_TEXTURES;
case 2:
return RED_OCELOT_TEXTURES;
case 3:
break;
}
return SIAMESE_OCELOT_TEXTURES;
}
protected void preRenderCallback(EntityOcelot entitylivingbaseIn, float partialTickTime) {
super.preRenderCallback(entitylivingbaseIn, partialTickTime);
if (entitylivingbaseIn.isTamed())
GlStateManager.scale(0.8F, 0.8F, 0.8F);
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\client\renderer\entity\RenderOcelot.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/ |
/*
* Copyright (c) 2014. igitras.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.igitras.codegen.common.java.element.file.part;
import com.igitras.codegen.common.java.element.enums.IsAbstract;
import org.junit.Test;
public class JavaAbstractMethodsPartTest {
@Test
public void testGetImports() throws Exception {
}
@Test
public void testBuild() throws Exception {
JavaAbstractMethodsPart methodsPart = new JavaAbstractMethodsPart();
JavaAbstractMethodPart methodPart = new JavaAbstractMethodPart(IsAbstract.ABSTRACT, String.class.getName(),
"testAbstractMethods");
methodsPart.addParts(methodPart);
methodPart = new JavaAbstractMethodPart(IsAbstract.ABSTRACT, String.class.getName(),
"testAbstractMethods1");
methodsPart.addParts(methodPart);
methodPart = new JavaAbstractMethodPart(IsAbstract.ABSTRACT, String.class.getName(),
"testAbstractMethods2");
methodsPart.addParts(methodPart);
System.out.println(methodsPart.build());
}
@Test
public void testBuildForInterface() throws Exception {
JavaAbstractMethodsPart methodsPart = new JavaAbstractMethodsPart();
JavaAbstractMethodPart methodPart = new JavaAbstractMethodPart(IsAbstract.DEFAULT, String.class.getName(),
"testAbstractMethods");
methodsPart.addParts(methodPart);
methodPart = new JavaAbstractMethodPart(IsAbstract.DEFAULT, String.class.getName(), "testAbstractMethods1");
methodsPart.addParts(methodPart);
methodPart = new JavaAbstractMethodPart(null, String.class.getName(), "testAbstractMethods2");
methodsPart.addParts(methodPart);
methodPart = new JavaAbstractMethodPart(null, String.class.getName(), "testAbstractMethods2");
methodsPart.addParts(methodPart);
System.out.println(methodsPart.build());
}
} |
/*
* 2012-3 Red Hat Inc. and/or its affiliates and other contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.overlord.rtgov.service.dependency.rest;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
import org.overlord.rtgov.active.collection.ActiveCollectionManager;
import org.overlord.rtgov.service.dependency.presentation.SeverityAnalyzer;
import java.util.HashSet;
import java.util.Set;
/**
* This class represents the REST application for the service dependency
* service.
*
*/
@ApplicationPath("/service/dependency")
public class RESTServiceDependencyServerApplication extends Application {
private static Set<Object> _singletons = new HashSet<Object>();
private Set<Class<?>> _empty = new HashSet<Class<?>>();
/**
* This is the default constructor.
*/
public RESTServiceDependencyServerApplication() {
synchronized (_singletons) {
if (_singletons.isEmpty()) {
_singletons.add(new RESTServiceDependencyServer());
}
}
}
/**
* This method sets the active collection manager.
*
* @param acm The active collection manager
*/
public void setActiveCollectionManager(ActiveCollectionManager acm) {
synchronized (_singletons) {
RESTServiceDependencyServer server=null;
if (!_singletons.isEmpty()) {
server = (RESTServiceDependencyServer)_singletons.iterator().next();
} else {
server = new RESTServiceDependencyServer();
_singletons.add(server);
}
server.setActiveCollectionManager(acm);
}
}
/**
* This method returns the active collection manager.
*
* @return The active collection manager
*/
public ActiveCollectionManager getActiveCollectionManager() {
ActiveCollectionManager ret=null;
synchronized (_singletons) {
if (!_singletons.isEmpty()) {
RESTServiceDependencyServer server = (RESTServiceDependencyServer)_singletons.iterator().next();
ret = server.getActiveCollectionManager();
}
}
return (ret);
}
/**
* This method sets the severity analyzer.
*
* @param sa The severity analyzer
*/
public void setSeverityAnalyzer(SeverityAnalyzer sa) {
synchronized (_singletons) {
RESTServiceDependencyServer server=null;
if (!_singletons.isEmpty()) {
server = (RESTServiceDependencyServer)_singletons.iterator().next();
} else {
server = new RESTServiceDependencyServer();
_singletons.add(server);
}
server.setSeverityAnalyzer(sa);
}
}
/**
* This method gets the severity analyzer.
*
* @return The severity analyzer
*/
public SeverityAnalyzer getSeverityAnalyzer() {
SeverityAnalyzer ret=null;
synchronized (_singletons) {
if (!_singletons.isEmpty()) {
RESTServiceDependencyServer server = (RESTServiceDependencyServer)_singletons.iterator().next();
ret = server.getSeverityAnalyzer();
}
}
return (ret);
}
/**
* {@inheritDoc}
*/
@Override
public Set<Class<?>> getClasses() {
return _empty;
}
/**
* {@inheritDoc}
*/
@Override
public Set<Object> getSingletons() {
return _singletons;
}
}
|
package net.plazmix.core.api.common.command;
import net.plazmix.core.api.common.util.Builder;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Function;
/**
* @author MasterCapeXD
*/
public interface CommandElementBuilder<B extends CommandElementBuilder<B, R>, R extends CommandElement>
extends Builder<R> {
B registerAlias(String alias);
B withDescription(String description);
B withPermission(String permission, Function<CommandSender, String> messageFunction);
B setWrongSenderMessage(Function<CommandSender, String> messageFunction);
B withExecutor(BiConsumer<CommandSender, String[]> biConsumer);
B withTabCompleter(BiFunction<CommandSender, String[], List<String>> biFunction);
default B registerAliases(String... aliases) {
B builder = null;
for (String alias : aliases)
builder = registerAlias(alias);
return builder;
}
default B withPermission(String permission, String message) {
return withPermission(permission, s -> message);
}
default B setWrongSenderMessage(String message) {
return setWrongSenderMessage(s -> message);
}
} |
package cz.ladicek.swarm.reproducer.SWARM_1929;
import org.eclipse.microprofile.faulttolerance.ExecutionContext;
import org.eclipse.microprofile.faulttolerance.FallbackHandler;
public class HelloFallback implements FallbackHandler<String> {
@Override
public String handle(ExecutionContext context) {
return "Fallback";
}
}
|
package com.vehicletracking;
public interface BaseFilter {
}
|
package app.com.example.ozgur.sunny;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.ShareActionProvider;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class DetailActivity extends ActionBarActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new DetailFragment())
.commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.detail, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch(item.getItemId())
{
case R.id.action_settings:
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class DetailFragment extends Fragment {
private final String LOG_TAG = this.getClass().getSimpleName();
private final String FORECAST_SHARE_HASHTAG = "#Sunshine App";
private String mForecastString;
private ShareActionProvider mShareActionProvider;
public DetailFragment() {
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Intent intent = getActivity().getIntent();
View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
if(intent != null && intent.hasExtra(Intent.EXTRA_TEXT))
mForecastString = intent.getStringExtra(Intent.EXTRA_TEXT);
((TextView)rootView.findViewById(R.id.txtDay)).setText(mForecastString);
return rootView;
}
@Override
public void onCreateOptionsMenu( Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.detailfragment, menu);
MenuItem item = menu.findItem(R.id.share);
mShareActionProvider = (ShareActionProvider)MenuItemCompat.getActionProvider(item);
if(mShareActionProvider != null)
mShareActionProvider.setShareIntent(CreateForecastShareIntent());
else
{
Log.d(LOG_TAG,"ShareActionProvide is null");
}
}
private Intent CreateForecastShareIntent(){
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); //when you click back makes sure that you go back to your own app. not somewhere else
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, mForecastString + " " + FORECAST_SHARE_HASHTAG);
return intent;
}
}
}
|
this and and and then and this
|
/*
* 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 controller;
import java.io.IOException;
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 model.Person;
import util.DBProcess;
/**
*
* @author resul
*/
@WebServlet(name = "KullaniciGuncelleServlet", urlPatterns = {"/KullaniciGuncelleServlet"})
public class KullaniciGuncelleServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
Person person = new Person();
String personId=request.getParameter("personId").toString();
System.out.println("personID : "+personId);
person.setPersonId(Integer.parseInt(personId));
person.setUsername(request.getParameter("username"));
person.setPassword(request.getParameter("password"));
boolean guncellediMi=DBProcess.editPersonn(person);
System.out.println("GuncellediMi : " + guncellediMi);
response.sendRedirect("kullaniciListesi.jsp");
} catch (Exception ex) {
System.out.println("HATA : " + ex.getStackTrace());
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}
|
package com.spbsu.flamestream.runtime.edge.socket;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryonet.Client;
import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.kryonet.Listener;
import com.spbsu.flamestream.runtime.edge.Front;
import com.spbsu.flamestream.core.data.PayloadDataItem;
import com.spbsu.flamestream.core.data.meta.GlobalTime;
import com.spbsu.flamestream.core.data.meta.Meta;
import com.spbsu.flamestream.runtime.master.acker.api.Heartbeat;
import com.spbsu.flamestream.runtime.master.acker.api.registry.UnregisterFront;
import com.spbsu.flamestream.runtime.edge.EdgeContext;
import org.objenesis.strategy.StdInstantiatorStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Arrays;
import java.util.function.Consumer;
/**
* User: Artem
* Date: 28.12.2017
*/
public class SocketFront extends Front.Stub {
private final static Logger LOG = LoggerFactory.getLogger(SocketFront.class);
private final Client client;
private final String host;
private final int port;
private volatile Consumer<Object> consumer = null;
//private final Tracing.Tracer tracer = Tracing.TRACING.forEvent("front-receive-send", 1000, 1);
public SocketFront(EdgeContext edgeContext, String host, int port, Class<?>[] classes) {
super(edgeContext.edgeId());
this.host = host;
this.port = port;
client = new Client(1000, 20_000_000);
Arrays.stream(classes).forEach(clazz -> client.getKryo().register(clazz));
((Kryo.DefaultInstantiatorStrategy) client.getKryo().getInstantiatorStrategy())
.setFallbackInstantiatorStrategy(new StdInstantiatorStrategy());
client.addListener(new Listener() {
public void received(Connection connection, Object object) {
if (Arrays.stream(classes).anyMatch(clazz -> clazz.isAssignableFrom(object.getClass()))) {
//tracer.log(object.hashCode());
final GlobalTime time = currentTime();
consumer.accept(new PayloadDataItem(new Meta(time), object));
consumer.accept(new Heartbeat(new GlobalTime(time.time() + 1, time.frontId())));
}
}
});
client.addListener(new Listener() {
@Override
public void disconnected(Connection connection) {
LOG.info("{} has been disconnected from {}", edgeId, connection);
client.stop();
consumer.accept(new UnregisterFront(edgeId));
}
});
}
@Override
public void onStart(Consumer<Object> consumer, GlobalTime from) {
final boolean init = this.consumer == null;
this.consumer = consumer;
if (init) {
LOG.info("{}: connecting to {}:{}", edgeId, host, port);
client.start();
try {
client.connect(20000, host, port);
client.sendTCP(edgeId.nodeId());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
@Override
public void onRequestNext() {
//socket front does not support backpressure
}
@Override
public void onCheckpoint(GlobalTime to) {
//socket front does not support checkpoints
}
}
|
package edu.eci.arsw.par1t;
import edu.eci.arsw.par1t.priv.DataLoaderOne;
import edu.eci.arsw.par1t.priv.Logger;
import edu.eci.arsw.par1t.priv.SorterTwo;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class DataProcessor {
private DataLoader dl;
private Sorter srt;
public DataLoader getDl() {
return dl;
}
public void setDl(DataLoader dl) {
this.dl = dl;
}
public Sorter getSrt() {
return srt;
}
public void setSrt(Sorter srt) {
this.srt = srt;
}
public int[] processData(){
Logger.log("Loading data...");
int[] data=dl.loadData();
Logger.log("Sorting data...");
srt.sort(data);
Logger.log("Data sorted...");
return data;
}
}
|
package com.dreamcatcher.member.action;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.JSONObject;
import com.dreamcatcher.action.Action;
import com.dreamcatcher.admin.model.service.AdminServiceImpl;
import com.dreamcatcher.member.model.MemberDto;
import com.dreamcatcher.member.model.service.MemberServiceImpl;
import com.dreamcatcher.util.*;
public class MemberResetPasswordAction implements Action {
@Override
public String execute(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
String id = StringCheck.nullToBlank(request.getParameter("id"));
String newPassword = StringCheck.nullToBlank(request.getParameter("password"));
Map validMap = new HashMap();
validMap.put("id",id);
validMap.put("password",newPassword);
int cnt = MemberServiceImpl.getInstance().passwordCheck(validMap);
JSONObject jSONObject = new JSONObject();
// 기존 패스워드와 일치
if(cnt == 1){
jSONObject.put("result", "passwordExist");
// 사용 가능한 패스워드
}else if(cnt == 0){
MemberDto memberDto = new MemberDto();
memberDto.setId(id);
memberDto.setPassword(newPassword);
memberDto.setM_state(1); // 1 : 정상 회원 상태
int cnt2 = MemberServiceImpl.getInstance().resetPassword(memberDto);
if( cnt2 == 1 ){
jSONObject.put("result", "resetPasswordSuccess");
}else{
jSONObject.put("result", "resetPasswordFailed");
}
}else{
jSONObject.put("result", "passwordCheckFailed");
}
String jSONStr = jSONObject.toJSONString();
response.setContentType("text/plain; charset="+CharacterConstant.DEFAULT_CHAR);
response.getWriter().write(jSONStr);
return null;
}
}
|
package io.peppermint100.server.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Data
@NoArgsConstructor
@Entity(name = "ITEM_TABLE")
@DiscriminatorColumn(name = "item_type")
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class Item {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long itemId;
private String itemName;
private Integer price;
private String description;
private String itemImage;
private String itemDetailImage;
@OneToMany(
mappedBy = "item",
cascade = CascadeType.ALL,
orphanRemoval = true
)
@JsonIgnore
private List<CartItem> cartItem = new ArrayList<>();
@OneToMany(
mappedBy = "item",
cascade = CascadeType.ALL,
orphanRemoval = true
)
@JsonIgnore
private List<OrderItem> orderItem = new ArrayList<>();
}
|
package bibliotheque;
import java.util.List;
public interface ServiceLoader {
List<Service> load(Bibliotheque b);
}
|
/*
* 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 db.dao;
import beans.Article;
import beans.Image;
import beans.ShareSiteUser;
import java.util.Date;
import java.util.List;
import org.apache.http.HttpResponse;
import org.junit.Before;
import org.junit.Test;
import org.primefaces.json.JSONException;
/**
*
* @author Pepijn
*/
public class ArticleDaoTest {
private ArticleDao dao;
Article article;
public ArticleDaoTest() {
}
@Before
public void setUp() {
dao = new ArticleDao();
UserDao userdao = new UserDao();
Image image = new Image();
image.setId("2");
image.setPath("new path");
ShareSiteUser user = new ShareSiteUser();
user.setEmail("newemail@test.com");
user.setId("11");
user.setName("testUser");
user.setPassword("test");
user.setUsergroupid(1);
article = new Article();
article.setContent("JUNIT TEST - CONTENT");
article.setId("999");
article.setTitle("JUNIT TEST - TITLE");
article.setDateOfPost(new Date("1/12/2015"));
article.setLocation("51.3 23.4");
article.setShareSiteUser(user);
article.setImage(image);
}
@Test
public void testSaveHttpClient() {
HttpResponse response = dao.saveHttpClient(article);
System.out.println(response);
}
@Test
public void testListAll() throws JSONException {
List<Article> list = dao.listAll();
for (Article article : list) {
System.out.println(article);
}
}
/*
@Test
public void testDeleteById(){
dao.deletebyId(article.getId());
}*/
}
|
package Project7api;
public class UsingString {
public static void main(String[] args){
String str= "I am a Java Developer";
System.out.println(str.length());
System.out.println(str.toUpperCase());
System.out.println(str.toLowerCase());
}
}
|
package com.perhab.napalm.statement;
public class StatementNotInitalizableException extends RuntimeException {
public StatementNotInitalizableException(String message, Exception e) {
super(message, e);
}
public StatementNotInitalizableException(String message) {
super(message);
}
}
|
package com.company.FirstBeginTasks;
import java.util.Scanner;
public class Main {
/**
* to moj pierwszy komentarz wielolinijkowy
* nie podam tu nic więcej
*/
public static void main(String[] args) {
/* Scanner scanner = new Scanner(System.in);
System.out.print("Podaj liczbą dla x: ");
int x = scanner.nextInt();
System.out.print("Podaj liczbą dla y: ");
int y = scanner.nextInt();
/* System.out.println("mam na imię: Krzysztof"); //użyłem tego do podania mojego imienia
System.out.println("Moje nazwisko: Lachowicz");
System.out.println("Mam net do zrobienia");
System.out.println("dzis");
*/
int a =0;
a = "czasopismo".toLowerCase().indexOf("so", a++);
System.out.println(a);
//int y = 11;
// int x = 10;
// int z1 = x * y;
// double z2 = x / y;
// char q1 = 74;
// char q1 = 74;
// char q2 = 65;
// char q3 = 86;
// char q4 = 32;
// char q5 = 8658;
// char q6 = 9786;
//System.out.println("to jest właśnieee!!! " + q1 + q2 + q3 + q2 + q4 + q5 + q4 + q6);
//x=15;
//System.out.println("zmienna z=" + x );
// System.out.println("zmienna z1=" + z1++);
// System.out.println("zmienna z1=" + z1++);
// System.out.println("zmienna z1=" + z1);
// System.out.println("zmienna z2=" + z2);
// boolean kot = x % 2 == 0;
// boolean pies = x > y && x < z1;
//System.out.println("zmienna kot=" + kot);
// System.out.println("zmienna pies=" + pies);
// int x =3;
// System.out.println("wartość zmiennej q=" + x);
//power3(x=3);
// power(13.2, 25.1 );
// power(x, y);
//devBy_3_5(y);
// alphabet();
// evenNumber(x=31);
}
/* **Podnoszeniedo potęgi 3
*
* @param x
public static void power3(double x) {
System.out.println(" x^3 = " + (x*x*x));
//System.out.println("power" + y);
}
*/
/**
* sprawdzanie czy liczba jest parzysta
* <p>
* <p>
* public static void evenNumber( int x) {
* boolean liczba = x%2 == 0;
* //System.out.println("x to liczba parzysta - " + liczba);
* }
*/
/*public static void devBy_3_5(int y) {
boolean number = y % 3 == 0 || y % 5 == 0;
System.out.println(" liczba jest podzielna przez 3 lub 5 - " + number);
}*/
/*public static void alphabet() {
char litLac = 'A';
char litHeb = 1488;
char litTyb = 3840;
System.out.println("pięć pierwszych liter alfabetu łacińskiego to: " + litLac + ++litLac + ++litLac + ++litLac + ++litLac);
System.out.println("pięć pierwszych liter alfabetu hebrajskiego to: " + litHeb + ++litHeb + ++litHeb + ++litHeb + ++litHeb);
System.out.println("pięć pierwszych liter alfabetu tybetańskiego to: " + litTyb + ++litTyb + ++litTyb + ++litTyb + ++litTyb);
}
*/
} |
package de.peterkossek.s10;
import java.awt.Component;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
public class WinnerDialog extends JDialog implements ActionListener {
private static final long serialVersionUID = 1L;
public WinnerDialog(Component parent, ArrayList<Player> finishedPlayers) {
Player winner;
if (finishedPlayers.size() == 1) {
winner = finishedPlayers.get(0);
} else {
winner = finishedPlayers.get(0);
for (int i=1; i<finishedPlayers.size(); i++) {
Player nextPlayer = finishedPlayers.get(i);
if (nextPlayer.getPoints() < winner.getPoints())
winner = nextPlayer;
}
}
getContentPane().setFont(new Font("Segoe UI", Font.PLAIN, 12));
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{434, 0};
gridBagLayout.rowHeights = new int[]{16, 0, 0, 0};
gridBagLayout.columnWeights = new double[]{0.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{0.0, 1.0, 0.0, Double.MIN_VALUE};
getContentPane().setLayout(gridBagLayout);
JLabel lblIntroduction = new JLabel("Der Gewinner ist:");
GridBagConstraints gbc_lblIntroduction = new GridBagConstraints();
gbc_lblIntroduction.insets = new Insets(0, 0, 5, 0);
gbc_lblIntroduction.anchor = GridBagConstraints.NORTH;
gbc_lblIntroduction.gridx = 0;
gbc_lblIntroduction.gridy = 0;
getContentPane().add(lblIntroduction, gbc_lblIntroduction);
JLabel lblWinnerName = new JLabel(winner.getName());
lblWinnerName.setFont(new Font("Segoe UI", Font.BOLD, 32));
GridBagConstraints gbc_lblWinnerName = new GridBagConstraints();
gbc_lblWinnerName.insets = new Insets(0, 0, 5, 0);
gbc_lblWinnerName.gridx = 0;
gbc_lblWinnerName.gridy = 1;
getContentPane().add(lblWinnerName, gbc_lblWinnerName);
JButton btnOk = new JButton("OK");
btnOk.addActionListener(this);
GridBagConstraints gbc_btnOk = new GridBagConstraints();
gbc_btnOk.gridx = 0;
gbc_btnOk.gridy = 2;
getContentPane().add(btnOk, gbc_btnOk);
setLocationRelativeTo(parent);
setModal(true);
pack();
setResizable(false);
setTitle("Gewinner!");
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent event) {
setVisible(false);
}
}
|
/*
* Gretty
*
* Copyright (C) 2013-2015 Andrey Hihlovskiy and contributors.
*
* See the file "LICENSE" for copying and usage permission.
* See the file "CONTRIBUTORS" for complete list of contributors.
*/
package org.akhikhl.examples.gretty.websocket;
import jakarta.websocket.ClientEndpoint;
import jakarta.websocket.CloseReason;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnError;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.ServerEndpoint;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ClientEndpoint
@ServerEndpoint(value="/hello")
public class EventSocket {
private static final Set<Session> sessions = Collections.synchronizedSet(new HashSet<Session>());
private static final Logger log = LoggerFactory.getLogger(EventSocket.class);
@OnOpen
public void onWebSocketConnect(final Session session) {
log.info("Socket Connected: {}", session);
sessions.add(session);
}
@OnMessage
public void onWebSocketText(final Session client, String message) throws Exception {
log.info("Received TEXT message: {}", message);
for( final Session session: sessions ) {
if(session != client)
session.getBasicRemote().sendText(message);
}
}
@OnClose
public void onWebSocketClose(final Session session, CloseReason reason) {
log.info("Socket Closed: {}", reason);
sessions.remove(session);
}
@OnError
public void onWebSocketError(Throwable cause) {
log.error("Socket Error", cause);
}
}
|
package com.tencent.mm.protocal.c;
import f.a.a.b;
import f.a.a.c.a;
import java.util.LinkedList;
public final class asz extends bhd {
public int jQd;
public String jRi;
public String lPl;
public int rJr;
public String rVi;
public String rVj;
public String rVk;
public int rVl;
public bhy rVm;
public int rVn;
public int rVo;
public int rVp;
public int rVq;
public bhy rVr;
public int rVs;
public int rVt;
public int rVu;
public int rVv;
public int rVw;
public String rVx;
public String rVy;
public int rmo;
public int rmp;
protected final int a(int i, Object... objArr) {
int fS;
if (i == 0) {
a aVar = (a) objArr[0];
if (this.rVm == null) {
throw new b("Not all required fields were included: DataBuffer");
} else if (this.rVr == null) {
throw new b("Not all required fields were included: ThumbData");
} else {
if (this.shX != null) {
aVar.fV(1, this.shX.boi());
this.shX.a(aVar);
}
if (this.rVi != null) {
aVar.g(2, this.rVi);
}
if (this.rVj != null) {
aVar.g(3, this.rVj);
}
if (this.rVk != null) {
aVar.g(4, this.rVk);
}
aVar.fT(5, this.jQd);
aVar.fT(6, this.rVl);
if (this.rVm != null) {
aVar.fV(7, this.rVm.boi());
this.rVm.a(aVar);
}
aVar.fT(8, this.rVn);
aVar.fT(9, this.rVo);
aVar.fT(10, this.rVp);
aVar.fT(11, this.rVq);
if (this.rVr != null) {
aVar.fV(12, this.rVr.boi());
this.rVr.a(aVar);
}
aVar.fT(13, this.rVs);
aVar.fT(14, this.rVt);
aVar.fT(15, this.rVu);
aVar.fT(16, this.rVv);
aVar.fT(17, this.rJr);
aVar.fT(18, this.rVw);
if (this.jRi != null) {
aVar.g(19, this.jRi);
}
if (this.lPl != null) {
aVar.g(20, this.lPl);
}
aVar.fT(21, this.rmp);
aVar.fT(22, this.rmo);
if (this.rVx != null) {
aVar.g(23, this.rVx);
}
if (this.rVy == null) {
return 0;
}
aVar.g(24, this.rVy);
return 0;
}
} else if (i == 1) {
if (this.shX != null) {
fS = f.a.a.a.fS(1, this.shX.boi()) + 0;
} else {
fS = 0;
}
if (this.rVi != null) {
fS += f.a.a.b.b.a.h(2, this.rVi);
}
if (this.rVj != null) {
fS += f.a.a.b.b.a.h(3, this.rVj);
}
if (this.rVk != null) {
fS += f.a.a.b.b.a.h(4, this.rVk);
}
fS = (fS + f.a.a.a.fQ(5, this.jQd)) + f.a.a.a.fQ(6, this.rVl);
if (this.rVm != null) {
fS += f.a.a.a.fS(7, this.rVm.boi());
}
fS = (((fS + f.a.a.a.fQ(8, this.rVn)) + f.a.a.a.fQ(9, this.rVo)) + f.a.a.a.fQ(10, this.rVp)) + f.a.a.a.fQ(11, this.rVq);
if (this.rVr != null) {
fS += f.a.a.a.fS(12, this.rVr.boi());
}
fS = (((((fS + f.a.a.a.fQ(13, this.rVs)) + f.a.a.a.fQ(14, this.rVt)) + f.a.a.a.fQ(15, this.rVu)) + f.a.a.a.fQ(16, this.rVv)) + f.a.a.a.fQ(17, this.rJr)) + f.a.a.a.fQ(18, this.rVw);
if (this.jRi != null) {
fS += f.a.a.b.b.a.h(19, this.jRi);
}
if (this.lPl != null) {
fS += f.a.a.b.b.a.h(20, this.lPl);
}
fS = (fS + f.a.a.a.fQ(21, this.rmp)) + f.a.a.a.fQ(22, this.rmo);
if (this.rVx != null) {
fS += f.a.a.b.b.a.h(23, this.rVx);
}
if (this.rVy != null) {
fS += f.a.a.b.b.a.h(24, this.rVy);
}
return fS;
} else if (i == 2) {
f.a.a.a.a aVar2 = new f.a.a.a.a((byte[]) objArr[0], unknownTagHandler);
for (fS = bhd.a(aVar2); fS > 0; fS = bhd.a(aVar2)) {
if (!super.a(aVar2, this, fS)) {
aVar2.cJS();
}
}
if (this.rVm == null) {
throw new b("Not all required fields were included: DataBuffer");
} else if (this.rVr != null) {
return 0;
} else {
throw new b("Not all required fields were included: ThumbData");
}
} else if (i != 3) {
return -1;
} else {
f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0];
asz asz = (asz) objArr[1];
int intValue = ((Integer) objArr[2]).intValue();
LinkedList IC;
int size;
byte[] bArr;
f.a.a.a.a aVar4;
boolean z;
bhy bhy;
switch (intValue) {
case 1:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
fk fkVar = new fk();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = fkVar.a(aVar4, fkVar, bhd.a(aVar4))) {
}
asz.shX = fkVar;
}
return 0;
case 2:
asz.rVi = aVar3.vHC.readString();
return 0;
case 3:
asz.rVj = aVar3.vHC.readString();
return 0;
case 4:
asz.rVk = aVar3.vHC.readString();
return 0;
case 5:
asz.jQd = aVar3.vHC.rY();
return 0;
case 6:
asz.rVl = aVar3.vHC.rY();
return 0;
case 7:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
bhy = new bhy();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = bhy.a(aVar4, bhy, bhd.a(aVar4))) {
}
asz.rVm = bhy;
}
return 0;
case 8:
asz.rVn = aVar3.vHC.rY();
return 0;
case 9:
asz.rVo = aVar3.vHC.rY();
return 0;
case 10:
asz.rVp = aVar3.vHC.rY();
return 0;
case 11:
asz.rVq = aVar3.vHC.rY();
return 0;
case 12:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
bhy = new bhy();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = bhy.a(aVar4, bhy, bhd.a(aVar4))) {
}
asz.rVr = bhy;
}
return 0;
case 13:
asz.rVs = aVar3.vHC.rY();
return 0;
case 14:
asz.rVt = aVar3.vHC.rY();
return 0;
case 15:
asz.rVu = aVar3.vHC.rY();
return 0;
case 16:
asz.rVv = aVar3.vHC.rY();
return 0;
case 17:
asz.rJr = aVar3.vHC.rY();
return 0;
case 18:
asz.rVw = aVar3.vHC.rY();
return 0;
case 19:
asz.jRi = aVar3.vHC.readString();
return 0;
case 20:
asz.lPl = aVar3.vHC.readString();
return 0;
case 21:
asz.rmp = aVar3.vHC.rY();
return 0;
case 22:
asz.rmo = aVar3.vHC.rY();
return 0;
case 23:
asz.rVx = aVar3.vHC.readString();
return 0;
case 24:
asz.rVy = aVar3.vHC.readString();
return 0;
default:
return -1;
}
}
}
}
|
package com.smxknife.java2.serializable;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
/**
* @author smxknife
* 2018/11/2
*/
public class EmployeeDeserializeDemo {
public static void main(String[] args) {
Employee e = null;
try {
FileInputStream fis = new FileInputStream("./employee.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
e = (Employee) ois.readObject();
ois.close();
fis.close();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
System.out.println("employee class not found");
e1.printStackTrace();
}
System.out.println("Deserialized Employee...");
System.out.println("Name: " + e.name);
System.out.println("Address: " + e.address);
System.out.println("SSN: " + e.SSN);
System.out.println("Number: " + e.number);
System.out.println("StaticAttr: " + e.staticAttr);
System.out.println("Class StaticAttr: " + Employee.staticAttr);
System.out.println("identity: " + e.identity);
}
}
|
package com.yougou.dto.input;
import com.yougou.dto.BaseDto;
/**
*
* @author 杨梦清
*
*/
public class InputDto extends BaseDto {
private static final long serialVersionUID = 7978719981956480110L;
/** 商家编码 **/
private String merchant_code;
public String getMerchant_code() {
return merchant_code;
}
public void setMerchant_code(String merchant_code) {
this.merchant_code = merchant_code;
}
}
|
package collection.visualizer.examples.bean;
import java.beans.PropertyChangeEvent;
import java.util.Date;
import javax.swing.JPanel;
import bus.uigen.shapes.Shape;
import collection.visualizer.common.ListenableVector;
import collection.visualizer.datatype.bean.ABeanBuffer;
import collection.visualizer.datatype.bean.BeanEventGenerator;
import collection.visualizer.examples.observer.ADateLayoutManager;
import collection.visualizer.examples.observer.ObservableDate;
import collection.visualizer.layout.LayoutManager;
public class ABeanDateLayoutManager implements
LayoutManager<BeanEventGenerator> {
private ADateLayoutManager layoutManager;
public ABeanDateLayoutManager(int x, int y, int radius) {
layoutManager = new ADateLayoutManager(x, y, radius);
}
public ListenableVector<Shape> display(BeanEventGenerator bean) {
if (bean instanceof ABeanBuffer) {
ObservableDate observableDate = new ObservableDate();
ABeanDate date = (ABeanDate) ((ABeanBuffer)bean).getBean();
observableDate.setDate(date.getDate());
return layoutManager.display(observableDate);
}
return null;
}
public ListenableVector<Shape> constructPseudoCode() {
return layoutManager.constructPseudoCode();
}
public ListenableVector<Shape> getPseudoCode() {
return layoutManager.getPseudoCode();
}
public int getPseudoCodeMarker() {
return layoutManager.getPseudoCodeMarker();
}
public void update(PropertyChangeEvent event) {
Object newVal = event.getNewValue();
if (newVal instanceof Date) {
ObservableDate observableDate = new ObservableDate();
observableDate.setDate((Date)newVal);
layoutManager.update(observableDate);
}
}
public JPanel displayInPanel() {
// TODO Auto-generated method stub
return null;
}
public JPanel getPanel() {
// TODO Auto-generated method stub
return null;
}
}
|
/*
* 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.parser.contractlog;
import com.hedera.mirror.common.domain.entity.EntityId;
import com.hedera.mirror.common.domain.transaction.RecordItem;
import lombok.Data;
import org.apache.tuweni.bytes.Bytes;
@Data
public abstract class AbstractSyntheticContractLog implements SyntheticContractLog {
private final RecordItem recordItem;
private final EntityId entityId;
private final byte[] topic0;
private final byte[] topic1;
private final byte[] topic2;
private final byte[] topic3;
private final byte[] data;
AbstractSyntheticContractLog(
RecordItem recordItem,
EntityId tokenId,
byte[] topic0,
byte[] topic1,
byte[] topic2,
byte[] topic3,
byte[] data) {
this.recordItem = recordItem;
this.entityId = tokenId;
this.topic0 = topic0;
this.topic1 = topic1;
this.topic2 = topic2;
this.topic3 = topic3;
this.data = data;
}
static final byte[] TRANSFER_SIGNATURE = Bytes.fromHexString(
"ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef")
.toArray();
static final byte[] APPROVE_FOR_ALL_SIGNATURE = Bytes.fromHexString(
"17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31")
.toArray();
static final byte[] APPROVE_SIGNATURE = Bytes.fromHexString(
"8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925")
.toArray();
static byte[] entityIdToBytes(EntityId entityId) {
return Bytes.ofUnsignedLong(entityId.getEntityNum()).toArrayUnsafe();
}
static byte[] longToBytes(long value) {
return Bytes.ofUnsignedLong(value).toArrayUnsafe();
}
static byte[] booleanToBytes(boolean value) {
return Bytes.of(value ? 1 : 0).toArrayUnsafe();
}
}
|
package com.demo.utils;
public class DataUtils {
public static Object[][] getData(String tcName,String sheetName,XlReader x){
int tcStartRow =0;
while(!x.getCellData(sheetName, 0, tcStartRow).equals(tcName)){
tcStartRow++;
}
System.out.println(tcStartRow);
int colStartRow =tcStartRow+1;
int cols=0;
while(!x.getCellData(sheetName, cols, colStartRow).equals("N")){
cols++;
}
System.out.println(cols);
int dataStartRow =tcStartRow+2;
int rows=0;
while(!x.getCellData(sheetName, 0, dataStartRow+rows).equals("N")){
rows++;
}
System.out.println(rows);
Object[][] data=new Object[rows][cols];
int index=0;
for(int rNum=dataStartRow;rNum<dataStartRow+rows;rNum++){
for(int cNum=0;cNum<cols;cNum++){
//System.out.println(x.getCellData(sheetName, cNum, rNum));
data[index][cNum]=x.getCellData(sheetName, cNum, rNum);
}
index++;
}
return data;
}
}
|
package com.tencent.mm.plugin.wallet.balance.a.a;
import com.tencent.mm.protocal.c.bcp;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.vending.c.a;
class o$4 implements a<bcp, bcp> {
final /* synthetic */ o oZs;
o$4(o oVar) {
this.oZs = oVar;
}
public final /* synthetic */ Object call(Object obj) {
bcp bcp = (bcp) obj;
o.a(this.oZs, bcp.qYx);
o.a(this.oZs).bNd();
x.i("MicroMsg.LqtSaveFetchLogic", "get tradeNo: %s", new Object[]{o.b(this.oZs)});
return bcp;
}
}
|
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
//1 2 3 4
boolean set = true;
if(head == null || head.next == null || n == m)
{
return head;
}
int count = 1;
ListNode prev = null;
ListNode prev1 = head;
ListNode cur = head;
while(count < m)
{
prev1 = cur;
cur = cur.next;
count++;
}
int iteration = n - m;
ListNode head1 = cur;
if(prev1 == cur)
set = false;
prev = cur;
cur = cur.next;
ListNode temp = cur;
while(iteration > 0 && cur != null)
{
temp = cur.next;
cur.next = prev;
prev = cur;
cur = temp;
iteration--;
}
|
package main;
import java.util.ArrayList;
import java.util.List;
class Team {
private static final int MAX_SALARY = 50000;
// 5 people, one of each
Player pointGuard;
Player shootingGuard;
Player powerForward;
Player smallForward;
Player center;
int totalSalary = 0;
public Team() {
// TODO Auto-generated constructor stub
}
public boolean CanAddPlayer(Player player) {
if (totalSalary + player.getSalary() > MAX_SALARY) {
return false;
}
switch (player.getPosition()) {
case PG:
if (pointGuard == null)
return true;
break;
case SG:
if (shootingGuard == null)
return true;
break;
case SF:
if (smallForward == null)
return true;
break;
case PF:
if (powerForward == null)
return true;
break;
case C:
if (center == null)
return true;
break;
default:
return false;
}
return false;
}
public boolean isFull() {
return center != null && pointGuard != null && powerForward != null && smallForward != null && shootingGuard != null;
}
public void AddPlayer(Player player) {
totalSalary += player.getSalary();
switch (player.getPosition()) {
case PG:
pointGuard = player;
break;
case SG:
shootingGuard = player;
break;
case SF:
smallForward = player;
break;
case PF:
powerForward = player;
break;
case C:
center = player;
break;
default:
break;
}
}
public Team Copy() {
Team backup = new Team();
backup.pointGuard = pointGuard;
backup.shootingGuard = shootingGuard;
backup.smallForward = smallForward;
backup.powerForward = powerForward;
backup.center = center;
return backup;
}
public void RemovePlayer(Player player) {
totalSalary -= player.getSalary();
switch (player.getPosition()) {
case PG:
pointGuard = null;
break;
case SG:
shootingGuard = null;
break;
case SF:
smallForward = null;
break;
case PF:
powerForward = null;
break;
case C:
center = null;
break;
default:
break;
}
}
public List<Team> CreateListofTeams(List<Player> playerList) {
List<Team> teamList = new ArrayList<>();
Team team = new Team();
BuildTeam(teamList, team, playerList);
return teamList;
}
public void BuildTeam(List<Team> tList, Team team, List<Player> pList) {
if (team.isFull()) {
System.out.println(team.Copy());
tList.add(team.Copy());
} else {
// XXX we could use the team to help us filter players
for (Player player : pList) {
if (team.CanAddPlayer(player)) {
team.AddPlayer(player);
List<Player> leftPositions = team.LeftPositions(pList);
BuildTeam(tList, team, leftPositions);
team.RemovePlayer(player);
}
}
}
}
public List<Player> LeftPositions(List<Player> pList) {
List<Player> playersP = new ArrayList<Player>();
for (Player player : pList) {
if (CanAddPlayer(player)) {
playersP.add(player);
}
}
return playersP;
}
@Override
public String toString() {
return "Team [pointGuard=" + pointGuard + ", shootingGuard=" + shootingGuard + ", powerForward=" + powerForward + ", smallForward=" + smallForward
+ ", center=" + center + "]";
}
}
|
package Test;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
/**
* @author admin
* @version 1.0.0
* @ClassName findDepth.java
* @Description 阿里笔试题 找到一个多维数组的维度
* @createTime 2021年03月16日 00:00:00
*/
public class findDepth {
public static int findDepth(ArrayList array){
List<Integer> depths = new ArrayList<>();
for (int i = 0; i <array.size(); i++) {
int depth = 0;
if (array.getClass().isArray()) {
depth = findDepth((ArrayList) array.get(i));
}
depths.add(depth);
}
depths.sort(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1-o2; //升序
}
});
return depths.get(depths.size() - 1) + 1;
}
}
|
package cn.aurora.ssh.service;
import java.util.List;
import java.util.zip.ZipInputStream;
import org.activiti.engine.repository.Deployment;
public interface IWorkflowService {
void saveDeployByZIP(ZipInputStream in, String fileName);
List<Deployment> findDeploymentAll();
}
|
/*
* Copyright (c) 2013, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.test.lib.compiler;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.tools.ForwardingJavaFileManager;
import javax.tools.FileObject;
import javax.tools.JavaCompiler;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.JavaFileObject;
import javax.tools.JavaFileObject.Kind;
import javax.tools.SimpleJavaFileObject;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider;
/**
* {@code InMemoryJavaCompiler} can be used for compiling a {@link
* CharSequence} to a {@code byte[]}.
*
* The compiler will not use the file system at all, instead using a {@link
* ByteArrayOutputStream} for storing the byte code. For the source code, any
* kind of {@link CharSequence} can be used, e.g. {@link String}, {@link
* StringBuffer} or {@link StringBuilder}.
*
* The {@code InMemoryCompiler} can easily be used together with a {@code
* ByteClassLoader} to easily compile and load source code in a {@link String}:
*
* <pre>
* {@code
* import jdk.test.lib.compiler.InMemoryJavaCompiler;
* import jdk.test.lib.ByteClassLoader;
*
* class Example {
* public static void main(String[] args) {
* String className = "Foo";
* String sourceCode = "public class " + className + " {" +
* " public void bar() {" +
* " System.out.println("Hello from bar!");" +
* " }" +
* "}";
* byte[] byteCode = InMemoryJavaCompiler.compile(className, sourceCode);
* Class fooClass = ByteClassLoader.load(className, byteCode);
* }
* }
* }
* </pre>
*/
public class InMemoryJavaCompiler {
private static class MemoryJavaFileObject extends SimpleJavaFileObject {
private final String className;
private final CharSequence sourceCode;
private final ByteArrayOutputStream byteCode;
public MemoryJavaFileObject(String className, CharSequence sourceCode) {
super(URI.create("string:///" + className.replace('.','/') + Kind.SOURCE.extension), Kind.SOURCE);
this.className = className;
this.sourceCode = sourceCode;
this.byteCode = new ByteArrayOutputStream();
}
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return sourceCode;
}
@Override
public OutputStream openOutputStream() throws IOException {
return byteCode;
}
public byte[] getByteCode() {
return byteCode.toByteArray();
}
public String getClassName() {
return className;
}
}
private static class FileManagerWrapper extends ForwardingJavaFileManager {
private static final Location PATCH_LOCATION = new Location() {
@Override
public String getName() {
return "patch module location";
}
@Override
public boolean isOutputLocation() {
return false;
}
};
private final MemoryJavaFileObject file;
private final String moduleOverride;
public FileManagerWrapper(MemoryJavaFileObject file, String moduleOverride) {
super(getCompiler().getStandardFileManager(null, null, null));
this.file = file;
this.moduleOverride = moduleOverride;
}
@Override
public JavaFileObject getJavaFileForOutput(Location location, String className,
Kind kind, FileObject sibling)
throws IOException {
if (!file.getClassName().equals(className)) {
throw new IOException("Expected class with name " + file.getClassName() +
", but got " + className);
}
return file;
}
@Override
public Location getLocationForModule(Location location, JavaFileObject fo) throws IOException {
if (fo == file && moduleOverride != null) {
return PATCH_LOCATION;
}
return super.getLocationForModule(location, fo);
}
@Override
public String inferModuleName(Location location) throws IOException {
if (location == PATCH_LOCATION) {
return moduleOverride;
}
return super.inferModuleName(location);
}
@Override
public boolean hasLocation(Location location) {
return super.hasLocation(location) || location == StandardLocation.PATCH_MODULE_PATH;
}
}
/**
* Compiles the class with the given name and source code.
*
* @param className The name of the class
* @param sourceCode The source code for the class with name {@code className}
* @param options additional command line options
* @throws RuntimeException if the compilation did not succeed
* @return The resulting byte code from the compilation
*/
public static byte[] compile(String className, CharSequence sourceCode, String... options) {
MemoryJavaFileObject file = new MemoryJavaFileObject(className, sourceCode);
CompilationTask task = getCompilationTask(file, options);
if(!task.call()) {
throw new RuntimeException("Could not compile " + className + " with source code " + sourceCode);
}
return file.getByteCode();
}
private static JavaCompiler getCompiler() {
return ToolProvider.getSystemJavaCompiler();
}
private static CompilationTask getCompilationTask(MemoryJavaFileObject file, String... options) {
List<String> opts = new ArrayList<>();
String moduleOverride = null;
for (String opt : options) {
if (opt.startsWith("--patch-module=")) {
moduleOverride = opt.substring("--patch-module=".length());
} else {
opts.add(opt);
}
}
return getCompiler().getTask(null, new FileManagerWrapper(file, moduleOverride), null, opts, null, Arrays.asList(file));
}
}
|
package com.smxknife.algorithm.demo01.quicksort;
import com.google.common.base.Preconditions;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @author smxknife
* 2019-04-29
*/
@Slf4j
public class QuickSort {
public static <T extends Comparable> List<T> sort(List<T> elements) {
Preconditions.checkNotNull(elements);
// List<T> org = new ArrayList<>(elements.size());
// org.addAll(elements);
// if (org.size() < 2) return org; // 基线条件
// T pivot = org.remove(0); // 基准值
if (elements.size() < 2) return new ArrayList<>(elements);
T pivot = elements.get(0); // 基准值
Map<Boolean, List<T>> partition = elements.stream()
.filter(e -> !e.equals(pivot))
.collect(Collectors.partitioningBy(t -> t.compareTo(pivot) <= 0));
List<T> subList = new ArrayList<>(elements.size());
if (log.isInfoEnabled()) log.info("elements = {}, pivot = {}, lf = {}, gt = {}", elements, pivot, partition.get(true), partition.get(false));
subList.addAll(sort(partition.get(true))); // 小于基准值递归
subList.add(pivot);
subList.addAll(sort(partition.get(false))); // 大于基准值递归
return subList;
}
}
|
package test.thread;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* Copyright (c) by www.leya920.com
* All right reserved.
* Create Date: 2017-02-14 09:51
* Create Author: maguoqiang
* File Name: CallableFutureTest.java
* Last version: 1.0
* Function: //TODO
* Last Update Date: 2017-02-14 09:51
* Last Update Log:
* Comment: //TODO
**/
public class CallableFutureTest {
@SuppressWarnings("unchecked")
public static void main(String[] args) throws ExecutionException,
InterruptedException {
CallableFutureTest test = new CallableFutureTest();
// 创建一个线程池
ExecutorService pool = Executors.newFixedThreadPool(2);
// 创建两个有返回值的任务
Callable c1 = test.new MyCallable("A");
Callable c2 = test.new MyCallable("B");
// 执行任务并获取Future对象
Future f1 = pool.submit(c1);
Future f2 = pool.submit(c2);
// 从Future对象上获取任务的返回值,并输出到控制台
System.out.println(">>>" + f1.get().toString());
System.out.println(">>>" + f2.get().toString());
// 关闭线程池
pool.shutdown();
}
@SuppressWarnings("unchecked")
class MyCallable implements Callable {
private String name;
MyCallable(String name) {
this.name = name;
}
public Object call() throws Exception {
return name + "任务返回的内容";
}
}
}
|
package com.company;
import org.junit.Test;
import java.util.Stack;
// WXG 技术研究1面 5道笔试题
public class Main_WXG {
static String path = "/Users/sunyindong/workspace/TestJava/Leetcode/src/main/resources/";
@Test
public void test1() {
// System.out.println(isLucky("1"));
System.out.println(isLucky("14"));
System.out.println(isLucky("144"));
System.out.println(isLucky("1411144"));
System.out.println(isLucky("14441"));
}
public static boolean isLucky(String num) {
if (num == null || num.length() == 0 || num.charAt(0) != '1') {
return false;
}
int sz = num.length();
int[] dp = new int[sz];
dp[0] = 1;
for (int i = 1; i < sz; i++) {
for (int j = 0; j <= 2; j++) {
int end = i + 1;
int start = i - j;
if (dp[i] == 1) break;
if (start >= 0) {
String item = num.substring(start, end);
switch (item) {
case "1":
case "14":
case "144": {
if (start == 0) {
dp[i] = 1;
} else {
dp[i] = dp[start - 1] == 1 ? 1 : dp[i];
}
break;
}
}
}
}
}
return dp[sz - 1] == 1;
}
@Test
public void test2() {
ListNode li4 = new ListNode(4, null);
ListNode li3 = new ListNode(3, li4);
ListNode li2 = new ListNode(2, li3);
ListNode li1 = new ListNode(1, li2);
System.out.println(isCycle_2(li1));
li4.next = li2;
System.out.println(isCycle_2(li1));
}
public static boolean isCycle_2(ListNode head) {
if (head == null || head.next == null) return false;
ListNode low = head, fast = head.next;
while (fast != null && fast.next != null) {
if (fast == low) return true;
fast = fast.next.next;
low = low.next;
}
return false;
}
@Test
public void test3() {
BigInteger bigInteger = new BigInteger("1233311110111321321213111");
bigInteger.add("22003000033432423423432432432432");
System.out.println(bigInteger);
}
public static class BigInteger {
private String val;
public void add(String need) {
add(new BigInteger(need));
}
public void add(BigInteger need) {
if (need == null) return;
String needAdd = need.getVal();
if (needAdd.equals("")) return;
int overFlow = 0;
if (needAdd.length() > val.length()) {
String tmp = val;
val = needAdd;
needAdd = tmp;
}
needAdd = new StringBuilder(needAdd).reverse().toString();
val = new StringBuilder(val).reverse().toString();
StringBuffer buffer = new StringBuffer();
int needAddSz = needAdd.length();
for (int i = 0; i <= val.length(); i++) {
char valChar = '0';
if (i < val.length()) {
valChar = val.charAt(i);
}
char needChar = '0';
if (i < needAddSz) {
needChar = needAdd.charAt(i);
}
if (!Character.isDigit(valChar) || !Character.isDigit(needChar)) {
throw new RuntimeException("ERROR INPUT");
}
int curNum = (needChar - '0') + (valChar - '0') + overFlow;
overFlow = curNum / 10;
curNum = curNum % 10;
buffer.append(curNum);
}
val = buffer.reverse().toString();
preZeroTrim();
}
private void preZeroTrim() {
for (int i = 0; i < val.length(); i++) {
if (val.charAt(i) == '0') {
continue;
} else {
val = val.substring(i);
break;
}
}
}
public BigInteger() {
this.val = "";
}
public BigInteger(String val) {
this.val = val;
}
public String getVal() {
return val;
}
public void setVal(String val) {
this.val = val;
}
@Override
public String toString() {
return val;
}
}
@Test
public void test4() {
int[] in = {1, 2, 3, 4, 5};
int[] out = {3, 2, 4, 1, 5};
System.out.println(isPostOrder_4(in, out));
int[] out2 = {2, 4, 3, 1, 5};
System.out.println(isPostOrder_4(in, out2));
int[] out3 = {5, 3, 4, 2, 1};
System.out.println(isPostOrder_4(in, out3));
}
public static boolean isPostOrder_4(int[] in, int[] out) {
if (in == null || out == null) return false;
if (in.length != out.length) return false;
Stack<Integer> stack = new Stack<>();
for (int i = 0, j = 0; i < out.length; i++) {
stack.add(in[i]);
while (!stack.isEmpty() && stack.peek().equals(out[j])) {
stack.pop();
j++;
}
}
return stack.isEmpty();
}
@Test
public void test5() {
TreeNode tree22 = new TreeNode(2);
TreeNode tree21 = new TreeNode(2);
TreeNode tree1 = new TreeNode(1);
TreeNode tree3 = new TreeNode(3);
tree1.left = tree21;
tree1.right = tree22;
System.out.println(isSame_5(tree1, tree1));
tree22.left = tree3;
System.out.println(isSame_5(tree1, tree1));
}
public static boolean isSame_5(TreeNode left, TreeNode right) {
if (left == null && right == null) {
return true;
}
if (left == null || right == null) {
return false;
}
return left.val == right.val && isSame_5(left.left, right.right) && isSame_5(left.right, right.left);
}
static class TreeNode {
int val;
TreeNode left, right;
public TreeNode(int val) {
this.val = val;
}
}
static class ListNode {
int val;
ListNode next;
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
}
|
package com.takshine.wxcrm.domain;
public class TaskParent {
private String taskid=null;
private String parentid=null;
private String parenttype=null;
public String getTaskid() {
return taskid;
}
public void setTaskid(String taskid) {
this.taskid = taskid;
}
public String getParentid() {
return parentid;
}
public void setParentid(String parentid) {
this.parentid = parentid;
}
public String getParenttype() {
return parenttype;
}
public void setParenttype(String parenttype) {
this.parenttype = parenttype;
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*/
package org.apache.clerezza.utils;
import org.apache.clerezza.*;
import org.apache.clerezza.implementation.TripleImpl;
import org.apache.clerezza.ontologies.OWL;
import org.apache.clerezza.ontologies.RDF;
import org.apache.clerezza.representation.Serializer;
import org.apache.clerezza.representation.SupportedFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileOutputStream;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.*;
/**
* An implementation of an <code>java.util.List</code> backed by an RDF
* collection (rdf:List). The list allows modification that are reflected
* to the underlying <code>Graph</code>. It reads the data from the
* <code>Graph</code> when it is first needed, so changes to the
* Graph affecting the rdf:List may or may not have an effect on the
* values returned by instances of this class. For that reason only one
* instance of this class should be used for accessing an rdf:List of sublists
* thereof when the lists are being modified, having multiple lists exclusively
* for read operations (such as for immutable <code>Graph</code>s) is
* not problematic.
*
* @author rbn, mir
*/
public class RdfList extends AbstractList<RDFTerm> {
private static final Logger logger = LoggerFactory.getLogger(RdfList.class);
private final static IRI RDF_NIL =
new IRI("http://www.w3.org/1999/02/22-rdf-syntax-ns#nil");
/**
* a list of the linked rdf:List elements in order
*/
private List<BlankNodeOrIRI> listList = new ArrayList<BlankNodeOrIRI>();
private List<RDFTerm> valueList = new ArrayList<RDFTerm>();
private BlankNodeOrIRI firstList;
private Graph tc;
private boolean totallyExpanded = false;
/**
* Get a list for the specified resource.
* <p>
* If the list is modified using the created instance
* <code>listRDFTerm</code> will always be the first list.
*
* @param listRDFTerm
* @param tc
*/
public RdfList(BlankNodeOrIRI listRDFTerm, Graph tc) {
firstList = listRDFTerm;
this.tc = tc;
}
/**
* Get a list for the specified resource node.
*
* @param listNode
*/
public RdfList(GraphNode listNode) {
this((BlankNodeOrIRI) listNode.getNode(), listNode.getGraph());
}
/**
* Creates an empty RdfList by writing a triple
* "{@code listRDFTerm} owl:sameAs rdf.nil ." to {@code tc}.
*
* @param listRDFTerm
* @param tc
* @return an empty rdf:List.
* @throws IllegalArgumentException if the provided {@code listRDFTerm} is a non-empty rdf:List.
*/
public static RdfList createEmptyList(BlankNodeOrIRI listRDFTerm, Graph tc)
throws IllegalArgumentException {
if (!tc.filter(listRDFTerm, RDF.first, null).hasNext()) {
RdfList list = new RdfList(listRDFTerm, tc);
list.tc.add(new TripleImpl(listRDFTerm, OWL.sameAs, RDF_NIL));
return list;
} else {
throw new IllegalArgumentException(listRDFTerm + "is a non-empty rdf:List.");
}
}
private void expandTill(int pos) {
if (totallyExpanded) {
return;
}
BlankNodeOrIRI currentList;
if (listList.size() > 0) {
currentList = listList.get(listList.size() - 1);
} else {
currentList = firstList;
if (!tc.filter(currentList, RDF.first, null).hasNext()) {
return;
}
listList.add(currentList);
valueList.add(getFirstEntry(currentList));
}
if (listList.size() >= pos) {
return;
}
while (true) {
currentList = getRest(currentList);
if (currentList.equals(RDF_NIL)) {
totallyExpanded = true;
break;
}
if (listList.size() == pos) {
break;
}
valueList.add(getFirstEntry(currentList));
listList.add(currentList);
}
}
@Override
public RDFTerm get(int index) {
expandTill(index + 1);
return valueList.get(index);
}
@Override
public int size() {
expandTill(Integer.MAX_VALUE);
return valueList.size();
}
@Override
public void add(int index, RDFTerm element) {
expandTill(index);
if (index == 0) {
//special casing to make sure the first list remains the same resource
if (listList.size() == 0) {
tc.remove(new TripleImpl(firstList, OWL.sameAs, RDF_NIL));
tc.add(new TripleImpl(firstList, RDF.rest, RDF_NIL));
tc.add(new TripleImpl(firstList, RDF.first, element));
listList.add(firstList);
} else {
tc.remove(new TripleImpl(listList.get(0), RDF.first, valueList.get(0)));
tc.add(new TripleImpl(listList.get(0), RDF.first, element));
addInRdfList(1, valueList.get(0));
}
} else {
addInRdfList(index, element);
}
valueList.add(index, element);
}
/**
* @param index is > 0
* @param element
*/
private void addInRdfList(int index, RDFTerm element) {
expandTill(index + 1);
BlankNodeOrIRI newList = new BlankNode() {
};
tc.add(new TripleImpl(newList, RDF.first, element));
if (index < listList.size()) {
tc.add(new TripleImpl(newList, RDF.rest, listList.get(index)));
tc.remove(new TripleImpl(listList.get(index - 1), RDF.rest, listList.get(index)));
} else {
tc.remove(new TripleImpl(listList.get(index - 1), RDF.rest, RDF_NIL));
tc.add(new TripleImpl(newList, RDF.rest, RDF_NIL));
}
tc.add(new TripleImpl(listList.get(index - 1), RDF.rest, newList));
listList.add(index, newList);
}
@Override
public RDFTerm remove(int index) {
//keeping the first list resource
tc.remove(new TripleImpl(listList.get(index), RDF.first, valueList.get(index)));
if (index == (listList.size() - 1)) {
tc.remove(new TripleImpl(listList.get(index), RDF.rest, RDF_NIL));
if (index > 0) {
tc.remove(new TripleImpl(listList.get(index - 1), RDF.rest, listList.get(index)));
tc.add(new TripleImpl(listList.get(index - 1), RDF.rest, RDF_NIL));
} else {
tc.add(new TripleImpl(listList.get(index), OWL.sameAs, RDF_NIL));
}
listList.remove(index);
} else {
tc.add(new TripleImpl(listList.get(index), RDF.first, valueList.get(index + 1)));
tc.remove(new TripleImpl(listList.get(index), RDF.rest, listList.get(index + 1)));
tc.remove(new TripleImpl(listList.get(index + 1), RDF.first, valueList.get(index + 1)));
if (index == (listList.size() - 2)) {
tc.remove(new TripleImpl(listList.get(index + 1), RDF.rest, RDF_NIL));
tc.add(new TripleImpl(listList.get(index), RDF.rest, RDF_NIL));
} else {
tc.remove(new TripleImpl(listList.get(index + 1), RDF.rest, listList.get(index + 2)));
tc.add(new TripleImpl(listList.get(index), RDF.rest, listList.get(index + 2)));
}
listList.remove(index + 1);
}
return valueList.remove(index);
}
private BlankNodeOrIRI getRest(BlankNodeOrIRI list) {
return (BlankNodeOrIRI) tc.filter(list, RDF.rest, null).next().getObject();
}
private RDFTerm getFirstEntry(final BlankNodeOrIRI listRDFTerm) {
try {
return tc.filter(listRDFTerm, RDF.first, null).next().getObject();
} catch (final NullPointerException e) {
RuntimeException runtimeEx = AccessController.doPrivileged(new PrivilegedAction<RuntimeException>() {
@Override
public RuntimeException run() {
try {
final FileOutputStream fileOutputStream = new FileOutputStream("/tmp/broken-list.nt");
final GraphNode graphNode = new GraphNode(listRDFTerm, tc);
Serializer.getInstance().serialize(fileOutputStream, graphNode.getNodeContext(), SupportedFormat.N_TRIPLE);
fileOutputStream.flush();
logger.warn("GraphNode: " + graphNode);
final Iterator<IRI> properties = graphNode.getProperties();
while (properties.hasNext()) {
logger.warn("available: " + properties.next());
}
return new RuntimeException("broken list " + listRDFTerm, e);
} catch (Exception ex) {
return new RuntimeException(ex);
}
}
});
throw runtimeEx;
}
}
public BlankNodeOrIRI getListRDFTerm() {
return firstList;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final RdfList other = (RdfList) obj;
if (!other.firstList.equals(this.firstList)) {
return false;
}
if (!other.tc.equals(this.tc)) {
return false;
}
return true;
}
@Override
public int hashCode() {
return 17 * this.firstList.hashCode() + this.tc.hashCode();
}
/**
* Returns the rdf lists of which the specified <code>GraphNode</code> is
* an element of. Sublists of other lists are not returned.
*
* @param element
* @return
*/
public static Set<RdfList> findContainingLists(GraphNode element) {
Set<GraphNode> listNodes = findContainingListNodes(element);
if (listNodes.isEmpty()) {
return null;
}
Set<RdfList> rdfLists = new HashSet<RdfList>();
for (Iterator<GraphNode> it = listNodes.iterator(); it.hasNext(); ) {
GraphNode listNode = it.next();
rdfLists.add(new RdfList(listNode));
}
return rdfLists;
}
/**
* Returns a set of <code>GraphNode</code>S which are the first list nodes (meaning
* they are not the beginning of a sublist) of the list containing the specified
* <code>GraphNode</code> as an element.
*
* @param element
* @return
*/
public static Set<GraphNode> findContainingListNodes(GraphNode element) {
Iterator<GraphNode> partOfaListNodesIter = element.getSubjectNodes(RDF.first);
if (!partOfaListNodesIter.hasNext()) {
return null;
}
Set<GraphNode> listNodes = new HashSet<GraphNode>();
while (partOfaListNodesIter.hasNext()) {
listNodes.addAll(findAllListNodes(partOfaListNodesIter.next()));
}
return listNodes;
}
private static Set<GraphNode> findAllListNodes(GraphNode listPart) {
Iterator<GraphNode> invRestNodesIter;
Set<GraphNode> listNodes = new HashSet<GraphNode>();
do {
invRestNodesIter = listPart.getSubjectNodes(RDF.rest);
if (invRestNodesIter.hasNext()) {
listPart = invRestNodesIter.next();
while (invRestNodesIter.hasNext()) {
GraphNode graphNode = invRestNodesIter.next();
listNodes.addAll(findAllListNodes(graphNode));
}
} else {
listNodes.add(listPart);
break;
}
} while (true);
return listNodes;
}
}
|
package com.wrtecnologia.servicecep.service;
import com.wrtecnologia.servicecep.util.CepUtil;
import com.wrtecnologia.servicecep.dto.CepDTO;
import com.wrtecnologia.servicecep.domain.Cep;
import com.google.gson.Gson;
import com.wrtecnologia.servicecep.mapper.CepDTOMapper;
import org.springframework.stereotype.Service;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
@Service
public class CepService {
private static final String webService = "http://viacep.com.br/ws/";
private CepDTO cepDTO;
public static <CepDTO> CepDTO buscaEnderecoPeloCep(String cep) throws Exception {
String urlParaChamada = webService + cep + "/json";
try {
URL url = new URL(urlParaChamada);
HttpURLConnection conexao = (HttpURLConnection) url.openConnection();
if (conexao.getResponseCode() != 200)
throw new RuntimeException("HTTP error code : " + conexao.getResponseCode());
BufferedReader resposta = new BufferedReader(new InputStreamReader((conexao.getInputStream())));
String jsonEmString = CepUtil.converteJsonEmString(resposta);
Gson gson = new Gson();
Cep endereco = gson.fromJson(jsonEmString, Cep.class);
return (CepDTO) CepDTOMapper.parseParaDTO(endereco);
//return parseParaDTO(endereco);
} catch (Exception e) {
throw new Exception("ERRO: " + e);
}
}
} |
package fontys.sot.rest.client;
import fontys.sot.rest.client.classes.OrdersRequestHandler;
import fontys.sot.rest.client.classes.ProductsRequestHandler;
import fontys.sot.rest.service.enums.Role;
import fontys.sot.rest.service.models.LineItem;
import fontys.sot.rest.service.models.Order;
import fontys.sot.rest.service.models.Product;
import fontys.sot.rest.service.models.User;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.Response;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
public class OrderApplication extends JFrame {
private JPanel shopPanel;
private JTabbedPane shopTabPane;
private JPanel orderPanel;
private JPanel managePanel;
private JList productList;
private JButton refreshBtn;
private JLabel nameLb;
private JLabel unitLb;
private JLabel priceLb;
private JLabel discountLb;
private JRadioButton defaultSortRbtn;
private JRadioButton discountSortRbtn;
private JRadioButton priceSortRbtn;
private JTextField createNameTextField;
private JLabel createNameLb;
private JTextField unitTextField;
private JLabel createUnitLb;
private JSpinner quantitySpinner;
private JLabel createQuantityLb;
private JTextField priceTextField;
private JLabel createPriceLb;
private JButton createBtn;
private JLabel createOrUpdateProductLb;
private JList createOrUpdateList;
private JLabel createFeedbackLb;
private JButton updateBtn;
private JButton deleteBtn;
private JLabel priceFeedbackLb;
private JLabel quantityFeedbackLb;
private JLabel unitFeedbackLb;
private JLabel nameFeedbackLb;
private JList orderLineList;
private JPanel createOrderPanel;
private JButton removeLineItemBtn;
private JButton orderBtn;
private JSpinner lineItemSpinner;
private JButton addProductToOrderBtn;
private JLabel nrSelectedProductsLb;
private JLabel orderOverviewLb;
private JLabel nrOfLineItemsFeedbackLb;
private JLabel orderTotalLb;
private JLabel removeLineItemFeedbackLb;
private JLabel productInformationLb;
private JLabel orderCartFeedbackLb;
private JTextField searchTextField;
private JButton searchBtn;
private JLabel searchNameLb;
private JLabel searchFeedbackLb;
private JLabel sortByLb;
private JLabel productsLb;
private JSpinner discountSpinner;
private JButton setDiscountBtn;
private JLabel applyDiscountLb;
private JLabel discountFeedbackLb;
private JLabel createDiscountPriceLb;
private JLabel createDiscountedPriceValueLb;
private static int MANAGE_TAB_INDEX = 1;
private User user;
private ProductsRequestHandler prh;
private OrdersRequestHandler orh;
private Product selectedProduct;
private Order order;
private boolean validProductDetails;
public OrderApplication(User user) {
this("SHOP");
this.user = user;
orh = new OrdersRequestHandler();
getNewOrder();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setContentPane(shopPanel);
pack();
if (isNotManager(this.user)) {
shopTabPane.setEnabledAt(MANAGE_TAB_INDEX, false);
shopTabPane.remove(MANAGE_TAB_INDEX);
}
addProductToOrderBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Product selected = (Product) productList.getSelectedValue();
if (selected != null) {
int quantity = (Integer) lineItemSpinner.getValue();
LineItem li = new LineItem(selected, quantity);
order.addLineItem(li);
updateOrderInfo();
clearLabel(nrOfLineItemsFeedbackLb);
} else {
nrOfLineItemsFeedbackLb.setText("Please select a product from the overview!");
nrOfLineItemsFeedbackLb.setForeground(Color.RED);
}
}
});
removeLineItemBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
LineItem selectedLi = (LineItem) orderLineList.getSelectedValue();
if (selectedLi != null) {
order.remove(selectedLi);
updateOrderInfo();
clearLabel(removeLineItemFeedbackLb);
} else {
removeLineItemFeedbackLb.setText("Please select a line item from your cart");
removeLineItemFeedbackLb.setForeground(Color.RED);
}
}
});
orderBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (order.isEmpty()) {
orderCartFeedbackLb.setText("Make sure to add products before ordering!");
orderCartFeedbackLb.setForeground(Color.RED);
} else {
Response response = orh.store(order);
if (response.getStatus() == Response.Status.OK.getStatusCode()) {
orderCartFeedbackLb.setText("Successfully placed order with number: " + order.getNumber());
orderCartFeedbackLb.setForeground(Color.GREEN);
getNewOrder();
updateOrderInfo();
} else {
orderCartFeedbackLb.setText("Something went wrong!");
orderCartFeedbackLb.setForeground(Color.RED);
}
}
}
});
searchBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String searchName = searchTextField.getText();
if (searchName != null) {
Response response = prh.find(searchName);
if (response.getStatus() == Response.Status.OK.getStatusCode()) {
clearLabel(searchFeedbackLb);
GenericType<List<Product>> genericType = new GenericType<>() {
};
List<Product> matches = response.readEntity(genericType);
productList.setListData(matches.toArray());
} else {
searchFeedbackLb.setText("Something went wrong when trying to get search matches");
searchFeedbackLb.setForeground(Color.RED);
}
} else {
searchFeedbackLb.setText("Please enter text to search");
searchFeedbackLb.setForeground(Color.RED);
}
}
});
setDiscountBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
clearLabel(discountFeedbackLb);
Product selectedProduct = (Product) createOrUpdateList.getSelectedValue();
if (selectedProduct != null) {
int discountPercentage = (Integer) discountSpinner.getValue();
prh.setDiscount(selectedProduct.getId(), discountPercentage);
refreshProducts();
discountSpinner.setValue(0);
} else {
discountFeedbackLb.setText("Please select a product");
discountFeedbackLb.setForeground(Color.RED);
}
}
});
}
private void updateOrderInfo() {
orderLineList.setListData(order.getLineItems().toArray());
orderTotalLb.setText(String.format("Order total: € %.2f", order.getTotal()));
}
public OrderApplication(String title) {
super(title);
prh = new ProductsRequestHandler();
// $$$setupUI$$$();
refreshProducts();
refreshBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
refreshProducts();
}
});
productList.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
selectedProduct = (Product) productList.getSelectedValue();
if (selectedProduct != null) {
setProductDetails(selectedProduct);
} else {
clearProductDetails();
}
}
});
createBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Product product = createProduct();
if (product != null) {
clearInputs();
refreshProducts();
}
}
});
deleteBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Product selected = (Product) createOrUpdateList.getSelectedValue();
if (selected != null) {
Response response = prh.delete(selected.getId());
if (response.getStatus() == Response.Status.OK.getStatusCode()) {
createFeedbackLb.setText("Successfully deleted: " + selected.getName());
createFeedbackLb.setForeground(Color.GREEN);
refreshProducts();
} else if (response.getStatus() == Response.Status.NOT_FOUND.getStatusCode()) {
createFeedbackLb.setText("Could not find: " + selected.getName());
createFeedbackLb.setForeground(Color.GREEN);
} else {
createFeedbackLb.setText("Something went wrong when trying to delete the selected product.");
createFeedbackLb.setForeground(Color.RED);
}
}
}
});
updateBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Product selected = (Product) createOrUpdateList.getSelectedValue();
int id = selected.getId();
String name = createNameTextField.getText();
String unit = unitTextField.getText();
int quantity = (Integer) quantitySpinner.getValue();
double price = 0.0;
try {
price = Double.parseDouble(priceTextField.getText());
} catch (NumberFormatException ex) {
}
Response response = prh.update(id, name, unit, quantity, price);
if (response.getStatus() == Response.Status.OK.getStatusCode()) {
createFeedbackLb.setText("Successfully updated: " + selected.getId());
createFeedbackLb.setForeground(Color.GREEN);
refreshProducts();
} else if (response.getStatus() == Response.Status.NOT_FOUND.getStatusCode()) {
createFeedbackLb.setText("Could not find: " + selected.getName());
createFeedbackLb.setForeground(Color.GREEN);
} else {
createFeedbackLb.setText("Something went wrong when trying to delete the selected product.");
createFeedbackLb.setForeground(Color.RED);
}
}
});
createOrUpdateList.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
clearFeedbackLabels();
Product selected = (Product) createOrUpdateList.getSelectedValue();
if (selected != null) {
createNameTextField.setText(selected.getName());
unitTextField.setText(selected.getUnit());
quantitySpinner.setValue(selected.getQuantity());
priceTextField.setText(String.valueOf(selected.getPrice()));
discountSpinner.setValue(selected.getDiscountPercentage());
createDiscountedPriceValueLb.setText(String.format("€ %.2f", selected.getDiscountedPrice()));
} else {
clearInputs();
}
}
});
}
private void getNewOrder() {
Response response = orh.get(user.getId());
order = response.readEntity(Order.class);
}
private void clearInputs() {
createNameTextField.setText("");
unitTextField.setText("");
quantitySpinner.setValue(0);
priceTextField.setText("");
discountSpinner.setValue(0);
createDiscountedPriceValueLb.setText("");
}
private Product createProduct() {
validProductDetails = true;
clearFeedbackLabels();
String name = createNameTextField.getText();
String unit = unitTextField.getText();
int quantity = (Integer) quantitySpinner.getValue();
double price = -1.0;
try {
price = Double.parseDouble(priceTextField.getText());
} catch (NumberFormatException ex) {
createFeedbackLb.setText("Could not parse price!");
createFeedbackLb.setForeground(Color.RED);
validProductDetails = false;
}
if (validProductDetails) {
validate(nameFeedbackLb, "Name", name);
validate(unitFeedbackLb, "Unit", unit);
validateQuantity(quantity);
validatePrice(price);
}
if (validProductDetails) {
Response response = prh.create(name, unit, quantity, price);
if (response.getStatus() == Response.Status.CREATED.getStatusCode()) {
clearInputs();
createFeedbackLb.setText("Product successfully created");
createFeedbackLb.setForeground(Color.GREEN);
return response.readEntity(Product.class);
}
}
return null;
}
private void clearFeedbackLabels() {
clearLabel(createFeedbackLb);
clearLabel(nameFeedbackLb);
clearLabel(unitFeedbackLb);
clearLabel(quantityFeedbackLb);
clearLabel(priceFeedbackLb);
}
private void validatePrice(double price) {
if (price < 0) {
priceFeedbackLb.setText("Price must be > 0");
priceFeedbackLb.setForeground(Color.RED);
validProductDetails = false;
}
}
private void validateQuantity(int quantity) {
if (quantity <= 0) {
quantityFeedbackLb.setText("Quantity must be > 0");
quantityFeedbackLb.setForeground(Color.RED);
validProductDetails = false;
}
}
private void validate(JLabel feedbackLb, String field, String value) {
if (nullOrEmpty(value)) {
feedbackLb.setText(field + " is required");
feedbackLb.setForeground(Color.RED);
validProductDetails = false;
}
}
private boolean nullOrEmpty(String value) {
return value == null || value.equals("");
}
private void clearProductDetails() {
clearLabel(nameLb);
clearLabel(unitLb);
clearLabel(priceLb);
clearLabel(discountLb);
}
private void clearLabel(JLabel label) {
label.setText("");
}
private void setProductDetails(Product product) {
nameLb.setText("Product: " + product.getName());
unitLb.setText("Quantity: " + product.getQuantity() + " " + product.getUnit());
priceLb.setText(String.format("Costs: € %.2f", product.getDiscountedPrice()));
if (product.isDiscounted()) {
discountLb.setText("Discount: " + product.getDiscountPercentage() + "% off");
} else {
discountLb.setText("");
}
}
private void refreshProducts() {
String sortMethod = getSortMethod();
Response response = prh.getAll(sortMethod);
if (response.getStatus() == Response.Status.OK.getStatusCode()) {
GenericType<List<Product>> genericTyp = new GenericType<>() {
};
List<Product> products = response.readEntity(genericTyp);
productList.setListData(products.toArray());
createOrUpdateList.setListData(products.toArray());
}
}
private String getSortMethod() {
if (priceSortRbtn.isSelected()) {
return "PRICE";
} else if (discountSortRbtn.isSelected()) {
return "DISCOUNT";
} else {
return "ID";
}
}
private boolean isNotManager(User user) {
return !isManager(user);
}
private boolean isManager(User user) {
for (Role role : user.getRoles()) {
if (role == Role.CATEGORY_MANAGER) {
return true;
}
}
return false;
}
private void createUIComponents() {
// TODO: place custom component creation code here
SpinnerModel model = new SpinnerNumberModel(1, 1, 999, 1);
SpinnerModel discountModel = new SpinnerNumberModel(0, 0, 100, 1);
quantitySpinner = new JSpinner(model);
lineItemSpinner = new JSpinner(model);
discountSpinner = new JSpinner(discountModel);
}
public static void main(String[] args) {
// Here for testing all functionality directly.
User manager = new User();
manager.getRoles().add(Role.CATEGORY_MANAGER);
OrderApplication orderApp = new OrderApplication(manager);
orderApp.setVisible(true);
}
}
|
package com.mentonica.subcraft.players;
import com.mentonica.subcraft.get.data.Constants;
import com.mentonica.subcraft.get.data.Variables;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class Insert extends JavaPlugin {
private static URL url;
public static void insertPlayer(String rank, String playerName) throws IOException {
if (!Variables.addedPlayers.contains(playerName)) {
String URL_LOCATION = Constants.URL_LOCATION + "player.php?username=" + playerName + "&rank=" + rank;
url = new URL(URL_LOCATION);
URLConnection conn = url.openConnection();
new BufferedReader(
new InputStreamReader(conn.getInputStream()));
Variables.addedPlayers.add(playerName);
System.out.println(URL_LOCATION);
}
}
}
|
package com.stark.innerclass;
/**
* 局部内部类
* 1.定义在方法体,甚至比方法体更小的代码块中
* 2.类比局部变量。
* 3.局部内部类是所有内部类中最少使用的一种形式。
* 4.局部内部类可以访问的外部类的成员根据所在方法体不同。
* 如果在静态方法中:
* 可以访问外部类中所有静态成员,包含私有
* 如果在实例方法中:
* 可以访问外部类中所有的成员,包含私有。
* 局部内部类可以访问所在方法中定义的局部变量,但是要求局部变量不会被修改(通常使用final 关键字)。
* 5.局部类内部类不能定义除了常量以外静态成员
*/
public class LocalInnerTest {
public static void main(String[] args) {
LocalOuter.test1();
new LocalOuter().test2();
}
}
class LocalOuter {
private static String s1 = "outer static member";
private String s3 = "outer member";
public static void test1() {
String s2 = "outer static fuction member";
class LocalInner {
private /*static*/ String s5 = "innner member";
private /*static*/ void print() {
System.out.println(s1);
System.out.println(s2);
System.out.println(s5);
}
}
new LocalInner().print();
}
public void test2() {
final String s2 = "outer fuction member";
String s4 = "outer fuction member no final";
class LocalInner {
private /*static*/ String s5 = "innner member";
private void print() {
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s4);
System.out.println(s5);
}
}
new LocalInner().print();
}
}
|
package gr.excite.atm.service;
import gr.excite.atm.model.Demand;
public interface IDistributer {
public void giveMoney(Demand demand);
public void setNextDistributer(IDistributer nextDistributer);
}
|
package pl.szczodrzynski.edziennik.ui.modules.settings;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.provider.Settings;
import android.widget.Toast;
import com.afollestad.materialdialogs.MaterialDialog;
import com.danielstone.materialaboutlibrary.ConvenienceBuilder;
import com.danielstone.materialaboutlibrary.MaterialAboutFragment;
import com.danielstone.materialaboutlibrary.items.MaterialAboutActionItem;
import com.danielstone.materialaboutlibrary.items.MaterialAboutActionSwitchItem;
import com.danielstone.materialaboutlibrary.items.MaterialAboutItem;
import com.danielstone.materialaboutlibrary.items.MaterialAboutItemOnClickAction;
import com.danielstone.materialaboutlibrary.items.MaterialAboutProfileItem;
import com.danielstone.materialaboutlibrary.items.MaterialAboutSwitchItem;
import com.danielstone.materialaboutlibrary.items.MaterialAboutTitleItem;
import com.danielstone.materialaboutlibrary.model.MaterialAboutCard;
import com.danielstone.materialaboutlibrary.model.MaterialAboutList;
import com.mikepenz.iconics.IconicsColor;
import com.mikepenz.iconics.IconicsDrawable;
import com.mikepenz.iconics.IconicsSize;
import com.mikepenz.iconics.typeface.library.community.material.CommunityMaterial;
import com.mikepenz.iconics.typeface.library.szkolny.font.SzkolnyFont;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import com.wdullaer.materialdatetimepicker.time.TimePickerDialog;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import pl.szczodrzynski.edziennik.App;
import pl.szczodrzynski.edziennik.BuildConfig;
import pl.szczodrzynski.edziennik.ExtensionsKt;
import pl.szczodrzynski.edziennik.MainActivity;
import pl.szczodrzynski.edziennik.R;
import pl.szczodrzynski.edziennik.data.api.szkolny.SzkolnyApi;
import pl.szczodrzynski.edziennik.data.db.entity.LoginStore;
import pl.szczodrzynski.edziennik.network.NetworkUtils;
import pl.szczodrzynski.edziennik.sync.SyncWorker;
import pl.szczodrzynski.edziennik.sync.UpdateWorker;
import pl.szczodrzynski.edziennik.ui.dialogs.changelog.ChangelogDialog;
import pl.szczodrzynski.edziennik.ui.dialogs.settings.AttendanceConfigDialog;
import pl.szczodrzynski.edziennik.ui.dialogs.settings.GradesConfigDialog;
import pl.szczodrzynski.edziennik.ui.dialogs.settings.ProfileRemoveDialog;
import pl.szczodrzynski.edziennik.ui.dialogs.sync.NotificationFilterDialog;
import pl.szczodrzynski.edziennik.ui.modules.login.LoginActivity;
import pl.szczodrzynski.edziennik.utils.Themes;
import pl.szczodrzynski.edziennik.utils.Utils;
import pl.szczodrzynski.edziennik.utils.models.Date;
import pl.szczodrzynski.edziennik.utils.models.Time;
import static android.app.Activity.RESULT_OK;
import static pl.szczodrzynski.edziennik.ExtensionsKt.initDefaultLocale;
import static pl.szczodrzynski.edziennik.data.db.entity.Profile.REGISTRATION_DISABLED;
import static pl.szczodrzynski.edziennik.data.db.entity.Profile.REGISTRATION_ENABLED;
import static pl.szczodrzynski.edziennik.utils.Utils.d;
import static pl.szczodrzynski.edziennik.utils.Utils.getRealPathFromURI;
import static pl.szczodrzynski.edziennik.utils.Utils.getResizedBitmap;
import static pl.szczodrzynski.edziennik.utils.managers.GradesManager.YEAR_1_AVG_2_AVG;
import static pl.szczodrzynski.edziennik.utils.managers.GradesManager.YEAR_1_AVG_2_SEM;
import static pl.szczodrzynski.edziennik.utils.managers.GradesManager.YEAR_1_SEM_2_AVG;
import static pl.szczodrzynski.edziennik.utils.managers.GradesManager.YEAR_1_SEM_2_SEM;
import static pl.szczodrzynski.edziennik.utils.managers.GradesManager.YEAR_ALL_GRADES;
public class SettingsNewFragment extends MaterialAboutFragment {
private static final String TAG = "Settings";
private App app = null;
private MainActivity activity;
private static final int CARD_PROFILE = 0;
private static final int CARD_THEME = 1;
private static final int CARD_SYNC = 2;
private static final int CARD_REGISTER = 3;
private static final int CARD_ABOUT = 4;
private int iconColor = Color.WHITE;
private int primaryTextOnPrimaryBg = -1;
private int secondaryTextOnPrimaryBg = -1;
private int iconSizeDp = 20;
private MaterialAboutCard getCardWithItems(CharSequence title, ArrayList<MaterialAboutItem> items, boolean primaryColor) {
MaterialAboutCard card = new MaterialAboutCard.Builder().title(title).cardColor(0xff1976D2).build();
card.getItems().addAll(items);
return card;
}
private MaterialAboutCard getCardWithItems(CharSequence title, ArrayList<MaterialAboutItem> items) {
MaterialAboutCard card = new MaterialAboutCard.Builder().title(title).cardColor(Utils.getAttr(activity, R.attr.mal_card_background)).build();
card.getItems().addAll(items);
return card;
}
private void addCardItems(int cardIndex, ArrayList<MaterialAboutItem> itemsNew) {
ArrayList<MaterialAboutItem> items = getList().getCards().get(cardIndex).getItems();
items.remove(items.size() - 1);
items.addAll(itemsNew);
refreshMaterialAboutList();
}
private void addCardItem(int cardIndex, int itemIndex, MaterialAboutItem item) {
ArrayList<MaterialAboutItem> items = getList().getCards().get(cardIndex).getItems();
items.add(itemIndex, item);
refreshMaterialAboutList();
}
private void removeCardItem(int cardIndex, int itemIndex) {
ArrayList<MaterialAboutItem> items = getList().getCards().get(cardIndex).getItems();
items.remove(itemIndex);
refreshMaterialAboutList();
}
private MaterialAboutActionItem getMoreItem(MaterialAboutItemOnClickAction onClickAction) {
return new MaterialAboutActionItem(
getString(R.string.settings_more_text),
null,
new IconicsDrawable(activity)
.icon(CommunityMaterial.Icon.cmd_chevron_down)
.size(IconicsSize.dp(14))
.color(IconicsColor.colorInt(iconColor)),
onClickAction
);
}
/* _____ __ _ _
| __ \ / _(_) |
| |__) | __ ___ | |_ _| | ___
| ___/ '__/ _ \| _| | |/ _ \
| | | | | (_) | | | | | __/
|_| |_| \___/|_| |_|_|\__*/
private Drawable getProfileDrawable() {
return app.getProfile().getImageDrawable(activity);
/*Bitmap profileImage = null;
if (app.getProfile().getImage() != null && !app.getProfile().getImage().equals("")) {
profileImage = BitmapFactory.decodeFile(app.getProfile().getImage());
RoundedBitmapDrawable roundDrawable = RoundedBitmapDrawableFactory.create(getResources(), profileImage);
roundDrawable.setCircular(true);
return roundDrawable;
}
return getDrawableFromRes(getContext(), R.drawable.profile);*/
/*if (profileImage == null) {
profileImage = BitmapFactory.decodeResource(getResources(), R.drawable.profile);
}
profileImage = ThumbnailUtils.extractThumbnail(profileImage, Math.min(profileImage.getWidth(), profileImage.getHeight()), Math.min(profileImage.getWidth(), profileImage.getHeight()));
RoundedBitmapDrawable roundDrawable = RoundedBitmapDrawableFactory.create(getResources(), profileImage);
roundDrawable.setCircular(true);
return roundDrawable;*/
}
private MaterialAboutProfileItem profileCardTitleItem;
private ArrayList<MaterialAboutItem> getProfileCard(boolean expandedOnly) {
ArrayList<MaterialAboutItem> items = new ArrayList<>();
if (!expandedOnly) {
profileCardTitleItem = new MaterialAboutProfileItem(
app.getProfile().getName(),
app.getProfile().getSubname(),
getProfileDrawable()
);
profileCardTitleItem.setOnClickAction(() -> {
new MaterialDialog.Builder(activity)
.title(R.string.settings_profile_change_title)
.items(
getString(R.string.settings_profile_change_name),
getString(R.string.settings_profile_change_image),
app.getProfile().getImage() == null ? null : getString(R.string.settings_profile_remove_image)
)
.itemsCallback((dialog, itemView, position, text) -> {
switch (position) {
case 0:
new MaterialDialog.Builder(activity)
.title(getString(R.string.settings_profile_change_name_dialog_title))
.input(getString(R.string.settings_profile_change_name_dialog_text), app.getProfile().getName(), (dialog1, input) -> {
app.getProfile().setName(input.toString());
profileCardTitleItem.setText(input);
profileCardTitleItem.setIcon(getProfileDrawable());
refreshMaterialAboutList();
app.profileSave();
})
.positiveText(R.string.ok)
.negativeText(R.string.cancel)
.show();
break;
case 1:
startActivityForResult(CropImage.getPickImageChooserIntent(activity), 21);
break;
case 2:
app.getProfile().setImage(null);
profileCardTitleItem.setIcon(getProfileDrawable());
refreshMaterialAboutList();
app.profileSave();
break;
}
})
.negativeText(R.string.cancel)
.show();
});
items.add(profileCardTitleItem);
/*items.add(
new MaterialAboutActionItem(
getString(R.string.settings_profile_change_password_text),
getString(R.string.settings_profile_change_password_subtext),
new IconicsDrawable(activity)
.icon(CommunityMaterial.Icon2.cmd_key_variant)
.size(IconicsSize.dp(iconSizeDp))
.color(IconicsColor.colorInt(iconColor))
)
.setOnClickAction(() -> {
})
);*/
items.add(
new MaterialAboutActionItem(
getString(R.string.settings_add_student_text),
getString(R.string.settings_add_student_subtext),
new IconicsDrawable(activity)
.icon(CommunityMaterial.Icon.cmd_account_plus_outline)
.size(IconicsSize.dp(iconSizeDp))
.color(IconicsColor.colorInt(iconColor))
)
.setOnClickAction(() -> {
startActivity(new Intent(activity, LoginActivity.class));
})
);
items.add(
new MaterialAboutActionItem(
getString(R.string.settings_profile_notifications_text),
getString(R.string.settings_profile_notifications_subtext),
new IconicsDrawable(activity)
.icon(CommunityMaterial.Icon.cmd_filter_outline)
.size(IconicsSize.dp(iconSizeDp))
.color(IconicsColor.colorInt(iconColor))
)
.setOnClickAction(() -> {
new NotificationFilterDialog(activity, null, null);
})
);
items.add(
new MaterialAboutActionItem(
getString(R.string.settings_profile_remove_text),
getString(R.string.settings_profile_remove_subtext),
new IconicsDrawable(activity)
.icon(SzkolnyFont.Icon.szf_delete_empty_outline)
.size(IconicsSize.dp(iconSizeDp))
.color(IconicsColor.colorInt(iconColor))
)
.setOnClickAction(() -> {
new ProfileRemoveDialog(activity, app.getProfile().getId(), app.getProfile().getName(), false);
})
);
items.add(getMoreItem(() -> addCardItems(CARD_PROFILE, getProfileCard(true))));
}
else {
items.add(
new MaterialAboutSwitchItem(
getString(R.string.settings_profile_sync_text),
getString(R.string.settings_profile_sync_subtext),
new IconicsDrawable(activity)
.icon(CommunityMaterial.Icon.cmd_account_convert)
.size(IconicsSize.dp(iconSizeDp))
.color(IconicsColor.colorInt(iconColor))
)
.setChecked(app.getProfile().getSyncEnabled())
.setOnChangeAction(((isChecked, tag) -> {
app.getProfile().setSyncEnabled(isChecked);
app.profileSave();
return true;
}))
);
}
return items;
}
/* _______ _
|__ __| |
| | | |__ ___ _ __ ___ ___
| | | '_ \ / _ \ '_ ` _ \ / _ \
| | | | | | __/ | | | | | __/
|_| |_| |_|\___|_| |_| |_|\__*/
private ArrayList<MaterialAboutItem> getThemeCard(boolean expandedOnly) {
ArrayList<MaterialAboutItem> items = new ArrayList<>();
if (!expandedOnly) {
Date today = Date.getToday();
if (today.month == 12 || today.month == 1) {
items.add(
new MaterialAboutSwitchItem(
getString(R.string.settings_theme_snowfall_text),
getString(R.string.settings_theme_snowfall_subtext),
new IconicsDrawable(activity)
.icon(CommunityMaterial.Icon2.cmd_snowflake)
.size(IconicsSize.dp(iconSizeDp))
.color(IconicsColor.colorInt(iconColor))
)
.setChecked(app.getConfig().getUi().getSnowfall())
.setOnChangeAction((isChecked, tag) -> {
app.getConfig().getUi().setSnowfall(isChecked);
activity.recreate();
return true;
})
);
}
items.add(
new MaterialAboutActionItem(
getString(R.string.settings_theme_theme_text),
Themes.INSTANCE.getThemeName(activity),
new IconicsDrawable(activity)
.icon(CommunityMaterial.Icon2.cmd_palette_outline)
.size(IconicsSize.dp(iconSizeDp))
.color(IconicsColor.colorInt(iconColor))
)
.setOnClickAction(() -> {
new MaterialDialog.Builder(activity)
.title(R.string.settings_theme_theme_text)
.items(Themes.INSTANCE.getThemeNames(activity))
.itemsCallbackSingleChoice(app.getConfig().getUi().getTheme(), (dialog, itemView, which, text) -> {
if (app.getConfig().getUi().getTheme() == which)
return true;
app.getConfig().getUi().setTheme(which);
Themes.INSTANCE.setThemeInt(app.getConfig().getUi().getTheme());
activity.recreate();
return true;
})
.show();
})
);
items.add(
new MaterialAboutSwitchItem(
getString(R.string.settings_theme_mini_drawer_text),
getString(R.string.settings_theme_mini_drawer_subtext),
new IconicsDrawable(activity)
.icon(CommunityMaterial.Icon.cmd_dots_vertical)
.size(IconicsSize.dp(iconSizeDp))
.color(IconicsColor.colorInt(iconColor))
)
.setChecked(app.getConfig().getUi().getMiniMenuVisible())
.setOnChangeAction((isChecked, tag) -> {
// 0,1 1
// 0,0 0
// 1,1 0
// 1,0 1
app.getConfig().getUi().setMiniMenuVisible(isChecked);
activity.getNavView().drawer.setMiniDrawerVisiblePortrait(isChecked);
return true;
})
);
items.add(getMoreItem(() -> addCardItems(CARD_THEME, getThemeCard(true))));
}
else {
items.add(
new MaterialAboutActionItem(
getString(R.string.settings_theme_mini_drawer_buttons_text),
null,
new IconicsDrawable(activity)
.icon(CommunityMaterial.Icon.cmd_format_list_checks)
.size(IconicsSize.dp(iconSizeDp))
.color(IconicsColor.colorInt(iconColor))
)
.setOnClickAction(() -> {
List<Integer> buttonIds = new ArrayList<>();
buttonIds.add(MainActivity.DRAWER_ITEM_HOME);
buttonIds.add(MainActivity.DRAWER_ITEM_TIMETABLE);
buttonIds.add(MainActivity.DRAWER_ITEM_AGENDA);
buttonIds.add(MainActivity.DRAWER_ITEM_GRADES);
buttonIds.add(MainActivity.DRAWER_ITEM_MESSAGES);
buttonIds.add(MainActivity.DRAWER_ITEM_HOMEWORK);
buttonIds.add(MainActivity.DRAWER_ITEM_BEHAVIOUR);
buttonIds.add(MainActivity.DRAWER_ITEM_ATTENDANCE);
buttonIds.add(MainActivity.DRAWER_ITEM_ANNOUNCEMENTS);
buttonIds.add(MainActivity.DRAWER_ITEM_NOTIFICATIONS);
buttonIds.add(MainActivity.DRAWER_ITEM_SETTINGS);
//buttonIds.add(MainActivity.DRAWER_ITEM_DEBUG);
List<String> buttonCaptions = new ArrayList<>();
buttonCaptions.add(getString(R.string.menu_home_page));
buttonCaptions.add(getString(R.string.menu_timetable));
buttonCaptions.add(getString(R.string.menu_agenda));
buttonCaptions.add(getString(R.string.menu_grades));
buttonCaptions.add(getString(R.string.menu_messages));
buttonCaptions.add(getString(R.string.menu_homework));
buttonCaptions.add(getString(R.string.menu_notices));
buttonCaptions.add(getString(R.string.menu_attendance));
buttonCaptions.add(getString(R.string.menu_announcements));
buttonCaptions.add(getString(R.string.menu_notifications));
buttonCaptions.add(getString(R.string.menu_settings));
//buttonCaptions.add(getString(R.string.title_debugging));
List<Integer> selectedIds = new ArrayList<>();
for (int id: app.getConfig().getUi().getMiniMenuButtons()) {
selectedIds.add(buttonIds.indexOf(id));
}
new MaterialDialog.Builder(activity)
.title(R.string.settings_theme_mini_drawer_buttons_dialog_title)
.content(getString(R.string.settings_theme_mini_drawer_buttons_dialog_text))
.items(buttonCaptions)
.itemsCallbackMultiChoice(selectedIds.toArray(new Integer[0]), (dialog, which, text) -> {
List<Integer> list = new ArrayList<>();
for (int index: which) {
if (index == -1)
continue;
// wtf
int id = buttonIds.get(index);
list.add(id);
}
app.getConfig().getUi().setMiniMenuButtons(list);
activity.setDrawerItems();
activity.getDrawer().updateBadges();
return true;
})
.positiveText(R.string.ok)
.show();
})
);
items.add(
new MaterialAboutActionItem(
getString(R.string.settings_theme_drawer_header_text),
null,
new IconicsDrawable(activity)
.icon(CommunityMaterial.Icon2.cmd_image_outline)
.size(IconicsSize.dp(iconSizeDp))
.color(IconicsColor.colorInt(iconColor))
)
.setOnClickAction(() -> {
if (app.getConfig().getUi().getHeaderBackground() != null) {
new MaterialDialog.Builder(activity)
.title(R.string.what_do_you_want_to_do)
.items(getString(R.string.settings_theme_drawer_header_dialog_set), getString(R.string.settings_theme_drawer_header_dialog_restore))
.itemsCallback((dialog, itemView, position, text) -> {
if (position == 0) {
startActivityForResult(CropImage.getPickImageChooserIntent(activity), 22);
} else {
MainActivity ac = (MainActivity) getActivity();
app.getConfig().getUi().setHeaderBackground(null);
if (ac != null) {
ac.getDrawer().setAccountHeaderBackground(null);
ac.getDrawer().open();
}
}
})
.show();
}
else {
startActivityForResult(CropImage.getPickImageChooserIntent(activity), 22);
}
})
);
items.add(
new MaterialAboutActionItem(
getString(R.string.settings_theme_app_background_text),
getString(R.string.settings_theme_app_background_subtext),
new IconicsDrawable(activity)
.icon(CommunityMaterial.Icon2.cmd_image_filter_hdr)
.size(IconicsSize.dp(iconSizeDp))
.color(IconicsColor.colorInt(iconColor))
)
.setOnClickAction(() -> {
if (app.getConfig().getUi().getAppBackground() != null) {
new MaterialDialog.Builder(activity)
.title(R.string.what_do_you_want_to_do)
.items(getString(R.string.settings_theme_app_background_dialog_set), getString(R.string.settings_theme_app_background_dialog_restore))
.itemsCallback((dialog, itemView, position, text) -> {
if (position == 0) {
startActivityForResult(CropImage.getPickImageChooserIntent(activity), 23);
} else {
app.getConfig().getUi().setAppBackground(null);
activity.recreate();
}
})
.show();
}
else {
startActivityForResult(CropImage.getPickImageChooserIntent(activity), 23);
}
})
);
items.add(
new MaterialAboutSwitchItem(
getString(R.string.settings_theme_open_drawer_on_back_pressed_text),
null,
new IconicsDrawable(activity)
.icon(CommunityMaterial.Icon2.cmd_menu_open)
.size(IconicsSize.dp(iconSizeDp))
.color(IconicsColor.colorInt(iconColor))
)
.setChecked(app.getConfig().getUi().getOpenDrawerOnBackPressed())
.setOnChangeAction((isChecked, tag) -> {
app.getConfig().getUi().setOpenDrawerOnBackPressed(isChecked);
return true;
})
);
}
return items;
}
/* _____
/ ____|
| (___ _ _ _ __ ___
\___ \| | | | '_ \ / __|
____) | |_| | | | | (__
|_____/ \__, |_| |_|\___|
__/ |
|__*/
private String getSyncCardIntervalSubText() {
if (app.getConfig().getSync().getInterval() < 60 * 60)
return getString(
R.string.settings_sync_sync_interval_subtext_format,
ExtensionsKt.plural(activity, R.plurals.time_till_minutes, app.getConfig().getSync().getInterval() / 60)
);
return getString(
R.string.settings_sync_sync_interval_subtext_format,
ExtensionsKt.plural(activity, R.plurals.time_till_hours, app.getConfig().getSync().getInterval() / 60 / 60) +
(app.getConfig().getSync().getInterval() / 60 % 60 == 0 ?
"" :
" " + ExtensionsKt.plural(activity, R.plurals.time_till_minutes, app.getConfig().getSync().getInterval() / 60 % 60)
)
);
}
private String getSyncCardQuietHoursSubText() {
if (app.getConfig().getSync().getQuietHoursStart() == null || app.getConfig().getSync().getQuietHoursEnd() == null)
return "";
return getString(
app.getConfig().getSync().getQuietHoursStart().getValue() >= app.getConfig().getSync().getQuietHoursEnd().getValue() ? R.string.settings_sync_quiet_hours_subtext_next_day_format : R.string.settings_sync_quiet_hours_subtext_format,
app.getConfig().getSync().getQuietHoursStart().getStringHM(),
app.getConfig().getSync().getQuietHoursEnd().getStringHM()
);
}
private MaterialAboutItem getSyncCardWifiItem() {
return new MaterialAboutSwitchItem(
getString(R.string.settings_sync_wifi_text),
getString(R.string.settings_sync_wifi_subtext),
new IconicsDrawable(activity)
.icon(CommunityMaterial.Icon2.cmd_wifi_strength_2)
.size(IconicsSize.dp(iconSizeDp))
.color(IconicsColor.colorInt(iconColor))
)
.setChecked(app.getConfig().getSync().getOnlyWifi())
.setOnChangeAction((isChecked, tag) -> {
app.getConfig().getSync().setOnlyWifi(isChecked);
SyncWorker.Companion.rescheduleNext(app);
return true;
});
}
private MaterialAboutActionSwitchItem syncCardIntervalItem;
private MaterialAboutActionSwitchItem syncCardQuietHoursItem;
private ArrayList<MaterialAboutItem> getSyncCard(boolean expandedOnly) {
ArrayList<MaterialAboutItem> items = new ArrayList<>();
if (!expandedOnly) {
syncCardIntervalItem = new MaterialAboutActionSwitchItem(
getString(R.string.settings_sync_sync_interval_text),
getString(R.string.settings_sync_sync_interval_subtext_disabled),
new IconicsDrawable(activity)
.icon(CommunityMaterial.Icon.cmd_download_outline)
.size(IconicsSize.dp(iconSizeDp))
.color(IconicsColor.colorInt(iconColor))
);
syncCardIntervalItem.setSubTextChecked(getSyncCardIntervalSubText());
syncCardIntervalItem.setChecked(app.getConfig().getSync().getEnabled());
syncCardIntervalItem.setOnClickAction(() -> {
List<CharSequence> intervalNames = new ArrayList<>();
if (App.Companion.getDebugMode() && false) {
intervalNames.add(ExtensionsKt.plural(activity, R.plurals.time_till_seconds, 30));
intervalNames.add(ExtensionsKt.plural(activity, R.plurals.time_till_minutes, 2));
}
intervalNames.add(ExtensionsKt.plural(activity, R.plurals.time_till_minutes, 30));
intervalNames.add(ExtensionsKt.plural(activity, R.plurals.time_till_minutes, 45));
intervalNames.add(ExtensionsKt.plural(activity, R.plurals.time_till_hours, 1));
intervalNames.add(ExtensionsKt.plural(activity, R.plurals.time_till_hours, 1)+" "+ ExtensionsKt.plural(activity, R.plurals.time_till_minutes, 30));
intervalNames.add(ExtensionsKt.plural(activity, R.plurals.time_till_hours, 2));
intervalNames.add(ExtensionsKt.plural(activity, R.plurals.time_till_hours, 3));
intervalNames.add(ExtensionsKt.plural(activity, R.plurals.time_till_hours, 4));
List<Integer> intervals = new ArrayList<>();
if (App.Companion.getDebugMode() && false) {
intervals.add(30);
intervals.add(2 * 60);
}
intervals.add(30 * 60);
intervals.add(45 * 60);
intervals.add(60 * 60);
intervals.add(90 * 60);
intervals.add(120 * 60);
intervals.add(180 * 60);
intervals.add(240 * 60);
new MaterialDialog.Builder(activity)
.title(getString(R.string.settings_sync_sync_interval_dialog_title))
.content(getString(R.string.settings_sync_sync_interval_dialog_text))
.items(intervalNames)
.itemsCallbackSingleChoice(intervals.indexOf(app.getConfig().getSync().getInterval()), (dialog, itemView, which, text) -> {
app.getConfig().getSync().setInterval(intervals.get(which));
syncCardIntervalItem.setSubTextChecked(getSyncCardIntervalSubText());
syncCardIntervalItem.setChecked(true);
if (!app.getConfig().getSync().getEnabled()) {
addCardItem(CARD_SYNC, 1, getSyncCardWifiItem());
}
else {
refreshMaterialAboutList();
}
app.getConfig().getSync().setEnabled(true);
// app.appConfig modifications have to surround syncCardIntervalItem and those ifs
SyncWorker.Companion.rescheduleNext(app);
return true;
})
.show();
});
syncCardIntervalItem.setOnChangeAction((isChecked, tag) -> {
if (isChecked && !app.getConfig().getSync().getEnabled()) {
addCardItem(CARD_SYNC, 1, getSyncCardWifiItem());
}
else if (!isChecked) {
removeCardItem(CARD_SYNC, 1);
}
app.getConfig().getSync().setEnabled(isChecked);
SyncWorker.Companion.rescheduleNext(app);
return true;
});
items.add(syncCardIntervalItem);
if (app.getConfig().getSync().getEnabled()) {
items.add(getSyncCardWifiItem());
}
/* items.add(
new MaterialAboutSwitchItem(
"Cisza na lekcjach",
"Nie odtwarzaj dźwięku powiadomień podczas lekcji",
new IconicsDrawable(activity)
.icon(CommunityMaterial.Icon2.cmd_volume_off)
.size(IconicsSize.dp(iconSizeDp))
.color(IconicsColor.colorInt(iconColor))
)
.setChecked(app.appConfig.quietDuringLessons)
.setOnChangeAction((isChecked) -> {
app.appConfig.quietDuringLessons = isChecked;
app.saveConfig("quietDuringLessons");
return true;
})
);*/
syncCardQuietHoursItem = new MaterialAboutActionSwitchItem(
getString(R.string.settings_sync_quiet_hours_text),
getString(R.string.settings_sync_quiet_hours_subtext_disabled),
new IconicsDrawable(activity)
.icon(CommunityMaterial.Icon.cmd_bell_sleep_outline)
.size(IconicsSize.dp(iconSizeDp))
.color(IconicsColor.colorInt(iconColor))
);
syncCardQuietHoursItem.setChecked(app.getConfig().getSync().getQuietHoursEnabled());
syncCardQuietHoursItem.setSubTextChecked(getSyncCardQuietHoursSubText());
syncCardQuietHoursItem.setOnClickAction(() -> {
new MaterialDialog.Builder(activity)
.title(R.string.settings_sync_quiet_hours_dialog_title)
.items(
getString(R.string.settings_sync_quiet_hours_set_beginning),
getString(R.string.settings_sync_quiet_hours_set_end)
)
.itemsCallback((dialog, itemView, position, text) -> {
if (position == 0) {
// set beginning
Time time = app.getConfig().getSync().getQuietHoursStart();
if (time == null)
time = new Time(22, 30, 0);
TimePickerDialog.newInstance((v2, hourOfDay, minute, second) -> {
app.getConfig().getSync().setQuietHoursEnabled(true);
app.getConfig().getSync().setQuietHoursStart(new Time(hourOfDay, minute, second));
syncCardQuietHoursItem.setChecked(true);
syncCardQuietHoursItem.setSubTextChecked(getSyncCardQuietHoursSubText());
refreshMaterialAboutList();
}, time.hour, time.minute, 0, true).show(activity.getSupportFragmentManager(), "TimePickerDialog");
}
else {
// set end
Time time = app.getConfig().getSync().getQuietHoursEnd();
if (time == null)
time = new Time(5, 30, 0);
TimePickerDialog.newInstance((v2, hourOfDay, minute, second) -> {
app.getConfig().getSync().setQuietHoursEnabled(true);
app.getConfig().getSync().setQuietHoursEnd(new Time(hourOfDay, minute, second));
syncCardQuietHoursItem.setChecked(true);
syncCardQuietHoursItem.setSubTextChecked(getSyncCardQuietHoursSubText());
refreshMaterialAboutList();
}, time.hour, time.minute, 0, true).show(activity.getSupportFragmentManager(), "TimePickerDialog");
}
})
.show();
});
syncCardQuietHoursItem.setOnChangeAction((isChecked, tag) -> {
app.getConfig().getSync().setQuietHoursEnabled(isChecked);
if (isChecked && app.getConfig().getSync().getQuietHoursStart() == null) {
app.getConfig().getSync().setQuietHoursStart(new Time(22, 30, 0));
app.getConfig().getSync().setQuietHoursEnd(new Time(5, 30, 0));
syncCardQuietHoursItem.setSubTextChecked(getSyncCardQuietHoursSubText());
refreshMaterialAboutList();
}
return true;
});
items.add(syncCardQuietHoursItem);
items.add(
new MaterialAboutActionItem(
getString(R.string.settings_sync_web_push_text),
getString(R.string.settings_sync_web_push_subtext),
new IconicsDrawable(activity)
.icon(CommunityMaterial.Icon2.cmd_laptop)
.size(IconicsSize.dp(iconSizeDp))
.color(IconicsColor.colorInt(iconColor))
)
.setOnClickAction(() -> {
activity.loadTarget(MainActivity.TARGET_WEB_PUSH, null);
})
);
items.add(getMoreItem(() -> addCardItems(CARD_SYNC, getSyncCard(true))));
}
else {
// TODO: 2019-04-27 add notification sound options: szkolny.eu, system default, custom
/*items.add(
new MaterialAboutActionItem(
"Dźwięk powiadomień",
"Szkolny.eu",
new IconicsDrawable(activity)
.icon(CommunityMaterial.Icon2.cmd_volume_high)
.size(IconicsSize.dp(iconSizeDp))
.color(IconicsColor.colorInt(iconColor))
)
.setOnClickAction(() -> {
})
);*/
items.add(
new MaterialAboutSwitchItem(
getString(R.string.settings_sync_updates_text),
null,
new IconicsDrawable(activity)
.icon(CommunityMaterial.Icon.cmd_cellphone_arrow_down)
.size(IconicsSize.dp(iconSizeDp))
.color(IconicsColor.colorInt(iconColor))
)
.setChecked(app.getConfig().getSync().getNotifyAboutUpdates())
.setOnChangeAction((isChecked, tag) -> {
app.getConfig().getSync().setNotifyAboutUpdates(isChecked);
UpdateWorker.Companion.rescheduleNext(app);
return true;
})
);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
items.add(
new MaterialAboutActionItem(
getString(R.string.settings_sync_notifications_settings_text),
getString(R.string.settings_sync_notifications_settings_subtext),
new IconicsDrawable(activity)
.icon(CommunityMaterial.Icon2.cmd_settings_outline)
.size(IconicsSize.dp(iconSizeDp))
.color(IconicsColor.colorInt(iconColor))
)
.setOnClickAction(() -> {
String channel = app.getNotificationChannelsManager().getData().getKey();
Intent intent = new Intent();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
intent.addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS);
intent.putExtra(Settings.EXTRA_CHANNEL_ID, channel);
intent.putExtra(Settings.EXTRA_APP_PACKAGE, activity.getPackageName());
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (channel != null) {
intent.setAction(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS);
intent.putExtra(Settings.EXTRA_CHANNEL_ID, channel);
} else {
intent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
}
intent.putExtra(Settings.EXTRA_APP_PACKAGE, activity.getPackageName());
} else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
intent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
intent.putExtra(Settings.EXTRA_APP_PACKAGE, activity.getPackageName());
} else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
intent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
intent.putExtra("app_package", activity.getPackageName());
intent.putExtra("app_uid", activity.getApplicationInfo().uid);
} else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setData(Uri.parse("package:" + activity.getPackageName()));
}
activity.startActivity(intent);
})
);
}
}
return items;
}
/* _____ _ _
| __ \ (_) | |
| |__) |___ __ _ _ ___| |_ ___ _ __
| _ // _ \/ _` | / __| __/ _ \ '__|
| | \ \ __/ (_| | \__ \ || __/ |
|_| \_\___|\__, |_|___/\__\___|_|
__/ |
|__*/
private String getRegisterCardAverageModeSubText() {
switch (app.getConfig().forProfile().getGrades().getYearAverageMode()) {
default:
case YEAR_1_AVG_2_AVG:
return getString(R.string.settings_register_avg_mode_0_short);
case YEAR_1_SEM_2_AVG:
return getString(R.string.settings_register_avg_mode_1_short);
case YEAR_1_AVG_2_SEM:
return getString(R.string.settings_register_avg_mode_2_short);
case YEAR_1_SEM_2_SEM:
return getString(R.string.settings_register_avg_mode_3_short);
case YEAR_ALL_GRADES:
return getString(R.string.settings_register_avg_mode_4_short);
}
}
private String getRegisterCardBellSyncSubText() {
if (app.getConfig().getTimetable().getBellSyncDiff() == null)
return getString(R.string.settings_register_bell_sync_subtext_disabled);
return getString(
R.string.settings_register_bell_sync_subtext_format,
(app.getConfig().getTimetable().getBellSyncMultiplier() == -1 ? "-" : "+") + app.getConfig().getTimetable().getBellSyncDiff().getStringHMS()
);
}
private MaterialAboutItem getRegisterCardSharedEventsItem() {
return new MaterialAboutSwitchItem(
getString(R.string.settings_register_shared_events_text),
getString(R.string.settings_register_shared_events_subtext),
new IconicsDrawable(activity)
.icon(CommunityMaterial.Icon2.cmd_share_outline)
.size(IconicsSize.dp(iconSizeDp))
.color(IconicsColor.colorInt(iconColor))
)
.setChecked(app.getProfile().getEnableSharedEvents())
.setOnChangeAction((isChecked, tag) -> {
app.getProfile().setEnableSharedEvents(isChecked);
app.profileSave();
if (isChecked) new MaterialDialog.Builder(activity)
.title(R.string.event_sharing)
.content(getString(R.string.settings_register_shared_events_dialog_enabled_text))
.positiveText(R.string.ok)
.show();
else new MaterialDialog.Builder(activity)
.title(R.string.event_sharing)
.content(getString(R.string.settings_register_shared_events_dialog_disabled_text))
.positiveText(R.string.ok)
.show();
return true;
});
}
private MaterialAboutSwitchItem registerCardAllowRegistrationItem;
private MaterialAboutActionItem registerCardBellSyncItem;
private ArrayList<MaterialAboutItem> getRegisterCard(boolean expandedOnly) {
ArrayList<MaterialAboutItem> items = new ArrayList<>();
if (!expandedOnly) {
items.add(new MaterialAboutActionItem(
getString(R.string.menu_grades_config),
null,
new IconicsDrawable(activity)
.icon(CommunityMaterial.Icon2.cmd_numeric_5_box_outline)
.size(IconicsSize.dp(iconSizeDp))
.color(IconicsColor.colorInt(iconColor))
).setOnClickAction(() -> new GradesConfigDialog(activity, false, null, null)));
items.add(new MaterialAboutActionItem(
getString(R.string.menu_attendance_config),
null,
new IconicsDrawable(activity)
.icon(CommunityMaterial.Icon.cmd_calendar_remove_outline)
.size(IconicsSize.dp(iconSizeDp))
.color(IconicsColor.colorInt(iconColor))
).setOnClickAction(() -> new AttendanceConfigDialog(activity, false, null, null)));
registerCardAllowRegistrationItem = new MaterialAboutSwitchItem(
getString(R.string.settings_register_allow_registration_text),
getString(R.string.settings_register_allow_registration_subtext),
new IconicsDrawable(activity)
.icon(CommunityMaterial.Icon.cmd_account_circle_outline)
.size(IconicsSize.dp(iconSizeDp))
.color(IconicsColor.colorInt(iconColor))
);
registerCardAllowRegistrationItem.setChecked(app.getProfile().getRegistration() == REGISTRATION_ENABLED);
registerCardAllowRegistrationItem.setOnChangeAction((isChecked, tag) -> {
if (isChecked) new MaterialDialog.Builder(activity)
.title(getString(R.string.settings_register_allow_registration_dialog_enabled_title))
.content(getString(R.string.settings_register_allow_registration_dialog_enabled_text))
.positiveText(R.string.i_agree)
.negativeText(R.string.not_now)
.onPositive(((dialog, which) -> {
registerCardAllowRegistrationItem.setChecked(true);
app.getProfile().setRegistration(REGISTRATION_ENABLED);
app.profileSave();
addCardItem(CARD_REGISTER, 2, getRegisterCardSharedEventsItem());
refreshMaterialAboutList();
}))
.show();
else new MaterialDialog.Builder(activity)
.title(getString(R.string.settings_register_allow_registration_dialog_disabled_title))
.content(getString(R.string.settings_register_allow_registration_dialog_disabled_text))
.positiveText(R.string.ok)
.negativeText(R.string.cancel)
.onPositive(((dialog, which) -> {
registerCardAllowRegistrationItem.setChecked(false);
app.getProfile().setRegistration(REGISTRATION_DISABLED);
app.profileSave();
removeCardItem(CARD_REGISTER, 2);
refreshMaterialAboutList();
MaterialDialog progressDialog = new MaterialDialog.Builder(activity)
.title(getString(R.string.settings_register_allow_registration_dialog_disabling_title))
.content(getString(R.string.settings_register_allow_registration_dialog_disabling_text))
.positiveText(R.string.ok)
.negativeText(R.string.abort)
.show();
AsyncTask.execute(() -> {
new SzkolnyApi(app).runCatching(szkolnyApi -> null, szkolnyApi -> null);
activity.runOnUiThread(() -> {
progressDialog.dismiss();
Toast.makeText(activity, getString(R.string.settings_register_allow_registration_dialog_disabling_finished), Toast.LENGTH_SHORT).show();
});
});
}))
.show();
return false;
});
items.add(registerCardAllowRegistrationItem);
if (app.getProfile().getRegistration() == REGISTRATION_ENABLED) {
items.add(getRegisterCardSharedEventsItem());
}
items.add(getMoreItem(() -> addCardItems(CARD_REGISTER, getRegisterCard(true))));
}
else {
registerCardBellSyncItem = new MaterialAboutActionItem(
getString(R.string.settings_register_bell_sync_text),
getRegisterCardBellSyncSubText(),
new IconicsDrawable(activity)
.icon(SzkolnyFont.Icon.szf_alarm_bell_outline)
.size(IconicsSize.dp(iconSizeDp))
.color(IconicsColor.colorInt(iconColor))
);
registerCardBellSyncItem.setOnClickAction(() -> {
new MaterialDialog.Builder(activity)
.title(R.string.bell_sync_title)
.content(R.string.bell_sync_adjust_content)
.positiveText(R.string.ok)
.negativeText(R.string.cancel)
.neutralText(R.string.reset)
.inputRangeRes(8, 8, R.color.md_red_500)
.input("±H:MM:SS",
(app.getConfig().getTimetable().getBellSyncDiff() != null
? (app.getConfig().getTimetable().getBellSyncMultiplier() == -1 ? "-" : "+") + app.getConfig().getTimetable().getBellSyncDiff().getStringHMS()
: ""), (dialog, input) -> {
if (input == null)
return;
if (input.length() < 8) {
Toast.makeText(activity, R.string.bell_sync_adjust_error, Toast.LENGTH_SHORT).show();
return;
}
if (input.charAt(2) != ':' || input.charAt(5) != ':') {
Toast.makeText(activity, R.string.bell_sync_adjust_error, Toast.LENGTH_SHORT).show();
return;
}
if (input.charAt(0) == '+') {
app.getConfig().getTimetable().setBellSyncMultiplier(1);
}
else if (input.charAt(0) == '-') {
app.getConfig().getTimetable().setBellSyncMultiplier(-1);
}
else {
Toast.makeText(activity, R.string.bell_sync_adjust_error, Toast.LENGTH_SHORT).show();
return;
}
int hour;
int minute;
int second;
try {
hour = Integer.parseInt(input.charAt(1) + "");
minute = Integer.parseInt(input.charAt(3) + "" + input.charAt(4));
second = Integer.parseInt(input.charAt(6) + "" + input.charAt(7));
}
catch (Exception e) {
e.printStackTrace();
Toast.makeText(activity, R.string.bell_sync_adjust_error, Toast.LENGTH_SHORT).show();
return;
}
app.getConfig().getTimetable().setBellSyncDiff(new Time(hour, minute, second));
registerCardBellSyncItem.setSubText(getRegisterCardBellSyncSubText());
refreshMaterialAboutList();
})
.onNeutral(((dialog, which) -> {
app.getConfig().getTimetable().setBellSyncDiff(null);
app.getConfig().getTimetable().setBellSyncMultiplier(0);
registerCardBellSyncItem.setSubText(getRegisterCardBellSyncSubText());
refreshMaterialAboutList();
}))
.show();
});
items.add(registerCardBellSyncItem);
items.add(
new MaterialAboutSwitchItem(
getString(R.string.settings_register_count_in_seconds_text),
getString(R.string.settings_register_count_in_seconds_subtext),
new IconicsDrawable(activity)
.icon(CommunityMaterial.Icon2.cmd_timer)
.size(IconicsSize.dp(iconSizeDp))
.color(IconicsColor.colorInt(iconColor))
)
.setChecked(app.getConfig().getTimetable().getCountInSeconds())
.setOnChangeAction((isChecked, tag) -> {
app.getConfig().getTimetable().setCountInSeconds(isChecked);
return true;
})
);
if (app.getProfile().getLoginStoreType() == LoginStore.LOGIN_TYPE_LIBRUS) {
items.add(
new MaterialAboutSwitchItem(
getString(R.string.settings_register_show_teacher_absences_text),
null,
new IconicsDrawable(activity)
.icon(CommunityMaterial.Icon.cmd_account_arrow_right_outline)
.size(IconicsSize.dp(iconSizeDp))
.color(IconicsColor.colorInt(iconColor))
)
.setChecked(app.getProfile().getStudentData("showTeacherAbsences", true))
.setOnChangeAction((isChecked, tag) -> {
app.getProfile().putStudentData("showTeacherAbsences", isChecked);
app.profileSave();
return true;
})
);
}
if (App.Companion.getDevMode()) {
items.add(
new MaterialAboutSwitchItem(
getString(R.string.settings_register_hide_sticks_from_old),
null,
new IconicsDrawable(activity)
.icon(CommunityMaterial.Icon2.cmd_numeric_1_box_outline)
.size(IconicsSize.dp(iconSizeDp))
.color(IconicsColor.colorInt(iconColor))
)
.setChecked(app.getConfig().forProfile().getGrades().getHideSticksFromOld())
.setOnChangeAction((isChecked, tag) -> {
app.getConfig().forProfile().getGrades().setHideSticksFromOld(isChecked);
return true;
})
);
}
}
return items;
}
/* _ _
/\ | | | |
/ \ | |__ ___ _ _| |_
/ /\ \ | '_ \ / _ \| | | | __|
/ ____ \| |_) | (_) | |_| | |_
/_/ \_\_.__/ \___/ \__,_|\_*/
private MaterialAboutActionItem pref_about_version;
private ArrayList<MaterialAboutItem> getAboutCard(boolean expandedOnly) {
primaryTextOnPrimaryBg = 0xffffffff;//getColorFromAttr(activity, R.attr.colorOnPrimary);
secondaryTextOnPrimaryBg = 0xd0ffffff;//activity.getResources().getColor(R.color.secondaryTextLight);
ArrayList<MaterialAboutItem> items = new ArrayList<>();
if (!expandedOnly) {
items.add(new MaterialAboutTitleItem.Builder()
.text(R.string.app_name)
.desc(R.string.settings_about_title_subtext)
.textColor(primaryTextOnPrimaryBg)
.descColor(secondaryTextOnPrimaryBg)
.icon(R.mipmap.ic_splash)
.build());
pref_about_version = new MaterialAboutActionItem.Builder()
.text(R.string.settings_about_version_text)
.textColor(primaryTextOnPrimaryBg)
.subTextColor(secondaryTextOnPrimaryBg)
.subText(BuildConfig.VERSION_NAME + ", " + BuildConfig.BUILD_TYPE)
.icon(new IconicsDrawable(activity)
.icon(CommunityMaterial.Icon2.cmd_information_outline)
.color(IconicsColor.colorInt(primaryTextOnPrimaryBg))
.size(IconicsSize.dp(iconSizeDp)))
.build();
final int[] clickCounter = {0};
pref_about_version.setOnClickAction(() -> {
if (6 - clickCounter[0] != 0) {
Toast.makeText(activity, ("\ud83d\ude02"), Toast.LENGTH_SHORT).show();
}
refreshMaterialAboutList();
clickCounter[0] = clickCounter[0] + 1;
if (clickCounter[0] > 6) {
final MediaPlayer mp = MediaPlayer.create(activity, R.raw.ogarnij_sie);
mp.start();
clickCounter[0] = 0;
}
});
items.add(pref_about_version);
items.add(new MaterialAboutActionItem.Builder()
.text(R.string.settings_about_privacy_policy_text)
.textColor(primaryTextOnPrimaryBg)
.subTextColor(secondaryTextOnPrimaryBg)
.icon(new IconicsDrawable(activity)
.icon(CommunityMaterial.Icon2.cmd_shield_outline)
.color(IconicsColor.colorInt(primaryTextOnPrimaryBg))
.size(IconicsSize.dp(iconSizeDp)))
.setOnClickAction(ConvenienceBuilder.createWebsiteOnClickAction(activity, Uri.parse("https://szkolny.eu/privacy-policy")))
.build());
items.add(new MaterialAboutActionItem.Builder()
.text(R.string.settings_about_discord_text)
.textColor(primaryTextOnPrimaryBg)
.subTextColor(secondaryTextOnPrimaryBg)
.subText(R.string.settings_about_discord_subtext)
.icon(new IconicsDrawable(activity)
.icon(SzkolnyFont.Icon.szf_discord_outline)
.color(IconicsColor.colorInt(primaryTextOnPrimaryBg))
.size(IconicsSize.dp(iconSizeDp)))
.setOnClickAction(ConvenienceBuilder.createWebsiteOnClickAction(activity, Uri.parse("https://szkolny.eu/discord")))
.build());
items.add(new MaterialAboutActionItem.Builder()
.text(R.string.settings_about_language_text)
.textColor(primaryTextOnPrimaryBg)
.subTextColor(secondaryTextOnPrimaryBg)
.subText(R.string.settings_about_language_subtext)
.icon(new IconicsDrawable(activity)
.icon(CommunityMaterial.Icon2.cmd_translate)
.color(IconicsColor.colorInt(primaryTextOnPrimaryBg))
.size(IconicsSize.dp(iconSizeDp)))
.setOnClickAction(() -> {
new MaterialDialog.Builder(activity)
.title(getString(R.string.settings_about_language_dialog_title))
.content(getString(R.string.settings_about_language_dialog_text))
.items(getString(R.string.language_system), getString(R.string.language_polish), getString(R.string.language_english), getString(R.string.language_german))
.itemsCallbackSingleChoice(app.getConfig().getUi().getLanguage() == null ? 0 : app.getConfig().getUi().getLanguage().equals("pl") ? 1 : app.getConfig().getUi().getLanguage().equals("en") ? 2 : 3, (dialog, itemView, which, text) -> {
switch (which) {
case 0:
app.getConfig().getUi().setLanguage(null);
initDefaultLocale();
break;
case 1:
app.getConfig().getUi().setLanguage("pl");
break;
case 2:
app.getConfig().getUi().setLanguage("en");
break;
case 3:
app.getConfig().getUi().setLanguage("de");
break;
}
activity.recreate(MainActivity.DRAWER_ITEM_SETTINGS);
return true;
})
.show();
})
.build());
items.add(getMoreItem(() -> addCardItems(CARD_ABOUT, getAboutCard(true))));
}
else {
items.add(new MaterialAboutActionItem.Builder()
.text(R.string.settings_about_update_text)
.subText(R.string.settings_about_update_subtext)
.textColor(primaryTextOnPrimaryBg)
.subTextColor(secondaryTextOnPrimaryBg)
.icon(new IconicsDrawable(activity)
.icon(CommunityMaterial.Icon2.cmd_update)
.color(IconicsColor.colorInt(primaryTextOnPrimaryBg))
.size(IconicsSize.dp(iconSizeDp)))
.setOnClickAction(() -> {
//open browser or intent here
NetworkUtils net = new NetworkUtils(app);
if (!net.isOnline()) {
new MaterialDialog.Builder(activity)
.title(R.string.you_are_offline_title)
.content(R.string.you_are_offline_text)
.positiveText(R.string.ok)
.show();
} else {
AsyncTask.execute(() -> {
new UpdateWorker.JavaWrapper(app);
});
}
})
.build());
items.add(new MaterialAboutActionItem.Builder()
.text(R.string.settings_about_changelog_text)
.textColor(primaryTextOnPrimaryBg)
.subTextColor(secondaryTextOnPrimaryBg)
.icon(new IconicsDrawable(activity)
.icon(CommunityMaterial.Icon2.cmd_radar)
.color(IconicsColor.colorInt(primaryTextOnPrimaryBg))
.size(IconicsSize.dp(iconSizeDp)))
.setOnClickAction(() -> new ChangelogDialog(activity, null, null))
.build());
items.add(new MaterialAboutActionItem.Builder()
.text(R.string.settings_about_licenses_text)
.textColor(primaryTextOnPrimaryBg)
.subTextColor(secondaryTextOnPrimaryBg)
.icon(new IconicsDrawable(activity)
.icon(CommunityMaterial.Icon.cmd_code_braces)
.color(IconicsColor.colorInt(primaryTextOnPrimaryBg))
.size(IconicsSize.dp(iconSizeDp)))
.setOnClickAction(() -> {
Intent intent = new Intent(activity, SettingsLicenseActivity.class);
startActivity(intent);
})
.build());
/*items.add(new MaterialAboutActionItem.Builder()
.text(R.string.settings_about_intro_text)
.icon(new IconicsDrawable(activity)
.icon(CommunityMaterial.Icon2.cmd_projector_screen)
.color(IconicsColor.colorInt(iconColor))
.size(IconicsSize.dp(iconSizeDp)))
.setOnClickAction(() -> {
if (tryingToDevMode[0]) {
if (getParentFragment() instanceof SettingsGeneralFragment) {
((SettingsGeneralFragment) getParentFragment()).showDevSettings();
}
tryingToDevMode[0] = false;
return;
}
IntroConnectionFragment.connectionOk = true;
IntroConnectionFragment.httpsOk = (app.requestScheme.equals("https"));
Intent intent = new Intent(activity, MainIntroActivity.class);
IntroSplashFragment.skipAnimation = false;
startActivity(intent);
})
.build());*/
if (App.Companion.getDevMode()) {
items.add(new MaterialAboutActionItem.Builder()
.text(R.string.settings_about_crash_text)
.subText(R.string.settings_about_crash_subtext)
.textColor(primaryTextOnPrimaryBg)
.subTextColor(secondaryTextOnPrimaryBg)
.icon(new IconicsDrawable(activity)
.icon(CommunityMaterial.Icon.cmd_bug_outline)
.color(IconicsColor.colorInt(primaryTextOnPrimaryBg))
.size(IconicsSize.dp(iconSizeDp)))
.setOnClickAction(() -> {
throw new RuntimeException("MANUAL CRASH");
})
.build());
}
}
return items;
}
@Override
protected MaterialAboutList getMaterialAboutList(Context activityContext) {
if (getActivity() == null || getContext() == null || !isAdded())
return null;
this.activity = (MainActivity) activityContext;
this.app = (App) activity.getApplication();
iconColor = Themes.INSTANCE.getPrimaryTextColor(activityContext);
if (app.getProfile() == null)
return new MaterialAboutList.Builder().build();
MaterialAboutList materialAboutList = new MaterialAboutList();
materialAboutList.addCard(getCardWithItems(null, getProfileCard(false)));
materialAboutList.addCard(getCardWithItems(getString(R.string.settings_theme_title_text), getThemeCard(false)));
materialAboutList.addCard(getCardWithItems(getString(R.string.settings_sync_title_text), getSyncCard(false)));
materialAboutList.addCard(getCardWithItems(getString(R.string.settings_about_register_title_text), getRegisterCard(false)));
//if (configurableEndpoints != null)
// materialAboutList.addCard(getCardWithItems(getString(R.string.settings_sync_customize_title_text), getSyncCustomizeCard(false)));
materialAboutList.addCard(getCardWithItems(null, getAboutCard(false), true));
return materialAboutList;
}
@Override
protected int getTheme() {
return Themes.INSTANCE.getAppTheme();
}
/* _____ _ ____ _ _
/ ____| | | | _ \ | | | |
| | _ _ ___| |_ ___ _ __ ___ | |_) | __ _ ___| | ____ _ _ __ ___ _ _ _ __ __| |___
| | | | | / __| __/ _ \| '_ ` _ \ | _ < / _` |/ __| |/ / _` | '__/ _ \| | | | '_ \ / _` / __|
| |___| |_| \__ \ || (_) | | | | | | | |_) | (_| | (__| < (_| | | | (_) | |_| | | | | (_| \__ \
\_____\__,_|___/\__\___/|_| |_| |_| |____/ \__,_|\___|_|\_\__, |_| \___/ \__,_|_| |_|\__,_|___/
__/ |
|__*/
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data == null) {
Toast.makeText(app, "Wystąpił błąd. Spróbuj ponownie", Toast.LENGTH_SHORT).show();
return;
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
Uri uri = result.getUri();
File photoFile = new File(uri.getPath());
File destFile = new File(getContext().getFilesDir(),"profile"+ app.getProfile().getId() +".jpg");
if (destFile.exists()) {
destFile.delete();
destFile = new File(getContext().getFilesDir(),"profile"+ app.getProfile().getId() +".jpg");
}
d(TAG, "Source file: "+photoFile.getAbsolutePath());
d(TAG, "Dest file: "+destFile.getAbsolutePath());
if (result.getCropRect().width() > 512 || true) {
Bitmap bigImage = BitmapFactory.decodeFile(uri.getPath());
Bitmap smallImage = getResizedBitmap(bigImage, 512, 512);
try (FileOutputStream out = new FileOutputStream(destFile)) {
smallImage.compress(Bitmap.CompressFormat.JPEG, 80, out); // bmp is your Bitmap instance
// PNG is a lossless format, the compression factor (100) is ignored
app.getProfile().setImage(destFile.getAbsolutePath());
app.profileSave();
profileCardTitleItem.setIcon(getProfileDrawable());
refreshMaterialAboutList();
if (photoFile.exists()) {
photoFile.delete();
}
//((MainActivity)getActivity()).recreateWithTransition(); // TODO somehow update miniDrawer profile picture
} catch (IOException e) {
e.printStackTrace();
}
}
else {
if (photoFile.renameTo(destFile)) {
// success
app.getProfile().setImage(destFile.getAbsolutePath());
app.profileSave();
profileCardTitleItem.setIcon(getProfileDrawable());
refreshMaterialAboutList();
//((MainActivity)getActivity()).recreateWithTransition(); // TODO somehow update miniDrawer profile picture
}
else {
// not this time
Toast.makeText(app, R.string.error_occured, Toast.LENGTH_LONG).show();
}
}
}
else if (requestCode == 21 && resultCode == Activity.RESULT_OK) {
Uri uri = data.getData();
if (uri != null) {
String path = getRealPathFromURI(activity, uri);
if (path.toLowerCase().endsWith(".gif")) {
app.getProfile().setImage(path);
app.profileSave();
profileCardTitleItem.setIcon(getProfileDrawable());
refreshMaterialAboutList();
}
else {
CropImage.activity(data.getData())
.setAspectRatio(1, 1)
//.setMaxCropResultSize(512, 512)
.setCropShape(CropImageView.CropShape.OVAL)
.setGuidelines(CropImageView.Guidelines.ON)
.start(activity, this);
}
}
}
else if (requestCode == 22 && resultCode == Activity.RESULT_OK) {
Uri uri = data.getData();
if (uri != null) {
app.getConfig().getUi().setHeaderBackground(getRealPathFromURI(getContext(), uri));
if (activity != null) {
activity.getDrawer().setAccountHeaderBackground(app.getConfig().getUi().getHeaderBackground());
activity.getDrawer().open();
}
}
}
else if (requestCode == 23 && resultCode == Activity.RESULT_OK) {
Uri uri = data.getData();
if (uri != null) {
app.getConfig().getUi().setAppBackground(getRealPathFromURI(getContext(), uri));
if (activity != null) {
activity.recreate();
}
}
}
}
}
|
package no.nav.vedtak.felles.prosesstask.impl;
import java.time.LocalDateTime;
/** IdentRunnable som tar id og Runnable. */
class IdentRunnableTask implements IdentRunnable {
private final Long id;
private final Runnable runnable;
private final LocalDateTime createTime;
IdentRunnableTask(Long id, Runnable run, LocalDateTime createTime) {
this.id = id;
this.runnable = run;
this.createTime = createTime;
}
@Override
public void run() {
runnable.run();
}
@Override
public Long getId() {
return id;
}
@Override
public LocalDateTime getCreateTime() {
return createTime;
}
} |
/*
*/
package com.cleverfishsoftware.loadgenerator;
/**
*
* @author peter
*/
public class Common {
public static final int ONE_KB = 1024;
public static final int ONE_MB = 1000 * ONE_KB;
public static boolean NotNullOrEmpty(String value) {
return value != null && value.length() > 0;
}
public static boolean NullOrEmpty(String value) {
return value == null || value.length() == 0;
}
public static boolean isTrue(String value) {
return NotNullOrEmpty(value) && (value.toLowerCase().equals("y")
|| value.toLowerCase().equals("yes")
|| value.toLowerCase().equals("true"));
}
}
|
import java.io.*;
import java.net.*;
public class s2
{
public static void main(String [] args)
{
if(args.length!=1)
{
System.out.println("Error in args listed");
System.exit(0);
}
try
{
//InetAddress h=InetAddress.getByName(args[0]);
int port=Integer.parseInt(args[0]);
//String m=args[2];
byte[] buff=new byte[100];
DatagramSocket s= new DatagramSocket(port);
DatagramPacket p=new DatagramPacket(buff,100);
s.receive(p);
String m=new String(buff);
System.out.println(m);
s.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
|
package com.hqhcn.android.entity;
public class Gps extends GpsKey {
private String kskm;
private String carinfoId;
private String gps;
public String getKskm() {
return kskm;
}
public void setKskm(String kskm) {
this.kskm = kskm == null ? null : kskm.trim();
}
public String getCarinfoId() {
return carinfoId;
}
public void setCarinfoId(String carinfoId) {
this.carinfoId = carinfoId == null ? null : carinfoId.trim();
}
public String getGps() {
return gps;
}
public void setGps(String gps) {
this.gps = gps == null ? null : gps.trim();
}
} |
package by.whiskarek.notes.models;
import androidx.annotation.NonNull;
import androidx.room.Entity;
import androidx.room.ForeignKey;
import androidx.room.Ignore;
import androidx.room.Index;
@Entity(primaryKeys = {"noteId", "tagId"},
foreignKeys = {
@ForeignKey(entity = Note.class,
parentColumns = "id",
childColumns = "noteId"),
@ForeignKey(entity = Tag.class,
parentColumns = "id",
childColumns = "tagId")
},
indices = {
@Index(value = "noteId"),
@Index(value = "tagId")
})
public class NoteTagJoin {
@NonNull
private String noteId;
@NonNull
private String tagId;
public NoteTagJoin() {
}
@Ignore
public NoteTagJoin(String noteId, String tagId) {
this.noteId = noteId;
this.tagId = tagId;
}
public String getNoteId() {
return noteId;
}
public String getTagId() {
return tagId;
}
public void setNoteId(String noteId) {
this.noteId = noteId;
}
public void setTagId(String tagId) {
this.tagId = tagId;
}
}
|
package com.tencent.mm.plugin.luckymoney.ui;
import android.view.View;
import android.view.View.OnClickListener;
import com.tencent.mm.plugin.luckymoney.ui.LuckyMoneyWishFooter.b;
class LuckyMoneyWishFooter$5 implements OnClickListener {
final /* synthetic */ LuckyMoneyWishFooter kXP;
final /* synthetic */ b kXQ;
LuckyMoneyWishFooter$5(LuckyMoneyWishFooter luckyMoneyWishFooter, b bVar) {
this.kXP = luckyMoneyWishFooter;
this.kXQ = bVar;
}
public final void onClick(View view) {
this.kXQ.Gf(LuckyMoneyWishFooter.a(this.kXP).getText().toString());
LuckyMoneyWishFooter.a(this.kXP).setText("");
}
}
|
package com.utils;
import lombok.extern.log4j.Log4j;
import java.util.Properties;
/**
* Kafka配置文件
* */
@Log4j
public class KafkaConfigUtil {
public static String topic="example";//Kafka的topic
public static String fieldDelimiter = ",";//字段分隔符,用于分隔Json解析后的字段
public static Properties buildKafkaProps(){
Properties properties = new Properties();
properties.setProperty("bootstrap.servers", "master:9092,slave01:9092,slave02:9092");
properties.setProperty("zookeeper.connect", "master:2181,slave01:2181,slave02:2181");
properties.setProperty("group.id", "meeting_group10");//
properties.put("auto.offset.reset", "latest");
/** earliest
当各分区下有已提交的offset时,从提交的offset开始消费;无提交的offset时,从头开始消费
latest
当各分区下有已提交的offset时,从提交的offset开始消费;无提交的offset时,消费新产生的该分区下的数据
none
topic各分区都存在已提交的offset时,从offset后开始消费;只要有一个分区不存在已提交的offset,则抛出异常
*/
properties.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
properties.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
log.info("get kafka config, config map-> " + properties.toString());
return properties;
}
}
|
package com.coding.java.serialize.byteserialize.jdkserializer2;
import java.io.*;
/**
* @author scq
*/
public class JavaSerializer implements ISerializer {
@Override
public <T> byte[] serializer(T obj) {
try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream outputStream = new ObjectOutputStream(byteArrayOutputStream)) {
outputStream.writeObject(obj);
return byteArrayOutputStream.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
public <T> T deSerializer(byte[] data, Class<T> clazz) {
try (ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
ObjectInputStream inputStream = new ObjectInputStream(byteArrayInputStream)) {
return (T) inputStream.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
|
package practica7_ej4;
import java.util.ArrayList;
//Eventual: datosEmpleado, honorariosPorHora, pagarSalario()
public class Eventual {
private ArrayList <String> datosEmpleado = new ArrayList<String>();
private double honorariosPorHora;
Eventual(){
super();
this.honorariosPorHora = 0;
}
Eventual(ArrayList <String> datosEmpleado , double honorariosPorHora){
super();
this.datosEmpleado = datosEmpleado;
this.honorariosPorHora = honorariosPorHora;
}
protected ArrayList<String> getDatosEmpleado() {
return datosEmpleado;
}
protected void setDatosEmpleado(ArrayList<String> datosEmpleado) {
this.datosEmpleado = datosEmpleado;
}
protected double getHonorariosPorHora() {
return honorariosPorHora;
}
protected void setHonorariosPorHora(double honorariosPorHora) {
this.honorariosPorHora = honorariosPorHora;
}
}
|
package com.hungtdo.demoactionbar;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;
public class SettingsActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
tv.setLayoutParams(params);
tv.setGravity(Gravity.CENTER);
tv.setTextSize(50f);
tv.setTextColor(Color.RED);
tv.setText(R.string.action_settings);
setContentView(tv);
//Enable Up Button
setUpButton();
//Set event
tv.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
Toast.makeText(SettingsActivity.this, "Finish", Toast.LENGTH_SHORT).show();
}
});
}
private void setUpButton() {
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
|
package com.test.xiaojian.simple_reader.ui.adapter;
import android.content.Context;
import com.test.xiaojian.simple_reader.model.bean.SortBookBean;
import com.test.xiaojian.simple_reader.ui.adapter.view.BookSortListHolder;
import com.test.xiaojian.simple_reader.ui.base.adapter.IViewHolder;
import com.test.xiaojian.simple_reader.widget.adapter.WholeAdapter;
/**
* Created by xiaojian on 17-5-3.
*/
public class BookSortListAdapter extends WholeAdapter<SortBookBean>{
public BookSortListAdapter(Context context, Options options) {
super(context, options);
}
@Override
protected IViewHolder<SortBookBean> createViewHolder(int viewType) {
return new BookSortListHolder();
}
}
|
package rti.calculator;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class OptionsPage extends Activity {
private float angle;
private EditText angle_box;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences settings = getSharedPreferences(RTI_calculator.PREFS_NAME, 0);
setContentView(R.layout.activity_options_page);
this.angle = settings.getFloat("angle", (float)Math.toRadians(30));
angle_box = (EditText) findViewById(R.id.editText1);
angle_box.setText(String.valueOf((float)Math.toDegrees(this.angle)));
}
public void saveHandler(View view) {
SharedPreferences settings = getSharedPreferences(RTI_calculator.PREFS_NAME, 0);
switch(view.getId()) {
case R.id.button1:
float entered_angle = Float.parseFloat(angle_box.getText().toString());
SharedPreferences.Editor editor = settings.edit();
editor.putFloat("angle", (float)Math.toRadians(entered_angle));
editor.commit();
}
}
}
|
package com.bozhong.lhdataaccess.infrastructure.dao;
import com.bozhong.lhdataaccess.domain.DoctorInDiagnosisDO;
import com.bozhong.lhdataaccess.domain.DoctorOutDiagnosisDO;
import com.bozhong.lhdataaccess.domain.OrganizStructureDO;
import java.util.List;
/**
* User: 李志坚
* Date: 2018/11/5
* 住院诊断数据的DAO
*/
public interface DoctorInDiagnosisDAO {
void updateOrInsertDoctorInDiagnosis(DoctorInDiagnosisDO doctorInDiagnosisDO);
List<DoctorInDiagnosisDO> selectDidDataByDoctorInDiagnosisDO(DoctorInDiagnosisDO doctorInDiagnosisDO);
}
|
package me.hoon.config;
import me.hoon.account.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
AccountService accountService; //스프링 시큐리티에서 명시적으로 선언
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.mvcMatchers("/", "/info", "/account/**").permitAll()
.mvcMatchers("/admin").hasRole("ADMIN")
.anyRequest().authenticated() //기타 등등은 인증만 하면 된다.
;
http.formLogin(); //form login을 사용하겠다. form login 설정 안하면 그냥 모달창 같은거 나오네. logout 기능도 제공
http.httpBasic(); //http basic을 사용하겠다.
}
/*
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("goohoon").password("{noop}123").roles("USER").and() //noop -> 패스워드 암호화 안한다. (패스워드 인코딩X)
.withUser("admin").password("{noop}!@#").roles("ADMIN");
}
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(accountService); //우리가 사용할 userDetailService가 이거라고 명시. 이렇게 하지 않아도 빈으로 등록만 되있으면 가져다가 씀.
}
}
|
package edu.nyu.cs.jsd410;
/**
* A class which represents customers to be partake in the queue that is exhibited in the Main class.
* @author juliansmithdeniro
*
*/
public class Customer {
private int id;
private int arrivalTime;
private int waitTime;
private int doneTime;
/**
* Default constructor for a Customer object.
*/
public Customer() {}
/**
* Constructor which allows the object to be instantiated an id and arrival time.
* @param id an int representing the ID number of the customer.
* @param arrivalTime an int representing the time of arrival by the customer in seconds.
*/
public Customer(int id, int arrivalTime) {
this.setId(id);
this.setArrivalTime(arrivalTime);
}
/**
* Return the customer id.
* @return an int representing the customer's id.
*/
public int getId() {
return this.id;
}
/**
* Set the customer id.
* @param id an int representing the customer's id.
*/
public void setId(int id) {
this.id = id;
}
/**
* Return the arrival time of the customer.
* @return an int representing the customer arrival time in seconds.
*/
public int getArrivalTime() {
return this.arrivalTime;
}
/**
* Set the arrival time of the customer.
* @param arrivalTime an int representing the customer arrival time in seconds.
*/
public void setArrivalTime(int arrivalTime) {
this.arrivalTime = arrivalTime;
}
/**
* Return the time the customer waits to be served in seconds.
* @return an int representing the amount of time the customer waits to be served in seconds.
*/
public int getWaitTime() {
return waitTime;
}
/**
* Set the wait time of the customer.
* @param waitTime an int representing the wait time of the customer in seconds.
*/
public void setWaitTime(int waitTime) {
this.waitTime = waitTime;
}
/**
* Return the time that the customer is done being served.
* @return an int representing the time the customer is done being served in seconds.
*/
public int getDoneTime() {
return doneTime;
}
/**
* Set the time the customer is done being served
* @param doneTime an int representing the time the customer is done being served in seconds.
*/
public void setDoneTime(int doneTime) {
this.doneTime = doneTime;
}
}
|
/*
* 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 carros;
import java.util.ArrayList;
/**
*
* @author Estudiante
*/
public class Escenario {
private String nombre;
private Carr carro;
private ArrayList<Obstaculo> obstaculos;
public Escenario(String nombre, Carr carro){
this.nombre=nombre;
this.carro=carro;
this.obstaculos=new ArrayList();
}
public String get_nombre(){
return this.nombre;
}
public Carr get_carro(){
return this.carro;
}
public Obstaculo get_obstaculo(int a){
return this.obstaculos.get(a);
}
public void addObstaculo(Obstaculo obs){
this.obstaculos.add(obs);
}
}
|
package com.thoughtworks.domain.product_list;
import com.thoughtworks.domain.product_detail.Product;
import java.util.List;
/**
* Created on 12-06-2018.
*/
public class ProductList {
private final List<Product> mData;
public ProductList(final List<Product> data) {
mData = data;
}
public List<Product> getData() {
return mData;
}
}
|
package ru.skel2007.warren.controller;
import java.util.concurrent.CompletableFuture;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import ru.tinkoff.invest.openapi.OpenApi;
import ru.tinkoff.invest.openapi.models.user.AccountsList;
import ru.tinkoff.invest.openapi.models.user.BrokerAccount;
@RestController
@RequestMapping(value = "/api/v1/accounts", produces = MediaType.APPLICATION_JSON_VALUE)
public class AccountsController {
@NotNull
private final OpenApi tinkoffApi;
@Autowired
public AccountsController(@NotNull OpenApi tinkoffApi) {
this.tinkoffApi = tinkoffApi;
}
@GetMapping
@NotNull
public Flux<BrokerAccount> getAccounts() {
CompletableFuture<AccountsList> accounts = tinkoffApi
.getUserContext()
.getAccounts();
return Mono.fromFuture(accounts)
.map(it -> it.accounts)
.flatMapMany(Flux::fromIterable);
}
}
|
package org.kuribko.moviecatalog.parser;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;
import org.kuribko.moviecatalog.model.Movie;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
@Component
public class NashnetSearchResultsParser implements SearchResultsParser {
private Logger log = LoggerFactory.getLogger(this.getClass());
@Value("${nashnet.homepage}")
private String homepage;
@Override
public List<Movie> parseHtml(String html) {
Document doc = Jsoup.parse(html);
return parse(doc);
}
@Override
public List<Movie> parseFromUrl(String url) throws IOException {
Document doc = Jsoup.connect(url).get();
return parse(doc);
}
private List<Movie> parse(Document doc) {
List<Movie> movies = new ArrayList<>();
Elements movieElements = doc.body().getElementsByClass("video");
for (Element m : movieElements) {
Movie movie = new Movie();
// original name
String origName = m.select("h4").first().text();
movie.setOriginalName(origName);
// russian name
Element rusNameElem = m.select("h4:has(a)").first();
String rusName = rusNameElem.text();
movie.setRussianName(rusName);
// year
Node yearNode = rusNameElem.nextSibling();
String yearAndCountries = yearNode.toString().trim();
String y = yearAndCountries.substring(0, yearAndCountries.indexOf(","));
int year = Integer.valueOf(y);
movie.setYear(year);
// countries
String countriesString = yearAndCountries.substring(yearAndCountries.indexOf(",") + 1);
List<String> countries = Arrays.asList(countriesString.replaceAll("\\p{C}", "").split("-"))
.stream().map(String::trim).filter(s -> !"".equals(s)).collect(Collectors.toList());
movie.setCountries(countries);
// genres
Node genreNode = yearNode.nextSibling().nextSibling();
String genre = genreNode.toString().trim();
List<String> genres = Arrays.asList(genre.replaceAll("\\p{C}", "").split("/"))
.stream().map(String::trim).filter(s -> !"".equals(s)).collect(Collectors.toList());
movie.setGenres(genres);
// producer
Node producerNode = genreNode.nextSibling();
String producer = "";
if (producerNode.childNodes().size() > 1) {
producer = producerNode.childNode(1).toString().trim();
}
List<String> producers = Arrays.asList(producer.replaceAll("\\p{C}", "").split(","))
.stream().map(String::trim).filter(s -> !"".equals(s)).collect(Collectors.toList());
movie.setProducers(producers);
// actors
Node actorsNode = producerNode.nextSibling().nextSibling();
String actor = "";
List<String> actors = null;
if (actorsNode != null) {
if (actorsNode.childNodes().size() > 1) {
actor = actorsNode.childNode(1).toString().trim();
}
actors = Arrays.asList(actor.replaceAll("\\p{C}", "").split(","))
.stream().map(String::trim).filter(s -> !"".equals(s)).collect(Collectors.toList());
}
movie.setActors(actors);
// full info url
String fullInfoUrl = homepage + m.select("a").first().attr("href");
movie.setFullInfoUrl(fullInfoUrl);
// cover
String imgUrl = m.getElementsByClass("cover").first().attr("style");
imgUrl = homepage + imgUrl.substring(imgUrl.indexOf("url(") + 4, imgUrl.indexOf(")"));
movie.setCover(imgUrl);
// kinopoisk raiting
String kp = m.getElementsByClass("kp").first().text().trim();
float kinopoiskRating = 0;
try {
kinopoiskRating = Float.valueOf(kp);
} catch (NumberFormatException e) {
log.error(String.format("Could not transform kinopoiskRaiting to float. value=[%s] url=%s", kp, fullInfoUrl), e);
}
movie.setKinopoiskRating(kinopoiskRating);
// imdb raiting
String imdb = m.getElementsByClass("imdb").first().text().trim();
float imdbRating = 0;
try {
imdbRating = Float.valueOf(imdb);
} catch (NumberFormatException e) {
log.error(String.format("Could not transform kinopoiskRaiting to float. value=[%s] url=%s", imdb, fullInfoUrl), e);
}
movie.setImdbRating(imdbRating);
movies.add(movie);
}
if (movies.isEmpty()) {
return null;
}
return movies;
}
}
|
package collection.test;
import java.util.ArrayList;
import java.util.List;
/*
* List
* 순서를 가지면서(내부적으로 index로 관리된다) 객체를 지정하는 방식
* 중복은 허용된다
*/
public class ArrayListTest3 {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
//Order(입력된 순서) | Sorting(알파벳 순서)
list.add("강호동");
list.add("이수근");
list.add("강호동");
list.add("서장훈");
list.add("김희철");
System.out.println(list);
//3번째 객체를 삭제
String name = list.remove(2);
//삭제된 데이터를 출력
System.out.println(list);
System.out.println("삭제된 사람은 "+name+"입니다.");
//첫번째 데이터를 아이유로 수정
list.set(0, "아이유");
//모든 정보를 출력
System.out.println(list);
//리스트에 저장된 멤버들 중에서 이름이 서장훈을 받아온다.
int cnt = 0;
for(String str : list) {
if(str.equals("서장훈")) System.out.println(list.get(cnt));
cnt++;
}
for(int i=0; i<list.size(); i++) {
if(list.get(i).equals("서장훈")) System.out.println(list.get(i));
}
}
}
|
package com.im.interfaces;
import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
public abstract class AbstractServerThread extends Logging implements Runnable{
protected Selector selector = null;
private CountDownLatch startupLatch = new CountDownLatch(1);
private CountDownLatch shutdownLatch = new CountDownLatch(1);
private AtomicBoolean alive = new AtomicBoolean(true);
public AbstractServerThread() {
try {
selector = Selector.open();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Initiates a graceful shutdown by signaling to stop and waiting for the
* shutdown to complete
* @throws InterruptedException
*/
public void shutdown() throws InterruptedException {
alive.set(false);
selector.wakeup();
shutdownLatch.await();
}
/**
* Wait for the thread to completely start up
* @throws InterruptedException
*/
public void awaitStartup() throws InterruptedException {
startupLatch.await();
}
/**
* Record that the thread startup is complete
*/
protected void startupComplete() {
startupLatch.countDown();
}
/**
* Record that the thread shutdown is complete
*/
protected void shutdownComplete() {
shutdownLatch.countDown();
}
/**
* Is the server still running?
*/
protected boolean isRunning() {
return alive.get();
}
/**
* Wakeup the thread for selection.
*/
public Selector wakeup() {
return selector.wakeup();
}
/**
* Close the given key and associated socket
*/
public void close(SelectionKey key) {
if (key != null) {
key.attach(null);
close((SocketChannel) key.channel());
try {
key.cancel();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void close(SocketChannel channel) {
if (channel != null) {
debug("Closing connection from " + channel.socket().getRemoteSocketAddress());
try {
channel.socket().close();
} catch (Exception e) {
e.printStackTrace();
}
try {
channel.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* Close all open connections
* @throws IOException
*/
public void closeAll() throws IOException {
// removes cancelled keys from selector.keys set
this.selector.selectNow();
Iterator<SelectionKey> iter = this.selector.keys().iterator();
while (iter.hasNext()) {
SelectionKey key = iter.next();
close(key);
}
}
public int countInterestOps(int ops) {
int count = 0;
Iterator<SelectionKey> it = this.selector.keys().iterator();
while (it.hasNext()) {
if ((it.next().interestOps() & ops) != 0) {
count += 1;
}
}
return count;
}
}
|
package com.example.mvptask.utils;
import com.example.mvptask.TaskApplication;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
public final class CommonUtils {
/**
*
* @param value
* @return formatted decimal format with grouping
*/
public static String formatDecimal(Double value) {
DecimalFormat df = new DecimalFormat("#,###.00");
BigDecimal example = new BigDecimal(String.valueOf(value));
return df.format(example);
}
/**
*
* @return String Json Data
* Load String (data.json) file from assets folder
*/
public static String loadJSONFromAsset(String file_name) {
String json = null;
try {
InputStream is = TaskApplication.getGlobalContext().getAssets().open(file_name);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
return json;
}
}
|
package hashtable;
/**
* @author: ZhiHao
* @date: 2021/1/7
* @version: 1.0
*/
class LinkedList {
/**
* 虚拟头节点,私有不可修改
*/
private Student head = new Student(-1, "");
/**
* 插入学生信息
*
* @param student 插入学生的信息
*/
public void add(Student student) {
if (head.next == null) {
head.next = student;
return;
}
Student temp = head.next;
while (temp.next != null) {
temp = temp.next;
}
temp.next = student;
}
/**
* 遍历链表
*/
public void traverse() {
if (head.next == null) {
System.out.println("链表为空");
return;
}
Student temp = head;
while (temp.next != null) {
temp = temp.next;
System.out.print(temp + " ");
}
//换行
System.out.println();
}
/**
* 通过id查找学生信息
*
* @param id 学生id
*/
public void findStuById(int id) {
if (head.next == null) {
System.out.println("链表为空");
return;
}
Student temp = head;
while (temp.next != null) {
temp = temp.next;
if (temp.id == id) {
//找到学生,打印学生信息
System.out.println("该学生信息:" + temp);
return;
}
}
System.out.println("未找到该学生信息");
}
}
|
package test;
import static org.junit.Assert.*;
import com.sun.jnlp.JNLPClassLoaderUtil;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Categories;
import org.junit.experimental.categories.Category;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.junit.runners.Suite.SuiteClasses;
//@RunWith(Parameterized.class)
public class CombineTest {
public static interface AddTests { /* category marker */ }
public static interface MulTests { /* category marker */ }
public static interface SmokeTests { /* category marker */ }
@RunWith(Parameterized.class)
@Category(AddTests.class)
public static class CombineAddTest {
private int a;
private int b;
private int expected;
public CombineAddTest(int a, int b, int expected) {
this.a = a;
this.b = b;
this.expected = expected;
}
@Parameters
public static Collection<Integer[]> data() {
return Arrays.asList(new Integer[][]{
{1,2,3},
{4,6,10},
{10,5,15}
});
}
@Test
public void add() {
assertEquals(expected, Combine.add(a, b));
}
}
@RunWith(Parameterized.class)
@Category(MulTests.class)
public static class CombineMulTest {
private int a;
private int b;
private int expected;
public CombineMulTest(int a, int b, int expected) {
this.a = a;
this.b = b;
this.expected = expected;
}
@Parameters
public static Collection<Integer[]> data() {
return Arrays.asList(new Integer[][]{
{1,2,2},
{4,6,24},
{10,5,50}
});
}
@Test
public void mul() {
System.out.println("Muliti");
assertEquals(expected, Combine.mul(a, b));
}
}
@RunWith(Categories.class)
@Categories.IncludeCategory(AddTests.class)
@SuiteClasses(CombineAddTest.class)
public static class AddSuite {
}
@RunWith(Categories.class)
@Categories.IncludeCategory(MulTests.class)
@SuiteClasses(CombineMulTest.class)
public static class MulSuite {
}
@Test
public void testCombine() {
Result testResult = JUnitCore.runClasses(AddSuite.class, MulSuite.class);
assertTrue(testResult.wasSuccessful());
}
} |
package net.minecraft.nbt;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
public class NBTTagLongArray extends NBTBase {
private long[] field_193587_b;
NBTTagLongArray() {}
public NBTTagLongArray(long[] p_i47524_1_) {
this.field_193587_b = p_i47524_1_;
}
public NBTTagLongArray(List<Long> p_i47525_1_) {
this(func_193586_a(p_i47525_1_));
}
private static long[] func_193586_a(List<Long> p_193586_0_) {
long[] along = new long[p_193586_0_.size()];
for (int i = 0; i < p_193586_0_.size(); i++) {
Long olong = p_193586_0_.get(i);
along[i] = (olong == null) ? 0L : olong.longValue();
}
return along;
}
void write(DataOutput output) throws IOException {
output.writeInt(this.field_193587_b.length);
byte b;
int i;
long[] arrayOfLong;
for (i = (arrayOfLong = this.field_193587_b).length, b = 0; b < i; ) {
long l = arrayOfLong[b];
output.writeLong(l);
b++;
}
}
void read(DataInput input, int depth, NBTSizeTracker sizeTracker) throws IOException {
sizeTracker.read(192L);
int i = input.readInt();
sizeTracker.read((64 * i));
this.field_193587_b = new long[i];
for (int j = 0; j < i; j++)
this.field_193587_b[j] = input.readLong();
}
public byte getId() {
return 12;
}
public String toString() {
StringBuilder stringbuilder = new StringBuilder("[L;");
for (int i = 0; i < this.field_193587_b.length; i++) {
if (i != 0)
stringbuilder.append(',');
stringbuilder.append(this.field_193587_b[i]).append('L');
}
return stringbuilder.append(']').toString();
}
public NBTTagLongArray copy() {
long[] along = new long[this.field_193587_b.length];
System.arraycopy(this.field_193587_b, 0, along, 0, this.field_193587_b.length);
return new NBTTagLongArray(along);
}
public boolean equals(Object p_equals_1_) {
return (super.equals(p_equals_1_) && Arrays.equals(this.field_193587_b, ((NBTTagLongArray)p_equals_1_).field_193587_b));
}
public int hashCode() {
return super.hashCode() ^ Arrays.hashCode(this.field_193587_b);
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\nbt\NBTTagLongArray.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/ |
package zm.gov.moh.core.repository.database.entity.system;
import java.util.HashMap;
import zm.gov.moh.core.repository.database.dao.Synchronizable;
import zm.gov.moh.core.repository.database.entity.domain.Person;
import zm.gov.moh.core.repository.database.entity.domain.PersonName;
public enum EntityType {
PATIENT(1),
ENCOUNTER(2),
VISIT(3),
OBS(4),
PERSON(5),
PERSON_NAME(6),
PERSON_ADDRESS(7),
CONCEPT(8),
CONCEPT_NAME(9),
CONCEPT_ANSWER(10),
LOCATION(11);
private int id;
EntityType(int id){
this.id = id;
}
public int getId() {
return id;
}
}
|
package pl.cwanix.opensun.agentserver.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
import lombok.Getter;
import lombok.Setter;
import pl.cwanix.opensun.commonserver.properties.SUNServerExternalServerProperties;
import pl.cwanix.opensun.commonserver.properties.SUNServerProperties;
@Getter
@Setter
@ConfigurationProperties(prefix = "opensun")
public class AgentServerProperties extends SUNServerProperties {
@NestedConfigurationProperty
private SUNServerExternalServerProperties db;
@NestedConfigurationProperty
private SUNServerExternalServerProperties world;
private String dataDirectory;
}
|
package FirstSteps.PrimitiveTypes.FloatAndDouble.Challenge;
public class FloatAndDoubleChallenge {
public static void main(String[] args) {
int myIntValue = 5 / 3;
float MyFloatValue = 5F / 3F;
double myDoubleValue = 5D / 3D;
double myDoubleValue1 = 5.00 / 3.00; // the same as doing 5D / 3D, java treats floating point operations with double as default.
System.out.println("MyIntValue= " +myIntValue);
System.out.println("MyFloatValue= " +MyFloatValue);
System.out.println("MyDoubleValue= " +myDoubleValue);
System.out.println("MyDoubleValue1= " +myDoubleValue1);
// It's better to use Double than float, it's acceded more rapidly with modern computers, it's more precise and it works with a wider range of numbers.
// Pounds to Kilograms Challenge:
double Pounds = 50;
double Kilograms = Pounds * 0.45359237D;
System.out.println(Pounds+" Pounds equals "+Kilograms+" Kilograms");
double pi = 3.1415927D;
double anotherNumber = 3_000_000.4_567_890D;
System.out.println(pi);
System.out.println(anotherNumber);
}
}
|
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;
class chess{
public static void main(String[] args) {
board b=new board();
b.menu();
b.board();
}
} |
import java.sql.*;
public class Main {
public static void main(String[] args) {
/*Напишите код, который выведет среднее количество покупок в месяц для каждого курса за
2018 год. Учитывайте диапазон месяцев, в течение которого были продажи. Подробнее в примере.*/
/*String query = "SELECT course_name,COUNT(subscription_date) / (1 + max(MONTH(subscription_date))-min(MONTH(subscription_date)))" +
" AS AveragePurchase FROM PurchaseList GROUP BY course_name";*/
/* Домашняя работа 1.10*/
/* Написать запрос для выбора студентов в порядке их регистрации на сервисе.*/
String query1 = "select name, registration_date registration_date from Students order by registration_date";
/* Написать запрос для выбора 5 самых дорогих курсов, на которых более 4 студентов, и которые длятся более 10 часов.*/
String query2 = "select name, price from courses where students_count > 4 and duration >10 order by price DESC LIMIT 5";
/* Написать один (!) запрос, который выведет одновременно список из имен трёх самых молодых студентов, имен трёх
самых старых учителей и названий трёх самых продолжительных курсов.*/
String query3 = "(select Students.name from Students order by Students.age LIMIT 3) union " +
"(select teachers.name from Teachers order by Teachers.age DESC LIMIT 3)" +
"union (select Courses.name from Courses order by Courses.duration DESC LIMIT 3)";
/*Написать запрос для выбора среднего возраста всех учителей с зарплатой более 10 000*/
String query4 = "select avg(age) from Teachers where salary > 10000";
/*Написать запрос для расчета суммы, сколько будет стоить купить все курсы по дизайну.*/
String query5 = "select sum(price) from Courses where type = 'DESIGN'";
/*Написать запрос для расчёта, сколько минут (!) длятся все курсы по программированию*/
String query6 = "select sum(duration*60 ) from Courses where type = 'PROGRAMMING'";
/*Напишите запрос, который выводит сумму, сколько часов должен в итоге проучиться каждый студент
(сумма длительности всех курсов на которые он подписан).
В результате запрос возвращает две колонки: Имя Студента — Количество часов.*/
String query7 = "select name, durations from(select student_id, sum(duration) as durations from Subscriptions, " +
"Courses where Subscriptions.course_id = Courses.id group by Subscriptions.student_id order by " +
"Subscriptions.student_id) as tb, Students where student_id = id";
/*Напишите запрос, который посчитает для каждого учителя средний возраст его учеников.
В результате запрос возвращает две колонки: Имя Учителя — Средний Возраст Учеников.*/
String query8 = "select teachers_name, avg(age) from (select teachers_name, student_id from " +
"(select Teachers.name as teachers_name, Courses.id as courses_id from Teachers, " +
"Courses where teachers.id = Courses.teacher_id order by Teachers.id) as tb, " +
"subscriptions where tb.courses_id = Subscriptions.course_id) as tb2, Students where tb2.student_id = students.id " +
"group by teachers_name";
/*Напишите запрос, который выводит среднюю зарплату учителей для каждого типа курса (Дизайн/Программирование/Маркетинг и т.д.).
В результате запрос возвращает две колонки: Тип Курса — Средняя зарплата.*/
String query9 = "select type, avg(salary) from Courses, Teachers where Courses.teacher_id = Teachers.id group by Courses.type";
/*String query10 = "select st_id,id as id_course from (select student_name,course_name,id as st_id from purchaselist, " +
"students where purchaselist.student_name = students.name)as tb, courses where tb.course_name = courses.name order by st_id";*/
try (Connection connection = MysqlConnection.connectionMysql();
Statement statement = connection.createStatement()) {
ResultSet resultSet = null;
/*System.out.println(System.lineSeparator() + "//Напишите код, который выведет среднее количество покупок в месяц для каждого курса за \n" +
"//2018 год. Учитывайте диапазон месяцев, в течение которого были продажи. Подробнее в примере.");
resultSet = statement.executeQuery(query);
while (resultSet.next()) {
System.out.print(resultSet.getString(1) + " - ");
System.out.println(resultSet.getString(2));
}*/
System.out.println(System.lineSeparator() + "Написать запрос для выбора студентов в порядке их регистрации на сервисе.");
resultSet = statement.executeQuery(query1);
while (resultSet.next()) {
System.out.print(resultSet.getString(1) + " - ");
System.out.println(resultSet.getString(2));
}
System.out.println(System.lineSeparator() + "Написать запрос для выбора 5 самых дорогих курсов, на которых более 4 студентов, и которые длятся более 10 часов.");
resultSet = statement.executeQuery(query2);
while (resultSet.next()) {
System.out.println(resultSet.getString(1) + " - ");
}
System.out.println(System.lineSeparator() + "//Написать один (!) запрос, который выведет одновременно список из имен трёх самых молодых студентов, имен трёх\n" +
"//самых старых учителей и названий трёх самых продолжительных курсов.");
resultSet = statement.executeQuery(query3);
while (resultSet.next()) {
System.out.println(resultSet.getString(1) + " - ");
}
System.out.println(System.lineSeparator() + "Написать запрос для выбора среднего возраста всех учителей с зарплатой более 10 000");
resultSet = statement.executeQuery(query4);
while (resultSet.next()) {
System.out.println(resultSet.getString(1) + " - ");
}
System.out.println(System.lineSeparator() + "Написать запрос для расчета суммы, сколько будет стоить купить все курсы по дизайну.");
resultSet = statement.executeQuery(query5);
while (resultSet.next()) {
System.out.println(resultSet.getString(1) + " - ");
}
System.out.println(System.lineSeparator() + "Написать запрос для расчёта, сколько минут (!) длятся все курсы по программированию");
resultSet = statement.executeQuery(query6);
while (resultSet.next()) {
System.out.println(resultSet.getString(1) + " - ");
}
System.out.println(System.lineSeparator() + "//Напишите запрос, который выводит сумму, сколько часов должен в итоге проучиться каждый студент (сумма длительности всех курсов на которые он подписан).\n" +
"//В результате запрос возвращает две колонки: Имя Студента — Количество часов.");
resultSet = statement.executeQuery(query7);
while (resultSet.next()) {
System.out.print(resultSet.getString(1) + " - ");
System.out.println(resultSet.getString(2));
}
System.out.println(System.lineSeparator() + "//Напишите запрос, который посчитает для каждого учителя средний возраст его учеников.\n" +
"//В результате запрос возвращает две колонки: Имя Учителя — Средний Возраст Учеников.");
resultSet = statement.executeQuery(query8);
while (resultSet.next()) {
System.out.print(resultSet.getString(1) + " - ");
System.out.println(resultSet.getString(2));
}
System.out.println(System.lineSeparator() + "//Напишите запрос, который выводит среднюю зарплату учителей для каждого типа курса (Дизайн/Программирование/Маркетинг и т.д.).\n" +
"//В результате запрос возвращает две колонки: Тип Курса — Средняя зарплата.");
resultSet = statement.executeQuery(query9);
while (resultSet.next()) {
System.out.print(resultSet.getString(1) + " - ");
System.out.println(resultSet.getString(2));
}
} catch (ExceptionConnectionMysql ex) {
ex.printStackTrace();
System.exit(-1);
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package com.xebia.retail.repo;
import org.springframework.data.jpa.repository.JpaRepository;
import com.xebia.retail.model.AffiliatedUser;
/**
*
* @author ashish
*
* Affiliated user Repository
*
*/
public interface AffiliatedUserRepo extends JpaRepository<AffiliatedUser, Integer> {
}
|
/**
*
*/
package exception;
/**
* Classe do tipo Exception que ao fazer a verificacao do erro lança a mensagem na ordenacao dos pratos e refeicoes no menu do restaurante
* @author Gabriel Alves - Joao Carlos - Melissa Diniz - Thais Nicoly
*
*/
@SuppressWarnings("serial")
public class ErroOrdenacaoException extends Exception{
/**
* Metodo que lanca a mensagem de erro quando a ordenacao dos pratos e refeicoes no menu do restaurante
* nao for realizada corretamente
* @param mensagem relativa ao erro em especifico da verificacao
*/
public ErroOrdenacaoException(String msgErro){
super("Erro Ordenacao " + msgErro);
}
}
|
/* 1: */ package com.kaldin.reports.action;
/* 2: */
/* 3: */ import com.kaldin.questionbank.topic.dao.impl.TopicImplementor;
/* 4: */ import com.kaldin.questionbank.topic.dto.TopicDTO;
/* 5: */ import com.kaldin.reports.dto.TopicQuestionCountDTO;
/* 6: */ import java.util.ArrayList;
/* 7: */ import java.util.Iterator;
/* 8: */ import java.util.List;
/* 9: */ import javax.servlet.http.HttpServletRequest;
/* 10: */ import javax.servlet.http.HttpServletResponse;
/* 11: */ import javax.servlet.http.HttpSession;
/* 12: */ import org.apache.struts.action.Action;
/* 13: */ import org.apache.struts.action.ActionForm;
/* 14: */ import org.apache.struts.action.ActionForward;
/* 15: */ import org.apache.struts.action.ActionMapping;
/* 16: */
/* 17: */ public class TopicWiseQuestion
/* 18: */ extends Action
/* 19: */ {
/* 20: */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
/* 21: */ throws Exception
/* 22: */ {
/* 23:32 */ int companyid = ((Integer)request.getSession().getAttribute("CompanyId")).intValue();
/* 24:33 */ TopicImplementor tpcImpl = new TopicImplementor();
/* 25:34 */ List<?> lstTopic = tpcImpl.showTopic(companyid);
/* 26:35 */ List<TopicQuestionCountDTO> topicquestCount = new ArrayList();
/* 27:36 */ Iterator<?> itr = lstTopic.iterator();
/* 28:37 */ while (itr.hasNext())
/* 29: */ {
/* 30:39 */ TopicQuestionCountDTO tqDTO = new TopicQuestionCountDTO();
/* 31:40 */ TopicDTO tpcDTO = (TopicDTO)itr.next();
/* 32:41 */ tqDTO.setTopicName(tpcDTO.getTopicName());
/* 33:42 */ tqDTO.setQuestionCount(tpcImpl.getTopicQuestionCount(tpcDTO.getTopicId()));
/* 34:43 */ topicquestCount.add(tqDTO);
/* 35: */ }
/* 36:45 */ request.setAttribute("TopicList", topicquestCount);
/* 37: */
/* 38: */
/* 39: */
/* 40: */
/* 41:50 */ return mapping.findForward("success");
/* 42: */ }
/* 43: */ }
/* Location: C:\Java Work\Workspace\Kaldin\WebContent\WEB-INF\classes\com\kaldin\kaldin_java.zip
* Qualified Name: kaldin.reports.action.TopicWiseQuestion
* JD-Core Version: 0.7.0.1
*/ |
package com.yc.biz;
import java.util.List;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import com.yc.bean.GoodsType;
@Repository
public interface GoodsTypeBiz {
/**
* 查找所有的商品类型
* @return
*/
public List<GoodsType> findAllGoodsType();
/**
* 根据id查找所有的商品类别
* @param typeid
* @return
*/
public GoodsType findGoodsTypeById(Integer typeid);
}
|
package mum.lesson5.problem1;
public class Square extends Rectangle{
public Square(String color, double height, double width) {
super(color, height, width);
}
@Override
public double calculateArea(){
return this.height*this.width;
}
@Override
public double calculatePerimeter(){
return 2*this.width+2*height;
}
}
|
/*
* Copyright (c) 2008-2011 by Jan Stender,
* Zuse Institute Berlin
*
* Licensed under the BSD License, see LICENSE file for details.
*
*/
package org.xtreemfs.mrc.operations;
import java.io.IOException;
import org.xtreemfs.foundation.logging.Logging;
import org.xtreemfs.foundation.logging.Logging.Category;
import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.ErrorType;
import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.POSIXErrno;
import org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.UserCredentials;
import org.xtreemfs.foundation.pbrpc.utils.ReusableBufferInputStream;
import org.xtreemfs.mrc.ErrorRecord;
import org.xtreemfs.mrc.MRCRequest;
import org.xtreemfs.mrc.MRCRequestDispatcher;
import org.xtreemfs.mrc.UserException;
import org.xtreemfs.pbrpc.generatedinterfaces.MRCServiceConstants;
import com.google.protobuf.Message;
/**
*
* @author bjko
*/
public abstract class MRCOperation {
protected final MRCRequestDispatcher master;
public MRCOperation(MRCRequestDispatcher master) {
this.master = master;
}
/**
* called after request was parsed and operation assigned.
*
* @param rq
* the new request
*/
public abstract void startRequest(MRCRequest rq) throws Throwable;
/**
* Parses the request arguments.
*
* @param rq
* the request
*
* @return null if successful, error message otherwise
*/
public ErrorRecord parseRequestArgs(MRCRequest rq) {
try {
if (Logging.isDebug())
Logging.logMessage(Logging.LEVEL_DEBUG, Category.stage, this, "parsing request arguments");
final Message rqPrototype = MRCServiceConstants.getRequestMessage(rq.getRPCRequest().getHeader()
.getRequestHeader().getProcId());
if (rqPrototype == null) {
rq.setRequestArgs(null);
if (Logging.isDebug())
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this,
"received request with empty message");
} else {
if (rq.getRPCRequest().getMessage() != null) {
rq.setRequestArgs(rqPrototype.newBuilderForType().mergeFrom(
new ReusableBufferInputStream(rq.getRPCRequest().getMessage())).build());
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this,
"received request of type %s", rq.getRequestArgs().getClass().getName());
}
} else {
rq.setRequestArgs(rqPrototype.getDefaultInstanceForType());
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.net, this,
"received request of type %s (empty message)", rq.getRequestArgs().getClass()
.getName());
}
}
}
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, this, "parsed request: %s", rqPrototype);
}
if (Logging.isDebug())
Logging.logMessage(Logging.LEVEL_DEBUG, Category.stage, this,
"successfully parsed request arguments:");
return null;
} catch (Throwable exc) {
if (Logging.isDebug()) {
Logging.logMessage(Logging.LEVEL_DEBUG, Category.stage, this,
"could not parse request arguments:");
Logging.logUserError(Logging.LEVEL_DEBUG, Category.stage, this, exc);
}
return new ErrorRecord(ErrorType.GARBAGE_ARGS, POSIXErrno.POSIX_ERROR_EINVAL, exc.getMessage(),
exc);
}
}
/**
* Returns the context associated with a request. If the request is not
* bound to a context, <code>null</code> is returned.
*
* @param rq
* the MRC request
* @return the context, or <code>null</code>, if not available
*/
public UserCredentials getUserCredentials(MRCRequest rq) throws IOException {
UserCredentials cred = (UserCredentials) rq.getRPCRequest().getHeader().getRequestHeader()
.getUserCreds();
return cred;
}
/**
* Completes a request. This method should be used if no error has occurred.
*
* @param rq
*/
public void finishRequest(MRCRequest rq) {
master.requestFinished(rq);
}
/**
* Completes a request. This method should be used if an error has occurred.
*
* @param rq
* @param error
*/
public void finishRequest(MRCRequest rq, ErrorRecord error) {
rq.setError(error);
master.requestFinished(rq);
}
protected void validateContext(MRCRequest rq) throws UserException, IOException {
UserCredentials ctx = getUserCredentials(rq);
if ((ctx == null) || (ctx.getGroupsCount() == 0) || (ctx.getUsername().length() == 0)) {
throw new UserException(POSIXErrno.POSIX_ERROR_EACCES,
"UserCredentials must contain a non-empty userID and at least one groupID!");
}
}
}
|
/*
* SUNSHINE TEAHOUSE PRIVATE LIMITED CONFIDENTIAL
* __________________
*
* [2015] - [2017] Sunshine Teahouse Private Limited
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Sunshine Teahouse Private Limited and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Sunshine Teahouse Private Limited
* and its suppliers, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Sunshine Teahouse Private Limited.
*/
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.12.19 at 12:10:26 PM IST
//
package www.chaayos.com.chaimonkbluetoothapp.domain.model.new_model;
import java.io.Serializable;
public class BasicInfo implements Serializable {
private static final long serialVersionUID = 9196734885916273962L;
private String _id;
private Long version;
/**
* Added to avoid a runtime error whereby the detachAll property is checked
* for existence but not actually used.
*/
private String detachAll;
protected int infoId;
protected String name;
protected String code;
protected String shortCode;
protected String type;
protected String status;
public String get_id() {
return _id;
}
public void set_id(String objectId) {
this._id = objectId;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
public String getDetachAll() {
return detachAll;
}
public void setDetachAll(String detachAll) {
this.detachAll = detachAll;
}
/**
* Gets the value of the productId property.
*
*/
public int getInfoId() {
return infoId;
}
/**
* Sets the value of the productId property.
*
*/
public void setInfoId(int value) {
this.infoId = value;
}
/**
* Gets the value of the name property.
*
* @return possible object is {@link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the code property.
*
* @return possible object is {@link String }
*
*/
public String getCode() {
return code;
}
/**
* Sets the value of the code property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setCode(String value) {
this.code = value;
}
/**
* Gets the value of the shortCode property.
*
* @return possible object is {@link String }
*
*/
public String getShortCode() {
return shortCode;
}
/**
* Sets the value of the shortCode property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setShortCode(String value) {
this.shortCode = value;
}
/**
* Gets the value of the type property.
*
* @return possible object is {@link String }
*
*/
public String getType() {
return type;
}
/**
* Sets the value of the type property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setType(String value) {
this.type = value;
}
/**
* Gets the value of the status property.
*
* @return possible object is {@link String }
*
*/
public String getStatus() {
return status;
}
/**
* Sets the value of the status property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setStatus(String value) {
this.status = value;
}
}
|
package com.kps.dsk;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class DSKControllerThread extends Thread {
private static final long SLEEP_DURATION = 16;
private final transient DSKController controller;
private final transient Lock stopLock;
private final transient Condition stopCondition;
private transient boolean stopping;
public DSKControllerThread(final DSKController controllerIn) {
this.controller = controllerIn;
this.stopLock = new ReentrantLock();
this.stopCondition = this.stopLock.newCondition();
}
@Override
public void run() {
boolean normalExit = true;
while (this.controller.getTime() < this.controller.getStopTime()) {
this.controller.fireVideoProgressed();
try {
Thread.sleep(SLEEP_DURATION);
} catch (final InterruptedException exception) {
normalExit = false;
break;
}
}
this.controller.fireVideoProgressed();
if (normalExit) {
this.controller.pauseWithoutStoppingThread();
}
this.stopLock.lock();
try {
this.stopping = true;
this.stopCondition.signal();
} finally {
this.stopLock.unlock();
}
}
/**
* Blocks until this DSKControllerThread is stopping.
*/
public void blockStop() {
doBlockStop();
}
/**
* Calls this.interrupt(), then blocks until this.stopping is true (I.E. block until we are certain that this
* DSKControllerThread is going to die very soon). This method should block for an extremely small amount of time.
*/
private void doBlockStop() {
this.stopLock.lock();
try {
this.interrupt();
while (!this.stopping) {
try {
this.stopCondition.await();
} catch (final InterruptedException exception) {
// We should only get here if the Thread which called this method is interrupted.
// Returning seems a reasonable thing to do in this highly exceptional circumstance because the
// DSKControllerThread is going to die soon anyway and something strange is going on anyway (Why did
// the thread calling blockStop() get interrupted?).
return;
}
}
} finally {
this.stopLock.unlock();
}
}
}
|
package timeseries.tests;
import java.util.ArrayList;
import java.util.Arrays;
import junit.framework.TestCase;
import timeseries.functions.Patterns;
public class TestSignature extends TestCase {
public void testSignature1() throws Exception {
assertEquals("=>=<<=<>>=<=====>", Patterns.getSignature(new ArrayList<>(
Arrays.asList(4, 4, 2, 2, 3, 5, 5, 6, 3, 1, 1, 2, 2, 2, 2, 2, 2, 1))));
}
public void testSignature2() throws Exception {
assertEquals("<<=>=><><><>=<=", Patterns.getSignature(new ArrayList<>(
Arrays.asList(1,2,6,6,4,4,3,5,2,5,1,5,3,3,4,4))));
}
public void testSignatureNumberOfValue() throws Exception {
assertEquals(17, Patterns.getSignature(new ArrayList<>(
Arrays.asList(4, 4, 2, 2, 3, 5, 5, 6, 3, 1, 1, 2, 2, 2, 2, 2, 2, 1))).length());
}
}
|
package boj2839;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int goal = sc.nextInt();
int maxNumFor3kg = goal / 3;
int numFor5kg = 0;
int min = 5000/3;
for(int i=0; i <= maxNumFor3kg; i++) {
if(( goal - 3*i ) % 5 == 0) {
numFor5kg = ( goal - 3*i ) / 5;
if( ( i + numFor5kg ) < min ) {
min = i + numFor5kg;
}
}
}
if(min == 5000/3) {
System.out.println(-1);
}else {
System.out.println(min);
}
}
}
|
/**
* Engine / Assets
*/
package edu.self.engine;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.Map;
/**
* Assets Class
*/
public class Assets {
/**
* Debug
*/
private static final Logger debug = Logger.getLogger(Assets.class.getName());
/**
* Components
*/
private Map<String, Sprite> sprites;
private Map<String, Sound> sounds;
/**
* Engine
*/
private Engine engine;
/**
* Constructor
*/
public Assets(Engine engine) {
debug.setLevel(Level.INFO);
engine.config.defer("path.assets", "res");
sprites = new HashMap<String, Sprite>();
sounds = new HashMap<String, Sound>();
this.engine = engine;
}
/**
* Asset Methods
*/
// Sprites
public Sprite sprite(String identifier) {
return sprites.get(identifier);
}
public void sprite(String identifier, String path, int width, int height) {
if(sprites.get(identifier) == null) {
debug.info("Storing sprite asset '" + identifier + "' from " + engine.config.get("path.assets") + "/" + path);
sprites.put(identifier, new Sprite(engine, (engine.config.get("path.assets") + "/" + path), width, height));
}
}
// Sounds
public Sound sound(String identifier) {
return sounds.get(identifier);
}
public void sound(String identifier, String path) {
if(sounds.get(identifier) == null) {
debug.info("Storing sound asset '" + identifier + "' from " + engine.config.get("path.assets") + "/" + path);
sounds.put(identifier, new Sound(engine, engine.config.get("path.assets") + "/" + path));
}
}
}
|
package chapter04;
import java.util.Scanner;
public class Exercise04_17 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a year: ");
int year = input.nextInt();
System.out
.println("Enter a month: (first three letters of a month name (with the first letter in uppercase)) ");
String month = input.next();
boolean isLeapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0 && year % 4000 != 0);
System.out.print(month + " " + year + " has ");
if (month.equals("Jun") || month.equals("Nov") || month.equals("Sep") || month.equals("Apr")) {
System.out.println("30 days");
} else if (month.equals("Mar") || month.equals("Aug") || month.equals("May") || month.equals("Oct")
|| month.equals("Jan") || month.equals("Dec") || month.equals("Jul")) {
System.out.println("31 days");
} else {
System.out.println(((isLeapYear) ? 29 : 28) + " days");
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.