text
stringlengths 10
2.72M
|
|---|
package tachyon.worker.hierarchy;
/**
* Different types of AllocationStrategy, which are used to allocate space among StorageDirs
*/
public enum AllocateStrategyType {
/**
* Allocate space on StorageDir that has max free space
*/
MAX_FREE,
/**
* Allocate space on StorageDirs randomly
*/
RANDOM,
/**
* Allocate space on StorageDirs by round robin
*/
ROUND_ROBIN;
}
|
package Amazon;
public class BinaryPalindrome {
public static void main(String[] args) {
int t = 3591;
StringBuilder sb = toBinary(t);
String tt = sb.toString();
if (sb.reverse().toString().equals(tt)) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
public static StringBuilder toBinary(int n) {
StringBuilder sb = new StringBuilder();
while (n > 0) {
if (n % 2 == 0) {
sb.append("0");
} else {
sb.append("1");
}
n = n / 2;
}
return sb;
}
}
|
package com.leetcode.oj;
// 61 https://leetcode.com/problems/rotate-list/
public class RotateList_61 {
// Definition for singly-linked list.
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public ListNode rotateRight(ListNode head, int k) {
int length = 0;
ListNode p = head;
while(p!=null){
length++;
p = p.next;
}
if(length==0){
return head;
}
k %= length;
if(k==0){
return head;
}
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode prev = dummy;
ListNode cur = dummy;
while(cur!=null&&k>0){
cur = cur.next;
k--;
}
while(cur!=null&&cur.next!=null){
prev = prev.next;
cur = cur.next;
}
ListNode tmpHead = prev.next;
prev.next = null;
cur.next=dummy.next;
return tmpHead;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
|
package littleservantmod;
import littleservantmod.entity.EntityLittleServant;
import littleservantmod.entity.ServantSkin;
import net.minecraft.util.DamageSource;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.SoundEvent;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
/**
* 効果音の関係を管理しているクラス
* @author shift02
*/
@Mod.EventBusSubscriber
public class LSMSounds {
public static SoundEvent getAmbientSound(EntityLittleServant servant) {
if (servant.getServantSkin() == ServantSkin.SKIN_ALEX) {
return ENTITY_LITTLEButler_AMBIENT;
}
return ENTITY_LITTLEMAID_AMBIENT;
//return SoundEvents.ENTITY_GHAST_AMBIENT;
}
public static SoundEvent getHurtSound(EntityLittleServant servant, DamageSource damageSourceIn) {
if (servant.getServantSkin() == ServantSkin.SKIN_ALEX) {
return ENTITY_LITTLEButler_HURT;
}
return ENTITY_LITTLEMAID_HURT;
}
public static SoundEvent getDeathSound(EntityLittleServant servant) {
if (servant.getServantSkin() == ServantSkin.SKIN_ALEX) {
return ENTITY_LITTLEButler_DEATH;
}
return ENTITY_LITTLEMAID_DEATH;
}
//メイド
public static final SoundEvent ENTITY_LITTLEMAID_AMBIENT = createSoundEvent("entity.little_maid.ambient");
public static final SoundEvent ENTITY_LITTLEMAID_HURT = createSoundEvent("entity.little_maid.hurt");
public static final SoundEvent ENTITY_LITTLEMAID_DEATH = createSoundEvent("entity.little_maid.death");
//バトラー
public static final SoundEvent ENTITY_LITTLEButler_AMBIENT = createSoundEvent("entity.little_butler.ambient");
public static final SoundEvent ENTITY_LITTLEButler_HURT = createSoundEvent("entity.little_butler.hurt");
public static final SoundEvent ENTITY_LITTLEButler_DEATH = createSoundEvent("entity.little_butler.death");
private static SoundEvent createSoundEvent(String soundName) {
final ResourceLocation soundID = new ResourceLocation(LittleServantMod.MOD_ID, soundName);
return new SoundEvent(soundID).setRegistryName(soundID);
}
@SubscribeEvent
public static void registerSoundEvents(RegistryEvent.Register<SoundEvent> event) {
event.getRegistry().registerAll(
ENTITY_LITTLEMAID_AMBIENT,
ENTITY_LITTLEMAID_HURT,
ENTITY_LITTLEMAID_DEATH,
ENTITY_LITTLEButler_AMBIENT,
ENTITY_LITTLEButler_HURT,
ENTITY_LITTLEButler_DEATH);
}
}
|
package at.fhj.itm.testingandroidtodoapp;
import android.content.Context;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
/**
* reads and write to text file to persist todo list
* @author Michael Ulm
*/
public class FileStorage {
// TODO Improve FileStorage with DB or https://developer.android.com/training/data-storage/files.html
private Context context;
private static FileStorage instance;
private String listName = "todo.txt";
File filesDir;
private FileStorage () {
}
public static FileStorage getInstance () {
if (FileStorage.instance == null) {
FileStorage.instance = new FileStorage ();
}
return FileStorage.instance;
}
/**
* set Application's Context to Non-Activity Class
* @param c
*/
public void setContext(Context c){
this.context = c;
filesDir = context.getFilesDir();
}
/**
* defines the list name for easier usage of multiple todo list
* and also easier unit testing
* @param listName
*/
public void setListName(String listName){
this.listName = listName;
}
/**
* read items from text file
* @return
*/
public ArrayList<String> readItems() {
File todoFile = new File(filesDir, listName);
ArrayList<String> tmpItems = null;
try {
tmpItems = new ArrayList<String>(FileUtils.readLines(todoFile));
} catch (IOException e) {
tmpItems = new ArrayList<>();
}
return tmpItems;
}
/**
* write items to text file
* @param items
*/
public void writeItems(ArrayList<String> items) {
File todoFile = new File(filesDir, listName);
try {
FileUtils.writeLines(todoFile, items);
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
package simulator.funf;
import java.io.IOException;
import java.util.List;
import pt.ulisboa.tecnico.cycleourcity.scout.mobilesensing.MobileSensing;
import pt.ulisboa.tecnico.cycleourcity.scout.mobilesensing.SensingUtils;
import pt.ulisboa.tecnico.cycleourcity.scout.mobilesensing.pipeline.PipelineConfiguration;
import pt.ulisboa.tecnico.cycleourcity.scout.mobilesensing.pipeline.sensor.ConfigurationCaretaker;
import pt.ulisboa.tecnico.cycleourcity.scout.mobilesensing.pipeline.sensor.location.PressureSensorPipeline;
import pt.ulisboa.tecnico.cycleourcity.scout.mobilesensing.pipeline.stages.CommonStages;
import pt.ulisboa.tecnico.cycleourcity.scout.proxy.LocalhostScoutProxy;
import pt.ulisboa.tecnico.cycleourcity.scout.proxy.ScoutProxyClient;
import pt.ulisboa.tecnico.cycleourcity.scout.proxy.exceptions.SessionNotInitiatedException;
import pt.ulisboa.tecnico.cycleourcity.scout.proxy.exceptions.UnableToPerformRequestException;
import pt.ulisboa.tecnico.cycleourcity.scout.storage.exceptions.NothingToArchiveException;
import storage.LocalStorageManager;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
public class SimulatedPipeline implements FunfPipeline {
private final MobileSensing mPipeline;
private final ScoutProxyClient mobileClient;
private final LocalStorageManager storage;
private boolean started = false;
private String samplingTag;
public SimulatedPipeline(){
mPipeline = new MobileSensing();
mobileClient = new LocalhostScoutProxy();
storage = LocalStorageManager.getInstance();
ConfigurationCaretaker pressureConfigCaretaker = new ConfigurationCaretaker();
PipelineConfiguration pressureConfig = new PipelineConfiguration();
pressureConfig.addStage(new PressureSensorPipeline.PressureMergeStage());
pressureConfig.addStage(new PressureSensorPipeline.FeatureExtractionStage());
pressureConfig.addFinalStage(new CommonStages.TagConfigurationStage(pressureConfigCaretaker));
pressureConfig.addFinalStage(new CommonStages.FinalizeStage());
pressureConfig.addFinalStage(new CommonStages.FeatureStorageStage(storage, false));
pressureConfigCaretaker.setOriginalPipelineConfiguration(pressureConfig);
PressureSensorPipeline pressurePipeline = new PressureSensorPipeline(pressureConfigCaretaker);
mPipeline.addSensorProcessingPipeline(pressurePipeline);
mPipeline.removeStage(SensingUtils.PRESSURE);
mPipeline.removeStage(SensingUtils.PRESSURE);
}
public void startSensing(){
try {
mobileClient.requestSession();
storage.clearStoredData();
System.out.println("Session granted, sessionID="+mobileClient.getCurrentSessionID());
mPipeline.startSensingSession();
started = true;
} catch (IOException e) {
e.printStackTrace();
}
}
public void stopSensing(){
mPipeline.stopSensingSession();
try {
mobileClient.requestSessionCompletion();
} catch (UnableToPerformRequestException | SessionNotInitiatedException e) {
e.printStackTrace();
}
started = false;
}
@Override
public void onRun(String action, JsonElement config) {
switch (action) {
case ACTION_ARCHIVE:
storage.archiveGPXTrack(samplingTag);
//TODO: check if there is information to store;
try {
storage.archive(samplingTag);
} catch (NothingToArchiveException e) {
e.printStackTrace();
}
//Clear database contents
storage.clearStoredData();
break;
case ACTION_UPDATE:
System.out.println("TODO: update");
break;
case ACTION_UPLOAD:
List<JsonObject> samples = storage.fetchStoredSamples();
if(mPipeline.allPipelinesUnmodified()) //TODO: remover
System.out.println("NOTHING HAS CHANGED, all values are features");
try {
if(mPipeline.allPipelinesUnmodified()) //TODO: remover '!'
mobileClient.publishExtractedFeatures(samples);
else
mobileClient.uploadSensorSamples(samples);
} catch (SessionNotInitiatedException
| UnableToPerformRequestException e) {
e.printStackTrace();
}
break;
default:
break;
}
}
@Override
public void onDataReceived(JsonObject data) {
if(started)
mPipeline.pushSensorSample(data);
}
@Override
public void onDataCompleted(JsonObject probeConfig, JsonObject checkpoint) {
// TODO Auto-generated method stub
}
@Override
public void setSamplingTag(String samplingTag) {
this.samplingTag = samplingTag;
}
}
|
package com.kaldin.questionbank.technology.dao;
import com.kaldin.common.util.PagingBean;
import com.kaldin.questionbank.technology.dto.CompTechInfoDTO;
import java.util.List;
public abstract interface TechnologyInterface
{
public abstract boolean saveTechnology(CompTechInfoDTO paramCompTechInfoDTO);
public abstract List<?> showTechnology(int paramInt);
public abstract List<?> showTechnology(PagingBean paramPagingBean, int paramInt1, int paramInt2);
public abstract boolean updateTechnology(int paramInt, String paramString);
public abstract boolean deleteTechnology(CompTechInfoDTO paramCompTechInfoDTO);
public abstract int getTechnologyCount(int paramInt);
}
/* Location: C:\Java Work\Workspace\Kaldin\WebContent\WEB-INF\classes\com\kaldin\kaldin_java.zip
* Qualified Name: kaldin.questionbank.technology.dao.TechnologyInterface
* JD-Core Version: 0.7.0.1
*/
|
package com.ua.serg.alex.buy.any.things.dao.daoImpl;
import com.ua.serg.alex.buy.any.things.dao.ProductDao;
import com.ua.serg.alex.buy.any.things.model.*;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;
@Repository
public class ProductDaoImpl implements ProductDao {
@PersistenceContext
private EntityManager entityManager;
@Override
public List<Product> getAllProduct() {
String hql = "from Product";
Query query = entityManager.createQuery(hql);
return query.getResultList();
}
@Override
public List<Product> getProductByCategory(Category category) {
return category.getProductList();
}
@Override
public Product getProductById(long id) {
Query query = entityManager.createQuery("from Product where productId=:id");
query.setParameter("id", id);
return (Product) query.getSingleResult();
}
@Override
public void addProductToShoppingCart(Product product, ShoppingCart shoppingCart) {
ShoppingCartDetail shoppingCartDetail = shoppingCart.getShoppingCartDetail();
shoppingCartDetail.getProducts().add(product);
entityManager.persist(shoppingCart);
}
@Override
public void addProductToOrder(Product product, User user) {
java.sql.Date sqlDate = new java.sql.Date(new java.util.Date().getTime());
Order order = new Order(sqlDate,product,user);
entityManager.persist(order);
}
@Override
public void deleteProductFromShoppingCart(Product product, ShoppingCart shoppingCart) {
ShoppingCartDetail shoppingCartDetail = shoppingCart.getShoppingCartDetail();
shoppingCartDetail.getProducts().remove(product);
product.getShoppingCartDetails().remove(shoppingCartDetail);
}
@Override
public void createProduct(Product product) {
entityManager.persist(product);
}
@Override
public void updateProduct(String paramName, String paramValue, String updateByValue, String updateBy) {
Query query = entityManager.createQuery("update Product set" + paramName + "=:param_value where " + updateByValue + "=:updateBy");
query.setParameter("param_value", paramValue);
query.setParameter("updateBy", updateBy);
query.executeUpdate();
}
@Override
public void deleteProduct(Product product) {
entityManager.remove(product);
}
@Override
public List<Product> getProductsByLimit(int offset, int limit) {
Query query = entityManager.createQuery("from Product");
query.setFirstResult(offset);
query.setMaxResults(limit);
return query.getResultList();
}
@Override
public List<Product> getProductsByLimitByCategory(Category category, int offset, int limit) {
Query query = entityManager.createQuery("select p FROM Product p JOIN Category c ON p.category.categoryId = c.categoryId WHERE c.categoryId=:id");
query.setParameter("id", category.getCategoryId());
query.setFirstResult(offset);
query.setMaxResults(limit);
return query.getResultList();
}
@Override
public long getCountAllProduct() {
Session session = entityManager.unwrap(Session.class);
long count = (long) session.createQuery("select count(*) from Product").uniqueResult();
return count;
}
@Override
public long getCountAllProductByCategory(int idCategory) {
Session session = entityManager.unwrap(Session.class);
// Query query = session.createQuery("select count(*) as totalCount From Product p " +
// "where p.category.categoryId in ( select category.categoryId from Category category where category.categoryId =:id)");
Query query = session.createQuery("select count(*) as totalCount From Product p " +
"where p.category.categoryId =:id");
query.setParameter("id", idCategory);
return (long) ((org.hibernate.query.Query) query).uniqueResult();
}
}
|
package br.com.tinyconn.layout.enumeration;
/**
* Define o tipo do frete "R"-Remetente, "D"-Destinat�rio
*
* @author Andre
*
*/
public enum TipoFreteEnum {
REMETENTE("R"), DESTINATARIO("D");
private String label;
private TipoFreteEnum(String label) {
this.label = label;
}
@Override
public String toString() {
return label;
}
}
|
/****************************************************
* $Project: DinoAge $
* $Date:: Jan 5, 2008 11:48:11 AM $
* $Revision: $
* $Author:: khoanguyen $
* $Comment:: $
**************************************************/
package org.ddth.dinoage.eclipse.ui.wizard;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import org.ddth.blogging.wordpress.WXR;
import org.ddth.dinoage.ResourceManager;
import org.ddth.dinoage.eclipse.ui.model.ExportModel;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Shell;
public class DinoAgeExportDlg extends WizardDialog {
/**
* Create the dialog
* @param parent
*/
public DinoAgeExportDlg(Shell parent, ExportModel model) {
super(parent, createWizard(model));
}
private static Wizard createWizard(final ExportModel model) {
final ExportWizardPage profileWizardPage = new ExportWizardPage(model);
Wizard wizard = new Wizard() {
@Override
public boolean performFinish() {
profileWizardPage.saveAndUpdate(false);
performExport(model);
return true;
}
};
wizard.addPage(profileWizardPage);
return wizard;
}
protected Button createButton(Composite parent, int id, String label, boolean defaultButton) {
String buttonLabel = label;
// Change FINISH button label to our own name
if (id == IDialogConstants.FINISH_ID) {
buttonLabel = ResourceManager.getMessage(ResourceManager.KEY_LABEL_EXPORT);
}
return super.createButton(parent, id, buttonLabel, defaultButton);
}
private static void performExport(ExportModel model) {
OutputStreamWriter outputStreamWriter = null;
try {
outputStreamWriter = new OutputStreamWriter(new FileOutputStream(model.getOutputFile()), "utf-8");
WXR.export(model.getBlog(), outputStreamWriter);
}
catch (Exception e) {
}
finally {
if (outputStreamWriter != null) {
try {
outputStreamWriter.close();
}
catch (IOException e) {
}
}
}
}
}
|
package br.com.alura.carteira.service;
import java.util.Random;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import br.com.alura.carteira.dto.UsuarioDto;
import br.com.alura.carteira.dto.UsuarioFormDto;
import br.com.alura.carteira.infra.EnviadorDeEmail;
import br.com.alura.carteira.modelo.Perfil;
import br.com.alura.carteira.modelo.Usuario;
import br.com.alura.carteira.repository.PerfilRepository;
import br.com.alura.carteira.repository.UsuarioRepository;
@Service
public class UsuarioService {
@Autowired
private UsuarioRepository repository;
@Autowired
private PerfilRepository perfilRepository;
@Autowired
private ModelMapper modelMapper;
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
@Autowired
private EnviadorDeEmail enviadorDeEmail;
public Page<UsuarioDto> listar(Pageable paginacao) {
return repository.findAll(paginacao).map(t -> modelMapper.map(t, UsuarioDto.class));
}
@Transactional
public UsuarioDto cadastrar(UsuarioFormDto dto) {
Usuario usuario = modelMapper.map(dto, Usuario.class);
Perfil perfil = perfilRepository.getById(dto.getPerfilId());
usuario.adicionarPerfil(perfil);
String senha = new Random().nextInt(999999) + "";
usuario.setSenha(bCryptPasswordEncoder.encode(senha));
repository.save(usuario);
String destinatario = usuario.getEmail();
String assunto = "Carteira - Bem vindo(a)";
String mensagem = String.format("Olá %s!\n\n"
+ "Segue seus dados de acesso ao sistema Carteira:"
+ "\nLogin:%s"
+ "\nSenha:%s", usuario.getNome(), usuario.getLogin(), senha);
enviadorDeEmail.enviarEmail(destinatario , assunto, mensagem);
return modelMapper.map(usuario, UsuarioDto.class);
}
}
|
package com.ytt.springcoredemo.service.base;
import com.ytt.springcoredemo.model.BaseEntity;
import com.ytt.springcoredemo.dao.mapper.core.CoreMapper;
@Deprecated
public abstract class DeleteBaseServiceImpl<T extends BaseEntity<ID>, ID, K extends CoreMapper<T,ID>>
extends DaoBaseServiceImpl<T, ID, K> implements DeleteBaseService<T,ID> {
@Override
public int deleteByID(ID id){
return mapper.deleteByPrimaryKey(id);
}
}
|
package com.tencent.mm.plugin.webview.stub;
import android.app.Dialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.ResultReceiver;
import com.tencent.mm.plugin.webview.ui.tools.d;
import com.tencent.mm.plugin.webview.ui.tools.jsapi.g;
import com.tencent.mm.sdk.platformtools.ag;
import com.tencent.mm.ui.MMActivity;
import com.tencent.mm.ui.base.a;
import com.tencent.mm.ui.base.h;
import com.tencent.smtt.sdk.TbsListener$ErrorCode;
import java.util.ArrayList;
@a(7)
public class WebViewStubTempUI extends MMActivity implements android.support.v4.app.a.a, MMActivity.a {
private int pUX = 0;
private boolean pUY = false;
private Dialog pUZ = null;
public static void a(Context context, String str, String str2, Intent intent, int i) {
Intent intent2 = new Intent(context, WebViewStubTempUI.class);
if (context instanceof Service) {
intent2.addFlags(268435456);
}
intent2.putExtra("key_action_code", 2);
StartActivityForResultTask startActivityForResultTask = new StartActivityForResultTask();
startActivityForResultTask.mOg = str;
startActivityForResultTask.pVe = str2;
startActivityForResultTask.pVf = intent;
startActivityForResultTask.bRZ = 15;
startActivityForResultTask.pVg = false;
startActivityForResultTask.pSV = i;
intent2.putExtra("key_activity_result_task", startActivityForResultTask);
context.startActivity(intent2);
}
public static void a(Context context, e eVar, String str, String str2, String str3, String str4, OnClickListener onClickListener, OnClickListener onClickListener2) {
Intent intent = new Intent(context, WebViewStubTempUI.class);
if (context instanceof Service) {
intent.addFlags(268435456);
}
intent.putExtra("key_action_code", 0);
intent.putExtra("key_alert_cancelable", false);
intent.putExtra("key_alert_message", str);
intent.putExtra("key_alert_title", str2);
intent.putExtra("key_alert_yes", str3);
intent.putExtra("key_alert_no", str4);
intent.putExtra("key_alert_result_receiver", new 1(ag.fetchFreeHandler(), onClickListener, onClickListener2));
d.a(intent.getExtras(), "webview", ".stub.WebViewStubTempUI", eVar, null);
}
public static boolean a(Context context, e eVar, String[] strArr, int i, int i2) {
if (context == null) {
return true;
}
ArrayList arrayList = new ArrayList();
for (int i3 = 0; i3 <= 0; i3++) {
String str = strArr[0];
if (android.support.v4.content.a.f(context, str) != 0) {
arrayList.add(str);
}
}
if (arrayList.size() == 0) {
return true;
}
Bundle bundle = new Bundle();
bundle.putInt("key_action_code", 1);
bundle.putStringArray("key_permission_types", (String[]) arrayList.toArray(new String[arrayList.size()]));
bundle.putInt("key_permission_request_code", i);
bundle.putInt("key_binder_id", i2);
d.a(bundle, "webview", ".stub.WebViewStubTempUI", eVar, null);
return false;
}
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
switch (getIntent().getIntExtra("key_action_code", -1)) {
case 0:
ResultReceiver resultReceiver = (ResultReceiver) getIntent().getParcelableExtra("key_alert_result_receiver");
if (resultReceiver == null) {
finish();
return;
}
this.pUZ = h.a(this, getIntent().getBooleanExtra("key_alert_cancelable", false), getIntent().getStringExtra("key_alert_message"), getIntent().getStringExtra("key_alert_title"), getIntent().getStringExtra("key_alert_yes"), getIntent().getStringExtra("key_alert_no"), new 2(this, resultReceiver), new 3(this, resultReceiver));
this.pUZ.setOnCancelListener(new 4(this));
return;
case 1:
android.support.v4.app.a.a(this, getIntent().getStringArrayExtra("key_permission_types"), getIntent().getIntExtra("key_permission_request_code", 0));
return;
case 2:
StartActivityForResultTask startActivityForResultTask = (StartActivityForResultTask) getIntent().getParcelableExtra("key_activity_result_task");
this.pUX = startActivityForResultTask.pSV;
this.pUY = true;
this.geJ = this;
com.tencent.mm.bg.d.a(this, startActivityForResultTask.mOg, startActivityForResultTask.pVe, startActivityForResultTask.pVf, startActivityForResultTask.bRZ, startActivityForResultTask.pVg);
return;
default:
finish();
return;
}
}
public void onDestroy() {
super.onDestroy();
if (this.pUZ != null) {
this.pUZ.dismiss();
}
}
public void onRequestPermissionsResult(int i, String[] strArr, int[] iArr) {
int intExtra = getIntent().getIntExtra("key_binder_id", 0);
switch (i) {
case 72:
case TbsListener$ErrorCode.DOWNLOAD_FILE_CONTENTLENGTH_NOT_MATCH /*113*/:
case 115:
case 116:
case 117:
case 118:
if (iArr[0] != 0) {
com.tencent.mm.plugin.webview.ui.tools.jsapi.h.Bh(intExtra).b(i, 0, null);
break;
} else {
com.tencent.mm.plugin.webview.ui.tools.jsapi.h.Bh(intExtra).b(i, -1, null);
break;
}
}
finish();
}
public final void b(int i, int i2, Intent intent) {
if (this.pUY) {
g Bh = com.tencent.mm.plugin.webview.ui.tools.jsapi.h.Bh(this.pUX);
if (Bh != null) {
Bh.b(i, i2, intent);
}
}
finish();
}
public final int getLayoutId() {
return -1;
}
}
|
package zm.gov.moh.common.submodule.form.widget;
public interface Labeled {
void setLabel(String label);
String getLabel();
void setTextSize(int size);
int getTextSize();
}
|
package COM.JambPracPortal.BEAN;
import COM.JambPracPortal.DAO.DAO;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import org.primefaces.context.RequestContext;
@ManagedBean
@SessionScoped
public class testResult extends DAO implements Serializable {
Connection con;
PreparedStatement ps;
Connection con2;
PreparedStatement ps2;
public String subject;
public String subject1;
public String subject2;
public String questionNo;
public String CorrectAnswer;
public String username;
public int result = 0;
public int result2 = 0;
public int subTotalNo2 = 0;
public int subTotalNo = 0;
public String userAnswers;
public int getResult2() {
return this.result2;
}
public void setResult2(int result2) {
this.result2 = result2;
}
public String getSubject() {
return this.subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getSubject1() {
return this.subject1;
}
public void setSubject1(String subject1) {
this.subject1 = subject1;
}
public String getSubject2() {
return this.subject2;
}
public void setSubject2(String subject2) {
this.subject2 = subject2;
}
public String getQuestionNo() {
return this.questionNo;
}
public void setQuestionNo(String questionNo) {
this.questionNo = questionNo;
}
public String getCorrectAnswer() {
return this.CorrectAnswer;
}
public void setCorrectAnswer(String CorrectAnswer) {
this.CorrectAnswer = CorrectAnswer;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public int getResult() {
return this.result;
}
public void setResult(int result) {
this.result = result;
}
public int getSubTotalNo2() {
return this.subTotalNo2;
}
public void setSubTotalNo2(int subTotalNo2) {
this.subTotalNo2 = subTotalNo2;
}
public int getSubTotalNo() {
return this.subTotalNo;
}
public void setSubTotalNo(int subTotalNo) {
this.subTotalNo = subTotalNo;
}
public String getUserAnswers() {
return this.userAnswers;
}
public void setUserAnswers(String userAnswers) {
this.userAnswers = userAnswers;
}
public void retriveCurrentUsernameFromUI() {
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
this.username = (String) ec.getRequestParameterMap().get("resultForm:myusername");
}
public void gettingsubject() throws ClassNotFoundException, SQLException, Exception {
retriveCurrentUsernameFromUI();
Class.forName("com.mysql.jdbc.Driver");
this.Connector();//
this.ps = this.getCn().prepareStatement("select Subject1,Subject2 from selectedsubjects where username=?");
this.ps.setString(1, this.username);
ResultSet rss = this.ps.executeQuery();
if (rss.next()) {
this.subject1 = rss.getString(1);
this.subject2 = rss.getString(2);
RequestContext.getCurrentInstance().update("resultForm:BigresultPanel");
//this.ps.close();
//this.Close();
} else {
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_WARN, "getting subjects erros", " pls, try again ");
RequestContext.getCurrentInstance().showMessageInDialog(message);
}
}
public void myresultForSubj1() throws ClassNotFoundException, SQLException, Exception {
String correctAnswerFlag = "yes";
retriveCurrentUsernameFromUI();
Class.forName("com.mysql.jdbc.Driver");
this.Connector();//
this.ps = this.getCn().prepareStatement("select count(*) from userresponse where flag=? and username=? AND subject=?");
this.ps.setString(1, correctAnswerFlag);
this.ps.setString(2, this.username);
this.ps.setString(3, this.subject1);
ResultSet rss = this.ps.executeQuery();
if (rss.next()) {
result = rss.getInt(1);
//RequestContext.getCurrentInstance().update("resultForm:BigresultPanel");
System.out.println("my Result under: " + result);
//this.ps.close();
// this.Close();
} else {
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_WARN, "Error user response", " pls, try again ");
RequestContext.getCurrentInstance().showMessageInDialog(message);
}
}
public void myresultForSubj2() throws ClassNotFoundException, SQLException, Exception {
String correctAnswerFlag = "yes";
retriveCurrentUsernameFromUI();
Class.forName("com.mysql.jdbc.Driver");
this.Connector();
this.ps = this.getCn().prepareStatement("select count(*) from userresponse where flag=? and username=? AND subject=?");
this.ps.setString(1, correctAnswerFlag);
this.ps.setString(2, this.username);
this.ps.setString(3, this.subject2);
ResultSet rss = this.ps.executeQuery();
if (rss.next()) {
this.result2 = rss.getInt(1);
System.out.println("my Result2 under: " + result2);
// RequestContext.getCurrentInstance().update("resultForm:BigresultPanel");
//this.ps.close();
// this.Close();
} else {
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_WARN, "Error user response", " pls, try again ");
RequestContext.getCurrentInstance().showMessageInDialog(message);
}
}
public void totalmarkssSubj1() throws ClassNotFoundException, SQLException, Exception {
String correctAnswerFlag = "yes";
retriveCurrentUsernameFromUI();
Class.forName("com.mysql.jdbc.Driver");
this.Connector();//
this.ps = this.getCn().prepareStatement("select count(*) from questiondataentry where subject=?");
this.ps.setString(1, this.subject1);
ResultSet rss = this.ps.executeQuery();
if (rss.next()) {
this.subTotalNo = rss.getInt(1);
RequestContext.getCurrentInstance().update("resultForm:BigresultPanel");
//this.ps.close();
//this.Close();
} else {
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_WARN, "Error user response", " pls, try again ");
RequestContext.getCurrentInstance().showMessageInDialog(message);
}
}
public void totalmarkssSubj2() throws ClassNotFoundException, SQLException, Exception {
String correctAnswerFlag = "yes";
retriveCurrentUsernameFromUI();
Class.forName("com.mysql.jdbc.Driver");
this.Connector();//
this.ps = this.getCn().prepareStatement("select count(*) from questiondataentry where subject=?");
this.ps.setString(1, this.subject2);
ResultSet rss = this.ps.executeQuery();
if (rss.next()) {
this.subTotalNo2 = rss.getInt(1);
RequestContext.getCurrentInstance().update("resultForm:BigresultPanel");
this.ps.close();
this.Close();
} else {
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_WARN, "Error user response", " pls, try again ");
RequestContext.getCurrentInstance().showMessageInDialog(message);
}
}
public void deleteResultAfterViewing() throws ClassNotFoundException, SQLException, Exception {
try {
Class.forName("com.mysql.jdbc.Driver");
this.Connector();//
this.ps = this.getCn().prepareStatement("DELETE FROM userresponse where username=?");
this.ps.setString(1, this.username);
this.ps.executeUpdate();
this.ps.close();
RequestContext.getCurrentInstance().update("TestDashBoardForm:TestDashBoardFormPanel");
} catch (Exception e) {
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_WARN, "Error user response", " pls, try again " + e);
RequestContext.getCurrentInstance().showMessageInDialog(message);
} finally {
this.Close();
}
}
public void clear() {
this.setResult(0);
this.setResult2(0);
this.setSubTotalNo(0);
this.setSubTotalNo2(0);
}
/*
public void Close() throws Exception {
try {
if (!this.con.isClosed()) {
this.con.close();
}
} catch (Exception e) {
throw e;
} finally {
this.con.close();
}
}
*/
public void viewResult() throws ClassNotFoundException, SQLException, Exception {
clear();
gettingsubject();
totalmarkssSubj1();
totalmarkssSubj2();
myresultForSubj1();
myresultForSubj2();
}
}//end of the class
|
package com.demo.test.service.impl;
import com.demo.test.dto.OrderDTO;
import com.demo.test.enums.ResultEnum;
import com.demo.test.service.BuyerService;
import com.demo.test.service.OrderService;
import com.demo.test.exception.SellException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
@Service
@CacheConfig(cacheNames = "buyerCache")
@Slf4j
public class BuyerServiceImpl implements BuyerService {
@Autowired
OrderService orderService;
@Override
@Cacheable
public OrderDTO findOrderOne(String openid, String orderId) {
return checkOwner(openid, orderId);
}
@Override
@Cacheable
public OrderDTO cancelOrder(String openid, String orderId) {
OrderDTO orderDTO = checkOwner(openid, orderId);
if (orderDTO == null) {
log.error("【取消订单】订单不存在, orderId={}", orderId);
throw new SellException(ResultEnum.ORDER_NOT_EXIST);
}
return orderService.cancel(orderDTO);
}
@Cacheable
private OrderDTO checkOwner(String openid, String orderId) {
if (StringUtils.isEmpty(openid)) {
log.error("【查询订单】openid为空");
throw new SellException(ResultEnum.PARAMS_ERROR);
}
OrderDTO orderDTO = orderService.findByOrderId(orderId);
if (orderDTO == null) {
return null;
}
if (!orderDTO.getBuyerOpenid().equals(openid)) {
log.error("【查询订单】订单openid不一致,openid={}, orderDTO={}", openid, orderDTO);
throw new SellException(ResultEnum.ORDER_OWNER_ERROR);
}
return orderDTO;
}
}
|
package org.apache.hadoop.mapreduce.v2.app.rm;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapreduce.v2.app.rm.RMContainerRequestor.ContainerRequest;
import org.apahce.hadoop.mapreduce.v2.app.ganglia.GangliaMonitor;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public abstract class ReduceScheduler extends GangliaMonitor {
static final Log LOG = LogFactory.getLog(ReduceScheduler.class);
@Override
protected void serviceInit(Configuration conf) throws Exception {
// TODO Auto-generated method stub
LOG.info("ReduceScheduler Init");
super.serviceInit(conf);
}
@Override
protected void serviceStart() throws Exception {
// TODO Auto-generated method stub
super.serviceStart();
}
@Override
protected void serviceStop() throws Exception {
// TODO Auto-generated method stub
super.serviceStop();
}
public ReduceScheduler(String name) {
super(name);
// TODO Auto-generated constructor stub
}
public abstract void selectHostForReduceRequest(ContainerRequest request);
}
|
package chat;
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer{
private ArrayList<ChatThread> chatThreadList = new ArrayList<ChatThread>();
private int port = 4101;
public void service() {
try (ServerSocket ss = new ServerSocket(port);) {
System.out.println("ChatServer 가 준비되었습니다. 접속 포트는 " + port + " 입니다.");
while (true) {
// 코드를 함께 작성해 봅시다.
Socket s = ss.accept();
System.out.println("ChatClient 가 접속했습니다.");
// 스레드에 소켓 전달
ChatThread t = new ChatThread(s);
// 스레드를 리스트에 담아두기
chatThreadList.add(t);
// 스레드 시작
t.start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void broadcast( String message ) {
// 코드를 함께 작성해 봅시다.
// 모든 스레드에게 sendmessage 호출
for (ChatThread t : chatThreadList) {
try {
t.sendMessage(message);
}catch(Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
// 챗서버의 서비스를 호출한다.
new ChatServer().service();
}
class ChatThread extends Thread {
private Socket socket;
private ObjectInputStream ois;
private ObjectOutputStream oos;
private boolean isExit = false;
public ChatThread(Socket socket) throws Exception {
this.socket = socket;
this.ois = new ObjectInputStream(socket.getInputStream());
this.oos = new ObjectOutputStream(socket.getOutputStream());
}
public void run() {
try {
// 클라이언트로 부터 날라오는 메세지를 처리한다.
while ( ! isExit ) {
// 코드를 함께 작성해 봅시다.
// 메세지를 받는다.
String msg =(String) ois.readObject();
// 종료 조건
if("^".equals(msg)) {
chatThreadList.remove(this);
isExit = true;
}else {
// 브로드캐스트 호출
broadcast(msg);
}
}
} catch (Exception e) {
e.printStackTrace();
chatThreadList.remove(this);
}
}
// 클라이언트에 메세지를 보낸다. 언제보낼까? 브로드캐스트가 호출될때 각자 담당하는 클라이언트에게 보내야지
public void sendMessage(String message) throws Exception {
// 코드를 함께 작성해 봅시다.
oos.writeObject(message);
}
}
}
|
package ba.bitcamp.LabS02D01;
import java.util.Scanner;
public class Palindorm {
public static void main(String[] args) {
//Korisnik unosi pet karaktera
Scanner unos = new Scanner (System.in);
String pocetni = unos.next();
char b = pocetni.charAt(3);
char c = pocetni.charAt(2);
char d = pocetni.charAt(1);
char e = pocetni.charAt(0);
String krajnji = (pocetni + b + c + d + e);
System.out.println(krajnji);
}
}
|
package com.base.engine;
public class GOWall extends GameObject{
public static final int STDSIZE = 16;
private GOBall ball;
public GOWall(float x, float y, float sx, float sy, GOBall ball, byte r, byte g, byte b) {
this.x = x;
this.y = y;
this.r = r;
this.g = g;
this.b = b;
this.sx = sx;
this.sy = sy;
this.ball = ball;
}
@Override
void update() {
if(Physics.checkCollision(this, ball))
ball.reverseY();
}
}
|
package interfaceAndExtends;
/**
* @author malf
* @description 物理攻击接口
* @project how2jStudy
* @since 2020/9/14
*/
public interface AD {
// 物理伤害
public void physicAttack();
}
|
package com.tencent.neattextview.textview.view;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.FontMetricsInt;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.text.Layout;
import android.text.Spannable;
import android.text.Spannable.Factory;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.TextUtils.TruncateAt;
import android.text.style.CharacterStyle;
import android.util.AttributeSet;
import android.util.LruCache;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.View.OnTouchListener;
import android.widget.TextView;
import android.widget.TextView.BufferType;
import com.tencent.neattextview.textview.layout.NeatLayout;
public class NeatTextView extends View implements a {
private static final LruCache<String, Boolean> vbe = new LruCache(500);
private static final LruCache<a, com.tencent.neattextview.textview.layout.b> vbf = new LruCache(500);
private static final HandlerThread vbg;
private static Handler vbh;
private int HB = 0;
private ColorStateList bv;
private TextPaint dG;
private int gg = Integer.MAX_VALUE;
private CharSequence iq;
private int kgE = Integer.MAX_VALUE;
public CharSequence mText;
private int qMj = Integer.MAX_VALUE;
private int tzM;
private Factory tzO = Factory.getInstance();
private TruncateAt tzP;
private float tzV = 0.0f;
private com.tencent.neattextview.textview.layout.b vaO;
private boolean vbi = false;
public boolean vbj;
private TextView vbk;
private ColorStateList vbl;
private ColorStateList vbm;
private int vbn;
private int vbo = 0;
private BufferType vbp = BufferType.NORMAL;
private b vbq;
private boolean vbr = true;
private b vbs;
private int vbt = 8388659;
private boolean vbu = true;
private d vbv;
private static class a {
float duz;
float fontScale;
int orientation;
CharSequence text;
int vbw = 1;
FontMetricsInt vbx;
int[] vby;
a(CharSequence charSequence, int[] iArr, float f, FontMetricsInt fontMetricsInt, float f2, int i) {
int i2 = 0;
this.vby = iArr;
this.text = TextUtils.isEmpty(charSequence) ? "" : charSequence;
this.duz = f;
this.vbx = fontMetricsInt;
this.fontScale = f2;
this.orientation = i;
if (charSequence instanceof Spannable) {
CharacterStyle[] characterStyleArr = (CharacterStyle[]) ((Spannable) charSequence).getSpans(0, charSequence.length(), CharacterStyle.class);
int length = characterStyleArr.length;
while (i2 < length) {
this.vbw = characterStyleArr[i2].hashCode() + this.vbw;
i2++;
}
}
}
public final int hashCode() {
return (int) (((((float) (this.vbw + this.text.hashCode())) + ((this.duz * this.fontScale) * ((float) this.orientation))) + ((float) this.vby[0])) + ((float) this.vby[1]));
}
public final boolean equals(Object obj) {
if (!(obj instanceof a)) {
return false;
}
a aVar = (a) obj;
if (this.duz == aVar.duz && this.fontScale == aVar.fontScale && this.vby[0] == aVar.vby[0] && this.vby[1] == aVar.vby[1] && this.vbx.descent == aVar.vbx.descent && this.vbx.top == aVar.vbx.top && this.vbx.bottom == aVar.vbx.bottom && this.vbx.ascent == aVar.vbx.ascent && this.vbx.leading == aVar.vbx.leading && this.text.equals(aVar.text)) {
return true;
}
return false;
}
}
public interface b {
boolean dK(View view);
}
public interface c extends OnTouchListener {
}
static final class d implements Runnable {
volatile boolean dDR = false;
TextPaint dtU = new TextPaint();
String text;
float[] vbz;
d(String str, TextPaint textPaint) {
this.dtU.set(textPaint);
this.text = str;
}
public final float[] d(Paint paint) {
if (paint.getTextSize() == this.dtU.getTextSize() && this.dDR) {
return this.vbz;
}
return null;
}
public final void run() {
this.vbz = new float[this.text.length()];
this.dtU.getTextWidths(this.text, this.vbz);
this.dDR = true;
}
}
static {
HandlerThread handlerThread = new HandlerThread("PreMeasuredThread", -8);
vbg = handlerThread;
handlerThread.start();
Looper looper = vbg.getLooper();
if (looper != null) {
vbh = new Handler(looper);
}
}
public NeatTextView(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
a(context, attributeSet, 0);
}
public NeatTextView(Context context, AttributeSet attributeSet, int i) {
super(context, attributeSet, i);
a(context, attributeSet, i);
}
private void a(Context context, AttributeSet attributeSet, int i) {
this.vbq = new b(getContext(), this);
TextView textView = new TextView(context);
textView.setClickable(true);
textView.setFocusable(true);
this.vbk = textView;
this.dG = getWrappedTextView().getPaint();
TypedArray obtainStyledAttributes = context.obtainStyledAttributes(attributeSet, com.tencent.neattextview.textview.a.a.NeatTextView, i, 0);
int i2 = 15;
int i3 = -16777216;
int i4 = -7829368;
int i5 = -16776961;
int i6 = -1;
CharSequence charSequence = null;
try {
int indexCount = obtainStyledAttributes.getIndexCount();
for (int i7 = 0; i7 < indexCount; i7++) {
int index = obtainStyledAttributes.getIndex(i7);
if (index == com.tencent.neattextview.textview.a.a.NeatTextView_android_textSize) {
i2 = obtainStyledAttributes.getDimensionPixelSize(index, 15);
} else if (index == com.tencent.neattextview.textview.a.a.NeatTextView_android_textColor) {
i3 = obtainStyledAttributes.getColor(index, -16777216);
} else if (index == com.tencent.neattextview.textview.a.a.NeatTextView_android_singleLine) {
if (obtainStyledAttributes.getBoolean(index, false)) {
index = 1;
} else {
index = -1;
}
setMaxLines(index);
} else if (index == com.tencent.neattextview.textview.a.a.NeatTextView_android_lines) {
setLines(obtainStyledAttributes.getInt(index, -1));
} else if (index == com.tencent.neattextview.textview.a.a.NeatTextView_android_gravity) {
setTextGravity(obtainStyledAttributes.getInt(index, 16));
} else if (index == com.tencent.neattextview.textview.a.a.NeatTextView_android_maxWidth) {
setMaxWidth(obtainStyledAttributes.getDimensionPixelSize(index, -1));
} else if (index == com.tencent.neattextview.textview.a.a.NeatTextView_android_lineSpacingExtra) {
setSpacingAdd(obtainStyledAttributes.getDimensionPixelSize(index, (int) this.tzV));
} else if (index == com.tencent.neattextview.textview.a.a.NeatTextView_android_minWidth) {
setMinWidth(obtainStyledAttributes.getDimensionPixelSize(index, -1));
} else if (index == com.tencent.neattextview.textview.a.a.NeatTextView_android_minHeight) {
setMinHeight(obtainStyledAttributes.getDimensionPixelSize(index, -1));
} else if (index == com.tencent.neattextview.textview.a.a.NeatTextView_android_maxHeight) {
setMaxHeight(obtainStyledAttributes.getDimensionPixelSize(index, -1));
} else if (index == com.tencent.neattextview.textview.a.a.NeatTextView_android_maxLines) {
setMaxLines(obtainStyledAttributes.getInt(index, -1));
} else if (index == com.tencent.neattextview.textview.a.a.NeatTextView_android_text) {
charSequence = obtainStyledAttributes.getString(index);
} else if (index == com.tencent.neattextview.textview.a.a.NeatTextView_android_width) {
setWidth(obtainStyledAttributes.getDimensionPixelSize(index, -1));
} else if (index == com.tencent.neattextview.textview.a.a.NeatTextView_android_height) {
setHeight(obtainStyledAttributes.getDimensionPixelSize(index, -1));
} else if (index == com.tencent.neattextview.textview.a.a.NeatTextView_android_hint) {
setHint(obtainStyledAttributes.getText(index));
} else if (index == com.tencent.neattextview.textview.a.a.NeatTextView_android_textColorHint) {
i4 = obtainStyledAttributes.getColor(index, -7829368);
} else if (index == com.tencent.neattextview.textview.a.a.NeatTextView_android_textColorLink) {
i5 = obtainStyledAttributes.getColor(index, -16776961);
} else if (index == com.tencent.neattextview.textview.a.a.NeatTextView_android_ellipsize) {
i6 = obtainStyledAttributes.getInt(index, i6);
} else if (index == com.tencent.neattextview.textview.a.a.NeatTextView_smartLetter) {
this.vbu = obtainStyledAttributes.getBoolean(index, true);
}
}
setTextColor(i3);
setRawTextSize((float) i2);
setLinkTextColor(i5);
setHintTextColor(i4);
switch (i6) {
case 1:
setEllipsize(TruncateAt.START);
break;
case 2:
setEllipsize(TruncateAt.MIDDLE);
break;
case 3:
setEllipsize(TruncateAt.END);
break;
}
if (!TextUtils.isEmpty(charSequence)) {
Q(charSequence);
}
getWrappedTextView().setPadding(getPaddingLeft(), getPaddingTop(), getPaddingRight(), getPaddingBottom());
} finally {
obtainStyledAttributes.recycle();
}
}
public com.tencent.neattextview.textview.layout.b getLayout() {
return this.vaO;
}
public b getOnDoubleClickListener() {
return this.vbs;
}
public void setOnDoubleClickListener(b bVar) {
this.vbs = bVar;
}
public boolean onTouchEvent(MotionEvent motionEvent) {
if (this.vbq == null || !this.vbq.onTouch(this, motionEvent)) {
return super.onTouchEvent(motionEvent);
}
return true;
}
public void onMeasure(int i, int i2) {
if (TextUtils.isEmpty(this.mText) && TextUtils.isEmpty(this.iq)) {
super.onMeasure(i, i2);
} else if (this.vbj) {
getWrappedTextView().measure(i, i2);
setMeasuredDimension(getWrappedTextView().getMeasuredWidth(), getWrappedTextView().getMeasuredHeight());
} else {
int i3;
int i4;
int mode = MeasureSpec.getMode(i);
int mode2 = MeasureSpec.getMode(i2);
int size = MeasureSpec.getSize(i);
int size2 = MeasureSpec.getSize(i2);
if (size <= 0 && mode2 == 0) {
size = getResources().getDisplayMetrics().widthPixels;
}
if (size2 <= 0 && mode2 == 0) {
size2 = Integer.MAX_VALUE;
}
if (this.gg <= 0 || this.gg >= size) {
i3 = size;
} else {
i3 = this.gg;
}
if (this.qMj <= 0 || this.qMj >= size2) {
i4 = size2;
} else {
i4 = this.qMj;
}
size2 = (i3 - getPaddingLeft()) - getPaddingRight();
size = (i4 - getPaddingTop()) - getPaddingBottom();
a aVar = new a(this.mText, new int[]{size2, size}, getTextSize(), getPaint().getFontMetricsInt(), getResources().getConfiguration().fontScale, getResources().getConfiguration().orientation);
if (this.vbi) {
this.vaO = null;
this.vbi = false;
} else {
this.vaO = (com.tencent.neattextview.textview.layout.b) vbf.get(aVar);
}
if (this.vaO == null) {
if (!TextUtils.isEmpty(this.mText) || TextUtils.isEmpty(this.iq)) {
this.vaO = new NeatLayout(this.mText, this.vbv == null ? null : this.vbv.d(this.dG));
} else {
this.vaO = new NeatLayout(this.iq, this.vbv == null ? null : this.vbv.d(this.dG));
}
this.vaO.a(getPaint(), (float) aVar.vby[0], (float) aVar.vby[1], (float) getPaddingLeft(), (float) getPaddingTop(), this.tzV, this.kgE, this.tzP, this.vbu);
vbf.put(aVar, this.vaO);
}
float[] cEh = this.vaO.cEh();
if (mode != 1073741824) {
i3 = (int) Math.min((cEh[0] + ((float) getPaddingLeft())) + ((float) getPaddingRight()), (float) this.gg);
}
if (mode2 != 1073741824) {
i4 = (int) Math.min((cEh[1] + ((float) getPaddingTop())) + ((float) getPaddingBottom()), (float) this.qMj);
}
setMeasuredDimension(Math.max(i3, this.HB), Math.max(i4, this.vbo));
}
}
public final com.tencent.neattextview.textview.layout.b Hg(int i) {
if (TextUtils.isEmpty(this.mText)) {
return null;
}
com.tencent.neattextview.textview.layout.b neatLayout = new NeatLayout(this.mText, null);
neatLayout.a(getPaint(), (float) i, 2.14748365E9f, (float) getPaddingLeft(), (float) getPaddingTop(), this.tzV, this.kgE, this.tzP, this.vbu);
return neatLayout;
}
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
int i = this.tzM;
if (!(TextUtils.isEmpty(this.iq) || !TextUtils.isEmpty(this.mText) || this.vbl == null)) {
i = this.vbn;
}
this.dG.setColor(i);
this.dG.drawableState = getDrawableState();
if (this.vbj) {
canvas.save();
canvas.translate((float) getPaddingLeft(), (float) getPaddingTop());
Layout layout = getWrappedTextView().getLayout();
if (layout != null) {
layout.draw(canvas);
}
canvas.restore();
} else if (this.vaO != null) {
if (this.vaO.cEi() != null) {
this.vaO.cEi().set(this.dG);
}
this.vaO.a(canvas, (float) getPaddingLeft(), getVerticalOffset());
}
}
public TextView getWrappedTextView() {
return this.vbk;
}
/* JADX WARNING: inconsistent code. */
/* Code decompiled incorrectly, please refer to instructions dump. */
public void Q(java.lang.CharSequence r7) {
/*
r6 = this;
r1 = 1;
r2 = 0;
r0 = android.widget.TextView.BufferType.NORMAL;
r6.vbp = r0;
if (r7 != 0) goto L_0x000b;
L_0x0008:
r7 = "";
L_0x000b:
r3 = android.widget.TextView.BufferType.NORMAL;
if (r0 != r3) goto L_0x0064;
L_0x000f:
r7 = android.text.TextUtils.stringOrSpannedString(r7);
L_0x0013:
r6.mText = r7;
r0 = r6.cAs();
if (r0 == 0) goto L_0x003e;
L_0x001b:
r3 = r7.toString();
r0 = vbe;
r0 = r0.get(r3);
r0 = (java.lang.Boolean) r0;
if (r0 != 0) goto L_0x0071;
L_0x0029:
r0 = "^[\\u0001-\\u00b7\\u4E00-\\u9FA5\\ue001-\\ue537\\u2005-\\u2027\\u3001-\\u3011\\uff01-\\uffe5\\u2100-\\u2900[\\ud83c\\udc00-\\ud83c\\udfff]|[\\ud83d\\udc00-\\ud83d\\udfff]]+$";
r0 = r3.matches(r0);
if (r0 != 0) goto L_0x006f;
L_0x0032:
r0 = r1;
L_0x0033:
r4 = vbe;
r5 = java.lang.Boolean.valueOf(r0);
r4.put(r3, r5);
L_0x003c:
if (r0 == 0) goto L_0x003f;
L_0x003e:
r2 = r1;
L_0x003f:
r6.vbj = r2;
r0 = r6.vbj;
if (r0 == 0) goto L_0x0076;
L_0x0045:
r0 = r6.getLayoutParams();
if (r0 == 0) goto L_0x0056;
L_0x004b:
r0 = r6.getWrappedTextView();
r1 = r6.getLayoutParams();
r0.setLayoutParams(r1);
L_0x0056:
r0 = r6.getWrappedTextView();
r0.setText(r7);
r6.requestLayout();
r6.invalidate();
L_0x0063:
return;
L_0x0064:
r3 = android.widget.TextView.BufferType.SPANNABLE;
if (r0 != r3) goto L_0x0013;
L_0x0068:
r0 = r6.tzO;
r7 = r0.newSpannable(r7);
goto L_0x0013;
L_0x006f:
r0 = r2;
goto L_0x0033;
L_0x0071:
r0 = r0.booleanValue();
goto L_0x003c;
L_0x0076:
r6.cEl();
goto L_0x0063;
*/
throw new UnsupportedOperationException("Method not decompiled: com.tencent.neattextview.textview.view.NeatTextView.Q(java.lang.CharSequence):void");
}
public float getVerticalOffset() {
if ((this.vbt & 112) == 48 || this.vaO == null) {
return (float) getPaddingTop();
}
return (((float) getMeasuredHeight()) - this.vaO.cEh()[1]) / 2.0f;
}
public float getHorizontalOffset() {
if ((this.vbt & 7) == 3 || this.vaO == null) {
return (float) getPaddingLeft();
}
return (((float) getMeasuredHeight()) - this.vaO.cEh()[0]) / 2.0f;
}
public void setEllipsize(TruncateAt truncateAt) {
if (this.tzP != truncateAt) {
this.tzP = truncateAt;
if (this.vaO != null) {
this.vaO = null;
requestLayout();
invalidate();
}
}
}
public int getTextGravity() {
return this.vbt;
}
public void setTextGravity(int i) {
int i2;
getWrappedTextView().setGravity(i);
if ((8388615 & i) == 0) {
i2 = 8388611 | i;
} else {
i2 = i;
}
if ((i2 & 112) == 0) {
i2 |= 48;
}
this.vbt = i2;
if (i2 != this.vbt) {
invalidate();
}
}
public void setPadding(int i, int i2, int i3, int i4) {
if (!(i == getPaddingLeft() && i3 == getPaddingRight() && i2 == getPaddingTop() && i4 == getPaddingBottom())) {
this.vaO = null;
}
super.setPadding(i, i2, i3, i4);
getWrappedTextView().setPadding(i, i2, i3, i4);
invalidate();
}
public TextPaint getPaint() {
return this.dG;
}
public int getLineCount() {
return this.vaO != null ? this.vaO.val.size() : 0;
}
public CharSequence getHint() {
return this.iq;
}
public final void setHint(int i) {
setHint(getContext().getResources().getText(i));
}
public final void setHint(CharSequence charSequence) {
this.iq = TextUtils.stringOrSpannedString(charSequence);
getWrappedTextView().setHint(this.iq);
if (TextUtils.isEmpty(this.mText)) {
cEl();
}
}
public boolean cAs() {
return this.vbr;
}
public void setNeatEnable(boolean z) {
this.vbr = z;
}
public void setSmartLetterEnable(boolean z) {
this.vbu = z;
}
public void setWidth(int i) {
this.vbi = true;
this.gg = i;
getWrappedTextView().setMaxWidth(i);
requestLayout();
invalidate();
}
public void setHeight(int i) {
this.vbi = true;
this.qMj = i;
getWrappedTextView().setMaxHeight(i);
requestLayout();
invalidate();
}
public void setMinHeight(int i) {
this.vbi = true;
this.vbo = i;
getWrappedTextView().setMinHeight(i);
requestLayout();
invalidate();
}
public void setMaxHeight(int i) {
this.vbi = true;
this.qMj = i;
getWrappedTextView().setMaxHeight(i);
requestLayout();
invalidate();
}
public void setMaxWidth(int i) {
this.vbi = true;
this.gg = i;
getWrappedTextView().setMaxWidth(i);
requestLayout();
invalidate();
}
public void setSpacingAdd(int i) {
this.vbi = true;
this.tzV = (float) i;
getWrappedTextView().setLineSpacing((float) i, 1.0f);
requestLayout();
invalidate();
}
public void setMinWidth(int i) {
this.vbi = true;
this.HB = i;
getWrappedTextView().setMinWidth(i);
requestLayout();
invalidate();
}
public void setMaxLines(int i) {
this.vbi = true;
this.kgE = i;
getWrappedTextView().setMaxLines(i);
requestLayout();
invalidate();
}
public void setLines(int i) {
this.vbi = true;
this.kgE = i;
getWrappedTextView().setLines(i);
requestLayout();
invalidate();
}
public void setTextColor(int i) {
this.bv = ColorStateList.valueOf(i);
getWrappedTextView().setTextColor(i);
updateTextColors();
}
public final void setLinkTextColor(int i) {
this.vbm = ColorStateList.valueOf(i);
updateTextColors();
}
public final void setHintTextColor(int i) {
this.vbl = ColorStateList.valueOf(i);
getWrappedTextView().setHintTextColor(i);
updateTextColors();
}
public final int getCurrentHintTextColor() {
return this.vbl != null ? this.vbn : this.tzM;
}
public final int getCurrentTextColor() {
return this.tzM;
}
private void cEl() {
this.vaO = null;
if (vbh != null) {
Handler handler;
Runnable dVar;
if (this.mText == null && this.iq != null) {
handler = vbh;
dVar = new d(this.iq.toString(), this.dG);
this.vbv = dVar;
handler.post(dVar);
} else if (this.mText != null) {
handler = vbh;
dVar = new d(this.mText.toString(), this.dG);
this.vbv = dVar;
handler.post(dVar);
} else {
return;
}
}
requestLayout();
invalidate();
}
private void updateTextColors() {
int colorForState = this.bv.getColorForState(getDrawableState(), 0);
if (colorForState != this.tzM) {
this.tzM = colorForState;
colorForState = 1;
} else {
colorForState = 0;
}
if (this.vbm != null) {
int colorForState2 = this.vbm.getColorForState(getDrawableState(), 0);
if (colorForState2 != this.dG.linkColor) {
this.dG.linkColor = colorForState2;
colorForState = 1;
}
}
if (this.vbl != null) {
int colorForState3 = this.vbl.getColorForState(getDrawableState(), 0);
if (colorForState3 != this.vbn) {
this.vbn = colorForState3;
if (this.mText == null || this.mText.length() == 0) {
colorForState = 1;
}
}
}
if (colorForState != 0) {
invalidate();
}
}
public float getTextSize() {
return getPaint().getTextSize();
}
public void setTextSize(float f) {
setTextSize(2, f);
}
public final void setTextSize(int i, float f) {
Resources system;
Context context = getContext();
if (context == null) {
system = Resources.getSystem();
} else {
system = context.getResources();
}
setRawTextSize(TypedValue.applyDimension(i, f, system.getDisplayMetrics()));
}
private void setRawTextSize(float f) {
if (f != this.dG.getTextSize()) {
this.dG.setTextSize(f);
if (this.vaO != null) {
cEl();
requestLayout();
invalidate();
}
}
}
}
|
package nb.dao;
import nb.domain.AssetHistory;
import nb.queryDomain.AcceptPriceHistory;
import org.hibernate.query.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.math.BigDecimal;
import java.util.List;
@Repository
public class AssetHistoryDaoImpl implements AssetHistoryDao {
@Autowired
private SessionFactory factory;
public AssetHistoryDaoImpl(){
}
public AssetHistoryDaoImpl(SessionFactory factory){
this.factory = factory;
}
public SessionFactory getFactory() {
return factory;
}
public void setFactory(SessionFactory factory) {
this.factory = factory;
}
@Override
public Long create( AssetHistory assetHistory) {
return (Long)factory.getCurrentSession().save(assetHistory);
}
@Override
public AssetHistory read(Long id) {
return (AssetHistory)factory.getCurrentSession().get(AssetHistory.class, id);
}
@Override
public boolean update(AssetHistory assetHistory) {
factory.getCurrentSession().update(assetHistory);
return true;
}
@Override
public boolean delete(AssetHistory assetHistory) {
factory.getCurrentSession().delete(assetHistory);
return true;
}
@Override
public BigDecimal getFirstAccPrice(Long assId) {
Query query = factory.getCurrentSession().createQuery("select ah.acceptPrice from AssetHistory ah where ah.id=:assId and ah.acceptPrice is not null ORDER BY ah.changeDate ASC ");
query.setParameter("assId", assId);
try {
return (BigDecimal) query.list().get(0);
}
catch(IndexOutOfBoundsException e){
return null;
}
}
@Override
public BigDecimal getLastAccPrice(Long assId) {
Query query = factory.getCurrentSession().createQuery("select ah.acceptPrice from AssetHistory ah where ah.id=:assId and ah.acceptPrice is not null ORDER BY ah.changeDate DESC ");
query.setParameter("assId", assId);
try {
return (BigDecimal) query.list().get(0);
}
catch(IndexOutOfBoundsException e){
return null;
}
}
@Override
public List getLotIdHistoryByAsset(Long assId){
Query query = factory.getCurrentSession().createQuery("select ah.lotId from AssetHistory ah where ah.id=:assId GROUP BY ah.lotId ");
query.setParameter("assId", assId);
try {
return query.list();
}
catch(IndexOutOfBoundsException e){
return null;
}
}
@Override
public BigDecimal getAccPriceByLotIdHistory(Long assetId, Long lotId){
Query query = factory.getCurrentSession().createQuery("select ah.acceptPrice from AssetHistory ah where ah.idKey in (SELECT max(a.idKey) from AssetHistory a where a.id=:assetId and a.lotId=:lotId)");
query.setParameter("assetId", assetId);
query.setParameter("lotId", lotId);
try {
return (BigDecimal) query.list().get(0);
}
catch(IndexOutOfBoundsException e){
return null;
}
}
@Override
public List<AcceptPriceHistory> getDateAndAccPriceHistoryByAsset(Long assId){
Query query = factory.getCurrentSession().createQuery("select new nb.queryDomain.AcceptPriceHistory(min(ah.changeDate), ah.acceptPrice) from AssetHistory ah where ah.id=:assId and acceptPrice is not null GROUP BY ah.acceptPrice ");
query.setParameter("assId", assId);
try {
return query.list();
}
catch(IndexOutOfBoundsException e){
return null;
}
}
}
|
class Main {
public static void main(String[] args) {
System.out.println("Ola, eu sou Luccas Santana e eu moro em bebedouro");
}
}
|
package loops;
public class interchange {
public void intChange(int a, int b){
//with using 3rd variable
/* int c = a;
a = b;
b = c;
*/
//without using 3rd variable
a = a+b;
b = a-b;
a = a-b;
System.out.println("Please print a value:-" +a);
System.out.println("Please print b value:-" +b);
}
}
|
package br.com.smarthouse.controledeluzes.persistence;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import br.com.smarthouse.controledeluzes.model.ambiente.SubAmbiente;
public interface SubAmbienteDAO extends JpaRepository<SubAmbiente, Long> {
@Query("select s from SubAmbiente s where s.ambiente.id = :idAmbiente")
public List<SubAmbiente> findByIdAmbiente(@Param("idAmbiente") Long idAmbiente);
}
|
package response;
public class StatusRes {
private String status;
public StatusRes(String status) {
this.status = status;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public StatusRes() {}
}
|
/** ****************************************************************************
* Copyright (c) 1, 2012The Spray Project.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Spray Dev Team - initial API and implementation
**************************************************************************** */
package org.eclipselabs.spray.generator.graphiti.tests;
import com.google.inject.Injector;
/**
* Sets up also bindings for Graphiti Generator and Runtime.
*
* @author Karsten Thoms
*/
public class SprayTestsInjectorProvider extends SprayInjectorProvider {
private Injector injector;
@Override
public Injector internalCreateInjector() {
if (injector == null) {
this.injector = new SprayTestsStandaloneSetup().createInjectorAndDoEMFRegistration();
}
return injector;
}
}
|
package ls.example.t.zero2line.util;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import java.util.Locale;
/**
* <pre>
* author: Blankj
* blog : http://blankj.com
* time : 2019/06/18
* desc : utils about view
* </pre>
*/
public class ViewUtils {
/**
* Set the enabled state of this view.
*
* @param view The view.
* @param enabled True to enabled, false otherwise.
*/
public static void setViewEnabled(android.view.View view, boolean enabled) {
setViewEnabled(view, enabled, (android.view.View) null);
}
/**
* Set the enabled state of this view.
*
* @param view The view.
* @param enabled True to enabled, false otherwise.
* @param excludes The excludes.
*/
public static void setViewEnabled(android.view.View view, boolean enabled, android.view.View... excludes) {
if (view == null) return;
if (excludes != null) {
for (android.view.View exclude : excludes) {
if (view == exclude) return;
}
}
if (view instanceof android.view.ViewGroup) {
android.view.ViewGroup viewGroup = (android.view.ViewGroup) view;
int childCount = viewGroup.getChildCount();
for (int i = 0; i < childCount; i++) {
setViewEnabled(viewGroup.getChildAt(i), enabled, excludes);
}
}
view.setEnabled(enabled);
}
/**
* @param runnable The runnable
*/
public static void runOnUiThread(final Runnable runnable) {
Utils.runOnUiThread(runnable);
}
/**
* @param runnable The runnable.
* @param delayMillis The delay (in milliseconds) until the Runnable will be executed.
*/
public static void runOnUiThreadDelayed(final Runnable runnable, long delayMillis) {
Utils.runOnUiThreadDelayed(runnable, delayMillis);
}
/**
* Return whether horizontal layout direction of views are from Right to Left.
*
* @return {@code true}: yes<br>{@code false}: no
*/
public static boolean isLayoutRtl() {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
java.util.Locale primaryLocale;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
primaryLocale = Utils.getApp().getResources().getConfiguration().getLocales().get(0);
} else {
primaryLocale = Utils.getApp().getResources().getConfiguration().locale;
}
return android.text.TextUtils.getLayoutDirectionFromLocale(primaryLocale) == android.view.View.LAYOUT_DIRECTION_RTL;
}
return false;
}
/**
* Fix the problem of topping the ScrollView nested ListView/GridView/WebView/RecyclerView.
*
* @param view The root view inner of ScrollView.
*/
public static void fixScrollViewTopping(android.view.View view) {
view.setFocusable(false);
android.view.ViewGroup viewGroup = null;
if (view instanceof android.view.ViewGroup) {
viewGroup = (android.view.ViewGroup) view;
}
if (viewGroup == null) {
return;
}
for (int i = 0, n = viewGroup.getChildCount(); i < n; i++) {
android.view.View childAt = viewGroup.getChildAt(i);
childAt.setFocusable(false);
if (childAt instanceof android.view.ViewGroup) {
fixScrollViewTopping(childAt);
}
}
}
}
|
package net.fexcraft.lib.tmt;
/**
* Similar to 'FlansMod'-type Models, for a fast convert.
* @Author Ferdinand Calo' (FEX___96)
*/
public class GenericModelBase extends ModelBase {
public ModelRendererTurbo base[] = new ModelRendererTurbo[0], open[] = new ModelRendererTurbo[0], closed[] = new ModelRendererTurbo[0];
public ModelRendererTurbo r0[] = new ModelRendererTurbo[0], r1[] = new ModelRendererTurbo[0], r2[] = new ModelRendererTurbo[0];
public ModelRendererTurbo r3[] = new ModelRendererTurbo[0], r4[] = new ModelRendererTurbo[0], r5[] = new ModelRendererTurbo[0];
public ModelRendererTurbo r6[] = new ModelRendererTurbo[0], r7[] = new ModelRendererTurbo[0], r8[] = new ModelRendererTurbo[0];
public ModelRendererTurbo r9[] = new ModelRendererTurbo[0];
public void render(){
render(base);
render(open); render(closed); render(r0);
render(r1); render(r2); render(r3);
render(r4); render(r5); render(r6);
render(r7); render(r8); render(r9);
}
@Override
public void translateAll(float x, float y, float z){
translate(base, x, y, z);
translate(open, x, y, z); translate(closed, x, y, z); translate(r0, x, y, z);
translate(r1, x, y, z); translate(r2, x, y, z); translate(r3, x, y, z);
translate(r4, x, y, z); translate(r5, x, y, z); translate(r6, x, y, z);
translate(r7, x, y, z); translate(r8, x, y, z); translate(r9, x, y, z);
}
@Override
public void rotateAll(float x, float y, float z){
rotate(base, x, y, z);
rotate(open, x, y, z); rotate(closed, x, y, z); rotate(r0, x, y, z);
rotate(r1, x, y, z); rotate(r2, x, y, z); rotate(r3, x, y, z);
rotate(r4, x, y, z); rotate(r5, x, y, z); rotate(r6, x, y, z);
rotate(r7, x, y, z); rotate(r8, x, y, z); rotate(r9, x, y, z);
}
}
|
package com.example.demo.controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@ControllerAdvice
public class GlobalExceptionHandler {
public String handleError(MultipartException exception, RedirectAttributes redirectAttributes)
{
redirectAttributes.addFlashAttribute("msg", exception.getCause().getMessage());
return " redirect:/status";
}
}
|
package com.bricenangue.nextgeneration.ebuycamer;
import android.net.Uri;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* Created by bricenangue on 29/11/2016.
*/
public class Publication {
PrivateContent privateContent;
PublicContent publicContent;
private CategoriesDeal categoriesDeal;
public Publication() {
}
public Publication(PrivateContent privateContent, PublicContent publicContent) {
this.privateContent = privateContent;
this.publicContent = publicContent;
}
public PrivateContent getPrivateContent() {
return privateContent;
}
public void setPrivateContent(PrivateContent privateContent) {
this.privateContent = privateContent;
}
public PublicContent getPublicContent() {
return publicContent;
}
public void setPublicContent(PublicContent publicContent) {
this.publicContent = publicContent;
}
public CategoriesDeal getCategoriesDeal() {
return categoriesDeal;
}
public void setCategoriesDeal(CategoriesDeal categoriesDeal) {
this.categoriesDeal = categoriesDeal;
}
}
|
/*
* #%L
* Over-the-air deployment library
* %%
* Copyright (C) 2012 SAP AG
* %%
* 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.
* #L%
*/
package com.sap.prd.mobile.ios.ota.lib;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import org.apache.commons.lang.StringUtils;
import org.sonatype.plexus.components.cipher.Base64;
public class LibUtils
{
public static URL buildUrl(String urlPrefix, String urlSuffix) throws MalformedURLException
{
String urlPrefixFixed = urlPrefix.trim();
while (urlPrefixFixed.endsWith("/")) { //Remove trailing '/'
urlPrefixFixed = urlPrefixFixed.substring(0, urlPrefixFixed.length() - 1);
}
URL url = new URL(urlPrefixFixed + "/" + urlSuffix);
return url;
}
/**
* Generates the link to the IPA file based on the referer to the HTML file, the used
* ipaClassifier and otaClassifier. If no classifiers are specified the IPA URL will have the same
* value as the referer, except of the file extension.
*
* @param referer
* Referer to the HTML file located next to the IPA file
* @param ipaClassifier
* classifier used in the IPA file. Can be null.
* @param otaClassifier
* classifier used in the OTA HTML file. Can be null.
* @return
* @throws MalformedURLException
*/
public static URL generateDirectIpaUrl(String referer, String ipaClassifier, String otaClassifier)
throws MalformedURLException
{
int idx = referer.lastIndexOf(".");
if (idx > 0 && idx > referer.length() - 6) {
String ipaUrl = referer.substring(0, idx) + ".ipa";
if (!StringUtils.isEmpty(otaClassifier)) {
if (!StringUtils.isEmpty(ipaClassifier)) {
ipaUrl = replaceLast(ipaUrl, "-" + otaClassifier, "-" + ipaClassifier);
}
else {
ipaUrl = replaceLast(ipaUrl, "-" + otaClassifier, "");
}
}
else {
if (!StringUtils.isEmpty(ipaClassifier)) {
ipaUrl = ipaUrl.substring(0, idx) + "-" + ipaClassifier + ".ipa";
}
}
return new URL(ipaUrl);
}
else {
throw new MalformedURLException("Referer does not end with a file (e.g. .htm)");
}
}
public static String replaceLast(String string, String searchString, String replaceString)
{
if (string == null || searchString == null || replaceString == null) {
throw new NullPointerException();
}
if (StringUtils.isEmpty(searchString)) {
return string;
}
if (StringUtils.countMatches(string, searchString) <= 1) {
return string.replace(searchString, replaceString);
}
else {
int idx = string.lastIndexOf(searchString);
return string.substring(0, idx) + string.substring(idx).replace(searchString, replaceString);
}
}
public static String urlEncode(String string)
{
if (string == null) {
return null;
}
try {
return URLEncoder.encode(string, "UTF-8");
}
catch (UnsupportedEncodingException e) {
throw new RuntimeException(e); //should never happen
}
}
public static String urlDecode(String string)
{
if (string == null) {
return null;
}
try {
return URLDecoder.decode(string, "UTF-8");
}
catch (UnsupportedEncodingException e) {
throw new RuntimeException(e); //should never happen
}
}
public static String encode(String string)
{
if (string == null) {
return null;
}
try {
byte[] bytes = string.getBytes("UTF-8");
byte[] base64Bytes = Base64.encodeBase64(bytes);
String base64String = new String(base64Bytes, "US-ASCII");
return URLEncoder.encode(base64String, "UTF-8");
}
catch (UnsupportedEncodingException e) {
throw new RuntimeException(e); //should never happen
}
}
public static String decode(String string)
{
if (string == null) {
return null;
}
try {
String urlDecodedString = URLDecoder.decode(string, "UTF-8");
byte[] urlDecodedBytes = urlDecodedString.getBytes("US-ASCII");
byte[] decodedBase64Bytes = Base64.decodeBase64(urlDecodedBytes);
return new String(decodedBase64Bytes, "UTF-8");
}
catch (UnsupportedEncodingException e) {
throw new RuntimeException(e); //should never happen
}
}
}
|
package leecode.other;
//设计hash表,拉链法
public class 设计哈希映射_706 {
class Node{
private int key;
private int value;
Node next;
public Node(int key,int value){
this.key=key;
this.value=value;
}
}
private final int size=1000;
private Node[]data;
public 设计哈希映射_706(){
data=new Node[size];
}
//put 、 remove 删除和更新都是用的pre去遍历,get查找用的cur遍历,其实好像无所谓?,
// 删除一定要用前一个!!更新最后跳出来要赋值next节点,也要用pre
public void put(int key,int value){
int hash=hash(key);
if(data[hash]==null){
data[hash]=new Node(-1,-1);//注意这个
data[hash].next=new Node(key,value);
}else {
Node pre=data[hash];//从头节点遍历
while (pre.next!=null){
if(pre.next.key==key){//原来就存在,则更新
pre.next.value=value;
return;
}
pre=pre.next;
}
pre.next=new Node(key,value);//没有,则添加,记住这个
}
}
public int get(int key){
int hash=hash(key);
if(data[hash]!=null){
Node cur=data[hash].next;
while (cur!=null){
if(cur.key==key){
return cur.value;
}
cur=cur.next;
}
}
return -1;
}
public void remove(int key){
int hash=hash(key);
if(data[hash]!=null){
Node pre=data[hash];
while (pre.next!=null){
if(pre.next.key==key){
Node delNode=pre.next;
pre.next=delNode.next;
delNode.next=null;
return;
}
pre=pre.next;
}
}
}
private int hash(int key){
return key%size;
}
}
|
package com.wanglu.movcat.repository;
import com.wanglu.movcat.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
public interface UserRepository extends JpaRepository<User, Integer>{
User findByTelOrEmail(String tel, String email);
User findByPasswordAndTelOrEmail(String password, String tel, String email);
User findByOpenId (String openId);
@Modifying
@Query(value = "INSERT INTO user (tel, name, password) VALUES (?1, ?2, ?3)", nativeQuery = true)
int saveTelUser(String tel, String name, String password);
}
|
package 배열생성;
public class 기본형배열 {
public static void main(String[] args) {
//int[] 변수명: int로 만들어진 배열을 가르키는 주소가 변수명에 들어간
int[] s = new int[10];
double[] s1 = new double[5];
String[] s2 = new String[100];
//배열은 자동으로 초기화시켜줌
System.out.println(s);
System.out.println(s[0]);
System.out.println(s1);
System.out.println(s2);
System.out.println(s2[0]);
}
}
|
package com.hit.neuruimall.model;
import org.apache.ibatis.type.Alias;
import java.util.Date;
@Alias("warning")
public class WarningModel {
private int warningId;
private String warningInfo;
private Date warningDate;
public int getWarningId() {
return warningId;
}
public void setWarningId(int warningId) {
this.warningId = warningId;
}
public String getWarningInfo() {
return warningInfo;
}
public void setWarningInfo(String warningInfo) {
this.warningInfo = warningInfo;
}
public Date getWarningDate() {
return warningDate;
}
public void setWarningDate(Date warningDate) {
this.warningDate = warningDate;
}
@Override
public String toString() {
return "WarningModel{" +
"warningId=" + warningId +
", warningInfo='" + warningInfo + '\'' +
", warningDate=" + warningDate +
'}';
}
}
|
package edu.monash.mymonashmate.activities;
import java.util.ArrayList;
import java.util.List;
import edu.monash.mymonashmate.R;
import edu.monash.mymonashmate.client.*;
import edu.monash.mymonashmate.entities.Course;
import edu.monash.mymonashmate.entities.Profile;
import edu.monash.mymonashmate.entities.Unit;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.Toast;
public class ProfileFragment extends Fragment{
public interface PostCreateViewListener{
public void OnCreateViewCompleted();
}
private PostCreateViewListener postCreateView;
public void setPostCreateViewListener(PostCreateViewListener listener){
postCreateView = listener;
}
MonashApplication app;
private LinearLayout unitParent;
private Button btnAddUnit;
private TableLayout layoutProfile;
private Boolean statusFlag = false;
private EditText editSurname;
private EditText editFirstname;
private EditText editNickname;
private Spinner spinCourse;
private EditText editLatitude;
private EditText editLongitude;
private EditText editNationality;
private EditText editNativeLang;
private EditText editSecondLang;
private EditText editSuburb;
private EditText editFavFood;
private EditText editFavMovie;
private EditText editFavProgLang;
private Spinner spinFavUnit;
private EditText editCurJob;
private EditText editPrevJob;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View rootView = inflater.inflate(R.layout.fragment_profile, container, false);
app = (MonashApplication)getActivity().getApplication();
layoutProfile = (TableLayout)rootView.findViewById(R.id.layout_profile);
editSurname = (EditText)rootView.findViewById(R.id.editSurname);
editFirstname = (EditText)rootView.findViewById(R.id.editFirstname);
editNickname = (EditText)rootView.findViewById(R.id.editNickname);
spinCourse = (Spinner)rootView.findViewById(R.id.spinCourse);
editLatitude = (EditText)rootView.findViewById(R.id.editLatitude);
editLongitude = (EditText)rootView.findViewById(R.id.editLongitude);
editNationality = (EditText)rootView.findViewById(R.id.editNationality);
editNativeLang = (EditText)rootView.findViewById(R.id.editNativelang);
editSecondLang = (EditText)rootView.findViewById(R.id.editSecondLang);
editSuburb = (EditText)rootView.findViewById(R.id.editSuburb);
editFavFood = (EditText)rootView.findViewById(R.id.editFavFood);
editFavMovie = (EditText)rootView.findViewById(R.id.editFavMovie);
editFavProgLang = (EditText)rootView.findViewById(R.id.editFavProgLang);
editCurJob = (EditText)rootView.findViewById(R.id.editCurJob);
editPrevJob = (EditText)rootView.findViewById(R.id.editPrevJob);
spinFavUnit = (Spinner)rootView.findViewById(R.id.spinFavUnit);
unitParent = (LinearLayout)rootView.findViewById(R.id.layout_unit_parent);
btnAddUnit = (Button)rootView.findViewById(R.id.addUnit);
// Course
List<String> listCourse = new ArrayList<String>();
listCourse.add("");
for(Course course : app.getAllCourses()){
listCourse.add(course.getName());
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_item, listCourse);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinCourse.setAdapter(dataAdapter);
spinCourse.setTag(0);
spinCourse.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// TODO Auto-generated method stub
spinCourse.setTag(pos - 1);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
spinCourse.setEnabled(false);
// Fav-Unit
List<String> listUnit = new ArrayList<String>();
listUnit.add("");
for(Unit unit : app.getAllUnits()){
listUnit.add(unit.getName());
}
ArrayAdapter<String> dataAdapterUnit = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_item, listUnit);
dataAdapterUnit.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinFavUnit.setAdapter(dataAdapterUnit);
spinFavUnit.setTag(0);
spinFavUnit.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// TODO Auto-generated method stub
spinFavUnit.setTag(pos - 1);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
spinFavUnit.setEnabled(false);
// Add Unit button
btnAddUnit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
addNewUnitView().setEnabled(true);
}
});
if(postCreateView != null)
postCreateView.OnCreateViewCompleted();
return rootView;
}
private Spinner addNewUnitView(){
final Spinner spin = new Spinner(getActivity());
spin.setTag(0);
List<String> listUnit = new ArrayList<String>();
listUnit.add("");
for(Unit item : app.getAllUnits()){
listUnit.add(item.getName());
}
final String removeString ="<<" + getString(R.string.removeUnit) + ">>";
listUnit.add(removeString);
ArrayAdapter<String> dataAdapterUnit = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_item, listUnit);
dataAdapterUnit.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(dataAdapterUnit);
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// TODO Auto-generated method stub
if(parent.getItemAtPosition(pos).toString().equalsIgnoreCase(removeString)){
removeUnit(spin);
return;
}
spin.setTag(pos - 1);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
unitParent.addView(spin, unitParent.getChildCount());
spin.setEnabled(false);
return spin;
}
private void removeUnit(Spinner spin){
unitParent.removeView(spin);
}
public void updateInterface(Profile profile) {
// update interface
if(null != profile){
editSurname.setText(profile.getSurname());
editFirstname.setText(profile.getFirstname());
editNickname.setText(profile.getNickname());
editLatitude.setText(String.valueOf(profile.getLatitude()));
editLongitude.setText(String.valueOf(profile.getLongitude()));
// Course
if(app.getAllCourses().size() > 0 && profile.getCourse() != null){
int pos = 0;
for(Course course : app.getAllCourses()){
if(course.getId() == profile.getCourse().getId()){
spinCourse.setSelection(pos + 1);
break;
}
++pos;
}
}
// Units
if (profile.getUnits().size() > 0) {
for (int i = 0; i < profile.getUnits().size(); ++i) {
Spinner spin = addNewUnitView();
int pos = 0;
for (Unit item : app.getAllUnits()) {
if (profile.getUnits().get(i).getId() == item.getId()) {
spin.setSelection(pos + 1);
break;
}
++pos;
}
}
}
btnAddUnit.setEnabled(true);
editNationality.setText(profile.getNationality());
editNativeLang.setText(profile.getNativLang());
editSecondLang.setText(profile.getSecondLang());
editSuburb.setText(profile.getSuburb());
editFavFood.setText(profile.getFavFood());
editFavMovie.setText(profile.getFavMovie());
editFavProgLang.setText(profile.getFavProgLang());
editPrevJob.setText(profile.getPrevJob());
editCurJob.setText(profile.getCurJob());
// FavUnit
if(app.getAllUnits().size() > 0 && profile.getFavUnit() != null){
int pos = 0;
for(Unit unit : app.getAllUnits()){
if(unit.getId() == profile.getFavUnit().getId()){
spinFavUnit.setSelection(pos + 1);
break;
}
++pos;
}
}
}
}
public void toggleEditStatus(){
// Enable interface view
statusFlag = !statusFlag;
for(int i=0; i<layoutProfile.getChildCount(); ++i){
TableRow row = (TableRow)layoutProfile.getChildAt(i);
for(int j=0; j<row.getChildCount(); ++j){
View cell = row.getChildAt(j);
cell.setEnabled(statusFlag);
if(cell instanceof LinearLayout){
LinearLayout container = (LinearLayout) cell;
for(int k=0; k<container.getChildCount(); ++k){
container.getChildAt(k).setEnabled(statusFlag);
}
}
}
}
if(statusFlag)
btnAddUnit.setVisibility(View.VISIBLE);
else
btnAddUnit.setVisibility(View.GONE);
}
public Profile collectInput(){
// validate input
String surname = editSurname.getText().toString();
if(surname.isEmpty()){
editSurname.setError("Surname is empty.");
editSurname.requestFocus();
return null;
}
String firstname = editFirstname.getText().toString();
if(firstname.isEmpty()){
editFirstname.setError("First name is empty.");
editFirstname.requestFocus();
return null;
}
if(spinCourse.getTag() == null || spinCourse.getTag().toString().isEmpty()){
Toast.makeText(getActivity(), "Please select a course.", Toast.LENGTH_SHORT).show();
spinCourse.requestFocus();
}
// latitude
Double latitude = 0d;
try {
latitude = Double.valueOf(editLatitude.getText().toString());
} catch (Exception e) {
// TODO: handle exception
editLatitude.setError("Incorrect latitude.");
editLatitude.requestFocus();
return null;
}
// longitude
Double longitude = 0d;
try {
longitude = Double.valueOf(editLongitude.getText().toString());
} catch (Exception e) {
// TODO: handle exception
editLongitude.setError("Incorrect longitude.");
editLongitude.requestFocus();
return null;
}
// disable interface view
toggleEditStatus();
// update to server
Profile profile = new Profile();
profile.setId(app.getClient().getUserid());
profile.setSurname(surname);
profile.setFirstname(firstname);
profile.setNickname(editNickname.getText().toString());
// course
if (spinCourse.getTag() != null) {
int pos = Integer.valueOf(spinCourse.getTag().toString());
if (pos >= 0 && pos < app.getAllCourses().size())
profile.setCourse(app.getAllCourses().get(pos));
}
// units
for (int i = 0; i < unitParent.getChildCount(); ++i) {
View child = unitParent.getChildAt(i);
if (child instanceof Spinner) {
int pos = Integer.valueOf(child.getTag().toString());
if (pos >= 0 && pos < app.getAllCourses().size()) {
Unit unit = app.getAllUnits().get(pos);
if (!profile.getUnits().contains(unit))
profile.getUnits().add(unit);
}
}
}
profile.setLatitude(latitude);
profile.setLongitude(longitude);
profile.setNationality(editNationality.getText().toString());
profile.setNativLang(editNativeLang.getText().toString());
profile.setSecondLang(editSecondLang.getText().toString());
profile.setSuburb(editSuburb.getText().toString());
profile.setFavFood(editFavFood.getText().toString());
profile.setFavMovie(editFavMovie.getText().toString());
profile.setFavProgLang(editFavProgLang.getText().toString());
// Fav unit
if (spinFavUnit.getTag() != null) {
int pos = Integer.valueOf(spinFavUnit.getTag().toString());
if (pos >= 0 && pos < app.getAllUnits().size())
profile.setFavUnit(app.getAllUnits().get(pos));
}
profile.setCurJob(editCurJob.getText().toString());
profile.setPrevJob(editPrevJob.getText().toString());
return profile;
}
}
|
package app.integro.sjbhs.adapters;
import android.content.Context;
import android.content.Intent;
import android.provider.CalendarContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import java.util.Calendar;
import app.integro.sjbhs.R;
import app.integro.sjbhs.models.Events;
public class EventsAdapter extends RecyclerView.Adapter<EventsAdapter.MyViewHolder> {
private final Context context;
private final ArrayList<Events> eventsArrayList;
public EventsAdapter(Context context, ArrayList<Events> eventsArrayList) {
this.context = context;
this.eventsArrayList = eventsArrayList;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.card_mun, parent, false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
final Events munsItem = eventsArrayList.get(position);
holder.tvN_Title.setText(munsItem.getTitle());
holder.tvDescription.setText(munsItem.getDescription());
Glide.with(context)
.load(munsItem.getImage())
.into(holder.ivNews);
holder.tvAddToCalendar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_INSERT);
intent.setType("vnd.android.cursor.item/event");
Calendar cal = Calendar.getInstance();
long startTime = cal.getTimeInMillis();
long endTime = cal.getTimeInMillis() + 60 * 60 * 1000;
intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, startTime);
intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endTime);
intent.putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, true);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(CalendarContract.Events.TITLE, "" + eventsArrayList.get(position).getTitle());
intent.putExtra(CalendarContract.Events.DESCRIPTION,""+eventsArrayList.get(position).getDescription());
context.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return eventsArrayList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
ImageView ivNews;
TextView tvN_Title;
TextView tvDescription;
TextView tvAddToCalendar;
public MyViewHolder(View itemView) {
super(itemView);
ivNews = (ImageView) itemView.findViewById(R.id.ivImage);
tvN_Title = (TextView) itemView.findViewById(R.id.tvTitle);
tvDescription = (TextView) itemView.findViewById(R.id.tvDescription);
tvAddToCalendar = (TextView) itemView.findViewById(R.id.tvAddToCalendar);
}
}
}
|
package com.liangtengyu.proxy;
import com.liangtengyu.handler.MyInvocationHandler;
import com.liangtengyu.service.Handler;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
/**
* @Author: lty
* @Date: 2021/2/3 14:58
*/
public class MyProxy<T> {
public T getProxy(T obj) {
MyInvocationHandler<T> tMyInvocationHandler = new MyInvocationHandler<>(obj);
return (T) Proxy.newProxyInstance(MyProxy.class.getClassLoader(), obj.getClass().getInterfaces(), tMyInvocationHandler);
}
}
|
package com.tangdi.production.mpnotice.service;
import java.util.Map;
/***
* 推送平台授权码接口
*
* @author sunhaining
*
*/
public interface PushAccessService {
/***
* 获取平台AccessToken
*
* @param plantForm
* @return
* @throws Exception
*/
public Map<String, Object> getAccessToken(String plantForm) throws Exception;
/***
* 修改平台AccessToken
*
* @param param
* @return
* @throws Exception
*/
public int modifyAccessToken(Map<String, Object> param) throws Exception;
public void process() throws Exception;
}
|
/*
4. Készítsünk egy osztályt, mely két hasábot térfogat szerint hasonlít össze, azaz megvalósítja a Comparator interészt! Az osztály segítéségvel a hasábokat növekvő sorrendbe rendezhetjük térfogat szerint a Collections.sort() metódussal!
*/
package polyhedra;
import java.util.Comparator;
public class ByVolume implements Comparator<Prism> {
public int compare(Prism p1, Prism p2) {
return (int)(p1.volume() - p2.volume());
}
}
|
package in.dailyhunt.internship.userprofile.repositories;
import in.dailyhunt.internship.userprofile.entities.Language;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface LanguageRepository extends JpaRepository<Language, Long> {
Optional<Language> findByName(String name);
Boolean existsByName(String name);
}
|
package com.podarbetweenus.Activities;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.podarbetweenus.BetweenUsConstant.Constant;
import com.podarbetweenus.Entity.LoginDetails;
import com.podarbetweenus.Entity.RecipentResult;
import com.podarbetweenus.R;
import com.podarbetweenus.Services.DataFetchService;
import com.podarbetweenus.Utility.AppController;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* Created by Administrator on 9/28/2015.
*/
public class EnterMessageActivity extends Activity implements View.OnClickListener{
//Linear Layout
LinearLayout lay_back_investment;
//EditText
EditText ed_category,ed_message_sub,ed_message_content;
//Button
Button btn_send_msg;
//ProgressDialog
ProgressDialog progressDialog;
//TextView
TextView tv_error_msg;
LoginDetails login_details;
DataFetchService dft;
public ArrayList<RecipentResult> receipent_dropdown_result = new ArrayList<RecipentResult>();
String msd_ID,clt_id,board_name,usl_id,check="1",toUslId,message,attachment_path,attachment_name,sender_name,date,
school_name,msg_subject,msg_body,receipent,versionName,announcementCount,behaviourCount,isStudentresource;
String[] select_receipent;
ArrayList<String> strings_receipent;
String ReceipentDropdownMethodName = "GetRecipentDropDownValue";
String EnterMessageMethod_name = "PostNewMessage";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.template_expandable_enter_message);
findViews();
init();
getIntentId();
AppController.listItemSelected = -1;
AppController.SentEnterDropdown = "true";
}
private void init() {
btn_send_msg.setOnClickListener(this);
dft = new DataFetchService(this);
login_details = new LoginDetails();
progressDialog = Constant.getProgressDialog(this);
ed_category.setOnClickListener(this);
}
private void findViews() {
//EditText
ed_category = (EditText) findViewById(R.id.ed_category);
ed_message_content = (EditText) findViewById(R.id.ed_message_content);
ed_message_sub = (EditText) findViewById(R.id.ed_message_sub);
//TextView
tv_error_msg = (TextView) findViewById(R.id.tv_error_msg);
//Button
btn_send_msg = (Button) findViewById(R.id.btn_send_msg);
}
private void getIntentId() {
Intent intent = getIntent();
board_name = intent.getStringExtra("board_name");
clt_id = intent.getStringExtra("clt_id");
msd_ID = intent.getStringExtra("msd_ID");
usl_id = intent.getStringExtra("usl_id");
school_name = intent.getStringExtra("School_name");
versionName = intent.getStringExtra("version_name");
announcementCount = intent.getStringExtra("annpuncement_count");
behaviourCount = intent.getStringExtra("behaviour_count");
isStudentresource = intent.getStringExtra("isStudentResource");
AppController.versionName = versionName;
AppController.clt_id = clt_id;
AppController.msd_ID = msd_ID;
AppController.usl_id = usl_id;
AppController.school_name = school_name;
}
@Override
public void onClick(View v) {
if(v==lay_back_investment)
{
if(AppController.SiblingActivity.equalsIgnoreCase("true"))
{
Intent back = new Intent(EnterMessageActivity.this,Profile_Sibling.class);
AppController.OnBackpressed = "false";
AppController.clt_id = clt_id;
AppController.msd_ID = msd_ID;
AppController.usl_id = usl_id;
AppController.school_name = school_name;
back.putExtra("clt_id", AppController.clt_id);
back.putExtra("msd_ID", AppController.msd_ID);
back.putExtra("usl_id", AppController.usl_id);
back.putExtra("board_name",board_name);
back.putExtra("isStudentResource",isStudentresource);
back.putExtra("School_name", AppController.school_name);
back.putExtra("version_name", AppController.versionName);
startActivity(back);
}
else {
Intent back = new Intent(EnterMessageActivity.this,ProfileActivity.class);
AppController.OnBackpressed = "false";
AppController.clt_id = clt_id;
AppController.msd_ID = msd_ID;
AppController.usl_id = usl_id;
AppController.school_name = school_name;
back.putExtra("clt_id", AppController.clt_id);
back.putExtra("msd_ID", AppController.msd_ID);
back.putExtra("usl_id", AppController.usl_id);
back.putExtra("board_name",board_name);
back.putExtra("isStudentResource",isStudentresource);
back.putExtra("School_name", AppController.school_name);
back.putExtra("version_name", AppController.versionName);
startActivity(back);
}
}
else if(v==ed_category){
//Call Webservice for Receipent dropdown
CallReceipentDropdownWebservice(clt_id, msd_ID);
}
else if (v==btn_send_msg){
InputMethodManager inputMethodManager = (InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
//Webservcie call for view Messages
enterMessage();
}
}
private void CallReceipentDropdownWebservice(String clt_id,String msd_ID) {
if(dft.isInternetOn()==true) {
if (!progressDialog.isShowing()) {
progressDialog.show();
}
}
else{
progressDialog.dismiss();
}
dft.getreceipentdatedeopdown(clt_id, msd_ID, ReceipentDropdownMethodName, Request.Method.POST,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
try {
login_details = (LoginDetails) dft.GetResponseObject(response, LoginDetails.class);
if (login_details.Status.equalsIgnoreCase("1")) {
strings_receipent = new ArrayList<String>();
try {
for (int i = 0; i < login_details.RecipentResult.size(); i++) {
strings_receipent.add(login_details.RecipentResult.get(i).name.toString());
select_receipent = new String[strings_receipent.size()];
select_receipent = strings_receipent.toArray(select_receipent);
}
} catch (Exception e) {
e.printStackTrace();
}
selectReceipent(select_receipent);
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
} else {
Constant.showOkPopup(EnterMessageActivity.this, "Please Check Internet Connectivity", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//Show error or whatever...
Log.d("LoginActivity", "ERROR.._---" + error.getCause());
}
});
}
private void selectReceipent( final String[] select_receipent) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
View convertView = (View) inflater.inflate(R.layout.dialog_list, null);
alertDialog.setView(convertView);
alertDialog.setTitle("Select Recipient");
final ListView select_list = (ListView) convertView.findViewById(R.id.select_list);
alertDialog.setItems(select_receipent, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
// Do something with the selection
ed_category.setText(select_receipent[item]);
dialog.dismiss();
String selectedreceipent = select_receipent[item];
Log.e("RECEIPENT", selectedreceipent);
toUslId = getIDfromReceipent(selectedreceipent);
Log.e("TOUSLID", toUslId);
}
});
alertDialog.show();
}
private void enterMessage() {
msg_subject = ed_message_sub.getText().toString();
msg_body = ed_message_content.getText().toString();
receipent = ed_category.getText().toString();
if(receipent.equalsIgnoreCase("")){
tv_error_msg.setText("Please Select Receipent");
tv_error_msg.setVisibility(View.VISIBLE);
}
else if(msg_subject.equalsIgnoreCase("")){
tv_error_msg.setText("Please Enter Message Subject");
tv_error_msg.setVisibility(View.VISIBLE);
}
else if(msg_body.equalsIgnoreCase("")){
tv_error_msg.setText("Please Enter Message");
tv_error_msg.setVisibility(View.VISIBLE);
}
else {
callEnterMessagewebservcie(clt_id, msg_subject,msg_body,usl_id, msd_ID, toUslId);
ed_message_content.setText("");
ed_message_sub.setText("");
ed_category.setText("");
}
}
private String getIDfromReceipent(String selectedUslId) {
String id = "0";
for(int i=0;i<login_details.RecipentResult.size();i++) {
if(login_details.RecipentResult.get(i).name.equalsIgnoreCase(selectedUslId)){
id= login_details.RecipentResult.get(i).usl_Id;
}
}
return id;
}
private void callEnterMessagewebservcie(String clt_id,String msg_subject,String msg_body,String usl_id,String msd_ID,String toUslId) {
if(!progressDialog.isShowing()) {
progressDialog.show();
}
dft.getEnterMessages(clt_id,msg_subject,msg_body,usl_id, msd_ID,toUslId, EnterMessageMethod_name, Request.Method.POST,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
try {
tv_error_msg.setVisibility(View.GONE);
login_details = (LoginDetails) dft.GetResponseObject(response, LoginDetails.class);
if (login_details.Status.equalsIgnoreCase("1")) {
tv_error_msg.setTextColor(getResources().getColor(R.color.green));
tv_error_msg.setText(login_details.StatusMsg);
tv_error_msg.setVisibility(View.VISIBLE);
Intent i = new Intent(EnterMessageActivity.this,DashboardActivity.class);
Intent intent = getIntent();
board_name = intent.getStringExtra("board_name");
String clt_id = intent.getStringExtra("clt_id");
String msd_ID = intent.getStringExtra("msd_ID");
String usl_id = intent.getStringExtra("usl_id");
String school_name = intent.getStringExtra("School_name");
announcementCount = intent.getStringExtra("annpuncement_count");
behaviourCount = intent.getStringExtra("behaviour_count");
AppController.clt_id = clt_id;
AppController.msd_ID = msd_ID;
AppController.usl_id = usl_id;
AppController.school_name = school_name;
AppController.clt_id = clt_id;
AppController.msd_ID = msd_ID;
i.putExtra("isStudentResource",isStudentresource);
AppController.usl_id = usl_id;
AppController.school_name = school_name;
AppController.parentMessageSent = "true";
i.putExtra("clt_id", AppController.clt_id);
i.putExtra("msd_ID", AppController.msd_ID);
i.putExtra("usl_id", AppController.usl_id);
i.putExtra("board_name", board_name);
i.putExtra("version_name", AppController.versionName);
i.putExtra("School_name", AppController.school_name);
i.putExtra("annpuncement_count",announcementCount);
i.putExtra("behaviour_count",behaviourCount);
startActivity(i);
} else if (login_details.Status.equalsIgnoreCase("0")) {
tv_error_msg.setText("Error!!!");
tv_error_msg.setVisibility(View.VISIBLE);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//Show error or whatever...
Log.d("EnterMessageActivity", "ERROR.._---" + error.getCause());
}
});
}
@Override
public void onBackPressed() {
super.onBackPressed();
if(AppController.SiblingActivity.equalsIgnoreCase("true"))
{
Intent back = new Intent(EnterMessageActivity.this,Profile_Sibling.class);
AppController.OnBackpressed = "false";
AppController.clt_id = clt_id;
AppController.msd_ID = msd_ID;
AppController.usl_id = usl_id;
AppController.school_name = school_name;
back.putExtra("clt_id", AppController.clt_id);
back.putExtra("msd_ID", AppController.msd_ID);
back.putExtra("usl_id", AppController.usl_id);
back.putExtra("board_name",board_name);
back.putExtra("version_name", AppController.versionName);
back.putExtra("School_name", AppController.school_name);
back.putExtra("isStudentResource",isStudentresource);
startActivity(back);
}
else {
Intent back = new Intent(EnterMessageActivity.this,ProfileActivity.class);
AppController.OnBackpressed = "false";
AppController.clt_id = clt_id;
AppController.msd_ID = msd_ID;
AppController.usl_id = usl_id;
AppController.school_name = school_name;
back.putExtra("clt_id", AppController.clt_id);
back.putExtra("msd_ID", AppController.msd_ID);
back.putExtra("usl_id", AppController.usl_id);
back.putExtra("board_name",board_name);
back.putExtra("version_name", AppController.versionName);
back.putExtra("School_name", AppController.school_name);
back.putExtra("isStudentResource",isStudentresource);
startActivity(back);
}
}
}
|
package cn.canlnac.onlinecourse.data.repository.datasource;
import cn.canlnac.onlinecourse.data.entity.CommentEntity;
import cn.canlnac.onlinecourse.data.entity.ReplyEntity;
import rx.Observable;
/**
* 评论数据储存.
*/
public interface CommentDataStore {
/** 点赞评论 */
Observable<Void> likeComment(int commentId);
/** 取消点赞评论 */
Observable<Void> unlikeComment(int commentId);
/** 获取指定评论 */
Observable<CommentEntity> getComment(int commentId);
/** 获取指定回复 */
Observable<ReplyEntity> getReply(int replyId);
}
|
package com.yqwl.service.impl;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.yqwl.dao.WantedMapper;
import com.yqwl.pojo.Wanted;
import com.yqwl.service.WantedService;
/**
*
*
* @ClassName: WantedServiceImpl
* @description 招聘信息表的Service实现层
*
* @author dujiawei
* @createDate 2019年3月28日
*/
@Service
@Transactional(rollbackFor = { Exception.class })
public class WantedServiceImpl implements WantedService {
@Resource
private WantedMapper wantedMapper;
/**
* @Title: listWanted
* @description 招聘信息列表
* @param page ,limit
* @return Map<String, Object>
* @author dujiawei
* @throws Exception
* @createDate 2019年3月28日
*/
@Override
public Map<String, Object> listWanted(Integer page, Integer limit) throws Exception {
// TODO Auto-generated method stub
int resultCount = wantedMapper.countWanted();
int beginPageIndex = ((page - 1) * limit);
List<Wanted> result = wantedMapper.listWanted(beginPageIndex, limit);
Map<String, Object> map = new HashMap<String,Object>();
map.put("count", resultCount); //数量
map.put("list", result);
return map;
}
/**
* @Title: countWanted
* @description 招聘信息的数据条数
* @return int
* @author dujiawei
* @createDate 2019年3月28日
*/
@Override
public int countWanted() throws Exception {
// TODO Auto-generated method stub
return wantedMapper.countWanted();
}
/**
* @Title: saveWanted
* @description 新增招聘信息
* @param wanted
* @return int
* @author dujiawei
* @createDate 2019年3月28日
*/
@Override
public int saveWanted(Wanted wanted) throws Exception {
// TODO Auto-generated method stub
return wantedMapper.saveWanted(wanted);
}
/**
* @Title: updateWanted
* @description 修改招聘信息
* @param wanted
* @return int
* @author dujiawei
* @createDate 2019年3月28日
*/
@Override
public int updateWanted(Wanted wanted) throws Exception {
// TODO Auto-generated method stub
return wantedMapper.updateWanted(wanted);
}
/**
* @Title: changeWantedState
* @description 修改招聘信息状态
* @param wanted
* @return int
* @author dujiawei
* @createDate 2019年3月28日
*/
@Override
public int changeWantedState(Wanted wanted) throws Exception {
// TODO Auto-generated method stub
return wantedMapper.changeWantedState(wanted);
}
/**
* @Title: removeWanted
* @description 删除招聘信息(硬删除)
* @param id
* @return int
* @author dujiawei
* @createDate 2019年3月28日
*/
@Override
public int removeWanted(BigInteger id) throws Exception {
// TODO Auto-generated method stub
return wantedMapper.removeWanted(id);
}
/**
* @Title: getWantedById
* @description 通过id查询招聘信息
* @param wanted
* @return Wanted
* @author dujiawei
* @createDate 2019年3月28日
*/
@Override
public Wanted getWantedById(Wanted wanted) {
// TODO Auto-generated method stub
return wantedMapper.getWantedById(wanted);
}
/**
* @Title: showListWanted
* @description 官网显示的招聘信息(状态为上架的)
* @return List<Wanted>
* @author dujiawei
* @createDate 2019年3月28日
*/
@Override
public List<Wanted> showListWanted() {
// TODO Auto-generated method stub
return wantedMapper.showListWanted();
}
/**
* @Title: getWantedByjob
* @description 通过职位名称查询招聘信息
* @param wanted
* @return List<Wanted>
* @author dujiawei
* @createDate 2019年3月29日
*/
@Override
public List<Wanted> getWantedByjob(Wanted wanted) {
// TODO Auto-generated method stub
return wantedMapper.getWantedByjob(wanted);
}
}
|
package master.app.demomvp.utils;
public class AppData {
public static String USERNAME = "ck_290ad50655c4d22546d084600b3deea5fa6b18a3";
//
public static String APP_SECRET= "cs_8ec0151f884bc7cac6220acbb04ac24b82c6f869";
public static final String BASE_URL="https://www.deveshsarees.com/wp-json/wc/v3/";
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.clerezza.sparql.query;
import java.util.List;
/**
* <p>This interface represents a SPARQL query which contains a specification
* of solution modifiers: GROUP BY, HAVING, ORDER BY, OFFSET, and LIMIT.</p>
*
* @see <a href="http://www.w3.org/TR/sparql11-query/#aggregates">
* SPARQL 1.1 Query Language: 11 Aggregates</a>
* and
* @see <a href="http://www.w3.org/TR/sparql11-query/#solutionModifiers">
* SPARQL 1.1 Query Language: 15 Solution Sequences and Modifiers</a>
*
* @author hasan
*/
public interface QueryWithSolutionModifier extends Query {
public List<Expression> getGroupConditions();
public List<Expression> getHavingConditions();
/**
* <p>Gets the list of required ordering conditions in decreasing ordering
* priority.</p>
* @see <a href="http://www.w3.org/TR/rdf-sparql-query/#modOrderBy">
* SPARQL Query Language: 9.1 ORDER BY</a>
* @return A list of {@link OrderCondition}s, in order of priority.
*/
public List<OrderCondition> getOrderConditions();
/**
* <p>Gets the numeric offset of the first row to be returned by the query.
* The default offset is 0, meaning to start at the beginning.</p>
* @see <a href="http://www.w3.org/TR/rdf-sparql-query/#modOffset">
* SPARQL Query Language: 9.4 OFFSET</a>
* @return The number of rows to skip in the result.
*/
public int getOffset();
/**
* <p>Gets the maximum number of results to be returned by the query.
* A limit of -1 means no limit (return all results).
* A limit of 0 means that no results should be returned.</p>
* @see <a href="http://www.w3.org/TR/rdf-sparql-query/#modResultLimit">
* SPARQL Query Language: 9.5 LIMIT</a>
* @return The maximum number of rows to returned by the query.
*/
public int getLimit();
}
|
class Solution {
public int[] solution(long n) {
int[] answer = {};
String size = String.valueOf(n);
answer = new int[size.length()];
int i=0;
while(true) {
if(n == 0) break;
answer[i++] = (int) n%10;
n /= 10;
}
return answer;
}
}
|
package org.scribe.builder.api;
import org.scribe.extractors.AccessTokenExtractor;
import org.scribe.extractors.JsonTokenExtractor;
import org.scribe.model.*;
import org.scribe.utils.OAuthEncoder;
/**
* OAuth API for Flickr.
*
* @author Darren Greaves
* @see <a href="http://www.flickr.com/services/api/">Flickr API</a>
*/
public class VimeoApi20 extends DefaultApi20
{
private static final String AUTHORIZE_URL = "https://api.vimeo.com/oauth/authorize?client_id=%s&redirect_uri=%s&response_type=code";
private static final String SCOPED_AUTHORIZE_URL = String.format("%s&scope=%%s", AUTHORIZE_URL);
@Override
public String getAccessTokenEndpoint()
{
return "https://api.vimeo.com/oauth/access_token";
}
@Override
public String getAuthorizationUrl(OAuthConfig config)
{
if(config.hasScope())// Appending scope if present
{
return String.format(SCOPED_AUTHORIZE_URL, config.getApiKey(), OAuthEncoder.encode(config.getCallback()), OAuthEncoder.encode(config.getScope()));
}
else
{
return String.format(AUTHORIZE_URL, config.getApiKey(), OAuthEncoder.encode(config.getCallback()));
}
}
@Override
public AccessTokenExtractor getAccessTokenExtractor()
{
return new JsonTokenExtractor();
}
}
|
package com.yingying.distributed.hw2.distributedIO.cassandraIO;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;
import com.yingying.distributed.hw2.distributedIO.DIOAction;
public abstract class CassandraAction extends DIOAction {
protected Session session;
public CassandraAction() {
}
public CassandraAction(Cluster cluster) {
session = cluster.connect("keyspace_user20");
}
}
|
public class Main {
public static void main(String[] args) {
Pessoa pessoas[] = new Pessoa[5];
Estudante estudante1 = new Estudante("Luiz","Recife PE");
Estudante estudante2 = new Estudante("José","Olinda PE");
Estudante estudante3 = new Estudante("Karla","Recife PE");
Professor professor1 = new Professor("Rafaela", "Olinda PE");
Professor professor2 = new Professor("Antonio", "Recife PE");
estudante1.addCursoNota("Programação", 9);
estudante1.addCursoNota("POO", 10);
estudante2.addCursoNota("Banco de Dados", 8);
estudante2.addCursoNota("Sistemas Operacionais", 10);
estudante3.addCursoNota("Programação", 10);
estudante3.addCursoNota("Banco de Dados", 9);
professor1.addCurso("Programação");
professor1.addCurso("POO");
professor2.addCurso("Banco de Dados");
professor2.addCurso("Sistemas Operacionais");
pessoas[0] = estudante1;
pessoas[1] = estudante2;
pessoas[2] = estudante3;
pessoas[3] = professor1;
pessoas[4] = professor2;
for (Pessoa p : pessoas) {
System.out.println(p);
}
metodo(pessoas);
}
public static void metodo(Pessoa[] p) {
System.out.println("Curso: Programação");
System.out.println("Professor: "+p[3].nome);
System.out.println("Alunos: ");
System.out.println(p[0].nome);
System.out.println(p[2].nome);
}
}
|
/**
*
*/
package com.wonders.task.todoItem.service;
import java.util.List;
import com.wonders.task.todoItem.model.bo.TodoItem;
/**
* @ClassName: TodoItemService
* @Description: TODO(这里用一句话描述这个类的作用)
* @author zhoushun
* @date 2013-1-22 下午03:50:41
*
*/
public interface TodoItemService {
public void saveBatch(List<TodoItem> list);
@SuppressWarnings("unchecked")
public Object load(String id,Class clazz) ;
public int deleteBatch();
}
|
/**************************************************************************
* Developed by Language Technologies Institute, Carnegie Mellon University
* Written by Richard Wang (rcwang#cs,cmu,edu)
**************************************************************************/
package com.rcwang.seal.rank;
import java.util.Set;
import java.util.Map.Entry;
import org.apache.log4j.Logger;
import com.rcwang.seal.expand.Entity;
import com.rcwang.seal.expand.EntityList;
import com.rcwang.seal.expand.Wrapper.EntityLiteral;
import com.rcwang.seal.fetch.DocumentSet;
import com.rcwang.seal.rank.Graph.EdgeSet;
import com.rcwang.seal.rank.Graph.Node;
import com.rcwang.seal.rank.Graph.NodeSet;
import com.rcwang.seal.util.Cell;
import com.rcwang.seal.util.MatrixUtil;
import com.rcwang.seal.util.SparseMatrix;
import com.rcwang.seal.util.SparseVector;
import com.rcwang.seal.util.StringFactory;
import com.rcwang.seal.util.StringFactory.SID;
public abstract class GraphRanker extends Ranker {
public static final double DEFAULT_CONVERGE_THRESHOLD = 1e-3;
public static final int DEFAULT_NUM_ITERATION = 50;
public static final boolean DEFAULT_DISABLE_WALK = false;
public static final int NUM_ITER_TO_OUTPUT_LEVEL = 10;
public static Logger log = Logger.getLogger(GraphRanker.class);
private Graph graph;
private int numIteration;
private double damper;
private double convergeThreshold;
private boolean useRelation;
private boolean useRestart;
private boolean disableWalk;
public static Graph toGraph(DocumentSet documentSet) {
Graph graph = new Graph();
graph.load(documentSet);
return graph;
}
public GraphRanker() {
super();
graph = new Graph();
setNumIteration(DEFAULT_NUM_ITERATION);
setConvergeThreshold(DEFAULT_CONVERGE_THRESHOLD);
setDisableWalk(DEFAULT_DISABLE_WALK);
}
public void clear() {
super.clear();
graph.clear();
}
public double getConvergeThreshold() {
return convergeThreshold;
}
public double getDamper() {
return damper;
}
public Graph getGraph() {
return graph;
}
public int getNumIteration() {
return numIteration;
}
public boolean isDisableWalk() {
return disableWalk;
}
public boolean isUseRelation() {
return useRelation;
}
public boolean isUseRestart() {
return useRestart;
}
public void load(EntityList entities, DocumentSet documentSet) {
// load documents into graph
graph.load(documentSet);
if (disableWalk) return;
// build transition matrix from graph
SparseMatrix matrix = makeMatrix(graph);
// make initial state vector
SparseVector stateVector = makeInitVector(matrix.getColumnIDs());
Set<SID> startNodes = stateVector.keySet();
entities.clearWeight(getRankerID());
for (int numIter = 0; numIter < numIteration; numIter++) {
SparseVector sv = MatrixUtil.dotProduct(matrix, stateVector.normalize());
if (damper < 1) {
for (Entry<SID, Cell> entry : sv.entrySet()) {
Cell cell = entry.getValue();
double prevalue = cell.value;
cell.value *= damper;
if (useRestart) {
if (startNodes.contains(entry.getKey()))
cell.value += (1-damper) / startNodes.size();
} else cell.value += (1-damper) / sv.size();
log.debug(String.format("gww\t%d\t%s\t%g\t%g",numIter,entry.getKey().toLiteral().toString(),prevalue,cell.value));
}
}
double euclidDistScore = MatrixUtil.euclideanDistance(sv, stateVector);
stateVector = sv;
if (euclidDistScore < convergeThreshold) {
log.info("[Level " + numIter + "] Converged!!!");
break;
}
if (numIter != 0 && numIter % NUM_ITER_TO_OUTPUT_LEVEL == 0)
log.info("[Level " + numIter + "] " + euclidDistScore);
}
// insert weights into each node of the graph
graph.assignWeights(stateVector);
// transfer weights from state vector to entity list
transferWeights(stateVector, entities, Graph.CONTENT_NODE_NAME);
}
public void setConvergeThreshold(double convergeThreshold) {
this.convergeThreshold = convergeThreshold;
}
public void setDamper(double damper) {
this.damper = damper;
}
public void setDisableWalk(boolean disableWalk) {
this.disableWalk = disableWalk;
}
public void setNumIteration(int numIteration) {
this.numIteration = numIteration;
}
public void setUseRelation(boolean useRelation) {
this.useRelation = useRelation;
}
public void setUseRestart(boolean useRestart) {
this.useRestart = useRestart;
}
private SparseVector makeInitVector(Set<SID> ids) {
SparseVector stateVector = new SparseVector();
if (seedDist.isEmpty()) {
// if no seeds specified, start from all nodes
for (SID id : ids)
stateVector.put(id, 1.0);
} else {
// assign probabilities to seeds in state vector
for (Entry<SID, Cell> entry : seedDist) {
SID id = entry.getKey();
stateVector.put(id.toLower(), seedDist.getProbability(id));
}
}
return stateVector;
}
private SparseMatrix makeMatrix(Graph graph) {
SparseMatrix matrix = new SparseMatrix();
NodeSet toNodeSet = new NodeSet();
// start making transition matrix
for (Node fromNode : graph.getAllNodes()) {
if (fromNode == null) {
log.error("Node " + fromNode + " is null!");
continue;
}
toNodeSet.clear();
EdgeSet edgeSet = graph.getEdges(fromNode);
double linkProb = 1.0 / edgeSet.size();
for (String edgeLabel : edgeSet) {
NodeSet toNodes = graph.followEdge(fromNode, edgeLabel);
if (useRelation) {
updateMatrix(matrix, fromNode, toNodes, edgeLabel, linkProb);
} else {
toNodeSet.addAll(toNodes);
}
}
if (!useRelation)
updateMatrix(matrix, fromNode, toNodeSet, null, linkProb);
}
return matrix;
}
private void transferWeights(SparseVector from, EntityList to, String type) {
for (Entry<SID, Cell> entry : from) {
SID id = entry.getKey();
Node node = graph.getNode(id);
if (node == null) continue;
if (!node.getType().equals(type)) continue;
EntityLiteral s = id.toLiteral();
double w = entry.getValue().value;
Entity entity = to.add(s);
if (entity == null) continue;
entity.setWeight(getRankerID(), w);
}
}
private void updateMatrix(SparseMatrix matrix, Node fromNode, NodeSet toNodes,
String linkLabel, double linkProb) {
double nodeProb = 1.0 / toNodes.size();
for (Node toNode : toNodes)
matrix.add(fromNode.getID(), toNode.getID(), linkProb * nodeProb);
}
}
|
package fr.lteconsulting.commandes;
import java.util.Collections;
import java.util.List;
import fr.lteconsulting.Commande;
import fr.lteconsulting.modele.Bibliotheque;
import fr.lteconsulting.modele.Disque;
public class AffichageDisquesParNom implements Commande
{
private Bibliotheque bibliotheque;
public AffichageDisquesParNom( Bibliotheque bibliotheque )
{
this.bibliotheque = bibliotheque;
}
@Override
public String getNom()
{
return "Afficher les disques par nom";
}
@Override
public void executer()
{
List<Disque> disques = bibliotheque.getDisques();
Collections.sort( disques, new ComparateurDisqueParNom() );
for( Disque disque : disques )
disque.afficher( false );
}
}
|
package org.rebioma.client.gxt3.treegrid;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NativeEvent;
import com.sencha.gxt.data.shared.Store;
import com.sencha.gxt.data.shared.TreeStore;
import com.sencha.gxt.widget.core.client.grid.Grid;
import com.sencha.gxt.widget.core.client.grid.GridSelectionModel;
public class CheckboxTreeGridSelectionModel<M> extends GridSelectionModel<M> {
protected CheckboxTreeGrid<M> tree;
protected TreeStore<M> treeStore;
@Override
public void bind(Store<M> store) {
super.bind(store);
if (store instanceof TreeStore<?>) {
treeStore = (TreeStore<M>) store;
} else {
treeStore = null;
}
}
@Override
public void bindGrid(Grid<M> grid) {
super.bindGrid(grid);
if (grid instanceof CheckboxTreeGrid<?>) {
tree = (CheckboxTreeGrid<M>) grid;
treeStore = tree.getTreeStore();
} else {
tree = null;
}
}
@Override
protected void onKeyLeft(NativeEvent ce) {
if (Element.is(ce.getEventTarget())
&& !grid.getView().isSelectableTarget(Element.as(ce.getEventTarget()))) {
return;
}
super.onKeyLeft(ce);
ce.preventDefault();
boolean leaf = tree.isLeaf(getLastFocused());
if (!leaf && tree.isExpanded(getLastFocused())) {
tree.setExpanded(getLastFocused(), false);
} else if (!leaf) {
M parent = treeStore.getParent(getLastFocused());
if (parent != null) {
select(parent, false);
}
} else if (leaf) {
M parent = treeStore.getParent(getLastFocused());
if (parent != null) {
select(parent, false);
}
}
}
@Override
protected void onKeyRight(NativeEvent ce) {
if (Element.is(ce.getEventTarget())
&& !grid.getView().isSelectableTarget(Element.as(ce.getEventTarget()))) {
return;
}
super.onKeyRight(ce);
ce.preventDefault();
if (!tree.isLeaf(getLastFocused()) && !tree.isExpanded(getLastFocused())) {
tree.setExpanded(getLastFocused(), true);
}
}
}
|
package com.airline.airline.airlinereseservation.repo;
import com.airline.airline.airlinereseservation.model.Booking;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface BookingRepo extends JpaRepository<Booking, Long> {
}
|
package com.polsl.edziennik.desktopclient.view.teacher;
import java.awt.BorderLayout;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.concurrent.ExecutionException;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import com.polsl.edziennik.delegates.DelegateFactory;
import com.polsl.edziennik.delegates.TeacherDelegate;
import com.polsl.edziennik.delegates.exceptions.DelegateException;
import com.polsl.edziennik.desktopclient.controller.utils.LangManager;
import com.polsl.edziennik.desktopclient.controller.utils.workers.Worker;
import com.polsl.edziennik.desktopclient.model.comboBoxes.GroupComboBoxModel;
import com.polsl.edziennik.desktopclient.model.tables.GroupTableModel;
import com.polsl.edziennik.desktopclient.model.tables.StudentTableModel;
import com.polsl.edziennik.desktopclient.properties.Properties;
import com.polsl.edziennik.desktopclient.view.common.panels.button.StudentButtonPanel;
import com.polsl.edziennik.desktopclient.view.common.panels.filter.DefaultFilterPanel;
import com.polsl.edziennik.desktopclient.view.common.panels.tablePanels.StudentTablePanel;
import com.polsl.edziennik.desktopclient.view.student.StudentSummary;
import com.polsl.edziennik.modelDTO.group.GroupDTO;
import com.polsl.edziennik.modelDTO.person.StudentDTO;
public class Summary extends JPanel {
private StudentButtonPanel buttonPanel;
private JSplitPane splitPane;
private StudentTablePanel tablePanel;
private GroupComboBoxModel comboModel;
private StudentTableModel tableModel;
private ResourceBundle bundle = LangManager.getResource(Properties.Component);
private DefaultFilterPanel filter;
public Summary() {
setLayout(new BorderLayout());
tableModel = new StudentTableModel();
comboModel = new GroupComboBoxModel();
filter = new DefaultFilterPanel(tableModel, comboModel, bundle.getString("studentNamesHint"), "lastName",
bundle.getString("groupHint"), "group");
DataProvider dataProvider = new DataProvider("get");
dataProvider.execute();
dataProvider.startProgress();
buttonPanel = new StudentButtonPanel();
tablePanel = new StudentTablePanel(tableModel, comboModel, filter, bundle.getString("StudentFrameTitle"),
buttonPanel, null);
tablePanel.getSelectionModel().addListSelectionListener(new StudentTableSelectionListener());
setWidths();
splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
splitPane.setDividerLocation(0.5);
splitPane.setDividerSize(1);
splitPane.add(tablePanel);
add(splitPane);
setVisible(true);
}
public void setWidths() {
tablePanel.getColumnModel().getColumn(0).setPreferredWidth(30);
for (int i = 1; i < 4; i++) {
tablePanel.getColumnModel().getColumn(i).setPreferredWidth(290);
}
}
private class StudentTableSelectionListener implements ListSelectionListener {
@Override
public void valueChanged(ListSelectionEvent e) {
int selected = tablePanel.getSelected();
if (selected > -1) {
StudentDTO s = tableModel.get(tablePanel.getSelected());
new StudentSummary(s.getId());
}
}
}
private class DataProvider extends Worker<List<StudentDTO>> {
public DataProvider(String operationType) {
super(operationType);
}
@Override
protected List<StudentDTO> doInBackground() throws Exception {
TeacherDelegate teacher = DelegateFactory.getTeacherDelegate();
return teacher.getAllStudentsWithGroups();
}
@Override
public void done() {
stopProgress();
try {
tableModel.setModel(get());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class GroupsDataProvider extends Worker<List<GroupDTO>> {
private GroupComboBoxModel comboModel;
private GroupTableModel tableModel;
private GroupComboBoxModel comboPreviewModel;
private JComboBox comboBox;
private JComboBox comboBoxPreview;
public GroupsDataProvider(GroupTableModel tableModel) {
super("get");
this.tableModel = tableModel;
}
public GroupsDataProvider(GroupComboBoxModel comboModel, JComboBox comboBox) {
super("get");
this.comboModel = comboModel;
this.comboBox = comboBox;
}
public GroupsDataProvider(GroupComboBoxModel comboModel, JComboBox comboBox,
GroupComboBoxModel comboPreviewModel) {
super("get");
this.comboModel = comboModel;
this.comboBox = comboBox;
this.comboPreviewModel = comboPreviewModel;
}
public GroupsDataProvider(GroupComboBoxModel comboModel, GroupComboBoxModel comboPreviewModel,
JComboBox comboBox, JComboBox comboBoxPreview) {
super("get");
this.comboModel = comboModel;
this.comboPreviewModel = comboPreviewModel;
this.comboBox = comboBox;
this.comboBoxPreview = comboBoxPreview;
}
@Override
protected List<GroupDTO> doInBackground() {
startProgress();
TeacherDelegate teacher;
try {
teacher = DelegateFactory.getTeacherDelegate();
return teacher.getAllGroups();
} catch (DelegateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
public void done() {
stopProgress();
try {
if (tableModel != null) {
tableModel.setModel(get());
} else if (comboModel != null) {
comboModel.setModel(new ArrayList<GroupDTO>(get()));
GroupDTO g = new GroupDTO();
g.setName("Wszystkie");
g.setId(-1);
comboModel.add(g);
comboModel.setSelectedItem(g);
if (comboBox != null) comboBox.repaint();
}
if (comboPreviewModel != null) {
comboPreviewModel.setModel(get());
if (comboBoxPreview != null) comboBoxPreview.repaint();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
|
package com.sprout.game;
import java.util.ArrayList;
import java.util.Set;
/**
* Created by megasoch on 19.12.2015.
*/
public class Intersection {
private static int turn(PointElement a, PointElement b, PointElement c)
{
double res = (b.getX() - a.getX()) * (c.getY() - a.getY()) - (b.getY() - a.getY()) * (c.getX() - a.getX());
double check = 0.1;
if(res > check) {
return 1;
}
if(res < -check) {
return -1;
}
return 0;
}
private static boolean intersectionSegments(PointElement a, PointElement b, PointElement c, PointElement d)
{
if(turn(a, b, c) * turn(a, b, d) < 0)
{
if(turn(c, d, a) * turn(c, d, b) < 0)
{
return true;
}
}
return false;
}
public static boolean hasIntersection(PointElement p, Set<EdgeElement> edges, ArrayList<PointElement> edgePointSequence) {
for (EdgeElement e: edges) {
ArrayList<PointElement> curr = e.getPoints();
for (int i = 0; i < curr.size() - 1; i++) {
if (intersectionSegments(p, edgePointSequence.get(edgePointSequence.size() - 1), curr.get(i), curr.get(i + 1))) {
return true;
}
}
}
for (int i = 0; i < edgePointSequence.size() - 1; i++) {
if (intersectionSegments(p, edgePointSequence.get(edgePointSequence.size() - 1), edgePointSequence.get(i), edgePointSequence.get(i + 1))) {
return true;
}
}
return false;
}
public static float length(PointElement a, PointElement b) {
float sqrX = (a.getX() - b.getX()) * (a.getX() - b.getX());
float sqrY = (a.getY() - b.getY()) * (a.getY() - b.getY());
return (float)Math.sqrt(sqrX + sqrY);
}
public static float sequenceLength(ArrayList<PointElement> edgePointSequence) {
float length = 0;
for (int i = 0; i < edgePointSequence.size() - 1; i++) {
PointElement a = edgePointSequence.get(i);
PointElement b = edgePointSequence.get(i + 1);
length += length(a, b);
}
return length;
}
private static boolean boundingBox(PointElement a, PointElement b, PointElement c, PointElement d)
{
return (a.getX() == c.getX() && a.getY() == c.getY() && b.getX() == d.getX() && b.getY() == d.getY());
}
}
|
package pl.connectis.cschool.client;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.sencha.gxt.core.client.IdentityValueProvider;
import com.sencha.gxt.core.client.util.Margins;
import com.sencha.gxt.data.shared.ListStore;
import com.sencha.gxt.widget.core.client.FramedPanel;
import com.sencha.gxt.widget.core.client.button.TextButton;
import com.sencha.gxt.widget.core.client.container.HBoxLayoutContainer;
import com.sencha.gxt.widget.core.client.container.VBoxLayoutContainer;
import com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer;
import com.sencha.gxt.widget.core.client.event.SelectEvent;
import com.sencha.gxt.widget.core.client.form.*;
import com.sencha.gxt.widget.core.client.form.TextField;
import com.sencha.gxt.widget.core.client.grid.CheckBoxSelectionModel;
import com.sencha.gxt.widget.core.client.grid.ColumnConfig;
import com.sencha.gxt.widget.core.client.grid.ColumnModel;
import com.sencha.gxt.widget.core.client.grid.Grid;
import pl.connectis.cschool.client.domain.InvoiceDTOProperties;
import pl.connectis.cschool.client.domain.ProductProperties;
import pl.connectis.cschool.shared.Invoice;
import pl.connectis.cschool.shared.Product;
import pl.connectis.cschool.shared.dto.InvoiceDTO;
import java.awt.*;
import java.util.*;
import java.util.List;
/**
* Created by Benia on 2017-06-24.
*/
public class InvoicePanel implements IsWidget {
final TextField invoiceNumberTF = new TextField();
final TextField productsTF = new TextField();
final TextField reciverFirstNameTF = new TextField();
final TextField reciverNameTF = new TextField();
final TextField invoiceAmountTF = new TextField();
final TextButton addInvoiceTB = new TextButton("Add invoice");
final TextButton getAllInvoiceTB = new TextButton("Pobierz faktury");
private CheckBoxSelectionModel<InvoiceDTO> checkBoxSelectionModel;
private CheckBoxSelectionModel<Product> productCheckBoxSelectionModel;
private InvoiceDTOProperties invoiceDTOProperties = GWT.create(InvoiceDTOProperties.class);
ListStore<InvoiceDTO> invoiceDTOListStore = new ListStore<InvoiceDTO>(invoiceDTOProperties.invoiceId());
private InvoiceServiceAsync invoiceServiceAsync = GWT.create(InvoiceService.class);
private ProductProperties productProperties = GWT.create(ProductProperties.class);
ListStore<Product> productListStore = new ListStore<Product>(productProperties.id());
private Widget prepareInvoiceForm() {
FramedPanel framedPanel = new FramedPanel();
framedPanel.setHeadingText("Invoice form");
VBoxLayoutContainer vBLC = new VBoxLayoutContainer(VBoxLayoutContainer.VBoxLayoutAlign.STRETCH);
vBLC.add(new FieldLabel(invoiceNumberTF, "Numer faktury"));
vBLC.add(new FieldLabel(productsTF, "Produkty"));
vBLC.add(new FieldLabel(reciverFirstNameTF, "Imie odbiorcy"));
vBLC.add(new FieldLabel(reciverNameTF, "Nazwisko odbiorcy"));
vBLC.add(new FieldLabel(invoiceAmountTF, "Kwota faktury"));
getAllInvoiceTB.addSelectHandler(new SelectEvent.SelectHandler() {
@Override
public void onSelect(SelectEvent selectEvent) {
fillInvoiceTable();
}
});
addInvoiceTB.addSelectHandler(new SelectEvent.SelectHandler() {
@Override
public void onSelect(SelectEvent selectEvent) {
int s = invoiceDTOListStore.size();
Invoice invoice = new Invoice();
Long id = Long.valueOf(s+1);
List<Product> pList = new ArrayList<Product>();
String splited = productsTF.getText();
String[] splitedArray = splited.split(",");
for(String productName: splitedArray){
Product p = new Product();
p.setProductName(productName);
pList.add(p);
}
invoice.setId(id);
invoice.setNumber(invoiceNumberTF.getText());
invoice.setProducts(pList);
invoice.setReciverFirstName(reciverFirstNameTF.getText());
invoice.setReciverName(reciverNameTF.getText());
invoice.setInvoiceAmount(invoiceAmountTF.getText());
invoiceServiceAsync.addInvoice(invoice, new AsyncCallback<Void>() {
@Override
public void onFailure(Throwable throwable) {
GWT.log( throwable.getMessage());
}
@Override
public void onSuccess(Void aVoid) {
}
});
}
});
HBoxLayoutContainer hBLC = new HBoxLayoutContainer(HBoxLayoutContainer.HBoxLayoutAlign.STRETCHMAX);
hBLC.add(addInvoiceTB);
hBLC.add(getAllInvoiceTB);
VerticalLayoutContainer mainVLC = new VerticalLayoutContainer();
mainVLC.add(vBLC);
mainVLC.add(hBLC);
framedPanel.add(mainVLC);
return framedPanel;
}
private Widget prepareInvoiceGrid() {
FramedPanel framedPanel = new FramedPanel();
framedPanel.setHeadingText("All invoices");
IdentityValueProvider<InvoiceDTO> identity = new IdentityValueProvider<InvoiceDTO>();
checkBoxSelectionModel = new CheckBoxSelectionModel<InvoiceDTO>(identity);
ColumnConfig<InvoiceDTO, String> invoiceNumberCol = new ColumnConfig<InvoiceDTO, String>(invoiceDTOProperties.invoiceNumber(), 70, "Numer faktury");
ColumnConfig<InvoiceDTO, String> invoiceReciverFNameCol = new ColumnConfig<InvoiceDTO, String>(invoiceDTOProperties.reciverFirstName(), 70, "Imie odbiorcy");
ColumnConfig<InvoiceDTO, String> invoiceReciverNameCol = new ColumnConfig<InvoiceDTO, String>(invoiceDTOProperties.reciverName(), 70, "Nazwisko odbiorcy");
ColumnConfig<InvoiceDTO, String> invoiceAmountCol = new ColumnConfig<InvoiceDTO, String>(invoiceDTOProperties.invoiceAmount(), 70, "Kwota faktury");
List<ColumnConfig<InvoiceDTO, ?>> columns = new ArrayList<ColumnConfig<InvoiceDTO, ?>>();
columns.add(checkBoxSelectionModel.getColumn());
columns.add(invoiceNumberCol);
columns.add(invoiceReciverFNameCol);
columns.add(invoiceReciverNameCol);
columns.add(invoiceAmountCol);
ColumnModel<InvoiceDTO> columnModel = new ColumnModel<InvoiceDTO>(columns);
Grid<InvoiceDTO> grid = new Grid<InvoiceDTO>(invoiceDTOListStore, columnModel);
grid.setSelectionModel(checkBoxSelectionModel);
framedPanel.add(grid);
return framedPanel;
}
private Widget prepareProductGrid() {
FramedPanel framedPanel = new FramedPanel();
framedPanel.setHeadingText("All products");
IdentityValueProvider<Product> identity = new IdentityValueProvider<Product>();
productCheckBoxSelectionModel = new CheckBoxSelectionModel<Product>(identity);
ColumnConfig<Product, String> productNameCol = new ColumnConfig<Product, String>(productProperties.productName(), 70, "Nazwa produktu");
java.util.List<ColumnConfig<Product, ?>> columns = new ArrayList<ColumnConfig<Product, ?>>();
columns.add(productCheckBoxSelectionModel.getColumn());
columns.add(productNameCol);
ColumnModel<Product> columnModel = new ColumnModel<Product>(columns);
Grid<Product> grid = new Grid<Product>(productListStore, columnModel);
grid.setSelectionModel(productCheckBoxSelectionModel);
framedPanel.add(grid);
return framedPanel;
}
private void fillInvoiceTable() {
invoiceServiceAsync.allInvoiceDTO(new AsyncCallback<List<InvoiceDTO>>() {
@Override
public void onFailure(Throwable throwable) {
GWT.log("Nie udało sie pobrać faktur");
}
@Override
public void onSuccess(List<InvoiceDTO> invoiceDTOS) {
invoiceDTOListStore.clear();
for (InvoiceDTO invoiceDTO : invoiceDTOS) {
invoiceDTOListStore.add(invoiceDTO);
}
}
});
fill();
}
private void fill(){
checkBoxSelectionModel.addSelectionHandler(new SelectionHandler<InvoiceDTO>() {
@Override
public void onSelection(SelectionEvent<InvoiceDTO> selectionEvent) {
Long dtoId = selectionEvent.getSelectedItem().getInvoiceId();
GWT.log(dtoId.toString());
invoiceServiceAsync.findProductById(dtoId, new AsyncCallback<List<Product>>() {
@Override
public void onFailure(Throwable throwable) {
GWT.log("Nie udalo się pobrać produktów");
}
@Override
public void onSuccess(List<Product> products) {
productListStore.clear();
for (Product product : products) {
productListStore.add(product);
}
}
});
}
});
}
@Override
public Widget asWidget (){
int width = 1; // 100%
int height = 1; // 50px
Margins margin = new Margins(10);
VerticalLayoutContainer.VerticalLayoutData verticalLayoutData = new VerticalLayoutContainer.VerticalLayoutData(width, height, margin);
VerticalLayoutContainer vLT = new VerticalLayoutContainer();
vLT.add(prepareInvoiceForm());
vLT.add(prepareInvoiceGrid());
vLT.add(prepareProductGrid());
return vLT;
}
}
|
package com.qgbase.biz.info.service;
import com.qgbase.biz.info.domain.TPicture;
import com.qgbase.biz.info.repository.PictureRepository;
import com.qgbase.biz.user.domain.TUser;
import com.qgbase.common.TBaseBo;
import com.qgbase.common.dao.CommonDao;
import com.qgbase.common.domain.OperInfo;
import com.qgbase.common.enumeration.EnumResultType;
import com.qgbase.util.StringUtil;
import com.qgbase.util.TToolRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Mark on 2019-08-06
* * 主要用于:图片 业务处理,此代码为自动生成
*/
@Component
public class TPictureService extends TBaseBo<TPicture> {
@Autowired
CommonDao commonDao;
@Autowired
private PictureRepository pictureRepository;
@Override
public TPicture createObj() {
return new TPicture();
}
@Override
public Class getEntityClass() {
return TPicture.class;
}
@Override
public TPicture newObj(OperInfo oper) throws Exception {
TPicture obj = super.newObj(oper);
//这里对新创建的对象进行初始化 ,比如 obj.setIsUsed(1);
//写下你的处理方法
obj.setPictureId(commonDao.getNewKey("pic", "pic", 4, 2));
return obj;
}
@Override
public String checkAddorUpdate(TPicture obj, OperInfo oper, boolean isNew) throws Exception {
//这里对 新增和修改 保存前进行检查,检查失败返回错误信息
//写下你的处理方法
return super.checkAddorUpdate(obj, oper, isNew);
}
@Override
public String checkDelete(TPicture obj, OperInfo oper) throws Exception {
//这里对 删除前进行检查,检查失败返回错误信息
//写下你的处理方法
return super.checkDelete(obj, oper);
}
/*
根据图片类型和业务对象id 获取所有图片
*/
public List getPicturesByObjectid(String pictureType, String objectId, OperInfo oper) {
return commonDao.getHqlListP("from TPicture where pictureType=? and objectId=?", pictureType, objectId);
}
/*
根据图片类型和业务对象id 删除所有图片
*/
public void delPicturesByObjectid(String pictureType, String objectId, OperInfo oper) throws Exception {
List objs = commonDao.getHqlListP("from TPicture where pictureType=? and objectId=?", pictureType, objectId);
for (Object obj : objs
) {
LogDebug(((TPicture) obj).getPictureId());
this.deleteobj(((TPicture) obj).getPictureId(), oper);
}
}
public TPicture getImgOne(String objectId, String pictureType) {
List<TPicture> pictureList = pictureRepository.findByObjectIdAndPictureType(objectId, pictureType);
if (null != pictureList && pictureList.size() > 0) {
return pictureList.get(0);
}
return null;
}
public List<TPicture> getImgList(String objectId, String pictureType) {
List<TPicture> pictureList = pictureRepository.findByObjectIdAndPictureType(objectId, pictureType);
if (null != pictureList && pictureList.size() > 0) {
return pictureList;
}
return null;
}
public TPicture saveImgOne(String objectId, String pictureType, String imgUrl, String imgSurl, OperInfo operInfo) throws Exception {
TPicture picture = newObj(operInfo);
picture.setObjectId(objectId);
picture.setPictureType(pictureType);
picture.setPictureSurl(imgSurl);
picture.setPictureUrl(imgUrl);
picture.setFileType(imgUrl.substring(imgUrl.lastIndexOf(".") + 1));
TPicture item = getImgOne(objectId, pictureType);
if (null != item) {
deleteobj(item.getPictureId(), operInfo);
return addobj(picture, operInfo);
}
return addobj(picture, operInfo);
}
public TPicture saveImgList(String objectId, String pictureType, String imgUrl, String imgSurl, OperInfo operInfo) throws Exception {
TPicture picture = newObj(operInfo);
picture.setObjectId(objectId);
picture.setPictureType(pictureType);
picture.setPictureSurl(imgSurl);
picture.setPictureUrl(imgUrl);
picture.setFileType(imgUrl.substring(imgUrl.lastIndexOf(".") + 1));
return addobj(picture, operInfo);
}
}
|
package com.koreait.guestbook.model;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.koreait.dao.GuestbookDao;
public class DeleteAction implements Action {
@Override
public String command(HttpServletRequest request, HttpServletResponse response) {
int idx = Integer.parseInt( request.getParameter("idx") );
GuestbookDao dao = GuestbookDao.getInstance();
int result = dao.getDelete(idx);
// 성공, 실패에 따라 다른 path 사용
String path = null;
if ( result > 0 ) {
path = "/list.do"; // 삭제 성공 -> 전체 보기
} else {
path = "/view.do?idx=" + idx; // 삭제 실패 -> 방명록 보기
}
return path;
}
}
|
package br.com.sysprojsp.classes.model;
public class Usuario {
private Long id;
private String primeironome;
private String sobrenome;
private String ultimonome;
private String email;
private String telefone;
private String login;
private String senha;
private boolean ativo;
private String perfil;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPrimeironome() {
return primeironome;
}
public void setPrimeironome(String primeironome) {
this.primeironome = primeironome;
}
public String getSobrenome() {
return sobrenome;
}
public void setSobrenome(String sobrenome) {
this.sobrenome = sobrenome;
}
public String getUltimonome() {
return ultimonome;
}
public void setUltimonome(String ultimonome) {
this.ultimonome = ultimonome;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getSenha() {
return senha;
}
public void setSenha(String senha) {
this.senha = senha;
}
public boolean isAtivo() {
return ativo;
}
public void setAtivo(boolean ativo) {
this.ativo = ativo;
}
public String getPerfil() {
return perfil;
}
public void setPerfil(String perfil) {
this.perfil = perfil;
}
}
|
package com.ojas.rpo.security.entity;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Table(name="GST")
@javax.persistence.Entity
public class GST implements Entity {
@Id
@GeneratedValue
private Long id;
@Column
private String Gst;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getGst() {
return Gst;
}
public void setGst(String gst) {
Gst = gst;
}
}
|
package com.qw.springboot;
import com.baidu.ueditor.PathFormat;
import com.baidu.ueditor.define.AppInfo;
import com.baidu.ueditor.define.BaseState;
import com.baidu.ueditor.define.MultiState;
import com.baidu.ueditor.define.State;
import com.baidu.ueditor.hunter.ImageHunter;
import com.baidu.ueditor.spring.EditorUploader;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Map;
/**
* 自定义上传
* 返回指定格式即可
*
* @author lihy
* @version 2018/12/25
*/
//@Component
public class MyEditorUploader implements EditorUploader {
@Override
public State binaryUpload(HttpServletRequest request, Map<String, Object> conf) {
String fieldName = (String) conf.get("fieldName");
MultiValueMap<String, MultipartFile> multiFileMap = ((MultipartHttpServletRequest) request).getMultiFileMap();
MultipartFile file = multiFileMap.getFirst(fieldName);
assert file != null;
// 文件名
String originFileName = file.getOriginalFilename();
assert originFileName != null;
// 文件扩展名
String suffix = originFileName.substring(originFileName.lastIndexOf(".")).toLowerCase();
// 不符合文件类型
if (!Arrays.asList((String[]) conf.get("allowFiles")).contains(suffix)) {
return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
}
long maxSize = (Long) conf.get("maxSize");
// 文件大小超出限制
if (maxSize < file.getSize()) {
return new BaseState(false, AppInfo.MAX_SIZE);
}
// 根据config.json 中的 imagePathFormat 生成 路径+文件名
String savePath = (String) conf.get("savePath");
savePath = savePath + suffix;
savePath = PathFormat.parse(savePath, originFileName);
System.out.println(savePath);
// TODO: 实现你自己的上传 比如ftp上传到服务器、上传到七牛云等
BaseState baseState = new BaseState();
// 必填项url,图片地址
baseState.putInfo("url", "https://www.baidu.com/img/baidu_jgylogo3.gif");
// 以下三项可以不填 都是 img 标签的属性
baseState.putInfo("type", "gif");
baseState.putInfo("original", "img-alt");
baseState.putInfo("title", "img-title");
return baseState;
}
@Override
public State base64Upload(HttpServletRequest request, Map<String, Object> conf) {
String filedName = (String) conf.get("fieldName");
String content = request.getParameter(filedName);
byte[] data = Base64.decodeBase64(content);
long maxSize = (Long) conf.get("maxSize");
// 文件大小超出限制
if (data.length > maxSize) {
return new BaseState(false, AppInfo.MAX_SIZE);
}
// 根据config.json 中的 imagePathFormat 生成 路径+文件名
String savePath = PathFormat.parse((String) conf.get("savePath"), (String) conf.get("filename"));
savePath = savePath + ".jpg";
// TODO: 实现你自己的上传 比如ftp上传到服务器、上传到七牛云等
BaseState baseState = new BaseState();
// 必填项url,图片地址
baseState.putInfo("url", "https://www.baidu.com/img/baidu_jgylogo3.gif");
// 以下三项可以不填 都是 img 标签的属性
baseState.putInfo("type", "gif");
baseState.putInfo("original", "img-alt");
baseState.putInfo("title", "img-title");
return baseState;
}
@Override
public MultiState listImage(int index, Map<String, Object> conf) {
// 每次列出图片数量 config.json 中的 imageManagerListSize
int count = (Integer) conf.get("count");
BaseState imageFirst = new BaseState();
imageFirst.putInfo("url", "https://www.baidu.com/img/baidu_jgylogo3.gif");
BaseState imageSecond = new BaseState();
imageSecond.putInfo("url", "https://www.baidu.com/img/bd_logo1.png");
MultiState multiState = new MultiState(true);
multiState.addState(imageFirst);
multiState.addState(imageSecond);
// 开始位置
multiState.putInfo("start", index);
// 总记录数
multiState.putInfo("total", 1);
return multiState;
}
@Override
public MultiState listFile(int index, Map<String, Object> conf) {
// 每次列出文件数量 config.json 中的 fileManagerListSize
int count = (Integer) conf.get("count");
BaseState baseState = new BaseState();
baseState.putInfo("url", "https://www.baidu.com/img/baidu_jgylogo3.pdf");
MultiState multiState = new MultiState(true);
multiState.addState(baseState);
// 开始位置
multiState.putInfo("start", index);
// 总记录数
multiState.putInfo("total", 1);
return multiState;
}
/**
* 抓取远程图片配置
*
* @param list 图片列表
*/
@Override
public State imageHunter(String[] list, Map<String, Object> conf) {
// 可以参考这个写
return new ImageHunter(conf).capture(list);
}
}
|
public class Test {
public static void main(String[] args) {
Faktura faktura1 = new Faktura("gotówka", "25.02.2019");
System.out.println(faktura1.wyswietlFakture());
}
}
|
/*
* 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 dto;
/**
*
* @author ASUS
*/
public class EmployeeAllowanceViewDTO {
private String empId;
private String contractId;
private String allowanceId;
private String allowance;
public String getEmpId() {
return empId;
}
public void setEmpId(String empId) {
this.empId = empId;
}
public String getContractId() {
return contractId;
}
public void setContractId(String contractId) {
this.contractId = contractId;
}
public String getAllowanceId() {
return allowanceId;
}
public void setAllowanceId(String allowanceId) {
this.allowanceId = allowanceId;
}
public String getAllowance() {
return allowance;
}
public void setAllowance(String allowance) {
this.allowance = allowance;
}
}
|
package total;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import util.ConnectionUtil;
import util.DatabaseUtil;
import util.Singleton;
public class TotalDAO {
public TotalDAO() {
}
public int selectTotal() {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
int result = -1;
try {
conn = ConnectionUtil.getConnection();
String SQL = " select * FROM \"TOTAL\" ";
pstmt = conn.prepareStatement(SQL);
rs = pstmt.executeQuery();
if(rs.next()) {
result = rs.getInt(1);
}
}catch(SQLException e) {
e.printStackTrace();
}finally {
if(rs != null) {
try {
rs.close();
}catch(SQLException e) {
e.printStackTrace();
}
}
if(pstmt != null) {
try {
pstmt.close();
}catch(SQLException e) {
e.printStackTrace();
}
}
if(conn != null) {
try {
conn.close();
}catch(SQLException e) {
e.printStackTrace();
}
}
}
return result;
}
public void updateTotal(int total) {
Connection conn = null;
PreparedStatement pstmt = null;
int result = 0;
try {
conn = ConnectionUtil.getConnection();
StringBuffer SQL = new StringBuffer();
SQL.append("update \"TOTAL\" ");
SQL.append("set \"TOTAL\" = ?");
pstmt =conn.prepareStatement(SQL.toString());
pstmt.setInt(1, total);
result = pstmt.executeUpdate();
}catch(SQLException e) {
e.printStackTrace();
}
}
}
|
package com.CallRail_Test.pages;
import java.util.List;
import org.junit.Assert;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.CallRail_Test.utils.CommonMethods;
public class UserListingPage extends BasePage{
@FindBy(id = "searchBtn")
WebElement searchBtn;
@FindBy(id = "btnAdd")
WebElement addBtn;
@FindBy(xpath = "//div[@class='message success fadable']")
WebElement successMsg;
@FindBy(xpath = "//table[@id='resultTable']//tbody//tr")
List<WebElement> listOfUsers;
@FindBy(xpath = "//table[@id='resultTable']/thead/tr/th[@class='header']")
List<WebElement> listOfColumn;
public UserListingPage(WebDriver webDriver) {
driver = webDriver;
PageFactory.initElements(webDriver, this);
}
public void verifyUserListingPage() {
CommonMethods.waitForElementToBePresent(searchBtn);
Assert.assertTrue("User Listing page is not loaded", CommonMethods.isDisplayed(searchBtn));
Assert.assertTrue("Add button is missing ono user listing page", CommonMethods.isDisplayed(addBtn));
}
public void clickOnAddBtn() {
addBtn.click();
}
public void verifySuccessMsg() {
Assert.assertTrue("Success message is missing on user listing page", CommonMethods.isDisplayed(successMsg));
}
}
|
package com.tencent.mm.plugin.qqmail.ui;
import android.view.View;
import android.view.View.OnClickListener;
class AttachDownloadPage$7 implements OnClickListener {
final /* synthetic */ AttachDownloadPage meu;
AttachDownloadPage$7(AttachDownloadPage attachDownloadPage) {
this.meu = attachDownloadPage;
}
public final void onClick(View view) {
AttachDownloadPage.e(this.meu);
AttachDownloadPage.f(this.meu);
AttachDownloadPage.h(this.meu);
}
}
|
class if_Test8 {
public static void main(String ar[]) {
int score = 78;
if (score >= 90)
{
System.out.println("A");
}
else if (score >= 80)
{
System.out.println("B");
}
else if (score >= 70)
{
System.out.println("C");
}
else if (score >= 60)
{
System.out.println("D");
}
else if (score <=59)
{
System.out.println("F");
}
}
}
|
package finggui;
import java.net.InetAddress;
import java.net.UnknownHostException;
import javax.swing.JOptionPane;
public class GetIPAddresses {
public static String[] getInetAddress() {
String hostname = null;
try {
hostname = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Error retrieving localhost "
+ "information!");
System.exit(1);
}
InetAddress[] address = null;
try {
address = InetAddress.getAllByName(hostname);
} catch (UnknownHostException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Error retrieving InetAddress "
+ "information!");
System.exit(1);
}
String[] addresslist = new String[address.length];
for (int i = 0; i < address.length; i++) {
int length = hostname.length();
String newstring = address[i].toString();
newstring = newstring.substring(length + 1);
addresslist[i] = newstring;
}
return addresslist;
}
}
|
package com.fang.example.db.store;
import java.io.IOException;
import java.io.Serializable;
/**
* Created by andy on 6/26/16.
*/
public interface Serializer
extends Serializable
{
/**
* Serialize the content of an object into a byte array.
*
* @param obj Object to serialize
* @return a byte array representing the object's state
*/
public byte[] serialize( Object obj )
throws IOException;
/**
* Deserialize the content of an object from a byte array.
*
* @param serialized Byte array representation of the object
* @return deserialized object
*/
public Object deserialize( byte[] serialized )
throws IOException;
}
|
package com.tencent.mm.plugin.messenger;
import com.tencent.mm.kernel.api.bucket.c;
import com.tencent.mm.kernel.b.f;
import com.tencent.mm.kernel.b.g;
import com.tencent.mm.plugin.messenger.a.e;
import com.tencent.mm.plugin.messenger.a.e.b;
import com.tencent.mm.plugin.messenger.b.a;
import com.tencent.mm.plugin.messenger.foundation.a.o;
public class PluginMessenger extends f implements c, com.tencent.mm.plugin.messenger.a.c {
a lbB = new a();
private a lbC = new a();
private b lbD = new 1(this);
private e.a lbE = new 2(this);
private e.a lbF = new 3(this);
private e.a lbG = new 4(this);
private e.a lbH = new 5(this);
public void installed() {
alias(com.tencent.mm.plugin.messenger.a.c.class);
}
public void dependency() {
dependsOn(com.tencent.mm.plugin.comm.a.a.class);
}
public void configure(g gVar) {
if (gVar.ES()) {
com.tencent.mm.kernel.g.Ek();
com.tencent.mm.kernel.g.a(com.tencent.mm.plugin.messenger.a.b.class, this.lbB);
com.tencent.mm.kernel.g.a(e.class, this.lbC);
}
}
public void execute(g gVar) {
if (gVar.ES()) {
pin(com.tencent.mm.plugin.ag.a.bqO());
}
}
public String toString() {
return "plugin-messenger";
}
public void onAccountInitialized(com.tencent.mm.kernel.e.c cVar) {
((o) com.tencent.mm.kernel.g.n(o.class)).getSysCmdMsgExtension().a("sysmsgtemplate", this.lbC.lcM);
((e) com.tencent.mm.kernel.g.l(e.class)).a("link_plain", this.lbD);
((e) com.tencent.mm.kernel.g.l(e.class)).a("link_plain", this.lbE);
((e) com.tencent.mm.kernel.g.l(e.class)).a("link_revoke", this.lbF);
((e) com.tencent.mm.kernel.g.l(e.class)).a("link_revoke_qrcode", this.lbG);
((e) com.tencent.mm.kernel.g.l(e.class)).a("link_profile", this.lbH);
}
public void onAccountRelease() {
((o) com.tencent.mm.kernel.g.n(o.class)).getSysCmdMsgExtension().b("sysmsgtemplate", this.lbC.lcM);
((e) com.tencent.mm.kernel.g.l(e.class)).Gs("link_plain");
((e) com.tencent.mm.kernel.g.l(e.class)).Gt("link_plain");
((e) com.tencent.mm.kernel.g.l(e.class)).Gt("link_revoke");
((e) com.tencent.mm.kernel.g.l(e.class)).Gt("link_revoke_qrcode");
((e) com.tencent.mm.kernel.g.l(e.class)).Gt("link_profile");
}
}
|
package com.capgemini.adm.tdd;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import org.junit.Before;
import org.junit.Test;
/**
* Integration test for simple App.
*/
public class AppTestIT {
@Before
public void expensiveSetup() throws InterruptedException {
System.err.println("... setting up an expensive test ...");
Thread.sleep(10_000);
}
/**
* Rigorous Test :-)
*/
@Test
public void shouldAlsoAnswerWithTrue() {
System.err.println("... running an expensive test ...");
assertThat( true, is(true) );
assertThat("hello, world", containsString("llo") );
}
}
|
package iarfmoose;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import com.github.ocraft.s2client.bot.S2Agent;
import com.github.ocraft.s2client.bot.gateway.UnitInPool;
import com.github.ocraft.s2client.protocol.spatial.Point;
import com.github.ocraft.s2client.protocol.unit.Alliance;
public class DefenceManager extends ResponsiveManager {
private static final float EARLY_DEFENCE_RADIUS = 12;
private PlayerState self;
private ArmyUnitTypeHandler armyUnitTypeHandler;
private List<ActiveUnit> unassignedUnitPool;
private List<Squad> unassignedSquads;
private List<Squad> squads;
private List<AssignedSquad> assignedSquads;
public DefenceManager(S2Agent bot, BaseLocator baseLocator) {
super(bot, baseLocator);
self = new PlayerState();
armyUnitTypeHandler = new ArmyUnitTypeHandler(bot);
unassignedUnitPool = new ArrayList<ActiveUnit>();
squads = new ArrayList<Squad>();
assignedSquads = new ArrayList<AssignedSquad>();
}
@Override
public void onStep(GameState currentState) {
self = currentState.findPlayerState(Alliance.SELF).orElse(new PlayerState());
removeEmptySquads();
checkForMorphedUnits();
}
@Override
public void onUnitCreated(UnitInPool unitInPool) {
ArmyUnit armyUnit = armyUnitTypeHandler.assignBehaviourType(unitInPool);
unassignedUnitPool.add(armyUnit);
}
@Override
public void onUnitDestroyed(UnitInPool unitInPool) {
removeUnassignedUnit(unitInPool);
for (Squad squad : squads) {
squad.removeMember(unitInPool);
}
}
private void checkForMorphedUnits() {
List<ActiveUnit> toAdd = new ArrayList<ActiveUnit>();
for (Iterator<ActiveUnit> armyIterator = unassignedUnitPool.iterator(); armyIterator.hasNext();) {
ArmyUnit armyUnit = (ArmyUnit) armyIterator.next();
if (!armyUnitTypeHandler.isCorrectType(armyUnit)) {
try {
UnitInPool unitInPool = armyUnit.getUnitInPool().orElseThrow(() -> new UnitNotFoundException());
armyIterator.remove();
toAdd.add(armyUnitTypeHandler.assignBehaviourType(unitInPool));
} catch (UnitNotFoundException e) {
armyIterator.remove();
}
}
}
unassignedUnitPool.addAll(toAdd);
}
public void removeUnassignedUnit(UnitInPool unitInPool) {
for (Iterator<ActiveUnit> memberIterator = unassignedUnitPool.iterator();
memberIterator.hasNext();) {
ActiveUnit member = memberIterator.next();
Optional<UnitInPool> memberUnitInPool = member.getUnitInPool();
if (memberUnitInPool.isPresent() && memberUnitInPool.get() == unitInPool) {
memberIterator.remove();
}
}
}
public void handleThreats(List<Threat> threats) {
if (threats.isEmpty()) {
for (AssignedSquad squad : assignedSquads) {
squad.getSquad().returnHome();
}
assignedSquads.clear();
squads.clear();
return;
}
assignedSquads = assignSquads(threats);
balanceSquadSizes();
attackTargets();
}
private List<AssignedSquad> assignSquads(List<Threat> threats) {
List<AssignedSquad> assignedSquads = new ArrayList<AssignedSquad>();
unassignedSquads = squads;
for (Threat threat : threats) {
if (threat.getUnits().size() > 0) {
Squad squad = findClosestSquad(threat);
if (squad == null) {
squad = new Squad(bot);
squads.add(squad);
}
AssignedSquad assignedSquad = new AssignedSquad(squad, threat);
assignedSquads.add(assignedSquad);
unassignedSquads.remove(squad);
}
}
return assignedSquads;
}
private Squad findClosestSquad(Threat threat) {
Point threatLocation = threat.getCentreOfGroup();
Squad closestSquad = null;
for (Squad squad : squads) {
if (closestSquad == null ||
squad.getCentreOfGroup().distance(threatLocation) <
closestSquad.getCentreOfGroup().distance(threatLocation)) {
closestSquad = squad;
}
}
return closestSquad;
}
private void balanceSquadSizes() {
if (assignedSquads.isEmpty()) {
return;
}
dissolveUnassignedSquads();
splitOversizedSquads();
addUnassignedUnitsToUndersizedSquads();
}
private void dissolveUnassignedSquads() {
for (Squad unassignedSquad : unassignedSquads) {
unassignedUnitPool.addAll(unassignedSquad.getMembers());
}
unassignedSquads.clear();
}
private void splitOversizedSquads() {
//separate the squads which have too many units
List<AssignedSquad> oversizedSquads = new ArrayList<AssignedSquad>();
for (AssignedSquad assignedSquad : assignedSquads) {
if (assignedSquad.getSquad().getTotalSupply() > assignedSquad.getThreat().getTotalSupply() * 2) {
oversizedSquads.add(assignedSquad);
}
}
assignedSquads.removeAll(oversizedSquads);
//cut the oversized squads in half and put the extra units in the pool
for (AssignedSquad oversizedSquad : oversizedSquads) {
List<ActiveUnit> squadUnits = oversizedSquad.getSquad().getMembers();
int limit = squadUnits.size() / 2;
int i = 0;
for (i = 0; i < limit; i++) {
unassignedUnitPool.add(squadUnits.get(i));
squadUnits.remove(i);
}
//add the resized squad back into the list
AssignedSquad assignedSquad = new AssignedSquad(new Squad(bot, squadUnits), oversizedSquad.getThreat());
assignedSquads.add(assignedSquad);
}
}
private void addUnassignedUnitsToUndersizedSquads() {
//separate the squads that are too small
List<AssignedSquad> undersizedSquads = new ArrayList<AssignedSquad>();
for (AssignedSquad assignedSquad : assignedSquads) {
if (assignedSquad.getSquad().getTotalSupply() < assignedSquad.getThreat().getTotalSupply()) {
undersizedSquads.add(assignedSquad);
}
}
assignedSquads.removeAll(undersizedSquads);
//add units from the unassigned pool to each squad
for (AssignedSquad undersizedSquad : undersizedSquads) {
List<ActiveUnit> squadUnits = undersizedSquad.getSquad().getMembers();
float difference = undersizedSquad.getThreat().getTotalSupply() -
undersizedSquad.getSquad().getTotalSupply();
float supplyAdded = 0;
Iterator<ActiveUnit> unitIterator = unassignedUnitPool.iterator();
while (unitIterator.hasNext() && supplyAdded < difference) {
ActiveUnit unassignedUnit = unitIterator.next();
try {
UnitInPool unitInPool = unassignedUnit.getUnitInPool().orElseThrow(() -> new UnitNotFoundException());
squadUnits.add(unassignedUnit);
supplyAdded += bot.observation()
.getUnitTypeData(false)
.get(unitInPool.unit().getType())
.getFoodRequired().orElse((float) 0);
} catch (UnitNotFoundException e) {
unitIterator.remove();
}
}
//add the resized squad back into the list
AssignedSquad assignedSquad = new AssignedSquad(new Squad(bot, squadUnits), undersizedSquad.getThreat());
assignedSquads.add(assignedSquad);
}
if (unassignedUnitPool.size() > 0) {
AssignedSquad weakestSquad = getWeakestSquad();
assignedSquads.remove(weakestSquad);
weakestSquad.addUnits(unassignedUnitPool);
assignedSquads.add(weakestSquad);
}
}
private AssignedSquad getWeakestSquad() {
AssignedSquad weakestSquad = null;
for (AssignedSquad assignedSquad : assignedSquads) {
if (weakestSquad == null) {
weakestSquad = assignedSquad;
} else {
float difference = assignedSquad.getThreat().getTotalSupply() - assignedSquad.getSquad().getTotalSupply();
float weakestDifference = weakestSquad.getThreat().getTotalSupply() - weakestSquad.getSquad().getTotalSupply();
if (difference > weakestDifference) {
weakestSquad = assignedSquad;
}
}
}
return weakestSquad;
}
private void attackTargets() {
for (AssignedSquad assignedSquad : assignedSquads) {
float threatSize = assignedSquad.getThreat().getTotalSupply();
float squadSize = assignedSquad.getSquad().getTotalSupply();
Point home = assignedSquad.getSquad().getHomeLocation();
UnitInPool closestEnemy = getClosestUnit(home, assignedSquad.getThreat().getUnits());
if (self.getBaseCount().orElse(0) > 2) {
assignedSquad.attackThreat();
} else if (squadSize > threatSize ||
closestEnemy.unit().getPosition().distance(home) < EARLY_DEFENCE_RADIUS) {
assignedSquad.attackThreat();
} else {
assignedSquad.getSquad().returnHome();
}
}
}
private void removeEmptySquads() {
for (Iterator<Squad> squadIterator = squads.iterator(); squadIterator.hasNext();) {
Squad squad = squadIterator.next();
if (squad.getTotalSupply() == 0) {
squadIterator.remove();
}
}
}
private UnitInPool getClosestUnit(Point point, List<UnitInPool> group) {
UnitInPool closestUnit = null;
for (UnitInPool unitInPool : group) {
Point unitPosition = unitInPool.unit().getPosition();
if (closestUnit == null ||
unitPosition.distance(point) <
closestUnit.unit().getPosition().distance(point)) {
closestUnit = unitInPool;
}
}
return closestUnit;
}
}
|
package c15;
public class a1
{
public static void main(String[] args)
{
// 객체 생성
SmartPhone sp = new SmartPhone("아이폰", "010-0000-0000");
// 전화 걸기
sp.call("010-1234-5678");
// 전화벨이 울림
sp.ring();
}
}
interface Phone
{
// targetNumber로 전화를 걸거야! 어떻게? 그건 아직 몰라!
public void call(String targetNumber);
// 전화벨이 울릴거야! 어떻게? 그건 아직 몰라!
public void ring();
}
class SmartPhone implements Phone
{
protected String name;
protected String phoneNumber;
public SmartPhone(String name, String phoneNumber)
{
this.name = name;
this.phoneNumber = phoneNumber;
}
/* Phone 인터페이스의 모든 프로토타입 메소드를 구현하시오. */
@Override
public void call(String targetNumber)
{
// TODO Auto-generated method stub
System.out.printf("%s로 전화를 겁니다!\n", targetNumber);
}
@Override
public void ring()
{
// TODO Auto-generated method stub
System.out.println("전화벨이 울립니다~");
}
}
|
package com.github.ezauton.visualizer.processor;
import com.github.ezauton.recorder.Recording;
import com.github.ezauton.visualizer.processor.factory.DataProcessorFactory;
import com.github.ezauton.visualizer.util.DataProcessor;
import com.github.ezauton.visualizer.util.Environment;
import javafx.animation.Interpolator;
import javafx.animation.KeyValue;
import java.util.*;
public class RecordingDataProcessor implements DataProcessor {
final List<DataProcessor> childDataProcessors = new ArrayList<>();
public RecordingDataProcessor(Recording recording, DataProcessorFactory factory) {
recording.getRecordingMap()
.values()
.stream()
.map(factory::getProcessor)
.filter(Optional::isPresent)
.map(Optional::get)
.forEach(childDataProcessors::add);
}
@Override
public void initEnvironment(Environment environment) {
for (DataProcessor d : childDataProcessors) {
if (d != null) {
d.initEnvironment(environment);
}
}
}
@Override
public Map<Double, List<KeyValue>> generateKeyValues(Interpolator interpolator) {
Map<Double, List<KeyValue>> ret = new HashMap<>();
for (DataProcessor dataProcessor : childDataProcessors) {
if (dataProcessor != null) {
Map<Double, List<KeyValue>> keyValMap = dataProcessor.generateKeyValues(interpolator);
if (keyValMap != null) {
for (Map.Entry<Double, List<KeyValue>> entry : keyValMap.entrySet()) {
if (!ret.containsKey(entry.getKey())) // not contained
{
ret.put(entry.getKey(), new ArrayList<>(entry.getValue()));
} else { // contained
ret.get(entry.getKey()).addAll(entry.getValue());
}
}
}
}
}
return ret;
}
}
|
package com.cjc.framework.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.boot.context.event.ApplicationPreparedEvent;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.ContextStartedEvent;
import org.springframework.context.event.ContextStoppedEvent;
/**
* spring-boot 启动事件
*
* @author: chengjunchao
* @date: 2018/11/20 18:46
*/
public class ApplicationEventListener implements ApplicationListener {
private final Logger logger = LoggerFactory.getLogger(getClass());
@Override
public void onApplicationEvent(ApplicationEvent event) {
// 在这里可以监听到Spring Boot的生命周期
if (event instanceof ApplicationEnvironmentPreparedEvent) {
//初始化环境变量
logger.info("初始化环境变量......");
} else if (event instanceof ApplicationPreparedEvent) {
// 初始化完成
logger.info("初始化完成......");
} else if (event instanceof ContextRefreshedEvent) {
// 应用刷新
logger.info("应用刷新......");
} else if (event instanceof ApplicationReadyEvent) {
// 应用已启动完成
logger.info("应用已启动完成......");
} else if (event instanceof ContextStartedEvent) {
// 应用启动,需要在代码动态添加监听器才可捕获
logger.info("应用启动,需要在代码动态添加监听器才可捕获......");
} else if (event instanceof ContextStoppedEvent) {
// 应用停止
logger.info("应用停止......");
} else if (event instanceof ContextClosedEvent) {
// 应用关闭
logger.info("应用关闭......");
} else {
}
}
}
|
package agents;
import chess.Board;
import chess.Move;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Random;
public class HumanPlayer implements Player {
private final BufferedReader br;
public HumanPlayer() {
br = new BufferedReader(new InputStreamReader(System.in));
}
@Override
public Move chooseMove(Board b, int color, int milliseconds, Random random) {
List<Move> moves = b.getValidMoves(color);
int size = moves.size();
System.out.println(b);
int chosen = -1;
do {
int idx = 0;
for (Move move : moves) {
System.out.println("#" + idx++ + "\t" + move);
}
System.out.println("Enter any number between 0 and " + (idx - 1) + " to choose that move");
try {
String line = br.readLine();
chosen = Integer.parseInt(line, 10);
if (chosen < 0 || chosen >= size) {
System.out.println("Number outside of range");
}
} catch (IOException ex) {
} catch (NumberFormatException ex) {
System.out.println("Not a valid number");
}
} while (chosen < 0 || chosen >= size);
return moves.get(chosen);
}
}
|
package com.sharpower.service.impl;
import com.sharpower.entity.PlcType;
import com.sharpower.service.PlcTypeService;
public class PlcTypeServiceImpl extends BaseServiceImpl<PlcType> implements PlcTypeService{
}
|
package edu.washington.cs.cse403d.coauthor.client.utils;
import java.awt.Font;
import javax.swing.JLabel;
/**
* Provides static methods to construct several different types of
* application-wide fonts, centralized so that the fonts are consistent across
* our application.
*
* @author William Cauchois
*/
public class Fonts {
/**
* This is just the font used for JLabels.
*/
public static Font getDialogFont() {
return new JLabel().getFont();
}
/**
* A large, bold font suitable for headers of pages.
*/
public static Font getHeaderFont() {
Font baseFont = getDialogFont();
return baseFont.deriveFont(baseFont.getSize2D() + 10.0f);
}
/**
* The font that should be used for search fields; slightly larger and
* bolder than normal.
*/
public static Font getSearchFont() {
return getDialogFont().deriveFont(Font.BOLD, 14);
}
}
|
package com.zidoo.scrapertest;
import org.sscraper.ScraperProcess;
import org.sscraper.database.android.AndroidHelper;
import org.sscraper.database.android.SqliteHelper;
import org.sscraper.model.MovieInfo;
import org.sscraper.network.HttpUtils;
import org.sscraper.utils.Log;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
final static String TAG = "ScraperTest.MainActivity";
private final String SERVER_ADDR = "http://192.168.11.204:8085";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// initialize data base
SqliteHelper.createHelper(getApplicationContext());
}
@Override
protected void onDestroy() {
super.onDestroy();
// close database
SqliteHelper helper = SqliteHelper.getInstance();
if (helper != null) {
helper.close();
}
}
@Override
protected void onResume() {
super.onResume();
// 通过http请求zidoo服务器获取影片信息
startServerTest();
//通过 搜刮接口 获取影片信息,
//先从本地数据库查询影片, 查到立即返回, 没有查到则调用搜刮器去网络上搜
//搜索到影片后先保存到本地数据库, 然后返回数据
startLocalTest();
// 从本地数据库查询影片
startDatabaseTest();
}
private void startDatabaseTest() {
Log.d(TAG, "startDatabaseTest");
// 必须先执行 SqliteHelper.createHelper(getApplicationContext());
// 这里我们在onCreate 中已经执行
AndroidHelper helper = new AndroidHelper();
MovieInfo info = helper.queryMovieByOriginalTitle("夏洛特烦恼", "2015");
if (info != null) {
Log.d(TAG, "db find moive : " + info.toJsonString());
} else {
Log.d(TAG, "db can not find movie");
}
}
void startLocalTest() {
Log.d(TAG, "startLocalTest");
new Thread(new Runnable() {
@Override
public void run() {
MovieInfo info = new ScraperProcess().findMovie4Local("夏洛特烦恼", "2015");
if (info != null) {
Log.d(TAG, "local find moive : " + info.toJsonString());
} else {
Log.d(TAG, "local can not find movie");
}
}
}).start();
}
void startServerTest() {
Log.d(TAG, "startServerTest");
new Thread(new Runnable() {
@Override
public void run() {
String response = HttpUtils.httpGet(SERVER_ADDR + "/search/movie?api_key=57983e31fb435df4df77afb854740ea9&query=夏洛特烦恼&year=2015");
if (response != null) {
Log.d(TAG, "server response = " + response);
} else {
Log.d(TAG, "server can not find movie");
}
}
}).start();
}
}
|
package com.mimi.mimigroup.model;
public class DM_Ward {
int Wardid;
int Districtid;
String Ward;
String District;
public DM_Ward() {
}
public DM_Ward(int wardid, int districtid, String ward) {
this.Wardid = wardid;
this.Districtid= districtid;
this.Ward = ward;
}
public int getWardid() {
return this.Wardid;
}
public void setWardid(int wardid) {
this.Wardid = wardid;
}
public int getDistrictid() {
return this.Districtid;
}
public void setDistrictid(int districtid) {
this.Districtid = districtid;
}
public String getWard() {
return this.Ward;
}
public void setWard(String ward) {
this.Ward = ward;
}
public String getDistrict() {
return this.District;
}
public void setDistrict(String District) {
this.District = District;
}
}
|
package kafka.consumer;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.PartitionInfo;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
/**
* @author supreethmurthy
* @project kafka-consumer
*/
public class ConsumerDemo {
private static Logger logger = LoggerFactory.getLogger(ConsumerDemo.class);
private static final String BOOTSTRAP_SERVER = "127.0.0.1:9092";
public static void main(String[] args) {
if (args.length < 2 || args.length > 3) {
logger.error("Invalid input arguments. GroupId and Topic name must be specified while partition is optional.");
System.exit(-1);
}
String groupId = args[0];
String topicName = args[1];
Integer partition = -1;
if (args.length == 3) {
try {
partition = Integer.parseInt(args[2]);
} catch (Exception ex) {
logger.error("Invalid Partition. Partition should be an integer. Subscribing to all paritions on the topic.");
}
}
// Consumer Properties
Properties properties = new Properties();
properties.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, BOOTSTRAP_SERVER);
properties.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
properties.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
properties.setProperty(ConsumerConfig.GROUP_ID_CONFIG, groupId);
properties.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
// Instantiate consumer
KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(properties);
List<TopicPartition> topicPartitions = new ArrayList<>();
if (partition != -1) {
//Subscribe to a specific partition on the topic
topicPartitions.add(new TopicPartition(topicName, partition));
consumer.assign(topicPartitions);
} else {
//Subscribe to all the partitions on the topic
consumer.subscribe(Arrays.asList(topicName));
}
logger.info("Starting consumer with groupId: {}", groupId);
// poll for new data
while(true){
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));
for (ConsumerRecord<String, String> record : records) {
logger.info("Key: " + record.key() + ", Value: " + record.value());
logger.info("Partition: " + record.partition() + ", Offset: " + record.offset());
}
}
}
}
|
/*
* Copyright (c) 2016 Mobvoi Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ticwear.design.widget;
import android.support.v7.widget.RecyclerView.Adapter;
import android.support.v7.widget.RecyclerView.LayoutManager;
import android.view.MotionEvent;
/**
* An interface for {@link LayoutManager} that can be ticklable.
*
* Created by tankery on 4/25/16.
*/
public interface TicklableLayoutManager {
void setTicklableRecyclerView(TicklableRecyclerView ticklableRecyclerView);
/**
* Check if the adapter is valid for this layout manager.
*/
boolean validAdapter(Adapter adapter);
/**
* Intercept pre scroll to quick show the AppBar.
*/
boolean interceptPreScroll();
/**
* Should use scroll as offset of view.
*/
boolean useScrollAsOffset();
int getScrollOffset();
int updateScrollOffset(int scrollOffset);
/**
* Pass touch event to LayoutManager
*/
boolean dispatchTouchEvent(MotionEvent e);
/**
* Pass side panel event to LayoutManager
*/
boolean dispatchTouchSidePanelEvent(MotionEvent ev);
}
|
package ec.edu.uce.vista;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import java.io.IOException;
import ec.edu.uce.controlador.RecyclerViewAdaptador;
public class ListaVehiculos extends AppCompatActivity {
private RecyclerView reciclerViewVehiculo;
private RecyclerViewAdaptador adaptadorVehiculo;
private Toolbar toolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
reciclerViewVehiculo = (RecyclerView) findViewById(R.id.recycler_vehiculo);
reciclerViewVehiculo.setLayoutManager(new LinearLayoutManager(this));
adaptadorVehiculo = new RecyclerViewAdaptador(Login.vehiculos);
reciclerViewVehiculo.setAdapter(adaptadorVehiculo);
}
public void nuevo(View view) {
RegistrarVehiculo.modificacion = false;
Intent siguiente;
siguiente = new Intent(this, RegistrarVehiculo.class);
startActivity(siguiente);
finish();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
//MenuInflater inflater = getMenuInflater();
//inflater.inflate(R.menu.menu_lista_vehiculos, menu);
//return super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menu_lista_vehiculos, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
//case R.id.insertarVehiculoMenu:
// Intent insertar = new Intent(ListaVehiculos.this, RegistrarVehiculo.class);
// startActivity(insertar);
// break;
case R.id.persistir:
try {
Login.persistir();
} catch (IOException e) {
e.printStackTrace();
}
break;
case R.id.regresarLoginMenu:
finish();
break;
case R.id.salirAppMenu:
Intent salir = new Intent(Intent.ACTION_MAIN);
salir.addCategory(Intent.CATEGORY_HOME);
salir.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(salir);
break;
}
return super.onOptionsItemSelected(item);
}
}
|
import java.util.Scanner;
public class Login extends Registration {
String f;
int g, h,i,j;
Scanner sc = new Scanner(System.in);
void loginn() {
System.out.println("login form:");
System.out.println("Enter the usr name");
f = sc.next();
System.out.println("Enter the password");
g = sc.nextInt();
}
void validate() {
if (d.equals(f) && (e == g)) {
System.out.println("Your login is success");
h = 1;
} else {
System.out.println("your login is not success");
}
}
public static void main(String[] args) {
Login ref1 = new Login();
for (ref1.i = 1; ref1.i >= 1; ref1.i++) {
ref1.register();
ref1.loginn();
ref1.validate();
if (ref1.h == 1)
{
ref1.display();
}
System.out.println("do you wish to continue 0 or 1");
ref1.j = ref1.sc.nextInt();
if (ref1.j == 1)
{
ref1.h=0;
ref1.i = 1;
}
else
{
break;
}
}
}
}
|
package com.rsm.yuri.projecttaxilivredriver.editprofile;
import android.net.Uri;
import com.rsm.yuri.projecttaxilivredriver.editprofile.events.EditProfileEvent;
/**
* Created by yuri_ on 02/04/2018.
*/
public interface UploaderPhoto {
void uploadPhoto(Uri selectedImageUri);
}
|
import java.util.*;
import java.io.*;
import java.util.Arrays;
import java.io.PrintWriter;
class Oblig1 {
public static void main(String [] args ) {
String path = args[0]; // input file
BinarySearchTree theTree = new BinarySearchTree();
//Read input file and call insert method.
try {
Scanner br = new Scanner (new FileReader(path));
while (br.hasNext()){
theTree.insert(br.nextLine());
}
} catch (IOException e) {
}
//theTree.inorderTraverse(theTree.rootnode);
UserInterface inter = new UserInterface(theTree);
inter.promptLoop();
inter.printTreeStatistics();
System.out.println("alphabetically first word " + theTree.findfirst());
System.out.println("alphabetically last word " + theTree.findLast());
}
}
class BinarySearchTree {
private Node rootnode;
private class Node {
Node leftChild;
Node rightChild;
String nodedata;
Node(String nodedata ) {
this( nodedata, null, null );
}
Node( String e, Node l, Node r ){
nodedata = e; leftChild = l; rightChild = r;
}
}
BinarySearchTree(){
this.rootnode = null;
}
public void insert( String e ) {
rootnode = insert( e, rootnode );
}
public void remove(String e) {
rootnode = remove(e, rootnode);
}
//
public boolean contains( String e ) {
return contains( e, rootnode );
}
//least value
public String findfirst(){
return findfirst(rootnode).nodedata;
}
public String findLast(){
return findLast(rootnode).nodedata;
}
public void inorderTraverse(Node focusNode) {
if (focusNode != null) {
// left node?
inorderTraverse(focusNode.leftChild);
// the current node
System.out.println(focusNode.nodedata);
// the right node
inorderTraverse(focusNode.rightChild);
}
}
private boolean contains(String check, Node rnode) {
//check if empty
if (rnode == null) {
return false;
}
int compare = check.compareTo(rnode.nodedata);
if (compare < 0 ) {
//check if the node is on the left side.
return contains(check, rnode.leftChild);
} else if (compare > 0 ) {
// else check if it contained on the right child
return contains(check, rnode.rightChild);
} else {
return true;
}
}
private Node insert(String e, Node rnode) {
// create and initialize If no root this becomes root
if (rnode == null) {
//root = newNode;
return new Node(e);
} else {
int compare = e.compareTo(rnode.nodedata);
// if less -> insert on left side.
if (compare < 0 ) {
rnode.leftChild = insert(e, rnode.leftChild);
} else if (compare > 0 ) {
// else insert on right side.
rnode.rightChild = insert(e, rnode.rightChild);
}
return rnode;
}
}
// always finds the least value.
private Node findfirst(Node n) {
if (n != null) {
while (n.leftChild != null) {
n = n.leftChild;
}
}
return n;
}
// right child
private Node findLast(Node n) {
if (n != null) {
while (n.rightChild != null) {
n = n.rightChild;
}
}
return n;
}
private Node remove(String check, Node rootnode) {
if (rootnode == null) {
return rootnode;
}
int compare = check.compareTo(rootnode.nodedata);
if (compare < 0 ) {
// node is on the leftchild
rootnode.leftChild = remove(check, rootnode.leftChild);
} else if (compare > 0 ) {
// on the rightchild
rootnode.rightChild = remove(check, rootnode.rightChild);
// else the the node has Two children
} else if (rootnode.leftChild != null && rootnode.rightChild != null) {
rootnode.nodedata = findfirst(rootnode.rightChild).nodedata;
rootnode.rightChild = remove(rootnode.nodedata, rootnode.rightChild);
} else {
//rootnode = (rootnode.leftChild != null) ? rootnode.leftChild : rootnode.rightChild;
if(rootnode.leftChild != null){
rootnode = rootnode.leftChild;
} else{
rootnode = rootnode.rightChild;
}
}
return rootnode;
}
private int treeDepth(Node nroot) {
if (nroot == null) {
return -1;
} else {
return 1 + Math.max(treeDepth(nroot.leftChild ), treeDepth(nroot.rightChild ));
}
}
private void nodesPerTreeDepth( Node nroot, int deps, int [] treeDep){
if (nroot != null) {
nodesPerTreeDepth(nroot.leftChild, deps+1, treeDep);
treeDep[deps]++;
nodesPerTreeDepth(nroot.rightChild, deps+1, treeDep);
}
}
public void statistics(){
int d = treeDepth(rootnode);
int sumnode = 0;
int sum = 0;
int average = 0;
int [] treeDep = new int [d+1];
nodesPerTreeDepth(rootnode, 0, treeDep);
System.out.println("Nodes per depth of the tree");
for (int k =0; k< treeDep.length; k++){
sumnode += treeDep[k]*k;
sum+= treeDep[k];
average = sumnode/sum;
System.out.println("node " +k +" is " + treeDep[k]);
}
System.out.println("The average depth of all nodes " + average);
System.out.println("The height of the Binary Search Tree is = " + d);
}
}
class UserInterface {
BinarySearchTree dictionary;
ArrayList<String> possiblewords; // arraylist to store the suggested/possible words.
int positveResultLookups; //look ups that gave +ve answer
UserInterface(BinarySearchTree spelling){
dictionary=spelling;
positveResultLookups = 0;
}
/*
while loop promt.
if the input is correct -> "has been spelled correctly" is printed.
else words with similar spellings are pritned out.
*/
public void promptLoop() {
Scanner userInput = new Scanner(System.in);
while(true) {
System.out.print("Enter a word> ");
String input = userInput.nextLine().toLowerCase();
if (input.equals("") ) {
System.out.println("an input is required, Exit loop with 'q'");
} else if (input.equals("q")) {
return;
} else if (dictionary.contains(input) ) {
System.out.println(input+" has been spelled correctly");
} else {
long starttime = System.currentTimeMillis(); // timing the process
possiblewords = new ArrayList<String>();
System.out.println(input+" has been misspelled");
// calling the four methods.
similarOne(input);
replacedLetter(input);
removedletter(input);
addedLetter(input);
long stoptime = System.currentTimeMillis(); // stop timing
long diff = stoptime - starttime;
System.out.println("Time taken to complete the task : " + diff+ " millisecond");
// check if the some possible words are generated
if (possiblewords.isEmpty()) {
System.out.println("No words with similar spellings found");
} else{
System.out.println("generated similar words are: " + possiblewords);
System.out.println("lookups with positive results : " + positveResultLookups);
}
}
positveResultLookups = 0;
}
}
//Rule 1
//identical input, except two letters next to each other switched.
// letters on the input string are swapped and cross check with the words in the dictionary.
private void similarOne(String word) {
char[] word_array = word.toCharArray();
char[] tmp;
String[] words = new String[word_array.length-1];
for (int i=0; i < word_array.length - 1; i++ ) {
tmp = word_array.clone();
words[i] = swap(i, i+1, tmp);
similarSpelling(words[i]);
}
}
private String swap(int a, int b, char[] word) {
//swap the char
char tmp = word[a];
word[a] = word[b];
word[b] = tmp;
return new String(word);
}
private void similarSpelling(String word) {
//check if the generated word is in the dictionary and add to the possible words tree.
if (dictionary.contains(word) ) {
positveResultLookups++;
possiblewords.add(word);
} else {
positveResultLookups++;
}
}
//Rule 2
//Identical input, except one letter replaced with another
private void replacedLetter(String input){
char[] word_array = input.toCharArray(); // to char array.
for(int i=0; i < word_array.length ; i++) {
alphabetcheck(i, word_array);
}
}
private void alphabetcheck(int i, char[] word_array) {
char[] tmpArray;
for (char c='a'; c <= 'z'; c++) {
tmpArray = word_array.clone();
tmpArray[i] = c;
// generate new words with different char and cross check if they exist in the dictionary with call of method similarspelling.
String stringalphabet = new String(tmpArray);
similarSpelling(stringalphabet);
}
}
//Rule 3
//Identical input, except one letter removed
// the method rearranges the input string and the different aphafabets are added and the generated words are checked
//if they exist in the dictionrary.
private void removedletter(String input){
char[] word_array = input.toCharArray(); //to char
int len = word_array.length+1;
char temp [][] = new char [len][len];
for(int i=0; i <= word_array.length; i++) {
for (int j=0; j <= word_array.length ; j++) {
if (i > j) {
temp[i][j] = word_array[j];
} else if (i < j) {
temp[i][j] = word_array[j-1];
}
}
alphabetcheck(i, temp[i]);
}
}
//Rule 4
//Identical input, one letter has been added in front, middle or at the end.
// In this case a letter is removed at a time and the new array is sent to the similarspelling
//to check if the new word generated is in the dictionary.
private void addedLetter(String input){
char[] word_array = input.toCharArray();
char tempArray [];
for(int i=0; i < word_array.length; i++) {
tempArray = new char[word_array.length - 1]; // to hold the new char with a less number of characters.
for(int j=0; j < word_array.length; j++) {
if (i > j) {
tempArray[j] = word_array[j];
} else if (i < j) {
tempArray[j-1] = word_array[j];
}
similarSpelling(new String(tempArray) );
}
}
}
public void printTreeStatistics(){
System.out.println("Binary Search Tree statistics");
dictionary.statistics();
}
}
|
package com.ellalee.travelmaker;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.ShareActionProvider;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class sharePractice extends Fragment {
private static final String LOG_TAG = sharePractice.class.getSimpleName();
private ShareActionProvider mShareActionProvider;
private String forecast;
private Intent mShareIntent;
public sharePractice() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_sharing, menu);
MenuItem shareItem = menu.findItem(R.id.action_share);
mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(shareItem);
if (mShareActionProvider != null) {
mShareActionProvider.setShareIntent(mShareIntent);
}
else {
Log.d(LOG_TAG, "Share action provider is null");
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
Intent intent = getActivity().getIntent();
if (intent != null && intent.hasExtra(Intent.EXTRA_TEXT)) {
forecast = intent.getStringExtra(Intent.EXTRA_TEXT);
TextView forecastTextview = (TextView) rootView.findViewById(R.id.detail_forecast_textview);
forecastTextview.setText(forecast);
setupShareIntent();
}
return rootView;
}
private void setupShareIntent() {
String textToShare = forecast + " #SunshineApp";
mShareIntent = new Intent(Intent.ACTION_SEND);
mShareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
mShareIntent.setType("text/plain");
mShareIntent.putExtra(Intent.EXTRA_TEXT, textToShare);
}
}
|
package com.simple.base.bz.iot.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.simple.base.bz.iot.dao.DeviceItemRepository;
import com.simple.base.bz.iot.entity.DeviceItem;
@Service
public class DeviceItemService {
@Autowired
DeviceItemRepository deviceItemDao;
public List<DeviceItem> getItems(){
List<DeviceItem> items = deviceItemDao.findAll();
return items;
}
public DeviceItem getItemById(Long id){
return deviceItemDao.findOne(id);
}
public DeviceItem save(DeviceItem dt){
return this.deviceItemDao.save(dt);
}
public void remove(Long id){
this.deviceItemDao.delete(id);
}
}
|
/*******************************************************************************
* Copyright (C) 2014, International Business Machines Corporation
* All Rights Reserved
*******************************************************************************/
package com.ibm.streamsx.jms.helper;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import com.ibm.streams.operator.OperatorContext;
import com.ibm.streams.operator.logging.TraceLevel;
import com.ibm.streamsx.jms.JMSOpConstants;
public class JmsClasspathUtil {
private static final Logger tracer = Logger.getLogger(JmsClasspathUtil.class.getName());
public static void setupClassPaths(OperatorContext context) {
tracer.log(TraceLevel.TRACE, "Setting up classpath"); //$NON-NLS-1$
boolean classpathSet = false;
// Dump the provided environment
Map<String,String> sysEnvMap = System.getenv();
Set<String> sysEnvKeys = sysEnvMap.keySet();
tracer.log(TraceLevel.TRACE, "------------------------------------------------------------------------------------"); //$NON-NLS-1$
tracer.log(TraceLevel.TRACE, "--- System Environment used during initialization"); //$NON-NLS-1$
for( String key : sysEnvKeys) {
tracer.log(TraceLevel.TRACE, key + " = " + System.getenv(key)); //$NON-NLS-1$
}
tracer.log(TraceLevel.TRACE, "------------------------------------------------------------------------------------"); //$NON-NLS-1$
if(context.getParameterNames().contains(JMSOpConstants.PARAM_CLASS_LIBS))
{
List<String> classLibPaths = context.getParameterValues(JMSOpConstants.PARAM_CLASS_LIBS);
for(String path : classLibPaths) {
tracer.log(TraceLevel.TRACE, "Handling " + JMSOpConstants.PARAM_CLASS_LIBS + " value: " + path); //$NON-NLS-1$ //$NON-NLS-2$
String pathToAdd;
if(path.startsWith("/")) {
pathToAdd = path;
}
else {
pathToAdd = context.getPE().getApplicationDirectory() + "/" + path; //$NON-NLS-1$
}
tracer.log(TraceLevel.TRACE, "Trying to load: " + JMSOpConstants.PARAM_CLASS_LIBS + " value: " + pathToAdd); //$NON-NLS-1$
Path pathObj = Paths.get(pathToAdd);
if(Files.exists(pathObj)) {
if(Files.isDirectory(pathObj)) {
pathToAdd += "/*";
}
try {
tracer.log(TraceLevel.TRACE, "Adding passed class lib to context: " + pathToAdd); //$NON-NLS-1$
context.addClassLibraries(new String[] {pathToAdd});
classpathSet = true;
}
catch (MalformedURLException e) {
tracer.log(TraceLevel.ERROR, "Failed to add class lib to context: " + e.getMessage()); //$NON-NLS-1$
}
}
else {
tracer.log(TraceLevel.ERROR, "Does not exist: " + pathToAdd); //$NON-NLS-1$
}
}
}
else
{
String AMQ_HOME = System.getenv("STREAMS_MESSAGING_AMQ_HOME"); //$NON-NLS-1$
if (AMQ_HOME != null) {
tracer.log(TraceLevel.TRACE, "Apache Active MQ classpath!"); //$NON-NLS-1$
String lib = AMQ_HOME + "/lib/*"; //$NON-NLS-1$
String libOptional = AMQ_HOME + "/lib/optional/*"; //$NON-NLS-1$
try {
tracer.log(TraceLevel.TRACE, "Adding ActiveMQ class libs to context"); //$NON-NLS-1$
context.addClassLibraries(new String[] { lib, libOptional });
classpathSet = true;
}
catch (MalformedURLException e) {
tracer.log(TraceLevel.ERROR, "Failed to add class libs to context: " + e.getMessage()); //$NON-NLS-1$
}
}
String WMQ_HOME = System.getenv("STREAMS_MESSAGING_WMQ_HOME"); //$NON-NLS-1$
if (WMQ_HOME != null) {
tracer.log(TraceLevel.TRACE, "IBM IBM MQ classpath!"); //$NON-NLS-1$
String javaLib = WMQ_HOME + "/java/lib/*"; //$NON-NLS-1$
try {
tracer.log(TraceLevel.TRACE, "Adding IBM MQ class libs to context"); //$NON-NLS-1$
context.addClassLibraries(new String[] { javaLib });
classpathSet = true;
}
catch (MalformedURLException e) {
tracer.log(TraceLevel.ERROR, "Failed to add class libs to context: " + e.getMessage()); //$NON-NLS-1$
}
}
}
if( classpathSet == false ) {
tracer.log(TraceLevel.ERROR, "No classpath has been set!"); //$NON-NLS-1$
}
tracer.log(TraceLevel.TRACE, "Finished setting up classpath!"); //$NON-NLS-1$
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.cwi.crescer.repositorio;
import br.cwi.crescer.model.Pessoa;
import java.util.List;
/**
*
* @author erico.loewe
*/
public interface IPessoa {
void insert(Pessoa pessoa);
void update(Pessoa pessoa);
void delete(Pessoa pessoa);
List<Pessoa> listAll();
List<Pessoa> findNome(String nome);
}
|
/**
* Solutii Ecommerce, Automatizare, Validare si Analiza | Seava.ro
* Copyright: 2013 Nan21 Electronics SRL. All rights reserved.
* Use is subject to license terms.
*/
package seava.ad.presenter.impl.scheduler.model;
import seava.ad.domain.impl.scheduler.JobTimer;
import seava.j4e.api.annotation.Ds;
import seava.j4e.api.annotation.DsField;
import seava.j4e.api.annotation.SortField;
import seava.j4e.presenter.impl.model.AbstractTypeLov_Ds;
@Ds(entity = JobTimer.class, sort = {@SortField(field = JobTimerLov_Ds.f_name)})
public class JobTimerLov_Ds extends AbstractTypeLov_Ds<JobTimer> {
public static final String ALIAS = "ad_JobTimerLov_Ds";
public static final String f_jobContextId = "jobContextId";
public static final String f_jobContext = "jobContext";
public static final String f_jobName = "jobName";
@DsField(join = "left", path = "jobContext.id")
private String jobContextId;
@DsField(join = "left", path = "jobContext.name")
private String jobContext;
@DsField(join = "left", path = "jobContext.jobName")
private String jobName;
public JobTimerLov_Ds() {
super();
}
public JobTimerLov_Ds(JobTimer e) {
super(e);
}
public String getJobContextId() {
return this.jobContextId;
}
public void setJobContextId(String jobContextId) {
this.jobContextId = jobContextId;
}
public String getJobContext() {
return this.jobContext;
}
public void setJobContext(String jobContext) {
this.jobContext = jobContext;
}
public String getJobName() {
return this.jobName;
}
public void setJobName(String jobName) {
this.jobName = jobName;
}
}
|
package com.example.demo;
import com.example.demo.config.EmbeddedRedisConfig;
import com.example.demo.config.LocalRedisClient;
import com.example.demo.service.TestService;
import io.lettuce.core.RedisFuture;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.async.RedisAsyncCommands;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
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.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
@SpringBootTest
public class RedisTests {
@Autowired
private TestService testService;
@MockBean(name = "redisTemplateString")
private RedisTemplate<String, String> redisTemplateString;
@Mock
private ValueOperations<String, String> valueOperations;
@MockBean(name = "redisTemplateObject")
private RedisTemplate<String, Object> redisTemplateObject;
@Mock
private ValueOperations<String, Object> valueOperationObject;
@MockBean
private LocalRedisClient localRedisClient;
@Mock
private StatefulRedisConnection<String, String> statefulRedisConnection;
@Mock
private RedisAsyncCommands<String, String> redisAsyncCommands;
@MockBean
private RedisFuture<String> redisFuture;
@BeforeAll
static void start () {
EmbeddedRedisConfig.start();
}
@AfterAll
static void stop () {
EmbeddedRedisConfig.stop();
}
@Test
void get1Test() throws ExecutionException, InterruptedException, TimeoutException {
String returnValue = "returnValue";
Mockito.when(statefulRedisConnection.async()).thenReturn(redisAsyncCommands);
Mockito.when(localRedisClient.getConnection()).thenReturn(statefulRedisConnection);
Mockito.when(redisAsyncCommands.get(Mockito.anyString())).thenReturn(redisFuture);
Mockito.when(redisFuture.get(Mockito.anyLong(), Mockito.any(TimeUnit.class))).thenReturn(returnValue);
String ret = testService.get("test");
Assertions.assertEquals("returnValue", ret);
}
@Test
void get2Test() {
String returnValue = "returnValue";
Mockito.when(redisTemplateString.opsForValue()).thenReturn(valueOperations);
Mockito.when(valueOperations.get(Mockito.anyString())).thenReturn(returnValue);
String ret = testService.get2("test");
Assertions.assertEquals("returnValue", ret);
}
@Test
void get3Test() {
Object returnValue = "returnValue";
Mockito.when(redisTemplateObject.opsForValue()).thenReturn(valueOperationObject);
Mockito.when(valueOperationObject.get(Mockito.anyString())).thenReturn(returnValue);
Object ret = testService.get3("test");
Assertions.assertEquals("returnValue", (String) ret);
}
}
|
package com.kangyh.ui;
import com.kangyh.service.IAccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @Auther: kangYh
* @Date: 2019/7/25 13:00
* @Description:
*/
public class Client
{
public static void main(String[] args)
{
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
IAccountService accountService = (IAccountService) applicationContext.getBean("13");
// System.out.println(accountService);
accountService.saveAccount();
}
}
|
package com.trust.demo;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Path;
/**
* Created by TrustTinker on 2017/3/21.
*/
public interface GitHubInterface {
@GET("{owner}/{repo}/{repos}")
Call<ResponseBody> contributorsBySimpleGetCall(@Path("owner") String owner,
@Path("repo") String repo,
@Path("repos") String repos);
// @Headers({"Content-Type: application/json","Accept: application/json"})//需要添加头
// @FormUrlEncoded
@POST("rest/gps/latest/")
Call<ResponseBody> postResult(@Body RequestBody route);
}
|
package org.fuserleer.apps.twitter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.fuserleer.Universe;
import org.fuserleer.crypto.Identity;
import org.fuserleer.crypto.Hash;
import org.fuserleer.exceptions.ValidationException;
import org.fuserleer.ledger.StateAddress;
import org.fuserleer.ledger.StateField;
import org.fuserleer.ledger.StateMachine;
import org.fuserleer.ledger.StateOp;
import org.fuserleer.ledger.StateOp.Instruction;
import org.fuserleer.ledger.atoms.Particle;
import org.fuserleer.ledger.atoms.SignedParticle;
import org.fuserleer.logging.Logger;
import org.fuserleer.logging.Logging;
import org.fuserleer.serialization.DsonOutput;
import org.fuserleer.serialization.DsonOutput.Output;
import org.fuserleer.serialization.SerializerId2;
import org.fuserleer.utils.Longs;
import org.fuserleer.utils.Numbers;
import org.fuserleer.utils.UInt256;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
@SerializerId2("apps.twitter.tweet")
public class TweetParticle extends SignedParticle
{
private static final Logger twitterLog = Logging.getLogger("twitter");
public static int MIN_TEXT_LENGTH = 3;
public static int MAX_TEXT_LENGTH = 512;
public static int MAX_HASH_TAGS = 32;
public static int MAX_MENTIONS = 32;
public static int MAX_MEDIA = 4;
@JsonProperty("id")
@DsonOutput(Output.ALL)
private Hash id;
@JsonProperty("user")
@DsonOutput(Output.ALL)
private String user;
@JsonProperty("created_at")
@DsonOutput(Output.ALL)
private long createdAt;
@JsonProperty("text")
@DsonOutput(Output.ALL)
private String text;
@JsonProperty("reply_to")
@DsonOutput(Output.ALL)
private Hash replyTo;
@JsonProperty("retweet_of")
@DsonOutput(Output.ALL)
private Hash retweetOf;
@JsonProperty("media")
@JsonDeserialize(as=LinkedHashSet.class)
@DsonOutput(Output.ALL)
private Set<Hash> media;
private transient Set<String> hashtags;
private transient Set<String> mentions;
TweetParticle()
{
super();
}
public TweetParticle(final long id, final String user, final String text, final Collection<Hash> media, final Hash replyTo, final Hash retweetOf, final long createdAt, final Identity owner)
{
super(Spin.UP, owner);
this.id = new Hash(Arrays.copyOf(Longs.toByteArray(id), Hash.BYTES));
this.user = user;
this.text = text;
this.replyTo = replyTo;
this.retweetOf = retweetOf;
this.createdAt = createdAt;
if (media != null && media.isEmpty() == false)
this.media = new LinkedHashSet<Hash>(media);
extractHashTags();
extractMentions();
verifyArguments();
}
public Hash getID()
{
return this.id;
}
public String getUser()
{
return this.user;
}
public long getCreatedAt()
{
return this.createdAt;
}
public String getText()
{
return this.text;
}
private void extractHashTags()
{
Objects.requireNonNull(this.text, "Text is null");
this.hashtags = new LinkedHashSet<String>();
// TODO Trims the # from the match... seems sensible as we know what it is, but maybe it should be included in full form?
// Pattern pattern = Pattern.compile("(?<=^#|\\s+#)([A-Za-z0-9_-]+)");
Pattern pattern = Pattern.compile("#[A-Za-z0-9_-]+");
Matcher matcher = pattern.matcher(this.text);
while(matcher.find() == true)
{
String hashtag = matcher.group();
if (this.hashtags.size() == TweetParticle.MAX_HASH_TAGS)
throw new IllegalStateException("Max hashtags of "+TweetParticle.MAX_HASH_TAGS+" reached");
this.hashtags.add(hashtag.substring(1).toLowerCase());
}
}
private void extractMentions()
{
Objects.requireNonNull(this.text, "Text is null");
this.mentions = new LinkedHashSet<String>();
// TODO Trims the @ from the match leaving the user name only, as @ symbols
// are usually an indicator of a use, and not included in the user name
// Pattern pattern = Pattern.compile("(?<=^@|\\s+@)([A-Za-z0-9_-]+)");
Pattern pattern = Pattern.compile("@[A-Za-z0-9_-]+");
Matcher matcher = pattern.matcher(this.text);
while(matcher.find() == true)
{
String mention = matcher.group();
if (this.mentions.size() == TweetParticle.MAX_MENTIONS)
throw new IllegalStateException("Max mentions of "+TweetParticle.MAX_MENTIONS+" reached");
this.mentions.add(mention.substring(1).toLowerCase());
}
}
@SuppressWarnings("unchecked")
@JsonProperty("hashtags")
@DsonOutput(Output.ALL)
public Collection<String> getHashTags()
{
if (this.hashtags == null)
return Collections.EMPTY_LIST;
return new ArrayList<String>(this.hashtags);
}
@JsonProperty("hashtags")
private void setHashTags(Collection<String> hashtags)
{
if (hashtags == null || hashtags.isEmpty())
return;
this.hashtags = new LinkedHashSet<String>();
hashtags.forEach(hashtag -> this.hashtags.add(hashtag.toLowerCase()));
}
public int hashTagCount()
{
if (this.hashtags == null)
return 0;
return this.hashtags.size();
}
@SuppressWarnings("unchecked")
@JsonProperty("mentions")
@DsonOutput(Output.ALL)
public Collection<String> getMentions()
{
if (this.mentions == null)
return Collections.EMPTY_LIST;
return new ArrayList<String>(this.mentions);
}
@JsonProperty("mentions")
private void setMentions(Collection<String> mentions)
{
if (mentions == null || mentions.isEmpty())
return;
this.mentions = new LinkedHashSet<String>();
mentions.forEach(mention -> this.mentions.add(mention.toLowerCase()));
}
public int mentionsCount()
{
if (this.mentions == null)
return 0;
return this.mentions.size();
}
@SuppressWarnings("unchecked")
public Collection<Hash> getMedia()
{
if (this.media == null)
return Collections.EMPTY_LIST;
return new ArrayList<Hash>(this.media);
}
public int mediaCount()
{
if (this.media == null)
return 0;
return this.media.size();
}
public Hash getReplyTo()
{
return this.replyTo;
}
public Hash getRetweetOf()
{
return this.retweetOf;
}
private void verifyArguments()
{
Objects.requireNonNull(this.text, "Text is null");
Numbers.inRange(this.text.length(), TweetParticle.MIN_TEXT_LENGTH, TweetParticle.MAX_TEXT_LENGTH, "Test length "+this.text.length()+" is not in range "+TweetParticle.MIN_TEXT_LENGTH+" -> "+TweetParticle.MAX_TEXT_LENGTH);
Numbers.lessThan(this.createdAt, Universe.getDefault().getTimestamp(), "Created time "+this.createdAt+" is before genesis time "+Universe.getDefault().getTimestamp());
// Hashtags
if (this.hashtags != null)
{
Numbers.greaterThan(this.hashtags.size(), TweetParticle.MAX_HASH_TAGS, "Hashtags exceeds max of "+TweetParticle.MAX_HASH_TAGS);
for (String hashTag : this.hashtags)
{
Numbers.isZero(hashTag.length(), "Hashtag length is zero");
if (this.text.toLowerCase().contains("#"+hashTag.toLowerCase()) == false)
throw new IllegalStateException("Tweet doesn't contain hashtag "+hashTag.toLowerCase());
}
}
// Mentions
if (this.mentions != null)
{
Numbers.greaterThan(this.mentions.size(), TweetParticle.MAX_MENTIONS, "Mentions exceeds max of "+TweetParticle.MAX_MENTIONS);
for (String mention : this.mentions)
{
Numbers.isZero(mention.length(), "Mention length is zero");
if (this.text.toLowerCase().contains("@"+mention.toLowerCase()) == false)
throw new IllegalStateException("Tweet doesn't contain mention "+mention.toLowerCase());
}
}
// Media
if (this.media != null)
Numbers.greaterThan(this.media.size(), TweetParticle.MAX_MEDIA, "Maximum media items is "+TweetParticle.MAX_MEDIA);
if (this.replyTo != null)
Hash.notZero(this.replyTo, "Reply hash is ZERO");
if (this.retweetOf != null)
Hash.notZero(this.retweetOf, "Retweet hash is ZERO");
if (this.replyTo != null && this.retweetOf != null)
throw new IllegalStateException("Tweets can not be a reply and retweet");
// User
Objects.requireNonNull(this.user, "User is null");
Numbers.inRange(this.user.length(), TwitterUserRegistration.MIN_HANDLE_LENGTH, TwitterUserRegistration.MAX_HANDLE_LENGTH, "User Handle "+this.user+" length "+this.user.length()+" is not in range "+TwitterUserRegistration.MIN_HANDLE_LENGTH+" -> "+TwitterUserRegistration.MAX_HANDLE_LENGTH);
}
@Override
public void prepare(StateMachine stateMachine) throws ValidationException, IOException
{
try
{
verifyArguments();
}
catch (NullPointerException | IllegalStateException | IllegalArgumentException ex)
{
// Can just throw the causes as they are uncaught exceptions?
throw new ValidationException(ex);
}
stateMachine.sop(new StateOp(new StateAddress(TweetParticle.class, this.id), Instruction.GET), this);
stateMachine.sop(new StateOp(new StateAddress(TweetParticle.class, this.id), Instruction.NOT_EXISTS), this);
stateMachine.sop(new StateOp(new StateField(this.id, "replies"), Instruction.GET), this);
stateMachine.sop(new StateOp(new StateField(this.id, "replies"), Instruction.NOT_EXISTS), this);
stateMachine.sop(new StateOp(new StateField(this.id, "retweets"), Instruction.GET), this);
stateMachine.sop(new StateOp(new StateField(this.id, "retweets"), Instruction.NOT_EXISTS), this);
stateMachine.sop(new StateOp(new StateAddress(TwitterUserRegistration.class, Hash.from(this.user.toLowerCase())), Instruction.EXISTS), this);
if (this.replyTo != null)
{
stateMachine.sop(new StateOp(new StateAddress(TweetParticle.class, this.replyTo), Instruction.EXISTS), this);
stateMachine.sop(new StateOp(new StateField(this.replyTo, "replies"), Instruction.GET), this);
}
if (this.retweetOf != null)
{
stateMachine.sop(new StateOp(new StateAddress(TweetParticle.class, this.retweetOf), Instruction.EXISTS), this);
stateMachine.sop(new StateOp(new StateField(this.retweetOf, "retweets"), Instruction.GET), this);
}
if (this.media != null)
this.media.forEach(media -> stateMachine.sop(new StateOp(new StateAddress(Particle.class, media), Instruction.EXISTS), this));
super.prepare(stateMachine);
}
@Override
public void execute(StateMachine stateMachine) throws ValidationException, IOException
{
stateMachine.sop(new StateOp(new StateAddress(TweetParticle.class, this.id), UInt256.from(this.id.toByteArray()), Instruction.SET), this);
stateMachine.sop(new StateOp(new StateField(this.id, "replies"), UInt256.ZERO, Instruction.SET), this);
stateMachine.sop(new StateOp(new StateField(this.id, "retweets"), UInt256.ZERO, Instruction.SET), this);
if (this.replyTo != null && this.replyTo.equals(Hash.ZERO) == false)
{
Optional<UInt256> replies = stateMachine.getInput(new StateField(this.replyTo, "replies"));
stateMachine.sop(new StateOp(new StateField(this.replyTo, "replies"), replies.get().increment(), Instruction.SET), this);
stateMachine.associate(this.replyTo, this);
}
if (this.retweetOf != null && this.retweetOf.equals(Hash.ZERO) == false)
{
Optional<UInt256> retweets = stateMachine.getInput(new StateField(this.retweetOf, "retweets"));
stateMachine.sop(new StateOp(new StateField(this.retweetOf, "retweets"), retweets.get().increment(), Instruction.SET), this);
}
// ASSOCIATIONS //
Set<Hash> associations = new HashSet<Hash>();
associations.add(Hash.from(this.user));
// Concatenated user + owner for faster searches
associations.add(Hash.from(Hash.from(this.user), getOwner().asHash()));
if (this.hashtags != null)
{
for (String hashTag : this.hashtags)
associations.add(Hash.from(hashTag));
}
if (this.mentions != null)
{
for (String mention : this.mentions)
associations.add(Hash.from(mention));
}
for (Hash association : associations)
stateMachine.associate(association, this);
}
@Override
public boolean isConsumable()
{
return false;
}
@Override
public String toString()
{
return super.toString()+" "+this.id+" "+this.user+" "+this.createdAt+" "+this.text;
}
}
|
import javax.swing.*;
import java.util.ArrayList;
public class StudentListModel extends AbstractListModel<String> {
ArrayList<String> arrayList;
public StudentListModel() {
super();
arrayList = new ArrayList<String>();
}
public ArrayList<String> getArrayList() {
return arrayList;
}
public void add (String string) {
arrayList.add(string);
}
public void deleteAll() {
arrayList.clear();
}
@Override
public int getSize() {
return arrayList.size();
}
@Override
public String getElementAt(int i) {
return arrayList.get(i);
}
public void pushBack(String student) {
arrayList.add(student);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.