text
stringlengths 10
2.72M
|
|---|
package devtec.co.mz.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import lombok.Data;
//@Data e da biblioteca lombok, gera os getters e setters em tempo de execucao
@Data
@SuppressWarnings("serial")
@Entity
@Table(name="Reposicao_Has_Venda")
public class ReposicaoVenda extends AbstractEntity<Long>{
@ManyToOne
@JoinColumn(name="venda_id")
private Venda venda;
@ManyToOne
@JoinColumn(name="reposicao_id")
private Reposicao reposicao;
@Column(name="preco")
private Double preco;
@Column(name="quantidade")
Integer quantidade;
public Venda getVenda() {
return venda;
}
public void setVenda(Venda venda) {
this.venda = venda;
}
public Reposicao getReposicao() {
return reposicao;
}
public void setReposicao(Reposicao reposicao) {
this.reposicao = reposicao;
}
public Double getPreco() {
return preco;
}
public void setPreco(Double preco) {
this.preco = preco;
}
public Integer getQuantidade() {
return quantidade;
}
public void setQuantidade(Integer quantidade) {
this.quantidade = quantidade;
}
}
|
package com.rishi.baldawa.iq;
import java.util.Arrays;
/*
Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
*/
public class RotateArray {
public void rotate(int[] nums, int k) {
int rotation = k % nums.length;
if (rotation != 0) {
reverse(nums, 0, nums.length - 1);
reverse(nums, 0, rotation - 1);
reverse(nums, rotation, nums.length - 1);
}
}
private void reverse(int[] nums, int left, int right) {
int tmp = 0;
while(left < right) {
tmp = nums[left];
nums[left] = nums[right];
nums[right] = tmp;
left += 1;
right -= 1;
}
}
}
|
package cbde.labs.hbase_mapreduce.writer;
public class MyHBaseWriter_KeyDesign extends MyHBaseWriter {
protected String nextKey() {
String new_key;
new_key = this.data.get("type")+"-"+this.data.get("region")+"-"+this.key;
return new_key;
}
}
|
package com.elepy.tests;
import com.elepy.annotations.*;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.math.BigDecimal;
import java.util.Date;
@RestModel(name = "Products", slug = "/products")
@Create(requiredPermissions = {})
@Delete(requiredPermissions = {})
@Update(requiredPermissions = {})
@Find(requiredPermissions = {})
@Entity(name = "Products")
@Table(name = "products")
public class Product {
@PrettyName("Product ID")
@Identifier(generated = false)
@Id
private Integer id;
@PrettyName("Price")
private BigDecimal price;
@DateTime()
@PrettyName("Expiration Date")
private Date date;
@TrueFalse(trueValue = "This product is awesome", falseValue = "This product is meh")
private boolean awesome;
public boolean isAwesome() {
return awesome;
}
public void setAwesome(boolean awesome) {
this.awesome = awesome;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
}
|
package com.zp.feignclient;
import com.sun.org.apache.regexp.internal.RE;
import org.springframework.stereotype.Component;
@Component
public class FeignClientFallBack implements ResumeFeignClient {
@Override
public Integer findDefaultResumeState(Long userId) {
return -1;
}
}
|
/*
* Copyright 2002-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.springframework.integration.splunk.support;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.messaging.MessageHandlingException;
import org.springframework.integration.splunk.core.DataReader;
import org.springframework.integration.splunk.core.DataWriter;
import org.springframework.integration.splunk.event.SplunkEvent;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessagingException;
/**
* Bundles common core logic for the Splunk components.
*
* @author Jarred Li
* @author David Turanski
* @since 1.0
*
*/
public class SplunkExecutor {
private static final Log logger = LogFactory.getLog(SplunkExecutor.class);
private DataReader reader;
private DataWriter writer;
/**
* Executes the outbound Splunk Operation.
*/
public Object write(final Message<?> message) {
try {
SplunkEvent payload = (SplunkEvent) message.getPayload();
writer.write(payload);
} catch (Exception e) {
String errorMsg = "error in writing data into Splunk";
logger.warn(errorMsg, e);
throw new MessageHandlingException(message, errorMsg, e);
}
return null;
}
public void handleMessage(final Message<?> message) {
write(message);
}
/**
* Execute the Splunk operation.
*/
public List<SplunkEvent> poll() {
logger.debug("poll start:");
List<SplunkEvent> queryData = null;
try {
queryData = reader.read();
} catch (Exception e) {
String errorMsg = "search Splunk data failed";
logger.warn(errorMsg, e);
throw new MessagingException(errorMsg, e);
}
return queryData;
}
public void setReader(DataReader reader) {
this.reader = reader;
}
public void setWriter(DataWriter writer) {
this.writer = writer;
}
}
|
/**
*
*/
package com.cnk.travelogix.b2c.storefront.controllers.pages;
import de.hybris.platform.acceleratorstorefrontcommons.controllers.pages.AbstractPageController;
import de.hybris.platform.cms2.exceptions.CMSItemNotFoundException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* @author i322561
*
*/
@Controller
@Scope("tenant")
@RequestMapping(value = "/", method = RequestMethod.GET)
public class TestPageController extends AbstractPageController
{
//CMS Pages
private static final String WISHLIST_CMS_PAGE = "ezgb2cWishlistPage";
private static final String CONFIRM_PASSWORD_PAGE = "completeAccPage";
private static final String SIGNUP_PAGE = "signupPage";
private static final String WALLET_CMS_PAGE = "ezgb2cWalletPage";
private static final String SETTINGS_CMS_PAGE = "ezgb2cSettingsPage";
private static final String BOOKING_LIST_PAGE = "ezgb2cbookinglistpage";
private static final String AMEND_CANCEL_ALL_PRODUCTS_PAGE = "ezgb2cAmendCancelAllProductsPage";
@RequestMapping(value = "/wishlist", method = RequestMethod.GET)
public String getWishlist(final HttpServletRequest request, final Model model) throws CMSItemNotFoundException
{
storeCmsPageInModel(model, getContentPageForLabelOrId(WISHLIST_CMS_PAGE));
setUpMetaDataForContentPage(model, getContentPageForLabelOrId(WISHLIST_CMS_PAGE));
return "pages/ezg/account/wishlistPage";
}
@RequestMapping(value = "/wishlistAuth", method = RequestMethod.GET)
public String getWishlistAuth(final HttpServletRequest request, final Model model) throws CMSItemNotFoundException
{
storeCmsPageInModel(model, getContentPageForLabelOrId(WISHLIST_CMS_PAGE));
setUpMetaDataForContentPage(model, getContentPageForLabelOrId(WISHLIST_CMS_PAGE));
return "pages/ezg/account/wishlistPage";
}
@RequestMapping(value = "/completeAcc", method = RequestMethod.GET)
public String getCompleteAcc(final HttpServletRequest request, final Model model) throws CMSItemNotFoundException
{
storeCmsPageInModel(model, getContentPageForLabelOrId(CONFIRM_PASSWORD_PAGE));
setUpMetaDataForContentPage(model, getContentPageForLabelOrId(CONFIRM_PASSWORD_PAGE));
return "pages/ezg/account/completeAccPage";
}
// @RequestMapping(value = "/signup", method = RequestMethod.GET)
// public String getSignup(final HttpServletRequest request, final Model model) throws CMSItemNotFoundException
// {
// storeCmsPageInModel(model, getContentPageForLabelOrId(SIGNUP_PAGE));
// setUpMetaDataForContentPage(model, getContentPageForLabelOrId(SIGNUP_PAGE));
//
// return "pages/ezg/account/signupPage";
// }
//
// @RequestMapping(value = "/wallet", method = RequestMethod.GET)
// public String getWallet(final HttpServletRequest request, final Model model) throws CMSItemNotFoundException
// {
// storeCmsPageInModel(model, getContentPageForLabelOrId(WALLET_CMS_PAGE));
// setUpMetaDataForContentPage(model, getContentPageForLabelOrId(WALLET_CMS_PAGE));
//
// return "pages/ezg/account/walletPage";
// }
//
// @RequestMapping(value = "/settings", method = RequestMethod.GET)
// public String getSettings(final HttpServletRequest request, final Model model) throws CMSItemNotFoundException
// {
// storeCmsPageInModel(model, getContentPageForLabelOrId(SETTINGS_CMS_PAGE));
// setUpMetaDataForContentPage(model, getContentPageForLabelOrId(SETTINGS_CMS_PAGE));
//
// return "pages/ezg/account/settingsPage";
// }
// @RequestMapping(value = "/bookList", method = RequestMethod.GET)
// public String getBookingList(final HttpServletRequest request, final Model model) throws CMSItemNotFoundException
// {
// storeCmsPageInModel(model, getContentPageForLabelOrId(BOOKING_LIST_PAGE));
// setUpMetaDataForContentPage(model, getContentPageForLabelOrId(BOOKING_LIST_PAGE));
//
// return "pages/ezg/cart/bookingList";
// }
@RequestMapping(value = "/amendCancelAllProduct", method = RequestMethod.GET)
public String getAmendCancelAllProduct(final HttpServletRequest request, final Model model) throws CMSItemNotFoundException
{
storeCmsPageInModel(model, getContentPageForLabelOrId(AMEND_CANCEL_ALL_PRODUCTS_PAGE));
setUpMetaDataForContentPage(model, getContentPageForLabelOrId(AMEND_CANCEL_ALL_PRODUCTS_PAGE));
return "pages/ezg/cart/amendCancelAllproducts";
}
}
|
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.sql.Statement;
public class Search {
Search()
{
JFrame fs=new JFrame("Search Students");
JLabel nm,id,rpt;
JTextField nmf,idf,rptf;
JButton sch,bck,del;
JLabel id1=new JLabel("ID:"),nm1=new JLabel("NAME:"),mn1=new JLabel("MOB NO:"),mn2=new JLabel("MOB NO:"),w1=new JLabel("WHATSAPP:"),em1=new JLabel("EMAIL:"),s1=new JLabel("SEX"),db1=new JLabel("DOB:"),ad1=new JLabel("ADDRESS:"),emp1=new JLabel("EMPLOYED:"),cr1=new JLabel("COURSES:"),ed1=new JLabel("EDUCATION:"),fe1=new JLabel("TOTAL FEE:"),pd1=new JLabel("PAID FEE"),pn1=new JLabel("PENDING FEE:"),da1=new JLabel("ADMISSION:"),rec1=new JLabel("RECEIPT NO:"),sc1=new JLabel("SCHEDULE:");
JLabel id1f=new JLabel(),nm1f=new JLabel(),mn1f=new JLabel(),mn2f=new JLabel(),w1f=new JLabel(),em1f=new JLabel(),s1f=new JLabel(),db1f=new JLabel(),ad1f=new JLabel(),emp1f=new JLabel(),cr1f=new JLabel(),ed1f=new JLabel(),fe1f=new JLabel(),pd1f=new JLabel(),pn1f=new JLabel(),da1f=new JLabel(),rec1f=new JLabel(),sc1f=new JLabel();
id1.setBounds(20,150,150,20); id1f.setBounds(140,150,450,20);
nm1.setBounds(20,190,150,20); nm1f.setBounds(140,190,450,20);
mn1.setBounds(20,230,150,20); mn1f.setBounds(140,230,450,20);
mn2.setBounds(20,270,150,20); mn2f.setBounds(140,270,450,20);
w1.setBounds(20,310,150,20); w1f.setBounds(140,310,450,20);
em1.setBounds(20,350,150,20); em1f.setBounds(140,350,450,20);
s1.setBounds(20,390,150,20); s1f.setBounds(140,390,450,20);
db1.setBounds(20,430,150,20); db1f.setBounds(140,430,450,20);
ad1.setBounds(20,470,150,20); ad1f.setBounds(140,470,450,20);
emp1.setBounds(630,150,150,20); emp1f.setBounds(740,150,450,20);
cr1.setBounds(630,190,150,20); cr1f.setBounds(740,190,450,20);
ed1.setBounds(630,230,150,20); ed1f.setBounds(740,230,450,20);
fe1.setBounds(630,270,150,20); fe1f.setBounds(740,270,450,20);
pd1.setBounds(630,310,150,20); pd1f.setBounds(740,310,450,20);
pn1.setBounds(630,350,150,20); pn1f.setBounds(740,350,450,20);
da1.setBounds(630,390,150,20); da1f.setBounds(740,390,450,20);
rec1.setBounds(630,430,150,20); rec1f.setBounds(740,430,450,20);
sc1.setBounds(630,470,150,20); sc1f.setBounds(740,470,450,20);
nm=new JLabel("NAME :"); id=new JLabel("ID :"); rpt=new JLabel("RECEIPT NO:"); JLabel tempf= new JLabel("RECORD DELETED SUCCESSFULLY.");
nmf=new JTextField(null); idf=new JTextField(null); rptf=new JTextField(null);
sch=new JButton("SEARCH"); bck=new JButton("BACK"); del=new JButton("DELETE RECORD"); del.setBackground(Color.RED);
nm.setBounds(10,20,150,20); id.setBounds(360,20,150,20); rpt.setBounds(630,20,150,20); tempf.setBounds(630,645,500,100);
nmf.setBounds(130,20,190,20); idf.setBounds(420,20,150,20); rptf.setBounds(760,20,150,20);
sch.setBounds(130,60,100,26); bck.setBounds(250,60,100,26); del.setBounds(740,620,180,26);
rptf.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
char character=e.getKeyChar();
if(((character<'0')||(character>'9'))&&(character !='\b') )
{
e.consume();
}
}
});
idf.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
char character=e.getKeyChar();
if(((character<'0')||(character>'9'))&&(character !='\b') )
{
e.consume();
}
}
});
bck.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
fs.setVisible(false);
}
});
sch.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// String nmfs,idfs,rptfs;
tempf.setVisible(false);
String idfs1 = idf.getText();String rptfs = rptf.getText();String nmfs = nmf.getText();
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("reg");
Connection con= DriverManager.getConnection("jdbc:mysql://localhost:3306/db1","root","amit123");
System.out.println("connected");
Statement st=con.createStatement();
try {
ResultSet rs = st.executeQuery("select * from admits where recipt=" + rptfs + "");
while (rs.next()) {
id1f.setText(String.valueOf(rs.getInt(1)));
nm1f.setText(rs.getString(2));
mn1f.setText(rs.getString(3));
mn2f.setText(rs.getString(4));
w1f.setText(rs.getString(5));
em1f.setText(rs.getString(6));
s1f.setText(rs.getString(7));
db1f.setText(rs.getString(8));
ad1f.setText(rs.getString(9));
emp1f.setText(rs.getString(10));
cr1f.setText(rs.getString(11));
ed1f.setText(rs.getString(12));
fe1f.setText(rs.getString(13));
pd1f.setText(rs.getString(14));
pn1f.setText(rs.getString(15));
da1f.setText(rs.getString(16));
rec1f.setText(String.valueOf(rs.getString(17)));
sc1f.setText(rs.getString(18));
// tempf.setText(rs.getString(2));//.setText(String.valueOf(rs.getInt(1)));
}
}catch (Exception e1)
{ try{
ResultSet rs1 = st.executeQuery("select * from admits where ID="+idfs1+"");
while (rs1.next()) {
id1f.setText(String.valueOf(rs1.getInt(1)));
nm1f.setText(rs1.getString(2));
mn1f.setText(rs1.getString(3));
mn2f.setText(rs1.getString(4));
w1f.setText(rs1.getString(5));
em1f.setText(rs1.getString(6));
s1f.setText(rs1.getString(7));
db1f.setText(rs1.getString(8));
ad1f.setText(rs1.getString(9));
emp1f.setText(rs1.getString(10));
cr1f.setText(rs1.getString(11));
ed1f.setText(rs1.getString(12));
fe1f.setText(rs1.getString(13));
pd1f.setText(rs1.getString(14));
pn1f.setText(rs1.getString(15));
da1f.setText(rs1.getString(16));
rec1f.setText(String.valueOf(rs1.getString(17)));
sc1f.setText(rs1.getString(18));
// tempf.setText(rs1.getString(2));
//.setText(String.valueOf(rs.getInt(1)));
}}catch (Exception e11){
ResultSet rs3 = st.executeQuery("select * from admits where name LIKE '%" + nmfs + "%'");
while (rs3.next()) {
id1f.setText(String.valueOf(rs3.getInt(1)));
nm1f.setText(rs3.getString(2));
mn1f.setText(rs3.getString(3));
mn2f.setText(rs3.getString(4));
w1f.setText(rs3.getString(5));
em1f.setText(rs3.getString(6));
s1f.setText(rs3.getString(7));
db1f.setText(rs3.getString(8));
ad1f.setText(rs3.getString(9));
emp1f.setText(rs3.getString(10));
cr1f.setText(rs3.getString(11));
ed1f.setText(rs3.getString(12));
fe1f.setText(rs3.getString(13));
pd1f.setText(rs3.getString(14));
pn1f.setText(rs3.getString(15));
da1f.setText(rs3.getString(16));
rec1f.setText(String.valueOf(rs3.getString(17)));
sc1f.setText(rs3.getString(18));
}
}
}
con.close();
del.setVisible(true);
}catch (Exception e1)
{
//tempf.setText("NOT FOUND / INVALID INPUT");
}
}
});
del.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e)throws ClassCastException {
String idel=id1f.getText();
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("reg");
Connection con1= DriverManager.getConnection("jdbc:mysql://localhost:3306/db1","root","amit123");
System.out.println("connected");
Statement st=con1.createStatement();
st.executeUpdate("delete from admits where id="+idel+"");
System.out.println("rec deleted");
tempf.setVisible(true);
} catch (Exception e1) {
System.out.println("rec not deleted");
e1.printStackTrace();
}
}
});
del.setVisible(false); tempf.setVisible(false);
fs.add(nm); fs.add(id); fs.add(rpt); fs.add(tempf);
fs.add(nmf); fs.add(idf); fs.add(rptf);
fs.add(sch); fs.add(bck); fs.add(del);
fs.add(id1); fs.add(nm1);fs.add(mn1);fs.add(mn2);fs.add(w1);fs.add(em1);fs.add(s1);fs.add(db1);fs.add(ad1);fs.add(emp1);fs.add(cr1);fs.add(ed1);fs.add(fe1);fs.add(pd1);fs.add(pn1);fs.add(da1);fs.add(rec1);fs.add(sc1);
fs.add(id1f); fs.add(nm1f);fs.add(mn1f);fs.add(mn2f);fs.add(w1f);fs.add(em1f);fs.add(s1f);fs.add(db1f);fs.add(ad1f);fs.add(emp1f);fs.add(cr1f);fs.add(ed1f);fs.add(fe1f);fs.add(pd1f);fs.add(pn1f);fs.add(da1f);fs.add(rec1f);fs.add(sc1f);
fs.setSize(1366,768);
fs.setLayout(null);
fs.setVisible(true);
}
}
|
package org.campustalk.sql;
import org.campustalk.entity.CampusTalkRoles;
//import com.mysql.jdbc.CallableStatement;
//import org.campustalk.ArrayList;
//import org.campustalk.ResultSet;
import java.util.*;
import java.sql.*;
public class dbRole extends DatabaseManager {
public dbRole()
{ super(); }
public CampusTalkRoles objrole[]=new CampusTalkRoles[10];
public CampusTalkRoles[] getRoleData()throws SQLException, ClassNotFoundException
{
this.open();
CallableStatement csSql = CON
.prepareCall("{call getAllRoleData()}");
ResultSet rs = csSql.executeQuery();
ArrayList<CampusTalkRoles> role = new ArrayList<>();
CampusTalkRoles temp_role;
while(rs.next())
{
temp_role = new CampusTalkRoles();
//temp_role.setroleId(rs.getInt("roleid"));
temp_role.setRoleId(rs.getInt("roleid"));
temp_role.setName(rs.getString("name"));
role.add(temp_role);
}
return role.toArray(new CampusTalkRoles[role.size()]);
/*while(rs.next())
{
objrole[i].setName(rs.getString("name"));
i++;
}
return objrole;*/
}
}
|
import java.util.Scanner;
//package Arrays.1d;
public class SortIn012 {
public static void main(String[] args){
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
int[] arr=new int[n];
for (int i = 0; i <=n-1 ; i++) {
arr[i]=scan.nextInt();
}
sort(arr);
System.out.println("");
System.out.println("");
for (int i : arr) {
System.out.println(i);
}
}
public static void sort(int[] arr){
int zerocounter=0;
int traverser=0;
int twocounter=arr.length-1;
while(traverser<=twocounter){
if(arr[traverser]==0){
swap(arr,traverser,zerocounter);
zerocounter++;
traverser++;
}
else if(arr[traverser]==1){
traverser++;
}
else{
swap(arr,traverser,twocounter);
twocounter--;
}
}
}
public static void swap(int[] arr,int i ,int j){
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
|
package com.spbsu.flamestream.runtime.state;
import akka.serialization.Serialization;
import com.spbsu.flamestream.core.data.meta.GlobalTime;
import com.spbsu.flamestream.core.graph.HashUnit;
import com.spbsu.flamestream.runtime.graph.state.GroupingState;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import scala.util.Try;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
public class RedisStateStorage implements StateStorage {
private final JedisPool jedisPool;
private final Serialization serialization;
public RedisStateStorage(String host, int port, Serialization serialization) {
this.serialization = serialization;
this.jedisPool = new JedisPool(host, port);
}
@Override
public Map<String, GroupingState> stateFor(HashUnit unit, GlobalTime time) {
try (final Jedis jedis = jedisPool.getResource()) {
final String key = unit.id() + '@' + time.toString();
final byte[] data = jedis.get(key.getBytes());
if (data != null) {
final Try<Map> trie = serialization.deserialize(data, Map.class);
//noinspection unchecked
return (Map<String, GroupingState>) trie.get();
} else {
return new ConcurrentHashMap<>();
}
}
}
@Override
public void putState(HashUnit unit, GlobalTime time, Map<String, GroupingState> state) {
try (final Jedis jedis = jedisPool.getResource()) {
final Set<String> keys = jedis.keys(unit.id() + '*');
if (keys.size() == 2) {
final String min = keys.stream().min(String::compareTo).get();
jedis.del(min);
}
final String key = unit.id() + '@' + time.toString();
final byte[] data = serialization.serialize(state).get();
jedis.set(key.getBytes(), data);
}
}
public void clear() {
try (final Jedis jedis = jedisPool.getResource()) {
jedis.flushAll();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
@Override
public void close() throws Exception {
jedisPool.close();
}
}
|
package com.sdk4.boot.api.user;
import com.sdk4.boot.apiengine.ApiResponse;
import com.sdk4.boot.apiengine.ApiService;
import com.sdk4.boot.apiengine.RequestContent;
import com.sdk4.boot.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* 用户信息
*/
@Service("BootUserInfo")
public class UserInfo implements ApiService {
@Autowired
AuthService authService;
@Override
public String method() {
return "user.info";
}
@Override
public boolean requiredLogin() {
return true;
}
@Override
public ApiResponse call(RequestContent rc) {
return new ApiResponse();
}
}
|
package com.library.bexam.service.impl;
import com.library.bexam.common.pojo.model.Result;
import com.library.bexam.dao.PaperContentDao;
import com.library.bexam.dao.PaperDao;
import com.library.bexam.entity.PaperContentEntity;
import com.library.bexam.entity.PaperEntity;
import com.library.bexam.entity.QuestionEntity;
import com.library.bexam.service.PaperService;
import com.library.bexam.util.ConvertResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
/**
* @author JayChen
*/
@Service
public class PaperServiceImpl implements PaperService {
@Autowired
private PaperDao paperDao;
@Autowired
private PaperContentDao paperContentDao;
/**
* 添加试卷
*
* @return boolean
* @author JayChen
*/
@Override
public Result add(List<PaperEntity> paperEntityList) {
if(paperEntityList==null || paperEntityList.isEmpty()){
return ConvertResult.getParamErrorResult("试题信息不能为空");
}
boolean addResult = paperDao.add(paperEntityList);
if (addResult) {
for (PaperEntity paperEntity : paperEntityList) {
// 先添加标题
List<PaperContentEntity> titleList = paperEntity.getPaperContent();
for (PaperContentEntity paperContentEntity : titleList) {
paperContentEntity.setPaperId(paperEntity.getPaperId());
}
addResult = paperContentDao.addTitle(titleList);
if (addResult) {
for (PaperContentEntity paperContentEntity : titleList) {
Set<String> questionIdSet=new HashSet<>();
List<PaperContentEntity> list=new ArrayList<>();
List<PaperContentEntity> questionList = paperContentEntity.getQuestions();
if(questionList!=null && !questionList.isEmpty()){
for(PaperContentEntity paperContent:questionList){
if(!questionIdSet.contains(paperContent.getQuestionId())){
list.add(paperContent);
questionIdSet.add(paperContent.getQuestionId());
}
}
paperContentDao.addQuestion(paperEntity.getPaperId(), paperContentEntity.getPaperContentId(), list);
//修改试题使用次数
paperContentDao.updateQuestionUseCount(list);
}
}
}
}
}
return ConvertResult.getSuccessResult(addResult);
}
/**
* 获取试卷列表
*
* @return List
* @author JayChen
*/
@Override
public List list(Map<String, Object> params) {
return paperDao.list(params);
}
/**
* 根据ID获取试卷信息
*
* @return PaperEntity
* @author JayChen
*/
@Override
public PaperEntity get(String paperId) {
PaperEntity paperEntity = paperDao.get(paperId);
List<PaperContentEntity> titleList = null;
if (paperEntity != null) {
titleList = paperContentDao.getTitleListByPaperId(paperId);
if (titleList != null) {
for (PaperContentEntity paperContentEntity : titleList) {
paperContentEntity.setQuestions(paperContentDao.getQuestionListByTitleId(paperContentEntity.getPaperContentId()));
}
}
paperEntity.setPaperContent(titleList);
}
return paperEntity;
}
/**
* 修改试卷
*
* @return boolean
* @author JayChen
*/
@Override
public boolean update(PaperEntity paperEntity) {
return paperDao.update(paperEntity);
}
@Override
public boolean updateContent(PaperEntity paperEntity) {
return false;
}
/**
* 批量删除试卷
*
* @return boolean
* @author JayChen
*/
@Override
public boolean delete(String[] paperIdArray) {
boolean deleteResult = paperDao.delete(paperIdArray);
if (deleteResult) {
paperContentDao.deleteByPaperIds(paperIdArray);
}
return deleteResult;
}
}
|
package com.sda.project.model;
public enum ItemType {
BUG, TASK, FEATURE;
}
|
package com.thomaster.ourcloud.repositories.file;
import javax.persistence.*;
@Entity
class PersistentUploadedFolder extends PersistentFileSystemElement {
@Override
public String toString() {
return "UploadedFolder{" +
"originalName='" + getOriginalName() + '\'' +
'}';
}
}
|
package ch.springcloud.lite.core.model;
import java.util.List;
import lombok.Data;
@Data
public class CloudService {
String name;
List<CloudMethod> methods;
}
|
package com.elepy.mongo.querybuilding;
import com.elepy.dao.Filter;
import com.elepy.exceptions.ElepyException;
import java.util.regex.Pattern;
public class MongoFilterTemplateFactory {
public static MongoFilterTemplate fromFilter(Filter filter) {
switch (filter.getFilterType()) {
case EQUALS:
return new MongoFilterTemplate("$eq", filter.getFilterableField(), filter.getFilterValue());
case NOT_EQUALS:
return new MongoFilterTemplate("$ne", filter.getFilterableField(), filter.getFilterValue());
case GREATER_THAN:
return new MongoFilterTemplate("$gt", filter.getFilterableField(), filter.getFilterValue());
case GREATER_THAN_OR_EQUALS:
return new MongoFilterTemplate("$gte", filter.getFilterableField(), filter.getFilterValue());
case LESSER_THAN:
return new MongoFilterTemplate("$lt", filter.getFilterableField(), filter.getFilterValue());
case LESSER_THAN_OR_EQUALS:
return new MongoFilterTemplate("$lte", filter.getFilterableField(), filter.getFilterValue());
case CONTAINS:
final Pattern pattern = Pattern.compile(".*" + filter.getFilterValue() + ".*", Pattern.CASE_INSENSITIVE);
return new MongoFilterTemplate("$regex", filter.getFilterableField(), pattern.toString());
}
throw new ElepyException("Mongo does not support: " + filter.getFilterType().getName());
}
}
|
package be.continuum.slice.model;
import be.continuum.slice.event.PhoneNumberAddedEvent;
import be.continuum.slice.event.CustomerDataChangedEvent;
import be.continuum.slice.event.PhoneNumberRemovedEvent;
import be.continuum.slice.value.FoodAllergen;
import be.continuum.slice.value.PhoneNumber;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.ToString;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.ForeignKey;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.MapKeyColumn;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import static lombok.AccessLevel.PRIVATE;
/**
* Customer
*
* @author bartgerard
* @version v0.0.1
*/
@Entity
@NoArgsConstructor(access = PRIVATE)
@AllArgsConstructor(access = PRIVATE)
@Getter
@Builder
@EqualsAndHashCode(of = "username")
@ToString
public class Customer {
@Id
private String username;
private String email;
private String firstName;
private String lastName;
@Embedded
@ElementCollection
@CollectionTable(
name = "customer_phone",
joinColumns = @JoinColumn(name = "customer_id"),
foreignKey = @ForeignKey(name = "fk_customer_phone")
)
private final Set<PhoneNumber> phoneNumbers = new HashSet<>();
@Enumerated(EnumType.STRING)
@ElementCollection
@CollectionTable(
name = "customer_allergen",
joinColumns = @JoinColumn(name = "customer_id"),
foreignKey = @ForeignKey(name = "fk_customer_allergen")
)
@Column(name = "allergen")
private final Set<FoodAllergen> allergens = new HashSet<>();
@ElementCollection
@CollectionTable(
name = "customer_address",
joinColumns = @JoinColumn(name = "customer_id"),
foreignKey = @ForeignKey(name = "fk_customer_address")
)
@MapKeyColumn(name = "alias") // alternative more specific annotations : @MapKeyEnumerated, ...
private final Map<String, Address> addresses = new HashMap<>();
public void handle(final CustomerDataChangedEvent customerDataChangedEvent) {
this.email = customerDataChangedEvent.getEmail();
this.firstName = customerDataChangedEvent.getFirstName();
this.lastName = customerDataChangedEvent.getLastName();
}
public void handle(final PhoneNumberAddedEvent phoneNumberAddedEvent) {
this.phoneNumbers.add(phoneNumberAddedEvent.getPhoneNumber());
}
public void handle(final PhoneNumberRemovedEvent phoneNumberRemovedEvent) {
this.phoneNumbers.remove(phoneNumberRemovedEvent.getPhoneNumber());
}
public void addAllergen(final FoodAllergen allergen) {
this.allergens.add(allergen);
}
public void removeAllergen(final FoodAllergen allergen) {
this.allergens.remove(allergen);
}
public void addAddress(
final String alias,
final Address address
) {
this.addresses.put(alias, address);
}
public void removeAddress(final String alias) {
this.addresses.remove(alias);
}
}
|
package com.sinata.rwxchina.component_aboutme.contract;
import com.sinata.rwxchina.basiclib.utils.retrofitutils.entity.PageInfo;
import com.sinata.rwxchina.basiclib.utils.rxUtils.BaseContract;
import com.sinata.rwxchina.component_aboutme.bean.IntegralBean;
import java.util.Map;
/**
* @author:zy
* @detetime:2017/12/27
* @describe:类描述
* @modifyRecord:修改记录
*/
public interface IntegralContract {
interface View extends BaseContract.BaseView{
void showView(IntegralBean integralBean,boolean isRefresh);
void getPage(PageInfo pageInfo);
void showLoadMore(IntegralBean integralBean);
}
interface Presenter<T> extends BaseContract.BasePresenter<T>{
void getData(boolean isRefresh);
void loadMore(Map<String,String> params);
}
}
|
/**
* OpenKM, Open Document Management System (http://www.openkm.com)
* Copyright (c) 2006-2015 Paco Avila & Josep Llort
*
* No bytes were intentionally harmed during the development of this application.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.openkm.kea;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.openrdf.query.BindingSet;
import org.openrdf.query.MalformedQueryException;
import org.openrdf.query.QueryEvaluationException;
import org.openrdf.query.QueryLanguage;
import org.openrdf.query.TupleQuery;
import org.openrdf.query.TupleQueryResult;
import org.openrdf.repository.Repository;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.RepositoryException;
import org.openrdf.repository.sail.SailRepository;
import org.openrdf.rio.RDFFormat;
import org.openrdf.rio.RDFParseException;
import org.openrdf.sail.memory.MemoryStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.openkm.bean.kea.Term;
import com.openkm.core.Config;
import com.openkm.frontend.client.util.StringIgnoreCaseComparator;
import com.openkm.kea.metadata.WorkspaceHelper;
import com.openkm.kea.tree.TermComparator;
/**
* @author jllort
*
*/
public class RDFREpository {
private static Logger log = LoggerFactory.getLogger(RDFREpository.class);
private static Repository SKOSRepository = null;
private static Repository OWLRepository = null;
private static RDFREpository instance;
private static List<Term> terms = null;
private static List<String> keywords = null;
/**
* getConnection
*/
public RepositoryConnection getSKOSConnection() throws RepositoryException {
if (SKOSRepository != null) {
return SKOSRepository.getConnection();
} else
throw new RepositoryException("SKOS Repository not started");
}
/**
* getConnection
*/
public RepositoryConnection getOWLConnection() throws RepositoryException {
if (OWLRepository != null) {
return OWLRepository.getConnection();
} else
throw new RepositoryException("OWL Repository not started");
}
/**
* RDFVocabulary
*/
private RDFREpository() {
if (!Config.KEA_THESAURUS_SKOS_FILE.equals("")) {
SKOSRepository = getSKOSMemStoreRepository();
loadTerms();
}
if (!Config.KEA_THESAURUS_OWL_FILE.equals("")) {
OWLRepository = getOWLMemStoreRepository();
}
}
/**
* getInstance
*/
public static synchronized RDFREpository getInstance() {
if (instance == null) {
instance = new RDFREpository();
}
return instance;
}
/**
* getTerms
*/
public List<Term> getTerms() {
if (terms == null || keywords == null) {
loadTerms();
}
return terms;
}
/**
* getTerms
*/
public List<String> getKeywords() {
if (terms == null || keywords == null) {
loadTerms();
}
return keywords;
}
/**
* loadTerms
*/
private void loadTerms() {
terms = new ArrayList<Term>();
keywords = new ArrayList<String>();
RepositoryConnection con = null;
TupleQuery query;
log.info("Loading skos terms in memory");
if (SKOSRepository != null) {
try {
con = SKOSRepository.getConnection();
query = con.prepareTupleQuery(QueryLanguage.SERQL, Config.KEA_THESAURUS_VOCABULARY_SERQL);
log.info("query:" + Config.KEA_THESAURUS_VOCABULARY_SERQL);
TupleQueryResult result;
result = query.evaluate();
while (result.hasNext()) {
BindingSet bindingSet = result.next();
Term term = new Term(bindingSet.getValue("UID").stringValue(), "");
terms.add(term);
keywords.add(term.getUid());
}
} catch (RepositoryException e) {
log.error("could not obtain connection to respository", e);
} catch (MalformedQueryException e) {
log.error(e.getMessage(), e);
} catch (QueryEvaluationException e) {
log.error(e.getMessage(), e);
} finally {
try {
con.close();
} catch (Throwable e) {
log.error("Could not close connection....", e);
}
}
}
// Sorting collections
Collections.sort(terms, new TermComparator());
Collections.sort(keywords, new StringIgnoreCaseComparator());
log.info("Finished loading skos terms in memory");
}
/**
* getSKOSMemStoreRepository
*/
private Repository getSKOSMemStoreRepository() {
InputStream is;
Repository repository = null;
String baseURL = Config.KEA_THESAURUS_BASE_URL;
log.info("Loading skos file in memory");
try {
log.info(WorkspaceHelper.RDF_SKOS_VOVABULARY_PATH);
is = new FileInputStream(WorkspaceHelper.RDF_SKOS_VOVABULARY_PATH);
repository = new SailRepository(new MemoryStore());
repository.initialize();
RepositoryConnection con = repository.getConnection();
con.add(is, baseURL, RDFFormat.RDFXML);
con.close();
log.info("New SAIL memstore created for SKOS RDF");
} catch (RepositoryException e) {
log.error("Cannot make connection to RDF repository.", e);
} catch (IOException e) {
log.error("cannot locate/read file", e);
e.printStackTrace();
} catch (RDFParseException e) {
log.error("Cannot parse file", e);
} catch (Throwable t) {
log.error("Unexpected exception loading repository", t);
}
log.info("Finished loading skos file in memory");
return repository;
}
/**
* getOWLMemStoreRepository
*/
private Repository getOWLMemStoreRepository() {
InputStream is;
Repository repository = null;
String baseURL = Config.KEA_THESAURUS_BASE_URL;
log.info("Loading owl file in memory");
try {
log.info(WorkspaceHelper.RDF_OWL_VOVABULARY_PATH);
is = new FileInputStream(WorkspaceHelper.RDF_OWL_VOVABULARY_PATH);
repository = new SailRepository(new MemoryStore());
repository.initialize();
RepositoryConnection con = repository.getConnection();
con.add(is, baseURL, RDFFormat.RDFXML);
con.close();
log.info("New SAIL memstore created for OWL RDF");
} catch (RepositoryException e) {
log.error("Cannot make connection to RDF repository.", e);
} catch (IOException e) {
log.error("cannot locate/read file", e);
e.printStackTrace();
} catch (RDFParseException e) {
log.error("Cannot parse file", e);
} catch (Throwable t) {
log.error("Unexpected exception loading repository", t);
}
log.info("Finished loading owl file in memory");
return repository;
}
}
|
package com.jasoftsolutions.mikhuna.activity;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import com.jasoftsolutions.mikhuna.R;
import com.jasoftsolutions.mikhuna.activity.fragment.ProblemReportFragment;
public class ProblemReportActivity extends BaseActivity {
private static final String TAG = ProblemReportActivity.class.getSimpleName();
private ProblemReportFragment problemReportFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_problem_report);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_action_back);
addProblemReportFragment();
}
private void addProblemReportFragment() {
problemReportFragment = new ProblemReportFragment();
problemReportFragment.setArguments(getIntent().getExtras());
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction().add(R.id.container, problemReportFragment).commit();
}
@Override
protected void onResume() {
super.onResume();
}
}
|
package com.stackroute.challenge.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.util.UUID;
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Document(collection = "challenge")
public class Challenge {
@Id
private UUID challengeId;
private String challengerName;
private String[] challengeDomain;
private String challengeTitle;
private String challengeAbstract; //I make capital (Abstract) due to abstract keyword predefined in java
private String description;
private String rules;
}
|
package at.htl.mealcounter.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "M_DEVICE")
public class Device {
@Id
@Column(name = "DEVICE_ID")
public String deviceId;
public Device(String deviceId) {
this.deviceId = deviceId;
}
public Device() {
}
public String getDeviceId() {
return deviceId;
}
public void setDeviceId(String deviceId) {
this.deviceId = deviceId;
}
@Override
public String toString() {
return "Device{" +
"deviceId='" + deviceId + '\'' +
'}';
}
}
|
package GameState;
import Main.GamePanel;
import TileMap.*;
import XML.MainXML;
import java.awt.*;
import java.awt.event.KeyEvent;
import AlmacenTemp.Temp;
import Entidades.*;
public class LevelBase extends GameState {
MainXML Datos= new MainXML();
//private Temp guardarPaCambio;
public static boolean dosJug;
private SpritesExtra caraPlayer1;
private SpritesExtra caraPlayer2;
private SpritesExtra caraPlayer3;
private SpritesExtra debajoSalud;
private SpritesExtra barraSalud;
private SpritesExtra cara2Player;
private SpritesExtra debajoSalud2;
private SpritesExtra barraSalud2;
private TileMap tileMap;
private Background bg;
private MC player1;
private MC player2;
private MC bondFire;
private MC vendedor;
private MC botiquin;
private MC munExComp;
private String[] textoFlotante = {
"Arcade",
"Stage 1",
"2Player Arena",
};
private Font font;
public LevelBase(GameStateManager gsm) {
this.gsm = gsm;
init();
}
public void init() {
dosJug=false;
tileMap = new TileMap(30);
tileMap.loadTiles("/Tilesets/tileset.gif");
tileMap.loadMap("/Maps/MapaBase.map");
tileMap.setPosition(0, 0);
//tileMap.setTween(1);
bg = new Background("/Backgrounds/bg1.gif", 0.1);
//primer jugador
player1 = new MC(tileMap);
player1.playerNumber=1;
player1.setPosition(100, 1120);
//Cargar datos guardados a la clase
/**ANOTACION Markel:
* Now, these points of data
* Make a beautiful line.
* And we're out of beta.
* We're releasing on time!
* So I'm glad, I got burned
* Think of all the things we learned
* For the people who are
* Still alive.
*/
player1.setPelas(Temp.getPelas());
player1.setSalud(Temp.getSalud());
player1.setMunExp(Temp.getMunExp());
if(Temp.getDeDonde()==2){
player1.setPosition(950, 810);
}
Datos.GuardarDatos();
//segundo jugador
player2 = new MC(tileMap);
player2.playerNumber=2;
player2.setPlayerSkin();
player2.setPosition(80, 810);
/**ANOTACION Markel:
* Like in firelink shrine!
* how nostalgic...
**/
bondFire = new MC(tileMap);
bondFire.playerNumber=5;
bondFire.setPlayerSkin();
bondFire.setPosition(180, 1145);
bondFire.setZonaColision(20,20);
vendedor = new MC(tileMap);
vendedor.playerNumber=6;
vendedor.setPlayerSkin();
vendedor.setPosition(1080, 1020);
vendedor.update();
botiquin = new MC(tileMap);
botiquin.playerNumber=7;
botiquin.setPlayerSkin();
botiquin.setPosition(1050, 1020);
botiquin.update();
munExComp = new MC(tileMap);
munExComp.playerNumber=8;
munExComp.setPlayerSkin();
munExComp.setPosition(1110, 1020);
munExComp.update();
caraPlayer1 = new SpritesExtra("/Interfaz/P1Face.gif");
caraPlayer1.setPosition(0, 0);
caraPlayer2 = new SpritesExtra("/Interfaz/P1Face2.gif");
caraPlayer2.setPosition(0, 0);
caraPlayer3 = new SpritesExtra("/Interfaz/P1Face3.gif");
caraPlayer3.setPosition(0, 0);
debajoSalud = new SpritesExtra("/Interfaz/bajosalud.gif");
debajoSalud.setPosition(59, 1);
barraSalud = new SpritesExtra("/Interfaz/salud.gif");
barraSalud.setPosition(-1, 2);
cara2Player = new SpritesExtra("/Interfaz/P2Face.gif");
cara2Player.setPosition(0, 60);
debajoSalud2 = new SpritesExtra("/Interfaz/bajosalud.gif");
debajoSalud2.setPosition(59, 61);
barraSalud2 = new SpritesExtra("/Interfaz/salud.gif");
barraSalud2.setPosition(-1, 62);
barraSalud2.cambiarSalud(player2.getSalud());
font = new Font("Arial", Font.PLAIN, 10);
barraSalud.cambiarSalud(player1.getSalud());
}
public void update() {
vendedor.update();
botiquin.update();
munExComp.update();
// update player
player1.update();
bondFire.setDisparando();
bondFire.update();
if(dosJug==true){player2.update();}
tileMap.setPosition(
GamePanel.WIDTH / 2 - player1.getx(),
GamePanel.HEIGHT / 2 - player1.gety()
);
/*if(muereunlanzabombas){
explosiones.add(new Explosion(enemigo.getX(), enemigo.getY()));
}*/
//background movimiento
//bg.setPosition(tileMap.getx(), tileMap.gety());
}
public void draw(Graphics2D g) {
//System.out.println(player1.getx()+"-----"+player1.gety());
//System.out.println(player1.getSalud());
// dibujar bg
bg.draw(g);
// dibujar tilemap
tileMap.draw(g);
// dibujar jugador/es
vendedor.draw(g);
munExComp.draw(g);
botiquin.draw(g);
player1.draw(g);
if(dosJug==true){player2.draw(g);}
bondFire.draw(g);
//eventos de mapa
System.out.println(player1.getx()+"------"+player1.gety());
if(player1.gety()>=770){
if(player1.gety()<=850){
//puerta 1
if (player1.getx()>=930){
if (player1.getx()<= 970){
g.setColor(Color.RED);
g.drawString(textoFlotante[0],315, 150);
}
}
//puerta 2
if (player1.getx()>=1050){
if (player1.getx()<= 1090){
g.setColor(Color.RED);
g.drawString(textoFlotante[1],315, 150);
}
}
//puerta 3
if (player1.getx()>=1160){
if (player1.getx()<= 1200){
g.setColor(Color.RED);
g.drawString(textoFlotante[2],315, 150);
}
}
}
}
/*g.setColor(Color.RED);
g.drawString(textoFlotante[0],280, 180);
g.drawString(textoFlotante[1],280, 180);*/
debajoSalud.draw(g);
barraSalud.draw(g);
if(player1.getSalud()>40){
caraPlayer1.draw(g);
}else if (player1.getSalud()>10){
caraPlayer2.draw(g);
}else{
caraPlayer3.draw(g);
}
if(dosJug){
debajoSalud2.draw(g);
barraSalud2.draw(g);
cara2Player.draw(g);
}
g.setFont(font);
g.setColor(Color.RED);
g.drawString(player1.getpelasString(), 61, 22);
g.setColor(Color.GRAY);
g.drawString(player1.getMunExp()+"", 61, 35);
}
public void keyPressed(int k) {
if (k == KeyEvent.VK_ENTER){
if(player1.gety()>=770){
if(player1.gety()<=850){
//puerta 1
if (player1.getx()>=930){
if (player1.getx()<= 970){
//de clase a temp
Temp.setPelas(player1.getpelas());
Temp.setSalud(player1.getSalud());
Temp.setMunExp(player1.getMunExp());
gsm.setState(GameStateManager.LEVELARENA);
/**ANOTACION Markel:
* It's A Trap!
**/
}
}
//puerta 2
if (player1.getx()>=1050){
if (player1.getx()<= 1090){
gsm.setState(GameStateManager.LEVEL1);
}
}
//Puerta3
if (player1.getx()>=1160){
if (player1.getx()<= 1200){
gsm.setState(GameStateManager.ARENA2PLAYERS);
}
}
}
}
//Tienda
/**ANOTACION Markel:
* Buy stuff now or kick yourself later,
* Everdays a sale,
* every sales a win,
* Every day is great when you're me.
**/
if(player1.gety()>=1000&&player1.gety()<=1030){
//Botiquin
if (player1.getx()>=1030){
if (player1.getx()<= 1080){
if(player1.getpelas()>=50){
player1.setSalud(60);
barraSalud.setPosition(-1, 2);
barraSalud.cambiarSalud(60);
player1.setPelas(player1.getpelas()-50);
}
}
}
//Balas
if (player1.getx()>=1095){
if (player1.getx()<= 1130){
if(player1.getpelas()>=5){
player1.setMunExp(player1.getMunExp()+1);
player1.setPelas(player1.getpelas()-5);
}
}
}
Temp.setPelas(player1.getpelas());
Temp.setSalud(player1.getSalud());
Temp.setMunExp(player1.getMunExp());
Datos.GuardarDatos();
}
}
// TODO Auto-generated method stub
if (k == KeyEvent.VK_A){player1.setLeft(true);}
if (k == KeyEvent.VK_D){player1.setRight(true);}
if (k == KeyEvent.VK_J){player1.setJumping(true);}
if (k == KeyEvent.VK_K){player1.setDisparando();}
//if (k == KeyEvent.VK_X){player1.setGolpe();}
/*if (k == KeyEvent.VK_L){player.setAtacandoCQC();}*/
if(dosJug==true){if (k == KeyEvent.VK_Z){player2.setLeft(true);}
if (k == KeyEvent.VK_X){player2.setRight(true);}
if (k == KeyEvent.VK_N){player2.setJumping(true);}
if (k == KeyEvent.VK_M){player2.setDisparando();}}
//if (k == KeyEvent.VK_K){player1.setDisparando();}
}
public void keyReleased(int k) {
// TODO Auto-generated method stub
if (k == KeyEvent.VK_A){player1.setLeft(false);}
if (k == KeyEvent.VK_D){player1.setRight(false);}
if (k == KeyEvent.VK_J){player1.setJumping(false);}
if(dosJug==true){if (k == KeyEvent.VK_Z){player2.setLeft(false);}
if (k == KeyEvent.VK_X){player2.setRight(false);}
if (k == KeyEvent.VK_N){player2.setJumping(false);}}
}
}
|
package com.github.vinja.compiler;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.io.FilenameUtils;
import com.github.vinja.util.VjdeUtil;
public class ProjectLocationConf {
private static Map<String,String> config = null;
private static void loadVarsFromFile(File file) {
config = new HashMap<String,String>();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(file));
while (true) {
String tmp = br.readLine();
if (tmp == null) break;
if (tmp.startsWith("#")) continue;
int splitIndex = tmp.indexOf("=");
if (splitIndex < 0 ) continue;
String name = tmp.substring(0,splitIndex).trim();
String path = tmp.substring(splitIndex+1).trim();
config.put(name, path);
}
} catch (IOException e) {
} finally {
if (br != null) try { br.close(); } catch (Exception e) {}
}
}
public static String getProjectLocation(String name) {
if (config == null) {
loadVarsFromFile(getConfigFile());
}
String value= config.get(name);
return value ;
}
private static File getConfigFile() {
String userCfgPath = FilenameUtils.concat(VjdeUtil.getToolDataHome(), "project.cfg");
File tmpFile = new File(userCfgPath);
if (tmpFile.exists()) return tmpFile;
return null;
}
}
|
/*
* Copyright 2019, E-Kohei
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.norana.numberplace.ui.dialog;
import androidx.annotation.NonNull;
import androidx.fragment.app.DialogFragment;
import androidx.appcompat.app.AlertDialog;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.content.DialogInterface;
import com.norana.numberplace.R;
import com.norana.numberplace.ui.activity.PlayActivity;
import com.norana.numberplace.ui.activity.SavedActivity;
public class NotSavedDialogFragment extends DialogFragment{
public NotSavedDialogFragment(){}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState){
Activity activity = requireActivity();
int style = R.style.Theme_AppCompat_Light_Dialog_Alert;
int text = R.string.dialog_play_notsaved_message;
if (activity instanceof PlayActivity) {
style = R.style.AlertStyleRed;
text = R.string.dialog_play_notsaved_message;
}
else if (activity instanceof SavedActivity) {
style = R.style.AlertStyleGreen;
text = R.string.dialog_saved_notsaved_message;
}
AlertDialog.Builder builder = new AlertDialog.Builder(activity, style);
builder.setMessage(text)
.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int id){
if (activity instanceof SavedActivity){
((SavedActivity) activity).saveSudoku();
((SavedActivity) activity)
.supportFinishAfterTransition();
}
else if (activity instanceof PlayActivity){
((PlayActivity) activity).saveSudoku();
activity.finish();
}
}
})
.setNegativeButton(R.string.no,
new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int id){
if (activity instanceof SavedActivity){
((SavedActivity) activity)
.supportFinishAfterTransition();
}
else if (activity instanceof PlayActivity){
activity.finish();
}
}
});
return builder.create();
}
}
|
package planner.heuristics;
import planner.core.PlanStep;
import planner.core.Predicate;
import search.core.BestFirstHeuristic;
import java.util.Set;
public class LeftToStack implements BestFirstHeuristic<PlanStep> {
@Override
public int getDistance(PlanStep node, PlanStep goal) {
int toStack = 0;
for (Predicate predicate : node.getWorldState()){
if (predicate.getName().contains("stack"))
++toStack;
}
return toStack;
}
}
|
package com.kashu.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.kashu.domain.Category;
import com.kashu.repository.CategoryRepository;
@Service
public class CategoryServiceImpl implements CategoryService {
@Autowired
private CategoryRepository categoryRepository;
@Override
public List<Category> findAll() {
List<Category> categories = null;
try{
categories = categoryRepository.findAll();
}catch(Exception e){
e.printStackTrace();
}
return categories;
}
}
|
package chapter10;
import java.math.BigInteger;
public class Exercise10_21 {
public static void main(String[] args) {
BigInteger bigNum = new BigInteger(Long.MAX_VALUE + "");
int count = 0;
while (count < 10) {
bigNum = bigNum.add(BigInteger.ONE);
if (bigNum.remainder(new BigInteger(5 + "")).equals(BigInteger.ZERO)
|| bigNum.remainder(new BigInteger(6 + "")).equals(BigInteger.ZERO)) {
count++;
System.out.println(bigNum);
}
}
}
}
|
import java.util.Random;
/**
* Created by wangshuyang on 2017/4/5.
*/
public class QuickSort {
public static void print(int[] array, int n){
for (int i = 0; i < n; i++) {
System.out.print(array[i] + ",");
}
System.out.println();
}
public static int partition(int[] array, int low, int high){
int pivotkey = array[low];
while (low < high) {
while (low < high && array[high] >= pivotkey) {
high--;
}
array[low] = array[high];
while (low < high && array[low] <= pivotkey) {
low++;
}
array[high] = array[low];
}
array[high] = pivotkey;
return high;
}
public static void quick(int[] array, int low, int high) {
if (low < high) {
int index = partition(array, low, high);
quick(array,low,index-1);
quick(array,index+1,high);
}
}
public static void main(String args[]){
Random random = new Random();
int[] intArray = new int[10];
for (int i = 0; i < 10; i++) {
intArray[i] = random.nextInt(100);
}
print(intArray,10);
quick(intArray,0,9);
print(intArray,10);
}
}
|
package org.apache.commons.net.util;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.net.ssl.SSLSocket;
public class SSLSocketUtils {
public static boolean enableEndpointNameVerification(SSLSocket socket) {
try {
Class<?> cls = Class.forName("javax.net.ssl.SSLParameters");
Method setEndpointIdentificationAlgorithm = cls.getDeclaredMethod("setEndpointIdentificationAlgorithm", new Class[] { String.class });
Method getSSLParameters = SSLSocket.class.getDeclaredMethod("getSSLParameters", new Class[0]);
Method setSSLParameters = SSLSocket.class.getDeclaredMethod("setSSLParameters", new Class[] { cls });
if (setEndpointIdentificationAlgorithm != null && getSSLParameters != null && setSSLParameters != null) {
Object sslParams = getSSLParameters.invoke(socket, new Object[0]);
if (sslParams != null) {
setEndpointIdentificationAlgorithm.invoke(sslParams, new Object[] { "HTTPS" });
setSSLParameters.invoke(socket, new Object[] { sslParams });
return true;
}
}
} catch (SecurityException securityException) {
} catch (ClassNotFoundException classNotFoundException) {
} catch (NoSuchMethodException noSuchMethodException) {
} catch (IllegalArgumentException illegalArgumentException) {
} catch (IllegalAccessException illegalAccessException) {
} catch (InvocationTargetException invocationTargetException) {}
return false;
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\org\apache\commons\ne\\util\SSLSocketUtils.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
package kimmyeonghoe.cloth.dao.cloth;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import kimmyeonghoe.cloth.dao.map.cloth.ClothMap;
import kimmyeonghoe.cloth.domain.cloth.Cloth;
@Repository("clothDao")
public class ClothDaoImpl implements ClothDao {
@Autowired private ClothMap clothMap;
@Override
public List<Cloth> selectCloths() {
return clothMap.selectCloths();
}
@Override
public List<Cloth> searchClothWithKeyword(String keyword) {
return clothMap.searchClothWithKeyword(keyword);
}
@Override
public Cloth searchCloth(int clothNum) {
return clothMap.searchCloth(clothNum);
}
}
|
public class Game{
// .iswon?()
// .players
// .dealer
// .deckofcards
// win()
}
|
public class Wlasciciel {
private String imie;
private String nazwisko;
public Wlasciciel(String imie, String nazwisko){
this.imie = imie;
this.nazwisko = nazwisko;
}
public String toString(){
return imie + " " + nazwisko;
}
public String dajImie(){
return imie;
}
public String dajNazwisko(){
return nazwisko;
}
}
|
package com.spring.shopping.cart;
import java.util.List;
public interface CartService {
public List getCartList(String id) throws Exception;
public void addProductToCart(int num, String id, int amount) throws Exception;
public int checkDuplicatedProduct(int num) throws Exception;
public void modifyProductAmount(int num, int amount) throws Exception;
public void deleteProduct(String id, String products) throws Exception;
}
|
package com.example.adi.escuelaapp.Recursos;
/**
* Created by Adi on 16/06/2018.
*/
public class Constantes {
public static final String HOST = "http://192.168.1.110/";
public static final String CARPETA_DAO = "escuela/dao/";
}
|
/**
* 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.hadoop.cli;
import org.apache.hadoop.cli.util.*;
import org.apache.hadoop.cli.util.CommandExecutor.Result;
import org.apache.hadoop.tools.HadoopArchives;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.MiniMRCluster;
import org.apache.hadoop.mapred.tools.MRAdmin;
import org.apache.hadoop.mapreduce.server.jobtracker.JTConfig;
import org.apache.hadoop.security.authorize.HadoopPolicyProvider;
import org.apache.hadoop.security.authorize.PolicyProvider;
import org.apache.hadoop.util.ToolRunner;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.xml.sax.SAXException;
public class TestMRCLI extends TestHDFSCLI {
protected MiniMRCluster mrCluster = null;
protected String jobtracker = null;
private JobConf mrConf;
@Before
public void setUp() throws Exception {
super.setUp();
conf.setClass(PolicyProvider.POLICY_PROVIDER_CONFIG,
HadoopPolicyProvider.class, PolicyProvider.class);
mrConf = new JobConf(conf);
mrCluster = new MiniMRCluster(1, dfsCluster.getFileSystem().getUri().toString(), 1,
null, null, mrConf);
jobtracker = mrCluster.createJobConf().get(JTConfig.JT_IPC_ADDRESS, "local");
}
@After
public void tearDown() throws Exception {
mrCluster.shutdown();
super.tearDown();
}
@Override
protected TestConfigFileParser getConfigParser() {
return new TestConfigFileParserMR();
}
protected String getTestFile() {
return "testMRConf.xml";
}
@Override
protected String expandCommand(final String cmd) {
String expCmd = cmd;
expCmd = expCmd.replaceAll("JOBTRACKER", jobtracker);
expCmd = super.expandCommand(expCmd);
return expCmd;
}
@Override
protected Result execute(CLICommand cmd) throws Exception {
if (cmd.getType() instanceof CLICommandMRAdmin)
return new TestMRCLI.MRCmdExecutor(jobtracker).executeCommand(cmd.getCmd());
else if (cmd.getType() instanceof CLICommandArchive)
return new TestMRCLI.ArchiveCmdExecutor(namenode, mrConf).executeCommand(cmd.getCmd());
else
return super.execute(cmd);
}
public static class MRCmdExecutor extends CommandExecutor {
private String jobtracker = null;
public MRCmdExecutor(String jobtracker) {
this.jobtracker = jobtracker;
}
@Override
protected void execute(final String cmd) throws Exception{
MRAdmin mradmin = new MRAdmin();
String[] args = getCommandAsArgs(cmd, "JOBTRACKER", jobtracker);
ToolRunner.run(mradmin, args);
}
}
public static class ArchiveCmdExecutor extends CommandExecutor {
private String namenode = null;
private JobConf jobConf = null;
public ArchiveCmdExecutor(String namenode, JobConf jobConf) {
this.namenode = namenode;
this.jobConf = jobConf;
}
@Override
protected void execute(final String cmd) throws Exception {
HadoopArchives archive = new HadoopArchives(jobConf);
String[] args = getCommandAsArgs(cmd, "NAMENODE", namenode);
ToolRunner.run(archive, args);
}
}
@Test
@Override
public void testAll () {
super.testAll();
}
class TestConfigFileParserMR extends CLITestHelper.TestConfigFileParser {
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (qName.equals("mr-admin-command")) {
if (testCommands != null) {
testCommands.add(new CLITestCmdMR(charString,
new CLICommandMRAdmin()));
} else if (cleanupCommands != null) {
cleanupCommands.add(new CLITestCmdMR(charString,
new CLICommandMRAdmin()));
}
} else if (qName.equals("archive-command")) {
if (testCommands != null) {
testCommands.add(new CLITestCmdMR(charString,
new CLICommandArchive()));
} else if (cleanupCommands != null) {
cleanupCommands.add(new CLITestCmdMR(charString,
new CLICommandArchive()));
}
} else {
super.endElement(uri, localName, qName);
}
}
}
}
|
package com.csc214.rebeccavandyke.socialnetworkingproject2.model;
/*
* Rebecca Van Dyke
* rvandyke@u.rochester.edu
* CSC 214 Project 2
* TA: Julian Weiss
*/
import java.text.SimpleDateFormat;
import java.util.UUID;
public class Post implements Comparable<Post>{
private UUID mId;
private String mUser;
private String mText;
private String mImagePath;
private long mTimestamp;
@Override
public int compareTo(Post other){
//this is more recent than other
if((mTimestamp - other.getTimestamp()) > 0){
return -1;
}
else{
return 1;
}
} //compareTo()
public boolean containsImage(){
return (!mImagePath.equals(""));
} //containsImage()
public Post(){
this(UUID.randomUUID());
mUser = "";
mText = "";
mImagePath = "";
mTimestamp = 0;
} //Post()
public Post(UUID id) {
mId = id;
}
public UUID getId() {
return mId;
}
public void setId(UUID mId) {
this.mId = mId;
}
public String getUser() {
return mUser;
}
public void setUser(String mUser) {
this.mUser = mUser;
}
public String getText() {
return mText;
}
public void setText(String mText) {
this.mText = mText;
}
public String getImagePath() {
return mImagePath;
}
public void setImagePath(String mImagePath) {
this.mImagePath = mImagePath;
}
public long getTimestamp() {
return mTimestamp;
}
public String getStringTimestamp() {
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
return df.format(mTimestamp);
}
public void setTimestamp(long mTimestamp) {
this.mTimestamp = mTimestamp;
}
} //end class
|
package com.example.healthmanage.ui.activity.memberinfo;
import android.os.Bundle;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.example.healthmanage.BR;
import com.example.healthmanage.R;
import com.example.healthmanage.base.BaseActivity;
import com.example.healthmanage.base.BaseAdapter;
import com.example.healthmanage.databinding.ActivityMemberInfoBinding;
import com.example.healthmanage.bean.recyclerview.DataItem;
import com.example.healthmanage.widget.TitleToolBar;
import java.util.List;
public class MemberInfoActivity extends BaseActivity<ActivityMemberInfoBinding,
MemberInfoViewModel> implements TitleToolBar.OnTitleIconClickCallBack {
TitleToolBar titleToolBar = new TitleToolBar();
BaseAdapter memberInfoAdapter;
@Override
protected void initData() {
titleToolBar.setLeftIconVisible(true);
titleToolBar.setTitle("会员简介");
viewModel.setTitleToolBar(titleToolBar);
viewModel.getMemberInfo(getIntent().getExtras().getInt("MemberId"));
}
@Override
public void initViewListener() {
super.initViewListener();
titleToolBar.setOnClickCallBack(this);
}
@Override
protected void registerUIChangeEventObserver() {
super.registerUIChangeEventObserver();
memberInfoAdapter = new BaseAdapter(this, null, R.layout.item_data, BR.DataItem);
dataBinding.recyclerViewMemberInfo.setLayoutManager(new LinearLayoutManager(this));
dataBinding.recyclerViewMemberInfo.setAdapter(memberInfoAdapter);
viewModel.dataItemMutableLiveData.observe(this, new Observer<List<DataItem>>() {
@Override
public void onChanged(List<DataItem> dataItems) {
memberInfoAdapter.setRecyclerViewList(dataItems);
memberInfoAdapter.notifyDataSetChanged();
}
});
}
@Override
public void onRightIconClick() {
}
@Override
public void onBackIconClick() {
finish();
}
@Override
protected int initVariableId() {
return BR.ViewModel;
}
@Override
protected int setContentViewSrc(Bundle savedInstanceState) {
return R.layout.activity_member_info;
}
}
|
package 剑指offer;
import java.util.Arrays;
/**
* 题目描述
* 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
* 例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
* 示例1
* 输入
* 复制
* [1,2,3,4,5,6,7],[3,2,4,1,6,5,7]
* 返回值
* 复制
* {1,2,5,3,4,6,7}
*/
public class RebuildBinaryTree06 {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
//思路:1.如果二个数组都为空的时候直接返回一个空的节点
// 前序遍历的第一个节点为树的根节点然后找到第二个数组的那个值,找到那个值的需要 将他分为在分为二个数组
// 使用递归.
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
if (pre.length==0||in.length==0) {
return null;
}
TreeNode root = new TreeNode(pre[0]);
for (int i = 0; i < in.length ; i++) {
//找出在根节点在第二个数组的值
if (in[i]==pre[0]){
//左子树 copyOfRang 左闭右开
root.left = reConstructBinaryTree(Arrays.copyOfRange(pre,1,i+1),
Arrays.copyOfRange(in,0,i));
//右子树1
root.right = reConstructBinaryTree(Arrays.copyOfRange(pre,i+1,pre.length),
Arrays.copyOfRange(in,i+1,in.length));
break;
}
}
return root;
}
}
|
package fr.pederobien.uhc.commands.configuration.edit.editions.configurations.blockedexgame;
import fr.pederobien.uhc.commands.configuration.edit.editions.configurations.CommonGameTime;
import fr.pederobien.uhc.dictionary.dictionaries.MessageCode;
import fr.pederobien.uhc.interfaces.IBlockedexConfiguration;
public class GameTimeBlockedexGame extends CommonGameTime<IBlockedexConfiguration> {
public GameTimeBlockedexGame() {
super(MessageCode.GAME_TIME_BLOCKEDEX_GAME_EXPLANATION);
}
}
|
package com.tencent.mm.model;
import com.tencent.mm.model.br.a;
import com.tencent.mm.sdk.platformtools.bi;
class br$6 extends a {
final /* synthetic */ br dDr;
br$6(br brVar) {
this.dDr = brVar;
super(brVar, (byte) 0);
}
public final boolean a(bp bpVar) {
if (System.currentTimeMillis() - bpVar.dDj <= 1800000 || bi.getInt(bpVar.dDi, 0) <= 0) {
return false;
}
br.r(bpVar.key, bpVar.dDi);
bpVar.dDi = "0";
bpVar.dDj = System.currentTimeMillis();
return true;
}
}
|
package forms;
import java.text.ParseException;
import org.sikuli.script.FindFailed;
public class TTNonPregnantForm extends SikuliBase {
public void fillTTNonPregnantForm(String staffId, String facilityId, String date, String motechId, TTValues str) throws ParseException
{
try {
// selecting the TT_Non_pregnant form
selectForm(FormName.TT_NON_PREGNANT);
//Entering values in TT_Non_Pregnant form
//1. filling the staff id
inputStaffId(staffId);
//2. Filling the facility_id
inputTextbox(facilityId);
//3. Filling the date of visit as current date
selectDate(stringToDateConvertor(date));
//4. Filling the motech id
inputTextbox(motechId);
// 5. Filling the TT value as TT1
selectTTValues(str);
//6. Saving the form
saveMform();
//7. Moving to Main Menu and uploading the form
traverseToMainMenuAndUploadForm();
closeMobileApp();
} catch (FindFailed e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package nl.rug.oop.flaps.aircraft_editor.controller.listeners.blueprint_listeners;
import nl.rug.oop.flaps.aircraft_editor.model.blueprint.BluePrintModel;
import nl.rug.oop.flaps.aircraft_editor.model.blueprint.BluePrintModelListener;
import nl.rug.oop.flaps.aircraft_editor.view.panels.blueprint.BluePrintPanel;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
/**
* This class uses {@link MouseListener} to listen to mouse actions. If the mouse is clicked we pass the point where
* the mouse was clicked and pass it to {@link BluePrintModel} to check if any of the indicators are selected.
* for difference events of the mouse a different action
* */
public class PointSelectionListener implements MouseListener {
private static final int CLICK_RADIUS = BluePrintPanel.getINDICATOR_SIZE()+1;
private final BluePrintModel bluePrintModel;
public PointSelectionListener(BluePrintModel bluePrintModel) {
this.bluePrintModel = bluePrintModel;
}
@Override
public void mouseClicked(MouseEvent e) {
bluePrintModel.selectPointByCoords(e.getPoint(), CLICK_RADIUS);
bluePrintModel.getListeners().forEach(BluePrintModelListener::pointSelectedUpdater);
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
}
|
package marcio.tcc.estacionamento.controle;
@SuppressWarnings("serial")
public class VeiculoException extends Exception {
public VeiculoException(String msg) {
super(msg);
}
}
|
/*
* 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 ambiente;
import baseconhecimento.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
*
* @author Rafael Braz
*/
public class Ambiente {
private final BaseConhecimento base;
private final List<Interface> interfaces;
private final List<MemoriaTrabalho> memoTrab;
private final List<Tipo> tipos;
private final List<Operador> operadores;
private final List<Execucao> execucoes;
public Ambiente(String nomeBase) {
this.base = new BaseConhecimento(nomeBase);
this.interfaces = new ArrayList<>();
this.memoTrab = new ArrayList<>();
(this.tipos = new ArrayList<>()).addAll(Arrays.asList(
new Tipo("numerico", false, true),
new Tipo("univalorado", false, false),
new Tipo("multivalorado", true, false)
));
(this.operadores = new ArrayList<>()).addAll(Arrays.asList(
new Operador("="),
new Operador("<>"),
new Operador(">", false),
new Operador("<", false),
new Operador(">=", false),
new Operador("<=", false)
));
this.execucoes = new ArrayList<>();
}
public Tipo getTipo(String identificador) {
return (Tipo) this.tipos.stream()
.filter(x -> x.getIdentificador().equals(identificador))
.findAny()
.orElse(null);
}
public void criarInterface(Variavel variavel) {
this.interfaces.add(new Interface(variavel));
}
public void criarInterface(Variavel variavel, String pergunta) {
this.interfaces.add(new Interface(variavel, pergunta));
}
public void criarInterface(Variavel variavel, String pergunta, String motivo) {
this.interfaces.add(new Interface(variavel, pergunta, motivo));
}
public Interface getInterface(Variavel variavel) {
return (Interface) this.interfaces.stream()
.filter(x -> x.getVariavel() == variavel)
.findAny()
.orElse(null);
}
public Operador getOperador(String identificador) {
return (Operador) this.operadores.stream()
.filter(x -> x.getIdentificador().equals(identificador))
.findAny()
.orElse(null);
}
public void criarMemoTrab(Variavel variavel) {
this.memoTrab.add(new MemoriaTrabalho(variavel));
}
public MemoriaTrabalho getMemoTrab(Variavel variavel) {
return (MemoriaTrabalho) this.memoTrab.stream()
.filter(x -> x.getVariavel() == variavel)
.findAny()
.orElse(null);
}
public BaseConhecimento getBase() {
return base;
}
public List<Interface> getInterfaces() {
return interfaces;
}
public List<MemoriaTrabalho> getMemoTrab() {
return memoTrab;
}
public List<Tipo> getTipos() {
return tipos;
}
public List<Operador> getOperadores() {
return operadores;
}
public List<Execucao> getExecucoes() {
return execucoes;
}
}
|
package nbody_pap1314.controller.implementation;
import nbody_pap1314.controller.interfaces.InputListener;
/**
* Concrete implementation of the InputListener interface.
*
* @author Michele Braccini
* @author Alessandro Fantini
*/
public class Controller implements InputListener {
/* Monitor that receives the events by the controller */
protected CommandMonitor monitor;
public Controller(CommandMonitor monitor) {
this.monitor = monitor;
}
/**
* Notifies the start event to the monitor, along with delta time info.
*/
public void start(double deltaTime) {
log("'Start' with delta time (seconds): " + deltaTime);
monitor.start(deltaTime);
}
/**
* Notifies the stop event to the monitor.
*/
public void stop() {
log("'Stop'");
monitor.stop();
}
/**
* Notifies the pause event to the monitor.
*/
public void pause() {
log("'Pause'");
monitor.pause();
}
/**
* Notifies the resume event to the monitor, along with delta time info.
*/
public void resume(double deltaTime) {
log("'Resume' with delta time (seconds): " + deltaTime);
monitor.resume(deltaTime);
}
private void log(String msg) {
System.out.println("[" + this.getClass().getSimpleName() + "] " + msg);
}
}
|
package pl.edu.pw.mini.gapso.function;
import pl.edu.pw.mini.gapso.bounds.Bounds;
public abstract class Function {
private int evaluationsCount;
public Function() {
evaluationsCount = 0;
}
public double getValue(double[] x) {
++evaluationsCount;
return computeValue(x);
}
protected abstract double computeValue(double[] x);
public abstract boolean isTargetReached();
public abstract int getDimension();
public abstract Bounds getBounds();
public int getEvaluationsCount() {
return evaluationsCount;
}
}
|
package com.espendwise.manta.history;
import com.espendwise.manta.auth.Auth;
import com.espendwise.manta.i18n.I18nUtil;
public class ModifyGenericReportHistoryRecord extends AbstractGenericReportHistoryRecord {
@Override
public String getHistoryTypeCode() {
return HistoryRecord.TYPE_CODE_MODIFY_GENERIC_REPORT;
}
@Override
public String getShortDescription() {
String objectType = I18nUtil.getMessage(Auth.getAppUser().getLocale(), "history.objectType.genericReport");
Object[] args = new Object[1];
args[0] = objectType;
return I18nUtil.getMessage(Auth.getAppUser().getLocale(), "history.type.modifyObject", args);
}
@Override
public String getLongDescription() {
return buildLongDescription(false, "history.description.modifiedObject");
}
@Override
public String getLongDescriptionAsHtml() {
return buildLongDescription(true, "history.description.modifiedObject");
}
}
|
package com.bricenangue.nextgeneration.ebuycamer;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.media.ExifInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import org.lucasr.twowayview.TwoWayView;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class CreateAndModifyPublicationActivity extends AppCompatActivity {
private static final int GALLERY_INTENT=1;
// private TwoWayView listview;
// private TowWaysViewAdapter towWaysViewAdapter;
private ArrayList<Uri> uris =new ArrayList<>();
private ArrayList<PublicationPhotos> downloadUris=new ArrayList<>();
private static final int CAMERA_INTENT=2;
private android.support.v7.app.AlertDialog alertDialog;
private EditText editTextDescription;
private EditText editTextTitle;
private EditText editTextPrice;
private String categorie;
private FirebaseAuth auth;
private DatabaseReference root;
private StorageReference rootStorage;
private Spinner spinnerCategory;
private Map<String,Uri> images;
private ProgressDialog progressBar;
private UserSharedPreference userSharedPreference;
private String postToeditId;
private String[] photonames={"photo1","photo2","photo3","photo4","photo5"};
private PrivateContent postToedit;
private String location;
private RecyclerView recyclerViewHorizontal;
private String [] categoriesArray;
private Spinner spinnerCurrency;
private ArrayList<Object> sortOptionslist;
private ImageView imageViewAddNewImage;
private String categoryFromPost;
private LinearLayoutManager layoutManager;
private HorizontalRecyclerViewAdapter recyclerViewAdapter;
private CheckBox checkBoxIsNegotiable, checkBoxForFree;
public boolean haveNetworkConnection() {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if ( "WIFI".equals(ni.getTypeName()))
if (ni.isConnected())
haveConnectedWifi = true;
if ("MOBILE".equals(ni.getTypeName()))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_and_modify_publication);
Bundle extras =getIntent().getExtras();
if(extras!=null && extras.containsKey("postToedit")){
postToeditId=extras.getString("postToedit");
}
userSharedPreference=new UserSharedPreference(this);
auth=FirebaseAuth.getInstance();
userSharedPreference.setUserDataRefreshed(haveNetworkConnection());
if(auth==null){
if(userSharedPreference.getUserLoggedIn()){
// user offline
if(!userSharedPreference.getUserDataRefreshed()){
// user refreshed data on start
}
}else {
// user online but auth problem
Toast.makeText(this,getString(R.string.problem_while_loading_user_data_auth_null),Toast.LENGTH_LONG).show();
startActivity(new Intent(this,MainActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_CLEAR_TASK |
Intent.FLAG_ACTIVITY_NEW_TASK));
finish();
}
}
//to save the path in one language (english)
categoriesArray=getResources().getStringArray(R.array.categories_arrays_create);
root= FirebaseDatabase.getInstance().getReference();
rootStorage= FirebaseStorage.getInstance().getReference();
spinnerCurrency=(Spinner) findViewById(R.id.spinner_currency);
spinnerCategory=(Spinner)findViewById(R.id.spinner_choose_categorie);
checkBoxIsNegotiable=(CheckBox)findViewById(R.id.check_box_create_post_is_negotiable);
checkBoxForFree=(CheckBox)findViewById(R.id.check_box_create_post_is_for_free);
checkBoxForFree.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b){
editTextPrice.setText("0");
editTextPrice.setEnabled(false);
checkBoxIsNegotiable.setChecked(false);
checkBoxIsNegotiable.setEnabled(false);
}else {
editTextPrice.setText("");
editTextPrice.setEnabled(true);
checkBoxIsNegotiable.setEnabled(true);
}
}
});
checkBoxIsNegotiable.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b){
}else {
}
}
});
editTextDescription=(EditText) findViewById(R.id.editText_description_post);
editTextPrice=(EditText) findViewById(R.id.editText_price_post);
editTextTitle=(EditText) findViewById(R.id.editText_title_post);
recyclerViewHorizontal=(RecyclerView)findViewById(R.id.horizontal_recycler_view_create_post) ;
layoutManager=new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false);
recyclerViewHorizontal.setHasFixedSize(true);
recyclerViewHorizontal.setLayoutManager(layoutManager);
populateImages(uris);
imageViewAddNewImage=(ImageView)findViewById(R.id.imageView_Choose_Image_post);
imageViewAddNewImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getPicture();
}
});
if(postToeditId!=null && !postToeditId.isEmpty()){
populate();
}
}
private void populate() {
DatabaseReference reference=root.child(ConfigApp.FIREBASE_APP_URL_USERS_POSTS_USER)
.child(auth.getCurrentUser().getUid()).child(postToeditId).child("privateContent");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
PrivateContent post = dataSnapshot.getValue(PrivateContent.class);
if (post!=null){
if(dataSnapshot.hasChild("description")){
editTextDescription.setText(post.getDescription());
}
editTextPrice.setText(post.getPrice());
editTextTitle.setText(post.getTitle());
if(dataSnapshot.hasChild("isNegotiable")){
checkBoxIsNegotiable.setChecked(post.isNegotiable());
}
if (post.getPrice().equals("0")){
checkBoxForFree.setChecked(true);
}
if(dataSnapshot.hasChild("publictionPhotos")){
for(PublicationPhotos uri : post.getPublictionPhotos()){
recyclerViewAdapter.addUri(Uri.parse(uri.getUri()));
//uris.add(Uri.parse(uri.getUri()));
//towWaysViewAdapter.notifyDataSetChanged();
if (recyclerViewAdapter!=null && recyclerViewAdapter.getItemCount()>=5){
imageViewAddNewImage.setEnabled(false);
}else {
imageViewAddNewImage.setEnabled(true);
}
}
}
categoryFromPost=categoriesArray[post.getCategorie().getCatNumber()];
int positionSpinner=post.getCategorie().getCatNumber();
spinnerCategory.setSelection(positionSpinner+1);
location=post.getLocation().getName();
spinnerCurrency.setSelection(getCurrencyPosition(post.getCurrency()));
spinnerCategory.setEnabled(false);
spinnerCurrency.setEnabled(false);
checkBoxIsNegotiable.setChecked(post.isNegotiable());
postToedit=post;
}else {
if (!haveNetworkConnection()){
Toast.makeText(getApplicationContext(),getString(R.string.alertDialog_no_internet_connection),Toast.LENGTH_SHORT).show();
finish();
}else {
Toast.makeText(getApplicationContext(), getString(R.string.string_toast_viewcontent_Post_deleted)
, Toast.LENGTH_SHORT).show();
finish();
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getApplicationContext(), databaseError.getMessage()
, Toast.LENGTH_SHORT).show();
}
});
}
private void populateImages(ArrayList<Uri> uris1){
recyclerViewAdapter=new HorizontalRecyclerViewAdapter(this, uris1
,new HorizontalRecyclerViewAdapter.HorizontalAdapterClickListener() {
@Override
public void onItemClick(int position, View v) {
startActivity(new Intent(CreateAndModifyPublicationActivity.this,
ViewImageFullScreenActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.putExtra("imageUri",uris.get(position).toString()));
}
@Override
public void ondelteCLick(int position) {
delete(position);
}
});
recyclerViewHorizontal.setAdapter(recyclerViewAdapter);
}
private int getCurrencyPosition(String currency){
if(currency.equals(getString(R.string.currency_xaf))
|| currency.equals("F CFA") || currency.equals("XAF")){
return 0;
}
return 0;
}
public void ButtonConfirmActionPostClicked(View view){
editTextDescription.setError(null);
editTextTitle.setError(null);
boolean cancel = false;
View focusView = null;
String title=editTextTitle.getText().toString();
String price=editTextPrice.getText().toString();
if (TextUtils.isEmpty(title)) {
editTextTitle.setError(getString(R.string.error_field_required_title));
focusView = editTextTitle;
cancel = true;
}
if (!haveNetworkConnection()){
Toast.makeText(getApplicationContext(),getString(R.string.connection_to_server_not_aviable)
,Toast.LENGTH_SHORT).show();
}else {
// Check for a valid email address.
if (TextUtils.isEmpty(price)) {
editTextPrice.setError(getString(R.string.error_field_required_price));
focusView = editTextPrice;
cancel = true;
}
if(spinnerCategory.getSelectedItem().toString()
.equals(getString(R.string.string_create_new_publication_spinner_category_default))
){
focusView=spinnerCategory;
cancel=true;
}
if (cancel) {
// There was an error;
focusView.requestFocus();
focusView.performClick();
} else {
if(postToeditId!=null && !postToeditId.isEmpty()){
updateItem(postToeditId, categoryFromPost, location,userSharedPreference.getUserLocation().getNumberLocation());
}else {
createAndSaveItem();
}
}
}
}
private void lockscreen(){
ConfigApp.lockScreenOrientation(this);
}
private void unloockscreen(){
ConfigApp.unlockScreenOrientation(this);
}
private void updateItem(final String postid, final String categoryFpost,final String location,int locationNumber) {
lockscreen();
progressBar = new ProgressDialog(this);
progressBar.setCancelable(false);
progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressBar.show();
final String title=editTextTitle.getText().toString();
final String price=editTextPrice.getText().toString();
final String description=editTextDescription.getText().toString();
categorie = categoriesArray[spinnerCategory.getSelectedItemPosition()-1];
final String currency=spinnerCurrency.getSelectedItem().toString();
//updatechildren
if(!categorie.equals(categoryFpost)){
final DatabaseReference reftoedit=root.child(ConfigApp.FIREBASE_APP_URL_REGIONS).child(location)
.child(categoryFpost).child(postid);
reftoedit.removeValue();
}
final ArrayList<Uri> arrayList =uris;
PrivateContent privateContent =new PrivateContent();
privateContent.setTitle(title);
privateContent.setDescription(description);
privateContent.setPrice(price);
privateContent.setCurrency(currency);
privateContent.setNegotiable(checkBoxIsNegotiable.isChecked());
privateContent.setCategorie(new Categories(categorie,null,spinnerCategory.getSelectedItemPosition()-1));
if(arrayList.size()>0){
final String firstimage=arrayList.get(0).toString();
for(int i=0; i<arrayList.size(); i++){
String downloadUri=arrayList.get(i).toString();
PublicationPhotos p=new PublicationPhotos();
p.setUri(downloadUri);
downloadUris.add(p);
if(downloadUris.size() == arrayList.size()){
privateContent.setFirstPicture(firstimage);
privateContent.setPublictionPhotos(downloadUris);
final Map<String, Object> childUpdates=new HashMap<String, Object>();
childUpdates.put("/title",title);
childUpdates.put("/description",description);
childUpdates.put("/price",price);
childUpdates.put("/currency",currency);
childUpdates.put("/isNegotiable",checkBoxIsNegotiable.isChecked());
childUpdates.put("/categorie",new Categories(categorie,null,spinnerCategory.getSelectedItemPosition()-1));
childUpdates.put("/publictionPhotos",downloadUris);
childUpdates.put("/firstPicture", firstimage);
root.child(ConfigApp.FIREBASE_APP_URL_USERS_POSTS_ALL_CITY)
.child(getString(R.string.fcm_notification_city)+String.valueOf(locationNumber))
.child(postid)
.child("privateContent").updateChildren(childUpdates).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
root.child("Cities").child(location).child(categorie)
.child(postid).child("privateContent").updateChildren(childUpdates)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful() && task.isComplete()){
Map<String, Object> childUpdates=new HashMap<String, Object>();
childUpdates=new HashMap<String, Object>();
childUpdates.put("/title",title);
childUpdates.put("/description",description);
childUpdates.put("/price",price);
childUpdates.put("/currency",currency);
childUpdates.put("/isNegotiable",checkBoxIsNegotiable.isChecked());
childUpdates.put("/categorie",new Categories(categorie,null,spinnerCategory.getSelectedItemPosition()-1));
childUpdates.put("/publictionPhotos",downloadUris);
childUpdates.put("/firstPicture", firstimage);
root.child(ConfigApp.FIREBASE_APP_URL_USERS_POSTS_USER).child(auth.getCurrentUser().getUid())
.child(postid).child("privateContent").updateChildren(childUpdates)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isComplete() && task.isSuccessful()){
Map<String, Object> childUpdates=new HashMap<String, Object>();
childUpdates=new HashMap<String, Object>();
childUpdates.put("/title",title);
childUpdates.put("/description",description);
childUpdates.put("/price",price);
childUpdates.put("/currency",currency);
childUpdates.put("/isNegotiable",checkBoxIsNegotiable.isChecked());
childUpdates.put("/categorie",new Categories(categorie,null,spinnerCategory.getSelectedItemPosition()-1));
childUpdates.put("/publictionPhotos",downloadUris);
childUpdates.put("/firstPicture", firstimage);
root.child(ConfigApp.FIREBASE_APP_URL_USERS_POSTS).child(postid).child("privateContent")
.updateChildren(childUpdates).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(getApplicationContext(),getString(R.string.string_toast_text_success),Toast.LENGTH_SHORT).show();
finish();
if (progressBar!=null){
progressBar.dismiss();
unloockscreen();
}
}else {
Toast.makeText(getApplicationContext(),getString(R.string.string_toast_text_error),Toast.LENGTH_SHORT).show();
if (progressBar!=null){
progressBar.dismiss();
unloockscreen();
}
}
}
});
}else {
Toast.makeText(getApplicationContext(),getString(R.string.string_toast_text_error_user),Toast.LENGTH_SHORT).show();
if (progressBar!=null){
progressBar.dismiss();
unloockscreen();
}
// error editing user post
}
}
});
}else {
Toast.makeText(getApplicationContext(),getString(R.string.string_toast_text_error_city),Toast.LENGTH_SHORT).show();
if (progressBar!=null){
progressBar.dismiss();
unloockscreen();
}
// error editing post in city with picture
}
}
});
}
});
}
}
}else {
final Map<String, Object> childUpdates=new HashMap<String, Object>();
childUpdates.put("/title",title);
childUpdates.put("/description",description);
childUpdates.put("/price",price);
childUpdates.put("/currency",currency);
childUpdates.put("/isNegotiable",checkBoxIsNegotiable.isChecked());
childUpdates.put("/categorie",new Categories(categorie,null,spinnerCategory.getSelectedItemPosition()-1));
root.child(ConfigApp.FIREBASE_APP_URL_USERS_POSTS_ALL_CITY)
.child(getString(R.string.fcm_notification_city)+String.valueOf(locationNumber))
.child(postid)
.child("privateContent").updateChildren(childUpdates).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
root.child("Cities").child(location).child(categorie)
.child(postid).child("privateContent").updateChildren(childUpdates)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isComplete() && task.isSuccessful()){
Map<String, Object> childUpdates=new HashMap<String, Object>();
childUpdates=new HashMap<String, Object>();
childUpdates.put("/title",title);
childUpdates.put("/description",description);
childUpdates.put("/price",price);
childUpdates.put("/currency",currency);
childUpdates.put("/isNegotiable",checkBoxIsNegotiable.isChecked());
childUpdates.put("/categorie",new Categories(categorie,null,spinnerCategory.getSelectedItemPosition()-1));
root.child(ConfigApp.FIREBASE_APP_URL_USERS_POSTS_USER).child(auth.getCurrentUser().getUid())
.child(postid).child("privateContent").updateChildren(childUpdates)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isComplete() && task.isSuccessful()){
Map<String, Object> childUpdates=new HashMap<String, Object>();
childUpdates=new HashMap<String, Object>();
childUpdates.put("/title",title);
childUpdates.put("/description",description);
childUpdates.put("/price",price);
childUpdates.put("/currency",currency);
childUpdates.put("/isNegotiable",checkBoxIsNegotiable.isChecked());
childUpdates.put("/categorie",new Categories(categorie,null,spinnerCategory.getSelectedItemPosition()-1));
root.child(ConfigApp.FIREBASE_APP_URL_USERS_POSTS).child(postid).child("privateContent")
.updateChildren(childUpdates).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(getApplicationContext(),getString(R.string.string_toast_text_success),Toast.LENGTH_SHORT).show();
finish();
if (progressBar!=null){
progressBar.dismiss();
unloockscreen();
}
}else {
Toast.makeText(getApplicationContext(),getString(R.string.string_toast_text_error),Toast.LENGTH_SHORT).show();
if (progressBar!=null){
progressBar.dismiss();
unloockscreen();
}
}
}
});
}else {
Toast.makeText(getApplicationContext(),getString(R.string.string_toast_text_error_user),Toast.LENGTH_SHORT).show();
if (progressBar!=null){
progressBar.dismiss();
unloockscreen();
}
// errro edting task user post
}
}
});
}else {
Toast.makeText(getApplicationContext(),getString(R.string.string_toast_text_error_city),Toast.LENGTH_SHORT).show();
if (progressBar!=null){
progressBar.dismiss();
unloockscreen();
}
//error editing post in city
}
}
});
}
});
}
}
private void createAndSaveItem() {
progressBar = new ProgressDialog(this);
progressBar.setCancelable(false);
progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressBar.show();
lockscreen();
String title=editTextTitle.getText().toString();
final String price=editTextPrice.getText().toString();
String description=editTextDescription.getText().toString();
categorie=categoriesArray[spinnerCategory.getSelectedItemPosition()-1];
final Publication post= new Publication();
final PrivateContent privateContent= new PrivateContent();
final PublicContent publicContent=new PublicContent();
privateContent.setPrice(price);
privateContent.setTitle(title);
privateContent.setCurrency(spinnerCurrency.getSelectedItem().toString() );
privateContent.setCategorie(new Categories(categorie,null,spinnerCategory.getSelectedItemPosition()-1));
if(!description.isEmpty()){
privateContent.setDescription(description);
}
privateContent.setLocation(userSharedPreference.getUserLocation());
privateContent.setCreatorid(auth.getCurrentUser().getUid());
privateContent.setNegotiable(checkBoxIsNegotiable.isChecked());
//updatechildren
final DatabaseReference ref = root;
final String key= ref.push().getKey();
privateContent.setUniquefirebaseId(key);
privateContent.setTimeofCreation(System.currentTimeMillis());
publicContent.setNumberoflikes(0);
publicContent.setNumberofView(0);
userSharedPreference.addNumberofAds();
final ArrayList<Uri> arrayList =uris;
final StorageReference referencePost = rootStorage.child(auth.getCurrentUser().getUid()).
child(ConfigApp.FIREBASE_APP_URL_USERS_POSTS).child(key);
if(arrayList.size()>0){
privateContent.setFirstPicture(arrayList.get(0).toString());
for(int j=0; j<arrayList.size();j++){
String downloadUri=arrayList.get(j).toString();
PublicationPhotos p=new PublicationPhotos();
p.setUri(downloadUri);
downloadUris.add(p);
if(downloadUris.size()==arrayList.size()){
privateContent.setPublictionPhotos(downloadUris);
post.setPrivateContent(privateContent);
post.setPublicContent(publicContent);
//create in city
DatabaseReference r0= root.child(ConfigApp.FIREBASE_APP_URL_REGIONS)
.child(post.getPrivateContent().getLocation().getName()).child(privateContent.getCategorie().getName())
.child(key).child("privateContent");
r0.setValue(privateContent).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()){
DatabaseReference r1=root.child(ConfigApp.FIREBASE_APP_URL_REGIONS)
.child(post.getPrivateContent().getLocation().getName()).child(privateContent.getCategorie().getName())
.child(key).child("publicContent");
r1.setValue(publicContent).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()){
//create in users' posts
root.child(ConfigApp.FIREBASE_APP_URL_USERS_POSTS_ALL_CITY)
.child(getString(R.string.fcm_notification_city)+String.valueOf(privateContent.getLocation().getNumberLocation()))
.child(key).setValue(post).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
root.child(ConfigApp.FIREBASE_APP_URL_USERS_POSTS_USER)
.child(auth.getCurrentUser().getUid()).child(key).child("publicContent").setValue(post.getPublicContent());
root.child(ConfigApp.FIREBASE_APP_URL_USERS_POSTS_USER)
.child(auth.getCurrentUser().getUid()).child(key).child("privateContent").setValue(post.getPrivateContent())
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
//create in exists post and all posts
root.child(ConfigApp.FIREBASE_APP_URL_USERS_POSTS).child(key).child("privateContent").setValue(privateContent);
root.child(ConfigApp.FIREBASE_APP_URL_USERS_POSTS).child(key).child("publicContent").setValue(publicContent);
root.child(ConfigApp.FIREBASE_APP_URL_POSTS_EXIST).child(key).setValue(true).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
//update user number of ads
root.child(ConfigApp.FIREBASE_APP_URL_USERS).child(auth.getCurrentUser().getUid())
.child("userPublic").child("numberOfAds").setValue(userSharedPreference.getUserNumberofAds())
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(getApplicationContext(),getString(R.string.string_toast_text_success),Toast.LENGTH_SHORT).show();
finish();
sendNotification("New Publication in your area",getString(R.string.fcm_notification_city)
+String.valueOf(userSharedPreference.getUserLocation().getNumberLocation()));
if (progressBar!=null){
progressBar.dismiss();
unloockscreen();
}
}else {
Toast.makeText(getApplicationContext(),getString(R.string.string_toast_text_error)
+ " " +task.getException().getMessage(),Toast.LENGTH_SHORT).show();
if (progressBar!=null){
progressBar.dismiss();
unloockscreen();
}
}
}
});
}
});
}
});
}
});
}else {
if(progressBar!=null){
progressBar.dismiss();
unloockscreen();
}
}
}
});
}else {
Toast.makeText(getApplicationContext(),getString(R.string.string_toast_text_error)
+ " " +task.getException().getMessage(),Toast.LENGTH_SHORT).show();
if (progressBar!=null){
progressBar.dismiss();
unloockscreen();
}
}
}
});
}
}
}else {
post.setPrivateContent(privateContent);
post.setPublicContent(publicContent);
//create in users' posts
root.child(ConfigApp.FIREBASE_APP_URL_USERS_POSTS_USER)
.child(auth.getCurrentUser().getUid()).child(key).child("publicContent").setValue(post.getPublicContent());
root.child(ConfigApp.FIREBASE_APP_URL_USERS_POSTS_USER)
.child(auth.getCurrentUser().getUid()).child(key).child("privateContent").setValue(post.getPrivateContent())
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
//create in exists post and all posts
//create in city
root.child(ConfigApp.FIREBASE_APP_URL_USERS_POSTS_ALL_CITY)
.child(getString(R.string.fcm_notification_city)+String.valueOf(privateContent.getLocation().getNumberLocation()))
.child(key).setValue(post).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
DatabaseReference r0 = root.child(ConfigApp.FIREBASE_APP_URL_REGIONS).child(post.getPrivateContent().getLocation().getName()).child(privateContent.getCategorie().getName())
.child(key).child("privateContent");
r0.setValue(privateContent);
DatabaseReference r1 = root.child(ConfigApp.FIREBASE_APP_URL_REGIONS).child(post.getPrivateContent().getLocation().getName()).child(privateContent.getCategorie().getName())
.child(key).child("publicContent");
r1.setValue(publicContent).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
root.child(ConfigApp.FIREBASE_APP_URL_USERS_POSTS).child(key).child("privateContent").setValue(privateContent);
root.child(ConfigApp.FIREBASE_APP_URL_USERS_POSTS).child(key).child("publicContent").setValue(publicContent);
root.child(ConfigApp.FIREBASE_APP_URL_POSTS_EXIST).child(key).setValue(true).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
//update user number of ads
root.child(ConfigApp.FIREBASE_APP_URL_USERS).child(auth.getCurrentUser().getUid())
.child("userPublic").child("numberOfAds").setValue(userSharedPreference.getUserNumberofAds())
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(getApplicationContext(),getString(R.string.string_toast_text_success),Toast.LENGTH_SHORT).show();
finish();
sendNotification("New Publication in your area"
,getString(R.string.fcm_notification_city)
+String.valueOf(userSharedPreference.getUserLocation().getNumberLocation()));
if (progressBar!=null){
progressBar.dismiss();
unloockscreen();
}
}else {
Toast.makeText(getApplicationContext(),getString(R.string.string_toast_text_error)
+ " " +task.getException().getMessage(),Toast.LENGTH_SHORT).show();
if (progressBar!=null){
progressBar.dismiss();
unloockscreen();
}
}
}
});
}
});
}
});
}
});
}
});
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_INTENT && resultCode==RESULT_OK){
Uri uri= data.getData();
recyclerViewAdapter.addUri(Uri.parse(compressImage(uri)));
//uris.add(uri);
//towWaysViewAdapter.notifyDataSetChanged();
if (recyclerViewAdapter.getItemCount()>=5){
imageViewAddNewImage.setEnabled(false);
}else {
imageViewAddNewImage.setEnabled(true);
}
}else if (requestCode == CAMERA_INTENT && resultCode==RESULT_OK){
Bitmap bm=ImagePicker.getImageFromResult(this,resultCode,data);
Uri uri= ImagePicker.getUriFromResult(getApplicationContext(),resultCode,data);
//towWaysViewAdapter.add(uri);
}
}
void showDialogSortingOptions() {
alertDialog = new android.support.v7.app.AlertDialog.Builder(this).create();
LayoutInflater inflater = getLayoutInflater();
View convertView = (View) inflater.inflate(R.layout.custom_sort_options, null);
alertDialog.setView(convertView);
alertDialog.setTitle("Categories");
ListView listView = (ListView) convertView.findViewById(R.id.listView_addItmeListActivity_sort_options);
sortOptionslist = new ArrayList<>();
sortOptionslist.add("Cars");
sortOptionslist.add("Smartphone");
sortOptionslist.add("Laptop");
sortOptionslist.add("Shoes");
sortOptionslist.add("Clothes");
listView.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
}
});
alertDialog.setCancelable(true);
alertDialog.show();
}
private void getPicture(){
Intent intent =new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Intent intent=ImagePicker.getPickImageIntent(this);
startActivityForResult(intent, GALLERY_INTENT);
}
private void delete(final int i){
recyclerViewAdapter.delete(uris.get(i),i);
if(recyclerViewAdapter.getItemCount()<5){
imageViewAddNewImage.setEnabled(true);
}
}
public String compressImage(Uri imageUri) {
String filePath = getRealPathFromURI(imageUri);
Bitmap scaledBitmap = null;
BitmapFactory.Options options = new BitmapFactory.Options();
// by setting this field as true, the actual bitmap pixels are not loaded in the memory. Just the bounds are loaded. If
// you try the use the bitmap here, you will get null.
options.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeFile(filePath, options);
int actualHeight = options.outHeight;
int actualWidth = options.outWidth;
// max Height and width values of the compressed image is taken as 816x612
float maxHeight = 816.0f;
float maxWidth = 612.0f;
float imgRatio = actualWidth / actualHeight;
float maxRatio = maxWidth / maxHeight;
// width and height values are set maintaining the aspect ratio of the image
if (actualHeight > maxHeight || actualWidth > maxWidth) {
if (imgRatio < maxRatio) { imgRatio = maxHeight / actualHeight;
actualWidth = (int) (imgRatio * actualWidth);
actualHeight = (int) maxHeight;
} else if (imgRatio > maxRatio) {
imgRatio = maxWidth / actualWidth;
actualHeight = (int) (imgRatio * actualHeight);
actualWidth = (int) maxWidth;
} else {
actualHeight = (int) maxHeight;
actualWidth = (int) maxWidth;
}
}
// setting inSampleSize value allows to load a scaled down version of the original image
options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);
// inJustDecodeBounds set to false to load the actual bitmap
options.inJustDecodeBounds = false;
// this options allow android to claim the bitmap memory if it runs low on memory
options.inPurgeable = true;
options.inInputShareable = true;
options.inTempStorage = new byte[16 * 1024];
try {
// load the bitmap from its path
bmp = BitmapFactory.decodeFile(filePath, options);
} catch (OutOfMemoryError exception) {
exception.printStackTrace();
}
try {
scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight,Bitmap.Config.ARGB_8888);
} catch (OutOfMemoryError exception) {
exception.printStackTrace();
}
float ratioX = actualWidth / (float) options.outWidth;
float ratioY = actualHeight / (float) options.outHeight;
float middleX = actualWidth / 2.0f;
float middleY = actualHeight / 2.0f;
Matrix scaleMatrix = new Matrix();
scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);
Canvas canvas = new Canvas(scaledBitmap);
canvas.setMatrix(scaleMatrix);
canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));
// check the rotation of the image and display it properly
ExifInterface exif;
try {
exif = new ExifInterface(filePath);
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION, 0);
Log.d("EXIF", "Exif: " + orientation);
Matrix matrix = new Matrix();
if (orientation == 6) {
matrix.postRotate(90);
Log.d("EXIF", "Exif: " + orientation);
} else if (orientation == 3) {
matrix.postRotate(180);
Log.d("EXIF", "Exif: " + orientation);
} else if (orientation == 8) {
matrix.postRotate(270);
Log.d("EXIF", "Exif: " + orientation);
}
scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0,
scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix,
true);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream stream = new ByteArrayOutputStream();
String encodedImage=null;
try {
// write the compressed bitmap at the destination specified by filename.
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream);
byte[] byteFormat = stream.toByteArray();
encodedImage = Base64.encodeToString(byteFormat, Base64.NO_WRAP);
} catch (Exception e) {
e.printStackTrace();
}
return encodedImage;
}
private String getRealPathFromURI(Uri contentURI) {
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) {
return contentURI.getPath();
} else {
cursor.moveToFirst();
int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(index);
}
}
public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int heightRatio = Math.round((float) height/ (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
final float totalPixels = width * height;
final float totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
return inSampleSize;
}
private void sendNotification(String message,String topic) {
new SendNotification(message, topic).execute();
}
private class SendNotification extends AsyncTask<Void,Void,Void>
{
String message;
String topic;
SendNotification(String message, String topic)
{
this.topic=topic;
this.message=message;
}
@Override
protected void onPostExecute(Void reponse) {
super.onPostExecute(reponse);
}
@Override
protected Void doInBackground(Void... params) {
HttpURLConnection conn=null;
try {
ArrayList<Pair<String,String>> data=new ArrayList<>();
data.add(new Pair<String, String>("message", message));
data.add(new Pair<String, String>("topic",topic));
data.add(new Pair<String, String>("title","New Publication" ));
data.add(new Pair<String, String>("sender_uid",auth.getCurrentUser().getUid()));
byte[] bytes = ConfigApp.getData(data).getBytes("UTF-8");
URL url=new URL(ConfigApp.OOOWEBHOST_SERVER_URL+ "FirebasePushToTopicNotification.php");
conn=(HttpURLConnection)url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
// post the request
OutputStream out = conn.getOutputStream();
out.write(bytes);
out.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer reponse = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
reponse.append(inputLine);
}
final String response =reponse.toString();
System.out.print(response);
} catch (Exception e) {
e.printStackTrace();
}finally {
if(conn!=null){
conn.disconnect();
}
}
return null;
}
}
}
|
package com.olfu.meis.api;
import com.google.gson.annotations.SerializedName;
/**
* Created by mykelneds on 11/01/2017.
*/
public class EarthquakeResponse {
@SerializedName("id")
private int id;
@SerializedName("latitude")
private double latitude;
@SerializedName("longitude")
private double longitude;
@SerializedName("address")
private String address;
@SerializedName("date_time")
private String dateTime; // YYYY-MM-DD HH:MM:SS
@SerializedName("magnitude")
private double magnitude;
// @SerializedName("intensity")
// private
@SerializedName("depth")
private double depth;
public EarthquakeResponse(int id, double latitude, double longitude, String address, String dateTime, double magnitude, double depth) {
this.id = id;
this.latitude = latitude;
this.longitude = longitude;
this.address = address;
this.dateTime = dateTime;
this.magnitude = magnitude;
this.depth = depth;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDateTime() {
return dateTime;
}
public void setDateTime(String dateTime) {
this.dateTime = dateTime;
}
public double getMagnitude() {
return magnitude;
}
public void setMagnitude(double magnitude) {
this.magnitude = magnitude;
}
public double getDepth() {
return depth;
}
public void setDepth(double depth) {
this.depth = depth;
}
}
|
package com.bl.logical.StopWatch;
public class StopWatchBL {
public long startTimer=0;
public long stopTimer=0;
public long elapsed;
public void start()
{
startTimer=System.currentTimeMillis();
System.out.println("Start Time is: "+startTimer);
}
public void stop()
{
stopTimer=System.currentTimeMillis();
System.out.println("Stop Time is: "+stopTimer);
}
public long getElapsedTime()
{
elapsed=stopTimer-startTimer;
return elapsed;
}
public void getElapsedSeconds(long elapsed)
{
long elapsedsec= elapsed/1000;
System.out.println("Time elapsed in seconds is: "+elapsedsec);
// return elapsedsec;
}
}
|
package daos;
import Entidades.Aeronave;
public class DAOAeronave extends DAOGenerico<Aeronave> {
public DAOAeronave() {
super(Aeronave.class);
}
public int autoIdAeronave() {
Integer a = (Integer) em.createQuery("SELECT MAX(e.id) FROM Aeronave e ").getSingleResult();
if (a != null) {
return a + 1;
} else {
return 1;
}
}
public String esp(int n) {
String t = "";
for (int i = 0; i < n; i++) {
t += " ";
}
return t;
}
}
|
package com.zhouyi.business.controller;
import com.zhouyi.business.core.common.ReturnCode;
import com.zhouyi.business.core.model.PageData;
import com.zhouyi.business.core.model.Response;
import com.zhouyi.business.core.model.SysUnit;
import com.zhouyi.business.core.model.SysUser;
import com.zhouyi.business.core.service.SysUnitService;
import com.zhouyi.business.core.service.SysUserService;
import com.zhouyi.business.core.utils.*;
import com.zhouyi.business.core.vo.SysUserPasswordVo;
import com.zhouyi.business.core.vo.SysUserVo;
import com.zhouyi.business.dto.ListSysUserDto;
import com.zhouyi.business.dto.SysUserDto;
import com.zhouyi.business.dto.UserInfoDto;
import com.zhouyi.business.dto.UserInfoReciverDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @author 李秸康
* @ClassNmae: SysUserController
* @Description: 用户控制器
* @date 2019/6/21 9:38
* @Version 1.0
**/
@RestController
@RequestMapping(value = "/api/sysUser")
@Api(description = "用户接口")
public class SysUserController {
@Autowired
private SysUserService sysUserService;
@Autowired
private JWTUtil jwtUtil;
@Autowired
private SysUnitService sysUnitService;
/**
* 获取用户信息
*
* @param reciverDto
* @return
*/
@RequestMapping(value = "/getSysUser", method = RequestMethod.POST)
@ApiOperation(value = "用户信息查询", notes = "获取用户信息", response = Response.class)
public Response<Object> getSysUserByUserCode(@RequestBody UserInfoReciverDto reciverDto) {
SysUser sysUser = sysUserService.searchSysUser(reciverDto.getUserAccount());
if (sysUser == null)
return ResponseUtil.returnError(ReturnCode.ERROR_1001);
//将密码加盐后比对
if (!sysUser.getUserPassword().equals(MD5Util.MD5(reciverDto.getUserPassword(), sysUser.getSalt())))
return ResponseUtil.returnError(ReturnCode.Error_1025);
//将数据封装为DTO
UserInfoDto userInfoDto = new UserInfoDto();
BeanUtils.copyProperties(sysUser, userInfoDto);
return ResponseUtil.getResponseInfo(ReturnCode.SUCCESS, userInfoDto);
}
/**
* 根据用户编码删除用户
*
* @param userCode
* @return
*/
@RequestMapping(value = "/deleteUser/{userCode}", method = RequestMethod.DELETE)
@ApiOperation(value = "删除用户(物理删除)", notes = "根据用户编码删除")
@ApiImplicitParam(value = "被删除的用户编码", paramType = "path")
public Response<Object> removeSysUser(@PathVariable String userCode) {
boolean result = sysUserService.deleteByPrimaryKey(userCode);
return ResponseUtil.getResponseInfo(result);
}
/**
* 分页获取数据
*
* @param listSysUserDto
* @return
*/
@RequestMapping(value = "/listSysUser", method = RequestMethod.POST)
@ApiOperation(value = "分页获取用户列表数据", response = Response.class)
public Response<SysUser> listSysUser(@RequestBody ListSysUserDto listSysUserDto) {
Map<String, Object> conditions = MapUtils.objectTransferToMap(listSysUserDto);
//查询下级部门
if (listSysUserDto.getCycle() == 1) {
List<SysUnit> childUnits = sysUnitService.getSysUnitByParent(listSysUserDto.getUnitCode()
);//获取下级部门list集合
//提取其中的部门编码
List<String> unitCodes = new ArrayList<>();
fetchUnitCode(childUnits, unitCodes);
unitCodes.add(listSysUserDto.getUnitCode());
//将下级部门条件带入数据库
conditions.put("units", unitCodes);
conditions.put("unitCode", null);
}
//查询数据
PageData<SysUser> pageData = sysUserService.searchSysUserPage(conditions);
return ResponseUtil.getResponseInfo(ReturnCode.SUCCESS, pageData);
}
private void fetchUnitCode(List<SysUnit> unit, List<String> list) {
unit.stream().collect(Collectors.toList()).forEach(x -> {
if (x.getChildUnit() != null && x.getChildUnit().size() > 0) {
fetchUnitCode(x.getChildUnit(), list);
}
list.add(x.getUnitCode());
});
}
/**
* 修改密码接口
*
* @param sysUserDto
* @return
*/
@RequestMapping(value = "/updatePassword", method = RequestMethod.PUT)
@ApiOperation(value = "修改密码", response = Response.class)
public Response<Object> modifyPassword(@RequestBody SysUserPasswordVo sysUserDto) {
SysUserVo sysUserVo = new SysUserVo();
sysUserVo.setUserCode(sysUserDto.getUserCode());
//生成随机盐值
String salt = MD5Util.generateSalt(sysUserVo.getUserCode());
//将密码加盐处理
String newPassword = MD5Util.MD5(sysUserDto.getUserPassword(), salt);
sysUserVo.setSalt(salt);
sysUserVo.setUserPassword(newPassword);
boolean flag = false;
try {
flag = sysUserService.modifySysUserSelective(sysUserVo);
} catch (Exception e) {
e.printStackTrace();
return ResponseUtil.ntrError("系统异常");
}
return ResponseUtil.getResponseInfo(flag);
}
/**
* 修改用户信息接口
*
* @param sysUserDto
* @return
*/
@ApiOperation(value = "修改用户信息", notes = "根据用户编码修改用户信息")
@RequestMapping(value = "/updateSysUser", method = RequestMethod.PUT)
public Response<Object> modifySysUser(@RequestBody SysUserDto sysUserDto) {
sysUserDto.setUpdateDatetime();//设置更新时间
SysUserVo sysUserVo = new SysUserVo();
BeanUtils.copyProperties(sysUserDto, sysUserVo);
boolean result = false;
try {
result = sysUserService.modifySysUserSelective(sysUserVo);
} catch (Exception e) {
e.printStackTrace();
return ResponseUtil.ntrError("系统日常");
}
return ResponseUtil.getResponseInfo(result);
}
/**
* 用户注册接口
*
* @param sysUserDto
* @return
*/
@ApiOperation(value = "用户注册接口")
@RequestMapping(value = "/userRegister", method = RequestMethod.POST)
public Response<Object> userRegister(@RequestBody SysUserDto sysUserDto) {
SysUserVo sysUserVo = new SysUserVo();
BeanUtils.copyProperties(sysUserDto, sysUserVo);
Boolean result = null;
try {
result = sysUserService.sysUserRegister(sysUserVo);
} catch (Exception e) {
e.printStackTrace();
return ResponseUtil.ntrError("系统异常");
}
return ResponseUtil.getResponseInfo(result);
}
@ApiOperation(hidden = true, value = "测试")
@RequestMapping(value = "/test", method = RequestMethod.GET)
public Response<Object> test(HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
for (Cookie cookie :
cookies) {
System.out.println(cookie.getName() + ":" + cookie.getValue());
}
return ResponseUtil.getResponseInfo(true);
}
@ApiOperation(value = "封禁用户")
@RequestMapping(value = "/forbid/{userCode}", method = RequestMethod.PUT)
@ApiImplicitParam(value = "用户编码", paramType = "path", name = "userCode")
public Response<Object> forbidSysUser(@PathVariable String userCode) {
SysUserVo sysUser = new SysUserVo();
sysUser.setUserCode(userCode);
sysUser.setDeleteFlag("1");
boolean result = false;
try {
result = sysUserService.modifySysUserSelective(sysUser);
} catch (Exception e) {
e.printStackTrace();
return ResponseUtil.ntrError("系统异常");
}
return ResponseUtil.getResponseInfo(result);
}
/**
* 注销接口
*
* @param response
* @return
*/
@RequestMapping(value = "/logout")
public Response<Object> logout(HttpServletResponse response, HttpServletRequest request) {
TokenUtil.delCookie(request, response, "token");
return ResponseUtil.getResponseInfo(true);
}
@RequestMapping(value = "/verification/password", method = RequestMethod.POST)
@ApiOperation(value = "确认旧密码接口")
public Response<Object> verificationPassword(@RequestBody VerificationPasswordDto verificationPasswordDto) {
//获取用户信息
boolean flag = sysUserService.checkUserPassword(verificationPasswordDto.getUserAccount(), verificationPasswordDto.getUserPassword());
return ResponseUtil.getResponseInfo(ReturnCode.SUCCESS, flag);
}
@RequestMapping(value = "/check/user_account/{userAccount}", method = RequestMethod.GET)
@ApiOperation(value = "/账户查重")
@ApiImplicitParam(value = "用户账户", name = "userAccount", paramType = "path")
public Response<Object> checkUserAccount(@PathVariable String userAccount) {
boolean flag = sysUserService.checkUserAccount(userAccount);
if (flag == true) {
return ResponseUtil.getResponseInfo(ReturnCode.SUCCESS, "exists");
} else {
return ResponseUtil.getResponseInfo(ReturnCode.SUCCESS, "noexists");
}
}
@Data
static class VerificationPasswordDto {
private String userAccount;
private String userPassword;
}
}
|
package com.mundo.web.support.wechat.miniprogram;
import lombok.*;
/**
* UserInfo
*
* @author maomao
* @see <a href="https://developers.weixin.qq.com/miniprogram/dev/api/UserInfo.html">小程序用户信息</a>
* @since 2019-03-31
*/
@Getter
@Setter
@ToString
@EqualsAndHashCode
@NoArgsConstructor
public class UserInfo {
private String openId;
private String nickName;
private GenderEnum gender;
private String language;
private String city;
private String province;
private String country;
private String avatarUrl;
private String unionId;
private Watermark watermark;
@AllArgsConstructor
public enum GenderEnum {
UNKNOW(0), MALE(1), FEMALE(2);
public final int gender;
}
@AllArgsConstructor
public enum Language {
EN("en"),
ZH_CN("zh_CN"),
ZH_TW("zh_TW");
private final String language;
}
@Getter
@Setter
@ToString
@EqualsAndHashCode
@NoArgsConstructor
public static class Watermark {
private String appid;
private String timestamp;
}
}
|
/*
* 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 edu.ub.informatica.disseny.stub;
import model.*;
/**
*
* @author anna
*/
public interface DAO_STUB {
public Serie loadSerie(String id, String title, String desc);
public Temporada loadTemporada(String idSerie, String numTemporada, String numEpisodis);
public Episodio loadEpisodi(String title, String duration, String idioma, String description, String data, String idSerie, String numTemporada);
public Artista loadArtista(String id, String nom, String tipus, String idSerie, String nacionalitat);
public Productora loadProductora(String id, String nom, String idSerie);
public Administrador loadAdmin(String id, String nom, String usuari, String password);
public Client loadClient(String id, String nom, String dni, String adreca, String usuari, String password);
public Subscripcio loadSubscripcio(String id, String client, String serie, String numTemporada, String episodi);
public Visualitzacio loadVisualització(String id, String client, String serie, String numTemporada, String episodi, String data);
public Valoracio loadValoracio(String id, String client, String idSerie, String numTemporada, String episodi, String puntuacio, String data);
}
|
package com.aifurion.track.entity.VO;
import java.io.Serializable;
import java.util.List;
/**
* @author :zzy
* @description:TODO 科室封装
* @date :2021/4/6 20:16
*/
public class DepartmentDoctorVO implements Serializable {
private static final long serialVersionUID = 8830957798297011778L;
private String secdepid;
private String secdep;
private List<DoctorVO> doctorVOS;
public DepartmentDoctorVO() {
}
public DepartmentDoctorVO(String secdepid, String secdep, List<DoctorVO> doctorVOS) {
this.secdepid = secdepid;
this.secdep = secdep;
this.doctorVOS = doctorVOS;
}
@Override
public String toString() {
return "DepartmentDoctorVO{" +
"secdepid='" + secdepid + '\'' +
", secdep='" + secdep + '\'' +
", doctorVOS=" + doctorVOS +
'}';
}
public String getSecdepid() {
return secdepid;
}
public void setSecdepid(String secdepid) {
this.secdepid = secdepid;
}
public String getSecdep() {
return secdep;
}
public void setSecdep(String secdep) {
this.secdep = secdep;
}
public List<DoctorVO> getDoctorVOS() {
return doctorVOS;
}
public void setDoctorVOS(List<DoctorVO> doctorVOS) {
this.doctorVOS = doctorVOS;
}
}
|
package LeetCodeTopics.graph.dfs.numberofenclaves;
public class Solution {
public static void main(String[] args) {
}
public int numClaves(int[][] grid) {
// grid =
int m = grid.length;
int n = grid[0].length;
boolean[][] visit = new boolean[m][n];
for (int i = 0; i < m; i++) {
// dfs the first column
if (grid[i][0] == 1 && !visit[i][0]) {
dfs(i, 0, m, n, grid, visit);
}
if (grid[i][n-1] == 1 && !visit[i][n-1]) {
dfs(i, n - 1, m, n, grid, visit);
}
// dfs the last column
}
for (int i = 0; i < n; i++) {
// first row
if (grid[0][i] == 1 && !visit[0][i]) {
dfs(0, i, m, n, grid, visit);
}
if (grid[m-1][i] == 1 && !visit[m-1][i]) {
dfs(m-1, i, m, n, grid, visit);
}
}
int count = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1 && !visit[i][j]) {
count++;
}
}
}
return count;
}
public void dfs(int x, int y, int m, int n, int[][] grid, boolean[][] visit) {
if (x < 0 || x >= m || y < 0 || y >= n || grid[x][y] == 0 || visit[x][y]) {
return;
}
visit[x][y] = true;
int[] dirx = {0, 1, 0, -1};
int[] diry = {-1, 0, 1, 0};
for (int i = 0; i < 4; i++) {
dfs(x + dirx[i], y + diry[i], m, n, grid, visit);
}
}
}
|
/**
* MOTECH PLATFORM OPENSOURCE LICENSE AGREEMENT
*
* Copyright (c) 2010-11 The Trustees of Columbia University in the City of
* New York and Grameen Foundation USA. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of Grameen Foundation USA, Columbia University, or
* their respective contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY GRAMEEN FOUNDATION USA, COLUMBIA UNIVERSITY
* AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRAMEEN FOUNDATION
* USA, COLUMBIA UNIVERSITY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.motechproject.server.service.impl;
import java.util.Date;
import org.apache.commons.collections.Predicate;
import org.openmrs.Obs;
public class ObsPredicate implements Predicate {
private Date minDate;
private Date maxDate;
private Integer value;
public boolean evaluate(Object input) {
if (input instanceof Obs) {
Obs obs = (Obs) input;
Date obsDate = obs.getObsDatetime();
boolean afterMinDate = true;
if (minDate != null) {
afterMinDate = obsDate.after(minDate);
}
boolean beforeMaxDate = true;
if (maxDate != null) {
beforeMaxDate = obsDate.before(maxDate);
}
Double obsValue = obs.getValueNumeric();
boolean matchingValue = true;
if (value != null && obsValue != null) {
matchingValue = value.intValue() == obsValue.intValue();
}
return afterMinDate && beforeMaxDate && matchingValue;
}
return false;
}
public Date getMinDate() {
return minDate;
}
public void setMinDate(Date minDate) {
this.minDate = minDate;
}
public Date getMaxDate() {
return maxDate;
}
public void setMaxDate(Date maxDate) {
this.maxDate = maxDate;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
|
/*
Given a rope of length n. You need to find the maximun
no of pieces you can make that the length of every piece
is in set {a, b, c} for given 3 values a, b, c
*/
package Recursion.MaximumNumberofPieces;
class MaximumNoOfPieces {
public static void main(String[] args) {
int n = 23;
int a = 12, b = 11, c = 9;
System.out.println("Max Number of Pieces: " + maxPieces(n, a, b, c));
}
static int maxPieces(int n, int a, int b, int c) {
// Base case: If the Length of the Rope becomes 0
if (n == 0)
return 0;
// Base Case: If the length of the rope becomes -1
if (n < 0)
return -1;
int res = Math.max(Math.max(maxPieces(n - a, a, b, c), maxPieces(n - b, a, b, c)), maxPieces(n - c, a, b, c));
// if the result is -1 then, return -1
if (res == -1)
return -1;
// else add +1 to the result if the result is zero
return 1 + res;
}
}
|
package org.rw.crow.commons;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class MathUtilsTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void test() {
fail("Not yet implemented");
}
@Test
public void testPrecisionDecimal() {
double num = 232.4338903427124;
double result = MathUtils.precisionDecimal(num, 2);
System.out.println(result);
}
@Test
public void testPrecisionDecimalFormatForFraction() {
double num = 232.4338903427124;
String result = MathUtils.precisionDecimalFormatForFraction(num, 1);
System.out.println(result);
}
}
|
package com.cube.storm.language.lib.factory;
import android.net.Uri;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.cube.storm.LanguageSettings;
import com.cube.storm.util.lib.resolver.Resolver;
import java.io.InputStream;
/**
* Factory class used to resolve a file based on it's Uri
*
* @author Callum Taylor
* @project LightningLanguage
*/
public abstract class FileFactory
{
/**
* Loads a file from disk based on its Uri location
*
* @param fileUri The file Uri to resolve
*
* @return The file byte array, nor null
*/
@Nullable
public InputStream loadFromUri(@NonNull Uri fileUri)
{
Resolver resolver = LanguageSettings.getInstance().getUriResolvers().get(fileUri.getScheme());
if (resolver != null)
{
return resolver.resolveFile(fileUri);
}
return null;
}
}
|
package pl.piomin.services.envoy.discovery.data;
public class DiscoveryHostRepository {
}
|
package file2;
public class Ifile1 {
public Ifile1() {
System.out.println("sdklfjdslaa");
}
public static void main(String[] args) {
System.out.println("sdklfjdslaa");
}
}
|
package com.example.demo.repository;
import com.example.demo.entity.Group;
import com.example.demo.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;
@Repository
public interface GroupRepository extends JpaRepository<Group, Long> {
Optional<List<Group>> findByIdIn(List<Long> ids);
@Query(value = "SELECT * FROM group_meta gm INNER JOIN group_service gs ON gm.id = gs.group_id INNER JOIN service s ON s.id = gs.service_id", nativeQuery = true)
Optional<List<Group>> findAllByServiceRequest();
}
|
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public void reorderList(ListNode head) {
if (head == null || head.next == null)
return;
ListNode fast = head;
ListNode slow = head;
ListNode prev = null;
ListNode l1 = head;
while(fast != null && fast.next != null) {
prev = slow;
slow = slow.next;
fast = fast.next.next;
}
prev.next = null;
ListNode l2 = rever(slow);
merge(l1, l2);
}
public ListNode rever(ListNode l) {
ListNode c = l;
ListNode p = null;
ListNode n = null;
while(c != null) {
n = c.next;
c.next = p;
p = c;
c = n;
}
return p;
}
public void merge(ListNode l1, ListNode l2) {
while(l1 != null) {
ListNode n1 = l1.next, n2 = l2.next;
l1.next = l2;
if(n1 == null)
break;
l2.next = n1;
l1 = n1;
l2 = n2;
}
}
}
|
/**
*Java main template
*/
class temp{
public static void main(String[] args) {
System.out.println("Salut");
}
}
|
package src.Enums;
/**
* Created with IntelliJ IDEA.
* User: B. Seelbinder
* UID: ga25wul
* Date: 14.07.2014
* Time: 22:48
* *
*/
public enum EWatchMode {
OBSERVER, CONTROLLED_PLAYER, CUSTOM_PLAYER;
}
|
package com.worker.framework.control;
import java.util.ConcurrentModificationException;
import java.util.Date;
import java.util.Set;
import javax.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.stereotype.Component;
import com.google.common.base.Optional;
import com.worker.framework.api.RoutingProperties;
import com.worker.framework.service.WorkMessageJoinService;
import com.worker.shared.ControlMessage;
import com.worker.shared.ControlMessageVisitor;
import com.worker.shared.FailedControlMessage;
import com.worker.shared.JoinedTaskFailed;
import com.worker.shared.JoinedTaskSucceded;
import com.worker.shared.WorkMessage;
import com.worker.shared.WorkMessageJoinDelta;
@Component
public class ControlMessageVisitorImpl implements ControlMessageVisitor {
private static final Logger logger = LoggerFactory.getLogger(ControlMessageVisitorImpl.class);
@Inject private RoutingProperties routingProperties;
@Inject private AmqpTemplate messagesTemplate;
@Inject private WorkMessageJoinService joinService;
public void visit(JoinedTaskSucceded message) {
// logger.debug(message);
handleJoinDelta(message);
}
public void visit(JoinedTaskFailed message) {
logger.error("To be joined task failed with error: " + message.getFailureReason());
handleJoinDelta(message);
}
private void handleJoinDelta(JoinedTaskSucceded message) {
String joinId = message.getJoinId();
Set<WorkMessageJoinDelta> joinDelta = message.getJoinDelta();
Optional<Date> releaseDate = Optional.absent();
try {
releaseDate = joinService.joinAndGet(joinId, joinDelta);
} catch (ConcurrentModificationException e) {
logger.debug("got concurrent insert for join state, retrying " + e.getMessage());
releaseDate = joinService.joinAndGet(joinId, joinDelta);
}
if (releaseDate.isPresent()) {// on re-transmits of message that made a release we will get multiple releases as
// well..
WorkMessage joinSinkMessage = message.getJoinSinkMessage();
logger.info("Sink release - all tasks reached join " + joinSinkMessage.toShortFormat());
logger.debug("Sink release - all tasks reached join " + joinSinkMessage);
String destQueue =
joinSinkMessage.isLowPriority() ? routingProperties.getLowQueueName()
: routingProperties.getQueueName();
messagesTemplate.convertAndSend(destQueue, joinSinkMessage);
}
}
@Override
public void visit(ControlMessage m) {
throw new IllegalArgumentException(m + " of type ControlMessage which is abstract, expected specific type");
}
@Override
public void visit(FailedControlMessage failedControlMessage) {
throw new IllegalStateException(failedControlMessage.getFailureReason());
}
}
|
package com.issp.ispp.service;
//ESTE SERVICIO HAY QUE BORRARLO
public class DefaultService {
}
|
package edu.buet.cse.spring.ch13.v4.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
@Controller("homeController")
public class HomeController extends AbstractController {
private static final int COUNT = 5;
private int upperLimit = 100;
public int getUpperLimit() {
return upperLimit;
}
public void setUpperLimit(int upperLimit) {
this.upperLimit = upperLimit;
}
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) {
ModelAndView mv = new ModelAndView("home");
Random randomGenerator = new Random();
List<Integer> numbers = new ArrayList<>();
for (int i = 0; i < COUNT; i++) {
numbers.add(randomGenerator.nextInt(upperLimit));
}
mv.addObject("numbers", numbers);
return mv;
}
}
|
package com.javademo.rx;
import rx.Observable;
import rx.Scheduler;
import rx.Subscriber;
import rx.functions.*;
import java.io.File;
import java.util.concurrent.atomic.AtomicLong;
/**
* Created by zl on 16/9/7.
*/
public class Main1 {
public static void main(String[] args){
File file=new File("/Users/zl/Downloads");
getFile(file).subscribe(new Action1<File>() {
@Override
public void call(File file) {
System.out.println(file);
}
});
getFile(file).collect(new Func0<AtomicLong>() {
@Override
public AtomicLong call() {
return new AtomicLong(0);
}
}, new Action2<AtomicLong, File>() {
@Override
public void call(AtomicLong aLong, File file) {
aLong.getAndAdd(file.length());
}
}).subscribe(new Action1<AtomicLong>() {
@Override
public void call(AtomicLong atomicLong) {
System.out.println(atomicLong);
}
});
}
public static Observable<File> getFile(File file){
if(file.isFile()){
return Observable.just(file);
}
return Observable.from(file.listFiles()).concatMap(new Func1<File, Observable<File>>() {
@Override
public Observable<File> call(File file) {
return getFile(file);
}
});
}
}
|
class Main {
public static void main(String[] args) {
ChuiniuRule cr = new ChuiniuRule();
int[] dices1 = { 1, 2, 3 };
if (! cr.satisfy(dices1, 2, 2, false))
throw new UnittestFailure();
int[] dices2 = { 2, 2, 3 };
if (! cr.satisfy(dices2, 2, 3, false))
throw new UnittestFailure();
}
}
|
package com.forsrc.cxf.server.restful.user.dao.impl;
import com.forsrc.base.dao.BaseHibernateDao;
import com.forsrc.base.dao.impl.BaseHibernateDaoImpl;
import com.forsrc.cxf.server.restful.user.dao.UserCxfDao;
import com.forsrc.exception.NoSuchUserException;
import com.forsrc.pojo.User;
import com.forsrc.springmvc.restful.user.dao.UserDao;
import com.forsrc.springmvc.restful.user.dao.impl.UserDaoImpl;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* The type User cxf dao.
*/
@Repository(value = "userCxfDaoImpl")
public class UserCxfDaoImpl extends UserDaoImpl
implements UserCxfDao, BaseHibernateDao<User, Long> {
@Override
public User findByUsername(String username) throws NoSuchUserException {
Session session = super.getSession();
Query query = session.getNamedQuery("hql_user_findByUsername");
query.setParameter("username", username);
query.setMaxResults(1);
List<User> list = query.list();
if(list.isEmpty()){
throw new NoSuchUserException(username);
}
return list.get(0);
}
}
|
/***********************************************************************
* Module: PrescriptionMode.java
* Author: Geri
* Purpose: Defines the Class PrescriptionMode
***********************************************************************/
package com.hesoyam.pharmacy.medicine.model;
public enum PrescriptionMode {
WITH_PRESCRIPTION,
WITHOUT_PRESCRIPTION;
}
|
// Sun Certified Java Programmer
// Chapter 4, P296_2
// Operators
class B extends A {
}
|
package com.espendwise.manta.web.validator;
import com.espendwise.manta.util.Constants;
import com.espendwise.manta.util.validation.*;
import com.espendwise.manta.web.forms.OrderItemNoteFilterForm;
import com.espendwise.manta.web.resolver.TextErrorWebResolver;
import com.espendwise.manta.web.util.WebErrors;
import org.apache.log4j.Logger;
public class OrderItemNoteFilterFormValidator extends AbstractFormValidator{
private static final Logger logger = Logger.getLogger(OrderItemNoteFilterFormValidator.class);
public OrderItemNoteFilterFormValidator() {
super();
}
@Override
public ValidationResult validate(Object obj) {
WebErrors errors = new WebErrors();
OrderItemNoteFilterForm valueObj = (OrderItemNoteFilterForm) obj;
ValidationResult vr;
logger.info("OrderItemNoteFilterFormValidator() ====>validate : valueObj.getItemNote() ="+ valueObj.getOrderItemNoteField());
TextValidator shortDescValidator = Validators.getTextValidator(Constants.VALIDATION_FIELD_CRITERIA.SHORT_DESC_LENGTH);
vr = shortDescValidator.validate(valueObj.getOrderItemNoteField(), new TextErrorWebResolver("admin.order.label.note"));
if (vr != null) {
errors.putErrors(vr.getResult());
}
logger.info("OrderItemNoteFilterFormValidator() ====>validate : errors.size ="+ errors.size());
return new MessageValidationResult(errors.get());
}
}
|
package com.ewisnor.randomur.imgur.model;
/**
* Based on this: https://api.imgur.com/models/gallery_album
*
* Created by evan on 2015-01-02.
*/
public class GalleryAlbum {
private String id;
private String title;
private String description;
private Long dateTime;
private String cover;
private Integer coverWidth;
private Integer coverHeight;
private String accountUrl;
private Integer accountId;
private String privacy;
private String layout;
private Integer views;
private String link;
private Integer ups;
private Integer downs;
private Integer score;
private Boolean isAlbum;
private String vote;
private Boolean favorite;
private Boolean nsfw;
private Integer commentCount;
private Integer imagesCount;
private GalleryImage[] images;
public String getId() {
return id;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public Long getDateTime() {
return dateTime;
}
public String getCover() {
return cover;
}
public Integer getCoverWidth() {
return coverWidth;
}
public Integer getCoverHeight() {
return coverHeight;
}
public String getAccountUrl() {
return accountUrl;
}
public Integer getAccountId() {
return accountId;
}
public String getPrivacy() {
return privacy;
}
public String getLayout() {
return layout;
}
public Integer getViews() {
return views;
}
public String getLink() {
return link;
}
public Integer getUps() {
return ups;
}
public Integer getDowns() {
return downs;
}
public Integer getScore() {
return score;
}
public Boolean getIsAlbum() {
return isAlbum;
}
public String getVote() {
return vote;
}
public Boolean getFavorite() {
return favorite;
}
public Boolean getNsfw() {
return nsfw;
}
public Integer getCommentCount() {
return commentCount;
}
public Integer getImagesCount() {
return imagesCount;
}
public GalleryImage[] getImages() {
return images;
}
}
|
package ru.job4j.chessboardframe;
public abstract class Figure {
public final Cell position;
Figure(Cell position) {
this.position = position;
}
public abstract Cell[] way(Cell source, Cell dest) throws ImpossibleMoveException;
public abstract Figure copy(Cell dest);
}
|
package com.tencent.mm.plugin.collect.ui;
import android.view.MenuItem;
import android.widget.Toast;
import com.tencent.mm.g.a.qu;
import com.tencent.mm.plugin.collect.a.a;
import com.tencent.mm.plugin.collect.ui.CollectMainUI.13;
import com.tencent.mm.plugin.report.service.h;
import com.tencent.mm.plugin.wxpay.a.i;
import com.tencent.mm.protocal.c.atm;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.ui.base.n.d;
import com.tencent.mm.wallet_core.ui.e;
class CollectMainUI$13$2 implements d {
final /* synthetic */ 13 hYS;
CollectMainUI$13$2(13 13) {
this.hYS = 13;
}
public final void onMMMenuItemSelected(MenuItem menuItem, int i) {
switch (menuItem.getItemId()) {
case 1:
a.aBC();
if (a.aBE()) {
CollectMainUI.v(this.hYS.hYN);
Toast.makeText(this.hYS.hYN.mController.tml, i.collect_main_close_ring_tone_tips, 1).show();
h.mEJ.h(13944, new Object[]{Integer.valueOf(8)});
return;
}
CollectMainUI.w(this.hYS.hYN);
Toast.makeText(this.hYS.hYN.mController.tml, i.collect_main_open_ring_tone_tips, 1).show();
h.mEJ.h(13944, new Object[]{Integer.valueOf(7)});
return;
default:
int itemId = (menuItem.getItemId() - 1) - 1;
if (itemId < 0) {
x.w("MicroMsg.CollectMainUI", "illegal pos: %s", new Object[]{Integer.valueOf(itemId)});
return;
}
atm atm = (atm) this.hYS.eRE.get(itemId);
if (atm.type == 1) {
x.w("MicroMsg.CollectMainUI", "wrong native type: %s", new Object[]{atm.url});
h.mEJ.h(14526, new Object[]{Integer.valueOf(2), Integer.valueOf(1), atm.bSc, "", "", "", Integer.valueOf(2)});
return;
} else if (atm.type == 2) {
if (!bi.oW(atm.url)) {
e.l(this.hYS.hYN.mController.tml, atm.url, false);
h.mEJ.h(14526, new Object[]{Integer.valueOf(2), Integer.valueOf(2), atm.bSc, "", "", atm.url, Integer.valueOf(2)});
return;
}
return;
} else if (atm.type == 3) {
qu quVar = new qu();
quVar.cbq.userName = atm.rWQ;
quVar.cbq.cbs = bi.aG(atm.rWR, "");
quVar.cbq.scene = 1072;
quVar.cbq.cbt = 0;
com.tencent.mm.sdk.b.a.sFg.m(quVar);
h.mEJ.h(14526, new Object[]{Integer.valueOf(2), Integer.valueOf(3), atm.bSc, atm.rWQ, atm.rWR, "", Integer.valueOf(2)});
return;
} else {
return;
}
}
}
}
|
package algorithm.baekjoon;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class _1012_OrganicCabbage {
static int M, N, K;
static int[][] map;
static int answer;
static int[] dy = {-1, 1, 0, 0}; // 상하좌우
static int[] dx = {0, 0, -1, 1}; // 상하좌우
public static void main(String[] args) throws IOException {
// input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
StringBuilder sb = new StringBuilder();
int T = Integer.parseInt(br.readLine());
for (int tc = 1; tc <= T; tc++) {
st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
K = Integer.parseInt(st.nextToken());
answer = 0;
map = new int[N][M];
for (int i = 0; i < K; i++) {
st = new StringTokenizer(br.readLine());
map[Integer.parseInt(st.nextToken())][Integer.parseInt(st.nextToken())] = 1;
}
// map을 돌면서 값이 1인 것만 찾는다
// 1인것을 찾으면 계속 들어가면서 인접한 부분 0으로 변경 마지막에 1리턴
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (map[i][j] == 1) {
dfs(i, j);
answer += 1;
}
}
}
sb.append(answer).append("\n");
}
System.out.print(sb);
}
private static void dfs(int y, int x) {
// 한 배추의 상하좌우 네 방향에 다른 배추가 위치한 경우에 서로 인접해있다고 간주
map[y][x] = 0;
for (int d = 0; d < 4; d++) {
int ny = y + dy[d];
int nx = x + dx[d];
if (ny < 0 || nx < 0 || ny >= N || nx >= M || map[ny][nx] == 0) continue;
dfs(ny, nx);
}
}
}
|
package com.example.retail.controllers.customers.edibleproducts_customer;
import com.example.retail.services.edibleproducts.EdibleProductsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/api/v1/customer/edibleProducts")
@CrossOrigin(origins = "*")
public class EdibleProductsCustomerController {
@Autowired
EdibleProductsService productsService;
@Autowired
EdibleProductsService edibleProductsService;
@RequestMapping(value = "/allEdibleProducts", produces = MediaType.APPLICATION_JSON_VALUE)
public List<?> finadAll(){
return edibleProductsService.findAll();
}
}
|
package com.hedong.hedongwx.dao;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Param;
import com.hedong.hedongwx.entity.Parameters;
/**
* @author origin
* 创建时间: 2019年5月24日 下午5:45:41
*/
public interface OperateRecordDao {
/**
* @Description: 查询操作记录数据
* @author: origin
*/
List<Map<String, Object>> userOperateRecord(Parameters paramet);
/**
* @Description: 插入操作记录数据
* @author: origin
*/
void insertoperate(@Param("name")String name, @Param("opeid")Integer opeid, @Param("objid")Integer objid,
@Param("type")Integer type, @Param("source")Integer source, @Param("remark")String remark, @Param("common")String common);
}
|
package co.edu.banco;
import co.edu.banco.model.Banco;
import co.edu.banco.model.Bolsillo;
import co.edu.banco.model.exception.BolsilloException;
import co.edu.banco.model.exception.CuentaException;
public class Principal {
public static void main(String[] args) throws BolsilloException, CuentaException {
Banco banco = new Banco();
try {
System.out.println(banco.crearCuenta("Stiven"));
} catch (CuentaException e) {
System.err.println(e.getMessage());
}
try {
System.out.println(banco.crearCuenta("Stiven"));
} catch (CuentaException e) {
System.err.println(e.getMessage());
}
try {
System.out.println(banco.crearCuenta("Herrera"));
} catch (CuentaException e) {
System.err.println(e.getMessage());
}
System.out.println("Prueba crear bolsillo");
System.out.println(banco.getListaCuentas().get("Herrera").getBolsilloCuenta());
banco.crearBolsillo(1);
System.out.println(banco.getListaCuentas());
System.out.println(banco.getListaCuentas().get("Herrera").getListaTransacciones());
System.out.println(banco.getListaCuentas().get("Herrera").getBolsilloCuenta());
System.out.println("Prueba depositar");
banco.depositarDineroCuenta(1, 1000);
banco.depositarDineroCuenta(1, 2000);
System.out.println(banco.obtenerCuenta(1));
System.out.println(banco.getListaCuentas().get("Herrera").getListaTransacciones());
System.out.println("Prueba retirar");
banco.retirarSaldoCuenta(1, 1500);
System.out.println(banco.obtenerCuenta(1));
System.out.println(banco.getListaCuentas().get("Herrera").getListaTransacciones());
System.out.println("Prueba trasladar");
Bolsillo b = banco.obtenerCuenta(1).getBolsilloCuenta();
banco.obtenerCuenta(1).trasladarDinero(1500);
System.out.println(banco.obtenerCuenta(1));
System.out.println(banco.getListaCuentas().get("Herrera").getListaTransacciones());
System.out.println(banco.obtenerCuenta(1).getBolsilloCuenta());
System.out.println(b.getListaTransacciones());
System.out.println("Prueba Consultar");
double saldo = banco.consultarSaldo("1b");
System.out.println(saldo);
System.out.println(banco.getListaCuentas().get("Herrera").getListaTransacciones());
System.out.println(banco.getListaCuentas().get("Herrera").getBolsilloCuenta().getListaTransacciones());
System.out.println("Prueba cancelar bolsillo");
banco.cancelarBolsillo("1b");
System.out.println(banco.getListaCuentas().get("Herrera").getListaTransacciones());
System.out.println(banco.obtenerCuenta(1).getBolsilloCuenta());
System.out.println("Prueba cancelar cuenta");
System.out.println(banco.obtenerCuenta(1));
banco.obtenerCuenta(1).setSaldo(0);
banco.cancelarCuenta(1);
System.out.println(banco.obtenerCuenta(1));
System.out.println(banco.getListaCuentas());
}
}
|
package co.vn.giabao;
public class SingletonPatternDemo {
public static void main(String[] args) {
// call showMessage from EagerInitializedSingleton
EagerInitializedSingleton.getInstance().showMessage();
// call showMessage from LazyInitializedSingleton
LazyInitializedSingleton.getInstance().showMessage();
// call showMessage from ThreadSafeSingleton
ThreadSafeSingleton.getInstance().showMessage();
// call showMessage from ThreadSafeUpgradedSingleton
ThreadSafeUpgradedSingleton.getInstance().showMessage();
}
}
|
package com.goldgov.gtiles.core.web.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.goldgov.gtiles.core.web.interceptor.handler.IRequestHandler;
public class WebInterceptor extends HandlerInterceptorAdapter{
private Log logger = LogFactory.getLog(this.getClass());
private IRequestHandler[] requestHandlers;
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
if(requestHandlers != null){
for (int i = 0; i < requestHandlers.length; i++) {
boolean result = requestHandlers[i].preHandle(request, response, handler);
logger.debug("[PRE]拦截器"+requestHandlers[i].getClass()+"执行:" + result);
if(!result){
//TODO WARN or 抛异常
return false;
}
}
}
return true;
}
@Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
if(requestHandlers != null){
for (int i = 0; i < requestHandlers.length; i++) {
boolean result = requestHandlers[i].postHandle(request, response, handler, modelAndView);
logger.debug("[POST]拦截器"+requestHandlers[i].getClass()+"执行:" + result);
if(!result){
//TODO WARN
break;
}
}
}
}
@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)
throws Exception {
}
public IRequestHandler[] getRequestHandlers() {
return requestHandlers;
}
public void setRequestHandlers(IRequestHandler[] requestHandlers) {
this.requestHandlers = requestHandlers;
}
}
|
package com.lanthaps.identime.model;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
/**
* Represents the contents of the account settings form.
* @author Andrew Miller
*/
public class AccountSettingModel {
public AccountSettingModel() {}
/**
* Creates a new AccountSettingModel with the specified parameters.
* @param token
* @param currentPassword
* @param newPassword
* @param newPassword2
* @param email
*/
public AccountSettingModel(String token, String currentPassword,
String newPassword, String newPassword2, String email) {
this.token = token;
this.currentPassword = currentPassword;
this.newPassword = newPassword;
this.newPassword2 = newPassword2;
this.email = email;
}
/**
* If non-null, the token to use to allow account setting access.
* Either token or currentPassword is required.
*/
String token;
/**
* The current password. Either token or currentPassword is required.
*/
String currentPassword;
/**
* The new password. If left blank, don't change the password.
*/
@Size(min=6,max=40) String newPassword;
/**
* The new password, repeated. Must match newPassword.
*/
@Size(min=6,max=40) String newPassword2;
/**
* The e-mail.
*/
@Email String email;
/**
* @return the token
*/
public String getToken() {
return token;
}
/**
* @param token the token to set
*/
public void setToken(String token) {
this.token = token;
}
/**
* @return the currentPassword
*/
public String getCurrentPassword() {
return currentPassword;
}
/**
* @param currentPassword the currentPassword to set
*/
public void setCurrentPassword(String currentPassword) {
this.currentPassword = currentPassword;
}
/**
* @return the newPassword
*/
public String getNewPassword() {
return newPassword;
}
/**
* @param newPassword the newPassword to set
*/
public void setNewPassword(String newPassword) {
this.newPassword = newPassword;
}
/**
* @return the newPassword2
*/
public String getNewPassword2() {
return newPassword2;
}
/**
* @param newPassword2 the newPassword2 to set
*/
public void setNewPassword2(String newPassword2) {
this.newPassword2 = newPassword2;
}
/**
* @return the email
*/
public String getEmail() {
return email;
}
/**
* @param email the email to set
*/
public void setEmail(String email) {
this.email = email;
}
}
|
package problems;
public class Roman_to_integer {
public static void main(String[] args) {
String s="III";
System.out.println(romanToInt(s));
}
public static int romanToInt(String s) {
int ans=0;
int[] nums={1000,900,500,400,100,90,50,40,10,9,5,4,1};
String[] roman={ "M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
for(int i=0;i<nums.length;i++){
while(s.startsWith(roman[i])){
ans+=nums[i];
s=s.substring(roman[i].length());
System.out.println(s);
}
}
return ans;
}
}
|
package com.example.safetyapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
public class MainActivity extends AppCompatActivity {
ImageView image, image1, image2;
Button continue_btn;
FirebaseAuth fAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
image = findViewById(R.id.image);
image1 = findViewById(R.id.image1);
image2 = findViewById(R.id.image2);
continue_btn = findViewById(R.id.continue_btn);
fAuth = FirebaseAuth.getInstance();
if(fAuth.getCurrentUser() != null){
startActivity(new Intent(MainActivity.this, Home.class));
this.finish();
}
TextView text_links = findViewById(R.id.link_texts);
String text = "By clicking on continue, you are accepting our privacy policy \nand terms & conditions.";
SpannableString ss = new SpannableString(text);
ClickableSpan clickableSpan = new ClickableSpan() {
@Override
public void onClick(@NonNull View view) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://social-media-integra-1.flycricket.io/privacy.html")));
}
};
ClickableSpan clickableSpan1 = new ClickableSpan() {
@Override
public void onClick(@NonNull View view) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://social-media-integra-1.flycricket.io/terms.html")));
}
};
ss.setSpan(clickableSpan,47,61, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
ss.setSpan(clickableSpan1,67,85,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
ss.setSpan(new ForegroundColorSpan(Color.rgb(119, 193, 253)), 47, 61, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
ss.setSpan(new ForegroundColorSpan(Color.rgb(119, 193, 253)), 67, 85, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
text_links.setText(ss);
text_links.setMovementMethod(LinkMovementMethod.getInstance());
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
image.startAnimation(AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
image.setVisibility(View.VISIBLE);
}
}, 1000);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
image.setVisibility(View.INVISIBLE);
image1.startAnimation(AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
image1.setVisibility(View.VISIBLE);
}
}, 3500);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
image1.setVisibility(View.INVISIBLE);
image2.startAnimation(AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade_in));
image2.setVisibility(View.VISIBLE);
}
}, 5500);
continue_btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, phoneno_auth.class));
finish();
}
});
}
}
|
package com.ssm.wechatpro.service;
import com.ssm.wechatpro.object.InputObject;
import com.ssm.wechatpro.object.OutputObject;
public interface MWechatDeliveryAddressService {
public void insertDeliveryAddress(InputObject inputObject, OutputObject outputObject) throws Exception;
public void selectByDeliveryUserId(InputObject inputObject, OutputObject outputObject) throws Exception;
public void deleteById(InputObject inputObject, OutputObject outputObject) throws Exception;
public void updateAddress(InputObject inputObject, OutputObject outputObject) throws Exception;
public void selectById(InputObject inputObject, OutputObject outputObject) throws Exception;
public void updateUse(InputObject inputObject, OutputObject outputObject) throws Exception;
}
|
package info.blockchain.wallet.ethereum;
final class EthUrls {
private EthUrls() {
throw new UnsupportedOperationException("You can't implement this class");
}
/* Base endpoint for all ETH operations */
private static final String ETH = "eth";
/* Base endpoint for v2 ETH operations */
private static final String ETHV2 = "v2/eth";
/* Additional paths for certain queries */
static final String IS_CONTRACT = "/isContract";
private static final String DATA = "/data";
/* Complete paths */
static final String ACCOUNT = ETH + "/account";
static final String PUSH_TX = ETH + "/pushtx";
static final String V2_DATA = ETHV2 + DATA;
static final String V2_DATA_ACCOUNT = ETHV2 + DATA + "/account";
static final String V2_DATA_TRANSACTION = ETHV2 + DATA + "/transaction";
}
|
import java.util.Random;
public class Board {
private int space[][] = new int[10][10];
private Random rand;
boolean bTryingtoPlace;
int direction;
int checkedBoardXpositionStart, checkedBoardXPositionEnd;
int checkedBoardYPositionStart, checkedBoardYPositionEnd;
boolean bThereisRoom;
public Board()
{
//when a car park object is initially created, make sure that all the spaces have an "E" for empty
for(int i = 0; i< 9; i++)
{
for( int j = 0; j<9; j++)
{
space[i][j] = 0;
}
}
//initialise our random number generator
rand = new Random();
bTryingtoPlace = false;
bThereisRoom = false;
//we will use x and y to reference the 5x5 grid coordinates where x is horizontal and y is vertical
//we will also use 0-direction for a horizontal placement and 1-direction for a vertical placement
direction = 0;checkedBoardXpositionStart = 0;checkedBoardYPositionStart = 0;
//the below helps us to see whether we can fit a whole vehicle in to the allocated spaces!
checkedBoardXPositionEnd = 0; checkedBoardYPositionEnd = 0;
}
public void DisplayBoardSpaces()
{
for(int i = 0; i< 10; i++)
{
for( int j = 0; j<10; j++)
{
System.out.print(space[j][i]);
System.out.print(" ");
}
System.out.println();
}
}
//this next method is NOT optimised and NOT the most efficient way of doing this, however it is a demonstration
//using step by step logic. Ideally this method would be broken down into smaller methods too.
public void PlaceShip(int lengthOfShip)
{
bTryingtoPlace = true;
while(bTryingtoPlace == true)
{
//rand returns a number of zero to four which matches the index locations of our CarPark array
checkedBoardXpositionStart = rand.nextInt(9);
checkedBoardYPositionStart = rand.nextInt(9);
checkedBoardXPositionEnd = checkedBoardXpositionStart;
checkedBoardYPositionEnd = checkedBoardYPositionStart;
//rand will return either a one or a zero so will randomly choose a direction
direction = rand.nextInt(2);
//lets check to see whether these randomly placed vehicle coordinates are viable in that they
//won't mean that a car is half sitting outside of the carpark grid:
//if the direction is horizontal find out what the end position will be based on the size of the car
if(direction == 0)
{
checkedBoardXPositionEnd = checkedBoardXpositionStart + (lengthOfShip - 1);
}
else
{
//if the direction is not zero, it must be one so the direction is vertical. Find out what the end
//position of the vertically placed car will be
checkedBoardYPositionEnd = checkedBoardYPositionStart + (lengthOfShip - 1);
}
//now make sure that these positions are not over extending the grid, and if they are, start all over again
if(checkedBoardXPositionEnd>9 || checkedBoardYPositionEnd>9)
{
//if either of the (remember '||' is 'OR') endpoint car positions are a number greater than the
// zero to four positions we have in our 5x5 grid:
//start the loop at the beginning again with all conditions reset, including the loop's initialisation
// condition - the true false bit!
// **PLEASE BE AWARE THIS IS NOT THE WAY WE WOULD DO IT IN INDUSTRY**
continue;
}
//if the positions created are valid and won't over extend the grid, we now need to check for spaces in the
//garage. We will split the logic in to two -
// a check for horizontal placement chosen
// and one for vertical placement chosen
// the logic however is the same and could potentially be combined or we could create two methods from it
//if the car is being placed HORIZONTALLY
if(direction == 0)
{
int noOfSpaces =0;
for(int i = checkedBoardXpositionStart; i<(checkedBoardXPositionEnd+1); i++)
{
if(space[i][checkedBoardYPositionStart]!= 0)
{
i = checkedBoardXPositionEnd+1;
bThereisRoom=false;
noOfSpaces =0;
}
else
{
noOfSpaces++;
}
//did we manage to loop through the size of the car and count enough empty space in the
//same direction
if(noOfSpaces == lengthOfShip)
{
//then there must be room to place a car
bThereisRoom = true;
//reset the count for next time around
noOfSpaces = 0;
}
}
//if we managed to find enough room then fill the car spaces up with the size of the car
if(bThereisRoom == true)
{
//fill the car park array with letters to represent the length of the car
for(int j = checkedBoardXpositionStart; j<(checkedBoardXPositionEnd+1); j++)
{
space[j][checkedBoardYPositionStart]= 1;
System.out.println("Horizontal: x: "+j+" y: "+checkedBoardYPositionStart);
}
//reset the spacefinder back to false for when the next vehicle needs to be checked
bThereisRoom = false;
//reset the parking method ready for use again for another vehicle
bTryingtoPlace = false;
}
}
else
{
int noOfSpaces =0;
//the car must be being placed VERTICALLY
for(int k = checkedBoardYPositionStart; k<checkedBoardYPositionEnd+1; k++)
{
if(space[checkedBoardXpositionStart][k]!= 0)
{
k = checkedBoardYPositionEnd+1;
bThereisRoom=false;
noOfSpaces = 0;
}
else
{
noOfSpaces++;
}
//did we manage to loop through the size of the car and count enough empty space in the
//same direction
if(noOfSpaces == lengthOfShip)
{
//then there must be room to place a car
bThereisRoom = true;
//reset the count for next time around
noOfSpaces = 0;
}
}
//if we managed to find enough room then fill the car spaces up with the size of the car
if(bThereisRoom == true)
{
//fill the car park array with letters to represent the length of the car
for(int m = checkedBoardYPositionStart; m< checkedBoardYPositionEnd+1; m++)
{
space[checkedBoardXpositionStart][m]= 1;
System.out.println("Vertical: x: "+checkedBoardXpositionStart+" y: "+m);
}
//reset the spacefinder back to false for when the next vehicle needs to be checked
bThereisRoom = false;
//reset the parking method ready for use again for another vehicle
bTryingtoPlace = false;
}
}
}
}
}
|
package game.entities;
/**
* Created by micha on 22.04.2017.
*
* Class for all in-game missiles fired by player's turrets.
*/
public class FriendlyMissile extends Missile {
// Constant sprite key for friendly missile.
private static final String FRIENDLY_MISSILE_SPRITE_KEY =
"friendly_missile.png";
public FriendlyMissile() {
super(GameEntitiesTypes.FRIENDLY_MISSILE, FRIENDLY_MISSILE_SPRITE_KEY);
}
public FriendlyMissile(
MissilesTypes missileType,
float x, float y, float rotation
) {
super(
GameEntitiesTypes.FRIENDLY_MISSILE, FRIENDLY_MISSILE_SPRITE_KEY,
missileType, x, y, rotation
);
}
}
|
package com.fourfire.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.thymeleaf.util.StringUtils;
import com.fourfire.converter.UserConverter;
import com.fourfire.dao.UserDao;
import com.fourfire.entity.User;
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserDao userDao;
@Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
if (StringUtils.isEmpty(username)) {
return null;
}
User user = userDao.getUserByName(username);
System.out.println("user=" + user);
if (user != null) {
UserDetails userDetails = UserConverter.convertToUserDetails(user);
return userDetails;
}
return null;
}
}
|
package dao;
import dao.impl.CategoryDaoImpl;
import dao.impl.CommentDaoImpl;
import dao.impl.RateResourceDaoImpl;
import dao.impl.ResourceDaoImpl;
import dao.impl.RoleDaoImpl;
import dao.impl.UserDaoImpl;
import models.*;
import org.junit.Before;
import org.junit.Test;
import play.libs.Yaml;
import testutils.BaseTest;
import utilities.Dependencies;
import static org.junit.Assert.*;
import static org.fest.assertions.Assertions.assertThat;
import java.util.List;
public class CommentDaoImplTest extends BaseTest{
@Before
public void before(){
List<Category> categoryList =(List) Yaml.load("test-data/categories.yml");
List<User> userList =(List) Yaml.load("test-data/users.yml");
Dependencies.initialize(new UserDaoImpl(), new RoleDaoImpl(), new CategoryDaoImpl(), new ResourceDaoImpl(), new CommentDaoImpl(), new RateResourceDaoImpl());
for (User user : userList) {
Dependencies.getUserDao().create(user);
}
for (Category category : categoryList) {
Dependencies.getCategoryDao().create(category);
}
Dependencies.getResourceDao().create(ResourceType.ARTICLE, "salam", null, "", Dependencies.getUserDao().findById(1), "","","");
}
@Test
public void CommentCreationTest(){
Resource resource = Dependencies.getResourceDao().findById(1);
User user = Dependencies.getUserDao().findById(1);
Comment comment = Dependencies.getCommentDao().create(user, "salam", resource);
assertThat(comment.user).isEqualTo(user);
assertThat(comment.body).isEqualTo("salam");
assertThat(comment.parResource).isEqualTo(resource);
assertNull(comment.parComment);
Comment comment2 = Dependencies.getCommentDao().create(user, "salam2", comment);
comment2 = Dependencies.getCommentDao().findById(comment2.id);
assertThat(comment2.user).isEqualTo(user);
assertThat(comment2.body).isEqualTo("salam2");
assertThat(comment2.parComment).isEqualTo(comment);
assertNull(comment2.parResource);
}
}
|
package stark.skplay.utils;
import android.text.format.DateUtils;
import java.util.Formatter;
import java.util.Locale;
public class TimeFormatUtil {
private static StringBuilder formatBuilder = new StringBuilder();
private static Formatter formatter = new Formatter(formatBuilder, Locale.getDefault());
/**
* Formats the specified milliseconds to a human readable format
* in the form of (Hours : Minutes : Seconds). If the specified
* milliseconds is less than 0 the resulting format will be
* "--:--" to represent an unknown time
*
* @param milliseconds The time in milliseconds to format
* @return The human readable time
*/
public static String formatMs(long milliseconds) {
if (milliseconds < 0) {
return "--:--";
}
long seconds = (milliseconds % DateUtils.MINUTE_IN_MILLIS) / DateUtils.SECOND_IN_MILLIS;
long minutes = (milliseconds % DateUtils.HOUR_IN_MILLIS) / DateUtils.MINUTE_IN_MILLIS;
long hours = (milliseconds % DateUtils.DAY_IN_MILLIS) / DateUtils.HOUR_IN_MILLIS;
formatBuilder.setLength(0);
if (hours > 0) {
return formatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
}
return formatter.format("%02d:%02d", minutes, seconds).toString();
}
}
|
package net.jefftran.tapestry5.kit.pages;
import org.apache.tapestry5.annotations.Property;
public class CapsLockDetectTest {
@Property
String text;
}
|
package com.creative.carviewslider;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.creative.carviewslider.ediciondatos.FragmentContactoItem;
import com.creative.carviewslider.ediciondatos.FragmentDireccionItem;
import com.creative.carviewslider.ediciondatos.FragmentPersonalesItem;
public class MainActivity extends AppCompatActivity
{
private ViewPager mViewPager;
private TabLayout mTabIndicator;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = findViewById(R.id.slider_viewpager);
mTabIndicator = findViewById(R.id.tab_indicator_tablayout);
createFragments();
}
private void createFragments()
{
FragmentPersonalesItem personales = new FragmentPersonalesItem();
Bundle argsPersonales = FragmentPersonalesItem.createBundle("3283283823","Javier Garcia","FSSD32323GRO00C","SJDFHDSHFHJDSHF34234","20/12/1996","Masculino","Mexico","Mexicana");
personales.setArguments(argsPersonales);
FragmentDireccionItem direcciones = new FragmentDireccionItem();
Bundle argsDirecciones = FragmentDireccionItem.createBundle("minita","8","","36990","Zona centro","","Mexico","Huanimaro","Guanajuato");
direcciones.setArguments(argsDirecciones);
FragmentContactoItem contacto = new FragmentContactoItem();
Bundle argsContacto = FragmentContactoItem.createBundle("4291233049","4296910253","","javier.creative.apps@gmail.com","");
contacto.setArguments(argsContacto);
CardFragmentAdapter adapter = new CardFragmentAdapter(getSupportFragmentManager());
adapter.addItem(personales);
adapter.addItem(direcciones);
adapter.addItem(contacto);
Transformer transformer = new Transformer(mViewPager, adapter);
transformer.enableScaling(true);
mViewPager.setPageTransformer(false, transformer);
mViewPager.setOffscreenPageLimit(3);
mViewPager.setAdapter(adapter);
mTabIndicator.setupWithViewPager(mViewPager);
}
}
|
package com.blazejprzyluski.chess.Pieces;
public enum Color
{
WHITE,BLACK;
}
|
package com.yy.webservice.server.core;
public interface BaseService {
public String invoke(String params);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.