text stringlengths 10 2.72M |
|---|
package ejercicio18;
import java.util.Scanner;
/**
*
* @author Javier
*/
public class Ejercicio18 {
public static void main(String[] args) {
// TODO code application logic here
Scanner entrada = new Scanner(System.in);
System.out.print("Introduce la cantidad: ");
int cantidad = entrada.nextInt();
// Billetes: 50, 20, 10, 5
int billetes50 = cantidad /50;
if (billetes50 != 0) System.out.println(billetes50 + " billetes de 50.");
cantidad = cantidad - billetes50 * 50;
if (cantidad > 0) {
int billetes20 = cantidad /20;
if (billetes20 != 0) System.out.println(billetes20 + " billetes de 20.");
cantidad = cantidad - billetes20 * 20;
}
if (cantidad > 0) {
int billetes10 = cantidad /10;
if (billetes10 != 0) System.out.println(billetes10 + " billetes de 10.");
cantidad = cantidad - billetes10 * 10;
}
if (cantidad > 0) {
int billetes5 = cantidad /5;
if (billetes5 != 0) System.out.println(billetes50 + " billetes de 5.");
cantidad = cantidad - billetes5 * 5;
}
if (cantidad > 0) {
int monedas2 = cantidad /2;
if (monedas2 != 0) System.out.println(monedas2 + " monedas de 2.");
cantidad = cantidad - monedas2 * 2;
}
if (cantidad > 0) {
// es redundante, pero lo dejo para entender mejor el codigo
int monedas1 = cantidad;
if (monedas1 != 0) System.out.println(monedas1 + " monedas de 1.");
}
}
} |
package com.impetus.common;
/**
* Class capturing constants
* @author punit
* @since 03-Aug-2012
*/
public interface EDRConstants {
// hadoop related constants
String MAPRED_SITE_XML = "mapred-site.xml";
String HDFS_SITE_XML = "hdfs-site.xml";
String CORE_SITE_XML = "core-site.xml";
//hbase related constants
String HBASE_SITE_XML = "hbase-site.xml";
String EDR_TABLE = "EDR_REQUEST_TRX";
String EDR_ID_TABLE = "EDR_ID_TRX";
String EDR_JOB_REQUEST_KEY = "JOB_REQ_SEQ";
String EDR_CF = "CF1";
enum EDR_COLUMN {ST,ET,STATUS,HDFSID,ALGO}
enum JOB_STATUS {SUBMITTED,PROCESSING,COMPLETED,FAILED,KILLED}
String DATE_FORMAT = "yyyyMM";
}
|
package com.ousl.listview;
import android.app.Activity;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.ousl.ouslnavigation.R;
public class RoomListView extends ArrayAdapter<String> {
private String rooms[];
private Activity context;
public RoomListView(Activity context, String rooms[]) {
super(context, R.layout.layout_upcoming_schedule, rooms);
this.context = context;
this.rooms = rooms;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View r = convertView;
RoomListView.ViewHolder viewHolder = null;
if(r == null){
LayoutInflater layoutInflater = context.getLayoutInflater();
r = layoutInflater.inflate(R.layout.layout_listview_rooms, null, true);
viewHolder = new RoomListView.ViewHolder(r);
r.setTag(viewHolder);
}
else{
viewHolder = (RoomListView.ViewHolder) r.getTag();
}
viewHolder.rooms.setText(rooms[position]);
return r;
}
class ViewHolder{
TextView rooms;
ViewHolder(View v){
rooms = (TextView) v.findViewById(R.id.listitem_roomname);
}
}
}
|
package com.contentstack.sdk;
/**
*
* @author Contentstack.com, Inc callback.
*
*/
public abstract class ContentTypesCallback extends ResultCallBack {
public abstract void onCompletion(ContentTypesModel contentTypesModel, Error error);
void onRequestFinish(ContentTypesModel contentTypesModel){
onCompletion(contentTypesModel, null);
}
@Override
void onRequestFail(ResponseType responseType, Error error) {
onCompletion(null, error);
}
@Override
public void always() {
}
}
|
package org.contract;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;
/**
* <p>Java class for EventData complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="EventData">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="DriverId" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* <element name="EventType" type="{http://schemas.datacontract.org/2004/07/Tmix.Cap.FleetMgmt.Library.Wcf.External.Contract.Data}EventType" minOccurs="0"/>
* <element name="Position" type="{http://schemas.datacontract.org/2004/07/Tmix.Cap.FleetMgmt.Library.Wcf.External.Contract.Data}Position" minOccurs="0"/>
* <element name="TestMode" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
* <element name="Timestamp" type="{http://www.w3.org/2001/XMLSchema}dateTime" minOccurs="0"/>
* <element name="VehicleId" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "EventData", propOrder = {
"driverId",
"eventType",
"position",
"testMode",
"timestamp",
"vehicleId"
})
public class EventDataType {
@XmlElementRef(name = "DriverId", namespace = "http://schemas.datacontract.org/2004/07/Tmix.Cap.FleetMgmt.Library.Wcf.External.Contract.Data", type = JAXBElement.class, required = false)
protected JAXBElement<Integer> driverId;
@XmlElement(name = "EventType")
protected EventTypeType eventType;
@XmlElementRef(name = "Position", namespace = "http://schemas.datacontract.org/2004/07/Tmix.Cap.FleetMgmt.Library.Wcf.External.Contract.Data", type = JAXBElement.class, required = false)
protected JAXBElement<PositionType> position;
@XmlElement(name = "TestMode")
protected Boolean testMode;
@XmlElement(name = "Timestamp")
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar timestamp;
@XmlElementRef(name = "VehicleId", namespace = "http://schemas.datacontract.org/2004/07/Tmix.Cap.FleetMgmt.Library.Wcf.External.Contract.Data", type = JAXBElement.class, required = false)
protected JAXBElement<Integer> vehicleId;
/**
* Gets the value of the driverId property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link Integer }{@code >}
*
*/
public JAXBElement<Integer> getDriverId() {
return driverId;
}
/**
* Sets the value of the driverId property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link Integer }{@code >}
*
*/
public void setDriverId(JAXBElement<Integer> value) {
this.driverId = value;
}
/**
* Gets the value of the eventType property.
*
* @return
* possible object is
* {@link EventTypeType }
*
*/
public EventTypeType getEventType() {
return eventType;
}
/**
* Sets the value of the eventType property.
*
* @param value
* allowed object is
* {@link EventTypeType }
*
*/
public void setEventType(EventTypeType value) {
this.eventType = value;
}
/**
* Gets the value of the position property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link PositionType }{@code >}
*
*/
public JAXBElement<PositionType> getPosition() {
return position;
}
/**
* Sets the value of the position property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link PositionType }{@code >}
*
*/
public void setPosition(JAXBElement<PositionType> value) {
this.position = value;
}
/**
* Gets the value of the testMode property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isTestMode() {
return testMode;
}
/**
* Sets the value of the testMode property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setTestMode(Boolean value) {
this.testMode = value;
}
/**
* Gets the value of the timestamp property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getTimestamp() {
return timestamp;
}
/**
* Sets the value of the timestamp property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setTimestamp(XMLGregorianCalendar value) {
this.timestamp = value;
}
/**
* Gets the value of the vehicleId property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link Integer }{@code >}
*
*/
public JAXBElement<Integer> getVehicleId() {
return vehicleId;
}
/**
* Sets the value of the vehicleId property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link Integer }{@code >}
*
*/
public void setVehicleId(JAXBElement<Integer> value) {
this.vehicleId = value;
}
}
|
package jire.world;
public final class ChatMessage {
private final String message;
private final int effects, color;
public ChatMessage(String message, int effects, int color) {
this.message = message;
this.effects = effects;
this.color = color;
}
public String getMessage() {
return message;
}
public int getEffects() {
return effects;
}
public int getColor() {
return color;
}
} |
package com.tech.interview.siply.redbus.controller.users;
import com.tech.interview.siply.redbus.entity.dto.OwnerDTO;
import com.tech.interview.siply.redbus.service.contract.OwnerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.UUID;
/**
* Controller layer for OWNER users
*/
@RestController
@RequestMapping("/api/user/owner")
public class OwnerController {
@Autowired
private OwnerService ownerService;
@PostMapping
public String addNewOwner(@RequestBody OwnerDTO ownerDTO) {
return ownerService.addOwner(ownerDTO);
}
@GetMapping("/all")
public List<OwnerDTO> getAllOwners() {
return ownerService.getAllOwnerUsers();
}
@GetMapping("/{ownerId}")
public String getOwner(@PathVariable UUID ownerId) {
return "This is the OWNER";
}
}
|
package by.orion.onlinertasks.presentation.profile.details;
import android.support.annotation.NonNull;
import com.arellomobile.mvp.InjectViewState;
import com.arellomobile.mvp.MvpPresenter;
import javax.inject.Inject;
import by.orion.onlinertasks.domain.interactors.ProfileDetailsInteractor;
import by.orion.onlinertasks.presentation.common.rx.RxSchedulersProvider;
@InjectViewState
public class ProfileDetailsPresenter extends MvpPresenter<ProfileDetailsView> {
@NonNull
private final Integer id;
@NonNull
private final ProfileDetailsInteractor profileDetailsInteractor;
@NonNull
private final RxSchedulersProvider rxSchedulersProvider;
@Inject
public ProfileDetailsPresenter(@NonNull Integer id, @NonNull ProfileDetailsInteractor profileDetailsInteractor, @NonNull RxSchedulersProvider rxSchedulersProvider) {
this.id = id;
this.profileDetailsInteractor = profileDetailsInteractor;
this.rxSchedulersProvider = rxSchedulersProvider;
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package stability;
import application.ExpoGenerator;
import network.Node;
import network.Scenario;
import network.TDMAScheduller;
/**
*
* @author bruker
*/
public class ExpoRun {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int nodes = Integer.valueOf(args[0]);
double transmissionRange = Double.valueOf(args[1]);
double topologySize = Double.valueOf(args[2]);
int slots = Integer.valueOf(args[3]);
double arrivalRate = Double.valueOf(args[4]);
Scenario.SchedulerType type = Scenario.SchedulerType.valueOf(args[5]);
Node.packet_loss = Double.valueOf(args[6]);
// Scenario scenario = new Scenario(10, 10, 50, 10, Scenario.SchedulerType.Balanced);
Scenario scenario = new Scenario(nodes, transmissionRange, topologySize, slots, type);
ExpoGenerator expoGen = new ExpoGenerator(scenario, arrivalRate, 0.001);
scenario.network.stats = expoGen.stats;
scenario.simulator.run();
expoGen.stats.dump();
if (args.length > 8 && Boolean.valueOf(args[8])) {
System.out.println("we have " + args.length + " args and the value is " +Boolean.valueOf(args[8]));
expoGen.stats.dump_hist();
}
}
}
|
package com.zhongyp.concurrency.thread.latchcyclicbarrier.cyclicbarrier;
import java.util.concurrent.CyclicBarrier;
import static java.lang.Thread.sleep;
/**
* project: demo
* author: zhongyp
* date: 2018/3/29
* mail: zhongyp001@163.com
*/
public class CycWork implements Runnable {
private CyclicBarrier cyclicBarrier;
private String name;
public CycWork(CyclicBarrier cyclicBarrier, String name){
this.cyclicBarrier = cyclicBarrier;
this.name = name;
}
@Override
public void run() {
System.out.println(this.name + "开始了");
try{
sleep(3000);
cyclicBarrier.await();
}catch(Exception e){
e.printStackTrace();
}
System.out.println(this.name + "干完了");
}
}
|
package com.google.track;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.google.firebase.auth.FirebaseAuth;
import butterknife.BindView;
import butterknife.ButterKnife;
public class ForgotPasswordActivity extends AppCompatActivity {
@BindView(R.id.input_forgot_email)
EditText edtForgotEmail;
@BindView(R.id.btn_reset)
Button btnResetPassword;
private FirebaseAuth auth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forgot_password);
ButterKnife.bind(this);
auth = FirebaseAuth.getInstance();
btnResetPassword.setOnClickListener(v -> resetPassword());
}
private void resetPassword() {
String mResetEmail = edtForgotEmail.getText().toString();
if (!validate(mResetEmail)) {
return;
}
auth.sendPasswordResetEmail(mResetEmail).addOnCompleteListener(this, task -> {
if (task.isSuccessful()) {
onResetSuccessful();
} else {
onResetFail();
}
})
.addOnFailureListener(this, e -> {
onResetFail();
});
}
private void onResetFail() {
Toast.makeText(this, "Unable to send reset email", Toast.LENGTH_LONG).show();
}
private void onResetSuccessful() {
Toast.makeText(this, "Reset link sent to your email", Toast.LENGTH_LONG).show();
}
private boolean validate(String mResetEmail) {
boolean valid = true;
if (mResetEmail.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(mResetEmail).matches()) {
edtForgotEmail.setError("enter a valid email address");
valid = false;
} else {
edtForgotEmail.setError(null);
}
return valid;
}
}
|
package com.webank.wedatasphere.schedulis.common.utils;
import com.webank.wedatasphere.schedulis.common.log.LogFilterEntity;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.core.Appender;
import org.apache.logging.log4j.core.Filter;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.appender.FileAppender;
import org.apache.logging.log4j.core.appender.RollingFileAppender;
import org.apache.logging.log4j.core.appender.rolling.*;
import org.apache.logging.log4j.core.config.AppenderRef;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.apache.logging.log4j.core.filter.CompositeFilter;
import org.apache.logging.log4j.core.filter.RegexFilter;
import org.apache.logging.log4j.core.layout.PatternLayout;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
public class LogUtils {
private static org.slf4j.Logger logger = LoggerFactory.getLogger(LogUtils.class);
private static final LoggerContext ctx = LoggerContext.getContext(false);
private static final Configuration config = ctx.getConfiguration();
public static void createFlowLog(String logDir, String logFileName, String logName){
if (config.getAppender(logName) != null) {
return;
}
final PatternLayout layout = PatternLayout.newBuilder()
.withCharset(Charset.forName("UTF-8"))
.withConfiguration(config)
.withPattern("%d{dd-MM-yyyy HH:mm:ss z} %c{1} %p - %m\n")
.build();
final Appender appender = FileAppender.newBuilder()
.withName(logName)
.withImmediateFlush(true)
.withFileName(String.format(logDir + File.separator + "%s", logFileName))
.withLayout(layout)
.build();
appender.start();
config.addAppender(appender);
AppenderRef[] refs = new AppenderRef[]{AppenderRef.createAppenderRef(logName, Level.ALL, null)};
LoggerConfig loggerConfig = LoggerConfig.createLogger(false, Level.ALL, logName, "true", refs, null, config, null);
loggerConfig.addAppender(appender, Level.ALL, null);
config.addLogger(logName, loggerConfig);
ctx.updateLoggers(config);
}
public static void createJobLog(String logDir, String logFileName, String logName, String logFileSize, int logFileNum, List<LogFilterEntity> logFilterEntityList){
if (config.getAppender(logName) != null) {
return;
}
final PatternLayout layout = PatternLayout.newBuilder()
.withCharset(Charset.forName("UTF-8"))
.withConfiguration(config)
.withPattern("%d{dd-MM-yyyy HH:mm:ss z} %c{1} %p - %m\n")
.build();
final TriggeringPolicy tp = SizeBasedTriggeringPolicy.createPolicy(logFileSize);
final CompositeTriggeringPolicy policyComposite = CompositeTriggeringPolicy.createPolicy(tp);
final DefaultRolloverStrategy defaultRolloverStrategy = DefaultRolloverStrategy.newBuilder()
.withMax(String.valueOf(logFileNum))
.build();
CompositeFilter compositeFilter = null;
if(CollectionUtils.isNotEmpty(logFilterEntityList)) {
List<Filter> filterList = new ArrayList<>();
for (int i = 0; i < logFilterEntityList.size(); i++) {
try {
LogFilterEntity logFilterEntity = logFilterEntityList.get(i);
Filter filter;
if (i < logFilterEntityList.size() - 1) {
filter = RegexFilter.createFilter(logFilterEntity.getCompareText(), null, false, Filter.Result.DENY, Filter.Result.NEUTRAL);
} else {
filter = RegexFilter.createFilter(logFilterEntity.getCompareText(), null, false, Filter.Result.DENY, Filter.Result.ACCEPT);
}
filterList.add(filter);
} catch (Exception e) {
logger.warn("create log filter failed.", e);
}
}
compositeFilter = CompositeFilter.createFilters(filterList.toArray(new Filter[filterList.size()]));
}
final Appender appender = RollingFileAppender.newBuilder()
.withName(logName)
.withImmediateFlush(true)
.withFileName(String.format(logDir + File.separator + "%s", logFileName))
.withFilePattern(logDir + File.separator + logFileName + ".%i")
.withLayout(layout)
.withPolicy(policyComposite)
.withStrategy(defaultRolloverStrategy)
.build();
appender.start();
config.addAppender(appender);
AppenderRef[] refs = new AppenderRef[]{AppenderRef.createAppenderRef(logName, Level.ALL, null)};
LoggerConfig loggerConfig = LoggerConfig.createLogger(false, Level.ALL, logName, "true", refs, null, config, null);
loggerConfig.addAppender(appender, Level.ALL, compositeFilter);
config.addLogger(logName, loggerConfig);
ctx.updateLoggers(config);
}
public static void stopLog(String logName){
if (config.getAppender(logName) == null) {
return;
}
config.getAppender(logName).stop();
config.getLoggerConfig(logName).removeAppender(logName);
config.removeLogger(logName);
ctx.updateLoggers();
}
}
|
package ir.ceit.search.view.adapters;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
import ir.ceit.search.R;
import ir.ceit.search.model.News;
import ir.ceit.search.view.activities.ResultActivity;
public class SimilarNewsAdapter extends RecyclerView.Adapter<SimilarNewsAdapter.ViewHolder> {
private List<News> news;
private Context mContext;
public SimilarNewsAdapter(List<News> news, Context mContext) {
this.news = news;
this.mContext = mContext;
}
@NonNull
@Override
public SimilarNewsAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.similar_news_item, parent, false);
SimilarNewsAdapter.ViewHolder holder = new SimilarNewsAdapter.ViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(@NonNull SimilarNewsAdapter.ViewHolder holder, int position) {
holder.newsTitle.setText(news.get(position).getTitle());
holder.url.setText(news.get(position).getUrl());
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Log.d(TAG, "onClick: clicked on: " + news.get(position).getTitle());
Intent intent = new Intent(mContext, ResultActivity.class);
intent.putExtra("news", news.get(position));
mContext.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return news.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView newsTitle;
TextView url;
RelativeLayout parentLayout;
public ViewHolder(View v) {
super(v);
newsTitle = v.findViewById(R.id.titleTV);
url = v.findViewById(R.id.urlTV);
parentLayout = itemView.findViewById(R.id.parent_layout);
}
}
}
|
/*
* Copyright 2003,2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cglib.proxy;
import java.lang.reflect.Method;
/**
* Map methods of subclasses generated by {@link Enhancer} to a particular
* callback. The type of the callbacks chosen for each method affects
* the bytecode generated for that method in the subclass, and cannot
* change for the life of the class.
* <p>Note: {@link CallbackFilter} implementations are supposed to be
* lightweight as cglib might keep {@link CallbackFilter} objects
* alive to enable caching of generated classes. Prefer using {@code static}
* classes for implementation of {@link CallbackFilter}.</p>
*/
public interface CallbackFilter {
/**
* Map a method to a callback.
* @param method the intercepted method
* @return the index into the array of callbacks (as specified by {@link Enhancer#setCallbacks}) to use for the method,
*/
int accept(Method method);
/**
* The <code>CallbackFilter</code> in use affects which cached class
* the <code>Enhancer</code> will use, so this is a reminder that
* you should correctly implement <code>equals</code> and
* <code>hashCode</code> for custom <code>CallbackFilter</code>
* implementations in order to improve performance.
*/
@Override
boolean equals(Object o);
}
|
package com.bestseller.service.staticPage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;
import javax.servlet.ServletContext;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class StaticPageServiceImpl implements StaticPageService ,ServletContextAware{
private Configuration conf;
private ServletContext servletContext;
public void setFreeMarkerConfigurer(FreeMarkerConfigurer fmc){
this.conf=fmc.getConfiguration();
}
@Override
public void productStaticized(Map<String, Object> map,Integer id) {
Writer out=null;
String path=servletContext.getRealPath("/html/product/"+id+".html");
try {
Template template = conf.getTemplate("productDetail.html");
File file=new File(path);
File parentFile=file.getParentFile();
if(!parentFile.exists()){
parentFile.mkdirs();
}
out=new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
template.process(map, out);
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}
finally{
if(out!=null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Override
public void setServletContext(ServletContext servletContext) {
this.servletContext=servletContext;
}
}
|
/*
* 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 tetris;
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Color;
public class Tetris extends Applet {
public void paint (Graphics g){
//declaration frame background
int rval,gval,bval;
for (int j = 30; j<(size().height-25);j+=10)
for (int i = 5; i<(size().width-25);i+=10){
rval = (int)Math.floor(Math.random()*256);
gval = (int)Math.floor(Math.random()*256);
bval = (int)Math.floor(Math.random()*256);
g.setColor(new Color(rval,gval,bval));
g.fillRect(i,j,25,25);
g.drawRect(i-1,i-j,25,25);
}
//kerangka luar
g.setColor(Color.white);
g.fillRoundRect(500, 120, 350, 500,20,20);
//frame dalam
g.setColor(Color.black);
g.fill3DRect(520, 150, 310, 300,true);
//ruang button
g.setColor(Color.yellow);
g.fillRoundRect(530, 470, 110, 120,20,20);
//button kiri
g.setColor(Color.black);
g.fillOval(541, 530, 30, 30);
//btn atas
g.setColor(Color.black);
g.fillOval(573, 490, 30, 30);
//btn kanan
g.setColor(Color.black);
g.fillOval(600, 530, 30, 30);
//buttonn start
//ruang button
g.setColor(Color.yellow);
g.fill3DRect(720, 488, 110, 120,true);
//btn atas
g.setColor(Color.black);
g.fill3DRect(763, 494, 30, 30,true);
//btn kanan
g.setColor(Color.black);
g.fill3DRect(730, 530, 30, 30,true);
//btn kiri
g.setColor(Color.black);
g.fill3DRect(793, 530, 30, 30,true);
//btn bawah
g.setColor(Color.black);
g.fill3DRect(762, 558, 30, 30,true);
//frame game
g.setColor(Color.yellow);
g.drawRect(550, 200, 90, 90);
g.drawRect(550, 200, 70, 70);
g.setColor(Color.yellow);
g.drawRect(700, 200, 90, 90);
g.drawRect(700, 200, 70, 70);
//mouth
g.setColor(Color.yellow);
g.drawArc(500, 340, 280, 280, 50, 50);
//retina 1
g.setColor(Color.white);
g.fill3DRect(590, 240, 30, 30,true);
//retina 2
g.setColor(Color.white);
g.fill3DRect(740, 240, 30, 30,true);
}
}
|
package com.alibaba.dubbo.rpc.cluster.router.script;
import com.alibaba.dubbo.common.URL;
import com.alibaba.dubbo.rpc.cluster.Router;
import com.alibaba.dubbo.rpc.cluster.RouterFactory;
public class ScriptRouterFactory implements RouterFactory {
public static final String NAME = "script";
@Override
public Router getRouter(URL url) {
return new ScriptRouter(url);
}
} |
package com.example.loginapplication.JavaObjects;
public class UserProfile {
public String username;
public String date_of_birth;
public String avatar_file_path="";
public String signin_role="";
public String TripsCreatedList="";
public String TripsJoinedList= "";
public String about_me="";
public UserProfile(String username, String date_of_birth) {
this.username = username;
this.date_of_birth = date_of_birth;
}
}
|
package com.zs.filevalidation.fileupload.service.impl;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.zs.filevalidation.fileupload.service.FileuploadService;
@Service
public class FileuploadServiceImpl implements FileuploadService {
@Override
public void uploadFile(MultipartFile file) throws IOException {
String content = new String(file.getBytes(), StandardCharsets.UTF_8);
//System.out.println(content);
InputStream inputStream = file.getInputStream();
new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))
.lines()
.forEach(System.out::println);
}
}
|
package com.yasin.processdemo;
import android.animation.Animator;
import android.animation.ValueAnimator;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.animation.AccelerateDecelerateInterpolator;
import com.yasin.processdemo.view.ProcessView;
public class MainActivity extends AppCompatActivity {
private ProcessView mProcessView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mProcessView= (ProcessView) findViewById(R.id.id_process);
startAni();
}
private void startAni() {
ValueAnimator a = ValueAnimator.ofFloat(0, 0.67f);
a.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float progress = (float) animation.getAnimatedValue();
mProcessView.setProgress(progress);
}
});
a.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
mProcessView.startAni();
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
a.setDuration(3000);
a.setInterpolator(new AccelerateDecelerateInterpolator());
a.start();
}
}
|
package com.junzhao.shanfen.activity;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.style.ClickableSpan;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.junzhao.base.base.APPCache;
import com.junzhao.base.base.BaseAct;
import com.junzhao.base.http.IHttpResultSuccess;
import com.junzhao.base.http.MLHttpRequestMessage;
import com.junzhao.base.http.MLHttpType;
import com.junzhao.base.http.MLRequestParams;
import com.junzhao.base.recycler.ViewHolder;
import com.junzhao.base.recycler.recyclerview.CommonAdapter;
import com.junzhao.base.recycler.recyclerview.OnItemClickListener;
import com.junzhao.base.utils.ImageUtils;
import com.junzhao.base.utils.MyLogger;
import com.junzhao.base.widget.refresh.SmartRefreshLayout;
import com.junzhao.shanfen.R;
import com.junzhao.shanfen.model.LZDayRankData;
import com.junzhao.shanfen.model.LZMeRankData;
import com.junzhao.shanfen.model.PHFriend;
import com.junzhao.shanfen.service.CommService;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import de.hdodenhof.circleimageview.CircleImageView;
/**
* Created by Administrator on 2018/3/23 0023.
*/
public class ZuopinActivity extends BaseAct {
private CommonAdapter adapter;
@ViewInject(R.id.rv_rank)
RecyclerView rv_rank;
@ViewInject(R.id.tv_name)
TextView tv_name;
@ViewInject(R.id.tv_mingci)
TextView tv_mingci;
@ViewInject(R.id.tv_jiangli)
TextView tv_jiangli;
@ViewInject(R.id.tv_data)
TextView tv_data;
@ViewInject(R.id.redbao_pill)
SmartRefreshLayout redbao_pill;
@ViewInject(R.id.iv_topic)
CircleImageView iv_topic;
public int pageNo = 1;
public String pageSize = "10";
private boolean mIsRefresh = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zuopin);
ViewUtils.inject(this);
// tv_name.setText(((PHUserData) APPCache.getUseData()).userName);
rv_rank.setHasFixedSize(true);
rv_rank.setNestedScrollingEnabled(false);
redbao_pill.setOnRefreshListener(new SmartRefreshLayout.onRefreshListener() {
@Override
public void onRefresh() {
mIsRefresh = true;
pageNo = 1;
getMonthRank();
}
@Override
public void onLoadMore() {
mIsRefresh = false;
pageNo = pageNo + 1;
getMonthRank();
}
});
adapter = new CommonAdapter<LZDayRankData.Rank>(getApplicationContext(), R.layout.item_zuopin, new ArrayList<LZDayRankData.Rank>()) {
@Override
public void convert(ViewHolder holder, LZDayRankData.Rank rank) {
holder.getView(R.id.rel_item_zuopin).setBackgroundResource(R.drawable.bg_paihangbang_round_commen);
holder.setText(R.id.iv_mingci, (getPosition(holder) + 1) + "");
if (getPosition(holder) == 0) {
holder.getView(R.id.rel_item_zuopin).setBackgroundResource(R.drawable.bg_paihangbang_round_first);
holder.getView(R.id.iv_mingci).setBackgroundResource(R.mipmap.one);
holder.setText(R.id.iv_mingci, "");
}
if (getPosition(holder) == 1) {
holder.getView(R.id.rel_item_zuopin).setBackgroundResource(R.drawable.bg_paihangbang_round_two);
holder.getView(R.id.iv_mingci).setBackgroundResource(R.mipmap.two);
holder.setText(R.id.iv_mingci, "");
}
if (getPosition(holder) == 2) {
holder.getView(R.id.rel_item_zuopin).setBackgroundResource(R.drawable.bg_paihangbang_round_three);
holder.getView(R.id.iv_mingci).setBackgroundResource(R.mipmap.three);
holder.setText(R.id.iv_mingci, "");
}
ImageUtils.dispatchImage(rank.photo, (CircleImageView) holder.getView(R.id.iv_topic));
holder.setText(R.id.tv_name, rank.userName);
holder.setText(R.id.tv_fensi, "粉丝:" + (rank.followNum == null ? "" : rank.followNum));
holder.setText(R.id.tv_zanNum, "点赞:" + (rank.likesNum == null ? "" : rank.likesNum));
holder.setText(R.id.tv_post, "帖子:" + getText(rank.postsContent == null ? "" : rank.postsContent));
}
};
adapter.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(ViewGroup parent, View view, Object o, int position, ViewHolder viewHolder) {
Intent intent = new Intent(ZuopinActivity.this, PostDetail2Activity.class);
intent.putExtra(PostDetail2Activity.POSTID, data.rank.get(position).postsId);
startActivity(intent);
}
@Override
public boolean onItemLongClick(ViewGroup parent, View view, Object o, int position, ViewHolder viewHolder) {
return false;
}
});
rv_rank.setAdapter(adapter);
// getDayRank();
selectPostsRankOfMonthByUserId();
getMonthRank();
}
LZDayRankData data;
private void getMonthRank() {
MLRequestParams mlHttpParam = new MLRequestParams();
mlHttpParam.put("pageNo", pageNo + "");
mlHttpParam.put("pageSize", pageSize);
MLHttpRequestMessage message = new MLHttpRequestMessage(
MLHttpType.RequestType.MONTH_ZUOPING, mlHttpParam, LZDayRankData.class,
CommService.getInstance(), true);
loadData(ZuopinActivity.this, message, new IHttpResultSuccess() {
@Override
public void success(MLHttpType.RequestType type, Object obj) {
// data = (LZDayRankData) obj;
if (mIsRefresh) {
data = (LZDayRankData) obj;
adapter.removeAllDate();
adapter.addDate(data.rank);
redbao_pill.stopRefresh();
} else {
LZDayRankData lzFaRedBaoData1 = (LZDayRankData) obj;
data.rank.addAll(lzFaRedBaoData1.rank);
adapter.addDate(lzFaRedBaoData1.rank);
redbao_pill.stopLoadMore();
//showMessage(ZuopinActivity.this,data.rank.size()+"");
}
if (data.rank != null && data.rank.size() > 0) {
tv_name.setText(data.rank.get(0).userName);
ImageUtils.dispatchImage(data.rank.get(0).photo, iv_topic);
}
tv_data.setText(data.rankDate);
// adapter.addDate(data.rank);
}
}
// , new IHttpResultError() {
// @Override
// public void error(MLHttpType.RequestType type, Object obj) {
//
// }
// }
);
}
private void selectPostsRankOfMonthByUserId() {
MLRequestParams mlHttpParam = new MLRequestParams();
mlHttpParam.put("token", APPCache.getToken());
MLHttpRequestMessage message = new MLHttpRequestMessage(
MLHttpType.RequestType.SELECTPOSTSRANKOFMONTHBYUSERID, mlHttpParam, LZMeRankData.class,
CommService.getInstance(), true);
loadData(ZuopinActivity.this, message, new IHttpResultSuccess() {
@Override
public void success(MLHttpType.RequestType type, Object obj) {
LZMeRankData data = (LZMeRankData) obj;
tv_mingci.setText("我的名次:" + (data.rank == null ? "暂无" : data.rank));
if (data.money != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
tv_jiangli.setText(Html.fromHtml(String.format
(" <font color=\"#fc8038\">现金 </font> <font color=\"#fc8038\" ><big><big><big>%s</big></big></big></font>", (data.money == null ? "暂无" : data.money)), Html.FROM_HTML_MODE_COMPACT));
} else {
tv_jiangli.setText(Html.fromHtml(String.format
("<font color=\"#fc8038\">现金 </font> <font color=\"#fc8038\" ><big><big><big>%s</big></big></big></font>", (data.money == null ? "暂无" : data.money))));
}
} else {
tv_jiangli.setText((data.money == null ? "暂无" : data.money));
}
//tv_jiangli.setText("获得奖励"+data.money);
}
}
// , new IHttpResultError() {
// @Override
// public void error(MLHttpType.RequestType type, Object obj) {
//
// }
// }
);
}
private void getDayRank() {
MLRequestParams mlHttpParam = new MLRequestParams();
mlHttpParam.put("pageNo", 1 + "");
mlHttpParam.put("pageSize", "10");
MLHttpRequestMessage message = new MLHttpRequestMessage(
MLHttpType.RequestType.DAY_ZUOPING, mlHttpParam, LZDayRankData.class,
CommService.getInstance(), true);
loadData(ZuopinActivity.this, message, new IHttpResultSuccess() {
@Override
public void success(MLHttpType.RequestType type, Object obj) {
LZDayRankData data = (LZDayRankData) obj;
adapter.addDate(data.rank);
}
}
// , new IHttpResultError() {
// @Override
// public void error(MLHttpType.RequestType type, Object obj) {
//
// }
// }
);
}
/**
* 将后台带有(@userName-userId_userid : @afff-userId_34234224)的字符串转成@字符 @[\\u4e00-\\u9fa5a-zA-Z0-9_-]+(-userId_)+[\\u4e00-\\u9fa5a-zA-Z0-9_-]*
*
* @param string
* @return
*/
public SpannableStringBuilder getText(String string) {
final List<PHFriend> data = getFriends(string);
string = string.replaceAll("(-userId_)+[a-zA-Z0-9_-]*", " ");
String reg = "@[\\u4e00-\\u9fa5a-zA-Z0-9_-]*";
Pattern pattern = Pattern.compile(reg);
Matcher matcher = pattern.matcher(string);
SpannableStringBuilder sp = new SpannableStringBuilder(string);
while (matcher.find()) {
final int start = matcher.start();
final int end = matcher.end();
MyLogger.kLog().e("start=" + start + ",end=" + end);
sp.setSpan(new ClickableSpan() {
@Override
public void onClick(View widget) {
//点击了@
MyLogger.kLog().e("---------------");
String spanString = ((TextView) widget).getText().toString().substring(start, end);
for (PHFriend friend : data) {
if (spanString.equals("@" + friend.userName + " ")) {
Intent intent = new Intent(ZuopinActivity.this, PostPersonActitity.class);
intent.putExtra(PostPersonActitity.USERID, friend.userId);
startActivity(intent);
}
}
}
public void updateDrawState(TextPaint ds) {
ds.setColor(Color.RED);
}
}, start, end, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
}
String reg1 = "((http|ftp|https)://)(([a-zA-Z0-9\\._-]+\\.[a-zA-Z]{2,6})|([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}))(:[0-9]{1,4})*(/[a-zA-Z0-9\\&%_\\./-~-]*)?";
Pattern pattern1 = Pattern.compile(reg1);
Matcher matcher1 = pattern1.matcher(string);
while (matcher1.find()) {
final int start = matcher1.start();
final int end = matcher1.end();
MyLogger.kLog().e("start=" + start + ",end=" + end + ",string = "+ string.substring(start,end));
final String finalString = string;
sp.setSpan(new ClickableSpan() {
@Override
public void onClick(View widget) {
//点击了链接
String url = finalString.substring(start,end);
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
public void updateDrawState(TextPaint ds) {
ds.setColor(Color.parseColor("#FC8138"));
}
}, start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
}
return sp;
}
public List<PHFriend> getFriends(String string) {
List<PHFriend> friends = new ArrayList<>();
String reg = "[\\u4e00-\\u9fa5a-zA-Z0-9_-]+(-userId_)+[\\u4e00-\\u9fa5a-zA-Z0-9_-]*";
Pattern pattern = Pattern.compile(reg);
Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
String userId = matcher.group();
MyLogger.kLog().e(userId);
String[] friend = userId.split("-userId_");
PHFriend pf = new PHFriend(friend[1], friend[0]);
friends.add(pf);
}
return friends;
}
@OnClick(R.id.tv_paihangguize)
public void tv_paihangguize(View view) {
startAct(ZuopinActivity.this, LZPaiHangBangRuleAty.class, data.rule);
}
@OnClick(R.id.titlebar_tv_left)
public void leftClick(View view) {
finish();
}
}
|
package com.geek._03;
import com.algorithm.list.ListNode;
import java.util.Stack;
public class ReverseKGroup {
/**
* 解法1:每k个节点进行链表翻转
* 使用栈,每k个new 一个stack,进行存放,然后把他们链接起来
* 该题需要注意的点:
* 1.while的终止条件,是当前值往后遍历的k个位置都不未null
* 2.每k个位置进行位置的reverse,剩下的节点,不进行reverse,直接拼上
*
* @param head
* @param k
* @return
*/
public static ListNode reverseKGroup(ListNode head, int k) {
if (head == null || head.next == null) {
return head;
}
ListNode pre = new ListNode(-1);
ListNode cur = head;
ListNode result = pre;
while (method(cur, k)) {
Stack<ListNode> stack = new Stack();
for (int i = 0; i < k; i++) {
stack.push(cur);
cur = cur.next;
}
for (int i = 0; i < k; i++) {
ListNode pop = stack.pop();
pre.next = pop;
pre = pre.next;
}
}
pre.next = cur;
return result.next;
}
/**
* 对该题进行最小粒度拆分
* 分为2步:
* 1.对每k个节点进行,链表翻转
* 2.将翻转后的节点进行拼接
*
* @param head
* @param k
* @return
*/
public static ListNode reverseKGroup2(ListNode head, int k) {
if (head == null || head.next == null) {
return head;
}
//定义一个虚拟头节点
ListNode dummyHead = new ListNode(0);
//假节点的next指向head
dummyHead.next = head;
//初始化pre和end都指向dummyhead
// pre指每次要翻转的链表的头结点的上一个节点。
// end指每次要翻转的链表的尾节点
ListNode pre = dummyHead;
ListNode end = dummyHead;
while (end.next != null) {
//循环k次,找到需要翻转的链表的结尾,这里每次循环要判断end是否等于空
for (int i = 0; i < k && end !=null; i++) {
end = end.next;
}
if(end == null){
break;
}
//记录下end.next,方便后面链接链表
ListNode next = end.next;
//然后断开链表
end.next = null;
//记录下要翻转链表的头节点
ListNode start = pre.next;
//翻转链表,pre.next指向翻转后的链表。1->2变成2->1
pre.next=reverse(start);
//翻转后头节点变到最后。通过之前记录的next指针连接起来
start.next = next;
//将pre换成下次要翻转的链表的头结点的上一个节点
pre = start;
end = start;
}
return dummyHead.next;
}
private static ListNode reverse(ListNode start) {
ListNode pre = null;
while(start != null){
ListNode temp = start.next;
start.next = pre;
pre = start;
start = temp;
}
return pre;
}
public ListNode reverseList(ListNode head) {
if (head == null) {
return null;
}
ListNode pre = null;
while (head != null) {
ListNode temp = head.next;
head.next = pre;
pre = head;
head = temp;
}
return pre;
}
private static boolean method(ListNode cur, int k) {
ListNode test = cur;
for (int i = 0; i < k; i++) {
if (test == null) {
return false;
}
test = test.next;
}
return true;
}
public static void main(String[] args) {
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
head.next.next.next.next = new ListNode(5);
ListNode listNode = reverseKGroup2(head, 2);
System.out.println(listNode);
}
}
|
package algdemo.dp;
import java.util.HashMap;
import java.util.Map;
public class DPCoin {
public static void main(String[] str) {
int n = 11;
int[] coins = { 1,2, 5, 3 }; //此算法只适用于包括1的情况
Map<Integer, StringBuilder> map = new HashMap<Integer, StringBuilder>();
int min = sort_and_select_min(coins);
int[] d = new int[n];
for (int i = min; i < 11; i++) {
int minCoinNum = d[i - min], lastCoin = i - min;
for (int j = 1; j < coins.length; j++) {
int coin = i - coins[j];
if (coin >= 0 && d[coin] < minCoinNum) {
minCoinNum = d[coin];
lastCoin = coin;
}
}
int coinTrace = i - lastCoin;
if (map.containsKey(lastCoin)) {
StringBuilder sb = new StringBuilder().append(map.get(lastCoin)).append(",").append(coinTrace);
map.put(i, sb);
} else {
StringBuilder sb = new StringBuilder();
sb.append(coinTrace);
map.put(i, sb);
}
d[i] = minCoinNum + 1;
System.out.println(i + "\t" + d[i] + "\t" + map.get(i).toString());
}
}
public static int sort_and_select_min(int[] coins) {
for (int i = 0; i < coins.length; i++) {
for (int j = i + 1; j < coins.length; j++) {
if (coins[i] > coins[j]) {
int tmp = coins[i];
coins[i] = coins[j];
coins[j] = tmp;
}
}
}
return coins[0];
}
}
|
package com.capgemini.service;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.ApplicationContext;
import com.capgemini.entity.Admin;
import com.capgemini.entity.CharityEvents;
import com.capgemini.entity.Donation;
import com.capgemini.entity.Donor;
import com.capgemini.entity.Ngo;
import com.capgemini.exception.InvalidCredentialsException;
import com.capgemini.exception.NoDonationFoundException;
import com.capgemini.exception.NoSuchEventFoundException;
import com.capgemini.exception.NoSuchNgoFoundException;
import com.capgemini.exception.NoSuchUserFoundException;
import com.capgemini.repository.AdminRepository;
import com.capgemini.repository.CharityEventsRepository;
import com.capgemini.repository.DonationRepository;
import com.capgemini.repository.DonorRepository;
import com.capgemini.repository.NgoRepository;
@SpringBootTest
class AdminServiceImplWithMock {
@Autowired
private AdminService service;
@Autowired
private ApplicationContext context;
@MockBean
private AdminRepository repository;
@MockBean
private NgoRepository repository2;
@MockBean
private DonationRepository donationRepository;
@MockBean
private DonorRepository donorRepository;
@MockBean
private CharityEventsRepository eventRepository;
@Test
void testFindAdminByUserNameShouldReturnAdmin() throws NoSuchUserFoundException{
Admin expected = context.getBean(Admin.class);
expected.setAdminId(1);
expected.setFirstName("Test");
expected.setLastName("Test");
expected.setPhoneNumber("0000000000");
expected.setEmail("Test@gmail.com");
expected.getAddress().setAddressId(1);
expected.getAddress().setFlatNo("Test");
expected.getAddress().setColony("Test");
expected.getAddress().setCity("Test");
expected.getAddress().setDistrict("Test");
expected.getAddress().setState("Test");
expected.getAddress().setPincode("400606");
expected.getUser().setUserId(1);
expected.getUser().setUsername("Test");
expected.getUser().setUserPassword("Test");
Admin expectation = expected;
when(repository.readAdminByUsername(expected.getUser().getUsername())).thenReturn(expectation);
Admin actual = service.findAdminByUserName(expected.getUser().getUsername());
assertEquals(expected.getAdminId(), actual.getAdminId());
assertEquals(expected.getFirstName(), actual.getFirstName());
assertEquals(expected.getLastName(), actual.getLastName());
assertEquals(expected.getPhoneNumber(), actual.getPhoneNumber());
assertEquals(expected.getEmail(), actual.getEmail());
assertEquals(expected.getAddress().getAddressId(), actual.getAddress().getAddressId());
assertEquals(expected.getAddress().getFlatNo(), actual.getAddress().getFlatNo());
assertEquals(expected.getAddress().getColony(), actual.getAddress().getColony());
assertEquals(expected.getAddress().getCity(), actual.getAddress().getCity());
assertEquals(expected.getAddress().getDistrict(), actual.getAddress().getDistrict());
assertEquals(expected.getAddress().getState(), actual.getAddress().getState());
assertEquals(expected.getAddress().getPincode(), actual.getAddress().getPincode());
assertEquals(expected.getUser().getUserId(), actual.getUser().getUserId());
assertEquals(expected.getUser().getUsername(), actual.getUser().getUsername());
assertEquals(expected.getUser().getUserPassword(), actual.getUser().getUserPassword());
}
@Test
void testFindAdminByEmailShouldReturnAdmin() throws InvalidCredentialsException, NoSuchUserFoundException{
Admin expected = context.getBean(Admin.class);
expected.setAdminId(2);
expected.setFirstName("Test");
expected.setLastName("Test");
expected.setPhoneNumber("0000000000");
expected.setEmail("Test2@gmail.com");
expected.getAddress().setAddressId(2);
expected.getAddress().setFlatNo("Test");
expected.getAddress().setColony("Test");
expected.getAddress().setCity("Test");
expected.getAddress().setDistrict("Test");
expected.getAddress().setState("Test");
expected.getAddress().setPincode("400606");
expected.getUser().setUserId(2);
expected.getUser().setUsername("Test1");
expected.getUser().setUserPassword("Test");
Admin expectation = expected;
when(repository.readAdminByEmail(expected.getEmail())).thenReturn(expectation);
Admin actual = service.findAdminByEmail(expected.getEmail());
assertEquals(expected.getAdminId(), actual.getAdminId());
assertEquals(expected.getFirstName(), actual.getFirstName());
assertEquals(expected.getLastName(), actual.getLastName());
assertEquals(expected.getPhoneNumber(), actual.getPhoneNumber());
assertEquals(expected.getEmail(), actual.getEmail());
assertEquals(expected.getAddress().getAddressId(), actual.getAddress().getAddressId());
assertEquals(expected.getAddress().getFlatNo(), actual.getAddress().getFlatNo());
assertEquals(expected.getAddress().getColony(), actual.getAddress().getColony());
assertEquals(expected.getAddress().getCity(), actual.getAddress().getCity());
assertEquals(expected.getAddress().getDistrict(), actual.getAddress().getDistrict());
assertEquals(expected.getAddress().getState(), actual.getAddress().getState());
assertEquals(expected.getAddress().getPincode(), actual.getAddress().getPincode());
assertEquals(expected.getUser().getUserId(), actual.getUser().getUserId());
assertEquals(expected.getUser().getUsername(), actual.getUser().getUsername());
assertEquals(expected.getUser().getUserPassword(), actual.getUser().getUserPassword());
}
@Test
void testFindAdminByFirstNameShouldReturnAdmin() throws NoSuchUserFoundException{
Admin admin = context.getBean(Admin.class);
admin.setAdminId(3);
admin.setFirstName("Test");
admin.setLastName("Test");
admin.setPhoneNumber("0000000000");
admin.setEmail("Test3@gmail.com");
admin.getAddress().setAddressId(3);
admin.getAddress().setFlatNo("Test");
admin.getAddress().setColony("Test");
admin.getAddress().setCity("Test");
admin.getAddress().setDistrict("Test");
admin.getAddress().setState("Test");
admin.getAddress().setPincode("400606");
admin.getUser().setUserId(3);
admin.getUser().setUsername("Test3");
admin.getUser().setUserPassword("Test");
List<Admin> list = new ArrayList<Admin>();
list.add(admin);
when(repository.readAdminByFirstName("Test")).thenReturn(list);
assertEquals(1, service.findAdminByFirstName("Test").size());
}
@Test
void testFindAdminByLastNameShouldReturnAdmin() throws NoSuchUserFoundException{
Admin admin = context.getBean(Admin.class);
admin.setAdminId(3);
admin.setFirstName("Test");
admin.setLastName("Test");
admin.setPhoneNumber("0000000000");
admin.setEmail("Test3@gmail.com");
admin.getAddress().setAddressId(3);
admin.getAddress().setFlatNo("Test");
admin.getAddress().setColony("Test");
admin.getAddress().setCity("Test");
admin.getAddress().setDistrict("Test");
admin.getAddress().setState("Test");
admin.getAddress().setPincode("400606");
admin.getUser().setUserId(3);
admin.getUser().setUsername("Test3");
admin.getUser().setUserPassword("Test");
List<Admin> list = new ArrayList<Admin>();
list.add(admin);
when(repository.readAdminByLastName("Test")).thenReturn(list);
assertEquals(1, service.findAdminByLastName("Test").size());
}
@Test
void testUpdateAdminEmail() throws InvalidCredentialsException, NoSuchUserFoundException {
Admin expected = context.getBean(Admin.class);
expected.setAdminId(1);
expected.setFirstName("Test");
expected.setLastName("Test");
expected.setPhoneNumber("0000000000");
expected.setEmail("Test@gmail.com");
expected.getAddress().setAddressId(1);
expected.getAddress().setFlatNo("Test");
expected.getAddress().setColony("Test");
expected.getAddress().setCity("Test");
expected.getAddress().setDistrict("Test");
expected.getAddress().setState("Test");
expected.getAddress().setPincode("400606");
expected.getUser().setUserId(1);
expected.getUser().setUsername("Test");
expected.getUser().setUserPassword("Test");
when(repository.readAdminByEmail("Test@gmail.com")).thenReturn(expected);
service.updateAdminEmail(1, "Test2@gmail.com");
verify(repository).updateAdminEmail(1, "Test2@gmail.com");
}
@Test
void testUpdateAdminPhoneNumber() throws InvalidCredentialsException, NoSuchUserFoundException{
Admin expected = context.getBean(Admin.class);
expected.setAdminId(1);
expected.setFirstName("Test");
expected.setLastName("Test");
expected.setPhoneNumber("0000000000");
expected.setEmail("Test@gmail.com");
expected.getAddress().setAddressId(1);
expected.getAddress().setFlatNo("Test");
expected.getAddress().setColony("Test");
expected.getAddress().setCity("Test");
expected.getAddress().setDistrict("Test");
expected.getAddress().setState("Test");
expected.getAddress().setPincode("400606");
expected.getUser().setUserId(1);
expected.getUser().setUsername("Test");
expected.getUser().setUserPassword("Test");
service.updateAdminPhoneNumber(1, "8329950738");
verify(repository).updateAdminPhoneNumber(1, "8329950738");
}
@Test
void testFindAdminDetails() throws NoSuchUserFoundException{
Admin admin = context.getBean(Admin.class);
admin.setAdminId(3);
admin.setFirstName("Test");
admin.setLastName("Test");
admin.setPhoneNumber("0000000000");
admin.setEmail("Test3@gmail.com");
admin.getAddress().setAddressId(3);
admin.getAddress().setFlatNo("Test");
admin.getAddress().setColony("Test");
admin.getAddress().setCity("Test");
admin.getAddress().setDistrict("Test");
admin.getAddress().setState("Test");
admin.getAddress().setPincode("400606");
admin.getUser().setUserId(3);
admin.getUser().setUsername("Test3");
admin.getUser().setUserPassword("Test");
List<Admin> list = new ArrayList<Admin>();
list.add(admin);
when(repository.findAll()).thenReturn(list);
assertEquals(1, service.findAdminDetails().size());
}
@Test
void testRemoveAdminByEmail() throws NoSuchUserFoundException{
Admin expected = context.getBean(Admin.class);
expected.setAdminId(1);
expected.setFirstName("Test");
expected.setLastName("Test");
expected.setPhoneNumber("0000000000");
expected.setEmail("Test@gmail.com");
expected.getAddress().setAddressId(1);
expected.getAddress().setFlatNo("Test");
expected.getAddress().setColony("Test");
expected.getAddress().setCity("Test");
expected.getAddress().setDistrict("Test");
expected.getAddress().setState("Test");
expected.getAddress().setPincode("400606");
expected.getUser().setUserId(1);
expected.getUser().setUsername("Test");
expected.getUser().setUserPassword("Test");
when(repository.readAdminByEmail("Test@gmail.com")).thenReturn(expected);
service.removeAdminByEmail("Test@gmail.com");
verify(repository).removeAdminByEmail("Test@gmail.com");
}
@Test
void testRemoveAdminByAdminId() throws NoSuchUserFoundException{
Admin expected = context.getBean(Admin.class);
expected.setAdminId(1);
expected.setFirstName("Test");
expected.setLastName("Test");
expected.setPhoneNumber("0000000000");
expected.setEmail("Test@gmail.com");
expected.getAddress().setAddressId(1);
expected.getAddress().setFlatNo("Test");
expected.getAddress().setColony("Test");
expected.getAddress().setCity("Test");
expected.getAddress().setDistrict("Test");
expected.getAddress().setState("Test");
expected.getAddress().setPincode("400606");
expected.getUser().setUserId(1);
expected.getUser().setUsername("Test");
expected.getUser().setUserPassword("Test");
when(repository.existsById(expected.getAdminId())).thenReturn(true);
Optional<Admin> expectation = Optional.of(expected);
when(repository.findById(expected.getAdminId())).thenReturn(expectation);
boolean result = service.removeAdminByadminId(1);
verify(repository).deleteById(1);
}
@Test
void testFindAllNgos() throws NoSuchNgoFoundException{
Ngo ngo = context.getBean(Ngo.class);
ngo.setNgoID(1);
ngo.setNgoName("Test");
ngo.setEmail("Test@gmail.com");
ngo.setPhoneNumber("0000000000");
ngo.setLicenceNo(0000000000);
ngo.getAddress().setAddressId(1);
ngo.getAddress().setFlatNo("Test");
ngo.getAddress().setColony("Test");
ngo.getAddress().setCity("Test");
ngo.getAddress().setDistrict("Test");
ngo.getAddress().setState("Test");
ngo.getAddress().setPincode("400606");
ngo.getUser().setUserId(1);
ngo.getUser().setUsername("Test");
ngo.getUser().setUserPassword("Test");
List<Ngo> list = new ArrayList<Ngo>();
list.add(ngo);
when(repository2.findAll()).thenReturn(list);
assertEquals(1, service.findNgo().size());
}
@Test
void testDeleteNgoByName() throws NoSuchNgoFoundException{
Ngo ngo = context.getBean(Ngo.class);
ngo.setNgoID(1);
ngo.setNgoName("Test");
ngo.setEmail("Test@gmail.com");
ngo.setPhoneNumber("0000000000");
ngo.setLicenceNo(0000000000);
ngo.getAddress().setAddressId(1);
ngo.getAddress().setFlatNo("Test");
ngo.getAddress().setColony("Test");
ngo.getAddress().setCity("Test");
ngo.getAddress().setDistrict("Test");
ngo.getAddress().setState("Test");
ngo.getAddress().setPincode("400606");
ngo.getUser().setUserId(1);
ngo.getUser().setUsername("Test");
ngo.getUser().setUserPassword("Test");
service.removeNgoByName("Test");
verify(repository).removeNgoByName("Test");
}
@Test
void testFindAllDonation() throws NoDonationFoundException{
Donation donation = context.getBean(Donation.class);
donation.setDonationId(1);
donation.setBankName("Test");
donation.setAccountNumber(00000000000);
donation.setAmount(1000);
donation.setIfscCode("Test");
//donation.setDate(16/07/2021);
donation.setPurposeOfDonation("Test");
List<Donation> list = new ArrayList<Donation>();
list.add(donation);
when(donationRepository.findAll()).thenReturn(list);
assertEquals(1, service.findDonation().size());
}
@Test
void testFindAllDonors() throws NoSuchUserFoundException{
Donor donor = context.getBean(Donor.class);
donor.setDonorId(1);
donor.setFirstName("Test");
donor.setLastName("Test");
donor.setOccupation("Test");
donor.setPhoneNumber("0000000000");
donor.setEmail("Test@gmail.com");
donor.getAddress().setAddressId(1);
donor.getAddress().setFlatNo("Test");
donor.getAddress().setColony("Test");
donor.getAddress().setCity("Test");
donor.getAddress().setDistrict("Test");
donor.getAddress().setState("Test");
donor.getAddress().setPincode("000000");
donor.getUser().setUserId(1);
donor.getUser().setUsername("Test");
donor.getUser().setUserPassword("Test");
donor.getNgos();
List<Donor> list = new ArrayList<Donor>();
list.add(donor);
when(donorRepository.findAll()).thenReturn(list);
assertEquals(1, service.findDonor().size());
}
@Test
void testFindAllCharityEvents() throws NoSuchEventFoundException{
CharityEvents events = context.getBean(CharityEvents.class);
events.setEventId(1);
events.setEventName("Test");
events.setEventType("Test");
events.setEventOrganizer("Test");
events.setSponseredBy("Test");
events.setCharitableInstitute("Test");
List<CharityEvents> list = new ArrayList<CharityEvents>();
list.add(events);
when(eventRepository.findAll()).thenReturn(list);
assertEquals(1, service.findEvents().size());
}
// @Test
// void testInvalidCredentialsException() {
// Admin admin = context.getBean(Admin.class);
// when(admin.getEmail()).thenReturn(null);
// when(repository.readAdminByEmail(admin.getEmail())).thenReturn(admin);
// assertThrows(InvalidCredentialsException.class, ()->{
// service.findAdminByEmail("test123");
// });
// }
} |
package com.example.shishir.mymusicplayer.Adapter;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import com.example.shishir.mymusicplayer.R;
import com.example.shishir.mymusicplayer.Song;
import java.util.ArrayList;
public class SongAdapter extends BaseAdapter{
private ArrayList<Song> songList;
private ArrayList<Song> orig;
private Context context;
public SongAdapter(Context context, ArrayList<Song> songList) {
this.context = context;
this.songList = songList;
}
@Override
public int getCount() {
return songList.size();
}
@Override
public Object getItem(int position) {
return songList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
static class ViewHolder {
TextView songTitleTv, artistTv;
TextView songDuration;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.single_song, null);
holder = new ViewHolder();
holder.songTitleTv = (TextView) convertView.findViewById(R.id.song_title);
holder.artistTv=(TextView)convertView.findViewById(R.id.artist);
holder.songDuration = (TextView) convertView.findViewById(R.id.song_duration);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.songTitleTv.setText(songList.get(position).getTitle());
holder.songDuration.setText(songList.get(position).getDuration());
holder.artistTv.setText(songList.get(position).getArtist());
return convertView;
}
}
|
package varliklar;
public class Kullanicilar {
private int idkullanicilar;
private String k_adi;
private String k_sifre;
private int k_yetki;
private String k_mail;
public String getK_mail() {
return k_mail;
}
public void setK_mail(String k_mail) {
this.k_mail = k_mail;
}
public int getIdkullanicilar() {
return idkullanicilar;
}
public void setIdkullanicilar(int idkullanicilar) {
this.idkullanicilar = idkullanicilar;
}
public String getK_adi() {
return k_adi;
}
public void setK_adi(String k_adi) {
this.k_adi = k_adi;
}
public String getK_sifre() {
return k_sifre;
}
public void setK_sifre(String k_sifre) {
this.k_sifre = k_sifre;
}
public int getK_yetki() {
return k_yetki;
}
public void setK_yetki(int k_yetki) {
this.k_yetki = k_yetki;
}
public Kullanicilar(int idkullanicilar, String k_adi, String k_sifre,
int k_yetki, String k_mail) {
super();
this.idkullanicilar = idkullanicilar;
this.k_adi = k_adi;
this.k_sifre = k_sifre;
this.k_yetki = k_yetki;
this.k_mail = k_mail;
}
public Kullanicilar(String k_adi, String k_sifre, int k_yetki, String k_mail) {
super();
this.k_adi = k_adi;
this.k_sifre = k_sifre;
this.k_yetki = k_yetki;
this.k_mail = k_mail;
}
public Kullanicilar() {
super();
}
}
|
package com.example.van.baotuan.VP.user.signIn;
import com.example.van.baotuan.VP.BasePresenter;
import com.example.van.baotuan.VP.BaseView;
/**
* Created by Van on 2016/11/09.
*/
public interface SignInContract {
interface View extends BaseView<Presenter>{
void signIn(String mail,String userName,String password,String repeat);
void onSuccess();
void onFailure(String msg);
}
interface Presenter extends BasePresenter{
void signIn(String mail,String userName,String password,String repeat);
void onSuccess();
void onFailure(String msg);
}
}
|
package pl.lodz.uni.math;
public class Mieszkanie {
private int iloscMieszkan;
public Mieszkanie() {
}
public int getIloscMieszkan() {
return iloscMieszkan;
}
public void setIloscMieszkan(int iloscMieszkan) {
this.iloscMieszkan = iloscMieszkan;
}
}
|
import java.util.Scanner;
public class page20 {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int total = 0;
int count = 0;
while (true) {
System.out.print("점수를 입력하시오 : ");
int grade = input.nextInt();
if (grade < 0)
break;
total += grade;
count++;
}
System.out.println("평균은 "+ total / count);
}
}
|
/*
* Copyright (c) 2008-2019 Haulmont.
*
* 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.haulmont.reports.entity;
import com.haulmont.chile.core.annotations.Composition;
import com.haulmont.chile.core.annotations.MetaProperty;
import com.haulmont.chile.core.annotations.NamePattern;
import com.haulmont.cuba.core.entity.StandardEntity;
import com.haulmont.cuba.core.entity.annotation.Listeners;
import com.haulmont.cuba.core.entity.LocaleHelper;
import com.haulmont.cuba.core.entity.annotation.SystemLevel;
import com.haulmont.cuba.security.entity.Role;
import com.haulmont.yarg.structure.ReportBand;
import com.haulmont.yarg.structure.ReportFieldFormat;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.Predicate;
import org.apache.commons.lang3.StringUtils;
import javax.persistence.*;
import java.util.*;
/**
* Attention! This entity should be detached for correct work. If you do not detach it please use logic as in
* com.haulmont.reports.listener.ReportDetachListener#onBeforeDetach(com.haulmont.reports.entity.Report, com.haulmont.cuba.core.EntityManager)
*/
@Entity(name = "report$Report")
@Table(name = "REPORT_REPORT")
@NamePattern("%s|locName,name,localeNames")
@Listeners("report_ReportDetachListener")
@SuppressWarnings("unused")
public class Report extends StandardEntity implements com.haulmont.yarg.structure.Report {
private static final long serialVersionUID = -2817764915661205093L;
@Column(name = "NAME", length = 255, nullable = false, unique = true)
protected String name;
@Column(name = "LOCALE_NAMES")
protected String localeNames;
@Column(name = "CODE", length = 255)
protected String code;
@ManyToOne(optional = false, fetch = FetchType.LAZY)
@JoinColumn(name = "GROUP_ID")
protected ReportGroup group;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "DEFAULT_TEMPLATE_ID")
protected ReportTemplate defaultTemplate;
@Column(name = "REPORT_TYPE")
protected Integer reportType;
@Column(name = "DESCRIPTION", length = 500)
protected String description;
@Column(name = "XML")
@Lob
protected String xml;
@Column(name = "ROLES_IDX", length = 1000)
protected String rolesIdx;
@Column(name = "SCREENS_IDX", length = 1000)
protected String screensIdx;
@Column(name = "INPUT_ENTITY_TYPES_IDX", length = 1000)
protected String inputEntityTypesIdx;
@Column(name = "REST_ACCESS")
protected Boolean restAccess;
@SystemLevel
@Column(name = "SYS_TENANT_ID")
protected String sysTenantId;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "report")
@Composition
protected List<ReportTemplate> templates;
@Column(name = "IS_SYSTEM")
protected Boolean system = false;
@Transient
protected BandDefinition rootBandDefinition;
@Transient @MetaProperty
protected Set<BandDefinition> bands = new HashSet<>();
@Transient @MetaProperty @Composition
protected List<ReportInputParameter> inputParameters = new ArrayList<>();
@Transient @MetaProperty @Composition
protected List<ReportValueFormat> valuesFormats = new ArrayList<>();
@Transient @MetaProperty
protected List<ReportScreen> reportScreens = new ArrayList<>();
@Transient @MetaProperty
protected Set<Role> roles = new HashSet<>();
@Transient
protected String localeName;
@Transient
protected Boolean isTmp = Boolean.FALSE;
@Transient
@MetaProperty
protected String validationScript;
@Transient
@MetaProperty
protected Boolean validationOn = false;
public Boolean getIsTmp() {
return isTmp;
}
public void setIsTmp(Boolean isTmp) {
this.isTmp = isTmp;
}
@MetaProperty
public BandDefinition getRootBandDefinition() {
if (rootBandDefinition == null && bands != null && bands.size() > 0) {
rootBandDefinition = (BandDefinition) CollectionUtils.find(bands, new Predicate() {
@Override
public boolean evaluate(Object object) {
BandDefinition band = (BandDefinition) object;
return band.getParentBandDefinition() == null;
}
});
}
return rootBandDefinition;
}
@Override
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<ReportInputParameter> getInputParameters() {
return inputParameters;
}
public void setInputParameters(List<ReportInputParameter> inputParameters) {
if (inputParameters == null) inputParameters = Collections.emptyList();
this.inputParameters = inputParameters;
}
public List<ReportValueFormat> getValuesFormats() {
return valuesFormats;
}
public void setValuesFormats(List<ReportValueFormat> valuesFormats) {
if (valuesFormats == null) valuesFormats = Collections.emptyList();
this.valuesFormats = valuesFormats;
}
public ReportType getReportType() {
return reportType != null ? ReportType.fromId(reportType) : null;
}
public void setReportType(ReportType reportType) {
this.reportType = reportType != null ? reportType.getId() : null;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
if (roles == null) roles = Collections.emptySet();
this.roles = roles;
}
public List<ReportScreen> getReportScreens() {
return reportScreens;
}
public void setReportScreens(List<ReportScreen> reportScreens) {
if (reportScreens == null) reportScreens = Collections.emptyList();
this.reportScreens = reportScreens;
}
public List<ReportTemplate> getTemplates() {
return templates;
}
public void setTemplates(List<ReportTemplate> templates) {
this.templates = templates;
}
public Boolean getSystem() {
return system;
}
public void setSystem(Boolean system) {
this.system = system;
}
public ReportTemplate getDefaultTemplate() {
return defaultTemplate;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public void setDefaultTemplate(ReportTemplate defaultTemplate) {
this.defaultTemplate = defaultTemplate;
}
public ReportTemplate getTemplateByCode(String templateCode) {
ReportTemplate template = null;
if (templates != null) {
Iterator<ReportTemplate> iter = templates.iterator();
while (iter.hasNext() && template == null) {
ReportTemplate temp = iter.next();
if (StringUtils.equalsIgnoreCase(temp.getCode(), templateCode)) {
template = temp;
}
}
}
return template;
}
public ReportGroup getGroup() {
return group;
}
public void setGroup(ReportGroup group) {
this.group = group;
}
public Set<BandDefinition> getBands() {
return bands;
}
public void setBands(Set<BandDefinition> bands) {
if (bands == null) bands = Collections.emptySet();
this.bands = bands;
}
public String getLocaleNames() {
return localeNames;
}
public void setLocaleNames(String localeNames) {
this.localeNames = localeNames;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getXml() {
return xml;
}
public void setXml(String xml) {
this.xml = xml;
}
public String getRolesIdx() {
return rolesIdx;
}
public void setRolesIdx(String rolesIdx) {
this.rolesIdx = rolesIdx;
}
public String getScreensIdx() {
return screensIdx;
}
public void setScreensIdx(String screensIdx) {
this.screensIdx = screensIdx;
}
public String getInputEntityTypesIdx() {
return inputEntityTypesIdx;
}
public void setInputEntityTypesIdx(String inputEntityTypesIdx) {
this.inputEntityTypesIdx = inputEntityTypesIdx;
}
public Boolean getRestAccess() {
return restAccess;
}
public void setRestAccess(Boolean restAccess) {
this.restAccess = restAccess;
}
public String getSysTenantId() {
return sysTenantId;
}
public void setSysTenantId(String sysTenantId) {
this.sysTenantId = sysTenantId;
}
@MetaProperty
public String getLocName() {
if (localeName == null) {
localeName = LocaleHelper.getLocalizedName(localeNames);
if (localeName == null)
localeName = name;
}
return localeName;
}
@Override
public Map<String, com.haulmont.yarg.structure.ReportTemplate> getReportTemplates() {
Map<String, com.haulmont.yarg.structure.ReportTemplate> templateMap = new HashMap<>();
for (ReportTemplate template : templates) {
templateMap.put(template.getCode(), template);
}
return templateMap;
}
@Override
public List<com.haulmont.yarg.structure.ReportParameter> getReportParameters() {
return (List) inputParameters;
}
@Override
public List<ReportFieldFormat> getReportFieldFormats() {
return (List) valuesFormats;
}
@Override
public ReportBand getRootBand() {
return getRootBandDefinition();
}
public String getValidationScript() {
return validationScript;
}
public void setValidationScript(String validationScript) {
this.validationScript = validationScript;
}
public Boolean getValidationOn() {
return validationOn;
}
public void setValidationOn(Boolean validationOn) {
this.validationOn = validationOn;
}
} |
public class Magicaldoor {
public Heroes[] generate() {
Heroes[] heroes = new Heroes[4];
Heroes warrior = new Heroes(200, 50, 20);
heroes[0] = warrior;
Heroes magic = new Heroes(200,50,20);
heroes[1]= magic;
Heroes mental = new Heroes (200,50,20);
heroes[2]= mental;
Heroes sniper = new Heroes(200,50,20);
heroes [3]= sniper;
return heroes;
}
}
|
package com.vp.lab.adp.fb.messenger;
import java.util.Arrays;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;
import com.vp.lab.config.AppConfig;
import com.vp.lab.model.Message;
import com.vp.lab.model.Messaging;
import com.vp.lab.model.User;
public class SendAPI {
private SendAPI() {
}
private static SendAPI INSTANCE = new SendAPI();
public static SendAPI getInstance() {
return INSTANCE;
}
@Autowired
private AppConfig appConfig;
private RestTemplate restTemplate = new RestTemplate();
public void send(String messagingType, String tag, String recipient, String message) {
System.out.println("Sending message: " + message);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
// headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
Messaging body = new Messaging();
body.setMessaging_type(messagingType);
body.setTag(tag);
body.setRecipient(new User(recipient));
body.setMessage(new Message(message));
String fake = "{\r\n" +
" \"messaging_type\": \"MESSAGE_TAG\",\r\n" +
" \"tag\": \"BUSINESS_PRODUCTIVITY\",\r\n" +
" \"recipient\": {\r\n" +
" \"id\": \"2510495532348174\"\r\n" +
" },\r\n" +
" \"message\": {\r\n" +
" \"text\": \"đm dễ vcl!\"\r\n" +
" }\r\n" +
"}";
HttpEntity<String> req = new HttpEntity<String>(fake, headers);
// String url =appConfig.getSendApiUri() + "?access_token=" + appConfig.getSendApiToken();
String url = "https://graph.facebook.com/v3.3/me/messages?access_token=EAAgyMVnfZA2EBALvSrUvPxRnRps15hSmyWQsC9ZB9s0Yw9jFrjaVX1gkptKcbjQzER5ZAz0rjzG85SZC8RyConFZB4QpffGi64SYiHiMuZAttXVNFr9ZCSZAsPQNDI7ZCwcmBZCQ2CwBYiWjx83FQZAYkZAHexAaOotQ05zTMevbWJDH8BmG7XRY3bjX";
System.out.println("URL : " + url);
String result = restTemplate.exchange(url, HttpMethod.POST, req, String.class).getBody();
System.out.println("Send result: " + result);
}
}
|
package dictionary;
public class Main {
public static void main(String[] args) {
// You can test your dictionary here
SaveableDictionary s = new SaveableDictionary("words.txt");
s.load();
}
}
|
package com.appirio.service.member.api;
import lombok.Getter;
import lombok.Setter;
/**
* Represents Srm division stats
*
* Created by rakeshrecharla on 7/13/15.
*/
public class SrmDivisionStats {
/**
* Level name
*/
@Getter
@Setter
private String levelName;
/**
* Problems submitted
*/
@Getter
@Setter
private Long problemsSubmitted;
/**
* Problems failed
*/
@Getter
@Setter
private Long problemsFailed;
/**
* Problem system by test
*/
@Getter
@Setter
private Long problemsSysByTest;
} |
package com.java8.concurrency;
/**
*
* Thread are based on Template method design pattern.We override the rum method from Thread but we don't invoke the run method
* unlness we want to be synchrounous.If we want to do true multithreading pro the method we invoke is start.
* The start is the method that set up all the mechanism for context switching and then it calls run
* and when the run method complete it does the graceful shutdown of the thread.
*
*/
public class MyThread extends Thread{
private int id;
public MyThread(int id){
this.id = id;
}
@Override
public void run(){
System.out.println("Hello from " + this);
}
@Override
public String toString(){
return String.format("My Thread {id = %d}", id);
}
}
|
package testObjects;
import enums.OliveColor;
import enums.OliveName;
public class Ligurio extends Olive {
public Ligurio() {
super(OliveName.LIGURIO, OliveColor.BLACK);
}
}
|
/* */ package net.minecraft.v1_7_3;
/* */
/* */ import java.util.Random;
/* */
/* */ public class NoiseGeneratorOctaves2 extends NoiseGenerator
/* */ {
/* */ private NoiseGenerator2[] a;
/* */ private int b;
/* */
/* */ public NoiseGeneratorOctaves2(Random paramRandom, int paramInt)
/* */ {
/* 14 */ this.b = paramInt;
/* 15 */ this.a = new NoiseGenerator2[paramInt];
/* 16 */ for (int i = 0; i < paramInt; i++)
/* 17 */ this.a[i] = new NoiseGenerator2(paramRandom);
/* */ }
/* */
/* */ public double[] a(double[] paramArrayOfDouble, double paramDouble1, double paramDouble2, int paramInt1, int paramInt2, double paramDouble3, double paramDouble4, double paramDouble5)
/* */ {
/* 46 */ return a(paramArrayOfDouble, paramDouble1, paramDouble2, paramInt1, paramInt2, paramDouble3, paramDouble4, paramDouble5, 0.5D);
/* */ }
/* */
/* */ public double[] a(double[] paramArrayOfDouble, double paramDouble1, double paramDouble2, int paramInt1, int paramInt2, double paramDouble3, double paramDouble4, double paramDouble5, double paramDouble6) {
/* 50 */ paramDouble3 /= 1.5D;
/* 51 */ paramDouble4 /= 1.5D;
/* */
/* 53 */ if ((paramArrayOfDouble == null) || (paramArrayOfDouble.length < paramInt1 * paramInt2)) paramArrayOfDouble = new double[paramInt1 * paramInt2]; else {
/* 54 */ for (int i = 0; i < paramArrayOfDouble.length; i++) {
/* 55 */ paramArrayOfDouble[i] = 0.0D;
/* */ }
/* */ }
/* 58 */ double d1 = 1.0D;
/* 59 */ double d2 = 1.0D;
/* 60 */ for (int j = 0; j < this.b; j++) {
/* 61 */ this.a[j].a(paramArrayOfDouble, paramDouble1, paramDouble2, paramInt1, paramInt2, paramDouble3 * d2, paramDouble4 * d2, 0.55D / d1);
/* 62 */ d2 *= paramDouble5;
/* 63 */ d1 *= paramDouble6;
/* */ }
/* */
/* 66 */ return paramArrayOfDouble;
/* */ }
/* */ }
/* Location: /home/pepijn/.m2/repository/org/bukkit/minecraft-server/1.6.6/minecraft-server-1.6.6.jar
* Qualified Name: net.minecraft.server.NoiseGeneratorOctaves2
* JD-Core Version: 0.6.0
*/ |
package bn.distributions;
import java.io.PrintStream;
import util.MathUtil;
import bn.distributions.DiscreteDistribution.DiscreteFiniteDistribution;
import bn.distributions.SparseDiscreteCPT.Entry;
import bn.messages.FiniteDiscreteMessage;
import bn.messages.MessageSet;
import bn.BNException;
/**
* Standard dense storage of a CPT of arbitrary number of conditions.
* @author Nils F Sandell
*/
public class DiscreteCPT extends DiscreteFiniteDistribution
{
/**
* Create a dense CPT
* @param dimSizes Size of the conditioned dimensions, in order
* @param cardinality Cardinality of this node.
* @param values Dense array that stores the values appropriately. The first index is
* the product space if indices and the second index is the variable value.
* @throws BNException CPT isn't normalized per condition or some index-mismatches.
*/
public DiscreteCPT(int[] dimSizes, int cardinality, double[][] values) throws BNException
{
super(cardinality);
this.dimSizes = dimSizes;
this.values = values.clone();
this.dimprod = 1;
for(int i = 0; i < this.dimSizes.length; i++)
this.dimprod *= this.dimSizes[i];
this.validate();
}
/**
* Special constructor for one parent CPT
* @param values The CPT
* @param cardinality The cardinality of this variable.
*/
public DiscreteCPT(double[][] values, int cardinality) throws BNException
{
super(cardinality);
this.dimSizes = new int[]{values.length};
this.values = values;
this.dimprod = values.length;
this.validate();
}
/**
* Create a dense CPT with an easier to form creation method.
* @param dimSizes Size of the conditioning variables in order.
* @param cardinality Size of the variable of interest.
* @param entries Iterable over entries. Each entry consists of conditionining indices,
* value for the variable of interest, and the probability.
* @throws BNException If the CPT formed with the arguments is invalid.
*/
public DiscreteCPT(int[] dimSizes, int cardinality, Iterable<SparseDiscreteCPT.Entry> entries) throws BNException
{
super(cardinality);
this.dimSizes = dimSizes;
this.dimprod = 1;
for(int i = 0; i < dimSizes.length; i++)
this.dimprod *= dimSizes[i];
this.values = new double[dimprod][];
for(int i = 0; i < dimprod; i++)
this.values[i] = new double[cardinality];
for(Entry entry : entries)
{
int index = getIndex(entry.conditional_indices, dimSizes);
values[index][entry.value_index] = entry.p;
}
this.validate();
}
/**
* Sample this distribution given some instantiation of the parents.
*/
@Override
public int sample(ValueSet<Integer> parents) throws BNException
{
int prod = 1;
for(int i = 0; i < parents.length(); i++)
prod *= parents.getValue(i);
double val = MathUtil.rand.nextDouble();
double[] dist = this.values[prod];
double sum = 0;
for(int i = 0; i < dist.length; i++)
{
sum += dist[i];
if(val < sum)
return i;
}
return dist.length-1;
}
/**
* Gibbs sample this node
*/
@Override
public int sample(ValueSet<Integer> parents, FiniteDiscreteMessage lambda) throws BNException
{
int prod = 1;
for(int i = 0; i < parents.length(); i++)
prod *= parents.getValue(i);
double val = MathUtil.rand.nextDouble();
double[] dist = this.values[prod].clone();
double distsum = 0;
for(int i = 0; i < dist.length; i++)
{
dist[i] *= lambda.getValue(i);
distsum += dist[i];
}
double sum = 0;
for(int i = 0; i < dist.length; i++)
{
double pval = dist[i]/distsum;
sum += pval;
if(val < sum)
return i;
}
return dist.length-1;
}
/**
* Validate this CPT
*/
private void validate() throws BNException
{
if(this.dimSizes.length==0)
throw new BNException("Cannot create CPT with no parents - use probability vector instead!");
int[] indices = new int[this.dimSizes.length];
for(int i = 0; i < indices.length; i++)
indices[i] = 0;
int index = 0;
do
{
double[] dist = values[index];
if(dist.length!=this.getCardinality())
throw new BNException("Attempted to initialize CPT with wrong sized dist vector at indices " + indexString(indices));
double sum = 0;
for(int i = 0; i < dist.length; i++)
{
sum += dist[i];
if(dist[i] < 0)
throw new BNException("Discrete CPT negative for indices" + indexString(indices) + " at entry" + i);
}
if(Math.abs(sum-1) > 1e-12)
throw new BNException("Discrete CPT non-normalized for indices " + indexString(indices));
index++;
} while((indices = incrementIndices(indices, dimSizes))!=null);
}
/**
* Change the distribution over the variable for a given set of parent indices
* @param indices Parent values
* @param dist New distribution
* @throws BNException If bad parent values or bad distribution.
*/
public void setDist(int[] indices, double[] dist) throws BNException
{
if(dist.length!=this.getCardinality())
throw new BNException("Attempted to set CPT dist vector at indices " + indexString(indices) + " with wrong sized pdist vector");
int index = getIndex(indices,dimSizes);
this.values[index] = dist;
}
@Override
public void validateConditionDimensions(int [] dimens) throws BNException
{
if(dimens.length!=this.dimSizes.length)
throw new BNException("Invalid parent set for CPT!");
for(int i = 0; i < dimens.length; i++)
if(dimens[i]!=dimSizes[i])
throw new BNException("Invalid parent set for CPT!");
}
@Override
public double evaluate(int[] indices, int value) throws BNException
{
return values[getIndex(indices, this.dimSizes)][value];
}
/**
* Get the dimensions of the conditioning variable set.
* @return The dimensions in an array.
*/
public int[] getConditionDimensions(){return this.dimSizes;}
@Override
public void computeLocalPi(FiniteDiscreteMessage local_pi, MessageSet<FiniteDiscreteMessage> incoming_pis) throws BNException
{
int[] indices = initialIndices(dimSizes.length);
int compositeindex = 0;
do
{
double tmp = 1;
for(int j = 0; j < indices.length; j++)
tmp *= incoming_pis.get(j).getValue(indices[j]);
for(int i = 0; i < this.getCardinality(); i++)
local_pi.setValue(i, local_pi.getValue(i)+tmp*this.values[compositeindex][i]);
compositeindex++;
}
while((indices = DiscreteDistribution.incrementIndices(indices, dimSizes))!=null);
local_pi.normalize();
}
@Override
public void computeLambdas(MessageSet<FiniteDiscreteMessage> lambdas_out, MessageSet<FiniteDiscreteMessage> incoming_pis, FiniteDiscreteMessage local_lambda, Integer obsvalue) throws BNException
{
int[] indices = initialIndices(dimSizes.length);
do
{
double pi_product = 1;
int zeroParent = -1;
for(int i = 0; i < indices.length; i++)
{
double value = incoming_pis.get(i).getValue(indices[i]);
if(value==0 && zeroParent==-1)
zeroParent = i;
else if(value==0){pi_product = 0;break;}
else
pi_product *= value;
}
if(obsvalue==null)
{
for(int i = 0; i < this.getCardinality(); i++)
{
double p = this.evaluate(indices, i);
for(int j = 0; j < indices.length; j++)
{
double local_pi_product = pi_product;
if(zeroParent!=-1 && j!=zeroParent)
local_pi_product = 0;
if(local_pi_product > 0 && zeroParent==-1)
local_pi_product /= incoming_pis.get(j).getValue(indices[j]);
lambdas_out.get(j).setValue(indices[j], lambdas_out.get(j).getValue(indices[j]) + p*local_pi_product*local_lambda.getValue(i));
}
}
}
else
{
Double p = this.evaluate(indices, obsvalue);
if(p!=null)
{
for(int j= 0; j < indices.length; j++)
{
double local_pi_product = pi_product;
if(local_pi_product > 0 && zeroParent!=j)
local_pi_product /= incoming_pis.get(j).getValue(indices[j]);
lambdas_out.get(j).setValue(indices[j], lambdas_out.get(j).getValue(indices[j]) + p*local_pi_product*local_lambda.getValue(obsvalue));
}
}
}
}
while((indices = DiscreteDistribution.incrementIndices(indices, this.dimSizes))!=null);
}
@Override
public CPTSufficient2SliceStat getSufficientStatisticObj()
{
return new CPTSufficient2SliceStat(this);
}
public void printDistribution(PrintStream ps)
{
ps.println("CPT:");
int[] indices = initialIndices(this.dimSizes.length);
int index = 0;
do
{
for(int i =0; i < this.getCardinality(); i++)
ps.println(indexString(indices) + " => " + i + " w.p. " + this.values[index][i]);
index++;
}
while((indices=incrementIndices(indices, this.dimSizes))!=null);
}
// THIS prior shit is hairy .. need a more rigorous way of ding it.
public CPTSufficient2SliceStat prior = null;
/**
* Sufficient statistic class for a dense CPT
* @author Nils F. Sandell
*/
public static class CPTSufficient2SliceStat implements DiscreteSufficientStatistic
{
/**
* Create a sufficient statistic object
* @param cpt For this CPT
*/
public CPTSufficient2SliceStat(DiscreteCPT cpt)
{
this.cpt = cpt;
this.exp_tr = new double[this.cpt.dimprod][this.cpt.getCardinality()];
this.current = new double[this.cpt.dimprod][this.cpt.getCardinality()];
this.reset();
}
@Override
public void reset()
{
for(int i = 0; i < this.cpt.dimprod; i++)
{
for(int j = 0; j < this.cpt.getCardinality(); j++)
{
this.exp_tr[i][j] = 0;
this.current[i][j] = 0;
}
}
}
@Override
public DiscreteSufficientStatistic update(SufficientStatistic stat) throws BNException
{
if(!(stat instanceof CPTSufficient2SliceStat))
throw new BNException("Attempted to combine sufficient statistics of differing types ("+this.getClass().getName()+","+stat.getClass().getName()+")");
CPTSufficient2SliceStat other = (CPTSufficient2SliceStat)stat;
if(other.cpt.dimprod!=this.cpt.dimprod || other.cpt.getCardinality()!=this.cpt.getCardinality())
throw new BNException("Attempted to combine different CPTs statistics..");
for(int i = 0; i < this.cpt.dimprod; i++)
for(int j = 0; j < this.cpt.getCardinality(); j++)
this.exp_tr[i][j] += other.exp_tr[i][j];
return this;
}
@Override
public DiscreteSufficientStatistic update(FiniteDiscreteMessage lambda,
MessageSet<FiniteDiscreteMessage> incomingPis) throws BNException
{
int[] indices = initialIndices(this.cpt.dimSizes.length);
double sum = 0;
int absIndex = 0;
do
{
double current_prod = 1;
for(int i = 0; i < indices.length; i++)
current_prod *= incomingPis.get(i).getValue(indices[i]);
for(int x = 0; x < this.cpt.getCardinality(); x++)
{
double jointBit = current_prod*this.cpt.values[absIndex][x];
this.current[absIndex][x] = jointBit*lambda.getValue(x);
sum += this.current[absIndex][x];
}
absIndex++;
}
while((indices = incrementIndices(indices, this.cpt.dimSizes))!=null);
for(int i = 0; i < this.cpt.dimprod; i++)
for(int j = 0; j < this.cpt.getCardinality(); j++)
this.exp_tr[i][j] += this.current[i][j]/sum;
return this;
}
@Override
public DiscreteSufficientStatistic update(Integer value,
MessageSet<FiniteDiscreteMessage> incomingPis) throws BNException
{
int[] indices = initialIndices(this.cpt.dimSizes.length);
double sum = 0;
int absIndex = 0;
do
{
double current_prod = 1;
for(int i = 0; i < indices.length; i++)
current_prod *= incomingPis.get(i).getValue(indices[i]);
this.current[absIndex][value] = current_prod*this.cpt.values[absIndex][value];
sum += this.current[absIndex][value];
absIndex++;
}
while((indices = incrementIndices(indices, this.cpt.dimSizes))!=null);
for(int i = 0; i < this.cpt.dimprod; i++)
this.exp_tr[i][value] += this.current[i][value]/sum;
return this;
}
public double[][] exp_tr;
double[][] current;
private DiscreteCPT cpt;
}
@Override
public double optimize(SufficientStatistic stat) throws BNException
{
if(!(stat instanceof CPTSufficient2SliceStat))
throw new BNException("Failure to optimize CPT parameters : invalid sufficient statistic object used..");
CPTSufficient2SliceStat stato = (CPTSufficient2SliceStat)stat;
if(prior!=null)
stato.update(this.prior);
double maxdiff = 0;
if(stato.cpt.dimprod!=this.dimprod || stato.cpt.getCardinality() != this.getCardinality())
throw new BNException("Failure to optimize CPT parameters : misfitting sufficient statistic object used...");
for(int i = 0; i < this.values.length; i++)
{
double rowsum = 0;
for(int j = 0; j < stato.cpt.getCardinality(); j++)
rowsum += stato.exp_tr[i][j];
if(rowsum > 0)
{
for(int j = 0; j < stato.cpt.getCardinality(); j++)
{
double newval;
if(!clampedLearn)
newval = stato.exp_tr[i][j]/rowsum;
else newval = (stato.exp_tr[i][j] + clampPct*rowsum/this.getCardinality())/(rowsum*(1+clampPct));
maxdiff = Math.max(Math.abs(this.values[i][j]-newval), maxdiff);
this.values[i][j] = newval;
}
}
}
return maxdiff;
}
@Override
public DiscreteCPT copy() throws BNException
{
double[][] newvalues = new double[dimprod][this.getCardinality()];
for(int i = 0; i < dimprod; i++)
for(int j = 0; j < this.getCardinality(); j++)
newvalues[i][j] = this.values[i][j];
DiscreteCPT copy = new DiscreteCPT(this.dimSizes, this.getCardinality(),newvalues);
copy.prior = this.prior;
return copy;
}
@Override
public double computeBethePotential(MessageSet<FiniteDiscreteMessage> incoming_pis,
FiniteDiscreteMessage local_lambda, FiniteDiscreteMessage marginal,
Integer value, int numChildren) throws BNException {
double[][] marginal_family = new double[dimprod][this.getCardinality()];
int[] indices = initialIndices(this.dimSizes.length);
double E = 0, H1 = 0, H2 = 0;
int numNeighbors = numChildren;
double sum = 0;
int iMin = 0, iMax = this.getCardinality();
int index = 0;
if(value!=null)
{
iMin = value;
iMax = value+1;
}
do
{
for(int i = iMin; i < iMax; i++)
{
double tmp = local_lambda.getValue(i)*this.values[index][i];
for(int j = 0; j < incoming_pis.size(); j++)
tmp *= incoming_pis.get(j).getValue(indices[j]);
marginal_family[index][i] = tmp;
sum += tmp;
}
index++;
} while((indices = incrementIndices(indices, this.dimSizes))!=null);
for(int idx = 0; idx < dimprod; idx++)
{
for(int i = iMin; i < iMax; i++)
{
if(marginal_family[idx][i] > 0)
{
marginal_family[idx][i] /= sum;
if(this.values[idx][i] > 0)
E -= marginal_family[idx][i]*Math.log(this.values[idx][i]);
H1 += marginal_family[idx][i]*Math.log(marginal_family[idx][i]);
}
}
}
if(value==null)
{
for(int i = 0; i < this.getCardinality(); i++)
if(marginal.getValue(i) > 0)
H2 += marginal.getValue(i)*Math.log(marginal.getValue(i));
H2*=numNeighbors;
}
return E+H1-H2;
}
@Override
public String getDefinition() {
String ret = "CPT("+this.getCardinality();
for(int i = 0; i < this.dimSizes.length; i++)
ret += "," + this.dimSizes[i];
ret += ")\n";
int[] indices = initialIndices(this.dimSizes.length);
int idx = 0;
do
{
String conds = "";
for(int i = 0; i < indices.length; i++)
conds += indices[i] + " ";
for(int i = 0; i < this.getCardinality(); i++)
ret += conds + i + " " + values[idx][i] + "\n";
idx++;
} while((indices=incrementIndices(indices, this.dimSizes))!=null);
ret += "*****\n";
return ret;
}
public static void setClampedLearn(boolean on)
{
clampedLearn = on;
}
private static boolean clampedLearn = true;
private static double clampPct = 1e-15;
private int dimprod;
private int[] dimSizes;
public double[][] values;
private static final long serialVersionUID = 50L;
} |
public class Main {
public void go(){
Sentence sentence = new Sentence();
sentence.readFile();
}
public static void main(String[] args) {
new Main().go();
}
}
|
import java.util.ArrayList;
import service.RoomService;
/*
* Museum representation (in the furure abstract)
* We have simple room creater
*
* Contains reference to RoomService
* @method openNewExhibition(int roomNumber, int howManyPersonInRoom)
*/
public class Museum {
private RoomService roomService;
private ArrayList<RoomService> allExhibitionRoom = new ArrayList<RoomService>();
public RoomService openNewExhibition(int roomNumber, int howManyPersonInRoom) {
roomService = new RoomService();
getAllExhibitionRoom().add(
roomService.createNewRoom(roomNumber, howManyPersonInRoom));
return roomService;
}
@Override
public String toString() {
for (RoomService room : getAllExhibitionRoom()) {
room.toString();
}
return new String("");
}
public ArrayList<RoomService> getAllExhibitionRoom() {
return allExhibitionRoom;
}
public void setAllExhibitionRoom(ArrayList<RoomService> allExhibitionRoom) {
this.allExhibitionRoom = allExhibitionRoom;
}
}
|
package com.example.mmazurkiewicz.s7_bbconnect;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.graphics.Color;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import Moka7.*;
public class MainActivity extends ActionBarActivity {
S7Client client = new S7Client(); //Klient połączenia Android <<>> PLC
Handler PlcConnHandler = new Handler(); //Handler operacji cyklicznych
SQLiteDatabase sourceDB= null; //Baza danych SQLite
Date curTime = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
String curTimeStr = format.format(curTime);
public boolean ConnectionState;
public boolean ConnectionStart;
//Dane SQLite
static final String srcTable = "Blueprint";
static final String colID = "ID";
static final String colName = "Name";
static final String colType = "Type";
static final String colComment = "Comment";
//Szablon w postaci lokalnych zmiennych
public String [] arrAddress = new String[99];
public String [] arrName = new String[99];
public String [] arrType = new String[99];
public String [] arrValue = new String[99];
public int [] arrStartByte = new int[99];
public int [] arrAmountByte = new int[99];
public int [] arrBitOfByte = new int[99];
public int nElements = 0; //liczba zmiennych w szablonie zapisu
//Dane pomocnicze dla wzorca AWL
public String AddrElms_DBnr = "";
public String AddrElms_VarSpec = "";
String retValue = "";
StringBuilder text4 = new StringBuilder();
//Dane połączenia ze sterownikiem
public int plcIP1 = 0;
public int plcIP2 = 0;
public int plcIP3 = 0;
public int plcIP4 = 0;
public int plcRack = 0;
public int plcSlot = 0;
public String adresIP = "";
File file = new File(Environment.getExternalStorageDirectory() + "/StoreFile.txt");
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
file.delete();
//Tworzenie folderu dla źródeł danych TXT/AWL
File folder = new File(Environment.getExternalStorageDirectory() +
File.separator + "S7BBsources");
boolean success = true;
if (!folder.exists()) {
success = folder.mkdirs();
}
File srcTXT = new File(Environment.getExternalStorageDirectory() + "/S7BBsources/SourceTXT.txt");
File srcAWL = new File(Environment.getExternalStorageDirectory() + "/S7BBsources/SourceAWL.awl");
if(!srcTXT.exists()) {
try {
FileOutputStream out = new FileOutputStream(srcTXT, true);
out.write("Tutaj wklej źródło TXT lub zastąp ten plik gotowym źródłem.".getBytes());
out.close();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Błąd zapisu do srcTXT!");
}
}
if(!srcAWL.exists()) {
try {
FileOutputStream out = new FileOutputStream(srcAWL, true);
out.write("Tutaj wklej źródło AWL lub zastąp ten plik gotowym źródłem.".getBytes());
out.close();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Błąd zapisu do srcAWL!");
}
}
//***
//Otwieranie bazy danych wzorca
sourceDB = this.openOrCreateDatabase("srcDB", MODE_PRIVATE, null);
sourceDB.execSQL("DROP TABLE IF EXISTS "+srcTable+";");//Czyszczenie bazy danych wzorca
sourceDB.execSQL("DROP TABLE IF EXISTS archiwumDB;");//Czyszczenie bazy danych wzorca
PlcConnHandler.post(CyclicPlc); //Start operacji cyklicznych
}
public void connect2PLC(View v){ //Funkcja nawiązania połączenia ze sterownikiem PLC
//Przepisanie do zmiennych podanego adresu IP sterownika PLC, jeśli poszczególne człony niepuste
EditText ETIP1 = (EditText) findViewById(R.id.eT_IP1);
if(!ETIP1.getText().toString().matches("")) {
plcIP1 = Integer.valueOf(ETIP1.getText().toString());
}
EditText ETIP2 = (EditText) findViewById(R.id.eT_IP2);
if(!ETIP2.getText().toString().matches("")) {
plcIP2 = Integer.valueOf(ETIP2.getText().toString());
}
EditText ETIP3 = (EditText) findViewById(R.id.eT_IP3);
if(!ETIP3.getText().toString().matches("")) {
plcIP3 = Integer.valueOf(ETIP3.getText().toString());
}
EditText ETIP4 = (EditText) findViewById(R.id.eT_IP4);
if(!ETIP4.getText().toString().matches("")) {
plcIP4 = Integer.valueOf(ETIP4.getText().toString());
}
EditText ETRack = (EditText) findViewById(R.id.eT_Rack);
if(!ETRack.getText().toString().matches("")) {
plcRack = Integer.valueOf(ETRack.getText().toString());
}
EditText ETSlot = (EditText) findViewById(R.id.eT_Slot);
if(!ETSlot.getText().toString().matches("")) {
plcSlot = Integer.valueOf(ETSlot.getText().toString());
}
adresIP = plcIP1+"."+plcIP2+"."+plcIP3+"."+plcIP4;
if(!ETIP1.getText().toString().matches("") & !ETIP2.getText().toString().matches("") & !ETIP3.getText().toString().matches("")
& !ETIP4.getText().toString().matches("") & !ETRack.getText().toString().matches("") & !ETSlot.getText().toString().matches("") ) {//Ustawienie rozpoczęcia połączenia
ConnectionStart = true;
}else{ //Błąd danych dla połączenia z PLC
TextView txout = (TextView) findViewById(R.id.tV_Wartosc);
txout.setText("Niepoprawne dane połączenia z PLC");
}
}
public void disconnectPLC(View v){//Funkcja zakończenia połączenia ze sterownikiem PLC
ConnectionStart = false;
}
//Operacje cykliczne
private Runnable CyclicPlc = new Runnable() {
@Override
public void run() {
//Wywołanie odczytu ze sterownika
new PlcReader().execute("");
//Aktualizacja wartości czasuaktualnego
curTime = new Date();
curTimeStr = format.format(curTime);
//Wystawienie informacji o statusie połączenia
TextView connSTS = (TextView) findViewById(R.id.tV_ConnectionState);
if(ConnectionStart){
if(ConnectionState){
connSTS.setText("Połączenie OK! :)");
connSTS.setBackgroundColor(Color.GREEN);
}else{
connSTS.setText("Brak połączenia! :/");
connSTS.setBackgroundColor(Color.RED);
}
}else{
connSTS.setText("Brak połączenia! :/");
connSTS.setBackgroundColor(Color.RED);
}
//Zdefiniowanie cyklu handlera 1000ms
PlcConnHandler.postDelayed(CyclicPlc, 1000);
}
};
private class PlcReader extends AsyncTask<String, Void, String> {
String ret = "";
@Override
protected String doInBackground(String... params) {
if (ConnectionStart){
try {
client.SetConnectionType(S7.S7_BASIC);
int res = client.ConnectTo(adresIP,plcRack,plcSlot); //S7-314
ConnectionState = client.Connected;
int n = 0;
retValue = "";
if (res == 0) {//connection ok
while (arrType [n] != null && client.Connected) {
byte[] data = new byte[arrAmountByte[n]];
res = client.ReadArea(S7.S7AreaDB, Integer.valueOf(AddrElms_DBnr), arrStartByte [n], arrAmountByte [n], data);//Read
ret = "";
if(arrType [n].contains("REAL")) {
retValue = "" + S7.GetFloatAt(data, 0);
}
if(arrType [n].contains("DWORD")) {
retValue = "" + S7.GetDWordAt(data, 0);
}
if(arrType [n].contains("DINT")) {
retValue = "" + S7.GetDIntAt(data, 0);
}
if(arrType [n].contains("WORD")) {
retValue = "" + S7.GetShortAt(data, 0);
}
if(arrType [n].contains("INT")) {
retValue = "" + S7.GetShortAt(data, 0);
}
if(arrType [n].contains("BYTE")) {
retValue = "" + data[0];
}
if(arrType [n].contains("BOOL")) {
retValue = "" + S7.GetBitAt(data, 0,arrBitOfByte[n]);
}
text4.append(retValue);
text4.append('\n');
arrValue [n] = retValue;
n=n+1;
}
} else {
ret = "Błąd: " + S7Client.ErrorText(res);
}
client.Disconnect();
} catch (Exception e) {
ret = "Wyjątek: " + e.toString();
e.printStackTrace();
System.out.println("Błąd odczytu z PLC");
Thread.interrupted();
}
return "wykonano";
}
return "wykonano";
}
@Override
protected void onPostExecute(String result){
if(ConnectionStart){
TextView txout = (TextView) findViewById(R.id.tV_Wartosc);
txout.setText(ret);
TextView tv4 = (TextView)findViewById(R.id.tV_Content_4);
tv4.setText(text4.toString());
text4.setLength(0);
int n = 0;
String sqlColumns = "";
String sqlValues = "";
String TxtNewLine = "";
while (arrType [n] != null){
sqlColumns = sqlColumns +", "+ arrName[n];
sqlValues = sqlValues + ", '"+ arrValue[n] +"'";
TxtNewLine =TxtNewLine + arrValue[n]+"; ";
n=n+1;
}
sourceDB.execSQL("INSERT INTO archiwumDB ( Czas"+ sqlColumns + ")"
+ " VALUES ('"+curTimeStr+"'" + sqlValues + ");");
String toWriteData = TxtNewLine +"\n";
try {
FileOutputStream out = new FileOutputStream(file, true);
out.write(toWriteData.toString().getBytes());
out.close();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Błąd zapisu do pliku!");
}
}
}
}
// public void openFolder(View v) //Otwieranie folderu
// {
// Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath() + "123app/");
// intent.setDataAndType(uri, "text/csv");
// startActivity(Intent.createChooser(intent, "Open folder"));
// }
public void sendMail(View v)
{
String filename="StoreFile.txt";
File filelocation = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), filename);
Uri path = Uri.fromFile(filelocation);
Intent emailIntent = new Intent(Intent.ACTION_SEND);
// set the type to 'email'
emailIntent .setType("vnd.android.cursor.dir/email");
String to[] = {"mazurkiewicz.m89@gmail.com"};
emailIntent .putExtra(Intent.EXTRA_EMAIL, to);
// the attachment
emailIntent .putExtra(Intent.EXTRA_STREAM, path);
// the mail subject
emailIntent .putExtra(Intent.EXTRA_SUBJECT, "S7-BBconnect-test mail");
startActivity(Intent.createChooser(emailIntent , "Send email..."));
}
public void readTXTsource (View v)
{
if(!ConnectionStart) {
//Get the text file
File srcTXT = new File(Environment.getExternalStorageDirectory() + "/S7BBsources/SourceTXT.txt");
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(srcTXT));
String line;
String lineSQL;
sourceDB.execSQL("DROP TABLE IF EXISTS " + srcTable + ";");
sourceDB.execSQL("CREATE TABLE IF NOT EXISTS " + srcTable + " (" //Tworzenie tabeli SQL
+ colID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ colName + " STRING, " + colType + " STRING, " + colComment + " STRING);");
while ((line = br.readLine()) != null) {
lineSQL = line.trim();
sourceDB.execSQL("INSERT INTO " + srcTable
+ " (" + colName + ")" + " VALUES ('" + lineSQL + "');");
text.append(line);
text.append('\n');
}
br.close();
} catch (IOException e) {
//You'll need to add proper error handling here
}
//Find the view by its id
TextView tv = (TextView) findViewById(R.id.tV_Content_1);
//Set the text
tv.setText(text.toString());
}
}
public void readAWLsource (View v)
{
file = new File(Environment.getExternalStorageDirectory() + "/StoreFile.txt");
if(!ConnectionStart) {
EditText ETDBnr = (EditText) findViewById(R.id.eT_DBnumber);
if (!ETDBnr.getText().toString().matches("")) {
AddrElms_DBnr = String.valueOf(ETDBnr.getText().toString());
}
//Get the text file
File srcAWL = new File(Environment.getExternalStorageDirectory() + "/S7BBsources/DB"+AddrElms_DBnr+".awl");
//Read text from file
StringBuilder text1 = new StringBuilder();
StringBuilder text2 = new StringBuilder();
StringBuilder text3 = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(srcAWL));
String line;
String lineSQL;
boolean var2SQL = false;
int n = 0;
sourceDB.execSQL("DROP TABLE IF EXISTS " + srcTable + ";");
sourceDB.execSQL("CREATE TABLE IF NOT EXISTS " + srcTable + " (" //Tworzenie tabeli SQL
+ colID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ colName + " STRING, " + colType + " STRING, " + colComment + " STRING);");
while ((line = br.readLine()) != null) {
lineSQL = line.trim();
if (lineSQL.contains("END_STRUCT")) {
var2SQL = false;
}
if (var2SQL) {
//Wyodrębnianie poszczególnych elementów-nazwa, typ zmiennej
String[] parts1 = lineSQL.split("\\:");
String part1_1 = parts1[0].trim();
String part2_1 = "";
String[] parts2 = null;
if (parts1.length > 1) {
String part1_2 = parts1[1].trim();
parts2 = part1_2.split("\\;");
part2_1 = parts2[0].trim();
}
sourceDB.execSQL("INSERT INTO " + srcTable
+ " (" + colName + ", " + colType + ", " + colComment + ")"
+ " VALUES ('" + part1_1 + "', '" + part2_1 + "', '');");
//line = part1_1 +" "+ part2_1;
arrName[n] = part1_1;
arrType[n] = part2_1;
text2.append(arrName[n]);
text2.append('\n');
text3.append(arrType[n]);
text3.append('\n');
//Wypełnienie kolumny adresów zmiennych
if (arrType[n].contains("REAL") || arrType[n].contains("DWORD") || arrType[n].contains("DINT")) {
arrAmountByte[n] = 4;
if (n == 0) {
arrStartByte[n] = 0;
} else {
arrStartByte[n] = arrStartByte[n - 1] + arrAmountByte[n - 1];
}
AddrElms_VarSpec = ("D " + arrStartByte[n]);
}
if ((arrType[n].contains("WORD") || arrType[n].contains("INT")) && !arrType[n].contains("DWORD") && !arrType[n].contains("DINT")) {
arrAmountByte[n] = 2;
if (n == 0) {
arrStartByte[n] = 0;
} else {
arrStartByte[n] = arrStartByte[n - 1] + arrAmountByte[n - 1];
}
AddrElms_VarSpec = ("W " + arrStartByte[n]);
}
if (arrType[n].contains("BYTE")) {
arrAmountByte[n] = 1;
if (n == 0) {
arrStartByte[n] = 0;
} else {
arrStartByte[n] = arrStartByte[n - 1] + arrAmountByte[n - 1];
}
AddrElms_VarSpec = ("B " + arrStartByte[n]);
}
if (arrType[n].contains("BOOL")) {
arrAmountByte[n] = 1;
if (n == 0) {
arrStartByte[n] = 0;
} else {
arrStartByte[n] = arrStartByte[n - 1] + arrAmountByte[n - 1];
}
if ((!arrType[n - 1].contains("BOOL") || arrBitOfByte[n - 1] == 7)) {
arrBitOfByte[n] = 0;
} else {
arrBitOfByte[n] = arrBitOfByte[n - 1] + 1;
}
AddrElms_VarSpec = ("X " + arrStartByte[n] + "." + arrBitOfByte[n]);
}
arrAddress[n] = ("DB" + AddrElms_DBnr + ".DB" + AddrElms_VarSpec);
text1.append(arrAddress[n]);
text1.append('\n');
nElements = n;
n = n + 1;
}
if (lineSQL.contains("STRUCT") & !lineSQL.contains("END_STRUCT")) {
var2SQL = true;
}
}
br.close();
} catch (IOException e) {
//You'll need to add proper error handling here
}
TextView tv1 = (TextView) findViewById(R.id.tV_Content_1);
tv1.setText(text1.toString());
TextView tv2 = (TextView) findViewById(R.id.tV_Content_2);
tv2.setText(text2.toString());
TextView tv3 = (TextView) findViewById(R.id.tV_Content_3);
tv3.setText(text3.toString());
sourceDB.execSQL("DROP TABLE IF EXISTS archiwumDB;");
int n = 0;
String SQLqueryAdd = "";
String TxtNewLine = "";
while(arrName [n] != null){
SQLqueryAdd = SQLqueryAdd + ", "+arrName [n]+" STRING";
TxtNewLine = TxtNewLine +arrName[n]+ "; " ;
n=n+1;
}
sourceDB.execSQL("CREATE TABLE IF NOT EXISTS archiwumDB (ID INTEGER PRIMARY KEY AUTOINCREMENT, Czas STRING"+SQLqueryAdd+");");
String toWriteData = TxtNewLine +"\n";
try {
FileOutputStream out = new FileOutputStream(file, true);
out.write(toWriteData.toString().getBytes());
out.close();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Błąd zapisu do pliku!");
}
}
}
}
|
package main;
import java.util.*;
import org.overture.codegen.runtime.*;
@SuppressWarnings("all")
public class Issue {
private String id;
private Boolean isClosed = false;
public String title;
public String description;
public VDMMap messages = MapUtil.map();
public VDMSet assignees = SetUtil.set();
public void cg_init_Issue_1(
final String issueID, final String issueTitle, final String issueDesc) {
id = issueID;
title = issueTitle;
description = issueDesc;
return;
}
public Issue(final String issueID, final String issueTitle, final String issueDesc) {
cg_init_Issue_1(issueID, issueTitle, issueDesc);
}
public void addMessage(final Message msg) {
Utils.mapSeqUpdate(messages, msg.id, msg);
}
public void assignUser(final User user) {
assignees = SetUtil.union(Utils.copy(assignees), SetUtil.set(user));
}
public void close() {
isClosed = true;
}
public void reopen() {
isClosed = false;
}
public Number numMessages() {
return MapUtil.dom(Utils.copy(messages)).size();
}
public Number numAssignees() {
return assignees.size();
}
public Boolean isIssueClosed() {
return isClosed;
}
public Issue() {}
public String toString() {
return "Issue{"
+ "id := "
+ Utils.toString(id)
+ ", isClosed := "
+ Utils.toString(isClosed)
+ ", title := "
+ Utils.toString(title)
+ ", description := "
+ Utils.toString(description)
+ ", messages := "
+ Utils.toString(messages)
+ ", assignees := "
+ Utils.toString(assignees)
+ "}";
}
}
|
/*
* work_wx
* wuhen 2020/1/16.
* Copyright (c) 2020 jianfengwuhen@126.com All Rights Reserved.
*/
package com.work.wx.task;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import com.work.wx.config.CustomConfig;
import com.work.wx.controller.modle.AuditModel;
import com.work.wx.controller.modle.ChatModel;
import com.work.wx.controller.modle.CorpModel;
import com.work.wx.controller.modle.KeywordConfigModel;
import com.work.wx.server.AuditServer;
import com.work.wx.server.ChatServer;
import com.work.wx.server.CorpServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class AutoBackUpAuditTask {
private final static int LIMIT = 1000;
private final static Logger logger = LoggerFactory.getLogger(AutoBackUpAuditTask.class);
private ChatServer chatServer;
private AuditServer auditServer;
private CorpServer corpServer;
@Autowired
public void setCorpServer(CorpServer corpServer) {
this.corpServer = corpServer;
}
@Autowired
public void setChatRecordIdServer(ChatServer chatServer) {
this.chatServer = chatServer;
}
@Autowired
public void setAuditServer(AuditServer auditServer) {
this.auditServer = auditServer;
}
/**
* @todo 自动备份消息存档
* @author wuhen
* @returns void
* @throws
* @date 2020/1/27 13:14
*/
@Async
@Scheduled(fixedRate = 1000*60*5, initialDelay = 1000*10)
public void backupWeChat() {
List<CorpModel> corpModels = corpServer.getCorpModels();
if (null != corpModels && corpModels.size() > 0) {
for (CorpModel corpModel : corpModels) {
ChatModel queryChatModel = new ChatModel(corpModel.getCorp());
queryChatModel.setMark(null);
ChatModel chatModel = chatServer.getChat(queryChatModel);
long seq = 0;
if (null != chatModel && chatModel.getSeq() != null) {
seq = chatModel.getSeq();
}
logger.debug("start backup seq start with "+seq);
boolean repeat = AuditBackUpUtil.insertChat(chatServer,auditServer,corpModel,seq,LIMIT);
if (repeat) {
backupWeChat();
}
}
}
}
/**
* @todo 自动备份消息存档
* @author wuhen
* @returns void
* @throws
* @date 2020/1/27 13:14
*/
@Async
@Scheduled(fixedRate = 1000*60*6, initialDelay = 1000*20)
public void backupWeChatData() {
List<CorpModel> corpModels = corpServer.getCorpModels();
if (null != corpModels && corpModels.size() > 0) {
for (CorpModel corpModel : corpModels) {
MultiDataProcess multiDataProcess = new MultiDataProcess();
multiDataProcess.FileTypeProcess(chatServer,corpModel);
}
}
}
}
|
package change;
public class Student {
public static void main(String[] args) {
//1111
//2222
System.out.println("1111");
}
}
|
package com.portware.FIXCertification;
import java.util.ArrayList;
import java.util.HashMap;
import org.w3c.dom.Element;
public class SavingXML {
FIXHandler F;
HashMap<String, String> MsgTypes;
MultiTransactionXMLWriter multiWriter;
String Output;
int trans_count;
Element root;
SavingXML(String Output) {
F = new FIXHandler();
trans_count = 0;
multiWriter = new MultiTransactionXMLWriter();
MsgTypes = new HashMap<>();
MsgTypes.put("R", "Request");
MsgTypes.put("S", "Response");
MsgTypes.put("D", "Order");
MsgTypes.put("8", "Execution");
MsgTypes.put("Z", "UnRegistration");
this.Output = Output;
}
public void writeTransactions(ArrayList<String> transactions) {
try {
Element transaction = null;
root = multiWriter.createRootElement();
for (String temp : transactions) {
String msgType = F.quickSearch(temp, "35");
msgType = MsgTypes.get(msgType);
if (msgType == null) {
msgType = "UnCategorized";
}
if (msgType.equals("Request")) {
if (transaction != null) {
root.appendChild(transaction);
transaction = null;
}
transaction = multiWriter.startTransaction(++trans_count);
}
multiWriter.appendChildTrans(transaction, msgType, temp);
}
multiWriter.writeToFile(Output);
} catch (Throwable e) {
e.printStackTrace();
}
}
}
|
package com.soldevelo.vmi.scheduler.server;
import com.soldevelo.vmi.config.Configuration;
import com.soldevelo.vmi.config.parameters.Parameters;
import com.soldevelo.vmi.ex.VMIException;
import com.soldevelo.vmi.scheduler.server.handler.TestResultHandler;
import com.soldevelo.vmi.scheduler.server.handler.factory.TestResultHandlerFactory;
import com.soldevelo.vmi.utils.AbstractThread;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@Component
public class TestResultThread extends AbstractThread {
private static final int THREAD_POOL_SIZE = 10;
private static final Logger LOG = LoggerFactory.getLogger(TestResultThread.class);
@Autowired
private Configuration configuration;
@Autowired
private TestResultHandlerFactory handlerFactory;
private ServerSocket serverSocket;
private ExecutorService executorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
private boolean ready;
@Override
public void run() {
start();
try {
createServerSocket();
LOG.info("Listening for test results on port "
+ configuration.getInt(Parameters.VERIZON_PROTOCOL_RESULTS_PORT));
ready = true;
while (continueRunning()) {
try {
Socket connection = serverSocket.accept();
TestResultHandler handler = handlerFactory.getObject();
handler.setConnection(connection);
executorService.execute(handler);
} catch (Exception e) {
LOG.error("Error in TestResultThread", e);
// reopen the socket if necessary
createServerSocket();
}
}
} catch (Exception e) {
ready = false;
throw new VMIException(e);
} finally {
if (serverSocket != null && !serverSocket.isClosed()) {
closeQuietly(serverSocket);
}
}
LOG.info("Stopping TestResult thread");
ready = false;
}
private void createServerSocket() throws IOException {
if (continueRunning() && (serverSocket == null || serverSocket.isClosed())) {
serverSocket = new ServerSocket(configuration.getInt(Parameters.VERIZON_PROTOCOL_RESULTS_PORT));
}
}
private void closeQuietly(ServerSocket socket) {
try {
socket.close();
} catch (IOException e) {
LOG.error("Error closing socket", e);
}
}
public boolean isReady() {
return ready;
}
@Override
public void halt() {
super.halt();
if (serverSocket != null) {
if (!serverSocket.isClosed()) {
closeQuietly(serverSocket);
}
}
}
}
|
/**
* Copyright (C) 2008 Atlassian
*
* 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.atlassian.theplugin.jira.model;
import com.atlassian.theplugin.commons.jira.api.JiraIssueAdapter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* User: jgorycki
* Date: Nov 19, 2008
* Time: 3:06:58 PM
*/
public abstract class JIRAIssueListModelListenerHolder
implements JIRAIssueListModelListener, FrozenModelListener, JIRAIssueListModel {
private List<JIRAIssueListModelListener> listeners = new ArrayList<JIRAIssueListModelListener>();
private List<FrozenModelListener> frozenListeners = new ArrayList<FrozenModelListener>();
protected final JIRAIssueListModel parent;
public JIRAIssueListModelListenerHolder(JIRAIssueListModel parent) {
this.parent = parent;
if (parent != null) {
parent.addModelListener(this);
}
}
protected void addListener(JIRAIssueListModelListener l) {
listeners.add(l);
}
protected void removeListener(JIRAIssueListModelListener l) {
listeners.remove(l);
}
public void modelChanged(JIRAIssueListModel model) {
for (JIRAIssueListModelListener l : listeners) {
l.modelChanged(model);
}
}
public void issueUpdated(JiraIssueAdapter issue) {
for (JIRAIssueListModelListener l : listeners) {
l.issueUpdated(issue);
}
}
public void issuesLoaded(JIRAIssueListModel model, int loadedIssues) {
for (JIRAIssueListModelListener l : listeners) {
l.issuesLoaded(model, loadedIssues);
}
}
public void modelFrozen(FrozenModel model, boolean frozen) {
for (FrozenModelListener l : frozenListeners) {
l.modelFrozen(model, frozen);
}
}
public void addFrozenModelListener(FrozenModelListener listener) {
if (parent != null) {
parent.addFrozenModelListener(listener);
} else {
frozenListeners.add(listener);
}
}
public void removeFrozenModelListener(FrozenModelListener listener) {
if (parent != null) {
parent.addFrozenModelListener(listener);
} else {
frozenListeners.remove(listener);
}
}
public void addModelListener(JIRAIssueListModelListener listener) {
addListener(listener);
}
public void removeModelListener(JIRAIssueListModelListener listener) {
removeListener(listener);
}
public void clear() {
if (parent != null) {
parent.clear();
}
}
// public void addIssue(JIRAIssue issue) {
// if (parent != null) {
// parent.addIssue(issue);
// }
// }
public void addIssues(Collection<JiraIssueAdapter> issues) {
if (parent != null) {
parent.addIssues(issues);
}
}
// public void setSeletedIssue(JIRAIssue issue) {
// if (parent != null) {
// parent.setSeletedIssue(issue);
// }
// }
public void updateIssue(JiraIssueAdapter issue) {
if (parent != null) {
parent.updateIssue(issue);
}
}
public void fireModelChanged() {
modelChanged(this);
}
public void fireIssueUpdated(final JiraIssueAdapter issue) {
issueUpdated(issue);
}
public void fireIssuesLoaded(int numberOfLoadedIssues) {
issuesLoaded(this, numberOfLoadedIssues);
}
public boolean isModelFrozen() {
if (parent != null) {
return parent.isModelFrozen();
}
return false;
}
public void setModelFrozen(boolean frozen) {
if (parent != null) {
parent.setModelFrozen(frozen);
}
}
}
|
package com.chatRobot.service.impl;
import com.chatRobot.dao.BookDao;
import com.chatRobot.dao.MyOrderDao;
import com.chatRobot.model.MyOrder;
import com.chatRobot.model.Record;
import com.chatRobot.service.MyOrderService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.jws.WebService;
import java.util.List;
@Service("myOrderService")
public class MyOrderServiceImpl implements MyOrderService {
@Resource
private MyOrderDao myOrderDao;
@Override
public void insertOrder(MyOrder myOrder) {
this.myOrderDao.insertOrder(myOrder);
}
@Override
public int borrowCount(int user_id) {
return this.myOrderDao.borrowCount(user_id);
}
@Override
public int bookBorrowExists(int user_id, int book_id) {
return this.myOrderDao.bookBorrowExists(user_id,book_id);
}
@Override
public void reBorrow(int order_id) {
this.myOrderDao.reBorrow(order_id);
}
@Override
public int selectOrderState(int order_id) {
return this.myOrderDao.selectOrderState(order_id);
}
@Override
public List<MyOrder> selectAllOrder(int user_id) {
return this.myOrderDao.selectAllOrder(user_id);
}
@Override
public List<MyOrder> selectIncompleteOrder(int user_id) {
return this.myOrderDao.selectIncompleteOrder(user_id);
}
@Override
public List<Record> selectRecord(int user_id,int page,String selectBookName) {
return this.myOrderDao.selectRecord(user_id,page,selectBookName);
}
}
|
package com.lti.Algorithms;
import java.util.HashMap;
import java.util.Map;
/**
* Created by busis on 2020-12-10.
*/
public class MultiDigitArraySum {
public static void main(String[] args) {
int[] a={12,34,56,91,45,11,77};
System.out.println(new MultiDigitArraySum().giveMaxMinSumV1(a));
System.out.println(new MultiDigitArraySum().giveMaxMinSumV2(a));
}
public static int giveMaxMinSumV1(int[] a){
/*
* Find the minimum and maximum and find the sum and return that
* in version2, find the frequency of minimum and maximum and multiply with that
* */
int min=10;
int max=-1;
for(int i:a){
int buff=i;
while(buff>0){
int j=buff%10;
buff/=10;
if(j<min)
min=j;
if(j>max)
max=j;
}
}
return max+min;
}
public static int giveMaxMinSumV2(int[] a){
Map<Integer,Integer> map = new HashMap<Integer, Integer>(0);
//We don't need a HashMap also.
//We can count the number of mins in the same loop and add
for(int i=0;i<10;i++)
map.put(i,0);
int min=10;
int max=-1;
for(int i:a){
int buff=i;
while(buff>0){
int j=buff%10;
int val;
val = map.get(j);
map.replace(j,val+1);
buff/=10;
if(j<min)
min=j;
if(j>max)
max=j;
}
}
return max*map.get(max)+min*map.get(min);
}
}
|
/**
*
*/
package com.vinodborole.portal.email.builder;
import java.util.Map;
import com.vinodborole.portal.common.Buildable.Builder;
import com.vinodborole.portal.email.PortalEmail;
import com.vinodborole.portal.email.PortalEmailTemplate;
/**
* @author vinodborole
*
*/
public interface PortalEmailBuilder extends Builder<PortalEmailBuilder, PortalEmail> {
PortalEmailBuilder from(String from);
PortalEmailBuilder to(String to);
PortalEmailBuilder subject(String subject);
PortalEmailBuilder body(String body);
PortalEmailBuilder template(PortalEmailTemplate template);
PortalEmailBuilder templateContent(Map<String, Object> content);
}
|
/*
* Dryuf framework
*
* ----------------------------------------------------------------------------------
*
* Copyright (C) 2000-2015 Zbyněk Vyškovský
*
* ----------------------------------------------------------------------------------
*
* LICENSE:
*
* This file is part of Dryuf
*
* Dryuf is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
*
* Dryuf 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 Lesser General Public License for
* more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Dryuf; if not, write to the Free Software Foundation, Inc., 51
* Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* @author 2000-2015 Zbyněk Vyškovský
* @link mailto:kvr@matfyz.cz
* @link http://kvr.matfyz.cz/software/java/dryuf/
* @link http://github.com/dryuf/
* @license http://www.gnu.org/licenses/lgpl.txt GNU Lesser General Public License v3
*/
package net.dryuf.comp.forum.mvp;
import java.util.LinkedList;
import java.util.List;
import net.dryuf.core.Dryuf;
import net.dryuf.text.markdown.MarkdownService;
import org.apache.commons.lang3.StringUtils;
import net.dryuf.comp.forum.ForumHandler;
import net.dryuf.comp.forum.ForumRecord;
import net.dryuf.comp.forum.bo.ForumBo;
import net.dryuf.core.EntityHolder;
import net.dryuf.core.Options;
import net.dryuf.time.util.DateTimeUtil;
import net.dryuf.mvp.Presenter;
import net.dryuf.srvui.Response;
import net.dryuf.xml.util.XmlFormat;
public class GuestbookPresenter extends net.dryuf.mvp.ChildPresenter
{
public GuestbookPresenter(Presenter parentPresenter, Options options)
{
super(parentPresenter, options);
String refBase = options.getOptionDefault("refBase", Dryuf.dotClassname(GuestbookFormPresenter.class));
String refKey = (String) options.getOptionMandatory("refKey");
forumBo = getCallerContext().getBeanTyped("forumBo", net.dryuf.comp.forum.bo.ForumBo.class);
forumHandler = forumBo.openCreateForumRef(this.getCallerContext(), refBase, refKey, "");
cssClass = Dryuf.dashClassname(options.getOptionDefault("cssClass", Dryuf.dotClassname(GuestbookPresenter.class)));
}
@Override
public Presenter init()
{
super.init();
if (markdownService == null)
markdownService = getCallerContext().getBeanTyped("markdownService", MarkdownService.class);
form = Presenter.createSubPresenter(GuestbookFormPresenter.class, this, Options.NONE);
return this;
}
public void prepare()
{
Response response = getRootPresenter().getResponse();
response.setDateHeader("Expires", System.currentTimeMillis());
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache, must revalidate");
super.prepare();
}
public void render()
{
super.render();
outputFormat("<div class='%s'>\n", cssClass);
List<EntityHolder<ForumRecord>> comments = new LinkedList<EntityHolder<ForumRecord>>();
forumHandler.listComments(comments, 0, null);
for (EntityHolder<ForumRecord> recordHolder: comments) {
ForumRecord record = recordHolder.getEntity();
outputFormat("<hr class='separator' />\n<div class=\"header\">");
if (!StringUtils.isEmpty(record.getEmail()))
outputFormat("<a class='email' href=\"mailto:%S\"><span class='name'>%S</span></a>", record.getEmail(), record.getName());
else
outputFormat("<span class='name'>%S</span>", StringUtils.defaultString(record.getName(), ""));
if (!StringUtils.isEmpty(record.getWebpage()))
outputFormat(" (<a class='webpage' href=\"http://%S\">%S</a>)", record.getWebpage(), record.getWebpage());
outputFormat(" - <span class='added'>%S</span></div>\n", DateTimeUtil.formatLocalReadable(Long.valueOf(record.getCreated())));
outputFormat("<div class='content'>%s</div>\n", markdownService.convertToXhtml(record.getContent()));
}
output("</div>\n");
}
protected ForumHandler forumHandler;
public ForumHandler getForumHandler()
{
return this.forumHandler;
}
protected MarkdownService markdownService;
public void setMarkdownService(MarkdownService markdownService_)
{
this.markdownService = markdownService_;
}
protected ForumBo forumBo;
protected String cssClass;
protected GuestbookFormPresenter form;
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Facil;
/*import Geral.imagens */
import javax.swing.ImageIcon;
/**
*
* @author Ellen
*/
public class SombrasF extends javax.swing.JFrame {
/**
* Creates new form sombras
*/
public SombrasF() {
initComponents();
this.setSize(550, 500);
//Para quando executar o jogo, a resposta correta nao apareça, e fique só o label com a sombra visivel
jLabel2.setVisible(false);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
setTitle("TIMB");
setBackground(new java.awt.Color(51, 255, 255));
setResizable(false);
getContentPane().setLayout(null);
jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/patopequeno.png"))); // NOI18N
jButton1.setContentAreaFilled(false);
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
getContentPane().add(jButton1);
jButton1.setBounds(380, 80, 161, 137);
jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/ha.png"))); // NOI18N
jButton2.setBorderPainted(false);
jButton2.setContentAreaFilled(false);
getContentPane().add(jButton2);
jButton2.setBounds(180, 80, 161, 137);
jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/fa.png"))); // NOI18N
jButton3.setBorderPainted(false);
jButton3.setContentAreaFilled(false);
getContentPane().add(jButton3);
jButton3.setBounds(0, 80, 161, 137);
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/sombra.png"))); // NOI18N
getContentPane().add(jLabel1);
jLabel1.setBounds(130, 230, 260, 240);
jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/parogrande.png"))); // NOI18N
getContentPane().add(jLabel2);
jLabel2.setBounds(130, 230, 260, 240);
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Gimagens/gif claro.gif"))); // NOI18N
getContentPane().add(jLabel3);
jLabel3.setBounds(0, 0, 550, 500);
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
setBounds((screenSize.width-566)/2, (screenSize.height-538)/2, 566, 538);
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
//Quando o botao com a resposta certa foi acionado, o label que contem a sombra irá sumir (false)
jLabel1.setVisible(false);
// e o com a resposta aparecer (true)
jLabel2.setVisible(true);
//cria um objeto do tipo do Jframe que irá aparecer, no caso a tela Acerto. entao variavel ac do tipo acerto
/*acerto ac = new acerto();*/
//quando a resposta certa for acionada, alem de aparecer o label2 , ira aparecer a tela acerto (true)
/*ac.setVisible(true);*/
}//GEN-LAST:event_jButton1ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(SombrasF.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(SombrasF.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(SombrasF.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(SombrasF.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new SombrasF().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
// End of variables declaration//GEN-END:variables
}
|
package com.alibaba.druid.bvt.pool;
import java.sql.Statement;
import junit.framework.TestCase;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
/**
* 这个场景测试initialSize > maxActive
*
* @author wenshao [szujobs@hotmail.com]
*/
public class DruidDataSourceTest_recycle extends TestCase {
private DruidDataSource dataSource;
protected void setUp() throws Exception {
dataSource = new DruidDataSource();
dataSource.setUrl("jdbc:mock:xxx");
dataSource.setTestOnBorrow(false);
dataSource.setMaxActive(1);
}
protected void tearDown() throws Exception {
dataSource.close();
}
public void test_recycle() throws Exception {
DruidPooledConnection conn = dataSource.getConnection();
conn.setAutoCommit(false);
conn.setReadOnly(false);
Statement stmt = conn.createStatement();
stmt.execute("select 1");
conn.close();
}
}
|
public class MobileZero {
public void moveZero(int[] nums){
int count = 0; //记录非0出现的次数,确定补0下标
for (int i = 0;i<nums.length;i++){
if (nums[i]!=0){
nums[count] = nums[i]; //将非0的位置与0的位置交换
count++; //相应的非0 数出现次数+1,出现0 的下标后移
}
}
for (int j = count;j<nums.length;j++){
nums[j] = 0; //在非0位置后补充0;count为记录下标
}
}
}
|
package org.jbpm.process.workitem.parser;
import static org.junit.Assert.assertEquals;
import java.util.Map;
import org.drools.core.process.instance.impl.WorkItemImpl;
import org.junit.Before;
import org.junit.Test;
import org.kie.api.runtime.process.WorkItem;
import org.kie.api.runtime.process.WorkItemHandler;
import org.kie.api.runtime.process.WorkItemManager;
public class ParserTest {
final int AGE = 27;
final String NAME = "William";
final String PERSON_XML = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><person><age>"
+ AGE + "</age><name>" + NAME + "</name></person>";
final String PERSON_JSON = "{\"name\":\"" + NAME + "\",\"age\":" + AGE
+ "}";
Parser handler;
@Before
public void init() {
handler = new Parser();
}
@Test
public void testXmlToObject() {
WorkItemImpl workItem = new WorkItemImpl();
workItem.setParameter(Parser.INPUT, PERSON_XML);
workItem.setParameter(Parser.FORMAT, Parser.XML);
workItem.setParameter(Parser.TYPE,
"org.jbpm.process.workitem.parser.Person");
handler.executeWorkItem(workItem, new TestWorkItemManager(workItem));
Person result = (Person) workItem.getResult(Parser.RESULT);
assertEquals(AGE, result.getAge());
assertEquals(NAME, result.getName());
}
@Test
public void testObjectToXml() {
Person p = new Person(NAME, AGE);
WorkItemImpl workItem = new WorkItemImpl();
workItem.setParameter(Parser.INPUT, p);
workItem.setParameter(Parser.FORMAT, Parser.XML);
handler.executeWorkItem(workItem, new TestWorkItemManager(workItem));
String result = (String) workItem.getResult(Parser.RESULT);
assertEquals(PERSON_XML, result);
}
@Test
public void testJsonToObject() {
WorkItemImpl workItem = new WorkItemImpl();
workItem.setParameter(Parser.INPUT, PERSON_JSON);
workItem.setParameter(Parser.FORMAT, Parser.JSON);
workItem.setParameter(Parser.TYPE,
"org.jbpm.process.workitem.parser.Person");
handler.executeWorkItem(workItem, new TestWorkItemManager(workItem));
Person result = (Person) workItem.getResult(Parser.RESULT);
assertEquals(AGE, result.getAge());
assertEquals(NAME, result.getName());
}
public void testObjectToJson() {
Person p = new Person(NAME, AGE);
WorkItemImpl workItem = new WorkItemImpl();
workItem.setParameter(Parser.INPUT, p);
workItem.setParameter(Parser.FORMAT, Parser.JSON);
handler.executeWorkItem(workItem, new TestWorkItemManager(workItem));
String result = (String) workItem.getResult(Parser.RESULT);
assertEquals(PERSON_JSON, result);
}
private class TestWorkItemManager implements WorkItemManager {
private WorkItem workItem;
TestWorkItemManager(WorkItem workItem) {
this.workItem = workItem;
}
public void completeWorkItem(long id, Map<String, Object> results) {
((WorkItemImpl) workItem).setResults(results);
}
public void abortWorkItem(long id) {
}
public void registerWorkItemHandler(String workItemName,
WorkItemHandler handler) {
}
}
}
|
package com.cm.transaction.declarative.xml;
import com.cm.transaction.declarative.xml.beans.DemoService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @autthor Mchi
* @since 2017/11/10
*/
public class XmlConfTransaction {
static {
System.setProperty("hikaricp.configurationFile", "data-access/target/classes/dbconf.properties");
}
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("declarative/applicationContext.xml");
DemoService demo = ctx.getBean(DemoService.class);
demo.get();
}
}
|
package net.music.demo.model;
import javax.persistence.*;
@Entity
@Table(name = "songs")
public class Song {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "artist", nullable = false)
private Artist artist;
@Column(name = "song_name", columnDefinition = "VARCHAR(50)")
private String songName;
@Column(name = "album", columnDefinition = "VARCHAR(50)")
private String album;
@Column(name = "lyrics", columnDefinition = "TEXT")
private String lyrics;
@Column(name = "year", columnDefinition = "INT(4)")
private int year;
public Song() {
}
public Song(String songName, String album, String lyrics, int year) {
this.songName = songName;
this.album = album;
this.lyrics = lyrics;
this.year = year;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Artist getArtist() {
return artist;
}
public void setArtist(Artist artist) {
this.artist = artist;
}
public String getSongName() {
return songName;
}
public void setSongName(String songName) {
this.songName = songName;
}
public String getAlbum() {
return album;
}
public void setAlbum(String album) {
this.album = album;
}
public String getLyrics() {
return lyrics;
}
public void setLyrics(String lyrics) {
this.lyrics = lyrics;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
} |
package oop;
import java.io.Serializable;
public class Kaitserüü extends Varustus {
private int kaitse;
private String nimi;
public Kaitserüü(int kaitse, String nimi) {
this.kaitse = kaitse;
this.nimi = nimi;
}
public int getKaitse() {
return kaitse;
}
@Override
public String toString() {
return "[Kaitserüü: " + nimi + " kaitsetase " + kaitse + "]";
}
}
|
/* ------------------------------------------------------------------------------
* 软件名称:BB语音
* 公司名称:乐多科技
* 开发作者:Yongchao.Yang
* 开发时间:2016年3月6日/2016
* All Rights Reserved 2012-2015
* ------------------------------------------------------------------------------
* 注意:本内容均来自乐多科技,仅限内部交流使用,未经过公司许可 禁止转发
* ------------------------------------------------------------------------------
* prj-name:com.ace.web.service
* fileName:TaskTrigger2.java
* -------------------------------------------------------------------------------
*/
package com.rednovo.ace.syn;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.log4j.Logger;
import com.rednovo.ace.robot.EnterEventRobot;
import com.rednovo.ace.robot.NewLiveShowRobot;
import com.rednovo.tools.PPConfiguration;
/**
* @author yongchao.Yang/2016年3月6日
*/
public class TaskTrigger implements ServletContextListener {
private static Logger logger = Logger.getLogger(TaskTrigger.class);
@Override
public void contextDestroyed(ServletContextEvent arg0) {
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
boolean isSynRun = PPConfiguration.getProperties("cfg.properties").getBoolean("data.syn.run");
logger.info("[数据同步开关设置为:" + isSynRun + "]");
if (isSynRun) {
logger.info("[加载用户同步线程]");
UserSynWorker usw = UserSynWorker.getInstance();
usw.start();
logger.info("[加载账户同步线程]");
BalanceSynWorker bsw = BalanceSynWorker.getInstance();
bsw.start();
logger.info("[加载礼物同步线程]");
GiftSynWorker gsw = GiftSynWorker.getInstance();
gsw.start();
logger.info("[加载商品同步线程]");
GoodSynWorker gsw2 = GoodSynWorker.getInstance();
gsw2.start();
logger.info("[加载兑点账户同步线程]");
IncomeSynWorker isw = IncomeSynWorker.getInstance();
isw.start();
logger.info("[加载号池警报线程]");
PIDAlarmWorker paw = PIDAlarmWorker.getInstance();
paw.start();
logger.info("[加载直播数据同步线程]");
NewShowSynWorker lss = NewShowSynWorker.getInstance();
lss.start();
logger.info("[加载排序更新线程]");
ShowSortUpdater ssu = ShowSortUpdater.getInstance();
ssu.start();
logger.info("[加载粉丝同步线程]");
FansSynWorker fsw = FansSynWorker.getInstance();
fsw.start();
logger.info("[加载订阅同步线程]");
SubscribeSynWorker ssw = SubscribeSynWorker.getInstance();
ssw.start();
logger.info("[加载系统参数同步线程]");
SysConfigSynWorker ccyw = SysConfigSynWorker.getInstance();
ccyw.start();
// logger.info("[加载僵尸数据回收线程]");
// GlobalCacheCleaner.getInstance().start();
logger.info("[加载AD同步线程]");
AdSynWorker adw = AdSynWorker.getInstance();
adw.start();
logger.info("[加载禁言清理线程]");
ForbiddenUserCleaner fuc = ForbiddenUserCleaner.getInstance();
fuc.start();
logger.info("[加载用户设备同步线程]");
UserDeviceSynWorker upsw = UserDeviceSynWorker.getInstance();
upsw.start();
logger.info("[加载开播推送线程]");
LiveShowPushService lsps = LiveShowPushService.getInstance();
lsps.start();
}
boolean isRobotRun = PPConfiguration.getProperties("cfg.properties").getBoolean("robot.run");
logger.info("[机器人开关设置为:" + isRobotRun + "]");
if (isRobotRun) {
logger.info("[加载进出房间机器人]");
new EnterEventRobot("").start();
// logger.info("[加载点赞机器人]");
// new SupportRobot("").start();
// logger.info("[加载广播消息机器人]");
// new SystemMessageRobot("").start();
}
}
}
|
package com.mmall.service.impl;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.mmall.common.ServerResponse;
import com.mmall.dao.CategoryMapper;
import com.mmall.pojo.Category;
import com.mmall.service.CategoryService;
/**
*
* 项目名称:mmall
* 类名称:CategoryServiceImpl
* 类描述:
* 创建人:xuzijia
* 创建时间:2017年10月13日 上午9:54:14
* 修改人:xuzijia
* 修改时间:2017年10月13日 上午9:54:14
* 修改备注:
* @version 1.0
*
*/
@Service("categoryService")
public class CategoryServiceImpl implements CategoryService {
@Autowired
private CategoryMapper categoryMapper;
/**
*
* @Title: addCategory
* @Description: 添加分类
* @param: @param categoryName
* @param: @param parentId
* @param: @return
* @return: ServerResponse
* @author: xuzijia
* @date: 2017年10月13日 上午10:06:38
* @throws
*/
public ServerResponse<String> addCategory(String categoryName,
Integer parentId) {
if (StringUtils.isBlank(categoryName)) {
return ServerResponse.createByErrorMessage("请输入分类名称");
}
// 校验该父节点下的是否存在一样的分类名称
int i = categoryMapper.checkCategoryName(parentId, categoryName);
if (i > 0) {
return ServerResponse.createByErrorMessage("该分类名称已存在");
}
// 校验是否存在该上级节点 排除根节点
if (parentId != 0) {
int checkParentId = categoryMapper.checkParentId(parentId);
if (checkParentId == 0) {
return ServerResponse.createByErrorMessage("上级分类不存在");
}
}
Category category = new Category();
category.setName(categoryName);
category.setParentId(parentId);
category.setStatus(true);
int insert = categoryMapper.insert(category);
if (insert > 0) {
return ServerResponse.createBySuccessMessage("添加分类成功");
}
return ServerResponse.createByErrorMessage("添加分类失败");
}
/**
* 查询父节点下的子分类
*/
public ServerResponse<List<Category>> getCategory(Integer parentId) {
List<Category> list = categoryMapper
.selectCategoryChildrenByParentId(parentId);
if (list.size() == 0) {
return ServerResponse.createBySuccessMessage("该分类暂时没有子分类 或者该分类不存在");
}
return ServerResponse.createBySuccess("查询成功", list);
}
/**
* 修改分类
*/
public ServerResponse<String> updateCategory(Category category) {
if (StringUtils.isBlank(category.getName())
|| category.getParentId() == null) {
return ServerResponse.createByErrorMessage("缺少参数或参数为空");
}
// 校验名称
int i = categoryMapper.checkCategoryNameById(category.getId(),category.getParentId(), category.getName());
if (i > 0) {
return ServerResponse.createByErrorMessage("该分类名称已存在");
}
// 校验是否存在该上级节点 排除根节点
if (category.getParentId() != 0) {
int checkParentId = categoryMapper.checkParentId(category.getParentId() );
if (checkParentId == 0) {
return ServerResponse.createByErrorMessage("上级分类不存在");
}
}
int i2 = categoryMapper.updateByPrimaryKeySelective(category);
if (i2 > 0) {
return ServerResponse.createBySuccessMessage("修改成功");
}
return ServerResponse.createByErrorMessage("修改失败");
}
/**
* 递归查询本节点的id及孩子节点的id
* @param categoryId
* @return
*/
public ServerResponse<List<Integer>> selectCategoryAndChildrenById(Integer categoryId){
Set<Category> categorySet = Sets.newHashSet();
findChildCategory(categorySet,categoryId);
List<Integer> categoryIdList = Lists.newArrayList();
if(categoryId != null){
for(Category categoryItem : categorySet){
categoryIdList.add(categoryItem.getId());
}
}
return ServerResponse.createBySuccess(categoryIdList);
}
//递归算法,算出子节点
private Set<Category> findChildCategory(Set<Category> categorySet ,Integer categoryId){
Category category = categoryMapper.selectByPrimaryKey(categoryId);
if(category != null){
categorySet.add(category);
}
//查找子节点,递归算法一定要有一个退出的条件
List<Category> categoryList = categoryMapper.selectCategoryChildrenByParentId(categoryId);
for(Category categoryItem : categoryList){
findChildCategory(categorySet,categoryItem.getId());
}
return categorySet;
}
}
|
package com.trump.auction.cust.service;
import com.cf.common.utils.ServiceResult;
import com.trump.auction.cust.domain.AccountRechargeRuleDetail;
import java.util.List;
/**
* Author: zhanping
*/
public interface AccountRechargeRuleDetailService {
/**
* 新增规则详情
* @param obj
* @return
*/
ServiceResult addRuleDetail(AccountRechargeRuleDetail obj);
/**
* 根据id查询规则详情
* @param id
* @return
*/
AccountRechargeRuleDetail findRuleDetailById(Integer id);
/**
* 根据id更新规则详情
* @param obj
* @return
*/
ServiceResult updateRuleDetailById(AccountRechargeRuleDetail obj);
/**
* 根据id删除规则详情
* @param id
* @return
*/
ServiceResult deleteRuleDetailById(Integer id);
/**
* 根据规则id查询所有规则详情列表
* @param id
* @return
*/
List<AccountRechargeRuleDetail> findRuleDetailByRuleId(Integer id);
/**
* 根据规则id删除所有规则详情
* @param id
* @return
*/
ServiceResult deleteRuleDetailByRuleId(Integer id);
}
|
package wholesalemarket_LMP;
//Download JAVA Excel API: http://sourceforge.net/projects/jexcelapi/files/jexcelapi/
import java.io.File;
import java.io.IOException;
import javax.swing.JOptionPane;
import jxl.*;
import jxl.read.biff.BiffException;
import wholesalemarket_LMP.simul.WholesaleMarket;
public class ReadExcel {
private String inputFile;
public void setInputFile(String _inputFile) {
this.inputFile = _inputFile;
}
public double[][] read(String _sheetName, int rowSize, int columnSize, boolean _isAgent) throws IOException {
double[][] dataMatrix = new double[rowSize][columnSize];
File inputWorkbook = new File(inputFile);
Workbook w;
int startCell = WholesaleMarket.START_HOUR + 1; // Excel does not start at 0. The hour 0 is the row number 1
int endCell = startCell + WholesaleMarket.HOUR_PER_DAY;
try {
w = Workbook.getWorkbook(inputWorkbook);
//System.out.println("Excel Sheet: "+_sheetName);
// Select the excel sheet
Sheet sheet = w.getSheet(_sheetName);
int index = 0;
for (int i = 0; i < sheet.getRows(); i++) {
for (int j = 0; j < sheet.getColumns(); j++) {
Cell cell = sheet.getCell(j, i);
//System.out.println("Cell: "+i+":"+j);
if (i != 0) {
if (_isAgent) {
if (i >= startCell && i < endCell) { //The start Hour and the End Hour are important
dataMatrix[index][j] = Double.parseDouble(cell.getContents().replace(",", "."));
if (j == sheet.getColumns() - 1) {
index++;
}
}
} else {
dataMatrix[i - 1][j] = Double.parseDouble(cell.getContents().replace(",", "."));
}
}
}
}
} catch (BiffException ex) {
}
//System.out.println("End of: "+_sheetName);
return dataMatrix;
}
public static double[][] readExcelData(String _fileLocation, String _excelSheet, int rowSize, int columnSize, boolean _isAgent) {
ReadExcel excel_file = new ReadExcel();
excel_file.setInputFile(_fileLocation);
double[][] auxMatrix = new double[rowSize][columnSize];
try {
auxMatrix = excel_file.read(_excelSheet, rowSize, columnSize, _isAgent);
} catch (IOException ioEx) {
JOptionPane.showMessageDialog(null, _fileLocation + " not found! (No such file or directory)",
"Error", JOptionPane.ERROR_MESSAGE);
}
return auxMatrix;
}
}
|
package io.ceph.rgw.client.model.notification;
/**
* @author zhuangshuo
* Created by zhuangshuo on 2020/6/4.
*/
public class SubscribeObjectResponse implements SubscribeResponse {
private final ObjectMetadataInfo objectMetadataInfo;
public SubscribeObjectResponse(ObjectMetadataInfo objectMetadataInfo) {
this.objectMetadataInfo = objectMetadataInfo;
}
public ObjectMetadataInfo getObjectMetadataInfo() {
return objectMetadataInfo;
}
@Override
public String toString() {
return "SubscribeObjectResponse{" +
"objectMetadataInfo=" + objectMetadataInfo +
'}';
}
}
|
package com.sapl.retailerorderingmsdpharma.activities;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.GetTokenResult;
import com.google.firebase.iid.FirebaseInstanceId;
import com.sapl.retailerorderingmsdpharma.R;
import com.sapl.retailerorderingmsdpharma.customView.CircularTextView;
import com.sapl.retailerorderingmsdpharma.customView.CustomButtonRegular;
import com.sapl.retailerorderingmsdpharma.customView.CustomEditTextMedium;
import com.sapl.retailerorderingmsdpharma.customView.CustomTextViewMedium;
import com.sapl.retailerorderingmsdpharma.customView.CustomTextViewRegular;
import org.w3c.dom.Text;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ActivityRegisterOne extends AppCompatActivity {
String LOG_TAG = "ActivityRegisterOne ";
CircularTextView txt_lable1, txt_lable2, txt_lable3,txt_no_of_product_taken;
CustomTextViewRegular txt_sign_up_link;
CustomEditTextMedium edt_shop_name, edt_retailer_owner_name, edt_contact_no, edt_ret_email_id;
CustomButtonRegular btn_next;
Context context;
ImageView img_menu,img_cart;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register_one);
context = this;
initComponants();
initComponantListner();
}
public void initComponants() {
img_cart = findViewById(R.id.img_cart);
img_cart.setVisibility(View.GONE);
img_menu = findViewById(R.id.img_menu);
img_menu.setVisibility(View.GONE);
txt_no_of_product_taken = findViewById(R.id.txt_no_of_product_taken);
txt_no_of_product_taken.setVisibility(View.GONE);
CustomTextViewMedium txt_title = findViewById(R.id.txt_title);
txt_title.setText(getResources().getString(R.string.sign_up));
txt_title.setTextColor((Color.parseColor(MyApplication.get_session(MyApplication.SESSION_PRIMARY_TEXT_COLOR))));
CustomTextViewMedium txt_cmpl_userName = findViewById(R.id.txt_cmpl_userName);
txt_cmpl_userName.setTextColor(getResources().getColor(R.color.red));
CustomTextViewMedium txt_cmpl_contact = findViewById(R.id.txt_cmpl_contact);
txt_cmpl_contact.setTextColor(getResources().getColor(R.color.red));
CustomTextViewMedium txt_cmpl_ownerName = findViewById(R.id.txt_cmpl_ownerName);
txt_cmpl_ownerName.setTextColor(getResources().getColor(R.color.red));
CustomTextViewMedium txt_cmpl_mail = findViewById(R.id.txt_cmpl_mail);
txt_cmpl_mail.setTextColor(getResources().getColor(R.color.red));
txt_sign_up_link = findViewById(R.id.txt_sign_up_link);
txt_lable1 = findViewById(R.id.txt_lable1);
txt_lable2 = findViewById(R.id.txt_lable2);
txt_lable3 = findViewById(R.id.txt_lable3);
//txt_lable1.setBackgroundColor(getResources().getColor(R.color.black));
//txt_lable1.setStrokeColor("#808080");
//txt_lable1.setStrokeColor(MyApplication.get_session(MyApplication.SESSION_HEADING_BACKGROUND_COLOR));
txt_lable1.setStrokeColor("#006e6e");
txt_lable1.setTextColor(getResources().getColor(R.color.white));
txt_lable2.setStrokeColor("#C0C0C0");
txt_lable2.setTextColor(getResources().getColor(R.color.white));
txt_lable3.setStrokeColor("#C0C0C0");
txt_lable3.setTextColor(getResources().getColor(R.color.white));
edt_shop_name = findViewById(R.id.edt_shop_name);
edt_contact_no = findViewById(R.id.edt_contact_no);
edt_ret_email_id = findViewById(R.id.edt_ret_email_id);
edt_retailer_owner_name = findViewById(R.id.edt_retailer_owner_name);
btn_next = findViewById(R.id.btn_next);
String firebaseToken = FirebaseInstanceId.getInstance().getToken();
//Toast.makeText(getApplicationContext(),"1St\n "+firebaseToken, Toast.LENGTH_LONG).show();
if(TextUtils.isEmpty(firebaseToken)) {
MyApplication.d(LOG_TAG+ "FCMTOKEN: "+firebaseToken);
//MyApplication.set_session(MyApplication.SESSION_FCM_TOKEN, firebaseToken);
//MyApplication.e(LOG_TAG+ "FCMTOKEN: "+MyApplication.get_session(MyApplication.SESSION_FCM_TOKEN));
}
/* if(!TextUtils.isEmpty(MyApplication.get_session(MyApplication.SESSION_SHOP_NAME))){
edt_shop_name.setText(MyApplication.get_session(MyApplication.SESSION_SHOP_NAME));
}
if(!TextUtils.isEmpty(MyApplication.get_session(MyApplication.SESSION_RETAILER_OWNER_NAME))){
edt_retailer_owner_name.setText(MyApplication.get_session(MyApplication.SESSION_RETAILER_OWNER_NAME));
}
if(!TextUtils.isEmpty(MyApplication.get_session(MyApplication.SESSION_CONTACT_NO))){
edt_contact_no.setText(MyApplication.get_session(MyApplication.SESSION_CONTACT_NO));
}
if(!TextUtils.isEmpty(MyApplication.get_session(MyApplication.SESSION_MAIL_ID))){
edt_ret_email_id.setText(MyApplication.get_session(MyApplication.SESSION_MAIL_ID));
}*/
}
public void initComponantListner() {
btn_next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String contactNo = edt_contact_no.getText() + "".trim();
String userName = edt_shop_name.getText() + "".trim();
String ownerName = edt_retailer_owner_name.getText() + "".trim();
String mailId = edt_ret_email_id.getText().toString().trim();
if(TextUtils.isEmpty(mailId)){
edt_ret_email_id.setError("Enter mail address.");
//MyApplication.displayMessage(context, "Enter mail address.");
return;
}
if (TextUtils.isEmpty(ownerName)) {
edt_retailer_owner_name.setError("Enter owner name");
return;
}
if (TextUtils.isEmpty(userName)) {
edt_shop_name.setError("Enter shop name");
return;
}
if(isEmailValid(mailId)) {
if (!TextUtils.isEmpty(contactNo) && contactNo.length() == 10) {
MyApplication.set_session(MyApplication.SESSION_SHOP_NAME, userName);
MyApplication.set_session(MyApplication.SESSION_RETAILER_OWNER_NAME, ownerName);
MyApplication.set_session(MyApplication.SESSION_CONTACT_NO, contactNo);
MyApplication.set_session(MyApplication.SESSION_MAIL_ID, mailId);
Intent i = new Intent(getApplicationContext(), ActivityRegisterTwo.class);
// finish();
overridePendingTransition(R.anim.fade_in_call, R.anim.fade_out_call);
startActivity(i);
} else
edt_contact_no.setError("Please enter valid number");
}
else
MyApplication.displayMessage(context, "Please enter valid mail address");
}
});
txt_sign_up_link.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), ActivityLogin.class);
finish();
overridePendingTransition(R.anim.fade_in_call, R.anim.fade_out_call);
startActivity(i);
}
});
}
@Override
public void onBackPressed() {
Intent i = new Intent(getApplicationContext(), ActivityLogin.class);
// finish();
overridePendingTransition(R.anim.fade_in_return, R.anim.fade_out_return);
startActivity(i);
}
public static boolean isEmailValid(String email)
{
/*regular expression*/
String EMAIL_REGEX =
"^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@" +
"(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
final Pattern EMAIL_PATTERN = Pattern.compile(EMAIL_REGEX);
if (email == null)
return false;
Matcher matcher = EMAIL_PATTERN.matcher(email);
return matcher.matches();
}
} |
package com.zantong.mobilecttx.model.repository;
import com.zantong.mobilecttx.BuildConfig;
import retrofit2.Retrofit;
/**
* Created by jianghw on 2017/4/26.
* 构建bases url工厂
*/
public class RetrofitFactory {
public static RetrofitFactory getInstance() {
return SingletonHolder.INSTANCE;
}
private static class SingletonHolder {
private static final RetrofitFactory INSTANCE = new RetrofitFactory();
}
public Retrofit createRetrofit(int type) {
return type == 1 || type == 5 ? DefaultRetrofit.getInstance().createRetrofit(getBaseUrl(type))
: type != 4 ? AnShengRetrofit.getInstance().createRetrofit(getBaseUrl(type))
: DefaultRetrofit.getInstance().createRetrofit(getBaseUrl(type));
}
private String getBaseUrl(int type) {
switch (type) {
case 1://同赞自己服务器
return BuildConfig.CAR_MANGER_URL;
case 2:
return BuildConfig.APP_URL;
case 3:
return BuildConfig.BASE_URL;
case 4://后台开发人员本地调试接口
return "http://192.168.1.127:80/";
case 5://拍照扫描上传接口
return "http://liyingtong.com:8080/";
default:
return "http://192.168.1.147:80/";
}
}
}
|
package dao.partners;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Vector;
import dao.DatabaseGateway;
import dto.partner.PartnerDTO;
import herramientas.herrramientasrs.HerramientasResultSet;
public class PartnerDAO {
private DatabaseGateway database;
private HerramientasResultSet herramientasResultSet;
/**
*
*/
public PartnerDAO(){
if(this.getDatabase() == null){
this.setDatabase(new DatabaseGateway());
}
if(getHerramientasResultSet() == null){
setHerramientasResultSet(new HerramientasResultSet());
}
}
public Vector<PartnerDTO> selectPartnersPorTipo(int tipoPartner){
Vector<PartnerDTO> partners = null;
if(getDatabase().openDatabase()){
partners = new Vector<PartnerDTO>();
ResultSet rs = null;
String query = "SELECT * FROM tb_partners WHERE fk_id_tipo_partner = " + tipoPartner;
try {
rs = getDatabase().executeQuery(query);
} catch (SQLException e1) {
e1.printStackTrace();
}
if(rs != null){
try {
while (rs.next()) {
PartnerDTO partner = new PartnerDTO();
partner = getHerramientasResultSet().inicializaPartnerSimple(rs);
partners.add(partner);
}
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}else{
System.out.println("rs == nullo");
}
if(getDatabase().closeDatabase()){
System.out.println("conexion cerrada en " + this.getClass().getSimpleName());
}else{
System.out.println("conexion no cerrada en " + this.getClass().getSimpleName());
}
}else{
System.out.println("conexion no abierta en " + this.getClass().getSimpleName());
}
return partners;
}
/**
* @return the herramientasResultSet
*/
public HerramientasResultSet getHerramientasResultSet() {
return herramientasResultSet;
}
/**
* @param herramientasResultSet the herramientasResultSet to set
*/
public void setHerramientasResultSet(HerramientasResultSet herramientasResultSet) {
this.herramientasResultSet = herramientasResultSet;
}
/**
* @return the database
*/
public DatabaseGateway getDatabase() {
return database;
}
/**
* @param database the database to set
*/
public void setDatabase(DatabaseGateway database) {
this.database = database;
}
}
|
package by.orion.onlinertasks.data.models.profile;
import com.google.auto.value.AutoValue;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.SerializedName;
import java.util.List;
import by.orion.onlinertasks.data.models.common.Page;
@AutoValue
public abstract class ProfilesPage {
@SerializedName("profiles")
public abstract List<Profile> profiles();
@SerializedName("total")
public abstract Integer total();
@SerializedName("page")
public abstract Page page();
public static TypeAdapter<ProfilesPage> typeAdapter(Gson gson) {
return new AutoValue_ProfilesPage.GsonTypeAdapter(gson);
}
}
|
package com.melodygram.chatinterface;
/**
* Created by FuGenX-01 on 15-09-2016.
*/
public interface InterFaceBadgeCount {
void badgeCountResponse(String isCount);
}
|
package com.feedback.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="feedback")
public class Store_Feedback {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name="feedback")
private String feedback;
public String getFeedback() {
return feedback;
}
public void setFeedback(String feedback) {
this.feedback = feedback;
}
public Store_Feedback(String feedback) {
this.feedback = feedback;
}
public Store_Feedback() {
}
}
|
package com.zhicai.byteera.activity.product.view;
import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;
import com.zhicai.byteera.R;
import com.zhicai.byteera.activity.product.entity.ProductInfo;
import com.zhicai.byteera.commonutil.ToastUtil;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnTextChanged;
@SuppressWarnings("unused")
public class IncomeCalCulateDialog extends AlertDialog {
@Bind(R.id.et_money_val) EditText etMoneyVal;
@Bind(R.id.tv_limit_val) TextView tvLimitVal;
@Bind(R.id.tv_expect_val) TextView tvExpectVal;
@Bind(R.id.tv_current_val) TextView tvCurrentVal;
@Bind(R.id.tv_yuebao_val) TextView tvYueBao;
@Bind(R.id.tv_deferral_val) TextView tvDeferralVal;
private ProductInfo productInfo;
public IncomeCalCulateDialog(Context context,ProductInfo productInfo) {
super(context);
this.productInfo = productInfo;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.income_calculate_dialog);
ButterKnife.bind(this);
initView();
}
private void initView() {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
tvLimitVal.setText(productInfo.getLimit() + "天");
}
@OnTextChanged(value = R.id.et_money_val,callback=OnTextChanged.Callback.AFTER_TEXT_CHANGED)
void onTextChange(){
String etMoney = etMoneyVal.getText().toString().equals("") ? "0" : etMoneyVal.getText().toString();
Long money = Long.decode(etMoney);
if (etMoney.length()<15) {
tvExpectVal.setText(String.format("%.02f", (money * productInfo.getIncome() * productInfo.getLimit() / 360))+"元");
tvCurrentVal.setText(String.format("%.02f", (money * productInfo.getCurrent_deposit() * productInfo.getLimit() / 360))+"元");
tvYueBao.setText(String.format("%.02f", (money * productInfo.getYuebao() * productInfo.getLimit() / 360))+"元");
tvDeferralVal.setText(String.format("%.02f", (money * productInfo.getFixed_deposit() * productInfo.getLimit() / 360))+"元");
} else{
ToastUtil.showLongToastText("请输入15位以内数");
etMoneyVal.setText(10000+"");
}
}
@OnClick(R.id.img_back)
void onClick(){dismiss();}
}
|
package codigoalvo.entity;
import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.ForeignKey;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.validation.constraints.NotNull;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotBlank;
@Entity
public class Categoria implements Serializable {
private static final long serialVersionUID = -4407612096913713967L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@NotNull
@NotBlank
@Length(max = 100)
private String nome;
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(foreignKey = @ForeignKey(name="fk_categoria_usuario"))
@OnDelete(action=OnDeleteAction.CASCADE)
private Usuario usuario;
public Categoria() {
}
public Categoria(String nome) {
this();
this.nome = nome;
}
@Override
public String toString() {
return this.nome;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.id == null) ? 0 : this.id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Categoria other = (Categoria) obj;
if (this.id == null) {
if (other.id != null)
return false;
} else if (!this.id.equals(other.id))
return false;
return true;
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNome() {
return this.nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Usuario getUsuario() {
return this.usuario;
}
public void setUsuario(
Usuario usuario) {
this.usuario = usuario;
}
}
|
/*
* This code is released under the terms and conditions of the Common Public License Version 1.0.
* You should have received a copy of the license with the code, if you didn't
* you can get it at the quantity project homepage or at
* <a href="http://www.opensource.org/licenses/cpl.php">http://www.opensource.org/licenses/cpl.php</a>
*/
package com.schneide.quantity;
import java.util.*;
import com.schneide.quantity.unit.*;
/**
*The <code>CompoundUnit</code> manages the different {@link com.schneide.quantity.unit.Unit}.
*Every {@link com.schneide.quantity.unit.AtomarSignature} is unique. To learn more about
*the use of <code>CompoundUnits</code> see "HowTo" on
*<a href="http://www.Softwareschneiderei.de/quantity.html">Homepage</a>
*
* @author <a href="mailto:matthias.kempka@softwareschneiderei.de">Matthias Kempka</a>,
* <a href="mailto:anja.hauth@softwareschneiderei.de">Anja Hauth</a>
*/
public class CompoundUnit implements Cloneable {
private static String SERIALIZING_DELIMITER = ":";
/**
* The signature the compound compoundUnit carries is a
* map containing AtomarSignature objects as key and
* Unit objects as value.
*/
protected Map signature = null;
protected String unitName = null;
/**
* Constructor for CompoundUnit.
*/
public CompoundUnit() {
super();
signature = new HashMap();
AtomarSignature key = new DimensionlessSignature();
Unit value = new DimensionlessUnit();
signature.put(key, value);
}
/**
* Constructor CompoundUnit.
* @param recreationableString
*/
public CompoundUnit(String recreationableString) {
super();
signature = new HashMap();
StringTokenizer tokenizer = new StringTokenizer(recreationableString, SERIALIZING_DELIMITER);
this.unitName = tokenizer.nextToken();
if (this.unitName.equals("null")) {
this.unitName = null;
}
while (tokenizer.hasMoreTokens()) {
Unit value = new Unit(tokenizer.nextToken());
AtomarSignature key = value.getAtomarSignature();
signature.put(key, value);
}
}
/**
* Puts the compoundUnit to the hashmap containing the
* signature. If an entry of the same atomar signature
* already exists, it is overwritten.
* @param unit
*/
public void extendSignature(Unit unit){
signature.put(unit.getAtomarUnit().getAtomarSignature(), unit);
}
/**
* returns the conversion factor from targetUnit to sourceUnit
* @param target holds the targetUnit
* @param source holds the sourceUnit
* @return ValueTransfer the factor you need to multiply to source
* to get target
*/
private ValueTransfer calculateValueTransfer(Unit target, Unit source){
ValueTransfer result = null;
if (target.getAtomarSignature().equals(source.getAtomarSignature())) {
if (target.getExponent() == source.getExponent()) {
ConversionFactor conversionFactor = calculateConversionFactor(
target.getAtomarUnit(), source.getAtomarUnit());
double changeValue = conversionFactor.getValue();
int changePower = conversionFactor.getPower()
- target.getScaleExponent()
+ source.getScaleExponent();
result = new ValueTransfer(changeValue, changePower);
result.toPower(source.getExponent());
} else {
throw new WrongUnitException("target und source needs same exponent");
}
} else {
throw new WrongUnitException("target und source needs same signature");
}
return result;
}
/**
* Method calculateConversionFactor calculate the factor to get target
* from source
* @param targetUnit
* @param sourceUnit
* @return ConversionFactor the factor you need to multiply to source
* to get target
*/
private ConversionFactor calculateConversionFactor(
AtomarUnit targetUnit,
AtomarUnit sourceUnit) {
ConversionFactor result = sourceUnit.getConversionFactorToReferenceUnit();
result.multiply(targetUnit.getConversionFactorToReferenceUnit().invert());
return result;
}
/**
* Method multiply.
* @param compoundUnit
*/
public ValueTransfer multiply(CompoundUnit compoundUnit) {
ValueTransfer result = new ValueTransfer();
for (Iterator iter = compoundUnit.signature.keySet().iterator(); iter.hasNext();) {
AtomarSignature element = (AtomarSignature) iter.next();
Unit currentUnit = (Unit) this.signature.get(element);
if (currentUnit == null) {
this.extendSignature((Unit)compoundUnit.signature.get(element));
} else {
/* speaking mathematically:
* transferUnit = (10^b * unit1)^k
* sourceUnit = (10^a * unit2)^n = (10^b * c * 10^d * unit1)^n
*
* transferUnit * sourceUnit
* = (10^b * unit1)^k * (10^b * unit1 * c * 10^d)^n
* = (c * 10^d)^n * (10^b * unit1)^(n+k)
*
* where unitValueTransfer = (c * 10^d)^(n)
*/
Unit sourceUnit = (Unit)compoundUnit.signature.get(element);
Unit transferUnit = new Unit(currentUnit.getAtomarUnit(),
sourceUnit.getExponent(),
currentUnit.getScaleExponent());
int exponent = currentUnit.getExponent() + sourceUnit.getExponent();
ValueTransfer unitValueTransfer = calculateValueTransfer(transferUnit, sourceUnit);
result.multiply(unitValueTransfer);
currentUnit.setExponent(exponent);
}
}
return result;
}
// /**
// * Method multiplySignature.
// * @param compoundUnit
// */
// private void multiplySignature(Unit unit) {
// }
/**
* Returns the unitName.
* @return String
*/
public String getUnitName() {
return unitName;
}
/**
* Sets the unitName.
* @param unitName The unitName to set
*/
public void setUnitName(String unitName) {
this.unitName = unitName;
}
/**
* inverts this CompoundUnit
*/
void invert() {
for (Iterator iter = this.signature.keySet().iterator(); iter.hasNext();) {
AtomarSignature element = (AtomarSignature) iter.next();
((Unit) this.signature.get(element)).invert();
}
}
/**
* @see java.lang.Object#clone()
*/
public Object clone() {
CompoundUnit result = new CompoundUnit();
for (Iterator iter = this.signature.keySet().iterator(); iter.hasNext();) {
AtomarSignature element = (AtomarSignature) iter.next();
Unit elementUnit = (Unit) this.signature.get(element);
result.signature.put(element.clone(), elementUnit.clone());
}
result.unitName = this.unitName;
return result;
}
/**
* The method isSameUnitAs() checks if the signature of targetUnit
* is identical with the signature of this CompoundUnit.
* @param targetUnit
* @return boolean
*/
public boolean isSameUnitAs(CompoundUnit targetUnit) {
return isSignatureSetEqual(targetUnit, true);
}
/**
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object obj) {
boolean result = false;
try {
CompoundUnit object = (CompoundUnit) obj;
if (this.signature.equals(object.signature)
&& ((this.unitName != null && this.unitName.equals(object.unitName))
|| (this.unitName == null && object.unitName == null))) {
result = true;
}
} catch(ClassCastException e) {
result = false;
}
return result;
}
/**
* Returns the signature.
* @return Map
*/
public Map getSignature() {
return signature;
}
/**
* Method transformTo transforms the signature of this CompoundUnit to the
* signature of targetCompoundUnit and returns the conversion factor that is
* to be multiplied to the value of this Quantity. The signature maps must
* contain the same AtomarSignatures.
*
* @param targetCompoundUnit
* @return ValueTransfer
*/
ValueTransfer transformTo(CompoundUnit targetCompoundUnit) {
ValueTransfer result = new ValueTransfer();
for (Iterator iter = this.signature.keySet().iterator(); iter.hasNext();) {
AtomarSignature element = (AtomarSignature) iter.next();
Unit elementUnit = (Unit) this.signature.get(element);
Unit targetUnit = (Unit) targetCompoundUnit.signature.get(element);
ValueTransfer unitValueTransfer = calculateValueTransfer(targetUnit, elementUnit);
result.multiply(unitValueTransfer);
}
return result;
}
public boolean hasEqualAtomarSignatureSet(CompoundUnit compareUnit) {
return isSignatureSetEqual(compareUnit, false);
}
/**
* Method isSignatureSetEqual.
* @param compareUnit
* @param b
* @return boolean
*/
private boolean isSignatureSetEqual(CompoundUnit compareUnit, boolean withValue) {
boolean result = true;
Set ownKeySet = this.signature.keySet();
Set compareKeySet = compareUnit.signature.keySet();
if (ownKeySet.size() == compareKeySet.size()) {
for (Iterator iterator = ownKeySet.iterator(); iterator.hasNext();) {
AtomarSignature key = (AtomarSignature) iterator.next();
if (!compareKeySet.contains(key)) {
result = false;
} else if (withValue){
Unit thisValue = (Unit) this.signature.get(key);
Unit compareValue = (Unit) compareUnit.signature.get(key);
if (!thisValue.equals(compareValue)) {
result = false;
}
}
}
} else {
result = false;
}
return result;
}
/**
* @see java.lang.Object#toString()
*/
public String toString() {
String result = null;
// this.unitName = null;
if (this.unitName != null) {
result = this.unitName;
} else {
Unit dimensionlessUnit = (Unit) (this.signature.get(new DimensionlessSignature()));
String up = ScaleUnit.getScaleUnitString(dimensionlessUnit.getScaleExponent());
for (Iterator iter = signature.values().iterator(); iter.hasNext();) {
Unit element = (Unit) iter.next();
if (element.getExponent() > 0 && !element.equals(dimensionlessUnit)) {
String elementName = ScaleUnit.getScaleUnitString(element.getScaleExponent())
+ element.getAtomarUnit().getUnitAbbreviation();
if (up.equals("")) {
up = elementName;
} else {
up = up + "*" + elementName;
}
if (element.getExponent() > 1) {
up = up + "^" + element.getExponent();
}
}
}
String down = "";
for (Iterator iter = signature.values().iterator(); iter.hasNext();) {
Unit element = (Unit) iter.next();
if (element.getExponent() < 0) {
String elementName = ScaleUnit.getScaleUnitString(element.getScaleExponent())
+ element.getAtomarUnit().getUnitAbbreviation();
if (down.equals("")) {
down = elementName;
} else {
down = down + "*" + elementName;
}
if (element.getExponent() < -1) {
down = down + "^" + (-1)*element.getExponent();
}
}
}
if (down.equals("")) {
result = up;
} else {
if (up.equals("")) {
up = "1";
}
result = up + "/" + down;
}
}
return result;
}
/**
* Method toRecreationableString.
* @return String returns a string of kind: <Unit.toRecreationableString>:
* <Unit.toRecreationableString>:...
*/
public String toRecreationableString() {
String result = new String();
result += this.unitName;
result += SERIALIZING_DELIMITER;
for (Iterator iter = this.signature.values().iterator(); iter.hasNext();) {
Unit element = (Unit) iter.next();
result += element.toRecreationableString();
result += SERIALIZING_DELIMITER;
}
return result;
}
}
|
package com.ipartek.formacion.javalibro.utilidades;
import junit.framework.TestCase;
public class ValidacionesTest extends TestCase {
public void testEmail() {
assertFalse(Validaciones.email(null));
assertFalse(Validaciones.email(""));
assertFalse(Validaciones.email("auraga.ipartek.com"));
assertFalse(Validaciones.email("auraga.ipartek."));
assertFalse(Validaciones.email("auraga@"));
assertFalse(Validaciones.email("auraga@ipartekcom"));
assertFalse(Validaciones.email("auraga@ipartekcom.e"));
assertTrue(Validaciones.email("auraga@ipartek.com"));
}
/*
public void testEmail() {
assertFalse(Validaciones.email(null));
assertFalse (Validaciones.email(""));
assertFalse (Validaciones.email("leire"));
//assertFalse (Validaciones.email("leire@gm..com"));
assertFalse (Validaciones.email("leire@gmail"));
assertFalse (Validaciones.email("leire@gmail."));
assertFalse (Validaciones.email("@leire"));
assertFalse (Validaciones.email("??"));
assertFalse (Validaciones.email("@.com"));
assertFalse (Validaciones.email(".es"));
assertTrue (Validaciones.email("13leire@gmail.com"));
assertTrue (Validaciones.email("leire6@hotmail.es"));
assertTrue (Validaciones.email("leire88@yahoo.es"));
}
*/
public void testDNI() {
assertFalse(Validaciones.dni(null));
assertFalse(Validaciones.dni(""));
assertFalse(Validaciones.dni("2eee"));
assertFalse(Validaciones.dni("1111111"));
assertFalse(Validaciones.dni("1111111Y"));
assertFalse ("Sin guiones",Validaciones.dni("66778999-F"));
assertFalse ("Sin espacios en blanco",Validaciones.dni("66778999 A"));
assertFalse ("Sin caracteres extraños",Validaciones.dni("34322#133"));
assertFalse (Validaciones.dni("76677899."));
assertFalse (Validaciones.dni("D667L8990"));
assertTrue (Validaciones.dni("77111118H"));
assertTrue (Validaciones.dni("11111118h"));
}
public void testEdad () {
assertTrue (Validaciones.edad(31));
assertFalse (Validaciones.edad(185));
assertFalse (Validaciones.edad(-5));
}
public void testRol(){
assertTrue (Validaciones.rol("X"));
assertFalse (Validaciones.rol("Y"));
}
}
|
/**
* Leetcode做题-猜数字游戏 https://leetcode-cn.com/problems/bulls-and-cows/
*/
public class 猜数字游戏 {
public String getHint(String secret, String guess) {
int bulls=0,cows=0;
int[] nums=new int[10];
for(int i=0;i<secret.length();i++){
if(secret.charAt(i)==guess.charAt(i)){
bulls++;
}else {
if(nums[secret.charAt(i)-'0']++<0){
cows++;
}
if(nums[guess.charAt(i)-'0']-->0){
cows++;
}
}
}
return bulls+"A"+cows+"B";
}
}
|
package nor;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import org.fife.ui.rtextarea.*;
import org.fife.ui.rsyntaxtextarea.*;
/******************************************************************************/
public class ChangeSyntaxStyle {
//El kell tárulnunk azt, hogy az egyes típusoknak, hol van a megfelelő
//xml fájlja.
private static String[][] types = {
{"Eclipse", "/org/fife/ui/rsyntaxtextarea/themes/eclipse.xml"},
{"Default-alt", "/org/fife/ui/rsyntaxtextarea/themes/default-alt.xml"},
{"Default", "/org/fife/ui/rsyntaxtextarea/themes/default.xml"},
{"Dark", "/org/fife/ui/rsyntaxtextarea/themes/dark.xml"},
{"Idea", "/org/fife/ui/rsyntaxtextarea/themes/idea.xml"},
{"Monokai", "/org/fife/ui/rsyntaxtextarea/themes/monokai.xml"},
{"Visual Studio", "/org/fife/ui/rsyntaxtextarea/themes/vs.xml"},
};
/******************************************************************************/
//Ezzel vagyunk képesek megváltoztatni a színezés típusát.
public static void createChangeSyntaxStyle(JMenu jmenu, RSyntaxTextArea rsta) {
//Valahogy jelölni kell, hogy éppen melyik van használatban.
JRadioButtonMenuItem rbm[] = new JRadioButtonMenuItem[types.length];
//Létrehozzuk a szükséges menüelemeket.
ButtonGroup bg = new ButtonGroup();
JMenu tmp = new JMenu("Change Syntax Style");
//Végig iteráljuk a típusokat, hogy minden egyes típus és beállítjuk
//rájuk a listenerket is.
for(int i = 0; i < types.length; i++) {
rbm[i] = new JRadioButtonMenuItem(types[i][0]);
tmp.add(rbm[i]);
bg.add(rbm[i]);
rbm[i].addActionListener(new ChangeSyntaxStyleListener(types[i][1], rsta));
}
//Alapjáraton az első teszi meg kiválasztottnak.
rbm[0].setSelected(true);
jmenu.add(tmp);
}
}
/******************************************************************************/
//Itt valósítjuk meg a listenert.
class ChangeSyntaxStyleListener implements ActionListener {
//Tudnunk kell, hogy milyen típusról van szó és azt, hogy minek kell
//beállítani ezeket.
private String type;
private RSyntaxTextArea rs;
/******************************************************************************/
//Konstruktor.
public ChangeSyntaxStyleListener(String th, RSyntaxTextArea rsta) {
this.rs = rsta;
type = new String(th);
}
/******************************************************************************/
//A figyelő.
public void actionPerformed(ActionEvent ev) {
try {
//Beállítjuk a témát és elfogadtatjuk a kapott komponenssel.
Theme theme = Theme.load(getClass().getResourceAsStream(type));
theme.apply(rs);
} catch (Exception e){
System.out.println(e);
}
}
/******************************************************************************/
}
|
package com.onairm.recordtool4android.utils;
/**
* 常量
*/
public class Constants {
public static final String RECORD_VIDEO_PATH="/sdcard/DRecord/cut4android.mp4";
public static final String CLIP_AFTER_VIDEO_PATH="/sdcard/DRecord/dest.mp4";
public static final int THUMB_COUNT=10;
public static final String BIG_IMG_PATH="/sdcard/DRecord/cover.png";
}
|
package com.example.kimnamgil.testapplication.widget;
import android.content.Context;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.kimnamgil.testapplication.R;
import com.example.kimnamgil.testapplication.data.Drama;
/**
* Created by kimnamgil on 2016. 7. 16..
*/
public class DramaView extends FrameLayout {
public DramaView(Context context) {
super(context);
init();
}
ImageView dramaPhoto;
TextView dramaStory,dramaName;
private void init()
{
inflate(getContext(), R.layout.drama_view, this);
dramaName = (TextView)findViewById(R.id.drama_name);
dramaStory = (TextView)findViewById(R.id.drama_story);
dramaPhoto = (ImageView)findViewById(R.id.drama_photo);
}
Drama drama;
public void setMovie(Drama drama)
{
this.drama = drama;
dramaName.setText(drama.drama_name);
dramaStory.setText(drama.drama_stroy);
dramaPhoto.setImageDrawable(drama.drama_photo);
}
}
|
import java.util.Scanner;
public class Problem3 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
//user enters number
System.out.print("Please enter a number: ");
int number = input.nextInt();
String result = "";
//while the number is greater than 1, divide starting at 2 and increasing
while(number > 1){
for(int i = 2; i <= number; i++){
//check if it's a number
if(number % i == 0){
number = number / i;
result = result + " " + i;
i = number;
}
}
}
//print results
System.out.println(result);
}
}
|
package com.github.fierioziy.particlenativeapi.core.particle.type;
import com.github.fierioziy.particlenativeapi.api.particle.type.ParticleTypeItemMotion;
import com.github.fierioziy.particlenativeapi.api.particle.type.ParticleTypeMotion;
import com.github.fierioziy.particlenativeapi.api.utils.ParticleException;
import org.bukkit.Material;
public class ParticleTypeItemMotionImpl implements ParticleTypeItemMotion {
public ParticleTypeMotion of(Material item) {
throw new ParticleException(
"Requested particle type is not supported by this server version!"
);
}
public boolean isPresent() {
return false;
}
}
|
import org.apache.geronimo.mail.util.Hex;
import org.junit.Assert;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class Week2 {
public static byte[] decrypt(byte[] key, byte[] initVector, byte[] encrypted, String mode) {
try {
IvParameterSpec iv = new IvParameterSpec(initVector);
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance(mode);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, iv);
return cipher.doFinal(encrypted);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
@org.junit.Test
public void test1() throws Exception {
// Arrange
String cbcKeyHex = "140b41b22a29beb4061bda66b6747e14";
byte[] cbcKeyBytes = Hex.decode(cbcKeyHex);
String cbcCipherText1Hex = "28a226d160dad07883d04e008a7897ee2e4b7465d5290d0c0e6c6822236e1daafb94ffe0c5da05d9476be028ad7c1d81";
byte[] cbcCipherText1 = Hex.decode(cbcCipherText1Hex);
String cbcCipherText2Hex = "b4832d0f26e1ab7da33249de7d4afc48e713ac646ace36e872ad5fb8a512428a6e21364b0c374df45503473c5242a253";
byte[] cbcCipherText2 = Hex.decode(cbcCipherText2Hex);
String initVector1Hex = "4ca00ff4c898d61e1edbf1800618fb28";
byte[] initVector1Bytes = Hex.decode(initVector1Hex);
String initVector2Hex = "5b68629feb8606f9a6667670b75b38a5";
byte[] initVector2Bytes = Hex.decode(initVector2Hex);
String cipherMode = "AES/CBC/PKCS5PADDING"; // algorithm/mode/padding
// Act
byte[] decrypted1 = decrypt(cbcKeyBytes, initVector1Bytes, cbcCipherText1, cipherMode);
byte[] decrypted2 = decrypt(cbcKeyBytes, initVector2Bytes, cbcCipherText2, cipherMode);
String decryptedText1 = new String(decrypted1, "UTF-8");
String decryptedText2 = new String(decrypted2, "UTF-8");
// Assert
Assert.assertNotNull(decryptedText1);
Assert.assertNotNull(decryptedText2);
}
@org.junit.Test
public void test2() throws Exception {
// Arrange
String cbcKeyHex = "36f18357be4dbd77f050515c73fcf9f2";
byte[] cbcKeyBytes = Hex.decode(cbcKeyHex);
String cbcCipherText1Hex = "0ec7702330098ce7f7520d1cbbb20fc388d1b0adb5054dbd7370849dbf0b88d393f252e764f1f5f7ad97ef79d59ce29f5f51eeca32eabedd9afa9329";
byte[] cbcCipherText1Bytes = Hex.decode(cbcCipherText1Hex);
String cbcCipherText2Hex = "e46218c0a53cbeca695ae45faa8952aa0e311bde9d4e01726d3184c34451";
byte[] cbcCipherText2Bytes = Hex.decode(cbcCipherText2Hex);
String initVector1Hex = "69dda8455c7dd4254bf353b773304eec";
byte[] initVector1Bytes = Hex.decode(initVector1Hex);
String initVector2Hex = "770b80259ec33beb2561358a9f2dc617";
byte[] initVector2Bytes = Hex.decode(initVector2Hex);
String cipherMode = "AES/CTR/NoPadding"; // algorithm/mode/padding
// Act
byte[] decrypted1 = decrypt(cbcKeyBytes, initVector1Bytes, cbcCipherText1Bytes, cipherMode);
byte[] decrypted2 = decrypt(cbcKeyBytes, initVector2Bytes, cbcCipherText2Bytes, cipherMode);
String decryptedText1 = new String(decrypted1, "UTF-8");
String decryptedText2 = new String(decrypted2, "UTF-8");
// Assert
Assert.assertNotNull(decryptedText1);
Assert.assertNotNull(decryptedText2);
}
} |
package com.karya.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.karya.bean.ItemdtBean;
import com.karya.bean.PRMatReqBean;
import com.karya.bean.PRPurOrdBean;
import com.karya.bean.PRQuotReqBean;
import com.karya.bean.PRSuQuotReqBean;
import com.karya.model.Itemdt001MB;
import com.karya.model.PRMatReq001MB;
import com.karya.model.PRPurOrd001MB;
import com.karya.model.PRQuotReq001MB;
import com.karya.model.PRSuQuotReq001MB;
import com.karya.service.IItemdtService;
import com.karya.service.IPurchaseService;
@Controller
@RequestMapping(value="PurchaseDetails")
public class PurchaseController extends BaseController{
@Resource(name="purchaseService")
private IPurchaseService purchaseService;
@Resource(name="ItemdtService")
private IItemdtService ItemdtService;
private @Value("${PRMatReq.Type}") String[] purchasetype;
private @Value("${PRSupp.Type}") String[] prreqquot;
private @Value("${PRRawmat.List}") String[] prrawmat;
@RequestMapping(value = "/prmatreq", method = RequestMethod.GET)
public ModelAndView prmatreq(@ModelAttribute("command") PRMatReqBean prmatreqBean,
BindingResult result,String mode,String menulink) {
Map<String, Object> model = new HashMap<String, Object>();
if(mode != null) {
if(mode.equals("New")) {
model.put("msg", submitSuccess);
} else if(mode.equals("Old")) {
model.put("msg", updateSuccess);
} else if(mode.equals("Delete")) {
model.put("msg", deleteSuccess);
}
}
model.put("PurchaseType", purchasetype);
model.put("itemlist", prepareListofBean(ItemdtService.listallItems()));
model.put("prMatReqList", prepareprmatreqListofBean(purchaseService.listprmatreq()));
model.put("menulink", menulink);
return new ModelAndView("prmatreq", model);
}
@RequestMapping(value = "/prreqquot", method = RequestMethod.GET)
public ModelAndView prreqquot(@ModelAttribute("command") PRQuotReqBean prquotreqBean,
BindingResult result,String mode) {
Map<String, Object> model = new HashMap<String, Object>();
if(mode != null) {
if(mode.equals("New")) {
model.put("msg", submitSuccess);
} else if(mode.equals("Old")) {
model.put("msg", updateSuccess);
} else if(mode.equals("Delete")) {
model.put("msg", deleteSuccess);
}
}
model.put("PurchaseReqQuot", prreqquot);
model.put("itemlist", prepareListofBean(ItemdtService.listallItems()));
model.put("prQuotReq", prepareprquotreqListofBean(purchaseService.listprquotreq()));
return new ModelAndView("prreqquot", model);
}
@RequestMapping(value = "/prsupplierquot", method = RequestMethod.GET)
public ModelAndView prsupplierquot(@ModelAttribute("command") PRSuQuotReqBean prsuquotreqBean,
BindingResult result,String mode) {
Map<String, Object> model = new HashMap<String, Object>();
if(mode != null) {
if(mode.equals("New")) {
model.put("msg", submitSuccess);
} else if(mode.equals("Old")) {
model.put("msg", updateSuccess);
} else if(mode.equals("Delete")) {
model.put("msg", deleteSuccess);
}
}
model.put("PurchaseType", purchasetype);
model.put("itemlist", prepareListofBean(ItemdtService.listallItems()));
model.put("itemlist", prepareListofBean(ItemdtService.listallItems()));
model.put("PurchaseReqQuot", prreqquot);
model.put("PurchaseType", purchasetype);
model.put("prSuQuotReq", prepareprsuppordListofBean(purchaseService.listprsuquotreq()));
return new ModelAndView("prsupplierquot", model);
}
@RequestMapping(value = "/prpurorder", method = RequestMethod.GET)
public ModelAndView prpurorder(@ModelAttribute("command") PRPurOrdBean prpurordBean,
BindingResult result,String mode) {
Map<String, Object> model = new HashMap<String, Object>();
if(mode != null) {
if(mode.equals("New")) {
model.put("msg", submitSuccess);
} else if(mode.equals("Old")) {
model.put("msg", updateSuccess);
} else if(mode.equals("Delete")) {
model.put("msg", deleteSuccess);
}
}
model.put("PurchaseRawMat", prrawmat);
model.put("itemlist", prepareListofBean(ItemdtService.listallItems()));
model.put("PurchaseReqQuot", prreqquot);
model.put("PurchaseType", purchasetype);
model.put("prPurOrd", prepareprpurorderListofBean(purchaseService.listprpurorder()));
return new ModelAndView("prpurorder", model);
}
@RequestMapping(value = "/deletematreq", method = RequestMethod.GET)
public ModelAndView deletematreq(@ModelAttribute("command") PRMatReqBean prmatreqBean,
BindingResult result,String menulink) {
purchaseService.deleteprmatreq(prmatreqBean.getPmrId());
Map<String, Object> model = new HashMap<String, Object>();
model.put("prMatReqList", prepareprmatreqListofBean(purchaseService.listprmatreq()));
return new ModelAndView("redirect:/PurchaseDetails/prmatreq?menulink="+menulink+"&mode=Delete");
}
@RequestMapping(value = "/deleteprreqquot", method = RequestMethod.GET)
public ModelAndView deleteprreqquot(@ModelAttribute("command") PRQuotReqBean prquotreqBean,
BindingResult result) {
purchaseService.deleteprquotreq(prquotreqBean.getPrqId());
Map<String, Object> model = new HashMap<String, Object>();
model.put("prQuotReq", prepareprquotreqListofBean(purchaseService.listprquotreq()));
return new ModelAndView("redirect:/PurchaseDetails/prreqquot?mode=Delete");
}
@RequestMapping(value = "/deleteprpurorder", method = RequestMethod.GET)
public ModelAndView deleteprpurorder(@ModelAttribute("command") PRPurOrdBean prpurordBean,
BindingResult result) {
purchaseService.deleteprpurorder(prpurordBean.getProId());
Map<String, Object> model = new HashMap<String, Object>();
model.put("prPurOrd", prepareprpurorderListofBean(purchaseService.listprpurorder()));
return new ModelAndView("redirect:/PurchaseDetails/prpurorder?mode=Delete");
}
@RequestMapping(value = "/deleteprsupplierquot", method = RequestMethod.GET)
public ModelAndView deleteprsupplierquot(@ModelAttribute("command") PRSuQuotReqBean prsupquotreqBean,
BindingResult result) {
purchaseService.deleteprsuquotreq(prsupquotreqBean.getPrsrId());
Map<String, Object> model = new HashMap<String, Object>();
model.put("prSuQuotReq", prepareprsuppordListofBean(purchaseService.listprsuquotreq()));
return new ModelAndView("redirect:/PurchaseDetails/prsupplierquot?mode=Delete");
}
@RequestMapping(value = "/editprmatreq", method = RequestMethod.GET)
public ModelAndView editprmatreq(@ModelAttribute("command") PRMatReqBean prmatreqBean,
BindingResult result,String menulink) {
Map<String, Object> model = new HashMap<String, Object>();
model.put("menulink", menulink);
model.put("PrmatreqEdit", prepareprmatreqeditBean(purchaseService.getprmatreq(prmatreqBean.getPmrId())));
model.put("PurchaseType", purchasetype);
model.put("itemlist", prepareListofBean(ItemdtService.listallItems()));
model.put("prMatReqList", prepareprmatreqListofBean(purchaseService.listprmatreq()));
return new ModelAndView("prmatreq", model);
}
@RequestMapping(value = "/editprreqquot", method = RequestMethod.GET)
public ModelAndView editprreqquot(@ModelAttribute("command") PRQuotReqBean prquotreqBean,
BindingResult result) {
Map<String, Object> model = new HashMap<String, Object>();
model.put("PrreqquotEdit", prepareprreqquoteditBean(purchaseService.getprquotreq(prquotreqBean.getPrqId())));
model.put("PurchaseReqQuot", prreqquot);
model.put("itemlist", prepareListofBean(ItemdtService.listallItems()));
model.put("prQuotReq", prepareprquotreqListofBean(purchaseService.listprquotreq()));
return new ModelAndView("prreqquot", model);
}
@RequestMapping(value = "/editprpurorder", method = RequestMethod.GET)
public ModelAndView editprpurorder(@ModelAttribute("command") PRPurOrdBean prpurordBean,
BindingResult result) {
Map<String, Object> model = new HashMap<String, Object>();
model.put("PrpurchordEdit", prepareprpurchordeditBean(purchaseService.getprpurorder(prpurordBean.getProId())));
model.put("PurchaseRawMat", prrawmat);
model.put("PurchaseType", purchasetype);
model.put("itemlist", prepareListofBean(ItemdtService.listallItems()));
model.put("PurchaseReqQuot", prreqquot);
model.put("prPurOrd", prepareprpurorderListofBean(purchaseService.listprpurorder()));
return new ModelAndView("prpurorder", model);
}
@RequestMapping(value = "/editprsupplierquot", method = RequestMethod.GET)
public ModelAndView editprsupplierquot(@ModelAttribute("command") PRSuQuotReqBean prsupquotreqBean,
BindingResult result) {
Map<String, Object> model = new HashMap<String, Object>();
model.put("PrsupquotordEdit", preparepusuppquoteditBean(purchaseService.getprsuquotreq(prsupquotreqBean.getPrsrId())));
model.put("itemlist", prepareListofBean(ItemdtService.listallItems()));
model.put("PurchaseReqQuot", prreqquot);
model.put("PurchaseType", purchasetype);
model.put("prSuQuotReq", prepareprsuppordListofBean(purchaseService.listprsuquotreq()));
return new ModelAndView("prsupplierquot", model);
}
@RequestMapping(value = "/saveprmatreq", method = RequestMethod.POST)
public ModelAndView saveprmatreq(@ModelAttribute("command") @Valid PRMatReqBean prmatreqBean,
BindingResult result,String menulink) {
PRMatReq001MB prmatreq1mb=preparematreqmodel(prmatreqBean);
Map<String, Object> model = new HashMap<String, Object>();
model.put("menulink", menulink);
model.put("PurchaseType", purchasetype);
model.put("itemlist", prepareListofBean(ItemdtService.listallItems()));
model.put("prMatReqList", prepareprmatreqListofBean(purchaseService.listprmatreq()));
if(result.hasErrors()) {
return new ModelAndView("prmatreq", model);
}
purchaseService.addprmatreq(prmatreq1mb);
if(prmatreqBean.getPmrId()== 0){
return new ModelAndView("redirect:/PurchaseDetails/prmatreq?menulink="+menulink+"&mode=New");
} else {
return new ModelAndView("redirect:/PurchaseDetails/prmatreq?menulink="+menulink+"&mode=Old");
}
}
@RequestMapping(value = "/saveprreqquot", method = RequestMethod.POST)
public ModelAndView saveprreqquot(@ModelAttribute("command") @Valid PRQuotReqBean prquotreqBean,
BindingResult result) {
PRQuotReq001MB prquotreq1MB=prepareprreqquotModel(prquotreqBean);
Map<String, Object> model = new HashMap<String, Object>();
model.put("PurchaseReqQuot", prreqquot);
model.put("itemlist", prepareListofBean(ItemdtService.listallItems()));
model.put("prQuotReq", prepareprquotreqListofBean(purchaseService.listprquotreq()));
if(result.hasErrors()){
return new ModelAndView("prreqquot", model);
}
purchaseService.addprquotreq(prquotreq1MB);
if(prquotreqBean.getPrqId()==0){
return new ModelAndView("redirect:/PurchaseDetails/prreqquot?mode=New");
}else
{
return new ModelAndView("redirect:/PurchaseDetails/prreqquot?mode=Old");
}
}
@RequestMapping(value = "/saveprpurorder", method = RequestMethod.POST)
public ModelAndView saveprpurorder(@ModelAttribute("command") @Valid PRPurOrdBean prpurordBean,
BindingResult result) {
PRPurOrd001MB prpurorder1MB=prepareprreqquotModel(prpurordBean);
Map<String, Object> model = new HashMap<String, Object>();
model.put("PurchaseRawMat", prrawmat);
model.put("itemlist", prepareListofBean(ItemdtService.listallItems()));
model.put("PurchaseReqQuot", prreqquot);
model.put("PurchaseType", purchasetype);
model.put("prPurOrd", prepareprpurorderListofBean(purchaseService.listprpurorder()));
if(result.hasErrors()){
return new ModelAndView("prpurorder", model);
}
purchaseService.addprpurorder(prpurorder1MB);
if(prpurordBean.getProId()==0){
return new ModelAndView("redirect:/PurchaseDetails/prpurorder?mode=New");
}else
{
return new ModelAndView("redirect:/PurchaseDetails/prpurorder?mode=Old");
}
}
@RequestMapping(value = "/saveprsupplierquot", method = RequestMethod.POST)
public ModelAndView saveprsupplierquot(@ModelAttribute("command") @Valid PRSuQuotReqBean prsupquotreqBean,
BindingResult result) {
PRSuQuotReq001MB prsuquotreq1MB=prepareprsupquotModel(prsupquotreqBean);
Map<String, Object> model = new HashMap<String, Object>();
/*model.put("PurchaseRawMat", prrawmat);
*/model.put("itemlist", prepareListofBean(ItemdtService.listallItems()));
model.put("PurchaseReqQuot", prreqquot);
model.put("PurchaseType", purchasetype);
model.put("prSuQuotReq", prepareprsuppordListofBean(purchaseService.listprsuquotreq()));
if(result.hasErrors()){
return new ModelAndView("prsupplierquot", model);
}
purchaseService.addprsuquotreq(prsuquotreq1MB);
if(prsupquotreqBean.getPrsrId()==0){
return new ModelAndView("redirect:/PurchaseDetails/prsupplierquot?mode=New");
}else
{
return new ModelAndView("redirect:/PurchaseDetails/prsupplierquot?mode=Old");
}
}
private List<ItemdtBean> prepareListofBean(List<Itemdt001MB> itemdts){
List<ItemdtBean> beans = null;
if(itemdts != null && !itemdts.isEmpty()){
beans=new ArrayList<ItemdtBean>();
ItemdtBean bean=null;
for(Itemdt001MB itemdt : itemdts ){
bean=new ItemdtBean();
bean.setItemId(itemdt.getItemId());
bean.setItemCode(itemdt.getItemCode());
bean.setQuantity(itemdt.getQuantity());
bean.setRate(itemdt.getRate());
bean.setAmount(itemdt.getAmount());
beans.add(bean);
}
}
return beans;
}
private List<PRMatReqBean> prepareprmatreqListofBean(List<PRMatReq001MB> prmatreq1mb){
List<PRMatReqBean> beans = null;
if(prmatreq1mb != null && !prmatreq1mb.isEmpty()){
beans=new ArrayList<PRMatReqBean>();
PRMatReqBean bean=null;
for(PRMatReq001MB matreq : prmatreq1mb ){
bean=new PRMatReqBean();
bean.setPmrId(matreq.getPmrId());
bean.setForWarehouse(matreq.getForWarehouse());
bean.setItemCode(matreq.getItemCode());
bean.setMrSeries(matreq.getMrSeries());
bean.setMrType(matreq.getMrType());
bean.setQuantity(matreq.getQuantity());
bean.setRequiredDate(matreq.getRequiredDate());
beans.add(bean);
}
}
return beans;
}
private List<PRQuotReqBean> prepareprquotreqListofBean(List<PRQuotReq001MB> prquotreq1MB){
List<PRQuotReqBean> beans = null;
if(prquotreq1MB != null && !prquotreq1MB.isEmpty()){
beans=new ArrayList<PRQuotReqBean>();
PRQuotReqBean bean=null;
for(PRQuotReq001MB quotreq : prquotreq1MB ){
bean=new PRQuotReqBean();
bean.setPrqId(quotreq.getPrqId());
bean.setContact(quotreq.getContact());
bean.setDate(quotreq.getDate());
bean.setEmailId(quotreq.getEmailId());
bean.setItemCode(quotreq.getItemCode());
bean.setQuantity(quotreq.getQuantity());
bean.setRequiredDate(quotreq.getRequiredDate());
bean.setRqSeries(quotreq.getRqSeries());
bean.setSupplier(quotreq.getSupplier());
bean.setWarehouse(quotreq.getWarehouse());
beans.add(bean);
}
}
return beans;
}
private List<PRPurOrdBean> prepareprpurorderListofBean(List<PRPurOrd001MB> prpurorder1MB){
List<PRPurOrdBean> beans = null;
if(prpurorder1MB != null && !prpurorder1MB.isEmpty()){
beans=new ArrayList<PRPurOrdBean>();
PRPurOrdBean bean=null;
for(PRPurOrd001MB quotreq : prpurorder1MB ){
bean=new PRPurOrdBean();
bean.setProId(quotreq.getProId());
bean.setAccountHead(quotreq.getAccountHead());
bean.setAmount(quotreq.getAmount());
bean.setDate(quotreq.getDate());
bean.setItemCode(quotreq.getItemCode());
bean.setPoSeries(quotreq.getPoSeries());
bean.setPrtype(quotreq.getPrtype());
bean.setQuantity(quotreq.getQuantity());
bean.setQuotrate(quotreq.getQuotrate());
bean.setRate(quotreq.getRate());
bean.setSupplier(quotreq.getSupplier());
bean.setSupplyrawmat(quotreq.getSupplyrawmat());
bean.setTaxandChg(quotreq.getTaxandChg());
beans.add(bean);
}
}
return beans;
}
private List<PRSuQuotReqBean> prepareprsuppordListofBean(List<PRSuQuotReq001MB> prsuquotreq1MB){
List<PRSuQuotReqBean> beans = null;
if(prsuquotreq1MB != null && !prsuquotreq1MB.isEmpty()){
beans=new ArrayList<PRSuQuotReqBean>();
PRSuQuotReqBean bean=null;
for(PRSuQuotReq001MB suqr : prsuquotreq1MB ){
bean=new PRSuQuotReqBean();
bean.setPrsrId(suqr.getPrsrId());
bean.setAccountHead(suqr.getAccountHead());
bean.setDate(suqr.getDate());
bean.setItemCode(suqr.getItemCode());
bean.setQuantity(suqr.getQuantity());
bean.setRate(suqr.getRate());
bean.setSquotrate(suqr.getSquotrate());
bean.setStockUOM(suqr.getStockUOM());
bean.setSupplier(suqr.getSupplier());
bean.setSuSeries(suqr.getSuSeries());
bean.setSutype(suqr.getSutype());
bean.setTaxandChg(suqr.getTaxandChg());
beans.add(bean);
}
}
return beans;
}
private PRMatReqBean prepareprmatreqeditBean(PRMatReq001MB prmatreq1mb){
PRMatReqBean bean = new PRMatReqBean();
bean.setPmrId(prmatreq1mb.getPmrId());
bean.setForWarehouse(prmatreq1mb.getForWarehouse());
bean.setItemCode(prmatreq1mb.getItemCode());
bean.setMrSeries(prmatreq1mb.getMrSeries());
bean.setMrType(prmatreq1mb.getMrType());
bean.setQuantity(prmatreq1mb.getQuantity());
bean.setRequiredDate(prmatreq1mb.getRequiredDate());
return bean;
}
private PRQuotReqBean prepareprreqquoteditBean(PRQuotReq001MB prquotreq1MB){
PRQuotReqBean bean = new PRQuotReqBean();
bean.setPrqId(prquotreq1MB.getPrqId());
bean.setContact(prquotreq1MB.getContact());
bean.setDate(prquotreq1MB.getDate());
bean.setEmailId(prquotreq1MB.getEmailId());
bean.setItemCode(prquotreq1MB.getItemCode());
bean.setQuantity(prquotreq1MB.getQuantity());
bean.setRequiredDate(prquotreq1MB.getRequiredDate());
bean.setRqSeries(prquotreq1MB.getRqSeries());
bean.setSupplier(prquotreq1MB.getSupplier());
bean.setWarehouse(prquotreq1MB.getWarehouse());
return bean;
}
private PRPurOrdBean prepareprpurchordeditBean(PRPurOrd001MB prpurorder1MB){
PRPurOrdBean bean = new PRPurOrdBean();
bean.setProId(prpurorder1MB.getProId());
bean.setAccountHead(prpurorder1MB.getAccountHead());
bean.setAmount(prpurorder1MB.getAmount());
bean.setDate(prpurorder1MB.getDate());
bean.setItemCode(prpurorder1MB.getItemCode());
bean.setPoSeries(prpurorder1MB.getPoSeries());
bean.setPrtype(prpurorder1MB.getPrtype());
bean.setQuantity(prpurorder1MB.getQuantity());
bean.setQuotrate(prpurorder1MB.getQuotrate());
bean.setRate(prpurorder1MB.getRate());
bean.setSupplier(prpurorder1MB.getSupplier());
bean.setSupplyrawmat(prpurorder1MB.getSupplyrawmat());
bean.setTaxandChg(prpurorder1MB.getTaxandChg());
return bean;
}
private PRSuQuotReqBean preparepusuppquoteditBean(PRSuQuotReq001MB prsuquotreq1MB){
PRSuQuotReqBean bean = new PRSuQuotReqBean();
bean.setPrsrId(prsuquotreq1MB.getPrsrId());
bean.setAccountHead(prsuquotreq1MB.getAccountHead());
bean.setDate(prsuquotreq1MB.getDate());
bean.setItemCode(prsuquotreq1MB.getItemCode());
bean.setQuantity(prsuquotreq1MB.getQuantity());
bean.setRate(prsuquotreq1MB.getRate());
bean.setSquotrate(prsuquotreq1MB.getSquotrate());
bean.setStockUOM(prsuquotreq1MB.getStockUOM());
bean.setSupplier(prsuquotreq1MB.getSupplier());
bean.setSuSeries(prsuquotreq1MB.getSuSeries());
bean.setSutype(prsuquotreq1MB.getSutype());
bean.setTaxandChg(prsuquotreq1MB.getTaxandChg());
return bean;
}
private PRMatReq001MB preparematreqmodel(PRMatReqBean prmatreqBean){
PRMatReq001MB prmatreq1mb = new PRMatReq001MB();
if(prmatreqBean.getPmrId()!= 0) {
prmatreq1mb.setPmrId(prmatreqBean.getPmrId());
}
prmatreq1mb.setForWarehouse(prmatreqBean.getForWarehouse());
prmatreq1mb.setItemCode(prmatreqBean.getItemCode());
prmatreq1mb.setMrSeries(prmatreqBean.getMrSeries());
prmatreq1mb.setMrType(prmatreqBean.getMrType());
prmatreq1mb.setQuantity(prmatreqBean.getQuantity());
prmatreq1mb.setRequiredDate(prmatreqBean.getRequiredDate());
return prmatreq1mb;
}
private PRQuotReq001MB prepareprreqquotModel(PRQuotReqBean prquotreqBean){
PRQuotReq001MB prquotreq1MB = new PRQuotReq001MB();
if(prquotreqBean.getPrqId()!= 0) {
prquotreq1MB.setPrqId(prquotreqBean.getPrqId());
}
prquotreq1MB.setContact(prquotreqBean.getContact());
prquotreq1MB.setDate(prquotreqBean.getDate());
prquotreq1MB.setEmailId(prquotreqBean.getEmailId());
prquotreq1MB.setItemCode(prquotreqBean.getItemCode());
prquotreq1MB.setQuantity(prquotreqBean.getQuantity());
prquotreq1MB.setRequiredDate(prquotreqBean.getRequiredDate());
prquotreq1MB.setRqSeries(prquotreqBean.getRqSeries());
prquotreq1MB.setSupplier(prquotreqBean.getSupplier());
prquotreq1MB.setWarehouse(prquotreqBean.getWarehouse());
return prquotreq1MB;
}
private PRPurOrd001MB prepareprreqquotModel(PRPurOrdBean prpurordBean){
PRPurOrd001MB prpurorder1MB = new PRPurOrd001MB();
if(prpurordBean.getProId()!= 0) {
prpurorder1MB.setProId(prpurordBean.getProId());
}
prpurorder1MB.setAccountHead(prpurordBean.getAccountHead());
prpurorder1MB.setAmount(prpurordBean.getAmount());
prpurorder1MB.setDate(prpurordBean.getDate());
prpurorder1MB.setItemCode(prpurordBean.getItemCode());
prpurorder1MB.setPoSeries(prpurordBean.getPoSeries());
prpurorder1MB.setPrtype(prpurordBean.getPrtype());
prpurorder1MB.setQuantity(prpurordBean.getQuantity());
prpurorder1MB.setQuotrate(prpurordBean.getQuotrate());
prpurorder1MB.setRate(prpurordBean.getRate());
prpurorder1MB.setSupplier(prpurordBean.getSupplier());
prpurorder1MB.setSupplyrawmat(prpurordBean.getSupplyrawmat());
prpurorder1MB.setTaxandChg(prpurordBean.getTaxandChg());
return prpurorder1MB;
}
private PRSuQuotReq001MB prepareprsupquotModel(PRSuQuotReqBean prsupquotreqBean){
PRSuQuotReq001MB prsuquotreq1MB = new PRSuQuotReq001MB();
if(prsupquotreqBean.getPrsrId()!= 0) {
prsuquotreq1MB.setPrsrId(prsupquotreqBean.getPrsrId());
}
prsuquotreq1MB.setAccountHead(prsupquotreqBean.getAccountHead());
prsuquotreq1MB.setDate(prsupquotreqBean.getDate());
prsuquotreq1MB.setItemCode(prsupquotreqBean.getItemCode());
prsuquotreq1MB.setQuantity(prsupquotreqBean.getQuantity());
prsuquotreq1MB.setRate(prsupquotreqBean.getRate());
prsuquotreq1MB.setSquotrate(prsupquotreqBean.getSquotrate());
prsuquotreq1MB.setStockUOM(prsupquotreqBean.getStockUOM());
prsuquotreq1MB.setSupplier(prsupquotreqBean.getSupplier());
prsuquotreq1MB.setSuSeries(prsupquotreqBean.getSuSeries());
prsuquotreq1MB.setSutype(prsupquotreqBean.getSutype());
prsuquotreq1MB.setTaxandChg(prsupquotreqBean.getTaxandChg());
return prsuquotreq1MB;
}
}
|
package com.netcracker.services;
import com.netcracker.entities.TypeGroup;
import com.netcracker.repositories.TypeGroupRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
public class TypeGroupService {
private static final Logger LOG = LoggerFactory.getLogger(UsersService.class);
@Autowired
private TypeGroupRepository typeGroupRepository;
public TypeGroup getTypeGroupByName (String name) {
LOG.debug("get type group by name");
TypeGroup possible = typeGroupRepository.findTypeGroupByNameType(name);
return possible;
}
}
|
package com.ming.pullloadmorerecyclerview;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
/**
* Author MingRuQi
* E-mail mingruqi@sina.cn
* DateTime 2019/2/20 15:35
*/
class ListsActivity extends AppCompatActivity{
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
}
}
|
package com.penglai.haima.jpush;
import cn.jpush.android.service.JCommonService;
/**
* 不要删,有用
*/
public class PushService extends JCommonService {
}
|
package com.sutran.client.bean;
import java.util.Date;
public class GenTbHorometro {
private Integer idHorometro;
private Long horometro;
private Date fechaInicio;
private Date fechaFin;
private Integer idVehiculo;
public Integer getIdHorometro() {
return idHorometro;
}
public void setIdHorometro(Integer idHorometro) {
this.idHorometro = idHorometro;
}
public Long getHorometro() {
return horometro;
}
public void setHorometro(Long horometro) {
this.horometro = horometro;
}
public Date getFechaInicio() {
return fechaInicio;
}
public void setFechaInicio(Date fechaInicio) {
this.fechaInicio = fechaInicio;
}
public Date getFechaFin() {
return fechaFin;
}
public void setFechaFin(Date fechaFin) {
this.fechaFin = fechaFin;
}
public Integer getIdVehiculo() {
return idVehiculo;
}
public void setIdVehiculo(Integer idVehiculo) {
this.idVehiculo = idVehiculo;
}
} |
package pageObjects;
public class VendorPage {
}
|
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Random;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import java.util.ArrayList;
import java.util.concurrent.*;
import java.util.*;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.data.Stat;
//import SyncPrimitive;
// distribui as tarefas para a thread pool
class DistribuirTarefas implements Runnable {
private Socket socket;
private TCPServer servidor;
private ExecutorService threadPool;
public DistribuirTarefas(Socket socket, TCPServer servidor, ExecutorService threadPool) {
this.socket = socket;
this.servidor = servidor;
this.threadPool = threadPool;
}
@Override
public void run() {
try {
// Create a BufferedReader object to read strings from the socket. (read strings FROM CLIENT)
BufferedReader br = new BufferedReader(new InputStreamReader(servidor.server.getInputStream()));
//Create output stream to write to/send TO CLIENT
DataOutputStream outStream = new DataOutputStream(servidor.server.getOutputStream());
try {
SyncPrimitive.Queue q = new SyncPrimitive.Queue("localhost", "/queueProjeto");
q.produce(1);
q.produce(2);
q.produce(3);
TarefaTiraEspacos t1 = new TarefaTiraEspacos(br, outStream);
TarefaReverter t2 = new TarefaReverter(br, outStream);
TarefaMaiuscula t3 = new TarefaMaiuscula(br, outStream);
for(int i = 0; i < 3; i++) {
int tarefa = q.consume();
switch(tarefa) {
case 1:
threadPool.execute(t1);
break;
case 2:
threadPool.execute(t2);
break;
case 3:
threadPool.execute(t3);
break;
default:
break;
}
}
SyncPrimitive.rodaBarrier(new TarefaMain());
ZooKeeper zk = SyncPrimitive.zk;
for(String filho : zk.getChildren("/b1", false)) {
zk.delete("/b1/"+filho, 0);
}
String resp = t1.getSaida() + t2.getSaida() + t3.getSaida();
System.out.println("\n\n\n"+resp);
outStream.writeBytes(resp);
} catch (InterruptedException e) {
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("\n\n\n\n\nConnection closed from "+ servidor.server.getInetAddress().getHostAddress()+":"+servidor.server.getPort());
//Close current connection
br.close();
outStream.close();
servidor.server.close();
// System.exit(0);
} catch (IOException e) {
//Print exception info
e.printStackTrace();
}
threadPool.shutdownNow();
}
}
abstract class Tarefa implements Runnable {
private BufferedReader entradaCliente;
private DataOutputStream saidaCliente;
private String input;
private String saida;
public Tarefa(BufferedReader entradaCliente, DataOutputStream saidaCliente) {
this.entradaCliente = entradaCliente;
this.saidaCliente = saidaCliente;
this.input = null;
this.saida = null;
}
public DataOutputStream getSaidaCliente() {
return this.saidaCliente;
}
public BufferedReader getEntrada() {
return this.entradaCliente;
}
public String getInput() {
return this.input;
}
public String getSaida() {
return this.saida;
}
public void setInput(String novo) {
this.input = novo;
}
public void setSaida(String nova) {
this.saida = nova;
}
public abstract void run();
public abstract void leInput() throws IOException, KeeperException, InterruptedException;
public abstract void processa() throws IOException, KeeperException, InterruptedException;
}
class TarefaTiraEspacos extends Tarefa {
public TarefaTiraEspacos(BufferedReader entradaCliente, DataOutputStream saidaCliente) {
super(entradaCliente, saidaCliente);
}
public void run() {
try {
System.out.println("----------------------------TarefaTiraEspacos: Entrando no lock");//this.setInput("frase tira espaco");
SyncPrimitive.rodaLock(this);
SyncPrimitive.rodaBarrier(this);
} catch (Exception e) {
e.printStackTrace();
}
}
public void leInput() throws IOException, KeeperException, InterruptedException {
this.getSaidaCliente().writeBytes("Digite uma frase para remover os espacos:\n");
this.setInput(this.getEntrada().readLine());
}
public void processa() throws IOException, KeeperException, InterruptedException {
this.setSaida(this.getInput().replaceAll("\\s+","") + "\n");
}
}
class TarefaMaiuscula extends Tarefa {
public TarefaMaiuscula(BufferedReader entradaCliente, DataOutputStream saidaCliente) {
super(entradaCliente, saidaCliente);
}
public void run() {
try {
System.out.println("----------------------------TarefaMaiuscula: Entrando no lock");//this.setInput("frase maiuscula");
SyncPrimitive.rodaLock(this);
SyncPrimitive.rodaBarrier(this);
} catch (Exception e) {
e.printStackTrace();
}
}
public void leInput() throws IOException, KeeperException, InterruptedException {
this.getSaidaCliente().writeBytes("Digite uma frase para colocar em caixa alta:\n");
this.setInput(this.getEntrada().readLine());
}
public void processa() throws IOException, KeeperException, InterruptedException {
this.setSaida(this.getInput().toUpperCase() + "\n");
}
}
class TarefaReverter extends Tarefa {
public TarefaReverter(BufferedReader entradaCliente, DataOutputStream saidaCliente) {
super(entradaCliente, saidaCliente);
}
public void run() {
try {
System.out.println("----------------------------TarefaReverter: Entrando no lock");//this.setInput("frase reverter");
SyncPrimitive.rodaLock(this);
SyncPrimitive.rodaBarrier(this);
} catch (Exception e) {
e.printStackTrace();
}
}
public void leInput() throws IOException, KeeperException, InterruptedException {
this.getSaidaCliente().writeBytes("Digite uma frase para ser revertida:\n");
this.setInput(this.getEntrada().readLine());
}
public void processa() throws IOException, KeeperException, InterruptedException {
StringBuilder strb = new StringBuilder(this.getInput());
this.setSaida(strb.reverse().toString() + "\n");
}
}
class TarefaMain extends Tarefa {
public TarefaMain() {
super(null, null);
}
public void run() {}
public void leInput() throws IOException, KeeperException, InterruptedException {
this.setInput("");
}
public void processa() throws IOException, KeeperException, InterruptedException {
this.setSaida("");
}
}
// Usada pelo threadpool para criar novos threads
class FabricaDeThreads implements ThreadFactory {
private static int numeroThread = 1;
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r, "Thread Servidor " + numeroThread++);
thread.setUncaughtExceptionHandler(new TratadorDeExcecao());
return thread;
}
}
// tradador de excecao que sera associado a cada thread criada pela thread pool
class TratadorDeExcecao implements UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("Deu erro na thread " + t.getName());
e.printStackTrace();
}
}
public class TCPServer extends Thread {
/** Well-known server port. */
public static int serverPort = 9000;
/** Client socket for the thread. */
Socket server;
/**
* Creates a new TCPServer worker thread.
* @param server The client socket for this object.
*/
public TCPServer (Socket server, int numTarefas){
this.server = server;
}
public void run() {
ExecutorService threadPool = Executors.newCachedThreadPool(new FabricaDeThreads());
threadPool.execute(new DistribuirTarefas(server, this, threadPool));
}
public static void main (String args[]) {
try {
//Dispatcher socket
ServerSocket serverSocket = new ServerSocket(serverPort);
//Waits for a new connection. Accepts connection from multiple clients
while (true) {
System.out.println("Waiting for connection at port "+serverPort+".");
//Worker socket
Socket s = serverSocket.accept();
System.out.println("Connection established from " + s.getInetAddress().getHostAddress() + ", local port: "+s.getLocalPort()+", remote port: "+s.getPort()+".");
//Invoke the worker thread
TCPServer worker = new TCPServer(s, 2);
worker.start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
} |
package cn.com.onlinetool.fastpay.constants;
/**
* @author choice
* @description: 货币类型
* @date 2019-06-06 14:56
*
*/
public final class CurrencyTypeConstants {
/**
* 中国人民币China Yuan Renminbi
*/
public static final String CNY = "CNY";
/**
* 港币Hong Kong Dollar
*/
public static final String HKD = "HKD";
/**
* 美元US Dollar
*/
public static final String USD = "USD";
}
|
/*
* 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 model;
/**
*
* @author HP
*/
public class ModCol1 {
//Déclaration des Variables
private String formulaire_id;
private String titre;
private String nat_juridique;
private String denomination;
private String reconnaisance_juridique;
private String pays;
private String region;
private String departement;
private String commune;
private String hors_senegal;
private String date_creation;
private String total_membre;
private String total_homme;
private String total_femme;
private String inscritPar;
// Importation Constructeur avec Paramètres
public ModCol1(String formulaire_id, String titre, String nat_juridique, String denomination,
String reconnaisance_juridique, String pays, String region,
String departement, String commune, String hors_senegal,
String date_creation, String total_membre, String total_homme,
String total_femme, String inscritPar) {
this.formulaire_id = formulaire_id;
this.titre = titre;
this.nat_juridique = nat_juridique;
this.denomination = denomination;
this.reconnaisance_juridique = reconnaisance_juridique;
this.pays = pays;
this.region = region;
this.departement = departement;
this.commune = commune;
this.hors_senegal = hors_senegal;
this.date_creation = date_creation;
this.total_membre = total_membre;
this.total_homme = total_homme;
this.total_femme = total_femme;
this.inscritPar = inscritPar;
}
// Importation des Getteurs et Setteurs
public String getFormulaire_id() {
return formulaire_id;
}
public void setFormulaire_id(String formulaire_id) {
this.formulaire_id = formulaire_id;
}
public String getTitre() {
return titre;
}
public void setTitre(String titre) {
this.titre = titre;
}
public String getNat_juridique() {
return nat_juridique;
}
public void setNat_juridique(String nat_juridique) {
this.nat_juridique = nat_juridique;
}
public String getDenomination() {
return denomination;
}
public void setDenomination(String denomination) {
this.denomination = denomination;
}
public String getReconnaisance_juridique() {
return reconnaisance_juridique;
}
public void setReconnaisance_juridique(String reconnaisance_juridique) {
this.reconnaisance_juridique = reconnaisance_juridique;
}
public String getPays() {
return pays;
}
public void setPays(String pays) {
this.pays = pays;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public String getDepartement() {
return departement;
}
public void setDepartement(String departement) {
this.departement = departement;
}
public String getCommune() {
return commune;
}
public void setCommune(String commune) {
this.commune = commune;
}
public String getHors_senegal() {
return hors_senegal;
}
public void setHors_senegal(String hors_senegal) {
this.hors_senegal = hors_senegal;
}
public String getDate_creation() {
return date_creation;
}
public void setDate_creation(String date_creation) {
this.date_creation = date_creation;
}
public String getTotal_membre() {
return total_membre;
}
public void setTotal_membre(String total_membre) {
this.total_membre = total_membre;
}
public String getTotal_homme() {
return total_homme;
}
public void setTotal_homme(String total_homme) {
this.total_homme = total_homme;
}
public String getTotal_femme() {
return total_femme;
}
public void setTotal_femme(String total_femme) {
this.total_femme = total_femme;
}
public String getInscritPar() {
return inscritPar;
}
public void setInscritPar(String inscritPar) {
this.inscritPar = inscritPar;
}
}
|
import java.io.*;
import java.util.*;
import java.util.stream.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
static int viralAdvertising(int n) {
int aud = 5;
int i = 1;
int like = 0;
int total = 0;
while(i <= n)
{
like = aud / 2;
aud = like * 3;
total += like;
i++;
}
return total;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int result = viralAdvertising(n);
System.out.println(result);
in.close();
}
}
|
package com.ut.database.dao;
import android.arch.lifecycle.LiveData;
import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.OnConflictStrategy;
import android.arch.persistence.room.Query;
import com.ut.database.entity.Record;
import java.util.List;
/**
* author : chenjiajun
* time : 2018/12/29
* desc :
*/
@Dao
public interface ORecordDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertRecords(List<Record> records);
@Query("select * from record where lockId = :lockId ORDER BY createTime desc limit 10 ")
LiveData<List<Record>> getRecordsByLockId(long lockId);
@Query("select * from record where keyId = :keyId ORDER BY createTime desc limit 10")
LiveData<List<Record>> getRecordsByKeyId(long keyId);
@Query("select * from record where lockId = :lockId ORDER BY createTime desc limit 10 ")
List<Record> getRecordListByLockId(long lockId);
@Query("select * from record where lockId = :lockId and keyId < 0 ORDER BY createTime desc limit 10")
LiveData<List<Record>> getGateLockRecordsByLockId(long lockId);
@Query("select * from record where keyId = :keyId and keyId < 0 ORDER BY createTime desc limit 10")
LiveData<List<Record>> getGateLockRecordsByKeyId(long keyId);
@Query("delete from record")
void deleteAll();
@Query("delete from record where lockId = :lockId")
void deleteByLockId(long lockId);
@Query("delete from record where keyId = :keyId")
void deleteByKeyId(long keyId);
}
|
package com.ets.gti785.labo1.controller;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* Created by Marc André on 14/06/2017.
*/
public class HttpController {
public static final String TAG = "HttpController";
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
private OkHttpClient client;
public HttpController() {
client = new OkHttpClient();
}
public String getServerURL(Context context) {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
return "http://" + sharedPref.getString("pref_ip", "") + ":" + sharedPref.getString("pref_port", "");
}
public String sendHttpGetRequest(String url) throws ExecutionException, InterruptedException {
return new HttpGetRequest().execute(url, "", "").get();
}
public String sendHttpPostRequest(String url){
try {
return new HttpPostRequest().execute(url, "{}", null).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return "";
}
public String sendHttpPostRequest(String url, String params){
try {
return new HttpPostRequest().execute(url, params, null).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return "";
}
private class HttpPostRequest extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... params){
String stringUrl = params[0];
String stringParams = params[1];
String result = "";
try {
result = post(stringUrl, stringParams);
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
protected void onPostExecute(String result){
super.onPostExecute(result);
Log.d(TAG, "HttpGetRequest onPostExecute result="+result);
}
}
public class HttpGetRequest extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... params) {
String result = "";
String url = params[0];
try {
result = getRequest(url);
Log.d("resultget", result);
} catch (IOException e){
e.printStackTrace();
}
return result;
}
@Override
protected void onPostExecute(String result){
super.onPostExecute(result);
}
}
private String post(String url, String id) throws IOException {
RequestBody formBody = new FormBody.Builder()
.add("id", String.valueOf(id))
.build();
Request request = new Request.Builder()
.url(url)
.post(formBody)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
String getRequest(String url) throws IOException {
Request request = new Request.Builder().url(url).get().build();
Response response = client.newCall(request).execute();
return response.body().string();
}
}
|
package com.what.yunbao.util;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import com.icanit.app_v2.common.IConstants;
import com.icanit.app_v2.common.UriConstants;
import android.util.Log;
public class HttpUtil {
private static final int CONNECT_TIMEOUT = 10000;
public static HttpClient client;
/**
* 修改密码
* @return
*/
public static String changePwd(String phone,String oldPwd,String newPwd){
String str = "";
String url =IConstants.URL_PREFIX+UriConstants.MODIFY_PASSWORD;
if(client == null){
client = getThreadSafeClient();
}
HttpPost post = new HttpPost(url);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("phone", phone));
params.add(new BasicNameValuePair("oldpassword",oldPwd));
params.add(new BasicNameValuePair("newpassword",newPwd));
try {
post.setEntity((new UrlEncodedFormEntity(params,HTTP.UTF_8)));
HttpResponse response = client.execute(post);
if(response.getStatusLine().getStatusCode() == 200){
str = EntityUtils.toString(response.getEntity());
}
} catch (IOException e) {
Log.e("MyHttpUtil...", "10秒无响应.发生异常");
e.printStackTrace();
}
System.out.println("+++++++"+str);
return str;
}
public static HttpClient getThreadSafeClient() {
client = new DefaultHttpClient();
//设置超时
client.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, CONNECT_TIMEOUT);
ClientConnectionManager mgr = client.getConnectionManager();
HttpParams params = client.getParams();
client = new DefaultHttpClient(new ThreadSafeClientConnManager(params,
mgr.getSchemeRegistry()), params);
return client;
}
}
|
package ru.dm_ushakov.mycalculator.parser;
public class InvalidTokenTransitionException extends ParserException {
private Token.TokenType from;
private Token.TokenType to;
private int symbolNum;
public InvalidTokenTransitionException(Token.TokenType from,Token.TokenType to,int symbolNum) {
super("Unallowed token transition from " + from + " to " + to + "at "+ symbolNum + " char.");
this.from = from;
this.to = to;
this.symbolNum = symbolNum;
}
public Token.TokenType getFromType(){
return from;
}
public Token.TokenType getToType(){
return to;
}
public int getSymbolNum() {
return symbolNum;
}
}
|
package com.phillippascual.main;
import java.sql.Connection;
import com.phillippascual.util.ConnectionUtil;
public class MeTrade {
public static Connection conn;
public static void main(String[] args) {
conn = ConnectionUtil.getConnection();
}
}
|
package com.qkj.adm.domain;
import java.util.Date;
public class FixAssets {
private String uuid;// (int)
private String title;// (varchar)资产名称
private Integer typea;
private String model;// (varchar)参考型号
private String spec;// (varchar)参考规格
private Double price;// 参考单价
private Integer num;// (int)数量
private Double price_scope;// (decimal)总价
private Integer company;// (int)所属公司
private Date p_time;// (datetime)采购时间
private Integer p_scrap;// (int)报废时限(月)
private Date add_time;// (datetime)添加时间
private String add_user;// (varchar)添加人
private Date lm_time;// (timestamp)修改时间
private String lm_user;// (varchar)修改人
private String warrantytime;
private String p_mobile;
private String p_company;
private Date use_time;
private String own_user;
private String position;
private String own_userdept;
// 非数据库字段
private Integer residue_num;// 剩余数量
private String type_title;// 类型名称
private String own_user_name;
private String own_userdept_name;
// 查询字段
private Integer residue_num_begin;
private Integer residue_num_end;
private Date p_time_start;// (datetime)采购时间
private Date p_time_end;// (datetime)采购时间
public String getOwn_userdept() {
return own_userdept;
}
public void setOwn_userdept(String own_userdept) {
this.own_userdept = own_userdept;
}
public String getOwn_userdept_name() {
return own_userdept_name;
}
public void setOwn_userdept_name(String own_userdept_name) {
this.own_userdept_name = own_userdept_name;
}
public String getOwn_user_name() {
return own_user_name;
}
public void setOwn_user_name(String own_user_name) {
this.own_user_name = own_user_name;
}
public Date getUse_time() {
return use_time;
}
public void setUse_time(Date use_time) {
this.use_time = use_time;
}
public String getOwn_user() {
return own_user;
}
public void setOwn_user(String own_user) {
this.own_user = own_user;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
public String getType_title() {
return type_title;
}
public void setType_title(String type_title) {
this.type_title = type_title;
}
public Integer getTypea() {
return typea;
}
public void setTypea(Integer typea) {
this.typea = typea;
}
public Date getP_time_start() {
return p_time_start;
}
public void setP_time_start(Date p_time_start) {
this.p_time_start = p_time_start;
}
public Date getP_time_end() {
return p_time_end;
}
public void setP_time_end(Date p_time_end) {
this.p_time_end = p_time_end;
}
public Integer getResidue_num() {
return residue_num;
}
public void setResidue_num(Integer residue_num) {
this.residue_num = residue_num;
}
public Integer getResidue_num_begin() {
return residue_num_begin;
}
public void setResidue_num_begin(Integer residue_num_begin) {
this.residue_num_begin = residue_num_begin;
}
public Integer getResidue_num_end() {
return residue_num_end;
}
public void setResidue_num_end(Integer residue_num_end) {
this.residue_num_end = residue_num_end;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getSpec() {
return spec;
}
public void setSpec(String spec) {
this.spec = spec;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getWarrantytime() {
return warrantytime;
}
public void setWarrantytime(String warrantytime) {
this.warrantytime = warrantytime;
}
public String getP_mobile() {
return p_mobile;
}
public void setP_mobile(String p_mobile) {
this.p_mobile = p_mobile;
}
public String getP_company() {
return p_company;
}
public void setP_company(String p_company) {
this.p_company = p_company;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Integer getNum() {
return num;
}
public void setNum(Integer num) {
this.num = num;
}
public Integer getCompany() {
return company;
}
public void setCompany(Integer company) {
this.company = company;
}
public Date getP_time() {
return p_time;
}
public void setP_time(Date p_time) {
this.p_time = p_time;
}
public Integer getP_scrap() {
return p_scrap;
}
public void setP_scrap(Integer p_scrap) {
this.p_scrap = p_scrap;
}
public Double getPrice_scope() {
return price_scope;
}
public void setPrice_scope(Double price_scope) {
this.price_scope = price_scope;
}
public Date getAdd_time() {
return add_time;
}
public void setAdd_time(Date add_time) {
this.add_time = add_time;
}
public String getAdd_user() {
return add_user;
}
public void setAdd_user(String add_user) {
this.add_user = add_user;
}
public Date getLm_time() {
return lm_time;
}
public void setLm_time(Date lm_time) {
this.lm_time = lm_time;
}
public String getLm_user() {
return lm_user;
}
public void setLm_user(String lm_user) {
this.lm_user = lm_user;
}
}
|
package gurveen.com.mynews;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
public class DbProvider extends ContentProvider {
private DbHelper dbHelper;
@Override
public boolean onCreate() {
dbHelper = new DbHelper(getContext());
return false;
}
@Nullable
@Override
public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
SQLiteDatabase database = dbHelper.getReadableDatabase();
Cursor cursor = database.query(DbContract.DbEntry.TABLE_NAME,
projection,selection,selectionArgs,null,null,sortOrder);
cursor.setNotificationUri(getContext().getContentResolver(),uri);
return cursor;
}
@Nullable
@Override
public String getType(@NonNull Uri uri) {
return null;
}
@Nullable
@Override
public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
return insertNews(uri,values);
}
private Uri insertNews(Uri uri, ContentValues contentValues){
SQLiteDatabase database = dbHelper.getWritableDatabase();
long id = database.insert(DbContract.DbEntry.TABLE_NAME,null,contentValues);
return ContentUris.withAppendedId(uri,id);
}
@Override
public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
SQLiteDatabase database = dbHelper.getWritableDatabase();
return database.delete(DbContract.DbEntry.TABLE_NAME,selection,selectionArgs);
}
@Override
public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
SQLiteDatabase database = dbHelper.getWritableDatabase();
return database.update(DbContract.DbEntry.TABLE_NAME,values,selection,selectionArgs);
}
}
|
package com.master;
import android.annotation.SuppressLint;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.master.activity.CardActivity;
import com.master.adapter.MyItemClickListener;
import com.master.adapter.RecyclerAdapter;
import com.master.api.TtsUtil;
import com.master.database.DatabaseUtils;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import butterknife.ButterKnife;
import butterknife.InjectView;
/**
* Created by Administrator on 2015/2/2.
*/
@SuppressLint("ValidFragment")
public class MainFragment extends Fragment implements MyItemClickListener {
public static final String TAG = "MainFragment";
private static final int SPAN_COUNT = 2;
private SQLiteDatabase db;
private Map<String, Integer> travelengMap;
private String[] travelengArray;
private String dbName;
private String id;
private String name;
private String tableName;
@InjectView(R.id.recycler_view)
RecyclerView mRecyclerView;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
initdata();
View view = inflater.inflate(R.layout.fragment_main, null);
ButterKnife.inject(this, view);
return view;
}
@SuppressLint("ValidFragment")
public MainFragment(String dbName,String tableName,String id , String name ){
this.dbName = dbName;
this.id = id ;
this.name = name;
this.tableName = tableName;
}
private void initdata() {
try {
DatabaseUtils.copyDB(getActivity(),dbName);
if (db == null)
db = getActivity().openOrCreateDatabase(getActivity().getFilesDir().getAbsolutePath() + "/" + dbName, Context.MODE_PRIVATE, null);
travelengMap = DatabaseUtils.getClassify(db, tableName,id,name);
travelengArray = travelengMap.keySet().toArray(new String[travelengMap.size()]);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(), SPAN_COUNT)); /* mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));*/
RecyclerAdapter adapter = new RecyclerAdapter(travelengArray);
mRecyclerView.setAdapter(adapter);
adapter.setOnItemClickListener(this);
}
@Override
public void onItemClick(View v, int position) {
Map<String, Object> data = new HashMap<String, Object>();
if (dbName.equals("traveleng.db")){
data.put("dbName","traveleng.db");
data.put("tableName","traveleng_sent");
data.put("id","cate_id");
data.put("zh","sent_zh");
data.put("en","sent_en");
data.put("idNum",travelengMap.get(travelengArray[position]));
}else if (dbName.equals("101_travel.db")){
data.put("dbName","101_travel.db");
data.put("tableName","sentence_list");
data.put("id","sub_indexid");
data.put("zh","topic_cn");
data.put("en","topic_x");
data.put("idNum",travelengMap.get(travelengArray[position]));
}
TtsUtil.openActivity(getActivity(),data, CardActivity.class);
}
// if (position == 1) {
// data.put(KSKey.KEY_CONTENT, ATTENTIONTYPE1);
// } else {
// data.put(KSKey.KEY_CONTENT, ATTENTIONTYPE2);
// }
// data.put("MonitorInfo", mMonitorUserInfo);
//
// if (dbName.equals("traveleng.db")){
// intent.putExtra()
//
// }else if (dbName.equals("101_travel.db")){
//
// }
// intent.putExtra(Intent.EXTRA_TEXT, travelengMap.get(travelengArray[position]));
// startActivity(intent);
}
|
package robustgametools.playstation;
/**
* A Config class to store configurations.
* All fields will be singleton model.
*/
public class Config {
}
|
package com.zundrel.ollivanders.api.spells;
import nerdhub.cardinal.components.api.util.NbtSerializable;
import net.minecraft.entity.player.PlayerEntity;
public interface ISpell extends NbtSerializable {
/**
* Returns the name of the spell.
*
* @return Name of the spell.
*/
String getName();
/**
* Returns the verbal name of the spell.
*
* @return Verbal name of the spell.
*/
String getVerbalName();
/**
* Returns the translation key of the spell.
*
* @return Translation key of the spell.
*/
String getTranslationKey();
/**
* Returns the color of the spell.
*
* @return Verbal name of the spell.
*/
int getColor();
EnumSpellCategory getCategory();
int getSpellLevel(PlayerEntity player);
void advanceSpellLevel(PlayerEntity player);
int getMaxSpellPower(PlayerEntity player);
boolean isMasteredSpell(PlayerEntity player);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.