blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 132 | path stringlengths 2 382 | src_encoding stringclasses 34
values | length_bytes int64 9 3.8M | score float64 1.5 4.94 | int_score int64 2 5 | detected_licenses listlengths 0 142 | license_type stringclasses 2
values | text stringlengths 9 3.8M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
b0433728156b4c1113afee87f4521500b714481d | Java | Shin-JungYeon/Java | /chap18/src/chap18/HW02.java | UHC | 2,732 | 3.6875 | 4 | [] | no_license | package chap18;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/*
* 2. ֿܼ ϸ ڸ Է¹Ƽ ش Էµ ڸŭ ϴ α ۼϱ. Scanner Ұ.
*
* []
*
* ϸ Է
* src/chap18/InputStreamEx1.java -> project ϱ () ʿ.
* μ Է
* 1
*
* []
*
* 1 :package chap15;
*/
public class HW02 {
public static void main(String[] args) throws IOException {
/*
String filepath = "src/chap18/";
while(true) {
try {
System.out.println(" ϸ Էϼ.");
InputStream input = System.in;
int data=0;
String filename = "";
while((data=input.read()) != -1) {
filename += (char)data;
if(input.available() == 0) break;
}
System.out.println(filename);
FileInputStream fis = new FileInputStream(filepath + "InputStreamEx1.java");
if(input.available() == 0) {
System.out.println(" μ Էϼ.");
InputStream input2 = System.in;
data = 0;
char line = (char) input2.read();
System.out.println(line);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
for(int i=1; i<=line; i++) {
System.out.println(i + ":" + ((br.readLine()!=null)?br.readLine():""));
}
break;
}
} catch (FileNotFoundException e) {
System.out.println(" ã ϴ. ٽ Էּ.");
continue;
} catch (IOException e) {
e.printStackTrace();
}
}
*/
//BufferedReader : ڿ پ ܼâ Űκ(System.in) Է¹ .
String filepath = "src/chap18/";
System.out.println(" ϸ Է");
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String filename = stdin.readLine(); //ڿ پ Է¹.
System.out.println(" μ Է");
int line = Integer.parseInt(stdin.readLine()); //String Է¹Ƽ Integer ȯ.
BufferedReader fbr = new BufferedReader(new FileReader(filepath + filename)); // Է .
String msg = null; // پ .
int prt = 0; //̹ .
while((msg = fbr.readLine()) != null) { //ڿ پ о.
if(line <= prt) break;
prt++;
System.out.println(prt + ":" + msg);
}
}
}
| true |
8b31b6d1fd8c4301fadf322c5999ae5b05befc70 | Java | JuliaPol/ProjectTSchool | /ProjectTSchool-backend/src/main/java/com/tsystems/ecare/config/AspectConfig.java | UTF-8 | 354 | 1.65625 | 2 | [] | no_license | package com.tsystems.ecare.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration
@EnableAspectJAutoProxy
@ComponentScan(basePackages = "com.tsystems.ecare.aop")
public class AspectConfig {
}
| true |
6457a13cb7cb843491f50addafa16f928242a5e0 | Java | yunjiayuan/ehome | /ehome-homeShop-goodsCenter/src/main/java/com/busi/dao/ShopFloorMasterOrdersDao.java | UTF-8 | 5,063 | 2.140625 | 2 | [] | no_license | package com.busi.dao;
import com.busi.entity.ShopFloorMasterOrders;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* @program: ehome
* @description: 楼店店主订单
* @author: ZHaoJiaJie
* @create: 2020-1-9 15:52:17
*/
@Mapper
@Repository
public interface ShopFloorMasterOrdersDao {
/***
* 新增厨房订座订单
* @param kitchenBookedOrders
* @return
*/
@Insert("insert into ShopFloorMasterOrders(buyerId,shopId,goods,money,addTime,paymentTime,deliveryTime,receivingTime,no,ordersState,ordersType," +
"addressId,distributioMode,shopName,remarks,address,addressName,addressPhone,addressProvince,addressCity,addressDistrict)" +
"values (#{buyerId},#{shopId},#{goods},#{money},#{addTime},#{paymentTime},#{deliveryTime},#{receivingTime},#{no},#{ordersState},#{ordersType}" +
",#{addressId},#{distributioMode},#{shopName},#{remarks},#{address},#{addressName},#{addressPhone},#{addressProvince},#{addressCity},#{addressDistrict})")
@Options(useGeneratedKeys = true)
int addOrders(ShopFloorMasterOrders kitchenBookedOrders);
/***
* 根据用户ID查询订单
* @param id
* @param type 查询场景 0删除 1由未发货改为已发货 2由未收货改为已收货 3取消订单
* @return
*/
@Select("<script>" +
"select * from ShopFloorMasterOrders" +
" where id = #{id}" +
"<if test=\"type == 0\">" +
" and ordersType >2 and ordersState=0" +
"</if>" +
"<if test=\"type == 1\">" +
" and ordersState=0 and ordersType=1" +
"</if>" +
"<if test=\"type == 2\">" +
" and ordersState=0 and ordersType=2 and buyerId=#{userId}" +
"</if>" +
"<if test=\"type == 3\">" +
" and ordersState=0 and ordersType < 3 and buyerId=#{userId}" +
"</if>" +
"</script>")
ShopFloorMasterOrders findById(@Param("id") long id, @Param("userId") long userId, @Param("type") int type);
/***
* 根据订单编号查询订单
* @param no 订单编号
* @return
*/
@Select("<script>" +
"select * from ShopFloorMasterOrders" +
" where no = #{no}" +
" and ordersState = 0" +
"</script>")
ShopFloorMasterOrders findByNo(@Param("no") String no);
/***
* 更新楼店订单状态
* updateCategory 更新类别 0删除状态 1由未发货改为已发货 2由未收货改为已收货 3取消订单 4更新支付状态
* @param orders
* @return
*/
@Update("<script>" +
"update ShopFloorMasterOrders set" +
"<if test=\"updateCategory == 0\">" +
" ordersState =1," +
"</if>" +
"<if test=\"updateCategory == 1\">" +
" deliveryTime =#{deliveryTime}," +
" ordersType =#{ordersType}," +
"</if>" +
"<if test=\"updateCategory == 2\">" +
" ordersType =#{ordersType}," +
" receivingTime =#{receivingTime}," +
"</if>" +
"<if test=\"updateCategory == 3\">" +
" ordersType =#{ordersType}," +
"</if>" +
"<if test=\"updateCategory == 4\">" +
" paymentTime =#{paymentTime}," +
" ordersType =#{ordersType}," +
"</if>" +
" id=#{id} " +
" where id=#{id} and ordersState=0" +
"</script>")
int updateOrders(ShopFloorMasterOrders orders);
/***
* 分页查询订单列表
* @param ordersType 订单类型: -1全部 0待付款,1待发货(已付款),2已发货(待收货), 3已收货(待评价) 4已评价 5付款超时、发货超时、买家取消订单、卖家取消订单
* @return
*/
@Select("<script>" +
"select * from ShopFloorMasterOrders" +
" where ordersState=0" +
"<if test=\"userId > 0 \">" +
" and buyerId = #{userId}" +
"</if>" +
"<if test=\"ordersType == -2\">" +
" and ordersType > 0" +
// " and ordersType in (1,2,3,4) " +
"</if>" +
"<if test=\"ordersType > 0 and ordersType < 5\">" +
" and ordersType = #{ordersType}" +
"</if>" +
"<if test=\"ordersType >= 5\">" +
" and ordersType > 5" +
"</if>" +
" order by addTime desc" +
"</script>")
List<ShopFloorMasterOrders> findOrderList(@Param("userId") long userId, @Param("ordersType") int ordersType);
/***
* 统计各类订单数量
* @return
*/
@Select("<script>" +
"select * from ShopFloorMasterOrders" +
" where 1=1 " +
" and buyerId = #{userId}" +
" and ordersState = 0" +
"</script>")
List<ShopFloorMasterOrders> findIdentity(@Param("userId") long userId);
}
| true |
e63fb7b4598f26b78cb3708fdf3737c1f5e43d09 | Java | royardhian/XSIS-POS | /src/main/java/com/bootcamp/pos/model/TrxPoModel.java | UTF-8 | 3,743 | 2.109375 | 2 | [] | no_license | package com.bootcamp.pos.model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.TableGenerator;
@Entity
@Table(name = "POS_TRX_PO")
public class TrxPoModel {
private int id;
private int prId;
private int outletId;
private int supplierId;
private String poNo;
private String notes;
private Double grandTotal;
private String status;
private int createdBy;
private Date createdOn;
private int modifiedBy;
private Date modifiedOn;
private TrxPrModel trxPr;
private MstOutletModel outlet;
private MstSupplierModel supplier;
@Id
@Column(name = "ID")
@GeneratedValue(strategy = GenerationType.TABLE, generator = "TRX_PO")
@TableGenerator(name = "TRX_PO", table = "POS_MST_SEQUENCE", pkColumnName = "SEQUENCE_ID", pkColumnValue = "TRX_PO", valueColumnName = "SEQUENCE_VALUE", allocationSize = 1, initialValue = 1)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name = "PR_ID")
public int getPrId() {
return prId;
}
public void setPrId(int prId) {
this.prId = prId;
}
@Column(name = "OUTLET_ID")
public int getOutletId() {
return outletId;
}
public void setOutletId(int outletId) {
this.outletId = outletId;
}
@Column(name = "SUPPLIER_ID")
public int getSupplierId() {
return supplierId;
}
public void setSupplierId(int supplierId) {
this.supplierId = supplierId;
}
@Column(name = "PO_NO", length = 50)
public String getPoNo() {
return poNo;
}
public void setPoNo(String poNo) {
this.poNo = poNo;
}
@Column(name = "NOTES", length = 255)
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
@Column(name = "GRAND_TOTAL")
public Double getGrandTotal() {
return grandTotal;
}
public void setGrandTotal(Double grandTotal) {
this.grandTotal = grandTotal;
}
@Column(name = "STATUS", length = 1)
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
@Column(name = "CREATED_ON")
public Date getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}
@Column(name = "CREATED_BY")
public int getCreatedBy() {
return createdBy;
}
public void setCreatedBy(int createdBy) {
this.createdBy = createdBy;
}
@Column(name = "MODIFIED_ON")
public Date getModifiedOn() {
return modifiedOn;
}
public void setModifiedOn(Date modifiedOn) {
this.modifiedOn = modifiedOn;
}
@Column(name = "MODIFIED_BY")
public int getModifiedBy() {
return modifiedBy;
}
public void setModifiedBy(int modifiedBy) {
this.modifiedBy = modifiedBy;
}
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "PR_ID", nullable = false, insertable = false, updatable = false)
public TrxPrModel getTrxPr() {
return trxPr;
}
public void setTrxPr(TrxPrModel trxPr) {
this.trxPr = trxPr;
}
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "OUTLET_ID", nullable = false, insertable = false, updatable = false)
public MstOutletModel getOutlet() {
return outlet;
}
public void setOutlet(MstOutletModel outlet) {
this.outlet = outlet;
}
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "SUPPLIER_ID", nullable = false, insertable = false, updatable = false)
public MstSupplierModel getSupplier() {
return supplier;
}
public void setSupplier(MstSupplierModel supplier) {
this.supplier = supplier;
}
} | true |
0952edda6de5c06951123bd1b82c6ec8b257af4a | Java | EzioL/leetcode-practice | /src/main/java/com/ezio/leetcodepractice/invertTree/InvertTreeTest.java | UTF-8 | 711 | 2.9375 | 3 | [] | no_license | package com.ezio.leetcodepractice.invertTree;
/**
* Here be dragons
* Created by haotian on 2018/8/21 下午9:54
*/
public class InvertTreeTest {
public static void main(String[] args) {
TreeNode treeNode = new TreeNode(4);
treeNode.setLeft(new TreeNode(2));
treeNode.getLeft().setLeft(new TreeNode(1));
treeNode.getLeft().setRight(new TreeNode(3));
treeNode.setRight(new TreeNode(7));
treeNode.getRight().setLeft(new TreeNode(6));
treeNode.getRight().setRight(new TreeNode(9));
System.err.println(treeNode);
InvertTreeProblem problem = new InvertTreeProblem(treeNode);
System.err.println(problem.getTreeNode());
}
}
| true |
0260c539ae9945ffca2a353526d3b2527c671d3c | Java | dalianpa/hasor | /hasor-dataql/src/main/java/net/hasor/dataql/UdfManager.java | UTF-8 | 1,053 | 1.960938 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2008-2009 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 net.hasor.dataql;
import java.util.List;
/**
* UDF数据源管理器
* @author 赵永春 (zyc@hasor.net)
* @version : 2017-03-23
*/
public interface UdfManager {
/**Source名*/
public List<UdfSource> getSourceByName(String sourceName);
/**数据源名字*/
public List<String> getSourceNames();
/**设置默认Udf数据源(默认数据源的name为空)*/
public void addSource(UdfSource udfSource);
} | true |
9bbeb7aafaa50e18a1b493d7c707173aa86a3504 | Java | damiansm/PhenotypeData | /indexers/src/test/java/org/mousephenotype/cda/indexers/ImpcImagesIndexerTest.java | UTF-8 | 1,773 | 1.90625 | 2 | [
"Apache-2.0"
] | permissive | package org.mousephenotype.cda.indexers;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mousephenotype.cda.config.TestConfigIndexers;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
/**
* Created by jmason on 01/12/2016.
*/
@RunWith(SpringRunner.class)
@ContextConfiguration(classes={TestConfigIndexers.class})
@TestPropertySource(locations = {"file:${user.home}/configfiles/${profile:dev}/test.properties"})
public class ImpcImagesIndexerTest implements ApplicationContextAware {
private ApplicationContext applicationContext;
private ImpcImagesIndexer impcImagesIndexer;
@Before
public void setUp() throws Exception {
impcImagesIndexer = ImpcImagesIndexer.class.newInstance();
applicationContext.getAutowireCapableBeanFactory().autowireBean(impcImagesIndexer);
applicationContext.getAutowireCapableBeanFactory().initializeBean(impcImagesIndexer, "IndexBean" + impcImagesIndexer.getClass().toGenericString());
}
@Test
public void getHighestObservationId() throws Exception {
Integer largest = impcImagesIndexer.getHighestObservationId();
System.out.println("Largest ID is " + largest);
assert(largest > 1000000); // There are at least One MILLION documents
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
} | true |
b4aedc6ab4d99c99976461113b5d6277257a6a4a | Java | pmuir/weld-core | /environments/servlet/core/src/main/java/org/jboss/weld/environment/servlet/deployment/WebAppBeanDeploymentArchive.java | UTF-8 | 4,211 | 1.710938 | 2 | [] | no_license | /**
* JBoss, Home of Professional Open Source
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.weld.environment.servlet.deployment;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.ServletContext;
import org.jboss.weld.bootstrap.api.Bootstrap;
import org.jboss.weld.bootstrap.api.ServiceRegistry;
import org.jboss.weld.bootstrap.api.helpers.SimpleServiceRegistry;
import org.jboss.weld.bootstrap.spi.BeanDeploymentArchive;
import org.jboss.weld.bootstrap.spi.BeansXml;
import org.jboss.weld.ejb.spi.EjbDescriptor;
import org.jboss.weld.environment.servlet.util.Reflections;
import org.jboss.weld.environment.servlet.util.Servlets;
/**
* The means by which Web Beans are discovered on the classpath. This will only
* discover simple web beans - there is no EJB/Servlet/JPA integration.
*
* @author Peter Royle
* @author Pete Muir
* @author Ales Justin
*/
public class WebAppBeanDeploymentArchive implements BeanDeploymentArchive
{
public static final String META_INF_BEANS_XML = "META-INF/beans.xml";
public static final String WEB_INF_BEANS_XML = "/WEB-INF/beans.xml";
public static final String WEB_INF_CLASSES = "/WEB-INF/classes";
private final Set<String> classes;
private final BeansXml beansXml;
private final ServiceRegistry services;
public WebAppBeanDeploymentArchive(ServletContext servletContext, Bootstrap bootstrap)
{
this.services = new SimpleServiceRegistry();
this.classes = new HashSet<String>();
Set<URL> urls = new HashSet<URL>();
URLScanner scanner = createScanner(servletContext);
scanner.scanResources(new String[] { META_INF_BEANS_XML }, classes, urls);
try
{
URL beans = servletContext.getResource(WEB_INF_BEANS_XML);
if (beans != null)
{
urls.add(beans); // this is consistent with how the JBoss weld.deployer works
File webInfClasses = Servlets.getRealFile(servletContext, WEB_INF_CLASSES);
if (webInfClasses != null)
{
File[] files = { webInfClasses };
scanner.scanDirectories(files, classes, urls);
}
}
}
catch (MalformedURLException e)
{
throw new IllegalStateException("Error loading resources from servlet context ", e);
}
this.beansXml = bootstrap.parse(urls);
}
protected URLScanner createScanner(ServletContext context)
{
URLScanner scanner = (URLScanner) context.getAttribute(URLScanner.class.getName());
if (scanner == null)
{
ClassLoader cl = Reflections.getClassLoader();
scanner = new URLScanner(cl);
}
else
{
// cleanup
context.removeAttribute(URLScanner.class.getName());
}
return scanner;
}
public Collection<String> getBeanClasses()
{
return classes;
}
public Collection<BeanDeploymentArchive> getBeanDeploymentArchives()
{
return Collections.emptySet();
}
public BeansXml getBeansXml()
{
return beansXml;
}
public Collection<EjbDescriptor<?>> getEjbs()
{
return Collections.emptySet();
}
public ServiceRegistry getServices()
{
return services;
}
public String getId()
{
// Use "flat" to allow us to continue to use ManagerObjectFactory
return "flat";
}
}
| true |
7d2bab507b57b2f320efcdd2ab3181046769e47a | Java | sivakumar27794/playboy | /StudentDetails/src/com/asminds/controller/Controller.java | UTF-8 | 3,610 | 2.59375 | 3 | [] | no_license | package com.asminds.controller;
import java.util.Iterator;
import java.util.List;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.asminds.daoimple.DaoImple;
import com.asminds.pojo.Student;
import com.asminds.pojo.UpdatePojo;
@org.springframework.stereotype.Controller
public class Controller {
@RequestMapping("/")
public String home()
{
System.out.println("i am in home method");
return "home";
}
@RequestMapping("/home")
public String ho()
{
System.out.println("i am in ho method ");
return"home";
}
@RequestMapping("/create")
public String insert1()
{
System.out.println("im in insert1 method");
return "insert1";
}
@RequestMapping("/save")
public String CreateValidatmethod(@ModelAttribute ("u") Student s)
{
System.out.println("im in CreateValidatemethod control");
DaoImple dao=new DaoImple();
dao.insert(s);
return "redirect:/" ;
}
@RequestMapping("/select")
public String search1()
{
System.out.println("i am in search1 method");
return "search1";
}
@RequestMapping("/search1")
public ModelAndView SearchAfter(@ModelAttribute ("t") Student s)
{
System.out.println("im in searchAfter control");
System.out.println(s.getId());
DaoImple dao=new DaoImple();
List<Student>l=dao.search(s);
return new ModelAndView("search2","kk",l);
}
@RequestMapping("/delete")
public ModelAndView EmpView() {
System.out.println(" Im in delete 2");
DaoImple dao=new DaoImple();
System.out.println(" Going to get details for delete ");
List<Student> emp = dao.getallStudentpojo();
return new ModelAndView("delete", "list", emp);
}
@RequestMapping(value="/deleteemp/{id}")
public ModelAndView delete(@PathVariable int id){
DaoImple dao=new DaoImple();
dao.deleteEmployee(id);
return new ModelAndView("redirect:/");
}
@RequestMapping("/update")
public ModelAndView update() {
System.out.println(" Im in logincheck");
DaoImple dao=new DaoImple();
System.out.println(" Going to get details for update");
List<Student> emp = dao.getallStudentpojo();
return new ModelAndView("update", "update", emp);
}
@RequestMapping("/update1")
public ModelAndView update1(@ModelAttribute("h") UpdatePojo up) {
System.out.println("sixth method");
DaoImple di=new DaoImple();
List<Student>l=di.updateDAO(up);
System.out.println("total number of records"+l.size());
return new ModelAndView("update1","up",l);
}
@RequestMapping("/update2")
public String Update2(@ModelAttribute("upd") Student loo) {
System.out.println("updted");
System.out.println(loo.getAddress());
DaoImple update=new DaoImple();
Boolean b = update.updateemployeeDao(loo);
if(b==true) {
return "redirect:/";
}else {
return "/update";
}
}
@RequestMapping("/displayall")
public ModelAndView display()
{
System.out.println(" Im in logincheck");
DaoImple dao=new DaoImple();
System.out.println(" Going to get the emp");
List<Student> emp = dao.getallStudentpojo();
return new ModelAndView("displayall", "list", emp);
}
}
| true |
7e46a783dd84e6ed168042c3c4188a42c077075c | Java | FairWolf01/The-Betweenlands | /src/main/java/thebetweenlands/common/block/misc/BlockRubberTap.java | UTF-8 | 6,697 | 2.03125 | 2 | [] | no_license | package thebetweenlands.common.block.misc;
import javax.annotation.Nullable;
import net.minecraft.block.Block;
import net.minecraft.block.BlockHorizontal;
import net.minecraft.block.ITileEntityProvider;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyInteger;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockRenderLayer;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.Mirror;
import net.minecraft.util.Rotation;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import thebetweenlands.common.block.terrain.BlockRubberLog;
import thebetweenlands.common.registries.BlockRegistry;
import thebetweenlands.common.tile.TileEntityRubberTap;
public class BlockRubberTap extends BlockHorizontal implements ITileEntityProvider {
public static final PropertyInteger AMOUNT = PropertyInteger.create("amount", 0, 15);
protected static final AxisAlignedBB TAP_WEST_AABB = new AxisAlignedBB(0.4D, 0.0D, 0.15D, 1.0D, 1.0D, 0.85D);
protected static final AxisAlignedBB TAP_EAST_AABB = new AxisAlignedBB(0.0D, 0.0D, 0.15D, 0.6D, 1.0D, 0.85D);
protected static final AxisAlignedBB TAP_SOUTH_AABB = new AxisAlignedBB(0.15D, 0.0D, 0.0D, 0.85D, 1.0D, 0.6D);
protected static final AxisAlignedBB TAP_NORTH_AABB = new AxisAlignedBB(0.15D, 0.0D, 0.4D, 0.85D, 1.0D, 1.0D);
/**
* The number of ticks it requires to fill up to the next step (15 steps in total)
*/
public final int ticksPerStep;
@SuppressWarnings("deprecation")
public BlockRubberTap(IBlockState material, int ticksPerStep) {
super(material.getMaterial());
this.setDefaultState(this.getBlockState().getBaseState().withProperty(AMOUNT, 0));
this.setSoundType(material.getBlock().getSoundType());
this.setHardness(2.0F);
this.ticksPerStep = ticksPerStep;
this.setCreativeTab(null);
}
@Override
public IBlockState onBlockPlaced(World worldIn, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer) {
if (this.canPlaceAt(worldIn, pos, facing)) {
return this.getDefaultState().withProperty(FACING, facing);
} else {
for (EnumFacing enumfacing : FACING.getAllowedValues()) {
if(this.canPlaceAt(worldIn, pos, enumfacing))
return this.getDefaultState().withProperty(FACING, enumfacing);
}
return this.getDefaultState();
}
}
@Override
public void onBlockAdded(World worldIn, BlockPos pos, IBlockState state) {
this.checkForDrop(worldIn, pos, state);
}
@Override
public boolean canPlaceBlockAt(World worldIn, BlockPos pos) {
for (EnumFacing enumfacing : FACING.getAllowedValues()) {
if (this.canPlaceAt(worldIn, pos, enumfacing)) {
return true;
}
}
return false;
}
@Override
public void neighborChanged(IBlockState state, World worldIn, BlockPos pos, Block blockIn) {
if (this.checkForDrop(worldIn, pos, state)) {
EnumFacing facing = (EnumFacing)state.getValue(FACING);
EnumFacing.Axis axis = facing.getAxis();
EnumFacing oppositeFacing = facing.getOpposite();
if (axis.isVertical() || !this.canPlaceOn(worldIn, pos.offset(oppositeFacing))) {
this.dropBlockAsItem(worldIn, pos, state, 0);
worldIn.setBlockToAir(pos);
}
}
}
protected boolean checkForDrop(World worldIn, BlockPos pos, IBlockState state) {
if (state.getBlock() == this && this.canPlaceAt(worldIn, pos, (EnumFacing)state.getValue(FACING))) {
return true;
} else {
if (worldIn.getBlockState(pos).getBlock() == this) {
this.dropBlockAsItem(worldIn, pos, state, 0);
worldIn.setBlockToAir(pos);
}
return false;
}
}
private boolean canPlaceAt(World worldIn, BlockPos pos, EnumFacing facing) {
BlockPos blockPos = pos.offset(facing.getOpposite());
boolean isHorizontal = facing.getAxis().isHorizontal();
return isHorizontal && this.canPlaceOn(worldIn, blockPos);
}
private boolean canPlaceOn(World worldIn, BlockPos pos) {
IBlockState state = worldIn.getBlockState(pos);
return state.getBlock() == BlockRegistry.LOG_RUBBER && state.getValue(BlockRubberLog.NATURAL);
}
@Override
public IBlockState withRotation(IBlockState state, Rotation rot) {
return state.withProperty(FACING, rot.rotate((EnumFacing)state.getValue(FACING)));
}
@Override
public IBlockState withMirror(IBlockState state, Mirror mirrorIn) {
return state.withRotation(mirrorIn.toRotation((EnumFacing)state.getValue(FACING)));
}
@Override
protected BlockStateContainer createBlockState() {
return new BlockStateContainer(this, new IProperty[] {FACING, AMOUNT});
}
@Override
public boolean isOpaqueCube(IBlockState state) {
return false;
}
@Override
public boolean isFullCube(IBlockState state) {
return false;
}
@Override
@SideOnly(Side.CLIENT)
public BlockRenderLayer getBlockLayer() {
return BlockRenderLayer.CUTOUT;
}
@Override
public IBlockState getStateFromMeta(int meta) {
return this.getDefaultState().withProperty(FACING, EnumFacing.getHorizontal(meta));
}
@Override
public int getMetaFromState(IBlockState state) {
return ((EnumFacing)state.getValue(FACING)).getHorizontalIndex();
}
@Override
public IBlockState getActualState(IBlockState state, IBlockAccess worldIn, BlockPos pos) {
TileEntity te = worldIn.getTileEntity(pos);
if(te != null && te instanceof TileEntityRubberTap) {
FluidStack drained = ((TileEntityRubberTap)te).drain(Fluid.BUCKET_VOLUME, false);
if(drained != null) {
int amount = (int)((float)drained.amount / (float)Fluid.BUCKET_VOLUME * 15.0F);
state = state.withProperty(AMOUNT, amount);
} else {
state = state.withProperty(AMOUNT, 0);
}
}
return state;
}
@Override
public TileEntity createNewTileEntity(World worldIn, int meta) {
return new TileEntityRubberTap();
}
@Override
public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos) {
switch ((EnumFacing)state.getValue(FACING)) {
default:
case EAST:
return TAP_EAST_AABB;
case WEST:
return TAP_WEST_AABB;
case SOUTH:
return TAP_SOUTH_AABB;
case NORTH:
return TAP_NORTH_AABB;
}
}
@Override
@Nullable
public AxisAlignedBB getCollisionBoundingBox(IBlockState blockState, World worldIn, BlockPos pos) {
return this.getBoundingBox(blockState, worldIn, pos);
}
}
| true |
0151ec72ed2b6fc5c19cad60c0ccbc5857fd033a | Java | ryangardner/excursion-decompiling | /divestory-CFR/com/google/api/client/http/HttpTransport.java | UTF-8 | 1,459 | 2.140625 | 2 | [] | no_license | /*
* Decompiled with CFR <Could not determine version>.
*/
package com.google.api.client.http;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.LowLevelHttpRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.logging.Logger;
public abstract class HttpTransport {
static final Logger LOGGER = Logger.getLogger(HttpTransport.class.getName());
private static final String[] SUPPORTED_METHODS;
static {
Object[] arrobject = new String[]{"DELETE", "GET", "POST", "PUT"};
SUPPORTED_METHODS = arrobject;
Arrays.sort(arrobject);
}
HttpRequest buildRequest() {
return new HttpRequest(this, null);
}
protected abstract LowLevelHttpRequest buildRequest(String var1, String var2) throws IOException;
public final HttpRequestFactory createRequestFactory() {
return this.createRequestFactory(null);
}
public final HttpRequestFactory createRequestFactory(HttpRequestInitializer httpRequestInitializer) {
return new HttpRequestFactory(this, httpRequestInitializer);
}
public void shutdown() throws IOException {
}
public boolean supportsMethod(String string2) throws IOException {
if (Arrays.binarySearch(SUPPORTED_METHODS, string2) < 0) return false;
return true;
}
}
| true |
ce7a479d91635d003065f177c095a551638426e0 | Java | LiuLubczdkg/HRMS | /HRMS/src/com/controller/ResumeController.java | UTF-8 | 1,391 | 2.203125 | 2 | [] | no_license | package com.controller;
import com.model.Recruitment;
import com.model.Resume;
import com.service.RecruitmentService;
import com.service.ResumeService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
@Controller
public class ResumeController {
@Resource
private ResumeService resumeService;
@RequestMapping(value = "/addResume")
public String addResume(Resume resume, HttpServletRequest request){
Resume resume1=resumeService.MyResume(resume);
if (null==resume1){
resumeService.addResume(resume);
return "guest";
}
return "wrong";
}
@RequestMapping(value = "/delResume")
public String delResume(Resume resume, HttpServletRequest request){
Resume resume1=resumeService.MyResume(resume);
if (null==resume1){
resumeService.deleteResume(resume);
return "guest";
}
return "wrong";
}
@RequestMapping(value = "/updateResume")
public String updateResume(Resume resume, HttpServletRequest request){
Resume resume1=resumeService.MyResume(resume);
if (null==resume1){
resumeService.updateResume(resume);
return "guest";
}
return "wrong";
}
}
| true |
5e18cf6fb0175688e1347b6466bd87062be558d9 | Java | ninepig/201920 | /201920/src/company/oracle/longestCommonPrefix14.java | UTF-8 | 1,553 | 3.5625 | 4 | [] | no_license | package company.oracle;
public class longestCommonPrefix14 {
// 自己的做法無法控制 str[0] 長度的影響
// 通過增加flag 來完成!
public String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) return "";
StringBuilder sb = new StringBuilder();
String first = strs[0];
boolean ifContinue = true;
for (int j = 0 ; j < first.length() ; j ++){
char c = first.charAt(j);
for (int i = 1 ; i < strs.length ; i++){
if ( j >= strs[i].length() || strs[i].charAt(j)!= c){
ifContinue = false;
break;
}
}
if (ifContinue) {
sb.append(c);
}else {
break;
}
}
return sb.toString();
}
public String longestCommonPrefixRightone(String[] strs) {
if (strs == null || strs.length ==0)
return "";
int index = 0;
StringBuilder sb = new StringBuilder();
boolean ifTrue = true;
while (ifTrue && index < strs[0].length()){
for (int i = 0 ; i<strs.length ; i++){
if (strs[i].length() <= index || strs[i].charAt(index) != strs[0].charAt(index)){
ifTrue = false;
break;
}
}
if (ifTrue){
sb.append(strs[0].charAt(index));
index++;
}
}
return sb.toString();
}
}
| true |
1c3c3b6942145215d7229f971f71fa50336405ad | Java | Tamitry/IT-company | /src/test/java/by/epam/TarlikovskiDzmitriy/task4/activity/ControlTest.java | UTF-8 | 1,040 | 2.453125 | 2 | [] | no_license | package by.epam.TarlikovskiDzmitriy.task4.activity;
import by.epam.javatraining.TarlikouskiDzmitri.task04.activity.Control;
import by.epam.javatraining.TarlikouskiDzmitri.task04.entity.department.TeamMembers;
import by.epam.javatraining.TarlikouskiDzmitri.task04.entity.employee.Tester;
import by.epam.javatraining.TarlikouskiDzmitri.task04.entity.enums.TestType;
import org.junit.Assert;
import org.junit.Test;
public class ControlTest {
@Test
public void collectTeamTest_equals() {
Control control = new Control();
TeamMembers teamMembers = control.collectTeam("./src/test/resource/Resource.txt");
TeamMembers expectedTeam = new TeamMembers();
expectedTeam.addEmpolyee(new Tester("Aleksei", "Ewart", 24, 3, 1000, TestType.MANUAL));
expectedTeam.addEmpolyee(new Tester("Ivan", "Dayan", 21, 1, 1100, TestType.AUTOMATIC));
expectedTeam.addEmpolyee(new Tester("Nicholas", "Watson", 30, 6, 600, TestType.AUTOMATIC));
Assert.assertEquals(expectedTeam, teamMembers);
}
}
| true |
ae0b27db1087b81521d08ea1130f7742b12b0206 | Java | Sashie/DragonSphereZ | /src/ud/bi0/dragonSphereZ/skriptAPI/expression/ExprActiveEffect.java | UTF-8 | 1,050 | 2.265625 | 2 | [
"MIT"
] | permissive | package ud.bi0.dragonSphereZ.skriptAPI.expression;
import javax.annotation.Nullable;
import org.bukkit.event.Event;
import ch.njol.skript.lang.Expression;
import ch.njol.skript.lang.SkriptParser.ParseResult;
import ch.njol.skript.lang.util.SimpleExpression;
import ch.njol.util.Kleenean;
import ud.bi0.dragonSphereZ.DragonSphereCore;
public class ExprActiveEffect extends SimpleExpression<Boolean>{
Expression<String> idName;
@Override
public Class<? extends Boolean> getReturnType() {
return Boolean.class;
}
@Override
public boolean isSingle() {
return true;
}
@SuppressWarnings("unchecked")
@Override
public boolean init(Expression<?>[] expr, int arg1, Kleenean arg2, ParseResult arg3) {
idName = (Expression<String>) expr[0];
return true;
}
@Override
public String toString(@Nullable Event arg0, boolean arg1) {
return "[particle ]effect %string% is active";
}
@Override
@Nullable
protected Boolean[] get(Event e) {
return new Boolean[]{DragonSphereCore.effectManager.isActive(idName.getSingle(e))};
}
}
| true |
82c37caaa440e4fbbd2cf534c08f0ebcfc7de056 | Java | fmalinowski/RamseyNumber | /apps/ramseyapp/src/test/java/edu/ucsb/cs290cloud/strategies/StrategyTest.java | UTF-8 | 5,293 | 3.046875 | 3 | [] | no_license | package edu.ucsb.cs290cloud.strategies;
import static org.junit.Assert.*;
import org.junit.Test;
import edu.ucsb.cs290cloud.commons.GraphWithInfos;
import edu.ucsb.cs290cloud.commons.GraphFactory;
public class StrategyTest {
//@Test
public void testSetAndGetInitialGraph() {
class StrategyChild extends Strategy {
@Override
public void runStrategy() {
}
};
StrategyChild newStrategy;
GraphWithInfos initialGraph, initialGraphInStrategy;
initialGraph = GraphFactory.generateRandomGraph(2);
initialGraph.setBestCount(2);
newStrategy = new StrategyChild();
assertEquals(Strategy.Status.NOT_YET_STARTED, newStrategy.getStrategyStatus());
newStrategy.setInitialGraph(initialGraph);
assertEquals(Strategy.Status.BEING_COMPUTED, newStrategy.getStrategyStatus());
initialGraphInStrategy = newStrategy.getInitialGraph();
assertNotSame(initialGraph, initialGraphInStrategy);
assertEquals(initialGraph.getBestCount(), initialGraphInStrategy.getBestCount());
assertTrue(initialGraph.equals(initialGraphInStrategy));
}
//@Test
public void testInitialGraph_canRetrieveInitialGraphInTheOtherThread() {
class GraphContainer {
public GraphWithInfos graphUsedInThread;
};
class StrategyChild extends Strategy {
public GraphContainer gc;
@Override
public void runStrategy() {
gc.graphUsedInThread = this.getInitialGraph();
}
};
StrategyChild newStrategy;
GraphContainer graphUsedInThread;
GraphWithInfos initialGraph;
graphUsedInThread = new GraphContainer();
newStrategy = new StrategyChild();
newStrategy.gc = graphUsedInThread;
initialGraph = new GraphWithInfos(2);
initialGraph.setValue(0, 0, 1);
initialGraph.setValue(0, 1, 2);
initialGraph.setValue(1, 0, 3);
initialGraph.setValue(1, 1, 4);
initialGraph.setBestCount(2);
newStrategy.setInitialGraph(initialGraph);
assertNull(graphUsedInThread.graphUsedInThread);
newStrategy.run();
try {
newStrategy.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
// Make sure getInitialGraph was called and that it cloned the graph
// but it's not the same instance as the one provided by setInitialGraph
assertNotNull(graphUsedInThread.graphUsedInThread);
assertNotSame(initialGraph, graphUsedInThread.graphUsedInThread);
// We check that the graph itself is the same
assertEquals(1, graphUsedInThread.graphUsedInThread.getValue(0, 0));
assertEquals(2, graphUsedInThread.graphUsedInThread.getValue(0, 1));
assertEquals(3, graphUsedInThread.graphUsedInThread.getValue(1, 0));
assertEquals(4, graphUsedInThread.graphUsedInThread.getValue(1, 1));
// We check also that the other properties are the same
assertEquals(initialGraph.getBestCount(),
graphUsedInThread.graphUsedInThread.getBestCount());
// We make sure that the setInitialGraph modified the status of the strategy
assertEquals(Strategy.Status.BEING_COMPUTED, newStrategy.getStrategyStatus());
}
//@Test
public void testStrategyStatusAndGraph_canSetValuesInOtherThreadAndReadThemFromOtherThread() {
class StrategyChild extends Strategy {
public volatile Boolean continueInfiniteLoop = true;
@Override
public void runStrategy() {
synchronized(this) {
GraphWithInfos graph = this.getInitialGraph();
graph.flipValue(0, 0);
this.setStrategyStatus(Strategy.Status.COUNTER_EXAMPLE, graph);
notify();
}
// Simulate processing in thread
while(continueInfiniteLoop);
}
};
StrategyChild newStrategy;
GraphWithInfos initialGraph, graphFromStrategy;
initialGraph = new GraphWithInfos(2);
initialGraph.setValue(0, 0, 0);
initialGraph.setValue(0, 1, 1);
initialGraph.setValue(1, 0, 1);
initialGraph.setValue(1, 1, 0);
initialGraph.setBestCount(2);
newStrategy = new StrategyChild();
newStrategy.setInitialGraph(initialGraph);
assertEquals(Strategy.Status.BEING_COMPUTED, newStrategy.getStrategyStatus());
newStrategy.start();
synchronized(newStrategy) {
try {
newStrategy.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
assertEquals(Strategy.Status.COUNTER_EXAMPLE, newStrategy.getStrategyStatus());
graphFromStrategy = newStrategy.getGraph();
assertEquals(initialGraph.getValue(0, 1), graphFromStrategy.getValue(0, 1));
assertEquals(initialGraph.getValue(1, 0), graphFromStrategy.getValue(1, 0));
assertEquals(initialGraph.getValue(1, 1), graphFromStrategy.getValue(1, 1));
assertNotEquals(initialGraph.getValue(0, 0), graphFromStrategy.getValue(0, 0));
assertEquals(1, graphFromStrategy.getValue(0, 0));
}
newStrategy.continueInfiniteLoop = false;
}
//@Test
public void testResetStrategy() {
class StrategyChild extends Strategy {
@Override
public void runStrategy() {
}
};
StrategyChild strategy;
GraphWithInfos graph;
graph = GraphFactory.generateRandomGraph(2);
strategy = new StrategyChild();
strategy.setInitialGraph(graph);
assertEquals(Strategy.Status.BEING_COMPUTED, strategy.getStrategyStatus());
assertNotNull(strategy.getGraph());
strategy.resetStrategy();
assertEquals(Strategy.Status.NOT_YET_STARTED, strategy.getStrategyStatus());
assertNull(strategy.getGraph());
}
}
| true |
657c93b7d09de3d9f3e1dbf7a09edbd58d232222 | Java | Wangminjun0207/DesignPattern_Java | /SimpleFactory/Fruit.java | GB18030 | 129 | 2.734375 | 3 | [] | no_license | // Fruit.java
/* һӿڣget̳еʱʵ */
interface Fruit{
public void get();
} | true |
8877d58030bcfbc160c905518a7aecd7aef31301 | Java | mhacks/onehack-android | /app/src/main/java/com/arbrr/onehack/ui/events/EditEventFragment.java | UTF-8 | 14,784 | 2.09375 | 2 | [] | no_license | package com.arbrr.onehack.ui.events;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TimePicker;
import android.widget.Toast;
import com.arbrr.onehack.R;
import com.arbrr.onehack.data.model.Event;
import com.arbrr.onehack.data.model.Location;
import com.arbrr.onehack.data.network.NetworkManager;
import com.arbrr.onehack.data.network.OneHackCallback;
import com.arbrr.onehack.ui.MainActivity;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
/**
* A simple {@link Fragment} subclass.
* Use the {@link EditEventFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class EditEventFragment extends Fragment implements AdapterView.OnItemSelectedListener,
DatePickerDialog.OnDateSetListener,
TimePickerDialog.OnTimeSetListener,
View.OnClickListener {
// Event fields
private String name, info;
public Date startTime, endTime;
private int role, hackathon_id, location_id, id;
// Views
private EditText editName, editInfo;
private Button editStartDate, editStartTime, editEndDate, editEndTime;
private Spinner editLocation;
// Locations
private ArrayList<Location> locationList = new ArrayList<>(LocationsManager.getLocations());
private ArrayList<String> locationNamesList;
// other shit
public boolean newEvent = false;
private int datePicker = 0; // 0 for start, 1 for end
private int timePicker = 0; // 0 for start, 1 for end
// Calendars
private Calendar startTimeC = Calendar.getInstance();
private Calendar endTimeC = Calendar.getInstance();
// Pickers
private DatePickerFragment sd, ed;
private TimePickerFragment st, et;
// Interface callback listeners
OnEventUpdatedListener mListener;
public static EditEventFragment newInstance(Event event) {
EditEventFragment f = new EditEventFragment();
Bundle args = new Bundle();
args.putBoolean("new", false);
args.putString("name", event.getName());
args.putString("info", event.getInfo());
args.putLong("startTime", event.getStartTime().getTime());
args.putLong("endTime", event.getEndTime().getTime());
args.putInt("role", event.getRole());
args.putInt("hackathon_id", event.getHackathon_id());
args.putInt("location_id", event.getLocation_id());
args.putInt("id", event.getId());
f.setArguments(args);
return f;
}
public static EditEventFragment newInstance() {
EditEventFragment f = new EditEventFragment();
Bundle args = new Bundle();
args.putBoolean("new", true);
f.setArguments(args);
return f;
}
public EditEventFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
Bundle args = getArguments();
if (!args.getBoolean("new")) {
this.name = args.getString("name");
this.info = args.getString("info");
this.startTime = new Date(args.getLong("startTime"));
this.endTime = new Date(args.getLong("endTime"));
this.role = args.getInt("role");
this.hackathon_id = args.getInt("hackathon_id");
this.location_id = args.getInt("location_id");
this.id = args.getInt("id");
} else this.newEvent = true;
locationNamesList = new ArrayList<>();
for (Location l : locationList) {
locationNamesList.add(l.getName());
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_edit_event, container, false);
// Set title
if (((MainActivity) getActivity()).getSupportActionBar() != null) {
if (newEvent) ((MainActivity) getActivity()).getSupportActionBar().setTitle("New event");
else ((MainActivity) getActivity()).getSupportActionBar().setTitle("Edit event");
}
// Views
editName = (EditText) view.findViewById(R.id.edit_event_name);
editInfo = (EditText) view.findViewById(R.id.edit_event_info);
editStartDate = (Button) view.findViewById(R.id.edit_event_startDate);
editStartTime = (Button) view.findViewById(R.id.edit_event_startTime);
editEndDate = (Button) view.findViewById(R.id.edit_event_endDate);
editEndTime = (Button) view.findViewById(R.id.edit_event_endTime);
// Locations spinner
editLocation = (Spinner) view.findViewById(R.id.edit_event_location);
ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_item, locationNamesList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
editLocation.setAdapter(adapter);
editLocation.setOnItemSelectedListener(this);
// Date/time buttons
Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();
if (!newEvent) {
start.setTime(startTime);
end.setTime(endTime);
}
// Button text
String startDateText = start.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.US) + " " + start.get(
Calendar.DATE) + ", " + start.get(Calendar.YEAR);
String startTimeMinutes = (start.get(Calendar.MINUTE) == 0) ? "00" : Integer.toString(start.get(Calendar.MINUTE));
String startTimeText = start.get(Calendar.HOUR) + ":" + startTimeMinutes;
String endDateText = end.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.US) + " " + end.get(
Calendar.DATE) + ", " + end.get(Calendar.YEAR);
String endTimeMinutes = (end.get(Calendar.MINUTE) == 0) ? "00" : Integer.toString(end.get(
Calendar.MINUTE));
String endTimeText = end.get(Calendar.HOUR) + ":" + endTimeMinutes;
editStartDate.setText(startDateText);
editEndDate.setText(endDateText);
editStartTime.setText(startTimeText);
editEndTime.setText(endTimeText);
// Button on click listener
editStartDate.setOnClickListener(this);
editStartTime.setOnClickListener(this);
editEndDate.setOnClickListener(this);
editEndTime.setOnClickListener(this);
// Edit texts
if (!newEvent) {
editName.setText(this.name);
editInfo.setText(this.info);
}
// Pickers
sd = new DatePickerFragment();
sd.setListener(this);
sd.setData(newEvent, this.startTime);
st = new TimePickerFragment();
st.setListener(this);
st.setData(newEvent, startTime);
ed = new DatePickerFragment();
ed.setListener(this);
ed.setData(newEvent, endTime);
et = new TimePickerFragment();
et.setListener(this);
et.setData(newEvent, endTime);
return view;
}
@Override
public void onCreateOptionsMenu (Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_edit_event, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.save_event:
saveEvent(newEvent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void saveEvent (boolean newEvent) {
NetworkManager mNetworkManager = NetworkManager.getInstance();
// Get info from views, etc.
this.startTime = new Date(startTimeC.getTimeInMillis());
this.endTime = new Date(endTimeC.getTimeInMillis());
if (editName.getText().toString().length() > 0) this.name = editName.getText().toString();
else editName.setError("Require field.");
this.info = editInfo.getText().toString();
// Build event
Event e = new Event();
e.setName(this.name);
e.setInfo(this.info);
e.setStartTime(this.startTime);
e.setEndTime(this.endTime);
e.setRole(this.role);
e.setHackathon_id(this.hackathon_id);
e.setLocation_id(this.location_id);
e.setId(this.id);
if (newEvent) {
mNetworkManager.createEvent(e, new OneHackCallback<Event>() {
@Override
public void success(Event response) {
mListener.OnEventUpdated(response);
}
@Override
public void failure(Throwable error) {
Toast.makeText(getActivity(), error.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
});
} else {
mNetworkManager.updateEvent(e, new OneHackCallback<Event>() {
@Override
public void success(Event response) {
mListener.OnEventUpdated(response);
}
@Override
public void failure(Throwable error) {
Toast.makeText(getActivity(), error.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
this.location_id = locationList.get(position).getId();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
switch (datePicker) {
case 0:
startTimeC.set(Calendar.YEAR, year);
startTimeC.set(Calendar.MONTH, monthOfYear);
startTimeC.set(Calendar.DAY_OF_MONTH, dayOfMonth);
break;
case 1:
endTimeC.set(Calendar.YEAR, year);
endTimeC.set(Calendar.MONTH, monthOfYear);
endTimeC.set(Calendar.DAY_OF_MONTH, dayOfMonth);
break;
}
}
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
switch (timePicker) {
case 0:
startTimeC.set(Calendar.HOUR_OF_DAY, hourOfDay);
startTimeC.set(Calendar.MINUTE, minute);
break;
case 1:
endTimeC.set(Calendar.HOUR_OF_DAY, hourOfDay);
endTimeC.set(Calendar.MINUTE, minute);
break;
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.edit_event_startDate:
datePicker = 0;
sd.show(getActivity().getSupportFragmentManager(), "start date picker");
break;
case R.id.edit_event_startTime:
timePicker = 0;
st.show(getActivity().getSupportFragmentManager(), "start time picker");
break;
case R.id.edit_event_endDate:
datePicker = 1;
ed.show(getActivity().getSupportFragmentManager(), "end date picker");
break;
case R.id.edit_event_endTime:
timePicker = 1;
et.show(getActivity().getSupportFragmentManager(), "end time picker");
break;
}
}
public void setOnEventUpdatedListener (OnEventUpdatedListener listener) {
this.mListener = listener;
}
///////////////////
// PICKER FRAGMENTS
///////////////////
public static class DatePickerFragment extends DialogFragment {
private EditEventFragment listener;
private boolean newEvent;
private Date defaultDate;
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
if (!newEvent) c.setTime(defaultDate);
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), listener, year, month, day);
}
public void setListener (EditEventFragment e) {
this.listener = e;
}
public void setData(boolean newEvent, Date defaultDate) {
this.newEvent = newEvent;
this.defaultDate = defaultDate;
}
}
public static class TimePickerFragment extends DialogFragment {
private EditEventFragment listener;
private boolean newEvent;
private Date defaultDate;
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
if (!newEvent) c.setTime(defaultDate);
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), listener, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
public void setListener (EditEventFragment e) {
this.listener = e;
}
public void setData(boolean newEvent, Date defaultDate) {
this.newEvent = newEvent;
this.defaultDate = defaultDate;
}
}
public interface OnEventUpdatedListener {
public void OnEventUpdated (Event event);
}
}
| true |
774b943394cd9a1a2cb078edcdb58f59e6d55165 | Java | puzzledPublic/firstRepository | /java8/src/java8/Jungol1023.java | WINDOWS-1252 | 1,063 | 3.28125 | 3 | [] | no_license | package java8;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Jungol1023 {
public static void main(String args[]){
/*
Scanner scanner = new Scanner(System.in);
List<String> list = new ArrayList<String>();
int n;
n= scanner.nextInt();
scanner.nextLine();
for(int i = 0 ; i < n;i++){
list.add(scanner.nextLine());
}
String[] str = list.get(0).split(" ");
*/
String[] str = "AH KH QH TH JH".split(" ");
System.out.println(" :"+ isRoyalFlush(str));
}
static boolean isRoyalFlush(String[] str){
String RF= "AKQJT";
if(isFlush(str)){
for(int i = 0 ; i < 5; i++){
if(RF.contains(str[i].subSequence(0, 1))){
RF.replace(str[i].charAt(0)+"", " ");
}
}
System.out.println(RF);
if(RF==" "){
return true;
}
}
return false;
}
static boolean isFlush(String[] str){
char t = str[0].charAt(1);
for(int i =0;i<5;i++){
if(str[i].charAt(1) != t){
return false;
}
}
return true;
}
}
| true |
09b6ab40f96e7107e407192ee6463fd4d8c38a2e | Java | craftsmanship-at-capgemini/directdronedelivery | /directdronedelivery-model/src/test/java/directdronedelivery/warehouse/process/BoxSpecificationTest.java | UTF-8 | 2,898 | 2.25 | 2 | [] | no_license | package directdronedelivery.warehouse.process;
import static directdronedelivery.cargo.OrderAndCargoInformationBuilder.aCargo;
import static directdronedelivery.drone.DroneBuilder.aDrone;
import static org.fest.assertions.api.Assertions.assertThat;
import org.junit.Before;
import org.junit.Test;
import testing.Testing;
import directdronedelivery.cargo.CargoAggregate;
import directdronedelivery.drone.DroneAggregate;
import directdronedelivery.drone.DroneType;
import directdronedelivery.warehouse.BoxType;
import directdronedelivery.warehouse.businessrules.BoxChooseSpecification;
public class BoxSpecificationTest {
@Before
public void setUp() throws Exception {
Testing.inject(this);
}
@Test
public void shouldPreferSmallFragileBox() {
CargoAggregate fragileCargo = aCargo().likeSmallGift().but().withFragileCommodity(true).build();
DroneAggregate smallDrone = aDrone().likeDocked4RotorsDrone().but().withDroneType(DroneType.SMALL_FOUR_ROTORS).build();
BoxChooseSpecification boxSpecification = new BoxChooseSpecification(fragileCargo, smallDrone);
BoxType preferredBoxTyp = boxSpecification.preferredBoxTyp();
assertThat(preferredBoxTyp).isEqualTo(BoxType.SMALL_FRAGILE);
}
@Test
public void shouldPreferBigFragileBox() {
CargoAggregate fragileCargo = aCargo().likeSmallGift().but().withFragileCommodity(true).build();
DroneAggregate bigDrone = aDrone().likeDocked4RotorsDrone().but().withDroneType(DroneType.BIG_SIX_ROTORS).build();
BoxChooseSpecification boxSpecification = new BoxChooseSpecification(fragileCargo, bigDrone);
BoxType preferredBoxTyp = boxSpecification.preferredBoxTyp();
assertThat(preferredBoxTyp).isEqualTo(BoxType.BIG_FRAGILE);
}
@Test
public void shouldPreferSmallBox() {
CargoAggregate nonfragileCargo = aCargo().likeSmallGift().but().withFragileCommodity(false).build();
DroneAggregate smallDrone = aDrone().likeDocked4RotorsDrone().but().withDroneType(DroneType.SMALL_FOUR_ROTORS).build();
BoxChooseSpecification boxChooseSpecSmall = new BoxChooseSpecification(nonfragileCargo, smallDrone);
assertThat(boxChooseSpecSmall.preferredBoxTyp()).isEqualTo(BoxType.SMALL);
}
@Test
public void shouldPreferBigBox() {
CargoAggregate nonfragileCargo = aCargo().likeSmallGift().but().withFragileCommodity(false).build();
DroneAggregate bigDrone = aDrone().likeDocked4RotorsDrone().but().withDroneType(DroneType.BIG_SIX_ROTORS).build();
BoxChooseSpecification boxSpecification = new BoxChooseSpecification(nonfragileCargo, bigDrone);
BoxType preferredBoxTyp = boxSpecification.preferredBoxTyp();
assertThat(preferredBoxTyp).isEqualTo(BoxType.BIG);
}
}
| true |
f977c378aa231b3a526cddaba03fb07c5779fb91 | Java | r351574nc3/sample-xpack-oauth-plugin | /src/main/java/com/github/r351574nc3/userinfo/UserInfoResponse.java | UTF-8 | 1,488 | 2.140625 | 2 | [] | no_license | package com.github.r351574nc3.realm.userinfo;
import java.util.List;
import com.google.api.client.json.GenericJson;
import com.google.api.client.util.Key;
import com.google.api.client.util.Preconditions;
/**
* <p>
* Implementation is not thread-safe.
* </p>
*
*/
public class UserInfoResponse extends GenericJson {
@Key("email")
protected String email;
@Key("groups")
protected String groups;
@Key("name")
protected String name;
@Key("sub")
protected String sub;
@Key("tenant")
protected Integer tenant;
@Key("username")
protected String username;
public void setEmail(final String email) {
this.email = email;
}
public String getEmail() {
return this.email;
}
public void setGroups(final String groups) {
this.groups = groups;
}
public String getGroups() {
return this.groups;
}
public void setName(final String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setSub(final String sub) {
this.sub = sub;
}
public String getSub() {
return this.sub;
}
public void setUsername(final String username) {
this.username = username;
}
public String getUsername() {
return this.username;
}
public void setTenant(final Integer tenant) {
this.tenant = tenant;
}
public Integer setTenant() {
return this.tenant;
}
@Override
public UserInfoResponse clone() {
return (UserInfoResponse) super.clone();
}
} | true |
541b2404a795d06841ec6c11087ac53eba4a01c6 | Java | huiyusun/ice_test | /src/edu/nyu/jet/ice/models/IcePath.java | UTF-8 | 2,464 | 2.609375 | 3 | [
"BSD-3-Clause",
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | package edu.nyu.jet.ice.models;
import gnu.trove.map.hash.TObjectDoubleHashMap;
/**
* A path in relation bootstrapping
*
* @author yhe
* @version 1.0
*/
public class IcePath implements Comparable<IcePath> {
public enum IcePathChoice {
NO, YES, UNDECIDED
}
private String path;
private String repr;
private String example;
private double score;
public TObjectDoubleHashMap subScores;
private IcePathChoice choice;
public IcePath(String path, String repr, String example, double score, IcePathChoice choice) {
this.path = path;
this.repr = repr;
this.example = example;
this.score = score;
this.choice = choice;
}
public IcePath(String path, String repr, String example, double score) {
this.path = path;
this.repr = repr;
this.example = example;
this.score = score;
this.choice = IcePathChoice.UNDECIDED;
}
public IcePath(String path, String repr, String example, double score, TObjectDoubleHashMap subScores) {
this.path = path;
this.repr = repr;
this.example = example;
this.score = score;
this.choice = IcePathChoice.UNDECIDED;
this.subScores = subScores;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getRepr() {
return repr;
}
public void setRepr(String repr) {
this.repr = repr;
}
public String getExample() {
return example;
}
public void setExample(String example) {
this.example = example;
}
public double getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public IcePathChoice getChoice() {
return choice;
}
public void setChoice(IcePathChoice choice) {
this.choice = choice;
}
public int compareTo(IcePath icePath) {
if (this.score < icePath.score) return 1;
if (this.score > icePath.score) return -1;
return 0;
}
@Override
public String toString() {
if (choice == IcePathChoice.UNDECIDED) {
return repr;
}
else {
if (choice == IcePathChoice.YES) {
return repr + " / YES";
}
else {
return repr + " / NO";
}
}
}
}
| true |
a937f2b2eaf756029d533c443dc702232c53af0f | Java | OFRF/BladeRush | /gameserver/src/main/java/ru/l2/gameserver/stats/conditions/ConditionPlayerHasBuff.java | UTF-8 | 843 | 2.453125 | 2 | [] | no_license | package ru.l2.gameserver.stats.conditions;
import ru.l2.gameserver.model.Creature;
import ru.l2.gameserver.model.Effect;
import ru.l2.gameserver.skills.EffectType;
import ru.l2.gameserver.stats.Env;
public class ConditionPlayerHasBuff extends Condition {
private final EffectType _effectType;
private final int _level;
public ConditionPlayerHasBuff(final EffectType effectType, final int level) {
_effectType = effectType;
_level = level;
}
@Override
protected boolean testImpl(final Env env) {
final Creature character = env.character;
if (character == null) {
return false;
}
final Effect effect = character.getEffectList().getEffectByType(_effectType);
return effect != null && (_level == -1 || effect.getSkill().getLevel() >= _level);
}
}
| true |
293fb50ee6250e1c764e24164474f21f1af124c2 | Java | Naadezhda/traveller-online | /src/main/java/finalproject/javaee/model/pojo/Comment.java | UTF-8 | 801 | 2.5 | 2 | [] | no_license | package finalproject.javaee.model.pojo;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.Set;
@NoArgsConstructor
@Getter
@Setter
@Entity
@Table(name = "comments")
public class Comment {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private long id;
private long userId;
private long postId;
private String text;
private LocalDateTime date;
@ManyToMany(fetch = FetchType.EAGER,
mappedBy = "likedComments")
private Set<User> usersWhoLiked;
public Comment(long userId, long postId, String text){
this.userId = userId;
this.postId = postId;
this.text = text;
this.date = LocalDateTime.now();
}
}
| true |
146dd2862d8b92300a80794b86c0fcf7ca62e4c7 | Java | MeitalRe/CouponSystem2 | /CouponSystem2/src/main/java/com/example/CouponSystem2/services/CompanyService.java | UTF-8 | 3,417 | 2.421875 | 2 | [] | no_license | package com.example.CouponSystem2.services;
import java.util.List;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import com.example.CouponSystem2.beans.Company;
import com.example.CouponSystem2.beans.Coupon;
import com.example.CouponSystem2.exceptions.IllegalLoginException;
import com.example.CouponSystem2.exceptions.NotValidException;
import lombok.RequiredArgsConstructor;
@Service
@Scope("prototype")
@RequiredArgsConstructor
public class CompanyService extends ClientService {
private final int companyId;
@Override
public boolean login(String email, String password) throws IllegalLoginException {
Company company = companyRepository.getOne(companyId);
if (company.getEmail().equals(email) || company.getPassword().equals(password)) {
System.out.println("Welcome");
return true;
}
throw new IllegalLoginException("Incorect email or password");
}
public void addCoupon(Coupon coupon) {
List<Coupon> companyCoupons = companyRepository.getOne(companyId).getCoupons();
for (int i = 0; i < companyCoupons.size(); i++) {
if (companyCoupons.get(i).getTitle().equals(coupon.getTitle())
&& companyCoupons.get(i).getCompany_id() == companyId) {
System.out.println("Can not add coupon");
} else {
coupon.setCompany_id(companyId);
companyCoupons.add(coupon);
companyRepository.getOne(companyId).setCoupons(companyCoupons);
companyRepository.saveAndFlush(companyRepository.getOne(companyId));
System.out.println("Coupon successfully added");
break;
}
}
if (companyCoupons.size() == 0) {
coupon.setCompany_id(companyId);
companyCoupons.add(coupon);
companyRepository.getOne(companyId).setCoupons(companyCoupons);
companyRepository.saveAndFlush(companyRepository.getOne(companyId));
System.out.println("Coupon successfully added");
}
}
public void updateCompanyCoupon(Coupon coupon) throws NotValidException {
List<Coupon> companyCoupons = companyRepository.getOne(companyId).getCoupons();
for (Coupon coupon2 : companyCoupons) {
if (coupon2.getId() != coupon.getId() || coupon2.getCompany_id() != coupon.getCompany_id()) {
throw new NotValidException("Can not update coupon");
}
}
couponRepository.saveAndFlush(coupon);
System.out.println("Coupon successfully updated");
}
public void deleteCompanyCoupon(Coupon coupon) {
couponRepository.delete(coupon);
}
public Coupon getCompanyCoupon(int id) {
Coupon coupon = null;
List<Coupon> companyCoupons = companyRepository.getOne(companyId).getCoupons();
for (Coupon coupon2 : companyCoupons) {
if (coupon2.getId() == id) {
coupon = coupon2;
break;
}
}
return coupon;
}
public List<Coupon> getCompanyCoupons() {
return couponRepository.findByCompanyId(companyId);
}
public List<Coupon> getCompanyOneCategoryCoupons(com.example.CouponSystem2.beans.Category category) {
return couponRepository.findByCompanyIdAndCategory(companyId,category);
}
public List<Coupon> getCompanyCouponsByMaxPrice(double maxPrice) {
return couponRepository.findByCompanyIdAndPriceLessThan(companyId,maxPrice);
}
public Company getCompanyDetails() {
return companyRepository.getOne(companyId);
}
} | true |
9c9531c4d112ecd7c86ef8a94cf56652fcdcf7cb | Java | elebescond/jweave | /src/main/java/info/elebescond/weave/UserWeave.java | UTF-8 | 3,417 | 2.515625 | 3 | [] | no_license | package info.elebescond.weave;
import info.elebescond.weave.exception.WeaveException;
public interface UserWeave {
public static String PREFIX = "user";
public static String VERSION = "1";
public static String USER_API_URL = "/" + PREFIX + "/" + VERSION;
/**
* Change the email address of the given user.
*
* @param userId
* @param password
* @param newEmail
* @return
* @throws WeaveException
*/
public boolean changeEmail(String userId, String password, String newEmail)
throws WeaveException;
/**
* Change the password of the given user.
*
* @param userId
* @param password
* @param newPassword
* @return
* @throws WeaveException
*/
public boolean changePassword(String userId, String password,
String newPassword) throws WeaveException;
/**
* Returns a boolean for whether the given userID is available at the given
* server.
*
* @param userId
* @return
* @throws WeaveException
*/
public boolean checkUserIdAvailable(String userId) throws WeaveException;
/**
* Create a new user at the given server, with the given userID, password,
* and email. If a secret is provided those will be provided as well. Note
* that the exact new-user-authorization logic is determined by the server.
*
* @param userId
* @param password
* @param email
* @return
* @throws WeaveException
*/
public boolean createUser(String userId, String password, String email)
throws WeaveException;
/**
* Create a new user at the given server, with the given userID, password,
* and email. If a secret is provided, or a captchaChallenge/captchaResponse
* pair, those will be provided as well. Note that the exact
* new-user-authorization logic is determined by the server.
*
* @param userId
* @param password
* @param email
* @param captchaChallenge
* @param captchaResponse
* @return
* @throws WeaveException
*/
public boolean createUser(String userId, String password, String email,
String captchaChallenge, String captchaResponse)
throws WeaveException;
/**
* Delete the given userId
*
* @param userId
* @param password
* @return
* @throws WeaveException
*/
public boolean deleteUser(String userId, String password)
throws WeaveException;
public String getSecret();
public String getServerUrl();
/**
* Returns the URL representing the storage node for the given user. Note
* that in the 1.0 server implementation hosted by Mozilla, the password is
* not actually required for this call.
*
* @param userId
* @param password
* @return
*/
public String getUserStorageNode(String userId, String password)
throws WeaveException;
/**
* Requests a password reset email be mailed to the email address on file.
*
* @param userId
* @return
* @throws WeaveException
*/
public boolean resetPassword(String userId) throws WeaveException;
/**
* Requests a password reset email be mailed to the email address on file.
* If a secret is provided, or a captchaChallenge/captchaResponse pair,
* those will be provided as well.
*
* @param userId
* @param captchaChallenge
* @param captchaResponse
* @return
* @throws WeaveException
*/
public boolean resetPassword(String userId, String captchaChallenge,
String captchaResponse) throws WeaveException;
public void setSecret(String secret);
public void setServerUrl(String serverUrl);
} | true |
c0060d96dd77bb08e75470c2505ee1ab933d4420 | Java | oscargaom/java-sb-form | /src/main/java/com/bolsadeideas/springboot/app/springbootform/validation/IdentificadorRegexValidator.java | UTF-8 | 451 | 2.203125 | 2 | [] | no_license | package com.bolsadeideas.springboot.app.springbootform.validation;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class IdentificadorRegexValidator implements ConstraintValidator<IdentificadorRegex, String> {
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
return value.matches("[\\d]{2}[.][\\d]{3}[.][\\d]{3}[-][A-Z]{1}");
}
}
| true |
bad43a552338cdfdf3da966d81072fa52032bb02 | Java | liuwen766/gulimall | /gulimall-coupon/src/main/java/com/xunqi/gulimall/coupon/service/impl/SeckillSessionServiceImpl.java | UTF-8 | 4,313 | 2.15625 | 2 | [
"Apache-2.0"
] | permissive | package com.xunqi.gulimall.coupon.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xunqi.common.utils.PageUtils;
import com.xunqi.common.utils.Query;
import com.xunqi.gulimall.coupon.dao.SeckillSessionDao;
import com.xunqi.gulimall.coupon.entity.SeckillSessionEntity;
import com.xunqi.gulimall.coupon.entity.SeckillSkuRelationEntity;
import com.xunqi.gulimall.coupon.service.SeckillSessionService;
import com.xunqi.gulimall.coupon.service.SeckillSkuRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Service("seckillSessionService")
public class SeckillSessionServiceImpl extends ServiceImpl<SeckillSessionDao, SeckillSessionEntity> implements SeckillSessionService {
@Autowired
private SeckillSkuRelationService seckillSkuRelationService;
@Override
public PageUtils queryPage(Map<String, Object> params) {
QueryWrapper<SeckillSessionEntity> queryWrapper = new QueryWrapper<>();
String key = (String) params.get("key");
if (!StringUtils.isEmpty(key)) {
queryWrapper.eq("id",key);
}
IPage<SeckillSessionEntity> page = this.page(
new Query<SeckillSessionEntity>().getPage(params),
queryWrapper
);
return new PageUtils(page);
}
@Override
public List<SeckillSessionEntity> getLates3DaySession() {
//计算最近三天
//查出这三天参与秒杀活动的商品
List<SeckillSessionEntity> list = this.baseMapper.selectList(new QueryWrapper<SeckillSessionEntity>()
.between("start_time", startTime(), endTime()));
if (list != null && list.size() > 0) {
List<SeckillSessionEntity> collect = list.stream().map(session -> {
Long id = session.getId();
//查出sms_seckill_sku_relation表中关联的skuId
List<SeckillSkuRelationEntity> relationSkus = seckillSkuRelationService.list(new QueryWrapper<SeckillSkuRelationEntity>()
.eq("promotion_session_id", id));
session.setRelationSkus(relationSkus);
return session;
}).collect(Collectors.toList());
return collect;
}
return null;
}
/**
* 当前时间
* @return
*/
private String startTime() {
LocalDate now = LocalDate.now();
LocalTime min = LocalTime.MIN;
LocalDateTime start = LocalDateTime.of(now, min);
//格式化时间
String startFormat = start.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
return startFormat;
}
/**
* 结束时间
* @return
*/
private String endTime() {
LocalDate now = LocalDate.now();
LocalDate plus = now.plusDays(2);
LocalTime max = LocalTime.MAX;
LocalDateTime end = LocalDateTime.of(plus, max);
//格式化时间
String endFormat = end.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
return endFormat;
}
public static void main(String[] args) {
// LocalDate now = LocalDate.now();
// LocalDate plus = now.plusDays(2);
// LocalDateTime now1 = LocalDateTime.now();
// LocalTime now2 = LocalTime.now();
//
// LocalTime max = LocalTime.MAX;
// LocalTime min = LocalTime.MIN;
//
// LocalDateTime start = LocalDateTime.of(now, min);
// LocalDateTime end = LocalDateTime.of(plus, max);
//
// System.out.println(now);
// System.out.println(now1);
// System.out.println(now2);
// System.out.println(plus);
//
// System.out.println(start);
// System.out.println(end);
// System.out.println(startTime());
// System.out.println(endTime());
}
} | true |
94668918b6e234fc51f8cc0a6595503dd2a50b56 | Java | RogerPf/aaBridge | /src/com/rogerpf/aabridge/model/Suit.java | UTF-8 | 3,945 | 2.15625 | 2 | [] | no_license | /*******************************************************************************
* Copyright (c) 2013 Roger Pfister.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v2.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* Roger Pfister - initial API and implementation
******************************************************************************/
package com.rogerpf.aabridge.model;
import java.awt.Color;
public enum Suit {
Clubs(0), Diamonds(1), Hearts(2), Spades(3), NoTrumps(4), Invalid(0); // Invalid is better than null and 0 is the best way to avoid a crash
public static final int papClubs = 0x01;
public static final int papDiamonds = 0x02;
public static final int papHearts = 0x04;
public static final int papSpades = 0x08;
public static final int papAllSuits = papClubs | papDiamonds | papHearts | papSpades;
private final static int to_pap[] = { papClubs, papDiamonds, papHearts, papSpades };
public int get_pap() {
return to_pap[v];
}
private Suit(int v) {
this.v = v;
}
public final int v;
/* External interfacing to from the dds
* */
public int vX() {
return (v == 4) ? 4 : 3 - v;
}
public Suit suitBelow() {
return suitFromInt((v == 0) ? 3 : v - 1);
}
public static Suit suitFromInt(int value) {
return instAy[value & 0x0f];
}
public char toChar() {
return suit_to_cdhsnCh[v];
}
public char toCharLower() {
return suit_to_cdhsnLowCh[v];
}
public String toLinStr() {
return suit_to_cdhsnSt[v];
}
public String toStr() {
return suit_to_cdhsnSt[v];
}
public String toStrLower() {
return suit_to_cdhsnLowSt[v];
}
public String toStrNt() {
return suit_to_cdhsntSt[v];
}
public String toStrDual() {
return suit_to_cdhsNDual[v];
}
//@formatter:off
// suit visibility control constants
public static final int SVC_noneSet = 0x00;
public static final int SVC_cards = 0x01;
public static final int SVC_count = 0x02;
public static final int SVC_dot = 0x04;
public static final int SVC_ansHere = 0x10;
public static final int SVC_qaCount = 0x20;
public static final int SVC_qaDot = 0x40;
public final static Suit[] cdhs = { Clubs, Diamonds, Hearts, Spades };
public final static Suit[] shdc = { Spades, Hearts, Diamonds, Clubs };
private final static char[] suit_to_cdhsnCh = { 'C', 'D', 'H', 'S', 'N' };
private final static char[] suit_to_cdhsnLowCh = { 'c', 'd', 'h', 's', 'n' };
private final static String[] suit_to_cdhsnLowSt = { "c", "d", "h", "s", "n" };
private final static String[] suit_to_cdhsnSt = { "C", "D", "H", "S", "N" };
private final static String[] suit_to_cdhsntSt = { "C", "D", "H", "S", "NT" };
private final static String[] suit_to_cdhsNDual = { "c", "d", "h", "s", "N" };
public static Suit fiveDenoms[] = { Clubs, Diamonds, Hearts, Spades, NoTrumps};
private static Suit instAy[] = { Clubs, Diamonds, Hearts, Spades, NoTrumps, Invalid };
//@formatter:on
public Color color(Cc.Ce power) {
return Cc.SuitColor(this, power);
}
public Color colorCd(Cc.Ce power) {
return Cc.SuitColorCd(this, power);
}
public static Suit charToSuit(char c) {
switch (c) {
case 'S':
case 's':
return Spades;
case 'H':
case 'h':
return Hearts;
case 'D':
case 'd':
return Diamonds;
case 'C':
case 'c':
return Clubs;
}
return Suit.Invalid;
}
public static Suit charToSuitOrNt(char c) {
switch (c) {
case 'S':
case 's':
return Spades;
case 'H':
case 'h':
return Hearts;
case 'D':
case 'd':
return Diamonds;
case 'C':
case 'c':
return Clubs;
case 'N':
case 'n':
return NoTrumps;
}
return Suit.Invalid;
}
public static Suit strToSuit(String s) {
if (s.length() > 0) {
return charToSuit(s.charAt(0));
}
return Suit.Invalid;
}
}
| true |
83ffc03a0cc8d421f2f30264b7dd0a4c1d42d542 | Java | joellarsson91/Aldacode | /MinMax/src/game/MoveInfo.java | UTF-8 | 156 | 2.390625 | 2 | [] | no_license | package game;
public class MoveInfo {
public Square square;
public int value;
public MoveInfo(Square s, int v) {
square = s;
value = v;
}
}
| true |
5fc6f60843f510ccd94d0abd9d334f8d676b1814 | Java | krunalmodi711/testrepository | /src/test/selectdropdown.java | UTF-8 | 1,389 | 2.234375 | 2 | [] | no_license | package test;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.Test;
public class selectdropdown {
@Test
public void getValues(){
System.setProperty("webdriver.gecko.driver", "G:\\Neon\\gecko driver\\geckodriver.exe");
WebDriver objDriver = new FirefoxDriver();
objDriver.manage().window().maximize();
objDriver.manage().deleteAllCookies();
objDriver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
objDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
objDriver.get("file:///C:/Users/krunal/Desktop/Selenium%20webpages/HTMLTag.html");
Select objSelect = new Select(objDriver.findElement(By.id("selCity")));
/*List<WebElement> objOptions = objSelect.getOptions();
for (WebElement obj :objOptions )
{
System.out.println(obj.getText());
}
objSelect.selectByVisibleText("Ahmedabad");
System.out.println("Selected option is " + objSelect.getFirstSelectedOption().getText()); */
Actions objAction = new Actions(objDriver);
objAction.moveToElement(objDriver.findElement(By.id("selCity"))).contextClick().perform();
}
}
| true |
438f7f96a52198880b99fe3fa1b3daf86f9293e0 | Java | Ploply1527/P4_Anthony-Esebra-Brian_Group-2 | /Q4 Project/src/GameObject.java | UTF-8 | 3,791 | 2.953125 | 3 | [] | no_license | import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.net.URL;
import java.awt.geom.AffineTransform;
///This should be a class that should be inherited from
public abstract class GameObject {
//Region:Position Variables
protected int gridX;//This is where on the x-axis on the grid the ghost is on grid
protected int gridY;//This is where on the y-axis on the grid the ghost is on grid
protected int posX;//This is the x pixel position the ghost is on the screen
protected int posY;//This is the y pixel position the ghost is on the screen
protected int startX;//This is xGrid of where the gameObject will start from
protected int startY;//This is yGrid of where the gameObejct will start from
protected boolean collide = false;
protected AffineTransform tx = AffineTransform.getTranslateInstance(posX, posY);
//PacMan board is 28 x 31
//Scale is x22 larger.
protected static int[][] grid;
protected static Tile[][] board = new Tile[29][28];
//endRegion
//Region: Animation Variables
protected Image baseImage;//This is the default image that the game object will use
protected int timerCount = 0; //This is the timer for the animation
protected final int changeFrame = 20; //This is how many frames later animation will change
//endRegion
//Region: GameState Variables
protected static boolean gameOver = false;
//endRegion
public GameObject(int xGrid, int yGrid, String imgName)
{
gridX = xGrid;
gridY = yGrid;
startX = xGrid;
startY = yGrid;
baseImage = getImage(imgName); //load the base image
posX = gridX * 22;
posY = gridY * 22;
init(posX, posY);//Initialize the position
}
//Region: Abstract voids
///This is going to be the main logic
public abstract void paint(Graphics g);
//This is the animation for each gameObject
//Protected means that only classes that inherit from this can access it
protected abstract void animation();
//endregion
//Game Resetting
public static void freeze()
{
gameOver = true;
}
//This resets the gameObject
public void reset()
{
gameOver = false;
gridX = startX;
gridY = startY;
posX = startX * 22;
posY = startY * 22 - 9;
}
//Region:Movement
protected void CollisionCheck(boolean vertical, int dir, int div)
{
int tempPos;
if(vertical)
{
tempPos = (posY + 12 * dir)/22;
collide = (grid[tempPos][gridX] % div == 0)
|| (grid[tempPos][((posX + 2)/ 22)] % div == 0)
|| (grid[tempPos][((posX - 2)/ 22)] % div == 0);
}
else
{
tempPos = (posX + (15 + (6*dir))* dir)/22;
//Took the easy way out of a problem. Never punished lol
try
{
collide = (grid[gridY][tempPos] % div == 0)
|| (grid[((posY + 2)/ 22)][tempPos] % div == 0)
|| (grid[((posY - 2)/ 22)][tempPos] % div == 0);
}
catch(ArrayIndexOutOfBoundsException e)
{
tempPos -= 1;
}
}
}
//endRegion
//Region: Getters and Setters
public int getX() {return posX;}
public int getY() {return posY;}
public static void setGrid(int[][] g, boolean first)
{
grid = g;
for(int i = 0; i < g.length; i++)
{
for(int o = 0; o < g[i].length; o++)
{
if(first) {board[i][o] = new Tile(g[i][o],o,i, 0);}
else { board[i][o].setTile(g[i][o]);}
}
}
}
//End Region
//I ripped this straight out of the duck hunt code
protected Image getImage(String path) {
Image tempImage = null;
try {
URL imageURL = GameObject.class.getResource(path);
tempImage = Toolkit.getDefaultToolkit().getImage(imageURL);
} catch (Exception e) {
e.printStackTrace();
}
return tempImage;
}
//This is for initialization
private void init(double a, double b) {
tx.setToTranslation(a-14, b-17);
tx.scale(1, 1);
}
}
| true |
b266905d0cf8e790098758c99b0c931486a36dc5 | Java | EdurtIO/gcm | /storage/storage-mysql/src/main/java/io/edurt/gcm/mysql/hikari/configuration/HikariConfiguration.java | UTF-8 | 1,058 | 1.867188 | 2 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | package io.edurt.gcm.mysql.hikari.configuration;
public class HikariConfiguration
{
public static final String DRIVER_CLASS_NAME = "jdbc.mysql.driverClassName";
public static final String URL = "jdbc.mysql.url";
public static final String USERNAME = "jdbc.mysql.username";
public static final String PASSWORD = "jdbc.mysql.password";
public static final String MINIMUM_IDLE = "jdbc.mysql.minimumIdle";
public static final String MAXIMUM_POOL_SIZE = "jdbc.mysql.maximumPoolSize";
public static final String CONNECTION_TEST_QUERY = "jdbc.mysql.connectionTestQuery";
public static final String CACHE_PREPSTMTS = "jdbc.mysql.cachePrepStmts";
public static final String PREP_STMT_CACHESIZE = "jdbc.mysql.prepStmtCacheSize";
public static final String PREP_STMT_CACHESQLLIMIT = "jdbc.mysql.prepStmtCacheSqlLimit";
public static final String USE_SERVER_PREPSTMTS = "jdbc.mysql.useServerPrepStmts";
public static final String SCAN_MAPPER_PACKAGE = "jdbc.mysql.scan.mapper.package";
private HikariConfiguration()
{}
}
| true |
90101a9f65bd3d967f27a80821b198c54e938344 | Java | cjie888/cryptocurrency-quant | /quant-base/src/main/java/com/cjie/cryptocurrency/quant/api/okex/v5/enums/I18nEnum.java | UTF-8 | 336 | 2.171875 | 2 | [] | no_license | package com.cjie.cryptocurrency.quant.api.okex.v5.enums;
public enum I18nEnum {
ENGLISH("en_US"),
SIMPLIFIED_CHINESE("zh_CN"),
//zh_TW || zh_HK
TRADITIONAL_CHINESE("zh_HK"),;
private String i18n;
I18nEnum(String i18n) {
this.i18n = i18n;
}
public String i18n() {
return i18n;
}
}
| true |
695be3b4e66fbe2bfd7ed98b8ed3490ec3fdc1b5 | Java | Thiziri2/CourseVoitures | /src/strategy/Strategy.java | UTF-8 | 168 | 1.859375 | 2 | [] | no_license | package strategy;
import java.io.Serializable;
import voiture.Commande;
public interface Strategy extends Serializable {
public Commande getCommande();
}
| true |
81772d04aca71b67242f5a9a1b40376927eccb64 | Java | jeffreylutz/katas | /kata-2-karate-chop/src/test/java/com/designhaiku/karate/BinarySearchTest.java | UTF-8 | 3,172 | 3.015625 | 3 | [] | no_license | package com.designhaiku.karate;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import static junit.framework.Assert.assertEquals;
public class BinarySearchTest {
private int[] values;
private BinarySearch binarySearch;
@Before
public void someBeforeMethod() {
values = null;
binarySearch = new BinarySearch();
}
@Test
public void successfullySearchEmptyArrayAndReturnNotFound() {
//precondition
int searchTarget = 4;
int expectedIndex = binarySearch.notFound;
//perform test
int actualIndex = binarySearch.chop(searchTarget, values);
//post-condition/assertion
assertEquals(expectedIndex, actualIndex);
}
@Test
public void successfullySearchSingleElementArrayAndReturnFirstIndex() {
//precondition
int searchTarget = 1;
values = new int[]{1};
int expectedIndex = 0;
//perform test
int actualIndex = binarySearch.chop(searchTarget, values);
//post-condition/assertion
assertEquals(expectedIndex, actualIndex);
}
@Test
public void successfullySearchTwoElementArrayAndReturnSecondIndex() {
//precondition
int searchTarget = 1;
values = new int[]{3,1};
int expectedIndex = 1;
//perform test
int actualIndex = binarySearch.chop(searchTarget, values);
//post-condition/assertion
assertEquals(expectedIndex, actualIndex);
}
@Test
public void successfullySearchTwoElementArrayWithValueNotInArray() {
//precondition
int searchTarget = 1;
values = new int[]{0,2};
int expectedIndex = binarySearch.notFound;
//perform test
int actualIndex = binarySearch.chop(searchTarget, values);
//post-condition/assertion
assertEquals(expectedIndex, actualIndex);
}
@Test
public void successfullySearchNullArrayWithReturnNotFound() {
//precondition
int searchTarget = 1;
values = null;
int expectedIndex = binarySearch.notFound;
//perform test
int actualIndex = binarySearch.chop(searchTarget, values);
//post-condition/assertion
assertEquals(expectedIndex, actualIndex);
}
@Test
public void successfullySearchMultipleValueArrayWhenSearchingNegativeNumber() {
//precondition
int searchTarget = 7;
values = new int[]{-12,-5,0,4,7};
int expectedIndex = 4;
//perform test
int actualIndex = binarySearch.chop(searchTarget, values);
//post-condition/assertion
assertEquals(expectedIndex, actualIndex);
}
@Test
public void successfullySearchMultipleValueArrayWithSameValuesAndReturnFirstIndex() {
//precondition
int searchTarget = 7;
values = new int[]{7,7,7,7,7,7};
int expectedIndex = 0;
//perform test
int actualIndex = binarySearch.chop(searchTarget, values);
//post-condition/assertion
assertEquals(expectedIndex, actualIndex);
}
}
| true |
9318aaec3ef8f4bec77b393b1a837cc74c48a2ca | Java | RahulXTmCoding/ORM-Framework | /src/com/thinking/machines/utils/DeleteValidator.java | UTF-8 | 844 | 2.53125 | 3 | [] | no_license | package com.thinking.machines.utils;
import com.thinking.machines.sqlDomain.*;
import java.lang.reflect.*;
import com.thinking.machines.exceptions.*;
import java.util.*;
import java.sql.*;
public class DeleteValidator
{
public List<String> psList=new LinkedList<>();
public List<String> refTables=new LinkedList<>();
public List<String> pks;
public Connection c;
public void validate(Table t,Map<String,Field> f,Object o)throws ORMException,Exception
{
for(int i=0;i<psList.size();i++)
{
String ps=psList.get(i);
PreparedStatement pss=c.prepareStatement(ps);
for(int j=0;j<pks.size();j++)
{
pss.setObject(j+1,f.get(pks.get(j)).get(o));
}
ResultSet rs=pss.executeQuery();
if(rs.next())
{
throw new ORMException("Table :"+t.getTableName()+", Referenced By table "+ refTables.get(i)+ " ,so following record cannot be deleted");
}
}
}
} | true |
8e027bb73a2ce23bad6f6043a1864b361006da83 | Java | lapots/editor-fx | /src/main/java/com/lapots/breed/editor/fx/controls/canvas/layer/EmptyLayer.java | UTF-8 | 663 | 2.484375 | 2 | [] | no_license | package com.lapots.breed.editor.fx.controls.canvas.layer;
import com.lapots.breed.editor.fx.controls.canvas.AbstractCanvasWrapper;
import com.lapots.breed.editor.fx.controls.canvas.LayerUtils;
import javafx.scene.canvas.Canvas;
import javafx.scene.layout.Pane;
import static com.lapots.breed.editor.fx.controls.UiConstants.DEFAULT_LAYER_COLOR;
public class EmptyLayer extends AbstractCanvasWrapper {
public EmptyLayer(Pane pane) {
super(pane);
}
@Override
protected void init(Pane pane) {
Canvas layer = LayerUtils.createLayer(pane.getPrefWidth(), pane.getPrefHeight(), DEFAULT_LAYER_COLOR);
setCanvas(layer);
}
}
| true |
d5e6600d7f9dd25efd1e3a4bc1e28f7acb478614 | Java | lxwguoba/zeroneStore | /shopingtime/src/main/java/com/zerone/store/shopingtimetest/DB/impl/UserInfoImpl.java | UTF-8 | 4,790 | 2.4375 | 2 | [] | no_license | package com.zerone.store.shopingtimetest.DB.impl;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;
import com.zerone.store.shopingtimetest.Bean.UserInfo;
import com.zerone.store.shopingtimetest.DB.abs.AbstractDao;
import java.util.ArrayList;
import java.util.List;
/**
* Created by on 2018/3/31 0031 16 46.
* Author LiuXingWen
* 保存用户的信息的实现类
*/
public class UserInfoImpl extends AbstractDao {
public UserInfoImpl(Context context) {
super(context);
}
/**
* @param userInfo 用户信息
* @throws Exception
*/
public void saveUserInfo(UserInfo userInfo) throws Exception {
try {
db = baseDao.getWritableDatabase();
String sql = "insert into customer (u_id, account_id,account,u_orgid,u_uuid,organization_name,realname,fansnamage_id) values (?,?,?,?,?,?,?,?)";
String[] param = new String[]{"10", userInfo.getAccount_id(), userInfo.getAccount(), userInfo.getOrganization_id(), userInfo.getUuid(), userInfo.getOrganization_name(), userInfo.getRealName(), userInfo.getFansnamage_id()};
db.execSQL(sql, param);
Log.i("URL", "保存用户信息成功");
} catch (Exception e) {
throw new Exception("插入数据失败", e);
} finally {
db.close();
}
}
/**
* @return
* @throws Exception
*/
public UserInfo getUserInfo(String u_id) throws Exception {
Cursor cur = null;
try {
db = baseDao.getReadableDatabase();
String[] field = new String[]{u_id};
cur = db.rawQuery("select * from customer where u_id=" + field[0], null);
int count = cur.getCount();
if (count == 0) {
return null;
}
UserInfo userInfo = new UserInfo();
if (cur.moveToFirst()) {
do {
userInfo.setAccount(cur.getString(cur.getColumnIndex("account")));
userInfo.setAccount_id(cur.getString(cur.getColumnIndex("account_id")));
userInfo.setOrganization_id(cur.getString(cur.getColumnIndex("u_orgid")));
userInfo.setUuid(cur.getString(cur.getColumnIndex("u_uuid")));
userInfo.setOrganization_name(cur.getString(cur.getColumnIndex("organization_name")));
userInfo.setRealName(cur.getString(cur.getColumnIndex("realname")));
userInfo.setFansnamage_id(cur.getString(cur.getColumnIndex("fansnamage_id")));
} while (cur.moveToNext());
}
return userInfo;
} catch (Exception e) {
throw new Exception("获取失败", e);
} finally {
cur.close();
db.close();
}
}
/**
* 清空表中数据
*
* @throws Exception
*/
public void deltable() throws Exception {
try {
db = baseDao.getWritableDatabase();
String sql = "delete from customer";
db.execSQL(sql);
} catch (Exception e) {
throw new Exception("清空失败", e);
} finally {
db.close();
}
}
/**
* 获取session
*
* @return
* @throws Exception
*/
public List<UserInfo> getAllUserInfo() throws Exception {
Cursor cur = null;
List<UserInfo> list = new ArrayList<>();
try {
db = baseDao.getReadableDatabase();
cur = db.rawQuery("select * from customer", null);
int count = cur.getCount();
if (count == 0) {
return null;
}
cur.moveToFirst();
return list;
} catch (Exception e) {
throw new Exception("获取失败", e);
} finally {
cur.close();
db.close();
}
}
/**
* 修改登录后的用户信息
*
* @param userInfo 用户信息实体类
*/
public void upDateUserInfo(UserInfo userInfo) {
db = baseDao.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("account_id", userInfo.getAccount_id());
values.put("account", userInfo.getAccount());
values.put("u_orgid", userInfo.getOrganization_id());
values.put("u_uuid", userInfo.getUuid());
values.put("organization_name", userInfo.getOrganization_name());
values.put("realname", userInfo.getRealName());
// new String[]{"10"}
int count = db.update("customer", values, "u_id = 10", null);
Log.i("URL", "修改数据成功了!!!!!" + count);
values.clear();
}
}
| true |
ed36059eb08557c0d560e896fd8438d2fa791bd9 | Java | dolphinss/code | /src/test/java/TestUserService.java | UTF-8 | 2,359 | 2.140625 | 2 | [] | no_license | import java.util.Date;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.zs.pms.po.TDep;
import com.zs.pms.po.TPermission;
import com.zs.pms.po.TUser;
import com.zs.pms.service.UserService;
import com.zs.pms.vo.QueryUser;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationcontext.xml")
public class TestUserService {
@Autowired
UserService us;
public void testquerypage() {
QueryUser query = new QueryUser();
query.setSex("女");
for (TUser user : us.queryByPage(1, query)) {
System.out.println(user.getId());
System.out.println(user.getLoginname());
}
System.out.println("共" + us.queryCount(query) + "页");
}
public void testquery() {
QueryUser query = new QueryUser();
query.setLoginname("dolphin");
query.setPassword("123");
query.setSex("女");
System.out.println(us.queryByCon(query).size());
}
public void testlogin() {
List<TPermission> list1 = us.queryByUid(3084);
for (TPermission per : list1) {
System.out.println(per.getPname());
}
System.out.println("------整理后的------");
for (TPermission per1 : us.getMenu(list1)) {
// 一级权限
System.out.println(per1.getPname());
for (TPermission per2 : per1.getChildren()) {
System.out.println("---" + per2.getPname());
}
}
}
@Test
public void testinsert() {
TUser user = new TUser();
TDep dep = new TDep();
dep.setId(3);
user.setDept(dep);
user.setIsenabled(1);
user.setLoginname("test123");
user.setPassword("123");
user.setSex("男");
user.setCreator(1001);
user.setEmail("insert@163.com");
user.setPic("inssert.jsp");
user.setRealname("新增测试");
user.setBirthday(new Date());
//System.out.println(us.insertUser(user));
}
public void testupdate() {
TUser user = new TUser();
user.setId(1001);
// user.setLoginname("update");
user.setSex("男");
us.updateUser(user);
}
public void testdelete() {
us.deleteUser(1003);
}
public void testdeletebyids() {
int[] ids = { 1001, 1002 };
us.deleteByIds(ids);
}
}
| true |
95efd47c4408db3d9d0f7aed891e9642f0b3ae8a | Java | nwpu043814/wifimaster4.2.02 | /WiFi万能钥匙dex1-dex2jar.jar.src/com/bluefay/preference/PSChildPaneSpecifier.java | UTF-8 | 963 | 1.601563 | 2 | [] | no_license | package com.bluefay.preference;
import android.content.Context;
import android.os.Bundle;
import android.util.AttributeSet;
import bluefay.preference.Preference;
public class PSChildPaneSpecifier
extends Preference
{
private int b;
public PSChildPaneSpecifier(Context paramContext, AttributeSet paramAttributeSet)
{
this(paramContext, paramAttributeSet, 16842894);
}
public PSChildPaneSpecifier(Context paramContext, AttributeSet paramAttributeSet, int paramInt)
{
super(paramContext, paramAttributeSet, paramInt);
this.b = paramAttributeSet.getAttributeResourceValue("http://schemas.android.com/apk/res/android", "fragment", 0);
b(PSChildPaneSpecifierFragement.class.getName());
m().putInt("file", this.b);
}
}
/* Location: /Users/hanlian/Downloads/WiFi万能钥匙dex1-dex2jar.jar!/com/bluefay/preference/PSChildPaneSpecifier.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | true |
9782336758b4a1a57e3bcf0902f24b65c20419ad | Java | adamturski/AuctionHelper | /src/main/java/pl/com/turski/ah/view/directoryChoose/DirectoryChooseController.java | UTF-8 | 2,311 | 2.40625 | 2 | [] | no_license | package pl.com.turski.ah.view.directoryChoose;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.stage.DirectoryChooser;
import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import pl.com.turski.ah.view.ViewController;
import java.io.File;
import java.io.FileFilter;
import java.util.Arrays;
import java.util.List;
/**
* User: Adam
*/
@Component
public class DirectoryChooseController implements ViewController {
private static final Logger LOG = LoggerFactory.getLogger(DirectoryChooseController.class);
@FXML
Button directoryChooseButton;
@FXML
Label directoryPathLabel;
@FXML
ListView<String> imagesFileList;
@FXML
Node view;
private List<File> images;
private File imagesDirectory;
public void folderChooseButtonAction(ActionEvent event) {
DirectoryChooser directoryChooser = new DirectoryChooser();
File directory = directoryChooser.showDialog(view.getScene().getWindow());
if (directory != null) {
LOG.info("Użytkownik wybrał katalog {}", directory);
imagesDirectory = directory;
images = Arrays.asList(directory.listFiles((FileFilter) new SuffixFileFilter(Arrays.asList(".jpg", ".jpeg",".JPG",".JPEG"))));
directoryPathLabel.setText(directory.getAbsolutePath());
ObservableList<String> fileList = FXCollections.observableArrayList();
for (File image : images) {
fileList.add(image.getName());
}
imagesFileList.setItems(fileList);
}
}
public void resetView() {
images = null;
imagesDirectory = null;
imagesFileList.setItems(FXCollections.<String>emptyObservableList());
directoryPathLabel.setText("");
}
public Node getView() {
return view;
}
public List<File> getImages() {
return images;
}
public File getImagesDirectory() {
return imagesDirectory;
}
}
| true |
6703b7e4ac9fdd9d87eedf764eec6253bbb80700 | Java | kleyton032/Projeto-Spring-e-Ionic-backend | /src/main/java/com/sistema/cursomc/resources/ClienteResources.java | UTF-8 | 3,932 | 2.359375 | 2 | [] | no_license | package com.sistema.cursomc.resources;
import java.net.URI;
import java.util.List;
import java.util.stream.Collectors;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import com.sistema.cursomc.dto.ClienteDTO;
import com.sistema.cursomc.dto.ClienteNewDTO;
import com.sistema.cursomc.model.Cliente;
import com.sistema.cursomc.services.ClienteService;
@RestController
@RequestMapping(value="/clientes")
public class ClienteResources {
@Autowired
private ClienteService clienteService;
@RequestMapping(value= "/{id}", method=RequestMethod.GET)
public ResponseEntity<Cliente> find(@PathVariable Integer id) {
Cliente objeto = clienteService.find(id);
return ResponseEntity.ok().body(objeto);
}
@RequestMapping(value="/email", method=RequestMethod.GET)
public ResponseEntity<Cliente> find(@RequestParam(value="value") String email) {
Cliente obj = clienteService.findByEmail(email);
return ResponseEntity.ok().body(obj);
}
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<Void> insert(@Valid @RequestBody ClienteNewDTO clienteNewDto) {
Cliente cliente = clienteService.fromDto(clienteNewDto);
cliente = clienteService.insert(cliente);
URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(cliente.getId())
.toUri();
return ResponseEntity.created(uri).build();
}
@RequestMapping(value= "/{id}", method=RequestMethod.PUT)
public ResponseEntity<Void> update(@Valid @RequestBody ClienteDTO clienteDto, @PathVariable Integer id){
Cliente cliente = clienteService.fromDto(clienteDto);
cliente.setId(id);
cliente = clienteService.update(cliente);
return ResponseEntity.noContent().build();
}
@PreAuthorize("hasAnyRole('ADMIN')")
//método de deletar cliente
@RequestMapping(value= "/{id}", method=RequestMethod.DELETE)
public ResponseEntity<Void> delete(@PathVariable Integer id){
clienteService.delete(id);
return ResponseEntity.noContent().build();
}
@PreAuthorize("hasAnyRole('ADMIN')")
@RequestMapping(method=RequestMethod.GET)
public ResponseEntity<List<ClienteDTO>> findAll() {
List<Cliente> list = clienteService.findAll();
List<ClienteDTO> listDto = list.stream().map(cliente -> new ClienteDTO(cliente)).collect(Collectors.toList());
return ResponseEntity.ok().body(listDto);
}
@PreAuthorize("hasAnyRole('ADMIN')")
@RequestMapping(value="/page", method=RequestMethod.GET)
public ResponseEntity<Page<ClienteDTO>> findPage(
@RequestParam(name="page", defaultValue="0") Integer page,
@RequestParam(name="linesPerPages", defaultValue="24")Integer linesPerPages,
@RequestParam(name="ordeBy", defaultValue="nome")String ordeBy,
@RequestParam(name="direction", defaultValue="ASC")String direction) {
Page<Cliente> list = clienteService.findPage(page, linesPerPages, ordeBy, direction);
Page<ClienteDTO> listDto = list.map(cliente -> new ClienteDTO(cliente));
return ResponseEntity.ok().body(listDto);
}
@RequestMapping(value = "/picture", method = RequestMethod.POST)
public ResponseEntity<Void> profilePicture(@RequestParam(name="file") MultipartFile file) {
URI uri = clienteService.uploadFileProfilePicture(file);
return ResponseEntity.created(uri).build();
}
}
| true |
8bccb09ff8ba9cfd98156d0b981fc667492c0d71 | Java | veraPDF/veraPDF-tools | /generation-json-from-profile/src/main/java/org/verapdf/tools/cli/RuleSerializer.java | UTF-8 | 1,707 | 2.171875 | 2 | [] | no_license | package org.verapdf.tools.cli;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import org.verapdf.pdfa.validation.profiles.Rule;
import org.verapdf.pdfa.validation.profiles.RuleId;
import java.io.IOException;
import java.util.Objects;
public class RuleSerializer extends StdSerializer<Rules> {
protected RuleSerializer(Class<Rules> t) {
super(t);
}
public void serialize(Rules rules, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
throws IOException {
RuleId lastRuleId = null;
jsonGenerator.writeStartObject();
for (Rule rule : rules.getRules()) {
RuleId id = rule.getRuleId();
if (lastRuleId == null || !Objects.equals(lastRuleId.getSpecification(), id.getSpecification())) {
if (lastRuleId != null) {
jsonGenerator.writeEndObject();
jsonGenerator.writeEndObject();
}
jsonGenerator.writeFieldName(id.getSpecification().getId());
jsonGenerator.writeStartObject();
}
if (lastRuleId == null || !lastRuleId.getClause().equals(id.getClause())) {
if (lastRuleId != null) {
jsonGenerator.writeEndObject();
}
jsonGenerator.writeFieldName(id.getClause());
jsonGenerator.writeStartObject();
}
jsonGenerator.writeFieldName(String.valueOf(id.getTestNumber()));
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("SUMMARY", rule.getError().getMessage());
jsonGenerator.writeStringField("DESCRIPTION", rule.getDescription());
jsonGenerator.writeEndObject();
lastRuleId = rule.getRuleId();
}
jsonGenerator.writeEndObject();
jsonGenerator.writeEndObject();
}
}
| true |
7b819dd60fe8416545419cb6db2f5a6c97a96c97 | Java | shishuai19910217/shishuai | /src/main/java/com/ido85/frame/web/rest/utils/RestUserUtils.java | UTF-8 | 1,387 | 2.078125 | 2 | [] | no_license | package com.ido85.frame.web.rest.utils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.util.ThreadContext;
import com.ido85.frame.web.UserInfo;
import com.ido85.frame.web.rest.security.Constants;
import com.ido85.frame.web.rest.security.StatelessPrincipal;
import com.ido85.frame.web.security.domain.UserOrm;
public class RestUserUtils {
public static final String USER_CACHE = "userCache";
/**
* 获取user
* @param accessKeyID
* @return
*/
public static final UserInfo getUserInfo() {
StatelessPrincipal principal = (StatelessPrincipal) SecurityUtils.getSubject().getPrincipal();
if (null == principal) {
principal = (StatelessPrincipal) ThreadContext.get("principal");
}
return getUserInfo(principal.getAccessKeyID());
}
public static Integer getTencentId() {
UserInfo userInfo = getUserInfo();
return userInfo == null ? null : userInfo.getTenantID();
}
/**
* 获取user
* @param accessKeyID
* @return
*/
public static UserInfo getUserInfo(String accessKeyID) {
UserOrm user = (UserOrm)CacheUtils.get(USER_CACHE, accessKeyID);
if (user == null){
user = UserClient.postForGetUserInfo(accessKeyID, Constants.USER_MANAGE_URL, Constants.USER_INFO_URI);
if(user == null || "".equals(user.getAccessKeyID())){
return null;
}
CacheUtils.put(USER_CACHE, user.getAccessKeyID(), user);
}
return user;
}
}
| true |
9a581a61a64434677f5a00ab1dd7714e6dd182f8 | Java | praveen8790/HotelReservation | /src/main/java/Main.java | UTF-8 | 244 | 2.359375 | 2 | [] | no_license | public class Main {
public static void main(String[] args) {
System.out.println("welcome to hotel management reservation");
HotelServices hotels = new HotelServices(1);
System.out.println(hotels.toString());
}
}
| true |
0037af00b168533775b4025f0e13f34b35064496 | Java | sinzua/baseApk | /src/main/java/org/codehaus/jackson/impl/Utf8StreamParser.java | UTF-8 | 94,296 | 1.90625 | 2 | [] | no_license | package org.codehaus.jackson.impl;
import android.support.v4.media.TransportMediator;
import com.anjlab.android.iab.v3.Constants;
import com.parse.ParseException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.codehaus.jackson.Base64Variant;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser.Feature;
import org.codehaus.jackson.JsonToken;
import org.codehaus.jackson.ObjectCodec;
import org.codehaus.jackson.SerializableString;
import org.codehaus.jackson.io.IOContext;
import org.codehaus.jackson.sym.BytesToNameCanonicalizer;
import org.codehaus.jackson.sym.Name;
import org.codehaus.jackson.util.ByteArrayBuilder;
import org.codehaus.jackson.util.CharTypes;
public final class Utf8StreamParser extends JsonParserBase {
static final byte BYTE_LF = (byte) 10;
private static final int[] sInputCodesLatin1 = CharTypes.getInputCodeLatin1();
private static final int[] sInputCodesUtf8 = CharTypes.getInputCodeUtf8();
protected boolean _bufferRecyclable;
protected byte[] _inputBuffer;
protected InputStream _inputStream;
protected ObjectCodec _objectCodec;
private int _quad1;
protected int[] _quadBuffer = new int[16];
protected final BytesToNameCanonicalizer _symbols;
protected boolean _tokenIncomplete = false;
public Utf8StreamParser(IOContext ctxt, int features, InputStream in, ObjectCodec codec, BytesToNameCanonicalizer sym, byte[] inputBuffer, int start, int end, boolean bufferRecyclable) {
super(ctxt, features);
this._inputStream = in;
this._objectCodec = codec;
this._symbols = sym;
this._inputBuffer = inputBuffer;
this._inputPtr = start;
this._inputEnd = end;
this._bufferRecyclable = bufferRecyclable;
if (!Feature.CANONICALIZE_FIELD_NAMES.enabledIn(features)) {
_throwInternal();
}
}
public ObjectCodec getCodec() {
return this._objectCodec;
}
public void setCodec(ObjectCodec c) {
this._objectCodec = c;
}
public int releaseBuffered(OutputStream out) throws IOException {
int count = this._inputEnd - this._inputPtr;
if (count < 1) {
return 0;
}
out.write(this._inputBuffer, this._inputPtr, count);
return count;
}
public Object getInputSource() {
return this._inputStream;
}
protected final boolean loadMore() throws IOException {
this._currInputProcessed += (long) this._inputEnd;
this._currInputRowStart -= this._inputEnd;
if (this._inputStream == null) {
return false;
}
int count = this._inputStream.read(this._inputBuffer, 0, this._inputBuffer.length);
if (count > 0) {
this._inputPtr = 0;
this._inputEnd = count;
return true;
}
_closeInput();
if (count != 0) {
return false;
}
throw new IOException("InputStream.read() returned 0 characters when trying to read " + this._inputBuffer.length + " bytes");
}
protected final boolean _loadToHaveAtLeast(int minAvailable) throws IOException {
if (this._inputStream == null) {
return false;
}
int amount = this._inputEnd - this._inputPtr;
if (amount <= 0 || this._inputPtr <= 0) {
this._inputEnd = 0;
} else {
this._currInputProcessed += (long) this._inputPtr;
this._currInputRowStart -= this._inputPtr;
System.arraycopy(this._inputBuffer, this._inputPtr, this._inputBuffer, 0, amount);
this._inputEnd = amount;
}
this._inputPtr = 0;
while (this._inputEnd < minAvailable) {
int count = this._inputStream.read(this._inputBuffer, this._inputEnd, this._inputBuffer.length - this._inputEnd);
if (count < 1) {
_closeInput();
if (count != 0) {
return false;
}
throw new IOException("InputStream.read() returned 0 characters when trying to read " + amount + " bytes");
}
this._inputEnd += count;
}
return true;
}
protected void _closeInput() throws IOException {
if (this._inputStream != null) {
if (this._ioContext.isResourceManaged() || isEnabled(Feature.AUTO_CLOSE_SOURCE)) {
this._inputStream.close();
}
this._inputStream = null;
}
}
protected void _releaseBuffers() throws IOException {
super._releaseBuffers();
if (this._bufferRecyclable) {
byte[] buf = this._inputBuffer;
if (buf != null) {
this._inputBuffer = null;
this._ioContext.releaseReadIOBuffer(buf);
}
}
}
public String getText() throws IOException, JsonParseException {
JsonToken t = this._currToken;
if (t != JsonToken.VALUE_STRING) {
return _getText2(t);
}
if (this._tokenIncomplete) {
this._tokenIncomplete = false;
_finishString();
}
return this._textBuffer.contentsAsString();
}
protected final String _getText2(JsonToken t) {
if (t == null) {
return null;
}
switch (t) {
case FIELD_NAME:
return this._parsingContext.getCurrentName();
case VALUE_STRING:
case VALUE_NUMBER_INT:
case VALUE_NUMBER_FLOAT:
return this._textBuffer.contentsAsString();
default:
return t.asString();
}
}
public char[] getTextCharacters() throws IOException, JsonParseException {
if (this._currToken == null) {
return null;
}
switch (this._currToken) {
case FIELD_NAME:
if (!this._nameCopied) {
String name = this._parsingContext.getCurrentName();
int nameLen = name.length();
if (this._nameCopyBuffer == null) {
this._nameCopyBuffer = this._ioContext.allocNameCopyBuffer(nameLen);
} else if (this._nameCopyBuffer.length < nameLen) {
this._nameCopyBuffer = new char[nameLen];
}
name.getChars(0, nameLen, this._nameCopyBuffer, 0);
this._nameCopied = true;
}
return this._nameCopyBuffer;
case VALUE_STRING:
if (this._tokenIncomplete) {
this._tokenIncomplete = false;
_finishString();
break;
}
break;
case VALUE_NUMBER_INT:
case VALUE_NUMBER_FLOAT:
break;
default:
return this._currToken.asCharArray();
}
return this._textBuffer.getTextBuffer();
}
public int getTextLength() throws IOException, JsonParseException {
if (this._currToken == null) {
return 0;
}
switch (this._currToken) {
case FIELD_NAME:
return this._parsingContext.getCurrentName().length();
case VALUE_STRING:
if (this._tokenIncomplete) {
this._tokenIncomplete = false;
_finishString();
break;
}
break;
case VALUE_NUMBER_INT:
case VALUE_NUMBER_FLOAT:
break;
default:
return this._currToken.asCharArray().length;
}
return this._textBuffer.size();
}
public int getTextOffset() throws IOException, JsonParseException {
if (this._currToken == null) {
return 0;
}
switch (this._currToken) {
case VALUE_STRING:
if (this._tokenIncomplete) {
this._tokenIncomplete = false;
_finishString();
break;
}
break;
case VALUE_NUMBER_INT:
case VALUE_NUMBER_FLOAT:
break;
default:
return 0;
}
return this._textBuffer.getTextOffset();
}
public byte[] getBinaryValue(Base64Variant b64variant) throws IOException, JsonParseException {
if (this._currToken != JsonToken.VALUE_STRING && (this._currToken != JsonToken.VALUE_EMBEDDED_OBJECT || this._binaryValue == null)) {
_reportError("Current token (" + this._currToken + ") not VALUE_STRING or VALUE_EMBEDDED_OBJECT, can not access as binary");
}
if (this._tokenIncomplete) {
try {
this._binaryValue = _decodeBase64(b64variant);
this._tokenIncomplete = false;
} catch (IllegalArgumentException iae) {
throw _constructError("Failed to decode VALUE_STRING as base64 (" + b64variant + "): " + iae.getMessage());
}
} else if (this._binaryValue == null) {
ByteArrayBuilder builder = _getByteArrayBuilder();
_decodeBase64(getText(), builder, b64variant);
this._binaryValue = builder.toByteArray();
}
return this._binaryValue;
}
public JsonToken nextToken() throws IOException, JsonParseException {
this._numTypesValid = 0;
if (this._currToken == JsonToken.FIELD_NAME) {
return _nextAfterName();
}
if (this._tokenIncomplete) {
_skipString();
}
int i = _skipWSOrEnd();
if (i < 0) {
close();
this._currToken = null;
return null;
}
this._tokenInputTotal = (this._currInputProcessed + ((long) this._inputPtr)) - 1;
this._tokenInputRow = this._currInputRow;
this._tokenInputCol = (this._inputPtr - this._currInputRowStart) - 1;
this._binaryValue = null;
JsonToken jsonToken;
if (i == 93) {
if (!this._parsingContext.inArray()) {
_reportMismatchedEndMarker(i, '}');
}
this._parsingContext = this._parsingContext.getParent();
jsonToken = JsonToken.END_ARRAY;
this._currToken = jsonToken;
return jsonToken;
} else if (i == ParseException.INVALID_EMAIL_ADDRESS) {
if (!this._parsingContext.inObject()) {
_reportMismatchedEndMarker(i, ']');
}
this._parsingContext = this._parsingContext.getParent();
jsonToken = JsonToken.END_OBJECT;
this._currToken = jsonToken;
return jsonToken;
} else {
if (this._parsingContext.expectComma()) {
if (i != 44) {
_reportUnexpectedChar(i, "was expecting comma to separate " + this._parsingContext.getTypeDesc() + " entries");
}
i = _skipWS();
}
if (!this._parsingContext.inObject()) {
return _nextTokenNotInObject(i);
}
this._parsingContext.setCurrentName(_parseFieldName(i).getName());
this._currToken = JsonToken.FIELD_NAME;
i = _skipWS();
if (i != 58) {
_reportUnexpectedChar(i, "was expecting a colon to separate field name and value");
}
i = _skipWS();
if (i == 34) {
this._tokenIncomplete = true;
this._nextToken = JsonToken.VALUE_STRING;
return this._currToken;
}
JsonToken t;
switch (i) {
case 45:
case 48:
case 49:
case 50:
case 51:
case 52:
case 53:
case 54:
case 55:
case 56:
case 57:
t = parseNumberText(i);
break;
case 91:
t = JsonToken.START_ARRAY;
break;
case 93:
case ParseException.INVALID_EMAIL_ADDRESS /*125*/:
_reportUnexpectedChar(i, "expected a value");
break;
case 102:
_matchToken("false", 1);
t = JsonToken.VALUE_FALSE;
break;
case Constants.BILLING_ERROR_OTHER_ERROR /*110*/:
_matchToken("null", 1);
t = JsonToken.VALUE_NULL;
break;
case ParseException.OBJECT_TOO_LARGE /*116*/:
break;
case ParseException.INVALID_ACL /*123*/:
t = JsonToken.START_OBJECT;
break;
default:
t = _handleUnexpectedValue(i);
break;
}
_matchToken("true", 1);
t = JsonToken.VALUE_TRUE;
this._nextToken = t;
return this._currToken;
}
}
private final JsonToken _nextTokenNotInObject(int i) throws IOException, JsonParseException {
if (i == 34) {
this._tokenIncomplete = true;
JsonToken jsonToken = JsonToken.VALUE_STRING;
this._currToken = jsonToken;
return jsonToken;
}
switch (i) {
case 45:
case 48:
case 49:
case 50:
case 51:
case 52:
case 53:
case 54:
case 55:
case 56:
case 57:
jsonToken = parseNumberText(i);
this._currToken = jsonToken;
return jsonToken;
case 91:
this._parsingContext = this._parsingContext.createChildArrayContext(this._tokenInputRow, this._tokenInputCol);
jsonToken = JsonToken.START_ARRAY;
this._currToken = jsonToken;
return jsonToken;
case 93:
case ParseException.INVALID_EMAIL_ADDRESS /*125*/:
_reportUnexpectedChar(i, "expected a value");
break;
case 102:
_matchToken("false", 1);
jsonToken = JsonToken.VALUE_FALSE;
this._currToken = jsonToken;
return jsonToken;
case Constants.BILLING_ERROR_OTHER_ERROR /*110*/:
_matchToken("null", 1);
jsonToken = JsonToken.VALUE_NULL;
this._currToken = jsonToken;
return jsonToken;
case ParseException.OBJECT_TOO_LARGE /*116*/:
break;
case ParseException.INVALID_ACL /*123*/:
this._parsingContext = this._parsingContext.createChildObjectContext(this._tokenInputRow, this._tokenInputCol);
jsonToken = JsonToken.START_OBJECT;
this._currToken = jsonToken;
return jsonToken;
default:
jsonToken = _handleUnexpectedValue(i);
this._currToken = jsonToken;
return jsonToken;
}
_matchToken("true", 1);
jsonToken = JsonToken.VALUE_TRUE;
this._currToken = jsonToken;
return jsonToken;
}
private final JsonToken _nextAfterName() {
this._nameCopied = false;
JsonToken t = this._nextToken;
this._nextToken = null;
if (t == JsonToken.START_ARRAY) {
this._parsingContext = this._parsingContext.createChildArrayContext(this._tokenInputRow, this._tokenInputCol);
} else if (t == JsonToken.START_OBJECT) {
this._parsingContext = this._parsingContext.createChildObjectContext(this._tokenInputRow, this._tokenInputCol);
}
this._currToken = t;
return t;
}
public void close() throws IOException {
super.close();
this._symbols.release();
}
public boolean nextFieldName(SerializableString str) throws IOException, JsonParseException {
this._numTypesValid = 0;
if (this._currToken == JsonToken.FIELD_NAME) {
_nextAfterName();
return false;
}
if (this._tokenIncomplete) {
_skipString();
}
int i = _skipWSOrEnd();
if (i < 0) {
close();
this._currToken = null;
return false;
}
this._tokenInputTotal = (this._currInputProcessed + ((long) this._inputPtr)) - 1;
this._tokenInputRow = this._currInputRow;
this._tokenInputCol = (this._inputPtr - this._currInputRowStart) - 1;
this._binaryValue = null;
if (i == 93) {
if (!this._parsingContext.inArray()) {
_reportMismatchedEndMarker(i, '}');
}
this._parsingContext = this._parsingContext.getParent();
this._currToken = JsonToken.END_ARRAY;
return false;
} else if (i == ParseException.INVALID_EMAIL_ADDRESS) {
if (!this._parsingContext.inObject()) {
_reportMismatchedEndMarker(i, ']');
}
this._parsingContext = this._parsingContext.getParent();
this._currToken = JsonToken.END_OBJECT;
return false;
} else {
if (this._parsingContext.expectComma()) {
if (i != 44) {
_reportUnexpectedChar(i, "was expecting comma to separate " + this._parsingContext.getTypeDesc() + " entries");
}
i = _skipWS();
}
if (this._parsingContext.inObject()) {
if (i == 34) {
byte[] nameBytes = str.asQuotedUTF8();
int len = nameBytes.length;
if (this._inputPtr + len < this._inputEnd) {
int end = this._inputPtr + len;
if (this._inputBuffer[end] == (byte) 34) {
int offset = 0;
int ptr = this._inputPtr;
while (offset != len) {
if (nameBytes[offset] == this._inputBuffer[ptr + offset]) {
offset++;
}
}
this._inputPtr = end + 1;
this._parsingContext.setCurrentName(str.getValue());
this._currToken = JsonToken.FIELD_NAME;
_isNextTokenNameYes();
return true;
}
}
}
_isNextTokenNameNo(i);
return false;
}
_nextTokenNotInObject(i);
return false;
}
}
private final void _isNextTokenNameYes() throws IOException, JsonParseException {
int i;
if (this._inputPtr >= this._inputEnd - 1 || this._inputBuffer[this._inputPtr] != (byte) 58) {
i = _skipColon();
} else {
this._inputPtr++;
byte[] bArr = this._inputBuffer;
int i2 = this._inputPtr;
this._inputPtr = i2 + 1;
i = bArr[i2];
if (i == 34) {
this._tokenIncomplete = true;
this._nextToken = JsonToken.VALUE_STRING;
return;
} else if (i == ParseException.INVALID_ACL) {
this._nextToken = JsonToken.START_OBJECT;
return;
} else if (i == 91) {
this._nextToken = JsonToken.START_ARRAY;
return;
} else {
i &= 255;
if (i <= 32 || i == 47) {
this._inputPtr--;
i = _skipWS();
}
}
}
switch (i) {
case 34:
this._tokenIncomplete = true;
this._nextToken = JsonToken.VALUE_STRING;
return;
case 45:
case 48:
case 49:
case 50:
case 51:
case 52:
case 53:
case 54:
case 55:
case 56:
case 57:
this._nextToken = parseNumberText(i);
return;
case 91:
this._nextToken = JsonToken.START_ARRAY;
return;
case 93:
case ParseException.INVALID_EMAIL_ADDRESS /*125*/:
_reportUnexpectedChar(i, "expected a value");
break;
case 102:
_matchToken("false", 1);
this._nextToken = JsonToken.VALUE_FALSE;
return;
case Constants.BILLING_ERROR_OTHER_ERROR /*110*/:
_matchToken("null", 1);
this._nextToken = JsonToken.VALUE_NULL;
return;
case ParseException.OBJECT_TOO_LARGE /*116*/:
break;
case ParseException.INVALID_ACL /*123*/:
this._nextToken = JsonToken.START_OBJECT;
return;
default:
this._nextToken = _handleUnexpectedValue(i);
return;
}
_matchToken("true", 1);
this._nextToken = JsonToken.VALUE_TRUE;
}
private final void _isNextTokenNameNo(int i) throws IOException, JsonParseException {
this._parsingContext.setCurrentName(_parseFieldName(i).getName());
this._currToken = JsonToken.FIELD_NAME;
i = _skipWS();
if (i != 58) {
_reportUnexpectedChar(i, "was expecting a colon to separate field name and value");
}
i = _skipWS();
if (i == 34) {
this._tokenIncomplete = true;
this._nextToken = JsonToken.VALUE_STRING;
return;
}
JsonToken t;
switch (i) {
case 45:
case 48:
case 49:
case 50:
case 51:
case 52:
case 53:
case 54:
case 55:
case 56:
case 57:
t = parseNumberText(i);
break;
case 91:
t = JsonToken.START_ARRAY;
break;
case 93:
case ParseException.INVALID_EMAIL_ADDRESS /*125*/:
_reportUnexpectedChar(i, "expected a value");
break;
case 102:
_matchToken("false", 1);
t = JsonToken.VALUE_FALSE;
break;
case Constants.BILLING_ERROR_OTHER_ERROR /*110*/:
_matchToken("null", 1);
t = JsonToken.VALUE_NULL;
break;
case ParseException.OBJECT_TOO_LARGE /*116*/:
break;
case ParseException.INVALID_ACL /*123*/:
t = JsonToken.START_OBJECT;
break;
default:
t = _handleUnexpectedValue(i);
break;
}
_matchToken("true", 1);
t = JsonToken.VALUE_TRUE;
this._nextToken = t;
}
public String nextTextValue() throws IOException, JsonParseException {
if (this._currToken == JsonToken.FIELD_NAME) {
this._nameCopied = false;
JsonToken t = this._nextToken;
this._nextToken = null;
this._currToken = t;
if (t == JsonToken.VALUE_STRING) {
if (this._tokenIncomplete) {
this._tokenIncomplete = false;
_finishString();
}
return this._textBuffer.contentsAsString();
} else if (t == JsonToken.START_ARRAY) {
this._parsingContext = this._parsingContext.createChildArrayContext(this._tokenInputRow, this._tokenInputCol);
return null;
} else if (t != JsonToken.START_OBJECT) {
return null;
} else {
this._parsingContext = this._parsingContext.createChildObjectContext(this._tokenInputRow, this._tokenInputCol);
return null;
}
} else if (nextToken() == JsonToken.VALUE_STRING) {
return getText();
} else {
return null;
}
}
public int nextIntValue(int defaultValue) throws IOException, JsonParseException {
if (this._currToken != JsonToken.FIELD_NAME) {
return nextToken() == JsonToken.VALUE_NUMBER_INT ? getIntValue() : defaultValue;
} else {
this._nameCopied = false;
JsonToken t = this._nextToken;
this._nextToken = null;
this._currToken = t;
if (t == JsonToken.VALUE_NUMBER_INT) {
return getIntValue();
}
if (t == JsonToken.START_ARRAY) {
this._parsingContext = this._parsingContext.createChildArrayContext(this._tokenInputRow, this._tokenInputCol);
return defaultValue;
} else if (t != JsonToken.START_OBJECT) {
return defaultValue;
} else {
this._parsingContext = this._parsingContext.createChildObjectContext(this._tokenInputRow, this._tokenInputCol);
return defaultValue;
}
}
}
public long nextLongValue(long defaultValue) throws IOException, JsonParseException {
if (this._currToken != JsonToken.FIELD_NAME) {
return nextToken() == JsonToken.VALUE_NUMBER_INT ? getLongValue() : defaultValue;
} else {
this._nameCopied = false;
JsonToken t = this._nextToken;
this._nextToken = null;
this._currToken = t;
if (t == JsonToken.VALUE_NUMBER_INT) {
return getLongValue();
}
if (t == JsonToken.START_ARRAY) {
this._parsingContext = this._parsingContext.createChildArrayContext(this._tokenInputRow, this._tokenInputCol);
return defaultValue;
} else if (t != JsonToken.START_OBJECT) {
return defaultValue;
} else {
this._parsingContext = this._parsingContext.createChildObjectContext(this._tokenInputRow, this._tokenInputCol);
return defaultValue;
}
}
}
public Boolean nextBooleanValue() throws IOException, JsonParseException {
if (this._currToken == JsonToken.FIELD_NAME) {
this._nameCopied = false;
JsonToken t = this._nextToken;
this._nextToken = null;
this._currToken = t;
if (t == JsonToken.VALUE_TRUE) {
return Boolean.TRUE;
}
if (t == JsonToken.VALUE_FALSE) {
return Boolean.FALSE;
}
if (t == JsonToken.START_ARRAY) {
this._parsingContext = this._parsingContext.createChildArrayContext(this._tokenInputRow, this._tokenInputCol);
return null;
} else if (t != JsonToken.START_OBJECT) {
return null;
} else {
this._parsingContext = this._parsingContext.createChildObjectContext(this._tokenInputRow, this._tokenInputCol);
return null;
}
}
switch (nextToken()) {
case VALUE_TRUE:
return Boolean.TRUE;
case VALUE_FALSE:
return Boolean.FALSE;
default:
return null;
}
}
protected final JsonToken parseNumberText(int c) throws IOException, JsonParseException {
int i;
int i2;
char[] outBuf = this._textBuffer.emptyAndGetCurrentSegment();
boolean negative = c == 45;
if (negative) {
i = 0 + 1;
outBuf[0] = '-';
if (this._inputPtr >= this._inputEnd) {
loadMoreGuaranteed();
}
byte[] bArr = this._inputBuffer;
int i3 = this._inputPtr;
this._inputPtr = i3 + 1;
c = bArr[i3] & 255;
if (c < 48 || c > 57) {
i2 = i;
return _handleInvalidNumberStart(c, true);
}
}
i = 0;
if (c == 48) {
c = _verifyNoLeadingZeroes();
}
i2 = i + 1;
outBuf[i] = (char) c;
int intLen = 1;
int end = this._inputPtr + outBuf.length;
if (end > this._inputEnd) {
end = this._inputEnd;
}
while (this._inputPtr < end) {
byte[] bArr2 = this._inputBuffer;
int i4 = this._inputPtr;
this._inputPtr = i4 + 1;
c = bArr2[i4] & 255;
if (c >= 48 && c <= 57) {
intLen++;
i = i2 + 1;
outBuf[i2] = (char) c;
i2 = i;
} else if (c == 46 || c == 101 || c == 69) {
return _parseFloatText(outBuf, i2, c, negative, intLen);
} else {
this._inputPtr--;
this._textBuffer.setCurrentLength(i2);
return resetInt(negative, intLen);
}
}
return _parserNumber2(outBuf, i2, negative, intLen);
}
private final JsonToken _parserNumber2(char[] outBuf, int outPtr, boolean negative, int intPartLength) throws IOException, JsonParseException {
int c;
while (true) {
if (this._inputPtr < this._inputEnd || loadMore()) {
byte[] bArr = this._inputBuffer;
int i = this._inputPtr;
this._inputPtr = i + 1;
c = bArr[i] & 255;
if (c <= 57 && c >= 48) {
if (outPtr >= outBuf.length) {
outBuf = this._textBuffer.finishCurrentSegment();
outPtr = 0;
}
int outPtr2 = outPtr + 1;
outBuf[outPtr] = (char) c;
intPartLength++;
outPtr = outPtr2;
}
} else {
this._textBuffer.setCurrentLength(outPtr);
return resetInt(negative, intPartLength);
}
}
if (c == 46 || c == 101 || c == 69) {
return _parseFloatText(outBuf, outPtr, c, negative, intPartLength);
}
this._inputPtr--;
this._textBuffer.setCurrentLength(outPtr);
return resetInt(negative, intPartLength);
}
private final int _verifyNoLeadingZeroes() throws IOException, JsonParseException {
if (this._inputPtr >= this._inputEnd && !loadMore()) {
return 48;
}
int ch = this._inputBuffer[this._inputPtr] & 255;
if (ch < 48 || ch > 57) {
return 48;
}
if (!isEnabled(Feature.ALLOW_NUMERIC_LEADING_ZEROS)) {
reportInvalidNumber("Leading zeroes not allowed");
}
this._inputPtr++;
if (ch != 48) {
return ch;
}
do {
if (this._inputPtr >= this._inputEnd && !loadMore()) {
return ch;
}
ch = this._inputBuffer[this._inputPtr] & 255;
if (ch < 48 || ch > 57) {
return 48;
}
this._inputPtr++;
} while (ch == 48);
return ch;
}
private final JsonToken _parseFloatText(char[] outBuf, int outPtr, int c, boolean negative, int integerPartLength) throws IOException, JsonParseException {
int outPtr2;
int fractLen = 0;
boolean eof = false;
if (c == 46) {
outPtr2 = outPtr + 1;
outBuf[outPtr] = (char) c;
outPtr = outPtr2;
while (true) {
if (this._inputPtr >= this._inputEnd && !loadMore()) {
break;
}
byte[] bArr = this._inputBuffer;
int i = this._inputPtr;
this._inputPtr = i + 1;
c = bArr[i] & 255;
if (c < 48 || c > 57) {
break;
}
fractLen++;
if (outPtr >= outBuf.length) {
outBuf = this._textBuffer.finishCurrentSegment();
outPtr = 0;
}
outPtr2 = outPtr + 1;
outBuf[outPtr] = (char) c;
outPtr = outPtr2;
}
eof = true;
if (fractLen == 0) {
reportUnexpectedNumberChar(c, "Decimal point not followed by a digit");
}
}
int expLen = 0;
if (c == 101 || c == 69) {
if (outPtr >= outBuf.length) {
outBuf = this._textBuffer.finishCurrentSegment();
outPtr = 0;
}
outPtr2 = outPtr + 1;
outBuf[outPtr] = (char) c;
if (this._inputPtr >= this._inputEnd) {
loadMoreGuaranteed();
}
bArr = this._inputBuffer;
i = this._inputPtr;
this._inputPtr = i + 1;
c = bArr[i] & 255;
if (c == 45 || c == 43) {
if (outPtr2 >= outBuf.length) {
outBuf = this._textBuffer.finishCurrentSegment();
outPtr = 0;
} else {
outPtr = outPtr2;
}
outPtr2 = outPtr + 1;
outBuf[outPtr] = (char) c;
if (this._inputPtr >= this._inputEnd) {
loadMoreGuaranteed();
}
bArr = this._inputBuffer;
i = this._inputPtr;
this._inputPtr = i + 1;
c = bArr[i] & 255;
outPtr = outPtr2;
} else {
outPtr = outPtr2;
}
while (c <= 57 && c >= 48) {
expLen++;
if (outPtr >= outBuf.length) {
outBuf = this._textBuffer.finishCurrentSegment();
outPtr = 0;
}
outPtr2 = outPtr + 1;
outBuf[outPtr] = (char) c;
if (this._inputPtr >= this._inputEnd && !loadMore()) {
eof = true;
outPtr = outPtr2;
break;
}
bArr = this._inputBuffer;
i = this._inputPtr;
this._inputPtr = i + 1;
c = bArr[i] & 255;
outPtr = outPtr2;
}
if (expLen == 0) {
reportUnexpectedNumberChar(c, "Exponent indicator not followed by a digit");
}
}
if (!eof) {
this._inputPtr--;
}
this._textBuffer.setCurrentLength(outPtr);
return resetFloat(negative, integerPartLength, fractLen, expLen);
}
protected final Name _parseFieldName(int i) throws IOException, JsonParseException {
if (i != 34) {
return _handleUnusualFieldName(i);
}
if (this._inputPtr + 9 > this._inputEnd) {
return slowParseFieldName();
}
byte[] input = this._inputBuffer;
int[] codes = sInputCodesLatin1;
int i2 = this._inputPtr;
this._inputPtr = i2 + 1;
int q = input[i2] & 255;
if (codes[q] == 0) {
i2 = this._inputPtr;
this._inputPtr = i2 + 1;
i = input[i2] & 255;
if (codes[i] == 0) {
q = (q << 8) | i;
i2 = this._inputPtr;
this._inputPtr = i2 + 1;
i = input[i2] & 255;
if (codes[i] == 0) {
q = (q << 8) | i;
i2 = this._inputPtr;
this._inputPtr = i2 + 1;
i = input[i2] & 255;
if (codes[i] == 0) {
q = (q << 8) | i;
i2 = this._inputPtr;
this._inputPtr = i2 + 1;
i = input[i2] & 255;
if (codes[i] == 0) {
this._quad1 = q;
return parseMediumFieldName(i, codes);
} else if (i == 34) {
return findName(q, 4);
} else {
return parseFieldName(q, i, 4);
}
} else if (i == 34) {
return findName(q, 3);
} else {
return parseFieldName(q, i, 3);
}
} else if (i == 34) {
return findName(q, 2);
} else {
return parseFieldName(q, i, 2);
}
} else if (i == 34) {
return findName(q, 1);
} else {
return parseFieldName(q, i, 1);
}
} else if (q == 34) {
return BytesToNameCanonicalizer.getEmptyName();
} else {
return parseFieldName(0, q, 0);
}
}
protected final Name parseMediumFieldName(int q2, int[] codes) throws IOException, JsonParseException {
byte[] bArr = this._inputBuffer;
int i = this._inputPtr;
this._inputPtr = i + 1;
int i2 = bArr[i] & 255;
if (codes[i2] == 0) {
q2 = (q2 << 8) | i2;
bArr = this._inputBuffer;
i = this._inputPtr;
this._inputPtr = i + 1;
i2 = bArr[i] & 255;
if (codes[i2] == 0) {
q2 = (q2 << 8) | i2;
bArr = this._inputBuffer;
i = this._inputPtr;
this._inputPtr = i + 1;
i2 = bArr[i] & 255;
if (codes[i2] == 0) {
q2 = (q2 << 8) | i2;
bArr = this._inputBuffer;
i = this._inputPtr;
this._inputPtr = i + 1;
i2 = bArr[i] & 255;
if (codes[i2] == 0) {
this._quadBuffer[0] = this._quad1;
this._quadBuffer[1] = q2;
return parseLongFieldName(i2);
} else if (i2 == 34) {
return findName(this._quad1, q2, 4);
} else {
return parseFieldName(this._quad1, q2, i2, 4);
}
} else if (i2 == 34) {
return findName(this._quad1, q2, 3);
} else {
return parseFieldName(this._quad1, q2, i2, 3);
}
} else if (i2 == 34) {
return findName(this._quad1, q2, 2);
} else {
return parseFieldName(this._quad1, q2, i2, 2);
}
} else if (i2 == 34) {
return findName(this._quad1, q2, 1);
} else {
return parseFieldName(this._quad1, q2, i2, 1);
}
}
protected Name parseLongFieldName(int q) throws IOException, JsonParseException {
int[] codes = sInputCodesLatin1;
int qlen = 2;
while (this._inputEnd - this._inputPtr >= 4) {
byte[] bArr = this._inputBuffer;
int i = this._inputPtr;
this._inputPtr = i + 1;
int i2 = bArr[i] & 255;
if (codes[i2] == 0) {
q = (q << 8) | i2;
bArr = this._inputBuffer;
i = this._inputPtr;
this._inputPtr = i + 1;
i2 = bArr[i] & 255;
if (codes[i2] == 0) {
q = (q << 8) | i2;
bArr = this._inputBuffer;
i = this._inputPtr;
this._inputPtr = i + 1;
i2 = bArr[i] & 255;
if (codes[i2] == 0) {
q = (q << 8) | i2;
bArr = this._inputBuffer;
i = this._inputPtr;
this._inputPtr = i + 1;
i2 = bArr[i] & 255;
if (codes[i2] == 0) {
if (qlen >= this._quadBuffer.length) {
this._quadBuffer = growArrayBy(this._quadBuffer, qlen);
}
int qlen2 = qlen + 1;
this._quadBuffer[qlen] = q;
q = i2;
qlen = qlen2;
} else if (i2 == 34) {
return findName(this._quadBuffer, qlen, q, 4);
} else {
return parseEscapedFieldName(this._quadBuffer, qlen, q, i2, 4);
}
} else if (i2 == 34) {
return findName(this._quadBuffer, qlen, q, 3);
} else {
return parseEscapedFieldName(this._quadBuffer, qlen, q, i2, 3);
}
} else if (i2 == 34) {
return findName(this._quadBuffer, qlen, q, 2);
} else {
return parseEscapedFieldName(this._quadBuffer, qlen, q, i2, 2);
}
} else if (i2 == 34) {
return findName(this._quadBuffer, qlen, q, 1);
} else {
return parseEscapedFieldName(this._quadBuffer, qlen, q, i2, 1);
}
}
return parseEscapedFieldName(this._quadBuffer, qlen, 0, q, 0);
}
protected Name slowParseFieldName() throws IOException, JsonParseException {
if (this._inputPtr >= this._inputEnd && !loadMore()) {
_reportInvalidEOF(": was expecting closing '\"' for name");
}
byte[] bArr = this._inputBuffer;
int i = this._inputPtr;
this._inputPtr = i + 1;
int i2 = bArr[i] & 255;
if (i2 == 34) {
return BytesToNameCanonicalizer.getEmptyName();
}
return parseEscapedFieldName(this._quadBuffer, 0, 0, i2, 0);
}
private final Name parseFieldName(int q1, int ch, int lastQuadBytes) throws IOException, JsonParseException {
return parseEscapedFieldName(this._quadBuffer, 0, q1, ch, lastQuadBytes);
}
private final Name parseFieldName(int q1, int q2, int ch, int lastQuadBytes) throws IOException, JsonParseException {
this._quadBuffer[0] = q1;
return parseEscapedFieldName(this._quadBuffer, 1, q2, ch, lastQuadBytes);
}
protected Name parseEscapedFieldName(int[] quads, int qlen, int currQuad, int ch, int currQuadBytes) throws IOException, JsonParseException {
int[] codes = sInputCodesLatin1;
while (true) {
int qlen2;
byte[] bArr;
int i;
if (codes[ch] != 0) {
if (ch == 34) {
break;
}
if (ch != 92) {
_throwUnquotedSpace(ch, "name");
} else {
ch = _decodeEscaped();
}
if (ch > TransportMediator.KEYCODE_MEDIA_PAUSE) {
if (currQuadBytes >= 4) {
if (qlen >= quads.length) {
quads = growArrayBy(quads, quads.length);
this._quadBuffer = quads;
}
qlen2 = qlen + 1;
quads[qlen] = currQuad;
currQuad = 0;
currQuadBytes = 0;
} else {
qlen2 = qlen;
}
if (ch < 2048) {
currQuad = (currQuad << 8) | ((ch >> 6) | 192);
currQuadBytes++;
qlen = qlen2;
} else {
currQuad = (currQuad << 8) | ((ch >> 12) | 224);
currQuadBytes++;
if (currQuadBytes >= 4) {
if (qlen2 >= quads.length) {
quads = growArrayBy(quads, quads.length);
this._quadBuffer = quads;
}
qlen = qlen2 + 1;
quads[qlen2] = currQuad;
currQuad = 0;
currQuadBytes = 0;
} else {
qlen = qlen2;
}
currQuad = (currQuad << 8) | (((ch >> 6) & 63) | 128);
currQuadBytes++;
}
ch = (ch & 63) | 128;
qlen2 = qlen;
if (currQuadBytes >= 4) {
currQuadBytes++;
currQuad = (currQuad << 8) | ch;
qlen = qlen2;
} else {
if (qlen2 >= quads.length) {
quads = growArrayBy(quads, quads.length);
this._quadBuffer = quads;
}
qlen = qlen2 + 1;
quads[qlen2] = currQuad;
currQuad = ch;
currQuadBytes = 1;
}
if (this._inputPtr >= this._inputEnd && !loadMore()) {
_reportInvalidEOF(" in field name");
}
bArr = this._inputBuffer;
i = this._inputPtr;
this._inputPtr = i + 1;
ch = bArr[i] & 255;
}
}
qlen2 = qlen;
if (currQuadBytes >= 4) {
if (qlen2 >= quads.length) {
quads = growArrayBy(quads, quads.length);
this._quadBuffer = quads;
}
qlen = qlen2 + 1;
quads[qlen2] = currQuad;
currQuad = ch;
currQuadBytes = 1;
} else {
currQuadBytes++;
currQuad = (currQuad << 8) | ch;
qlen = qlen2;
}
_reportInvalidEOF(" in field name");
bArr = this._inputBuffer;
i = this._inputPtr;
this._inputPtr = i + 1;
ch = bArr[i] & 255;
}
if (currQuadBytes > 0) {
if (qlen >= quads.length) {
quads = growArrayBy(quads, quads.length);
this._quadBuffer = quads;
}
qlen2 = qlen + 1;
quads[qlen] = currQuad;
qlen = qlen2;
}
Name name = this._symbols.findName(quads, qlen);
if (name == null) {
return addName(quads, qlen, currQuadBytes);
}
return name;
}
protected final Name _handleUnusualFieldName(int ch) throws IOException, JsonParseException {
if (ch == 39 && isEnabled(Feature.ALLOW_SINGLE_QUOTES)) {
return _parseApostropheFieldName();
}
int qlen;
if (!isEnabled(Feature.ALLOW_UNQUOTED_FIELD_NAMES)) {
_reportUnexpectedChar(ch, "was expecting double-quote to start field name");
}
int[] codes = CharTypes.getInputCodeUtf8JsNames();
if (codes[ch] != 0) {
_reportUnexpectedChar(ch, "was expecting either valid name character (for unquoted name) or double-quote (for quoted) to start field name");
}
int[] quads = this._quadBuffer;
int currQuad = 0;
int currQuadBytes = 0;
int qlen2 = 0;
while (true) {
if (currQuadBytes < 4) {
currQuadBytes++;
currQuad = (currQuad << 8) | ch;
qlen = qlen2;
} else {
if (qlen2 >= quads.length) {
quads = growArrayBy(quads, quads.length);
this._quadBuffer = quads;
}
qlen = qlen2 + 1;
quads[qlen2] = currQuad;
currQuad = ch;
currQuadBytes = 1;
}
if (this._inputPtr >= this._inputEnd && !loadMore()) {
_reportInvalidEOF(" in field name");
}
ch = this._inputBuffer[this._inputPtr] & 255;
if (codes[ch] != 0) {
break;
}
this._inputPtr++;
qlen2 = qlen;
}
if (currQuadBytes > 0) {
if (qlen >= quads.length) {
quads = growArrayBy(quads, quads.length);
this._quadBuffer = quads;
}
qlen2 = qlen + 1;
quads[qlen] = currQuad;
qlen = qlen2;
}
Name name = this._symbols.findName(quads, qlen);
if (name == null) {
return addName(quads, qlen, currQuadBytes);
}
return name;
}
protected final Name _parseApostropheFieldName() throws IOException, JsonParseException {
if (this._inputPtr >= this._inputEnd && !loadMore()) {
_reportInvalidEOF(": was expecting closing ''' for name");
}
byte[] bArr = this._inputBuffer;
int i = this._inputPtr;
this._inputPtr = i + 1;
int ch = bArr[i] & 255;
if (ch == 39) {
return BytesToNameCanonicalizer.getEmptyName();
}
int qlen;
int[] quads = this._quadBuffer;
int currQuad = 0;
int currQuadBytes = 0;
int[] codes = sInputCodesLatin1;
int qlen2 = 0;
while (ch != 39) {
if (!(ch == 34 || codes[ch] == 0)) {
if (ch != 92) {
_throwUnquotedSpace(ch, "name");
} else {
ch = _decodeEscaped();
}
if (ch > TransportMediator.KEYCODE_MEDIA_PAUSE) {
if (currQuadBytes >= 4) {
if (qlen2 >= quads.length) {
quads = growArrayBy(quads, quads.length);
this._quadBuffer = quads;
}
qlen = qlen2 + 1;
quads[qlen2] = currQuad;
currQuad = 0;
currQuadBytes = 0;
qlen2 = qlen;
}
if (ch < 2048) {
currQuad = (currQuad << 8) | ((ch >> 6) | 192);
currQuadBytes++;
qlen = qlen2;
} else {
currQuad = (currQuad << 8) | ((ch >> 12) | 224);
currQuadBytes++;
if (currQuadBytes >= 4) {
if (qlen2 >= quads.length) {
quads = growArrayBy(quads, quads.length);
this._quadBuffer = quads;
}
qlen = qlen2 + 1;
quads[qlen2] = currQuad;
currQuad = 0;
currQuadBytes = 0;
} else {
qlen = qlen2;
}
currQuad = (currQuad << 8) | (((ch >> 6) & 63) | 128);
currQuadBytes++;
}
ch = (ch & 63) | 128;
qlen2 = qlen;
}
}
if (currQuadBytes < 4) {
currQuadBytes++;
currQuad = (currQuad << 8) | ch;
qlen = qlen2;
} else {
if (qlen2 >= quads.length) {
quads = growArrayBy(quads, quads.length);
this._quadBuffer = quads;
}
qlen = qlen2 + 1;
quads[qlen2] = currQuad;
currQuad = ch;
currQuadBytes = 1;
}
if (this._inputPtr >= this._inputEnd && !loadMore()) {
_reportInvalidEOF(" in field name");
}
bArr = this._inputBuffer;
i = this._inputPtr;
this._inputPtr = i + 1;
ch = bArr[i] & 255;
qlen2 = qlen;
}
if (currQuadBytes > 0) {
if (qlen2 >= quads.length) {
quads = growArrayBy(quads, quads.length);
this._quadBuffer = quads;
}
qlen = qlen2 + 1;
quads[qlen2] = currQuad;
} else {
qlen = qlen2;
}
Name name = this._symbols.findName(quads, qlen);
if (name == null) {
return addName(quads, qlen, currQuadBytes);
}
return name;
}
private final Name findName(int q1, int lastQuadBytes) throws JsonParseException {
Name name = this._symbols.findName(q1);
if (name != null) {
return name;
}
this._quadBuffer[0] = q1;
return addName(this._quadBuffer, 1, lastQuadBytes);
}
private final Name findName(int q1, int q2, int lastQuadBytes) throws JsonParseException {
Name name = this._symbols.findName(q1, q2);
if (name != null) {
return name;
}
this._quadBuffer[0] = q1;
this._quadBuffer[1] = q2;
return addName(this._quadBuffer, 2, lastQuadBytes);
}
private final Name findName(int[] quads, int qlen, int lastQuad, int lastQuadBytes) throws JsonParseException {
if (qlen >= quads.length) {
quads = growArrayBy(quads, quads.length);
this._quadBuffer = quads;
}
int qlen2 = qlen + 1;
quads[qlen] = lastQuad;
Name name = this._symbols.findName(quads, qlen2);
if (name == null) {
return addName(quads, qlen2, lastQuadBytes);
}
return name;
}
private final Name addName(int[] quads, int qlen, int lastQuadBytes) throws JsonParseException {
int lastQuad;
int byteLen = ((qlen << 2) - 4) + lastQuadBytes;
if (lastQuadBytes < 4) {
lastQuad = quads[qlen - 1];
quads[qlen - 1] = lastQuad << ((4 - lastQuadBytes) << 3);
} else {
lastQuad = 0;
}
char[] cbuf = this._textBuffer.emptyAndGetCurrentSegment();
int ix = 0;
int cix = 0;
while (ix < byteLen) {
int i;
int i2 = (quads[ix >> 2] >> ((3 - (ix & 3)) << 3)) & 255;
ix++;
if (i2 > TransportMediator.KEYCODE_MEDIA_PAUSE) {
int needed;
if ((i2 & 224) == 192) {
i2 &= 31;
needed = 1;
} else if ((i2 & 240) == 224) {
i2 &= 15;
needed = 2;
} else if ((i2 & 248) == 240) {
i2 &= 7;
needed = 3;
} else {
_reportInvalidInitial(i2);
i2 = 1;
needed = 1;
}
if (ix + needed > byteLen) {
_reportInvalidEOF(" in field name");
}
int ch2 = quads[ix >> 2] >> ((3 - (ix & 3)) << 3);
ix++;
if ((ch2 & 192) != 128) {
_reportInvalidOther(ch2);
}
i2 = (i2 << 6) | (ch2 & 63);
if (needed > 1) {
ch2 = quads[ix >> 2] >> ((3 - (ix & 3)) << 3);
ix++;
if ((ch2 & 192) != 128) {
_reportInvalidOther(ch2);
}
i2 = (i2 << 6) | (ch2 & 63);
if (needed > 2) {
ch2 = quads[ix >> 2] >> ((3 - (ix & 3)) << 3);
ix++;
if ((ch2 & 192) != 128) {
_reportInvalidOther(ch2 & 255);
}
i2 = (i2 << 6) | (ch2 & 63);
}
}
if (needed > 2) {
i2 -= 65536;
if (cix >= cbuf.length) {
cbuf = this._textBuffer.expandCurrentSegment();
}
i = cix + 1;
cbuf[cix] = (char) (55296 + (i2 >> 10));
i2 = 56320 | (i2 & 1023);
if (i >= cbuf.length) {
cbuf = this._textBuffer.expandCurrentSegment();
}
cix = i + 1;
cbuf[i] = (char) i2;
}
}
i = cix;
if (i >= cbuf.length) {
cbuf = this._textBuffer.expandCurrentSegment();
}
cix = i + 1;
cbuf[i] = (char) i2;
}
String baseName = new String(cbuf, 0, cix);
if (lastQuadBytes < 4) {
quads[qlen - 1] = lastQuad;
}
return this._symbols.addName(baseName, quads, qlen);
}
protected void _finishString() throws IOException, JsonParseException {
int ptr = this._inputPtr;
if (ptr >= this._inputEnd) {
loadMoreGuaranteed();
ptr = this._inputPtr;
}
char[] outBuf = this._textBuffer.emptyAndGetCurrentSegment();
int[] codes = sInputCodesUtf8;
int max = Math.min(this._inputEnd, outBuf.length + ptr);
byte[] inputBuffer = this._inputBuffer;
int outPtr = 0;
while (ptr < max) {
int c = inputBuffer[ptr] & 255;
if (codes[c] != 0) {
if (c == 34) {
this._inputPtr = ptr + 1;
this._textBuffer.setCurrentLength(outPtr);
return;
}
this._inputPtr = ptr;
_finishString2(outBuf, outPtr);
}
ptr++;
int outPtr2 = outPtr + 1;
outBuf[outPtr] = (char) c;
outPtr = outPtr2;
}
this._inputPtr = ptr;
_finishString2(outBuf, outPtr);
}
private final void _finishString2(char[] outBuf, int outPtr) throws IOException, JsonParseException {
int[] codes = sInputCodesUtf8;
byte[] inputBuffer = this._inputBuffer;
while (true) {
int ptr = this._inputPtr;
if (ptr >= this._inputEnd) {
loadMoreGuaranteed();
ptr = this._inputPtr;
}
if (outPtr >= outBuf.length) {
outBuf = this._textBuffer.finishCurrentSegment();
outPtr = 0;
}
int max = Math.min(this._inputEnd, (outBuf.length - outPtr) + ptr);
int ptr2 = ptr;
int outPtr2 = outPtr;
while (ptr2 < max) {
ptr = ptr2 + 1;
int c = inputBuffer[ptr2] & 255;
if (codes[c] != 0) {
this._inputPtr = ptr;
if (c == 34) {
this._textBuffer.setCurrentLength(outPtr2);
return;
}
switch (codes[c]) {
case 1:
c = _decodeEscaped();
outPtr = outPtr2;
break;
case 2:
c = _decodeUtf8_2(c);
outPtr = outPtr2;
break;
case 3:
if (this._inputEnd - this._inputPtr < 2) {
c = _decodeUtf8_3(c);
outPtr = outPtr2;
break;
}
c = _decodeUtf8_3fast(c);
outPtr = outPtr2;
break;
case 4:
c = _decodeUtf8_4(c);
outPtr = outPtr2 + 1;
outBuf[outPtr2] = (char) (55296 | (c >> 10));
if (outPtr >= outBuf.length) {
outBuf = this._textBuffer.finishCurrentSegment();
outPtr = 0;
}
c = 56320 | (c & 1023);
break;
default:
if (c >= 32) {
_reportInvalidChar(c);
outPtr = outPtr2;
break;
}
_throwUnquotedSpace(c, "string value");
outPtr = outPtr2;
break;
}
if (outPtr >= outBuf.length) {
outBuf = this._textBuffer.finishCurrentSegment();
outPtr = 0;
}
outPtr2 = outPtr + 1;
outBuf[outPtr] = (char) c;
outPtr = outPtr2;
} else {
outPtr = outPtr2 + 1;
outBuf[outPtr2] = (char) c;
ptr2 = ptr;
outPtr2 = outPtr;
}
}
this._inputPtr = ptr2;
outPtr = outPtr2;
}
}
protected void _skipString() throws java.io.IOException, org.codehaus.jackson.JsonParseException {
/* JADX: method processing error */
/*
Error: jadx.core.utils.exceptions.JadxOverflowException: Regions stack size limit reached
at jadx.core.utils.ErrorsCounter.addError(ErrorsCounter.java:37)
at jadx.core.utils.ErrorsCounter.methodError(ErrorsCounter.java:61)
at jadx.core.dex.visitors.DepthTraversal.visit(DepthTraversal.java:33)
at jadx.core.dex.visitors.DepthTraversal.visit(DepthTraversal.java:17)
at jadx.core.ProcessClass.process(ProcessClass.java:37)
at jadx.api.JadxDecompiler.processClass(JadxDecompiler.java:306)
at jadx.api.JavaClass.decompile(JavaClass.java:62)
*/
/*
r7 = this;
r6 = 0;
r7._tokenIncomplete = r6;
r1 = sInputCodesUtf8;
r2 = r7._inputBuffer;
L_0x0007:
r4 = r7._inputPtr;
r3 = r7._inputEnd;
if (r4 < r3) goto L_0x004e;
L_0x000d:
r7.loadMoreGuaranteed();
r4 = r7._inputPtr;
r3 = r7._inputEnd;
r5 = r4;
L_0x0015:
if (r5 >= r3) goto L_0x0028;
L_0x0017:
r4 = r5 + 1;
r6 = r2[r5];
r0 = r6 & 255;
r6 = r1[r0];
if (r6 == 0) goto L_0x004e;
L_0x0021:
r7._inputPtr = r4;
r6 = 34;
if (r0 != r6) goto L_0x002b;
L_0x0027:
return;
L_0x0028:
r7._inputPtr = r5;
goto L_0x0007;
L_0x002b:
r6 = r1[r0];
switch(r6) {
case 1: goto L_0x003a;
case 2: goto L_0x003e;
case 3: goto L_0x0042;
case 4: goto L_0x0046;
default: goto L_0x0030;
};
L_0x0030:
r6 = 32;
if (r0 >= r6) goto L_0x004a;
L_0x0034:
r6 = "string value";
r7._throwUnquotedSpace(r0, r6);
goto L_0x0007;
L_0x003a:
r7._decodeEscaped();
goto L_0x0007;
L_0x003e:
r7._skipUtf8_2(r0);
goto L_0x0007;
L_0x0042:
r7._skipUtf8_3(r0);
goto L_0x0007;
L_0x0046:
r7._skipUtf8_4(r0);
goto L_0x0007;
L_0x004a:
r7._reportInvalidChar(r0);
goto L_0x0007;
L_0x004e:
r5 = r4;
goto L_0x0015;
*/
throw new UnsupportedOperationException("Method not decompiled: org.codehaus.jackson.impl.Utf8StreamParser._skipString():void");
}
protected JsonToken _handleUnexpectedValue(int c) throws IOException, JsonParseException {
switch (c) {
case 39:
if (isEnabled(Feature.ALLOW_SINGLE_QUOTES)) {
return _handleApostropheValue();
}
break;
case 43:
if (this._inputPtr >= this._inputEnd && !loadMore()) {
_reportInvalidEOFInValue();
}
byte[] bArr = this._inputBuffer;
int i = this._inputPtr;
this._inputPtr = i + 1;
return _handleInvalidNumberStart(bArr[i] & 255, false);
case 78:
_matchToken("NaN", 1);
if (!isEnabled(Feature.ALLOW_NON_NUMERIC_NUMBERS)) {
_reportError("Non-standard token 'NaN': enable JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS to allow");
break;
}
return resetAsNaN("NaN", Double.NaN);
}
_reportUnexpectedChar(c, "expected a valid value (number, String, array, object, 'true', 'false' or 'null')");
return null;
}
protected JsonToken _handleApostropheValue() throws IOException, JsonParseException {
int outPtr = 0;
char[] outBuf = this._textBuffer.emptyAndGetCurrentSegment();
int[] codes = sInputCodesUtf8;
byte[] inputBuffer = this._inputBuffer;
while (true) {
if (this._inputPtr >= this._inputEnd) {
loadMoreGuaranteed();
}
if (outPtr >= outBuf.length) {
outBuf = this._textBuffer.finishCurrentSegment();
outPtr = 0;
}
int max = this._inputEnd;
int max2 = this._inputPtr + (outBuf.length - outPtr);
if (max2 < max) {
max = max2;
}
while (this._inputPtr < max) {
int i = this._inputPtr;
this._inputPtr = i + 1;
int c = inputBuffer[i] & 255;
int outPtr2;
if (c != 39 && codes[c] == 0) {
outPtr2 = outPtr + 1;
outBuf[outPtr] = (char) c;
outPtr = outPtr2;
} else if (c == 39) {
this._textBuffer.setCurrentLength(outPtr);
return JsonToken.VALUE_STRING;
} else {
switch (codes[c]) {
case 1:
if (c != 34) {
c = _decodeEscaped();
break;
}
break;
case 2:
c = _decodeUtf8_2(c);
break;
case 3:
if (this._inputEnd - this._inputPtr < 2) {
c = _decodeUtf8_3(c);
break;
}
c = _decodeUtf8_3fast(c);
break;
case 4:
c = _decodeUtf8_4(c);
outPtr2 = outPtr + 1;
outBuf[outPtr] = (char) (55296 | (c >> 10));
if (outPtr2 >= outBuf.length) {
outBuf = this._textBuffer.finishCurrentSegment();
outPtr = 0;
} else {
outPtr = outPtr2;
}
c = 56320 | (c & 1023);
break;
default:
if (c < 32) {
_throwUnquotedSpace(c, "string value");
}
_reportInvalidChar(c);
break;
}
if (outPtr >= outBuf.length) {
outBuf = this._textBuffer.finishCurrentSegment();
outPtr = 0;
}
outPtr2 = outPtr + 1;
outBuf[outPtr] = (char) c;
outPtr = outPtr2;
}
}
}
}
protected JsonToken _handleInvalidNumberStart(int ch, boolean negative) throws IOException, JsonParseException {
double d = Double.NEGATIVE_INFINITY;
if (ch == 73) {
if (this._inputPtr >= this._inputEnd && !loadMore()) {
_reportInvalidEOFInValue();
}
byte[] bArr = this._inputBuffer;
int i = this._inputPtr;
this._inputPtr = i + 1;
ch = bArr[i];
String match;
if (ch == 78) {
match = negative ? "-INF" : "+INF";
_matchToken(match, 3);
if (isEnabled(Feature.ALLOW_NON_NUMERIC_NUMBERS)) {
if (!negative) {
d = Double.POSITIVE_INFINITY;
}
return resetAsNaN(match, d);
}
_reportError("Non-standard token '" + match + "': enable JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS to allow");
} else if (ch == Constants.BILLING_ERROR_OTHER_ERROR) {
match = negative ? "-Infinity" : "+Infinity";
_matchToken(match, 3);
if (isEnabled(Feature.ALLOW_NON_NUMERIC_NUMBERS)) {
if (!negative) {
d = Double.POSITIVE_INFINITY;
}
return resetAsNaN(match, d);
}
_reportError("Non-standard token '" + match + "': enable JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS to allow");
}
}
reportUnexpectedNumberChar(ch, "expected digit (0-9) to follow minus sign, for valid numeric value");
return null;
}
protected final void _matchToken(String matchStr, int i) throws IOException, JsonParseException {
int len = matchStr.length();
do {
if (this._inputPtr >= this._inputEnd && !loadMore()) {
_reportInvalidEOF(" in a value");
}
if (this._inputBuffer[this._inputPtr] != matchStr.charAt(i)) {
_reportInvalidToken(matchStr.substring(0, i), "'null', 'true', 'false' or NaN");
}
this._inputPtr++;
i++;
} while (i < len);
if (this._inputPtr < this._inputEnd || loadMore()) {
int ch = this._inputBuffer[this._inputPtr] & 255;
if (ch >= 48 && ch != 93 && ch != ParseException.INVALID_EMAIL_ADDRESS && Character.isJavaIdentifierPart((char) _decodeCharForError(ch))) {
this._inputPtr++;
_reportInvalidToken(matchStr.substring(0, i), "'null', 'true', 'false' or NaN");
}
}
}
protected void _reportInvalidToken(String matchedPart, String msg) throws IOException, JsonParseException {
StringBuilder sb = new StringBuilder(matchedPart);
while (true) {
if (this._inputPtr >= this._inputEnd && !loadMore()) {
break;
}
byte[] bArr = this._inputBuffer;
int i = this._inputPtr;
this._inputPtr = i + 1;
char c = (char) _decodeCharForError(bArr[i]);
if (!Character.isJavaIdentifierPart(c)) {
break;
}
sb.append(c);
}
_reportError("Unrecognized token '" + sb.toString() + "': was expecting " + msg);
}
private final int _skipWS() throws IOException, JsonParseException {
while (true) {
if (this._inputPtr < this._inputEnd || loadMore()) {
byte[] bArr = this._inputBuffer;
int i = this._inputPtr;
this._inputPtr = i + 1;
int i2 = bArr[i] & 255;
if (i2 > 32) {
if (i2 != 47) {
return i2;
}
_skipComment();
} else if (i2 != 32) {
if (i2 == 10) {
_skipLF();
} else if (i2 == 13) {
_skipCR();
} else if (i2 != 9) {
_throwInvalidSpace(i2);
}
}
} else {
throw _constructError("Unexpected end-of-input within/between " + this._parsingContext.getTypeDesc() + " entries");
}
}
}
private final int _skipWSOrEnd() throws IOException, JsonParseException {
while (true) {
if (this._inputPtr < this._inputEnd || loadMore()) {
byte[] bArr = this._inputBuffer;
int i = this._inputPtr;
this._inputPtr = i + 1;
int i2 = bArr[i] & 255;
if (i2 > 32) {
if (i2 != 47) {
return i2;
}
_skipComment();
} else if (i2 != 32) {
if (i2 == 10) {
_skipLF();
} else if (i2 == 13) {
_skipCR();
} else if (i2 != 9) {
_throwInvalidSpace(i2);
}
}
} else {
_handleEOF();
return -1;
}
}
}
private final int _skipColon() throws IOException, JsonParseException {
if (this._inputPtr >= this._inputEnd) {
loadMoreGuaranteed();
}
byte[] bArr = this._inputBuffer;
int i = this._inputPtr;
this._inputPtr = i + 1;
int i2 = bArr[i];
if (i2 != 58) {
i2 &= 255;
while (true) {
switch (i2) {
case 9:
case 32:
break;
case 10:
_skipLF();
break;
case 13:
_skipCR();
break;
case 47:
_skipComment();
break;
default:
if (i2 < 32) {
_throwInvalidSpace(i2);
}
if (i2 != 58) {
_reportUnexpectedChar(i2, "was expecting a colon to separate field name and value");
break;
}
break;
}
if (this._inputPtr >= this._inputEnd) {
loadMoreGuaranteed();
}
bArr = this._inputBuffer;
i = this._inputPtr;
this._inputPtr = i + 1;
i2 = bArr[i] & 255;
}
} else if (this._inputPtr < this._inputEnd) {
i2 = this._inputBuffer[this._inputPtr] & 255;
if (i2 > 32 && i2 != 47) {
this._inputPtr++;
return i2;
}
}
while (true) {
if (this._inputPtr < this._inputEnd || loadMore()) {
bArr = this._inputBuffer;
i = this._inputPtr;
this._inputPtr = i + 1;
i2 = bArr[i] & 255;
if (i2 > 32) {
if (i2 != 47) {
return i2;
}
_skipComment();
} else if (i2 != 32) {
if (i2 == 10) {
_skipLF();
} else if (i2 == 13) {
_skipCR();
} else if (i2 != 9) {
_throwInvalidSpace(i2);
}
}
} else {
throw _constructError("Unexpected end-of-input within/between " + this._parsingContext.getTypeDesc() + " entries");
}
}
}
private final void _skipComment() throws IOException, JsonParseException {
if (!isEnabled(Feature.ALLOW_COMMENTS)) {
_reportUnexpectedChar(47, "maybe a (non-standard) comment? (not recognized as one since Feature 'ALLOW_COMMENTS' not enabled for parser)");
}
if (this._inputPtr >= this._inputEnd && !loadMore()) {
_reportInvalidEOF(" in a comment");
}
byte[] bArr = this._inputBuffer;
int i = this._inputPtr;
this._inputPtr = i + 1;
int c = bArr[i] & 255;
if (c == 47) {
_skipCppComment();
} else if (c == 42) {
_skipCComment();
} else {
_reportUnexpectedChar(c, "was expecting either '*' or '/' for a comment");
}
}
private final void _skipCComment() throws IOException, JsonParseException {
int[] codes = CharTypes.getInputCodeComment();
while (true) {
if (this._inputPtr < this._inputEnd || loadMore()) {
byte[] bArr = this._inputBuffer;
int i = this._inputPtr;
this._inputPtr = i + 1;
int i2 = bArr[i] & 255;
int code = codes[i2];
if (code != 0) {
switch (code) {
case 2:
_skipUtf8_2(i2);
continue;
case 3:
_skipUtf8_3(i2);
continue;
case 4:
_skipUtf8_4(i2);
continue;
case 10:
_skipLF();
continue;
case 13:
_skipCR();
continue;
case 42:
if (this._inputPtr >= this._inputEnd && !loadMore()) {
break;
} else if (this._inputBuffer[this._inputPtr] == (byte) 47) {
this._inputPtr++;
return;
} else {
continue;
}
default:
_reportInvalidChar(i2);
continue;
}
}
}
_reportInvalidEOF(" in a comment");
return;
}
}
private final void _skipCppComment() throws IOException, JsonParseException {
int[] codes = CharTypes.getInputCodeComment();
while (true) {
if (this._inputPtr < this._inputEnd || loadMore()) {
byte[] bArr = this._inputBuffer;
int i = this._inputPtr;
this._inputPtr = i + 1;
int i2 = bArr[i] & 255;
int code = codes[i2];
if (code != 0) {
switch (code) {
case 2:
_skipUtf8_2(i2);
break;
case 3:
_skipUtf8_3(i2);
break;
case 4:
_skipUtf8_4(i2);
break;
case 10:
_skipLF();
return;
case 13:
_skipCR();
return;
case 42:
break;
default:
_reportInvalidChar(i2);
break;
}
}
} else {
return;
}
}
}
protected final char _decodeEscaped() throws IOException, JsonParseException {
if (this._inputPtr >= this._inputEnd && !loadMore()) {
_reportInvalidEOF(" in character escape sequence");
}
byte[] bArr = this._inputBuffer;
int i = this._inputPtr;
this._inputPtr = i + 1;
int c = bArr[i];
switch (c) {
case 34:
case 47:
case 92:
return (char) c;
case 98:
return '\b';
case 102:
return '\f';
case Constants.BILLING_ERROR_OTHER_ERROR /*110*/:
return '\n';
case 114:
return '\r';
case ParseException.OBJECT_TOO_LARGE /*116*/:
return '\t';
case 117:
int value = 0;
for (int i2 = 0; i2 < 4; i2++) {
if (this._inputPtr >= this._inputEnd && !loadMore()) {
_reportInvalidEOF(" in character escape sequence");
}
bArr = this._inputBuffer;
i = this._inputPtr;
this._inputPtr = i + 1;
int ch = bArr[i];
int digit = CharTypes.charToHex(ch);
if (digit < 0) {
_reportUnexpectedChar(ch, "expected a hex-digit for character escape sequence");
}
value = (value << 4) | digit;
}
return (char) value;
default:
return _handleUnrecognizedCharacterEscape((char) _decodeCharForError(c));
}
}
protected int _decodeCharForError(int firstByte) throws IOException, JsonParseException {
int c = firstByte;
if (c >= 0) {
return c;
}
int needed;
if ((c & 224) == 192) {
c &= 31;
needed = 1;
} else if ((c & 240) == 224) {
c &= 15;
needed = 2;
} else if ((c & 248) == 240) {
c &= 7;
needed = 3;
} else {
_reportInvalidInitial(c & 255);
needed = 1;
}
int d = nextByte();
if ((d & 192) != 128) {
_reportInvalidOther(d & 255);
}
c = (c << 6) | (d & 63);
if (needed <= 1) {
return c;
}
d = nextByte();
if ((d & 192) != 128) {
_reportInvalidOther(d & 255);
}
c = (c << 6) | (d & 63);
if (needed <= 2) {
return c;
}
d = nextByte();
if ((d & 192) != 128) {
_reportInvalidOther(d & 255);
}
return (c << 6) | (d & 63);
}
private final int _decodeUtf8_2(int c) throws IOException, JsonParseException {
if (this._inputPtr >= this._inputEnd) {
loadMoreGuaranteed();
}
byte[] bArr = this._inputBuffer;
int i = this._inputPtr;
this._inputPtr = i + 1;
int d = bArr[i];
if ((d & 192) != 128) {
_reportInvalidOther(d & 255, this._inputPtr);
}
return ((c & 31) << 6) | (d & 63);
}
private final int _decodeUtf8_3(int c1) throws IOException, JsonParseException {
if (this._inputPtr >= this._inputEnd) {
loadMoreGuaranteed();
}
c1 &= 15;
byte[] bArr = this._inputBuffer;
int i = this._inputPtr;
this._inputPtr = i + 1;
int d = bArr[i];
if ((d & 192) != 128) {
_reportInvalidOther(d & 255, this._inputPtr);
}
int c = (c1 << 6) | (d & 63);
if (this._inputPtr >= this._inputEnd) {
loadMoreGuaranteed();
}
bArr = this._inputBuffer;
i = this._inputPtr;
this._inputPtr = i + 1;
d = bArr[i];
if ((d & 192) != 128) {
_reportInvalidOther(d & 255, this._inputPtr);
}
return (c << 6) | (d & 63);
}
private final int _decodeUtf8_3fast(int c1) throws IOException, JsonParseException {
c1 &= 15;
byte[] bArr = this._inputBuffer;
int i = this._inputPtr;
this._inputPtr = i + 1;
int d = bArr[i];
if ((d & 192) != 128) {
_reportInvalidOther(d & 255, this._inputPtr);
}
int c = (c1 << 6) | (d & 63);
bArr = this._inputBuffer;
i = this._inputPtr;
this._inputPtr = i + 1;
d = bArr[i];
if ((d & 192) != 128) {
_reportInvalidOther(d & 255, this._inputPtr);
}
return (c << 6) | (d & 63);
}
private final int _decodeUtf8_4(int c) throws IOException, JsonParseException {
if (this._inputPtr >= this._inputEnd) {
loadMoreGuaranteed();
}
byte[] bArr = this._inputBuffer;
int i = this._inputPtr;
this._inputPtr = i + 1;
int d = bArr[i];
if ((d & 192) != 128) {
_reportInvalidOther(d & 255, this._inputPtr);
}
c = ((c & 7) << 6) | (d & 63);
if (this._inputPtr >= this._inputEnd) {
loadMoreGuaranteed();
}
bArr = this._inputBuffer;
i = this._inputPtr;
this._inputPtr = i + 1;
d = bArr[i];
if ((d & 192) != 128) {
_reportInvalidOther(d & 255, this._inputPtr);
}
c = (c << 6) | (d & 63);
if (this._inputPtr >= this._inputEnd) {
loadMoreGuaranteed();
}
bArr = this._inputBuffer;
i = this._inputPtr;
this._inputPtr = i + 1;
d = bArr[i];
if ((d & 192) != 128) {
_reportInvalidOther(d & 255, this._inputPtr);
}
return ((c << 6) | (d & 63)) - 65536;
}
private final void _skipUtf8_2(int c) throws IOException, JsonParseException {
if (this._inputPtr >= this._inputEnd) {
loadMoreGuaranteed();
}
byte[] bArr = this._inputBuffer;
int i = this._inputPtr;
this._inputPtr = i + 1;
c = bArr[i];
if ((c & 192) != 128) {
_reportInvalidOther(c & 255, this._inputPtr);
}
}
private final void _skipUtf8_3(int c) throws IOException, JsonParseException {
if (this._inputPtr >= this._inputEnd) {
loadMoreGuaranteed();
}
byte[] bArr = this._inputBuffer;
int i = this._inputPtr;
this._inputPtr = i + 1;
c = bArr[i];
if ((c & 192) != 128) {
_reportInvalidOther(c & 255, this._inputPtr);
}
if (this._inputPtr >= this._inputEnd) {
loadMoreGuaranteed();
}
bArr = this._inputBuffer;
i = this._inputPtr;
this._inputPtr = i + 1;
c = bArr[i];
if ((c & 192) != 128) {
_reportInvalidOther(c & 255, this._inputPtr);
}
}
private final void _skipUtf8_4(int c) throws IOException, JsonParseException {
if (this._inputPtr >= this._inputEnd) {
loadMoreGuaranteed();
}
byte[] bArr = this._inputBuffer;
int i = this._inputPtr;
this._inputPtr = i + 1;
int d = bArr[i];
if ((d & 192) != 128) {
_reportInvalidOther(d & 255, this._inputPtr);
}
if (this._inputPtr >= this._inputEnd) {
loadMoreGuaranteed();
}
bArr = this._inputBuffer;
i = this._inputPtr;
this._inputPtr = i + 1;
d = bArr[i];
if ((d & 192) != 128) {
_reportInvalidOther(d & 255, this._inputPtr);
}
if (this._inputPtr >= this._inputEnd) {
loadMoreGuaranteed();
}
bArr = this._inputBuffer;
i = this._inputPtr;
this._inputPtr = i + 1;
d = bArr[i];
if ((d & 192) != 128) {
_reportInvalidOther(d & 255, this._inputPtr);
}
}
protected final void _skipCR() throws IOException {
if ((this._inputPtr < this._inputEnd || loadMore()) && this._inputBuffer[this._inputPtr] == BYTE_LF) {
this._inputPtr++;
}
this._currInputRow++;
this._currInputRowStart = this._inputPtr;
}
protected final void _skipLF() throws IOException {
this._currInputRow++;
this._currInputRowStart = this._inputPtr;
}
private int nextByte() throws IOException, JsonParseException {
if (this._inputPtr >= this._inputEnd) {
loadMoreGuaranteed();
}
byte[] bArr = this._inputBuffer;
int i = this._inputPtr;
this._inputPtr = i + 1;
return bArr[i] & 255;
}
protected void _reportInvalidChar(int c) throws JsonParseException {
if (c < 32) {
_throwInvalidSpace(c);
}
_reportInvalidInitial(c);
}
protected void _reportInvalidInitial(int mask) throws JsonParseException {
_reportError("Invalid UTF-8 start byte 0x" + Integer.toHexString(mask));
}
protected void _reportInvalidOther(int mask) throws JsonParseException {
_reportError("Invalid UTF-8 middle byte 0x" + Integer.toHexString(mask));
}
protected void _reportInvalidOther(int mask, int ptr) throws JsonParseException {
this._inputPtr = ptr;
_reportInvalidOther(mask);
}
public static int[] growArrayBy(int[] arr, int more) {
if (arr == null) {
return new int[more];
}
int[] old = arr;
int len = arr.length;
arr = new int[(len + more)];
System.arraycopy(old, 0, arr, 0, len);
return arr;
}
protected byte[] _decodeBase64(Base64Variant b64variant) throws IOException, JsonParseException {
ByteArrayBuilder builder = _getByteArrayBuilder();
while (true) {
if (this._inputPtr >= this._inputEnd) {
loadMoreGuaranteed();
}
byte[] bArr = this._inputBuffer;
int i = this._inputPtr;
this._inputPtr = i + 1;
int ch = bArr[i] & 255;
if (ch > 32) {
int bits = b64variant.decodeBase64Char(ch);
if (bits < 0) {
if (ch == 34) {
return builder.toByteArray();
}
bits = _decodeBase64Escape(b64variant, ch, 0);
if (bits < 0) {
continue;
}
}
int decodedData = bits;
if (this._inputPtr >= this._inputEnd) {
loadMoreGuaranteed();
}
bArr = this._inputBuffer;
i = this._inputPtr;
this._inputPtr = i + 1;
ch = bArr[i] & 255;
bits = b64variant.decodeBase64Char(ch);
if (bits < 0) {
bits = _decodeBase64Escape(b64variant, ch, 1);
}
decodedData = (decodedData << 6) | bits;
if (this._inputPtr >= this._inputEnd) {
loadMoreGuaranteed();
}
bArr = this._inputBuffer;
i = this._inputPtr;
this._inputPtr = i + 1;
ch = bArr[i] & 255;
bits = b64variant.decodeBase64Char(ch);
if (bits < 0) {
if (bits != -2) {
if (ch != 34 || b64variant.usesPadding()) {
bits = _decodeBase64Escape(b64variant, ch, 2);
} else {
builder.append(decodedData >> 4);
return builder.toByteArray();
}
}
if (bits == -2) {
if (this._inputPtr >= this._inputEnd) {
loadMoreGuaranteed();
}
bArr = this._inputBuffer;
i = this._inputPtr;
this._inputPtr = i + 1;
ch = bArr[i] & 255;
if (b64variant.usesPaddingChar(ch)) {
builder.append(decodedData >> 4);
} else {
throw reportInvalidBase64Char(b64variant, ch, 3, "expected padding character '" + b64variant.getPaddingChar() + "'");
}
}
}
decodedData = (decodedData << 6) | bits;
if (this._inputPtr >= this._inputEnd) {
loadMoreGuaranteed();
}
bArr = this._inputBuffer;
i = this._inputPtr;
this._inputPtr = i + 1;
ch = bArr[i] & 255;
bits = b64variant.decodeBase64Char(ch);
if (bits < 0) {
if (bits != -2) {
if (ch != 34 || b64variant.usesPadding()) {
bits = _decodeBase64Escape(b64variant, ch, 3);
} else {
builder.appendTwoBytes(decodedData >> 2);
return builder.toByteArray();
}
}
if (bits == -2) {
builder.appendTwoBytes(decodedData >> 2);
}
}
builder.appendThreeBytes((decodedData << 6) | bits);
}
}
}
}
| true |
ca2539f36f552596354b2e09d29a72c2bedfbb16 | Java | mak-spectrum/profwell | /course/app/org/profwell/vacancy/model/HookupPersonLink.java | UTF-8 | 1,832 | 2.140625 | 2 | [] | no_license | package org.profwell.vacancy.model;
import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.profwell.generic.model.Identifiable;
import org.profwell.person.model.Person;
import org.profwell.security.model.Workspace;
@Entity
@Table(name = "HOOKUP_PERSON_LINK")
@Access(AccessType.FIELD)
public class HookupPersonLink implements Identifiable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="ID", nullable = false)
private long id = DEFAULT_UNINITIALIZED_ID_VALUE;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "PERSON_ID",
referencedColumnName = "ID",
nullable = false)
private Person person;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "WORKSPACE_ID",
referencedColumnName = "ID",
nullable = false)
private Workspace workspace;
@Override
public boolean isNew() {
return this.id == DEFAULT_UNINITIALIZED_ID_VALUE;
}
@Override
public long getId() {
return this.id;
}
public void setId(long id) {
this.id = id;
}
public Person getPerson() {
return this.person;
}
public void setPerson(Person person) {
this.person = person;
}
public Workspace getWorkspace() {
return this.workspace;
}
public void setWorkspace(Workspace workspace) {
this.workspace = workspace;
}
}
| true |
3156eccb8d8f928015906f7ad127ef419eda7033 | Java | patricsteiner/efalg | /hw1/KnightsTour/src/ch/fhnw/edu/efalg/chessboard/ChessBoard.java | UTF-8 | 1,124 | 3.28125 | 3 | [] | no_license | package ch.fhnw.edu.efalg.chessboard;
/**
* Represents a chessboard. In this case it is not just a regular 8x8 chessboard but a board with many different sizes.
*
* @author Martin Schaub
*/
public interface ChessBoard {
/**
* Sets a new status to a field at the specified location.
*
* @param position the location of the field
* @param status field status.
*/
void setField(Position position, Field status);
/**
* Gets the field content from the specified location.
*
* @param position the location of the field
* @return field status
*/
Field getField(Position position);
/**
* Returns the number of rows.
*
* @return number of rows
*/
int getNumOfRows();
/**
* Returns the number of columns.
*
* @return number of columns
*/
int getNumOfColumns();
/**
* Registers a new listener
*
* @param listener listener to add
*/
void addChessBoardListener(ChessBoardListener listener);
/**
* Removes a listener from the list of notified listeners.
*
* @param listener listener to deregister
*/
void removeChessBoardListener(ChessBoardListener listener);
}
| true |
2882cfd9cbbe0a2ffd698a0f94b51c5c6f503213 | Java | HealerJean/common-arith | /src/main/java/com/hlj/arith/demo00027_整数转罗马数字/整数转罗马数字.java | UTF-8 | 1,639 | 3.84375 | 4 | [] | no_license | package com.hlj.arith.demo00027_整数转罗马数字;
import org.junit.Test;
/**
* @author HealerJean
* @ClassName 整数转罗马数字
* @date 2020/2/25 12:27.
* @Description
*/
/**
作者:HealerJean
题目:整数转罗马数字
解题思路: 找规律
复杂度:
时间复杂度:O(1),虽然看起来是两层循环,但是外层循环的次数是有限制的,因为数字最大才3999,内层循环的此时其实也是有限次的
空间复杂度:O(1),这里使用了两个辅助数字,空间都为 1313,还有常数个变量
*/
public class 整数转罗马数字 {
@Test
public void test(){
System.out.println(intToRoman(11));
}
public String intToRoman(int num) {
// 把阿拉伯数字与罗马数字可能出现的所有情况和对应关系,放在两个数组中,按照阿拉伯数字的大小降序排列,因为我们要尽可能的做减法
int[] nums = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
String[] romans = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
int length = nums.length;
StringBuilder stringBuilder = new StringBuilder();
int index = 0;
while (index < length) {
// 这里是等号,这样就保证了那种特殊的数字
while (num >= nums[index]) {
// 注意:这里是等于号,表示尽量使用大的"面值"
stringBuilder.append(romans[index]);
num = num - nums[index];
}
index++;
}
return stringBuilder.toString();
}
}
| true |
7d851c7979279a1bcb00d3abbbedae338b9f4406 | Java | amandahaha/Learn_Api | /app/src/main/java/com/example/amandachen/vg_api/GroupsGson.java | UTF-8 | 276 | 1.640625 | 2 | [] | no_license | package com.example.amandachen.vg_api;
import java.util.ArrayList;
/**
* Created by amandachen on 11/03/2018.
*/
public class GroupsGson {
public ArrayList groups = new ArrayList<>();
public class Groups{
public int url;
public int name;
}
}
| true |
383e10aee6582b57e8d5c04f7249d2068937d8a9 | Java | uTernity/MyRoute | /src/main/java/de/uternity/myroute/creator/streams/HighwayReader.java | UTF-8 | 2,318 | 2.734375 | 3 | [] | no_license | package de.uternity.myroute.creator.streams;
import de.uternity.myroute.creator.classes.Highway;
import de.uternity.myroute.creator.classes.Node;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class HighwayReader implements Iterable<Highway>
{
private DataInputStream in;
private String path, sig, format;
private int version;
public HighwayReader(String path) throws IOException
{
this.in = new DataInputStream(new BufferedInputStream(getClass().getClassLoader().getResourceAsStream(path)));
this.path = path;
readHeader();
}
private void readHeader() throws IOException
{
byte[] data = new byte[4];
in.readFully(data);
sig = new String(data, "ISO-8859-1");
in.readFully(data);
format = new String(data, "ISO-8859-1");
version = in.readByte();
}
public void close() throws IOException
{
in.close();
}
@Override
public Iterator<Highway> iterator()
{
return new Iterator<Highway>()
{
@Override
public void remove()
{}
@Override
public boolean hasNext()
{
if (!sig.equals("UTR!") || !format.equals("EXHW"))
{
System.err.println("Input file is not a valid highway file");
return false;
}
try
{
if (in.available() >= 43)
return true;
}
catch (IOException e)
{
e.printStackTrace();
}
return false;
}
@Override
public Highway next()
{
Highway highway = new Highway();
try
{
highway.setId(in.readLong());
List<Node> nodes = new ArrayList<>();
short size = in.readShort();
for (short i = 0; i < size; i++)
{
Node node = new Node();
node.setId(in.readLong());
node.setLat(in.readDouble());
node.setLon(in.readDouble());
nodes.add(node);
}
highway.setWayNodes(nodes);
//highwayEntry.setType(in.readByte());
highway.setLength(in.readDouble());
//highwayEntry.setOneWay(in.readByte());
byte[] tags = new byte[in.readShort()];
in.readFully(tags);
highway.setTags(tags);
}
catch (IOException e)
{
e.printStackTrace();
}
return highway;
}
};
}
} | true |
1370240bc912ab0ff999281a37c7dd9da4e3a51d | Java | venkatakrishnan-srinivasaraj/Library-Management | /src/main/java/com/venkatakrishnans/cs6360/librarymanagement/service/BookCheckoutService.java | UTF-8 | 580 | 2.234375 | 2 | [] | no_license | package com.venkatakrishnans.cs6360.librarymanagement.service;
import com.venkatakrishnans.cs6360.librarymanagement.domain.Book;
import com.venkatakrishnans.cs6360.librarymanagement.domain.Borrower;
import com.venkatakrishnans.cs6360.librarymanagement.exception.BookAlreadyCheckedOutException;
import com.venkatakrishnans.cs6360.librarymanagement.exception.MaximumCheckoutLimitReachedException;
public interface BookCheckoutService {
void checkoutBookForBorrower(Book book, Borrower borrower) throws BookAlreadyCheckedOutException, MaximumCheckoutLimitReachedException;
}
| true |
3d8effa89b9f3cfe23180e348546a93bf7d6b6d6 | Java | baiyu7297/MyAndroidDemo | /app/src/main/java/com/fantasy/android/demo/java/MyOOTest.java | UTF-8 | 822 | 3.046875 | 3 | [] | no_license | package com.fantasy.android.demo.java;
public class MyOOTest {
private static class A {
protected void print() {
System.out.println("A");
}
public static void haha() {
System.out.println("hahaAAAA");
}
}
private static class B extends A{
@Override
protected void print() {
System.out.println("B");
}
public static void haha() {
System.out.println("hahaBBBB");
}
public static void xixi() {
System.out.println("xixi");
}
}
public static void main(String args[]) {
B b = new B();
b.print();
((A)b).print();
A a = new B();
a.print();
//a.xixi();
b.haha();
((A)b).haha();
}
}
| true |
890944c1d69c37f9e63cdad95087bd1d692f440d | Java | srikanthkakumanu/JavaPro | /src/main/java/com/srikanth/jdp/cp/SingletonDemo.java | UTF-8 | 955 | 3.203125 | 3 | [] | no_license | package com.srikanth.jdp.cp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created with IntelliJ IDEA.
* User: Srikanth
* Date: 11/4/13
* Time: 12:12 PM
* To change this template use File | Settings | File Templates.
*/
public class SingletonDemo {
/**
* It ensures that only one instance of a class is created and provides global access point to the object.
*/
/**
*
*/
private SingletonDemo() {
}
public static void main(String... args) {
Singleton singleton = Singleton.getInstance();
singleton.sayHello();
}
}
class Singleton {
private static Logger logger = LoggerFactory.getLogger(Singleton.class);
private static Singleton instance = null;
public static Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
}
return instance;
}
public void sayHello() {
logger.info("Hello.!!!");
}
}
| true |
58b71c4a560f694b05f6184ea17b69fdac47c550 | Java | srishti9419/AutomationRepo | /SeleniumProject/src/basicSelenium/CaptureScreenshot.java | UTF-8 | 993 | 2.4375 | 2 | [] | no_license | package basicSelenium;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.io.FileHandler;
import org.testng.annotations.Test;
public class CaptureScreenshot {
@Test
public void test1() throws IOException
{
System.setProperty("webdriver.chrome.driver","D:\\Drivers\\chromedriver.exe");
ChromeDriver dr=new ChromeDriver();
dr.manage().window().maximize();
dr.manage().timeouts().implicitlyWait(5,TimeUnit.SECONDS);
dr.get("https://www.flipkart.com");
String path="D:\\AutomationRepo\\SeleniumProject\\src\\basicSelenium\\test1.jpg";
TakesScreenshot scrshot= (TakesScreenshot) dr;
File scrfile=scrshot.getScreenshotAs(OutputType.FILE);
File desFile=new File(path);
FileHandler.copy(scrfile, desFile);
}
}
| true |
fa81f7b67747014e75a8d774866e10a5633eeb21 | Java | 16130586/AgileManagement | /backend/src/main/java/nlu/project/backend/middleware/AuthenticationEntryPointHandleException.java | UTF-8 | 883 | 2.421875 | 2 | [] | no_license | package nlu.project.backend.middleware;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class AuthenticationEntryPointHandleException implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
try{
response.setStatus(401);
response.getWriter().println("Unauthorised!");
response.flushBuffer();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e){
throw e;
}
}
}
| true |
8ba7b73bc6d78569683069ad797164a5e9f5df5e | Java | pvvnarayana/teachme | /SpringBootJPA/src/main/java/com/tm/sb/jpa/model/Product.java | UTF-8 | 848 | 2.390625 | 2 | [] | no_license | package com.tm.sb.jpa.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="product")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private int code;
private int price;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
} | true |
29908984b6b8cb4eedbbd49447bfb9b0d40a7424 | Java | ggiorkhelidze/xs2a | /consent-management/consent-management-lib/src/test/java/de/adorsys/psd2/consent/service/security/MockCryptoProvider.java | UTF-8 | 1,829 | 2.140625 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2018-2018 adorsys GmbH & Co KG
*
* 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 de.adorsys.psd2.consent.service.security;
import de.adorsys.psd2.consent.service.security.provider.CryptoProvider;
import org.apache.commons.lang3.StringUtils;
import java.util.Optional;
public class MockCryptoProvider implements CryptoProvider {
private final boolean alwaysFail;
private final String cryptoProviderId;
MockCryptoProvider(String cryptoProviderId, boolean alwaysFail) {
this.alwaysFail = alwaysFail;
this.cryptoProviderId = cryptoProviderId;
}
@Override
public Optional<EncryptedData> encryptData(byte[] data, String password) {
if (alwaysFail) {
return Optional.empty();
}
String encrypted = new String(data) + password;
return Optional.of(new EncryptedData(encrypted.getBytes()));
}
@Override
public Optional<DecryptedData> decryptData(byte[] data, String password) {
if (alwaysFail) {
return Optional.empty();
}
String decrypted = StringUtils.removeEnd(new String(data), password);
return Optional.of(new DecryptedData(decrypted.getBytes()));
}
@Override
public String getCryptoProviderId() {
return cryptoProviderId;
}
}
| true |
00e01c528d9e5e113f1d970efacce86ffb3268ed | Java | hrkk/Android-TimeReg | /TimeReg/app/src/main/java/timereg/roninit/dk/timereg/MainActivityFragment.java | UTF-8 | 1,972 | 1.867188 | 2 | [] | no_license | package timereg.roninit.dk.timereg;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Build;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
/**
* A placeholder fragment containing a simple view.
*/
public class MainActivityFragment extends Fragment {
Calendar selectedDate;
List<TimeRegTask> taskList;
ArrayAdapter<TimeRegTask> arrayAdapter;
public MainActivityFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// setDate(date, DateUtil.getFormattedDate(selectedDate));
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
// EditText date = (EditText) rootView.findViewById(R.id.date);
//
// if (selectedDate == null) {
// selectedDate = Calendar.getInstance();
// }
//
// setDate(date, DateUtil.getFormattedDate(selectedDate));
//
// taskList = Globals.getInstance().getTaskMap().get(DateUtil.getFormattedDate(selectedDate));
// ListView listView = (ListView) rootView.findViewById(R.id.listView);
// // sets op task list
// arrayAdapter
// = new ArrayAdapter<TimeRegTask>(
// rootView.getContext(),
// android.R.layout.simple_list_item_1,
// taskList);
//
// listView.setAdapter(arrayAdapter);
return rootView;
}
}
| true |
08ae1ff01da139f26f1a28affc898b78ce8d2acf | Java | tracyhenryduck2/siterLink_android | /branches/siterlink/app/src/main/java/com/siterwell/application/MyApplication.java | UTF-8 | 3,636 | 1.890625 | 2 | [] | no_license | package com.siterwell.application;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.os.Bundle;
import android.os.Process;
import android.support.multidex.MultiDexApplication;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.siterwell.application.common.CrashHandler;
import com.siterwell.sdk.common.SitewellSDK;
import com.xiaomi.mipush.sdk.MiPushClient;
import java.util.List;
import me.hekr.sdk.HekrSDK;
/**
* Created by hekr_jds on 6/30 0030.
**/
public class MyApplication extends MultiDexApplication {
private static MyApplication mApp;
public static Activity sActivity;
// user your appid the key.
private static final String APP_ID = "2882303761517683139";
// user your appid the key.
private static final String APP_KEY = "5251768341139";
@Override
public void onCreate() {
super.onCreate();
mApp = this;
// 可以从DemoMessageReceiver的onCommandResult方法中MiPushCommandMessage对象参数中获取注册信息
if (shouldInit()) {
MiPushClient.registerPush(this, APP_ID, APP_KEY);
}
//推送服务初始化
// PushManager.getInstance().initialize(getApplicationContext());
//初始化HekrSDK
HekrSDK.init(getApplicationContext(), R.raw.config);
HekrSDK.enableDebug(true);
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
.memoryCacheExtraOptions(80, 80)
.denyCacheImageMultipleSizesInMemory()
//.writeDebugLogs()
.tasksProcessingOrder(QueueProcessingType.LIFO)
.build();
ImageLoader.getInstance().init(config);
this.registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
@Override
public void onActivityStarted(Activity activity) {
sActivity=activity;
}
@Override
public void onActivityResumed(Activity activity) {
}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivityStopped(Activity activity) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
});
SitewellSDK.getInstance(this).init();
CrashHandler.getInstance().init(getApplicationContext());
}
public static Context getAppContext() {
return mApp;
}
public static Activity getActivity(){
return sActivity;
}
private boolean shouldInit() {
ActivityManager am = ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE));
List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
String mainProcessName = getPackageName();
int myPid = Process.myPid();
for (ActivityManager.RunningAppProcessInfo info : processInfos) {
if (info.pid == myPid && mainProcessName.equals(info.processName)) {
return true;
}
}
return false;
}
}
| true |
61cacf3f54a7a8365e3996fc3adbb1a897a6e702 | Java | iddi/sofia | /eu.sofia.sib_2.0.5/src/eu/sofia/adk/sib/model/query/SOFIAResultSet.java | UTF-8 | 7,407 | 2 | 2 | [] | no_license | /*******************************************************************************
* Copyright (c) 2009,2011 Tecnalia Research and Innovation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Raul Otaolea (Tecnalia Research and Innovation - Software Systems Engineering) - initial API, implementation and documentation
* Fran Ruiz (Tecnalia Research and Innovation - Software Systems Engineering) - initial API, implementation and documentation
*******************************************************************************/
package eu.sofia.adk.sib.model.query;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.sparql.engine.binding.Binding;
/**
* This class is responsible for containing the result set obtained
* after executing a query.
*
* @author Fran Ruiz, fran.ruiz@tecnalia.com, ESI
* @author Raul Otaolea, raul.otaolea@tecnalia.com, ESI
*
*/
public class SOFIAResultSet implements ResultSet {
/** The collection of solutions */
private Collection<QuerySolution> solutions = new ArrayList<QuerySolution>();
/** The collection of solutions */
private Iterator<QuerySolution> iterator = null;
private int rowNumber = 0;
private Model model;
private List<String> varNames = new ArrayList<String>();
/**
* The constructor
* @param results the list of QuerySolutions
*/
public SOFIAResultSet(ResultSet results) {
try {
if (results != null) {
model = results.getResourceModel();
while (results.hasNext()) {
QuerySolution sol = results.next();
solutions.add(sol);
}
iterator = solutions.iterator();
varNames = results.getResultVars();
} else {
model = null;
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Adds a solution to the model
* @param solution a QuerySolution containing a single result
* @return <code>true</code> if it is successfully added
*/
public boolean add(QuerySolution solution) {
boolean added = solutions.add(solution);
rowNumber = 0;
iterator = solutions.iterator();
return added;
}
/**
* Removes a solution from the model
* @param solution a QuerySolution containing a single result
* @return <code>true</code> if it is successfully added
*/
public boolean remove(QuerySolution solution) {
boolean removed = solutions.remove(solution);
rowNumber = 0;
iterator = solutions.iterator();
return removed;
}
/**
* Move back to the start of the iterator for this instance of results of a query.
*/
public void reset() {
iterator = solutions.iterator();
rowNumber = 0;
}
/**
* Return the number of solutions
*/
public int size() {
return solutions.size();
}
/**
* Gets the query solutions
* @return the set of solutions
*/
public Collection<QuerySolution> getQuerySolutions() {
return solutions;
}
/**
* Gets the query solutions
* @return the set of solutions
*/
private Collection<String> getVarNames() {
return varNames;
}
/**
* Sets the var names
* @param varNames the var names
*/
private void setVarNames(Collection<String> varNames) {
this.varNames.addAll(varNames);
}
/**
* Gets the model associated to this result set
* @return the JENA model
* @see Model
*/
@Override
public Model getResourceModel() {
return model;
}
/**
* Gets the result var names
* @return a list of string with the var names
*/
@Override
public List<String> getResultVars() {
return varNames;
}
/**
* Gets the row number
* @return the row number
*/
@Override
public int getRowNumber() {
return rowNumber;
}
/**
* Determines if there are more solutions
* @return <code>true</code> if there are more solutions
*/
@Override
public boolean hasNext() {
return iterator.hasNext();
}
/**
* Gets the next query solution
* @return the QuerySolution
* @see SOFIAResultSet#nextSolution()
*/
@Override
public QuerySolution next() {
rowNumber++;
return iterator.next();
}
/**
* Gets the next binding
*/
@Override
public Binding nextBinding() {
return null;
}
/**
* Gets the next solution
* @return a QuerySolution containin the next result
*/
@Override
public QuerySolution nextSolution() {
return iterator.next();
}
/**
* Removes the iterator
*/
@Override
public void remove() {
iterator = null;
}
/**
* Gets the obsolete result sets
* @param result the result obtained after an indication
* @return a SOFIAResultSet with the obsolete results
*/
public SOFIAResultSet getObsoleteResults(SOFIAResultSet result) {
// Creates a new void SOFIAResultSet
SOFIAResultSet returnResult = new SOFIAResultSet(null);
// Adds the var names
returnResult.setVarNames(this.getVarNames());
for (QuerySolution solution : this.getQuerySolutions()) {
if (!result.contains(solution)) {
returnResult.add(solution);
}
}
return returnResult;
}
/**
* Gets the new result sets
* @param result the result obtained after an indication
* @return a SOFIAResultSet with the obsolete results
*/
public SOFIAResultSet getNewResults(SOFIAResultSet result) {
// Creates a new void SOFIAResultSet
SOFIAResultSet returnResult = new SOFIAResultSet(null);
// Adds the var names
returnResult.setVarNames(result.getVarNames());
for (QuerySolution solution : result.getQuerySolutions()) {
if (!this.contains(solution)) {
returnResult.add(solution);
}
}
return returnResult;
}
/**
* Determines if the current solution contains a determinate solution
* @param solution the QuerySolution to obtain
* @return <code>true</code> if the solution set contains the given solution
*/
private boolean contains(QuerySolution solution) {
// For each solution
for (QuerySolution currentSolution : this.getQuerySolutions()) {
boolean equals = true;
// Compare one-to-one the var obtained RDFNodes
for (String var : varNames) {
RDFNode node1 = solution.get(var);
RDFNode node2 = currentSolution.get(var);
if (node1 != null) {
if (!node1.equals(node2)) {
equals = false;
}
} else {
if (node1 == null && node2 != null) {
equals = false;
}
}
}
// after all, if we found equality, return true value
if (equals) {
return true;
}
}
return false;
}
/**
* Returns the String representation of the result set
* @return a String with the representation of the result set
*/
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
// For each solution
for (QuerySolution currentSolution : solutions) {
sb.append(currentSolution.toString());
}
return sb.toString();
}
}
| true |
d1ed20f96379a632d7182e5fc24bcb7be1db440f | Java | clarence-ng/Experimental | /src/ng/clarence/collections/BinarySearch.java | UTF-8 | 1,651 | 3.875 | 4 | [] | no_license | package ng.clarence.collections;
public class BinarySearch {
// find the smallest index that is larger than or equal to target.
static int findSmallestIndexGreaterThanOrEqualTo(int[] values, int target) {
if (values.length == 0) return -1;
int start = 0;
int end = values.length - 1;
while (end - start > 1) {
int mid = (end + start) / 2;
int midValue = values[mid];
if (midValue < target) {
start = mid;
} else {
end = mid;
}
}
if (values[start] >= target) { return start; }
return end;
}
// find the largest index that is smaller than or equals to target.
static int findLargestIndexSmallerThanOrEqualTo(int[] values, int target) {
if (values.length == 0) return -1;
int start = 0;
int end = values.length - 1;
while (end - start > 1) {
int mid = (end + start) / 2;
int midValue = values[mid];
if (midValue <= target) {
start = mid;
} else {
end = mid;
}
}
if (values[end] <= target) { return end; }
return start;
}
public static int numOfValuesInRangeInclusive(int[] values, int start, int end) {
if (values.length == 0) return 0;
if (end < values[0] || start > values[values.length -1]) return 0;
int startIndex = findSmallestIndexGreaterThanOrEqualTo(values, start);
int endIndex = findLargestIndexSmallerThanOrEqualTo(values, end);
return endIndex - startIndex + 1;
}
}
| true |
96a51e8c30ddce8179980e99f562c9f42585b013 | Java | clafonta/canyon | /test/web/org/tll/canyon/webapp/action/AssetAccessRequestStatusFormControllerTest.java | UTF-8 | 2,675 | 2 | 2 | [
"Apache-2.0"
] | permissive | package org.tll.canyon.webapp.action;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.servlet.ModelAndView;
import org.tll.canyon.model.AssetAccessRequestStatus;
import org.tll.canyon.webapp.action.AssetAccessRequestStatusFormController;
import org.tll.canyon.webapp.action.BaseControllerTestCase;
public class AssetAccessRequestStatusFormControllerTest extends BaseControllerTestCase {
private AssetAccessRequestStatusFormController c;
private MockHttpServletRequest request;
private ModelAndView mv;
protected void setUp() throws Exception {
// needed to initialize a user
super.setUp();
c = (AssetAccessRequestStatusFormController) ctx.getBean("assetAccessRequestStatusFormController");
}
protected void tearDown() {
c = null;
}
public void testEdit() throws Exception {
log.debug("testing edit...");
request = newGet("/editAssetAccessRequestStatus.html");
request.addParameter("id", "1");
mv = c.handleRequest(request, new MockHttpServletResponse());
assertEquals("assetAccessRequestStatusForm", mv.getViewName());
}
public void testSave() throws Exception {
request = newGet("/editAssetAccessRequestStatus.html");
request.addParameter("id", "1");
mv = c.handleRequest(request, new MockHttpServletResponse());
AssetAccessRequestStatus assetAccessRequestStatus = (AssetAccessRequestStatus) mv.getModel().get(c.getCommandName());
assertNotNull(assetAccessRequestStatus);
request = newPost("/editAssetAccessRequestStatus.html");
super.objectToRequestParameters(assetAccessRequestStatus, request);
// update the form's fields and add it back to the request
mv = c.handleRequest(request, new MockHttpServletResponse());
Errors errors = (Errors) mv.getModel().get(BindException.MODEL_KEY_PREFIX + "assetAccessRequestStatus");
if (errors != null) {
log.debug(errors);
}
assertNull(errors);
assertNotNull(request.getSession().getAttribute("successMessages"));
}
public void testRemove() throws Exception {
request = newPost("/editAssetAccessRequestStatus.html");
request.addParameter("delete", "");
request.addParameter("id", "2");
mv = c.handleRequest(request, new MockHttpServletResponse());
assertNotNull(request.getSession().getAttribute("successMessages"));
}
}
| true |
26a4d63f1fc9d28f02749b70dd3854d2447126d8 | Java | pengxianggui/jianboke-dev | /jianboke-core/src/main/java/com/jianboke/mapper/UsersMapper.java | UTF-8 | 377 | 1.84375 | 2 | [] | no_license | package com.jianboke.mapper;
import com.jianboke.domain.User;
import com.jianboke.model.UsersModel;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
/**
* Created by pengxg on 2017/4/23.
*/
@Mapper(componentModel = "spring", uses = {})
public interface UsersMapper {
UsersModel entityToModel(User user);
User modelToEntity(UsersModel model);
}
| true |
c6adaf24d8f0b927af4713df08012cdad58391ec | Java | AndrasescOvidiu/SP_Labs | /AlignStrategy/RaptorAlign.java | UTF-8 | 186 | 2.15625 | 2 | [] | no_license | package AlignStrategy;
public class RaptorAlign implements AlignStrategy{
public void printAligned(String text) {
System.out.println("afisare pe randuri: " + text);
}
}
| true |
6d7064f67d5b07f8ee53bfd692b20bc5c5c36ed7 | Java | SaiKumar2705/Ihomeo | /app/src/main/java/com/ihomeo/ihomeouploading/model/Appointments_Model.java | UTF-8 | 6,281 | 1.859375 | 2 | [] | no_license | package com.ihomeo.ihomeouploading.model;
public class Appointments_Model {
private int appointment_id;
private String from_time = null;
private String to_time = null;
private String patient_name = null;
private String book = null;
private String arrived = null;
private String ForDate = null;
private String pay_consultation = null;
private String pay_pharmacy = null;
private int token_number;
private String mobile_number = null;
private String new_patient_name = null;
private String mr_Number = null;
private int consultationType_id, App_Master_Id;
private String consultation_Type = null;
private String consultation_Type_amt = null;
private String mMobile_number_Call = null;
private int TotalCount, NewCount, OldCount, ConsAmt, PharAmount, TotalAmount, PerConsAmt, PerPharAmt;
public Appointments_Model(String from_Time2, String to_Time2, String patient_name, String mBook, String mArrived, String mPay_Consultation, String mPay_Pharmacy, int token_number, int App_Master_Id, String Mobile) {
// TODO Auto-generated constructor stub
this.from_time = from_Time2;
this.to_time = to_Time2;
this.patient_name = patient_name;
this.book = mBook;
this.arrived = mArrived;
this.pay_consultation = mPay_Consultation;
this.pay_pharmacy = mPay_Pharmacy;
this.token_number = token_number;
this.App_Master_Id = App_Master_Id;
this.mMobile_number_Call = Mobile;
}
public Appointments_Model(int TotalCount, int NewCount, int OldCount) {
this.TotalCount = TotalCount;
this.NewCount = NewCount;
this.OldCount = OldCount;
}
public Appointments_Model() {
// TODO Auto-generated constructor stub
}
public Appointments_Model(String newPatient_Name, String mMR_Number) {
// TODO Auto-generated constructor stub
this.new_patient_name = newPatient_Name;
this.mr_Number = mMR_Number;
}
public Appointments_Model(int mConsultation_ID, String mConsultation_Type, String mConsultation_Amt) {
// TODO Auto-generated constructor stub
this.consultationType_id = mConsultation_ID;
this.consultation_Type = mConsultation_Type;
this.consultation_Type_amt = mConsultation_Amt;
}
public void setAppointments_ID(int mAppointment_id) {
this.appointment_id = mAppointment_id;
}
public int getAppointments_ID() {
return this.appointment_id;
}
public void setFrom_Time(String mFrom_time) {
this.from_time = mFrom_time;
}
public String getFrom_Time() {
return this.from_time;
}
public void setTo_Time(String mTo_time) {
this.to_time = mTo_time;
}
public String getTo_Time() {
return this.to_time;
}
public void setPatient_Name(String mPatient_name) {
this.patient_name = mPatient_name;
}
public String getPatient_Name() {
return this.patient_name;
}
public void setBook(String mBook) {
this.book = mBook;
}
public String getBook() {
return this.book;
}
public void setArrived(String mArrived) {
this.arrived = mArrived;
}
public String getArrived() {
return this.arrived;
}
public void setPay_Consultation(String mPay_Consultation) {
this.pay_consultation = mPay_Consultation;
}
public String getPay_Consultation() {
return this.pay_consultation;
}
public void setPay_Pharmacy(String mPay_Pharmacy) {
this.pay_pharmacy = mPay_Pharmacy;
}
public String getPay_Pharmacy() {
return this.pay_pharmacy;
}
public void setToken_Number(int mToken_numb) {
this.token_number = mToken_numb;
}
public int getToken_Number() {
return this.token_number;
}
public void setMobile_Numb(String mMobile_number) {
this.mobile_number = mMobile_number;
}
public String getMobile_Numb() {
return this.mobile_number;
}
public void setMobile_NumbCall(String mMobile_number_Call) {
this.mMobile_number_Call = mMobile_number_Call;
}
public String getMobile_numberCall() {
return this.mMobile_number_Call;
}
public void setNew_PatientName(String mNew_patientName) {
this.new_patient_name = mNew_patientName;
}
public String getNew_PatientName() {
return this.new_patient_name;
}
public void setMR_Number(String mMR_Number) {
this.mr_Number = mMR_Number;
}
public String getMR_Number() {
return this.mr_Number;
}
public void setConsultationType_ID(int mConsultationType_id) {
this.consultationType_id = mConsultationType_id;
}
public int getConsultationType_ID() {
return this.consultationType_id;
}
public int getNewCount() {
return this.NewCount;
}
public int getOldCount() {
return this.OldCount;
}
public int getTotalCount() {
return this.TotalCount;
}
public Appointments_Model(int ConsAmt, int PharAmount, int TotalAmount, int PerConsAmt, int PerPharAmt) {
this.ConsAmt = ConsAmt;
this.PharAmount = PharAmount;
this.TotalAmount = TotalAmount;
this.PerConsAmt = PerConsAmt;
this.PerPharAmt = PerPharAmt;
}
//revenuebycategory
public int getConsAmt() {
return this.ConsAmt;
}
public int getPharAmount() {
return this.PharAmount;
}
public int getTotalAmount() {
return this.TotalAmount;
}
public int PerConsAmt() {
return this.PerConsAmt;
}
public int getPerPharAmt() {
return this.PerPharAmt;
}
public void setConsultation_Type(String mConsultation_Type) {
this.consultation_Type = mConsultation_Type;
}
public String getConsultation_Type() {
return this.consultation_Type;
}
public void setConsultation_Type_Amount(String mConsultation_Type_Amount) {
this.consultation_Type_amt = mConsultation_Type_Amount;
}
public String getConsultation_Type_Amount() {
return this.consultation_Type_amt;
}
}
| true |
36a3fcdf347f5bc8d6c79a4d6403aaba01285b32 | Java | deepbiswas736/restspringhibernate | /src/main/java/com/revolution/raipur/jerseystart/models/Company.java | UTF-8 | 1,421 | 2.171875 | 2 | [] | no_license | package com.revolution.raipur.jerseystart.models;
import java.util.ArrayList;
import java.util.Collection;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
//@Entity
public class Company {
/*@Id
private String companyName;
private String location;
@OneToMany
private Collection<Employee> employeeList = new ArrayList<Employee>();
@OneToMany
private Collection<Project> projectList = new ArrayList<Project>();
@OneToMany
private Collection<Resource> resourceList = new ArrayList<Resource>();
public Collection<Employee> getEmployeeList() {
return employeeList;
}
public void setEmployeeList(Collection<Employee> employeeList) {
this.employeeList = employeeList;
}
public Collection<Project> getProjectList() {
return projectList;
}
public void setProjectList(Collection<Project> projectList) {
this.projectList = projectList;
}
public Collection<Resource> getResourceList() {
return resourceList;
}
public void setResourceList(Collection<Resource> resourceList) {
this.resourceList = resourceList;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
*/
}
| true |
163d5b59f31ffcd46b19838cfc1bbad4866b24c4 | Java | proconics1/LARS | /source/src/bsi/lars/gui/Util.java | UTF-8 | 1,862 | 3.03125 | 3 | [
"Apache-2.0"
] | permissive | package bsi.lars.gui;
public class Util {
public static String breakLines(String string, int maxcharacterperline) {
if(string.length() < maxcharacterperline) {
return string;
}
StringBuilder result = new StringBuilder();
for(String line : string.split("\n")) {
if(line.length() > maxcharacterperline) {
StringBuilder newline = new StringBuilder();
StringBuilder newblock = new StringBuilder();
for(String word : line.split(" ")) {
if(newline.length() + word.length() > maxcharacterperline) {
if(newline.length() == 0) {
newblock.append(word);
newblock.append("\n");
}else{
newblock.append(newline);
newblock.append("\n");
newline = new StringBuilder();
newline.append(word);
newline.append(" ");
}
}else{
newline.append(word);
newline.append(" ");
}
}
result.append(newblock);
if(newline.length() > 0) {
result.append(newline);
result.append("\n");
}else{
result.append("\n");
}
}else{
result.append(line);
result.append("\n");
}
}
// for(String word : string.split(" ")) {
// if(line.length() + word.length() > maxcharacterperline) {
// result.append(line);
// result.append(" \n");
// line = new StringBuilder();
// line.append(word);
// line.append(" ");
// }else{
// line.append(word);
// line.append(" ");
// }
// }
return result.toString();
}
public static String toHTML(String string) {
// return "<html><p align=\"justify\">" + string + "</p></html>";
return "<html><p align=\"justify\">" + string.replaceAll("\n", "<br />") + "</p></html>";
// return "<html><p align=\"justify\">" + string.replaceAll("\n", " ")/*.replaceAll("\n", "<br />")*/ + "</p></html>";
}
}
| true |
99c791b140212161f1b8e7a8b1f8a803532c9ebf | Java | MaksymD/Java_start | /src/lesson3/homework/Task2.java | UTF-8 | 520 | 3.546875 | 4 | [] | no_license | package lesson3.homework;
/*
Implement the print3 method. The method should display the given string 3 times.
Every time from a new line.
Реализуй метод print3. Метод должен вывести на экран переданную строку 3 раза.
Каждый раз с новой строки.
*/
public class Task2 {
public static void print3 (String s){
// your code here
}
public static void main(String[] args) {
print3("I made it!");
}
}
| true |
d0d0b74b520acefa4a2201342775aa29ceb5e2c5 | Java | zubairov/KieserTrainingMIDlet | /src/de/jki/phone/kieser/test/TestTrainingComparator.java | UTF-8 | 3,464 | 2.640625 | 3 | [] | no_license | package de.jki.phone.kieser.test;
import de.jki.phone.kieser.persistence.TrainingComparator;
import de.jki.phone.kieser.persistence.data.Training;
import de.jki.phone.kieser.persistence.data.TrainingUnit;
import javax.microedition.rms.RecordComparator;
import jmunit.framework.cldc11.TestCase;
/**
*
* @author jkindler
*/
public class TestTrainingComparator extends TestCase {
private TrainingComparator tc;
private final static String A1 = "A1";
private final static String B1 = "B1";
private final static int FOLLOWS = RecordComparator.FOLLOWS;
private final static int EQUIVALENT = RecordComparator.EQUIVALENT;
private final static int PRECEDES = RecordComparator.PRECEDES;
public TestTrainingComparator() {
super(4, "Test TrainingComparator");
}
public void setUp() throws Exception {
tc = new TrainingComparator();
}
private TrainingUnit getUnfinished(String id) {
TrainingUnit u = new TrainingUnit(id);
return u;
}
private TrainingUnit getFinished(String id) {
TrainingUnit u = getUnfinished(id);
u.setSecondsDone(u.getSecondsPlanned());
return u;
}
public void test(int testNumber) throws Throwable {
switch(testNumber) {
case 0: test2FinishedSortByDate(); break;
case 1: test2UnstartedSortByDate(); break;
case 2: test2UnfinishedSortByReversedDate(); break;
case 3: testFinishedFollowsUnfinished(); break;
default:
throw new IllegalArgumentException("Test " + testNumber + " does not exist");
}
}
private void test2FinishedSortByDate() throws Exception {
Training t1 = new Training();
t1.setUnits(new TrainingUnit[] {getFinished(A1), getUnfinished(B1)});
t1.doStart();
t1.doFinish();
Thread.sleep(10);
Training t2 = new Training();
t2.setUnits(new TrainingUnit[] {getFinished(A1), getUnfinished(B1)});
t2.doStart();
t2.doFinish();
assertEquals(EQUIVALENT, tc.compare(t1.serialize(), t1.serialize()));
assertEquals(PRECEDES, tc.compare(t1.serialize(), t2.serialize()));
assertEquals(FOLLOWS, tc.compare(t2.serialize(), t1.serialize()));
}
private void test2UnstartedSortByDate() throws Exception {
Training t1 = new Training();
t1.setUnits(new TrainingUnit[] {getUnfinished(A1)});
Training t2 = new Training();
t2.setUnits(new TrainingUnit[] {getUnfinished(A1)});
assertEquals(EQUIVALENT, tc.compare(t1.serialize(), t2.serialize()));
}
private void test2UnfinishedSortByReversedDate() throws Exception {
Training t1 = new Training();
t1.setUnits(new TrainingUnit[] {getUnfinished(A1)});
t1.doStart();
Thread.sleep(10);
Training t2 = new Training();
t2.setUnits(new TrainingUnit[] {getUnfinished(A1)});
t2.doStart();
assertEquals(FOLLOWS, tc.compare(t1.serialize(), t2.serialize()));
}
private void testFinishedFollowsUnfinished() throws Exception {
Training t1 = new Training();
t1.setUnits(new TrainingUnit[] {getFinished(A1)});
t1.doStart();
t1.doFinish();
Training t2 = new Training();
t2.setUnits(new TrainingUnit[] {getUnfinished(A1)});
t2.doStart();
assertEquals(FOLLOWS, tc.compare(t1.serialize(), t2.serialize()));
}
}
| true |
b9371f9420836ac4b4c6e261ac66df9e901f8198 | Java | ufouso/demoJAVA | /demoJAVA/src/com/test/java/basics/Test10_6.java | UTF-8 | 961 | 3.53125 | 4 | [] | no_license | package com.test.java.basics;
/**
* 匿名内部类
* @author xpp
*
*/
public class Test10_6 {
public static void main(String[] args) {
Outer4 out = new Outer4();
out.dotest();
function(
new Demoshow() {
@Override
public void show2() {
System.out.println("show2");
}
@Override
public void show1() {
System.out.println("show1");
}
}
);
}
public static void function(Demoshow ds) {
ds.show1();
ds.show2();
}
}
abstract class Demo{
abstract void show();
abstract void showw();
}
class Outer4{
private int num=5;
void dotest() {
//匿名内部类必须是继承或者实现接口
Demo dd = new Demo() {
void show() {
System.out.println("输出num:"+num);
}
@Override
void showw() {
System.out.println("showw");
}
};
dd.show();
}
}
interface Demoshow{
void show1();
void show2();
}
| true |
f82088baf01c34f6f69e0a589efb22f226e85023 | Java | cghsir/note | /src/main/java/com/cghsir/service/impl/InstructionsServiceImpl.java | UTF-8 | 1,881 | 2.421875 | 2 | [] | no_license | package com.cghsir.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cghsir.dao.InstructionsDao;
import com.cghsir.model.Instructions;
import com.cghsir.service.InstructionsServiceI;
/**
* @author cghsir
* @datetime 2017年4月2日 22:52:02
* @description 指令service实现
*/
@Service
public class InstructionsServiceImpl implements InstructionsServiceI {
@Autowired
private InstructionsDao instructionsDao;
/**
* 根据主键删除一个对象
* @param id
* @return
*/
public int deleteByPrimaryKey(String id) {
return instructionsDao.deleteByPrimaryKey(id);
}
/**
* 新增一个对象
* @param record
* @return
*/
public int insert(Instructions record) {
return instructionsDao.insert(record);
}
/**
* 动态新增一个对象
* @param record
* @return
* @throws Exception
*/
public int insertSelective(Instructions record) throws Exception {
return instructionsDao.insertSelective(record);
}
/**
* 根据主键查询一个对象
* @param id
* @return
*/
public Instructions selectByPrimaryKey(String id) {
return instructionsDao.selectByPrimaryKey(id);
}
/**
* 动态更新一条记录
* @param record
* @return
*/
public int updateByPrimaryKeySelective(Instructions record) {
return instructionsDao.updateByPrimaryKeySelective(record);
}
/**
* 更新一条记录
* @param record
* @return
*/
public int updateByPrimaryKey(Instructions record) {
return instructionsDao.updateByPrimaryKey(record);
}
/**
* 根据一个对象查询列表
* @param record
* @return
*/
@Override
public List<Instructions> queryList(Instructions record) {
return instructionsDao.queryList(record);
}
}
| true |
f06415455fb98eae0759adee9cbb5c73cc5a8f56 | Java | bltuckerdevblog/docker-swarm-with-compose | /echo-service/src/main/java/com/abnormallydriven/swarm/Main.java | UTF-8 | 421 | 2.109375 | 2 | [] | no_license | package com.abnormallydriven.swarm;
import java.util.UUID;
import static spark.Spark.port;
import static spark.Spark.post;
public class Main {
public static void main(String[] args) {
final String randomUUID = UUID.randomUUID().toString();
port(4568);
post("/echo", (req, res) -> {
res.header("Instance-UUID", randomUUID);
return req.body();
});
}
}
| true |
dcb4038a95a238fcb802f7f7710a83348d64b011 | Java | zhongxingyu/Seer | /Diff-Raw-Data/2/2_fc72c7b4b5939eef40a5fff3023b9e78b6afcedc/SQLHandler/2_fc72c7b4b5939eef40a5fff3023b9e78b6afcedc_SQLHandler_s.java | UTF-8 | 7,326 | 3.0625 | 3 | [] | no_license | package com.jenjinstudios.sql;
import com.jenjinstudios.util.Hash;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import static java.sql.ResultSet.CONCUR_UPDATABLE;
import static java.sql.ResultSet.TYPE_SCROLL_SENSITIVE;
/**
* The SQLHandler class is responsible for connecting to and querying the SQL database associated with a given Server.
* @author Caleb Brinkman
*/
@SuppressWarnings("SameParameterValue")
public class SQLHandler
{
/** The name of the column in the user table specifying whether the user is currently logged in. */
public static final String LOGGED_IN_COLUMN = "loggedin";
/** The Logger used for this class. */
private static final Logger LOGGER = Logger.getLogger(SQLHandler.class.getName());
/** The String used in connection protocol. */
private static final String connectionStringProtocol = "jdbc:mysql:thin://";
/** The username used to access the database. */
private final String dbUsername;
/** The password used to access the database. */
private final String dbPassword;
/** The name of the database used by this server. */
protected final String dbName;
/** The url used to connect with the SQL database. */
private final String dbUrl;
/** The string used to get all information about the user. */
private final String USER_QUERY;
/** Flags whether this SQLHandler is connected to the database. */
private boolean connected;
/** The connection used to communicate with the SQL database. */
protected Connection dbConnection;
/**
* Create a new SQLHandler with the given database information, and connect to the database.
* @param dbAddress The URL of the database, in the format www.example.place
* @param dbName The name of the database.
* @param dbUsername The username used to access the database.
* @param dbPassword The password used to access the database
* @throws SQLException If there is an issue connecting to the database.
*/
public SQLHandler(String dbAddress, String dbName, String dbUsername, String dbPassword) throws SQLException {
/* The address of the database to which to connect. */
this.dbUsername = dbUsername;
this.dbPassword = dbPassword;
this.dbName = dbName;
dbUrl = connectionStringProtocol + dbAddress + "/" + dbName;
try
{
Class.forName("org.drizzle.jdbc.DrizzleDriver").newInstance();
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e)
{
LOGGER.log(Level.SEVERE, "Unable to register Drizzle driver; is the Drizzle dependency present?");
}
USER_QUERY = "SELECT * FROM " + dbName + ".users WHERE username = ?";
connectToDatabase();
}
/**
* Attempt to log the given user with the given password into the database. This method does not perform any sort of
* hashing or encryption on the password. If the user is already logged in this method will return false.
* <p/>
* This method should be overwritten by implementations, or called from super if they still wish to use the "loggedIn"
* column.
* @param username The username of the user to be logged in.
* @param password The password of the user to be logged in.
* @return true if the user was logged in successfully, false if the user was already logged in or the update to the
* database failed.
*/
public synchronized boolean logInUser(String username, String password) {
boolean success = false;
if (!connected)
return success;
try // TODO Make sure error is handled gracefully
{
ResultSet results = makeUserQuery(username);
results.next();
// Determine if the user is logged in. If yes, end of method.
boolean loggedIn = results.getBoolean(LOGGED_IN_COLUMN);
if (loggedIn)
return success;
// Hash the user-supplied password with the salt in the database.
String hashedPassword = Hash.getHashedString(password, results.getString("salt"));
// Determine if the correct password was supplied.
boolean passwordCorrect = hashedPassword.equalsIgnoreCase(results.getString("password"));
results.getStatement().close();
if (!passwordCorrect)
return success;
updateLoggedinColumn(username, true);
success = true;
} catch (SQLException | IndexOutOfBoundsException e)
{
LOGGER.log(Level.FINE, "Failed to log in user: {0}", username);
success = false;
}
return success;
}
/**
* Attempt to log out the given user with the given password into the database. This method does not perform any sort
* of hashing or encryption on the password. If the user is already logged in this method will return false.
* @param username The username of the user to be logged out.
* @return true if the user was logged out successfully, false if the user was already logged out or the update to the
* database failed.
*/
public synchronized boolean logOutUser(String username) {
boolean success = false;
if (!connected)
return success;
try // TODO Make sure error is handled gracefully
{
ResultSet results = makeUserQuery(username);
results.next();
// Determine if the user is logged in. If no, end of method.
boolean loggedIn = results.getBoolean(LOGGED_IN_COLUMN);
results.getStatement().close();
if (!loggedIn)
return success;
updateLoggedinColumn(username, false);
success = true;
} catch (SQLException | IndexOutOfBoundsException e)
{
LOGGER.log(Level.FINE, "Failed to log out user: {0}", username);
success = false;
}
return success;
}
/**
* Attempt to connect to the database.
* @throws SQLException If there is an error connecting to the SQL database.
*/
private void connectToDatabase() throws SQLException {
dbConnection = DriverManager.getConnection(dbUrl, dbUsername, dbPassword);
connected = true;
}
/**
* Get whether this SQLHandler is connected to the database.
* @return true if the SQLHandler has successfully connected to the database.
*/
public boolean isConnected() {
return connected;
}
/**
* Query the database for user info.
* @param username The username of the user we're looking for.
* @return The ResultSet returned by the query.
* @throws SQLException If there is a SQL error.
*/
protected ResultSet makeUserQuery(String username) throws SQLException {
PreparedStatement statement = dbConnection.prepareStatement(USER_QUERY, TYPE_SCROLL_SENSITIVE, CONCUR_UPDATABLE);
statement.setString(1, username);
return statement.executeQuery();
}
/**
* Update the loggedin column to reflect the supplied boolean.
* @param username The user being queried.
* @param status The new status of the loggedin column.
* @throws SQLException If there is a SQL error.
*/
protected void updateLoggedinColumn(String username, boolean status) throws SQLException {
String newValue = status ? "1" : "0";
String updateLoggedInQuery = "UPDATE " + dbName + ".users SET " + LOGGED_IN_COLUMN + "=" + newValue + " WHERE " +
"username = ?";
PreparedStatement updateLoggedin;
updateLoggedin = dbConnection.prepareStatement(updateLoggedInQuery);
updateLoggedin.setString(1, username);
updateLoggedin.executeUpdate();
updateLoggedin.close();
}
}
| true |
23bf381ad4139b4cd34f75eaceea2454cf00f793 | Java | fahrrad/droolspoc | /src/main/java/com/gb/cropdesign/droolspoc/mapper/PlantResultMapper.java | UTF-8 | 512 | 2.109375 | 2 | [
"Apache-2.0"
] | permissive | package com.gb.cropdesign.droolspoc.mapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
import com.gb.cropdesign.droolspoc.PlantResult;
public class PlantResultMapper implements RowMapper<PlantResult> {
@Override
public PlantResult mapRow(ResultSet resultSet, int rowCount)
throws SQLException {
return new PlantResult(resultSet.getString("plant_name")
, resultSet.getString("pcr_target")
, resultSet.getBoolean("result"));
}
}
| true |
2238bd286a3b2aa8a97e0c243158d41009ec3d1e | Java | LucasAlves011/ProjetoGigantesco | /ProjetoGigantesco/src/gui/Main.java | UTF-8 | 583 | 2.171875 | 2 | [] | no_license | package gui;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(String[] args) {
launch();
}
@Override
public void start(Stage principal) throws Exception {
Pane a = FXMLLoader.load(getClass().getResource("dxml.fxml"));
Scene b = new Scene(a);
principal.setScene(b);
principal.setTitle("Projeto meu - Em desenvolvimento");
principal.show();
}
}
| true |
d992d136390543157b2ab825ad9d1a0baa8bd1f3 | Java | huythang38/Certificate | /Certificate/source_code/src/client/action/student/CreateStudents.java | UTF-8 | 2,823 | 2.15625 | 2 | [] | no_license | package client.action.student;
import java.rmi.RemoteException;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import client.Client;
import client.action.account.NextAccount;
import client.event.DisconnectToExit;
import client.gui.admin.nav_panel.CreateStudent;
public class CreateStudents extends Thread {
/**
* @uml.property name="name"
*/
public String name;
/**
* @uml.property name="address"
*/
public String address;
/**
* @uml.property name="birthday"
*/
public String birthday;
/**
* @uml.property name="email"
*/
public String email;
/**
* @uml.property name="candidate"
*/
public String candidate;
/**
* @uml.property name="class"
*/
public String Class;
/**
* @uml.property name="id"
*/
public int id;
/**
* @uml.property name="gender"
*/
public int gender;
/**
* @uml.property name="phone"
*/
public int phone;
/**
* @uml.property name="class_id"
*/
public int class_id;
public CreateStudents(String _name, String _address, int _gender,
String _birthday, String _email, int _phone, String _candidate,
String _class) {
this.name = _name;
this.address = _address;
this.gender = _gender;
this.birthday = _birthday;
this.email = _email;
this.phone = _phone;
this.candidate = _candidate;
this.Class = _class;
}
public boolean createAccount() throws RemoteException {
return Client.conn.createAccount();
}
public boolean createPayment(int students_id) throws RemoteException {
return Client.conn.createPayment(students_id);
}
public int getIDClass(String class_name) throws RemoteException {
return Client.conn.getClassID(class_name);
}
public void run() {
CreateStudent.lblWaitting.setVisible(true);
//
try {
if (createAccount()) {
if (Client.conn.createStudent(name, address, gender, birthday,
email, phone, candidate, Class,
(NextAccount.nextAccount() - 1))) {
if (createPayment(Client.conn.getStudentsLastID())) {
CreateStudent.lblWaitting.setVisible(false);
CreateStudent.model = new DefaultTableModel(
ModeltoTable.getModel(getIDClass(Class)),
CreateStudent.headTable);
CreateStudent.table.setModel(CreateStudent.model);
CreateStudent.txtUsername.setText("Student"
+ NextAccount.nextAccount());
JOptionPane.showMessageDialog(new JFrame(), "Created!");
}
} else {
CreateStudent.lblWaitting.setVisible(false);
JOptionPane
.showMessageDialog(new JFrame(), "Don't create!");
}
}
} catch (RemoteException e) {
// TODO Auto-generated catch block
new DisconnectToExit();
e.printStackTrace();
}
}
}
| true |
886bac6498d6b492c2f5c67fe7d93f1378617a7b | Java | reverseengineeringer/com.yelp.android | /src/com/google/android/gms/analytics/r.java | UTF-8 | 458 | 1.695313 | 2 | [] | no_license | package com.google.android.gms.analytics;
import java.util.List;
public abstract interface r
{
public abstract int a(List<ab> paramList, af paramaf, boolean paramBoolean);
public abstract void ad(String paramString);
public abstract boolean ea();
public abstract void setDryRun(boolean paramBoolean);
}
/* Location:
* Qualified Name: com.google.android.gms.analytics.r
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | true |
4c94b2c7a0d39c85937f3a4ddfabbc18ff29695b | Java | adeaver/OSS-NLP | /GrammarCorrection/src/test/java/com/ardeaver/grammar/postagger/PartOfSpeechTaggerTest.java | UTF-8 | 1,853 | 2.546875 | 3 | [] | no_license | package com.ardeaver.grammar.postagger;
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.junit.Test;
import com.ardeaver.grammar.preprocessing.Token;
import com.ardeaver.grammar.preprocessing.Tokenizer;
public class PartOfSpeechTaggerTest {
private PartOfSpeechTagger tagger;
public PartOfSpeechTaggerTest() {
tagger = new PartOfSpeechTagger();
}
@Test
public void testPartOfSpeechTagging() {
String input = "He is a good person.";
List<Token> outputTokens = tagger.tagSentence(Tokenizer.tokenizeInput(input));
String taggedSentence = Tokenizer.getTaggedSentence(outputTokens);
assertEquals("(He)_PRP (is)_BEZ (a)_Z (good)_JJ (person)_NN", taggedSentence);
}
@Test
public void testIncorrectGrammar() {
String input = "She have patient when she teach me difficult word";
List<Token> outputTokens = tagger.tagSentence(Tokenizer.tokenizeInput(input));
String taggedSentence = Tokenizer.getTaggedSentence(outputTokens);
assertEquals("(She)_PRP (have)_HVP (patient)_NN (when)_WRB (she)_PRP (teach)_VB (me)_PRP (difficult)_JJ (word)_NN", taggedSentence);
}
@Test
public void testIncorrect2() {
String input = "She has patient when she teach me difficult word";
List<Token> outputTokens = tagger.tagSentence(Tokenizer.tokenizeInput(input));
String taggedSentence = Tokenizer.getTaggedSentence(outputTokens);
assertEquals("(She)_PRP (has)_HVZ (patient)_JJ (when)_WRB (she)_PRP (teach)_VB (me)_PRP (difficult)_JJ (word)_NN", taggedSentence);
}
@Test
public void testBackoff() {
String input = "He is a nice person";
List<Token> outputTokens = tagger.tagSentence(Tokenizer.tokenizeInput(input));
String taggedSentence = Tokenizer.getTaggedSentence(outputTokens);
assertEquals("(He)_PRP (is)_BEZ (a)_Z (nice)_NN (person)_NN", taggedSentence);
}
} | true |
ddd7cc218f641fda648a7de29a9e5eafd173b990 | Java | Grace007/milkana | /src/main/java/com/itextpdf/html2pdf/attach/util/WaitingColgroupsHelper.java | UTF-8 | 7,089 | 1.609375 | 2 | [] | no_license | /*
This file is part of the iText (R) project.
Copyright (c) 1998-2017 iText Group NV
Authors: Bruno Lowagie, Paulo Soares, et al.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
ITEXT GROUP. ITEXT GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, see http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://itextpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using iText.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the iText software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping iText with a closed
source product.
For more information, please contact iText Software Corp. at this
address: sales@itextpdf.com
*/
package com.itextpdf.html2pdf.attach.util;
import com.itextpdf.html2pdf.attach.wrapelement.ColWrapper;
import com.itextpdf.html2pdf.attach.wrapelement.ColgroupWrapper;
import com.itextpdf.html2pdf.css.util.CssUtils;
import com.itextpdf.html2pdf.html.AttributeConstants;
import com.itextpdf.html2pdf.html.TagConstants;
import com.itextpdf.html2pdf.html.node.IElementNode;
import com.itextpdf.html2pdf.html.node.INode;
import java.util.ArrayList;
/**
* Helper class for waiting column groups.
*/
public class WaitingColgroupsHelper {
/** The table element. */
private IElementNode tableElement;
/** The column groups. */
private ArrayList<ColgroupWrapper> colgroups = new ArrayList<>();
/** The maximum value of the index. */
private int maxIndex = -1;
/** The index to column group mapping. */
private int[] indexToColgroupMapping;
/** The shift values for the columns. */
private int[] shiftCol;
/**
* Creates a new {@link WaitingColgroupsHelper} instance.
*
* @param tableElement the table element
*/
public WaitingColgroupsHelper(IElementNode tableElement) {
this.tableElement = tableElement;
}
/**
* Adds a column group.
*
* @param colgroup the column group
*/
public void add(ColgroupWrapper colgroup) {
colgroups.add(colgroup);
}
/**
* Applies column styles.
*/
public void applyColStyles() {
if (colgroups.isEmpty() || maxIndex != -1) {
return;
}
finalizeColgroups();
RowColHelper tableRowColHelper = new RowColHelper();
RowColHelper headerRowColHelper = new RowColHelper();
RowColHelper footerRowColHelper = new RowColHelper();
IElementNode element;
for (INode child : tableElement.childNodes()) {
if (child instanceof IElementNode) {
element = (IElementNode) child;
if (element.name().equals(TagConstants.THEAD)) {
applyColStyles(element, headerRowColHelper);
} else if (element.name().equals(TagConstants.TFOOT)) {
applyColStyles(element, footerRowColHelper);
} else {
applyColStyles(element, tableRowColHelper);
}
}
}
}
/**
* Gets a specific column.
*
* @param index the index of the column
* @return the column
*/
public ColWrapper getColWrapper(int index) {
if (index > maxIndex) {
return null;
}
return colgroups.get(indexToColgroupMapping[index]).getColumnByIndex(index - shiftCol[indexToColgroupMapping[index]]);
}
/**
* Applies column styles.
*
* @param node the node
* @param rowColHelper the helper class to keep track of the position inside the table
*/
private void applyColStyles(INode node, RowColHelper rowColHelper) {
int col;
IElementNode element;
for (INode child : node.childNodes()) {
if (child instanceof IElementNode) {
element = (IElementNode) child;
if (element.name().equals(TagConstants.TR)) {
applyColStyles(element, rowColHelper);
rowColHelper.newRow();
} else if (element.name().equals(TagConstants.TH) || element.name().equals(TagConstants.TD)) {
Integer colspan = CssUtils.parseInteger(element.getAttribute(AttributeConstants.COLSPAN));
Integer rowspan = CssUtils.parseInteger(element.getAttribute(AttributeConstants.ROWSPAN));
colspan = colspan != null ? colspan : 1;
rowspan = rowspan != null ? rowspan : 1;
col = rowColHelper.moveToNextEmptyCol();
if (getColWrapper(col) != null && getColWrapper(col).getCellCssProps() != null) {
element.addAdditionalHtmlStyles(getColWrapper(col).getCellCssProps());
}
rowColHelper.updateCurrentPosition((int) colspan, (int) rowspan);
} else {
applyColStyles(child, rowColHelper);
}
}
}
}
/**
* Finalizes the column groups.
*/
private void finalizeColgroups() {
int shift = 0;
shiftCol = new int[colgroups.size()];
for (int i = 0; i < colgroups.size(); ++i) {
shiftCol[i] = shift;
shift += colgroups.get(i).getSpan();
}
maxIndex = shift - 1;
indexToColgroupMapping = new int[shift];
for (int i = 0; i < colgroups.size(); ++i) {
for (int j = 0; j < colgroups.get(i).getSpan(); ++j) {
indexToColgroupMapping[j + shiftCol[i]] = i;
}
}
colgroups.trimToSize();
}
}
| true |
509eb58f35fdbdf73693646aedfd241f46bab24b | Java | TheDooft/Dark-Side-Simulator | /src/dss/model/Alteration.java | UTF-8 | 1,551 | 2.84375 | 3 | [] | no_license | package dss.model;
public class Alteration {
private AlterationType type;
private int maxDuration;
private int ttl;
private int curStack;
private int maxStack;
private int lastRefresh;
private String name;
private int period;
private int lastTick;
private String tag;
public Alteration(String name,AlterationType type, int maxDuration, int maxStack) {
this.name = name;
this.type = type;
this.maxDuration = maxDuration;
this.curStack = 0;
this.maxStack = maxStack;
this.lastRefresh = -1;
this.period = -1;
this.lastTick = -1;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public String getName(){
return name;
}
public void apply(int time){
this.ttl = this.maxDuration;
this.lastRefresh = time;
this.lastTick = time;
if (this.curStack < this.maxStack)
this.curStack++;
}
public int getTTL(){
return this.ttl;
}
public int getNumberOfStack(){
return this.curStack;
}
public AlterationType getType(){
return type;
}
public boolean refresh(int time){
if (ttl < 0)
return true;
int diff = time - this.lastRefresh;
ttl -= diff;
if (this.lastTick + this.period <= time){
this.lastTick += this.period;
this.tick();
}
if (ttl <= 0){
this.curStack = 0;
return false;
}
this.lastRefresh = time;
return true;
}
public void tick() {
}
public void setPeriod(int period) {
this.period = period;
}
}
| true |
4771fa89322ee34020b4ddad44133446d8755fb0 | Java | kmat231/Network_Simulator | /src/Packet.java | UTF-8 | 1,851 | 3.25 | 3 | [] | no_license | //name: Kevin Mathew
//id number: 112167040
//recitation: 02
/**
* Class Packet consists of particular variables for each Packet
*
* @author Kevin
*
*/
public class Packet {
private static int packetCount = 0;
private int id;
private int packetSize;
private int timeArrive;
private int timeToDest;
/**
* Constructor for the Packet Class
*/
public Packet() {
packetCount++;
this.id = packetCount;
}
/**
*
* @return id - the packets id represented my packet count
*/
public int getId() {
return id;
}
/**
*
* @param id set the id of the packet
*/
public void setId(int id) {
this.id = id;
}
/**
*
* @return packetSize - returns the size of the packet
*/
public int getPacketSize() {
return packetSize;
}
/**
*
* @param
* packetSize set the packetSize of the packet
*/
public void setPacketSize(int packetSize) {
this.packetSize = packetSize;
}
/**
*
* @return
* returns the time arrived
*/
public int getTimeArrive() {
return timeArrive;
}
/**
*
* @param timeArrive
* the time arrived for the packet
*/
public void setTimeArrive(int timeArrive) {
this.timeArrive = timeArrive;
}
/**
*
* @return
* returns the time arrived
*/
public int getTimeToDest() {
timeToDest = packetSize / 100;
return timeToDest;
}
/**
*
* @param timeToDest
* set the time to destination
*/
public void setTimeToDest(int timeToDest) {
this.timeToDest = timeToDest;
}
/**
* toString method for the packet
*/
@Override
public String toString() {
String packet;
if (this.getPacketSize() > 999) {
packet = Integer.toString(this.getPacketSize()).substring(0, 2);
} else {
packet = Integer.toString(this.getPacketSize()).substring(0, 1);
}
return "[" + this.getId() + ", " + this.getTimeArrive() + ", " + packet + "]";
}
}
| true |
7f40874127fd5b477516576cf13c0f0285f7e355 | Java | przor3n/VICAR | /vos/java/jpl/mipl/io/vicar/MgnFbidrInputFile.java | UTF-8 | 16,407 | 2.09375 | 2 | [] | no_license | /*
* This class manages a single Magellan F-BIDR input image file.
* <p>
* Based on PDSInputFile.java.
*
* @author Bob Deen
*/
package jpl.mipl.io.vicar;
import java.io.*;
import jpl.mipl.io.util.DOMutils;
import jpl.mipl.io.plugins.MgnFbidrImageReadParam;
import org.w3c.dom.*;
import java.util.*;
public class MgnFbidrInputFile extends VicarInputFile
{
DataInput _di_hdr; // Appropriate DI for the header wrapped around stream
boolean _validPixelsOnly = true;
ArrayList<MgnFbidrHeader> _fbidr_headers = null; // F-BIDR metadata holder
int _n_headers;
int _phys_nl, _logical_nl;
int _logical_ns;
int _phys_min_line, _phys_max_line;
int _logical_min_line, _logical_max_line;
int _min_samp, _max_samp;
boolean _oblique_projection;
long _line_ptrs[]; // pointer into the file for this line
int _header_index[]; // which header value applies to this line
VicarDataFormat _vdf_hdr; // VAX format for header
Document _xml_doc = null; // XML for header
boolean _gotMetadata = false;
MgnFbidrImageReadParam _mgnFbidrImageReadParam = null;
boolean debug = false;
public void setDebug(boolean d) {
debug = d;
}
/** Constructor */
public MgnFbidrInputFile(MgnFbidrImageReadParam param)
{
super();
_mgnFbidrImageReadParam = param;
if (debug) System.out.println("%%%%%% MgnFbidrInputFile constructor with MgnFbidrImageReadParam");
}
/***********************************************************************
* Called at the end of open() by the superclass. Here we make sure the
* file is not sequential, as random-access is mandatory for F-BIDRs.
*/
protected void openInternalLast() {
if (!_random_allowed || !_random_easy)
throw new UnsupportedOperationException("F-BIDR must be read from a stream allowing random access");
}
/***********************************************************************
* Read the labels (metadata) from the file. This actually reads ALL of the
* logical records in the file.
*/
protected void setupLabels() throws IOException {
if (debug) {
System.out.println("MgnFbidrInputFile.setupLabels()");
System.out.println("input type: "+_input_stream);
}
// We use a fairly large number here just to avoid re-allocs
_fbidr_headers = new ArrayList<MgnFbidrHeader>(6200);
// Create a Vax-format input stream to read the header
_vdf_hdr = new VicarDataFormat("VAX-VMS", "LOW", "VAX");
_di_hdr = _vdf_hdr.getDataInputWrapper(_input_stream);
//DataInput di_hdr = _vdf_hdr.getDataInputWrapper(_input_stream);
// Read in the heaers
//_fbidr_header = new MgnFbidrHeader(di_hdr);
boolean done = false;
_n_headers = 0;
while (!done) {
try {
MgnFbidrHeader h = new MgnFbidrHeader(_di_hdr, stream_pos());
// read successful
_fbidr_headers.add(_n_headers, h);
_n_headers++;
// Skip the data portion
_di_hdr.skipBytes(h.getDataSize());
} catch (Exception e) {
done = true;
}
}
// Scan the headers to create accessor data structures
scanHeaders();
// Create the system label
_system = createSystemLabel();
// Fix sizes based on label
_lblsize_front = 92; // constant label size
_current_file_pos = _lblsize_front; // we read the entire label
_image_size_bytes = (_system.getNLB() +
((long)_system.getN2() * (long)_system.getN3()))
* _system.getRecsize();
_record_size = _system.getRecsize();
// put things into the properties of the image
// setProperty("MgnFbidrHeader", (Object) _fbidr_header);
// setProperty("MgnFbidrHeader_ClassName",
// (Object) _fbidr_header.getClass().getName());
// setProperty("ImageFormatName", (Object) "mgn-fbidr");
// setProperty("SystemLabel", (Object) _system);
// setProperty("SystemLabel_ClassName",
// (Object) _system.getClass().getName() );
// Create the XML
//DOMutils domUtils = new DOMutils();
//_xml_doc = domUtils.getNewDocument();
//_fbidr_header.buildDom(_xml_doc);
//if (debug)
// _fbidr_header.print(System.out);
if (debug)
_fbidr_headers.get(0).print(System.out);
}
/**************************************************************
* Scan the headers and build the per-line accessor tables
*/
protected void scanHeaders()
{
// This can get confusing. For Oblique, things are in the "right"
// order, with the smallest line # at the top. For non-oblique,
// they're backwards, with the smallext line # at the bottom (these
// are called C1 values in the SIS). In all cases both phys and
// logical min/max refer to the numeric min/max extents, all relative
// to the projection origin. But the line number indexes into the
// arrays are 0..n, where 0 is at the top of the image always. So for
// non-oblique, we have to invert the line numbers when going to the
// line arrays.
// Get the projection type. They should be the same throughout the
// file so we just look at the first.
int data_class = _fbidr_headers.get(0).getDataClass();
if (data_class == 2) // multi-look sinusoidal
_oblique_projection = false;
else if (data_class == 66) // multi-look oblique
_oblique_projection = true;
else
throw new UnsupportedOperationException(
"Data must be multi-look image, either sinusoidal or oblique");
// First prescan to count the number of lines
_phys_min_line = 1000000;
_phys_max_line = -1000000;
_min_samp = 1000000;
_max_samp = -1000000;
for (MgnFbidrHeader h : _fbidr_headers) {
if (_oblique_projection) {
int start_line = h.getReferencePointOffsetLines();
if (start_line < _phys_min_line)
_phys_min_line = start_line;
int end_line = start_line + h.getImageLineCount() - 1;
if (end_line > _phys_max_line)
_phys_max_line = end_line;
}
else {
int end_line = h.getReferencePointOffsetLines();
if (end_line > _phys_max_line)
_phys_max_line = end_line;
int start_line = end_line - h.getImageLineCount() + 1;
if (start_line < _phys_min_line)
_phys_min_line = start_line;
}
}
_logical_min_line = _phys_min_line;
_logical_max_line = _phys_max_line;
int max_lines = 50000; // ultimate default
if (_mgnFbidrImageReadParam != null) {
if (_mgnFbidrImageReadParam.isMinSet())
_logical_min_line = _mgnFbidrImageReadParam.getMinLogicalLine();
if (_mgnFbidrImageReadParam.isMaxSet())
_logical_max_line = _mgnFbidrImageReadParam.getMaxLogicalLine();
max_lines = _mgnFbidrImageReadParam.getMaxNumLines();
}
// Keep from getting too big
if (_logical_max_line-_logical_min_line>max_lines)
_logical_max_line=_logical_min_line+max_lines;
for (MgnFbidrHeader h : _fbidr_headers) {
int ln = h.getReferencePointOffsetLines();
if (ln > _logical_max_line ||
(ln+h.getImageLineCount()) < _logical_min_line)
continue; // not in logical range
int start_samp = h.getReferencePointOffsetPixels();
if (start_samp < _min_samp)
_min_samp = start_samp;
int end_samp = start_samp + h.getImageLineLength() - 1;
if (end_samp > _max_samp)
_max_samp = end_samp;
}
// Now allocate the arrays
_phys_nl = (_phys_max_line - _phys_min_line) + 1;
_logical_nl = (_logical_max_line - _logical_min_line) + 1;
_logical_ns = (_max_samp - _min_samp) + 1;
_line_ptrs = new long[_phys_nl];
_header_index = new int[_phys_nl];
Arrays.fill(_line_ptrs, -1);
Arrays.fill(_header_index, -1);
// Now scan the headers again and fill in the arrays
// Can't use foreach because we need the loop index for _header_index.
// Note that we make no assumption the lines are contiguous - this is
// really a mosaic-like process
if (debug) {
System.out.println("phys min_line="+_phys_min_line+" phys max_line="+_phys_max_line);
System.out.println("log min_line="+_logical_min_line+" log max_line="+_logical_max_line);
System.out.println("min_samp="+_min_samp+" max_samp="+_max_samp);
System.out.println("phys_nl="+_phys_nl+" log nl="+_logical_nl);
}
for (int i=0; i < _n_headers; i++) {
MgnFbidrHeader h = _fbidr_headers.get(i);
long pos = h.getDataPosInFile();
int ref_line = h.getReferencePointOffsetLines();
int line_index;
if (_oblique_projection)
line_index = ref_line - _phys_min_line;
else
line_index = _phys_max_line - ref_line;
int nlines = h.getImageLineCount();
int len = h.getImageLineLength();
for (int j=0; j < nlines; j++) {
_line_ptrs[line_index] = pos;
_header_index[line_index] = i;
line_index++;
pos += len;
}
}
}
/**************************************************************
* Create a SystemLabel from the contents of the header.
*/
protected SystemLabel createSystemLabel()
{
SystemLabel sys = new SystemLabel();
sys.setFormat("BYTE");
sys.setType("IMAGE");
sys.setDim(3);
sys.setEOL(0);
sys.setOrg("BSQ");
sys.setNL(_logical_nl);
sys.setNS(_logical_ns); // 4 bytes of prefix
sys.setNB(1);
sys.setNBB(0);
sys.setNLB(0);
sys.setHost("VAX-VMS");
sys.setIntFmt("LOW");
sys.setRealFmt("VAX");
sys.setBHost("VAX-VMS");
sys.setBIntFmt("LOW");
sys.setBRealFmt("VAX");
sys.setBLType("MGN-FBIDR");
sys.calcRecsize();
if (debug) {
System.out.println("*** SYSTEM LABEL ***");
System.out.println(sys.toString());
}
return sys;
}
/**************************************************************
* @return the XML Document derived from the label
*/
public Document getXMLDocument() {
if (_xml_doc == null) {
// Create the XML
DOMutils domUtils = new DOMutils();
_xml_doc = domUtils.getNewDocument();
Element root = (Element)_xml_doc.createElement("mgn_fbidr");
for (MgnFbidrHeader h : _fbidr_headers) {
root.appendChild(h.buildDom(_xml_doc));
}
_xml_doc.appendChild(root);
}
return _xml_doc;
}
/***********************************************************************
* There is no Vicar label for MGN F-BIDR's, so we just return null here.
*/
public synchronized VicarLabel getVicarLabel() throws IOException
{
return null;
}
/***********************************************************************
* Indicates whether or not the <code>PDSLabel</code> has been completely
* read. Always true for MGN F-BIDRs since there are no EOL labels.
*/
public synchronized boolean isLabelComplete()
{
return true;
}
/***********************************************************************
* Returns the MgnFbidrHeader objects.
*/
public List<MgnFbidrHeader> getHeaders()
{
return _fbidr_headers;
}
/***********************************************************************
* Override of VicarInputFile.readRecordNS (byte version). This reads things
* in the rather strange F-BIDR format rather than assuming a simple raster
* of bytes.
* @see VicarInputFile.readRecord(byte[], int, int, int, int, int, int)
*/
protected void readRecordNS(byte[] data,
int start, int length, int offset, int pixelStride,
int n2, int n3) throws IOException
{
// Fill data buffer with 0 to start, since there almost always is extra
// blank space around the image
if (pixelStride == 1)
Arrays.fill(data, offset, offset+length, (byte)0);
else {
for (int i=0; i < length; i++)
data[offset+(i*pixelStride)] = 0;
}
// Adjust line number for logical window
int line_index;
if (_oblique_projection)
line_index = n2 + (_logical_min_line - _phys_min_line);
else
line_index = n2 + (_phys_max_line - _logical_max_line);
int hdr_index = _header_index[line_index];
if (hdr_index < 0)
return; // no data on line, done!
MgnFbidrHeader hdr = _fbidr_headers.get(hdr_index);
long pos = _line_ptrs[line_index];
if (pos < 0)
return; // really shouldn't happen unless hdr_index<0 too
// Figure out the horizontal extent of *this* line. The -4 accounts
// for the prefix while the -1 gives us the ending coordinate
// file_start/end are in coords relative to the lines in this block
// min/max_samp_file are in overall file coords (starting at 0)
// min/max_samp_buf are in overall file coords (starting at 0)
int file_start = 0;
int file_end = hdr.getImageLineLength() - 4 - 1;
// If we only want valid pixels, adjust the start/end based on the
// valid pixel pointers at the start of the line
if (_validPixelsOnly) {
seekToLocation(pos);
file_start = _di_hdr.readShort() - 1;
file_end = _di_hdr.readShort() - 1;
if (file_start == file_end)
return; // no data on this line
}
int min_samp_file = file_start + hdr.getReferencePointOffsetPixels()
- _min_samp;
int max_samp_file = file_end + hdr.getReferencePointOffsetPixels()
- _min_samp;
int min_samp_buf = start;
int max_samp_buf = start + length - 1;
int new_offset = offset;
// System.out.println("min_samp_file="+min_samp_file+" max="+max_samp_file);
// System.out.println("min_samp_buf= "+min_samp_buf+" max="+max_samp_buf);
// System.out.println("file_start="+file_start+" end="+file_end);
if (min_samp_file > max_samp_buf)
return; // all before the image
if (max_samp_file < min_samp_buf)
return; // all after the image
if (min_samp_buf < min_samp_file) { // starting before image
int delta = min_samp_file - min_samp_buf;
min_samp_buf = min_samp_file;
new_offset += delta;
}
if (min_samp_buf > min_samp_file) { // starting past image
int delta = min_samp_buf - min_samp_file;
min_samp_file += delta;
file_start += delta;
}
if (max_samp_buf > max_samp_file) { // ending after image
max_samp_buf = max_samp_file;
}
if (max_samp_buf < max_samp_file) { // ending before image end
int delta = max_samp_file - max_samp_buf;
max_samp_file -= delta;
file_end -= delta;
}
// add 4 to skip line prefix
pos += 4 + file_start;
int new_length = max_samp_file - min_samp_file + 1;
if (new_length == 0)
return;
// System.out.println("final min_samp_file="+min_samp_file+" max="+max_samp_file);
// System.out.println("final min_samp_buf= "+min_samp_buf+" max="+max_samp_buf);
// System.out.println("final file_start="+file_start+" end="+file_end);
seekToLocation(pos);
if (_system.getFormatCode() == SystemLabel.TYPE_BYTE) {
_input_stream_wrap.readBytes(data, new_offset, new_length,
pixelStride);
}
else //!!!! OTHER CASES: MAYBE DONE IN WRAPPER????!!!!
throw new UnsupportedOperationException("Data type conversions not implemented yet!!!!");
}
}
| true |
afd94901e87ce09149e89f9f78176a6ad35ff9cc | Java | TRomesh/DailySelfie | /app/src/main/java/com/sliit/dailyselfie/Challenges/PostMaternityActivity.java | UTF-8 | 11,924 | 1.78125 | 2 | [] | no_license | package com.sliit.dailyselfie.Challenges;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.sliit.dailyselfie.AlertReciver.AlarmReciver;
import com.sliit.dailyselfie.Camera.CameraActivity;
import com.sliit.dailyselfie.DB.DBHelper;
import com.sliit.dailyselfie.R;
import com.vi.swipenumberpicker.OnValueChangeListener;
import com.vi.swipenumberpicker.SwipeNumberPicker;
import java.util.GregorianCalendar;
import picker.ugurtekbas.com.Picker.Picker;
public class PostMaternityActivity extends AppCompatActivity {
private EditText pmaternityname,pmaternityDescription;
private TextInputLayout inputLayoutName,inputLayoutDescription;
private Button btnAdd;
private SwipeNumberPicker pmaternityheight,pmaternityweight,pmaternityWaist,pmaternityTargetWaist;
String userID;
Button bset,bcancle;
Dialog d;
Picker picker;
Spinner spn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_maternity);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
findViewById(R.id.postMsetAlarm).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
d = new Dialog(PostMaternityActivity.this);
d.requestWindowFeature(Window.FEATURE_NO_TITLE);
d.setContentView(R.layout.alarmmodel);
bset = (Button) d.findViewById(R.id.BsetAlarm);
bcancle = (Button) d.findViewById(R.id.BcancleAlarm);
picker = (Picker) d.findViewById(R.id.amPicker);
picker.setClockColor(Color.parseColor("#2196F3"));
picker.setDialColor(Color.parseColor("#FF9800"));
picker.getCurrentHour();
picker.getCurrentMin();
d.show();
bset.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Toast.makeText(getApplicationContext(), "Set Alarm", Toast.LENGTH_SHORT).show();
d.dismiss();
}
});
bcancle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Toast.makeText(getApplicationContext(), "cancle Alarm", Toast.LENGTH_SHORT).show();
d.dismiss();
}
});
}
});
SharedPreferences userDetails = getSharedPreferences("userDetails", Context.MODE_PRIVATE);
userID = userDetails.getString("loggedUserId","");
spn = (Spinner)findViewById(R.id.postMdate);
final String [] challengePeriodType = getResources().getStringArray(R.array.challengePeriodType);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,challengePeriodType);
spn.setAdapter(adapter);
pmaternityheight = (SwipeNumberPicker)findViewById(R.id.snppostM0);
pmaternityheight.setOnValueChangeListener(new OnValueChangeListener() {
@Override
public boolean onValueChange(SwipeNumberPicker view, int oldValue, int newValue) {
return true;
}
});
pmaternityweight = (SwipeNumberPicker)findViewById(R.id.snppostM2);
pmaternityweight.setOnValueChangeListener(new OnValueChangeListener() {
@Override
public boolean onValueChange(SwipeNumberPicker view, int oldValue, int newValue) {
return true;
}
});
pmaternityWaist = (SwipeNumberPicker)findViewById(R.id.snppostM3);
pmaternityWaist.setOnValueChangeListener(new OnValueChangeListener() {
@Override
public boolean onValueChange(SwipeNumberPicker view, int oldValue, int newValue) {
return true;
}
});
pmaternityTargetWaist = (SwipeNumberPicker)findViewById(R.id.snppostM4);
pmaternityTargetWaist.setOnValueChangeListener(new OnValueChangeListener() {
@Override
public boolean onValueChange(SwipeNumberPicker view, int oldValue, int newValue) {
return true;
}
});
inputLayoutName = (TextInputLayout) findViewById(R.id.input_layout_postMName);
inputLayoutDescription = (TextInputLayout) findViewById(R.id.input_layout_postMdescription);
pmaternityname = (EditText)findViewById(R.id.postMName);
pmaternityDescription = (EditText)findViewById(R.id.postMdescription);
btnAdd = (Button) findViewById(R.id.postM_submit_btn);
pmaternityheight = (SwipeNumberPicker)findViewById(R.id.snppostM0);
pmaternityweight = (SwipeNumberPicker)findViewById(R.id.snppostM2);
pmaternityWaist = (SwipeNumberPicker)findViewById(R.id.snppostM3);
pmaternityTargetWaist = (SwipeNumberPicker)findViewById(R.id.snppostM4);
pmaternityname.addTextChangedListener(new MyTextWatcher(pmaternityname));
//fitDescription.addTextChangedListener(new MyTextWatcher(fitDescription));
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (submitForm()) {
String pmaternityChallangename = pmaternityname.getText().toString();
Double pmaternityHeight = Double.parseDouble((String) pmaternityheight.getText());
Double pmaternityWeight = Double.parseDouble((String) pmaternityweight.getText());
Double pmaternitywaist = Double.parseDouble((String) pmaternityWaist.getText());
Double pmaternitytargetwaist = Double.parseDouble((String) pmaternityTargetWaist.getText());
String pmaternitydescription = pmaternityDescription.getText().toString();
String type = "PostMaternity";
int userId = Integer.parseInt(userID);
DBHelper helper = new DBHelper(PostMaternityActivity.this);
String sql = "INSERT INTO challanges (type,name,height,weight,waistSize,targetWaistSize,description,userId)" +
" VALUES ('"+type+"','"+pmaternityChallangename+"','"+pmaternityHeight+"','"+pmaternityWeight+"','"+pmaternitywaist+"','"+pmaternitytargetwaist+"','"+pmaternitydescription+"','"+userId+"') ";
SQLiteDatabase db = helper.getWritableDatabase();
try {
db.execSQL(sql);
successfulAlert();
SharedPreferences cDetails = getSharedPreferences("cDetails", Context.MODE_PRIVATE);
SharedPreferences.Editor editor1 = cDetails.edit();
editor1.putString("chName",pmaternityChallangename);
editor1.apply();
} catch (SQLiteException e) {
AlertDialog.Builder a_builder = new AlertDialog.Builder(PostMaternityActivity.this);
a_builder.setMessage("User already exist!")
.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
pmaternityname.setText("");
pmaternityDescription.setText("");
dialog.cancel();
}
});
AlertDialog alert = a_builder.create();
alert.setTitle("Alert");
alert.show();
}
//Toast.makeText(this, "Registed !", Toast.LENGTH_LONG).show();
}
}
});
}
public void successfulAlert(){
AlertDialog.Builder a_builder = new AlertDialog.Builder(PostMaternityActivity.this);
a_builder.setMessage("Successfully created Post Maternity challange")
.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
pmaternityname.setText("");
pmaternityDescription.setText("");
startActivity(new Intent(getApplicationContext(), CameraActivity.class).putExtra("Challenge", "postmaternity"));
dialog.cancel();
}
});
AlertDialog alert = a_builder.create();
alert.setTitle("Congratulation!");
alert.show();
}
private boolean submitForm() {
if (!validatePMName()) {
return false;
}
return true;
}
private boolean validatePMName() {
if (pmaternityname.getText().toString().trim().isEmpty()) {
inputLayoutName.setError("Enter the Challange name");
requestFocus(pmaternityname);
return false;
} else {
inputLayoutName.setErrorEnabled(false);
return true;
}
}
private void requestFocus(View view) {
if (view.requestFocus()) {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
private class MyTextWatcher implements TextWatcher {
private View view;
private MyTextWatcher(View view) {
this.view = view;
}
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
public void afterTextChanged(Editable editable) {
switch (view.getId()) {
case R.id.postMName:
validatePMName();
break;
}
}
}
public void SetAlarmBroadcast(){
Long alertTime =new GregorianCalendar().getTimeInMillis();
Intent alertIntent = new Intent(PostMaternityActivity.this,AlarmReciver.class);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP,alertTime,PendingIntent.getBroadcast(PostMaternityActivity.this,1,alertIntent,PendingIntent.FLAG_UPDATE_CURRENT));
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,alertTime,alarmManager.INTERVAL_DAY*7,PendingIntent.getBroadcast(PostMaternityActivity.this,1,alertIntent,PendingIntent.FLAG_UPDATE_CURRENT));
}
}
| true |
b5eea1ecd38e12dbc8572ea4237badd642768f3e | Java | dannyhuo/easy-man | /src/main/java/com/easy/man/mapper/NodesMapper.java | UTF-8 | 520 | 1.867188 | 2 | [
"Apache-2.0"
] | permissive | package com.easy.man.mapper;
import com.easy.man.entity.po.Nodes;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.easy.man.entity.vo.NodesVO;
import java.util.List;
import java.util.Map;
/**
* <p>
* Mapper 接口
* </p>
*
* @author danny
* @since 2019-01-07
*/
public interface NodesMapper extends BaseMapper<Nodes> {
/**
* 查询节点及其节点的内存信息
* @param param
* @return
*/
List<NodesVO> listNodeAndMemoryByPage(Map<String, Object> param);
}
| true |
e6f6154cebc7dad985bc28c0453b011969cfd517 | Java | OrionOrg/Orion | /src/base-src/src/org/ratchetgx/orion/ssm/ugr/web/select/SelectGroupController.java | UTF-8 | 9,648 | 1.96875 | 2 | [] | no_license | package org.ratchetgx.orion.ssm.ugr.web.select;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONObject;
import org.ratchetgx.orion.ssm.ugr.service.select.SelectGroupService;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
@Controller
@RequestMapping(value = "ugr/select/selectGroup")
public class SelectGroupController extends MultiActionController {
private org.slf4j.Logger log = LoggerFactory.getLogger(this.getClass());
private SelectGroupService selectGroupService;
@Autowired
public void setSelectGroupService(SelectGroupService selectGroupService) {
this.selectGroupService = selectGroupService;
}
@RequestMapping(value="listSelectedOfRole")
public ModelAndView listSelectedOfRole(HttpServletRequest request,
HttpServletResponse response) throws Exception {
String role = request.getParameter("role");
List<Map<String, String>> groups = selectGroupService
.listSelectedOfRole(role);
JSONObject rev = new JSONObject();
JSONArray groupArray = new JSONArray();
Iterator<Map<String, String>> groupItr = groups.iterator();
while (groupItr.hasNext()) {
Map<String, String> map = groupItr.next();
JSONObject groupObject = new JSONObject();
groupObject.put("wid", map.get("wid"));
groupObject.put("name", map.get("name"));
groupArray.put(groupObject);
}
rev.put("groups", groupArray);
response.setContentType("text/json;charset=utf-8");
response.getWriter().println(rev);
return null;
}
@RequestMapping(value="listUnSelectedOfRole")
public ModelAndView listUnSelectedOfRole(HttpServletRequest request,
HttpServletResponse response) throws Exception {
String role = request.getParameter("role");
List<Map<String, String>> groups = selectGroupService
.listUnSelectedOfRole(role);
JSONObject rev = new JSONObject();
JSONArray groupArray = new JSONArray();
Iterator<Map<String, String>> groupItr = groups.iterator();
while (groupItr.hasNext()) {
Map<String, String> map = groupItr.next();
JSONObject groupObject = new JSONObject();
groupObject.put("wid", map.get("wid"));
groupObject.put("name", map.get("name"));
groupArray.put(groupObject);
}
rev.put("groups", groupArray);
response.setContentType("text/json;charset=utf-8");
response.getWriter().println(rev);
return null;
}
@RequestMapping(value="listSelectedOfUser")
public ModelAndView listSelectedOfUser(HttpServletRequest request,
HttpServletResponse response) throws Exception {
String userWid = request.getParameter("userWid");
List<Map<String, String>> groups = selectGroupService
.listSelectedOfUser(userWid);
JSONObject rev = new JSONObject();
JSONArray groupArray = new JSONArray();
Iterator<Map<String, String>> groupItr = groups.iterator();
while (groupItr.hasNext()) {
Map<String, String> map = groupItr.next();
JSONObject groupObject = new JSONObject();
groupObject.put("wid", map.get("wid"));
groupObject.put("name", map.get("name"));
groupArray.put(groupObject);
}
rev.put("groups", groupArray);
response.setContentType("text/json;charset=utf-8");
response.getWriter().println(rev);
return null;
}
@RequestMapping(value="listUnSelectedOfUser")
public ModelAndView listUnSelectedOfUser(HttpServletRequest request,
HttpServletResponse response) throws Exception {
String userWid = request.getParameter("userWid");
List<Map<String, String>> groups = selectGroupService
.listUnSelectedOfUser(userWid);
JSONObject rev = new JSONObject();
JSONArray groupArray = new JSONArray();
Iterator<Map<String, String>> groupItr = groups.iterator();
while (groupItr.hasNext()) {
Map<String, String> map = groupItr.next();
JSONObject groupObject = new JSONObject();
groupObject.put("wid", map.get("wid"));
groupObject.put("name", map.get("name"));
groupArray.put(groupObject);
}
rev.put("groups", groupArray);
response.setContentType("text/json;charset=utf-8");
response.getWriter().println(rev);
return null;
}
/**
* 取消用户组与某角色的对应关系
*
* @param request
* @param response
* @return
* @throws Exception
*/
@RequestMapping(value="cancelOfRole")
public ModelAndView cancelOfRole(HttpServletRequest request,
HttpServletResponse response) throws Exception {
String role = request.getParameter("role");
String groupWidsStr = request.getParameter("groupWids");
JSONArray groupWidArray = new JSONArray(groupWidsStr);
List<String> groupWids = new ArrayList<String>();
for (int i = 0; i < groupWidArray.length(); i++) {
groupWids.add(groupWidArray.getString(i));
}
final JSONObject rev = new JSONObject();
rev.put("success", true);
try {
selectGroupService.cancelOfRole(role, groupWids);
} catch (Exception e) {
log.error("", e);
rev.put("success", false);
}
response.setContentType("text/json;charset=utf-8");
response.getWriter().println(rev);
return null;
}
/**
* 添加用户组与某角色的关系
*
* @param request
* @param response
* @return
* @throws Exception
*/
@RequestMapping(value="addOfRole")
public ModelAndView addOfRole(HttpServletRequest request,
HttpServletResponse response) throws Exception {
String role = request.getParameter("role");
String groupWidsStr = request.getParameter("groupWids");
JSONArray groupWidArray = new JSONArray(groupWidsStr);
List<String> groupWids = new ArrayList<String>();
for (int i = 0; i < groupWidArray.length(); i++) {
groupWids.add(groupWidArray.getString(i));
}
final JSONObject rev = new JSONObject();
rev.put("success", true);
try {
selectGroupService.addOfRole(role, groupWids);
} catch (Exception e) {
log.error("", e);
rev.put("success", false);
}
response.setContentType("text/json;charset=utf-8");
response.getWriter().println(rev);
return null;
}
/**
* 取消用户与某用户的对应关系
*
* @param request
* @param response
* @return
* @throws Exception
*/
@RequestMapping(value="cancelOfUser")
public ModelAndView cancelOfUser(HttpServletRequest request,
HttpServletResponse response) throws Exception {
String userWid = request.getParameter("userWid");
String groupWidsStr = request.getParameter("groupWids");
JSONArray groupWidArray = new JSONArray(groupWidsStr);
List<String> groupWids = new ArrayList<String>();
for (int i = 0; i < groupWidArray.length(); i++) {
groupWids.add(groupWidArray.getString(i));
}
final JSONObject rev = new JSONObject();
rev.put("success", true);
try {
selectGroupService.cancelOfUser(userWid, groupWids);
} catch (Exception e) {
log.error("", e);
rev.put("success", false);
}
response.setContentType("text/json;charset=utf-8");
response.getWriter().println(rev);
return null;
}
/**
* 添加用户与某用户的对应关系
*
* @param request
* @param response
* @return
* @throws Exception
*/
@RequestMapping(value="addOfUser")
public ModelAndView addOfUser(HttpServletRequest request,
HttpServletResponse response) throws Exception {
String userWid = request.getParameter("userWid");
String groupWidsStr = request.getParameter("groupWids");
JSONArray groupWidArray = new JSONArray(groupWidsStr);
List<String> groupWids = new ArrayList<String>();
for (int i = 0; i < groupWidArray.length(); i++) {
groupWids.add(groupWidArray.getString(i));
}
final JSONObject rev = new JSONObject();
rev.put("success", true);
try {
selectGroupService.addOfUser(userWid, groupWids);
} catch (Exception e) {
log.error("", e);
rev.put("success", false);
}
response.setContentType("text/json;charset=utf-8");
response.getWriter().println(rev);
return null;
}
}
| true |
463469934fe1e1fcec47a445e8af0f664371a6e8 | Java | lamiaarakik/Machine-management-with-springboot-and-android | /src/main/java/com/example/demo/model/Produit.java | UTF-8 | 1,071 | 2.390625 | 2 | [] | no_license | package com.example.demo.model;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
public class Produit {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
private String code;
private String nom;
@Temporal(TemporalType.DATE)
private Date dateAchat;
private double prix;
public Produit() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public double getPrix() {
return prix;
}
public void setPrix(double prix) {
this.prix = prix;
}
public Date getDateAchat() {
return dateAchat;
}
public void setDateAchat(Date dateAchat) {
this.dateAchat = dateAchat;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
| true |
43f47487e81ef1f46ba5a4fec829e343251e15c8 | Java | JulianColihuinca/Teoria_de_la_Informacion | /TrabajoPracticoIntegrador2/src/main/java/main/Main.java | UTF-8 | 403 | 2.1875 | 2 | [] | no_license | package main;
import front.controladores.ControladorGeneral;
import front.views.VistaGeneral;
import front.views.interfaces.IVistaGeneral;
public class Main {
public static void main(String[] args) {
IVistaGeneral vista = new VistaGeneral();
ControladorGeneral controlador = new ControladorGeneral(vista);
vista.setControlador(controlador);
vista.abrir();
}
}
| true |
477c8649c6cad3a678e94a4fb77df44b0844fb5e | Java | dominikjaniga91/commandline-args | /src/main/java/picocli/ArgumentExceptionHandler.java | UTF-8 | 972 | 2.4375 | 2 | [] | no_license | package picocli;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Collectors;
import static picocli.CommandLine.*;
class ArgumentExceptionHandler implements IParameterExceptionHandler {
@Override
public int handleParseException(ParameterException ex, String[] strings) {
CommandLine cmd = ex.getCommandLine();
PrintWriter writer = cmd.getOut();
Model.CommandSpec spec = cmd.getCommandSpec();
String usage = "";
try {
usage = Files.readAllLines(Path.of("0_usage.screen")).stream().collect(Collectors.joining("\n"));
} catch (IOException exception) {
exception.printStackTrace();
}
writer.printf(usage);
return cmd.getExitCodeExceptionMapper() != null
? cmd.getExitCodeExceptionMapper().getExitCode(ex)
: spec.exitCodeOnInvalidInput();
}
}
| true |
dfebeea1c8ed965186b8d187091a25d1fa82c358 | Java | jcinqmars2000/phonelist | /PhoneList_old/src/main/java/com/steereengineering/converters/PhoneListToPhoneListCommand.java | UTF-8 | 940 | 2.359375 | 2 | [] | no_license | package com.steereengineering.converters;
import com.steereengineering.commands.PhoneListCommand;
import com.steereengineering.model.PhoneList;
import lombok.Synchronized;
import org.springframework.core.convert.converter.Converter;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
@Component
public class PhoneListToPhoneListCommand implements Converter<PhoneList, PhoneListCommand> {
@Synchronized
@Nullable
@Override
public PhoneListCommand convert(PhoneList phoneList) {
if (phoneList != null) {
final PhoneListCommand plc = new PhoneListCommand();
plc.setId(phoneList.getId());
plc.setFirstname(phoneList.getFirstname());
plc.setLastname(phoneList.getFirstname());
plc.setEmail(phoneList.getEmail());
plc.setExtension(phoneList.getExtension());
plc.setCellphone(phoneList.getCellphone());
return plc;
}
return null;
}
}
| true |
1b1c350eb48750fbedf7a20885d99f5a0ab2a3ac | Java | xiusan/xiao | /src/main/java/com/xjl/partten/xjldemo/flyweight/Shape.java | UTF-8 | 140 | 1.96875 | 2 | [] | no_license | package com.xjl.partten.xjldemo.flyweight;
/**
* Created by xiaojinlu1990@163.partten on 2019/11/27.
*/
public interface Shape {
public void draw();
}
| true |
173277fd4e76163c6fa2880f23e6e7705a62ed34 | Java | anand96769/geeksforgeeks | /src/com/practice/programs/basicprograms/PalindromeNumber.java | UTF-8 | 952 | 3.796875 | 4 | [] | no_license | package com.practice.programs.basicprograms;
import java.util.Scanner;
public class PalindromeNumber {
public static void main(String[] args) {
System.out.println("Enter Number to check number is palidrome or not - ");
Scanner scanner = new Scanner ( System.in );
int num = scanner.nextInt ();
if (isPalindromeNumber ( num )){
System.out.println("The Given num is Palidrome num");
}else{
System.out.println ("Num is Not Palidrome nums");
}
}
public static boolean isPalindromeNumber(int num){
int remainder = 0;
boolean isPalidromeNumber = false;
int copyOfNum = num;
while (num > 0){
int rem = num % 10;
num = num / 10;
remainder = (remainder * 10) +rem;
}
if (remainder == copyOfNum){
isPalidromeNumber = true;
}
return isPalidromeNumber;
}
}
| true |
4089cd47596130b7b2c1abfeeef82024009350a0 | Java | yujin122/MovieReview | /MovieReview/src/main/java/com/movie/model/CommDAOImpl.java | UTF-8 | 2,232 | 2.015625 | 2 | [] | no_license | package com.movie.model;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.movie.service.Pagination;
@Repository
public class CommDAOImpl implements CommDAO{
@Autowired
private SqlSessionTemplate sqlSession;
String sql;
@Override
public List<CommDTO> getCommList(int bnum, Pagination pagination) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("bnum", bnum);
map.put("startNo", pagination.getStartNo());
map.put("rowsize", pagination.getRowsize());
return sqlSession.selectList("getCommList", map);
}
@Override
public int insertComm(CommDTO dto) {
return sqlSession.insert("insertComm", dto);
}
@Override
public int deleteComm(int comm_num) {
return sqlSession.delete("deleteComm", comm_num);
}
@Override
public int deleteBoardComm(int bnum) {
return sqlSession.delete("deleteBoardComm", bnum);
}
@Override
public int updateComm(CommDTO dto) {
return sqlSession.update("updateComm", dto);
}
@Override
public CommDTO getCommCont(int comm_num) {
return sqlSession.selectOne("getCommCont", comm_num);
}
@Override
public int getMaxStep(int comm_group) {
return sqlSession.selectOne("getMaxStep", comm_group);
}
@Override
public int insertCommReply(final CommDTO dto) {
return sqlSession.insert("insertCommReply", dto);
}
@Override
public int getCommCnt(int bnum) {
return sqlSession.selectOne("getCommCnt", bnum);
}
@Override
public int getMyCommCnt(String mem_id) {
return sqlSession.selectOne("getMyCommCnt", mem_id);
}
@Override
public List<CommDTO> getMyCommList(String mem_id, Pagination pagination) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("mem_id", mem_id);
map.put("startNum", pagination.getStartNo());
map.put("rowsize", pagination.getRowsize());
return sqlSession.selectList("getMyCommList", map);
}
@Override
public int getMaxNum() {
return sqlSession.selectOne("getMaxNum");
}
@Override
public int getCommAllCnt() {
return sqlSession.selectOne("getCommAllCnt");
}
}
| true |
0d40967c65afbeed9784ad2fbfddc0e87eaeb9ec | Java | hailid88/FLAG | /src/com/multi/threading/SemaphoreTest2.java | UTF-8 | 1,036 | 3.640625 | 4 | [] | no_license | package com.multi.threading;
import java.util.concurrent.Semaphore;
public class SemaphoreTest2 {
public static void main(String[] args){
Semaphore s = new Semaphore(1); // binary
Thread task1 = new Thread(new ExclusiveTask("Task 1", s));
Thread task2 = new Thread(new ExclusiveTask("Task 2", s));
Thread task3 = new Thread(new ExclusiveTask("Task 3", s));
task1.start();
task2.start();
task3.start();
}
}
class ExclusiveTask implements Runnable{
private String name = null;
private Semaphore shared = null;
public ExclusiveTask(String name, Semaphore shared){
this.name = name;
this.shared = shared;
}
@Override
public void run(){
try {
Thread.sleep(1000);
shared.acquire();
System.out.println("Trying to enter the critical region");
System.out.println("Running Task " + name);
} catch (InterruptedException e) {
e.printStackTrace();
}
finally{
System.out.println("Leave the critical region");
shared.release();
}
}
}
| true |
8881dae1cb8fa5b6814542724d0a139e6e318706 | Java | qqsandy/2240_votingSystem | /src/Candidate.java | UTF-8 | 1,248 | 3.34375 | 3 | [] | no_license | public class Candidate extends BallotCreation{
// Private field from class diagram
private String candidateName;
private String candidateBiography;
// An no arg constructor that takes super.
Candidate(){
super();
this.candidateName="Leroy Jenkins";
this.candidateBiography="Great voice";
}
// An argument constructor that is used to iniltalize the instance of the candidate class
public Candidate(String candidateName, String candidateBiography){
this.candidateName=candidateName;
this.candidateBiography=candidateBiography;
}
// An toString method that overrides a method in BallotCreation. Used to display candidate's name.
@Override
public String toString(){
return candidateName;
}
// Setters and getters of the private fields in this Candidate class
public void setCandidateName(String candidateName){
this.candidateName=candidateName;
}
public String getCandidateName(){
return candidateName;
}
public void setCandidateBiography(String candidateBio){
this.candidateBiography=candidateBio;
}
public String getCandidateBiography(){
return this.candidateBiography;
}
} | true |
8be9b80b90a60c2e11626b2860af214d59502add | Java | vishalpawale/FastFeeds | /src/com/sudosaints/rssfeeds/db/DbUtils.java | UTF-8 | 401 | 2.09375 | 2 | [] | no_license | package com.sudosaints.rssfeeds.db;
import android.content.Context;
public class DbUtils {
Context context;
DbHelper dbHelper;
public DbUtils(Context context) {
super();
this.context = context;
}
public DbHelper getDbHelper() {
if(dbHelper != null && dbHelper.isDbOpened()) {
return dbHelper;
}
dbHelper = new DbHelper(context);
dbHelper.open();
return dbHelper;
}
}
| true |
33275dc8a452ef5560856087410b216405f7df83 | Java | nikugame/share-sdk-android | /app/src/main/java/com/nikugame/tanchishe/wxapi/WXEntryActivity.java | UTF-8 | 2,650 | 2.125 | 2 | [] | no_license | package com.nikugame.tanchishe.wxapi;
import android.app.Activity;
import android.os.Bundle;
import com.nkgame.nksharesdk.NKShareConfig;
import com.nkgame.nksharesdk.NKShareConstants;
import com.nkgame.nksharesdk.NKShareListener;
import com.nkgame.nksharesdk.NKShareLog;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
/**
* Created by zhangzhen on 2016/11/21.
*/
public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
private IWXAPI mApi;
private MyListener listener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mApi = WXAPIFactory.createWXAPI(this, NKShareConfig.getInstatnce().getAppId_Wechat(), true);
mApi.handleIntent(this.getIntent(), this);
}
@Override
public void onReq(BaseReq baseReq) {
}
@Override
public void onResp(BaseResp baseResp) {
listener=new MyListener();
switch (baseResp.errCode) {
case BaseResp.ErrCode.ERR_OK:
//发送成功
NKShareLog.NKGame.e("分享成功");
listener.onResult(NKShareConstants.ResultOK,NKShareConstants.ShareSuccess);
break;
case BaseResp.ErrCode.ERR_USER_CANCEL:
listener.onResult(NKShareConstants.ResultUserCancel,NKShareConstants.ShareCanceled);
NKShareLog.NKGame.e("分享取消");
//发送取消
break;
case BaseResp.ErrCode.ERR_AUTH_DENIED:
//发送被拒绝
NKShareLog.NKGame.e("认证被拒绝");
listener.onResult(NKShareConstants.ResultUnknownError,NKShareConstants.SharetFailed);
break;
default:
//发送返回
NKShareLog.NKGame.e("分享返回");
listener.onResult(NKShareConstants.ResultUnknownError,NKShareConstants.SharetFailed);
break;
}
finish();
}
private class MyListener implements NKShareListener {
@Override
public void onInit(int errorCode, String result) {
}
@Override
public void onResult(int errorCode, String result) {
NKShareLog.NKGame.e("errorCode: "+errorCode+" ,result: "+result);
// WXEntryActivity.this.finish();
}
@Override
public void onAuth(int errorCode, String result) {
}
}
}
| true |
4a1a70dc8b160ee125293002dde20a6789f811dc | Java | qu3stbaby/chimeapp | /app/src/main/java/info/guardianproject/chime/MainActivity.java | UTF-8 | 12,411 | 1.617188 | 2 | [
"Apache-2.0"
] | permissive | package info.guardianproject.chime;
import android.app.ActionBar;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import org.altbeacon.beacon.BeaconConsumer;
import org.altbeacon.beacon.BeaconManager;
import org.altbeacon.beacon.MonitorNotifier;
import org.altbeacon.beacon.Region;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import info.guardianproject.chime.db.ChimeAdapter;
import info.guardianproject.chime.db.ChimeEventAdapter;
import info.guardianproject.chime.geo.GeoManager;
import info.guardianproject.chime.model.Chime;
import info.guardianproject.chime.model.ChimeEvent;
import info.guardianproject.chime.service.ChimeNotifier;
import info.guardianproject.chime.service.WifiJobService;
import info.guardianproject.chime.service.WifiReceiver;
import static android.net.wifi.WifiManager.WIFI_STATE_CHANGED_ACTION;
public class MainActivity extends AppCompatActivity implements BeaconConsumer {
private SwipeRefreshLayout refreshLayout;
private BottomNavigationView navigation;
@Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(R.style.AppTheme);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.abs_layout);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
refreshLayout = (SwipeRefreshLayout)findViewById(R.id.swipe_layout);
refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
if (hasPermissions()) {
listenForChimes();
if (navigation.getSelectedItemId() == R.id.navigation_home)
showHomeList();
else if (navigation.getSelectedItemId() == R.id.navigation_dashboard)
showDashboardList();
else
showChimeEventList();
}
refreshLayout.setRefreshing(false);
}
});
List<Chime> chimeList = Chime.listAll(Chime.class);
if (chimeList.size() == 0)
{
startActivity(new Intent(this,OnboardingActivity.class));
}
else {
if (hasPermissions())
showHomeList();
}
}
@Override
protected void onResume() {
super.onResume();
showHomeList();
wifiReceiver = new WifiReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
registerReceiver(wifiReceiver,intentFilter);
new ChimeNotifier(this).clearAll();
}
WifiReceiver wifiReceiver;
ChimeAdapter chimeAdapter;
ChimeEventAdapter chimeEventAdapter;
RecyclerView recyclerView;
@Override
protected void onDestroy() {
super.onDestroy();
chimeAdapter.onDestroy();
beaconManager.unbind(this);
GeoManager.disconnect();
unregisterReceiver(wifiReceiver);
}
private List<Chime> chimeList;
private void showHomeList ()
{
String[] args = {"1"};
chimeList = Chime.find(Chime.class,"is_nearby = ?",args,null,"last_seen DESC",null);
if (chimeList.size() > 0) {
recyclerView.setVisibility(View.VISIBLE);
findViewById(R.id.empty_view).setVisibility(View.GONE);
chimeAdapter = new ChimeAdapter(this, chimeList, R.layout.layout_card_large);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(chimeAdapter);
}
else
{
recyclerView.setVisibility(View.GONE);
}
}
List<Chime> chimeDashList;
ChimeAdapter chimeDashAdapter;
private void showDashboardList ()
{
chimeDashList = Chime.listAll(Chime.class);
chimeDashList = Chime.find(Chime.class,null,null,null,"last_seen DESC",null);
if (chimeDashList.size() > 0) {
recyclerView.setVisibility(View.VISIBLE);
chimeDashAdapter = new ChimeAdapter(this, chimeDashList, R.layout.layout_card_mixed);
RecyclerView.LayoutManager mLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(chimeDashAdapter);
}
}
private void showChimeEventList ()
{
List<ChimeEvent> chimeEventList = ChimeEvent.listAll(ChimeEvent.class);
chimeEventAdapter = new ChimeEventAdapter(this, chimeEventList, R.layout.layout_card_event_small);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(chimeEventAdapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
//mDrawerLayout.openDrawer(GravityCompat.START);
return true;
case R.id.menu_add_chime:
addNewChime();
return true;
case R.id.menu_scan:
listenForChimes();
return true;
}
return super.onOptionsItemSelected(item);
}
private void addNewChime ()
{
if (hasPermissions()) {
Intent sintent = new Intent(this, AddNewChimeActivity.class);
startActivity(sintent);
}
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
showHomeList();
return true;
case R.id.navigation_dashboard:
showDashboardList();
return true;
case R.id.navigation_notifications:
showChimeEventList();
return true;
}
return false;
}
};
private boolean hasPermissions ()
{
if (askForPermission("android.permission.ACCESS_FINE_LOCATION",1))
return false;
return true;
}
private boolean askForPermission(String permission, Integer requestCode) {
if (ContextCompat.checkSelfPermission(MainActivity.this, permission) != PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, permission)) {
//This is called if user has denied the permission before
//In this case I am just asking the permission again
ActivityCompat.requestPermissions(MainActivity.this, new String[]{permission}, requestCode);
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{permission}, requestCode);
}
return true;
}
return false;
}
private BeaconManager beaconManager;
private void initBeaconSupport ()
{
beaconManager = BeaconManager.getInstanceForApplication(this);
// To detect proprietary beacons, you must add a line like below corresponding to your beacon
// type. Do a web search for "setBeaconLayout" to get the proper expression.
// beaconManager.getBeaconParsers().add(new BeaconParser().
// setBeaconLayout("m:2-3=beac,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25"));
beaconManager.bind(this);
}
@Override
public void onBeaconServiceConnect() {
Snackbar snackbar = Snackbar.make(recyclerView, R.string.status_beacons,Snackbar.LENGTH_LONG);
snackbar.show();
beaconManager.addMonitorNotifier(new MonitorNotifier() {
@Override
public void didEnterRegion(Region region) {
// Log.i(TAG, "I just saw an beacon for the first time!");
String[] args = {region.getBluetoothAddress()};
List<Chime> chimes = Chime.find(Chime.class,"ssid = ?",args);
if (chimes.size() == 0)
{
Chime chime = new Chime();
chime.name = region.getBluetoothAddress();
chime.lastSeen = new Date();
chime.isNearby = true;
chime.ssid = region.getBluetoothAddress();
chime.serviceType = "altbeacon";
chime.chimeId = region.getUniqueId();
if (region.getId1() != null)
{
chime.serviceUri = region.getId1().toString();
}
chime.save();
ChimeEvent event = new ChimeEvent();
event.type = ChimeEvent.TYPE_FOUND_NEW_CHIME;
event.happened = chime.lastSeen;
event.description = getString(R.string.status_beacon_found);
event.chimeId = chime.getId()+"";
event.save();
showHomeList();
}
}
@Override
public void didExitRegion(Region region) {
// Log.i(TAG, "I no longer see an beacon");
String[] args = {region.getBluetoothAddress()};
List<Chime> chimes = Chime.find(Chime.class,"ssid = ?",args);
for (Chime chime : chimes)
{
chime.isNearby = false;
chime.lastSeen = new Date();
chime.save();
}
}
@Override
public void didDetermineStateForRegion(int state, Region region) {
// Log.i(TAG, "I have just switched from seeing/not seeing beacons: "+state);
}
});
try {
beaconManager.startMonitoringBeaconsInRegion(new Region("chime1", null, null, null));
} catch (RemoteException e) { }
}
private void listenForChimes ()
{
initBeaconSupport();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
WifiJobService.initJob(this);
}
}
}
| true |
56ab67b241a8779c2aa2958b185fdc1c7668861b | Java | 2dum/DongerText | /DongerFont.java | UTF-8 | 835 | 2.953125 | 3 | [] | no_license | package dongerfont;
import java.util.Scanner;
import java.awt.datatransfer.*;
import java.awt.Toolkit;
public class DongerFont
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter phrase: ");
String phrase = scan.nextLine();
Scanner input = new Scanner(phrase);
String word;
String output = "";
while (input.hasNext())
{
word = input.next();
DongerText.convert(word);
output += DongerText.getOutput();
}
input.close();
StringSelection ss = new StringSelection(output);
Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
cb.setContents(ss, null);
System.out.println("You can now paste your new text!");
}
}
| true |