text
stringlengths
10
2.72M
package com.bytedance.sandboxapp.protocol.service.c; import android.app.Activity; import com.bytedance.sandboxapp.b.b; public interface a extends b { boolean canCheckFollowAwemeState(); void checkFollowAwemeState(String paramString1, String paramString2, c paramc); void getAwemeUidFromSuffixMeta(b paramb); boolean hasAwemeDepend(); boolean hasLogin(); void openAwemeUserProfile(Activity paramActivity, String paramString1, String paramString2, boolean paramBoolean, c paramc); } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\bytedance\sandboxapp\protocol\service\c\a.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package cn.wycclub.dto; import javax.validation.constraints.*; /** * 注册表单信息 * * @author WuYuchen * @create 2018-02-13 22:24 **/ public class RegisterForm { @Pattern(regexp = "^[a-zA-Z0-9]{5,10}$", message = "用户名为5位到10位之间的数字或字母!") private String username; @Pattern(regexp = "^[a-zA-Z\\d]{6,18}$", message = "密码必须为字母或数字(必须以字母开头)的6-18位!") private String password; @Pattern(regexp = "^(\\w)+(\\.\\w+)*@(\\w)+((\\.\\w{2,3}){1,3})$", message = "邮箱格式不对!") private String email; @Pattern(regexp = "^[a-zA-Z\\d]{6,18}$", message = "密码必须为字母或数字(必须以字母开头)的6-18位!") private String repassword; public String getRepassword() { return repassword; } public void setRepassword(String repassword) { this.repassword = repassword; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
package com.DataJpa; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Component; /** * Created by bakhodir on 5/13/16. */ @Component public interface BaseDao<T> extends CrudRepository<T, Long> { @Query("select u from #{#T} u where u.lastname = ?1") Iterable<T> findAll(); }
class MyPrint implements Runnable { @Override public void run() { System.out.print(Thread.currentThread().getName()+ " : "); for(char ch = 'g'; ch<='m'; ch++) { System.out.printf("%c",ch); } System.out.println(); } } public class PrintChar3 { public static void main(String[] args) { Thread th1 = new Thread(new MyPrint(),"스레드1"); Thread th2 = new Thread(new MyPrint(),"스레드2"); th1.start(); th2.start(); } }
package cn.com.ykse.santa.repository.entity; public class DemandFileCfgDO { private Integer cfgId; private Integer demandId; private Integer fileId; public Integer getCfgId() { return cfgId; } public void setCfgId(Integer cfgId) { this.cfgId = cfgId; } public Integer getDemandId() { return demandId; } public void setDemandId(Integer demandId) { this.demandId = demandId; } public Integer getFileId() { return fileId; } public void setFileId(Integer fileId) { this.fileId = fileId; } }
package com.store.pojo; /** * 分页对象 * @author 付军 * */ public class Page { //当前页 private int pageNo=1; //每页显示的条数 private int pageSize=5; //一共有多少条记录 private int allCount=1; //一共有多少页 需要计算的 private int totalPage=1; public int getPageNo() { //判断 if(pageNo<1) { pageNo=1; } return pageNo; } public void setPageNo(int pageNo) { this.pageNo = pageNo; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getAllCount() { return allCount; } public void setAllCount(int allCount) { this.allCount = allCount; } public int getTotalPage() { //获取总页数 // 总条数 +每页显示的条数 -1 除以 每页显示的条数 totalPage=(allCount+pageSize-1)/pageSize; return totalPage; } public void setTotalPage(int totalPage) { this.totalPage = totalPage; } }
package com.widera.petclinic.controller; import com.widera.petclinic.domain.entities.User; import com.widera.petclinic.service.OwnerService; import com.widera.petclinic.service.UserManagementService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationTrustResolver; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Controller public class LoginController { OwnerService ownerService; UserManagementService userService; AuthenticationTrustResolver authenticationTrustResolver; @Autowired public LoginController(OwnerService ownerService, UserManagementService userService, AuthenticationTrustResolver authenticationTrustResolver) { this.ownerService = ownerService; this.userService = userService; this.authenticationTrustResolver = authenticationTrustResolver; } @RequestMapping(value = "/signup", method = RequestMethod.GET) public String getCreateAccountForm(Model model){ User user = new User(); model.addAttribute("user", user); return "createAccountForm"; } @RequestMapping(value = "/signup", method = RequestMethod.POST) public String processCreateAccountForm(@ModelAttribute("user") User user) { userService.saveUser(user); return "redirect:/login"; } @RequestMapping(value = "/login", method = RequestMethod.GET) public String loginPage() { return "login"; } @RequestMapping(value="/logout", method = RequestMethod.GET) public String logoutPage (HttpServletRequest request, HttpServletResponse response) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth != null){ new SecurityContextLogoutHandler().logout(request, response, auth); } return "redirect:/login?logout"; } @RequestMapping(value = "/owner-data", method = RequestMethod.GET) public String getUserForm(){ if(isUserAnonymous()){ return "login"; } else { return "redirect:/home"; } } private boolean isUserAnonymous() { final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); return authenticationTrustResolver.isAnonymous(authentication); } }
package com.hxzy.mapper; import com.hxzy.entity.JobtableViews; /** * 作品浏览和点赞 */ public interface JobtableViewsMapper { int deleteByPrimaryKey(Integer jobTableId); int insert(JobtableViews record); JobtableViews selectByPrimaryKey(Integer jobTableId); int updateByPrimaryKeySelective(JobtableViews record); int updateByPrimaryKey(JobtableViews record); }
package woundsDetection; import javafx.event.EventHandler; import javafx.geometry.Rectangle2D; import javafx.scene.canvas.Canvas; import javafx.scene.input.MouseEvent; import javafx.scene.shape.Rectangle; import javafx.stage.FileChooser; import javafx.stage.Stage; import java.io.File; public class EventHandlerr { private static FileChooser fileChooser; //Method take a Canvas and specific area as rectangle coordinates //if mouse triggered on particular area it get image path from user //and return as string public static String openFile(String chooserTitle, Canvas canvas, Rectangle2D rectangle, final Stage stage){ final StringBuilder path=new StringBuilder(); canvas.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { //Check wheather user clicks on specified rectangl area double x=event.getX(); double y=event.getY(); if(x>=rectangle.getMinX() && x<=rectangle.getMaxX()&& y>=rectangle.getMinY() && y<=rectangle.getMaxY()){ fileChooser=new FileChooser(); fileChooser.setTitle(chooserTitle); fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("png","*.png"),new FileChooser.ExtensionFilter("jpg","*.jpg"),new FileChooser.ExtensionFilter("jpeg","*.jpeg")); File file =fileChooser.showOpenDialog(stage); if(file!=null){ path.append(file.getAbsolutePath()); } } } }); return path.toString(); } }
package pe.egcc.interesapp.service; import pe.egcc.interesapp.dto.InteresDto; public class InteresService { public InteresDto calculaImporteAcmulado(InteresDto interesDto) { double capital; double interes; double importeAcumulado; double tasaInteresMensual; double periodo; float resultado; capital = interesDto.getCapital(); interes = interesDto.getTasaInteres(); tasaInteresMensual = (interes / 100) / 12; periodo = interesDto.getPeriodo(); interes = capital * (Math.pow(1 + tasaInteresMensual, periodo)); importeAcumulado = interesDto.getCapital() + interes; interesDto.setImporteAcumulado(importeAcumulado); return interesDto; } }
package org.eginez; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.HashMap; import java.util.List; public class Problem4Test { @Test public void test2() { int sol = Problem4.coinsCount(31, Arrays.asList(1, 10, 25), new HashMap<>()); Assertions.assertEquals(4, sol); sol = Problem4.coinsCount(33, Arrays.asList(1, 10, 25), new HashMap<>()); Assertions.assertEquals(6, sol); } }
package com.softvilla.slmparentportal; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.github.aakira.expandablelayout.ExpandableRelativeLayout; /** * Created by Malik on 04/08/2017. */ public class ViewHolder_Fee extends RecyclerView.ViewHolder { CardView cv; TextView received, remaining, advance,issueDate, expireDate, submittedAt, arrears, fee; Button expBtn; ExpandableRelativeLayout expandLayout; //ImageView imageView; ViewHolder_Fee(View itemView) { super(itemView); cv = (CardView) itemView.findViewById(R.id.cardViewfee); received = (TextView) itemView.findViewById(R.id.recieved); remaining = (TextView) itemView.findViewById(R.id.remaining); advance = (TextView) itemView.findViewById(R.id.advance); issueDate = (TextView) itemView.findViewById(R.id.issuedate); submittedAt = (TextView) itemView.findViewById(R.id.submittedAt); arrears = (TextView) itemView.findViewById(R.id.arrears); fee = (TextView) itemView.findViewById(R.id.fee); expireDate = (TextView) itemView.findViewById(R.id.expiredate); expBtn = (Button) itemView.findViewById(R.id.lbs); expandLayout = (ExpandableRelativeLayout) itemView.findViewById(R.id.expandableLayout); //imageView = (ImageView) itemView.findViewById(R.id.circleView); } }
package com.example.dou.mysale; import android.app.ListActivity; import android.os.Bundle; import android.widget.ArrayAdapter; import java.util.ArrayList; import java.util.List; /** * Created by Dou on 2016/4/27. */ public class TicketActivity extends ListActivity { private List listItem; private ArrayAdapter<String> list; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); listItem = new ArrayList<String>(); listItem.add("我是抵用券"); listItem.add("我是抵用券"); listItem.add("我是抵用券"); listItem.add("我是抵用券"); listItem.add("我是抵用券"); listItem.add("我是抵用券"); //建立adapter,并且绑定数据源 list = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, listItem); //绑定UI setListAdapter(list); } }
import java.util.HashMap; import java.util.Scanner; public class MainERP { public static void main(String[] args) { Scanner teclado = new Scanner(System.in); int id,qtde; float preco; String nome; HashMap<Integer, Produto> mapa; mapa = new HashMap<Integer, Produto>(); int opcao; do { System.out.println("1 - Cadastro / 2 - Busca / -1 - Encerra"); opcao = Integer.parseInt(teclado.nextLine()); switch (opcao) { case 1: System.out.println("Digite id / nome / preco / qtde"); //leia do teclado e faça as devidas conversões id = Integer.parseInt(teclado.nextLine()); nome = teclado.nextLine(); preco = Float.parseFloat(teclado.nextLine()); qtde = Integer.parseInt(teclado.nextLine()); //cria um objeto do tipo "Produto" com os dados digitados Produto p = new Produto(id, nome, preco, qtde); //adiciona na lista mapa.put(p.getId(),p); break; case 2: System.out.println("---> Buscando Produtos <---"); System.out.println("Digite o ID:"); id = Integer.parseInt(teclado.nextLine()); // internamente o get calcula a posição baseada no valor de id e retorna // o objeto. Se a posição estiver vazia, retorna NULL Produto busca = mapa.get(id); if (busca == null) System.out.println(" *** Desculpe, produto não encontrado!"); else System.out.println("Encontrado! "+busca.getId()+" - "+busca.getTitulo()+" R$ "+busca.getPreco()+" | "+busca.getQtde()); break; case -1: System.out.println("Encerrando programa..."); break; default: System.out.println("Erro - Opção Invalida"); } } while (opcao != -1); teclado.close(); } }
import java.util.ArrayList; public class Passenger { String name; int numberOfBags; ArrayList<Flight> flight; int seatNumber; public Passenger(String name, int numberOfBags) { this.name = name; this.numberOfBags = numberOfBags; this.flight = new ArrayList<Flight>(); this.seatNumber = seatNumber; } public String getName() { return this.name; } public int getNumberOfBags() { return this.numberOfBags; } public Object getFlight() { return this.flight.get(0); } public void addFlight(Flight flight, int seatNumber) { this.flight.add(flight); this.seatNumber = seatNumber; } public int getSeatNumber(){ return this.seatNumber; } public int setSeatNumber(int seatNumber){ return this.seatNumber = seatNumber; } }
package com.NewIO; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class Test { }
package com.tencent.mm.plugin.wallet_core.ui; import android.app.Dialog; import android.content.Context; import android.view.View; import android.view.View.OnClickListener; import com.tencent.mm.g.a.le; import com.tencent.mm.plugin.wallet_core.model.ECardInfo; import com.tencent.mm.sdk.b.a; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.wallet_core.ui.e; import java.lang.ref.WeakReference; class k$9 implements OnClickListener { final /* synthetic */ Dialog nmd; final /* synthetic */ ECardInfo pvF; final /* synthetic */ Context val$context; public k$9(ECardInfo eCardInfo, Context context, Dialog dialog) { this.pvF = eCardInfo; this.val$context = context; this.nmd = dialog; } public final void onClick(View view) { x.i("MicroMsg.WalletIdCardTip", "go to: %s", new Object[]{Integer.valueOf(this.pvF.pne)}); if (this.pvF.pne == 1) { e.l(this.val$context, this.pvF.ceh, false); } else { le leVar = new le(); leVar.bVx.YC = new WeakReference(this.val$context); a.sFg.m(leVar); } if (this.nmd != null && this.nmd.isShowing()) { this.nmd.dismiss(); } } }
public class LinkedList { private ListNode head = null; private ListNode tail = null; private int n = 0; public Object get(int i) { if (i<0 || i>=n) { return null; } ListNode node = head; for (int j=0; j<i; j++) { node = node.next; } return node.element; } public void insert(Object o, int i) { if (i<0 || i>n) { return; } if (i==0) { addFirst(o); return; } if (i==n){ add(o); return; } ListNode node = head; for (int j=0; j<i-1; j++){ node = node.next; } node.next = new ListNode(o, node.next); n++; } public void remove(int i) { if (i<0 || i>=n){ return; } if (i==0) { head = head.next; if (n==1) { tail = null; } n--; return; } ListNode node = head; for (int j=0; j<i-1; j++){ node = node.next; } node.next = node.next.next; if (i==n-1){ tail = node; } n--; } public void addFirst(Object o) { if (head==null) { head = new ListNode (o, null); tail = head; n++; return; } head = new ListNode (o, head); n++; } public void add(Object o) { if (n==0){ addFirst(o); return; } ListNode node = new ListNode(o, null); tail.next = node; tail = node; n++; } }
package com.kingcar.rent.pro.utils; import org.json.JSONObject; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.security.KeyFactory; import java.security.PrivateKey; import java.security.spec.PKCS8EncodedKeySpec; /** * Created by cwj on 2016/3/18. */ public class AliPaySignUtil { //商户PID private static String PARTNER = "2088611974864105"; //商户收款账号 private static String SELLER = ""; //商户私钥,pkcs8格式 private static String RSA_PRIVATE = ""; //支付结果通知 private static String NOTIFY_URL; private static final String ALGORITHM = "RSA"; private static final String SIGN_ALGORITHMS = "SHA1WithRSA"; private static final String DEFAULT_CHARSET = "UTF-8"; public static String sign(String content) { try { PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec( Base64.decode(RSA_PRIVATE)); KeyFactory keyf = KeyFactory.getInstance(ALGORITHM,"BC"); PrivateKey priKey = keyf.generatePrivate(priPKCS8); java.security.Signature signature = java.security.Signature .getInstance(SIGN_ALGORITHMS); signature.initSign(priKey); signature.update(content.getBytes(DEFAULT_CHARSET)); byte[] signed = signature.sign(); return Base64.encode(signed); } catch (Exception e) { e.printStackTrace(); } return null; } /** 创建订单信息*/ public static String getOrderInfo(JSONObject jsonObject) { RSA_PRIVATE=RSA_PRIVATE.replaceAll("\n",""); PARTNER = jsonObject.optString("mer_id"); SELLER = jsonObject.optString("seller_account_name"); RSA_PRIVATE = jsonObject.optString("key"); NOTIFY_URL = jsonObject.optString("callback_url"); String orderid=jsonObject.optString("payment_id"); String subject=jsonObject.optString("shopName")+jsonObject.optString("payment_id"); String body=jsonObject.optString("body"); String price="0.00"; if(jsonObject.has("cur_money")){ price=jsonObject.optString("cur_money"); }else if(jsonObject.has("total_amount")){ price=jsonObject.optString("total_amount"); } // 签约合作者身份ID String orderInfo = "partner=" + "\"" + PARTNER + "\""; // 签约卖家支付宝账号 orderInfo += "&seller_id=" + "\"" + SELLER + "\""; // 商户网站唯一订单号 // orderInfo += "&out_trade_no=" + "\"" + getOutTradeNo() + "\""; orderInfo += "&out_trade_no=" + "\"" + orderid + "\""; // 商品名称 orderInfo += "&subject=" + "\"" + subject + "\""; // 商品详情 orderInfo += "&body=" + "\"" + body + "\""; // 商品金额 orderInfo += "&total_fee=" + "\"" + price + "\""; // 服务器异步通知页面路径 // orderInfo += "&notify_url=" + "\"" + "http://notify.msp.hk/notify.htm" // + "\""; // 服务器异步通知页面路径 orderInfo += "&notify_url=" + "\"" + NOTIFY_URL + "\""; // 服务接口名称, 固定值 orderInfo += "&service=\"mobile.securitypay.pay\""; // 支付类型, 固定值 orderInfo += "&payment_type=\"1\""; // 参数编码, 固定值 orderInfo += "&_input_charset=\"utf-8\""; // 设置未付款交易的超时时间 // 默认30分钟,一旦超时,该笔交易就会自动被关闭。 // 取值范围:1m~15d。 // m-分钟,h-小时,d-天,1c-当天(无论交易何时创建,都在0点关闭)。 // 该参数数值不接受小数点,如1.5h,可转换为90m。 orderInfo += "&it_b_pay=\"30m\""; // extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付 // orderInfo += "&extern_token=" + "\"" + extern_token + "\""; // 支付宝处理完请求后,当前页面跳转到商户指定页面的路径,可空 orderInfo += "&return_url=\"m.alipay.com\""; // 调用银行卡支付,需配置此参数,参与签名, 固定值 (需要签约《无线银行卡快捷支付》才能使用) // orderInfo += "&paymethod=\"expressGateway\""; /** * 特别注意,这里的签名逻辑需要放在服务端,切勿将私钥泄露在代码中! */ String sign = sign(orderInfo); try { /** * 仅需对sign 做URL编码 */ sign = URLEncoder.encode(sign, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } /** * 完整的符合支付宝参数规范的订单信息 */ String payInfo = orderInfo + "&sign=\"" + sign + "\"&" + getSignType(); return payInfo; } /** * get the sign type we use. 获取签名方式 * */ public static String getSignType() { return "sign_type=\"RSA\""; } }
package Kodluyoruz_HomeWork_AbdAlrahimZakaria.Week3_AirplaneSystem.Concrete_Classes; import Kodluyoruz_HomeWork_AbdAlrahimZakaria.Week3_AirplaneSystem.Abstract_Classes.FlightTicketSystem; public class THYAirLines extends FlightTicketSystem { public static void main(String[] args) { THYAirLines THY = new THYAirLines(); THY.setSeatsNumber(); System.out.println("Welcome to THY Airlines system!"); THY.createTicket(); } }
package com.atguigu.boot.bean; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; @NoArgsConstructor @AllArgsConstructor @Data @ToString public class Pet { private Integer age; private String name; }
package nodomain.cleversort.time; public class StopWatch { private StopWatchService stopWatchService; private long startTime; public void start() { startTime = stopWatchService.getNanoCounterValue(); } public long calculateElapsedTimeInMilliSeconds() { return (stopWatchService.getNanoCounterValue() - startTime) / 1000; } StopWatch(StopWatchService stopWatchService) { this.stopWatchService = stopWatchService; } }
package org.quarkchain.web3j.protocol.core.response; import java.math.BigInteger; import org.quarkchain.web3j.protocol.core.Response; import org.quarkchain.web3j.utils.Numeric; /** * eth_gasPrice */ public class GasPrice extends Response<String> { public BigInteger getGasPrice() { return Numeric.decodeQuantity(getResult()); } }
package com.leetcode.oj; import java.util.Stack; // 114 https://leetcode.com/problems/flatten-binary-tree-to-linked-list/ public class FlattenBinaryTreeToLinkedList_114 { // Definition for a binary tree node. public static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } //recursive public void flatten(TreeNode root) { if(root==null){ return; } flatten(root.left); flatten(root.right); if(root.left==null){ return; } TreeNode p = root.left; while(p.right!=null){ p = p.right; } p.right = root.right; root.right = root.left; root.left = null; } //stack public void flatten_0(TreeNode root) { if(root==null){ return; } TreeNode dummy = new TreeNode(-1); TreeNode prev = dummy; Stack<TreeNode> stack = new Stack<TreeNode>(); stack.push(root); while(!stack.isEmpty()){ TreeNode p = stack.pop(); prev.right = p; prev.left = null; prev = prev.right; if(p.right!=null){ stack.push(p.right); } if(p.left!=null){ stack.push(p.left); } } } public static void main(String[] args) { // TODO Auto-generated method stub TreeNode two = new TreeNode(2); TreeNode one = new TreeNode(1); one.left = two; new FlattenBinaryTreeToLinkedList_114().flatten(one); } }
package com.feicui.edu.eshop.feature.category; import android.view.View; import android.widget.TextView; import com.feicui.edu.eshop.R; import com.feicui.edu.eshop.base.utils.BaseListAdapter; import com.feicui.edu.eshop.network.entity.CategoryPrimary; import butterknife.BindView; /** * Created by Administrator on 2017/2/25 0025. */ public class CategoryAdapter extends BaseListAdapter<CategoryPrimary, CategoryAdapter.ViewHolder> { @Override protected ViewHolder getItemViewHolder(View view) { return new ViewHolder(view); } @Override protected int getItemViewLayout() { return R.layout.item_primary_category; } class ViewHolder extends BaseListAdapter.ViewHolder { @BindView(R.id.text_category) TextView textCategory; public ViewHolder(View itemView) { super(itemView); } @Override public void bind(int position) { textCategory.setText(getItem(position).getName()); } } }
package decorator.design.pattern.example1; public abstract class Beverage { String description; public String getDescription(){ return description; } public abstract float getCost(); }
package pl.edu.amu.datasupplier.resource; import org.bson.types.ObjectId; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.mockito.MockitoAnnotations; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import pl.edu.amu.datasupplier.config.SpringUnitTest; import pl.edu.amu.datasupplier.model.TestCaseTemplate; import pl.edu.amu.datasupplier.model.Vacancy; import pl.edu.amu.datasupplier.service.TestCaseTemplateService; import java.time.LocalDateTime; import java.util.Arrays; import java.util.HashMap; import java.util.Optional; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.notNullValue; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @WebMvcTest(TestCaseTemplateController.class) @TestInstance(TestInstance.Lifecycle.PER_CLASS) class TestCaseTemplateControllerTest extends SpringUnitTest { @Autowired private MockMvc mockMvc; @Autowired private ModelMapper modelMapper; @MockBean private TestCaseTemplateService service; private TestCaseTemplate testCaseTemplate; @BeforeAll public void setup() { MockitoAnnotations.initMocks(this); this.mockMvc = MockMvcBuilders.standaloneSetup(new TestCaseTemplateController(modelMapper, service)).build(); HashMap<String, String> testData = new HashMap<>(); testData.put("limit", "@limit.value"); Vacancy vacancy = new Vacancy(Arrays.asList("internet", "transaction", "settings")); testCaseTemplate = new TestCaseTemplate(); testCaseTemplate.setId(new ObjectId("5a9da9efab4017359f1eaa26")); testCaseTemplate.setName("Set up transaction limit."); testCaseTemplate.setGroup("android.transaction.domestic"); testCaseTemplate.setTags(Arrays.asList("web", "settings", "transaction", "limit")); testCaseTemplate.setSteps(Optional.of(Arrays.asList("Login to website", "go to setting cart", "set up new transaction limit", "logout"))); testCaseTemplate.setData(testData); testCaseTemplate.setVacancies(Arrays.asList(vacancy)); testCaseTemplate.setLastModifiedDate(LocalDateTime.now()); testCaseTemplate.setCreatedDate(LocalDateTime.now()); } @Test void Should_ReturnNewUser_When_ValidData() throws Exception { System.out.println("Return new user"); HashMap<String, String> testData = new HashMap<>(); testData.put("limit", "@limit.value"); Vacancy vacancy = new Vacancy(Arrays.asList("internet", "transaction", "settings")); TestCaseTemplate testCaseTemplateToSave = new TestCaseTemplate(); testCaseTemplateToSave.setName("Set up transaction limit."); testCaseTemplateToSave.setGroup("android.transaction.domestic"); testCaseTemplateToSave.setTags(Arrays.asList("web", "settings", "transaction", "limit")); testCaseTemplateToSave.setData(testData); testCaseTemplateToSave.setVacancies(Arrays.asList(vacancy)); String postBody = "{\"name\":\"Set up transaction limit.\", " + "\"group\":\"android.transaction.domestic\"," + "\"tags\": [\"web\",\"settings\", \"transaction\", \"limit\"]," + "\"data\": {\"limit\":\"@limit.value\"}, " + "\"vacancies\":[{\"roles\":[\"internet\",\"transaction\", \"settings\"]}]}"; when(service.save(testCaseTemplateToSave)).thenReturn(testCaseTemplate); this.mockMvc.perform(post("/api/testCaseTemplates").accept(MediaType.APPLICATION_JSON_UTF8_VALUE) .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE).content(postBody)) .andDo(print()) .andExpect(status().isOk()) .andExpect(jsonPath("$.id", notNullValue())) .andExpect(jsonPath("$.tags", hasSize(4))); } @Test void Should_ReturnUpdateUser_When_ValidUser() throws Exception { System.out.println("Update user"); HashMap<String, String> testData = new HashMap<>(); testData.put("limit", "@limit.value"); Vacancy vacancy = new Vacancy(Arrays.asList("internet", "transaction", "settings")); TestCaseTemplate testCaseTemplateToUpdate = new TestCaseTemplate(); testCaseTemplateToUpdate.setId(new ObjectId("5a9da9efab4017359f1eaa26")); testCaseTemplateToUpdate.setName("Set up transaction limit."); testCaseTemplateToUpdate.setGroup("android.transaction.domestic"); testCaseTemplateToUpdate.setTags(Arrays.asList("web", "settings", "transaction", "limit")); testCaseTemplateToUpdate.setData(testData); testCaseTemplateToUpdate.setVacancies(Arrays.asList(vacancy)); String postBody = "{\"id\": \"5a9da9efab4017359f1eaa26\", \"name\":\"Set up transaction limit.\", " + "\"group\":\"android.transaction.domestic\"," + "\"tags\": [\"web\",\"settings\", \"transaction\", \"limit\"]," + "\"data\": {\"limit\":\"@limit.value\"}, " + "\"vacancies\":[{\"roles\":[\"internet\",\"transaction\", \"settings\"]}]}"; when(service.update(testCaseTemplateToUpdate)).thenReturn(testCaseTemplate); this.mockMvc.perform(put("/api/testCaseTemplates").accept(MediaType.APPLICATION_JSON_UTF8_VALUE) .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE).content(postBody)) .andDo(print()) .andExpect(status().isOk()) .andExpect(jsonPath("$.id", notNullValue())) .andExpect(jsonPath("$.tags", hasSize(4))); } @Test void Should_ReturnTestCaseTemplate_When_ValidObjectId() throws Exception { System.out.println("Get testCaseTemplate by id."); when(service.findById(new ObjectId("5a9da9efab4017359f1eaa26"))).thenReturn(testCaseTemplate); this.mockMvc.perform(get("/api/testCaseTemplates/5a9da9efab4017359f1eaa26").contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andDo(print()) .andExpect(status().isOk()) .andExpect(jsonPath("$.id", notNullValue())) .andExpect(jsonPath("$.tags", hasSize(4))); } @Test void Should_ReturnTestCaseTemplates_When_ValidTags() throws Exception { System.out.println("Get testCaseTemplates by tags."); when(service.findByTags(Optional.of(Arrays.asList("limit", "settings")))).thenReturn(Arrays.asList(testCaseTemplate)); this.mockMvc.perform(get("/api/testCaseTemplates?tags=limit,settings").contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andDo(print()) .andExpect(status().isOk()) .andExpect(jsonPath("$", hasSize(1))) .andExpect(jsonPath("$.[0].id", notNullValue())) .andExpect(jsonPath("$.[0].tags", hasSize(4))); } }
package com.cnk.travelogix.presales.core.interceptors; import de.hybris.platform.servicelayer.interceptor.InterceptorContext; import de.hybris.platform.servicelayer.interceptor.InterceptorException; import de.hybris.platform.servicelayer.interceptor.ValidateInterceptor; import de.hybris.platform.util.localization.Localization; import org.apache.log4j.Logger; import com.cnk.travelogix.presales.core.service.AssuredBusinessService; import com.cnk.travelogix.presales.model.AssuredBusinessModel; /** * Validate Intercepter to validate from and To Date. */ public class AssuredBusinessValidateInterceptor implements ValidateInterceptor<AssuredBusinessModel> { private AssuredBusinessService assuredBusinessService; private static final Logger LOG = Logger.getLogger(AssuredBusinessValidateInterceptor.class.getName()); @Override public void onValidate(final AssuredBusinessModel assuredBusinessModel, final InterceptorContext ctx) throws InterceptorException { if (LOG.isDebugEnabled()) { LOG.info("Inside onValidate() of AssuredBusinessValidateInterceptor"); } final boolean isToDateCorrect = assuredBusinessService.validateToDate(assuredBusinessModel); if (!isToDateCorrect) { throw new InterceptorException(Localization.getLocalizedString("assuredBusinessDetails.validTo.error")); } if (LOG.isDebugEnabled()) { LOG.info("End onValidate() of AssuredBusinessValidateInterceptor"); } } /** * @return the assuredBusinessService */ public AssuredBusinessService getAssuredBusinessService() { return assuredBusinessService; } /** * @param assuredBusinessService * the assuredBusinessService to set */ public void setAssuredBusinessService(final AssuredBusinessService assuredBusinessService) { this.assuredBusinessService = assuredBusinessService; } }
/* * 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 edufarming; import java.awt.Desktop; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ResourceBundle; import javafx.application.Platform; import javafx.embed.swing.SwingFXUtils; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.MenuItem; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.image.ImageView; import javafx.scene.text.Text; import javafx.stage.Stage; import javax.imageio.ImageIO; /** * FXML Controller class * * @author Study */ public class InfoDisplayController implements Initializable { @FXML private TextArea text_Area_farm; @FXML private Button next; @FXML private Button prev; @FXML private Button back_btn; String descrip; java.sql.Connection conn = null; @FXML private TextArea descriptionArea; @FXML private ImageView cropAninName; String lasName=""; String firsName=""; @FXML private Text txt_DisplayName; @FXML private MenuItem hm_page; @FXML private MenuItem expfarmLogout_btn; @FXML private MenuItem expFarmExit_btn; @FXML private MenuItem expOnlRes_menu; /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { // TODO } @FXML private void nextPage(ActionEvent event) { } @FXML private void prevPage(ActionEvent event) { } @FXML private void backOpt(ActionEvent event) throws IOException { Stage stage = (Stage) back_btn.getScene().getWindow(); FXMLLoader fxmlloader = new FXMLLoader(getClass().getResource("experience_farmer.fxml")); Parent root2 = (Parent) fxmlloader.load(); Scene scene1 = new Scene(root2); stage.setScene(scene1); Experience_farmerController ef = fxmlloader.<Experience_farmerController>getController(); ef.passOnInfo(firsName, lasName); ef.setUsername(); stage.show(); } public void setDescription(String data) { descrip = data; try { Class.forName("com.mysql.jdbc.Driver"); conn = java.sql.DriverManager.getConnection( "jdbc:mysql://localhost/ICP?user=root&password=root"); System.out.println("Connection established"); java.sql.Statement s = conn.createStatement(); java.sql.ResultSet r = s.executeQuery("SELECT * FROM information WHERE description like " + "'%" + data + "%'"); while (r.next()) { String info = r.getString("cropName").toUpperCase() + "\n\nPlanting:\n\n" + r.getString("planting") + "\n\nNuture/Care:\n\n" + r.getString("care") + "\n\nPest and Disease:\n\n" + r.getString("pest_diseases") + "\n\nHarvest and Storage:\n\n" + r.getString("harvest_storage"); text_Area_farm.setText(info); descriptionArea.setText("\n" + r.getString("description")); cropAninName.setImage(SwingFXUtils.toFXImage(ImageIO.read(r.getBlob("image").getBinaryStream()), null)); } //System.out.println(farming); } catch (Exception e) { System.out.println(e); } } public void passOnInfo(String fName, String lName) { lasName = lName; firsName = fName; } @FXML private void goToHomePaage(ActionEvent event) throws IOException { Stage stage = (Stage) back_btn.getScene().getWindow(); Parent root2 = FXMLLoader.load(getClass().getResource("experience_farmer.fxml")); Scene scene1 = new Scene(root2); scene1.getStylesheets().add("myCSS.css"); stage.setScene(scene1); stage.show(); } @FXML private void logoutFromMenu(ActionEvent event) throws IOException { Stage stage =(Stage) back_btn.getScene().getWindow(); FXMLLoader fxmlLoad = new FXMLLoader(getClass().getResource("FXMLDocument.fxml")); Parent root2 = (Parent) fxmlLoad.load(); Scene scene1 = new Scene(root2); scene1.getStylesheets().add("myCSS.css"); stage.setScene(scene1); stage.show(); } @FXML private void exitFromMenu(ActionEvent event) { Platform.exit(); } @FXML private void goOnline(ActionEvent event) throws URISyntaxException, IOException { Desktop desktop = Desktop.getDesktop(); desktop.browse(new URI("http://almanac.com/plants")); } }
package com.wb.cloud.entitles; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; /** * @ClassName : CommonResult * @Author : 王斌 * @Date : 2020-11-18 09:37 * @Description * @Version */ @Data @NoArgsConstructor @AllArgsConstructor @Builder public class CommonResult<T> { private long code; private String message; private T data; public CommonResult(long code, String message) { this.code = code; this.message = message; } }
package com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.builder; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.ArbeitsvorgangTypType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.SPALTENSolldatenType; import java.io.StringWriter; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.namespace.QName; public class SPALTENSolldatenTypeBuilder { public static String marshal(SPALTENSolldatenType sPALTENSolldatenType) throws JAXBException { JAXBElement<SPALTENSolldatenType> jaxbElement = new JAXBElement<>(new QName("TESTING"), SPALTENSolldatenType.class , sPALTENSolldatenType); StringWriter stringWriter = new StringWriter(); return stringWriter.toString(); } private Integer anzahlStreifen; private Boolean geaendertKz; private ArbeitsvorgangTypType arbeitsvorgang; public SPALTENSolldatenTypeBuilder setAnzahlStreifen(Integer value) { this.anzahlStreifen = value; return this; } public SPALTENSolldatenTypeBuilder setGeaendertKz(Boolean value) { this.geaendertKz = value; return this; } public SPALTENSolldatenTypeBuilder setArbeitsvorgang(ArbeitsvorgangTypType value) { this.arbeitsvorgang = value; return this; } public SPALTENSolldatenType build() { SPALTENSolldatenType result = new SPALTENSolldatenType(); result.setAnzahlStreifen(anzahlStreifen); result.setGeaendertKz(geaendertKz); result.setArbeitsvorgang(arbeitsvorgang); return result; } }
package com.cs4125.bookingapp.ui.main; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.navigation.NavController; import androidx.navigation.Navigation; import androidx.navigation.fragment.NavHostFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import com.cs4125.bookingapp.R; public class MainFragment extends Fragment { private MainViewModel mainViewModel; private NavController navController; // private Button bookBtn; // can be used later for viewing user's bookings private Button searchBtn; private int userId; public static MainFragment newInstance() { return new MainFragment(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.main_fragment, container, false); configureUiItems(view); userId = MainFragmentArgs.fromBundle(getArguments()).getUserId(); return view; } private void configureUiItems(View view) { bindUiItems(view); NavHostFragment navHostFragment = (NavHostFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment); navController = navHostFragment.getNavController(); searchBtn.setOnClickListener(view1 -> goToSearchScreen()); //bookBtn.setOnClickListener(view1 -> goToBookingScreen()); } private void bindUiItems(View view){ searchBtn = view.findViewById(R.id.toSearchBtn); // bookBtn = view.findViewById(R.id.toBookingBtn); } private void goToSearchScreen(){ MainFragmentDirections.ActionMainFragmentToSearchFragment action = MainFragmentDirections.actionMainFragmentToSearchFragment(userId); navController.navigate(action); } // private void goToBookingScreen(){ // MainFragmentDirections.ActionMainFragmentToBookingFragment action = MainFragmentDirections.actionMainFragmentToBookingFragment(userId); // navController.navigate(action); // } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); } }
package com.aummn.suburb.validator; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import org.junit.Test; import org.junit.runner.RunWith; import static org.assertj.core.api.Assertions.assertThat; @RunWith(JUnitParamsRunner.class) public class SuburbValidatorJUnitParamsTest { @Test @Parameters({ "melbourne, true", "mel2, true", "Chris'park, true", "Chris-park, true", "mel2_222, false", " m, true", ", false", "mel2 syd qld, true", " perth underline's park , true", "mel2 syd qld-, true", " perth underlineP1 @, false" }) public void shouldReturnSuburbNameIsValid(String suburbName, boolean isValid) { FieldValidationResult result = SuburbValidator.validateSuburbName(suburbName); assertThat(result.isValid()).isEqualTo(isValid); } @Test @Parameters({ "1000, true", "20, false", "Chris'park, false", "Chris-park, false", "mel2_222, false", "m, false", ", false", "10001, false", " 2000, true", " 20020, false", " 20 , false", " 2090 , true", " 20 01, false" }) public void shouldReturnPostcodeIsValid(String postcode, boolean isValid) { FieldValidationResult result = SuburbValidator.validatePostcode(postcode); assertThat(result.isValid()).isEqualTo(isValid); } @Test @Parameters({ "1000, true", "20, true", "10001, true", " 2000, true", " 20020, true", " 20 , true", " 2090 , true", "-1, false", "0, false" }) public void shouldReturnSuburbIdIsValid(Long id, boolean isValid) { FieldValidationResult result = SuburbValidator.validateSuburbId(id); assertThat(result.isValid()).isEqualTo(isValid); } }
package com.spring.JunitTest; public class Calculator { public double sum(double n1, double n2) { return n1 + n2; } }
package com.studio.saradey.aplicationvk.ui.fragment; /** * @author jtgn on 15.08.2018 */ import android.os.Bundle; import android.preference.PreferenceFragment; import com.studio.saradey.aplicationvk.R; public class MyPreferencesFragment extends PreferenceFragment { public MyPreferencesFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); } }
package evm.dmc.core.api.back; /** * Interface allows implementations to be plotted on chart * * @author id23cat * */ public interface Plottable { default double[] plot(int index) { return null; } default int getElementsCount() { return -1; } default String getTitle(int index) { return null; } }
package com.ciphertext.implementation; import com.ciphertext.decrypt.Decryptor; import com.ciphertext.encrypt.Encryptor; import com.ciphertext.input.StringIO; import com.ciphertext.interfaces.CipherInterface; public class CipherTextImplementation { public static void main(String[] args) { System.out.println("Cipher Texts"); while (true) { StringIO input = new StringIO(); input.getUserInput(); CipherInterface encryptdecrypt; if (input.isEncrypt()) { encryptdecrypt = new Encryptor(input); encryptdecrypt.constructMatrix(); encryptdecrypt.getResultFromMatrix(); System.out.println("Encrypted String is: " + encryptdecrypt.getInput().getOutput()); } else if (input.isDecrypt()) { encryptdecrypt = new Decryptor(input); encryptdecrypt.constructMatrix(); encryptdecrypt.getResultFromMatrix(); System.out.println("Decrypted String is: " + encryptdecrypt.getInput().getOutput()); } } } }
package com.brainmentors.apps.jdbcexample; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; @Repository public class UserDAO { @Autowired private JdbcTemplate jdbcTemplate; public UserDTO login(UserDTO user) { return null; } public boolean register(UserDTO user) { return false; } }
package productimporter; import java.util.ArrayList; import java.util.List; public final class ProductInventorySpy implements ProductInventory { private ArrayList<Product> log; public ProductInventorySpy() { log = new ArrayList<Product>(); } public ArrayList<Product> getLog() { return log; } @Override public void upsertProduct(Product product) { log.add(product); } }
package com.tencent.mm.ai; import com.tencent.mm.ai.c.4; import com.tencent.mm.model.am.b.a; import com.tencent.mm.sdk.platformtools.bi; class c$4$1 implements Runnable { final /* synthetic */ String bAA; final /* synthetic */ String dSW; final /* synthetic */ boolean dSX; final /* synthetic */ 4 dSY; c$4$1(4 4, String str, String str2, boolean z) { this.dSY = 4; this.bAA = str; this.dSW = str2; this.dSX = z; } public final void run() { a aVar = (a) this.dSY.dST.dSL.remove(this.bAA); a aVar2 = bi.oW(this.dSW) ? null : (a) this.dSY.dST.dSL.remove(this.dSW); if (aVar != null) { aVar.x(this.bAA, this.dSX); } if (aVar2 != null && !bi.oW(this.dSW)) { aVar2.x(this.dSW, this.dSX); } } }
package com.bmb.test; import com.basic.icon.IconBase; import com.basic.view.screen.SplashScreen; import com.global.App; import com.jgoodies.looks.*; import com.jgoodies.looks.windows.WindowsLookAndFeel; import com.mlm.comp.impl.WindowMlm; import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal; import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; import javax.swing.*; import java.awt.*; public class Main { public static void main(String[] args) { m1(); } public static void m1() { long t1 = System.currentTimeMillis(); try { UIManager .setLookAndFeel("com.jgoodies.looks.windows.WindowsLookAndFeel"); UIManager.put("Tree.leafIcon", IconBase.TREEP); UIManager.put("Tree.openIcon", IconBase.TREEO); UIManager.put("Tree.closedIcon", IconBase.TREEA); UIManager.put("TaskPaneContainer.useGradient", Boolean.FALSE); UIManager.put("TaskPaneContainer.background", Color.WHITE); UIManager.put("TaskPane.titleForeground", Color.WHITE); UIManager.put("TaskPane.titleOver", Color.LIGHT_GRAY.darker()); UIManager.put("TaskPane.background", Color.WHITE); UIManager.put("TaskPane.titleBackgroundGradientStart", Color.BLACK); UIManager.put("TaskPane.titleBackgroundGradientEnd", Color.BLACK); UIManager.put("SplitPaneDivider.border", App.borderBlackKananKiri); UIManager.put("SplitPaneDivider.draggingColor", App.aqua); UIManager.put("SplitPane.background", Color.WHITE); UIDefaults ui = UIManager.getLookAndFeelDefaults(); ui.put("PopupMenuSeparator.background", Color.RED); ui.put("Menu.background", Color.WHITE); ui.put("OptionPane.background", Color.WHITE); ui.put("MenuBar.opaque", true); ui.put("Panel.background", Color.WHITE); ui.put("RootPane.background", Color.WHITE); ui.put("DesktopPane.background", Color.WHITE); ui.put("Menu.opaque", true); ui.put("Menu.foreground", Color.BLACK); ui.put("TabbedPane.background", Color.WHITE); UIManager.put("jgoodies.popupDropShadowEnabled", Boolean.TRUE); Options.setSelectOnFocusGainEnabled(true); System.setProperty("Windows.controlFont", "Segoe UI-plain-15"); Font controlFont = Fonts.WINDOWS_VISTA_96DPI_NORMAL; FontSet fontSet = FontSets.createDefaultFontSet(controlFont); FontPolicy fontPolicy = FontPolicies.createFixedPolicy(fontSet); WindowsLookAndFeel.setFontPolicy(fontPolicy); WindowsLookAndFeel.setFontPolicy(FontPolicies .getLooks1xWindowsPolicy()); } catch (Exception e) { App.printErr(e); } try { SplashScreen splash = new SplashScreen(); splash.setVisible(true); splash.getBar().setValue(30); WindowMlm w = new WindowMlm(); splash.getBar().setValue(40); w.setProgressBar(splash.getBar()); ODatabaseDocumentTx db = App.getDbd(); ODatabaseRecordThreadLocal.INSTANCE.set(db); splash.getBar().setValue(70); w.build(db); w.getFrame().setVisible(true); db.close(); splash.setVisible(false); splash.dispose(); } catch (Exception e) { App.showErrSementara(e.getMessage()); App.printErr(e); System.exit(0); } long t2 = System.currentTimeMillis(); long t3 = t2 - t1; //App.showErrSementara(t2 + "-" + t1 + "=" + t3); } }
package com.walkerwang.algorithm.swordoffer; import java.util.ArrayList; import java.util.Iterator; public class TreeFindPath { public static void main(String[] args) { TreeNode treeNode10 = new TreeNode(10); TreeNode treeNode5 = new TreeNode(5); TreeNode treeNode4 = new TreeNode(4); TreeNode treeNode7 = new TreeNode(7); TreeNode treeNode12 = new TreeNode(12); treeNode10.left = treeNode5; treeNode10.right = treeNode12; treeNode5.left = treeNode4; treeNode5.right = treeNode7; int target = 22; ArrayList<ArrayList<Integer>> list = FindPath(treeNode10, target); Iterator<ArrayList<Integer>> iterList = list.iterator(); while(iterList.hasNext()){ ArrayList<Integer> iter = iterList.next(); Iterator<Integer> it = iter.iterator(); while(it.hasNext()){ int x = it.next(); System.out.print(x + " "); } System.out.println(); } } public static ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target){ ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>(); if (root == null) return list; return list; } }
import java.awt.Point; import javafx.application.Application; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.KeyEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; public class OceanExplorer extends Application { final static int dimension = 10; final int scale = 50; Image shipImage; ImageView shipImageView; OceanMap oceanMap; Pane root; Scene scene; Ship ship; Point startPosition; public static void main(String[] args) { launch(args); // TODO Auto-generated method stub } @Override public void start(Stage oceanStage) throws Exception { root = new AnchorPane(); drawMap(); startPosition = OceanMap.getShipLocation(); ship = new Ship(startPosition.x, startPosition.y); loadShipImage(); scene = new Scene(root, 500, 500); oceanStage.setTitle("Christopher columbus Sails The Blue Ocean"); oceanStage.setScene(scene); oceanStage.show(); startSailing(); } private void startSailing() { scene.setOnKeyPressed(new EventHandler<KeyEvent>() { @Override public void handle(KeyEvent ke) { switch (ke.getCode()) { case RIGHT: ship.goEast(); break; case LEFT: ship.goWest(); break; case UP: ship.goNorth(); break; case DOWN: ship.goSouth(); break; default: break; } shipImageView.setX(ship.getShipLocation().x * scale); shipImageView.setY(ship.getShipLocation().y * scale); } }); } public void drawMap() { for (int x = 0; x < dimension; x++) { for (int y = 0; y < dimension; y++) { Rectangle rect = new Rectangle(x * scale, y * scale, scale, scale); rect.setStroke(Color.BLACK); rect.setFill(Color.PALETURQUOISE); root.getChildren().add(rect); } } } private void loadShipImage() { Image shipImage = new Image("\\ship.png", 50, 50, true, true); shipImageView = new ImageView(shipImage); shipImageView.setX(OceanMap.getShipLocation().x * scale); shipImageView.setY(OceanMap.getShipLocation().y * scale); root.getChildren().add(shipImageView); } }
// CS 349 Undo Demo // Daniel Vogel (2013) import javax.swing.*; import javax.swing.event.UndoableEditEvent; import javax.swing.undo.UndoManager; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.*; public class Main { Model model; public static void main(String[] args) { new Main(); } public Main() { JFrame frame = new JFrame("UndoDemo"); // create Model and initialize it // (value, min, max in this model) model = new Model(22, 0, 100); // create View View view = new View(model); // create Menu View MainMenuView menuView = new MainMenuView(model); // add views to the window frame.getContentPane().add(view); frame.setJMenuBar(menuView); frame.setPreferredSize(new Dimension(300, 220)); frame.pack(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); // let all the views know that they're connected to the model model.updateViews(); } }
package controllers; import dao.impl.UserDaoImpl; import dto.UserDTO; import model.Role; import model.User; import service.impl.UserServiceImpl; 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; @WebServlet(name = "NewAccountServlet", urlPatterns={"/newaccount"}) public class NewAccountServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("name"); String surname = request.getParameter("surname"); String login = request.getParameter("login"); String password = request.getParameter("password"); String email = request.getParameter("email"); int age =Integer.parseInt(request.getParameter("age")); boolean f= false; try { UserDTO user = UserServiceImpl.getInstance().getByLogin(login); }catch(Exception e) { f=true; } if(f==true) { UserDTO userDTO = new UserDTO(name, surname, email, login, password, Role.VISITOR, age); UserServiceImpl.getInstance().save(userDTO); request.getSession().setAttribute("user", userDTO); response.sendRedirect(request.getContextPath() + "/allUsers/myaccount.jsp"); } else { String warn = new String("please, choose another login"); request.setAttribute("warn", warn); response.sendRedirect(request.getContextPath() + "/allUsers/createaccount.jsp"); } } }
package com.nisa.doaharian.Services; import com.nisa.doaharian.Models.DaftarDzikirPagi; import java.util.List; import retrofit2.Call; import retrofit2.http.GET; public interface DaftarDzikirPagiService { @GET("/NisaNH/doa-harian-muslim-server/dzikir_pagi") Call<List<DaftarDzikirPagi>> getDzikirPagi(); }
package pdx.module.frontdesk.gui; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.JTabbedPane; import javax.swing.JToolBar; import javax.swing.JPanel; import javax.swing.WindowConstants; import pdx.misc.PdxTable; import pdx.misc.PdxTableRenderer; import pdx.module.frontdesk.AvailableRooms; import pdx.module.frontdesk.FloorRooms; import java.awt.FlowLayout; import javax.swing.JButton; import javax.swing.LayoutStyle.ComponentPlacement; import javax.swing.JTable; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Font; import java.awt.Point; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellRenderer; import javax.swing.JScrollPane; import javax.swing.JTextPane; import javax.swing.JTextArea; /** * Basic implementation of a tabbed GUI * @author Paul * */ public class FrontDeskGUI { private JFrame frmFrontDesk; private JTable availableTable; private JTable floorOneTable; private JTextArea txtAreaNotifications; /** * Launch the front desk GUI. */ public FrontDeskGUI() { initialize(); this.frmFrontDesk.setVisible(true); notificationDemo(); } private int i; private Date date; private void notificationDemo() { final SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss a"); Runnable runnable = new Runnable() { public void run() { date = new Date(); txtAreaNotifications.append(format.format(date) + ": Notification "+i+"\n"); i++; } }; ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); service.scheduleAtFixedRate(runnable, 0, 3, TimeUnit.SECONDS); } /** * Initialize the contents of the frame. */ private void initialize() { frmFrontDesk = new JFrame(); frmFrontDesk.setTitle("Front Desk"); frmFrontDesk.setBounds(100, 100, 640, 555); frmFrontDesk.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP); GroupLayout groupLayout = new GroupLayout(frmFrontDesk.getContentPane()); groupLayout.setHorizontalGroup( groupLayout.createParallelGroup(Alignment.LEADING) .addComponent(tabbedPane, GroupLayout.DEFAULT_SIZE, 509, Short.MAX_VALUE) ); groupLayout.setVerticalGroup( groupLayout.createParallelGroup(Alignment.TRAILING) .addComponent(tabbedPane, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 375, Short.MAX_VALUE) ); JPanel guestPanel = new JPanel(); tabbedPane.addTab("Guest Check-in/out", null, guestPanel, null); guestPanel.setLayout(new BorderLayout(0, 0)); JTabbedPane tabbedPane_1 = new JTabbedPane(JTabbedPane.TOP); JScrollPane availablePanel = new JScrollPane(); tabbedPane_1.addTab("Available Rooms", null, availablePanel, null); availableTable = new JTable(new PdxTable(AvailableRooms.columns, AvailableRooms.placeholder)); //availableTable.setDefaultRenderer(Object.class, new PdxTableRenderer()); availableTable.setFont(new Font("Arial", Font.PLAIN, 14)); availableTable.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent mEvent) { Point p = mEvent.getPoint(); int row = availableTable.rowAtPoint(p); if (mEvent.getClickCount() == 2) { System.out.println(Integer.parseInt(((String) availableTable.getValueAt(row, 2)).split("/")[0])); new CheckInGUI(Integer.parseInt((String) availableTable.getValueAt(row, 0)), Integer.parseInt((String) availableTable.getValueAt(row, 1)), 5, Integer.parseInt(((String) availableTable.getValueAt(row, 2)).split("/")[0]), Integer.parseInt(((String) availableTable.getValueAt(row, 2)).split("/")[1]), "This is a description", "These are the amenities", (Double.parseDouble((String) availableTable.getValueAt(row, 3)))); //PdxTable model = (PdxTable) availableTable.getModel(); //model.setRowColor(row, new Color(0xDB3737)); } } }); availablePanel.setViewportView(availableTable); JScrollPane floorOnePanel = new JScrollPane(); tabbedPane_1.addTab("Floor 1", null, floorOnePanel, null); floorOneTable = new JTable(new PdxTable(FloorRooms.columns, FloorRooms.placeholderOne)); floorOneTable.setDefaultRenderer(Object.class, new PdxTableRenderer()); floorOneTable.setFont(new Font("Arial", Font.PLAIN, 14)); //Now change color for each row based on FloorRooms.availableFloorOne PdxTable model = (PdxTable)floorOneTable.getModel(); for(int i = 0; i < model.getRowCount(); i++) { model.setRowColor(i, FloorRooms.availableFloorOne[i]); } floorOnePanel.setViewportView(floorOneTable); JScrollPane floorTwoPanel = new JScrollPane(); tabbedPane_1.addTab("Floor 2", null, floorTwoPanel, null); JScrollPane floorThreePanel = new JScrollPane(); tabbedPane_1.addTab("Floor 3", null, floorThreePanel, null); JScrollPane floorFourPanel = new JScrollPane(); tabbedPane_1.addTab("Floor 4", null, floorFourPanel, null); JScrollPane floorFivePanel = new JScrollPane(); tabbedPane_1.addTab("Floor 5", null, floorFivePanel, null); JScrollPane floorSixPanel = new JScrollPane(); tabbedPane_1.addTab("Floor 6", null, floorSixPanel, null); guestPanel.add(tabbedPane_1); JPanel notificationsPanel = new JPanel(); tabbedPane.addTab("Notifications", null, notificationsPanel, null); txtAreaNotifications = new JTextArea(); txtAreaNotifications.setEditable(false); txtAreaNotifications.setFont(new Font("Arial", Font.PLAIN, 14)); JButton btnNewButton = new JButton("Clear Notifications"); btnNewButton.setFont(new Font("Arial", Font.PLAIN, 14)); GroupLayout gl_notificationsPanel = new GroupLayout(notificationsPanel); gl_notificationsPanel.setHorizontalGroup( gl_notificationsPanel.createParallelGroup(Alignment.LEADING) .addGroup(gl_notificationsPanel.createSequentialGroup() .addContainerGap() .addGroup(gl_notificationsPanel.createParallelGroup(Alignment.LEADING) .addComponent(txtAreaNotifications, GroupLayout.DEFAULT_SIZE, 599, Short.MAX_VALUE) .addComponent(btnNewButton)) .addContainerGap()) ); gl_notificationsPanel.setVerticalGroup( gl_notificationsPanel.createParallelGroup(Alignment.LEADING) .addGroup(gl_notificationsPanel.createSequentialGroup() .addContainerGap() .addComponent(txtAreaNotifications, GroupLayout.PREFERRED_SIZE, 340, GroupLayout.PREFERRED_SIZE) .addGap(18) .addComponent(btnNewButton) .addContainerGap(96, Short.MAX_VALUE)) ); notificationsPanel.setLayout(gl_notificationsPanel); frmFrontDesk.setLocationRelativeTo(null); frmFrontDesk.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); frmFrontDesk.getContentPane().setLayout(groupLayout); } }
package gr.athena.innovation.fagi.core.normalizer; /** * Interface for a normalization class. * * @author nkarag */ public interface INormalizer { /** * Returns the name of the normalizer. * * @return the name of the transformation as a String */ public String getName(); }
package com.designPattern.SOLID.isp.solution; public interface UPIPayments { public void doTransfer(); }
package io.kuoche.share.data.db.jpa.repository; import io.kuoche.share.data.db.jpa.entity.OrderDetailData; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public interface JpaOrderDetailRepository extends JpaRepository<OrderDetailData, Long> { List<OrderDetailData> findAllByActivityId(Long activityId); }
package com.youthchina.domain.Qinghong; import java.sql.Timestamp; /** * @program: youthchina * @description: 简历存储 * @author: Qinghong Wang * @create: 2019-03-23 14:19 **/ public class ResumeStore { private Integer store_id; private String resume_name; private Integer stu_id; private Integer is_delete; private Timestamp is_delete_time; public Integer getStore_id() { return store_id; } public void setStore_id(Integer store_id) { this.store_id = store_id; } public String getResume_name() { return resume_name; } public void setResume_name(String resume_name) { this.resume_name = resume_name; } public Integer getStu_id() { return stu_id; } public void setStu_id(Integer stu_id) { this.stu_id = stu_id; } public Integer getIs_delete() { return is_delete; } public void setIs_delete(Integer is_delete) { this.is_delete = is_delete; } public Timestamp getIs_delete_time() { return is_delete_time; } public void setIs_delete_time(Timestamp is_delete_time) { this.is_delete_time = is_delete_time; } }
package org.a55889966.bleach.saran.tourguide; import java.io.Serializable; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class EventClass implements Serializable { String eventId; String eventName; String startingLocation; String destination; String departureDate; String startedDate; int daysLeft; double budget; public EventClass() { } public EventClass(String eventId, String eventName, String startingLocation, String destination, String departureDate, String startedDate, int daysLeft, double budget) { this.eventId = eventId; this.eventName = eventName; this.startingLocation = startingLocation; this.destination = destination; this.departureDate = departureDate; this.startedDate = startedDate; this.daysLeft = daysLeft; this.budget = budget; } public EventClass(String eventId, String eventName, String startingLocation, String destination, String departureDate, String startedDate, double budget) { this.eventId = eventId; this.eventName = eventName; this.startingLocation = startingLocation; this.destination = destination; this.departureDate = departureDate; this.startedDate = startedDate; this.budget = budget; } public EventClass(String eventName, String startingLocation, String destination, String departureDate, String startedDate, double budget) { this.eventName = eventName; this.startingLocation = startingLocation; this.destination = destination; this.departureDate = departureDate; this.startedDate = startedDate; this.budget = budget; } public String getEventId() { return eventId; } public void setEventId(String eventId) { this.eventId = eventId; } public String getEventName() { return eventName; } public void setEventName(String eventName) { this.eventName = eventName; } public String getStartingLocation() { return startingLocation; } public void setStartingLocation(String startingLocation) { this.startingLocation = startingLocation; } public String getDestination() { return destination; } public void setDestination(String destination) { this.destination = destination; } public String getDepartureDate() { return departureDate; } public void setDepartureDate(String departureDate) { this.departureDate = departureDate; } public String getStartedDate() { return startedDate; } public void setStartedDate(String startedDate) { this.startedDate = startedDate; } public int getDaysLeft() { Calendar calendar = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("dd, MMM, yyyy"); String dateInString = departureDate; Date date = null; try { date = sdf.parse(dateInString); } catch (ParseException e) { e.printStackTrace(); } calendar.setTime(date); long depDateMillis=calendar.getTimeInMillis(); long currentTimeMillis=System.currentTimeMillis(); daysLeft=(int) (Math.ceil((depDateMillis-currentTimeMillis)/(60.0*60.0*24.0*1000.0))); return daysLeft; } public void setDaysLeft(int daysLeft) { this.daysLeft = daysLeft; } public double getBudget() { return budget; } public void setBudget(double budget) { this.budget = budget; } }
package by.epam.concexamples.synchronizer.exchanger; import java.util.concurrent.Exchanger; /** * Created by Alex on 21.10.2016. */ public class TeamBox extends Thread{ private String teamName; private Tyre tyre; private Exchanger<Tyre> tyreExchanger; public TeamBox(String teamName, Tyre tyre, Exchanger<Tyre> tyreExchanger) { this.teamName = teamName; this.tyre = tyre; this.tyreExchanger = tyreExchanger; } @Override public void run() { try { System.out.println(teamName + " preparing " + tyre.name()); System.out.println(teamName + " is ready to change tyres"); tyre = tyreExchanger.exchange(tyre);//шины подготовили, ждем пилота System.out.println(teamName + " changed tyres. They got " + tyre.name()); } catch (InterruptedException ex){ ex.printStackTrace(); } } }
package com.ss.android.ugc.aweme.miniapp; import android.app.Activity; import android.content.Context; import com.ss.android.ugc.aweme.dfbase.c.f; public class BaseActivity extends Activity { protected void attachBaseContext(Context paramContext) { super.attachBaseContext(paramContext); f.a(paramContext); } } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\ss\androi\\ugc\aweme\miniapp\BaseActivity.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package com.arkaces.aces_marketplace_api.security; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.core.env.Environment; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; @Configuration @EnableAuthorizationServer public class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Autowired private UserDetailsService customUserDetailService; @Autowired private AuthenticationManager authenticationManager; @Autowired private Environment environment; @Override public void configure(AuthorizationServerEndpointsConfigurer configurer) throws Exception { configurer.authenticationManager(authenticationManager); configurer.userDetailsService(customUserDetailService); } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { String clientId = environment.getProperty("oauth2.clientId"); String secret = environment.getProperty("oauth2.secret"); Integer tokenValiditySeconds = environment.getProperty("oauth2.tokenValiditySeconds", Integer.class); clients.inMemory() .withClient(clientId).secret(secret) .accessTokenValiditySeconds(tokenValiditySeconds) .scopes("read", "write") .authorizedGrantTypes("password", "refresh_token") .resourceIds("account") .accessTokenValiditySeconds(86400); } @Bean public FilterRegistrationBean corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); config.addAllowedOrigin("*"); config.addAllowedHeader("*"); config.addAllowedMethod("*"); source.registerCorsConfiguration("/**", config); FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source)); bean.setOrder(Ordered.HIGHEST_PRECEDENCE); return bean; } }
package view; import javafx.animation.FadeTransition; import javafx.scene.Group; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.scene.shape.Rectangle; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.scene.text.TextAlignment; import javafx.util.Duration; import model.Game; import utilities.Coord; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * View taht displays everything in the main gameplay screen, floors, players, stats and such */ public class GameplayView implements ViewInterface { private static final int X = 0; private static final int Y = 1; private final int width; private final int height; private final Pane rootPane; private AnchorPane mapPane; private AnchorPane statsPane; private AnchorPane playersPane; private AnchorPane inventoryPane; private AnchorPane floorPane; private int rectSize; private int doorButtonSize; private int doorButtonOffset; private HashMap<Integer, int[]> doorOffsetMap; private List<Circle> playerSprites; private List<Circle> playersSpritesCurrentFloor; private List<Text> allPlayersList; private Text currentPlayerIindicator; private Text currentplayer; private List<Text> currentPlayerStats; private List<Coord> playerCoords; private int currentPlayerIndex; private Text currentFloor; private Text eventEffectText; private Text stepsLeft; private HashMap<Integer, Boolean> currentTileDoors; private List<Button> doorButtons; private Button endTurnButton; private List<Text> itemsInInventory; private List<Text> stairs; private final Game game; private List<List<Rectangle>> tileViews; public GameplayView(Group root, int width, int height, Game game) { rootPane = new Pane(); rootPane.setPrefSize(width, height); root.getChildren().add(rootPane); this.width = width; this.height = height; this.game = game; initPanes(); initTileViews(); } /** * created all its different panes to display data on */ private void initPanes() { mapPane = new AnchorPane(); mapPane.setPrefSize(height - 150, height - 150); mapPane.setLayoutY(0); mapPane.setLayoutX(width / 2 - (height - 150) / 2); statsPane = new AnchorPane(); statsPane.setPrefSize((width - (height - 150)) / 2, height - 150); statsPane.setLayoutY(0); statsPane.setLayoutX(width - (width - (height - 150)) / 2); statsPane.setStyle("-fx-background-color: black; -fx-border-color: white; -fx-border-width: 5;"); playersPane = new AnchorPane(); playersPane.setPrefSize((width - (height - 150)) / 2, (height - 150) / 2); playersPane.setLayoutY(0); playersPane.setLayoutX(0); playersPane.setStyle("-fx-background-color: black; -fx-border-color: white; -fx-border-width: 5;"); inventoryPane = new AnchorPane(); inventoryPane.setPrefSize((width - (height - 150)) / 2, height - (height - 150) / 2); inventoryPane.setLayoutY((height - 150) / 2); inventoryPane.setLayoutX(0); inventoryPane.setStyle("-fx-background-color: black; -fx-border-color: white; -fx-border-width: 5;"); floorPane = new AnchorPane(); floorPane.setPrefSize(width - (height - 150) / 2, 150); floorPane.setLayoutX((height - 150) / 2); floorPane.setLayoutY(height - 150); floorPane.setStyle("-fx-background-color: black; -fx-border-color: white; -fx-border-width: 5;"); addNode(inventoryPane); addNode(playersPane); addNode(statsPane); addNode(mapPane); addNode(floorPane); } /** * creates the tiles in the tilemap */ private void initTileViews() { tileViews = new ArrayList<>(); Rectangle currentRect; rectSize = (height - 150) / 6; for (int i = 0; i < 6; i++) { tileViews.add(new ArrayList<Rectangle>()); for (int k = 0; k < 6; k++) { currentRect = new Rectangle(rectSize, rectSize); currentRect.setX(i * rectSize); currentRect.setY(k * rectSize); currentRect.setStyle(" -fx-fill: black; -fx-stroke: white; -fx-stroke-width: 5;"); mapPane.getChildren().add(currentRect); tileViews.get(i).add(currentRect); } } } /** * gets data from model and inits everything */ public void initMapData() { currentPlayerIndex = game.getCurrentPlayerIndex(); initPlayerSprites(); initPlayersPaneData(); initStatsPane(); initFloorPane(); initButtons(); initInventoryPane(); initStair(); } private void initInventoryPane() { itemsInInventory = new ArrayList<>(); Text titleText = new Text("Inventory"); titleText.setWrappingWidth((width - (height - 150)) / 2); titleText.setTextAlignment(TextAlignment.CENTER); titleText.setLayoutX(0); titleText.setLayoutY(40); titleText.setFont(Font.font("Ink Free", 30)); titleText.setFill(Color.WHITE); inventoryPane.getChildren().add(titleText); updateInventoryPane(); } private void initPlayerSprites() { Circle currCircle; playerSprites = new ArrayList<>(); playersSpritesCurrentFloor = new ArrayList<>(); playerCoords = game.getPlayerPositions(); for (int i = 0; i < game.getPlayerAmount(); i++) { currCircle = new Circle(); currCircle.setCenterX(playerCoords.get(i).getX() * rectSize + rectSize / 2); currCircle.setCenterY(playerCoords.get(i).getY() * rectSize + rectSize / 2); currCircle.setRadius(15); currCircle.setFill(Color.WHITE); playerSprites.add(currCircle); } for (Integer index : game.getPlayerIndicesOnCurrentFloor()) { playersSpritesCurrentFloor.add(playerSprites.get(index)); mapPane.getChildren().add(playerSprites.get(index)); } playerSprites.get(currentPlayerIndex).setStyle("-fx-stroke: #ff0000; -fx-stroke-width: 2"); } private void initPlayersPaneData() { allPlayersList = new ArrayList<>(); currentPlayerIindicator = new Text("->"); currentPlayerIindicator.setFont(Font.font("Ink Free", 30)); currentPlayerIindicator.setFill(Color.WHITE); playersPane.getChildren().add(currentPlayerIindicator); Text currText; for (int i = 0; i < game.getPlayerAmount(); i++) { currText = new Text("Player " + (i + 1)); currText.setWrappingWidth((width - (height - 150)) / 2); currText.setTextAlignment(TextAlignment.CENTER); currText.setLayoutX(0); currText.setLayoutY(50 + i * ((height - 150) / 2) / game.getPlayerAmount()); currText.setFont(Font.font("Ink Free", 30)); currText.setFill(Color.WHITE); playersPane.getChildren().add(currText); allPlayersList.add(currText); } currentPlayerIindicator.setLayoutX(50); currentPlayerIindicator.setLayoutY(allPlayersList.get(currentPlayerIndex).getLayoutY()); } private void initStatsPane() { currentplayer = new Text(game.getCurrentPlayersCharacterName()); currentplayer.setWrappingWidth((width - (height - 150)) / 2); currentplayer.setTextAlignment(TextAlignment.CENTER); currentplayer.setLayoutX(0); currentplayer.setLayoutY(50); currentplayer.setFont(Font.font("Ink Free", 30)); currentplayer.setFill(Color.WHITE); currentPlayerStats = new ArrayList<>(); List<String> playerStatStrings = game.getCurrentPlayerStatsAsStrings(); Text currStatText; for (int i = 0; i < playerStatStrings.size(); i++) { currStatText = new Text(playerStatStrings.get(i)); currStatText.setWrappingWidth((width - (height - 150)) / 2); currStatText.setTextAlignment(TextAlignment.CENTER); currStatText.setLayoutX(0); currStatText.setLayoutY(100 + i * 50); currStatText.setFont(Font.font("Ink Free", 20)); currStatText.setFill(Color.WHITE); currentPlayerStats.add(currStatText); statsPane.getChildren().add(currStatText); } statsPane.getChildren().add(currentplayer); stepsLeft = new Text("Steps left: " + game.getCurrentPlayerStepsLeft()); stepsLeft.setWrappingWidth((width - (height - 150)) / 2); stepsLeft.setTextAlignment(TextAlignment.CENTER); stepsLeft.setLayoutX(0); stepsLeft.setLayoutY(120 + playerStatStrings.size() * 50); stepsLeft.setFont(Font.font("Ink Free", 30)); stepsLeft.setFill(Color.WHITE); statsPane.getChildren().add(stepsLeft); } private void initFloorPane() { currentFloor = new Text("Showing Floor: " + (game.getCurrentFloorNumber() + 1)); currentFloor.setWrappingWidth(height - 150); currentFloor.setTextAlignment(TextAlignment.CENTER); currentFloor.setLayoutX(0); currentFloor.setLayoutY(50); currentFloor.setFont(Font.font("Ink Free", 30)); currentFloor.setFill(Color.WHITE); floorPane.getChildren().add(currentFloor); eventEffectText = new Text(); eventEffectText.setWrappingWidth(height - 150); eventEffectText.setTextAlignment(TextAlignment.CENTER); eventEffectText.setLayoutX(0); eventEffectText.setLayoutY(100); eventEffectText.setFont(Font.font("Ink Free", 20)); eventEffectText.setFill(Color.RED); floorPane.getChildren().add(eventEffectText); endTurnButton = new Button(); endTurnButton.setText("End Turn"); endTurnButton.setPrefSize((width - (height - 150)) / 2 - 10, 150 - 5); endTurnButton.setFont(Font.font("Ink Free", 30)); endTurnButton.setLayoutX(height - 150 + 10); endTurnButton.setLayoutY(5); floorPane.getChildren().add(endTurnButton); } private void initStair() { stairs = new ArrayList<>(); updateStairs(); } private void updateStairs() { for (Text stair : stairs) { mapPane.getChildren().remove(stair); } stairs = new ArrayList<>(); List<Coord> stairsUp = game.getStairsUpOnCurrentFloor(); Text currText; for (Coord coord : stairsUp) { currText = new Text("^"); currText.setStyle("-fx-text-fill: red; -fx-font-size: 20"); currText.setFill(Color.RED); currText.setWrappingWidth(rectSize); currText.setTextAlignment(TextAlignment.CENTER); currText.setLayoutY(rectSize * coord.getY() + 40); currText.setLayoutX(rectSize * coord.getX()); mapPane.getChildren().add(currText); stairs.add(currText); } List<Coord> stairsDown = game.getStairsDownOnCurrentFloor(); for (Coord coord : stairsDown) { currText = new Text("v"); currText.setStyle("-fx-text-fill: red; -fx-font-size: 20"); currText.setFill(Color.RED); currText.setWrappingWidth(rectSize); currText.setTextAlignment(TextAlignment.CENTER); currText.setLayoutY(rectSize * coord.getY() + 40); currText.setLayoutX(rectSize * coord.getX()); mapPane.getChildren().add(currText); stairs.add(currText); } } void setEventEffectText() { eventEffectText.setText(game.getEventEffectText()); } void fadeEventText() { FadeTransition fade = new FadeTransition(); fade.setDuration(Duration.millis(4000)); fade.setFromValue(10); fade.setToValue(0); fade.setNode(eventEffectText); fade.setAutoReverse(false); fade.play(); } private void initButtons() { currentTileDoors = game.getCurrentTileDoors(); doorButtonOffset = rectSize / 4; doorButtonSize = 10; doorOffsetMap = new HashMap<>(); doorOffsetMap.put(0, new int[]{0, -doorButtonOffset}); doorOffsetMap.put(1, new int[]{doorButtonOffset, 0}); doorOffsetMap.put(2, new int[]{0, doorButtonOffset}); doorOffsetMap.put(3, new int[]{-doorButtonOffset, 0}); doorButtons = new ArrayList<>(); Button currButton; for (int i = 0; i < 4; i++) { // 4 directions to walk currButton = new Button(); currButton.setPrefSize(doorButtonSize, doorButtonSize); currButton.setLayoutX(getCurrentPlayerCenterX() + doorOffsetMap.get(i)[X] - doorButtonSize); currButton.setLayoutY(getCurrentPlayerCenterY() + doorOffsetMap.get(i)[Y] - doorButtonSize); currButton.setDisable(!currentTileDoors.get(i)); doorButtons.add(currButton); mapPane.getChildren().add(currButton); } } /** * gets data from model and updates view */ public void updateMapData() { currentPlayerIndex = game.getCurrentPlayerIndex(); updatePlayerSprites(); updatePlayersPaneData(); updateStatsPane(); updateFloorPane(); updateButtons(); updateInventoryPane(); updateStairs(); } private void updateInventoryPane() { for (Text itemText : itemsInInventory) { inventoryPane.getChildren().remove(itemText); } itemsInInventory = new ArrayList<>(); List<String> itemStrings = game.getCurrentPlayerItemsAsText(); Text currText; for (int i = 0; i < itemStrings.size(); i++) { currText = new Text(itemStrings.get(i)); currText.setWrappingWidth((width - (height - 150)) / 2); currText.setTextAlignment(TextAlignment.CENTER); currText.setLayoutX(0); currText.setLayoutY(80 + i * 30); currText.setFont(Font.font("Ink Free", 20)); currText.setFill(Color.WHITE); itemsInInventory.add(currText); inventoryPane.getChildren().add(currText); } } private void updateButtons() { currentTileDoors = game.getCurrentTileDoors(); for (int i = 0; i < doorButtons.size(); i++) { doorButtons.get(i).setLayoutX(getCurrentPlayerCenterX() + doorOffsetMap.get(i)[X] - doorButtonSize); doorButtons.get(i).setLayoutY(getCurrentPlayerCenterY() + doorOffsetMap.get(i)[Y] - doorButtonSize); doorButtons.get(i).setDisable(!currentTileDoors.get(i)); } } private void updateFloorPane() { currentFloor.setText("Showing Floor: " + (game.getCurrentFloorNumber() + 1)); } private void updateStatsPane() { //updates the big character name in the statspane currentplayer.setText(game.getCurrentPlayersCharacterName()); //updates stepcounter stepsLeft.setText("Steps left: " + game.getCurrentPlayerStepsLeft()); //updates the stat texts List<String> playerStatStrings = game.getCurrentPlayerStatsAsStrings(); for (int i = 0; i < playerStatStrings.size(); i++) { currentPlayerStats.get(i).setText(playerStatStrings.get(i)); } } private void updatePlayersPaneData() { List<Text> deadPlayerTexts = new ArrayList<>(); for (Integer i : game.getDeadPlayerIndices()) { deadPlayerTexts.add(allPlayersList.get(i)); playersPane.getChildren().remove(allPlayersList.get(i)); } for (Text deadPlayer : deadPlayerTexts) { allPlayersList.remove(deadPlayer); } currentPlayerIindicator.setLayoutY(allPlayersList.get(currentPlayerIndex).getLayoutY()); } private void updatePlayerSprites() { //reset players that are shown for (Circle playerSprite : playerSprites) { mapPane.getChildren().remove(playerSprite); } initPlayerSprites(); for (Circle playerSprite : playersSpritesCurrentFloor) { playerSprite.setStyle("-fx-stroke-width: none; -fx-stroke: none"); // one of these will be the last currentplayer mapPane.getChildren().remove(playerSprite); } playersSpritesCurrentFloor = new ArrayList<>(); //update position of all players playerCoords = game.getPlayerPositions(); for (int i = 0; i < playerSprites.size(); i++) { playerSprites.get(i).setCenterX(playerCoords.get(i).getX() * rectSize + rectSize / 2); playerSprites.get(i).setCenterY(playerCoords.get(i).getY() * rectSize + rectSize / 2); } //update currentplayer indicator playerSprites.get(currentPlayerIndex).setStyle("-fx-stroke: red; -fx-stroke-width: 2"); //show players on current floor for (Integer index : game.getPlayerIndicesOnCurrentFloor()) { playersSpritesCurrentFloor.add(playerSprites.get(index)); mapPane.getChildren().add(playerSprites.get(index)); } } private int getCurrentPlayerCenterX() { return (int) playerSprites.get(currentPlayerIndex).getCenterX(); } private int getCurrentPlayerCenterY() { return (int) playerSprites.get(currentPlayerIndex).getCenterY(); } HashMap<Integer, Button> getDoorButtons() { HashMap<Integer, Button> buttonHashMap = new HashMap<>(); for (int i = 0; i < doorButtons.size(); i++) { buttonHashMap.put(i, doorButtons.get(i)); } return buttonHashMap; } Button getEndTurnButton() { return endTurnButton; } @Override public void viewToFront() { rootPane.toFront(); } @Override public void addNode(Node node) { rootPane.getChildren().add(node); } }
package com.qswy.app.activity.aroundbusiness; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.google.gson.reflect.TypeToken; import com.qswy.app.R; import com.qswy.app.activity.BaseActivity; import com.qswy.app.adapter.ABHomeListAdapter; import com.qswy.app.application.MyApplication; import com.qswy.app.model.BannerModel; import com.qswy.app.model.OutParams; import com.qswy.app.model.Shops; import com.qswy.app.model.TempAb; import com.qswy.app.utils.Contents; import com.qswy.app.utils.GsonParser; import com.qswy.app.utils.MyUtils; import com.qswy.app.utils.ToastUtils; import com.qswy.app.view.RefreshLayout; import com.sivin.Banner; import com.sivin.BannerAdapter; import java.util.ArrayList; import java.util.List; public class ABHomeActivity extends BaseActivity implements View.OnClickListener,SwipeRefreshLayout.OnRefreshListener,RefreshLayout.OnLoadListener{ private View headView; private ListView abHomeLv; private ABHomeListAdapter mAdapter; private RefreshLayout swipe; private LinearLayout errorLayout; private Button errorBtn; private Banner mBanner; private TextView clothesTv,foodTv,walkTv,useTv; private List<BannerModel> mBannerDatas = new ArrayList<>(); private String url; private int pageNo = 1; private int pageSize = 20; private int totalPages; private boolean isLoadMore = false; private boolean isLast = false; private ArrayList<Shops> abArrayList = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.activity_abhome); super.onCreate(savedInstanceState); } @Override protected void initView() { ivBack = (ImageView) findViewById(R.id.iv_public_back); tvTitle = (TextView) findViewById(R.id.tv_public_title); headView = View.inflate(this,R.layout.activity_abhome_list_title,null); abHomeLv = (ListView) findViewById(R.id.lv_abhome_list); mBanner = (Banner) headView.findViewById(R.id.banner_ab_home); clothesTv = (TextView) headView.findViewById(R.id.tv_ab_clothes); foodTv = (TextView) headView.findViewById(R.id.tv_ab_food); walkTv = (TextView) headView.findViewById(R.id.tv_ab_walk); useTv = (TextView) headView.findViewById(R.id.tv_ab_use); swipe = (RefreshLayout) findViewById(R.id.swipe); errorLayout = (LinearLayout) findViewById(R.id.layout_public_error); errorBtn = (Button) findViewById(R.id.btn_public_error); } @Override protected void onDestroy() { Contents.item = 0; super.onDestroy(); } @Override protected void initialization() { for (int i=0;i<3;i++){ BannerModel bannerModel = new BannerModel(); bannerModel.setImageId(R.mipmap.around_store_banner); mBannerDatas.add(bannerModel); } BannerAdapter adapter = new BannerAdapter<BannerModel>(mBannerDatas) { @Override protected void bindTips(TextView tv, BannerModel bannerModel) { } @Override public void bindImage(ImageView imageView, BannerModel bannerModel) { imageView.setImageResource(bannerModel.getImageId()); } }; mBanner.setBannerAdapter(adapter); mBanner.notifiDataHasChanged(); tvTitle.setText(R.string.surrounding_shop); mAdapter = new ABHomeListAdapter(this,R.layout.activity_abhome_list_item,abArrayList); abHomeLv.addHeaderView(headView); abHomeLv.setAdapter(mAdapter); showProgressDialogNotAsk(); } @Override protected void loadData() { switch (Contents.item){ case 0: pageNo = 1; isLoadMore = false; isLast = false; url = Contents.AROUNDCLOTHING; break; case 1: pageNo = 1; isLoadMore = false; isLast = false; url = Contents.AROUNDFOOD; break; } url = url+"?pageNo="+pageNo+"&pageSize="+pageSize+"&item=4"; StringRequest sr = new StringRequest(url, new Response.Listener<String>() { @Override public void onResponse(String response) { if (pageNo==1){ abArrayList.clear(); } initProgressEnd(); OutParams out = (OutParams) GsonParser.gsonparser(response,new TypeToken<OutParams>(){}.getType()); if (MyUtils.ifOutParams(ABHomeActivity.this,out,"获取数据失败")){ ArrayList<Shops> shopses = (ArrayList<Shops>) GsonParser.gsonparser(response,new TypeToken<ArrayList<Shops>>(){}.getType(),"data"); if (shopses.size()>0){ for (Shops shops:shopses){ abArrayList.add(shops); } mAdapter.notifyDataSetChanged(); }else { ToastUtils.show(ABHomeActivity.this,"数据为空"); } } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { initProgressEnd(); errorLayout.setVisibility(View.VISIBLE); swipe.setVisibility(View.GONE); } }); MyApplication.getHttpRequest().add(sr); } private void initProgressEnd(){ dissmissProgressDialogNotAsk(); swipe.setRefreshing(false); if (isLoadMore){ isLoadMore = false; swipe.setLoading(false); } } @Override protected void initListener() { ivBack.setOnClickListener(this); clothesTv.setOnClickListener(this); foodTv.setOnClickListener(this); walkTv.setOnClickListener(this); useTv.setOnClickListener(this); errorBtn.setOnClickListener(this); swipe.setOnRefreshListener(this); swipe.setOnLoadListener(this); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.iv_public_back: finish(); break; case R.id.tv_ab_clothes: clothesTv.setBackgroundResource(R.mipmap.around_store_btn_selected); foodTv.setBackgroundResource(R.mipmap.around_store_btn_unselected); walkTv.setBackgroundResource(R.mipmap.around_store_btn_unselected); useTv.setBackgroundResource(R.mipmap.around_store_btn_unselected); Contents.item = 0; loadData(); break; case R.id.tv_ab_food: clothesTv.setBackgroundResource(R.mipmap.around_store_btn_unselected); foodTv.setBackgroundResource(R.mipmap.around_store_btn_selected); walkTv.setBackgroundResource(R.mipmap.around_store_btn_unselected); useTv.setBackgroundResource(R.mipmap.around_store_btn_unselected); Contents.item = 1; loadData(); break; case R.id.tv_ab_walk: clothesTv.setBackgroundResource(R.mipmap.around_store_btn_unselected); foodTv.setBackgroundResource(R.mipmap.around_store_btn_unselected); walkTv.setBackgroundResource(R.mipmap.around_store_btn_selected); useTv.setBackgroundResource(R.mipmap.around_store_btn_unselected); Contents.item = 2; loadData(); break; case R.id.tv_ab_use: clothesTv.setBackgroundResource(R.mipmap.around_store_btn_unselected); foodTv.setBackgroundResource(R.mipmap.around_store_btn_unselected); walkTv.setBackgroundResource(R.mipmap.around_store_btn_unselected); useTv.setBackgroundResource(R.mipmap.around_store_btn_selected); Contents.item = 3; loadData(); break; case R.id.btn_public_error: showProgressDialogNotAsk(); loadData(); break; } } @Override public void onRefresh() { pageNo = 1; loadData(); } @Override public void onLoad() { swipe.setLoading(false); // return; } }
package hello; import java.util.Comparator; /** * Created by Javier on 06/04/2017. */ public class CustomComparator implements Comparator<Contexto> { @Override public int compare(Contexto object1, Contexto object2) { if(object1.getValor() > object2.getValor()) { return -1; } else { return 1; } } }
package org.vice.core.generate; import org.vice.core.Constants; import org.vice.core.conf.VColumn; import org.vice.core.conf.VTable; import org.vice.core.conf.ViceConfig; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; /** * Created by dongzhaocheng on 2014/12/21. * dao层代码生成 */ public class DaoGenerator extends AbstractGenerator { @Override public void generate() throws IOException{ if(template!=null){ String path = config.getPackageValue().replace(".","\\"); path = path + "\\dao"; File f = new File(path); if(!f.mkdirs()){ return; } for (VTable table : config.getTables()){ StringBuilder val = new StringBuilder(); StringBuilder templateCopy = new StringBuilder(template); //package语句 { val.append(config.getPackageValue()).append(".dao;").append(System.lineSeparator()); templateReplace(templateCopy,Constants.DAO_KEY_PACK,val.toString()); } //import语句 { val = new StringBuilder(); val.append("import ").append(config.getPackageValue()) .append(".model.").append(upperCase(table.getName())) .append("Model;").append(System.lineSeparator());//import User if(config.getLoggerType().equals("slf4j")){ val.append("import org.slf4j.Logger;").append(System.lineSeparator()); val.append("import org.slf4j.LoggerFactory;").append(System.lineSeparator()); } templateReplace(templateCopy,Constants.DAO_KEY_IMPORT,val.toString()); } //daoClass/Interface Name { val = new StringBuilder(); val.append(upperCase(table.getName())).append("Dao"); templateReplace(templateCopy,Constants.DAO_KEY_INTERFACE,val.toString()); val = new StringBuilder(); val.append(upperCase(table.getName())).append("DaoImpl"); templateReplace(templateCopy,Constants.DAO_KEY_CLASS,val.toString()); } //DAO_KEY_DOMAIN_CLASS = "#domainClass#"; { val = new StringBuilder(); val.append(upperCase(table.getName())).append("Model"); templateReplace(templateCopy,Constants.DAO_KEY_DOMAIN_CLASS,val.toString()); } // DAO_KEY_DOMAIN_CLASS = "#domainClass#"; { } //Autowired { val = new StringBuilder(); val.append("@Autowired"); templateReplace(templateCopy,Constants.DAO_KEY_AUTO,val.toString()); } //DAO_KEY_LOGGER = "#logger.code#" { val = new StringBuilder(); if(config.getLoggerType().equals("slf4j")){ val.append("logger.info(sql.toString())"); } templateReplace(templateCopy, Constants.DAO_KEY_LOGGER,val.toString()); } //DAO_KEY_ID_TYPE = "#garbage.tableId.type#"; { val = new StringBuilder(); if(config.getGarbageTableIdType().equals("Integer")){ val.append("Integer"); }else if(config.getGarbageTableIdType().equals("String")){ val.append("String"); } templateReplace(templateCopy,Constants.DAO_KEY_ID_TYPE,val.toString()); } //DAO_KEY_ID_NAME = "#id#"; { val = new StringBuilder(); for (VColumn c : table.getColumns()){ if(c.isPk()){ val.append("\"").append(c.getColName()).append("\""); } } templateReplace(templateCopy,Constants.DAO_KEY_ID_NAME,val.toString()); } //DAO_KEY_PARA_COLS = "#para.columns#";获得列名的参数 { val = new StringBuilder(); for (VColumn c : table.getColumns()){ val.append(c.getType()).append(" ").append(c.getColName()).append(","); } val.deleteCharAt(val.length()-1); templateReplace(templateCopy,Constants.DAO_KEY_PARA_COLS,val.toString()); } //DAO_KEY_APP_INSERT = "#append.insert#"; { val = new StringBuilder(); val.append("append( \"(\")"); for (VColumn c : table.getColumns()){ if(!c.isPk()) if(c.getType().equals("String")){ val.append(".append(\"'\").append(r.get").append(upperCase(c.getColName())).append("()).append(\"'\").append(\",\")"); }else{ val.append(".append(r.get").append(upperCase(c.getColName())).append("()).append(\",\")"); } } val.delete(val.length()-".append(\",\")".length(),val.length()); val.append(".append(\"),\")"); templateReplace(templateCopy,Constants.DAO_KEY_APP_INSERT,val.toString()); } //DAO_KEY_APP_UPDATE = "#append.update#"; { val = new StringBuilder(); for(VColumn c : table.getColumns()){ if(c.getType().equals("String")){ val.append(".append(\"").append(c.getColName()) .append("='\").append(domain.get") .append(upperCase(c.getColName())).append("()).append(\"'\").append(\",\")"); }else{ val.append(".append(\"").append(c.getColName()) .append("=\").append(domain.get") .append(upperCase(c.getColName())).append("()).append(\",\")"); } } //删除逗号 val.delete(val.length()-".append(\",\")".length(),val.length()); templateReplace(templateCopy,Constants.DAO_KEY_APP_UPDATE,val.toString()); } //DAO_KEY_TABLE_NAME = "#table.name#"; { val = new StringBuilder(); val.append("\"").append(table.getName()).append("\""); templateReplace(templateCopy,Constants.DAO_KEY_TABLE_NAME,val.toString()); } //DAO_KEY_ADD_WHERE = "#addWhere#"; { val = new StringBuilder(); for(VColumn c : table.getColumns()){ if(c.getType().equals("Integer")){ val.append("\t\tif(").append(c.getColName()).append("!=null && !").append(c.getColName()).append(".equals(-1)){sql.append(\"") .append(c.getColName()).append("=\").append(").append(c.getColName()) .append(").append(HYPHEN);}").append(System.lineSeparator()); }else if(c.getType().equals("String")){ val.append("\t\tif(").append(c.getColName()).append("!=null){sql.append(\"") .append(c.getColName()).append("=\'\").append(").append(c.getColName()) .append(").append(\"\'\").append(HYPHEN);}").append(System.lineSeparator()); } } templateReplace(templateCopy,Constants.DAO_KEY_ADD_WHERE,val.toString()); } //DAO_KEY_COLS = "#append.columns#"; { val = new StringBuilder(); val.append(".append(\" "); for (VColumn c : table.getColumns()){ if(!c.isPk()) val.append(c.getColName()).append(","); } val.deleteCharAt(val.length()-1); val.append(" \")"); templateReplace(templateCopy,Constants.DAO_KEY_COLS,val.toString()); } //DAO_KEY_ID_MET = "#id.method#"; { val = new StringBuilder(); for (VColumn c : table.getColumns()){ if(c.isPk()){ val.append(upperCase(c.getColName())); } } templateReplace(templateCopy,Constants.DAO_KEY_ID_MET,val.toString()); } //DAO_KEY_COLS_USED = "#para.columns.used#"; //col1,col2,col3 { val = new StringBuilder(); for (VColumn c : table.getColumns()){ val.append(c.getColName()).append(","); } val.deleteCharAt(val.length()-1); templateReplace(templateCopy,Constants.DAO_KEY_COLS_USED,val.toString()); } //生成文件 //包名创建目录 String javaFile = path+"\\"+upperCase(table.getName())+"Dao.java"; f = new File(javaFile); if(f.createNewFile()){ BufferedWriter writer = new BufferedWriter(new FileWriter(f)); writer.write(templateCopy.toString()); writer.flush(); writer.close(); } } } } @Override public void setTemplate(StringBuilder t) { template = t; } @Override public void setVConfig(ViceConfig c) { config = c; } }
package api; public class Position { private double x; private double y; private double direction; // in degrees public Position() { x = 0; y = 0; direction = 0; } public Position(double x, double y, double direction) { this.x = x; this.y = y; this.direction = direction; } public double getX() { return x; } public double getY() { return y; } public void setX(double x) { this.x = x; } public void setY(double y) { this.y = y; } public void setDirection(double degrees) { this.direction = degrees; } public double getDirection() { return direction; } @Override public String toString() { return "[" + x + ", " + y + "] " + direction + "°"; } }
package com.rc.portal.interceptor; import java.net.URLEncoder; import javax.servlet.http.HttpServletRequest; import com.opensymphony.webwork.ServletActionContext; import com.opensymphony.xwork.ActionInvocation; import com.opensymphony.xwork.interceptor.Interceptor; import com.opensymphony.xwork.util.OgnlValueStack; /** * 会员登录验证 * @author 刘天灵 * */ public class LoginInterceptor implements Interceptor { private static final long serialVersionUID = 56589424541L; /** "重定向URL"参数名称 */ private static final String REDIRECT_URL_PARAMETER_NAME = "redirectUrl"; /** "会员"属性名称 */ private static final String MEMBER_ATTRIBUTE_NAME = "member"; public void destroy() {} public void init() {} /** * 验证会员是否登录,否则跳转登录页 */ public String intercept(ActionInvocation invocation) throws Exception { // ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext*.xml"); // // TMemberManager tmembermanager = (TMemberManager)context.getBean("tmembermanager", TMemberManagerImpl.class); // // TMember selectByPrimaryKey = tmembermanager.selectByPrimaryKey(8L); // // ServletActionContext.getRequest().getSession().setAttribute(MEMBER_ATTRIBUTE_NAME,selectByPrimaryKey); Object loginUser = ServletActionContext.getRequest().getSession().getAttribute(MEMBER_ATTRIBUTE_NAME); if (loginUser == null) { HttpServletRequest request = ServletActionContext.getRequest(); //String redirectUrl = request.getRequestURL().toString(); String redirectUrl = request.getQueryString() != null ? request.getRequestURI() + "?" + request.getQueryString() : request.getRequestURI(); if(redirectUrl != null){ OgnlValueStack stack = invocation.getStack(); stack.getContext().put(REDIRECT_URL_PARAMETER_NAME, URLEncoder.encode(redirectUrl, "utf-8")); } return "login_page"; } return invocation.invoke(); } }
package at.htl.mealcounter.control; import at.htl.mealcounter.entity.Consumation; import at.htl.mealcounter.entity.NfcCard; import at.htl.mealcounter.entity.Person; import io.quarkus.hibernate.orm.panache.PanacheRepository; import org.eclipse.microprofile.config.inject.ConfigProperty; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.TemporalType; import javax.transaction.Transactional; import java.io.IOException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.YearMonth; import java.util.Date; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import static java.lang.System.out; @ApplicationScoped public class ConsumationRepository implements PanacheRepository<Consumation> { @Inject EntityManager em; @Inject PersonRepository personRepository; public Consumation findByDateAndPerson(LocalDate myDate, Person person) { Consumation consumation; try { consumation = em.createQuery("select c from Consumation c where " + "c.date = :DATE AND " + "c.person.id = :ID", Consumation.class) .setParameter("DATE", myDate) .setParameter("ID", person.getId()) .getSingleResult(); }catch (NoResultException e){ consumation = null; } return consumation; } @Transactional public void readFromCsv() { URL url = Thread.currentThread().getContextClassLoader().getResource("consumations.csv"); try (Stream<String> stream = Files.lines(Paths.get(url.getPath()), StandardCharsets.UTF_8)) { stream.skip(1) .map(c -> c.split(";")) .map(c -> new Consumation( personRepository.findById(Long.parseLong(c[2])), LocalDate.parse(c[0]), Boolean.parseBoolean(c[1]))) .peek(out::println) .forEach(em::merge); } catch (IOException e) { e.printStackTrace(); } } @Transactional public void fillWithTestData() { for (int i = 1; i <= personRepository.findAll().list().size(); i++) { for (int j = 1; j <= 12; j++) { YearMonth yearMonthObject = YearMonth.of(2020, j); int daysInMonth = yearMonthObject.lengthOfMonth(); for (int k = 1; k <= daysInMonth; k++) { String month = String.valueOf(j); String day= String.valueOf(k); String date = ""; boolean consumed = true; int zahl = (int)((Math.random()) * 2 + 1); if(j < 10){ month = "0"+j; } if(k < 10){ day = "0"+k; } date = "2020-"+month+"-"+day; consumed = zahl == 1; Consumation consumation = new Consumation(personRepository.findById((long)i),LocalDate.parse(date),consumed); em.merge(consumation); } } } } }
package ru.romanbrazhnikov.userformsender.viewer.business; import android.content.Context; import android.content.Intent; import android.net.Uri; import ru.romanbrazhnikov.userformsender.R; import ru.romanbrazhnikov.userformsender.application.model.UserForm; /** * Created by roman on 21.10.17. * <p> * Tool class to open "Email chooser" and send UserForm data */ public class ImplicitActions { public static void openEmailChooser(UserForm form, Context context) { Intent emailIntent = new Intent( Intent.ACTION_SENDTO, Uri.fromParts("mailto", "mail@example.com", null)); emailIntent.putExtra(Intent.EXTRA_SUBJECT, context.getString(R.string.app_name) + ": " + context.getString(R.string.form_data)); emailIntent.putExtra( Intent.EXTRA_TEXT, String.format(context.getString(R.string.email_format), form.getEmail(), form.getPhone())); emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(form.getFile())); context.startActivity( Intent.createChooser(emailIntent, context.getString(R.string.send_by_mail))); } }
package com.horical.hrc7.lib_base.recycle_view; import android.support.v7.widget.RecyclerView; import android.view.View; import com.horical.hrc7.lib_base.helper.finder.ViewFinder; import java.util.List; /** * Created by quang.pv on 6/1/2017. */ public abstract class BaseViewHolder<T, K> extends RecyclerView.ViewHolder { private K listener; protected T item; public BaseViewHolder(View itemView) { super(itemView); } public abstract void setupView(); public void bind(T item) { this.item = item; onBind(item); } protected abstract void onBind(T t); void onBindWithPayload(T t, List<Object> payloads) { onBind(t); } void setListener(K myViewHolderListener) { this.listener = myViewHolderListener; } public T getItem() { return item; } protected K getListener() { return listener; } }
package com.lingnet.vocs.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import com.lingnet.common.entity.BaseEntity; @Entity @Table(name = "machine") public class Machine extends BaseEntity implements java.io.Serializable{ /** * */ private static final long serialVersionUID = -4854886689016521467L; private String equipmentCode;//设备编号 private String equipmentName;//设备名称 private String equipmentType;//工艺类型 private String imgpath;//设备封面 private String equipmentfirm;//设备厂商 private String description;//工作原理描述 private String point;//产品特点 private String trade;//适用行业 private int num;//市场投放数量 private String describe;//描述 private String partnerId;//公司名称 private String status;//发布状态(0发布,1撤回) private String isrm;//是否热门(0热门,1撤回) private String iszd;//是否置顶(0置顶,1撤回) private Double price;//价格 private String models;//设备规格型号 private String wxcc;//设备外形尺寸 private String cslxr;//厂商联系人 private String csphone;//厂商联系方式 private String supplierid;//供应商名称 @Column(name="supplierid") public String getSupplierid() { return supplierid; } public void setSupplierid(String supplierid) { this.supplierid = supplierid; } @Column(name="equipmentcode") public String getEquipmentCode() { return equipmentCode; } public void setEquipmentCode(String equipmentCode) { this.equipmentCode = equipmentCode; } @Column(name="equipmentName") public String getEquipmentName() { return equipmentName; } public void setEquipmentName(String equipmentName) { this.equipmentName = equipmentName; } @Column(name="equipmentType") public String getEquipmentType() { return equipmentType; } public void setEquipmentType(String equipmentType) { this.equipmentType = equipmentType; } @Column(name="equipmentfirm") public String getEquipmentfirm() { return equipmentfirm; } public void setEquipmentfirm(String equipmentfirm) { this.equipmentfirm = equipmentfirm; } @Column(name="description") public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Column(name="point") public String getPoint() { return point; } public void setPoint(String point) { this.point = point; } @Column(name="trade") public String getTrade() { return trade; } public void setTrade(String trade) { this.trade = trade; } @Column(name="num") public int getNum() { return num; } public void setNum(int num) { this.num = num; } @Column(name="equipmentpicture") public String getImgpath() { return imgpath; } public void setImgpath(String imgpath) { this.imgpath = imgpath; } @Column(name="describe") public String getDescribe() { return describe; } public void setDescribe(String describe) { this.describe = describe; } @Column(name="status") public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } @Column(name="partnerId") public String getPartnerId() { return partnerId; } public void setPartnerId(String partnerId) { this.partnerId = partnerId; } public String getIsrm() { return isrm; } public void setIsrm(String isrm) { this.isrm = isrm; } public String getIszd() { return iszd; } public void setIszd(String iszd) { this.iszd = iszd; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } @Column(name="models") public String getModels() { return models; } public void setModels(String models) { this.models = models; } @Column( name="wxcc" ) public String getWxcc() { return wxcc; } public void setWxcc(String wxcc) { this.wxcc = wxcc; } @Column( name = "cslxr" ) public String getCslxr() { return cslxr; } public void setCslxr(String cslxr) { this.cslxr = cslxr; } @Column( name = "csphone" ) public String getCsphone() { return csphone; } public void setCsphone(String csphone) { this.csphone = csphone; } }
package servletHandle; import dao.ImageDao; import javaBean.Image; 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.ArrayList; @WebServlet("/deleteImage") public class deleteImageServlet extends HttpServlet { private ImageDao imageDao; private Image image; private String FileId=""; private String Filename=""; @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { imageDao=new ImageDao(); FileId=request.getParameter("id"); Filename=request.getParameter("fileName"); Boolean result=imageDao.deleteImageByID(FileId); if (result){ java.io.File iof = new java.io.File("main\\webapp\\PersonalPage\\img/"+Filename); System.out.println(iof); //删除文件 iof.delete(); response.sendRedirect("/loadImage"); }else { /*String msg = "删除失败"; request.getSession().setAttribute("deletefail_msg",msg); response.sendRedirect("/user/uploading.jsp");*/ } } }
package com.caicaiRibbon; /** * @author caicai * @Date 2021/3/28 下午9:58 */ public class caicaiRibbonRule { }
/** * @author smxknife * 2020/7/9 */ package com.smxknife.servlet.async;
package com.tencent.mm.plugin.appbrand.jsapi.bluetooth.ble.sdk.c; public enum j { OK(0, ""), FAIL(-1, "fail"), BLE_NO_INIT(10000, "fail:not init"), BLE_NOT_AVAILABLE(10001, "fail:not available"), BLE_NO_DEVICE(10002, "fail:no device"), BLE_CONNECTION_FAIL(10003, "fail:connection fail"), BLE_NO_SERVICE(10004, "fail:no service"), BLE_NO_CHARACTERISTIC(10005, "fail:no characteristic"), BLE_NO_CONNECTION(10006, "fail:no connection"), BLE_PROPERTY_NOT_SUPPORT(10007, "fail:property not support"), BLE_SYSTEM_ERROR(10008, "fail:system error"), BLE_SYSTEM_NOT_SUPPORT(10009, "fail:system not support"), BLE_NO_DESCRIPTOR(10008, "fail:no descriptor"), BLE_SET_DESCRIPTOR_FAIL(10008, "fail:fail to set descriptor"), BLE_WRITE_DESCRIPTOR_FAIL(10008, "fail:fail to write descriptor"), BLE_OPERATE_TIME_OUT(10012, "fail:operate time out"), BLE_ALREADY_CONNECT(-1, "fail:already connect"); public String Yy; public int errCode; private j(int i, String str) { this.errCode = i; this.Yy = str; } public final String toString() { return "Result{errCode=" + this.errCode + ", errMsg='" + this.Yy + '\'' + '}'; } }
package kr.highthon.common.exception; public class AlreadyPaidException extends RuntimeException { }
package animatronics.debug; import animatronics.common.inventory.elements.SlotLocked; import animatronics.utils.inventory.container.ContainerBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; public class ContainerDebug extends ContainerBase{ public TileEntityDebug debug; public ContainerDebug(InventoryPlayer inventoryPlayer, TileEntityDebug tile){ debug = tile; addSlotToContainer(new SlotLocked(tile, 0, 80, 44)); bindPlayerInventory(inventoryPlayer); } public boolean canInteractWith(EntityPlayer player) { return debug.isUseableByPlayer(player); } public ItemStack transferStackInSlot(EntityPlayer player, int slot){ ItemStack iStack = null; Slot slotObject = (Slot)inventorySlots.get(slot); if(slotObject != null && slotObject.getHasStack()){ ItemStack stackInSlot = slotObject.getStack(); iStack = stackInSlot.copy(); if(slot == 0){ if(!mergeItemStack(stackInSlot, 1, 37, true)){ return null; } }else if(slot >= 28 && slot <= 37 && !mergeItemStack(stackInSlot, 1, 28, false)){ return null; }else if(slot >= 0 && slot <= 27 && !mergeItemStack(stackInSlot, 28, 37, false)){ return null; } if(stackInSlot.stackSize == 0){ slotObject.putStack(null); }else{ slotObject.onSlotChanged(); } if(stackInSlot.stackSize == iStack.stackSize){ return null; } slotObject.onPickupFromSlot(player, stackInSlot); } return iStack; } }
<<<<<<< HEAD package chapter08; public class Exercise08_08 { public static void main(String[] args) { printClosestPoints( new int[][] { { 0, 0 }, { 1, 1 }, { -1, -1 }, { 2, 2 }, { -2, -2 }, { -3, -3 }, { -4, -4 }, { 5, 5 } }); } public static void printClosestPoints(int[][] list) { String str = ""; double minDistance = Double.MAX_VALUE; for (int i = 0; i < list.length - 1; i++) { for (int j = i + 1; j < list.length; j++) { double currentDistance = distance(list[i][0], list[i][1], list[j][0], list[j][0]); if (currentDistance <= minDistance) { if (currentDistance == minDistance) { str += "The closest two points are: (" + list[i][0] + "," + list[i][1] + ") and (" + list[j][0] + "," + list[j][0] + ")\n"; } else { str = "The closest two points are: (" + list[i][0] + "," + list[i][1] + ") and (" + list[j][0] + "," + list[j][0] + ")\n"; } minDistance = currentDistance; } } } System.out.println(str + "\nThe distance is: " + minDistance); } public static double distance(double x1, double y1, double x2, double y2) { return Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2)); } } ======= package chapter08; public class Exercise08_08 { public static void main(String[] args) { printClosestPoints( new int[][] { { 0, 0 }, { 1, 1 }, { -1, -1 }, { 2, 2 }, { -2, -2 }, { -3, -3 }, { -4, -4 }, { 5, 5 } }); } public static void printClosestPoints(int[][] list) { String str = ""; double minDistance = Double.MAX_VALUE; for (int i = 0; i < list.length - 1; i++) { for (int j = i + 1; j < list.length; j++) { double currentDistance = distance(list[i][0], list[i][1], list[j][0], list[j][0]); if (currentDistance <= minDistance) { if (currentDistance == minDistance) { str += "The closest two points are: (" + list[i][0] + "," + list[i][1] + ") and (" + list[j][0] + "," + list[j][0] + ")\n"; } else { str = "The closest two points are: (" + list[i][0] + "," + list[i][1] + ") and (" + list[j][0] + "," + list[j][0] + ")\n"; } minDistance = currentDistance; } } } System.out.println(str + "\nThe distance is: " + minDistance); } public static double distance(double x1, double y1, double x2, double y2) { return Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2)); } } >>>>>>> 7af1d9968804c80cea04654b9c2daefeb8630261
package com.beiyelin.document.controller; import com.beiyelin.document.entity.Document; import com.beiyelin.document.entity.PathTree; import com.beiyelin.document.repository.DocumentRepository; import com.beiyelin.document.service.DocumentQueryService; import com.beiyelin.document.service.StorageService; import org.apache.commons.io.FilenameUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.Resource; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import javax.servlet.http.HttpServletRequest; import java.util.Date; import java.util.List; import static java.util.stream.Collectors.toList; /** * Created by xinsh on 2017/9/13. */ @RestController @RequestMapping("/document") public class FileManagerController { @Autowired private StorageService storageService; @Autowired private DocumentRepository documentRepository; @Autowired private DocumentQueryService documentQueryService; // public FileManagerController(StorageService storageService){ // this.storageService = storageService; // } @GetMapping("/get-file/{filename}") public ResponseEntity<Resource> getFile(@PathVariable String filename) throws Exception { Resource file = storageService.loadAsResource(filename); return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"").body(file); } @PostMapping("/add-file") public ResponseEntity<String> addFile(@RequestParam("name") String name, @RequestParam("parentPath") String parentPath, @RequestParam("createTime") long createTime, @RequestParam("desc") String desc, HttpServletRequest request ) throws Exception { if (request instanceof MultipartHttpServletRequest) { parentPath = StringUtils.cleanPath(parentPath);//规范化路径 Document doc = new Document(); doc.setName(name); doc.setCreateTime(new Date(createTime)); doc.setParentPath(parentPath); doc.setDesc(desc); doc.setItemType(Document.ITEM_TYPE_FILE);//是文件,不是文件夹 MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request; // 获取上传的文件 MultipartFile file = multipartHttpServletRequest.getFile("file"); //保存文件,同时完善doc的信息 List<Document> docContent; docContent = storageService.saveFile(doc,file); //Map<String, MultipartFile> fileMap = multipartHttpServletRequest.getFileMap(); // for(Map.Entry<String, MultipartFile> entry : fileMap.entrySet()){ // storageService.saveFile(entry.getValue()); // } docContent.stream().forEach(item->documentRepository.save(item)); return ResponseEntity.ok().body("保存成功"); } else { throw new Exception("必须提交对应的文件"); } // System.out.println(name); } /** * 新增文件夹 * @return * @throws Exception */ @PostMapping("/add-path") public ResponseEntity<String> addPath(@RequestBody Document doc ) throws Exception { // public ResponseEntity<String> addPath(@RequestParam("name") String name, // @RequestParam("parentPath") String parentPath, // @RequestParam("desc") String desc // ) throws Exception { // parentPath = storageService.processPath(parentPath);//规范化路径 // Document doc = new Document(); // doc.setName(name); // doc.setParentPath(parentPath); // doc.setDesc(desc); doc.setItemType(Document.ITEM_TYPE_DIR);//是文件夹,不是文件 doc.setCreateTime(new Date()); //创建本地文件夹名称 doc.setPath(FilenameUtils.concat(doc.getParentPath(),storageService.resetPathName(doc.getName()))); //保存文件 documentRepository.save(doc); return ResponseEntity.ok().body("保存成功"); } @PostMapping("/update-path") public ResponseEntity<String> updatePath(@RequestParam("id") String id, @RequestParam("name") String name, @RequestParam("parentPath") String parentPath, @RequestParam("createTime") long createTime, @RequestParam("desc") String desc ) throws Exception { parentPath = StringUtils.cleanPath(parentPath);//规范化路径 Document doc = documentRepository.findOne(id); doc.setName(name); doc.setCreateTime(new Date(createTime)); doc.setParentPath(parentPath); doc.setDesc(desc); // doc.setItemType(Document.ITEM_TYPE_DIR);//是文件夹,不是文件 documentRepository.save(doc); return ResponseEntity.ok().body("保存成功"); } @GetMapping("/list-files") public ResponseEntity<List<String>> listFiles(@RequestParam("path") String path) throws Exception { // List<String> list = storageService.listFiles(path).map( // pathName -> MvcUriComponentsBuilder.fromMethodName(FileManagerController.class, // "getFile", pathName.getFileName().toString()).build().toString()) // .collect(toList()); String searchPath = storageService.processPath(path);//规范化路径 List<String> list = documentRepository.findByItemTypeAndParentPath(Document.ITEM_TYPE_FILE,searchPath) .stream() .map(item -> item.getPath()) .collect(toList()); return ResponseEntity.ok().body(list); } /** * 获取指定目录一下的所有子目录 * @param path * @return * @throws Exception */ // @GetMapping("/list-paths") // public ResponseEntity<List<String>> listPaths(@RequestParam("path") String path) throws Exception { // String searchPath = storageService.processPath(path);//规范化路径 // List<Document> docList; //// docList = documentRepository.findByItemTypeAndParentPath(Document.ITEM_TYPE_DIR, searchPath); // docList = documentQueryService.getSubPath( searchPath); // List<String> list = docList.stream() // .map(item -> item.getPath() ).collect(toList()); // // return ResponseEntity.ok().body(list); // } @GetMapping("/list-paths") public ResponseEntity<List<Document>> listPaths(String path) throws Exception { String searchPath = storageService.processPath(path);//规范化路径 List<Document> docList; // docList = documentRepository.findByItemTypeAndParentPath(Document.ITEM_TYPE_DIR, searchPath); docList = documentQueryService.getSubPath( searchPath); List<Document> list = docList.stream() .collect(toList()); return ResponseEntity.ok().body(list); } @GetMapping("/list-all-paths") public ResponseEntity<List<PathTree>> listAllPaths(String path) throws Exception { String searchPath = storageService.processPath(path);//规范化路径 List<PathTree> pathList; // docList = documentRepository.findByItemTypeAndParentPath(Document.ITEM_TYPE_DIR, searchPath); pathList = documentQueryService.getAllSubPath( searchPath); return ResponseEntity.ok().body(pathList); } @GetMapping("/get-path") public ResponseEntity<Document> getPath(@RequestParam("path") String path) throws Exception { Document doc = documentRepository.getByPath(path); return ResponseEntity.ok().body(doc); } @GetMapping("/get-path-by-name") public ResponseEntity<List<Document>> getPathbyName(@RequestParam("pathname") String pathname) throws Exception { List<Document> doc = documentRepository.findByName(pathname); return ResponseEntity.ok().body(doc); } }
/************************************************ * * Dispositivos Programables, Funciones * de filtros digitales para la implementación * de un Transmultiplexor simétrico. * * Profesor: Juan Manuel Madrigal Bravo. * * Elaboró: Juan Capiz Castro. * * *************************************************/ package org.jcapizcastro.transmul; public class FuncionesFiltro { /************************************************ * * Las presentes subrutinas son auxiliares en la * * implementación y el modelado de un banco de * * filtros simétrico con la propiedad de * * reconstrucción perfecta. * *************************************************/ /** Agrega ceros al principio de un vector de flotantes. **/ public double[] addZerosAtFirst(int ceroz, double[] A) { if (ceroz < 0) // Agregar una cantidad negativa no tiene caso. return null; int i; // Se crea un nuevo vector con capacidad para los ceros a agregar. double[] newVector = new double[A.length + ceroz]; // Asignamos ceros al inicio. for (i = 0; i < ceroz; i++) { newVector[i] = 0; } // Copiamos lo que había en el vector original. for (i = 0; i < A.length; i++) { newVector[i + ceroz] = A[i]; } // Devolvemos el nuevo vector con los ceros al inicio. return newVector; } /** Multiplexa las muestras correspondientes a los canales. **/ public double[] multiplexation(double[][] vectors, int channels) { // Variables de control de bucle. int i; int j; // Acumulador. double gatherer; // Se crea un vector con la cantidad de las muestras que tiene cada canal, // aprovechando que se trata de un banco de filtros simétrico y que todos // sus canales son de la misma lengitud (tras operaciones de convolución // e interpolado). // De tratarse de un banco de filtros asimétrico, se debe cuidar que el // primer canal asignado sea el de mayor muestras a su salida. double[] mux = new double[vectors[0].length]; // Se recogen las muestras de cada canal, una a una y son sumadas, superpuestas, // para luego ser transmitidas como un único vector. // En caso de tratarse de un banco de filtros asimétrico, se cuida que cada // canal sume sólo los elementos que contiene, es decir, se cuida el desbordamiento. for (i = 0; i < mux.length; i++) { gatherer = 0; for (j = 0; j < channels; j++) { if (i < vectors[j].length) { // Medida contra desbordamiento (ArrayIndexOutOfBounds Exception). gatherer += vectors[j][i]; } } mux[i] = gatherer; } return mux; } /** Subrutina que suma un vector dado. **/ public double sumVector(double[] FloatVector) { double sum = 0.0; int i; for (i = 0; i < FloatVector.length; i++) sum += FloatVector[i]; return sum; } /** Subrutina que lleva a cabo la interpolación. **/ public double[] interpolacion(int factor, double[] buffer) { // Declaración del vector que contendrá el total de muestras // tras el interpolado: buffer_length = "muestras que ya había" + // "muestras que ya había" * "doblés - 1"; double floatVector[] = new double[buffer.length + ((factor - 1) * (buffer.length))]; int i; // Asignación de ceros, si el módulo del índice que recoore el arreglo // respecto del factor de doblés de la operación de interpolado resulta // cero, es decir, para todos los múltiplos del doblés, guardamos la muestra // ubicada en esa posición del arreglo, se guarda un cero en otro caso. for (i = 0; i < floatVector.length; i++) { if (i % factor == 0) { floatVector[i] = buffer[i / factor]; } else { floatVector[i] = 0; } } return floatVector; } /** Subrutina de interpolación de filtros. **/ public double[] interpolacionDeFiltro(int dobles, double elementos[]) { // La presente subrutina es lo mismo que la de interpolado, excepto que // esta cuida no agregar más ceros después de la última muestra. double nuevoVector[] = new double[elementos.length + ((dobles - 1) * (elementos.length - 1))]; int i; for (i = 0; i < nuevoVector.length; i++) { if (i % dobles == 0) { nuevoVector[i] = elementos[i / dobles]; } else { nuevoVector[i] = 0; } } return nuevoVector; } /** Subrutina de diezmado en un doblés igual a "factor". **/ public double[] diezmado(int factor, double[] elementos) { int i; // La presente función toma los elementos localizados en múltiplos // del índice por el factor (doblés) proporcionado. double[] floatVector = new double[(int) (elementos.length / factor)]; for (i = 0; i < floatVector.length; i++) { floatVector[i] = elementos[i * factor]; } return floatVector; } /** Subrutina de convolución tradicional (se programa la sumatoria). **/ public double[] convolucionTradicional(double[] x, double[] h) { // Variables tradicionales de indexado de la sumatoria y de las muestras de la // señal de salida y. int n; int k; // La nueva secuencia contiene N - 1 muestras, donde N = x.length + h.length int length = x.length + h.length - 1; // Variables auxiliares, que sirven para almacenar temporalmente el valor // existente en un vector en cuanto a índice, para cuidarse de desbordamientos // (IndexOutOfBoundException). A veces la operación n-k resulta ser un número // negativo, y desde que n-k es un índice en la señal de convolución, lo que se // sabe es que se hace referencia a una muestra con valor cero, pero ponerlo directo // resultaría en una mala referecia. Del mismo modo con k, hay veces en las que exede // el tamaño del arreglo, sabemos que esa es una muestra de valor cero, pero no cuidarse // de ello resultaria en un "desbordamiento de flujo". double aux; double aux2; double[] y = new double[length]; for (n = 0; n < length; n++) { y[n] = 0; for (k = 0; k < length; k++) { aux = 0; aux2 = 0; if (n - k >= 0 && n - k < h.length) { } if (k < x.length) { aux2 = x[k]; } y[n] += aux * aux2; } } return (y); } }
package com.infotecsjava.keyvalue.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.web.bind.annotation.*; import com.infotecsjava.keyvalue.model.KeyValueModel; import com.infotecsjava.keyvalue.service.KeyValueService; import java.io.IOException; import java.util.List; /* * Контролер для обработки запросов к хранилищу */ @RestController @EnableScheduling public class KeyValueController { private KeyValueService keyValueService; //Связываем компоненты сервиса и контроллера приложения @Autowired public KeyValueController(KeyValueService keyValueService) { this.keyValueService = keyValueService; } /* * Метод для обработки операции чтения * Обрабатывает Get-запросы на адрес /get/{key} * @param key - ключ для хранилища * @return данные, хранящиеся по ключу, и HTTP-статус 200 OK * Или сообщение об ошибке и статус 404 Not Found, если данные не обнаружены */ @GetMapping("/get/{key}") public ResponseEntity<String> getValue(@PathVariable(name = "key") String key) { String value = this.keyValueService.getValue(key); return value != null ? new ResponseEntity<>(value, HttpStatus.OK) : new ResponseEntity<>("No data found", HttpStatus.NOT_FOUND); } /* * Метод для обработки получения всех пар ключ-значение * Обрабатывает Get-запросы на адрес /getall * @return список всех пар ключ-значение и HTTP-статус 200 OK * Или сообщение об ошибке и статус 404 Not Found, если репозиторий пуст */ @GetMapping(value = "/getall") public ResponseEntity<?> getAll() { final List<KeyValueModel> repository = keyValueService.getAll(); return repository != null && !repository.isEmpty() ? new ResponseEntity<>(repository, HttpStatus.OK) : new ResponseEntity<>("No data found", HttpStatus.NOT_FOUND); } /* * Метод для обработки операции записи без заданного параметра ttl * Обрабатывает Post-запросы на адрес /set/{key}/{value} * @param key - ключ для хранилища * @param value - данные для хранилища * @return сообщение "Ok" и HTTP-статус 201 Created * Или сообщение об ошибке и статус 409 Conflict, если введенные данные некорректны */ @PostMapping(value = "/set/{key}/{value}") public ResponseEntity<String> setValue(@PathVariable(name = "key") String key, @PathVariable(name = "value") String value) { boolean set = keyValueService.setValue(key, value); return set != false ? new ResponseEntity<>("Ok", HttpStatus.CREATED) : new ResponseEntity<>("Incorrect data", HttpStatus.CONFLICT); } /* * Метод для обработки операции записи с заданным параметром ttl * Обрабатывает Post-запросы на адрес /set/{key}/{value} * @param key - ключ для хранилища * @param value - данные для хранилища * @param ttl - продолжительность жизни записи * @return сообщение "Ok" и HTTP-статус 201 Created * Или сообщение об ошибке и статус 409 Conflict, если введенные данные некорректны */ @PostMapping(value = "/set/{key}/{value}/{ttl}") public ResponseEntity<String> setValue(@PathVariable(name = "key") String key, @PathVariable(name = "value") String value, @PathVariable(name = "ttl") long ttl) { boolean set = keyValueService.setValue(key, value, ttl); return set != false ? new ResponseEntity<>("Ok", HttpStatus.CREATED) : new ResponseEntity<>("Incorrect data", HttpStatus.CONFLICT); } /* * Метод для обработки операции удаления * Обрабатывает Put-запросы на адрес /remove/{key} * @param key - ключ для хранилища * @return данные, хранившиеся по ключу, и HTTP-статус 200 OK * Или сообщение об ошибке и статус 404 Not Found, если данные не обнаружены */ @PutMapping(value = "/remove/{key}") public ResponseEntity<String> removeValue(@PathVariable(name = "key") String key) { String value = keyValueService.remove(key); return value != null ? new ResponseEntity<>(value, HttpStatus.OK) : new ResponseEntity<>("No data found", HttpStatus.NOT_FOUND); } /* * Метод для обработки операции сохранения состояния хранилища * Обрабатывает Get-запросы на адрес /dump * @return текущее состояние проекта в формате json и HTTP-статус 200 OK, * Или сообщение об ошибке и статус 404 Not Found, если данные не обнаружены, * Или сообщение об ошибке и статус 409 Conflict при проблемах с обработкой файла или перевода объектов в json */ @GetMapping(value = "/dump") public ResponseEntity<String> dump() { String dump; try { dump = this.keyValueService.dump(); if(dump == null) { return new ResponseEntity<>("JSON processing error", HttpStatus.CONFLICT); } return !dump.isEmpty() ? new ResponseEntity<>(dump, HttpStatus.OK) : new ResponseEntity<>("No data found", HttpStatus.NOT_FOUND); } catch (IOException e) { return new ResponseEntity<>("File processing error", HttpStatus.CONFLICT); } } /* * Метод для обработки операции загрузки состояния хранилища * Обрабатывает Post-запросы на адрес /load * @return сообщение "Ok" и HTTP-статус 201 Created * Или сообщение об ошибке и статус 409 Conflict при проблемах с обработкой файла или json-объектов */ @PostMapping(value = "/load") public ResponseEntity<String> load() { try { this.keyValueService.load(); return new ResponseEntity<>("Ok", HttpStatus.CREATED); } catch (IOException e) { return new ResponseEntity<>("File processing error", HttpStatus.CONFLICT); } } /* * Метод для проверки времени до удаления записей в хранилище * Запускается с интервалом в 1 миллисекунду независимо от предыдущего запуска */ @Scheduled(fixedRate = 1) public void checkTtl() { this.keyValueService.checkTtls(1); } }
package com.syzible.dublinnotifier.ui; /** * Created by ed on 21/02/2017. */ public interface FilterListener { void onFilter(); }
package com.mcf.service.impl; import java.util.Date; import java.util.Map; import javax.annotation.Resource; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanUtils; import org.springframework.stereotype.Service; import com.mcf.base.common.dao.IBaseMapperDao; import com.mcf.base.common.page.Pager; import com.mcf.base.common.service.impl.BaseServiceImpl; import com.mcf.base.common.utils.JodaUtils; import com.mcf.base.common.utils.RandomUtils; import com.mcf.base.common.utils.ShowConvertUtils; import com.mcf.base.dao.IContactInfoDao; import com.mcf.base.exception.BaseException; import com.mcf.base.pojo.ContactInfo; import com.mcf.service.IContactInfoService; @Service("contactInfoService") public class ContactInfoServiceImpl extends BaseServiceImpl<ContactInfo> implements IContactInfoService { private static Logger logger = LoggerFactory.getLogger(ContactInfoServiceImpl.class); @Resource private IContactInfoDao contactInfoDao; @Resource(name = "contactInfoDao") @Override public void setBaseMapperDao(IBaseMapperDao<ContactInfo> baseMapperDao) { super.setBaseMapperDao(baseMapperDao); } @Override public boolean updateIsContact(String id, Byte isContact) { boolean flag = false; try { if (StringUtils.isNotBlank(id)) { ContactInfo contactInfo = contactInfoDao.getById(id); if (contactInfo != null) { contactInfo.setIsContact(ShowConvertUtils.isContact(isContact)); contactInfo.setVisitTime(JodaUtils.getNowDate()); flag = contactInfoDao.update(contactInfo); } } } catch (Exception e) { logger.error("修改是否已经联系客户--->{}"); flag = false; } return flag; } @Override public Map<String, Object> getContactInfoList(Map<String, Object> parameter, Pager pager) throws BaseException { Map<String, Object> listMap = null; try { listMap = this.getListData("getContactInfoList", parameter, pager); } catch (BaseException e) { logger.error("获取联系信息列表失败--->{}"); throw e; } return listMap; } @Override public boolean updateRemark(String id, String remark) { boolean flag = false; try { if (StringUtils.isNotBlank(id)) { ContactInfo updateObj = contactInfoDao.getById(id); if (updateObj != null) { updateObj.setRemark(remark); flag = contactInfoDao.update(updateObj); } } } catch (Exception e) { logger.error("添加备注信息失败--->{}"); flag = false; } return flag; } @Override public boolean addContactInfo(ContactInfo contactInfo) { boolean status = false; Date nowTime = JodaUtils.getNowDate(); // 发送联系信息 contactInfo.setId(RandomUtils.getGenerateId()); contactInfo.setCreateTime(nowTime); // 将entity对象值复制给target对象 ContactInfo target = new ContactInfo(); BeanUtils.copyProperties(contactInfo, target); // 执行保存 status = contactInfoDao.add(target); return status; } }
package com.tencent.mm.plugin.ext; import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.os.Looper; import com.tencent.mm.bt.h.d; import com.tencent.mm.compatible.e.m; import com.tencent.mm.compatible.util.k; import com.tencent.mm.g.a.et; import com.tencent.mm.kernel.g; import com.tencent.mm.model.ar; import com.tencent.mm.model.au; import com.tencent.mm.model.bs; import com.tencent.mm.model.c; import com.tencent.mm.plugin.messenger.foundation.a.a.f; import com.tencent.mm.plugin.messenger.foundation.a.a.f.a; import com.tencent.mm.pluginsdk.model.app.ao; import com.tencent.mm.pluginsdk.model.i; import com.tencent.mm.sdk.e.j; import com.tencent.mm.sdk.platformtools.ad; import com.tencent.mm.sdk.platformtools.ag; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.storage.aa; import com.tencent.mm.storage.ab; import com.tencent.mm.storage.bk; import com.tencent.mm.storage.bv; import com.tencent.mm.storage.x; import java.io.File; import java.util.HashMap; import java.util.LinkedList; public class b implements ar { private static HashMap<Integer, d> cVM; private static boolean iJn = false; private final long iIX = 1600; private x iIY; private bk iIZ; private bv iJa; private a iJb; private b iJc; private HashMap<String, Integer> iJd = new HashMap(); private a iJe = new 5(this); i.a iJf = new 6(this); private ag iJg = new 7(this, Looper.getMainLooper()); private LinkedList<String> iJh = new LinkedList(); private final long iJi = 60; private ag iJj = new 8(this, Looper.getMainLooper()); private j.a iJk = new 9(this); private boolean iJl = true; private boolean iJm = false; com.tencent.mm.sdk.e.m.b iwy = new 10(this); static { int zj = m.zj(); try { if (!Build.CPU_ABI.contains("armeabi")) { com.tencent.mm.sdk.platformtools.x.e("hakon SilkCodec", "x86 machines not supported."); } else if ((zj & 1024) != 0) { k.b("wechatvoicesilk_v7a", b.class.getClassLoader()); } else if ((zj & 512) != 0) { k.b("wechatvoicesilk", b.class.getClassLoader()); } else { com.tencent.mm.sdk.platformtools.x.e("hakon SilkCodec", "load library failed! silk don't support armv5!!!!"); } } catch (Exception e) { com.tencent.mm.sdk.platformtools.x.e("hakon SilkCodec", "load library failed!"); } HashMap hashMap = new HashMap(); cVM = hashMap; hashMap.put(Integer.valueOf("OPENMSGLISTENER_TABLE".hashCode()), new 1()); cVM.put(Integer.valueOf("USEROPENIDINAPP_TABLE".hashCode()), new 3()); } public static b aIJ() { au.HN(); b bVar = (b) bs.iK("plugin.ext"); if (bVar != null) { return bVar; } bVar = new b(); au.HN().a("plugin.ext", bVar); return bVar; } public static x aIK() { g.Eg().Ds(); if (aIJ().iIY == null) { b aIJ = aIJ(); au.HU(); aIJ.iIY = new x(c.FO()); } return aIJ().iIY; } public static bk aIL() { g.Eg().Ds(); if (aIJ().iIZ == null) { b aIJ = aIJ(); au.HU(); aIJ.iIZ = new bk(c.FO()); } return aIJ().iIZ; } public static bv aIM() { g.Eg().Ds(); if (aIJ().iJa == null) { b aIJ = aIJ(); au.HU(); aIJ.iJa = new bv(c.FO()); } return aIJ().iJa; } public final HashMap<Integer, d> Ci() { return cVM; } public final void bo(boolean z) { aIN(); } private static void aIN() { File file = new File(g.Ei().dqp); if (!file.exists()) { file.mkdirs(); } file = new File(g.Ei().dqp + "image/ext/pcm"); if (!file.exists()) { file.mkdirs(); } com.tencent.mm.sdk.platformtools.x.i("MicroMsg.SubCoreExt", "summerpcm accPath[%s] [%s]", new Object[]{g.Ei().dqp, bi.cjd()}); } public final void bn(boolean z) { et etVar = new et(); etVar.bMw.op = 1; if (!com.tencent.mm.sdk.b.a.sFg.m(etVar)) { com.tencent.mm.sdk.platformtools.x.e("MicroMsg.SubCoreExt", "ExtAgentLifeEvent event fail in onAccountPostReset"); } i.cbs().cbt(); au.HU(); c.FT().a(this.iJe, null); if (this.iJb == null) { this.iJb = new a(); } com.tencent.mm.sdk.b.a.sFg.b(this.iJb); if (this.iJc == null) { this.iJc = new b(); } com.tencent.mm.sdk.b.a.sFg.b(this.iJc); com.tencent.mm.pluginsdk.model.app.i bmf = ao.bmf(); if (bmf != null) { bmf.c(this.iJk); } SharedPreferences chZ = ad.chZ(); this.iJm = chZ.getBoolean("hasTryToInitVoiceControlData", false); iJn = chZ.getBoolean("hasCallVoiceControlApi", false); com.tencent.mm.sdk.platformtools.x.i("MicroMsg.SubCoreExt", "onAccountPostReset,hasTryToInit:%s,hasCallApi:%s", new Object[]{Boolean.valueOf(this.iJm), Boolean.valueOf(iJn)}); au.HU(); c.FR().a(this.iwy); eC(true); com.tencent.mm.plugin.ext.c.c.aJe(); aIN(); } public final void onAccountRelease() { if (this.iJb != null) { com.tencent.mm.sdk.b.a.sFg.c(this.iJb); } if (this.iJc != null) { com.tencent.mm.sdk.b.a.sFg.c(this.iJc); } com.tencent.mm.pluginsdk.model.app.i bmf = ao.bmf(); if (bmf != null) { bmf.d(this.iJk); } au.HU(); c.FT().a(this.iJe); et etVar = new et(); etVar.bMw.op = 2; if (!com.tencent.mm.sdk.b.a.sFg.m(etVar)) { com.tencent.mm.sdk.platformtools.x.e("MicroMsg.SubCoreExt", "ExtAgentLifeEvent event fail in onAccountRelease"); } i cbs = i.cbs(); if (au.HX()) { i.qyP = false; ao.bmi().b(14, cbs); } au.HU(); c.FR().b(this.iwy); com.tencent.mm.plugin.ext.c.c.aJf(); } public static String aIO() { return g.Ei().dqp + "image/ext/pcm"; } public static void aIP() { String str = (String) aIK().get(aa.a.sUa, null); com.tencent.mm.sdk.platformtools.x.i("MicroMsg.SubCoreExt", "sendSportBroadcast pkgNames = " + str); if (str != null) { for (String str2 : str.split(";")) { Intent intent = new Intent("com.tencent.mm.plugin.openapi.Intent.ACTION_SET_SPORT_STEP"); intent.setPackage(str2); com.tencent.mm.compatible.a.a.a(12, new 4(intent)); intent.putExtra("EXTRA_EXT_OPEN_NOTIFY_TYPE", "SPORT_MESSAGE"); ad.getContext().sendBroadcast(intent); } } } public final void gi(int i) { } public static ab da(long j) { if (!au.HX() || j <= 0) { return null; } au.HU(); return c.FR().gl(j); } public static void db(long j) { if (j > 0) { try { au.HU(); if (c.FT().dZ(j)) { au.HU(); f FT = c.FT(); au.HU(); FT.U(c.FT().dW(j)); return; } com.tencent.mm.sdk.platformtools.x.e("MicroMsg.SubCoreExt", "msgId is out of range, " + j); } catch (Throwable e) { com.tencent.mm.sdk.platformtools.x.e("MicroMsg.SubCoreExt", e.getMessage()); com.tencent.mm.sdk.platformtools.x.printErrStackTrace("MicroMsg.SubCoreExt", e, "", new Object[0]); } } } public final void aIQ() { this.iJg.removeMessages(0); this.iJg.sendEmptyMessageDelayed(0, 1600); } private void eC(boolean z) { if (!this.iJl) { return; } if (z && this.iJm) { com.tencent.mm.sdk.platformtools.x.i("MicroMsg.SubCoreExt", "fromStartApp and already try to init"); } else if (z || iJn) { com.tencent.mm.sdk.platformtools.x.i("MicroMsg.SubCoreExt", "initLocalVoiceControl,fromStartApp:%s,hasTryToInit:%s,hasCallApi:%s", new Object[]{Boolean.valueOf(z), Boolean.valueOf(this.iJm), Boolean.valueOf(iJn)}); this.iJl = false; au.Em().h(new 2(this), 10000); } } }
package com.example.news.Util; import com.example.news.Gson.NewsList; import com.google.gson.Gson; public class Utility { //使用Gson解析获取的json数据 public static NewsList parseJsonWithGson(final String requestText) { Gson gson = new Gson(); return gson.fromJson(requestText, NewsList.class); } }
import static edu.princeton.cs.algs4.StdRandom.uniform; /** * @author andreea teodor */ public class CalculateAvgThreshold{ public static void main(String[] args) { double sum = 0.0; int times = 0; for (int i = 0; i < 100; i++) { int n = uniform(2, 100); Percolation a = new Percolation(n); for (int j = 0; j < n * n; j++) { int k = uniform(1, n + 1); int q = uniform(1, n + 1); a.open(k, q); if (a.percolates()) { int openSites = a.numberOfOpenSites(); double p = (double) openSites / (n * n); sum += p; times++; break; } } } double threshP = sum / times; System.out.println("p* = " + threshP); } }
package kr.or.kosta.sample; import java.util.Calendar; import kr.or.kosta.sample2.Bar; public class Foo { public static void main(String[] args) { Bar bar = new Bar(); bar.myMethod(); String message = "명절 잘들 쉬세요"; Calendar today; int num = 343434343; String a; String str = String.valueOf(num); System.out.println(str.length()); } }
package com.facebook.react; import android.app.Activity; import android.app.Application; import android.content.Context; import com.facebook.i.a.a; import com.facebook.react.bridge.JSBundleLoader; import com.facebook.react.bridge.JSCJavaScriptExecutorFactory; import com.facebook.react.bridge.JSIModulesProvider; import com.facebook.react.bridge.JavaScriptExecutorFactory; import com.facebook.react.bridge.NativeModuleCallExceptionHandler; import com.facebook.react.bridge.NotThreadSafeBridgeIdleDebugListener; import com.facebook.react.bridge.RNDegradeExceptionHandler; import com.facebook.react.bridge.RNJavaScriptRuntime; import com.facebook.react.common.LifecycleState; import com.facebook.react.devsupport.RedBoxHandler; import com.facebook.react.devsupport.interfaces.DevBundleDownloadListener; import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler; import com.facebook.react.modules.systeminfo.AndroidInfoHelpers; import com.facebook.react.uimanager.UIImplementationProvider; import java.util.ArrayList; import java.util.List; public class ReactInstanceManagerBuilder { private Application mApplication; private NotThreadSafeBridgeIdleDebugListener mBridgeIdleDebugListener; private Activity mCurrentActivity; private DefaultHardwareBackBtnHandler mDefaultHardwareBackBtnHandler; private RNDegradeExceptionHandler mDegradeExceptionHandler; private boolean mDelayViewManagerClassLoadsEnabled; private DevBundleDownloadListener mDevBundleDownloadListener; private LifecycleState mInitialLifecycleState; private String mJSBundleAssetUrl; private JSBundleLoader mJSBundleLoader; private JSIModulesProvider mJSIModulesProvider; private String mJSMainModulePath; private JavaScriptExecutorFactory mJavaScriptExecutorFactory; private boolean mLazyNativeModulesEnabled; private boolean mLazyViewManagersEnabled; private int mMinNumShakes = 1; private int mMinTimeLeftInFrameForNonBatchedOperationMs = -1; private NativeModuleCallExceptionHandler mNativeModuleCallExceptionHandler; private final List<ReactPackage> mPackages = new ArrayList<ReactPackage>(); private RedBoxHandler mRedBoxHandler; private RNJavaScriptRuntime.SplitCommonType mSplitCommonType; private UIImplementationProvider mUIImplementationProvider; private boolean mUseDeveloperSupport; public ReactInstanceManagerBuilder addPackage(ReactPackage paramReactPackage) { this.mPackages.add(paramReactPackage); return this; } public ReactInstanceManagerBuilder addPackages(List<ReactPackage> paramList) { this.mPackages.addAll(paramList); return this; } public ReactInstanceManager build() { JSCJavaScriptExecutorFactory jSCJavaScriptExecutorFactory; a.a(this.mApplication, "Application property has not been set with this builder"); boolean bool = this.mUseDeveloperSupport; boolean bool1 = true; if (bool || this.mJSBundleAssetUrl != null || this.mJSBundleLoader != null) { bool = true; } else { bool = false; } a.a(bool, "JS Bundle File or Asset URL has to be provided when dev support is disabled"); bool = bool1; if (this.mJSMainModulePath == null) { bool = bool1; if (this.mJSBundleAssetUrl == null) if (this.mJSBundleLoader != null) { bool = bool1; } else { bool = false; } } a.a(bool, "Either MainModulePath or JS Bundle File needs to be provided"); if (this.mUIImplementationProvider == null) this.mUIImplementationProvider = new UIImplementationProvider(); String str1 = this.mApplication.getPackageName(); String str2 = AndroidInfoHelpers.getFriendlyDeviceName(); Application application = this.mApplication; Activity activity = this.mCurrentActivity; DefaultHardwareBackBtnHandler defaultHardwareBackBtnHandler = this.mDefaultHardwareBackBtnHandler; JavaScriptExecutorFactory javaScriptExecutorFactory2 = this.mJavaScriptExecutorFactory; JavaScriptExecutorFactory javaScriptExecutorFactory1 = javaScriptExecutorFactory2; if (javaScriptExecutorFactory2 == null) jSCJavaScriptExecutorFactory = new JSCJavaScriptExecutorFactory(str1, str2, this.mSplitCommonType); if (this.mJSBundleLoader == null) { String str = this.mJSBundleAssetUrl; if (str != null) { JSBundleLoader jSBundleLoader1 = JSBundleLoader.createAssetLoader((Context)this.mApplication, str, false, this.mSplitCommonType); return new ReactInstanceManager((Context)application, activity, defaultHardwareBackBtnHandler, (JavaScriptExecutorFactory)jSCJavaScriptExecutorFactory, jSBundleLoader1, this.mJSMainModulePath, this.mPackages, this.mUseDeveloperSupport, this.mBridgeIdleDebugListener, (LifecycleState)a.a(this.mInitialLifecycleState, "Initial lifecycle state was not set"), this.mUIImplementationProvider, this.mNativeModuleCallExceptionHandler, this.mRedBoxHandler, this.mLazyNativeModulesEnabled, this.mLazyViewManagersEnabled, this.mDelayViewManagerClassLoadsEnabled, this.mDevBundleDownloadListener, this.mMinNumShakes, this.mMinTimeLeftInFrameForNonBatchedOperationMs, this.mJSIModulesProvider, this.mDegradeExceptionHandler); } } JSBundleLoader jSBundleLoader = this.mJSBundleLoader; return new ReactInstanceManager((Context)application, activity, defaultHardwareBackBtnHandler, (JavaScriptExecutorFactory)jSCJavaScriptExecutorFactory, jSBundleLoader, this.mJSMainModulePath, this.mPackages, this.mUseDeveloperSupport, this.mBridgeIdleDebugListener, (LifecycleState)a.a(this.mInitialLifecycleState, "Initial lifecycle state was not set"), this.mUIImplementationProvider, this.mNativeModuleCallExceptionHandler, this.mRedBoxHandler, this.mLazyNativeModulesEnabled, this.mLazyViewManagersEnabled, this.mDelayViewManagerClassLoadsEnabled, this.mDevBundleDownloadListener, this.mMinNumShakes, this.mMinTimeLeftInFrameForNonBatchedOperationMs, this.mJSIModulesProvider, this.mDegradeExceptionHandler); } public ReactInstanceManager prebuild() { JSCJavaScriptExecutorFactory jSCJavaScriptExecutorFactory; a.a(this.mApplication, "Application property has not been set with this builder"); if (this.mUIImplementationProvider == null) this.mUIImplementationProvider = new UIImplementationProvider(); String str1 = this.mApplication.getPackageName(); String str2 = AndroidInfoHelpers.getFriendlyDeviceName(); Application application = this.mApplication; Activity activity = this.mCurrentActivity; DefaultHardwareBackBtnHandler defaultHardwareBackBtnHandler = this.mDefaultHardwareBackBtnHandler; JavaScriptExecutorFactory javaScriptExecutorFactory2 = this.mJavaScriptExecutorFactory; JavaScriptExecutorFactory javaScriptExecutorFactory1 = javaScriptExecutorFactory2; if (javaScriptExecutorFactory2 == null) jSCJavaScriptExecutorFactory = new JSCJavaScriptExecutorFactory(str1, str2, this.mSplitCommonType); if (this.mJSBundleLoader == null) { String str = this.mJSBundleAssetUrl; if (str != null) { JSBundleLoader jSBundleLoader1 = JSBundleLoader.createAssetLoader((Context)this.mApplication, str, false, this.mSplitCommonType); return new ReactInstanceManager((Context)application, activity, defaultHardwareBackBtnHandler, (JavaScriptExecutorFactory)jSCJavaScriptExecutorFactory, jSBundleLoader1, this.mJSMainModulePath, this.mPackages, this.mUseDeveloperSupport, this.mBridgeIdleDebugListener, (LifecycleState)a.a(this.mInitialLifecycleState, "Initial lifecycle state was not set"), this.mUIImplementationProvider, this.mNativeModuleCallExceptionHandler, this.mRedBoxHandler, this.mLazyNativeModulesEnabled, this.mLazyViewManagersEnabled, this.mDelayViewManagerClassLoadsEnabled, this.mDevBundleDownloadListener, this.mMinNumShakes, this.mMinTimeLeftInFrameForNonBatchedOperationMs, this.mJSIModulesProvider, this.mDegradeExceptionHandler); } } JSBundleLoader jSBundleLoader = this.mJSBundleLoader; return new ReactInstanceManager((Context)application, activity, defaultHardwareBackBtnHandler, (JavaScriptExecutorFactory)jSCJavaScriptExecutorFactory, jSBundleLoader, this.mJSMainModulePath, this.mPackages, this.mUseDeveloperSupport, this.mBridgeIdleDebugListener, (LifecycleState)a.a(this.mInitialLifecycleState, "Initial lifecycle state was not set"), this.mUIImplementationProvider, this.mNativeModuleCallExceptionHandler, this.mRedBoxHandler, this.mLazyNativeModulesEnabled, this.mLazyViewManagersEnabled, this.mDelayViewManagerClassLoadsEnabled, this.mDevBundleDownloadListener, this.mMinNumShakes, this.mMinTimeLeftInFrameForNonBatchedOperationMs, this.mJSIModulesProvider, this.mDegradeExceptionHandler); } public ReactInstanceManagerBuilder setApplication(Application paramApplication) { this.mApplication = paramApplication; RNJavaScriptRuntime.setApplication(paramApplication); return this; } public ReactInstanceManagerBuilder setBridgeIdleDebugListener(NotThreadSafeBridgeIdleDebugListener paramNotThreadSafeBridgeIdleDebugListener) { this.mBridgeIdleDebugListener = paramNotThreadSafeBridgeIdleDebugListener; return this; } public ReactInstanceManagerBuilder setBundleAssetName(String paramString) { if (paramString == null) { paramString = null; } else { StringBuilder stringBuilder = new StringBuilder("assets://"); stringBuilder.append(paramString); paramString = stringBuilder.toString(); } this.mJSBundleAssetUrl = paramString; this.mJSBundleLoader = null; return this; } public ReactInstanceManagerBuilder setBundleAssetName(String paramString, RNJavaScriptRuntime.SplitCommonType paramSplitCommonType) { if (paramString == null) { paramString = null; } else { StringBuilder stringBuilder = new StringBuilder("assets://"); stringBuilder.append(paramString); paramString = stringBuilder.toString(); } this.mJSBundleAssetUrl = paramString; this.mJSBundleLoader = null; this.mSplitCommonType = paramSplitCommonType; return this; } public ReactInstanceManagerBuilder setCurrentActivity(Activity paramActivity) { this.mCurrentActivity = paramActivity; return this; } public ReactInstanceManagerBuilder setDefaultHardwareBackBtnHandler(DefaultHardwareBackBtnHandler paramDefaultHardwareBackBtnHandler) { this.mDefaultHardwareBackBtnHandler = paramDefaultHardwareBackBtnHandler; return this; } public ReactInstanceManagerBuilder setDegradeExceptionHandler(RNDegradeExceptionHandler paramRNDegradeExceptionHandler) { this.mDegradeExceptionHandler = paramRNDegradeExceptionHandler; return this; } public ReactInstanceManagerBuilder setDelayViewManagerClassLoadsEnabled(boolean paramBoolean) { this.mDelayViewManagerClassLoadsEnabled = paramBoolean; return this; } public ReactInstanceManagerBuilder setDevBundleDownloadListener(DevBundleDownloadListener paramDevBundleDownloadListener) { this.mDevBundleDownloadListener = paramDevBundleDownloadListener; return this; } public ReactInstanceManagerBuilder setInitialLifecycleState(LifecycleState paramLifecycleState) { this.mInitialLifecycleState = paramLifecycleState; return this; } public ReactInstanceManagerBuilder setJSBundleFile(String paramString) { if (paramString.startsWith("assets://")) { this.mJSBundleAssetUrl = paramString; this.mJSBundleLoader = null; return this; } return setJSBundleLoader(JSBundleLoader.createFileLoader(paramString)); } public ReactInstanceManagerBuilder setJSBundleFile(String paramString, RNJavaScriptRuntime.SplitCommonType paramSplitCommonType) { if (paramString.startsWith("assets://")) { this.mJSBundleAssetUrl = paramString; this.mJSBundleLoader = null; this.mSplitCommonType = paramSplitCommonType; return this; } return setJSBundleLoader(JSBundleLoader.createFileLoader(paramString, paramSplitCommonType)); } public ReactInstanceManagerBuilder setJSBundleLoader(JSBundleLoader paramJSBundleLoader) { this.mJSBundleLoader = paramJSBundleLoader; this.mJSBundleAssetUrl = null; return this; } public ReactInstanceManagerBuilder setJSIModulesProvider(JSIModulesProvider paramJSIModulesProvider) { this.mJSIModulesProvider = paramJSIModulesProvider; return this; } public ReactInstanceManagerBuilder setJSMainModulePath(String paramString) { this.mJSMainModulePath = paramString; return this; } public ReactInstanceManagerBuilder setJavaScriptExecutorFactory(JavaScriptExecutorFactory paramJavaScriptExecutorFactory) { this.mJavaScriptExecutorFactory = paramJavaScriptExecutorFactory; return this; } public ReactInstanceManagerBuilder setLazyNativeModulesEnabled(boolean paramBoolean) { this.mLazyNativeModulesEnabled = paramBoolean; return this; } public ReactInstanceManagerBuilder setLazyViewManagersEnabled(boolean paramBoolean) { this.mLazyViewManagersEnabled = paramBoolean; return this; } public ReactInstanceManagerBuilder setMinNumShakes(int paramInt) { this.mMinNumShakes = paramInt; return this; } public ReactInstanceManagerBuilder setMinTimeLeftInFrameForNonBatchedOperationMs(int paramInt) { this.mMinTimeLeftInFrameForNonBatchedOperationMs = paramInt; return this; } public ReactInstanceManagerBuilder setNativeModuleCallExceptionHandler(NativeModuleCallExceptionHandler paramNativeModuleCallExceptionHandler) { this.mNativeModuleCallExceptionHandler = paramNativeModuleCallExceptionHandler; return this; } public ReactInstanceManagerBuilder setRedBoxHandler(RedBoxHandler paramRedBoxHandler) { this.mRedBoxHandler = paramRedBoxHandler; return this; } public ReactInstanceManagerBuilder setSplitCommonBundleFile(String paramString, RNJavaScriptRuntime.SplitCommonType paramSplitCommonType) { if (paramSplitCommonType == RNJavaScriptRuntime.SplitCommonType.SPLIT_COMMONJS) { RNJavaScriptRuntime.setCommonJsBundle(paramString); } else if (paramSplitCommonType == RNJavaScriptRuntime.SplitCommonType.SPLIT_SNAPSHOT) { RNJavaScriptRuntime.setSnapSHotBundle(paramString); } this.mSplitCommonType = paramSplitCommonType; return this; } public ReactInstanceManagerBuilder setSplitCommonType(RNJavaScriptRuntime.SplitCommonType paramSplitCommonType) { this.mSplitCommonType = paramSplitCommonType; return this; } public ReactInstanceManagerBuilder setUIImplementationProvider(UIImplementationProvider paramUIImplementationProvider) { this.mUIImplementationProvider = paramUIImplementationProvider; return this; } public ReactInstanceManagerBuilder setUseDeveloperSupport(boolean paramBoolean) { this.mUseDeveloperSupport = paramBoolean; return this; } } /* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\facebook\react\ReactInstanceManagerBuilder.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
/* * 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 pe.gob.onpe.adan.service.Adan.impl; import java.util.ArrayList; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import pe.gob.onpe.adan.dao.adan.ReporteElectorDao; import pe.gob.onpe.adan.model.adan.ReporteElector; import pe.gob.onpe.adan.model.adan.ReporteElectorPorLocal; import pe.gob.onpe.adan.service.Adan.ReporteElectorService; /** * * @author bvaldez */ @Service("reporteElectorService") public class ReporteElectorServiceImpl implements ReporteElectorService{ @Autowired private ReporteElectorDao dao; @Override public ReporteElector getNacion(String tipo) { return dao.getNacion(tipo); } @Override public ReporteElector getPeru(String tipo) { return dao.getPeru(tipo); } @Override public ReporteElector getExtranjero(String tipo) { return dao.getExtranjero(tipo); } @Override public ReporteElector getOdpe(String tipo, String codigo) { return dao.getOdpe(tipo,codigo); } @Override public ReporteElector getOdpebyProvincia(String tipo, String codigo, String codigo2) { return dao.getOdpebyProvincia(tipo,codigo,codigo2); } @Override public ReporteElector getOdpebyDepartamento(String tipo, String codigo, String codigo2) { return dao.getOdpebyDepartamento(tipo,codigo,codigo2); } @Override public ReporteElector getDepartamentoOrContinente(String tipo, String codigo) { return dao.getDepartamentoOrContinente(tipo,codigo); } @Override public ReporteElector getProvinciaOrPais(String tipo, String codigo) { return dao.getProvinciaOrPais(tipo,codigo); } @Override public ReporteElector getDistritoOrCiudad(String tipo, String codigo) { return dao.getDistritoOrCiudad(tipo,codigo); } @Override public ReporteElectorPorLocal getLocalOrMesa(String tipo, String codigo) { return dao.getLocalOrMesa(tipo,codigo); } @Override public String getReporteElector(Integer option, String ubigeo) { return dao.getReporteElector(option, ubigeo); } @Override public ArrayList getElectorByHistoricoAndMesa(String dni) { return dao.getElectorByHistoricoAndMesa(dni); } @Override public ArrayList getElectorByHistoricoAndLocal(String dni) { return dao.getElectorByHistoricoAndLocal(dni); } @Override public boolean isAssignedMesaElector(String dni) { return dao.isAssignedMesaElector(dni); } }
package com.snow.gk.core.utils; import com.snow.gk.core.exception.CustomException; import com.snow.gk.core.ui.drivers.DriverSetup; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.WebElement; public class JSExecutor { private JSExecutor(){} public static void jsExecutor(String value) throws CustomException { try { JavascriptExecutor js = (JavascriptExecutor) DriverSetup.getDriver(); js.executeScript(value); } catch (WebDriverException we) { throw new CustomException("Failed in jsExecutor method "+we); } } public static void jsClick(WebElement element){ getJavaScriptExec().executeScript("arguments[0].click();", element); Waits.waitForPageLoadJS(); } public static JavascriptExecutor getJavaScriptExec() { return (JavascriptExecutor) DriverSetup.getDriver(); } // Get Value using Java Script Executor public static String jsGetValue(WebElement element){ return getJavaScriptExec().executeScript("return arguments[0].value;",element).toString(); } }
package javadatetime; import java.time.*; import java.time.temporal.Temporal; import java.time.temporal.ChronoUnit; public class JavaPeriodExample { public static void main(String[] args) { Period period1=Period.ofDays(24);//Obtains a Period representing a number of days. Temporal temp=period1.addTo(LocalDate.now()); //period of days adding to current days System.out.println(temp); Period period2=Period.of(2020, 01, 03); //Period representing a number of years, months and days System.out.println(period2.toString()); Period period3=Period.ofMonths(4); Period period4=period3.minus(Period.ofMonths(2)); System.out.println(period4); Period period5=period3.plus(Period.ofMonths(2)); System.out.println(period5); Duration d=Duration.between(LocalTime.NOON,LocalTime.MAX);//Obtains a Duration representing the duration between two temporal objects. System.out.println(d.get(ChronoUnit.SECONDS)); Duration d1=Duration.between(LocalTime.MAX,LocalTime.NOON); System.out.println(d1.isNegative()); Duration d2=Duration.between(LocalTime.NOON,LocalTime.MAX); System.out.println(d2.isNegative()); System.out.println(d.getSeconds()); Duration d3=d.minus(d);//Returns a copy of this duration with the specified duration subtracted System.out.println(d3.getSeconds()); Duration d4=d.plus(d);//Returns a copy of this duration with the specified duration added System.out.println(d4.getSeconds()); } }
package co.th.aten.network.report; import java.io.File; import java.util.List; import java.util.Map; import javax.faces.context.FacesContext; import javax.servlet.ServletContext; import net.sf.jasperreports.engine.JREmptyDataSource; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperReport; import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource; import net.sf.jasperreports.engine.util.JRLoader; import co.th.aten.network.model.MoneyReportModel; public class MoneyReportAdjustReport extends AbstractReport { /** * */ private static final long serialVersionUID = -5326919701601476597L; private final String fileName = "/reports/MoneyAdjustReport.jasper"; private List<MoneyReportModel> model; public MoneyReportAdjustReport() { super(); } @Override public void fill() { try { FacesContext facesContext = FacesContext.getCurrentInstance(); ServletContext servletContext = (ServletContext) facesContext .getExternalContext().getContext(); File reportFile = new File(servletContext.getRealPath(fileName)); System.out.println("report file="+reportFile.getAbsolutePath()); jasperReport = (JasperReport) JRLoader.loadObject(reportFile); if (model == null) { jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, new JREmptyDataSource()); } else { jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, new JRBeanCollectionDataSource(model)); } } catch (JRException e) { e.printStackTrace(); }catch(Exception e){ e.printStackTrace(); } } public List<MoneyReportModel> getModel() { return model; } public void setModel(List<MoneyReportModel> model) { this.model = model; } public Map<String, Object> getParameter() { return parameters; } }
//对冲型双指针,不断把短的那一边往里移动 class Solution { public int maxArea(int[] height) { int size = height.length; int start = 0; int end = size - 1; int ans = 0; while(start < end){ ans = Math.max(Math.min(height[start], height[end]) * (end - start), ans); if(height[start] > height[end]){ end--; } else{ start++; } } return ans; } }
package kr.co.sist.mgr.faq.vo; /** * 관리자 화면에서 문의목록을 간단하게 보여주기 위한 목적의 VO * @author JU */ public class MgrReqVO { private int reqNum; private String reqType, reqTitle, id, reqFlag; public MgrReqVO() { } public MgrReqVO(int reqNum, String reqType, String reqTitle, String id, String reqFlag) { this.reqNum = reqNum; this.reqType = reqType; this.reqTitle = reqTitle; this.id = id; this.reqFlag = reqFlag; } public int getReqNum() { return reqNum; } public String getReqType() { return reqType; } public String getReqTitle() { return reqTitle; } public String getId() { return id; } public String getReqFlag() { return reqFlag; } public void setReqNum(int reqNum) { this.reqNum = reqNum; } public void setReqType(String reqType) { this.reqType = reqType; } public void setReqTitle(String reqTitle) { this.reqTitle = reqTitle; } public void setId(String id) { this.id = id; } public void setReqFlag(String reqFlag) { this.reqFlag = reqFlag; } }
*/ package Iterator; /** * * @author MSI */ public interface patientDetails { public Iterator getIterator(); }
package com.estilox.application.entityModel; import java.io.Serializable; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToOne; import javax.persistence.Table; import com.estilox.application.resolver.EntityIdResolver; import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.ObjectIdGenerators; /** * * @author Kamesh * **/ @Entity @Table(name="DOC_USER_ORDERS") @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id",resolver=EntityIdResolver.class,scope=UserOrders.class) public class UserOrders implements Serializable{ private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="ORDER_ID",nullable=false,updatable=false) private Long id; @Column(name="DELIVERY_STATUS") private String deliveryStatus; @Column(name="QUANTITY") private Integer quantity; private Integer productPrice; private Integer productPriceTotal; @OneToOne(cascade=CascadeType.ALL) @JoinColumn(name="PRODUCT_ID") private Products products; @ManyToOne(cascade=CascadeType.ALL) @JoinColumn(name="USER_ID") private User user; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getDeliveryStatus() { return deliveryStatus; } public void setDeliveryStatus(String deliveryStatus) { this.deliveryStatus = deliveryStatus; } public Integer getQuantity() { return quantity; } public void setQuantity(Integer quantity) { this.quantity = quantity; } public Integer getProductPrice() { return productPrice; } public void setProductPrice(Integer productPrice) { this.productPrice = productPrice; } public Integer getProductPriceTotal() { return productPriceTotal; } public void setProductPriceTotal(Integer productPriceTotal) { this.productPriceTotal = productPriceTotal; } public Products getProducts() { return products; } public void setProducts(Products products) { this.products = products; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; public class Store implements process { LinkedList<Item> stock; LinkedList<Customer> customers; Queue<Customer> customerQueue; Store() { stock = new LinkedList<>(); customers = new LinkedList<>(); customerQueue = new LinkedList<>(); } void addNewCustomer(Customer customer) { customers.add(customer); } Customer addNewCustomerToQueue(String id, LinkedList<Item> items) { for (Customer customer : customers) { if (customer.customerId.equals(id)) { customer.cart = items; customerQueue.add(customer); return customer; } } return null; } // this will add item to the stock void addItems(Item item) { stock.add(item); } // this will print all items using iterator void printItem() { Iterator<Item> iterator = stock.iterator(); while (iterator.hasNext()) System.out.println(iterator.next()); } // this will sort items on the basis of id using bubble sort void sortItems() { int n = stock.size(); for (int i = 0; i < n - 1; i++) for (int j = 0; j < n - i - 1; j++) if (stock.get(j).itemId.compareTo(stock.get(j + 1).itemId) > 0) { Item temp = stock.get(j); stock.set(j, stock.get(j + 1)); stock.set(j + 1, temp); } } // this will search id using binary search and return its index0 Item searchItem(String id) { int index = binarySearch(stock, 0, stock.size() - 1, id); if (index < 0) return null; return stock.get(index); } // the actual implementation of binary search int binarySearch(LinkedList<Item> arr, int l, int r, String x) { if (r >= l) { int mid = l + (r - l) / 2; if (arr.get(mid).itemId.compareTo(x) == 0) return mid; if (arr.get(mid).itemId.compareTo(x) > 0) return binarySearch(arr, l, mid - 1, x); return binarySearch(arr, mid + 1, r, x); } return -1; } @Override public void run() { while (!customerQueue.isEmpty()) { customerQueue.poll().run(); } } // this will print all customersA public void printCustomer() { Iterator<Customer> iterator = customers.iterator(); while (iterator.hasNext()) System.out.println(iterator.next()); } }
/* * 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 choiceofuser; import mainclasses.Student; import mainclasses.Course; import mainclasses.Teacher; import mainclasses.Assignments; import java.util.Scanner; import methodsforhelp.Instructions; import methodsforhelp.Utils; import methodsforhelp.colour; import static methodsforhelp.Utils.checkingIntegers; import static methodsforhelp.Utils.checkingStringToBeOnlyLetters; import static methodsforhelp.Utils.validationAssignment; /** * * @author Nasos */ public class Creation { private static Scanner scanner = new Scanner(System.in); /** * Create Student and put him in the list. */ private static void createStudent() { Student newStudent = new Student(); while (true) { System.out.println(colour.TEXT_GREEN+"Give Student Details"+colour.TEXT_RESET); System.out.println(colour.TEXT_CYAN+"Give the first name of the new Student : "+colour.TEXT_RESET); newStudent.setFirstName(checkingStringToBeOnlyLetters()); System.out.println(colour.TEXT_CYAN+"Give the last name of the new Student : "+colour.TEXT_RESET); newStudent.setLastName(checkingStringToBeOnlyLetters()); System.out.println(colour.TEXT_CYAN+"Give Date of Birth : "+colour.TEXT_RESET); System.out.println(colour.TEXT_YELLOW+"dd-MM-yyyy"+colour.TEXT_RESET); newStudent.setDateOfBirth(); System.out.println(colour.TEXT_CYAN+"Give tuition Fees : "+colour.TEXT_RESET); newStudent.setTuitionFees(checkingIntegers()); if (!Student.existStudent(newStudent)) { //Here we Check is this alredy exist! Student.saveStudent(newStudent); break; } else { System.out.println(colour.TEXT_RED+"This Student already exists! Give a new Student!"+colour.TEXT_RESET); } } } /** * Create Teacher and put him in the list. */ private static void createTeacher() { Teacher newTeacher = new Teacher(); while (true) { System.out.println(colour.TEXT_GREEN+"Give Teacher Details"+colour.TEXT_RESET); System.out.println(colour.TEXT_CYAN+"Give the first name of the new Teacher : "+colour.TEXT_RESET); newTeacher.setFirstName(checkingStringToBeOnlyLetters()); System.out.println(colour.TEXT_CYAN+"Give the last name of the new Teacher : "+colour.TEXT_RESET); newTeacher.setLastName(checkingStringToBeOnlyLetters()); System.out.println(colour.TEXT_CYAN+"Give Courses he is gonna Teach : "+colour.TEXT_RESET); newTeacher.setTeachingCourses(checkingStringToBeOnlyLetters()); if (!Teacher.existTeacher(newTeacher)) { Teacher.saveTeacher(newTeacher); break; //Here we Check is this alredy exist! } else { System.out.println(colour.TEXT_RED+"This teacher already exists! Give a new Teacher!"+colour.TEXT_RESET); } } } /** * Create course and put it in the list. */ private static void createCourse() { Course newCourse = new Course(); while (true) { System.out.println(colour.TEXT_GREEN+"Give Course Details"+colour.TEXT_RESET); System.out.println(colour.TEXT_CYAN+"Give Course Title : "+colour.TEXT_RESET); newCourse.setCourseTitle(scanner.nextLine()); System.out.println(colour.TEXT_CYAN+"Give course Stream : "+colour.TEXT_RESET); newCourse.setStream(scanner.nextLine()); System.out.println(colour.TEXT_CYAN+"Give Course Type : "+colour.TEXT_RESET); newCourse.setType(checkingStringToBeOnlyLetters()); System.out.println(colour.TEXT_CYAN+"Give the date this course Start : "+colour.TEXT_RESET); System.out.println(colour.TEXT_YELLOW+"dd-MM-yyyy"+colour.TEXT_RESET); newCourse.setStartDate(); System.out.println(colour.TEXT_CYAN+"Give the date this course Ends : "+colour.TEXT_RESET); System.out.println(colour.TEXT_YELLOW+"dd-MM-yyyy"+colour.TEXT_RESET); newCourse.setEndDate(); if (!Course.existCourse(newCourse)) { Course.getCoursesList().add(newCourse); break; //Here we Check is this alredy exist! } else { System.out.println(colour.TEXT_RED+"This course already exists! Give a new Course!"+colour.TEXT_RESET); } } } /** * Create course and put it in the list. */ private static void createAssignment() { Assignments newAssignment = new Assignments(); while (true) { System.out.println(colour.TEXT_GREEN+"Give Assignment Details!"+colour.TEXT_RESET); System.out.println(colour.TEXT_CYAN+"Give Assignment Title :"+colour.TEXT_RESET); newAssignment.setTitle(scanner.nextLine()); System.out.println(colour.TEXT_CYAN+"Give Assignment Description : "+colour.TEXT_RESET); newAssignment.setDescription(scanner.nextLine()); System.out.println(colour.TEXT_CYAN+"Give Assignment Sub Date Time : "+colour.TEXT_RESET); System.out.println(colour.TEXT_YELLOW+"dd-MM-yyyy"+colour.TEXT_RESET); newAssignment.setSubDateTime(validationAssignment()); System.out.println(colour.TEXT_CYAN+"Give Assignment Oral Mark : "+colour.TEXT_RESET); newAssignment.setOralMark(checkingIntegers()); System.out.println(colour.TEXT_CYAN+"Give Assignment Total Mark : "+colour.TEXT_RESET); newAssignment.setTotalMark(checkingIntegers()); if (!Assignments.existAssignemnt(newAssignment)) { Assignments.saveAssignment(newAssignment); break; //Here we Check is this alredy exist! } else { System.out.println(colour.TEXT_RED+"This Assignment already exists! Give a new Assignemnt"+colour.TEXT_RESET); } } } static void menuCreationStudent() { while (true) { Creation.createStudent(); Instructions.IntsructionsSelectionBetweenOneOrTwo(); boolean result = Utils.optionsTrueOrFalse(); if (result) { System.out.println(colour.TEXT_GREEN+"Lets make the new Student!"+colour.TEXT_RESET); } else { break; } } } static void menuCreationTeacher() { while (true) { Creation.createTeacher(); Instructions.IntsructionsSelectionBetweenOneOrTwo(); boolean result = Utils.optionsTrueOrFalse(); if (result) { System.out.println(colour.TEXT_GREEN+"Lets make the new Teacher!"+colour.TEXT_RESET); } else { break; } } } static void menuCreationAssignment() { while (true) { Creation.createAssignment(); Instructions.IntsructionsSelectionBetweenOneOrTwo(); boolean result = Utils.optionsTrueOrFalse(); if (result) { System.out.println(colour.TEXT_GREEN+"Lets make the new Assignment!"+colour.TEXT_RESET); } else { break; } } } static void menuCreationCourse() { while (true) { Creation.createCourse(); Instructions.IntsructionsSelectionBetweenOneOrTwo(); boolean result = Utils.optionsTrueOrFalse(); if (result) { System.out.println(colour.TEXT_GREEN+"Lets make the new Course!"+colour.TEXT_RESET); } else { break; } } } }
package com.espendwise.manta.web.util.smac; import com.espendwise.manta.util.Utility; import com.espendwise.manta.web.util.UrlPathAssistent; import org.apache.log4j.Logger; import org.springframework.context.ApplicationContext; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.context.support.WebApplicationContextUtils; import org.springframework.web.servlet.HandlerMapping; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSessionAttributeListener; import javax.servlet.http.HttpSessionBindingEvent; import java.util.Map; public class SmacListener implements HttpSessionAttributeListener { private static final Logger logger = Logger.getLogger(SmacListener.class); @Override public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) { logger.debug("attributeAdded()=> BEGIN"); try { String attrName = httpSessionBindingEvent.getName(); HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder .getRequestAttributes()) .getRequest(); logger.debug("attributeAdded()=> attrName: " + attrName + ", " + request.getRequestURI()); ApplicationContext ctx = WebApplicationContextUtils. getWebApplicationContext(httpSessionBindingEvent.getSession().getServletContext()); SmacHandler smacHandler = ctx.getBeansOfType(SmacHandler.class) .values() .iterator() .next(); logger.debug("attributeAdded()=> HandlerMappings: " + "{" + ctx.getBeansOfType(HandlerMapping.class) + "}"); if (smacHandler.getDescriptions().containsKey(attrName)) { SmacDesc desc = smacHandler.getDescriptions().get(attrName); Map<String, String> pathParams = UrlPathAssistent.getPathVariables(request); String processPath = UrlPathAssistent.createPath(desc.getHandlerPath(), pathParams); SmacMapping modelAttributesMapping = (SmacMapping) httpSessionBindingEvent.getSession().getAttribute(SmacMapping.SESSION_KEY); if (modelAttributesMapping == null) { modelAttributesMapping = new SmacMapping(); httpSessionBindingEvent.getSession().setAttribute(SmacMapping.SESSION_KEY, modelAttributesMapping); } logger.debug("attributeAdded()=> bind path " + processPath); if (Utility.isSet(pathParams) && Utility.isSet(pathParams)) { modelAttributesMapping.bindSma( processPath, new SmacDesc(desc.getHandlerPath(), desc.getName(), desc.getPathMapping(), desc.getController() ) ); } } } catch (Exception e) { logger.error(e.getMessage(), e); } logger.debug("attributeAdded()=> END"); } @Override public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) { logger.debug("attributeRemoved()=> BEGIN"); logger.debug("attributeRemoved()=> remove value: " + httpSessionBindingEvent.getName()); httpSessionBindingEvent.getSession().removeAttribute(httpSessionBindingEvent.getName()); logger.debug("attributeRemoved()=> END"); } @Override public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) { } }
/* * 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 padraosingletonnumerotelefone; import java.io.IOException; import persistencia.PersistenciaSerializada; /** * * @author 20131BSI0173 */ public class Principal { /** * @param args the command line arguments * @throws java.io.IOException * @throws java.lang.ClassNotFoundException */ public static void main(String[] args) throws IOException, ClassNotFoundException { // TODO code application logic here GeradorDeNumerosUnicos gerador = GeradorDeNumerosUnicos.getNumero(); persistencia.PersistenciaSerializada persistencia = new PersistenciaSerializada(); // System.out.println("Próximo número: "+ gerador.getProximoNumero()); // System.out.println("Próximo número: "+ gerador.getProximoNumero()); // System.out.println("Próximo número: "+ gerador.getProximoNumero()); persistencia.salvarObjeto(gerador); GeradorDeNumerosUnicos numeroRecuperado = (GeradorDeNumerosUnicos) persistencia.recuperarObjeto(GeradorDeNumerosUnicos.class); numeroRecuperado.listarNumerosGerados(10); } }
package ru.kappers.service.parser; import org.apache.tomcat.util.digester.DocumentProperties; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.util.ResourceUtils; import ru.kappers.model.CurrencyRate; import java.io.File; import java.io.IOException; import java.math.BigDecimal; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.time.LocalDate; import java.util.Arrays; import java.util.List; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.*; import static org.mockito.Mockito.*; @RunWith(MockitoJUnitRunner.class) public class CBRFDailyCurrencyRatesParserTest { @InjectMocks private CBRFDailyCurrencyRatesParser currencyRatesParser = new CBRFDailyCurrencyRatesParser(); private final String testJSON; public CBRFDailyCurrencyRatesParserTest() throws IOException { File file = ResourceUtils.getFile("classpath:data/cbr_daily_json.js"); testJSON = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8); } @Test public void defaultConstructor() throws MalformedURLException { currencyRatesParser = new CBRFDailyCurrencyRatesParser(); assertThat(currencyRatesParser.getCbrfUrl().toString(), is(CBRFDailyCurrencyRatesParser.CBRF_DAILY_JSON_DEFAULT_URL)); } @Test public void parseFromCBRFMustCallParseFromURL() { final URL cbrfUrl = currencyRatesParser.getCbrfUrl(); currencyRatesParser = spy(currencyRatesParser); final List<CurrencyRate> currencyRates = Arrays.asList(mock(CurrencyRate.class)); doReturn(currencyRates).when(currencyRatesParser).parseFromURL(cbrfUrl); final List<CurrencyRate> result = currencyRatesParser.parseFromCBRF(); assertThat(result, is(currencyRates)); verify(currencyRatesParser).parseFromURL(cbrfUrl); } @Test public void parseFromURL() { final URL cbrfUrl = currencyRatesParser.getCbrfUrl(); currencyRatesParser = spy(currencyRatesParser); doReturn(testJSON).when(currencyRatesParser).getJSONStringFromURL(cbrfUrl); final List<CurrencyRate> result = currencyRatesParser.parseFromURL(cbrfUrl); assertThat(result, is(notNullValue())); assertThat(result.size(), is(34)); verify(currencyRatesParser).getJSONStringFromURL(cbrfUrl); verify(currencyRatesParser).parseFromJSON(testJSON); } @Test public void parseFromJSON() { final List<CurrencyRate> currencyRates = currencyRatesParser.parseFromJSON(testJSON); assertThat(currencyRates, is(notNullValue())); assertThat(currencyRates.size(), is(34)); final CurrencyRate usdCurrencyRate = currencyRates.stream() .filter(currencyRate -> "USD".equals(currencyRate.getCharCode())) .findFirst() .orElse(null); assertThat(usdCurrencyRate, is(notNullValue())); assertThat(usdCurrencyRate.getNumCode(), is("840")); assertThat(usdCurrencyRate.getCharCode(), is("USD")); assertThat(usdCurrencyRate.getName(), is("Доллар США")); assertThat(usdCurrencyRate.getDate(), is(LocalDate.parse("2019-05-17"))); assertThat(usdCurrencyRate.getNominal(), is(1)); assertThat(usdCurrencyRate.getValue(), is(new BigDecimal("64.5598"))); } }
package bootcamp.test; import org.testng.annotations.Test; public class ExecutionOrder { @Test public void a() { System.out.println("Test a"); } @Test public void c() { System.out.println("Test c"); } @Test public void b() { System.out.println("Test b"); } @Test public void A() { System.out.println("Test A"); } @Test public void C() { System.out.println("Test C"); } @Test public void B() { System.out.println("Test B"); } }
package org.rebioma.server.hibernate; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.log4j.Logger; import org.hibernate.Session; import org.rebioma.client.bean.Activity; import org.rebioma.server.services.OccurrenceDbImpl; import org.rebioma.server.util.ManagedSession; public class ActivityLogDA { private static Logger log = Logger.getLogger(ActivityLogDA.class); private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public List<Activity> getCommentActivity(int userId){ String sql = "select uid, count(*), reviewed, usercomment, substr(datecommented || '', 0,15) || '00:00' as date " + "from occurrencecomments oc " + "left join record_review rv on (" + " uid = userid " + " and occurrenceid = oid " + " and substr(datecommented || '', 0,15) = substr(reviewed_date || '', 0,15)" + ") " + "where trim(trim(both E'\\n' from usercomment)) <> 'comment left when reviewed.' " + "and reviewed is null " + "and uid = " + userId + " " + "group by uid,usercomment, date, reviewed"; log.info(sql); List<Activity> lists = new ArrayList<Activity>(); try { Session sess = null; Connection conn =null; Statement st=null; ResultSet rst=null; sess= ManagedSession.createNewSessionAndTransaction(); conn=sess.connection(); st = conn.createStatement(); rst = st.executeQuery(sql); int id = 0; while(rst.next()) { lists.add(new Activity( "c"+(++id), rst.getLong(2), null, format.parse(rst.getString(5)), rst.getString(4) )); } ManagedSession.commitTransaction(sess); } catch (Exception e) { e.printStackTrace(); } return lists; } public List<Activity> getReviewActivity(int userId){ String sql = "select userid, count(*), reviewed, substr(reviewed_date || '', 0,15) || '00:00' as date , usercomment " + "from record_review rv " + "left join occurrencecomments cm on (userid = uid and occurrenceid = oid and substr(datecommented || '', 0,15) = substr(reviewed_date || '', 0,15)) " + "where userid = " + userId + " and reviewed is not null " + "group by userid, reviewed, date , usercomment"; log.info(sql); List<Activity> lists = new ArrayList<Activity>(); try { Session sess = null; Connection conn =null; Statement st=null; ResultSet rst=null; sess= ManagedSession.createNewSessionAndTransaction(); conn=sess.connection(); st = conn.createStatement(); rst = st.executeQuery(sql); int id = 1; while(rst.next()) { lists.add(new Activity( "r"+(++id), rst.getLong(2), rst.getBoolean(3), format.parse(rst.getString(4)), rst.getString(5) )); } ManagedSession.commitTransaction(sess); } catch (Exception e) { e.printStackTrace(); } return lists; } public boolean removeCommentActivity(int userId, Activity activity) { String sql = "delete from occurrencecomments where id in (select oc.id " + "from occurrencecomments oc " + "left join record_review rv on (" + " uid = userid " + " and occurrenceid = oid " + " and substr(datecommented || '', 0,15) = substr(reviewed_date || '', 0,15)" + ") " + "where trim(trim(both E'\\n' from usercomment)) <> 'comment left when reviewed.' " + "and reviewed is null " + "and uid = " + userId + " " + "and substr(datecommented || '', 0,15) || '00:00' = '" + format.format(activity.getDate()) + "' " + "and usercomment = '" + activity.getComment().replace("'", "''") + "')"; log.info(sql); boolean rep = false; try { Session sess = null; Connection conn =null; Statement st=null; sess= ManagedSession.createNewSessionAndTransaction(); conn=sess.connection(); st = conn.createStatement(); st.executeUpdate(sql); rep = true; log.warn("done"); ManagedSession.commitTransaction(sess); } catch (Exception e) { e.printStackTrace(); } return rep; } public boolean removeReviewActivity(int userId, Activity activity) { String sql = "select rv.id, cm.id, occurrenceid " + "from record_review rv " + "left join occurrencecomments cm on (userid = uid and occurrenceid = oid and substr(datecommented || '', 0,15) = substr(reviewed_date || '', 0,15)) " + "where userid = " + userId + " and reviewed = " + activity.getAction() + " " + "and substr(reviewed_date || '', 0,15) || '00:00' = '" + format.format(activity.getDate()) + "' "; sql += activity.getComment()==null?" and usercomment is null":"and usercomment = '" + activity.getComment().replace("'", "''") + "'"; log.info(sql); boolean rep = false; List<Integer> ocId = new ArrayList<Integer>(); try { Session sess = null; Connection conn =null; Statement st=null; ResultSet rst=null; sess= ManagedSession.createNewSessionAndTransaction(); conn=sess.connection(); st = conn.createStatement(); rst = st.executeQuery(sql); // List<Integer> idComment = new ArrayList<Integer>(); String idReview = ""; String idComment = ""; while(rst.next()) { idReview+=rst.getInt(1)+","; ocId.add(rst.getInt(3)); if(rst.getString(2)!=null) idComment+=rst.getInt(2)+","; } idReview+="0"; idComment+="0"; resetReview(st, idReview); delectComment(st, idComment); rep = true; // log.warn(idReview + " - " + idComment + " - Updated: "); ManagedSession.commitTransaction(sess); int updated = 0; // String ids = ""; for (Iterator iterator = ocId.iterator(); iterator.hasNext();) { Integer integer = (Integer) iterator.next(); // ids += integer+ ","; if(new OccurrenceDbImpl().checkForReviewedChanged(integer))updated++; } // log.warn("- Updated: " + updated + " (" + ids + ")"); } catch (Exception e) { e.printStackTrace(); } return rep; } private void resetReview(Statement st, String ids) throws SQLException { String sql = "update record_review set reviewed = null, reviewed_date = null where id in (" +ids +")"; st.executeUpdate(sql); } private void delectComment(Statement st, String ids) throws SQLException { String sql = "delete from occurrencecomments where id in (" +ids +")"; st.executeUpdate(sql); } public ActivityLogDA() { super(); } public static void main(String[] args) { new OccurrenceDbImpl().checkForReviewedChanged(234381); } }
package Query.Plan; import Query.Engine.QueryIndexer; import Query.Entities.PlanTable; import Entity.Constraint; import Entity.Value; import java.util.List; /** * Created by liuche on 5/29/17. * */ public class FilterConstraintPlan extends Plan { private Constraint varConstraint; public FilterConstraintPlan(QueryIndexer queryIndexer, String var, Constraint constraint,PlanTable table) { super(queryIndexer); this.variable = var; this.varConstraint = constraint; estimatedSize = table.estimatedSize; switch (constraint.name){ case "nodeLabels": assert constraint.value.type.contains("List"); List<String> labels = (List<String>)(constraint.value.val); for(String label : labels){ estimatedSize = estimatedSize * (queryIndexer.getNodesWithLabel(label) * 1.0 / queryIndexer.getNumberOfNode()); } break; case "id": estimatedSize = 1; break; default: Value val = constraint.value; //TODO: Add supply for other equality types. assert val.type.equals("String"); if(constraint.equality.equals("==")){ String property = constraint.name; this.estimatedSize /= indexer.getNodesWithProperty(property) ; } break; } } @Override public void applyTo(PlanTable table) { table.cost += table.estimatedSize; table.estimatedSize = estimatedSize; table.plans.add(this); } public Constraint getConstraint(){ return this.varConstraint; } @Override public String getParams() { return varConstraint.toString(); } @Override public String getName() { return "FilterConstraint"; } }
package com.koreait.dto; public class ClientDto { private int cId,cEmpId; private String cName,cAddr,cSSn; public ClientDto() { } public int getcId() { return cId; } public void setcId(int cId) { this.cId = cId; } public int getcEmpId() { return cEmpId; } public void setcEmpId(int cEmpId) { this.cEmpId = cEmpId; } public String getcName() { return cName; } public void setcName(String cName) { this.cName = cName; } public String getcAddr() { return cAddr; } public void setcAddr(String cAddr) { this.cAddr = cAddr; } public String getcSSn() { return cSSn; } public void setcSSn(String cSSn) { this.cSSn = cSSn; } }
package uk.gov.ons.ctp.response.action.export.message; import com.godaddy.logging.Logger; import com.godaddy.logging.LoggerFactory; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.integration.annotation.MessageEndpoint; @MessageEndpoint public class EventPublisher { private static final Logger log = LoggerFactory.getLogger(EventPublisher.class); @Qualifier("amqpTemplate") @Autowired private RabbitTemplate rabbitTemplate; public void publishEvent(String event) { log.with("event", event).debug("Publish Event action exporter "); rabbitTemplate.convertAndSend(event); } }