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
b9919d99c16876af287a06f7ba2cc3f2d28cca1d
Java
ZYFCodes/zyfboot-javabasic
/src/main/java/org/zyf/javabasic/es/service/impl/IndexGoodServiceImpl.java
UTF-8
3,611
2.03125
2
[]
no_license
package org.zyf.javabasic.es.service.impl; import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; import org.elasticsearch.action.support.master.AcknowledgedResponse; import org.elasticsearch.client.IndicesClient; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.client.indices.CreateIndexRequest; import org.elasticsearch.client.indices.CreateIndexResponse; import org.elasticsearch.client.indices.GetIndexRequest; import org.elasticsearch.client.indices.GetIndexResponse; import org.elasticsearch.cluster.metadata.MappingMetaData; import org.elasticsearch.common.xcontent.XContentType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.zyf.javabasic.es.service.IndexGoodService; import java.util.Map; /** * @author yanfengzhang * @description 索引服务类 * @date 2022/12/7 23:03 */ @Service public class IndexGoodServiceImpl implements IndexGoodService { @Autowired private RestHighLevelClient restHighLevelClient; /** * 创建索引 * * @param indexName 索引名 * @param mapping 映射结构配置 * @return true-创建成功 * @throws Exception 异常 */ @Override public boolean indexCreate(String indexName, String mapping) throws Exception { CreateIndexRequest indexRequest = new CreateIndexRequest(indexName); IndicesClient indicesClient = restHighLevelClient.indices(); indexRequest.mapping(mapping, XContentType.JSON); // 请求服务器 CreateIndexResponse response = indicesClient.create(indexRequest, RequestOptions.DEFAULT); return response.isAcknowledged(); } /** * 获取索引结构 * * @param indexName 索引名 * @return 索引结构 * @throws Exception 异常 */ @Override public Map<String, Object> getMapping(String indexName) throws Exception { IndicesClient indicesClient = restHighLevelClient.indices(); // 创建get请求 GetIndexRequest request = new GetIndexRequest(indexName); // 发送get请求 GetIndexResponse response = indicesClient.get(request, RequestOptions.DEFAULT); // 获取表结构 Map<String, MappingMetaData> mappings = response.getMappings(); Map<String, Object> sourceAsMap = mappings.get(indexName).getSourceAsMap(); return sourceAsMap; } /** * 删除索引库 * * @param indexName 索引名 * @return true-删除成功 * @throws Exception 异常 */ @Override public boolean indexDelete(String indexName) throws Exception { IndicesClient indicesClient = restHighLevelClient.indices(); // 创建delete请求方式 DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(indexName); // 发送delete请求 AcknowledgedResponse response = indicesClient.delete(deleteIndexRequest, RequestOptions.DEFAULT); return response.isAcknowledged(); } /** * 判断索引是否存在 * * @param indexName 索引名 * @return true-存在 * @throws Exception 异常 */ @Override public boolean indexExists(String indexName) throws Exception { IndicesClient indicesClient = restHighLevelClient.indices(); // 创建get请求 GetIndexRequest request = new GetIndexRequest(indexName); // 判断索引库是否存在 return indicesClient.exists(request, RequestOptions.DEFAULT); } }
true
776d5d9c4c2270246cbd072e3c9183186e7f400d
Java
liangmengmeng/ThePeople
/app/src/main/java/com/people/ui/adapter/DayNewsAdapter.java
UTF-8
2,718
2.40625
2
[]
no_license
package com.people.ui.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.people.R; import com.people.api.bean.SectionListBean; import java.util.ArrayList; /** * autour: 梁萌萌 * date: 2017/1/12 15:23 * update: 2017/1/12 */ public class DayNewsAdapter extends RecyclerView.Adapter<DayNewsAdapter.MyViewHolder> { private ArrayList<SectionListBean.DataBean> list; private Context context; private static OnItemClickListener mOnItemClickListener; //设置点击和长按事件 public interface OnItemClickListener { void onItemClick(View view, int position); //设置点击事件 } public static void setOnItemClickListener(OnItemClickListener listener) { mOnItemClickListener = listener; } public DayNewsAdapter(Context context, ArrayList<SectionListBean.DataBean> list) { this.context=context; this.list=list; } @Override public DayNewsAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { MyViewHolder holder=new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.fm2_recycler_item,parent,false)); return holder; } @Override public void onBindViewHolder(final DayNewsAdapter.MyViewHolder holder, final int position) { holder.tv1.setText(list.get(position).getDescription()); Glide.with(context) .load(list.get(position).getThumbnail()) .into(holder.iv); holder.tv2.setText(list.get(position).getName()); if (mOnItemClickListener != null) { holder.itemView.setOnClickListener(new View.OnClickListener() { //itemview是holder里的所有控件,可以单独设置比如ImageButton Button等 @Override public void onClick(View v) { mOnItemClickListener.onItemClick(holder.itemView,position); } }); } } @Override public int getItemCount() { return list.size(); } public class MyViewHolder extends RecyclerView.ViewHolder{ ImageView iv; TextView tv1; TextView tv2; public MyViewHolder(View itemView) { super(itemView); iv = (ImageView) itemView.findViewById(R.id.fm2_recycler_image); tv1 = (TextView) itemView.findViewById(R.id.fm2_recycler_desc); tv2 = (TextView) itemView.findViewById(R.id.fm2_recycler_title); } } }
true
a7408187758bb75bdb48d6651d169d06cbacacb5
Java
vi34/DKVS
/src/com/vi34/Client.java
UTF-8
3,332
3
3
[]
no_license
package com.vi34; import java.io.IOException; import java.util.Scanner; /** * Created by vi34 on 11/06/16. */ public class Client { static Proxy proxy; public static void main(String[] args) { try (Proxy p = new Proxy()){ proxy = p; if (args.length == 1 && args[0].equals("auto")) { autoClient(); } else { consoleClient(); } } catch (IOException e) { e.printStackTrace(); } } private static void consoleClient() { proxy.directConnect("lead"); Scanner scanner = new Scanner(System.in); while (true) { System.out.print("> "); String cmd = scanner.nextLine(); if (cmd.startsWith("get") || cmd.startsWith("set") || cmd.startsWith("ping") || cmd.startsWith("delete") ) { if (correctReq(cmd)) { System.out.println(proxy.sendRequest(cmd)); } else { System.out.println("wrong command: " + cmd); } } else if (cmd.startsWith("node")) { String[] tmp = cmd.split(" "); if (tmp.length != 2) { System.out.println("wrong command: " + cmd); } else { System.out.println(proxy.directConnect(cmd.split(" ")[1])); } } else if (cmd.startsWith("exit")) { return; } else { System.out.println("unknown command"); } } } private static void autoClient() { Server.cleanLogs(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } int n = 3; for (int i = 0; i < n; ++i) { Server.startNode(i + 1); } try { Thread.sleep(100); proxy.directConnect("lead"); makeReq("get x"); makeReq("ping"); makeReq("set x 10"); makeReq("get x"); makeReq("set y 20"); System.out.println("==== stop 1 ===="); Server.stopNode(1); Thread.sleep(3000); makeReq("set z 50"); Thread.sleep(2000); System.out.println("==== start 1 ===="); Server.startNode(1); makeReq("get x"); makeReq("get y"); makeReq("get z"); Thread.sleep(4000); } catch (InterruptedException e) { e.printStackTrace(); } finally { for (int i = 0; i < n; ++i) { Server.stopNode(i + 1); } } } private static boolean correctReq(String s) { String[] parts = s.split(" "); switch (parts[0]) { case "get": return parts.length == 2; case "set": return parts.length == 3; case "delete": return parts.length == 2; case "ping": return parts.length == 1; default: return false; } } private static void makeReq(String req) { System.out.println("\n> " + req); System.out.println("\n< " + proxy.sendRequest(req)); } }
true
474233d69b47a33db97dd81bdae95286999c67c7
Java
LaDellafa/TankBuddy
/Tank Buddy/src/tankbuddy/ITankBuddy.java
UTF-8
172
1.617188
2
[]
no_license
package tankbuddy; public interface ITankBuddy { void inloggen(String gebruikersnaam, String wachtwoord); void registreren(String gebruikersnaam, String wachtwoord); }
true
4617e111e82eb38df6c44d1afb42973db1c85c08
Java
nurban/NJUPOSProject
/src/posproject/CashRegister.java
UTF-8
2,956
3.421875
3
[]
no_license
package posproject; /** * * @author Neil Urban * Version: 1.0 */ public class CashRegister { //create a new receipt object -- used to at call the method which outputs //completed receipt. private Receipt receipt = new Receipt(); //Instantiate Discount Strategy objects for each sub-type of discount. IDiscountStrategy xmasDiscount = new ChristmasDiscountStrategy(); IDiscountStrategy halfDiscount = new HalfOffDiscountStrategy(); IDiscountStrategy noDiscount = new NoDiscountStrategy(); IDiscountStrategy schoolDiscount = new BackToSchoolDiscountStrategy(); IDiscountStrategy quarterDiscount = new QuarterOffDiscountStrategy(); IDiscountStrategy blackFridayDiscount = new BlackFridayDiscountStrategy(); //create an array of products and pass the values over to Product class. //objects of the varying discount strategy types are used to pass discounts. private Product[] products = { new Product("A101", "Nintendo 3DS ", 199.99, xmasDiscount), new Product("B205", "XL Abercrombie Hoodie", 35.50, halfDiscount), new Product("C222", "Men's Underwear ", 9.50, noDiscount), new Product("L135", "Backpack ", 17.95, schoolDiscount), new Product("F198", "MacBook Pro ", 1499.99, quarterDiscount), new Product("H123", "Hoover Vacuum ", 249.99, blackFridayDiscount) }; //method which adds each product to the item line. public final void addPurchasedProductToLine(String productID, int quantity) { Product product = null; for (Product p : products) { if (productID.equals(p.getProductName())) { product = p; break; } } if (product != null) { receipt.addNewLineItem(product, quantity); } } //create an array of customers and pass the values over to Customer class. private Customer[] customers = { new Customer("A117", "Adam Smith", "1234 S Main Street, Waukesha, WI"), new Customer("F22J", "Jessica Rodriguez", "9753 Mapleton Drive, Watertown, WI"), new Customer("B379", "Joe Shmoe", "4631 W Java Drive, Madison, WI") }; //method which adds each customer to the item line. public final void addCustomerToReceipt(String customerID) { Customer customer = null; //check to see if a for (Customer c : customers) { if (customerID.equals(c.getCustomerID())) { customer = c; break; } } //add the customer to the receipt, if one is found. if (customer != null) { receipt.setCustomerInfo(customer); } } //calls the method in Receipt, to print the complete receipt. public final void printCompleteReceipt() { receipt.printReceipt(); } }
true
55a781c8daeb0fd4169296b3a6be89100f9fdfe3
Java
michal-sydoryk/OX
/src/main/java/com/michalsydoryk/app/ui/UI.java
UTF-8
133
2.078125
2
[]
no_license
package com.michalsydoryk.app.ui; public interface UI<T> { int takeInput(); void print(T toPrint); void printBoard(); }
true
c110ddfff37f105f60c87bf960db22804d702e3b
Java
harborl/RTCrawler
/src/main/java/io/harborl/crawler/core/Result.java
UTF-8
781
2.421875
2
[ "MIT" ]
permissive
package io.harborl.crawler.core; import java.util.List; /** * The operation result returns by the {@linkplain Robot#startAndAwait(long, java.util.concurrent.TimeUnit)} * call. <br/> * * <h4>NOTE</h4> * You can customize or decorate the result through the same way of * {@linkplain HTMLResult}. * @author Harbor Luo * @since v0.0.1 * @param <T> the result entity type * @param <V> the external data type * */ public interface Result<T, V> { /** Returns the size of this result */ int size(); /** Returns all results without any filter test */ List<T> get(); /** Returns the qualified results with a filter test */ List<T> get(Filter<T> filter); /** Returns the external data besides the productions, * or null if not exists */ V ext(); }
true
bf2d0c1c3c4ff219d991c282d005c4459beb6d73
Java
anton96121/Agil-opgaver
/Mojn/src/test/Plusser.java
UTF-8
1,222
3.40625
3
[]
no_license
package test; public class Plusser { public static int add(int x, int y) { return x+y*x*x; } public static int loop1(int n) { int x = 0; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) x++; } return x; } public static int loop2(int n) { int x = 0; for(int i = 0; i <= n; i++) x++; for(int j = 0; j <= n; j++) x++; return x; } public static int loop3(int n) { int x = 0; for(int i = 0; i < n; i++) { if (i == n-1) for(int j = 0; j < n; j++) x++; } return x; } public static int loop4(int n) { int x = 0; for(int i = 0; i < n; i++) { for(int j = i; j < n; j++) x++; } return x; } public static int f(int n) { int[] A = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}; int k = 0; for(int i=0; i<n; i++){ k = k + A[i]; } return k; } public static void main(String[] args) { System.out.format("a: %d, b: %d, c: %d, d: %d, e: %d, f: %d", loop1(1000), loop2(1000), loop3(1000), loop4(1000), f(10), add(5,6)); } }
true
76ba048ba756e046d7b9e2dd4c5595f381efea3b
Java
smartBun/multimodules
/multimodules-web/src/test/java/com/learn/designPattern/creationalPatterns/factory/abstractFactory/concreteProduct/Display.java
UTF-8
529
3.125
3
[]
no_license
package com.learn.designPattern.creationalPatterns.factory.abstractFactory.concreteProduct; import com.learn.designPattern.creationalPatterns.factory.abstractFactory.abstractProduct.AbstractPeripheralProduct; import com.learn.designPattern.creationalPatterns.factory.abstractFactory.abstractProduct.OutputAble; public class Display extends AbstractPeripheralProduct implements OutputAble { @Override public String output() { System.out.println("This is a display. Made In " + getMadeIn()); return "Output a movie"; } }
true
a0639bbf082016bc7350f656820e9bed4a25d5f1
Java
fil7/XO-demo
/src/ru/fil7/demo/xo/XOCLI.java
UTF-8
647
2.65625
3
[]
no_license
package ru.fil7.demo.xo; import ru.fil7.demo.xo.model.*; import ru.fil7.demo.xo.view.ConsoleView; public class XOCLI { public static void main(final String[] args) { final String name1 = "Max"; final String name2 = "Alex"; final Player[] players = new Player[2]; players[0] = new Player(name1, Figure.X); players[1] = new Player(name2, Figure.O); final Game game = new Game(players, new Field(3), "XO"); final ConsoleView consoleView = new ConsoleView(); consoleView.show(game); while(consoleView.move(game)) { consoleView.show(game); } } }
true
3bc1ded2ba44bf7d6ddca415f5793e7e460f6287
Java
atongmu376/food-pairing
/src/main/java/com/phj/service/impl/SysRolePermissionRelationServiceImpl.java
UTF-8
5,254
2
2
[]
no_license
package com.phj.service.impl; import com.baomidou.mybatisplus.core.conditions.Wrapper; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.phj.mapper.SysRolePermissionRelationMapper; import com.phj.pojo.SysRolePermissionRelation; import com.phj.service.SysRolePermissionRelationService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * <p> * 角色权限关系表 服务实现类 * </p> * * @author Mr.Pan * @since 2021-08-19 */ @Service public class SysRolePermissionRelationServiceImpl implements SysRolePermissionRelationService { private final Logger logger = LoggerFactory.getLogger(SysRolePermissionRelationServiceImpl.class); @Autowired private SysRolePermissionRelationMapper sysRolePermissionRelationMapper; /** * @param id 通过id查询 SysRolePermissionRelation * @return SysRolePermissionRelation */ @Override public SysRolePermissionRelation selectById(Long id) { return sysRolePermissionRelationMapper.selectById(id); } /** * @param ids 通过id批量查询 SysRolePermissionRelation * @return SysRolePermissionRelation */ @Override public List<SysRolePermissionRelation> selectByIds(List<Long> ids) { return sysRolePermissionRelationMapper.selectBatchIds(ids); } /** param构建条件 */ @Override public List<SysRolePermissionRelation> selectList(SysRolePermissionRelation param){ Wrapper<SysRolePermissionRelation> wrapper = getWrapper(param); return sysRolePermissionRelationMapper.selectList(wrapper); } /** * 查询All * @return List<SysRolePermissionRelation> */ @Override public List<SysRolePermissionRelation> selectAll(){ return sysRolePermissionRelationMapper.selectList(null); } /** 分页查询所有 */ @Override public Page<SysRolePermissionRelation> selectPage(Integer currentNo, Integer pageSize) { if(currentNo<=0){ currentNo=1; } if(pageSize<=0){ pageSize=10; } Page page=new Page<SysRolePermissionRelation>(currentNo,pageSize,true); return sysRolePermissionRelationMapper.selectPage(page,null); } /** * @param param 通过param构建条件查询多个SysRolePermissionRelation * @return List<SysRolePermissionRelation> */ @Override public Page<SysRolePermissionRelation> selectPage(Integer currentNo, Integer pageSize, SysRolePermissionRelation param) { if(currentNo<=0){ currentNo=1; } if(pageSize<=0){ pageSize=10; } Wrapper<SysRolePermissionRelation> wrapper = getWrapper(param); return sysRolePermissionRelationMapper.selectPage(new Page<>(currentNo,pageSize),wrapper); } /** * @param list 批量新增 * @return Integer 受影响条数 */ @Override public Integer insertList(List<SysRolePermissionRelation> list) { Integer integer = sysRolePermissionRelationMapper.insertBatchSomeColumn(list); return integer; } /** * @param param 单个新增 * @return boolean */ @Override public boolean insert(SysRolePermissionRelation param) { int i = sysRolePermissionRelationMapper.insert(param); return i<1?false:true; } /** * @param param 必须带有主键 * @return boolean */ @Override public boolean updateById(SysRolePermissionRelation param) { int i = sysRolePermissionRelationMapper.updateById(param); return i<1?false:true; } /** * @param id 通过id删除 * @return boolean */ @Override public boolean deleteById(Long id) { int i = sysRolePermissionRelationMapper.deleteById(id); return i<1?false:true; } /** * @param ids 通过id集合批量删除 * @return boolean */ @Override public boolean deleteByIds(List<Long> ids) { int i = sysRolePermissionRelationMapper.deleteBatchIds(ids); return i<1?false:true; } /** * 角色权限关系表条件列表 * @param param 根据需要进行传值 * @return */ public Wrapper<SysRolePermissionRelation> getWrapper(SysRolePermissionRelation param) { return Wrappers.<SysRolePermissionRelation>lambdaUpdate() // 主键 .eq(param.getId() != null, SysRolePermissionRelation::getId, param.getId()) // 角色id .eq(param.getRoleId() != null, SysRolePermissionRelation::getRoleId, param.getRoleId()) // 用户id .eq(param.getPermissionId() != null, SysRolePermissionRelation::getPermissionId, param.getPermissionId()) ; } }
true
534f763b01e9248947644daba0af7b4f47e6be19
Java
twinkle-cloud/twinkle-cloud
/twinkle-core/twinkle-user-mgmt/src/main/java/com/twinkle/cloud/core/usermgmt/service/OrganizationService.java
UTF-8
1,290
1.921875
2
[]
no_license
package com.twinkle.cloud.core.usermgmt.service; import com.baomidou.mybatisplus.extension.service.IService; import com.twinkle.cloud.core.usermgmt.entity.query.OrganizationQuery; import com.twinkle.cloud.core.usermgmt.entity.Organization; import java.util.List; /** * Function: TODO ADD FUNCTION. <br/> * Reason: TODO ADD REASON. <br/> * Date: 1/2/20 8:09 PM<br/> * * @author chenxj * @see * @since JDK 1.8 */ public interface OrganizationService extends IService<Organization> { /** * 获取用户组 * * @param _id * @return */ Organization get(String _id); /** * 新增用户组 * * @param _org * @return true为新增成功 */ boolean add(Organization _org); /** * 查询用户组 * @param _condition * @return */ List<Organization> query(OrganizationQuery _condition); /** * 根据父id查询用户组 * * @param _parentId * @return */ List<Organization> queryByParentId(String _parentId); /** * 更新用户组信息 * * @param _org * @return */ boolean update(Organization _org); /** * 根据id删除用户组 * * @param _id * @return */ boolean delete(String _id); }
true
9e62ae1046a271d3d2dbec0ea1a88571e7af6ea6
Java
escalonc/wall-medical
/src/main/java/com/walltechsolutions/wallmedical/controllers/RecordController.java
UTF-8
1,141
2.234375
2
[]
no_license
package com.walltechsolutions.wallmedical.controllers; import com.walltechsolutions.wallmedical.core.record.RecordService; import com.walltechsolutions.wallmedical.core.representationmodels.RecordRepresentation; import com.walltechsolutions.wallmedical.data.models.Record; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/records") public class RecordController { private final RecordService recordService; public RecordController( RecordService recordService ) { this.recordService = recordService; } public Page<RecordRepresentation> records(Pageable pageable) { return this.recordService.findAll(pageable); } @GetMapping("/{id}") public RecordRepresentation patient(@PathVariable long id) { return this.recordService.findById(id); } }
true
71cc8275ccef410d31cdc554831bcd8a89f609fc
Java
QqqingYuan/KejsoSpider
/src/cn/kejso/Tool/ProxyUtil.java
UTF-8
2,147
2.453125
2
[]
no_license
package cn.kejso.Tool; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.commons.configuration.ConfigurationException; import cn.kejso.Config.Config; import cn.kejso.Template.ToolEntity.ProxyAccountConfig; import cn.kejso.Tool.Proxy.MimvpProxy; public class ProxyUtil { /* * //获得代理IP public static List<ProxyHost> getProxyIP() { List<ProxyHost> * proxyhosts=new ArrayList<ProxyHost>(); * * File confdir=new File("configs\\ProxyConfig"); try { ProxyIPFactory * factory=new ProxyIPFactory(confdir); * * long startTime=System.currentTimeMillis(); * proxyhosts=ProxyIPFactory.getProxyHosts(); long * endTime=System.currentTimeMillis(); System.out.println("程序运行时间: " * +(endTime-startTime)+"ms"); } catch (ConfigurationException | IOException * | InterruptedException e) { // TODO Auto-generated catch block * e.printStackTrace(); } * * return proxyhosts; } * * public static void main(String[] args){ ProxyUtil.getProxyIP(); } */ //Mimvp如果换了IP,即使免费上限已到,也可以提取到代理 private static List<String[]> proxys; public static List<String[]> getMimvpProxyList() { if (proxys!=null && !proxys.isEmpty()) { return proxys; } String proxyList = Config.mimvpProxyDir + new SimpleDateFormat("yyyyMMdd").format(new Date()); // 如果存在则读取 if (FileUtil.isFileExisted(proxyList)) { proxys = FileUtil.readProxy(proxyList); } //如果未能成功读取或文件不存在 if (proxys == null || proxys.isEmpty()) { String accountConfigPath = Config.mimvpProxyDir + Config.mimvpProxyAccount; ProxyAccountConfig config = TemplateConstructor.getProxyAccountConfig(accountConfigPath); proxys = MimvpProxy.getProxy(config); FileUtil.PrintProxy(proxyList, proxys); } return proxys; } public static void main(String[] args) { List<String[]> list = ProxyUtil.getMimvpProxyList(); for (String[] item : list) { System.out.println(item[0]+":"+item[1]); } } }
true
e4b9152f4469b494e80d667eb5403f078df290f7
Java
dominisz/bulk-email-generator
/src/main/java/pl/dominisz/bulkemailgenerator/TemplateService.java
UTF-8
181
1.703125
2
[]
no_license
package pl.dominisz.bulkemailgenerator; import java.util.List; public class TemplateService { public List<String> generate(List<String> template) { return List.of(); } }
true
cc1bce2e5f606508f84be0e5a431887fb932abb0
Java
abhinavsingh3281/FinalSchoolAppDbaseSystem
/app/src/main/java/com/example/finalschoolappdbasesystem/class1/Profileclass1.java
UTF-8
2,748
2.078125
2
[]
no_license
package com.example.finalschoolappdbasesystem.class1; import android.content.Intent; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import com.example.finalschoolappdbasesystem.R; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.google.firebase.storage.FirebaseStorage; public class Profileclass1 extends AppCompatActivity { private TextView name, phone, email; private ImageView profileback; private FirebaseAuth firebaseAuth; private FirebaseDatabase firebaseDatabase; private FirebaseStorage firebaseStorage; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profileclass1); name = findViewById(R.id.tvprofilename); phone = findViewById(R.id.tvProfileNumber); email = findViewById(R.id.tvProfileEmail); //abhiabhinav13281@gmail.com profileback=findViewById(R.id.profileback); firebaseAuth = FirebaseAuth.getInstance(); firebaseDatabase = FirebaseDatabase.getInstance(); FirebaseDatabase.getInstance().getReference("Class1") .child(FirebaseAuth.getInstance().getCurrentUser().getUid()).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { Class1 class1 = dataSnapshot.getValue(Class1.class); name.setText(class1.getNameclass1()+""); phone.setText( class1.getPhoneclass1() + ""); email.setText( class1.getEmailclass1()+""); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { Toast.makeText(Profileclass1.this, databaseError.getCode(), Toast.LENGTH_SHORT).show(); } }); profileback.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Profileclass1.this,Class1Dashboard.class)); } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()){ case android.R.id.home: onBackPressed(); } return super.onOptionsItemSelected(item); } }
true
7143f2ed7a6b233bd9a095088b0cca2fbfc284cc
Java
ljz890530/Student
/src/main/java/com/woniu/action/StuAction.java
UTF-8
565
2.34375
2
[]
no_license
package com.woniu.action; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import com.woniu.pojo.Student; import com.woniu.service.IStuService; @Controller public class StuAction { @Autowired private IStuService is; private Student stu; public Student getStu() { return stu; } public void setStu(Student stu) { this.stu = stu; } //增加学生信息 public String addStu() { System.out.println(stu); is.save(stu); return "success"; } }
true
63d491ce65ad9c1fe67a23e4fe5089b56c1e0fb0
Java
saiedoc/SimulationEngine
/src/collision/BoxCollision.java
UTF-8
1,755
2.6875
3
[]
no_license
package collision; import models.TexturedModel; import org.lwjgl.util.vector.Vector3f; import physics.RigidBody; import toolbox.Maths; public class BoxCollision { private CollisionResponse response = new CollisionResponse(); protected TexturedModel model; public BoxCollision() { } public void checkCollision(RigidBody marble, BoundingBox box, float cor) { Vector3f closestPoint = ClosestPointBoxPoint(box, marble.getEntity().getPosition()); boolean isCollide = OverlapSphereBox(closestPoint, marble); if (isCollide && !box.getBalls().contains(marble)) { // box.getBalls().clear(); box.getBalls().add(marble); response.response(marble, closestPoint, box.getMass(), cor); } else if (!OverlapSphereBox(closestPoint, marble)) { box.getBalls().remove(marble); } } public Vector3f ClosestPointBoxPoint(BoundingBox box, Vector3f point) { Vector3f temp = max(point, box.getMin()); Vector3f result = min(temp, box.getMax()); return result; } private Vector3f max(Vector3f vec1, Vector3f vec2) { return new Vector3f( Math.max(vec1.x, vec2.x), Math.max(vec1.y, vec2.y), Math.max(vec1.z, vec2.z) ); } private Vector3f min(Vector3f vec1, Vector3f vec2) { return new Vector3f( Math.min(vec1.x, vec2.x), Math.min(vec1.y, vec2.y), Math.min(vec1.z, vec2.z) ); } private boolean OverlapSphereBox(Vector3f vec1, RigidBody rg) { float distance = (float) Maths.Distance(vec1, rg.getEntity().getPosition()); return distance < (rg.getRadius()); } }
true
e1d3f16d3f05adfc2b7c1594672adbe08428bfbb
Java
pxson001/facebook-app
/classes5.dex_source_from_JADX/com/facebook/graphql/model/GraphQLSinglePublisherVideoChannelsEdgeSerializer.java
UTF-8
840
1.539063
2
[]
no_license
package com.facebook.graphql.model; import com.facebook.common.json.FbSerializerProvider; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; /* compiled from: UserWorkExperiencesEdge */ public class GraphQLSinglePublisherVideoChannelsEdgeSerializer extends JsonSerializer<GraphQLSinglePublisherVideoChannelsEdge> { public final void m21670a(Object obj, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) { GraphQLSinglePublisherVideoChannelsEdge__JsonHelper.m21672a(jsonGenerator, (GraphQLSinglePublisherVideoChannelsEdge) obj, true); } static { FbSerializerProvider.a(GraphQLSinglePublisherVideoChannelsEdge.class, new GraphQLSinglePublisherVideoChannelsEdgeSerializer()); } }
true
12dba8934fb970296184f90ab5ec6dd0f14f9d69
Java
marcelosrodrigues/varejodigital
/src/test/java/test/com/pmrodrigues/varejodigital/integration/rest/ITestSecaoController.java
UTF-8
1,113
1.84375
2
[]
no_license
package test.com.pmrodrigues.varejodigital.integration.rest; import com.pmrodrigues.varejodigital.models.Secao; import org.json.JSONException; import org.junit.Test; import org.springframework.test.context.ContextConfiguration; import java.util.List; import static java.lang.String.format; import static org.junit.Assert.assertEquals; /** * Created by Marceloo on 13/01/2015. */ @ContextConfiguration(locations = {"classpath:test-applicationContext.xml"}) public class ITestSecaoController extends AbstractTestRest<Secao> { @Test public void listarSecoesPorLoja() throws JSONException { final Long id = this.jdbcTemplate.queryForObject("select id from loja where nome = 'PROJETANDOO'", Long.class); final List<Secao> secoes = this.list(format("\"http://localhost:8080/varejo/%s/secoes.json", id), "marsilvarodrigues@gmail.com", "12345678"); final Long count = this.jdbcTemplate.queryForObject("select count(id) from secao inner join areas_vendas on id = secao_id where produto_id = ? and pai_id is null", Long.class, id); assertEquals(count, Long.valueOf(secoes.size())); } }
true
d43e1e270b89cf1d0cff4422ee9269828223dc55
Java
nqlz/elastic-job
/elastic-common/src/main/java/com/zt/elasticcommon/model/TJobStatusTraceLog.java
UTF-8
1,788
1.796875
2
[]
no_license
package com.zt.elasticcommon.model; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.extension.activerecord.Model; import com.baomidou.mybatisplus.annotation.TableId; import java.time.LocalDateTime; import com.baomidou.mybatisplus.annotation.TableField; import java.io.Serializable; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; /** * <p> * * </p> * * @author MR.zt * @since 2019-08-21 */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) public class TJobStatusTraceLog extends Model<TJobStatusTraceLog> { private static final long serialVersionUID = 1L; @TableId(value = "id", type = IdType.ID_WORKER) private String id; /** * 作业名称 */ @TableField("job_name") private String jobName; /** * 原任务名称 */ @TableField("original_task_id") private String originalTaskId; /** * 任务名称 */ @TableField("task_id") private String taskId; /** * 作业执行服务器IP */ @TableField("slave_id") private String slaveId; /** * 执行源 */ @TableField("source") private String source; /** * 任务执行类型 */ @TableField("execution_type") private String executionType; /** * 分片项集合 */ @TableField("sharding_item") private String shardingItem; /** * 执行状态 */ @TableField("state") private String state; /** * 相关信息 */ @TableField("message") private String message; @TableField("creation_time") private LocalDateTime creationTime; @Override protected Serializable pkVal() { return this.id; } }
true
0ea71306679cd8e42bb62a8801aec3641b87c394
Java
godstady/springboot-myp-mppdb
/springboot-demo/src/main/java/com/dataql/service/impl/UsertestServiceImpl.java
UTF-8
480
1.53125
2
[]
no_license
package com.dataql.service.impl; import com.dataql.bean.Usertest; import com.dataql.mapper.UsertestMapper; import com.dataql.service.IUsertestService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; /** * <p> * 服务实现类 * </p> * * @author astupidcoder * @since 2021-01-26 */ @Service public class UsertestServiceImpl extends ServiceImpl<UsertestMapper, Usertest> implements IUsertestService { }
true
f27f2aaada808177364611772cfe55d1071dbfce
Java
magex9/api-java
/crm-hazelcast-service/src/main/java/ca/magex/crm/hazelcast/repository/HazelcastLocationRepository.java
UTF-8
3,625
2.375
2
[]
no_license
package ca.magex.crm.hazelcast.repository; import java.util.List; import java.util.stream.Collectors; import org.apache.commons.lang3.SerializationUtils; import com.hazelcast.core.TransactionalMap; import ca.magex.crm.api.crm.LocationDetails; import ca.magex.crm.api.crm.LocationSummary; import ca.magex.crm.api.filters.LocationsFilter; import ca.magex.crm.api.filters.PageBuilder; import ca.magex.crm.api.filters.Paging; import ca.magex.crm.api.repositories.CrmLocationRepository; import ca.magex.crm.api.system.FilteredPage; import ca.magex.crm.api.system.id.LocationIdentifier; import ca.magex.crm.hazelcast.predicate.CrmFilterPredicate; import ca.magex.crm.hazelcast.xa.XATransactionAwareHazelcastInstance; /** * An implementation of the Location Repository that uses the Hazelcast in memory data grid * for persisting instances across multiple nodes * * @author Jonny */ public class HazelcastLocationRepository implements CrmLocationRepository { private XATransactionAwareHazelcastInstance hzInstance; /** * Creates the new repository using the backing Transaction Aware Hazelcast Instance * * @param hzInstance */ public HazelcastLocationRepository(XATransactionAwareHazelcastInstance hzInstance) { this.hzInstance = hzInstance; } @Override public LocationDetails saveLocationDetails(LocationDetails location) { TransactionalMap<LocationIdentifier, LocationDetails> locations = hzInstance.getLocationsMap(); /* persist a clone of this location, and return the original */ locations.put(location.getLocationId(), SerializationUtils.clone(location)); return location; } @Override public LocationDetails findLocationDetails(LocationIdentifier locationId) { TransactionalMap<LocationIdentifier, LocationDetails> locations = hzInstance.getLocationsMap(); LocationDetails locDetails = locations.get(locationId); if (locDetails == null) { return null; } return SerializationUtils.clone(locDetails); } @Override public LocationSummary findLocationSummary(LocationIdentifier locationId) { TransactionalMap<LocationIdentifier, LocationDetails> locations = hzInstance.getLocationsMap(); LocationDetails locDetails = locations.get(locationId); if (locDetails == null) { return null; } return SerializationUtils.clone(locDetails.asSummary()); } @Override public FilteredPage<LocationDetails> findLocationDetails(LocationsFilter filter, Paging paging) { TransactionalMap<LocationIdentifier, LocationDetails> locations = hzInstance.getLocationsMap(); List<LocationDetails> allMatchingLocations = locations.values(new CrmFilterPredicate<LocationSummary>(filter)) .stream() .sorted(filter.getComparator(paging)) .map(i -> SerializationUtils.clone(i)) .collect(Collectors.toList()); return PageBuilder.buildPageFor(filter, allMatchingLocations, paging); } @Override public FilteredPage<LocationSummary> findLocationSummary(LocationsFilter filter, Paging paging) { TransactionalMap<LocationIdentifier, LocationDetails> locations = hzInstance.getLocationsMap(); List<LocationSummary> allMatchingLocations = locations.values(new CrmFilterPredicate<LocationSummary>(filter)) .stream() .sorted(filter.getComparator(paging)) .map(i -> i.asSummary()) .collect(Collectors.toList()); return PageBuilder.buildPageFor(filter, allMatchingLocations, paging); } @Override public long countLocations(LocationsFilter filter) { TransactionalMap<LocationIdentifier, LocationDetails> locations = hzInstance.getLocationsMap(); return locations.values(new CrmFilterPredicate<LocationSummary>(filter)).size(); } }
true
220e4bf9204ffe50e20b03f7b856a445c2e89efc
Java
onschrif/ERP
/esprit1718b3erp-client/src/main/java/tn/esprit/b3/esprit1718b3erp/app/client/scm_purchase/SuppliersListController.java
UTF-8
6,608
1.78125
2
[]
no_license
package tn.esprit.b3.esprit1718b3erp.app.client.scm_purchase; import javafx.animation.TranslateTransition; import javafx.application.Platform; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.chart.BarChart; import javafx.scene.chart.CategoryAxis; import javafx.scene.chart.NumberAxis; import javafx.scene.chart.PieChart; import javafx.scene.chart.StackedBarChart; import javafx.scene.chart.XYChart; import javafx.scene.control.Label; import javafx.scene.control.PasswordField; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; import javafx.stage.Window; import javafx.util.Duration; import tn.esprit.b3.esprit1718b3erp.app.client.login.Login; import tn.esprit.b3.esprit1718b3erp.conatactmangment.ContactMangmentRemote2; import tn.esprit.b3.esprit1718b3erp.entities.Suppliers; import tn.esprit.b3.esprit1718b3erp.utilities.ServiceLocator; import java.io.IOException; import java.net.URL; import java.util.Arrays; import java.util.List; import java.util.ResourceBundle; import com.jfoenix.controls.JFXTextField; public class SuppliersListController implements Initializable { @FXML private TableView<Suppliers> tableSupplier; @FXML private TableColumn<Suppliers, String> col1; @FXML private TableColumn<Suppliers, String> col2; @FXML private TableColumn<Suppliers, String> col3; @FXML private TableColumn<Suppliers, String> col4; @FXML JFXTextField search; @FXML private AnchorPane dashpane; static Boolean dash=false; String jndiNameS = "esprit1718b3erp-ear/esprit1718b3erp-service/ContactMangmentService2!tn.esprit.b3.esprit1718b3erp.conatactmangment.ContactMangmentRemote2"; ServiceLocator s = ServiceLocator.getInstance(); ContactMangmentRemote2 contactMangmentRemote2 = (ContactMangmentRemote2) s.getProxy(jndiNameS); @FXML public void dsh(ActionEvent event) { TranslateTransition translateTransition1 = new TranslateTransition(Duration.seconds(0.5), dashpane); if(dash) { translateTransition1.setByX(-250); dash=false; } else {translateTransition1.setByX(+250); dash=true; } translateTransition1.play(); } @Override public void initialize(URL url, ResourceBundle rb) { act() ; dash=false; } @FXML public void close(ActionEvent event) { Platform.exit(); } @FXML public void minimize(ActionEvent event) { Node source = (Node) event.getSource(); Window theStage = source.getScene().getWindow(); ((Stage) theStage).setIconified(true); } public void to(ActionEvent event, String str, String title) throws IOException { Parent root = FXMLLoader.load(getClass().getResource(str)); Scene scene = new Scene(root); scene.getStylesheets().addAll(Login.class.getResource("style.css").toExternalForm()); Stage app_stage = (Stage) ((Node) event.getSource()).getScene().getWindow(); app_stage.setScene(scene); app_stage.setTitle(title); app_stage.show(); } @FXML public void home(ActionEvent event) throws IOException { to(event, "PurchaseDashboard.fxml", "Home"); } @FXML public void toProduct(ActionEvent event) throws IOException { to(event, "Product.fxml", "Product"); } @FXML public void toBillofMaterial(ActionEvent event) throws IOException { to(event, "BillofMaterial.fxml", "Bill of Material"); } @FXML public void logout(ActionEvent event) throws IOException { to(event, "../login/Login.fxml", "Login"); } @FXML public void toPurchaseOrder(ActionEvent event) throws IOException { to(event, "PurchaseOrder.fxml", "Purchase Order"); } @FXML public void toOrder(ActionEvent event) throws IOException { to(event, "OrdersList.fxml", "Orders"); } @FXML public void toLocation(ActionEvent event) throws IOException { to(event, "../scm_inventory/Location.fxml", " Inventory Location"); } @FXML public void toMovement(ActionEvent event) throws IOException { to(event, "../scm_inventory/Movement.fxml", "Inventory Movement"); } @FXML public void toUpdateInventoy(ActionEvent event) throws IOException { to(event, "../scm_inventory/UpdateInventory.fxml", "Update Inventoy"); } @FXML public void toAdjustment(ActionEvent event) throws IOException { to(event, "../scm_inventory/Adjustment.fxml", "Adjustment Inventoy"); } @FXML public void toSuppliers(ActionEvent event) throws IOException { to(event, "SuppliersList.fxml", "Suppliers"); } public void act() { col1.setCellValueFactory(new PropertyValueFactory<Suppliers, String>("name")); col2.setCellValueFactory(new PropertyValueFactory<Suppliers, String>("adress")); col3.setCellValueFactory(new PropertyValueFactory<Suppliers, String>("phone")); col4.setCellValueFactory(new PropertyValueFactory<Suppliers, String>("email")); List<Suppliers> listS = null; listS = contactMangmentRemote2.findAll(); System.out.println("List of Supplier Act"); ObservableList<Suppliers> items = FXCollections.observableArrayList(listS); tableSupplier.setItems(items); } @FXML void Refresh(ActionEvent event) { search.setText(""); act(); } @FXML public void searchSupplier(KeyEvent event) { ObservableList table = tableSupplier.getItems(); search.textProperty() .addListener((ObservableValue<? extends String> observable, String oldValue, String newValue) -> { if (oldValue != null && (newValue.length() < oldValue.length())) { tableSupplier.setItems(table); } String value = newValue.toLowerCase(); ObservableList<Suppliers> subentries = FXCollections.observableArrayList(); long count = tableSupplier.getColumns().stream().count(); for (int i = 0; i < tableSupplier.getItems().size(); i++) { for (int j = 0; j < count; j++) { String entry = "" + tableSupplier.getColumns().get(j).getCellData(i); if (entry.toLowerCase().contains(value)) { subentries.add(tableSupplier.getItems().get(i)); break; } } } tableSupplier.setItems(subentries); }); } }
true
0a8a06c6c166d22b3c4ad3577a2cec49072ba86c
Java
stanop/ecos-community-core
/ecos-forms-repo/src/main/java/ru/citeck/ecos/webscripts/invariants/NodeViewPost.java
UTF-8
5,407
1.640625
2
[]
no_license
/* * Copyright (C) 2008-2015 Citeck LLC. * * This file is part of Citeck EcoS * * Citeck EcoS is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Citeck EcoS is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Citeck EcoS. If not, see <http://www.gnu.org/licenses/>. */ package ru.citeck.ecos.webscripts.invariants; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.alfresco.service.cmr.repository.NodeRef; import org.alfresco.service.namespace.NamespacePrefixResolver; import org.alfresco.service.namespace.QName; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import org.json.simple.parser.ParseException; import org.springframework.extensions.webscripts.Cache; import org.springframework.extensions.webscripts.DeclarativeWebScript; import org.springframework.extensions.webscripts.Status; import org.springframework.extensions.webscripts.WebScriptRequest; import ru.citeck.ecos.invariants.view.NodeViewService; import ru.citeck.ecos.model.InvariantsModel; import ru.citeck.ecos.utils.RepoUtils; public class NodeViewPost extends DeclarativeWebScript { private static final String PARAM_TYPE = "type"; private static final String PARAM_NODEREF = "nodeRef"; private static final String REQ_VIEW = "view"; private static final String REQ_VIEW_ID = "id"; private static final String REQ_VIEW_PARAMS = "params"; private static final String REQ_ATTRIBUTES = "attributes"; private static final String REQ_IS_DRAFT = "isDraft"; private static final String MODEL_NODE = "node"; private NodeViewService nodeViewService; private NamespacePrefixResolver prefixResolver; @Override protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) { String typeParam = req.getParameter(PARAM_TYPE); String nodeRefParam = req.getParameter(PARAM_NODEREF); JSONObject requestBody; try { Object data = JSONValue.parseWithException(req.getContent().getReader()); if(!(data instanceof JSONObject)) { status.setCode(Status.STATUS_BAD_REQUEST, "Expected JSON object, but got " + data.getClass()); return null; } requestBody = (JSONObject) data; } catch (IOException e) { status.setCode(Status.STATUS_INTERNAL_SERVER_ERROR, e.getMessage()); return null; } catch (ParseException e) { status.setCode(Status.STATUS_BAD_REQUEST, e.getMessage()); return null; } @SuppressWarnings("unchecked") Map<String, Object> attributesModel = (Map<String, Object>) requestBody.get(REQ_ATTRIBUTES); if(attributesModel == null) { status.setCode(Status.STATUS_BAD_REQUEST, REQ_ATTRIBUTES + " should be specified in request body"); return null; } Map<QName, Object> attributes = RepoUtils.convertStringMapToQNameMap(attributesModel, prefixResolver); Boolean isDraftParam = (Boolean) requestBody.get(REQ_IS_DRAFT); if (isDraftParam != null) { attributes.put(InvariantsModel.PROP_IS_DRAFT, isDraftParam); } @SuppressWarnings("unchecked") Map<String, Object> viewModel = (Map<String, Object>) requestBody.get(REQ_VIEW); String viewId = viewModel != null ? (String) viewModel.get(REQ_VIEW_ID) : null; @SuppressWarnings("unchecked") Map<String, Object> viewParams = viewModel != null ? (Map<String, Object>) viewModel.get(REQ_VIEW_PARAMS) : null; NodeRef nodeRef; if(typeParam != null && !typeParam.isEmpty()) { QName type = QName.createQName(typeParam, prefixResolver); nodeRef = nodeViewService.saveNodeView(type, viewId, attributes, viewParams); } else if(nodeRefParam != null && !nodeRefParam.isEmpty()) { if(!NodeRef.isNodeRef(nodeRefParam)) { status.setCode(Status.STATUS_BAD_REQUEST, "Parameter '" + PARAM_NODEREF + "' should contain nodeRef"); return null; } nodeRef = new NodeRef(nodeRefParam); nodeViewService.saveNodeView(nodeRef, viewId, attributes, viewParams); } else { status.setCode(Status.STATUS_BAD_REQUEST, "Either type, or nodeRef parameters should be set"); return null; } Map<String, Object> model = new HashMap<>(); model.put(MODEL_NODE, nodeRef); return model; } public void setNodeViewService(NodeViewService nodeViewService) { this.nodeViewService = nodeViewService; } public void setPrefixResolver(NamespacePrefixResolver prefixResolver) { this.prefixResolver = prefixResolver; } }
true
3129635afc45b4774e562a1e1f52e3d720ee59e3
Java
AndersonFerrigo/professorama-api
/src/main/java/com/clearsys/professorama/api/services/AtividadeService.java
UTF-8
1,132
2.5
2
[ "MIT" ]
permissive
package com.clearsys.professorama.api.services; import java.util.List; import java.util.Optional; import com.clearsys.professorama.api.entities.Atividade; public interface AtividadeService { /** * Retorna uma atividade com base em um ID * * @param id * @return Optional<Atividade> */ Optional<Atividade> buscarPorId(Long id); /** * Retorna uma atividade com base na materia * * @param materia * @return Optional<Atividade> */ Optional<List<Atividade>> buscarPorMateria(String materia); /** * Retorna uma atividade com base na data de entrega * * @param dataEntrega * @return Optional<Atividade> */ Optional<Atividade> buscarPorDataEntrega(String dataEntrega); /** * Retorna uma atividade com base no nivel escolar * * @param nivelEscolar * @return Optional<Atividade> */ Optional<List<Atividade>> buscarPorSerie(String serie); /** * Cadastra uma nova atividade * * @param atividade * @return Atividade */ Atividade persistir(Atividade atividade); /** * Remove uma atividade da base de dados. * * @param id * @return */ void deletar(Long id); }
true
46197681b31919a68ad2f330dc7c92f7b1d384bf
Java
He1md4ll/SmartFridge
/src/main/java/com/smart/fridge/JerseyConfig.java
UTF-8
788
1.984375
2
[]
no_license
package com.smart.fridge; import com.smart.fridge.controller.CreateTestDataController; import com.smart.fridge.controller.IngredientController; import com.smart.fridge.controller.MealController; import com.smart.fridge.controller.MealPlanController; import com.smart.fridge.exception.CustomExceptionHandler; import org.glassfish.jersey.server.ResourceConfig; import org.springframework.context.annotation.Configuration; @Configuration public class JerseyConfig extends ResourceConfig { public JerseyConfig() { register(MealController.class); register(IngredientController.class); register(MealPlanController.class); register(CreateTestDataController.class); //Register ExcptionMapper register(CustomExceptionHandler.class); } }
true
faa8775d7112bc3921147b5dc186e82e934e38ae
Java
kingroma/information-client-api
/src/main/java/information/client/api/daoimpl/BaseDaoImpl.java
UTF-8
2,971
2.234375
2
[]
no_license
package information.client.api.daoimpl; import java.io.Serializable; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.springframework.beans.factory.annotation.Autowired; import com.googlecode.genericdao.dao.jpa.GenericDAOImpl; import com.googlecode.genericdao.search.Filter; import com.googlecode.genericdao.search.Search; import com.googlecode.genericdao.search.Sort; import com.googlecode.genericdao.search.jpa.JPASearchProcessor; import information.client.api.dao.BaseDao; public class BaseDaoImpl<T, ID extends Serializable> extends GenericDAOImpl<T, ID> implements BaseDao<T, ID> { @Override @PersistenceContext(unitName = "domainPU") public void setEntityManager(EntityManager entityManager) { super.setEntityManager(entityManager); } @Override @Autowired public void setSearchProcessor(JPASearchProcessor searchProcessor) { super.setSearchProcessor(searchProcessor); } @Override public Integer countAll() { Search s = new Search(); List<T> list = search(s); return list.size(); } @Override public List<T> findAll(Sort sort){ Search s = new Search(); s.addSort(sort); return search(s); } @Override public List<T> findAll(int offset, int limit) { Search s = new Search(); s.setFirstResult(offset); s.setMaxResults(limit); return search(s); } @Override public List<T> findAll(Sort sort, int offset, int limit) { Search s = new Search(); s.addSort(sort); s.setFirstResult(offset); s.setMaxResults(limit); return search(s); } @Override public List<T> find(Filter... filters) { Search s = new Search(); for (Filter filter : filters) { s.addFilter(filter); } return search(s); } @Override public List<T> find(Sort sort, Filter... filters) { Search s = new Search(); for (Filter filter : filters) { s.addFilter(filter); } s.addSort(sort); return search(s); } @Override public List<T> find(Sort[] sorts, Filter... filters) { Search s = new Search(); for (Filter filter : filters) { s.addFilter(filter); } for (Sort sort : sorts) { s.addSort(sort); } return search(s); } @Override public List<T> find(int offset, int limit, Sort sort, Filter... filters) { Search s = new Search(); for (Filter filter : filters) { s.addFilter(filter); } s.addSort(sort); s.setFirstResult(offset); s.setMaxResults(limit); return search(s); } @Override public List<T> find(int offset, int limit, Sort[] sorts, Filter... filters) { Search s = new Search(); for (Filter filter : filters) { s.addFilter(filter); } for (Sort sort : sorts) { s.addSort(sort); } s.setFirstResult(offset); s.setMaxResults(limit); return search(s); } @Override public EntityManager getEntityManager() { return this.em(); } }
true
bbd4258e2a559869b4432861e0e37323a1d5ec04
Java
cmaxwell9/CSCC-Android-Fundamentals-week2
/week-10/src/com/cmaxw103/Main.java
UTF-8
841
3.65625
4
[]
no_license
package com.cmaxw103; /** * Created by Clint on 4/7/2016. */ import java.util.Random; interface WeatherReport { public void display(double value); } class WeatherApp { private double temperature; public void updateTemperature() { temperature = new Random().nextDouble() * 100; } //anonymous class implementing WeatherReport public void displayTemperatureReport() { new WeatherReport() { @Override public void display(double value) { System.out.println("The current temperature is " + value + "."); } }.display(temperature); } } public class Main { public static void main(String[] args) { WeatherApp weather = new WeatherApp(); weather.updateTemperature(); weather.displayTemperatureReport(); } }
true
e59af5cacc09da42c6ccda54d2dcf6c55900d0a8
Java
IvoArsov/job-application-vivacom
/src/test/java/pages/BasePage.java
UTF-8
1,186
2.71875
3
[]
no_license
package pages; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; public class BasePage { public WebDriver browser; private By devicesBtnLocator = By.xpath("(//a[text()='Устройства'])[2]"); private By backToHomeBtnLocator = By.xpath("(//a[@href='/'])[2]"); public BasePage(WebDriver browserDriver) { this.browser = browserDriver; } public void selectSubmenuByMenu(String submenu) throws InterruptedException { Thread.sleep(3000); String xpath = "//a[@title='" + submenu + "']"; WebElement submenuBtn = this.browser.findElement(By.xpath(xpath)); WebElement deviceBtn = this.browser.findElement(devicesBtnLocator); deviceBtn.click(); Thread.sleep(3000); submenuBtn.click(); } public String getPageTitle() throws InterruptedException { Thread.sleep(3000); return this.browser.getTitle(); } public void backToHome() throws InterruptedException { Thread.sleep(3000); WebElement backToHomeBtn = this.browser.findElement(backToHomeBtnLocator); backToHomeBtn.click(); } }
true
76b6d94ec5b1f069c3e92e66d93236172d6248ff
Java
moiseslima/aplication
/src/distoleos/DistOleos.java
UTF-8
654
2.09375
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package distoleos; /** * * @author moises */ public class DistOleos { private static visao _app; public static visao getSharedApplication() { if (_app == null) _app = new visao(); return _app; } public static void main(String[] args) { // TODO code application logic here //new visao().setVisible(true); getSharedApplication().setVisible(true); } }
true
2565efae38cb1768dfaf340e593fc893f566cc84
Java
LingWu0/MyStudy
/mvptest/src/main/java/com/example/mvptest/model/RegisterModel.java
UTF-8
1,374
2.25
2
[]
no_license
package com.example.mvptest.model; import android.support.annotation.NonNull; import com.example.mvptest.model.app.MyApplication; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; /** * Created by xxsj on 2017/10/30. */ public class RegisterModel { //构造方法 public RegisterModel(){ } public void Register(@NonNull final DataCallBack<String> dataCallBack){ OkHttpClient okHttpClient = MyApplication.okHttpClient(); Request request = new Request.Builder() .url("http://news-at.zhihu.com/api/4/news/before/20131119") .build(); okHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { dataCallBack.GetDataFailed(e); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()){ String json = response.body().string(); dataCallBack.GetDataSucced(json); } } }); } public interface DataCallBack<T>{ void GetDataSucced(T t); void GetDataFailed(IOException s); } }
true
74f03a8bdf1bd507c91c8004fe3f60f44e55cd81
Java
luisguns/Poster_TCC
/app/src/main/java/com/tcc/luis/poster/interessado/ui/meu_perfil/MeuPerfilFragment.java
UTF-8
14,431
1.617188
2
[]
no_license
package com.tcc.luis.poster.interessado.ui.meu_perfil; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.os.Bundle; 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.Button; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.cardview.widget.CardView; import androidx.constraintlayout.widget.ConstraintLayout; import androidx.core.graphics.drawable.RoundedBitmapDrawable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; import com.squareup.picasso.Callback; import com.squareup.picasso.NetworkPolicy; import com.squareup.picasso.Picasso; import com.tcc.luis.poster.R; import com.tcc.luis.poster.adapter.CompetenciasAdapter; import com.tcc.luis.poster.adapter.ExperienciaProfissionalAdapter; import com.tcc.luis.poster.adapter.FormacoesAcademicasAdapter; import com.tcc.luis.poster.helpers.Constantes; import com.tcc.luis.poster.helpers.CountHelper; import com.tcc.luis.poster.helpers.ImageHelper; import com.tcc.luis.poster.helpers.ProgressHelper; import com.tcc.luis.poster.interessado.ui.meu_perfil.ui.EditaPerfilActivity; import com.tcc.luis.poster.interessado.ui.meu_perfil.ui.competencias.CompetenciasActivity; import com.tcc.luis.poster.interessado.ui.meu_perfil.ui.experiencia.ExperienciaProfissionalActivity; import com.tcc.luis.poster.interessado.ui.meu_perfil.ui.formacao.FormacoesAcademicaActivity; import com.tcc.luis.poster.model.Competencia; import com.tcc.luis.poster.model.Curriculo; import com.tcc.luis.poster.model.ExperienciaProfissional; import com.tcc.luis.poster.model.FormacaoAcademica; import com.tcc.luis.poster.model.Usuario; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class MeuPerfilFragment extends Fragment { private ImageView mImgEditAcademic; private ImageView mImgEditCompetencia; private ImageView mImgEditExperiencia; private ImageView mImgEditPerfil; private ConstraintLayout mContainerViews; private ProgressBar mProgressGeral; private Button mEnviarEmail; private TextView mTxtName; private TextView mTxtSobre; private TextView mTxtOcupacao; private TextView mTxtEmail; private ImageView mImgPerfil; private String actualUser; private FirebaseFirestore firebaseFirestore; private FirebaseAuth firebaseAuth; private Curriculo curriculo; private ProgressBar mProgressImgPerfil; private RecyclerView mRvCompetencias; private RecyclerView mRvFormacoes; private RecyclerView mRvExperiencias; private List<View> ownerViews; private Activity activity; private TextView mTxtVerMaisFormacao; private TextView mTxtVerMaisCompetencia; private TextView mTxtVerMaisExperiencia; public MeuPerfilFragment(){ ownerViews = new ArrayList<>(); } public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_meu_perfil, container, false); setHasOptionsMenu(true); initViews(v); aplyListens(); mEnviarEmail.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_SENDTO); intent.setType("text/plain"); intent.setData(Uri.parse("mailto:" + mTxtEmail.getText().toString())); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra(Intent.EXTRA_SUBJECT, "VAGA DE EMPROGO DO POSTER"); startActivity(intent); } }); Bundle bd = getArguments(); if (bd != null) { String interessadoKey = bd.getString(Constantes.INTERESSADO_KEY); if(interessadoKey != null){ actualUser = interessadoKey; mEnviarEmail.setVisibility(View.VISIBLE); dimissAllViews(ownerViews); } else { mEnviarEmail.setVisibility(View.GONE); actualUser = firebaseAuth.getCurrentUser().getUid(); } } else { mEnviarEmail.setVisibility(View.GONE); actualUser = firebaseAuth.getCurrentUser().getUid(); } return v; } @Override public void onResume() { super.onResume(); ProgressHelper.show(mProgressGeral, mContainerViews, true); new Thread(new Runnable() { @Override public void run() { findUser(); } }).start(); new Thread(new Runnable() { @Override public void run() { findCurriculo(); } }).start(); } private void loadUserUi(Usuario usuario) { String name = ""; if (usuario.getName() != null) { name = name + usuario.getName(); } if (usuario.getLastName() != null) { name = name + " " + usuario.getLastName(); } if (usuario.getSobre() != null) { mTxtSobre.setText(usuario.getSobre()); } if (usuario.getOcupacao() != null && !usuario.getOcupacao().isEmpty()) { mTxtOcupacao.setText(usuario.getOcupacao()); } mTxtName.setText(name); if (!usuario.getProfileImage().isEmpty()) { loadImage(usuario.getProfileImage(), mImgPerfil); } if (usuario.getEmail() != null) { mTxtEmail.setText(usuario.getEmail()); } } private void dimissAllViews(List<View> views){ for (View view: views ) { view.setVisibility(View.GONE); } } private void loadImage(String url, final ImageView img) { Picasso.with(activity).load(url).networkPolicy(NetworkPolicy.OFFLINE).resize(80, 80) .resize(512, 512).centerCrop().into(img, new Callback() { @Override public void onSuccess() { Bitmap imageBitmap = ((BitmapDrawable) img.getDrawable()).getBitmap(); RoundedBitmapDrawable imageDrawable = ImageHelper.makeRoundDrawer(imageBitmap, getResources()); img.setImageDrawable(imageDrawable); ProgressHelper.show(mProgressImgPerfil, null, false); } @Override public void onError() { img.setVisibility(View.GONE); ProgressHelper.show(mProgressImgPerfil, null, false); } }); ; } private void findUser() { firebaseFirestore.collection(Constantes.TABELA_DATABASE_USUARIO) .document(actualUser) .get() .addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { @Override public void onComplete(@NonNull Task<DocumentSnapshot> task) { if (task.isSuccessful()) { Usuario usuario = task.getResult().toObject(Usuario.class); loadUserUi(usuario); } } }); } private void findCurriculo() { firebaseFirestore.collection(Constantes.TABELA_DATABASE_CURRICULO).document(actualUser) .get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { @Override public void onComplete(@NonNull Task<DocumentSnapshot> task) { if (task.isSuccessful()) { curriculo = task.getResult().toObject(Curriculo.class); if (curriculo != null) { loadViewsWIthCurriculo(); } } } }); } private void loadViewsWIthCurriculo() { List<FormacaoAcademica> formacoesAcademicas = curriculo.getFormacoesAcademicas(); List<Competencia> competencias = curriculo.getCompetencias(); List<ExperienciaProfissional> experiencias = curriculo.getExperienciasProfissionais(); if (formacoesAcademicas != null) { loadRecyclerViewFormacoes(formacoesAcademicas); } else { mRvFormacoes.setVisibility(View.GONE); } if (competencias != null) { loadRecyclerViewCompetencias(competencias); } else { mRvCompetencias.setVisibility(View.GONE); } if (experiencias != null) { loadRecyclerViewExperiencia(experiencias); } else { mRvExperiencias.setVisibility(View.GONE); } ProgressHelper.show(mProgressGeral, mContainerViews, false); } private void loadRecyclerViewExperiencia(List<ExperienciaProfissional> experiencias) { if (experiencias.size() > 3) { mTxtVerMaisExperiencia.setVisibility(View.VISIBLE); } ExperienciaProfissionalAdapter adapter = new ExperienciaProfissionalAdapter(experiencias, getActivity(), false); mRvExperiencias.setAdapter(adapter); mRvExperiencias.setNestedScrollingEnabled(false); } private void loadRecyclerViewCompetencias(List<Competencia> competencias) { if (competencias.size() > 3) { mTxtVerMaisCompetencia.setVisibility(View.VISIBLE); } CompetenciasAdapter adapter = new CompetenciasAdapter(competencias, getActivity(), false); mRvCompetencias.setAdapter(adapter); mRvCompetencias.setNestedScrollingEnabled(false); } private void loadRecyclerViewFormacoes(List<FormacaoAcademica> formacoesAcademicas) { if (formacoesAcademicas.size() > 3) { mTxtVerMaisFormacao.setVisibility(View.VISIBLE); } FormacoesAcademicasAdapter adapter = new FormacoesAcademicasAdapter(formacoesAcademicas, getActivity(), false); mRvFormacoes.setAdapter(adapter); mRvFormacoes.setNestedScrollingEnabled(false); } private void aplyListens() { mImgEditAcademic.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getActivity().startActivity(new Intent(getActivity(), FormacoesAcademicaActivity.class)); } }); mImgEditCompetencia.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getActivity().startActivity(new Intent(getActivity(), CompetenciasActivity.class)); } }); mImgEditExperiencia.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getActivity().startActivity(new Intent(getActivity(), ExperienciaProfissionalActivity.class)); } }); mImgEditPerfil.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getActivity().startActivity(new Intent(getActivity(), EditaPerfilActivity.class)); } }); } private void initViews(View v) { mImgEditAcademic = v.findViewById(R.id.meu_perfil_interessado_img_edit_formacao); mImgEditCompetencia = v.findViewById(R.id.meu_perfil_interessado_img_edit_competencias); mImgEditExperiencia = v.findViewById(R.id.meu_perfil_interessado_img_edit_experiencia); mImgEditPerfil = v.findViewById(R.id.meu_perfil_interessado_img_edit_perfil); mTxtVerMaisFormacao = v.findViewById(R.id.meu_perfil_formacao_ver_mais_label); mTxtVerMaisCompetencia = v.findViewById(R.id.meu_perfil_competencia_ver_mais); mTxtVerMaisExperiencia = v.findViewById(R.id.meu_perfil_experiencia_ver_mais); mEnviarEmail = v.findViewById(R.id.meu_perfil_enviar_email); firebaseFirestore = FirebaseFirestore.getInstance(); firebaseAuth = FirebaseAuth.getInstance(); activity = getActivity(); mProgressImgPerfil = v.findViewById(R.id.meu_perfil_progress_image); mRvFormacoes = v.findViewById(R.id.meu_perfil_rv_formacoes_academicas); mRvCompetencias = v.findViewById(R.id.meu_perfil_rv_competencias); mRvExperiencias = v.findViewById(R.id.meu_perfil_container_rv_experiencias); mTxtName = v.findViewById(R.id.meu_perfil_nome); mTxtOcupacao = v.findViewById(R.id.meu_perfil_usuario_atual_ocupação); mTxtEmail = v.findViewById(R.id.meu_perfil_contato_email); mTxtSobre = v.findViewById(R.id.meu_perfil_sobre); mImgPerfil = v.findViewById(R.id.meu_perfil_imagem_perfil); mContainerViews = v.findViewById(R.id.meu_perfil_layout_views); mProgressGeral = v.findViewById(R.id.meu_perfil_progress_geral); LinearLayoutManager llm = new LinearLayoutManager(getContext()); LinearLayoutManager llm2 = new LinearLayoutManager(getContext()); LinearLayoutManager llm3 = new LinearLayoutManager(getContext()); mRvFormacoes.setLayoutManager(llm); mRvCompetencias.setLayoutManager(llm2); mRvExperiencias.setLayoutManager(llm3); ownerViews.addAll(Arrays.asList(mImgEditAcademic,mImgEditCompetencia, mImgEditExperiencia,mImgEditPerfil)); } @Override public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) { inflater.inflate(R.menu.option_menu_company, menu); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.nav_exit_company: CountHelper.logout(getActivity()); return true; } return super.onOptionsItemSelected(item); } }
true
af3c0c3308ae5928a10dfd84dcc393abce92542f
Java
christiannoubi/projectoverview
/src/main/java/de/adorsys/projectoverview/domain/Description.java
UTF-8
1,621
2.359375
2
[]
no_license
package de.adorsys.projectoverview.domain; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.*; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import java.util.Date; import java.time.ZonedDateTime; @Entity @EqualsAndHashCode @ToString public class Description { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private double budget; private String quality; private Date calenderWeeks; @JsonFormat(pattern = "yyyy-MM-dd") private ZonedDateTime time; public Description() { } /*public Description(Date calenderWeeks, ZonedDateTime time, double budget, String quality) { this.calenderWeeks = calenderWeeks; this.time = time; this.budget = budget; this.quality = quality; }*/ public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Date getCalenderWeeks() { return calenderWeeks; } public void setCalenderWeeks(Date calenderWeeks) { this.calenderWeeks = calenderWeeks; } public ZonedDateTime getTime() { return time; } public void setTime(ZonedDateTime time) { this.time = time; } public double getBudget() { return budget; } public void setBudget(double budget) { this.budget = budget; } public String getQuality() { return quality; } public void setQuality(String quality) { this.quality = quality; } }
true
dcbda51c05871550cfceccaa545ab2f93137d93a
Java
CMPUT301W16T03/papaya
/src/app/src/main/java/ca/ualberta/papaya/interfaces/IDataManager.java
UTF-8
681
2.234375
2
[ "MIT" ]
permissive
package ca.ualberta.papaya.interfaces; import android.content.Context; import java.util.ArrayList; import ca.ualberta.papaya.models.Thing; import ca.ualberta.papaya.models.User; import ca.ualberta.papaya.util.Observable; /** * Created by adlawren on 13/03/16. * * Interface for ThrowawayDataManager * @see ca.ualberta.papaya.data.ThrowawayDataManager */ public interface IDataManager { User getCurrentUser(Context context); void setCurrentUser(Context context, User newUser); ArrayList<Thing> getCurrentUserThings(Context context); void setCurrentUserThings(Context context, ArrayList<Thing> newThings); ArrayList<Thing> getNonCurrentUserThings(); }
true
8e75b262941250197b05ca58fd2c962f1ece3155
Java
ChenFengHub/design-pattern
/adapter-pattern/src/main/java/com/opensource/collectlog/LogWriteFileService.java
UTF-8
259
1.554688
2
[]
no_license
package com.opensource.collectlog; import java.util.List; /** * @program: designpattern * @description: 类功能描述 * @author: Mr.CF * @create: 2019-09-11 10:10:42 */ public interface LogWriteFileService { void logWriteFile(String logMsg); }
true
ca7ab508bf9d2178859a9ed26da7eef7255614a1
Java
HEAlex/radio-scheduler
/src/test/java/FileTreeNodeTest.java
UTF-8
1,657
2.59375
3
[]
no_license
import org.junit.Ignore; import ua.edu.sumdu.domain.FileTreeNode; import ua.edu.sumdu.domain.Mp3File; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class FileTreeNodeTest{ static Mp3File file1, file2, file3; static { file1 = new Mp3File(); file1.setId(1); file1.setFilename("/filetest1.mp3"); file2 = new Mp3File(); file2.setId(2); file2.setFilename("/test1/filetest2.mp3"); file3 = new Mp3File(); file3.setId(3); file3.setFilename("/test1/test2/filetest3.mp3"); } private static FileTreeNode initSimpleFileTreeNode(){ FileTreeNode root = new FileTreeNode("/"); root.add(file1); root.add(file2); root.add(file3); return root; } @Ignore public void insertTest(){ FileTreeNode root = initSimpleFileTreeNode(); assertTrue(root.getChildren().contains(file1)); assertTrue(root.getNodes().size() > 0); assertTrue(root.getNodes().containsKey("test1")); assertTrue(root.getNodes().get("test1").getChildren().contains(file2)); assertTrue(root.getNodes().get("test1").getNodes().containsKey("test2")); assertTrue(root.getNodes().get("test1").getNodes().get("test2").getChildren().contains(file3)); } @Ignore public void deleteTest(){ FileTreeNode root = initSimpleFileTreeNode(); root.deleteFile(file2); assertFalse(root.getNodes().get("test1").getChildren().contains(file2)); root.deleteFile(file3); assertFalse(root.getNodes().containsKey("test1")); } }
true
c2c090b04cd39b257dd9632105f76dd18271b745
Java
cardSeller/cardSeller
/common/domain/src/main/java/com/card/seller/domain/OrdersPaymentLog.java
UTF-8
1,246
2.078125
2
[]
no_license
package com.card.seller.domain; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import java.util.Date; @Entity @Table(name = "order_payment_log") @SequenceGenerator(name = "seq_gen", sequenceName = "seq_order_payment_log", allocationSize = 1) public class OrdersPaymentLog extends IdEntity { @Column(name = "order_id", nullable = false) private String orderId; @Column(name = "type", nullable = false) private String type; @Column(name = "context") private String context; @Column(name = "log_date", nullable = false) private Date logDate; public String getOrderId() { return orderId; } public void setOrderId(String orderId) { this.orderId = orderId; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getContext() { return context; } public void setContext(String context) { this.context = context; } public Date getLogDate() { return logDate; } public void setLogDate(Date logDate) { this.logDate = logDate; } }
true
5314e0126c5ded6401415a35d994dff0bf5e0212
Java
yunagile/weex-saoa
/platforms/android/farwolf/src/main/java/com/farwolf/view/qrCode/BarcodeScannerView.java
UTF-8
4,825
2.140625
2
[ "MIT" ]
permissive
package com.farwolf.view.qrCode; import android.content.Context; import android.graphics.Rect; import android.hardware.Camera; import android.util.AttributeSet; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; public abstract class BarcodeScannerView extends FrameLayout implements Camera.PreviewCallback { private Camera mCamera; private CameraPreview mPreview; private ViewFinderView mViewFinderView; private Rect mFramingRectInPreview; public static RelativeLayout layout; public BarcodeScannerView(Context context) { super(context); setupLayout(); } public BarcodeScannerView(Context context, AttributeSet attributeSet) { super(context, attributeSet); setupLayout(); } public void setupLayout() { mPreview = new CameraPreview(getContext()); mViewFinderView = new ViewFinderView(getContext()); layout = new RelativeLayout(getContext()); layout.addView(mPreview); TextView textView = new TextView(getContext()); ImageView imageView = new ImageView(getContext()); layout.addView(textView); layout.addView(imageView); addView(layout); addView(mViewFinderView); } public void startCamera(int cameraId) { startCamera(CameraUtils.getCameraInstance(cameraId)); } public void startCamera(Camera camera) { mCamera = camera; if (mCamera != null) { mViewFinderView.setupViewFinder(); mPreview.setCamera(mCamera, this); mPreview.initCameraPreview(); } } public void startCamera() { startCamera(CameraUtils.getCameraInstance()); } public void stopCamera() { if (mCamera != null) { mPreview.stopCameraPreview(); mPreview.setCamera(null, null); Camera temporary = mCamera; mCamera = null; temporary.release(); } } public synchronized Rect getFramingRectInPreview(int previewWidth, int previewHeight) { if (mFramingRectInPreview == null) { Rect framingRect = mViewFinderView.getFramingRect(); int viewFinderViewWidth = mViewFinderView.getWidth(); int viewFinderViewHeight = mViewFinderView.getHeight(); if (framingRect == null || viewFinderViewWidth == 0 || viewFinderViewHeight == 0) { return null; } Rect rect = new Rect(framingRect); rect.left = rect.left * previewWidth / viewFinderViewWidth; rect.right = rect.right * previewWidth / viewFinderViewWidth; rect.top = rect.top * previewHeight / viewFinderViewHeight; rect.bottom = rect.bottom * previewHeight / viewFinderViewHeight; mFramingRectInPreview = rect; } return mFramingRectInPreview; } public void setFlash(boolean flag) { if (mCamera != null && CameraUtils.isFlashSupported(mCamera)) { Camera.Parameters parameters = mCamera.getParameters(); if (flag) { if (parameters.getFlashMode().equals(Camera.Parameters.FLASH_MODE_TORCH)) { return; } parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH); } else { if (parameters.getFlashMode().equals(Camera.Parameters.FLASH_MODE_OFF)) { return; } parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); } mCamera.setParameters(parameters); } } public boolean getFlash() { if (mCamera != null && CameraUtils.isFlashSupported(mCamera)) { Camera.Parameters parameters = mCamera.getParameters(); if (parameters.getFlashMode().equals(Camera.Parameters.FLASH_MODE_TORCH)) { return true; } else { return false; } } return false; } public void toggleFlash() { if (mCamera != null && CameraUtils.isFlashSupported(mCamera)) { Camera.Parameters parameters = mCamera.getParameters(); if (parameters.getFlashMode().equals(Camera.Parameters.FLASH_MODE_TORCH)) { parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); } else { parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH); } mCamera.setParameters(parameters); } } public void setAutoFocus(boolean state) { if (mPreview != null) { mPreview.setAutoFocus(state); } } public boolean cameraAvailable() { return mCamera == null ? false : true; } }
true
8b04ea0e7a403d3ea6838b53a59a0b2ffe4d3e51
Java
RyanTech/Android-Apprentissage
/workspace_apprentissage/googleplus/src/com/google/api/services/plusi/model/SafeMobileUrlJson.java
UTF-8
635
1.992188
2
[]
no_license
package com.google.api.services.plusi.model; import com.google.android.apps.plus.json.EsJson; public final class SafeMobileUrlJson extends EsJson<SafeMobileUrl> { static final SafeMobileUrlJson INSTANCE = new SafeMobileUrlJson(); private SafeMobileUrlJson() { super(SafeMobileUrl.class, new Object[] { "url", "urlFormat" }); } public static SafeMobileUrlJson getInstance() { return INSTANCE; } } /* Location: C:\Dev\Java\android\adt-bundle-windows\workspace\googleplus\classes_dex2jar.jar * Qualified Name: com.google.api.services.plusi.model.SafeMobileUrlJson * JD-Core Version: 0.6.2 */
true
3553a77e1b3ca6bd5b42b9de6b6be9966326ae4e
Java
ateeb-hk/otalib
/src/main/java/org/opentravel/ota/StatusApplicationControlType.java
UTF-8
21,311
1.578125
2
[ "Apache-2.0" ]
permissive
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2017.07.11 at 07:19:31 PM IST // package org.opentravel.ota; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * The StatusApplicationControl class is used to indicate to which block codes/rate plans/inventory codes a status should be applied. * * <p>Java class for StatusApplicationControlType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="StatusApplicationControlType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="DestinationSystemCodes" type="{http://www.opentravel.org/OTA/2003/05}DestinationSystemCodesType" minOccurs="0"/> * &lt;/sequence> * &lt;attGroup ref="{http://www.opentravel.org/OTA/2003/05}StatusApplicationGroup"/> * &lt;attGroup ref="{http://www.opentravel.org/OTA/2003/05}InvBlockCodeApplyGroup"/> * &lt;attGroup ref="{http://www.opentravel.org/OTA/2003/05}RatePlanCodeTypeGroup"/> * &lt;attGroup ref="{http://www.opentravel.org/OTA/2003/05}DOW_PatternGroup"/> * &lt;attribute name="RateTier" type="{http://www.opentravel.org/OTA/2003/05}StringLength1to64" /> * &lt;attribute name="AllRateCode" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * &lt;attribute name="AllInvCode" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * &lt;attribute name="InvBlockCode" type="{http://www.opentravel.org/OTA/2003/05}StringLength1to32" /> * &lt;attribute name="Override" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * &lt;attribute name="QuoteID" type="{http://www.opentravel.org/OTA/2003/05}StringLength1to32" /> * &lt;attribute name="SubBlockCode" type="{http://www.opentravel.org/OTA/2003/05}StringLength1to32" /> * &lt;attribute name="WingIdentifier" type="{http://www.opentravel.org/OTA/2003/05}StringLength1to32" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "StatusApplicationControlType", propOrder = { "destinationSystemCodes" }) public class StatusApplicationControlType { @XmlElement(name = "DestinationSystemCodes") protected DestinationSystemCodesType destinationSystemCodes; @XmlAttribute(name = "RateTier") protected String rateTier; @XmlAttribute(name = "AllRateCode") protected Boolean allRateCode; @XmlAttribute(name = "AllInvCode") protected Boolean allInvCode; @XmlAttribute(name = "InvBlockCode") protected String invBlockCode; @XmlAttribute(name = "Override") protected Boolean override; @XmlAttribute(name = "QuoteID") protected String quoteID; @XmlAttribute(name = "SubBlockCode") protected String subBlockCode; @XmlAttribute(name = "WingIdentifier") protected String wingIdentifier; @XmlAttribute(name = "Start") protected String start; @XmlAttribute(name = "Duration") protected String duration; @XmlAttribute(name = "End") protected String end; @XmlAttribute(name = "RatePlanType") protected String ratePlanType; @XmlAttribute(name = "RatePlanCode") protected String ratePlanCode; @XmlAttribute(name = "RatePlanID") protected String ratePlanID; @XmlAttribute(name = "RatePlanQualifier") protected Boolean ratePlanQualifier; @XmlAttribute(name = "PromotionCode") protected String promotionCode; @XmlAttribute(name = "PromotionVendorCode") protected List<String> promotionVendorCode; @XmlAttribute(name = "RatePlanCategory") protected String ratePlanCategory; @XmlAttribute(name = "InvCodeApplication") protected String invCodeApplication; @XmlAttribute(name = "InvCode") protected String invCode; @XmlAttribute(name = "InvType") protected String invType; @XmlAttribute(name = "InvTypeCode") protected String invTypeCode; @XmlAttribute(name = "IsRoom") protected Boolean isRoom; @XmlAttribute(name = "InvBlockCodeApply") protected String invBlockCodeApply; @XmlAttribute(name = "RatePlanCodeType") protected String ratePlanCodeType; @XmlAttribute(name = "Mon") protected Boolean mon; @XmlAttribute(name = "Tue") protected Boolean tue; @XmlAttribute(name = "Weds") protected Boolean weds; @XmlAttribute(name = "Thur") protected Boolean thur; @XmlAttribute(name = "Fri") protected Boolean fri; @XmlAttribute(name = "Sat") protected Boolean sat; @XmlAttribute(name = "Sun") protected Boolean sun; /** * Gets the value of the destinationSystemCodes property. * * @return * possible object is * {@link DestinationSystemCodesType } * */ public DestinationSystemCodesType getDestinationSystemCodes() { return destinationSystemCodes; } /** * Sets the value of the destinationSystemCodes property. * * @param value * allowed object is * {@link DestinationSystemCodesType } * */ public void setDestinationSystemCodes(DestinationSystemCodesType value) { this.destinationSystemCodes = value; } /** * Gets the value of the rateTier property. * * @return * possible object is * {@link String } * */ public String getRateTier() { return rateTier; } /** * Sets the value of the rateTier property. * * @param value * allowed object is * {@link String } * */ public void setRateTier(String value) { this.rateTier = value; } /** * Gets the value of the allRateCode property. * * @return * possible object is * {@link Boolean } * */ public Boolean isAllRateCode() { return allRateCode; } /** * Sets the value of the allRateCode property. * * @param value * allowed object is * {@link Boolean } * */ public void setAllRateCode(Boolean value) { this.allRateCode = value; } /** * Gets the value of the allInvCode property. * * @return * possible object is * {@link Boolean } * */ public Boolean isAllInvCode() { return allInvCode; } /** * Sets the value of the allInvCode property. * * @param value * allowed object is * {@link Boolean } * */ public void setAllInvCode(Boolean value) { this.allInvCode = value; } /** * Gets the value of the invBlockCode property. * * @return * possible object is * {@link String } * */ public String getInvBlockCode() { return invBlockCode; } /** * Sets the value of the invBlockCode property. * * @param value * allowed object is * {@link String } * */ public void setInvBlockCode(String value) { this.invBlockCode = value; } /** * Gets the value of the override property. * * @return * possible object is * {@link Boolean } * */ public Boolean isOverride() { return override; } /** * Sets the value of the override property. * * @param value * allowed object is * {@link Boolean } * */ public void setOverride(Boolean value) { this.override = value; } /** * Gets the value of the quoteID property. * * @return * possible object is * {@link String } * */ public String getQuoteID() { return quoteID; } /** * Sets the value of the quoteID property. * * @param value * allowed object is * {@link String } * */ public void setQuoteID(String value) { this.quoteID = value; } /** * Gets the value of the subBlockCode property. * * @return * possible object is * {@link String } * */ public String getSubBlockCode() { return subBlockCode; } /** * Sets the value of the subBlockCode property. * * @param value * allowed object is * {@link String } * */ public void setSubBlockCode(String value) { this.subBlockCode = value; } /** * Gets the value of the wingIdentifier property. * * @return * possible object is * {@link String } * */ public String getWingIdentifier() { return wingIdentifier; } /** * Sets the value of the wingIdentifier property. * * @param value * allowed object is * {@link String } * */ public void setWingIdentifier(String value) { this.wingIdentifier = value; } /** * Gets the value of the start property. * * @return * possible object is * {@link String } * */ public String getStart() { return start; } /** * Sets the value of the start property. * * @param value * allowed object is * {@link String } * */ public void setStart(String value) { this.start = value; } /** * Gets the value of the duration property. * * @return * possible object is * {@link String } * */ public String getDuration() { return duration; } /** * Sets the value of the duration property. * * @param value * allowed object is * {@link String } * */ public void setDuration(String value) { this.duration = value; } /** * Gets the value of the end property. * * @return * possible object is * {@link String } * */ public String getEnd() { return end; } /** * Sets the value of the end property. * * @param value * allowed object is * {@link String } * */ public void setEnd(String value) { this.end = value; } /** * Gets the value of the ratePlanType property. * * @return * possible object is * {@link String } * */ public String getRatePlanType() { return ratePlanType; } /** * Sets the value of the ratePlanType property. * * @param value * allowed object is * {@link String } * */ public void setRatePlanType(String value) { this.ratePlanType = value; } /** * Gets the value of the ratePlanCode property. * * @return * possible object is * {@link String } * */ public String getRatePlanCode() { return ratePlanCode; } /** * Sets the value of the ratePlanCode property. * * @param value * allowed object is * {@link String } * */ public void setRatePlanCode(String value) { this.ratePlanCode = value; } /** * Gets the value of the ratePlanID property. * * @return * possible object is * {@link String } * */ public String getRatePlanID() { return ratePlanID; } /** * Sets the value of the ratePlanID property. * * @param value * allowed object is * {@link String } * */ public void setRatePlanID(String value) { this.ratePlanID = value; } /** * Gets the value of the ratePlanQualifier property. * * @return * possible object is * {@link Boolean } * */ public Boolean isRatePlanQualifier() { return ratePlanQualifier; } /** * Sets the value of the ratePlanQualifier property. * * @param value * allowed object is * {@link Boolean } * */ public void setRatePlanQualifier(Boolean value) { this.ratePlanQualifier = value; } /** * Gets the value of the promotionCode property. * * @return * possible object is * {@link String } * */ public String getPromotionCode() { return promotionCode; } /** * Sets the value of the promotionCode property. * * @param value * allowed object is * {@link String } * */ public void setPromotionCode(String value) { this.promotionCode = value; } /** * Gets the value of the promotionVendorCode property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the promotionVendorCode property. * * <p> * For example, to add a new item, do as follows: * <pre> * getPromotionVendorCode().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getPromotionVendorCode() { if (promotionVendorCode == null) { promotionVendorCode = new ArrayList<String>(); } return this.promotionVendorCode; } /** * Gets the value of the ratePlanCategory property. * * @return * possible object is * {@link String } * */ public String getRatePlanCategory() { return ratePlanCategory; } /** * Sets the value of the ratePlanCategory property. * * @param value * allowed object is * {@link String } * */ public void setRatePlanCategory(String value) { this.ratePlanCategory = value; } /** * Gets the value of the invCodeApplication property. * * @return * possible object is * {@link String } * */ public String getInvCodeApplication() { return invCodeApplication; } /** * Sets the value of the invCodeApplication property. * * @param value * allowed object is * {@link String } * */ public void setInvCodeApplication(String value) { this.invCodeApplication = value; } /** * Gets the value of the invCode property. * * @return * possible object is * {@link String } * */ public String getInvCode() { return invCode; } /** * Sets the value of the invCode property. * * @param value * allowed object is * {@link String } * */ public void setInvCode(String value) { this.invCode = value; } /** * Gets the value of the invType property. * * @return * possible object is * {@link String } * */ public String getInvType() { return invType; } /** * Sets the value of the invType property. * * @param value * allowed object is * {@link String } * */ public void setInvType(String value) { this.invType = value; } /** * Gets the value of the invTypeCode property. * * @return * possible object is * {@link String } * */ public String getInvTypeCode() { return invTypeCode; } /** * Sets the value of the invTypeCode property. * * @param value * allowed object is * {@link String } * */ public void setInvTypeCode(String value) { this.invTypeCode = value; } /** * Gets the value of the isRoom property. * * @return * possible object is * {@link Boolean } * */ public Boolean isIsRoom() { return isRoom; } /** * Sets the value of the isRoom property. * * @param value * allowed object is * {@link Boolean } * */ public void setIsRoom(Boolean value) { this.isRoom = value; } /** * Gets the value of the invBlockCodeApply property. * * @return * possible object is * {@link String } * */ public String getInvBlockCodeApply() { return invBlockCodeApply; } /** * Sets the value of the invBlockCodeApply property. * * @param value * allowed object is * {@link String } * */ public void setInvBlockCodeApply(String value) { this.invBlockCodeApply = value; } /** * Gets the value of the ratePlanCodeType property. * * @return * possible object is * {@link String } * */ public String getRatePlanCodeType() { return ratePlanCodeType; } /** * Sets the value of the ratePlanCodeType property. * * @param value * allowed object is * {@link String } * */ public void setRatePlanCodeType(String value) { this.ratePlanCodeType = value; } /** * Gets the value of the mon property. * * @return * possible object is * {@link Boolean } * */ public Boolean isMon() { return mon; } /** * Sets the value of the mon property. * * @param value * allowed object is * {@link Boolean } * */ public void setMon(Boolean value) { this.mon = value; } /** * Gets the value of the tue property. * * @return * possible object is * {@link Boolean } * */ public Boolean isTue() { return tue; } /** * Sets the value of the tue property. * * @param value * allowed object is * {@link Boolean } * */ public void setTue(Boolean value) { this.tue = value; } /** * Gets the value of the weds property. * * @return * possible object is * {@link Boolean } * */ public Boolean isWeds() { return weds; } /** * Sets the value of the weds property. * * @param value * allowed object is * {@link Boolean } * */ public void setWeds(Boolean value) { this.weds = value; } /** * Gets the value of the thur property. * * @return * possible object is * {@link Boolean } * */ public Boolean isThur() { return thur; } /** * Sets the value of the thur property. * * @param value * allowed object is * {@link Boolean } * */ public void setThur(Boolean value) { this.thur = value; } /** * Gets the value of the fri property. * * @return * possible object is * {@link Boolean } * */ public Boolean isFri() { return fri; } /** * Sets the value of the fri property. * * @param value * allowed object is * {@link Boolean } * */ public void setFri(Boolean value) { this.fri = value; } /** * Gets the value of the sat property. * * @return * possible object is * {@link Boolean } * */ public Boolean isSat() { return sat; } /** * Sets the value of the sat property. * * @param value * allowed object is * {@link Boolean } * */ public void setSat(Boolean value) { this.sat = value; } /** * Gets the value of the sun property. * * @return * possible object is * {@link Boolean } * */ public Boolean isSun() { return sun; } /** * Sets the value of the sun property. * * @param value * allowed object is * {@link Boolean } * */ public void setSun(Boolean value) { this.sun = value; } }
true
ab59df291efbe722ce046083c190bb20a27d6359
Java
GonzaDiz/TP1J
/TP1J/src/src/Compra.java
UTF-8
1,664
3.046875
3
[]
no_license
package src; import java.util.ArrayList; public class Compra { private ArrayList<Producto> productosAComprar; private double precioTotal; private ArrayList<Servicio> servicios; private Cupon cupon; public Compra() { this.productosAComprar = new ArrayList<Producto>(); this.precioTotal = 0; this.servicios = new ArrayList<Servicio>(); this.cupon = new Cupon(); } public static Compra crearNuevaCompra() { Compra compra = new Compra(); return compra; } public double getPrecioTotal() { for (Servicio s : servicios ) { precioTotal = s.modificarPrecio(precioTotal); } precioTotal = cupon.modificarPrecio(precioTotal); return precioTotal; } public void agregarProducto(Producto producto) { productosAComprar.add(producto); precioTotal = precioTotal + producto.getPrecio(); } public static Compra crearNuevaCompraConEnvio() { Compra compra = new Compra(); compra.agregarEnvio(); return compra; } private void agregarEnvio() { Envio envio = new Envio(); servicios.add(envio); } public static Compra crearNuevaCompraConGarantia() { Compra compra = new Compra(); compra.agregarGarantia(); return compra; } private void agregarGarantia() { Garantia garantia = new Garantia(); servicios.add(garantia); } public static Compra crearNuevaCompraConEnvioYGarantia() { Compra compra = new Compra(); compra.agregarGarantia(); compra.agregarEnvio(); return compra; } public void agregarCupon(Cupon cupon) { if (this.cupon.getPorcentajeDescuento() < cupon.getPorcentajeDescuento()) { this.cupon = cupon; } } }
true
ffcd1fc6324bfcb89cb4c9e888d214f6bcaf482f
Java
sysdruid/roundforest-dev-task
/src/main/java/com/cib/roundforest/translator/TranslatorImpl.java
UTF-8
1,936
2.703125
3
[]
no_license
package com.cib.roundforest.translator; import com.cib.roundforest.google.GoogleTranslator; import com.cib.roundforest.google.GoogleTranslatorMock; import com.google.gson.Gson; import com.google.gson.GsonBuilder; /** * * @author Yury Altukhou */ public class TranslatorImpl implements Translator{ private final static int MAX_REQUEST_COUNT = 100; private final GsonBuilder gsonBuilder; private GoogleTranslator googleTranslator = new GoogleTranslatorMock(); private final Object semaphore = new Object(); private int count = 0 ; @Override public <T> void translate(T key, String text, TranslatorCallback<T> callback) { synchronized(semaphore) { while(count == MAX_REQUEST_COUNT) { try { semaphore.wait(); } catch (InterruptedException ex) { ex.printStackTrace(); } } googleTranslator.translate(request(text), (translated) -> { TranslationResult[] result = gson().fromJson(translated, TranslationResult[].class); decCount(); callback.translated(key, result[0].text); }); count++; } } public TranslatorImpl() { this.gsonBuilder = new GsonBuilder(); gsonBuilder.disableHtmlEscaping(); } private synchronized Gson gson() { return gsonBuilder.create(); } private void decCount() { synchronized(semaphore) { count--; semaphore.notifyAll(); } } private String request(String text) { text = text.substring(0, Math.min(900, text.length())); text = gson().toJson(text); final String template= "[{input_lang:\"en\",output_lang:\"fr\",text:%s}]"; return String.format(template, text); } private final static class TranslationResult { String text; } }
true
6543366ebbfce288e1868d186ad2cd596a1cc991
Java
theanh2010/Chien
/Module_2/src/_11_dsa_stack_queue/bai_tap/kiem_tra_chuoi_palindrome/CheckPanlindrome.java
UTF-8
1,219
3.71875
4
[]
no_license
package _11_dsa_stack_queue.bai_tap.kiem_tra_chuoi_palindrome; import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; import java.util.Stack; public class CheckPanlindrome { public void Check(String str){ Stack<Character> stack = new Stack<>(); Queue<Character> queue = new LinkedList<>(); int count = 0; int check = 0 ; for (int i = 0; i < str.length(); i++){ stack.push(str.charAt(i)); queue.add(str.charAt(i)); count++; } while (!stack.isEmpty()){ if (stack.pop() == queue.poll()){ check++; } if (check == count){ System.out.println("Chuỗi "+ str + " là chuỗi panlindrome!"); return; } else { System.out.println("Chuỗi "+ str + " không phải là chuỗi panlindrome!"); return; } } } public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Nhập chuỗi muốn kiểm tra: "); String str = input.nextLine(); new CheckPanlindrome().Check(str); } }
true
2247df2d2ce4daf5aa783aebf979144fef7927a4
Java
mmcclain117/School-Code
/High School/HS-Extra-Code/File Stuff Extra/src/CompareFiles.java
UTF-8
5,093
3.46875
3
[ "Apache-2.0" ]
permissive
import java.io.*; import static java.lang.System.out; import java.util.*; /** * * @author Master */ public class CompareFiles { /* Things to test and fix If there is 3 files that are the same How to cut down on time to if i was to be testing 340,000 files If there are two of the same folders Enter C:\\ as one and see how long it takes */ public static void main(String[] args) throws Exception { // Scanner scan = new Scanner(System.in); // boolean run = true;// Used if you want to have it repeat if you dont input a valid anwser // String y = "C:\\Users\\Jacob\\Desktop\\Final\\Erica Soccer Stuff"; String y = "C:\\Users\\Jacob\\Dropbox\\File Stuff\\T9"; File start = new File(y); File st[] = start.listFiles(); // Starting list of files ArrayList<File> ar = new ArrayList<>(); ArrayList<File> tempAR = new ArrayList<>(); ArrayList<File> Final = new ArrayList<>(); ArrayList<File> NS = new ArrayList<>(); // Not sure ar.addAll(Arrays.asList(st)); /* Finds all of the possible files in the folder and puts them in final */ while (!ar.isEmpty()) { for (int i = 0; i < ar.size(); i++) { if (ar.get(i).isFile()) { Final.add(ar.get(i)); } else if (FileNameTest(ar.get(i))) { NS.add(ar.get(i)); } else { tempAR.add(ar.get(i)); } ar.remove(i); } while (!tempAR.isEmpty()) { File g[] = tempAR.get(0).listFiles(); ar.addAll(Arrays.asList(g)); tempAR.remove(0); } } out.println("ar"); printA(ar); out.println("temp"); printA(tempAR); out.println("final"); printA(Final); out.println("NS"); printA(NS); // try (FileWriter fw = new FileWriter(new File("FinalPaths.txt"))) { // for (File f : Final) { // fw.write(f.getAbsolutePath() + "\n"); // } // fw.flush(); // } // System.gc(); Name(Final); } /* Alternate way to check if a file is a file and not a directory */ private static boolean FileNameTest(File get) throws IOException { File gp[] = get.listFiles(); if (gp == null) { return true; } else { for (File gp1 : gp) { if (gp1 == null) { return true; } } } return false; } private static void Name(ArrayList<File> Final) throws IOException { try (FileWriter fr = new FileWriter(new File("SameName.txt"))) { ArrayList<File> a = Final; // Sorted Final int finlen = Final.size(); Collections.sort(a); ArrayList<String> FN = new ArrayList(); // File name for (File a1 : a) { FN.add(a1.getName()); // out.println(a1.getName()); } // int i1 = Final.get(i).toString().lastIndexOf("\\"); // String i2 = Final.get(i).toString().substring(i1); // int j1 = Final.get(j).toString().lastIndexOf("\\"); // String j2 = Final.get(j).toString().substring(j1); for (int i = 0; i < finlen - 1; i++) { int con = 0; String f1 = FN.get(i); for (int j = i + 1; j < finlen - 1; j++) { String f2 = FN.get(j); if (f2.equalsIgnoreCase(f1)) { if (con == 0) { fr.write(a.get(i) + " "); } fr.write(a.get(j) + ""); con++; } else { break; } } } fr.write("\n"); fr.flush(); } } private static void NameUnsort(ArrayList<File> Final) throws IOException { try (FileWriter fr = new FileWriter(new File("SameName.txt"))) { int finlen = Final.size(); for (int i = 0; i < finlen; i++) { for (int j = i + 1; j < finlen; j++) { int i1 = Final.get(i).toString().lastIndexOf("\\"); String i2 = Final.get(i).toString().substring(i1); int j1 = Final.get(j).toString().lastIndexOf("\\"); String j2 = Final.get(j).toString().substring(j1); if (i2.equals(j2)) { File fte = new File(j2); // Folder Temperary Name fr.write(Final.get(i) + " " + Final.get(j) + "\n"); } } fr.write("\n"); } fr.flush(); } } private static void printA(ArrayList<File> ar) { for (File a : ar) { out.println(a.getName()); } } }
true
9a606960613fb3b6df66cfac5a27f8310fabe8af
Java
umar07/class_10_codes
/pascal.java
UTF-8
560
3.40625
3
[ "MIT" ]
permissive
/* package whatever; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ class Ideone { public static void main (String[] args) throws java.lang.Exception { int i,b,p=5,j; for(i=1;i<=5;i++) { for(b=1;b<=p;b++) { System.out.print(" "); } for( j=1;j<=i;j++) { System.out.print(j); } for(int k=j-2;k>=1;k--) { System.out.print(k); } System.out.println(); p--; } } }
true
14c95c87948d7d3cf29257899567d83d4099dd4a
Java
g2vinay/azure-sdk-for-java
/sdk/appconfiguration/spring-cloud-azure-appconfiguration-config/src/main/java/com/microsoft/azure/spring/cloud/config/AppConfigurationCredentialProvider.java
UTF-8
318
1.578125
2
[ "MIT", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-warranty-disclaimer", "BSD-3-Clause", "CC0-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference", "LGPL-2.1-or-later" ]
permissive
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.microsoft.azure.spring.cloud.config; import com.azure.core.credential.TokenCredential; public interface AppConfigurationCredentialProvider { public TokenCredential getAppConfigCredential(String uri); }
true
3e119a2cc5306a6d98da0b547af72da252956c7d
Java
cleristonm/Book-and-Courses
/Java-Concurrency-Cookbook/C06E06-Transforming the elements of a stream/src/com/keko/code/FileGenerator.java
UTF-8
664
2.578125
3
[]
no_license
package com.keko.code; import java.util.ArrayList; import java.util.List; public class FileGenerator { public static List<String> generateFile(int size) { List<String> file=new ArrayList<>(); for (int i=0; i<size; i++) { file.add("Lorem ipsum dolor sit amet, " + "consectetur adipiscing elit. Morbi lobortis" + "cursus venenatis. Mauris tempus elit ut " + " malesuada luctus. Interdum et malesuada fames " + " ac ante ipsum primis in faucibus. Phasellus " + " laoreet sapien eu pulvinar rhoncus. Integer vel" + " ultricies leo. Donec vel sagittis nibh." + " Maecenas eu quam non est hendrerit pu"); } return file; } }
true
9e3e24b6f5087e0088bc8c39b2710633d0094345
Java
BytesOfPi/LEDSuitAndroid
/app/src/main/java/com/degroff/pandaled/util/Toolbox.java
UTF-8
1,179
2.390625
2
[]
no_license
package com.degroff.pandaled.util; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.content.Context; import android.content.Intent; import android.view.Gravity; import android.widget.Toast; import com.degroff.pandaled.MainActivity; public final class Toolbox { /** * Check if adapter exists and is enabled * * @param adapter * @return */ public static boolean checkBLEAdapter(final BluetoothAdapter adapter) { return !(adapter == null || !adapter.isEnabled()); } public static void requestUserBluetooth(final Activity activity) { final Intent enableBleIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); activity.startActivityForResult(enableBleIntent, MainActivity.REQUEST_ENABLE_BLE); } /** * Generate Toast Message * * @param context * @param msg */ public static void toast(final Context context, final String msg) { final Toast toast = Toast.makeText(context, msg, Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER | Gravity.BOTTOM, 0, 0); toast.show(); } }
true
22f69efbeeb38df06612f2bebee82faafb9efc25
Java
masroorasghar/GsonActivity
/app/src/main/java/com/example/usmanahmed/gsonactivity/Main2Activity.java
UTF-8
867
2.4375
2
[]
no_license
package com.example.masroor.gsonactivity; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; import com.google.gson.Gson; public class Main2Activity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); Gson gson=new Gson(); String datatoGet=getIntent().getStringExtra("rice"); String datatoGet1=getIntent().getStringExtra("rice1"); person get= gson.fromJson(datatoGet,person.class); person get1=gson.fromJson(datatoGet1,person.class); Toast.makeText(this,get.getName()+" : "+get.getNumber(),Toast.LENGTH_SHORT).show(); Toast.makeText(this,get1.getName()+" : "+get1.getNumber(),Toast.LENGTH_SHORT).show(); } }
true
519a5e6e284699a9abd01e2c4f38c25da98d4847
Java
JordanPonder23/Android
/OreoPractice/app/src/main/java/com/example/oreopractice/MainActivity.java
UTF-8
10,068
2.265625
2
[]
no_license
package com.example.oreopractice; import androidx.appcompat.app.AppCompatActivity; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.ref.WeakReference; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Random; public class MainActivity extends AppCompatActivity { DbAdapter dbAdapter; ArrayAdapter<String> itemsAdapter; ListView listView; ArrayList<String> listOfSchoolsArray = new ArrayList<>(); private class DownloadSchoolTask extends AsyncTask<String,Void,String> { private WeakReference<MainActivity> mActivity; public DownloadSchoolTask(MainActivity activity) { mActivity = new WeakReference<MainActivity>(activity); } MainActivity activity; URL url = null; JSONArray satData; JSONArray schoolData = new JSONArray(); private JSONArray mixedData = new JSONArray(); /* * the getSATData and getSchoolData getters provide no real meaningful implementation now * but I might build something out that requires them later */ protected JSONArray getSATData() { return satData; } protected JSONArray getSchoolData() { return schoolData; } protected ArrayList<String> getSchoolDataForAdapter() { ArrayList<String> sList = new ArrayList<>(); for(int i = 0; i < this.schoolData.length(); i++ ){ try { sList.add(new JSONObject(this.schoolData.get(i).toString()).getString("schoolName")); }catch (JSONException e) {} } return sList; } protected List<String> mixedData(){ List<String> aList = new ArrayList<>(); for(int i = 0; i < this.mixedData.length(); i++ ){ try { aList.add( this.mixedData.get(i).toString() ); }catch (JSONException e) {} } return aList; } private void associateData() throws JSONException{ JSONArray combined = new JSONArray(); /* * There is no point to having a list item without a mentioend school, so SAT scores will * be appended to new view-ready objects of final list on the basis that a school already exists. */ for(int i =0; i < getSchoolData().length(); i++){ try { Log.i("An-Object", getSchoolData().get(i).toString()); }catch (Exception e) {} for(int e = 0; e < getSATData().length(); e ++) { JSONObject school = new JSONObject( getSchoolData().get(i).toString()); JSONObject satObject = new JSONObject( getSATData().get(e).toString()); if(school.getString("dbn").equals(satObject.getString("dbn"))) { JSONObject combinedObject = new JSONObject(); combinedObject.put("dbn",school.getString("dbn")); combinedObject.put("schoolName", school.getString("schoolName")); combinedObject.put("boro", school.getString("boro")); combinedObject.put("overview_paragraph", school.getString("overview_paragraph")); combinedObject.put("location", school.getString("location")); combinedObject.put("website", school.getString("website")); combinedObject.put("phone_number", school.getString("phone_number")); combinedObject.put("takers", satObject.getString("takers")); combinedObject.put("reading", satObject.getString("reading")); combinedObject.put("math", satObject.getString("math")); combinedObject.put("writing", satObject.getString("writing")); combined.put(combinedObject); } } } } @Override protected String doInBackground(String... urls) { String result = ""; HttpURLConnection urlConnection = null; this.satData = new JSONArray(); this.schoolData = new JSONArray(); /* * Loop through multiple URLS * * This will make for an easy update process in case there are * new data sources (eg. ACT scores) that are to be appended in the future * * Only downside is that SAT and School list are not being fetched at same time * (this could have been down by having a separate ASYNC task performed for SAT scores * and executed adjacent to schools being fetched..) */ for(int e =0; e < urls.length; e++) { try { this.url = new URL(urls[e]); urlConnection = (HttpURLConnection) this.url.openConnection(); urlConnection.setInstanceFollowRedirects(true); urlConnection.setUseCaches(true); urlConnection.setDefaultUseCaches(true); InputStream in = urlConnection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String line = ""; while ((line = br.readLine()) != null) { result += line; } Log.i("result: ", result); return result; } catch (Exception err) { err.printStackTrace(); Log.e("Error Log: ", err.getClass().toString()); return "error: "+err.getClass(); } } return null; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); this.activity = mActivity.get(); if (activity != null) { activity.listView = (ListView) activity.findViewById(R.id.listViewSchool); activity.itemsAdapter = new ArrayAdapter<String>(activity, android.R.layout.simple_list_item_1, activity.listOfSchoolsArray); activity.listView.setAdapter(itemsAdapter); } try { Log.i("PostExecute",s); JSONArray jsonList = new JSONArray(s); if (this.url.toString().contains("s3k6")) { persistSchoolData(jsonList); } else if(this.url.toString().contains("f9bf")){ persistSATData(jsonList) ; } associateData(); } catch (Exception e) { e.printStackTrace(); } } //SAT json data is persisted as initially provided by resource private void persistSATData (JSONArray satList) throws JSONException { for(int i = 0; i < satList.length(); i++) { JSONObject row = satList.getJSONObject(i); long id = dbAdapter.insertSATData(row.getString("dbn"), row.getString("school_name"), row.getString("num_of_sat_test_takers"), row.getString("sat_critical_reading_avg_score"), row.getString("sat_math_avg_score"), row.getString("sat_writing_avg_score")); JSONObject data = dbAdapter.getSATData(); this.satData.put(data); Log.i("SATData", getSATData().toString() ); } } //School json data is persisted as initially provided by resource private void persistSchoolData(JSONArray dbSchoolList) throws JSONException { for(int i = 0; i < dbSchoolList.length(); i++){ JSONObject row = dbSchoolList.getJSONObject(i); long id = dbAdapter.insertSchoolData(row.getString("dbn"), row.getString("school_name"), row.getString("boro"), row.getString("overview_paragraph"), row.getString("location"), row.getString("website"), row.getString("phone_number")); JSONObject data = dbAdapter.getSchoolData(); this.schoolData.put(data); activity.listOfSchoolsArray.add( getSchoolDataForAdapter().get(i) ); /* * A lot of this was done with loading the list items asynchronously as they are * returned from DB. After further research, this is a little tougher than MVP * than I original thought. */ activity.listView.invalidateViews(); activity.itemsAdapter.notifyDataSetChanged(); Log.i("SchoolData", getSchoolData().toString()); } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.i("main", "At entry point"); DownloadSchoolTask task = new DownloadSchoolTask(this); dbAdapter = new DbAdapter(this); Toast.makeText(getApplicationContext(), "Eager Loading School and SAT data", Toast.LENGTH_LONG).show(); task.execute( "https://data.cityofnewyork.us/resource/s3k6-pzi2.json", "https://data.cityofnewyork.us/resource/f9bf-2cp4.json"); } }
true
a671b2634edd6c63cd3348bee62373ed875b6553
Java
xiaoxuda/stockDataCatch
/src/com/kimi/stockanalysis/catcher/BaseCatcher.java
UTF-8
6,295
2.5
2
[]
no_license
package com.kimi.stockanalysis.catcher; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import javax.annotation.PostConstruct; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.support.TransactionTemplate; import com.kimi.stockanalysis.catcher.enums.TaskTypeEnum; import com.kimi.stockanalysis.catcher.service.CatchTask; import com.kimi.stockanalysis.catcher.service.TaskQueueService; import com.kimi.stockanalysis.entity.StockInfo; /* * @author kimi */ public abstract class BaseCatcher { /** 为每个子类提供一个区别化的日志类 **/ protected final Logger LOGGER = LoggerFactory.getLogger(this.getClass()); /** 事务 **/ @Autowired protected TransactionTemplate transactionTemplate; @Autowired private TaskQueueService taskQueueService; /** 线程池,子类只能通过覆盖入口方法修改部分属性,核心默认6个线程 **/ private final ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(6); private boolean isRunning = false; // 标识任务正在运行 private int defaultWaitTime = 1000; // 默认抓取间隔 private int maxWaitTime = 2 * 60 * 1000; // 最大抓取间隔2分钟 private int waitTime = 1000; // 当前抓取间隔 private int waitMultiplier = 3;// 抓取时间乘数 private int againTime = 5; // 异常重试次数 /** * 子类可以通过重载此方法调用customExecutor来定制化工作线程池 */ public void customExecutor() { } /** * 定制线程池,不允许重载,不需要设置的参数可设为null * * @param corePoolSize * @param handler */ protected final void customExecutor(Integer corePoolSize, RejectedExecutionHandler handler) { if (null != corePoolSize) { this.executor.setCorePoolSize(corePoolSize); this.executor.setMaximumPoolSize(corePoolSize); } if (null != handler) { this.executor.setRejectedExecutionHandler(handler); } } /** * 初始化属性 */ @PostConstruct public void init() { executor.setKeepAliveTime(5*60*1000L, TimeUnit.SECONDS); executor.allowCoreThreadTimeOut(true); //定制化扩展钩子 this.customExecutor(); } /** * 生成爬虫任务 * @param stockInfo * @return */ public abstract CatchTask generateTask(StockInfo stockInfo); /** * 数据提取及保存逻辑,需要爬虫具体实现 * * @param src 数据文本 * @param task 任务信息 * @return */ public abstract boolean extract(String src, CatchTask task); /** * 返回任务类型,不能为空,需要爬虫具体实现 * * @author kimi * @return 返回值不能为空 */ public abstract TaskTypeEnum getTaskType(); /** * 判断爬虫是否处于运行中 * * @return */ public boolean isRunning() { return this.isRunning; } /** * 启动爬虫,定时请求数据抓取任务 */ public void start() { if (this.isRunning) { return; } Thread thread_catcher = new Thread(getTaskType() + "_Catcher") { public void run() { while (true) { CatchTask task = taskQueueService.getTask(getTaskType()); try { if (task == null) {// 当前没有任务,将抓取间隔调高waitMultiplier倍让出CPU资源 LOGGER.info("{}:no task", getTaskType()); if (waitTime == maxWaitTime) { LOGGER.info("{}等待任务时间超时,爬虫退出,等待重新唤起。", getTaskType()); break; } waitTime *= waitMultiplier; waitTime = waitTime > maxWaitTime ? maxWaitTime : waitTime; } else { // 当前任务列表有任务,恢复抓取间隔为默认值 waitTime = defaultWaitTime; //提交任务 executor.submit(new CatcherRunable(task)); //当前任务数量没有达到最大核心数,继续添加任务 if(executor.getActiveCount()<executor.getCorePoolSize()){ continue; } } Thread.sleep(waitTime); } catch (Exception e) { // TODO Auto-generated catch block LOGGER.error("任务{}异常", task, e); } } isRunning = false; } }; LOGGER.info("{}:start", getTaskType() + "_Catcher"); thread_catcher.start(); this.isRunning = true; } /** * 根据任务抓取远程数据 * * @param task * 任务信息 * @param againTime * 失败重试次数 * @return */ public String catchAction(CatchTask task, int nowAgainTime) { try { URL url = new URL(task.getUrl()); HttpURLConnection con = (HttpURLConnection) url.openConnection(); InputStream inputStream = con.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream); BufferedReader reader = new BufferedReader(inputStreamReader); StringBuilder builder = new StringBuilder(); // 将html文档格式化为单行文本 String line = null; while ((line = reader.readLine()) != null) { builder.append(line); } extract(builder.toString(), task); } catch (Exception e) { // TODO Auto-generated catch block LOGGER.error("任务{}异常", task, e); // 异常重试 if (nowAgainTime <= againTime) { catchAction(task, ++nowAgainTime); } else { LOGGER.info("任务重试超过{}次,重新放回任务队列等待调度,参数{}", againTime, task); } } return null; } /** * 爬虫执行单元 * * @author kimi * */ class CatcherRunable implements Runnable { private CatchTask task; public CatcherRunable(CatchTask task) { this.task = task; } @Override public void run() { catchAction(this.task, againTime); } } /** * @return the transactionTemplate */ public TransactionTemplate getTransactionTemplate() { return transactionTemplate; } /** * @param transactionTemplate the transactionTemplate to set */ public void setTransactionTemplate(TransactionTemplate transactionTemplate) { this.transactionTemplate = transactionTemplate; } }
true
435305a407b923d7cda58526fb025ddd236d0a80
Java
elui/machine-learning-information-retrieval
/src/cs276/pa4/Scorers/SmallestWindowScorer.java
UTF-8
7,806
2.546875
3
[]
no_license
package cs276.pa4.Scorers; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import cs276.pa4.Document; import cs276.pa4.Pair; import cs276.pa4.Query; /** * A skeleton for implementing the Smallest Window scorer in Task 3. * Note: The class provided in the skeleton code extends BM25Scorer in Task 2. However, you don't necessarily * have to use Task 2. (You could also use Task 1, in which case, you'd probably like to extend CosineSimilarityScorer instead.) * Also, feel free to modify or add helpers inside this class. */ //public class SmallestWindowScorer extends CosineSimilarityScorer{ public class SmallestWindowScorer extends BM25Scorer{ private double B = 1.2; public static Set<String> STOP_WORDS = new HashSet<String>(Arrays.asList("a", "an", "and", "are", "as", "at", "be", "by", "for", "from", "has", "is", "of", "that", "the", "to", "was", "were", "will", "with")); public SmallestWindowScorer(Map<String, Double> idfs, Map<Query,Map<String, Document>> queryDict) { // super(idfs); super(idfs, queryDict); } public String[] stem(String[] tokens) { String[] result = new String[tokens.length]; for (int i = 0; i < tokens.length; i++) { String token = tokens[i]; } return result; } /** * get smallest window of one document and query pair. * @param d: document * @param q: query */ private int getWindow(Document d, Query q) { /* * @//TODO : Your code here */ List<String> stemmedQuery = q.queryWords(); Set<String> queryWords = new HashSet<String>(stemmedQuery); queryWords.removeAll(STOP_WORDS); if (queryWords.size() == 0) { queryWords = new HashSet<String>(stemmedQuery); } // Set<String> queryWords = new HashSet<String>(q.processedQueryWords()); // Smallest URL window String decodedUrl = this.decodedUrl(d.url); String[] tokenizedUrl = decodedUrl.split("[^A-Za-z0-9\\s ]"); tokenizedUrl = stem(tokenizedUrl); int smallestUrlWindow = containsAllQueryWords(tokenizedUrl, queryWords) ? smallestWindow(sentenceToTermPositions(tokenizedUrl, queryWords)) : Integer.MAX_VALUE; // Smallest title window int smallestTitleWindow = Integer.MAX_VALUE; if (d.title != null) { String[] tokenizedTitle = d.title.split("\\s+"); tokenizedTitle = stem(tokenizedTitle); if (containsAllQueryWords(tokenizedTitle, queryWords)) { smallestTitleWindow = smallestWindow(sentenceToTermPositions(tokenizedTitle, queryWords)); } } // Smallest header window int smallestHeaderWindow = Integer.MAX_VALUE; if (d.headers != null){ for (String header : d.headers) { String[] tokenizedHeader = header.split("\\s+"); tokenizedHeader = stem(tokenizedHeader); if (containsAllQueryWords(tokenizedHeader, queryWords)) { int headerWindow = smallestWindow(sentenceToTermPositions(tokenizedHeader, queryWords)); if (headerWindow < smallestHeaderWindow) { smallestHeaderWindow = headerWindow; } } } } // Smallest body window int smallestBodyWindow = Integer.MAX_VALUE; if (d.body_hits != null) { if (d.body_hits.keySet().containsAll(queryWords)) { Map<String, List<Integer>> body_hits = new HashMap<String, List<Integer>>(d.body_hits); body_hits.keySet().retainAll(queryWords); // ehh see if this works smallestBodyWindow = smallestWindow(body_hits); } } // Smallest anchor window int smallestAnchorWindow = Integer.MAX_VALUE; if (d.anchors != null) { for (String anchor : d.anchors.keySet()) { String[] tokenizedAnchor = anchor.split("\\s+"); tokenizedAnchor = stem(tokenizedAnchor); if (containsAllQueryWords(tokenizedAnchor, queryWords)) { int anchorWindow = smallestWindow(sentenceToTermPositions(tokenizedAnchor, queryWords)); if (anchorWindow < smallestAnchorWindow) { smallestAnchorWindow = anchorWindow; } } } } List<Integer> smallestWindows = new ArrayList<Integer>(Arrays.asList(smallestUrlWindow, smallestTitleWindow, smallestHeaderWindow, smallestBodyWindow, smallestAnchorWindow)); return Collections.min(smallestWindows); } private boolean containsAllQueryWords(String[] tokenizedSentence, Set<String> queryWords) { Set<String> sentenceSet = new HashSet<String>(Arrays.asList(tokenizedSentence)); return sentenceSet.containsAll(queryWords); } private Map<String, List<Integer>> sentenceToTermPositions(String[] tokenizedSentence, Set<String> queryWords) { Map<String, List<Integer>> termPositions = new HashMap<String,List<Integer>>(); for (int i = 0; i < tokenizedSentence.length; i++) { String term = tokenizedSentence[i]; if (!queryWords.contains(term)) continue; List<Integer> positions = termPositions.get(term); if (positions != null) { positions.add(i); } else { positions = new ArrayList<Integer>(); positions.add(i); } termPositions.put(term, positions); } return termPositions; } private int smallestWindow(Map<String, List<Integer>> sentenceTermPositions) { if (sentenceTermPositions.size() == 0) return Integer.MAX_VALUE; Map<String, Integer> termIndexes = new HashMap<String,Integer>(); String firstTerm = (String) sentenceTermPositions.keySet().toArray()[0]; Pair<String,Integer> minTermAndPos = new Pair<String,Integer>(firstTerm,Integer.MAX_VALUE); Pair<String,Integer> maxTermAndPos = new Pair<String,Integer>(firstTerm,0); // initialize values: indexes to 0, min amd max pos for (String term : sentenceTermPositions.keySet()) { termIndexes.put(term, 0); } while (true) { updateMinAndMax(sentenceTermPositions, termIndexes, minTermAndPos, maxTermAndPos); int minTermIndex = termIndexes.get(minTermAndPos.getFirst()); // if the min is already at the end of its array, then we break since window cannot be any smaller if (minTermIndex + 1 == sentenceTermPositions.get(minTermAndPos.getFirst()).size()) { break; } // increment the min index termIndexes.put(minTermAndPos.getFirst(), minTermIndex + 1); } int smallestWindow = maxTermAndPos.getSecond() - minTermAndPos.getSecond(); return smallestWindow; } // find the curr min and max private void updateMinAndMax(Map<String, List<Integer>> sentenceTermPositions,Map<String,Integer> termIndexes, Pair<String, Integer> minTermAndPos, Pair<String,Integer> maxTermAndPos) { minTermAndPos.setSecond(Integer.MAX_VALUE); maxTermAndPos.setSecond(0); for (String term : sentenceTermPositions.keySet()) { int termIndex = termIndexes.get(term); int termPos = sentenceTermPositions.get(term).get(termIndex); // find minimum position here if (termPos < minTermAndPos.getSecond()) { minTermAndPos.setFirst(term); minTermAndPos.setSecond(termPos); } // find maximum position here if (termPos > maxTermAndPos.getSecond()) { maxTermAndPos.setFirst(term); maxTermAndPos.setSecond(termPos); } } } /** * get boost score of one document and query pair. * @param d: document * @param q: query */ private double getBoostScore (Document d, Query q) { int smallestWindow = getWindow(d, q); /* * @//TODO : Your code here, calculate the boost score. * */ double x = smallestWindow - q.queryWords().size(); if (x == 0) { return B; } else { return 1 + (B-1) * (1 / Math.exp(x)); } } @Override public double getSimScore(Document d, Query q) { Map<String,Map<String, Double>> tfs = this.getDocTermFreqs(d,q); this.normalizeTFs(tfs, d, q); // Map<String,Double> tfQuery = getQueryFreqs(q); // double boost = getBoostScore(d, q); // double rawScore = this.getNetScore(tfs, q, tfQuery, d); // return boost * rawScore; return getWindow(d, q); } }
true
9281d85863c8565769f4c3a7bc903bc665d0098d
Java
bohdanvan/javastart-group54
/src/com/bvan/javastart/lessons7_8/matrix/MatrixExample.java
UTF-8
1,130
3.578125
4
[]
no_license
package com.bvan.javastart.lessons7_8.matrix; import java.util.Arrays; import static com.bvan.javastart.lessons7_8.matrix.MatrixUtils.printMatrix; /** * @author bvanchuhov */ public class MatrixExample { public static void main(String[] args) { int[][] matrix = { {1, 2, 3}, {4, 5, 6} }; int[][] res = transpose(matrix); printMatrix(res); } private static int[][] transpose(int[][] matrix) { int rows = matrix.length; int cols = matrix[0].length; int[][] res = new int[cols][rows]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { res[j][i] = matrix[i][j]; } } return res; } public static int[][] createTestMatrix() { return new int[][]{ {1, 2, 3}, {4, 5}, {5, 6, 7} }; } private static int elemsNum(int[][] matrix) { int elemsNum = 0; for (int[] row : matrix) { elemsNum += row.length; } return elemsNum; } }
true
d3da505d05be2e60f8970b430b763f6a2fb03248
Java
yooflyhigh/CMM
/ClubManageMent/app/src/main/java/com/example/clubmanagement/Join/Center.java
UTF-8
6,340
1.976563
2
[]
no_license
package com.example.clubmanagement.Join; import android.content.Intent; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.Toast; import com.example.clubmanagement.System.Adapter.ListViewAdapter.Fragment_List_Adapter; import com.example.clubmanagement.ClubPage.Home.ClubPoster; import com.example.clubmanagement.DataBase.DBConnect.ImageURL.CNT_Image_File; import com.example.clubmanagement.System.Fragment.Fragment_Start; import com.example.clubmanagement.System.ListVO.ListVO_Frg; import com.example.clubmanagement.R; import java.util.HashMap; import static java.lang.Thread.sleep; import static com.example.clubmanagement.DataBase.DataPool.Club.Club_Item_list; public class Center extends Fragment implements Fragment_Start.OnBackPressedListener{ private ListView listview; private Fragment_List_Adapter adapter; Button applyUp; CNT_Image_File ImageDown; boolean flag = false; int Pos = Integer.MAX_VALUE ; public static Center newInstance() { Bundle args = new Bundle(); Center fragment = new Center(); fragment.setArguments(args); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.frg_center_list, container, false); Spinner checkSpinner = (Spinner) v.findViewById(R.id.spinner_Check); ArrayAdapter Adapter = ArrayAdapter.createFromResource(this.getActivity(), R.array.major, android.R.layout.simple_spinner_item); Adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); checkSpinner.setAdapter(Adapter); checkSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int SpinnerNumber, long id) { adapter = new Fragment_List_Adapter(); ShowList(SpinnerNumber); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); listview = (ListView) v.findViewById(R.id.List_view); ApplyStart(v); return v; } private void ShowList(int SpinnerNumber) { listview.setAdapter(adapter); HashMap<String, String> Club; for (int i = 0; i < Club_Item_list.size(); i++) { Club = Club_Item_list.get(i); String url = Club.get("INTRO_FILE_NM"); ImageDown = new CNT_Image_File(url); ImageDown.run(); try { sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } ClubPoster.image = new BitmapDrawable(getResources(),ImageDown.bitmap); if (Club.get("CLUB_GB_CD").equals("1002") && SpinnerNumber == 0) { adapter.addVO(ClubPoster.image, Club.get("CLUB_ID"), Club.get("CLUB_NM"), Club.get("INTRO_CONT")); } else if (Club.get("CLUB_GB_CD").equals("1002") && SpinnerNumber == 1) { if (Club.get("CLUB_AT_CD").equals("2001")) { adapter.addVO(ClubPoster.image, Club.get("CLUB_ID"), Club.get("CLUB_NM"), Club.get("INTRO_CONT")); } } else if (Club.get("CLUB_GB_CD").equals("1002") && SpinnerNumber == 2) { if (Club.get("CLUB_AT_CD").equals("2002")) { adapter.addVO(ClubPoster.image, Club.get("CLUB_ID"), Club.get("CLUB_NM"), Club.get("INTRO_CONT")); } } else if (Club.get("CLUB_GB_CD").equals("1002") && SpinnerNumber == 3) { if (Club.get("CLUB_AT_CD").equals("2003")) { adapter.addVO(ClubPoster.image, Club.get("CLUB_ID"), Club.get("CLUB_NM"), Club.get("INTRO_CONT")); } } else if (Club.get("CLUB_GB_CD").equals("1002") && SpinnerNumber == 4) { if (Club.get("CLUB_AT_CD").equals("2004")) { adapter.addVO(ClubPoster.image, Club.get("CLUB_ID"), Club.get("CLUB_NM"), Club.get("INTRO_CONT")); } } else if (Club.get("CLUB_GB_CD").equals("1002") && SpinnerNumber == 5) { if (Club.get("CLUB_AT_CD").equals("2005")) { adapter.addVO(ClubPoster.image, Club.get("CLUB_ID"), Club.get("CLUB_NM"), Club.get("INTRO_CONT")); } } else if (Club.get("CLUB_GB_CD").equals("1002") && SpinnerNumber == 6) { if (Club.get("CLUB_AT_CD").equals("2006")) { adapter.addVO(ClubPoster.image, Club.get("CLUB_ID"), Club.get("CLUB_NM"), Club.get("INTRO_CONT")); } } } } private void ApplyStart(final View v) { listview.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Pos = position; } }); applyUp = (Button) v.findViewById(R.id.button); applyUp.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View view) { if(Pos < listview.getCount()){ ListVO_Frg SelectedClub = (ListVO_Frg)(listview.getAdapter().getItem(Pos)); ClubPoster.image = (BitmapDrawable) SelectedClub.getImg(); Intent intent = new Intent(getActivity(), JoinPopUp.class); intent.putExtra("CLUB_ID",SelectedClub.getCLUB_ID()); startActivity(intent); } else{ Toast.makeText(getContext(),"동아리를 선택하세요.", Toast.LENGTH_SHORT).show(); } } }); } @Override public void onBackPressed() { //fragment_start로 가서 이벤트 뒤로가기 이벤트 처리 } }
true
a8ff384eadd681ba4e730915753e26b79251c09f
Java
myrfa/initiatives_backend_auth
/src/main/java/com/soprasteria/initiatives/auth/web/AuthorityResource.java
UTF-8
1,621
2.1875
2
[ "MIT" ]
permissive
package com.soprasteria.initiatives.auth.web; import com.soprasteria.initiatives.auth.domain.Authority; import com.soprasteria.initiatives.auth.service.AuthorityService; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import javax.validation.Valid; /** * Resource publishing {@link Authority} entity * * @author jntakpe * @author cegiraud */ @RestController @RequestMapping(ApiConstants.AUTHORITIES) public class AuthorityResource { private final AuthorityService authorityService; public AuthorityResource(AuthorityService authorityService) { this.authorityService = authorityService; } @GetMapping public Flux<Authority> findAll() { return authorityService.findAll(); } @GetMapping("/{authorityId}") public Mono<Authority> findById(@PathVariable String authorityId) { return authorityService.findById(authorityId); } @ResponseStatus(HttpStatus.CREATED) @PostMapping public Mono<Authority> create(@RequestBody @Valid Authority authority) { return authorityService.create(authority); } @PutMapping("/{authorityId}") public Mono<Authority> edit(@PathVariable String authorityId, @RequestBody @Valid Authority authority) { return authorityService.edit(authorityId, authority); } @ResponseStatus(HttpStatus.NO_CONTENT) @DeleteMapping("/{authorityId}") public Mono<Void> remove(@PathVariable String authorityId) { return authorityService.delete(authorityId); } }
true
0a1c7cea96b4d558ce619444c591a52b0fdb1722
Java
alenzhao/bunny-logs
/src/main/java/com/google/bunnylog/analyzer/gcp/ClientStdoutParser.java
UTF-8
4,849
2.0625
2
[ "Apache-2.0" ]
permissive
package com.google.bunnylog.analyzer.gcp; import com.google.bunnylog.analyzer.core.ConcreteOperationInterval; import com.google.bunnylog.analyzer.core.OperationInterval; import java.io.BufferedReader; import java.io.FileReader; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.TimeZone; /** * Reads the stdout of a Dataflow application (client-side). */ public class ClientStdoutParser { static SimpleDateFormat timestampFormat = new SimpleDateFormat("yyyy-MM-dd'T'H:m:s.S'Z:'"); public static List<OperationInterval> parse(String fname) throws Exception { BufferedReader r = new BufferedReader(new FileReader(fname)); ArrayList<OperationInterval> ret = new ArrayList<OperationInterval>(); String line; ConcreteOperationInterval job = null; String jobID = null; String opInProgress = null; Date opStartTime = null; while ((line=r.readLine())!=null) { try { // We're looking for the following sequence: // Submitted job: 2015-07-14_12_26_52-15432457801169333516 // 2015-07-14T19:26:59.295Z: (52599cc9274ddb4): Basic: Starting worker pool synchronously... // 2015-07-14T19:31:46.412Z: (52599cc9274dde3): Basic: Worker pool is running. // 2015-07-14T19:32:35.720Z: S04: (5f60ac31b9f746ee): Basic: Executing operation Globally/Combine.Globally/AsIterable/CreatePCollectionView // 2015-07-14T19:31:47.829Z: (623062ee9246d205): Basic: Executing operation Globally/Combine.Globally/AnonymousParDo/Reshard/Close // 2015-07-14T19:32:38.658Z: (bc4d81d0e967ade9): Basic: Starting worker pool teardown. // 2015-07-14T19:33:42.023Z: (bc4d81d0e967a41e): Basic: Worker pool stopped. Date when; String[] p = line.split(" "); if (p.length<2) continue; if (line.startsWith("Submitted job: ") && p.length==3) { jobID = p[2]; } try { timestampFormat.setTimeZone(TimeZone.getTimeZone("UTC")); when = timestampFormat.parse(p[0]); } catch (Exception x) { // not the format we're looking for continue; } if (line.contains("Starting worker pool synchronously")) { job = new ConcreteOperationInterval(); job.begin = when; job.attributes.put("log", "stdout"); if (null!=jobID) { job.attributes.put("jobID", jobID); job.label = "Client for job "+jobID; job.group = job.label; } else { job.label = "Client of Dataflow job"; } } else if (line.contains("Worker pool is running")) { ConcreteOperationInterval startup = new ConcreteOperationInterval(); startup.begin = job.begin; startup.end = when; startup.label = "setup"; addDuration(startup); job.sub.add(startup); opStartTime = when; } else if (line.contains("Executing operation")) { if (opInProgress!=null) { ConcreteOperationInterval op = new ConcreteOperationInterval(); op.begin = opStartTime; op.end = when; op.label = opInProgress; addDuration(op); job.sub.add(op); opInProgress = null; } opInProgress = line.substring(line.indexOf("Executing operation")); opStartTime = when; } else if (line.contains("Starting worker pool teardown") || line.contains("Stopping worker pool synchronously...")) { if ("TEARDOWN".equals(opInProgress)) continue; if (opInProgress!=null) { ConcreteOperationInterval op = new ConcreteOperationInterval(); op.begin = opStartTime; op.end = when; op.label = opInProgress; addDuration(op); job.sub.add(op); opInProgress = null; } opInProgress = "TEARDOWN"; opStartTime = when; } else if (line.contains("Worker pool stopped")) { if (opInProgress=="TEARDOWN") { ConcreteOperationInterval op = new ConcreteOperationInterval(); op.begin = opStartTime; op.end = when; op.label = "teardown"; addDuration(op); job.sub.add(op); opInProgress = null; } job.end = when; } } catch (Exception x) { System.out.println("Parsing error: "+x.getMessage()+", continuing. The line was: "+line); } } if (null!=job && null!=job.begin && null!=job.end) { ret.add(job); } return ret; } private static void addDuration(ConcreteOperationInterval op) { long diff = (op.getEnd().getTime() - op.getStart().getTime())/1000; op.label += "\n" + diff+"s"; } }
true
f9341703292f17354fec13e78eaf16f9a2364594
Java
razfriman/SnowMS
/net.sf.odinms.exttools/src/net/sf/odinms/exttools/wzextract/HTMLWzExtract.java
UTF-8
8,978
1.953125
2
[]
no_license
/* This file is part of the OdinMS Maple Story Server Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc> Matthias Butz <matze@odinms.de> Jan Christian Meyer <vimes@odinms.de> 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. You may not use, modify or distribute this program under any other version of the GNU Affero General Public License. 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/>. */ package net.sf.odinms.exttools.wzextract; import java.awt.Point; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.List; import javax.imageio.ImageIO; import net.sf.odinms.provider.MapleCanvas; import net.sf.odinms.provider.MapleData; import net.sf.odinms.provider.MapleDataDirectoryEntry; import net.sf.odinms.provider.MapleDataEntry; import net.sf.odinms.provider.MapleDataProvider; import net.sf.odinms.provider.MapleDataProviderFactory; import net.sf.odinms.provider.MapleDataTool; import net.sf.odinms.provider.wz.ImgMapleSound; import net.sf.odinms.tools.HexTool; import net.sf.odinms.tools.StringUtil; import ch.ubique.inieditor.IniEditor; public class HTMLWzExtract { private boolean dumpPNG; private boolean dumpMP3; private File pngBaseDir = null; private File mp3BaseDir = null; private byte[] keyIv; private boolean hadError = false; private boolean overwriteOld; private int version; public HTMLWzExtract(int version, boolean dumpPNG, boolean dumpMP3, boolean overwriteOld, byte[] keyIv) throws Exception { this.version = version; this.dumpPNG = dumpPNG; this.dumpMP3 = dumpMP3; this.overwriteOld = overwriteOld; this.keyIv = keyIv; } public void extractWZ(File wzFile, File outputBaseDirectory) { if (!outputBaseDirectory.exists()) { outputBaseDirectory.mkdir(); } else if (!overwriteOld) { System.out.println("skipping " + wzFile.getName() + " (directory exists)"); return; } MapleDataProvider dataProv; dataProv = MapleDataProviderFactory.getDataProvider(wzFile, dumpPNG, dumpMP3, keyIv); MapleDataDirectoryEntry root = dataProv.getRoot(); dumpDirectory(dataProv, "", root, outputBaseDirectory, 0); } private void dumpDirectory(MapleDataProvider dataProv, String path, MapleDataDirectoryEntry root, File outputBaseDirectory, int dirLevel) { File file = new File(outputBaseDirectory, root.getName()); file.mkdir(); System.out.println("[Dumping] " + root.getName()); int i = 0; int imgFiles = root.getFiles().size(); for (MapleDataEntry entry : root.getFiles()) { i++; File imgDirFile = new File(file, entry.getName()); imgDirFile.mkdir(); File htmlOutFile = new File(imgDirFile, "index.html"); try { String filePath = path; if (filePath.length() > 0) { filePath += "/"; } filePath += entry.getName(); htmlOutFile.createNewFile(); pngBaseDir = imgDirFile; mp3BaseDir = imgDirFile; System.out.println("[" + i + ":" + imgFiles + "] " + entry.getName()); dumpImg(dataProv.getData(filePath), new FileOutputStream(htmlOutFile), dirLevel); } catch (FileNotFoundException e) { hadError = true; e.printStackTrace(); } catch (IOException e) { hadError = true; e.printStackTrace(); } } for (MapleDataDirectoryEntry child : root.getSubdirectories()) { dumpDirectory(dataProv, path + (path.equals("") ? "" : "/") + child.getName(), child, file, dirLevel + 1); } } public void dumpImg(MapleData wzFile, OutputStream os, int dirLevel) { PrintWriter pw = new PrintWriter(os); pw.println("<table>"); dumpData(wzFile, pw, "", dirLevel); pw.println("</table>"); pw.flush(); } private void dumpData(MapleData data, PrintWriter pw, String pathInImg, int dirLevel) { String[] paths = MapleDataTool.getFullDataPath(data).split("/"); String path = StringUtil.joinStringFrom(paths, 2 + dirLevel, "."); switch (data.getType()) { case PROPERTY: case EXTENDED: case CONVEX: dumpDataList(data.getChildren(), pw, pathInImg + data.getName() + "/", dirLevel); break; case CANVAS: pw.println("<tr><td>" + path + ".image<td><img src=" + path + ".png>"); MapleCanvas canvas = (MapleCanvas) data.getData(); if (dumpPNG) { File pngFile = new File(pngBaseDir, path + ".png"); try { ImageIO.write(canvas.getImage(), "png", pngFile); } catch (FileNotFoundException e) { hadError = true; e.printStackTrace(); } catch (IOException e) { hadError = true; e.printStackTrace(); } } dumpDataList(data.getChildren(), pw, pathInImg + data.getName() + "/", dirLevel); break; case SOUND: pw.println("<tr><td>" + path + "<td>" + getHtmlLink(data.getName() + ".mp3", data.getName())); ImgMapleSound mapleSound = (ImgMapleSound) data.getData(); if (dumpMP3) { File mp3File = new File(mp3BaseDir, data.getName() + ".mp3"); FileOutputStream outputStream = null; try { outputStream = new FileOutputStream(mp3File); outputStream.write(mapleSound.getSoundData()); } catch (FileNotFoundException e) { hadError = true; e.printStackTrace(); } catch (IOException e) { hadError = true; e.printStackTrace(); } finally { try { if (outputStream != null) { outputStream.close(); } } catch (IOException e) { hadError = true; e.printStackTrace(); } } } break; case UOL: case DOUBLE: case FLOAT: case INT: case SHORT: case STRING: pw.println("<tr><td>" + path + "<td>" + data.getData()); break; case VECTOR: Point pos = (Point) data.getData(); pw.println("<tr><td>" + path + ".x" + "<td>" + pos.x); pw.println("<tr><td>" + path + ".y" + "<td>" + pos.y); break; case IMG_0x00: pw.println("<tr><td>" + path + "<td>" + "-NONE-"); break; default: throw new RuntimeException("Unexpected img data type " + data.getType() + " path: " + pathInImg); } } private void dumpDataList(List<MapleData> datalist, PrintWriter pw, String pathInImg, int dirLevel) { for (MapleData data : datalist) { dumpData(data, pw, pathInImg, dirLevel); } } public String getHtmlLink(String title, String dest) { return "<a href=\"" + title + "\">" + dest + "</a>"; } public boolean isHadError() { return hadError; } public static void main(String args[]) { boolean dumpPng = false; boolean dumpMp3 = false; boolean overwriteOld = false; boolean hadError = false; String outputDir = null; byte[] keyIv; int version = -1; IniEditor ini = new IniEditor(); long startTime = System.currentTimeMillis(); try { ini.load("settings.ini"); } catch (Exception e) { System.out.println("Unable to find settings.ini"); return; } version = Integer.parseInt(ini.get("GENERAL", "VERSION")); dumpPng = Integer.parseInt(ini.get("GENERAL", "DUMP_PNG")) > 0; dumpMp3 = Integer.parseInt(ini.get("GENERAL", "DUMP_MP3")) > 0; String keyIvStr = ini.get("GENERAL", "IV"); if (keyIvStr != null) { keyIv = HexTool.getByteArrayFromHexString(keyIvStr); } else { keyIv = null; } overwriteOld = Integer.parseInt(ini.get("GENERAL", "OVERWRITE_OLD")) > 0; outputDir = ini.get("HTML", "OUTPUT_PATH"); String[] fileNames = ini.get("GENERAL", "FILES").split(" "); for (String fileName : fileNames) { File file = new File(fileName); try { HTMLWzExtract wzExtract = new HTMLWzExtract(version, dumpPng, dumpMp3, overwriteOld, keyIv); if (fileName.endsWith("*.wz")) { for (File child : file.getParentFile().listFiles()) { if (child.getName().endsWith(".wz")) { wzExtract.extractWZ(child, new File(outputDir)); hadError |= wzExtract.isHadError(); } } } else { wzExtract.extractWZ(file, new File(outputDir)); hadError |= wzExtract.isHadError(); } } catch (Exception e) { hadError = true; System.out.println("Exception occured while dumping " + file + " continuing with next file"); System.out.flush(); e.printStackTrace(); } } long endTime = System.currentTimeMillis(); double elapsedSeconds = (endTime - startTime) / 1000.0; int elapsedSecs = (((int) elapsedSeconds) % 60); int elapsedMinutes = (int) (elapsedSeconds / 60.0); System.out.println("Finished" + (hadError ? " with errors" : "") + " in " + elapsedMinutes + " minutes " + elapsedSecs + " seconds"); } }
true
ded50be4f84122da3c8741f7a189bfd5abe7e7d0
Java
UNDERHMA/LeetCode-with-Unit-Tests
/LeetCode/src/main/java/leetcode/LeetCode/DecodeWays.java
UTF-8
1,505
3.359375
3
[ "MIT" ]
permissive
package leetcode.LeetCode; import java.util.HashMap; import java.util.Map; public class DecodeWays { public int numDecodings(String s) { // checking for invalid inputs (0 in wrong place) if(s.length() == 0) return 0; if(s.charAt(0) == '0') return 0; if(s.length() == 1) return 1; Map<String,Integer> memo = new HashMap<>(); return calculateWays(s,memo); } public int calculateWays(String s, Map<String,Integer> memo) { if(memo.containsKey(s)) return memo.get(s); if(s.length() == 0) return 1; // base case int firstChar = Character.getNumericValue(s.charAt(0)); if(s.length() == 1) { if(firstChar != 0) return 1; // base case else return 0; } int secondChar = Character.getNumericValue(s.charAt(1)); int memoResult = 0; if(secondChar == 0 && firstChar > 2) return 0; // no possible solutions else if(firstChar == 0) return 0; // no possible solutions else if(secondChar == 0) memoResult += calculateWays(s.substring(2),memo); else if(firstChar > 2) memoResult += calculateWays(s.substring(1),memo); else if(s.length() > 2 && s.charAt(2) == '0') memoResult += calculateWays(s.substring(1),memo); else if(firstChar > 2) memoResult += calculateWays(s.substring(1),memo); else if(firstChar == 2 && secondChar > 6) memoResult += calculateWays(s.substring(1),memo); else memoResult += calculateWays(s.substring(1),memo) + calculateWays(s.substring(2),memo); memo.put(s,memoResult); return memoResult; } }
true
f4ccc7b583d42e334a6efcee1208efc6a7030d82
Java
plastya-flomaster/pyatnashki
/src/com/company/pyatnashki/Main.java
UTF-8
1,651
3.171875
3
[]
no_license
package com.company.pyatnashki; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Collection; import com.company.initialRules.State; import com.company.initialRules.Algorithm; public class Main { private static boolean isShowStatistic = true; //подробный вывод private static int sideSize = 3; public static void main(String[] args) { // получим общее кол-во клеток int size = sideSize * sideSize; // зададим стартовое и конечное состояния пятнашки byte[] startField = new byte[] {2, 1, 6, 4, 0, 8, 7, 5, 3}; byte[] finalField = new byte[] {1, 2, 3, 8, 0, 4, 7, 6, 5}; FifteenRules rules = new FifteenRules(sideSize, finalField); FifteenState startState = new FifteenState(null, sideSize); startState.setField(startField); Algorithm<FifteenState, FifteenRules> algorithm = new Algorithm<>(rules); long time = System.currentTimeMillis(); Collection<State> res = algorithm.search(startState); time = System.currentTimeMillis() - time; if (res == null) { System.out.println("Ошибка или решение не было найдено"); return; } else { for (State s : res) { System.out.println(s.toString()); } } if (isShowStatistic) { System.out.println("Время: " + time + "мс"); System.out.println("Кратчайший путь: " + (res.size())); System.out.println("Всего просмотрено матриц: " + algorithm.getClosedStatesCount()); } } }
true
ea310b300c6f956a24761ca784a939d869ff5ae4
Java
Eric-Sun/jax_old
/src/main/java/com/j13/bar/server/facade/resp/UserLoginResp.java
UTF-8
533
2.046875
2
[]
no_license
package com.j13.bar.server.facade.resp; import com.j13.bar.server.poppy.anno.Parameter; public class UserLoginResp { @Parameter(desc="用户id") private long userId; @Parameter(desc="用户名") private String userName; public long getUserId() { return userId; } public void setUserId(long userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } }
true
3a4182265b7b142b6ff1467583966f8eb2eb54f3
Java
chengnshan/netty
/src/main/java/cxp/xuexi/rocketMQ/retry_timeout/Producer.java
UTF-8
1,151
2.3125
2
[]
no_license
package cxp.xuexi.rocketMQ.retry_timeout; import com.alibaba.rocketmq.client.exception.MQClientException; import com.alibaba.rocketmq.client.producer.DefaultMQProducer; import com.alibaba.rocketmq.client.producer.SendResult; import com.alibaba.rocketmq.common.message.Message; /** * Created by ASUS on 2018/4/5. */ public class Producer { public static void main(String[] args) throws MQClientException, InterruptedException { DefaultMQProducer producer = new DefaultMQProducer("timeout_producer"); producer.setNamesrvAddr("192.168.0.133:9876;192.168.0.134:9876"); producer.start(); for (int i = 1; i <= 1; i++) { try { Message msg = new Message("TopicRetryTimeout", // topic "Tag1", // tag ("信息内容" + i).getBytes() // body ); SendResult sendResult = producer.send(msg, 1000); System.out.println(sendResult); } catch (Exception e) { e.printStackTrace(); Thread.sleep(1000); } } producer.shutdown(); } }
true
7ae660e44741df0f0fb996db9003b4d7a7259fa9
Java
EthanAI/ParkingGarageApp
/src/com/ethanai/parkinggarageapp/UserSettings.java
UTF-8
15,521
1.867188
2
[]
no_license
package com.ethanai.parkinggarageapp; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import com.ethanai.parkinggarageapp.dataStructures.Floor; import android.location.Location; import android.os.Environment; import android.util.Log; public class UserSettings implements Serializable { /** * */ private static final long serialVersionUID = -8023067763707780880L; public boolean isDebug = false; //for me to autoswitch on dev settings public ArrayList<GarageLocation> enabledGarageLocations = new ArrayList<GarageLocation>(); public ArrayList<GarageLocation> allGarageLocations = new ArrayList<GarageLocation>(); public ArrayList<GarageLocation> userAddedGarageLocations = new ArrayList<GarageLocation>(); public ArrayList<GarageLocation> presetGarageLocations = new ArrayList<GarageLocation>(); public String carBTName; public String carBTMac; public boolean isFirstRun; public boolean isBluetoothUser; public boolean isGarageSelectionComplete; public ParkingRecord parkingRecordRecent; public int recentDataHistoryCount = 2000; //safe default if loading has trouble public int graphHistoryCount; public int FLOOR_COLUMN_INDEX; public String STORAGE_DIRECTORY_NAME = "AppGarageParking"; public String DATABASE_DIRECTORY_NAME = "AppGarageParking/ResourceData"; public String SETTINGS_FILE_NAME; public String PRESETS_FILE_NAME; public String CUSTOM_GARAGE_FILE_NAME; public File userSettingsFile; public File userCustomGaragesFile; //public File presetGaragesFile; //public static final String GARAGE_LOG_NAME = "garageRecords.ser"; //public static File garageLocationFile = new File(Environment.getExternalStorageDirectory().toString() // + "/" + STORAGE_DIRECTORY_NAME + "/" + GARAGE_LOG_NAME); UserSettings() { SETTINGS_FILE_NAME = "_parkingAppSettings.ser"; PRESETS_FILE_NAME = "_presetGarages.ser"; CUSTOM_GARAGE_FILE_NAME = "_customGarages.ser"; userSettingsFile = new File(Environment.getExternalStorageDirectory().toString() + "/" + STORAGE_DIRECTORY_NAME + "/" + SETTINGS_FILE_NAME); userCustomGaragesFile = new File(Environment.getExternalStorageDirectory().toString() + "/" + STORAGE_DIRECTORY_NAME + "/" + CUSTOM_GARAGE_FILE_NAME); //presetGaragesFile = new File(Environment.getExternalStorageDirectory().toString() // + "/" + DATABASE_DIRECTORY_NAME + "/" + PRESETS_FILE_NAME); //create Directory createDirectory(STORAGE_DIRECTORY_NAME); //createDirectory(DATABASE_DIRECTORY_NAME); //load settings from storage loadSettings(); //for testing //resetSettings(); } //temporary hard code, need to be able to add /* public void setBluetoothRecord() { carBTName = "XPLOD"; carBTMac = "54:42:49:B0:7A:C6"; } */ //for testing public void resetGeneralSettings() { //copy values into this() allGarageLocations = new ArrayList<GarageLocation>(); presetGarageLocations = new ArrayList<GarageLocation>(); enabledGarageLocations = new ArrayList<GarageLocation>(); parkingRecordRecent = null; carBTName = null; carBTMac = null; isFirstRun = true; isBluetoothUser = false; isGarageSelectionComplete = false; recentDataHistoryCount = 2000; graphHistoryCount = 2000; FLOOR_COLUMN_INDEX = 3; Log.i("UserSettings", "Non-garage settings reset to install defaults"); } public void restoreDebugSettings() { //RecentSensorData recentData = MainActivity.recentData; allGarageLocations = new ArrayList<GarageLocation>(); recentDataHistoryCount = 2000; graphHistoryCount = 2000; FLOOR_COLUMN_INDEX = 3; carBTName = null; carBTMac = null; isFirstRun = true; isBluetoothUser = false; isGarageSelectionComplete = false; loadPresetGarages(); if(null != presetGarageLocations) { for(GarageLocation garageLocation : presetGarageLocations) enabledGarageLocations.add(garageLocation); } else { } saveSettings(); //savePresetGarages(); } //saves everything except presets. That should never be altered at runtime public void saveSettings() { try { //save general settings ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(userSettingsFile)); //overwrite old file os.writeObject(this); os.close(); //save user's custom garages os = new ObjectOutputStream(new FileOutputStream(userCustomGaragesFile)); //overwrite old file os.writeObject(userAddedGarageLocations); os.close(); } catch (Exception e) { Log.e("UserSettings", e.toString()); } } /* private void savePresetGarages() { try { ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(presetGaragesFile)); //overwrite old file os.writeObject(enabledGarageLocations); os.close(); } catch (Exception e) { Log.e("UserSettings", e.toString()); } } */ public void loadSettings() { loadGeneralSettings(); loadPresetGarages(); loadCustomGarages(); } //Load the general settings public void loadGeneralSettings() { UserSettings loadedSettings = null; if(userSettingsFile != null && userSettingsFile.exists()) { try { ObjectInputStream is = new ObjectInputStream(new FileInputStream(userSettingsFile)); loadedSettings = (UserSettings) is.readObject(); is.close(); } catch (Exception e) { Log.e("UserSettings", "Error: " + e.getMessage()); } if(null != loadedSettings) { //copy values into this() if(null != loadedSettings.enabledGarageLocations) enabledGarageLocations = loadedSettings.enabledGarageLocations; if(null != loadedSettings.parkingRecordRecent) parkingRecordRecent = loadedSettings.parkingRecordRecent; carBTName = loadedSettings.carBTName; carBTMac = loadedSettings.carBTMac; isFirstRun = loadedSettings.isFirstRun; isBluetoothUser = loadedSettings.isBluetoothUser; isGarageSelectionComplete = loadedSettings.isGarageSelectionComplete; if(loadedSettings.recentDataHistoryCount > 100) recentDataHistoryCount = loadedSettings.recentDataHistoryCount; else { recentDataHistoryCount = 2000; Log.i("UserSettings", "History Count too low. Forcefully corrected. " + loadedSettings.recentDataHistoryCount); } graphHistoryCount = loadedSettings.graphHistoryCount; FLOOR_COLUMN_INDEX = loadedSettings.FLOOR_COLUMN_INDEX; //STORAGE_DIRECTORY_NAME = loadedSettings.STORAGE_DIRECTORY_NAME; //SETTINGS_FILE_NAME = loadedSettings.SETTINGS_FILE_NAME; //userSettingsFile = loadedSettings.userSettingsFile; Log.i("UserSettings", "Basic settings loaded"); } else { Log.e("UserSettings", "Basic settings failed to load"); } } else { resetGeneralSettings(); //deletes EVERYTHING be sure to do this before trying to load custom garages or database garages } } @SuppressWarnings("unchecked") public void loadCustomGarages() { //load user's custom garages, add to the array of all garages if(userCustomGaragesFile != null && userCustomGaragesFile.exists()) { try { ObjectInputStream is = new ObjectInputStream(new FileInputStream(userCustomGaragesFile)); userAddedGarageLocations = (ArrayList<GarageLocation>) is.readObject(); is.close(); if(null != userAddedGarageLocations) { for(GarageLocation garageLocation : userAddedGarageLocations) allGarageLocations.add(garageLocation); Log.i("UserSettings", "Custom garages loaded " + userAddedGarageLocations.size() + " " + allGarageLocations.size()); } else { Log.e("UserSettings", "Custom garages failed to load"); } } catch (Exception e) { Log.e("UserSettings", e.getMessage()); } } } public void loadPresetGarages() { presetGarageLocations = PresetGarages.getPresetGarages(); if(null != presetGarageLocations) { for(GarageLocation garageLocation : presetGarageLocations) { allGarageLocations.add(garageLocation); if(isFirstRun) enabledGarageLocations.add(garageLocation); } Log.i("UserSettings", "preset garages loaded " + presetGarageLocations.size() + " " + allGarageLocations.size()); } else { Log.e("UserSettings", "Preset garages failed to load"); } /*//garages no longer stored in files //load official database of garages, add to the array of all garages if(presetGaragesFile != null && presetGaragesFile.exists()) { try { ObjectInputStream is = new ObjectInputStream(new FileInputStream(presetGaragesFile)); presetGarageLocations = (ArrayList<GarageLocation>) is.readObject(); is.close(); if(null != presetGarageLocations) { for(GarageLocation garageLocation : presetGarageLocations) allGarageLocations.add(garageLocation); Log.i("UserSettings", "preset garages loaded " + presetGarageLocations.size() + " " + allGarageLocations.size()); } else { Log.e("UserSettings", "Preset garages failed to load"); } } catch (Exception e) { Log.e("UserSettings", e.getMessage()); } } */ } /* * Assert: all garage locations are stored to disk and loaded to allGarageLocations identically * We just add the new one to our array and overwrite the local file */ // good info on serilizable limitations http://www.javacodegeeks.com/2013/03/serialization-in-java.html /*//garage locations more complicated now (preset and user defined separated) use individual methods for adding //to the proper one(s). public void addGarageLocation(String name, PhoneLocation phoneLocation, ArrayList<Floor> borders) { allGarageLocations.add(new GarageLocation(name, phoneLocation, borders)); saveSettings(); } public void removeGarageLocation(GarageLocation garageLocation) { allGarageLocations.remove(garageLocation); saveSettings(); } */ //return sucess or fail public boolean addFloorRecord(String garageName, String floorName, float turnCount) { GarageLocation editingGarage = getGarageLocation(garageName); String tokens[] = floorName.split("[a-zA-Z]"); if(null != editingGarage && floorName.matches("[0-9][a-zA-Z]*")) { float floorNumber = Integer.parseInt(tokens[0]); if(floorName.matches("[0-9][a-zA-Z]+")) { //if anything entered other than numbers, assume partial floor change floorNumber += 0.5; } Floor newBorder = new Floor(turnCount, floorNumber, floorName); editingGarage.floors.add(newBorder); //might not be in order, we should do better deryption method saveSettings(); return true; } else { return false; } } public GarageLocation getGarageLocation(String searchName) { GarageLocation returnValue = null; for(GarageLocation garageLocation : allGarageLocations) { if(garageLocation.name.equalsIgnoreCase(searchName)) { returnValue = garageLocation; } } /* //catch case just for testing if(returnValue == null) { returnValue = allGarageLocations.get(0); } */ return returnValue; } public ArrayList<String> toArrayList() { ArrayList<String> settingData = new ArrayList<String>(); for(GarageLocation garageLocation : allGarageLocations) { String text = ""; text += garageLocation.name + " " + garageLocation.phoneLocation.getLatitude() + " " + garageLocation.phoneLocation.getLongitude(); settingData.add(text); } return settingData; } /* Checks if external storage is available for read and write */ public boolean isExternalStorageWritable() { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { return true; } return false; } /* Checks if external storage is available to at least read * http://developer.android.com/guide/topics/data/data-storage.html#filesExternal * */ public boolean isExternalStorageReadable() { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { return true; } return false; } public void createDirectory(String directoryName) { String sdCard = Environment.getExternalStorageDirectory().toString(); //get root of external storage File dir = new File(sdCard, directoryName); if (!dir.exists()) { //make directory if it doesnt exist dir.mkdirs(); //make all parent directories even. } } class ParkingRecord implements Serializable { /** * */ private static final long serialVersionUID = -780668416286718326L; public String dateString; public double latitude; public double longitude; public String locationName; public String floorName; public String sourceFileName; ParkingRecord(String newDateString, PhoneLocation newestPhoneLocation, String parkedFloor, File sourceFile) { dateString = newDateString; longitude = newestPhoneLocation.getLongitude(); latitude = newestPhoneLocation.getLatitude(); locationName = newestPhoneLocation.getLocationName(); floorName = parkedFloor; sourceFileName = sourceFile.toString(); } public String toString() { return dateString + ", " + latitude + " " + longitude + ", " + locationName + ", " + floorName + "," + sourceFileName + "\n"; } } } class GarageLocation implements Serializable { /** * */ private static final long serialVersionUID = 6855129699792130834L; public String name = ""; public PhoneLocation phoneLocation; public ArrayList<Floor> floors; //structure to hold all the borders between floors for this particular garages //add location address etc? GarageLocation(String newName, PhoneLocation newLocation, ArrayList<Floor> newBorders) { name = newName; phoneLocation = newLocation; if(null == newBorders) floors = new ArrayList<Floor>(); else floors = newBorders; } GarageLocation(String newName, Location location, ArrayList<Floor> newBorders) { this(newName, new PhoneLocation(location, null), newBorders); } /* public void delete() { removeGarageLocation(this); } */ public Floor getMatchingFloor(float correctedTurnCount) { Floor parkedFloor = null; //iterate through the floor borders until we find our first, minimum floor hit. //maybe we could do some cool hashmap thing here? if(null != floors && floors.size() > 0) { float difference = Math.abs(floors.get(0).turns - correctedTurnCount); parkedFloor = floors.get(0); for(Floor floor : floors) { if(Math.abs(floor.turns - correctedTurnCount) < difference) { difference = Math.abs(floor.turns - correctedTurnCount); parkedFloor = floor; } } return parkedFloor; } else { return null; } } public String toString() { return name + " " + phoneLocation.getLatitude() + " " + phoneLocation.getLongitude(); } }
true
ea667d1c765d055df1e4f9b6b12578d200cf328e
Java
ningjianguo/drivetest
/drivetest Maven Webapp/src/main/java/com/hnrw/action/AindexAction.java
UTF-8
1,471
1.890625
2
[]
no_license
package com.hnrw.action; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.ServletActionContext; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import com.hnrw.entity.ExamQuestion1; import com.hnrw.service.IQuestion1Service; @Controller @Scope("prototype") public class AindexAction extends BaseAction<ExamQuestion1>{ private static final long serialVersionUID = 2741894337161616239L; private String page; private String rows; @Resource private IQuestion1Service question1ServiceImpl; public String index(){ HttpServletRequest request = ServletActionContext.getRequest(); request.setAttribute("loginerr", 1); return SUCCESS; } public String toManageUser(){ return SUCCESS; } public String toManageQuestion1(){ return SUCCESS; } public String toManageQuestion4(){ return SUCCESS; } /*public String loadAllQuestion1(){ String type = request.getParameter("type"); if("1".equals(type)){ printJsonStringToBrowser(question1ServiceImpl.loadAllData(Integer.parseInt(page), Integer.parseInt(rows))); }else{ } return null; } public String getPage() { return page; } public void setPage(String page) { this.page = page; } public String getRows() { return rows; } public void setRows(String rows) { this.rows = rows; }*/ }
true
ebfd85b116eaebe0be920708b7d192d92ef7b22b
Java
chldbtjd2272/blog-code
/thread-pool-test/src/main/java/com/blogcode/threadpooltest/ThreadPoolJobExecutor.java
UTF-8
2,216
2.671875
3
[]
no_license
package com.blogcode.threadpooltest; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.concurrent.Semaphore; import java.util.function.Function; public class ThreadPoolJobExecutor { private final ThreadPoolTaskExecutor executor; private final Semaphore semaphore; private boolean enableUse = true; public ThreadPoolJobExecutor(String processorName, int corePoolSize, int maxPoolSize, int queueCapacity) { this.executor = new ThreadPoolTaskExecutor(); this.semaphore = new Semaphore(maxPoolSize); this.executor.setThreadNamePrefix(processorName + "-"); this.executor.setCorePoolSize(corePoolSize); this.executor.setMaxPoolSize(maxPoolSize); this.executor.setQueueCapacity(queueCapacity); this.executor.setWaitForTasksToCompleteOnShutdown(true); this.executor.initialize(); } public void executeJob(Function<Integer, List<Runnable>> receiveJob) throws InterruptedException { validateThreadPool(); for (Runnable runnable : getJob(receiveJob)) { executeJob(runnable); } } private void executeJob(Runnable job) throws InterruptedException { semaphore.acquire(); executor.execute(() -> { job.run(); semaphore.release(); }); } private List<Runnable> getJob(Function<Integer, List<Runnable>> receiveJob) throws InterruptedException { semaphore.acquire(); try { final int availableCount = executor.getMaxPoolSize() - executor.getActiveCount(); return receiveJob.apply(availableCount); } catch (RuntimeException e) { return new ArrayList<>(); } finally { semaphore.release(); } } private void validateThreadPool() { if (!enableUse) { throw new IllegalStateException("Already destroy threadPool"); } } public void destroy() { this.semaphore.acquireUninterruptibly(this.executor.getMaxPoolSize()); this.executor.destroy(); this.enableUse = false; } }
true
0ad68315c78b27249cf986adbed7ea0ec6017db9
Java
airomem/airomem
/airomem-direct-banksample/src/main/java/pl/setblack/airomem/direct/banksample/rest/BankResource.java
UTF-8
1,307
2.296875
2
[ "Apache-2.0" ]
permissive
/* * Created by Jarek Ratajski */ package pl.setblack.airomem.direct.banksample.rest; import java.math.BigDecimal; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import pl.setblack.airomem.direct.Persistent; import pl.setblack.airomem.direct.PersistentObject; import pl.setblack.airomem.direct.banksample.domain.Account; import pl.setblack.airomem.direct.banksample.domain.Bank; /** * REST Web Service * * @author jarek ratajski */ @Path("bank") @Persistent public class BankResource { @PersistentObject private Bank bank; public BankResource() { } @GET @Path("/account/{id}") @Produces(MediaType.APPLICATION_JSON) public Account getAccount(@PathParam("id") final String id) { return this.bank.getAccount(id); } @POST @Path("/account") @Produces(MediaType.APPLICATION_JSON) public Account putAccount() { return this.bank.registerNewAccount(BigDecimal.ZERO); } @PUT @Path("/account/{id}") @Produces(MediaType.APPLICATION_JSON) public Account deposit(@PathParam("id") final String id, String value) { return this.bank.change(id, new BigDecimal(value)); } }
true
afd484ec8c307bb609a150979a2a240d4bd2f799
Java
Thodoras/Algorithms-Java-
/Data Structures/BST.java
UTF-8
2,434
3.5
4
[]
no_license
import java.util.*; public class BST <Key extends Comparable<Key>, Value> { // A basic class for (unbalanced) binary search trees, with recursive methods // that have avg. O(logN) completion time (O(N) worst case). private Node root; private class Node { private Key key; private Value val; private Node left, right; public Node(Key key, Value val) { this.key = key; this.val = val; } } public Value get(Key key) { return get(root, key); } private Value get(Node node, Key key) { if (node == null) return null; int cmp = key.compareTo(node.key); if (cmp < 0) return get(node.left, key); else if (cmp > 0) return get(node.right, key); else return node.val; } public void put(Key key, Value val) { root = put(root, key, val); } private Node put(Node node, Key key, Value val) { if (node == null) return new Node(key, val); int cmp = key.compareTo(node.key); if (cmp < 0) node.left = put(node.left, key, val); else if (cmp > 0) node.right = put(node.right, key, val); else node.val = val; return node; } public void delete(Key key) { root = delete(root, key); } private Node delete(Node node, Key key) { if (node == null) return null; int cmp = key.compareTo(node.key); if (cmp < 0) node.left = delete(node.left, key); else if (cmp > 0) node.right = delete(node.right, key); else { if (node.right == null) return node.left; if (node.left == null) return node.right; Node temp = node; node = min(temp.right); node.right = deleteMin(temp.right); node.left = temp.left; } return node; } public Iterable<Key> keys() { Queue<Key> queue = new LinkedList<Key>(); inorder(root, queue); return queue; } private void inorder(Node node, Queue<Key> queue) { if (node == null) return; inorder(node.left, queue); queue.add(node.key); inorder(node.right, queue); } public Node max() { return max(root); } private Node max(Node node) { if (node == null) return null; if (node.right == null) return node; else return max(node.right); } public Node min() { return min(root); } private Node min(Node node) { if (node == null) return null; if (node.left == null) return node; else return max(node.left); } private void deleteMin() { root = deleteMin(root); } private Node deleteMin(Node node) { if (node.left == null) return node.right; node.left = deleteMin(node.left); return node; } }
true
a306b47ec8fd461f9486dbbe5a4a235d1de2e704
Java
cr88192/bgbtech_engine
/bscc/bgbcc2/frbc2c_ij/fricore/FrPointer.java
UTF-8
1,393
2.3125
2
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
package fricore; /** Represents a virtual pointer object */ public abstract class FrPointer { public abstract int geti(int idx); public abstract long getl(int idx); public abstract float getf(int idx); public abstract double getd(int idx); public abstract int getsb(int idx); public abstract int getub(int idx); public abstract int getss(int idx); public abstract int getus(int idx); public abstract long getsi(int idx); public abstract long getui(int idx); public abstract long getsl(int idx); public abstract long getul(int idx); public abstract void seti(int idx, int val); public abstract void setl(int idx, long val); public abstract void setf(int idx, float val); public abstract void setd(int idx, double val); public abstract void setsb(int idx, int val); public abstract void setub(int idx, int val); public abstract void setss(int idx, int val); public abstract void setus(int idx, int val); public abstract FrPointer getp(int idx); public abstract void setp(int idx, FrPointer val); public abstract FrPointer leai(int idx); public abstract FrPointer leal(int idx); public abstract FrPointer leaf(int idx); public abstract FrPointer lead(int idx); public abstract FrPointer leab(int idx); public abstract FrPointer leas(int idx); public abstract FrPointer leap(int idx); public abstract FrMemSpace getSpace(); public abstract long getAddress(); }
true
f93a6450a5534a204f2d4a9a1447be01cc80be1e
Java
ydchou/KGC_Online
/src/main/java/cn/kgc/wxc/exam/entity/Exam.java
UTF-8
2,179
2.359375
2
[]
no_license
package cn.kgc.wxc.exam.entity; import java.io.Serializable; import java.util.Date; public class Exam implements Serializable { private Integer eid; private Integer epid; private Integer rid; private Date startTime; private Date endTime; private Integer peopleCount; private static final long serialVersionUID = 1L; public Exam(Integer eid, Integer epid, Integer rid, Date startTime, Date endTime, Integer peopleCount) { this.eid = eid; this.epid = epid; this.rid = rid; this.startTime = startTime; this.endTime = endTime; this.peopleCount = peopleCount; } public Exam() { super(); } public Integer getEid() { return eid; } public void setEid(Integer eid) { this.eid = eid; } public Integer getEpid() { return epid; } public void setEpid(Integer epid) { this.epid = epid; } public Integer getRid() { return rid; } public void setRid(Integer rid) { this.rid = rid; } public Date getStartTime() { return startTime; } public void setStartTime(Date startTime) { this.startTime = startTime; } public Date getEndTime() { return endTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } public Integer getPeopleCount() { return peopleCount; } public void setPeopleCount(Integer peopleCount) { this.peopleCount = peopleCount; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", eid=").append(eid); sb.append(", epid=").append(epid); sb.append(", rid=").append(rid); sb.append(", startTime=").append(startTime); sb.append(", endTime=").append(endTime); sb.append(", peopleCount=").append(peopleCount); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
true
0c954e623ad864fbd68b885b6808f20117d4adfe
Java
gtwave1/ruanchuang
/JavaOJSystem/src/main/java/cn/superman/web/exception/UnAuthorizedException.java
UTF-8
365
2.109375
2
[]
no_license
package cn.superman.web.exception; public class UnAuthorizedException extends RuntimeException { private String redirectUrl; /** * */ private static final long serialVersionUID = -5655523165098528556L; public UnAuthorizedException(String redirectUrl) { this.redirectUrl = redirectUrl; } public String getRedirectUrl() { return redirectUrl; } }
true
75d780c9412980e3e9c6fb38cae6025be7579b86
Java
VORONIN-Roman-1/WebQuizEngine
/src/main/java/engine/controller/QuizController.java
UTF-8
6,212
2.078125
2
[]
no_license
package engine.controller; import engine.entity.QuizzesCompleted; import engine.repository.QuizRepository; import engine.repository.QuizzesCompletedRepository; import engine.repository.UsersRepository; import engine.entity.Quiz; import engine.entity.Users; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.data.jpa.repository.Query; import org.springframework.data.web.PageableDefault; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.*; import org.springframework.web.server.ResponseStatusException; import org.springframework.data.domain.Pageable; import javax.validation.Valid; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Set; @Component @RestController public class QuizController { AnswerToChecker success = new AnswerToChecker(true, "Congratulations, you are right!"); AnswerToChecker fail = new AnswerToChecker(false, "Wrong answer! Please, try again."); @Autowired private PasswordEncoder passwordEncoder; @Bean public PasswordEncoder getPasswordEncoder() { return new BCryptPasswordEncoder(8); } @Autowired private QuizRepository quizRepository; @Autowired private QuizzesCompletedRepository quizzesCompletedRepository; @Autowired private UsersRepository usersRepository; @GetMapping(path = "api/quizzes/{id}") public Quiz getQuiz(@PathVariable Integer id) { return quizRepository.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "entity not found")); } @GetMapping(value = "api/quizzes") public Page<Quiz> getAllQuizzes( @RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "10") Integer pageSize, @RequestParam(defaultValue = "id") String sortBy // @PageableDefault(sort = {"id"}, direction = Sort.Direction.DESC) Pageable pageable ) { Pageable pageable = PageRequest.of(page, pageSize, Sort.by(sortBy)); // Pageable firstPageWithTwoElements = PageRequest.of(0, 2); return quizRepository.findAll(pageable); } @PostMapping(path = "api/quizzes", consumes = "application/json") public Quiz postQuiz(@Valid @RequestBody Quiz quiz) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); String username = auth.getName(); System.out.println("User= " + username); quiz.setUsername(username); quizRepository.save(quiz); return quiz; } @PostMapping(path = "api/quizzes/{id}/solve", consumes = "application/json") public AnswerToChecker answerQuiz(@PathVariable Integer id, @RequestBody Checker checker) { if (checker.getAnswer().equals(quizRepository.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "RRR entity not found")).getAnswer())) { String name= SecurityContextHolder.getContext().getAuthentication().getName(); QuizzesCompleted quizzesCompleted= new QuizzesCompleted(id, name, new Date()); quizzesCompletedRepository.save(quizzesCompleted); return success; } else{ return fail;} } @GetMapping(path = "api/quizzes/completed") public Page<QuizzesCompleted> getQuizzesCompleted( @PageableDefault(sort = {"completedAt"}, direction = Sort.Direction.DESC) Pageable pageable){ //return quizzesCompletedRepository.findAll(pageable); String name= SecurityContextHolder.getContext().getAuthentication().getName(); return quizzesCompletedRepository.findByName(name, pageable); } @PostMapping(path = "api/register", consumes = "application/json") public void registerQuiz(@Valid @RequestBody Users users) { Users users1 = usersRepository.findByEmail(users.getEmail()); if (users1 != null) { throw new ResponseStatusException(HttpStatus.BAD_REQUEST); } users.setPassword(passwordEncoder.encode(users.getPassword())); usersRepository.save(users); } @GetMapping(value = "api/register") public List<Users> getAllUsers() { return usersRepository.findAll(); } @DeleteMapping(path = "/api/quizzes/{id}") public ResponseEntity<Integer> deleteQuiz(@PathVariable Integer id) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); String username = auth.getName(); Quiz quiz = quizRepository.findById(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND)); if (quiz.getUsername().equals(username)) { quizRepository.deleteById(id); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } else return new ResponseEntity<>(HttpStatus.FORBIDDEN); } } class Checker { Set<Integer> answer; public Checker() { } public Set<Integer> getAnswer() { return answer; } public void setAnswer(Set<Integer> answer) { this.answer = answer; } } class AnswerToChecker { private Boolean success; private String feedback; public AnswerToChecker(Boolean success, String feedback) { this.success = success; this.feedback = feedback; } public Boolean getSuccess() { return success; } public void setSuccess(Boolean success) { this.success = success; } public String getFeedback() { return feedback; } public void setFeedback(String feedback) { this.feedback = feedback; } }
true
8fddb99474695851770fd535f417d4664571b4f1
Java
cha63506/AppCompat-Extension-Library
/appcompat-extension/src/main/java/com/tr4android/support/extension/internal/AccountAdapter.java
UTF-8
5,550
2.125
2
[ "Apache-2.0" ]
permissive
/* * Copyright (C) 2015 Thomas Robert Altstidl * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tr4android.support.extension.internal; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.tr4android.appcompat.extension.R; import com.tr4android.support.extension.widget.AccountHeaderView; import com.tr4android.support.extension.widget.CircleImageView; import java.util.ArrayList; import java.util.Arrays; /** * Adapter for accounts */ public class AccountAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private static final int VIEW_TYPE_ACCOUNT = 0; private static final int VIEW_TYPE_HEADER = 1; private ArrayList<Account> mAccounts; private AccountHeaderView mHeader; private boolean mShowAccountAdd; private boolean mShowAccountManage; private final View.OnClickListener mClickListener = new View.OnClickListener() { @Override public void onClick(View view) { mHeader.handleAccountClick((Integer) view.getTag()); } }; public AccountAdapter(ArrayList<Account> accounts, AccountHeaderView header, boolean showAccountAdd, boolean showAccountManage) { mAccounts = accounts; mHeader = header; mShowAccountAdd = showAccountAdd; mShowAccountManage = showAccountManage; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { switch (viewType) { case VIEW_TYPE_ACCOUNT: return new AccountViewHolder(LayoutInflater.from(parent.getContext()) .inflate(R.layout.appcompat_extension_account_list_item, parent, false), mClickListener); case VIEW_TYPE_HEADER: return new HeaderViewHolder(mHeader); } return null; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { if (holder instanceof AccountViewHolder) { AccountViewHolder accountViewHolder = (AccountViewHolder) holder; holder.itemView.setTag(position); if (position < getAccountCount()) { Account account = mAccounts.get(position); // apply the account to the list item account.applyAccountIcon(accountViewHolder.iconView); account.applyAccountEmail(accountViewHolder.nameView); } else if (position == getItemCount() - 1 && mShowAccountManage) { // Manage accounts item accountViewHolder.iconView.setCircleImageEnabled(false); accountViewHolder.iconView.setImageResource(R.drawable.ic_settings_black_24dp); accountViewHolder.nameView.setText(R.string.account_header_list_item_manage_accounts); } else { // Add account item accountViewHolder.iconView.setCircleImageEnabled(false); accountViewHolder.iconView.setImageResource(R.drawable.ic_add_black_24dp); accountViewHolder.nameView.setText(R.string.account_header_list_item_add_account); } } } @Override public int getItemCount() { return mAccounts.size() + (mShowAccountAdd ? 1 : 0) + (mShowAccountManage ? 1 : 0); } @Override public int getItemViewType(int position) { return (position == 0) ? VIEW_TYPE_HEADER : VIEW_TYPE_ACCOUNT; } private static class AccountViewHolder extends RecyclerView.ViewHolder { CircleImageView iconView; TextView nameView; public AccountViewHolder(View itemView, View.OnClickListener listener) { super(itemView); iconView = (CircleImageView) itemView.findViewById(R.id.icon); nameView = (TextView) itemView.findViewById(R.id.name); itemView.setOnClickListener(listener); } } private static class HeaderViewHolder extends RecyclerView.ViewHolder { public HeaderViewHolder(View itemView) { super(itemView); } } public int getAccountCount() { return mAccounts.size(); } public boolean isAccountAddEnabled() { return mShowAccountAdd; } public boolean isAccountManageEnabled() { return mShowAccountManage; } // Functions for managing the accounts public void add(Account account) { mAccounts.add(account); } public void addAll(Account... accounts) { mAccounts.addAll(Arrays.asList(accounts)); } public void remove(Account account) { mAccounts.remove(account); } public void insert(Account account, int position) { mAccounts.add(position, account); } public void clear() { mAccounts.clear(); } public Account get(int position) { return mAccounts.get(position); } public ArrayList<Account> getAll() { return mAccounts; } }
true
caecbadce71df354a4dbaf3db0fa560a36e12780
Java
heriawanfx/whatsapp-sticker-maker
/WhatsAppStickers/app/src/main/java/com/unusualapps/whatsappstickers/activities/NewStickerPackActivity.java
UTF-8
8,512
1.953125
2
[ "MIT" ]
permissive
package com.unusualapps.whatsappstickers.activities; import android.app.ProgressDialog; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.*; import com.facebook.drawee.view.SimpleDraweeView; import com.google.gson.Gson; import com.sangcomz.fishbun.FishBun; import com.sangcomz.fishbun.adapter.image.impl.GlideAdapter; import com.sangcomz.fishbun.define.Define; import com.unusualapps.whatsappstickers.R; import com.unusualapps.whatsappstickers.constants.Constants; import com.unusualapps.whatsappstickers.utils.FileUtils; import com.unusualapps.whatsappstickers.utils.StickerPacksManager; import com.unusualapps.whatsappstickers.whatsapp_api.Sticker; import com.unusualapps.whatsappstickers.whatsapp_api.StickerContentProvider; import com.unusualapps.whatsappstickers.whatsapp_api.StickerPack; import com.unusualapps.whatsappstickers.whatsapp_api.StickerPackDetailsActivity; import java.util.ArrayList; import java.util.List; import java.util.Objects; public class NewStickerPackActivity extends AppCompatActivity { ImageAdapter imageAdapter; EditText nameEdit; EditText authorEdit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_new_sticker_pack); // UI references. nameEdit = findViewById(R.id.sticker_pack_name_edit); authorEdit = findViewById(R.id.sticker_pack_author_edit); Button btnCreate = findViewById(R.id.btn_create_pack); btnCreate.setOnClickListener(v -> { FishBun.with(NewStickerPackActivity.this) .setImageAdapter(new GlideAdapter()) .setMaxCount(30) .exceptGif(true) .setActionBarColor(Color.parseColor("#128c7e"), Color.parseColor("#128c7e"), false) .setMinCount(3).setActionBarTitleColor(Color.parseColor("#ffffff")) .startAlbum(); }); GridView gridview = findViewById(R.id.sticker_pack_grid_images_preview); imageAdapter = new ImageAdapter(this); gridview.setAdapter(imageAdapter); gridview.setOnItemClickListener((parent, v, position, id) -> { Toast.makeText(NewStickerPackActivity.this, "Image removed", Toast.LENGTH_SHORT).show(); imageAdapter.uries.remove(position); imageAdapter.notifyDataSetChanged(); }); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_new_sticker_pack, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.save_sticker_pack) { if (validateValues()) { Toast.makeText(this, "You have to fill all empty spaces", Toast.LENGTH_SHORT).show(); } else { saveStickerPack(imageAdapter.uries, nameEdit.getText().toString(), authorEdit.getText().toString()); } } return super.onOptionsItemSelected(item); } private boolean validateValues() { return nameEdit.getText().toString().trim().length() == 0 || authorEdit.getText().toString().trim().length() == 0 || imageAdapter.uries.size() == 0; } private void saveStickerPack(List<Uri> uries, String name, String author) { ProgressDialog progressDialog = new ProgressDialog(this); progressDialog.setMessage("Wait a moment while we process your stickers..."); // Setting Message progressDialog.setTitle("Processing images"); // Setting Title progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // Progress Dialog Style Spinner progressDialog.show(); // Display Progress Dialog progressDialog.setCancelable(false); new Thread(() -> { try { Intent intent = new Intent(NewStickerPackActivity.this, StickerPackDetailsActivity.class); intent.putExtra(StickerPackDetailsActivity.EXTRA_SHOW_UP_BUTTON, true); String identifier = "." + FileUtils.generateRandomIdentifier(); StickerPack stickerPack = new StickerPack(identifier, name, author, Objects.requireNonNull(uries.toArray())[0].toString(), "", "", "", ""); //Save the sticker images locally and get the list of new stickers for pack List<Sticker> stickerList = StickerPacksManager.saveStickerPackFilesLocally(stickerPack.identifier, uries, NewStickerPackActivity.this); stickerPack.setStickers(stickerList); //Generate image tray icon String stickerPath = Constants.STICKERS_DIRECTORY_PATH + identifier; String trayIconFile = FileUtils.generateRandomIdentifier() + ".png"; StickerPacksManager.createStickerPackTrayIconFile(uries.get(0), Uri.parse(stickerPath + "/" + trayIconFile), NewStickerPackActivity.this); stickerPack.trayImageFile = trayIconFile; //Save stickerPack created to write in json StickerPacksManager.stickerPacksContainer.addStickerPack(stickerPack); StickerPacksManager.saveStickerPacksToJson(StickerPacksManager.stickerPacksContainer); insertStickerPackInContentProvider(stickerPack); //Start new activity with stickerpack information intent.putExtra(StickerPackDetailsActivity.EXTRA_STICKER_PACK_DATA, stickerPack); startActivity(intent); NewStickerPackActivity.this.finish(); } catch (Exception e) { e.printStackTrace(); } progressDialog.dismiss(); }).start(); } private void insertStickerPackInContentProvider(StickerPack stickerPack) { ContentValues contentValues = new ContentValues(); contentValues.put("stickerPack", new Gson().toJson(stickerPack)); getContentResolver().insert(StickerContentProvider.AUTHORITY_URI, contentValues); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == Define.ALBUM_REQUEST_CODE) { ArrayList<Uri> uries = new ArrayList<>(); if (resultCode == RESULT_OK) { uries = data.getParcelableArrayListExtra(Define.INTENT_PATH); if (uries.size() > 0) { imageAdapter.uries = uries; imageAdapter.notifyDataSetChanged(); ((TextView) findViewById(R.id.stickers_selected_textview)).setText(uries.size() + " stickers selected"); } } } } class ImageAdapter extends BaseAdapter { private Context mContext; public ImageAdapter(Context c) { mContext = c; } public int getCount() { return uries.size(); } public Object getItem(int position) { return null; } public long getItemId(int position) { return 0; } // create a new ImageView for each item referenced by the Adapter public View getView(int position, View convertView, ViewGroup parent) { SimpleDraweeView imageView; if (convertView == null) { // if it's not recycled, initialize some attributes imageView = new SimpleDraweeView(mContext); imageView.setLayoutParams(new ViewGroup.LayoutParams(150, 150)); imageView.setScaleType(ImageView.ScaleType.FIT_CENTER); imageView.setAdjustViewBounds(true); imageView.setPadding(8, 8, 8, 8); } else { imageView = (SimpleDraweeView) convertView; } imageView.setImageURI(uries.get(position)); return imageView; } // references to our images ArrayList<Uri> uries = new ArrayList<>(); } }
true
b7df054934304f0b43f4ceafc1dfb953ecd558d9
Java
arturbakhshaliiev/corona-stats
/src/main/java/com/example/coronastats/telegram/repository/TelegramUserRepository.java
UTF-8
319
1.882813
2
[]
no_license
package com.example.coronastats.telegram.repository; import com.example.coronastats.telegram.model.TelegramUser; import org.springframework.data.jpa.repository.JpaRepository; public interface TelegramUserRepository extends JpaRepository<TelegramUser, Long> { TelegramUser findByTelegramId(Integer telegramId); }
true
ea9e9cd29b5e269f1fb834049d26a166f548d031
Java
chentianming11/study
/concurrent/src/main/java/com/chen/study/concurrent/concurrent3/juc/util/countdownlatch/CountDownLatchExample2.java
UTF-8
1,554
3.5625
4
[ "Apache-2.0" ]
permissive
package com.chen.study.concurrent.concurrent3.juc.util.countdownlatch; import java.util.concurrent.CountDownLatch; /** * @author 陈添明 * @date 2018/11/4 */ public class CountDownLatchExample2 { public static void main(String[] args) { final CountDownLatch latch = new CountDownLatch(1); /** * 第一个线程先执行一部分逻辑后阻塞,等待另外一个线程放行 */ new Thread(() -> { System.out.println("do some initial working..."); try { Thread.sleep(1_000); latch.await(); System.out.println("do other working..."); } catch (InterruptedException e) { e.printStackTrace(); } }).start(); /** * 第二个线程执行完成后,countdown之后,让第一个线程放行。 */ new Thread(() -> { System.out.println("async prepare for some data."); try { Thread.sleep(2_000); System.out.println("data prepare done"); } catch (InterruptedException e) { e.printStackTrace(); } finally { latch.countDown(); } }).start(); new Thread(() -> { try { latch.await(); System.out.println("线程3也停止阻塞。。"); } catch (InterruptedException e) { e.printStackTrace(); } }).start(); } }
true
3c0ef5edd2f026f0db1a74f3016691c3e4009dfe
Java
SanjayaKumarSahoo/datastructure
/src/main/java/com/string/ReverseAllWordsInSentence.java
UTF-8
1,126
3.8125
4
[]
no_license
package com.string; public class ReverseAllWordsInSentence { public static void main(String[] args) { String sentence = "Hi I am good hence d nnn,m ,nm,n,mn"; System.out.println(reverseAllWords(sentence)); } private static String reverseAllWords(String sentence) { if (sentence == null) { throw new IllegalArgumentException("Invalid input"); } char[] charArray = sentence.toCharArray(); int i = 0; for (int k = 0; k < charArray.length; k++) { if (charArray[k] == ' ') { reverse(i, k - 1, charArray); i = k + 1; } // handling last word if (k == charArray.length - 1) { reverse(i, charArray.length - 1, charArray); } } return new String(charArray); } private static void reverse(int start, int last, char[] data) { while (start < last) { char temp = data[start]; data[start] = data[last]; data[last] = temp; start++; last--; } } }
true
609c72531bc1141045224896ab0daa3803f38835
Java
icerisa/UsedCar
/UsedCar/src/java/model/NCB.java
UTF-8
2,802
2.859375
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package model; import controller.DBConnector; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.HashMap; import java.util.Map; public class NCB { int NCB_Type; String NCB_Name; public NCB() { } public NCB(int NCB_Type) { this.NCB_Type = NCB_Type; getNCBData(); } public NCB(int NCB_Type, String NCB_Name) { this.NCB_Type = NCB_Type; this.NCB_Name = NCB_Name; } public int getNCB_Type() { return NCB_Type; } public void setNCB_Type(int NCB_Type) { this.NCB_Type = NCB_Type; } public String getNCB_Name() { return NCB_Name; } public void setNCB_Name(String NCB_Name) { this.NCB_Name = NCB_Name; } @Override public String toString() { return "NCB{" + "NCB_Type=" + NCB_Type + ", NCB_Name=" + NCB_Name + '}'; } public void getNCBData(){ try{ Connection con = DBConnector.getConnection(); String sql = "SELECT * FROM ncb WHERE NCB_Type=?"; PreparedStatement pstm = con.prepareStatement(sql); pstm.setInt(1, this.NCB_Type); ResultSet rs = pstm.executeQuery(); if(rs.next()){ this.NCB_Name = rs.getString("NCB_Name"); } else { this.NCB_Name = "NCB not found"; } } catch(Exception e){ System.out.println(e); } } public static Map<Integer,String> getAllNCB(){ Map<Integer,String> subModels = new HashMap<Integer,String>(); try{ Connection con = DBConnector.getConnection(); String sql = "SELECT * FROM ncb"; PreparedStatement pstm = con.prepareStatement(sql); ResultSet rs = pstm.executeQuery(); while(rs.next()){ subModels.put(rs.getInt("NCB_Type"),rs.getString("NCB_Name")); } con.close(); } catch (Exception e){ System.out.println(e); }; return subModels; } public static String getNCBNameFromType(int type){ try{ Connection con = DBConnector.getConnection(); String sql = "SELECT * FROM ncb WHERE NCB_Type=?"; PreparedStatement pstm = con.prepareStatement(sql); pstm.setInt(1, type); ResultSet rs = pstm.executeQuery(); if(rs.next()){ return rs.getString("NCB_Name"); } } catch(Exception e){ System.out.println(e); } return "NCB not found"; } }
true
60f98fa90c17cd8010133a97a71b6f72087de1f1
Java
Darshitpipariya/Playground
/Target practice/Main.java
UTF-8
237
2.25
2
[]
no_license
#include<iostream> using namespace std; int main() { int num, sum=0, count, n; cin>>num; for(count=0;sum<num;count++) { cin>>n; sum=sum+n; } cout<<"The number of turns is "<<count; return 0; }
true
c50506c63b03a47644ec9189f2690bd3cc44d2f2
Java
sumitpalsingh/open-kilda
/services/wfm/src/main/java/org/openkilda/wfm/topology/splitter/InfoEventSplitterBolt.java
UTF-8
6,806
1.96875
2
[ "Apache-2.0" ]
permissive
/* Copyright 2017 Telstra Open Source * * 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.openkilda.wfm.topology.splitter; import static org.openkilda.messaging.Utils.PAYLOAD; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.storm.task.OutputCollector; import org.apache.storm.task.TopologyContext; import org.apache.storm.topology.OutputFieldsDeclarer; import org.apache.storm.topology.base.BaseRichBolt; import org.apache.storm.tuple.Fields; import org.apache.storm.tuple.Tuple; import org.apache.storm.tuple.Values; import org.openkilda.messaging.info.event.IslChangeType; import org.openkilda.messaging.info.event.PortChangeType; import org.openkilda.messaging.info.event.SwitchState; import java.io.IOException; import java.util.Map; /** * InfoEventSplitterBolt - split the INFO message types * - All SWITCH / PORT / ISL messages will be sent to their respective queues * - UP / DOWN for each of SWITCH/PORT/ISL will be sent to a their respective queues * - OTHER will be used for each are if there isn't a match (INFO.OTHER,SWITCH.OTHER, etc.) */ public class InfoEventSplitterBolt extends BaseRichBolt { public static final String INFO = OFEventSplitterBolt.INFO; // topic created elsewhere public static final String I_OTHER = INFO + ".other"; public static final String I_SWITCH = INFO + ".switch"; public static final String I_SWITCH_UPDOWN = I_SWITCH + ".updown"; public static final String I_SWITCH_OTHER = I_SWITCH + ".other"; public static final String I_PORT = INFO + ".port"; public static final String I_PORT_UPDOWN = I_PORT + ".updown"; public static final String I_PORT_OTHER = I_PORT + ".other"; public static final String I_ISL = INFO + ".isl"; public static final String I_ISL_UPDOWN = I_ISL + ".updown"; public static final String I_ISL_OTHER = I_ISL + ".other"; public static final String[] outputStreams = { I_OTHER, I_SWITCH, I_SWITCH_UPDOWN, I_SWITCH_OTHER, I_PORT, I_PORT_UPDOWN, I_PORT_OTHER, I_ISL, I_ISL_UPDOWN, I_ISL_OTHER }; private static Logger logger = LogManager.getLogger(InfoEventSplitterBolt.class); OutputCollector _collector; @Override public void prepare(Map conf, TopologyContext context, OutputCollector collector) { _collector = collector; } /** * The data field holds the "message_type" and "state" fields. * * @param root the "payload" field of an "INFO" message */ private void splitInfoMessage(Map<String, ?> root, Tuple tuple) throws JsonProcessingException { Values dataVal = new Values(PAYLOAD, new ObjectMapper().writeValueAsString(root)); String key = ((String) root.get("message_type")).toLowerCase(); String state = (String) root.get("state"); switch (key) { case "switch": _collector.emit(I_SWITCH, tuple, dataVal); logger.debug("EMIT {} : {}", I_SWITCH, dataVal); if (isSwitchUpdownStream(state)) { _collector.emit(I_SWITCH_UPDOWN, tuple, dataVal); logger.debug("EMIT {} : {}", I_SWITCH_UPDOWN, dataVal); } else { _collector.emit(I_SWITCH_OTHER, tuple, dataVal); logger.debug("EMIT {} : {}", I_SWITCH_OTHER, dataVal); } break; case "port": _collector.emit(I_PORT, tuple, dataVal); logger.debug("EMIT {} : {}", I_PORT, dataVal); if (isPortUpdownStream(state)) { _collector.emit(I_PORT_UPDOWN, tuple, dataVal); } else { _collector.emit(I_PORT_OTHER, tuple, dataVal); } break; case "isl": _collector.emit(I_ISL, tuple, dataVal); logger.debug("EMIT {} : {}", I_ISL, dataVal); if (state != null && isIslUpdownStream(state)) { _collector.emit(I_ISL_UPDOWN, tuple, dataVal); } else { _collector.emit(I_ISL_OTHER, tuple, dataVal); } break; default: // NB: we'll push the original message onto the CONFUSED channel _collector.emit(I_OTHER, tuple, dataVal); logger.warn("Unknown INFO Message Type: {}\nJSON:{}", key, root); } } @SuppressWarnings("unchecked") @Override public void execute(Tuple tuple) { String json = tuple.getStringByField("message"); logger.info("Processing INFO message: {}", json); Map<String, ?> root = null; try { root = (Map<String, ?>) new ObjectMapper().readValue(json, Map.class); splitInfoMessage(root, tuple); } catch (IOException e) { logger.error("IOException processing an INFO message: {}, error: {} ", json, e.getMessage()); e.printStackTrace(); } finally { // Regardless of whether we have errors, we don't want to reprocess for now, so send ack _collector.ack(tuple); } } @Override public void declareOutputFields(OutputFieldsDeclarer declarer) { Fields f = new Fields("key", "message"); for (String name : outputStreams) { logger.trace("Declaring Stream: " + name); declarer.declareStream(name, f); } } private boolean isSwitchUpdownStream(String state) { SwitchState switchState = SwitchState.from(state); return switchState.isActive() || switchState.isInactive(); } private boolean isPortUpdownStream(String state) { PortChangeType type = PortChangeType.from(state); return type.isActive() || type == PortChangeType.DOWN || type == PortChangeType.CACHED; } private boolean isIslUpdownStream(String state) { IslChangeType changeType = IslChangeType.from(state); return changeType == IslChangeType.DISCOVERED || changeType == IslChangeType.FAILED; } }
true
ba677c8aca501e8ba39aeccc6dbe83a28ef306a0
Java
devendrakasture/Accenture
/Practical/src/Abhi.java
UTF-8
659
2.859375
3
[]
no_license
import java.util.*; public class Abhi { public static void main (String[] args) { Scanner sc=new Scanner(System.in); String input; int s,i; input=sc.nextLine(); for( i=1,s=1;i<=input.length();i++) { s=s*i; } System.out.println(s); // String[][] input2=new String[input][3]; // for(int i=0;i<=input;i++) // { // input1[i]=sc.nextLine(); // input2[i]=input1[i].split(","); // } // System.out.println("f"); // System.out.println("Abhi"); // System.out.println("ABhi1"); } }
true
6b757e21dba1e1639bfa95bc5e703eadb66aeea7
Java
thanghaqn2000/A1020I1-HoDucThang
/module3/99_CaseStudy/MainWebsite/src/main/java/controller/customer/SearchServlet.java
UTF-8
1,202
2.265625
2
[]
no_license
package controller.customer; import model.bean.Customer; import model.service.customer.CustomerService; import model.service.customer.impl.CustomerServiceImpl; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; @WebServlet(name = "SearchServlet", urlPatterns = "/searchCustomer") public class SearchServlet extends HttpServlet { CustomerService customerService = new CustomerServiceImpl(); protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("nameSearch"); List<Customer> listCustomer = name == "" ? customerService.selectAllCus() : customerService.findCus(name); request.setAttribute("listCustomer",listCustomer); request.getRequestDispatcher("jsp/user/displayCustomer.jsp").forward(request,response); } }
true
82813f1ee6ec240e7af305ed47c95c2168ff6eab
Java
floodboad/zyj-hssp
/zyj-hec-master/zyj-hec/src/main/java/com/hand/hec/bpm/dto/TpltLayoutForm.java
UTF-8
2,541
1.976563
2
[]
no_license
package com.hand.hec.bpm.dto; /** * Auto Generated By Code Generator * Description: */ import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Transient; import javax.persistence.GeneratedValue; import com.hand.hap.mybatis.common.query.Comparison; import com.hand.hap.mybatis.common.query.Where; import org.springframework.stereotype.Component; import org.hibernate.validator.constraints.Length; import com.hand.hap.mybatis.annotation.ExtensionAttribute; import com.hand.hap.system.dto.BaseDTO; @Component @ExtensionAttribute(disable = true) @Table(name = "bpm_tplt_layout_form") public class TpltLayoutForm extends BaseDTO { public static final String FIELD_LAYOUT_ID = "layoutId"; public static final String FIELD_PROMPT = "prompt"; public static final String FIELD_TITLE = "title"; public static final String FIELD_COLUMN_NUM = "columnNum"; public static final String FIELD_ROW_NUM = "rowNum"; public static final String FIELD_LABELWIDTH = "labelwidth"; public static final String FIELD_LABELSEPARATOR = "labelseparator"; @Id @Where private Long layoutId;//布局组件ID @Length(max = 200) private String prompt;//描述 @Length(max = 200) private String title;//标题 private Long columnNum;//列数 private Long rowNum;//行数 private Long labelwidth;//标签宽度 @Length(max = 200) private String labelseparator;//标签分割符 public void setLayoutId(Long layoutId) { this.layoutId = layoutId; } public Long getLayoutId() { return layoutId; } public void setPrompt(String prompt) { this.prompt = prompt; } public String getPrompt() { return prompt; } public void setTitle(String title) { this.title = title; } public String getTitle() { return title; } public void setLabelwidth(Long labelwidth) { this.labelwidth = labelwidth; } public Long getLabelwidth() { return labelwidth; } public void setLabelseparator(String labelseparator) { this.labelseparator = labelseparator; } public String getLabelseparator() { return labelseparator; } public Long getColumnNum() { return columnNum; } public void setColumnNum(Long columnNum) { this.columnNum = columnNum; } public Long getRowNum() { return rowNum; } public void setRowNum(Long rowNum) { this.rowNum = rowNum; } }
true
fb4f16bd7ffe18731ad32081e05250fb5dd45f8e
Java
Lylio/java-archive
/Big-Java-Late-Objects/Chapter-3/P3_28.java
UTF-8
1,113
4.1875
4
[]
no_license
import java.util.Scanner; /** * P3.28 A year with 366 days is called a leap year. Leap years are necessary to keep the calendar * synchronized with the sun because the earth revolves around the sun once * every 365.25 days. Actually, that figure is not entirely precise, and for all dates after * 1582 the Gregorian correction applies. Usually years that are divisible by 4 are leap * years, for example 1996. However, years that are divisible by 100 (for example, 1900) * are not leap years, but years that are divisible by 400 are leap years (for example 2000). Write a program that asks the user for a year and computes whether that year * is a leap year. Use a single if statement and Boolean operators. * @author Lyle * */ public class P3_28 { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Please enter year: "); int year = in.nextInt(); in.close(); if(year % 4 == 0 || year % 400 == 0 && !(year % 100 == 0)) { System.out.println(year + " is a leap year."); } else {System.out.println(year + " is not a leap year.");} } }
true
4f11c159f4a674cd24cc5665cebbe83c55084ea3
Java
ileanavasilica99/ObjectOrientedDesign
/Hero/src/org/learning/ood/Character.java
UTF-8
1,345
3.40625
3
[]
no_license
package org.learning.ood; public abstract class Character implements Attacker, Defender { private int healthPoints; private int strengthPoints; private int defensePoints; private int speedPoints; private int luckPoints; private int turns = 20; public Character(int health, int strength, int defense, int speed, int luck) { healthPoints = health; strengthPoints = strength; defensePoints = defense; speedPoints = speed; luckPoints = luck; } public int getHealthPoints() { return healthPoints; } public int getStrengthPoints() { return strengthPoints; } public int getDefensePoints() { return defensePoints; } public int getSpeedPoints() { return speedPoints; } public int getLuckPoints() { return luckPoints; } public int getTurns() { return turns; } public void setTurns(int turns) { this.turns = turns; } public int isAlive() { return healthPoints != 0 ? 1 : 0; } public void attack(Character defender) { int damage = strengthPoints - defender.getDefensePoints(); takeDamage(damage); } public void takeDamage(int damage) { if (healthPoints - damage > 0) { healthPoints = healthPoints - damage; } else { healthPoints = 0; } } }
true
74be283a80a7897dd2a6e024c0fb0cae899c12c0
Java
tdsoft/Github-Tharndu
/AppFoundationTest/androidappfoundation/src/main/java/com/android/tdsoft/androidappfoundation/base/callbacks/OnRetryClickListener.java
UTF-8
175
1.585938
2
[]
no_license
package com.android.tdsoft.androidappfoundation.base.callbacks; /** * Created by Admin on 12/22/2015. */ public interface OnRetryClickListener { void onRetryClick(); }
true
ac8591874dc7daa8320ca8a55b8b8524a59f5398
Java
SuhailMujawar/HashMap-and-ConHashMap
/src/com/sam/Demoproj/HashMapIteration.java
UTF-8
1,114
3.34375
3
[]
no_license
package com.sam.Demoproj; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class HashMapIteration { public static void main(String[] args) { Map<Integer,String> items = new HashMap<>(); items.put(1, "coins"); items.put(2, "coins"); items.put(5, "coins"); IteratorMap(items); // EntryMapSet(items); } private static void EntryMapSet(Map<Integer, String> items) { for (Map.Entry<Integer, String> entry : items.entrySet()) { System.out.println("Key=" +entry.getKey()); System.out.println("Value="+entry.getValue()); System.out.println(" "); } } private static void IteratorMap(Map<Integer,String> items) { Iterator<Map.Entry<Integer,String>> iterator=items.entrySet().iterator(); while(iterator.hasNext()) { Map.Entry<Integer,String> entry = iterator.next(); items.put(6, "Coins"); System.out.print("Key="+entry.getKey()); System.out.print(","); System.out.print("Value="+entry.getValue()); } } }
true
6efdcf3b48c8444a3bfe93e72459c101b334c8c8
Java
jmvalmeria/Summer2020_B20
/src/day03_sequences_Variables/lToGal.java
UTF-8
198
2.671875
3
[]
no_license
package day03_sequences_Variables; public class lToGal { public static void main(String[] args) { double gal = 4; double l = gal / 3.78; System.out.println(l); } }
true
2b6befb9f4b45d0df7126e439b340b6a272829ce
Java
stefff94/teammates-manager
/src/test/java/it/polste/attsw/teammatesmanagerbackend/controllers/TeammateRestControllerTest.java
UTF-8
9,165
2.390625
2
[]
no_license
package it.polste.attsw.teammatesmanagerbackend.controllers; import io.restassured.module.mockmvc.RestAssuredMockMvc; import it.polste.attsw.teammatesmanagerbackend.exceptions.TeammateAlreadyExistsException; import it.polste.attsw.teammatesmanagerbackend.exceptions.TeammateNotExistsException; import it.polste.attsw.teammatesmanagerbackend.exceptions.TeammateRestControllerExceptionHandler; import it.polste.attsw.teammatesmanagerbackend.models.PersonalData; import it.polste.attsw.teammatesmanagerbackend.models.Skill; import it.polste.attsw.teammatesmanagerbackend.models.Teammate; import it.polste.attsw.teammatesmanagerbackend.services.TeammateService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import static io.restassured.module.mockmvc.RestAssuredMockMvc.given; import static io.restassured.module.mockmvc.RestAssuredMockMvc.when; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.Matchers.empty; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class TeammateRestControllerTest { @Mock private TeammateService teammateService; @InjectMocks private TeammateRestController teammateRestController; @InjectMocks private TeammateRestControllerExceptionHandler teammateRestControllerExceptionHandler; private PersonalData stefanosData; private PersonalData paolosData; private Set<Skill> skills; private String teammateAlreadyExistsMessage; private String teammateNotExistsMessage; @Before public void setup() { RestAssuredMockMvc.standaloneSetup(teammateRestController, teammateRestControllerExceptionHandler); stefanosData = new PersonalData("Stefano Vannucchi", "stefano.vannucchi@stud.unifi.it", "M", "Prato", "student", "https://semantic-ui.com/images/avatar/large/steve.jpg"); paolosData = new PersonalData("Paolo Innocenti", "paolo.innocenti@stud.unifi.it", "M", "Pistoia", "student", "https://semantic-ui.com/images/avatar/large/elliot.jpg"); skills = new HashSet<>(); skills.add(new Skill(1L, "Spring Boot")); skills.add(new Skill(2L, "Vue js")); teammateAlreadyExistsMessage = "The entered email has already been associated with a Teammate"; teammateNotExistsMessage = "No Teammate with id 1 exists!"; } @Test public void testGetAllTeammatesWhenEmpty() { when(). get("/api/teammates"). then(). statusCode(HttpStatus.OK.value()). assertThat(). body("", empty()); } @Test public void testGetAllTeammatesWhenNotEmpty() { when(teammateService.getAllTeammates()) .thenReturn(Arrays.asList( new Teammate(1L, stefanosData, skills), new Teammate(2L, paolosData, skills) )); when(). get("/api/teammates"). then(). statusCode(HttpStatus.OK.value()). assertThat(). body( "id", hasItems(1, 2), "personalData.name", hasItems("Stefano Vannucchi", "Paolo Innocenti"), "personalData.email", hasItems( "stefano.vannucchi@stud.unifi.it", "paolo.innocenti@stud.unifi.it" ), "personalData.gender", hasItem("M"), "personalData.city", hasItems("Prato", "Pistoia"), "personalData.role", hasItem("student"), "personalData.photoUrl", hasItems( "https://semantic-ui.com/images/avatar/large/steve.jpg", "https://semantic-ui.com/images/avatar/large/elliot.jpg" ), "skills.id", everyItem(hasItems(1, 2)), "skills.name", everyItem(hasItems("Spring Boot", "Vue js")) ); } @Test public void testInsertNewTeammateWithSuccess() { Teammate teammateToInsert = new Teammate(null, stefanosData, skills); when(teammateService.insertNewTeammate(any(Teammate.class))) .thenReturn(new Teammate(1L, stefanosData, skills)); given(). contentType(MediaType.APPLICATION_JSON_VALUE). body(teammateToInsert). when(). post("/api/teammates/new"). then(). statusCode(HttpStatus.OK.value()). assertThat(). body( "id", equalTo(1), "personalData.name", equalTo("Stefano Vannucchi"), "personalData.email", equalTo("stefano.vannucchi@stud.unifi.it"), "personalData.gender", equalTo("M"), "personalData.city", equalTo("Prato"), "personalData.role", equalTo("student"), "personalData.photoUrl", equalTo( "https://semantic-ui.com/images/avatar/large/steve.jpg"), "skills.id", hasItems(1, 2), "skills.name", hasItems("Spring Boot", "Vue js") ); } @Test public void testInsertNewTeammateWhenDuplicateEmail() { Teammate teammateToInsert = new Teammate(null, stefanosData, skills); when(teammateService.insertNewTeammate(any(Teammate.class))) .thenThrow(new TeammateAlreadyExistsException(teammateAlreadyExistsMessage)); given(). contentType(MediaType.APPLICATION_JSON_VALUE). body(teammateToInsert). when(). post("/api/teammates/new"). then(). statusCode(HttpStatus.FORBIDDEN.value()). assertThat(). body("message", equalTo(teammateAlreadyExistsMessage)); } @Test public void testUpdateTeammateWithSuccess() { Teammate teammateToUpdate = new Teammate(null, stefanosData, skills); when(teammateService.updateTeammate(anyLong(), any(Teammate.class))) .thenReturn(new Teammate(1L, stefanosData, skills)); given(). contentType(MediaType.APPLICATION_JSON_VALUE). body(teammateToUpdate). when(). put("/api/teammates/update/1"). then(). statusCode(HttpStatus.OK.value()). assertThat(). body( "id", equalTo(1), "personalData.name", equalTo("Stefano Vannucchi"), "personalData.email", equalTo("stefano.vannucchi@stud.unifi.it"), "personalData.gender", equalTo("M"), "personalData.city", equalTo("Prato"), "personalData.role", equalTo("student"), "personalData.photoUrl", equalTo( "https://semantic-ui.com/images/avatar/large/steve.jpg"), "skills.id", hasItems(1, 2), "skills.name", hasItems("Spring Boot", "Vue js") ); } @Test public void testUpdateTeammateWhenNoExisting() { Teammate teammateToUpdate = new Teammate(null, stefanosData, skills); when(teammateService.updateTeammate(anyLong(), any(Teammate.class))) .thenThrow(new TeammateNotExistsException(teammateNotExistsMessage)); given(). contentType(MediaType.APPLICATION_JSON_VALUE). body(teammateToUpdate). when(). put("/api/teammates/update/1"). then(). statusCode(HttpStatus.NOT_FOUND.value()). assertThat(). body("message", equalTo(teammateNotExistsMessage)); } @Test public void testUpdateTeammateWhenDuplicateEmail() { Teammate teammateToUpdate = new Teammate(null, stefanosData, skills); when(teammateService.updateTeammate(anyLong(), any(Teammate.class))) .thenThrow(new TeammateAlreadyExistsException(teammateAlreadyExistsMessage)); given(). contentType(MediaType.APPLICATION_JSON_VALUE). body(teammateToUpdate). when(). put("/api/teammates/update/1"). then(). statusCode(HttpStatus.FORBIDDEN.value()). assertThat(). body("message", equalTo(teammateAlreadyExistsMessage)); } @Test public void testDeleteTeammateWithSuccess() { when(). delete("api/teammates/delete/1"). then(). statusCode(HttpStatus.OK.value()); verify(teammateService, times(1)).deleteTeammate(1L); } @Test public void testDeleteTeammateWhenNotExists() { doThrow(new TeammateNotExistsException(teammateNotExistsMessage)) .when(teammateService).deleteTeammate(1L); when(). delete("api/teammates/delete/1"). then(). statusCode(HttpStatus.NOT_FOUND.value()). assertThat(). body("message", equalTo(teammateNotExistsMessage)); } }
true
c86b0d9fcdaf1bd54932c81d03ea8948b02df5ee
Java
avfyodorov/psc_21_03
/src/main/java/cons08solid/solid/Solid.java
UTF-8
4,754
2.96875
3
[]
no_license
package cons08solid.solid; public class Solid { } /* public class OrderProcessor { public void process(Order order){ if (order.isValid() && save(order)) { sendConfirmationEmail(order); } } private boolean save(Order order) { MySqlConnection connection = new MySqlConnection("database.url"); // сохраняем заказ в базу данных return true; } private void sendConfirmationEmail(Order order) { String name = order.getCustomerName(); String email = order.getCustomerEmail(); // Шлем письмо клиенту } } //-------------------- public class MySQLOrderRepository { public boolean save(Order order) { MySqlConnection connection = new MySqlConnection("database.url"); // сохраняем заказ в базу данных return true; } } public class ConfirmationEmailSender { public void sendConfirmationEmail(Order order) { String name = order.getCustomerName(); String email = order.getCustomerEmail(); // Шлем письмо клиенту } } public class OrderProcessor { public void process(Order order){ MySQLOrderRepository repository = new MySQLOrderRepository(); ConfirmationEmailSender mailSender = new ConfirmationEmailSender(); if (order.isValid() && repository.save(order)) { mailSender.sendConfirmationEmail(order); } } } //====================== //======================= //===================== public class OrderProcessorWithPreAndPostProcessing extends OrderProcessor { @Override public void process(Order order) { beforeProcessing(); super.process(order); afterProcessing(); } private void beforeProcessing() { // Осуществим некоторые действия перед обработкой заказа } private void afterProcessing() { // Осуществим некоторые действия после обработки заказа } } //================== //================== //================== public class OrderStockValidator { public boolean isValid(Order order) { for (Item item : order.getItems()) { if (! item.isInStock()) { return false; } } return true; } } public class OrderStockAndPackValidator extends OrderStockValidator { @Override public boolean isValid(Order order) { for (Item item : order.getItems()) { if ( !item.isInStock() || !item.isPacked() ){ throw new IllegalStateException( String.format("Order %d is not valid!", order.getId()) ); } } return true; } } //======================== //======================== //======================== public class OrderProcessor { public void process(Order order){ MySQLOrderRepository repository = new MySQLOrderRepository(); ConfirmationEmailSender mailSender = new ConfirmationEmailSender(); if (order.isValid() && repository.save(order)) { mailSender.sendConfirmationEmail(order); } } } public class MySQLOrderRepository { public boolean save(Order order) { MySqlConnection connection = new MySqlConnection("database.url"); // сохраняем заказ в базу данных return true; } } public class ConfirmationEmailSender { public void sendConfirmationEmail(Order order) { String name = order.getCustomerName(); String email = order.getCustomerEmail(); // Шлем письмо клиенту } } public interface MailSender { void sendConfirmationEmail(Order order); } public interface OrderRepository { boolean save(Order order); } public class ConfirmationEmailSender implements MailSender { @Override public void sendConfirmationEmail(Order order) { String name = order.getCustomerName(); String email = order.getCustomerEmail(); // Шлем письмо клиенту } } public class MySQLOrderRepository implements OrderRepository { @Override public boolean save(Order order) { MySqlConnection connection = new MySqlConnection("database.url"); // сохраняем заказ в базу данных return true; } } public class OrderProcessor { private MailSender mailSender; private OrderRepository repository; public OrderProcessor(MailSender mailSender, OrderRepository repository) { this.mailSender = mailSender; this.repository = repository; } public void process(Order order){ if (order.isValid() && repository.save(order)) { mailSender.sendConfirmationEmail(order); } } } */
true
7777125ee33bd938c4d1482f445118890d409b19
Java
renatamarques97/freecell-got
/src/freecell/MainFreeCell.java
UTF-8
1,529
2.75
3
[]
no_license
package freecell; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MainFreeCell extends JFrame { private final Jogo modelo; private final PaineldeCarta _boardDisplay; //private final JCheckBox _autoCompleteCB; public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new MainFreeCell(); } }); } public MainFreeCell() { //this._autoCompleteCB = new JCheckBox("Auto Complete"); this.modelo = new Jogo(); _boardDisplay = new PaineldeCarta(modelo); JButton newGameBtn; newGameBtn = new JButton("Novo"); newGameBtn.addActionListener(new ActionNewGame()); JPanel controlPanel = new JPanel(new FlowLayout()); controlPanel.add(newGameBtn); JPanel content = new JPanel(); content.setLayout(new BorderLayout()); content.add(controlPanel, BorderLayout.NORTH); content.add(_boardDisplay, BorderLayout.CENTER); setContentPane(content); setTitle("FreeCell Game of Thrones"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //fechar no x pack(); setLocationRelativeTo(null); setResizable(false); setVisible(true); } class ActionNewGame implements ActionListener { @Override public void actionPerformed(ActionEvent evt) { modelo.reset(); } } }
true
2461b68da33d7a3477d2877a4323e18182c27f6e
Java
loshirleyve/android
/Mobile/jupiter/src/main/java/com/yun9/jupiter/http/support/DefaultRequestParams.java
UTF-8
1,449
2.1875
2
[]
no_license
package com.yun9.jupiter.http.support; import com.yun9.jupiter.http.RequestParams; import com.yun9.jupiter.repository.Page; import com.yun9.jupiter.util.AssertValue; import java.util.HashMap; import java.util.Map; public class DefaultRequestParams implements RequestParams { private String token; private String action; private Map<String, Object> header; private Map<String, Object> data = new HashMap<>(); private Page page; public Map<String, Object> getHeader() { return header; } public void setHeader(Map<String, Object> header) { this.header = header; } public Map<String, Object> getData() { return data; } public void setData(Map<String, Object> data) { this.data = data; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } public String getAction() { return action; } public void setAction(String action) { this.action = action; } public RequestParams data(String key, Object value) { if (!AssertValue.isNotNull(data)) { this.data = new HashMap<String, Object>(); } this.data.put(key, value); return this; } public RequestParams header(String key, Object value) { if (!AssertValue.isNotNull(this.header)) { this.header = new HashMap<String, Object>(); } this.header.put(key, value); return this; } public Page getPage() { return page; } public void setPage(Page page) { this.page = page; } }
true
fd4e8f40c8af7000df50163df34d59ea57ecf12e
Java
yamgent/collate
/src/test/TestLogic.java
UTF-8
4,630
2.40625
2
[]
no_license
package test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.HashMap; import main.java.backend.Command; import main.java.backend.Logic; import main.java.data.Author; import main.java.data.SourceFile; import org.junit.Before; import org.junit.Test; public class TestLogic { private static final String ROOT_DIR = System.getProperty("user.dir"); private static final String TEST_RESOURCES_DIR = "/src/test/testFiles/"; private static final String TEST_FILE1 = "testFile1.txt"; private static final String TEST_FILE2 = "testFile2.txt"; private static final String TEST_FILE_NO_EXTENSION = "testFileNoExtension"; private static final String TEST_FILE_IN_SUBFOLDER = "testFile1.txt"; private static final String RELATIVE_PATH_TEST_FILE_IN_SUBFOLDER = "subfolder/" + TEST_FILE_IN_SUBFOLDER; private static final String FULL_PATH_TEST_FILE1 = "\"" + ROOT_DIR + TEST_RESOURCES_DIR + TEST_FILE1 + "\""; private static final String AUTHOR1 = "author1"; private static final String AUTHOR2 = "author2"; private Logic logic; @Before public void init() { logic = new Logic(); } @Test public void testHandleEnterPress() { assertEquals(Command.Type.COLLATE, logic.executeCommand("collate from \"" + ROOT_DIR + TEST_RESOURCES_DIR + "\"")); assertEquals(Command.Type.COLLATE, logic.executeCommand("collate from \"" + ROOT_DIR + TEST_RESOURCES_DIR + "\" only")); assertEquals(Command.Type.COLLATE, logic.executeCommand("collate from \"" + ROOT_DIR + TEST_RESOURCES_DIR + "\" include java")); assertEquals(Command.Type.COLLATE, logic.executeCommand("collate from \"" + ROOT_DIR + TEST_RESOURCES_DIR + "\" include txt")); assertEquals(Command.Type.COLLATE, logic.executeCommand("collate from " + FULL_PATH_TEST_FILE1)); assertEquals(Command.Type.VIEW, logic.executeCommand("view A1234567Z")); assertEquals(Command.Type.VIEW, logic.executeCommand("view author1")); assertEquals(Command.Type.SUMMARY, logic.executeCommand("summary")); assertEquals(Command.Type.INVALID, logic.executeCommand("from")); } @Test public void testGetAuthors() { logic.executeCommand("collate from " + FULL_PATH_TEST_FILE1); assertEquals(1, logic.getAuthors().size()); for (Author author : logic.getAuthors()) { assertEquals(AUTHOR1, author.getName()); } } @Test public void testGetTargetAuthorName() { assertEquals(null, logic.getTargetAuthorName()); logic.executeCommand("collate from " + FULL_PATH_TEST_FILE1); logic.executeCommand("view " + AUTHOR1); assertEquals(AUTHOR1, logic.getTargetAuthorName()); } @Test public void testGetTargetAuthorStatistics() { logic.executeCommand("collate from " + ROOT_DIR + TEST_RESOURCES_DIR); assertTrue(logic.getTargetAuthorStatistics().isEmpty()); logic.executeCommand("view " + AUTHOR1); HashMap<SourceFile, Integer> statistics = logic.getTargetAuthorStatistics(); for (SourceFile sourceFile : statistics.keySet()) { String currentFileLocation = sourceFile.getRelativeFilePath(); if (currentFileLocation.equals(TEST_FILE1)) { assertEquals(5, (int) statistics.get(sourceFile)); } else if (currentFileLocation.equals(TEST_FILE2)) { assertEquals(2, (int) statistics.get(sourceFile)); } else if (currentFileLocation.equals(TEST_FILE_NO_EXTENSION)) { assertEquals(1, (int) statistics.get(sourceFile)); } } logic.executeCommand("view " + AUTHOR2); statistics = logic.getTargetAuthorStatistics(); for (SourceFile sourceFile : statistics.keySet()) { String currentFileLocation = sourceFile.getRelativeFilePath(); if (currentFileLocation.equals(RELATIVE_PATH_TEST_FILE_IN_SUBFOLDER)) { assertEquals(4, (int) statistics.get(sourceFile)); } } } }
true
375f16f48c69501fd562e46bc1b4565b0f8639fe
Java
lixiayang168/test
/Test/src/com/Lisa/TestCalculator.java
UTF-8
499
2.625
3
[]
no_license
package com.Lisa; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; import static org.mockito.Mockito.*; public class TestCalculator { Calculator objCalculator = null; CalculatorService service = mock(CalculatorService.class); @Before public void setUp(){ objCalculator = new Calculator(); } @Test public void testMyAdd(){ when(service.add(2,3)).thenReturn(5); assertEquals(5,objCalculator.myAdd(2,3)); } }
true
8ab97345f8f9deac8baa5ef18041e5e0744ee1d1
Java
Shahedrazavi/AP-Project-2021-Phase2
/src/main/java/listener/settings/ComboBoxListener.java
UTF-8
537
2.375
2
[ "MIT" ]
permissive
package listener.settings; import event.settings.ComboBoxEvent; import controller.settings.SettingsLogic; public class ComboBoxListener { private SettingsLogic logic; public ComboBoxListener() { logic = new SettingsLogic(); } public void eventOccurred(ComboBoxEvent event){ if (event.getCommand().equals("changeAccountType")){ logic.ChangeAccType(event); } if (event.getCommand().equals("changeLastSeen")) { logic.ChangeLastSeenType(event); } } }
true
c2a3a2bbaea947da7f5cdceadb897282070d2097
Java
RoboGameplays/TitansCraft-Launcher
/src/main/java/org/spoutcraft/launcher/skin/options/ImportOptions.java
UTF-8
15,574
1.8125
2
[]
no_license
package org.spoutcraft.launcher.skin.options; import net.titanscraft.launchercore.install.AvailablePackList; import net.titanscraft.launchercore.install.InstalledPack; import net.titanscraft.launchercore.install.user.UserModel; import net.titanscraft.launchercore.mirror.MirrorStore; import net.titanscraft.launchercore.restful.PackInfo; import net.titanscraft.launchercore.restful.PlatformConstants; import net.titanscraft.launchercore.restful.RestObject; import net.titanscraft.launchercore.restful.platform.PlatformPackInfo; import net.titanscraft.launchercore.restful.solder.SolderPackInfo; import net.titanscraft.launchercore.util.ResourceUtils; import net.titanscraft.launchercore.util.Utils; import net.titanscraft.launchercore.util.ZipUtils; import org.spoutcraft.launcher.skin.LauncherFrame; import org.spoutcraft.launcher.skin.components.ImageButton; import org.spoutcraft.launcher.skin.components.LiteButton; import org.spoutcraft.launcher.skin.components.LiteTextBox; import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.text.SimpleAttributeSet; import java.awt.*; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.event.*; import java.io.File; import java.io.IOException; import java.util.concurrent.ExecutionException; public class ImportOptions extends JDialog implements ActionListener, MouseListener, MouseMotionListener, DocumentListener { private static final long serialVersionUID = 1L; private static final String QUIT_ACTION = "quit"; private static final String IMPORT_ACTION = "import"; private static final String CHANGE_FOLDER = "folder"; private static final String PASTE_URL = "paste"; private static final String ESCAPE_ACTION = "escape"; private static final int FRAME_WIDTH = 520; private static final int FRAME_HEIGHT = 222; private JLabel msgLabel; private JLabel background; private LiteButton save; private LiteButton folder; private LiteButton paste; private LiteTextBox install; private JFileChooser fileChooser; private int mouseX = 0, mouseY = 0; private PackInfo info = null; private String url = ""; private Document urlDoc; private File installDir; private LiteTextBox urlTextBox; private AvailablePackList mPackList; private UserModel mUserModel; private MirrorStore mirrorStore; public ImportOptions(AvailablePackList packList, UserModel userModel, MirrorStore mirrorStore) { this.mPackList = packList; this.mUserModel = userModel; this.mirrorStore = mirrorStore; setTitle("Adicionar Modpack"); setSize(FRAME_WIDTH, FRAME_HEIGHT); addMouseListener(this); addMouseMotionListener(this); setResizable(false); setUndecorated(true); initComponents(); } public void initComponents() { Font minecraft = LauncherFrame.getMinecraftFont(12); KeyStroke escape = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false); Action escapeAction = new AbstractAction() { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { dispose(); } }; getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(escape, ESCAPE_ACTION); getRootPane().getActionMap().put(ESCAPE_ACTION, escapeAction); background = new JLabel(); background.setBounds(0, 0, FRAME_WIDTH, FRAME_HEIGHT); LauncherFrame.setIcon(background, "platformBackground.png", background.getWidth(), background.getHeight()); Container contentPane = getContentPane(); contentPane.setLayout(null); ImageButton optionsQuit = new ImageButton(ResourceUtils.getIcon("quit.png", 28, 28), ResourceUtils.getIcon("quit.png", 28, 28)); optionsQuit.setRolloverIcon(ResourceUtils.getIcon("quitHover.png", 28, 28)); optionsQuit.setBounds(FRAME_WIDTH - 38, 10, 28, 28); optionsQuit.setActionCommand(QUIT_ACTION); optionsQuit.addActionListener(this); msgLabel = new JLabel(); msgLabel.setBounds(10, 75, FRAME_WIDTH - 20, 25); msgLabel.setText("Coloque a URL do Modpack a baixo:"); msgLabel.setForeground(Color.white); msgLabel.setFont(minecraft); urlTextBox = new LiteTextBox(this, "Coloque a URL do Modpack aqui"); urlTextBox.setBounds(10, msgLabel.getY() + msgLabel.getHeight() + 5, FRAME_WIDTH - 115, 30); urlTextBox.setFont(minecraft); urlTextBox.getDocument().addDocumentListener(this); urlDoc = urlTextBox.getDocument(); save = new LiteButton("Adicionar Modpack"); save.setFont(minecraft.deriveFont(14F)); save.setBounds(FRAME_WIDTH - 145, FRAME_HEIGHT - 40, 135, 30); save.setActionCommand(IMPORT_ACTION); save.addActionListener(this); fileChooser = new JFileChooser(Utils.getLauncherDirectory()); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); folder = new LiteButton("Mudar Pasta"); folder.setFont(minecraft.deriveFont(14F)); folder.setBounds(FRAME_WIDTH - 290, FRAME_HEIGHT - 40, 135, 30); folder.setActionCommand(CHANGE_FOLDER); folder.addActionListener(this); paste = new LiteButton("Colar"); paste.setFont(minecraft.deriveFont(14F)); paste.setBounds(FRAME_WIDTH - 95, msgLabel.getY() + msgLabel.getHeight() + 5, 85, 30); paste.setActionCommand(PASTE_URL); paste.addActionListener(this); paste.setVisible(true); install = new LiteTextBox(this, ""); install.setBounds(10, FRAME_HEIGHT - 75, FRAME_WIDTH - 20, 25); install.setFont(minecraft.deriveFont(10F)); install.setEnabled(false); install.setVisible(false); enableComponent(save, false); enableComponent(folder, false); enableComponent(paste, true); contentPane.add(install); contentPane.add(optionsQuit); contentPane.add(msgLabel); contentPane.add(folder); contentPane.add(paste); contentPane.add(urlTextBox); contentPane.add(save); contentPane.add(background); setLocationRelativeTo(this.getOwner()); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof JComponent) { action(e.getActionCommand()); } } private void action(String action) { if (action.equals(QUIT_ACTION)) { dispose(); } else if (action.equals(CHANGE_FOLDER)) { int result = fileChooser.showOpenDialog(this); if (result == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); if (!ZipUtils.checkEmpty(file)) { install.setText("Por favor use uma pasta vazia."); return; } if (info.shouldForceDirectory() && file.getAbsolutePath().startsWith(Utils.getSettingsDirectory().getAbsolutePath())) { install.setText("Este pacote requer um diretório fora da " + Utils.getSettingsDirectory().getAbsolutePath()); return; } installDir = file; install.setText("Localização: " + installDir.getPath()); folder.setText("Mudar Pasta"); folder.setLocation(FRAME_WIDTH - 290, FRAME_HEIGHT - 40); enableComponent(save, true); } } else if (action.equals(IMPORT_ACTION)) { if (info != null) { InstalledPack pack = new InstalledPack(mirrorStore, info.getName(), true); pack.setInfo(info); mPackList.add(pack); dispose(); } } else if (action.equals(PASTE_URL)) { Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); Transferable clipData = clipboard.getContents(clipboard); if (clipData != null) { try { if (clipData.isDataFlavorSupported(DataFlavor.stringFlavor)) { String s = (String) (clipData.getTransferData(DataFlavor.stringFlavor)); urlDoc.remove(0, urlDoc.getLength()); urlDoc.insertString(0, s, new SimpleAttributeSet()); urlTextBox.setLabelVisible(false); } } catch (UnsupportedFlavorException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (BadLocationException e) { e.printStackTrace(); } } } } public void urlUpdated(Document doc) { try { final String url = doc.getText(0, doc.getLength()).trim(); if (url.isEmpty()) { msgLabel.setText("Coloque a URL da plataforma TitansCraft"); enableComponent(save, false); enableComponent(folder, false); enableComponent(install, false); info = null; this.url = ""; return; } if (matchUrl(url)) { msgLabel.setText("Tentando encontrar informações do Modpack..."); // Turn everything off while the data is being fetched enableComponent(urlTextBox, false); enableComponent(paste, false); enableComponent(install, false); enableComponent(folder, false); enableComponent(save, false); // fetch the info asynchronously SwingWorker<PlatformPackInfo, Void> worker = new SwingWorker<PlatformPackInfo, Void>() { @Override protected PlatformPackInfo doInBackground() throws Exception { return RestObject.getRestObject(PlatformPackInfo.class, url); } @Override public void done() { try { PlatformPackInfo result = get(); if (!result.hasSolder() && !(result.getUrl().startsWith("http://") || result.getUrl().startsWith("https://"))) { msgLabel.setText("Link de download do modpack invalido, procure informar esse erro ao dono do modpack."); return; } else { if (result.hasSolder()) { info = SolderPackInfo.getSolderPackInfo(result.getSolder(), result.getName(), mUserModel.getCurrentUser()); } else { info = result; } } System.out.println(info.getName()); msgLabel.setText("Modpack: " + info.getDisplayName()); ImportOptions.this.url = url; enableComponent(folder, true); enableComponent(install, true); if (info.shouldForceDirectory()) { install.setText("Este pacote requer um diretório fora da " + Utils.getSettingsDirectory().getAbsolutePath()); folder.setText("Selecionar"); folder.setLocation(FRAME_WIDTH - 145, FRAME_HEIGHT - 40); enableComponent(save, false); } else { installDir = new File(Utils.getLauncherDirectory(), info.getName()); install.setText("Localização: " + installDir.getPath()); enableComponent(save, true); } } catch (ExecutionException e) { msgLabel.setText("Resposta da plataforma a análise de erros"); enableComponent(save, false); enableComponent(folder, false); enableComponent(install, false); info = null; ImportOptions.this.url = ""; e.printStackTrace(); } catch (InterruptedException e) { // TODO Interrupted exception? e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); msgLabel.setText("Modpack tem Link solder inválido. Consulte autor do modpack."); } finally { // always turn these back on enableComponent(urlTextBox, true); enableComponent(paste, true); } } }; worker.execute(); } else { msgLabel.setText("URL fornecido pela Plataforma TitansCraft é inválido"); enableComponent(save, false); enableComponent(folder, false); enableComponent(install, false); info = null; this.url = ""; } } catch (BadLocationException e) { // This should never ever happen. // Java is stupid for not having a getAllText of some kind on the // Document class e.printStackTrace(); } } public boolean matchUrl(String url) { boolean result = false; result = (url.matches(PlatformConstants.MODPACK + "([a-zA-Z0-9-]+)") || result); return result; } public void enableComponent(JComponent component, boolean enable) { component.setEnabled(enable); component.setVisible(enable); } @Override public void mouseDragged(MouseEvent e) { this.setLocation(e.getXOnScreen() - mouseX, e.getYOnScreen() - mouseY); } @Override public void mouseMoved(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseClicked(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent e) { mouseX = e.getX(); mouseY = e.getY(); } @Override public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } @Override public void changedUpdate(DocumentEvent e) { urlUpdated(e.getDocument()); } @Override public void insertUpdate(DocumentEvent e) { urlUpdated(e.getDocument()); } @Override public void removeUpdate(DocumentEvent e) { urlUpdated(e.getDocument()); } }
true
d44a58951183b4bb9d80b1ca0e31e3d4c2280b08
Java
shanglun-t/Session-Analytics
/src/main/java/com/shangTsai/session_analytics/dao/ITaskDAO.java
UTF-8
240
1.976563
2
[]
no_license
package com.shangTsai.session_analytics.dao; import com.shangTsai.session_analytics.domain.Task; /** * * Task DAO Interface * @author shangluntsai * */ public interface ITaskDAO { Task findById(long task_id) throws Exception; }
true
a5cc8e3094ba69ac2f3d7bbee28afeaa5784ec4c
Java
liveqmock/hsxt
/hsxt/hsxt-tc/hsxt-tc-batchService/src/main/java/com/gy/hsxt/tc/batch/mapper/TcAccountDaysMapper.java
UTF-8
424
1.820313
2
[]
no_license
package com.gy.hsxt.tc.batch.mapper; import com.gy.hsxt.tc.batch.bean.TcAccountDays; public interface TcAccountDaysMapper { int deleteByPrimaryKey(Long accDaysId); int insert(TcAccountDays record); int insertSelective(TcAccountDays record); TcAccountDays selectByPrimaryKey(Long accDaysId); int updateByPrimaryKeySelective(TcAccountDays record); int updateByPrimaryKey(TcAccountDays record); }
true
5b57f06700191a6877c820977ede2960210431b0
Java
AL-Kaisi/Spring-JDBC-CRUD-Operation
/src/main/java/com/SpringJdbc/SpringJdbcApplication/EmployeeJdbcDAO.java
UTF-8
2,422
2.828125
3
[]
no_license
package com.SpringJdbc.SpringJdbcApplication; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Component; import org.springframework.dao.DataAccessException; import java.util.List; import java.util.Optional; @Component public class EmployeeJdbcDAO implements EmployeeDAOInterface<EmployeeDetails> { private JdbcTemplate jdbcTemplate; RowMapper<EmployeeDetails> rowMap = (result, num) -> { EmployeeDetails employees = new EmployeeDetails(); employees.setEmployeeId(result.getInt("employeeId")); employees.setFirstName(result.getString("firstName")); employees.setLastName(result.getString("lastName")); employees.setDesignation(result.getString("designation")); return employees; }; public EmployeeJdbcDAO(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } @Override public List<EmployeeDetails> list() { String query = "SELECT * FROM EmployeeDetails"; return jdbcTemplate.query(query, rowMap); } @Override public Optional<EmployeeDetails> getById(int id) { String query = "SELECT * FROM EmployeeDetails WHERE employeeId = ?"; EmployeeDetails employee = null; try { employee = jdbcTemplate.queryForObject(query, rowMap, id); } catch (DataAccessException dataAccessException) { System.out.println(dataAccessException); } return Optional.ofNullable(employee); } @Override public void addNewEmployee(EmployeeDetails employeeDetails) { String insertQuery = "INSERT INTO EmployeeDetails(firstName,lastName,Designation) " + "VALUES (?,?,?)"; jdbcTemplate.update(insertQuery, employeeDetails.getFirstName(), employeeDetails.getLastName(), employeeDetails.getDesignation()); } @Override public void updateEmployee(EmployeeDetails employeeDetails) { String updateQuery = "UPDATE EmployeeDetails SET firstName = ?, " + "lastName = ?, designation = ? where employeeId = ? "; jdbcTemplate.update(updateQuery, employeeDetails.getFirstName(), employeeDetails.getLastName(), employeeDetails.getDesignation(), employeeDetails.getEmployeeId()); } }
true
7ce22965641c68a5280414a304cae43ba2af5e0c
Java
ArthixFR/InfinityLib
/src/main/java/com/infinityraider/infinitylib/crafting/fallback/FallbackIngredient.java
UTF-8
5,806
2.140625
2
[ "MIT" ]
permissive
package com.infinityraider.infinitylib.crafting.fallback; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.infinityraider.infinitylib.InfinityLib; import com.infinityraider.infinitylib.crafting.IInfIngredientSerializer; import it.unimi.dsi.fastutil.ints.IntList; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.Ingredient; import net.minecraft.network.PacketBuffer; import net.minecraft.tags.ITag; import net.minecraft.tags.ItemTags; import net.minecraft.util.JSONUtils; import net.minecraft.util.ResourceLocation; import net.minecraftforge.common.crafting.CraftingHelper; import net.minecraftforge.common.crafting.IIngredientSerializer; import javax.annotation.Nullable; import java.util.stream.Stream; public class FallbackIngredient extends Ingredient { public static final ResourceLocation ID = new ResourceLocation(InfinityLib.instance.getModId(), "fallback"); public static final Serializer SERIALIZER = new Serializer(); private final ITag<Item> tag; private final Ingredient fallback; private Ingredient ingredient; public FallbackIngredient(ITag<Item> tag, Ingredient fallback) { super(Stream.empty()); this.tag = tag; this.fallback = fallback; } protected ITag<Item> getTag() { return this.tag; } protected Ingredient getFallback() { return this.fallback; } private Ingredient getActualIngredient() { if(this.ingredient == null) { if(this.getTag() != null && this.getTag().getAllElements().size() > 0) { this.ingredient = Ingredient.fromTag(this.getTag()); } else if (this.getFallback().hasNoMatchingItems()) { return EMPTY; } else { this.ingredient = getFallback(); } } return this.ingredient; } @Override public ItemStack[] getMatchingStacks() { return this.getActualIngredient().getMatchingStacks(); } @Override public boolean test(@Nullable ItemStack stack) { return this.getActualIngredient().test(stack); } @Override public IntList getValidItemStacksPacked() { return this.getActualIngredient().getValidItemStacksPacked(); } @Override public JsonElement serialize() { JsonObject rootJson = new JsonObject(); JsonObject ingredientJson = new JsonObject(); ResourceLocation rl = ItemTags.getCollection().getDirectIdFromTag(this.getTag()); ingredientJson.addProperty("tag", rl.toString()); ingredientJson.add("fallback", this.getFallback().serialize()); rootJson.add("ingredient", ingredientJson); rootJson.addProperty("type", InfinityLib.instance.getModId() + ":fallback"); return rootJson; } @Override public boolean hasNoMatchingItems() { return this.getActualIngredient().hasNoMatchingItems(); } @Override protected void invalidate() { this.ingredient = null; } @Override public boolean isSimple() { return this.getActualIngredient().isSimple(); } @Override public IIngredientSerializer<FallbackIngredient> getSerializer() { return SERIALIZER; } public static void registerSerializer() { } private static final class Serializer implements IInfIngredientSerializer<FallbackIngredient> { @Override public ResourceLocation getId() { return ID; } @Override public FallbackIngredient parse(PacketBuffer buffer) { boolean flag = buffer.readBoolean(); ITag<Item> tag = null; if(flag) { ResourceLocation rl = buffer.readResourceLocation(); tag = ItemTags.getCollection().getTagByID(rl); } Ingredient fallback = Ingredient.read(buffer); return new FallbackIngredient(tag, fallback); } @Override public FallbackIngredient parse(JsonObject json) { if(!json.has("ingredient")) { throw new JsonParseException("com.infinityraider.infinitylib.crafting.FallBackIngredient requires an ingredient element"); } JsonElement element = json.get("ingredient"); if(!(element instanceof JsonObject)) { throw new JsonParseException("com.infinityraider.infinitylib.crafting.FallBackIngredient expected an object for ingredient"); } JsonObject ingredientJson = (JsonObject) element; if(!ingredientJson.has("tag")) { throw new JsonParseException("com.infinityraider.infinitylib.crafting.FallBackIngredient requires a tag element"); } if(!ingredientJson.has("fallback")) { throw new JsonParseException("com.infinityraider.infinitylib.crafting.FallBackIngredient requires a fallback element"); } ResourceLocation rl = new ResourceLocation(JSONUtils.getString(ingredientJson, "tag")); ITag<Item> tag = ItemTags.getCollection().getTagByID(rl); Ingredient fallback = CraftingHelper.getIngredient(ingredientJson.get("fallback")); return new FallbackIngredient(tag, fallback); } @Override public void write(PacketBuffer buffer, FallbackIngredient ingredient) { ResourceLocation rl = ItemTags.getCollection().getDirectIdFromTag(ingredient.getTag()); boolean flag = rl != null; buffer.writeBoolean(flag); if(flag) { buffer.writeResourceLocation(rl); } ingredient.getFallback().write(buffer); } } }
true
c9311bf90501830b9c45a233709859db2666d8a5
Java
hewhlster/crm-ssm
/src/main/java/org/fjh/dao/CstServiceMapper.java
UTF-8
1,270
2.03125
2
[]
no_license
package org.fjh.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import org.fjh.entity.CstService; import org.fjh.entity.CstServiceExample; import org.fjh.entity.CstServiceWithBLOBs; public interface CstServiceMapper { long countByExample(CstServiceExample example); int deleteByExample(CstServiceExample example); int deleteByPrimaryKey(Long svrId); int insert(CstServiceWithBLOBs record); int insertSelective(CstServiceWithBLOBs record); List<CstServiceWithBLOBs> selectByExampleWithBLOBs(CstServiceExample example); List<CstService> selectByExample(CstServiceExample example); CstServiceWithBLOBs selectByPrimaryKey(Long svrId); int updateByExampleSelective(@Param("record") CstServiceWithBLOBs record, @Param("example") CstServiceExample example); int updateByExampleWithBLOBs(@Param("record") CstServiceWithBLOBs record, @Param("example") CstServiceExample example); int updateByExample(@Param("record") CstService record, @Param("example") CstServiceExample example); int updateByPrimaryKeySelective(CstServiceWithBLOBs record); int updateByPrimaryKeyWithBLOBs(CstServiceWithBLOBs record); int updateByPrimaryKey(CstService record); }
true