hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
dbcdde40e29a80e778d78a73aec6d32e6009ef97
918
package org.firstinspires.ftc.teamcode.commands; import java.lang.System; import com.arcrobotics.ftclib.command.CommandBase; import com.arcrobotics.ftclib.gamepad.GamepadEx; import org.firstinspires.ftc.teamcode.subsystems.ClawSys; public class OpenClawCmd extends CommandBase { public ClawSys ss; private final long openMs = 750l; private final long start = System.currentTimeMillis(); public OpenClawCmd(final ClawSys subsystem) { ss = subsystem; addRequirements(subsystem); } public void task() { ss.openClaw(); } public boolean shouldRun() { return !ss.isOpen(); } @Override public void execute() { if (shouldRun()) { task(); } } public boolean isFinished() { if (!shouldRun()) { return true; } return System.currentTimeMillis() - start >= openMs; } }
21.857143
61
0.631808
2b74a7615b6469fb2514f5dbc15bd477d2a3f9c5
1,486
package com.lemon.portti.web.controller.rabbit; import com.lemon.portti.response.BaseResponse; import com.lemon.portti.response.StatusCode; import com.lemon.portti.web.listener.event.PushOrderRecordEvent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; /** * Created by steadyjack on 2018/8/21. */ @RestController public class OrderRecordController { private static final Logger log= LoggerFactory.getLogger(OrderRecordController.class); private static final String Prefix="order"; //TODO:类似于RabbitTemplate @Autowired private ApplicationEventPublisher publisher; /** * 下单 * @return */ @RequestMapping(value = Prefix+"/push",method = RequestMethod.GET) public BaseResponse pushOrder(){ BaseResponse response=new BaseResponse(StatusCode.Success); try { PushOrderRecordEvent event=new PushOrderRecordEvent(this,"orderNo_20180821001","物流12"); publisher.publishEvent(event); }catch (Exception e){ log.error("下单发生异常:",e.fillInStackTrace()); } return response; } }
25.62069
100
0.708614
05ea529865327a8114daeef8ee8fd2e44bf13e4e
2,459
/* * Copyright 2015 Kevin Liu * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.airk.tool.sobitmap; import android.text.TextUtils; /** * Created by kevin on 15/3/24. * <p/> * Custom HuntException */ public class HuntException extends Exception { public static final int REASON_FILE_NOT_FOUND = 0x01; public static final int REASON_TOO_LARGE = 0x02; public static final int REASON_OOM = 0x03; public static final int REASON_IO_EXCEPTION = 0x04; public static final int REASON_UNSUPPORT_TYPE = 0x05; public static final int REASON_CANT_DECODE = 0x06; public static final int REASON_NETWORK_ERROR = 0x07; private int reason; private String extra; public HuntException(int reason) { this.reason = reason; } public void setExtra(String extra) { this.extra = extra; } public int getReason() { return reason; } @Override public String getMessage() { String ret; switch (reason) { case REASON_FILE_NOT_FOUND: ret = "File not found."; break; case REASON_TOO_LARGE: ret = "Input file is too large, please check your options."; break; case REASON_OOM: ret = "OOM occurred while hunting bitmap."; break; case REASON_IO_EXCEPTION: ret = "IOException occurred while hunting bitmap."; break; case REASON_CANT_DECODE: ret = "Can't decode this request."; break; case REASON_NETWORK_ERROR: ret = "Network error."; break; default: ret = "unknown"; } return ret + (TextUtils.isEmpty(extra) ? "" : (" Extra: " + extra)); } @Override public String getLocalizedMessage() { return getMessage(); } }
29.626506
76
0.614477
fda9c05b1aa5de608d0d3450ef070ca9e1997c26
3,878
package com.dbtest.dao; public class PageMaker { private int totalcount;//전체 게시물 개수 private int countlist; private int pagenum;//첫페이지를 표시하기 위함, 페이지 번호를 나타낸다 private int contentnum=10;//한페이지에 몇개 보일지 private int startPage=1;//beginpage 디폴트 1 private int endPage=5;//endpage 디폴트 5 private boolean prev=false;//이전 페이지 화살표 private boolean next;//다음 페이지 화살표 private int currentblock=1; private int lastblock; public boolean isPrev() { return prev; } public void setPrev(boolean prev) { this.prev = prev; } public boolean isNext() { return next; } public void setNext(boolean next) { this.next = next; } public int getStartPage() { return startPage; } public void setStartPage(int currentblock) { this.startPage = (currentblock*5)-4; //한 페이지에 5개씩 보여지므로 //현재 페이지 블록의 번호 * 블록당 페이지의 개수(5) - 4를 하면 시작 페이지 번호를 정할 수 있다 } public int getEndPage() { return endPage; } public void setEndPage(int getlastblock,int getcurrentblock) { if (getlastblock==getcurrentblock) { this.endPage = calcpage(getTotalcount(),getContentnum()); } else { this.endPage = getStartPage()+4; } //기본 시작페이지 +4 //조건 , 마지막 페이지 블록이면 마지막 페이지 번호 } public int getCurrentblock() { return currentblock; } public void setCurrentblock(int pagenum) {//현재 페이지 블록의 번호가 몇번인지 지정해주는 함수 // 페이지번호 / 페이지 그룹 안의 페이지 개수(5) // ->나머지 있으면 더하기 1한다. -> 이 결과를 현재 블록 번호라고 부른다. cblock this.currentblock = pagenum/5; if (pagenum%5>0) { this.currentblock++; } } public int getLastblock() { return lastblock; } public void setLastblock(int totalcount) {//마지막 페이지 블록의 번호가 뭔지 지정해주는 함수 //전체 글 개수를 사용해서 지정한다 this.lastblock = totalcount / (5*this.contentnum); if (totalcount%(5*this.contentnum)>0) { this.lastblock++; } // 전체 글 개수(128) / 페이지 그룹 안의 페이지 개수(5) * 한페이지당 글 개수(10) // ->나머지 있으면 더하기 1한다. -> 이 결과를 마지막 블록 번호라고 부른다. last block } public void prevnext(int pagenum) { if (pagenum>0 && pagenum<6) { setPrev(false); setNext(true); } else if(getLastblock()==getCurrentblock()) {//5개씩 페이지의 그룹번호를 지정한다. //그룹 번호가 3이라는 것은 해당 페이지 그룹이 마지막이라는 것이기에 이전 화살표만 활성화한다 //이 두개가 같다면 마지막 블록이므로 이전만 있고 이후가 없다. setPrev(true); setNext(false); } else { setPrev(true); setNext(true); } } public int calcpage(int totalcount,int contentnum) {//전체 몇페이지까지 있을지 함수로 계산한다 int totalpage = totalcount/contentnum;//전체 게시물 수를 한 페이지당 몇개 보이는지로 나눈다 if (totalcount % contentnum>0) {//그리고 나머지가 있다면 1을 더해서 한 페이지 증가 시킨다 totalpage++; } if (totalpage<this.pagenum) { this.pagenum=totalpage; } return totalpage;//페이지 개수를 리턴한다 } public int getTotalcount() { return totalcount; } public void setTotalcount(int totalcount) { this.totalcount = totalcount; } public int getCountlist() { return countlist; } public void setCountlist(int countlist) { this.countlist = countlist; } public int getPagenum() { return pagenum; } public void setPagenum(int pagenum) { this.pagenum = pagenum; } public int getContentnum() { return contentnum; } public void setContentnum(int contentnum) { this.contentnum = contentnum; } }
26.202703
81
0.544353
ae46f5422a4ce07212f67efe69e58229208b5be0
1,635
package com.envisioniot.enos.iot_mqtt_sdk.message.upstream.ota; import com.envisioniot.enos.iot_mqtt_sdk.core.internals.constants.DeliveryTopicFormat; import com.envisioniot.enos.iot_mqtt_sdk.core.internals.constants.MethodConstants; import com.envisioniot.enos.iot_mqtt_sdk.message.upstream.BaseMqttRequest; import com.google.common.collect.Maps; import java.util.Map; public class OtaVersionReportRequest extends BaseMqttRequest<OtaVersionReportResponse> { private static final long serialVersionUID = 234410161857671987L; public static Builder builder() { return new Builder(); } public static class Builder extends BaseMqttRequest.Builder<Builder, OtaVersionReportRequest> { private String version; public Builder setVersion(String version) { this.version = version; return this; } @Override protected String createMethod() { return MethodConstants.OTA_INFORM; } @Override protected Object createParams() { Map<String, String> map = Maps.newHashMap(); map.put("version", version); return map; } @Override protected OtaVersionReportRequest createRequestInstance() { return new OtaVersionReportRequest(); } } @Override public Class<OtaVersionReportResponse> getAnswerType() { return OtaVersionReportResponse.class; } @Override protected String _getPK_DK_FormatTopic() { return DeliveryTopicFormat.VERSION_REPORT_TOPIC_FMT; } private OtaVersionReportRequest() { } }
29.196429
99
0.69419
c9612b2f829fd4bc32dca03d7e16e609290b7d98
6,489
package org.openqa.selenium.server.browserlaunchers; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import junit.framework.TestCase; import org.openqa.selenium.browserlaunchers.Proxies; import org.openqa.selenium.server.BrowserConfigurationOptions; public class MakeProxyPacUnitTest extends TestCase { public MakeProxyPacUnitTest(String name) { super(name); } private File parentDir, pacFile; private boolean proxySeleniumTrafficOnly = true; private boolean avoidProxy = false; private String httpProxyHost = null; private String httpProxyPort = null; private String httpNonProxyHosts = null; public void setUp() { parentDir = LauncherUtils.createCustomProfileDir("LauncherUtilsUnitTest"); pacFile = new File(parentDir, "proxy.pac"); } public void tearDown() { LauncherUtils.recursivelyDeleteDir(parentDir); } private String makeProxyPAC() throws IOException { BrowserConfigurationOptions options = new BrowserConfigurationOptions(); options.setOnlyProxySeleniumTraffic(proxySeleniumTrafficOnly); options.setAvoidProxy(avoidProxy); Proxies .makeProxyPAC(parentDir, 4444, httpProxyHost, httpProxyPort, httpNonProxyHosts, options.asCapabilities()); return readEntirePacFile(); } private String readEntirePacFile() throws IOException { FileReader fileReader = new FileReader(pacFile); BufferedReader reader = new BufferedReader(fileReader); StringBuffer sb = new StringBuffer(); String line; while ((line = reader.readLine()) != null) { sb.append(line).append('\n'); } String pac = sb.toString(); return pac.replaceAll("\\s+", " ").trim(); } public void testBasic() throws IOException { proxySeleniumTrafficOnly = false; String pac = makeProxyPAC(); String expected = "function FindProxyForURL(url, host) " + "{ return 'PROXY localhost:4444; DIRECT'; }"; assertEquals(expected, pac); } public void testNeverProxySeleniumTrafficOnly() throws IOException { proxySeleniumTrafficOnly = false; String pac = makeProxyPAC(); String expected = "function FindProxyForURL(url, host) " + "{ return 'PROXY localhost:4444; DIRECT'; }"; assertEquals(expected, pac); } public void testAvoidProxyNeverProxySeleniumTrafficOnly() throws IOException { proxySeleniumTrafficOnly = false; avoidProxy = true; String pac = makeProxyPAC(); String expected = "function FindProxyForURL(url, host) " + "{ return 'PROXY localhost:4444; DIRECT'; }"; assertEquals(expected, pac); } public void testAvoidProxy() throws IOException { avoidProxy = true; String pac = makeProxyPAC(); String expected = "function FindProxyForURL(url, host) " + "{ if (shExpMatch(url, '*/selenium-server/*')) { return 'PROXY localhost:4444; DIRECT'; } }"; assertEquals(expected, pac); } public void testConfiguredProxy() throws IOException { proxySeleniumTrafficOnly = false; httpProxyHost = "foo"; String pac = makeProxyPAC(); String expected = "function FindProxyForURL(url, host) " + "{ return 'PROXY localhost:4444; PROXY foo'; }"; assertEquals(expected, pac); } public void testConfiguredProxyAvoidProxy() throws IOException { httpProxyHost = "foo"; avoidProxy = true; String pac = makeProxyPAC(); String expected = "function FindProxyForURL(url, host) " + "{ if (shExpMatch(url, '*/selenium-server/*')) { return 'PROXY localhost:4444; PROXY foo'; } return 'PROXY foo'; }"; assertEquals(expected, pac); } public void testAvoidProxyNonProxyHost() throws IOException { avoidProxy = true; httpNonProxyHosts = "www.google.com"; String pac = makeProxyPAC(); String expected = "function FindProxyForURL(url, host) { " + "if (shExpMatch(host, 'www.google.com')) { return 'DIRECT'; } " + "if (shExpMatch(url, '*/selenium-server/*')) " + "{ return 'PROXY localhost:4444; DIRECT'; } }"; assertEquals(expected, pac); } public void testConfiguredProxyAvoidProxyNonProxyHost() throws IOException { avoidProxy = true; httpProxyHost = "foo"; httpNonProxyHosts = "www.google.com"; String pac = makeProxyPAC(); String expected = "function FindProxyForURL(url, host) { " + "if (shExpMatch(host, 'www.google.com')) { return 'DIRECT'; } " + "if (shExpMatch(url, '*/selenium-server/*')) { " + "return 'PROXY localhost:4444; PROXY foo'; } return 'PROXY foo'; }"; assertEquals(expected, pac); } public void testAvoidProxyNonProxyHosts() throws IOException { avoidProxy = true; httpNonProxyHosts = "www.google.com|*.yahoo.com"; String pac = makeProxyPAC(); String expected = "function FindProxyForURL(url, host) { " + "if (shExpMatch(host, 'www.google.com')) { return 'DIRECT'; } " + "if (shExpMatch(host, '*.yahoo.com')) { return 'DIRECT'; } " + "if (shExpMatch(url, '*/selenium-server/*')) { " + "return 'PROXY localhost:4444; DIRECT'; } }"; assertEquals(expected, pac); } public void testConfiguredProxyAvoidProxyNonProxyHosts() throws IOException { avoidProxy = true; httpProxyHost = "foo"; httpNonProxyHosts = "www.google.com|*.yahoo.com"; String pac = makeProxyPAC(); String expected = "function FindProxyForURL(url, host) { " + "if (shExpMatch(host, 'www.google.com')) { return 'DIRECT'; } " + "if (shExpMatch(host, '*.yahoo.com')) { return 'DIRECT'; } " + "if (shExpMatch(url, '*/selenium-server/*')) " + "{ return 'PROXY localhost:4444; PROXY foo'; } return 'PROXY foo'; }"; assertEquals(expected, pac); } }
42.136364
127
0.59963
6677ef7f5c8716a699ca1c4bb65498d5b9509c17
135
package tech.brownbear.server; import java.io.File; public interface FileRenderer { void render(File file, FileFormat format); }
16.875
46
0.762963
bdfdeb7735f000bc08e7682dbcd5c7801fd1c29f
1,719
package com.blog.model; import java.util.Date; import javax.validation.constraints.NotNull; /** * * @author sselman * Copyright - 2018 Selman Selman * MIT License */ public class Post { @NotNull private String title; @NotNull private String source; @NotNull private String summary_one; @NotNull private String img_source; @NotNull private String summary_two; @NotNull private Date published_at; public String getTitle() { return title; } public String getSource() { return source; } public String getSummary_one() { return summary_one; } public String getSummary_two() { return summary_two; } public Date getPublished_at() { return published_at; } public String getImg_source() { return img_source; } public void setImg_source(String img_source) { this.img_source = img_source; } public void setTitle(String title) { this.title = title; } public void setSource(String source) { this.source = source; } public void setSummary_one(String summary_one) { this.summary_one = summary_one; } public void setSummary_two(String summary_two) { this.summary_two = summary_two; } public void setPublished_at(Date published_at) { this.published_at = published_at; } public Post(@NotNull String title, @NotNull String source, @NotNull String img_source, @NotNull String summary_one, @NotNull String summary_two, @NotNull Date published_at) { super(); this.title = title; this.source = source; this.img_source = img_source; this.summary_one = summary_one; this.summary_two = summary_two; this.published_at = published_at; } }
18.483871
146
0.687609
3004b3b5dac476ba574a58d2240064796ff8c472
2,562
package test.recursividadebig; import java.util.ArrayList; import java.util.Scanner; class FloodFlill { private int rows; private int cols; private char[][] petri; private boolean[][] visited; FloodFlill (int cols, int rows, char[][] petri, boolean[][] visited) { this.rows = rows; this.cols = cols; this.petri = petri; this.visited = visited; } public int t (int i, int j) { if (i < 0 || i >= rows) return 0; if (j < 0 || j >= cols) return 0; if (petri[i][j] == '.') return 0; if (visited[i][j]) return 0; visited[i][j] = true; int count = 1; // Flood fill em todas as 8 direçoes count += t(i+1, j); count += t(i, j+1); count += t(i-1, j); count += t(i, j-1); count += t(i+1, j+1); count += t(i+1, j-1); count += t(i-1, j+1); count += t(i-1, j-1); return count; } } public class ED200 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int cases = scan.nextInt(); while (cases > 0) { int rows = scan.nextInt(); int cols = scan.nextInt(); scan.nextLine(); char[][] petri = new char[rows][cols]; boolean[][] visited = new boolean[rows][cols]; // Ler placa de petri for (int i = 0; i < rows; i++) petri[i] = scan.nextLine().toCharArray(); FloodFlill f = new FloodFlill(cols, rows, petri, visited); ArrayList<Integer> micro = new ArrayList<>(); // Nao era necessario, mas eu quis guardar o tamanho de todos os microbios, podia-se fazer Math.max // Fazer flood fill em todas as células da placa de petri nao visitadas for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (!visited[i][j]) { int temp = f.t(i, j); // Tamnho do microbio if (temp > 0) micro.add(temp); } } } cases--; // Ver maior microbio int max = 0; for (Integer cel : micro) if (cel > max) max = cel; System.out.println(max); } scan.close(); } }
25.366337
159
0.43872
e4101ad54d694ab88ac8fc6c70c1b7b43935aea5
2,392
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; public class PointInCircle { public static void main (String[] args) throws IOException { File file = new File(args[0]); BufferedReader in = new BufferedReader(new FileReader(file)); String line; // Example: // Center: (2.12, -3.48); Radius: 17.22; Point: (16.21, -5) Pattern p = Pattern.compile( "Center: \\(([0-9.\\-]+), ([0-9.\\-]+)\\); " + "Radius: ([0-9.\\-]+); Point: \\(([0-9.\\-]+), ([0-9.\\-]+)\\)"); while ((line = in.readLine()) != null) { line = line.trim(); if (line.length() == 0) { continue; } Matcher m = p.matcher(line); if (m.find()) { double centerX = Double.parseDouble(m.group(1)); double centerY = Double.parseDouble(m.group(2)); double radius = Double.parseDouble(m.group(3)); double pointX = Double.parseDouble(m.group(4)); double pointY = Double.parseDouble(m.group(5)); Circle circle = new Circle(new Point(centerX, centerY), radius); Point point = new Point(pointX, pointY); System.out.println(circle.containsPoint(point)); } } in.close(); } public static class Point { private final double _x; private final double _y; public Point(double x, double y) { _x = x; _y = y; } public double getX() { return _x; } public double getY() { return _y; } } public static class Circle { private final Point _center; private final double _radius; public Circle(Point center, double radius) { _center = center; _radius = radius; } public boolean containsPoint(Point p) { double xDiff = _center.getX() - p.getX(); double yDiff = _center.getY() - p.getY(); double distance = Math.sqrt((xDiff*xDiff) + (yDiff*yDiff)); return distance < _radius; } } }
26.285714
81
0.498328
68652a4c97411e50abcdc8e3c16cf52b8e53f84e
3,714
package me.ihdeveloper.spigot.devtools; import me.ihdeveloper.spigot.devtools.api.DevTools; import me.ihdeveloper.spigot.devtools.api.SDTServerWall; import org.bukkit.entity.Player; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Map; import java.util.Set; import java.util.TreeMap; public class SimpleServerWall implements SDTServerWall { private final Map<String, String> wall = new TreeMap<>(); @Override public void put(String name, String value) { this.wall.put(name, value); byte[] data = buildChunkOfWall(name, value); DevTools.getInstance().broadcast(data); } @Override public void remove(String name) { this.wall.remove(name); byte[] data = buildRemovePartOfWall(name); DevTools.getInstance().broadcast(data); } @Override public void clear() { this.wall.clear(); byte[] data = buildClear(); DevTools.getInstance().broadcast(data); } @Override public Set<Map.Entry<String, String>> get() { return this.wall.entrySet(); } public void sendWall(Player player) { byte[] data = buildWall(); DevTools.getInstance().send(player, data); } private byte[] buildWall() { ByteArrayOutputStream stream = new ByteArrayOutputStream(); DataOutputStream output = new DataOutputStream(stream); try { output.writeUTF("server-wall–put"); output.writeInt(get().size()); for (Map.Entry<String, String> entry : get()) { output.writeUTF(entry.getKey()); output.writeUTF(entry.getValue()); } } catch (IOException exception) { DevTools.getInstance().getPlugin().getLogger().warning("Failed to write server wall(put) packet data! (not enough memory?)"); exception.printStackTrace(); } return stream.toByteArray(); } private byte[] buildChunkOfWall(String name, String value) { ByteArrayOutputStream stream = new ByteArrayOutputStream(); DataOutputStream output = new DataOutputStream(stream); try { output.writeUTF("server-wall–put"); output.writeInt(1); output.writeUTF(name); output.writeUTF(value); } catch (IOException exception) { DevTools.getInstance().getPlugin().getLogger().warning("Failed to write server wall(chunk) packet data! (not enough memory?)"); exception.printStackTrace(); } return stream.toByteArray(); } private byte[] buildRemovePartOfWall(String name) { ByteArrayOutputStream stream = new ByteArrayOutputStream(); DataOutputStream output = new DataOutputStream(stream); try { output.writeUTF("server-wall–remove"); output.writeUTF(name); } catch (IOException exception) { DevTools.getInstance().getPlugin().getLogger().warning("Failed to write server wall(remove) packet data! (not enough memory?)"); exception.printStackTrace(); } return stream.toByteArray(); } private byte[] buildClear() { ByteArrayOutputStream stream = new ByteArrayOutputStream(); DataOutputStream output = new DataOutputStream(stream); try { output.writeUTF("server-wall–reset"); } catch (IOException exception) { DevTools.getInstance().getPlugin().getLogger().warning("Failed to write server wall(reset) packet data! (not enough memory?)"); exception.printStackTrace(); } return stream.toByteArray(); } }
32.295652
140
0.633549
c01b6906d07c165433aeb8151c3ec10fc4d8df65
1,044
package com.genability.client.api.request; import java.util.List; import org.apache.http.NameValuePair; import com.fasterxml.jackson.annotation.JsonIgnore; public class GetTerritoryRequest extends AbstractRequest { private Long territoryId; private Boolean populateItems; private Boolean populateLses; public Long getTerritoryId() { return territoryId; } public void setTerritoryId(final Long territoryId) { this.territoryId = territoryId; } public Boolean getPopulateItems() { return populateItems; } public void setPopulateItems(final Boolean populateItems) { this.populateItems = populateItems; } public Boolean getPopulateLses() { return populateLses; } public void setPopulateLses(final Boolean populateLses) { this.populateLses = populateLses; } @Override @JsonIgnore public List<NameValuePair> getQueryParams() { List<NameValuePair> qparams = super.getQueryParams(); addParam(qparams, "populateItems", populateItems); addParam(qparams, "populateLses", populateLses); return qparams; } }
23.2
60
0.777778
39c4ba64b32ac6564814a428504ce5b65e56b8c0
198
package com.ceph.rados; public enum ChecksumType { XXHASH32(0), XXHASH64(1), CRC32C(2); private final int value; ChecksumType(int value) { this.value = value; } }
14.142857
29
0.606061
4d0a4336dcfdc105c85d53015bc1362de8325d41
1,086
package cn.stylefeng.guns.modular.system.service; import cn.stylefeng.guns.modular.system.dto.ResponseResult; import com.baomidou.mybatisplus.service.IService; import cn.stylefeng.guns.modular.system.dto.BankCashflowVo; import cn.stylefeng.guns.modular.system.dto.BankFlowsModel; import cn.stylefeng.guns.modular.system.dto.SelectCardReq; import cn.stylefeng.guns.modular.system.model.BankCard; import java.util.Date; import java.util.Map; /** * <p> * 服务类 * </p> * * @author steven123 * @since 2019-05-27 */ public interface IBankCardService extends IService<BankCard> { void changeSwitch(Integer id, Byte status); void updateOnlineStats(Integer card_id, Byte status); void syncBankOnlineStatus(Integer card_id); void reportBankOnlineStatus(String cardNo); void syncAllBankOnlineStatus(); Object bankSelect(SelectCardReq req); Object saveBankCashFlow(BankCashflowVo req, Date cutoffTime); void saveFlows(BankFlowsModel req); ResponseResult getTransLastTimeByCardNo(String card_no); Map getBankCard(SelectCardReq selectCardReq); }
28.578947
65
0.779006
beadd4dd4e9d00fc445b094f7d3313d7ff6e10e8
160
package com.facebook.soloader; final class Elf64_Dyn { public static final int d_tag = 0; public static final int d_un = 8; Elf64_Dyn() { } }
16
38
0.65625
ccf164fb5857c9f1502e48730508f8d1afa80efa
3,790
package metadata.etl.lhotse.crawler; import metadata.etl.lhotse.LzExecMessage; import metadata.etl.lhotse.LzTaskExecRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import wherehows.common.Constant; import wherehows.common.utils.FileOperator; import wherehows.common.utils.SshUtils; import java.io.File; import java.util.Arrays; /** * Created by thomas young on 5/22/17. */ public class LhtoseConfCrawler implements BaseCrawler { private static final Logger logger = LoggerFactory.getLogger(LhtoseConfCrawler.class); public static final String defaultRemoteConfLocation = "/usr/local/lhotse_runners/log/"; public static final String defaultLocalConfLocation = "/var/tmp/wherehows/crawl_data/"; @Override public String getRemoteLog(LzExecMessage message) throws Exception { LzTaskExecRecord lzRecord = message.lzTaskExecRecord; String localLogLocation = null; if (message.prop.getProperty(Constant.LZ_LINEAGE_LOG_REMOTE, "false").equalsIgnoreCase("false")) { // the full path localLogLocation = defaultRemoteConfLocation; localLogLocation += String.format("tasklog/%d/%s", lzRecord.taskType, lzRecord.taskId); // find the latest file name. String fileName = FileOperator.getOneLogFile(localLogLocation); localLogLocation += "/" + fileName; } else { String remoteUser = message.prop.getProperty(Constant.LZ_REMOTE_USER_KEY); // String remoteHost = message.prop.getProperty(Constant.LZ_REMOTE_MACHINE_KEY); String remoteHost = lzRecord.brokerId; logger.info("conf lhotse runner ip is: {}", remoteHost); String keyLocation = message.prop.getProperty(Constant.LZ_PRIVATE_KEY_LOCATION_KEY); // in remote mode, this field stands for the local dir to store the log files. // String localLogFile = message.prop.getProperty(Constant.LZ_LINEAGE_LOG_DEFAULT_DIR); String localLogFile = defaultLocalConfLocation; // move the log file from remote host to local host String remoteLogLocation = message.prop.getProperty(Constant.LZ_REMOTE_LOG_DIR, defaultRemoteConfLocation); remoteLogLocation += String.format("tasklog/%d/%s", lzRecord.taskType, lzRecord.taskId); // get the file list in the remote directory. String fileList = SshUtils.exec(remoteHost, remoteUser, keyLocation, "ls " + remoteLogLocation); String []files = fileList.split(" "); if (files.length > 0) { Arrays.sort(files); } else { logger.error("no log file found! task_id is: {}", message.lzTaskExecRecord.taskId); return null; } // prepare the remote log file. String remoteLogFileName = files[files.length - 1]; String remoteLogFile = String.format("%s/%s", remoteLogLocation, remoteLogFileName); // prepare the local log file. localLogFile += String.format("tasklog/%d/%s/", lzRecord.taskType, lzRecord.taskId); new File(localLogFile).mkdirs(); // fetch the remote log file to local directory. logger.info("local log directory is: {}", localLogFile); SshUtils.fileFetch(remoteHost, remoteUser, keyLocation, remoteLogFile, localLogFile); localLogLocation = localLogFile + remoteLogFileName; } // for debug. if (localLogLocation == null) { logger.error("log file location error!"); throw new Exception("log file location error!"); } else { logger.info("log file to parse: {}", localLogLocation); } return localLogLocation; } }
47.974684
119
0.665172
a3ebce1f7c8b2cbd2b6d25bc3687419a2f31295e
17,327
package io.onedev.server.rest; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import javax.inject.Inject; import javax.inject.Singleton; import javax.validation.Valid; import javax.validation.constraints.NotNull; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.apache.shiro.authc.credential.PasswordService; import org.apache.shiro.authz.UnauthenticatedException; import org.apache.shiro.authz.UnauthorizedException; import org.hibernate.validator.constraints.Email; import org.hibernate.validator.constraints.NotEmpty; import io.onedev.commons.utils.ExplicitException; import io.onedev.server.entitymanager.EmailAddressManager; import io.onedev.server.entitymanager.SshKeyManager; import io.onedev.server.entitymanager.UserManager; import io.onedev.server.model.BuildQueryPersonalization; import io.onedev.server.model.CodeCommentQueryPersonalization; import io.onedev.server.model.CommitQueryPersonalization; import io.onedev.server.model.EmailAddress; import io.onedev.server.model.IssueQueryPersonalization; import io.onedev.server.model.IssueVote; import io.onedev.server.model.IssueWatch; import io.onedev.server.model.Membership; import io.onedev.server.model.PullRequestAssignment; import io.onedev.server.model.PullRequestQueryPersonalization; import io.onedev.server.model.PullRequestReview; import io.onedev.server.model.PullRequestWatch; import io.onedev.server.model.SshKey; import io.onedev.server.model.User; import io.onedev.server.model.UserAuthorization; import io.onedev.server.model.support.NamedProjectQuery; import io.onedev.server.model.support.build.NamedBuildQuery; import io.onedev.server.model.support.issue.NamedIssueQuery; import io.onedev.server.model.support.pullrequest.NamedPullRequestQuery; import io.onedev.server.rest.annotation.Api; import io.onedev.server.rest.annotation.EntityCreate; import io.onedev.server.rest.exception.InvalidParamException; import io.onedev.server.rest.support.RestConstants; import io.onedev.server.security.SecurityUtils; import io.onedev.server.util.validation.annotation.UserName; @Api(order=5000) @Path("/users") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Singleton public class UserResource { private final UserManager userManager; private final SshKeyManager sshKeyManager; private final PasswordService passwordService; private final EmailAddressManager emailAddressManager; @Inject public UserResource(UserManager userManager, SshKeyManager sshKeyManager, PasswordService passwordService, EmailAddressManager emailAddressManager) { this.userManager = userManager; this.sshKeyManager = sshKeyManager; this.passwordService = passwordService; this.emailAddressManager = emailAddressManager; } @Api(order=100) @Path("/{userId}") @GET public User getProfile(@PathParam("userId") Long userId) { User user = userManager.load(userId); if (!SecurityUtils.isAdministrator() && !user.equals(SecurityUtils.getUser())) throw new UnauthorizedException(); return user; } @Api(order=200) @Path("/me") @GET public User getMyProfile() { User user = SecurityUtils.getUser(); if (user == null) throw new UnauthenticatedException(); return user; } @Api(order=250) @Path("/{userId}/access-token") @GET public String getAccessToken(@PathParam("userId") Long userId) { User user = userManager.load(userId); if (!SecurityUtils.isAdministrator() && !user.equals(SecurityUtils.getUser())) throw new UnauthorizedException(); return user.getAccessToken(); } @Api(order=275) @Path("/{userId}/email-addresses") @GET public Collection<EmailAddress> getEmailAddresses(@PathParam("userId") Long userId) { User user = userManager.load(userId); if (!SecurityUtils.isAdministrator() && !user.equals(SecurityUtils.getUser())) throw new UnauthorizedException(); return user.getEmailAddresses(); } @Api(order=300) @Path("/{userId}/authorizations") @GET public Collection<UserAuthorization> getAuthorizations(@PathParam("userId") Long userId) { if (!SecurityUtils.isAdministrator()) throw new UnauthorizedException(); return userManager.load(userId).getAuthorizations(); } @Api(order=400) @Path("/{userId}/memberships") @GET public Collection<Membership> getMemberships(@PathParam("userId") Long userId) { if (!SecurityUtils.isAdministrator()) throw new UnauthorizedException(); return userManager.load(userId).getMemberships(); } @Api(order=600) @Path("/{userId}/pull-request-reviews") @GET public Collection<PullRequestReview> getPullRequestReviews(@PathParam("userId") Long userId) { User user = userManager.load(userId); if (!SecurityUtils.isAdministrator() && !user.equals(SecurityUtils.getUser())) throw new UnauthorizedException(); return user.getPullRequestReviews(); } @Api(order=700) @Path("/{userId}/issue-votes") @GET public Collection<IssueVote> getIssueVotes(@PathParam("userId") Long userId) { User user = userManager.load(userId); if (!SecurityUtils.isAdministrator() && !user.equals(SecurityUtils.getUser())) throw new UnauthorizedException(); return user.getIssueVotes(); } @Api(order=800) @Path("/{userId}/issue-watches") @GET public Collection<IssueWatch> getIssueWatches(@PathParam("userId") Long userId) { User user = userManager.load(userId); if (!SecurityUtils.isAdministrator() && !user.equals(SecurityUtils.getUser())) throw new UnauthorizedException(); return user.getIssueWatches(); } @Api(order=900) @Path("/{userId}/project-build-query-personalizations") @GET public Collection<BuildQueryPersonalization> getProjectBuildQueryPersonalizations(@PathParam("userId") Long userId) { User user = userManager.load(userId); if (!SecurityUtils.isAdministrator() && !user.equals(SecurityUtils.getUser())) throw new UnauthorizedException(); return user.getBuildQueryPersonalizations(); } @Api(order=1000) @Path("/{userId}/project-code-comment-query-personalizations") @GET public Collection<CodeCommentQueryPersonalization> getProjectCodeCommentQueryPersonalizations(@PathParam("userId") Long userId) { User user = userManager.load(userId); if (!SecurityUtils.isAdministrator() && !user.equals(SecurityUtils.getUser())) throw new UnauthorizedException(); return user.getCodeCommentQueryPersonalizations(); } @Api(order=1100) @Path("/{userId}/project-commit-query-personalizations") @GET public Collection<CommitQueryPersonalization> getProjectCommitQueryPersonalizations(@PathParam("userId") Long userId) { User user = userManager.load(userId); if (!SecurityUtils.isAdministrator() && !user.equals(SecurityUtils.getUser())) throw new UnauthorizedException(); return user.getCommitQueryPersonalizations(); } @Api(order=1200) @Path("/{userId}/project-issue-query-personalizations") @GET public Collection<IssueQueryPersonalization> getProjecIssueQueryPersonalizations(@PathParam("userId") Long userId) { User user = userManager.load(userId); if (!SecurityUtils.isAdministrator() && !user.equals(SecurityUtils.getUser())) throw new UnauthorizedException(); return user.getIssueQueryPersonalizations(); } @Api(order=1300) @Path("/{userId}/project-pull-request-query-personalizations") @GET public Collection<PullRequestQueryPersonalization> getProjecPullRequestQueryPersonalizations(@PathParam("userId") Long userId) { User user = userManager.load(userId); if (!SecurityUtils.isAdministrator() && !user.equals(SecurityUtils.getUser())) throw new UnauthorizedException(); return user.getPullRequestQueryPersonalizations(); } @Api(order=1400) @Path("/{userId}/pull-request-assignments") @GET public Collection<PullRequestAssignment> getPullRequestAssignments(@PathParam("userId") Long userId) { User user = userManager.load(userId); if (!SecurityUtils.isAdministrator() && !user.equals(SecurityUtils.getUser())) throw new UnauthorizedException(); return user.getPullRequestAssignments(); } @Api(order=1500) @Path("/{userId}/pull-request-watches") @GET public Collection<PullRequestWatch> getPullRequestWatches(@PathParam("userId") Long userId) { User user = userManager.load(userId); if (!SecurityUtils.isAdministrator() && !user.equals(SecurityUtils.getUser())) throw new UnauthorizedException(); return user.getPullRequestWatches(); } @Api(order=1600) @Path("/{userId}/ssh-keys") @GET public Collection<SshKey> getSshKeys(@PathParam("userId") Long userId) { User user = userManager.load(userId); if (!SecurityUtils.isAdministrator() && !user.equals(SecurityUtils.getUser())) throw new UnauthorizedException(); return user.getSshKeys(); } @Api(order=1700) @Path("/{userId}/queries-and-watches") @GET public QueriesAndWatches getQueriesAndWatches(@PathParam("userId") Long userId) { User user = userManager.load(userId); if (!SecurityUtils.isAdministrator() && !user.equals(SecurityUtils.getUser())) throw new UnauthorizedException(); QueriesAndWatches queriesAndWatches = new QueriesAndWatches(); queriesAndWatches.buildQuerySubscriptions = user.getBuildQuerySubscriptions(); queriesAndWatches.issueQueryWatches = user.getIssueQueryWatches(); queriesAndWatches.pullRequestQueryWatches = user.getPullRequestQueryWatches(); queriesAndWatches.buildQueries = user.getUserBuildQueries(); queriesAndWatches.issueQueries = user.getUserIssueQueries(); queriesAndWatches.projectQueries = user.getUserProjectQueries(); queriesAndWatches.pullRequestQueries = user.getUserPullRequestQueries(); return queriesAndWatches; } @Api(order=1800) @GET public List<User> queryProfile( @QueryParam("term") @Api(description="Any string in login name, full name or email address") String term, @QueryParam("offset") @Api(example="0") int offset, @QueryParam("count") @Api(example="100") int count) { if (!SecurityUtils.isAdministrator()) throw new UnauthorizedException(); if (count > RestConstants.MAX_PAGE_SIZE) throw new InvalidParamException("Count should not be greater than " + RestConstants.MAX_PAGE_SIZE); return userManager.query(term, offset, count); } @Api(order=1900, description="Create new user") @POST public Long create(@NotNull @Valid UserCreateData data) { if (SecurityUtils.isAdministrator()) { if (userManager.findByName(data.getName()) != null) throw new ExplicitException("Login name is already used by another user"); if (emailAddressManager.findByValue(data.getEmailAddress()) != null) throw new ExplicitException("Email address is already used by another user"); User user = new User(); user.setName(data.getName()); user.setFullName(data.getFullName()); user.setPassword(passwordService.encryptPassword(data.getPassword())); userManager.save(user); EmailAddress emailAddress = new EmailAddress(); emailAddress.setGit(true); emailAddress.setPrimary(true); emailAddress.setOwner(user); emailAddress.setValue(data.getEmailAddress()); emailAddress.setVerificationCode(null); emailAddressManager.save(emailAddress); return user.getId(); } else { throw new UnauthenticatedException(); } } @Api(order=1950, description="Update user profile") @Path("/{userId}") @POST public Long updateProfile(@PathParam("userId") Long userId, @NotNull @Valid ProfileUpdateData data) { User user = userManager.load(userId); if (SecurityUtils.isAdministrator() || user.equals(SecurityUtils.getUser())) { User existingUser = userManager.findByName(data.getName()); if (existingUser != null && !existingUser.equals(user)) throw new ExplicitException("Login name is already used by another user"); user.setName(data.getName()); user.setFullName(data.getFullName()); userManager.save(user); return user.getId(); } else { throw new UnauthenticatedException(); } } @Api(order=2000) @Path("/{userId}/password") @POST public Response setPassword(@PathParam("userId") Long userId, @NotEmpty String password) { User user = userManager.load(userId); if (!SecurityUtils.isAdministrator() && !user.equals(SecurityUtils.getUser())) { throw new UnauthorizedException(); } else if (user.getPassword().equals(User.EXTERNAL_MANAGED)) { if (user.getSsoConnector() != null) { throw new ExplicitException("The user is currently authenticated via SSO provider '" + user.getSsoConnector() + "', please change password there instead"); } else { throw new ExplicitException("The user is currently authenticated via external system, " + "please change password there instead"); } } else { user.setPassword(passwordService.encryptPassword(password)); userManager.save(user); return Response.ok().build(); } } @Api(order=2100) @Path("/{userId}/queries-and-watches") @POST public Response setQueriesAndWatches(@PathParam("userId") Long userId, @NotNull QueriesAndWatches queriesAndWatches) { User user = userManager.load(userId); if (!SecurityUtils.isAdministrator() && !user.equals(SecurityUtils.getUser())) throw new UnauthorizedException(); user.setBuildQuerySubscriptions(queriesAndWatches.buildQuerySubscriptions); user.setIssueQueryWatches(queriesAndWatches.issueQueryWatches); user.setPullRequestQueryWatches(queriesAndWatches.pullRequestQueryWatches); user.setBuildQueries(queriesAndWatches.buildQueries); user.setIssueQueries(queriesAndWatches.issueQueries); user.setIssueQueryWatches(queriesAndWatches.issueQueryWatches); user.setProjectQueries(queriesAndWatches.projectQueries); user.setPullRequestQueries(queriesAndWatches.pullRequestQueries); userManager.save(user); return Response.ok().build(); } @Api(order=2200) @Path("/{userId}/ssh-keys") @POST public Long addSshKey(@PathParam("userId") Long userId, @NotNull String content) { User user = SecurityUtils.getUser(); SshKey sshKey = new SshKey(); sshKey.setContent(content); sshKey.setCreatedAt(new Date()); sshKey.setOwner(user); sshKey.digest(); sshKeyManager.save(sshKey); return sshKey.getId(); } @Api(order=2300) @Path("/{userId}") @DELETE public Response delete(@PathParam("userId") Long userId) { if (!SecurityUtils.isAdministrator()) throw new UnauthorizedException(); User user = userManager.load(userId); if (user.isRoot()) throw new ExplicitException("Root user can not be deleted"); else if (user.equals(SecurityUtils.getUser())) throw new ExplicitException("Can not delete yourself"); else userManager.delete(user); return Response.ok().build(); } @EntityCreate(User.class) public static class UserCreateData implements Serializable { private static final long serialVersionUID = 1L; private String name; private String password; private String fullName; private String emailAddress; @Api(order=100, description="Login name of the user") @UserName @NotEmpty public String getName() { return name; } public void setName(String name) { this.name = name; } @Api(order=150) @NotEmpty public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Api(order=200) public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } @Api(order=300) @Email @NotEmpty public String getEmailAddress() { return emailAddress; } public void setEmailAddress(String emailAddress) { this.emailAddress = emailAddress; } } public static class ProfileUpdateData implements Serializable { private static final long serialVersionUID = 1L; private String name; private String fullName; @Api(order=100, description="Login name of the user") @UserName @NotEmpty public String getName() { return name; } public void setName(String name) { this.name = name; } @Api(order=200) public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } } public static class QueriesAndWatches implements Serializable { private static final long serialVersionUID = 1L; ArrayList<NamedProjectQuery> projectQueries; ArrayList<NamedIssueQuery> issueQueries; LinkedHashMap<String, Boolean> issueQueryWatches; ArrayList<NamedPullRequestQuery> pullRequestQueries; LinkedHashMap<String, Boolean> pullRequestQueryWatches; ArrayList<NamedBuildQuery> buildQueries; LinkedHashSet<String> buildQuerySubscriptions; } }
33.64466
133
0.739597
ee6e6f32bc64eeae15fd59e4377cd8a42c2ddff8
1,374
package cf.witcheskitchen.common.statuseffect; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.damage.DamageSource; import net.minecraft.entity.effect.StatusEffect; import net.minecraft.entity.effect.StatusEffectCategory; import net.minecraft.sound.SoundCategory; import net.minecraft.sound.SoundEvents; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; public class ParalysisStatusEffect extends StatusEffect { public ParalysisStatusEffect(StatusEffectCategory type, int color) { super(type, color); } @Override public boolean isInstant() { return false; } @Override public boolean canApplyUpdateEffect(int duration, int amplifier) { return true; } @Override public boolean isBeneficial() { return false; } //Todo: Make paralysis potions cause the player to sink if they are in water @Override public void applyUpdateEffect(LivingEntity entity, int amplifier) { BlockPos pos = entity.getBlockPos(); World world = entity.getEntityWorld(); entity.setVelocity(0, 0, 0); if (entity.isSwimming()) { entity.damage(DamageSource.DROWN, 2f); entity.setAir(0); world.playSound(null, pos, SoundEvents.ENTITY_PLAYER_HURT_DROWN, SoundCategory.HOSTILE, 1, 1); } } }
30.533333
106
0.70524
a50952d7f288c9b595770a58d6d4793b747b73b8
684
package dagger.internal.codegen; import com.google.auto.common.BasicAnnotationProcessor; import com.google.common.collect.ImmutableSet; import com.google.common.collect.SetMultimap; import dagger.HelloWorld; import javax.lang.model.element.Element; import java.lang.annotation.Annotation; import java.util.Set; public class HelloWoldStep implements BasicAnnotationProcessor.ProcessingStep { @Override public Set<? extends Class<? extends Annotation>> annotations() { return ImmutableSet.of(HelloWorld.class); } @Override public Set<Element> process(SetMultimap<Class<? extends Annotation>, Element> elementsByAnnotation) { return null; } }
29.73913
105
0.77193
64870de2a408d01a84345b2b92eee3cade23aec1
1,150
import io.vertx.core.AbstractVerticle; import io.vertx.core.Future; import io.vertx.core.net.NetServer; import io.vertx.core.net.NetServerOptions; import java.util.concurrent.atomic.AtomicInteger; public class TcpServer extends AbstractVerticle { private static AtomicInteger counter = new AtomicInteger(1); @Override public void start(final Future<Void> startFuture) throws Exception { try { NetServerOptions opts = new NetServerOptions(); NetServer netServer = vertx.createNetServer(opts); netServer.connectHandler(socket -> { String address = socket.remoteAddress().host() + ":" + socket.remoteAddress().port(); final int i = counter.getAndAdd(1); if (i % 1000 == 0) { System.out.println(i + " connections connects in..."); } socket.handler(buffer -> { socket.write("pong"); }); }); netServer.listen(8001); startFuture.succeeded(); } catch (Exception e) { startFuture.fail(e); } } }
31.081081
101
0.581739
d026ff15de6d01d49c3befaaa13e8b1779a6a01d
60
package common.framework; public interface ServiceParam { }
15
31
0.816667
7b151db251fd60bac228630083e55c149dff3bb3
2,416
package br.edu.infnet.model; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.springframework.format.annotation.DateTimeFormat; @Entity @Table(name="evaluation") public class Evaluation { @Id @Column(name = "oid_evaluation") @GeneratedValue(strategy=GenerationType.IDENTITY) private Long oid; @DateTimeFormat(pattern = "dd/MM/yyyy HH:mm:ss") @Column(name = "start_date") @Temporal(TemporalType.TIMESTAMP) private Date startDate; @DateTimeFormat(pattern = "dd/MM/yyyy HH:mm:ss") @Column(name = "final_date") @Temporal(TemporalType.TIMESTAMP) private Date endDate; @DateTimeFormat(pattern = "dd/MM/yyyy hh:mm:ss") @Column(name = "creation_date") @Temporal(TemporalType.TIMESTAMP) private Date creationDate; @Column(name = "invite_text") private String inviteText; @Column(name = "objective") private String objective; @Column(name = "oid_module") private Long oidModule; @Column(name = "status") private String status; public Evaluation() { super(); } public Long getOid() { return oid; } public void setOid(Long oid) { this.oid = oid; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public String getInviteText() { return inviteText; } public void setInviteText(String inviteText) { this.inviteText = inviteText; } public String getObjective() { return objective; } public void setObjective(String objective) { this.objective = objective; } public Date getCreationDate() { return creationDate; } public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } public Long getOidModule() { return oidModule; } public void setOidModule(Long oidModule) { this.oidModule = oidModule; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } }
19.966942
61
0.698262
7c806f90bd1d231e4f3deb3dba379ead16aa6b5c
12,609
package org.apache.rya.indexing.external; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.junit.Assert; import org.junit.Test; import org.openrdf.query.algebra.Projection; import org.openrdf.query.algebra.QueryModelNode; import org.openrdf.query.algebra.StatementPattern; import org.openrdf.query.algebra.TupleExpr; import org.openrdf.query.algebra.helpers.QueryModelVisitorBase; import org.openrdf.query.algebra.helpers.StatementPatternCollector; import org.openrdf.query.parser.ParsedQuery; import org.openrdf.query.parser.sparql.SPARQLParser; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.apache.rya.indexing.external.tupleSet.ExternalTupleSet; import org.apache.rya.indexing.external.tupleSet.SimpleExternalTupleSet; import org.apache.rya.indexing.pcj.matching.PCJOptimizer; public class PrecompJoinOptimizerTest { @Test public void testThreeIndex() throws Exception { final String q7 = ""// + "SELECT ?s ?t ?u " // + "{" // + " ?s a ?t ."// + " ?t <http://www.w3.org/2000/01/rdf-schema#label> ?u ."// + " ?u <uri:talksTo> ?s . "// + "}";// final String q8 = ""// + "SELECT ?e ?l ?c " // + "{" // + " ?e a ?l ."// + " ?l <http://www.w3.org/2000/01/rdf-schema#label> ?c ."// + " ?c <uri:talksTo> ?e . "// + "}";// final String q9 = ""// + "SELECT ?f ?m ?d " // + "{" // + " ?f a ?m ."// + " ?m <http://www.w3.org/2000/01/rdf-schema#label> ?d ."// + " ?d <uri:talksTo> ?f . "// + "}";// final String q15 = ""// + "SELECT ?f ?m ?d ?e ?l ?c " // + "{" // + " ?f a ?m ."// + " ?e a ?l ."// + " ?d <uri:talksTo> ?f . "// + " ?c <uri:talksTo> ?e . "// + " ?m <http://www.w3.org/2000/01/rdf-schema#label> ?d ."// + " ?l <http://www.w3.org/2000/01/rdf-schema#label> ?c ."// + "}";// final SPARQLParser parser = new SPARQLParser(); final ParsedQuery pq1 = parser.parseQuery(q15, null); final ParsedQuery pq2 = parser.parseQuery(q7, null); final ParsedQuery pq3 = parser.parseQuery(q8, null); final ParsedQuery pq4 = parser.parseQuery(q9, null); final SimpleExternalTupleSet extTup1 = new SimpleExternalTupleSet( (Projection) pq2.getTupleExpr()); final SimpleExternalTupleSet extTup2 = new SimpleExternalTupleSet( (Projection) pq3.getTupleExpr()); final SimpleExternalTupleSet extTup3 = new SimpleExternalTupleSet( (Projection) pq4.getTupleExpr()); final List<ExternalTupleSet> list = new ArrayList<ExternalTupleSet>(); list.add(extTup1); final List<QueryModelNode> optTupNodes = Lists.newArrayList(); optTupNodes.add(extTup2); optTupNodes.add(extTup3); final PCJOptimizer pcj = new PCJOptimizer(list, true); final TupleExpr te = pq1.getTupleExpr(); pcj.optimize(te, null, null); final NodeCollector nc = new NodeCollector(); te.visit(nc); Assert.assertEquals(nc.qNodes.size(), optTupNodes.size()); for (final QueryModelNode node : nc.qNodes) { Assert.assertTrue(optTupNodes.contains(node)); } } @Test public void testThreeIndex2() throws Exception { final String q1 = ""// + "SELECT ?f ?m ?d ?e ?l ?c " // + "{" // + " ?f a ?m ."// + " ?c a ?l ."// + " ?d <uri:talksTo> ?f . "// + " ?e <uri:talksTo> ?c . "// + " ?m <http://www.w3.org/2000/01/rdf-schema#label> ?d ."// + " ?l <http://www.w3.org/2000/01/rdf-schema#label> ?e ."// + " ?m <uri:talksTo> ?e . "// + "}";// final String q2 = ""// + "SELECT ?u ?s ?t " // + "{" // + " ?s a ?t ."// + " ?t <http://www.w3.org/2000/01/rdf-schema#label> ?u ."// + " ?u <uri:talksTo> ?s . "// + "}";// final String q3 = ""// + "SELECT ?e ?c ?l " // + "{" // + " ?c a ?l ."// + " ?l <http://www.w3.org/2000/01/rdf-schema#label> ?e ."// + " ?e <uri:talksTo> ?c . "// + "}";// final String q4 = ""// + "SELECT ?d ?f ?m " // + "{" // + " ?f a ?m ."// + " ?m <http://www.w3.org/2000/01/rdf-schema#label> ?d ."// + " ?d <uri:talksTo> ?f . "// + "}";// final SPARQLParser parser = new SPARQLParser(); final ParsedQuery pq1 = parser.parseQuery(q1, null); final ParsedQuery pq2 = parser.parseQuery(q2, null); final ParsedQuery pq3 = parser.parseQuery(q3, null); final ParsedQuery pq4 = parser.parseQuery(q4, null); final SimpleExternalTupleSet extTup1 = new SimpleExternalTupleSet( (Projection) pq2.getTupleExpr()); final SimpleExternalTupleSet extTup2 = new SimpleExternalTupleSet( (Projection) pq3.getTupleExpr()); final SimpleExternalTupleSet extTup3 = new SimpleExternalTupleSet( (Projection) pq4.getTupleExpr()); final List<ExternalTupleSet> list = new ArrayList<ExternalTupleSet>(); list.add(extTup1); final List<StatementPattern> spList = StatementPatternCollector .process(pq1.getTupleExpr()); final List<QueryModelNode> optTupNodes = Lists.newArrayList(); optTupNodes.add(extTup3); optTupNodes.add(spList.get(6)); optTupNodes.add(extTup2); final PCJOptimizer pcj = new PCJOptimizer(list, true); final TupleExpr te = pq1.getTupleExpr(); pcj.optimize(te, null, null); final NodeCollector nc = new NodeCollector(); te.visit(nc); Assert.assertEquals(nc.qNodes, Sets.newHashSet(optTupNodes)); } @Test public void testSixIndex() throws Exception { final String q1 = ""// + "SELECT ?f ?m ?d ?h ?i " // + "{" // + " ?f a ?m ."// + " ?m <http://www.w3.org/2000/01/rdf-schema#label> ?d ."// + " ?d <uri:talksTo> ?f . "// + " ?d <uri:hangOutWith> ?f ." // + " ?f <uri:hangOutWith> ?h ." // + " ?f <uri:associatesWith> ?i ." // + " ?i <uri:associatesWith> ?h ." // + "}";// final String q2 = ""// + "SELECT ?t ?s ?u " // + "{" // + " ?s a ?t ."// + " ?t <http://www.w3.org/2000/01/rdf-schema#label> ?u ."// + " ?u <uri:talksTo> ?s . "// + "}";// final String q3 = ""// + "SELECT ?s ?t ?u " // + "{" // + " ?s <uri:hangOutWith> ?t ." // + " ?t <uri:hangOutWith> ?u ." // + "}";// final String q4 = ""// + "SELECT ?s ?t ?u " // + "{" // + " ?s <uri:associatesWith> ?t ." // + " ?t <uri:associatesWith> ?u ." // + "}";// final String q5 = ""// + "SELECT ?m ?f ?d " // + "{" // + " ?f a ?m ."// + " ?m <http://www.w3.org/2000/01/rdf-schema#label> ?d ."// + " ?d <uri:talksTo> ?f . "// + "}";// final String q6 = ""// + "SELECT ?d ?f ?h " // + "{" // + " ?d <uri:hangOutWith> ?f ." // + " ?f <uri:hangOutWith> ?h ." // + "}";// final String q7 = ""// + "SELECT ?f ?i ?h " // + "{" // + " ?f <uri:associatesWith> ?i ." // + " ?i <uri:associatesWith> ?h ." // + "}";// final SPARQLParser parser = new SPARQLParser(); final ParsedQuery pq1 = parser.parseQuery(q1, null); final ParsedQuery pq2 = parser.parseQuery(q2, null); final ParsedQuery pq3 = parser.parseQuery(q3, null); final ParsedQuery pq4 = parser.parseQuery(q4, null); final ParsedQuery pq5 = parser.parseQuery(q5, null); final ParsedQuery pq6 = parser.parseQuery(q6, null); final ParsedQuery pq7 = parser.parseQuery(q7, null); final SimpleExternalTupleSet extTup1 = new SimpleExternalTupleSet( (Projection) pq2.getTupleExpr()); final SimpleExternalTupleSet extTup2 = new SimpleExternalTupleSet( (Projection) pq3.getTupleExpr()); final SimpleExternalTupleSet extTup3 = new SimpleExternalTupleSet( (Projection) pq4.getTupleExpr()); final SimpleExternalTupleSet extTup4 = new SimpleExternalTupleSet( (Projection) pq5.getTupleExpr()); final SimpleExternalTupleSet extTup5 = new SimpleExternalTupleSet( (Projection) pq6.getTupleExpr()); final SimpleExternalTupleSet extTup6 = new SimpleExternalTupleSet( (Projection) pq7.getTupleExpr()); final List<ExternalTupleSet> list = new ArrayList<ExternalTupleSet>(); list.add(extTup2); list.add(extTup1); list.add(extTup3); final List<QueryModelNode> optTupNodes = Lists.newArrayList(); optTupNodes.add(extTup4); optTupNodes.add(extTup6); optTupNodes.add(extTup5); final PCJOptimizer pcj = new PCJOptimizer(list, true); final TupleExpr te = pq1.getTupleExpr(); pcj.optimize(te, null, null); System.out.println(te); final NodeCollector nc = new NodeCollector(); te.visit(nc); Assert.assertEquals(nc.qNodes, Sets.newHashSet(optTupNodes)); } @Test public void twoFourIndexWithFilterTest() throws Exception { final String q1 = ""// + "SELECT ?f ?m ?d ?e ?l ?c " // + "{" // + " Filter(?f > \"5\")." // + " Filter(?e > \"5\")." // + " ?f a ?m ."// + " ?e a ?l ."// + " ?d <uri:talksTo> ?f . "// + " ?c <uri:talksTo> ?e . "// + " ?m <http://www.w3.org/2000/01/rdf-schema#label> ?d ."// + " ?l <http://www.w3.org/2000/01/rdf-schema#label> ?c ."// + "}";// final String q2 = ""// + "SELECT ?s ?t ?u " // + "{" // + " ?s a ?t ."// + " ?t <http://www.w3.org/2000/01/rdf-schema#label> ?u ."// + " ?u <uri:talksTo> ?s . "// + "}";// final String q3 = ""// + "SELECT ?s ?t ?u " // + "{" // + " Filter(?s > \"5\") ."// + " ?s a ?t ."// + " ?t <http://www.w3.org/2000/01/rdf-schema#label> ?u ."// + " ?u <uri:talksTo> ?s . "// + "}";// final String q4 = ""// + "SELECT ?f ?m ?d " // + "{" // + " Filter(?f > \"5\") ."// + " ?f a ?m ."// + " ?m <http://www.w3.org/2000/01/rdf-schema#label> ?d ."// + " ?d <uri:talksTo> ?f . "// + "}";// final String q5 = ""// + "SELECT ?e ?l ?c " // + "{" // + " Filter(?e > \"5\") ."// + " ?e a ?l ."// + " ?l <http://www.w3.org/2000/01/rdf-schema#label> ?c ."// + " ?c <uri:talksTo> ?e . "// + "}";// final SPARQLParser parser = new SPARQLParser(); ParsedQuery pq1 = null; ParsedQuery pq2 = null; ParsedQuery pq3 = null; ParsedQuery pq4 = null; ParsedQuery pq5 = null; try { pq1 = parser.parseQuery(q1, null); pq2 = parser.parseQuery(q2, null); pq3 = parser.parseQuery(q3, null); pq4 = parser.parseQuery(q4, null); pq5 = parser.parseQuery(q5, null); } catch (final Exception e) { e.printStackTrace(); } final SimpleExternalTupleSet extTup1 = new SimpleExternalTupleSet( (Projection) pq2.getTupleExpr()); final SimpleExternalTupleSet extTup2 = new SimpleExternalTupleSet( (Projection) pq3.getTupleExpr()); final SimpleExternalTupleSet extTup3 = new SimpleExternalTupleSet( (Projection) pq4.getTupleExpr()); final SimpleExternalTupleSet extTup4 = new SimpleExternalTupleSet( (Projection) pq5.getTupleExpr()); final List<ExternalTupleSet> list = new ArrayList<ExternalTupleSet>(); list.add(extTup2); list.add(extTup1); final List<ExternalTupleSet> list2 = new ArrayList<ExternalTupleSet>(); list2.add(extTup3); list2.add(extTup4); final PCJOptimizer pcj = new PCJOptimizer(list, true); final TupleExpr te = pq1.getTupleExpr(); pcj.optimize(te, null, null); System.out.println(te); final NodeCollector nc = new NodeCollector(); te.visit(nc); Assert.assertEquals(nc.qNodes.size(), list2.size()); for (final QueryModelNode e : nc.qNodes) { Assert.assertTrue(list2.contains(e)); } } public static class NodeCollector extends QueryModelVisitorBase<RuntimeException> { Set<QueryModelNode> qNodes = new HashSet<>(); @Override public void meetNode(final QueryModelNode node) { if (node instanceof StatementPattern || node instanceof ExternalTupleSet) { qNodes.add(node); } super.meetNode(node); } public List<QueryModelNode> getNodes() { return Lists.newArrayList(qNodes); } } }
29.323256
73
0.604727
111d584c802770c1594585a65a0a1b3ed3274b03
2,273
package gg.projecteden.nexus.features.commands; import gg.projecteden.nexus.framework.commands.models.CustomCommand; import gg.projecteden.nexus.framework.commands.models.annotations.Arg; import gg.projecteden.nexus.framework.commands.models.annotations.Description; import gg.projecteden.nexus.framework.commands.models.annotations.Path; import gg.projecteden.nexus.framework.commands.models.annotations.Permission.Group; import gg.projecteden.nexus.framework.commands.models.annotations.Redirects.Redirect; import gg.projecteden.nexus.framework.commands.models.events.CommandEvent; import gg.projecteden.nexus.utils.Tasks; import gg.projecteden.utils.StringUtils; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.inventivetalent.glow.GlowAPI; import java.util.Collections; import static gg.projecteden.nexus.utils.StringUtils.stripColor; @Redirect(from = "/entityhealth", to = "/health target") @Description("View the health of a player or entity") public class HealthCommand extends CustomCommand { public HealthCommand(CommandEvent event) { super(event); } @Path("<player> [number]") void health(@Arg("self") Player player, @Arg(permission = Group.STAFF, min = 0.0, max = 20.0) Double health) { String healthFormat = getFormattedHealth(player); if (health == null) send(PREFIX + player.getName() + "'s health is &e" + healthFormat); else { player.setHealth(health); send(PREFIX + stripColor(player.getName()) + "'s health set to &e" + healthFormat); } } @Path("target [number]") void target(@Arg(permission = Group.STAFF, min = 0.0, max = 20.0) Double health) { LivingEntity target = getTargetLivingEntityRequired(); Tasks.GlowTask.builder() .duration(10 * 20) .entity(target) .color(GlowAPI.Color.RED) .viewers(Collections.singletonList(player())) .start(); String healthFormat = getFormattedHealth(target); if (health == null) send(PREFIX + stripColor(target.getName()) + "'s health is &e" + healthFormat); else { target.setHealth(health); send(PREFIX + stripColor(target.getName()) + "'s health set to &e" + healthFormat); } } private String getFormattedHealth(LivingEntity livingEntity) { return StringUtils.getDf().format(livingEntity.getHealth()); } }
36.079365
111
0.75407
9747e26bb80f0439a87ca25b1a608515ffbcd0bf
2,594
package com.revature.security; import java.util.Date; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Component; import com.revature.model.CustomUserBean; import io.jsonwebtoken.Claims; import io.jsonwebtoken.ExpiredJwtException; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.MalformedJwtException; import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.SignatureException; import io.jsonwebtoken.UnsupportedJwtException; /** * A utility class that does following three tasks: * * - 1. Generate the token by setting user name, issued time, expiration time. * - 2. Validate token * - 3. Get user name from taken. */ @Component public class JwtTokenUtil { /** * This annotation can be used for injecting values into fields in * Spring-managed beans, and it can be applied at the field or * constructor/method parameter level. */ @Value("${jwttoken.secret}") private String jwtTokenSecret; @Value("${jwttoken.expiration}") private long jwtTokenExpiration; public String generateJwtToken(Authentication authentication) { CustomUserBean userPrincipal = (CustomUserBean)authentication.getPrincipal(); return Jwts.builder() .setSubject(userPrincipal.getUsername()) .setIssuedAt(new Date(System.currentTimeMillis())) .setExpiration(new Date(System.currentTimeMillis() + jwtTokenExpiration)) .signWith(SignatureAlgorithm.HS512, jwtTokenSecret) .compact(); } public boolean validateJwtToken(String token) { try { Jwts.parser() .setSigningKey(jwtTokenSecret) .parseClaimsJws(token); return true; }catch(UnsupportedJwtException exp) { System.out.println("claimsJws argument does not represent Claims JWS" + exp.getMessage()); }catch(MalformedJwtException exp) { System.out.println("claimsJws string is not a valid JWS" + exp.getMessage()); }catch(SignatureException exp) { System.out.println("claimsJws JWS signature validation failed" + exp.getMessage()); }catch(ExpiredJwtException exp) { System.out.println("Claims has an expiration time before the method is invoked" + exp.getMessage()); }catch(IllegalArgumentException exp) { System.out.println("claimsJws string is null or empty or only whitespace" + exp.getMessage()); } return false; } public String getUserNameFromJwtToken(String token) { Claims claims =Jwts.parser() .setSigningKey(jwtTokenSecret) .parseClaimsJws(token) .getBody(); return claims.getSubject(); } }
32.425
103
0.751349
810f065b574b5ef5ad20d87546cef6c592a6d58d
4,448
package com.datapath.ocds.kyrgyzstan.exporter.receivers; import com.datapath.ocds.kyrgyzstan.exporter.OrderStatus; import com.datapath.ocds.kyrgyzstan.exporter.dao.entity.JsonEvent; import com.datapath.ocds.kyrgyzstan.exporter.dao.entity.LotDAO; import com.datapath.ocds.kyrgyzstan.exporter.dao.entity.Order; import com.datapath.ocds.kyrgyzstan.exporter.dao.services.EvaluationCompletedDAOService; import com.datapath.ocds.kyrgyzstan.exporter.events.*; import com.neovisionaries.i18n.CountryCode; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; import java.util.ArrayList; import java.util.List; import static com.datapath.ocds.kyrgyzstan.exporter.Constants.DASH; import static com.datapath.ocds.kyrgyzstan.exporter.Constants.OCID_PREFIX; import static com.datapath.ocds.kyrgyzstan.exporter.Constants.convert; import static java.util.Collections.singletonList; import static java.util.Objects.nonNull; @Component public class EvaluationCompletedReceiver extends EventReceiverAbs { @Autowired private EvaluationCompletedDAOService dao; public EvaluationCompletedEvent receive(JsonEvent jsonEvent) { Order order = dao.getOrder(jsonEvent.getOrderId()); EvaluationCompletedEvent event = new EvaluationCompletedEvent(); event.setDate(convert(jsonEvent.getDateCreated())); event.setSingleTag("award"); event.setOcid(OCID_PREFIX + jsonEvent.getOrderId()); event.setId(event.getOcid() + DASH + jsonEvent.getId()); event.setEventType(jsonEvent.getType()); Tender tender = new Tender(); tender.setId(String.valueOf(order.getId())); tender.setCurrentStage(OrderStatus.getStatus(order.getStatus()).getName()); tender.setLots(getLots(order.getId())); event.setTender(tender); event.setParties(getParties(jsonEvent.getId())); event.setBids(getBids(jsonEvent)); event.setAwards(getAwards(jsonEvent)); event.setEventErrors(getSequenceErrors(jsonEvent)); return event; } private List<Lot> getLots(Integer orderId) { List<Lot> lots = new ArrayList<>(); List<LotDAO> daoLots = dao.getLots(orderId); for (LotDAO daoLot : daoLots) { Lot lot = new Lot(); lot.setId(daoLot.getId()); if (daoLot.getStatus().equals(3)) { lot.setStatus("unsuccessful"); } else { lot.setStatus("active"); } lots.add(lot); } return lots; } private List<Party> getParties(Integer jsonEventId) { List<Party> parties = new ArrayList<>(); dao.getParties(jsonEventId).forEach(daoParty -> { Party party = new Party(); String alpha2 = CountryCode.getByCode(daoParty.getCountryCode()).getAlpha2(); party.setId(alpha2 + "-INN" + DASH + daoParty.getId()); if (nonNull(daoParty.getRole())) { party.setRoles(singletonList(daoParty.getRole())); } parties.add(party); }); return parties; } private Bids getBids(JsonEvent jsonEvent) { List<BidDetail> details = new ArrayList<>(); dao.getBids(jsonEvent.getId()).forEach(daoDetail -> { BidDetail detail = new BidDetail(); detail.setId(daoDetail.getId()); detail.setStatus(daoDetail.getStatus()); detail.setDate(convert(jsonEvent.getDateCreated())); details.add(detail); }); return details.isEmpty() ? null : new Bids(details); } private List<Award> getAwards(JsonEvent jsonEvent) { List<Award> awards = new ArrayList<>(); dao.getAwards(jsonEvent.getId()).forEach(daoAward -> { Award award = new Award(); award.setId(daoAward.getId()); award.setStatus(daoAward.getStatus()); award.setRelatedLots(List.of(daoAward.getRelatedLot())); award.setRelatedBid(daoAward.getRelatedBid()); award.setDatePublished(convert(jsonEvent.getDateCreated())); Value value = new Value(); value.setAmount(daoAward.getAmount()); value.setCurrency("KGS"); award.setValue(value); awards.add(award); }); return awards.isEmpty() ? null : awards; } }
37.378151
89
0.659397
23d220799bcb91973f38ad6ed0c2f534eeed1e55
2,639
package com.norsepotions.burlesquenamegenerator; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; public class MainActivity extends BaseActivity { @Bind(R.id.nameView) TextView mNameView; @Bind(R.id.shareImageView) ImageView mShareImageView; @Bind(R.id.newNameButton) Button mNewNameButton; NameFetcher mNameFetcher; String mLastGeneratedName; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); attachListeners(); mNameFetcher = new NameFetcher(); generateNewName(); } @OnClick(R.id.newNameButton) public void generateNewName() { String newName = mNameFetcher.getName(); mNameView.setText(newName); mLastGeneratedName = newName; } @OnClick(R.id.shareImageView) public void shareName() { String body = "My new burlesque name is " + mLastGeneratedName +".\n\n via Burlesque Name Generator for Android"; Intent sendIntent = new Intent(Intent.ACTION_SEND); sendIntent.setType("text/plain"); sendIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.share_subject)); sendIntent.putExtra(Intent.EXTRA_TEXT, body); startActivity(Intent.createChooser(sendIntent, getString(R.string.share_via))); mShareImageView.setBackgroundColor(0x00000000); } public void attachListeners() { mShareImageView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { mShareImageView.setBackgroundColor(Color.parseColor("#000000")); mShareImageView.getBackground().setAlpha(20); return false; } }); mNewNameButton.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { mNewNameButton.getBackground().setAlpha(180); } else if (event.getAction() == MotionEvent.ACTION_UP) { mNewNameButton.getBackground().setAlpha(255); } return false; } }); } }
31.047059
121
0.665404
11a1900fd8de048e7494fcfe633ee5597cda7891
3,114
/* * Copyright (c) 2018, The University of Memphis, MD2K Center of Excellence * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.md2k.motionsense; import android.app.Application; import android.content.Context; import android.util.Log; import com.polidea.rxandroidble.RxBleClient; import com.polidea.rxandroidble.internal.RxBleLog; import org.md2k.mcerebrum.commons.debug.MyLogger; import org.md2k.mcerebrum.core.access.MCerebrum; /** * This class connects this application to the <code>MCerebrum</code> core library. */ public class MyApplication extends Application { private RxBleClient rxBleClient; /** * Creates the activity, an <code>RxBleClient</code>, and calls on the <code>MCerebrum</code> * library for initialization. */ @Override public void onCreate() { super.onCreate(); Log.d("abc","MyApplication.. onCreate()"); rxBleClient = RxBleClient.create(this); MCerebrum.init(getApplicationContext(), MyMCerebrumInit.class); Log.d("abc","rxBleClient: state=" + rxBleClient.getState().toString()); Log.d("abc","rxBleClient: bondedDevices size=" + rxBleClient.getBondedDevices().size()); MyLogger.setLogger(getApplicationContext()); } /** * Returns the <code>RxBleClient</code> for this application. * @param context Android context * @return The <code>RxBleClient</code> for this application. */ public static RxBleClient getRxBleClient(Context context) { MyApplication application = (MyApplication) context.getApplicationContext(); Log.d("abc","rxBleClient: state=" + application.rxBleClient.getState().toString()); Log.d("abc","rxBleClient: bondedDevices size=" + application.rxBleClient.getBondedDevices().size()); return application.rxBleClient; } }
41.52
108
0.734425
7ba2eba456b8ec41bfc898a06c1a0bec9bb4b61b
4,012
/* Generic definitions */ /* Assertions (useful to generate conditional code) */ /* Current type and class (and size, if applicable) */ /* Value methods */ /* Interfaces (keys) */ /* Interfaces (values) */ /* Abstract implementations (keys) */ /* Abstract implementations (values) */ /* Static containers (keys) */ /* Static containers (values) */ /* Implementations */ /* Synchronized wrappers */ /* Unmodifiable wrappers */ /* Other wrappers */ /* Methods (keys) */ /* Methods (values) */ /* Methods (keys/values) */ /* Methods that have special names depending on keys (but the special names depend on values) */ /* Equality */ /* Object/Reference-only definitions (keys) */ /* Primitive-type-only definitions (keys) */ /* Object/Reference-only definitions (values) */ /* * Copyright (C) 2003-2013 Sebastiano Vigna * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package it.unimi.dsi.fastutil.floats; /** A class providing static methods and objects that do useful things with type-specific priority queues. * * @see it.unimi.dsi.fastutil.PriorityQueue */ public class FloatPriorityQueues { private FloatPriorityQueues() {} /** A synchronized wrapper class for priority queues. */ public static class SynchronizedPriorityQueue implements FloatPriorityQueue { final protected FloatPriorityQueue q; final protected Object sync; protected SynchronizedPriorityQueue( final FloatPriorityQueue q, final Object sync ) { this.q = q; this.sync = sync; } protected SynchronizedPriorityQueue( final FloatPriorityQueue q ) { this.q = q; this.sync = this; } public void enqueue( float x ) { synchronized( sync ) { q.enqueue( x ); } } public float dequeueFloat() { synchronized( sync ) { return q.dequeueFloat(); } } public float firstFloat() { synchronized( sync ) { return q.firstFloat(); } } public float lastFloat() { synchronized( sync ) { return q.lastFloat(); } } public boolean isEmpty() { synchronized( sync ) { return q.isEmpty(); } } public int size() { synchronized( sync ) { return q.size(); } } public void clear() { synchronized( sync ) { q.clear(); } } public void changed() { synchronized( sync ) { q.changed(); } } public FloatComparator comparator() { synchronized( sync ) { return q.comparator(); } } public void enqueue( Float x ) { synchronized( sync ) { q.enqueue( x ); } } public Float dequeue() { synchronized( sync ) { return q.dequeue(); } } public Float first() { synchronized( sync ) { return q.first(); } } public Float last() { synchronized( sync ) { return q.last(); } } } /** Returns a synchronized type-specific priority queue backed by the specified type-specific priority queue. * * @param q the priority queue to be wrapped in a synchronized priority queue. * @return a synchronized view of the specified priority queue. */ public static FloatPriorityQueue synchronize( final FloatPriorityQueue q ) { return new SynchronizedPriorityQueue( q ); } /** Returns a synchronized type-specific priority queue backed by the specified type-specific priority queue, using an assigned object to synchronize. * * @param q the priority queue to be wrapped in a synchronized priority queue. * @param sync an object that will be used to synchronize the access to the priority queue. * @return a synchronized view of the specified priority queue. */ public static FloatPriorityQueue synchronize( final FloatPriorityQueue q, final Object sync ) { return new SynchronizedPriorityQueue( q, sync ); } }
45.078652
151
0.716351
04eddd7710b3f615a9d6dc73da8ca5b7f0ff21a6
11,020
/* * 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 cz.muni.fi.mir.controllers; import cz.muni.fi.mir.db.domain.AnnotationValue; import cz.muni.fi.mir.db.domain.Configuration; import cz.muni.fi.mir.db.domain.User; import cz.muni.fi.mir.db.domain.UserRole; import cz.muni.fi.mir.db.service.AnnotationValueSerivce; import cz.muni.fi.mir.db.service.CanonicOutputService; import cz.muni.fi.mir.db.service.ConfigurationService; import cz.muni.fi.mir.db.service.RevisionService; import cz.muni.fi.mir.db.service.UserRoleService; import cz.muni.fi.mir.db.service.UserService; import cz.muni.fi.mir.forms.UserForm; import cz.muni.fi.mir.services.MailService; import cz.muni.fi.mir.tools.EntityFactory; import cz.muni.fi.mir.tools.Tools; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.IOUtils; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.access.annotation.Secured; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.ServletRequestBindingException; import org.springframework.web.bind.ServletRequestUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; /** * * @author emptka */ @RequestMapping("/setup") @Controller public class InstallController { private static final Logger logger = Logger.getLogger(InstallController.class); @Autowired private UserService userService; @Autowired private UserRoleService userRoleService; @Autowired private ConfigurationService configurationService; @Autowired private MailService mailService; @Autowired private RevisionService revisionService; @Autowired private AnnotationValueSerivce annotationValueSerivce; @Autowired private CanonicOutputService canonicOutputService; @Value("${mathml-canonicalizer.default.revision}") private String revisionValue; @RequestMapping(value = "/", method = RequestMethod.GET) public ModelAndView landingPage() { if (Tools.getInstance().isEmpty(userService.getAllUsers())) { ModelMap mm = new ModelMap(); mm.addAttribute("userForm", new UserForm()); return new ModelAndView("setup/step1", mm); } else { return new ModelAndView("redirect:/reset/"); } } @RequestMapping(value = "/step2/", method = RequestMethod.POST) public ModelAndView step2(HttpServletRequest request) { String username = null; String email = null; String pass1 = null; String passVerify = null; try { username = ServletRequestUtils.getStringParameter(request, "username"); email = ServletRequestUtils.getStringParameter(request, "email"); pass1 = ServletRequestUtils.getStringParameter(request, "password"); passVerify = ServletRequestUtils.getStringParameter(request, "passwordVerify"); } catch (ServletRequestBindingException ex) { logger.error(ex); } if(Tools.getInstance().stringIsEmpty(username)) { ModelMap mm = new ModelMap(); mm.addAttribute("email", email); return new ModelAndView("setup/step1", mm); } else if(Tools.getInstance().stringIsEmpty(email)) { ModelMap mm = new ModelMap(); mm.addAttribute("username", username); return new ModelAndView("setup/step1", mm); } else if(pass1 != null && !pass1.equals(passVerify)) { ModelMap mm = new ModelMap(); mm.addAttribute("email", email); mm.addAttribute("username", username); return new ModelAndView("setup/step1", mm); } else { List<UserRole> roles = userRoleService.getAllUserRoles(); if(Tools.getInstance().isEmpty(roles)) { UserRole ur1 = EntityFactory.createUserRole("ROLE_ADMINISTRATOR"); UserRole ur2 = EntityFactory.createUserRole("ROLE_USER"); userRoleService.createUserRole(ur1); userRoleService.createUserRole(ur2); roles = new ArrayList<>(); roles.add(ur1); roles.add(ur2); } User u = EntityFactory.createUser(username, pass1, username, email, roles); User u2 = EntityFactory.createUser("system", null, "system", "webmias@fi.muni.cz", roles); u.setPassword(Tools.getInstance().SHA1(u.getPassword())); userService.createUser(u); userService.createUser(u2); revisionService.createRevision( EntityFactory .createRevision(revisionValue, "Default revision created by install process.") ); // config should be outside controller, but its run only once per // aplication setup so it does not matter somehow InputStream is = InstallController.class.getClassLoader().getResourceAsStream("other/sample-config-1.1SNAP.xml"); Configuration config = null; try { String xmlContent = IOUtils.toString(is); config = EntityFactory.createConfiguration(xmlContent, "sample-config-1.1SNAP", "Default configuration created by install process."); logger.info("Loaded sample config"); logger.info(xmlContent); } catch(IOException ex) { logger.error(ex); } finally { if(is != null) { try { is.close(); } catch(IOException ex) { logger.error(ex); } } } if(config != null) { configurationService.createConfiguration(config); } for(AnnotationValue av : provideAnnotaionValues()) { annotationValueSerivce.createAnnotationValue(av); } mailService.sendMail(null, email, "Installation is now complete.", "Installation of MathCanEval application has ended. Below are user credentials submited in setup process.\n" +"Username: "+username+"\nPassword: "+passVerify); return new ModelAndView("redirect:/"); } } private AnnotationValue[] provideAnnotaionValues() { AnnotationValue[] values = new AnnotationValue[6]; values[0] = prepareAnnotationValue(AnnotationValue.Type.FORMULA, "#formulaRemove", "Formula should be removed from the database as the formula markup is" + " invalid (i.e. the formula MathML is not valid XML)", "remove", "danger", Integer.valueOf("10")); values[1] = prepareAnnotationValue(AnnotationValue.Type.FORMULA, "#formulaMeaningless", "Formula is valid MathML but is meaningless, for example " + "some text improperly encoded as string of math variables.", "trash", "danger", Integer.valueOf("9")); values[2] = prepareAnnotationValue(AnnotationValue.Type.CANONICOUTPUT, "#isValid", "Canonicalization result is correct according to current implementation of the canonicalization functions, " + "i.e. all the canonicalization methods were applied correctly and the result is valid MathML " + "with the same meaning of the input formula.", "ok", "success", Integer.valueOf("10")); values[3] = prepareAnnotationValue(AnnotationValue.Type.CANONICOUTPUT, "#isInvalid", "Implemented canonicalization methods were not applied correctly according their specification, or the " + "result is not valid MathML, or the result formula has different meaning as the input one.", "flag", "warning", Integer.valueOf("9")); values[4] = prepareAnnotationValue(AnnotationValue.Type.CANONICOUTPUT, "#uncertain", "The annotator is not able to decide the canonicalization was applied correctly.", "question-sign", "info", Integer.valueOf("8")); values[5] = prepareAnnotationValue(AnnotationValue.Type.CANONICOUTPUT, "#removeResult", "The result should be removed for any reason.", "remove", "danger", Integer.valueOf("7")); return values; } @RequestMapping("/update") public ModelAndView setupCanonicOutputs() { canonicOutputService.recalculateHashes(); User u2 = EntityFactory.createUser("system", null, "system", "webmias@fi.muni.cz", userRoleService.getAllUserRoles()); userService.createUser(u2); return new ModelAndView("redirect:/"); } private AnnotationValue prepareAnnotationValue(AnnotationValue.Type type, String value, String description, String icon, String label, Integer priority) { AnnotationValue av = new AnnotationValue(); av.setDescription(description); av.setIcon(icon); av.setLabel(label); av.setPriority(priority); av.setType(type); av.setValue(value); return av; } @Secured("ROLE_ADMINISTRATOR") @RequestMapping(value = "/reset/",method = RequestMethod.GET) public ModelAndView handleReset() { // Configuration cfg = new Configuration(); // cfg.setProperty(null, null) return new ModelAndView("redirect:/"); } }
39.498208
141
0.588475
81622ece25c085ceeefc7218fc46299c51da48b6
160
package com.hvpaiva.factorymethod; /** * Interface de Pizza. */ public interface Pizza { /** * @return O tipo daquela pizza. */ String tipoPizza(); }
12.307692
34
0.65
590c2e5e1caff9f2dee621de15e1dc32abd65065
2,547
package com.old.time.utils; import com.old.time.BuildConfig; import com.old.time.beans.UserInfoBean; import com.old.time.constants.Key; import java.util.Random; /** * Created by NING on 2018/4/5. */ public class UserLocalInfoUtils { private static UserLocalInfoUtils mUserLocalInfoUtils; /** * 全局用户信息实例 * * @return */ public static UserLocalInfoUtils instance() { if (mUserLocalInfoUtils == null) { mUserLocalInfoUtils = new UserLocalInfoUtils(); mUserLocalInfoUtils.initLocalUserInfo(); } return mUserLocalInfoUtils; } private UserInfoBean mUserInfoBean; private void initLocalUserInfo() { mUserInfoBean = SpUtils.getObject(Key.GET_USER_INFO_BEAN); } public UserInfoBean getmUserInfoBean() { return mUserInfoBean; } /** * 获取用户手机号 * * @return */ public String getMobile() { if (mUserInfoBean == null) { return "-1"; } return mUserInfoBean.getMobile(); } /** * 获取用户心id * * @return */ public String getUserId() { if (mUserInfoBean == null) { return "-1"; } return mUserInfoBean.getUserId(); } private Random mRandom = new Random(); /** * 获取用户userId * * @return */ public String getParamUserId() { if (mUserInfoBean == null) { return "-1"; } if (!BuildConfig.DEBUG && ("15093073252".equals(getMobile()) || "17600075773".equals(getMobile()))) { return String.valueOf("01" + mRandom.nextInt(56)); } else { return getUserId(); } } /** * 设置用户信息 * * @param mUserInfoBean */ public void setmUserInfoBean(UserInfoBean mUserInfoBean) { if (mUserInfoBean != null) { SpUtils.setObject(Key.GET_USER_INFO_BEAN, mUserInfoBean); } this.mUserInfoBean = mUserInfoBean; } /** * 获取用户登陆状态 * * @return */ public boolean isUserLogin() { if (mUserInfoBean != null) { return true; } return false; } /** * 退出登陆 */ public void setUserLogOut() { SpUtils.clear(); mUserInfoBean = null; } /** * 获取融云token * * @return */ public String getRongIMToken() { if (mUserInfoBean == null) { return "-1"; } return mUserInfoBean.getToken(); } }
18.06383
109
0.538673
234ba656a0d2124c0e126047a0493b53a5972441
1,054
package com.cardealer.beans; public class UserCreds { private Integer id; private String username; private String password; private Integer customer; public UserCreds(Integer id, String username, String password, Integer customer) { super(); this.id = id; this.username = username; this.password = password; this.setCustomer(customer); } public UserCreds() { super(); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } 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 Integer getCustomer() { return customer; } public void setCustomer(Integer customer) { this.customer = customer; } @Override public String toString() { return "UserCreds [id=" + id + ", username=" + username + ", password=" + password + ", customer=" + customer + "]"; } }
17
111
0.681214
6d648c62fa1d3685b73e6accad15a2f182b2bf56
923
package com.geeksforgeeks.arrays; public class ReArrangeArrayAlternatelyOptimized { public static void main(String[] args) { ReArrangeArrayAlternatelyOptimized reArrangeArrayAlternatelyOptimized = new ReArrangeArrayAlternatelyOptimized(); reArrangeArrayAlternatelyOptimized.rearrange(new int[]{1, 2, 3, 4, 5, 6}, 6); } public void rearrange(int[] arr, int n) { //Tricky solution int maxElement = arr[n - 1] + 1; int minIndex = 0; int maxIndex = n - 1; for (int i = 0; i < n; i++) { if (i % 2 == 0) { arr[i] += (arr[maxIndex] % maxElement) * maxElement; maxIndex--; } else { arr[i] += (arr[minIndex] % maxElement) * maxElement; minIndex++; } } for (int i = 0; i < n; i++) { arr[i] = arr[i] / maxElement; } } }
28.84375
121
0.527627
4615ed445ba765e8504ef9fc3ad670595975d271
293
package com.fun.zpetchain.constant; public class CodeConstant { // 成功 public static String SUCCESS = "00"; // 专属分享,3分钟后可购买 public static String ERROR_30010 = "30010"; // 验证码错误 public static String ERROR_100 = "100"; // 有人抢先下单 public static String ERROR_10002 = "10002"; }
22.538462
45
0.68942
719190168213edc31fab4bbb750422c3bd91c428
4,633
/** * Copyright © 2016-2017 PT VIO Intelligence Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.thingsboard.server.dao.model.nosql; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.PartitionKey; import com.datastax.driver.mapping.annotations.Table; import com.fasterxml.jackson.databind.JsonNode; import org.thingsboard.server.common.data.id.ComponentDescriptorId; import org.thingsboard.server.common.data.plugin.ComponentDescriptor; import org.thingsboard.server.common.data.plugin.ComponentScope; import org.thingsboard.server.common.data.plugin.ComponentType; import org.thingsboard.server.dao.model.SearchTextEntity; import org.thingsboard.server.dao.model.type.JsonCodec; import java.util.UUID; import static org.thingsboard.server.dao.model.ModelConstants.*; /** * @author Andrew Shvayka */ @Table(name = COMPONENT_DESCRIPTOR_COLUMN_FAMILY_NAME) public class ComponentDescriptorEntity implements SearchTextEntity<ComponentDescriptor> { @PartitionKey @Column(name = ID_PROPERTY) private UUID id; @Column(name = COMPONENT_DESCRIPTOR_TYPE_PROPERTY) private ComponentType type; @Column(name = COMPONENT_DESCRIPTOR_SCOPE_PROPERTY) private ComponentScope scope; @Column(name = COMPONENT_DESCRIPTOR_NAME_PROPERTY) private String name; @Column(name = COMPONENT_DESCRIPTOR_CLASS_PROPERTY) private String clazz; @Column(name = COMPONENT_DESCRIPTOR_CONFIGURATION_DESCRIPTOR_PROPERTY, codec = JsonCodec.class) private JsonNode configurationDescriptor; @Column(name = COMPONENT_DESCRIPTOR_ACTIONS_PROPERTY) private String actions; @Column(name = SEARCH_TEXT_PROPERTY) private String searchText; public ComponentDescriptorEntity() { } public ComponentDescriptorEntity(ComponentDescriptor component) { if (component.getId() != null) { this.id = component.getId().getId(); } this.actions = component.getActions(); this.type = component.getType(); this.scope = component.getScope(); this.name = component.getName(); this.clazz = component.getClazz(); this.configurationDescriptor = component.getConfigurationDescriptor(); this.searchText = component.getName(); } @Override public ComponentDescriptor toData() { ComponentDescriptor data = new ComponentDescriptor(new ComponentDescriptorId(id)); data.setType(type); data.setScope(scope); data.setName(this.getName()); data.setClazz(this.getClazz()); data.setActions(this.getActions()); data.setConfigurationDescriptor(this.getConfigurationDescriptor()); return data; } @Override public UUID getId() { return id; } @Override public void setId(UUID id) { this.id = id; } public String getActions() { return actions; } public void setActions(String actions) { this.actions = actions; } public ComponentType getType() { return type; } public void setType(ComponentType type) { this.type = type; } public ComponentScope getScope() { return scope; } public void setScope(ComponentScope scope) { this.scope = scope; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getClazz() { return clazz; } public void setClazz(String clazz) { this.clazz = clazz; } public JsonNode getConfigurationDescriptor() { return configurationDescriptor; } public void setConfigurationDescriptor(JsonNode configurationDescriptor) { this.configurationDescriptor = configurationDescriptor; } public String getSearchText() { return searchText; } @Override public void setSearchText(String searchText) { this.searchText = searchText; } @Override public String getSearchTextSource() { return getSearchText(); } }
28.25
99
0.701273
4c901e883ff167ae9bf727e33e4bfd9726336efe
3,095
package com.ubaid.ms.currencyconversion.service; import com.ubaid.ms.common.dto.CurrencyInfoDTO; import com.ubaid.ms.common.dto.AuditDTO; import com.ubaid.ms.common.dto.AuditDTOBuilder; import com.ubaid.ms.common.dto.ConvertedCurrency; import com.ubaid.ms.common.dto.ExchangeValueDTO; import com.ubaid.ms.currencyconversion.feignProxy.CurrencyConversionServiceProxy; import com.ubaid.ms.currencyconversion.feignProxy.CurrencyExchangeServiceProxy; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; @Service @Slf4j @RequiredArgsConstructor public class CurrencyConversionServiceImp implements CurrencyConversionService { private final CurrencyExchangeServiceProxy exchangeServiceProxy; private final CurrencyConversionServiceProxy conversionServiceProxy; private final AuditService auditService; private final AuthService authService; private final RequestService requestService; @Override public ExchangeValueDTO convertCurrency(CurrencyInfoDTO currencyInfo) { ExchangeValueDTO exchangeValueDTO = getExchangeRate(currencyInfo.fromCurrency(), currencyInfo.toCurrency()); ConvertedCurrency convertedCurrency = getConvertedCurrency(currencyInfo.quantity(), exchangeValueDTO); exchangeValueDTO.setExchangedCurrencyQuantity(convertedCurrency.getConvertedCurrency()); exchangeValueDTO.setQuantity(currencyInfo.quantity()); AuditDTO auditDTO = convertToAudit(exchangeValueDTO, convertedCurrency); auditService.sendAuditLogToMQ(auditDTO); return exchangeValueDTO; } private AuditDTO convertToAudit(ExchangeValueDTO exchangeValueDTO, ConvertedCurrency convertedCurrency) { log.debug("Creating Audit DTO from {} and {}", exchangeValueDTO, convertedCurrency); AuditDTO auditDTO = AuditDTOBuilder .builder() .fromCurrency(exchangeValueDTO.getFrom()) .fromCurrencyValue(exchangeValueDTO.getQuantity()) .toCurrency(exchangeValueDTO.getTo()) .toCurrencyValue(exchangeValueDTO.getExchangedCurrencyQuantity()) .exchangeRate(exchangeValueDTO.getExchangeRate()) .userUUID(authService.getUserUUID()) .currencyConversionPort(convertedCurrency.getPort()) .currencyConversionIP(convertedCurrency.getIpAddress()) .currencyExchangePort(exchangeValueDTO.getPort()) .currencyExchangeIP(exchangeValueDTO.getIpAddress()) .userIPAddress(requestService.getClientIP()) .build(); log.debug("Audit DTO: {}", auditDTO); return auditDTO; } ConvertedCurrency getConvertedCurrency(Double quantity, ExchangeValueDTO exchangeValueDTO) { return conversionServiceProxy.convert(authService.getBearerToken(), quantity, exchangeValueDTO.getExchangeRate()); } ExchangeValueDTO getExchangeRate(String fromCurrency, String toCurrency) { return exchangeServiceProxy.getCurrencyExchangeRate(authService.getBearerToken(), fromCurrency, toCurrency); } }
48.359375
122
0.769628
303708dec1e7718c88c98e9dae61d07571a9fd12
15,597
package com.tu.FinancialQuickCheck.IntegrationTests; import com.tu.FinancialQuickCheck.RatingArea; import com.tu.FinancialQuickCheck.Score; import com.tu.FinancialQuickCheck.db.*; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.http.*; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.logging.Logger; import static org.assertj.core.api.Assertions.assertThat; /** * The current test class verifies the functionalities of the Product Rating Controller */ @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) public class ProductRatingControllerIntegrationTest { static Logger log = Logger.getLogger(ProductRatingControllerIntegrationTest.class.getName()); @LocalServerPort private int port; @Autowired private ProductRatingRepository repository; @Autowired private ProductRepository productRepository; @Autowired private RatingRepository ratingRepository; @Autowired private ProjectRepository projectRepository; @Autowired private TestRestTemplate restTemplate; private String host = "http://localhost:"; private String products = "/products/"; private String ratings = "/ratings"; private String complexity = "?ratingArea=COMPLEXITY"; private String economic = "?ratingArea=ECONOMIC"; private String jsonStringCorrectOneEntry = "{\"ratings\": [{\"ratingID\": 1, \"answer\": \"700 Mio. EUR\",\"comment\": \"new comment 1\",\"score\": \"GERING\"}]}"; private String jsonStringCorrectTwoEntries = "{\"ratings\": [{\"ratingID\": 1, \"answer\": \"700 Mio. EUR\",\"comment\": \"new comment 1\",\"score\": \"GERING\"}," + "{\"ratingID\": 2, \"answer\": \"700 Mio. EUR\",\"comment\": \"new comment 2\",\"score\": \"MITTEL\"}]}"; private String jsonStringEmpty = "{}"; private String jsonStringInvalidRatingID = "{\"ratings\": [{\"ratingID\": 100, \"answer\": \"700 Mio. EUR\",\"comment\": \"new comment 1\",\"score\": \"GERING\"}]}"; private String jsonStringCorrectTwoEntriesInvalidRatingID = "{\"ratings\": [{\"ratingID\": 1, \"answer\": \"700 Mio. EUR\",\"comment\": \"new comment 1\",\"score\": \"GERING\"}," + "{\"ratingID\": 200, \"answer\": \"700 Mio. EUR\",\"comment\": \"new comment 2\",\"score\": \"MITTEL\"}]}"; private String jsonStringMissingAnswer = "{\"ratings\": [{\"ratingID\": 1, \"comment\": \"new comment 1\",\"score\": \"GERING\"}]}"; private String jsonStringMissingComment = "{\"ratings\": [{\"ratingID\": 1, \"answer\": \"700 Mio. EUR\",\"score\": \"GERING\"}]}"; private String jsonStringMissingScore = "{\"ratings\": [{\"ratingID\": 1, \"answer\": \"700 Mio. EUR\",\"comment\": \"new comment 1\"}]}"; HttpHeaders header = new HttpHeaders(); private ProjectEntity project; private ProductEntity product; private ProductEntity productWithoutRatings; private List<RatingEntity> ratingEntities; private List<RatingEntity> econimicRatingEntities; private List<RatingEntity> complexityRatingEntities; private List<ProductRatingEntity> entities; private List<ProductRatingEntity> entitiesComplexity; private List<ProductRatingEntity> entitiesEconomic; /** * This annotated method should be executed before each invocation of @Test */ @BeforeEach public void initEach(){ System.out.println("Initilize ProductRatingControllerTest........."); header = new HttpHeaders(); header.setContentType(MediaType.APPLICATION_JSON); project = new ProjectEntity(); projectRepository.save(project); product = new ProductEntity(); product.project = project; productRepository.save(product); productWithoutRatings = new ProductEntity(); productWithoutRatings.project = project; productRepository.save(productWithoutRatings); ratingEntities = new ArrayList<>(); econimicRatingEntities = new ArrayList<>(); complexityRatingEntities = new ArrayList<>(); entities = new ArrayList<>(); entitiesComplexity = new ArrayList<>(); entitiesEconomic = new ArrayList<>(); for(int i = 1; i < 48; i++){ ProductRatingEntity tmp = new ProductRatingEntity(); tmp.answer = "answer" + i; tmp.score = Score.HOCH; tmp.comment = "comment" + i; Optional<RatingEntity> ratingEntity = ratingRepository.findById(i); if(ratingEntity.isEmpty()){ RatingEntity rating = new RatingEntity(); rating.criterion = "criterion" + i; rating.category = "category"; rating.ratingarea = (i < 9) ? RatingArea.ECONOMIC : RatingArea.COMPLEXITY; ratingEntities.add(rating); tmp.productRatingId = new ProductRatingId(product, rating); if(i < 9){ econimicRatingEntities.add(rating); }else{ complexityRatingEntities.add(rating); } }else{ tmp.productRatingId = new ProductRatingId(product, ratingEntity.get()); } entities.add(tmp); if(i < 9){ entitiesEconomic.add(tmp); }else{ entitiesComplexity.add(tmp); } } ratingRepository.saveAll(ratingEntities); repository.saveAll(entities); } /** * The method should be run after every @Test */ @AfterEach public void reset(){ List<ProductRatingEntity> tmp = repository.findAll(); if(!tmp.isEmpty()){ for(ProductRatingEntity pr: tmp){ repository.deleteById(pr.productRatingId); } } } /** * tests for getProductRatings() * * testGetProductRatings: no product rating exist with/without productID--> return HTTP.NOT_FOUND * testGetProductRatings: no product rating exist with/without product rating--> return HTTP.OK and empty list * testGetProductRatings: ratings exist with/without productID--> return HTTP.OK and json string containing product * ratings */ @Test public void test1_getProductRatings_resourceNotFound_productID(){ // test object String[] urls = {host + port + products + "0" + ratings, host + port + products + "0" + ratings + complexity, host + port + products + "0" + ratings + economic}; for (String tmpUrl : urls) { ResponseEntity<String> response = restTemplate.exchange(tmpUrl, HttpMethod.GET,null, String.class); log.info("@Test 1 - getProductRatings_resourceNotFound - productID not in db"); log.info("@Test 1 - Response Body: " + response.getBody()); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } } @Test public void test2_getProductRatings_success_returnEmptyList(){ // test object String[] urls = {host + port + products + productWithoutRatings.id + ratings, host + port + products + productWithoutRatings.id + ratings + complexity, host + port + products + productWithoutRatings.id + ratings + economic}; for (String tmpUrl : urls) { ResponseEntity<String> response = restTemplate.exchange(tmpUrl, HttpMethod.GET,null, String.class); log.info("@Test 2 - getProductRatings_success - product has no ratings - return empty list"); log.info("@Test 2 - Response Body: " + response.getBody()); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); } } @Test public void test3_getProductRatings_success(){ // test object String[] urls = {host + port + products + product.id + ratings, host + port + products + product.id + ratings + complexity, host + port + products + product.id + ratings + economic}; for (String tmpUrl : urls) { ResponseEntity<String> response = restTemplate.exchange(tmpUrl, HttpMethod.GET,null, String.class); log.info("@Test 2 - getProductRatings_success - product has ratings"); log.info("@Test 2 - Response Body: " + response.getBody()); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); // TODO: check output against db } } /** * tests for updateProductRatings() * * testUpdateProductRatings: no product rating exist with/without productID--> return HTTP.NOT_FOUND * testUpdateProductRatings: no product rating exist with/without ratingID--> return HTTP.NOT_FOUND * testUpdateProductRatings: no product rating exist with/without empty JSON--> return HTTP.BAD_REQUEST * testUpdateProductRatings: product ratings exist with/without ratingID--> return HTTP.OK and json string * containing product ratings * testUpdateProductRatings: product rating exists with/without answer --> return HTTP.OK and json string * containing product ratings * testUpdateProductRatings: product rating exists with/without comment --> return HTTP.OK and json string * containing product ratings * testUpdateProductRatings: product rating exists with/without score --> return HTTP.OK and json string * containing product ratings */ @Test public void test4_updateProductRatings_resourceNotFound_productID(){ ResponseEntity<String> response = restTemplate.exchange(host + port + products + "0" + ratings, HttpMethod.PUT,new HttpEntity<>(jsonStringCorrectOneEntry, header), String.class); log.info("@Test 4 - updateProductRatings_resourceNotFound - productID not in db"); log.info("@Test 4 - Response Body: " + response.getBody()); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } @Test public void test5_updateProductRatings_resourceNotFound_ratingID(){ String[] testobjects = {jsonStringInvalidRatingID, jsonStringCorrectTwoEntriesInvalidRatingID}; for(String jsonString: testobjects){ ResponseEntity<String> response = restTemplate.exchange(host + port + products + product.id + ratings, HttpMethod.PUT,new HttpEntity<>(jsonString, header), String.class); log.info("@Test 5 - updateProductRatings_resourceNotFound - ratingID not in db"); log.info("@Test 5 - Response Body: " + response.getBody()); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND); } } @Test public void test6_updateProductRatings_badRequest_emptyJSON(){ ResponseEntity<String> response = restTemplate.exchange(host + port + products + product.id + ratings, HttpMethod.PUT,new HttpEntity<>(jsonStringEmpty, header), String.class); log.info("@Test 6 - updateProductRatings_badRequest - json string is empty"); log.info("@Test 6 - Response Body: " + response.getBody()); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); } @Test public void test7_updateProductRatings_success_fullUpdate(){ String[] testobjects = {jsonStringCorrectOneEntry, jsonStringCorrectTwoEntries}; for(String jsonString: testobjects){ ResponseEntity<String> response = restTemplate.exchange(host + port + products + product.id + ratings, HttpMethod.PUT,new HttpEntity<>(jsonString, header), String.class); log.info("@Test 7 - updateProductRatings_success - ratingID not in db"); log.info("@Test 7 - Response Body: " + response.getBody()); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); //TODO: check output against original db entry } } @Test public void test8_updateProductRatings_success_partialUpdate_missingAnswer(){ // String[] testobjects = {jsonStringMissingAnswer}; List<RatingEntity> test = ratingRepository.findAll(); List<ProductRatingEntity> tmp = repository.findAll(); // for(String jsonString: testobjects){ ResponseEntity<String> response = restTemplate.exchange(host + port + products + product.id + ratings, HttpMethod.PUT,new HttpEntity<>(jsonStringMissingAnswer, header), String.class); log.info("@Test 8 - updateProductRatings_success - comment and score of one product rating entity updated"); log.info("@Test 8 - Response Body: " + response.getBody()); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); //TODO: check output against original db entry // } } @Test public void test9_updateProductRatings_success_partialUpdate_missingComment(){ String[] testobjects = {jsonStringMissingComment}; for(String jsonString: testobjects){ ResponseEntity<String> response = restTemplate.exchange(host + port + products + product.id + ratings, HttpMethod.PUT,new HttpEntity<>(jsonString, header), String.class); log.info("@Test 9 - updateProductRatings_success - answer and score of one product rating entity updated"); log.info("@Test 9 - Response Body: " + response.getBody()); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); //TODO: check output against original db entry } } @Test public void test10_updateProductRatings_success_partialUpdate_missingScore(){ String[] testobjects = {jsonStringMissingScore}; for(String jsonString: testobjects){ ResponseEntity<String> response = restTemplate.exchange(host + port + products + product.id + ratings, HttpMethod.PUT,new HttpEntity<>(jsonString, header), String.class); log.info("@Test 10 - updateProductRatings_success - answer and comment of one product rating entity updated"); log.info("@Test 10 - Response Body: " + response.getBody()); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); //TODO: check output against original db entry } } /** * The test should indicate that the server knows the request method, but the target resource doesn't support this * method. * * @result The status code indicates that the method was not allowed. */ @Test public void notAllowedMethodsProductRatings() { String[] urls = {host + port + products + product.id + ratings, host + port + products + product.id + ratings + complexity, host + port + products + product.id + ratings + economic}; for (String tmpUrl : urls) { ResponseEntity<String> response = restTemplate.exchange( tmpUrl, HttpMethod.DELETE, null, String.class); log.info("@Test xx - not allowed methods on Product Rating Controller"); log.info("@Test xx - Response Body: " + response.getBody()); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.METHOD_NOT_ALLOWED); } } }
45.078035
184
0.658268
119736e1b6c221ffbbd6c98496fce6c0338a453d
592
package ca.cgjennings.apps.arkham.deck.item; /** * Implemented by cards that can be edited. If the card needs to take control of * the page's interface during editing, it must call {@code setEditingCard} to * set the edited card to this when it begins editing, and call it again with * {@code null} when it is finished. * <p> * Typically, a page will call an editable item's {@link #beginEditing} method * when the item is double-clicked. * * @author Chris Jennings <https://cgjennings.ca/contact> */ public interface EditablePageItem { public abstract void beginEditing(); }
32.888889
80
0.72973
e8930a584bc89f34dd5f54896fad47f5abf701da
2,691
import static org.junit.jupiter.api.Assertions.*; import com.soynomm.lava.ArgParser; import org.junit.jupiter.api.Test; public class ArgParserTests { @Test public void testGetSingleArg() { var args = new String[]{"--arg", "value"}; var argParser = new ArgParser(args); var result = argParser.get("--arg", "default"); assertEquals("value", result); } @Test public void testGetSingleArgNoValue() { var args = new String[]{"--arg"}; var argParser = new ArgParser(args); var result = argParser.get("--arg", "default"); assertEquals("default", result); } @Test public void testGetSingleArgNonePresent() { var args = new String[]{}; var argParser = new ArgParser(args); var result = argParser.get("--arg", "default"); assertEquals("default", result); } @Test public void testGetMultipleArg() { var args = new String[]{"--arg", "value"}; var argParser = new ArgParser(args); var result = argParser.get("--arg", "-a", "default"); assertEquals("value", result); } @Test public void testGetMultipleArgNoValues() { var args = new String[]{"--arg1", "--arg2"}; var argParser = new ArgParser(args); var result = argParser.get("--arg1", "-a", "default"); assertEquals("default", result); } @Test public void testGetMultipleArgBothPresent() { var args = new String[]{"--arg", "value", "-a", "value"}; var argParser = new ArgParser(args); var result = argParser.get("--arg", "-a", "default"); assertEquals("value", result); } @Test public void testGetMultipleArgAlternativePresent() { var args = new String[]{"-a", "value"}; var argParser = new ArgParser(args); var result = argParser.get("--arg", "-a", "default"); assertEquals("value", result); } @Test public void testGetMultipleArgNonePresent() { var args = new String[]{}; var argParser = new ArgParser(args); var result = argParser.get("--arg", "-a", "default"); assertEquals("default", result); } @Test public void testGetMultipleArgBoolean() { var args = new String[]{"--arg"}; var argParser = new ArgParser(args); var result = argParser.get("--arg", "-a", false); assertTrue(result); } @Test public void testGetMultipleArgBooleanNonePresentTrue() { var args = new String[]{}; var argParser = new ArgParser(args); var result = argParser.get("--arg", "-a", true); assertTrue(result); } }
27.459184
65
0.578967
5f9661a38b998258fe8e11bbe55b8a5714a9f78b
4,614
package br.com.rhribeiro25.manageLabs.controller; import br.com.rhribeiro25.manageLabs.error.exception.NotFoundException; import br.com.rhribeiro25.manageLabs.model.ExaminationModel; import br.com.rhribeiro25.manageLabs.model.LaboratoryModel; import br.com.rhribeiro25.manageLabs.service.ExaminationService; import br.com.rhribeiro25.manageLabs.service.LaboratoryService; import io.swagger.annotations.*; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.PatchMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Set; /** * @author Renan Ribeiro * @date 15/07/2020. */ @Api(value = "Associação API") @RestController @RequestMapping("/manage-labs/associations") @Slf4j public class AssociationController { @Autowired private ExaminationService examinationService; @Autowired private LaboratoryService laboratoryService; @ApiOperation(value = "Associar Exame ATIVO a Laboratório ATIVO", notes = "Associa um exame ATIVO a um laboratório ATIVO") @ApiResponses(value = {@ApiResponse(code = 200, message = "OK")}) @PatchMapping("/create/{id-exam}/{id-lab}") @PreAuthorize("hasRole('ADMIN')") @Transactional(rollbackFor = Exception.class) public ResponseEntity<?> associate(@ApiParam(value = "Id do Exame") @PathVariable("id-exam") Long idExam, @ApiParam(value = "Id do Laboratório") @PathVariable("id-lab") Long idLab) { ExaminationModel examUpdate = this.verifyActiveExistsExam(idExam); Set<LaboratoryModel> labsAssociated = examUpdate.getLaboratories(); LaboratoryModel labUpdate = this.verifyActiveExistsLab(idLab); Set<ExaminationModel> examsAssociated = labUpdate.getExaminations(); labsAssociated.add(labUpdate); examUpdate.setLaboratories(labsAssociated); examinationService.update(examUpdate); examsAssociated.add(examUpdate); labUpdate.setExaminations(examsAssociated); laboratoryService.update(labUpdate); return new ResponseEntity<>("Successful to associate examination/laboratory!", HttpStatus.OK); } @ApiOperation(value = "Desassociar Exame ATIVO a Laboratório ATIVO", notes = "Desassocia um exame ATIVO a um laboratório ATIVO") @ApiResponses(value = {@ApiResponse(code = 200, message = "OK")}) @PatchMapping("/delete/{id-exam}/{id-lab}") @PreAuthorize("hasRole('ADMIN')") @Transactional(rollbackFor = Exception.class) public ResponseEntity<?> disassociate(@ApiParam(value = "Id do Exame") @PathVariable("id-exam") Long idExam, @ApiParam(value = "Id do Laboratório") @PathVariable("id-lab") Long idLab) { ExaminationModel examUpdate = this.verifyActiveExistsExam(idExam); Set<LaboratoryModel> labsAssociated = examUpdate.getLaboratories(); LaboratoryModel labUpdate = this.verifyActiveExistsLab(idLab); Set<ExaminationModel> examsAssociated = labUpdate.getExaminations(); labsAssociated.removeIf(lab -> lab.getId() == idLab); examUpdate.setLaboratories(labsAssociated); examinationService.update(examUpdate); examsAssociated.removeIf(exam -> exam.getId() == idExam); labUpdate.setExaminations(examsAssociated); laboratoryService.update(labUpdate); return new ResponseEntity<>("Successful to disassociate examination/laboratory!", HttpStatus.OK); } protected ExaminationModel verifyActiveExistsExam(Long id) { ExaminationModel exam = examinationService.findActiveById(id); if (exam == null) { throw new NotFoundException("Active Examamination not found by ID: " + id); } return exam; } protected LaboratoryModel verifyActiveExistsLab(Long id) { LaboratoryModel lab = laboratoryService.findActiveById(id); if (lab == null) { throw new NotFoundException("Active Laboratory not found by ID: " + id); } return lab; } }
42.722222
132
0.699827
03045e9aed4e74d19af9c91b1db6e145dead242f
1,127
package com.ruoyi.system.domain; import java.util.Date; /** * 运动统计返回信息对象 cqie_run * * @author 王康 * @date 2020-10-21 */ public class CqieTotalRunInfo { private static final long serialVersionUID = 1L; /*开炮时间*/ private Date runStarTime; /*跑步总距离*/ private Double totalDistance; /*跑步总次数*/ private Long totalFrequency; /*跑步总时长*/ private Double totalDuration; public Double getTotalDistance() { return totalDistance; } public void setTotalDistance(Double totalDistance) { this.totalDistance = totalDistance; } public Long getTotalFrequency() { return totalFrequency; } public void setTotalFrequency(Long totalFrequency) { this.totalFrequency = totalFrequency; } public Double getTotalDuration() { return totalDuration; } public void setTotalDuration(Double totalDuration) { this.totalDuration = totalDuration; } public Date getRunStarTime() { return runStarTime; } public void setRunStarTime(Date runStarTime) { this.runStarTime = runStarTime; } }
18.783333
56
0.658385
3cbbe9d71d583ee517a58f1e455dd5e4e7c19210
371
package uk.co.blackpepper.bowman; import com.fasterxml.jackson.databind.ObjectMapper; /** * Interface supporting the configuration of the Jackson {@link com.fasterxml.jackson.databind.ObjectMapper} which is * used internally by the {@link Client}. * * @author Karl Spies */ public interface ObjectMapperConfigurer { void configure(ObjectMapper objectMapper); }
24.733333
117
0.77628
f712168514bb89c9f7acbd583458a9f106afe130
470
package cn.lxtkj.gulimall.coupon.service; import com.baomidou.mybatisplus.extension.service.IService; import cn.lxtkj.common.utils.PageUtils; import cn.lxtkj.gulimall.coupon.entity.SeckillPromotionEntity; import java.util.Map; /** * 秒杀活动 * * @author leixiaotian * @email 1124378213@qq.com * @date 2021-08-12 22:32:32 */ public interface SeckillPromotionService extends IService<SeckillPromotionEntity> { PageUtils queryPage(Map<String, Object> params); }
22.380952
83
0.776596
f98ef278e86f90ef6f5752065a7e6ba517de6fbf
3,415
package JavaCode.top_interview_questions_easy.array; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class ten { class Solution { /** * 坐标数据封装类 */ class Point { public Point(int x,int y) { this.x=x; this.y=y; } int x,y; } private Map<Integer, List<Point>> map;//储存每个数字的坐标,key为数字,value为坐标集合 public boolean isValidSudoku(char[][] board) { //存储坐标 map=new HashMap<>(); for(int i=0;i<board.length;i++) { for(int j=0;j<board[i].length;j++) { if(board[i][j]>='0'&&board[i][j]<='9') { int x=board[i][j]-'0'; if(map.containsKey(x)) { map.get(x).add(new Point(i,j)); } else { List<Point> list=new ArrayList<>(); list.add(new Point(i,j)); map.put(x,list); } } } } //遍历判断 for(int key:map.keySet()) { List<Point> list=map.get(key); for(int i=0;i<list.size()-1;i++) { Point a=list.get(i); for(int j=i+1;j<list.size();j++) { Point b=list.get(j); if(!judge(a,b)) { return false; } } } } return true; } /** * 判断两个坐标是否符合规则 * @param a * @param b * @return */ boolean judge(Point a,Point b) { if(a.x==b.x||a.y==b.y) { return false; } if(a.x/3==b.x/3&&a.y/3==b.y/3) { return false; } return true; } } } /** * https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/1/array/30/ * 判断一个 9x9 的数独是否有效。只需要根据以下规则,验证已经填入的数字是否有效即可。 * 数字 1-9 在每一行只能出现一次。 * 数字 1-9 在每一列只能出现一次。 * 数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。 * * 上图是一个部分填充的有效的数独。 * 数独部分空格内已填入了数字,空白格用 '.' 表示。 * 示例 1: * 输入: * [ * ["5","3",".",".","7",".",".",".","."], * ["6",".",".","1","9","5",".",".","."], * [".","9","8",".",".",".",".","6","."], * ["8",".",".",".","6",".",".",".","3"], * ["4",".",".","8",".","3",".",".","1"], * ["7",".",".",".","2",".",".",".","6"], * [".","6",".",".",".",".","2","8","."], * [".",".",".","4","1","9",".",".","5"], * [".",".",".",".","8",".",".","7","9"] * ] * 输出: true * 示例 2: * 输入: * [ * ["8","3",".",".","7",".",".",".","."], * ["6",".",".","1","9","5",".",".","."], * [".","9","8",".",".",".",".","6","."], * ["8",".",".",".","6",".",".",".","3"], * ["4",".",".","8",".","3",".",".","1"], * ["7",".",".",".","2",".",".",".","6"], * [".","6",".",".",".",".","2","8","."], * [".",".",".","4","1","9",".",".","5"], * [".",".",".",".","8",".",".","7","9"] * ] */
26.068702
90
0.293704
24c3d366a2af40ce668da5f10630538a72f8464b
1,902
package io.kestra.plugin.templates; import io.swagger.v3.oas.annotations.media.Schema; import lombok.*; import lombok.experimental.SuperBuilder; import org.apache.commons.lang3.StringUtils; import io.kestra.core.models.annotations.PluginProperty; import io.kestra.core.models.tasks.RunnableTask; import io.kestra.core.models.tasks.Task; import io.kestra.core.runners.RunContext; import org.slf4j.Logger; @SuperBuilder @ToString @EqualsAndHashCode @Getter @NoArgsConstructor @Schema( title = "Short description for this task", description = "Full description of this task" ) public class Example extends Task implements RunnableTask<Example.Output> { @Schema( title = "Short description for this input", description = "Full description of this input" ) @PluginProperty(dynamic = true) // If the variables will be rendered with template {{ }} private String format; @Override public Example.Output run(RunContext runContext) throws Exception { Logger logger = runContext.logger(); String render = runContext.render(format); logger.debug(render); return Output.builder() .child(new OutputChild(StringUtils.reverse(render))) .build(); } /** * Input or Output can nested as you need */ @Builder @Getter public static class Output implements io.kestra.core.models.tasks.Output { @Schema( title = "Short description for this output", description = "Full description of this output" ) private final OutputChild child; } @Builder @Getter public static class OutputChild implements io.kestra.core.models.tasks.Output { @Schema( title = "Short description for this output", description = "Full description of this output" ) private final String value; } }
29.261538
92
0.68244
f19fa05290823b0ae97ffb1d3b0a7f63afe47b0c
792
package solutions; /** * Solution for https://leetcode.com/problems/house-robber/ problem with * Time complexity: O(n) * Space complexity: O(1) */ public class HouseRobber { public int rob(int[] nums) { // f(1) = nums[0] // f(2) = max(nums[0], nums[1]) // f(3) = max(nums[2] + nums[0], nums[1]) = max(nums[2] + f(1), f(2)) // f(4) = max(nums[3] + f(2), f(3)) // f(n) = max(nums[n-1] + f(n-2), f(n-1)) if (nums == null || nums.length == 0) { return 0; } int prev_prev = 0; int prev = nums[0]; for (int i = 1; i < nums.length; i++) { int curr = Math.max(nums[i] + prev_prev, prev); prev_prev = prev; prev = curr; } return prev; } }
24
77
0.464646
36df7faace15016998970bf12be3ac56d0ff8ff3
3,852
// Copyright � 2006-2007 ASERT. Released under the Canoo Webtest license. package com.canoo.webtest.plugins.exceltest; import com.canoo.webtest.engine.MimeMap; import com.canoo.webtest.engine.StepExecutionException; import com.canoo.webtest.steps.Step; import com.gargoylesoftware.htmlunit.Page; import org.apache.commons.io.IOUtils; import org.apache.log4j.Logger; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.InputStream; import java.util.Map; import java.util.WeakHashMap; /** * Base class for Excel steps. * * @author Rob Nielsen * @author Paul King */ public abstract class AbstractExcelStep extends Step { private static final Logger LOG = Logger.getLogger(AbstractExcelStep.class); private static final Map sMapWorkbooks = new WeakHashMap(); // needed until we plug a "ExcelPage" in htmlunit protected static final String KEY_CURRENT_SHEET = AbstractExcelStep.class.getName() + "#CurrentSheet"; protected AbstractExcelStep() { } /** * @throws StepExecutionException * if pdf analyzer cannot be initialized correctly */ protected Workbook getExcelWorkbook() { final Page currentPage = getContext().getCurrentResponse(); Workbook workbook = (Workbook) sMapWorkbooks.get(currentPage); if (workbook == null) { workbook = createWorkbook(currentPage); sMapWorkbooks.put(currentPage, workbook); // weak map, analyser garbage collected together with the page } return workbook; } /** * Creates an Workbook for the page. This method should not be used directly, * use {@link #getExcelWorkbook()} instead. * @param currentPage the page containing the Excel document * @return the analyzer */ private Workbook createWorkbook(final Page currentPage) { InputStream is = null; try { getContext().put(KEY_CURRENT_SHEET, null); try { is = currentPage.getWebResponse().getContentAsStream(); final POIFSFileSystem excelFile = new RetryWithCapsPOIFSFileSystem(is); return new HSSFWorkbook(excelFile); } catch (Exception e) { is = currentPage.getWebResponse().getContentAsStream(); return new XSSFWorkbook(is); } } catch (final Exception e) { final String message = "Could not open Excel file."; LOG.debug(message, e); throw new StepExecutionException(message, this, e); } finally { IOUtils.closeQuietly(is); } } protected void verifyParameters() { super.verifyParameters(); nullResponseCheck(); final Page currentResponse = getContext().getCurrentResponse(); String contentType = currentResponse.getWebResponse().getContentType(); if (!MimeMap.EXCEL_MIME_TYPE.equals(contentType) && !MimeMap.EXCELX_MIME_TYPE.equals(contentType)) { throw new StepExecutionException("File does not have correct content type (not a '.xls' file?): " + currentResponse.getWebResponse().getContentType(), this); } } protected boolean verifyStrings(final String expectedValue, final String actualValue) { boolean regex=false; String newExpectedValue = expectedValue; if (expectedValue != null && expectedValue.length() >= 2 && expectedValue.charAt(0)=='/' && expectedValue.charAt(expectedValue.length() - 1)=='/') { regex = true; newExpectedValue = expectedValue.substring(1, expectedValue.length() - 1); } return getVerifier(regex).verifyStrings(newExpectedValue, actualValue); } }
38.52
156
0.676532
b5e613c6b6298bf7f5fc9df3de526db0bbd25e22
1,902
package peapod.internal.classes; import java.lang.Class; import java.lang.Object; import java.lang.String; import java.lang.SuppressWarnings; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Element; import peapod.FramedEdge; import peapod.FramedElement; import peapod.FramedGraph; import peapod.internal.runtime.Framer; import peapod.internal.runtime.IFramer; @SuppressWarnings("unused") public final class Knows$Impl extends Knows implements FramedEdge { private FramedGraph graph; private Edge e; public Knows$Impl(Edge e, FramedGraph graph) { this.e = e; this.graph = graph; } public FramedGraph graph() { return graph; } public Element element() { return e; } public Person getPerson() { // edge-getter-vertex return graph().frame(e.outVertex(), Person.class); } public Person getOtherPerson() { // edge-getter-vertex return graph().frame(e.inVertex(), Person.class); } public int hashCode() { return e.hashCode(); } public boolean equals(Object other) { return (other instanceof FramedElement) && e.equals(((FramedElement) other).element()); } public String toString() { return e.label() + "[" + e.id() + "]"; } @Framer public static final class KnowsFramer implements IFramer<Edge, Knows> { public Class<Edge> type() { return Edge.class; } public Class<Knows> frameClass() { return Knows.class; } public String label() { return "knows"; } public Knows frame(Edge e, FramedGraph graph) { return new Knows$Impl(e, graph); } public Knows frameNew(Edge e, FramedGraph graph) { return frame(e, graph); } } }
25.36
95
0.618822
fb0c4fd8aed869e00e691eabef4bacb2be6c17ca
1,304
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package br.com.palestrapizzaria.entidade; /** * * @author alvaro */ public class Item { private String item; private Integer quantidade; private Double valor; private Integer id; public Item() { } public Item(String item, Integer quantidade, Double valor) { this.item = item; this.quantidade = quantidade; this.valor = valor; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Double subTotal() { return valor*quantidade; } public String getItem() { return item; } public void setItem(String item) { this.item = item; } public Integer getQuantidade() { return quantidade; } public void setQuantidade(Integer quantidade) { this.quantidade = quantidade; } public Double getValor() { return valor; } public void setValor(Double valor) { this.valor = valor; } public Double getTotal() { return this.valor*this.quantidade; } }
18.628571
79
0.597393
4b4f4d5a14a89403a81203d491584c8f315b4c13
2,897
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|jackrabbit operator|. name|oak operator|. name|spi operator|. name|security operator|. name|authentication operator|. name|external package|; end_package begin_import import|import name|org operator|. name|jetbrains operator|. name|annotations operator|. name|NotNull import|; end_import begin_import import|import name|org operator|. name|jetbrains operator|. name|annotations operator|. name|Nullable import|; end_import begin_comment comment|/** * Defines the result of a sync operation */ end_comment begin_interface specifier|public interface|interface name|SyncResult block|{ comment|/** * The synchronized identity * @return the identity */ annotation|@ name|Nullable name|SyncedIdentity name|getIdentity parameter_list|() function_decl|; comment|/** * The status of the sync operation * @return the status */ annotation|@ name|NotNull name|Status name|getStatus parameter_list|() function_decl|; comment|/** * Result codes for sync operation. */ enum|enum name|Status block|{ comment|/** * No update */ name|NOP block|, comment|/** * authorizable added */ name|ADD block|, comment|/** * authorizable updated */ name|UPDATE block|, comment|/** * authorizable deleted */ name|DELETE block|, comment|/** * authorizable enabled */ name|ENABLE block|, comment|/** * authorizable disabled */ name|DISABLE block|, comment|/** * nothing changed. no such authorizable found. */ name|NO_SUCH_AUTHORIZABLE block|, comment|/** * nothing changed. no such identity found. */ name|NO_SUCH_IDENTITY block|, comment|/** * nothing changed. corresponding identity missing */ name|MISSING block|, comment|/** * nothing changed. idp name not correct */ name|FOREIGN block|} block|} end_interface end_unit
25.866071
810
0.705557
5b002a6bf2fc858a0f8c2bcdab75fe0fd504e5e3
6,128
package org.wisekg.main; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.*; import java.util.concurrent.*; import org.wisekg.model.StarPattern; import org.wisekg.util.Config; import org.wisekg.util.FamiliesConfig; import org.apache.commons.io.FileUtils; import org.apache.jena.graph.Node; import org.eclipse.rdf4j.query.algebra.Projection; import org.eclipse.rdf4j.query.algebra.ProjectionElem; import org.eclipse.rdf4j.query.algebra.StatementPattern; import org.eclipse.rdf4j.query.algebra.TupleExpr; import org.eclipse.rdf4j.query.algebra.helpers.StatementPatternCollector; import org.eclipse.rdf4j.query.parser.ParsedQuery; import org.eclipse.rdf4j.query.parser.QueryParser; import org.eclipse.rdf4j.query.parser.sparql.SPARQLParserFactory; import org.wisekg.model.TriplePattern; public class Experiment { private static List<ProjectionElem> projectionElemList; private static ArrayList<TriplePattern> triplePatterns; private static ArrayList<StarPattern> starPatterns; private static String queryStr; private static HashMap<Node, List> familiesHashedByPredicate; public static int CLIENT_NUM = 0; public static String QUERY = ""; private static Map<String, String> map = new HashMap<>(); public static ArrayList<Integer> cardinalities = new ArrayList<>(); public static void main(String[] args) throws IllegalArgumentException, IOException, InterruptedException, ExecutionException { if (!(args.length == 7)) { System.out.println("Usage: java -jar [filename].jar [query directory] [method] [output dir] [number of clients] [client no.] [dataset] [load]"); return; } String configf = args[0]; String queryDir = args[1]; String method = args[2]; String outDir = args[3]; int num_clients = Integer.parseInt(args[4]); int client_num = Integer.parseInt(args[5]); String dataset = args[6]; int executing = 0; //String validDir = args[7]; CLIENT_NUM = client_num; Config config = new Config(configf); familiesHashedByPredicate = FamiliesConfig.getInstance().getFamiliesByPredicate(); String oDir = outDir + "/" + dataset + "/" + num_clients + "_clients/" + method; new File(oDir).mkdirs(); String filename = oDir + "/client" + client_num + ".csv"; FileWriter writer = new FileWriter(filename); File[] dirs = new File(queryDir).listFiles(); for (File qf : dirs) { System.out.println(qf.getName()); QUERY = qf.getName(); initializeQueryAndConfig(qf.getPath()); QueryInput input = new QueryInput(); input.setStartFragment(Config.getInstance().getServer()); SparqlQueryProcessor sqp = new SparqlQueryProcessor(triplePatterns, input, false, false); final Duration timeout = Duration.ofMinutes(5); ExecutorService executor = Executors.newSingleThreadExecutor(); final Future handler = executor.submit(new Callable() { @Override public String call() throws Exception { sqp.processQuery(); return ""; } }); try { executing++; handler.get(timeout.toMillis(), TimeUnit.MILLISECONDS); String str = qf.getName() + ";" + SparqlQueryProcessor.SERVER_REQUESTS.get() + ";" + sqp.getQueryProcessingTime() + ";" + SparqlQueryProcessor.TRANSFERRED_BYTES.get() + ";" + SparqlQueryProcessor.RESPONSE_TIME + ";" + SparqlQueryProcessor.NUMBER_OF_OUTPUT_BINDINGS; System.out.println(str); writer.write(str + "\n"); } catch (TimeoutException | InterruptedException e) { handler.cancel(true); sqp.terminate(); String str = qf.getName() + ";-1;-1;-1;-1;-1"; System.out.println(str); writer.write(str + "\n"); } finally { executing--; executor.shutdownNow(); sqp.close(); } } writer.close(); if(executing == 0) System.exit(0); } private static void initializeQueryAndConfig(String queryFile) throws IOException, IllegalArgumentException { triplePatterns = new ArrayList<TriplePattern>(); String queryString = FileUtils.readFileToString(new File(queryFile), StandardCharsets.UTF_8); queryStr = queryString; SPARQLParserFactory factory = new SPARQLParserFactory(); QueryParser parser = factory.getParser(); ParsedQuery parsedQuery = parser.parseQuery(queryString, null); TupleExpr query = parsedQuery.getTupleExpr(); if (query instanceof Projection) { Projection proj = (Projection) query; projectionElemList = proj.getProjectionElemList().getElements(); } else { throw new IllegalArgumentException("The given query should be a select query."); } List<StatementPattern> statementPatterns = StatementPatternCollector.process(query); Map<String, List<StatementPattern>> patterns = new HashMap<>(); for (StatementPattern statementPattern : statementPatterns) { TriplePattern tp = new TriplePattern(statementPattern); triplePatterns.add(tp); String subj = tp.getSubjectVarName(); if(patterns.containsKey(subj)) { patterns.get(subj).add(statementPattern); } else { List<StatementPattern> lst = new ArrayList<>(); lst.add(statementPattern); patterns.put(subj, lst); } } starPatterns = new ArrayList<>(); Collection<List<StatementPattern>> lst = patterns.values(); for(List<StatementPattern> stps : lst) { starPatterns.add(new StarPattern(stps)); } } }
39.792208
281
0.635607
b6d7700c8d7fec78361146741262cb290da8621c
1,898
package tk.bookyclient.bookyclient; // Created by booky10 in bookyClient (19:14 29.12.20) import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import tk.bookyclient.bookyclient.accounts.encryption.Standards; import tk.bookyclient.bookyclient.accounts.skins.SkinUtils; import tk.bookyclient.bookyclient.accounts.utils.AccountConfig; import tk.bookyclient.bookyclient.settings.ClientSettings; import tk.bookyclient.bookyclient.utils.Constants; import java.util.Timer; import java.util.TimerTask; @Mod(modid = Constants.MOD_ID, name = Constants.MOD_NAME, version = Constants.VERSION, acceptedMinecraftVersions = "[1.8.9]") public class ClientMod { @Mod.EventHandler public void onPreInit(FMLPreInitializationEvent event) { Constants.LOGGER.info("Pre-Loading " + Constants.MOD_NAME + "..."); ClientSettings.loadSettings(); } @Mod.EventHandler public void onInit(FMLInitializationEvent event) { Constants.LOGGER.info("Loading " + Constants.MOD_NAME + "..."); AccountConfig.readFromFile(); Standards.importAccounts(); } @Mod.EventHandler public void onPostInit(FMLPostInitializationEvent event) { Constants.LOGGER.info("Post-Loading " + Constants.MOD_NAME + "..."); SkinUtils.cacheSkins(); Runtime.getRuntime().addShutdownHook(new Thread(() -> ClientSettings.saveSettings(false), Constants.MOD_NAME + " Config Saver Thread")); Constants.LOGGER.info("Starting auto config saver timer"); new Timer().schedule(new TimerTask() { @Override public void run() { ClientSettings.saveSettings(true); } }, 1000 * 5, 1000 * 10); } }
37.215686
144
0.720232
69472c6e904b21978d0e163451a4a4cc3d97f91f
376
package fr.lacazethomas.movieApplication; import lombok.*; import java.time.LocalDate; import java.util.List; @Getter @Setter @ToString @AllArgsConstructor @NoArgsConstructor @Builder public class Movie { private Long id; private int rank; private double rating; private String title; private LocalDate releaseDate; private List<Long> actorsID; }
15.666667
41
0.75
24aad730780dbe1c3c0ed60f08187b2561f1633f
12,351
// RobotBuilder Version: 2.0 // // This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. // //test package org.firebears; import org.firebears.commands.ActivateCompressor; import org.firebears.commands.BackIntoWallCommand; import org.firebears.commands.CelebrateCommand; import org.firebears.commands.DriveToDistanceStraightCommand; import org.firebears.commands.I2CCommand; import org.firebears.commands.NonPIDRotateCommand; //import org.firebears.commands.NonPIDAngle; import org.firebears.commands.PlayMirroredRecording; import org.firebears.commands.PlayRecordingCommand; import org.firebears.commands.ResetNavX; import org.firebears.commands.RotateToAngleCommandFast; import org.firebears.commands.RelativeAngleCommand; import org.firebears.commands.StartRecordingCommand; import org.firebears.commands.StopRecordingCommand; import org.firebears.commands.TestMotors; import org.firebears.commands.TurnToAngleDeceleration; import org.firebears.commands.VisionForwardCommand; import org.firebears.commands.VisionGetCubeCommandGroup; import org.firebears.commands.VisionRotateCommandFast; import org.firebears.commands.auto.ChangePriority; import org.firebears.commands.auto.ChangeShouldCross; import org.firebears.commands.auto.ChangeSide; import org.firebears.commands.auto.DriveToDistanceCommand; import org.firebears.commands.auto.DriveToTapeCommand; import org.firebears.commands.auto.TestCommandGroup; import org.firebears.commands.auto.TestCrossFieldCommandGroup; import org.firebears.commands.driver.GrabberDownCommand; import org.firebears.commands.driver.GrabberUpCommand; import org.firebears.commands.driver.DanceCommand; import org.firebears.commands.driver.DriverCloseCommand; import org.firebears.commands.driver.FireCubeCommand; import org.firebears.commands.grabber.OpenGrabberCommand; import org.firebears.commands.grabber.RaiseGrabberCommand; import org.firebears.commands.grabber.ReverseGrabberWheelsCommand; import org.firebears.commands.grabber.SpinGrabberWheelsCommand; import org.firebears.commands.shooter.ExtendShooterCommand; import org.firebears.commands.shooter.SpinShooterWheelsCommand; import org.firebears.commands.shooter.TestShooterSpeedCommand; import org.firebears.commands.testing.TestRobotCommand; import org.firebears.util.RobotReport; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.buttons.JoystickButton; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /** * This class is the glue that binds the controls on the physical operator * interface to the commands and command groups that allow control of the robot. */ public class OI { public Joystick joystick1; public Joystick joystick2; public JoystickButton testPID; public JoystickButton Driveinches; public JoystickButton extendShooter; public JoystickButton highShot; public JoystickButton medShot; public JoystickButton lowShot; public JoystickButton switchShot; public JoystickButton armDown; public JoystickButton armUp; public JoystickButton armClose; public JoystickButton armOpen; public JoystickButton armOpenClose; public JoystickButton celebrateButton; public JoystickButton celebrateButton2; public JoystickButton spinGrabberWheels; public JoystickButton reverseGrabberWheels; public JoystickButton stopGrabberWheels; public JoystickButton dance; public JoystickButton testMotors; public JoystickButton testMotors2; String testRecording = "recordings/MiddleSideRightSwitch.csv"; public OI(RobotReport report) { // Intialize the joysticks joystick1 = new Joystick(0); report.addJoystick(0, "Joystick 1", joystick1); joystick2 = new Joystick(1); // Driveinches = new JoystickButton(joystick1,1); // Driveinches.whileHeld(new DriveToDistanceCommand(18.8)); report.addJoystick(1, "Joystick 2", joystick2); // Joystick Buttons testMotors = new JoystickButton(joystick1, 7); TestMotors testMotorsStraightForward = new TestMotors(true, true); testMotors.whileHeld(testMotorsStraightForward); report.addJoystickButton(0, 7, "Test Motors Forward", testMotorsStraightForward); testMotors = new JoystickButton(joystick1, 9); TestMotors testMotorsStraightBackwards = new TestMotors(true, false); testMotors.whileHeld(testMotorsStraightBackwards); report.addJoystickButton(0, 9, "Test Motors Backward", testMotorsStraightBackwards); extendShooter = new JoystickButton(joystick2, 1); Command fireCubeCommand = new FireCubeCommand(); extendShooter.whenPressed(fireCubeCommand); report.addJoystickButton(1, 1, "Shoot", fireCubeCommand); // highShot = new JoystickButton(joystick2, 6); // highShot.whenPressed(new SpinShooterWheelsCommand(.9)); // // medShot = new JoystickButton(joystick2, 5); // medShot.whenPressed(new SpinShooterWheelsCommand(.6)); // // lowShot = new JoystickButton(joystick2, 4); // lowShot.whenPressed(new SpinShooterWheelsCommand(.4)); // // switchShot = new JoystickButton(joystick2, 3); // switchShot.whenPressed(new SpinShooterWheelsCommand(.25)); armDown = new JoystickButton(joystick2, 7); Command grabberDownCommand = new GrabberDownCommand(); armDown.whenPressed(grabberDownCommand); report.addJoystickButton(1, 7, "Arm Down", grabberDownCommand); armUp = new JoystickButton(joystick2, 9); Command grabberUpCommand = new GrabberUpCommand(); armUp.whenPressed(grabberUpCommand); report.addJoystickButton(1, 9, "Arm Up", grabberUpCommand); // armClose = new JoystickButton(joystick2, 8); Command armCloseCommand = new DriverCloseCommand(); // armClose.whenPressed(armCloseCommand); // report.addJoystickButton(1, 8, "Arm Close", armCloseCommand); // armOpen = new JoystickButton(joystick2, 10); Command armOpenCommand = new OpenGrabberCommand(true); // armOpen.whenPressed(armOpenCommand); // report.addJoystickButton(1, 10, "Arm Open", armOpenCommand); armOpenClose = new JoystickButton(joystick2, 14); Command armClosedCommand = new OpenGrabberCommand(false); armOpenClose.whenPressed(armOpenCommand); armOpenClose.whenReleased(armClosedCommand); report.addJoystickButton(1, 14, "Toggle arms open/closed", armClosedCommand); spinGrabberWheels = new JoystickButton(joystick2, 11); Command spinnerWheelsStartCommand = new SpinGrabberWheelsCommand(true); spinGrabberWheels.whenPressed(spinnerWheelsStartCommand); Command spinnerWheelsStopCommand = new SpinGrabberWheelsCommand(false); spinGrabberWheels.whenReleased(spinnerWheelsStopCommand); report.addJoystickButton(1, 11, "Spinner wheels", spinnerWheelsStartCommand); reverseGrabberWheels = new JoystickButton(joystick2, 12); Command grabberWheelsStartCommand = new ReverseGrabberWheelsCommand(true); reverseGrabberWheels.whenPressed(grabberWheelsStartCommand); Command grabberWheelsStopCommand = new ReverseGrabberWheelsCommand(false); reverseGrabberWheels.whenReleased(grabberWheelsStopCommand); report.addJoystickButton(1, 12, "Grabber wheels", spinnerWheelsStartCommand); celebrateButton = new JoystickButton(joystick2, 13); Command celebrateCommand = new CelebrateCommand(); celebrateButton.whenPressed(celebrateCommand); report.addJoystickButton(1, 13, "Celebrate", celebrateCommand); // dance = new JoystickButton(joystick1, 1); // dance.whileHeld(new DanceCommand()); // Switch between Open and Closed Loop Driving // testPID = new JoystickButton(joystick1, 1); // Command switchDriving = new SwitchDrivingType(); // testPID.whenPressed(new SwitchDrivingType()); // report.addJoystickButton(0, 1, "Swtich Driving Type", switchDriving); // celebrateButton2 = new JoystickButton(joystick1, 2); // celebrateButton2.whileHeld(celebrateCommand); report.addJoystickButton(1, 2, "Right-side", "Autonomous"); report.addJoystickButton(1, 3, "Left-side", "Autonomous"); report.addJoystickButton(1, 8, "Split", "Autonomous"); report.addJoystickButton(1, 15, "Switch/Scale", "Autonomous"); report.addJoystickButton(1, 16, "Cross/Dont-cross", "Autonomous"); // SmartDashboard Buttons // Recording Commands if (RobotMap.DEBUG) { SmartDashboard.putData("Start Recording", new StartRecordingCommand()); SmartDashboard.putData("Stop Recording", new StopRecordingCommand()); SmartDashboard.putData("Play Recording", new PlayRecordingCommand()); SmartDashboard.putData("Play Recording Mirrored", new PlayMirroredRecording()); SmartDashboard.putData("Test Recording", new PlayRecordingCommand(testRecording)); SmartDashboard.putData("Mirror Test Recording", new PlayMirroredRecording(testRecording)); // Vision Commands SmartDashboard.putData("Vision Turn", new VisionRotateCommandFast()); SmartDashboard.putData("Drive to Cube", new VisionForwardCommand(.5)); SmartDashboard.putData("Vision Get Cube", new VisionGetCubeCommandGroup()); // Other Commands SmartDashboard.putData("DriveToTapeCommand", new DriveToTapeCommand(.4)); SmartDashboard.putData("RotateToAngle", new RelativeAngleCommand(90)); SmartDashboard.putData("Rotate to Specific Angle", new RotateToAngleCommandFast(90)); SmartDashboard.putNumber("Target Angle", 90); SmartDashboard.putNumber("Max Speed", .7); SmartDashboard.putNumber("Decel Degree", 80); SmartDashboard.putNumber("Min Speed", .1); SmartDashboard.putNumber("Target Speed", .5); SmartDashboard.putData("Drive into Wall", new BackIntoWallCommand(12)); SmartDashboard.putData("DriveStraight", new DriveToDistanceStraightCommand(200, .5)); SmartDashboard.putData("Test Command Group", new TestCommandGroup()); // SmartDashboard.putData("Nullzone Command",new DriveIntoNullZoneCommand()); SmartDashboard.putData("Decel Turn to Angle", new TurnToAngleDeceleration(90, .5, 80)); SmartDashboard.putData("Extend Shooter", new ExtendShooterCommand(true)); SmartDashboard.putData("Retract Shooter", new ExtendShooterCommand(false)); SmartDashboard.putData("Spin Shooter Wheels Fast", new SpinShooterWheelsCommand(Robot.shooter.HIGH_SPEED)); SmartDashboard.putData("Spin Shooter Wheels Slow", new SpinShooterWheelsCommand(Robot.shooter.LOW_SPEED)); SmartDashboard.putData("Stop Shooter Wheels", new SpinShooterWheelsCommand(0)); SmartDashboard.putData("Test Shooter Speed", new TestShooterSpeedCommand()); SmartDashboard.putNumber("Set Shooter Test Speed", 0); SmartDashboard.putData("Open Grabber", new OpenGrabberCommand(true)); SmartDashboard.putData("Close Grabber", new OpenGrabberCommand(false)); SmartDashboard.putData("Raise Grabber", new RaiseGrabberCommand(true)); SmartDashboard.putData("Lower Grabber", new RaiseGrabberCommand(false)); SmartDashboard.putData("Spin Grabber Wheels", spinnerWheelsStartCommand); SmartDashboard.putData("Stop Grabber Wheels", spinnerWheelsStopCommand); SmartDashboard.putData("Turn on Compressor", new ActivateCompressor(true)); SmartDashboard.putData("Turn off Compressor", new ActivateCompressor(false)); SmartDashboard.putData("Reset NavX", new ResetNavX()); // SmartDashboard.putData("NOTPIDROTATECOMMAND", new NonPIDRotateCommand(-90)); // Auto commands SmartDashboard.putData("Left side", new ChangeSide("Left")); SmartDashboard.putData("Middle", new ChangeSide("Middle")); SmartDashboard.putData("Right side", new ChangeSide("Right")); SmartDashboard.putData("Scale priority", new ChangePriority("Scale")); SmartDashboard.putData("Switch priority", new ChangePriority("Switch")); SmartDashboard.putData("Should cross", new ChangeShouldCross(true)); SmartDashboard.putData("Shouldn't cross", new ChangeShouldCross(false)); SmartDashboard.putData("setAnimation", new I2CCommand(1, 3)); SmartDashboard.putData("TEST", new TestRobotCommand()); SmartDashboard.putData("Celebrate", new CelebrateCommand()); } } public Joystick getJoystick1() { return joystick1; } }
46.432331
111
0.788762
6f7279860c2ba5afbc6be31f1616eeab82b3597c
1,384
package com.example.hbaseMiniCluserDemo; import static org.junit.Assert.*; import java.io.IOException; import static org.mockito.BDDMockito.given; import org.apache.hadoop.hbase.HBaseTestingUtility; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.Table; import org.apache.hadoop.hbase.util.Bytes; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest() public class MyHBaseDAOIT { @MockBean private Connection connection; @Autowired private MyHBaseDAO dao; private static HBaseTestingUtility utility; @Before public void setup() throws Exception { utility = new HBaseTestingUtility(); utility.startMiniCluster(); } @Test public void test() throws IOException { Table table = utility.createTable(Bytes.toBytes("table"), Bytes.toBytes("family")); given(connection.getTable(TableName.valueOf("table"))).willReturn(table); dao.push("example"); // TODO check that the push was successful assertTrue(true); } }
25.163636
87
0.768064
774e005336cc975aee6db123a66e487f7533c34f
5,100
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package skyproc; import java.io.IOException; import java.util.ArrayList; import java.util.zip.DataFormatException; import lev.LImport; import lev.LOutFile; import skyproc.AltTextures.AltTexture; import skyproc.exceptions.BadParameter; import skyproc.exceptions.BadRecord; /** * * @author Justin Swanson */ public class MISC extends MajorRecordNamed { // Static prototypes and definitions static final SubPrototype MISCproto = new SubPrototype(MajorRecordNamed.namedProto) { @Override protected void addRecords() { after(new ScriptPackage(), "EDID"); add(new SubData("OBND", new byte[12])); reposition("FULL"); add(new Model()); add(SubString.getNew("ICON", true)); add(new SubForm("YNAM")); add(new SubForm("ZNAM")); add(new KeywordSet()); add(new DATA()); add(SubString.getNew("MICO", true)); add(new DestructionData()); } }; static class DATA extends SubRecord { int value = 0; float weight = 0; DATA() { super(); } @Override void export(ModExporter out) throws IOException { super.export(out); out.write(value); out.write(weight); } @Override void parseData(LImport in, Mod srcMod) throws BadRecord, DataFormatException, BadParameter { super.parseData(in, srcMod); value = in.extractInt(4); weight = in.extractFloat(); if (SPGlobal.logMods){ logMod(srcMod, "", "Setting DATA: Weight: " + weight); } } @Override SubRecord getNew(String type) { return new MISC.DATA(); } @Override int getContentLength(ModExporter out) { return 8; } @Override ArrayList<String> getTypes() { return Record.getTypeList("DATA"); } } // Common Functions MISC() { super(); subRecords.setPrototype(MISCproto); } @Override ArrayList<String> getTypes() { return Record.getTypeList("MISC"); } @Override Record getNew() { return new MISC(); } /** * @deprecated use getModelData() * @param path */ public void setModel(String path) { subRecords.getModel().setFileName(path); } /** * @deprecated use getModelData() * @return */ public String getModel() { return subRecords.getModel().getFileName(); } DATA getDATA() { return (DATA) subRecords.get("DATA"); } /** * * @param value */ public void setValue(int value) { getDATA().value = value; } /** * * @return */ public int getValue() { return getDATA().value; } /** * * @param weight */ public void setWeight(float weight) { getDATA().weight = weight; } /** * * @return */ public float getWeight() { return getDATA().weight; } /** * * @return */ public KeywordSet getKeywordSet() { return subRecords.getKeywords(); } /** * * @return */ public ScriptPackage getScriptPackage() { return subRecords.getScripts(); } /** * @deprecated use getModelData() * @return List of the AltTextures applied. */ public ArrayList<AltTextures.AltTexture> getAltTextures() { return subRecords.getModel().getAltTextures(); } /** * * @return */ public Model getModelData() { return subRecords.getModel(); } /** * * @param sound */ public void setPickupSound(FormID sound) { subRecords.setSubForm("YNAM", sound); } /** * * @return */ public FormID getPickupSound() { return subRecords.getSubForm("YNAM").getForm(); } /** * * @param sound */ public void setDropSound(FormID sound) { subRecords.setSubForm("ZNAM", sound); } /** * * @return */ public FormID getDropSound() { return subRecords.getSubForm("ZNAM").getForm(); } /** * * @param path */ public void setInventoryImage(String path) { subRecords.setSubString("ICON", path); } /** * * @return */ public String getInventoryImage() { return subRecords.getSubString("ICON").print(); } /** * * @param path */ public void setMessageImage(String path) { subRecords.setSubString("MICO", path); } /** * * @return */ public String getMessageImage() { return subRecords.getSubString("MICO").print(); } @Override public MajorRecord merge(MajorRecord no, MajorRecord bo) { super.merge(no, bo); MISC e = this; if (!(no == null && bo == null && (no instanceof MISC) && (bo instanceof MISC))) { final MISC ne = (MISC) no; final MISC be = (MISC) bo; SubRecords sList = e.subRecords; SubRecords nsList = ne.subRecords; SubRecords bsList = be.subRecords; for (SubRecord s : sList) { s.merge(nsList.get(s.getType()), bsList.get(s.getType())); } } return e; } }
19.391635
93
0.583333
25cd343f74bf54c37f9c088f718ffdbe48ce74df
386
package com.scality.osis.security.crypto.model; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Getter @Setter @AllArgsConstructor @NoArgsConstructor @Builder public class SecretKeyRepoData { private String keyID; private CipherInformation cipherInfo; private byte[] encryptedBytes; }
20.315789
47
0.810881
db7e2f86a5b1a510348d07d714f93a15ef1cef45
2,340
package ryulib.socket; import android.annotation.SuppressLint; import android.os.AsyncTask; import android.util.Log; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; public class SocketUDP{ public void open() { try { socket_ = new DatagramSocket(); } catch (SocketException e) { Log.e("SocketUDP", e.getMessage()); } } public void close() { socket_.close(); } @SuppressLint("StaticFieldLeak") public void send(String host, int port, String text) { InetAddress addr = null; try { addr = InetAddress.getByName(host); } catch (UnknownHostException e) { Log.e("SocketUDP", e.getMessage()); } byte[] buffer = text.getBytes(); DatagramPacket packet = new DatagramPacket(buffer, buffer.length, addr, port); new AsyncTask<DatagramPacket, Void, Void>() { @Override protected Void doInBackground(DatagramPacket... packets) { try { socket_.send(packets[0]); } catch (IOException e) { Log.e("SocketUDP", e.getMessage()); } return null; } }.execute(packet); } @SuppressLint("StaticFieldLeak") public void broadcast(int port, String text) { byte[] broadcast_ip = new byte[] { -1, -1, -1, -1 }; InetAddress addr = null; try { addr = InetAddress.getByAddress(broadcast_ip); } catch (UnknownHostException e) { Log.e("SocketUDP", e.getMessage()); } byte[] buffer = text.getBytes(); DatagramPacket packet = new DatagramPacket(buffer, buffer.length, addr, port); new AsyncTask<DatagramPacket, Void, Void>() { @Override protected Void doInBackground(DatagramPacket... packets) { try { socket_.send(packets[0]); } catch (IOException e) { Log.e("SocketUDP", e.getMessage()); } return null; } }.execute(packet); } DatagramSocket socket_; }
27.209302
86
0.557692
c28c54aa459f84e224c9353fb19dadbf866a00ff
542
package org.gingolph.gingmap.processing; import org.gingolph.gingmap.NameImpl; import org.gingolph.gingmap.TopicImpl; public class TopicWalker { public void visitTopic(TopicImpl topic, TopicVisitor visitor) { topic.names().forEach(name -> visitName(name, visitor)); topic.occurrences().forEach(visitor::onOccurrence); topic.rolesPlayed().forEach(visitor::onRolePlayed); } private void visitName(NameImpl name, TopicVisitor visitor) { visitor.onName(name); name.variants().forEach(visitor::onVariant);; } }
28.526316
65
0.743542
5af5b59ee6e2fa57beaecc9c6d95d8ad23ce0ad3
5,068
package seedu.address.storage; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static seedu.address.testutil.TypicalDeliverymen.getTypicalDeliverymenList; import static seedu.address.testutil.TypicalOrders.getTypicalOrderBook; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import seedu.address.commons.events.model.HealthHubChangedEvent; import seedu.address.commons.events.storage.DataSavingExceptionEvent; import seedu.address.model.RequestBook; import seedu.address.model.ReadOnlyRequestBook; import seedu.address.model.ReadOnlyUsersList; import seedu.address.model.UserPrefs; import seedu.address.model.healthworker.HealthworkerList; import seedu.address.storage.user.XmlUsersListStorage; import seedu.address.ui.testutil.EventsCollectorRule; public class StorageManagerTest { @Rule public final EventsCollectorRule eventsCollectorRule = new EventsCollectorRule(); @Rule public TemporaryFolder testFolder = new TemporaryFolder(); private StorageManager storageManager; @Before public void setUp() { XmlUsersListStorage usersListStorage = new XmlUsersListStorage(getTempFilePath("users")); XmlHealthHubStorage foodZoomStorage = new XmlHealthHubStorage(getTempFilePath("foodzoom")); JsonUserPrefsStorage userPrefsStorage = new JsonUserPrefsStorage(getTempFilePath("prefs")); storageManager = new StorageManager(usersListStorage, foodZoomStorage, userPrefsStorage); } private Path getTempFilePath(String fileName) { return testFolder.getRoot().toPath().resolve(fileName); } @Test public void prefsReadSave() throws Exception { /* * Note: This is an integration test that verifies the StorageManager is properly wired to the * {@link JsonUserPrefsStorage} class. * More extensive testing of UserPref saving/reading is done in {@link JsonUserPrefsStorageTest} class. */ UserPrefs original = new UserPrefs(); original.setGuiSettings(300, 600, 4, 6); storageManager.saveUserPrefs(original); UserPrefs retrieved = storageManager.readUserPrefs().get(); assertEquals(original, retrieved); } @Test public void foodZoomReadSave() throws Exception { /* * Note: This is an integration test that verifies the StorageManager is properly wired to the * {@link XmlHealthHubStorage} class. * More extensive testing of UserPref saving/reading is done in {@link XmlFoodZoomStorageTest} class. */ RequestBook original = getTypicalOrderBook(); HealthworkerList healthworkerList = getTypicalDeliverymenList(); storageManager.saveHealthHub(original, healthworkerList); ReadOnlyRequestBook ordersRetrieved = storageManager.readRequestBook().get(); assertEquals(original, new RequestBook(ordersRetrieved)); HealthworkerList dmenRetrieved = storageManager.readHealthworkerList().get(); assertEquals(healthworkerList, new HealthworkerList(dmenRetrieved)); } @Test public void getFoodZoomFilePath() { assertNotNull(storageManager.getHealthHubFilePath()); } @Test public void handleOrderBookChangedEvent_exceptionThrown_eventRaised() { // Create a StorageManager while injecting a stub that throws an exception when the save method is called Storage storage = new StorageManager(new XmlUsersListStorageExceptionThrowingStub(Paths.get("dummy")), new XmlHealthHubStorageExceptionThrowingStub(Paths.get("dummy2")), new JsonUserPrefsStorage(Paths.get("dummy"))); storage.handleFoodZoomChangedEvent(new HealthHubChangedEvent(new RequestBook(), new HealthworkerList())); assertTrue(eventsCollectorRule.eventsCollector.getMostRecent() instanceof DataSavingExceptionEvent); } /** * A Stub class to throw an exception when the save method is called */ class XmlHealthHubStorageExceptionThrowingStub extends XmlHealthHubStorage { public XmlHealthHubStorageExceptionThrowingStub(Path filePath) { super(filePath); } @Override public void saveHealthHub(ReadOnlyRequestBook orderBook, HealthworkerList healthworkerList, Path filePath) throws IOException { throw new IOException("dummy exception"); } } /** * A Stub class to throw an exception when the save method is called */ class XmlUsersListStorageExceptionThrowingStub extends XmlUsersListStorage { public XmlUsersListStorageExceptionThrowingStub(Path filePath) { super(filePath); } @Override public void saveUsersList(ReadOnlyUsersList usersList, Path filePath) throws IOException { throw new IOException("dummy exception"); } } }
40.222222
121
0.736977
bd7dda400304e9cb8140711f69814c1a86a37c12
1,475
package com.github.bingoohuang.westcache.outofbox; import com.github.bingoohuang.westcache.base.WestCacheException; import com.github.bingoohuang.westcache.keyer.SimpleKeyer; import com.github.bingoohuang.westcache.utils.WestCacheOption; import com.google.common.base.Splitter; import lombok.val; import org.n3r.diamond.client.Miner; /** * @author bingoohuang [bingoohuang@gmail.com] Created on 2016/12/30. */ public class PackageLimitedKeyer extends SimpleKeyer { public static final String GROUP = "west.cache.packagelimit"; public static final String DATAID = "packages"; private static Splitter splitter = Splitter.onPattern("[\r\n;\\s]") .omitEmptyStrings().trimResults(); @Override public String getCacheKey(WestCacheOption option, String methodName, Object bean, Object... args) { String packageName = bean.getClass().getPackage().getName(); val pkgsConfig = new Miner().getStone(GROUP, DATAID); if (pkgsConfig == null) reportInvalidPackage(packageName); val pkgs = splitter.splitToList(pkgsConfig); if (!pkgs.contains(packageName)) reportInvalidPackage(packageName); return super.getCacheKey(option, methodName, bean, args); } private void reportInvalidPackage(String packageName) { throw new WestCacheException(packageName + " is not allowed for the cache key"); } }
37.820513
88
0.690169
47c065c4e85f73e9e25f2ac475c0d5cd1d4d3054
9,123
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|rest operator|. name|model package|; end_package begin_import import|import static name|org operator|. name|junit operator|. name|Assert operator|. name|assertEquals import|; end_import begin_import import|import static name|org operator|. name|junit operator|. name|Assert operator|. name|assertFalse import|; end_import begin_import import|import static name|org operator|. name|junit operator|. name|Assert operator|. name|assertTrue import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Iterator import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|HBaseClassTestRule import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|testclassification operator|. name|RestTests import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|testclassification operator|. name|SmallTests import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|ClassRule import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Test import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|experimental operator|. name|categories operator|. name|Category import|; end_import begin_import import|import name|org operator|. name|slf4j operator|. name|Logger import|; end_import begin_import import|import name|org operator|. name|slf4j operator|. name|LoggerFactory import|; end_import begin_class annotation|@ name|Category argument_list|( block|{ name|RestTests operator|. name|class block|, name|SmallTests operator|. name|class block|} argument_list|) specifier|public class|class name|TestTableSchemaModel extends|extends name|TestModelBase argument_list|< name|TableSchemaModel argument_list|> block|{ annotation|@ name|ClassRule specifier|public specifier|static specifier|final name|HBaseClassTestRule name|CLASS_RULE init|= name|HBaseClassTestRule operator|. name|forClass argument_list|( name|TestTableSchemaModel operator|. name|class argument_list|) decl_stmt|; specifier|private specifier|static specifier|final name|Logger name|LOG init|= name|LoggerFactory operator|. name|getLogger argument_list|( name|TestTableSchemaModel operator|. name|class argument_list|) decl_stmt|; specifier|public specifier|static specifier|final name|String name|TABLE_NAME init|= literal|"testTable" decl_stmt|; specifier|private specifier|static specifier|final name|boolean name|IS_META init|= literal|false decl_stmt|; specifier|private specifier|static specifier|final name|boolean name|IS_ROOT init|= literal|false decl_stmt|; specifier|private specifier|static specifier|final name|boolean name|READONLY init|= literal|false decl_stmt|; name|TestColumnSchemaModel name|testColumnSchemaModel decl_stmt|; specifier|public name|TestTableSchemaModel parameter_list|() throws|throws name|Exception block|{ name|super argument_list|( name|TableSchemaModel operator|. name|class argument_list|) expr_stmt|; name|testColumnSchemaModel operator|= operator|new name|TestColumnSchemaModel argument_list|() expr_stmt|; name|AS_XML operator|= literal|"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" operator|+ literal|"<TableSchema name=\"testTable\" IS_META=\"false\" IS_ROOT=\"false\" READONLY=\"false\">" operator|+ literal|"<ColumnSchema name=\"testcolumn\" BLOCKSIZE=\"16384\" BLOOMFILTER=\"NONE\" " operator|+ literal|"BLOCKCACHE=\"true\" COMPRESSION=\"GZ\" VERSIONS=\"1\" TTL=\"86400\" IN_MEMORY=\"false\"/>" operator|+ literal|"</TableSchema>" expr_stmt|; name|AS_PB operator|= literal|"Cgl0ZXN0VGFibGUSEAoHSVNfTUVUQRIFZmFsc2USEAoHSVNfUk9PVBIFZmFsc2USEQoIUkVBRE9O" operator|+ literal|"TFkSBWZhbHNlGpcBCgp0ZXN0Y29sdW1uEhIKCUJMT0NLU0laRRIFMTYzODQSEwoLQkxPT01GSUxU" operator|+ literal|"RVISBE5PTkUSEgoKQkxPQ0tDQUNIRRIEdHJ1ZRIRCgtDT01QUkVTU0lPThICR1oSDQoIVkVSU0lP" operator|+ literal|"TlMSATESDAoDVFRMEgU4NjQwMBISCglJTl9NRU1PUlkSBWZhbHNlGICjBSABKgJHWigA" expr_stmt|; name|AS_JSON operator|= literal|"{\"name\":\"testTable\",\"IS_META\":\"false\",\"IS_ROOT\":\"false\"," operator|+ literal|"\"READONLY\":\"false\",\"ColumnSchema\":[{\"name\":\"testcolumn\"," operator|+ literal|"\"BLOCKSIZE\":\"16384\",\"BLOOMFILTER\":\"NONE\",\"BLOCKCACHE\":\"true\"," operator|+ literal|"\"COMPRESSION\":\"GZ\",\"VERSIONS\":\"1\",\"TTL\":\"86400\",\"IN_MEMORY\":\"false\"}]}" expr_stmt|; block|} annotation|@ name|Override specifier|protected name|TableSchemaModel name|buildTestModel parameter_list|() block|{ return|return name|buildTestModel argument_list|( name|TABLE_NAME argument_list|) return|; block|} specifier|public name|TableSchemaModel name|buildTestModel parameter_list|( name|String name|name parameter_list|) block|{ name|TableSchemaModel name|model init|= operator|new name|TableSchemaModel argument_list|() decl_stmt|; name|model operator|. name|setName argument_list|( name|name argument_list|) expr_stmt|; name|model operator|. name|__setIsMeta argument_list|( name|IS_META argument_list|) expr_stmt|; name|model operator|. name|__setIsRoot argument_list|( name|IS_ROOT argument_list|) expr_stmt|; name|model operator|. name|__setReadOnly argument_list|( name|READONLY argument_list|) expr_stmt|; name|model operator|. name|addColumnFamily argument_list|( name|testColumnSchemaModel operator|. name|buildTestModel argument_list|() argument_list|) expr_stmt|; return|return name|model return|; block|} annotation|@ name|Override specifier|protected name|void name|checkModel parameter_list|( name|TableSchemaModel name|model parameter_list|) block|{ name|checkModel argument_list|( name|model argument_list|, name|TABLE_NAME argument_list|) expr_stmt|; block|} specifier|public name|void name|checkModel parameter_list|( name|TableSchemaModel name|model parameter_list|, name|String name|tableName parameter_list|) block|{ name|assertEquals argument_list|( name|model operator|. name|getName argument_list|() argument_list|, name|tableName argument_list|) expr_stmt|; name|assertEquals argument_list|( name|IS_META argument_list|, name|model operator|. name|__getIsMeta argument_list|() argument_list|) expr_stmt|; name|assertEquals argument_list|( name|IS_ROOT argument_list|, name|model operator|. name|__getIsRoot argument_list|() argument_list|) expr_stmt|; name|assertEquals argument_list|( name|READONLY argument_list|, name|model operator|. name|__getReadOnly argument_list|() argument_list|) expr_stmt|; name|Iterator argument_list|< name|ColumnSchemaModel argument_list|> name|families init|= name|model operator|. name|getColumns argument_list|() operator|. name|iterator argument_list|() decl_stmt|; name|assertTrue argument_list|( name|families operator|. name|hasNext argument_list|() argument_list|) expr_stmt|; name|ColumnSchemaModel name|family init|= name|families operator|. name|next argument_list|() decl_stmt|; name|testColumnSchemaModel operator|. name|checkModel argument_list|( name|family argument_list|) expr_stmt|; name|assertFalse argument_list|( name|families operator|. name|hasNext argument_list|() argument_list|) expr_stmt|; block|} annotation|@ name|Override annotation|@ name|Test specifier|public name|void name|testBuildModel parameter_list|() throws|throws name|Exception block|{ name|checkModel argument_list|( name|buildTestModel argument_list|() argument_list|) expr_stmt|; block|} annotation|@ name|Override annotation|@ name|Test specifier|public name|void name|testFromXML parameter_list|() throws|throws name|Exception block|{ name|checkModel argument_list|( name|fromXML argument_list|( name|AS_XML argument_list|) argument_list|) expr_stmt|; block|} annotation|@ name|Override annotation|@ name|Test specifier|public name|void name|testFromPB parameter_list|() throws|throws name|Exception block|{ name|checkModel argument_list|( name|fromPB argument_list|( name|AS_PB argument_list|) argument_list|) expr_stmt|; block|} block|} end_class end_unit
16.320215
814
0.802039
df30a360c321c27839a226e42fd4fc032a6575cf
747
package com.github.ben.zhihudaily.ui.base; import android.content.Context; import android.os.Bundle; import android.support.annotation.Nullable; import com.github.ben.zhihudaily.utils.SharePreUtils; import com.trello.rxlifecycle2.components.support.RxAppCompatActivity; /** * Created on 16/9/20. * * @author Ben */ public abstract class BaseActivity extends RxAppCompatActivity { protected Context mContext; protected boolean isNightMode() { return SharePreUtils.isNight(); } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mContext = this; } @Override protected void onDestroy() { super.onDestroy(); } }
20.75
70
0.716198
a706329966f3e440f28bf62ff7765373ed278f27
1,647
package com.cezarykluczynski.stapi.etl.food.creation.configuration; import com.cezarykluczynski.stapi.etl.configuration.job.service.StepCompletenessDecider; import com.cezarykluczynski.stapi.etl.food.creation.processor.FoodReader; import com.cezarykluczynski.stapi.etl.util.constant.CategoryTitle; import com.cezarykluczynski.stapi.etl.util.constant.JobName; import com.cezarykluczynski.stapi.etl.util.constant.StepName; import com.cezarykluczynski.stapi.sources.mediawiki.api.CategoryApi; import com.cezarykluczynski.stapi.sources.mediawiki.api.enums.MediaWikiSource; import com.cezarykluczynski.stapi.sources.mediawiki.dto.PageHeader; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.DependsOn; import javax.inject.Inject; import java.util.List; @Configuration public class FoodCreationConfiguration { @Inject private CategoryApi categoryApi; @Inject private StepCompletenessDecider stepCompletenessDecider; @Bean @DependsOn("batchDatabaseInitializer") public FoodReader foodReader() { List<PageHeader> foods = Lists.newArrayList(); if (!stepCompletenessDecider.isStepComplete(JobName.JOB_CREATE, StepName.CREATE_FOODS)) { foods.addAll(categoryApi.getPagesIncludingSubcategories(CategoryTitle.FOODS, MediaWikiSource.MEMORY_ALPHA_EN)); foods.addAll(categoryApi.getPagesIncludingSubcategories(CategoryTitle.BEVERAGES, MediaWikiSource.MEMORY_ALPHA_EN)); } return new FoodReader(Lists.newArrayList(Sets.newHashSet(foods))); } }
37.431818
118
0.840923
ceaae9044ecd4962ec588e17f1437cc45852d603
731
/* * Copyright © 2014-2015 Paul Waslowski <freack1208@gmail.com> * This work is free. You can redistribute it and/or modify it under the * terms of the Do What The Fuck You Want To Public License, Version 2, * as published by Sam Hocevar. See the LICENSE file for more details. */ package me.freack100.trapsplus; import me.freack100.trapsplus.traps.Traps; import org.bukkit.Location; public class TrapsAPI { private TrapsPlus plugin; public TrapsAPI(TrapsPlus plugin) { this.plugin = plugin; } public boolean isTrap(Location loc) { return this.plugin.getTraps().containsKey(loc); } public void addTrap(Location loc, Traps trap) { this.plugin.addTrap(loc, trap); } }
24.366667
72
0.699042
a19c8abe1a4dbfdf2a58c4fb5267965c2e557815
356
package com.zejian.structures.LinkedList.singleLinked; /** * Created by zejian on 2016/10/21. * 单向链表节点 */ public class Node<T> { public T data; public Node<T> next; public Node(){ } public Node(T data){ this.data=data; } public Node(T data,Node<T> next){ this.data=data; this.next=next; } }
14.24
54
0.578652
d182e84e6c999de2210d86fd9421f7c3a49f1f65
411
package ua.logos.entity; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; @Getter @Setter @NoArgsConstructor @Entity @Table(name = "categories") public class CategoryEntity extends BaseEntity { @Column(length = 80, nullable = false, unique = true) private String name; }
17.869565
57
0.773723
9185bf52bbdb63ae8a46d3d8e4319e19ee7c1cd6
240
package com.hsj.http.oauth2; /** * @Author:HSJ * @E-mail:shengjunhu@foxmail.com * @Date:2017/6/12 12:51 * @Class:HttpManager * @Description: */ public class HttpManager { private String TAG = this.getClass().getSimpleName(); }
16
57
0.675
c52852fc7d69e6580ad0e15196359a7e1df4fb7f
3,462
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.s4.benchmark.utils; import java.util.List; import java.util.concurrent.CountDownLatch; import org.I0Itec.zkclient.IZkChildListener; import org.I0Itec.zkclient.ZkClient; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.Watcher.Event.EventType; import org.apache.zookeeper.ZooKeeper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Utils { private static Logger logger = LoggerFactory.getLogger(Utils.class); public static CountDownLatch getReadySignal(String zkString, final String parentPath, final int counts) { ZkClient zkClient = new ZkClient(zkString); if (zkClient.exists(parentPath)) { System.out.println(parentPath + " path exists and will be deleted"); zkClient.deleteRecursive(parentPath); } zkClient.createPersistent(parentPath); final CountDownLatch signalReady = new CountDownLatch(1); zkClient.subscribeChildChanges(parentPath, new IZkChildListener() { @Override public void handleChildChange(String arg0, List<String> arg1) throws Exception { if (parentPath.equals(arg0)) { if (arg1.size() >= counts) { logger.info("Latch reached for {} with {} children", arg0, counts); signalReady.countDown(); } } } }); return signalReady; } public static void watchAndSignalChildrenReachedCount(final String path, final CountDownLatch latch, final ZooKeeper zk, final int count) throws KeeperException, InterruptedException { List<String> children = zk.getChildren(path, new Watcher() { @Override public void process(WatchedEvent event) { if (EventType.NodeChildrenChanged.equals(event.getType())) { try { if (count == zk.getChildren(path, false).size()) { latch.countDown(); } } catch (KeeperException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } latch.countDown(); } } }); if (children.size() == count) { latch.countDown(); } } }
39.340909
109
0.625072
72b8138b2113963cd9d026a4e9d33a7de182b6b2
3,353
package view; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.RadioButton; import javafx.scene.control.ToggleGroup; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class Window_Perform_Complete_Maintenance extends Stage { private Panel_Perform_Maintenance panel_perform_maintenance = new Panel_Perform_Maintenance(); private Panel_Complete_Maintenance panel_complete_maintenance = new Panel_Complete_Maintenance(); private RadioButton selectPerform = new RadioButton("Perform Maintenance"); private RadioButton selectComplete = new RadioButton("Complete Maintenance"); private ToggleGroup toggleGroup = new ToggleGroup(); public Window_Perform_Complete_Maintenance() { setup(); } private void setup() { VBox root = new VBox(5); root.setAlignment(Pos.CENTER); root.setPadding(new Insets(10, 10, 10, 10)); HBox buttonContainer = new HBox(10); buttonContainer.setAlignment(Pos.CENTER); HBox panelContainer = new HBox(10); panelContainer.getChildren().addAll(panel_perform_maintenance, panel_complete_maintenance); root.getChildren().addAll(buttonContainer, panelContainer); this.setScene(new Scene(root)); panel_perform_maintenance.setDisable(false); panel_complete_maintenance.setDisable(true); selectPerform.setSelected(true); selectComplete.setToggleGroup(toggleGroup); selectPerform.setToggleGroup(toggleGroup); selectPerform.setOnAction(event -> { panel_perform_maintenance.setDisable(false); panel_complete_maintenance.setDisable(true); }); selectComplete.setOnAction(event -> { panel_perform_maintenance.setDisable(true); panel_complete_maintenance.setDisable(false); }); buttonContainer.getChildren().addAll(selectPerform, selectComplete); this.setResizable(false); } public void Clear(){ panel_complete_maintenance.clearInput(); panel_perform_maintenance.clearInput(); } public Panel_Perform_Maintenance getPanel_perform_maintenance() { return panel_perform_maintenance; } public void setPanel_perform_maintenance(Panel_Perform_Maintenance panel_perform_maintenance) { this.panel_perform_maintenance = panel_perform_maintenance; } public Panel_Complete_Maintenance getPanel_complete_maintenance() { return panel_complete_maintenance; } public void setPanel_complete_maintenance(Panel_Complete_Maintenance panel_complete_maintenance) { this.panel_complete_maintenance = panel_complete_maintenance; } public RadioButton getSelectPerform() { return selectPerform; } public void setSelectPerform(RadioButton selectPerform) { this.selectPerform = selectPerform; } public RadioButton getSelectComplete() { return selectComplete; } public void setSelectComplete(RadioButton selectComplete) { this.selectComplete = selectComplete; } public ToggleGroup getToggleGroup() { return toggleGroup; } public void setToggleGroup(ToggleGroup toggleGroup) { this.toggleGroup = toggleGroup; } }
34.214286
102
0.728601
6079982be0995e0e21166b8b86b441aa332e2bf9
839
package us.myles.ViaVersion.api.type.types.minecraft; import io.netty.buffer.ByteBuf; import us.myles.ViaVersion.api.minecraft.Position; import us.myles.ViaVersion.api.type.Type; public class PositionType extends Type<Position> { public PositionType() { super(Position.class); } @Override public Position read(ByteBuf buffer) { long val = buffer.readLong(); long x = (val >> 38); // signed long y = (val >> 26) & 0xfff; // unsigned // this shifting madness is used to preserve sign long z = (val << 38) >> 38; // signed return new Position(x, y, z); } @Override public void write(ByteBuf buffer, Position object) { buffer.writeLong(((object.getX() & 0x3ffffff) << 38) | ((object.getY() & 0xfff) << 26) | (object.getZ() & 0x3ffffff)); } }
29.964286
126
0.624553
4e0f003ecad02c8a9d5ac4ca84e04567250bec3d
1,004
package problems.leetcode; /** * https://leetcode.com/problems/longest-common-subsequence/ * https://www.youtube.com/watch?v=NnD96abizww */ public class LongestCommonSubsequence { public static int longestCommonSubsequence(String text1, String text2) { /* if text2[i] == text2[j] T[i][j] = 1 + T[i-1][j-1] else T[i][j] = max(T[i-1][j], T[i][j-1]) */ int dp[][] = new int[text1.length() + 1][text2.length() + 1]; int longest = 0; for (int i = 1; i < dp.length; i++) { for (int j = 1; j < dp[i].length; j++) { if (text1.charAt(i - 1) == text2.charAt(j - 1)) { dp[i][j] = dp[i - 1][j - 1] + 1; } else { dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]); } if (dp[i][j] > longest) { longest = dp[i][j]; } } } return longest; } }
25.1
76
0.425299
a1250a10976efeb0ba44f0dd13a69e2399be1cba
17,057
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at *<p/> * http://www.apache.org/licenses/LICENSE-2.0 *<p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|activemq operator|. name|bugs package|; end_package begin_import import|import name|java operator|. name|util operator|. name|ArrayList import|; end_import begin_import import|import name|javax operator|. name|jms operator|. name|Connection import|; end_import begin_import import|import name|javax operator|. name|jms operator|. name|DeliveryMode import|; end_import begin_import import|import name|javax operator|. name|jms operator|. name|Message import|; end_import begin_import import|import name|javax operator|. name|jms operator|. name|MessageConsumer import|; end_import begin_import import|import name|javax operator|. name|jms operator|. name|MessageProducer import|; end_import begin_import import|import name|javax operator|. name|jms operator|. name|Session import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|activemq operator|. name|ActiveMQConnectionFactory import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|activemq operator|. name|broker operator|. name|BrokerService import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|activemq operator|. name|broker operator|. name|TransportConnector import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|activemq operator|. name|broker operator|. name|region operator|. name|Queue import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|activemq operator|. name|command operator|. name|ActiveMQQueue import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|After import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Before import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Test import|; end_import begin_import import|import name|org operator|. name|slf4j operator|. name|Logger import|; end_import begin_import import|import name|org operator|. name|slf4j operator|. name|LoggerFactory import|; end_import begin_import import|import static name|org operator|. name|junit operator|. name|Assert operator|. name|assertEquals import|; end_import begin_class specifier|public class|class name|AMQ6094Test block|{ specifier|private specifier|static name|Logger name|LOG init|= name|LoggerFactory operator|. name|getLogger argument_list|( name|AMQ6094Test operator|. name|class argument_list|) decl_stmt|; specifier|private name|BrokerService name|brokerService decl_stmt|; specifier|private name|String name|connectionUri decl_stmt|; annotation|@ name|Before specifier|public name|void name|before parameter_list|() throws|throws name|Exception block|{ name|brokerService operator|= operator|new name|BrokerService argument_list|() expr_stmt|; name|TransportConnector name|connector init|= name|brokerService operator|. name|addConnector argument_list|( literal|"tcp://localhost:0" argument_list|) decl_stmt|; name|connectionUri operator|= name|connector operator|. name|getPublishableConnectString argument_list|() expr_stmt|; name|brokerService operator|. name|setDeleteAllMessagesOnStartup argument_list|( literal|true argument_list|) expr_stmt|; name|brokerService operator|. name|start argument_list|() expr_stmt|; name|brokerService operator|. name|waitUntilStarted argument_list|() expr_stmt|; block|} annotation|@ name|After specifier|public name|void name|after parameter_list|() throws|throws name|Exception block|{ if|if condition|( name|brokerService operator|!= literal|null condition|) block|{ name|brokerService operator|. name|stop argument_list|() expr_stmt|; name|brokerService operator|. name|waitUntilStopped argument_list|() expr_stmt|; block|} block|} annotation|@ name|Test specifier|public name|void name|testQueueMemoryUsage parameter_list|() throws|throws name|Exception block|{ specifier|final name|ArrayList argument_list|< name|ThreadSlot argument_list|> name|producerThreads init|= operator|new name|ArrayList argument_list|<> argument_list|() decl_stmt|; specifier|final name|ArrayList argument_list|< name|ThreadSlot argument_list|> name|consumerThreads init|= operator|new name|ArrayList argument_list|<> argument_list|() decl_stmt|; for|for control|( name|int name|i init|= literal|0 init|; name|i operator|< literal|4 condition|; name|i operator|++ control|) name|producerThreads operator|. name|add argument_list|( name|runInThread argument_list|( operator|new name|UnsafeRunnable argument_list|() block|{ annotation|@ name|Override specifier|public name|void name|run parameter_list|() throws|throws name|Exception block|{ name|producer argument_list|( name|connectionUri argument_list|, literal|"queueA" argument_list|) expr_stmt|; block|} block|} argument_list|) argument_list|) expr_stmt|; for|for control|( name|int name|i init|= literal|0 init|; name|i operator|< literal|4 condition|; name|i operator|++ control|) name|consumerThreads operator|. name|add argument_list|( name|runInThread argument_list|( operator|new name|UnsafeRunnable argument_list|() block|{ annotation|@ name|Override specifier|public name|void name|run parameter_list|() throws|throws name|Exception block|{ name|consumer argument_list|( name|connectionUri argument_list|, literal|"queueA" argument_list|, literal|2500 argument_list|) expr_stmt|; block|} block|} argument_list|) argument_list|) expr_stmt|; comment|// kill and restart random threads for|for control|( name|int name|count init|= literal|0 init|; name|count operator|< literal|10 condition|; name|count operator|++ control|) block|{ name|Thread operator|. name|sleep argument_list|( literal|5000 argument_list|) expr_stmt|; specifier|final name|int name|i init|= call|( name|int call|) argument_list|( name|Math operator|. name|random argument_list|() operator|* name|consumerThreads operator|. name|size argument_list|() argument_list|) decl_stmt|; specifier|final name|ThreadSlot name|slot init|= name|consumerThreads operator|. name|get argument_list|( name|i argument_list|) decl_stmt|; name|slot operator|. name|thread operator|. name|interrupt argument_list|() expr_stmt|; name|consumerThreads operator|. name|remove argument_list|( name|i argument_list|) expr_stmt|; name|consumerThreads operator|. name|add argument_list|( name|runInThread argument_list|( name|slot operator|. name|runnable argument_list|) argument_list|) expr_stmt|; name|Queue name|queue init|= operator|( name|Queue operator|) name|brokerService operator|. name|getDestination argument_list|( operator|new name|ActiveMQQueue argument_list|( literal|"queueA" argument_list|) argument_list|) decl_stmt|; name|LOG operator|. name|info argument_list|( literal|"cursorMemoryUsage: " operator|+ name|queue operator|. name|getMessages argument_list|() operator|. name|getSystemUsage argument_list|() operator|. name|getMemoryUsage argument_list|() operator|. name|getUsage argument_list|() argument_list|) expr_stmt|; name|LOG operator|. name|info argument_list|( literal|"messagesStat: " operator|+ name|queue operator|. name|getDestinationStatistics argument_list|() operator|. name|getMessages argument_list|() operator|. name|getCount argument_list|() argument_list|) expr_stmt|; block|} comment|// verify usage name|Queue name|queue init|= operator|( name|Queue operator|) name|brokerService operator|. name|getDestination argument_list|( operator|new name|ActiveMQQueue argument_list|( literal|"queueA" argument_list|) argument_list|) decl_stmt|; name|LOG operator|. name|info argument_list|( literal|"cursorMemoryUsage: " operator|+ name|queue operator|. name|getMessages argument_list|() operator|. name|getSystemUsage argument_list|() operator|. name|getMemoryUsage argument_list|() operator|. name|getUsage argument_list|() argument_list|) expr_stmt|; name|LOG operator|. name|info argument_list|( literal|"messagesStat: " operator|+ name|queue operator|. name|getDestinationStatistics argument_list|() operator|. name|getMessages argument_list|() operator|. name|getCount argument_list|() argument_list|) expr_stmt|; comment|// drain the queue for|for control|( name|ThreadSlot name|threadSlot range|: name|producerThreads control|) block|{ name|threadSlot operator|. name|thread operator|. name|interrupt argument_list|() expr_stmt|; name|threadSlot operator|. name|thread operator|. name|join argument_list|( literal|4000 argument_list|) expr_stmt|; block|} for|for control|( name|ThreadSlot name|threadSlot range|: name|consumerThreads control|) block|{ name|threadSlot operator|. name|thread operator|. name|interrupt argument_list|() expr_stmt|; name|threadSlot operator|. name|thread operator|. name|join argument_list|( literal|4000 argument_list|) expr_stmt|; block|} name|consumer argument_list|( name|connectionUri argument_list|, literal|"queueA" argument_list|, literal|2500 argument_list|, literal|true argument_list|) expr_stmt|; name|LOG operator|. name|info argument_list|( literal|"After drain, cursorMemoryUsage: " operator|+ name|queue operator|. name|getMessages argument_list|() operator|. name|getSystemUsage argument_list|() operator|. name|getMemoryUsage argument_list|() operator|. name|getUsage argument_list|() argument_list|) expr_stmt|; name|LOG operator|. name|info argument_list|( literal|"messagesStat: " operator|+ name|queue operator|. name|getDestinationStatistics argument_list|() operator|. name|getMessages argument_list|() operator|. name|getCount argument_list|() argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"Queue memory usage to 0" argument_list|, literal|0 argument_list|, name|queue operator|. name|getMessages argument_list|() operator|. name|getSystemUsage argument_list|() operator|. name|getMemoryUsage argument_list|() operator|. name|getUsage argument_list|() argument_list|) expr_stmt|; block|} specifier|public specifier|static name|void name|producer parameter_list|( name|String name|uri parameter_list|, name|String name|topic parameter_list|) throws|throws name|Exception block|{ specifier|final name|ActiveMQConnectionFactory name|factory init|= operator|new name|ActiveMQConnectionFactory argument_list|( name|uri operator|+ literal|"?jms.useCompression=true&jms.useAsyncSend=true&daemon=true" argument_list|) decl_stmt|; name|Connection name|connection init|= name|factory operator|. name|createConnection argument_list|() decl_stmt|; name|Session name|session init|= name|connection operator|. name|createSession argument_list|( literal|false argument_list|, name|Session operator|. name|AUTO_ACKNOWLEDGE argument_list|) decl_stmt|; name|MessageProducer name|producer init|= name|session operator|. name|createProducer argument_list|( operator|new name|ActiveMQQueue argument_list|( name|topic argument_list|) argument_list|) decl_stmt|; name|producer operator|. name|setTimeToLive argument_list|( literal|6000 argument_list|) expr_stmt|; name|producer operator|. name|setDeliveryMode argument_list|( name|DeliveryMode operator|. name|NON_PERSISTENT argument_list|) expr_stmt|; while|while condition|( literal|true condition|) block|{ name|producer operator|. name|send argument_list|( name|session operator|. name|createTextMessage argument_list|( name|msg argument_list|() argument_list|) argument_list|) expr_stmt|; if|if condition|( name|Math operator|. name|random argument_list|() operator|> literal|0.5 condition|) name|Thread operator|. name|sleep argument_list|( literal|1 argument_list|) expr_stmt|; block|} block|} specifier|public specifier|static name|void name|consumer parameter_list|( name|String name|uri parameter_list|, name|String name|queue parameter_list|, name|int name|prefetchSize parameter_list|) throws|throws name|Exception block|{ name|consumer argument_list|( name|uri argument_list|, name|queue argument_list|, name|prefetchSize argument_list|, literal|false argument_list|) expr_stmt|; block|} specifier|public specifier|static name|void name|consumer parameter_list|( name|String name|uri parameter_list|, name|String name|queue parameter_list|, name|int name|prefetchSize parameter_list|, name|boolean name|drain parameter_list|) throws|throws name|Exception block|{ specifier|final name|ActiveMQConnectionFactory name|factory init|= operator|new name|ActiveMQConnectionFactory argument_list|( name|uri operator|+ literal|"?jms.prefetchPolicy.queuePrefetch=" operator|+ name|prefetchSize operator|+ literal|"&jms.useAsyncSend=true" argument_list|) decl_stmt|; name|Connection name|connection init|= literal|null decl_stmt|; try|try block|{ name|connection operator|= name|factory operator|. name|createConnection argument_list|() expr_stmt|; name|connection operator|. name|start argument_list|() expr_stmt|; name|Session name|session init|= name|connection operator|. name|createSession argument_list|( literal|false argument_list|, name|Session operator|. name|AUTO_ACKNOWLEDGE argument_list|) decl_stmt|; name|MessageConsumer name|consumer init|= name|session operator|. name|createConsumer argument_list|( operator|new name|ActiveMQQueue argument_list|( name|queue argument_list|) argument_list|) decl_stmt|; if|if condition|( name|drain condition|) block|{ name|Message name|message init|= literal|null decl_stmt|; do|do block|{ name|message operator|= name|consumer operator|. name|receive argument_list|( literal|4000 argument_list|) expr_stmt|; block|} do|while condition|( name|message operator|!= literal|null condition|) do|; block|} else|else block|{ comment|// block while|while condition|( literal|true condition|) block|{ name|consumer operator|. name|receive argument_list|() expr_stmt|; block|} block|} block|} finally|finally block|{ name|Thread operator|. name|interrupted argument_list|() expr_stmt|; if|if condition|( operator|! name|drain condition|) block|{ name|Thread operator|. name|sleep argument_list|( literal|5000 argument_list|) expr_stmt|; comment|// delay closing of connection block|} name|LOG operator|. name|info argument_list|( literal|"Now closing" argument_list|) expr_stmt|; if|if condition|( name|connection operator|!= literal|null condition|) name|connection operator|. name|close argument_list|() expr_stmt|; block|} block|} specifier|private specifier|static name|String name|msg parameter_list|() block|{ specifier|final name|StringBuilder name|builder init|= operator|new name|StringBuilder argument_list|() decl_stmt|; for|for control|( name|int name|i init|= literal|0 init|; name|i operator|< literal|100 condition|; name|i operator|++ control|) name|builder operator|. name|append argument_list|( literal|"123457890" argument_list|) expr_stmt|; return|return name|builder operator|. name|toString argument_list|() return|; block|} specifier|private specifier|static interface|interface name|UnsafeRunnable block|{ specifier|public name|void name|run parameter_list|() throws|throws name|Exception function_decl|; block|} specifier|public specifier|static class|class name|ThreadSlot block|{ specifier|private name|UnsafeRunnable name|runnable decl_stmt|; specifier|private name|Thread name|thread decl_stmt|; block|} specifier|public specifier|static name|ThreadSlot name|runInThread parameter_list|( specifier|final name|UnsafeRunnable name|runnable parameter_list|) block|{ specifier|final name|Thread name|thread init|= operator|new name|Thread argument_list|( operator|new name|Runnable argument_list|() block|{ annotation|@ name|Override specifier|public name|void name|run parameter_list|() block|{ try|try block|{ name|runnable operator|. name|run argument_list|() expr_stmt|; block|} catch|catch parameter_list|( name|Exception name|e parameter_list|) block|{ comment|//e.printStackTrace(); block|} block|} block|} argument_list|) decl_stmt|; name|thread operator|. name|start argument_list|() expr_stmt|; specifier|final name|ThreadSlot name|result init|= operator|new name|ThreadSlot argument_list|() decl_stmt|; name|result operator|. name|thread operator|= name|thread expr_stmt|; name|result operator|. name|runnable operator|= name|runnable expr_stmt|; return|return name|result return|; block|} block|} end_class end_unit
13.856214
814
0.802369
c7579e9c86711f519bbf7ce70ed1a5f70e666e4e
792
package net; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.util.concurrent.GenericFutureListener; public class gh { public static ChannelFuture a(ChannelFuture var0, GenericFutureListener[] var1) { return var0.addListeners(var1); } public static ChannelFuture a(ChannelFuture var0, GenericFutureListener var1) { return var0.addListener(var1); } public static ChannelFuture a(ChannelFuture var0) { return var0.awaitUninterruptibly(); } public static ChannelFuture c(ChannelFuture var0) { return var0.syncUninterruptibly(); } public static Channel d(ChannelFuture var0) { return var0.channel(); } public static ChannelFuture b(ChannelFuture var0) { return var0.sync(); } }
24.75
84
0.724747
b24c88b7d5218b73a9303378323015b0f3f7a50c
411
package com.fdmgroup; import static org.junit.Assert.*; import static org.mockito.Mockito.verify; import org.junit.Test; import org.mockito.Mockito; public class BuildingGUITest { @Test public void test_buildingInit(){ System.out.println("Test initializing building GUI"); BuildingGUI buildingGUI= Mockito.spy(new BuildingGUI()); buildingGUI.buildingInit(); verify(buildingGUI).listerner(); } }
20.55
58
0.766423
fb287bd28b12045a52a4251b22dbeb9266b19b6c
32,577
package com.battlelancer.seriesguide.ui.episodes; import android.content.Intent; import android.database.Cursor; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.widget.TextViewCompat; import androidx.fragment.app.Fragment; import androidx.loader.app.LoaderManager; import androidx.loader.content.CursorLoader; import androidx.loader.content.Loader; import com.battlelancer.seriesguide.R; import com.battlelancer.seriesguide.api.Action; import com.battlelancer.seriesguide.backend.settings.HexagonSettings; import com.battlelancer.seriesguide.databinding.ButtonsEpisodeBinding; import com.battlelancer.seriesguide.databinding.ButtonsEpisodeMoreBinding; import com.battlelancer.seriesguide.databinding.ButtonsServicesBinding; import com.battlelancer.seriesguide.databinding.FragmentEpisodeBinding; import com.battlelancer.seriesguide.databinding.LayoutEpisodeBinding; import com.battlelancer.seriesguide.databinding.RatingsShowsBinding; import com.battlelancer.seriesguide.extensions.ActionsHelper; import com.battlelancer.seriesguide.extensions.EpisodeActionsContract; import com.battlelancer.seriesguide.extensions.EpisodeActionsLoader; import com.battlelancer.seriesguide.extensions.ExtensionManager; import com.battlelancer.seriesguide.provider.SeriesGuideContract.Episodes; import com.battlelancer.seriesguide.provider.SeriesGuideContract.ListItemTypes; import com.battlelancer.seriesguide.provider.SeriesGuideContract.Seasons; import com.battlelancer.seriesguide.provider.SeriesGuideContract.Shows; import com.battlelancer.seriesguide.provider.SeriesGuideDatabase.Tables; import com.battlelancer.seriesguide.settings.DisplaySettings; import com.battlelancer.seriesguide.streaming.StreamingSearch; import com.battlelancer.seriesguide.streaming.StreamingSearchConfigureDialog; import com.battlelancer.seriesguide.thetvdbapi.TvdbImageTools; import com.battlelancer.seriesguide.thetvdbapi.TvdbLinks; import com.battlelancer.seriesguide.traktapi.CheckInDialogFragment; import com.battlelancer.seriesguide.traktapi.RateDialogFragment; import com.battlelancer.seriesguide.traktapi.TraktCredentials; import com.battlelancer.seriesguide.traktapi.TraktRatingsTask; import com.battlelancer.seriesguide.traktapi.TraktTools; import com.battlelancer.seriesguide.ui.BaseMessageActivity; import com.battlelancer.seriesguide.ui.FullscreenImageActivity; import com.battlelancer.seriesguide.ui.comments.TraktCommentsActivity; import com.battlelancer.seriesguide.ui.lists.ManageListsDialogFragment; import com.battlelancer.seriesguide.util.ClipboardTools; import com.battlelancer.seriesguide.util.DialogTools; import com.battlelancer.seriesguide.util.LanguageTools; import com.battlelancer.seriesguide.util.ServiceUtils; import com.battlelancer.seriesguide.util.ShareUtils; import com.battlelancer.seriesguide.util.TextTools; import com.battlelancer.seriesguide.util.TimeTools; import com.battlelancer.seriesguide.util.Utils; import com.battlelancer.seriesguide.util.ViewTools; import com.squareup.picasso.Callback; import com.squareup.picasso.Picasso; import com.uwetrottmann.androidutils.CheatSheet; import java.text.NumberFormat; import java.util.Date; import java.util.List; import java.util.Locale; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import timber.log.Timber; /** * Displays details about a single episode like summary, ratings and episode image if available. */ public class EpisodeDetailsFragment extends Fragment implements EpisodeActionsContract { private static final String ARG_EPISODE_TVDBID = "episode_tvdbid"; private static final String KEY_EPISODE_TVDB_ID = "episodeTvdbId"; private Handler handler = new Handler(); private TraktRatingsTask ratingsTask; private int episodeTvdbId; private int showTvdbId; @Nullable private String showTvdbSlug; private int seasonTvdbId; private int seasonNumber; private int episodeNumber; private int episodeFlag; private boolean collected; private String episodeTitle; private String showTitle; private int showRunTime; private long episodeReleaseTime; private LayoutEpisodeBinding binding; private ButtonsEpisodeBinding bindingButtons; private RatingsShowsBinding bindingRatings; private ButtonsServicesBinding bindingActions; private ButtonsEpisodeMoreBinding bindingBottom; public static EpisodeDetailsFragment newInstance(int episodeId) { EpisodeDetailsFragment f = new EpisodeDetailsFragment(); // Supply index input as an argument. Bundle args = new Bundle(); args.putInt(ARG_EPISODE_TVDBID, episodeId); f.setArguments(args); return f; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle args = getArguments(); if (args != null) { episodeTvdbId = args.getInt(ARG_EPISODE_TVDBID); } else { throw new IllegalArgumentException("Missing arguments"); } } @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { FragmentEpisodeBinding bindingRoot = FragmentEpisodeBinding.inflate(inflater, container, false); binding = bindingRoot.includeEpisode; bindingButtons = binding.includeButtons; bindingRatings = binding.includeRatings; bindingActions = binding.includeServices; bindingBottom = bindingActions.includeMore; return bindingRoot.getRoot(); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { binding.getRoot().setVisibility(View.GONE); bindingRatings.textViewRatingsRange.setText(getString(R.string.format_rating_range, 10)); bindingButtons.buttonEpisodeStreamingSearch.setOnClickListener( v -> onButtonStreamingSearchClick()); bindingButtons.buttonEpisodeStreamingSearch.setOnLongClickListener( v -> onButtonStreamingSearchLongClick()); // other bottom buttons bindingBottom.buttonEpisodeShare.setOnClickListener(v -> shareEpisode()); bindingBottom.buttonEpisodeCalendar .setOnClickListener(v -> ShareUtils.suggestCalendarEvent( getActivity(), showTitle, TextTools.getNextEpisodeString( getActivity(), seasonNumber, episodeNumber, episodeTitle ), episodeReleaseTime, showRunTime )); bindingBottom.buttonEpisodeLists.setOnClickListener(v -> ManageListsDialogFragment.show( getParentFragmentManager(), episodeTvdbId, ListItemTypes.EPISODE ) ); // set up long-press to copy text to clipboard (d-pad friendly vs text selection) ClipboardTools.copyTextToClipboardOnLongClick(binding.textviewTitle); ClipboardTools.copyTextToClipboardOnLongClick(binding.textviewReleaseTime); ClipboardTools.copyTextToClipboardOnLongClick(binding.textviewDescription); ClipboardTools.copyTextToClipboardOnLongClick(binding.textviewGuestStars); ClipboardTools.copyTextToClipboardOnLongClick(binding.textviewDirectors); ClipboardTools.copyTextToClipboardOnLongClick(binding.textviewWriters); ClipboardTools.copyTextToClipboardOnLongClick(binding.textviewDvd); ClipboardTools.copyTextToClipboardOnLongClick(binding.textviewReleaseDate); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); LoaderManager.getInstance(this) .initLoader(EpisodesActivity.EPISODE_LOADER_ID, null, episodeLoaderCallbacks); } @Override public void onResume() { super.onResume(); BaseMessageActivity.ServiceActiveEvent event = EventBus.getDefault() .getStickyEvent(BaseMessageActivity.ServiceActiveEvent.class); setEpisodeButtonsEnabled(event == null); EventBus.getDefault().register(this); loadEpisodeActionsDelayed(); } @Override public void onPause() { super.onPause(); if (handler != null) { handler.removeCallbacks(actionsRunnable); } EventBus.getDefault().unregister(this); } @Override public void onDestroyView() { super.onDestroyView(); // Always cancel the request here, this is safe to call even if the image has been loaded. // This ensures that the anonymous callback we have does not prevent the fragment from // being garbage collected. It also prevents our callback from getting invoked even after the // fragment is destroyed. Picasso.get().cancelRequest(binding.imageviewScreenshot); binding = null; bindingButtons = null; bindingRatings = null; bindingActions = null; bindingBottom = null; } @Override public void onDestroy() { super.onDestroy(); if (ratingsTask != null) { ratingsTask.cancel(true); ratingsTask = null; } } /** * If episode was watched, flags as unwatched. Otherwise, flags as watched. */ private void onToggleWatched() { boolean watched = EpisodeTools.isWatched(episodeFlag); changeEpisodeFlag(watched ? EpisodeFlags.UNWATCHED : EpisodeFlags.WATCHED); } /** * If episode was skipped, flags as unwatched. Otherwise, flags as skipped. */ private void onToggleSkipped() { boolean skipped = EpisodeTools.isSkipped(episodeFlag); changeEpisodeFlag(skipped ? EpisodeFlags.UNWATCHED : EpisodeFlags.SKIPPED); } private void changeEpisodeFlag(int episodeFlag) { this.episodeFlag = episodeFlag; EpisodeTools.episodeWatched(requireContext(), showTvdbId, episodeTvdbId, seasonNumber, episodeNumber, episodeFlag); } private void onToggleCollected() { collected = !collected; EpisodeTools.episodeCollected(requireContext(), showTvdbId, episodeTvdbId, seasonNumber, episodeNumber, collected); } private void onButtonStreamingSearchClick() { if (showTitle == null) { return; } if (StreamingSearch.isNotConfigured(requireContext())) { showStreamingSearchConfigDialog(); } else { StreamingSearch.searchForShow(requireContext(), showTitle); } } private boolean onButtonStreamingSearchLongClick() { showStreamingSearchConfigDialog(); return true; } private void showStreamingSearchConfigDialog() { StreamingSearchConfigureDialog.show(getParentFragmentManager()); } @Subscribe(threadMode = ThreadMode.MAIN) public void onStreamingSearchConfigured( StreamingSearchConfigureDialog.StreamingSearchConfiguredEvent event) { if (event.getTurnedOff()) { bindingButtons.buttonEpisodeStreamingSearch.setVisibility(View.GONE); } else { onButtonStreamingSearchClick(); } } @Override @Subscribe(threadMode = ThreadMode.MAIN) public void onEventMainThread(ExtensionManager.EpisodeActionReceivedEvent event) { if (episodeTvdbId == event.episodeTvdbId) { loadEpisodeActionsDelayed(); } } @Subscribe(threadMode = ThreadMode.MAIN) public void onEventEpisodeTask(BaseMessageActivity.ServiceActiveEvent event) { setEpisodeButtonsEnabled(false); } @Subscribe(threadMode = ThreadMode.MAIN) public void onEventEpisodeTask(BaseMessageActivity.ServiceCompletedEvent event) { setEpisodeButtonsEnabled(true); } private void setEpisodeButtonsEnabled(boolean enabled) { bindingButtons.buttonEpisodeWatched.setEnabled(enabled); bindingButtons.buttonEpisodeCollected.setEnabled(enabled); bindingButtons.buttonEpisodeSkip.setEnabled(enabled); bindingButtons.buttonEpisodeCheckin.setEnabled(enabled); bindingButtons.buttonEpisodeWatchedUpTo.setEnabled(enabled); bindingButtons.buttonEpisodeStreamingSearch.setEnabled(enabled); } private LoaderManager.LoaderCallbacks<Cursor> episodeLoaderCallbacks = new LoaderManager.LoaderCallbacks<Cursor>() { @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { return new CursorLoader(requireContext(), Episodes.buildEpisodeWithShowUri(String .valueOf(episodeTvdbId)), DetailsQuery.PROJECTION, null, null, null); } @Override public void onLoadFinished(@NonNull Loader<Cursor> loader, Cursor data) { if (!isAdded()) { return; } populateEpisodeData(data); } @Override public void onLoaderReset(@NonNull Loader<Cursor> loader) { // do nothing (we are never holding onto the cursor } }; private void populateEpisodeData(Cursor cursor) { if (cursor == null || !cursor.moveToFirst()) { // no data to display if (binding != null) { binding.getRoot().setVisibility(View.GONE); } return; } showTvdbId = cursor.getInt(DetailsQuery.SHOW_ID); showTvdbSlug = cursor.getString(DetailsQuery.SHOW_SLUG); seasonNumber = cursor.getInt(DetailsQuery.SEASON); episodeNumber = cursor.getInt(DetailsQuery.NUMBER); showRunTime = cursor.getInt(DetailsQuery.SHOW_RUNTIME); episodeReleaseTime = cursor.getLong(DetailsQuery.FIRST_RELEASE_MS); // title and description episodeFlag = cursor.getInt(DetailsQuery.WATCHED); episodeTitle = TextTools.getEpisodeTitle(requireContext(), cursor.getString(DetailsQuery.TITLE), episodeNumber); boolean hideDetails = EpisodeTools.isUnwatched(episodeFlag) && DisplaySettings.preventSpoilers(requireContext()); binding.textviewTitle.setText( TextTools.getEpisodeTitle(requireContext(), hideDetails ? null : episodeTitle, episodeNumber)); String overview = cursor.getString(DetailsQuery.OVERVIEW); if (TextUtils.isEmpty(overview)) { // no description available, show no translation available message String languageCode = cursor.getString(DetailsQuery.SHOW_LANGUAGE); overview = getString(R.string.no_translation, LanguageTools.getShowLanguageStringFor(getContext(), languageCode), getString(R.string.tvdb)); } else if (hideDetails) { overview = getString(R.string.no_spoilers); } long lastEditSeconds = cursor.getLong(DetailsQuery.LAST_EDITED); binding.textviewDescription.setText( TextTools.textWithTvdbSource(binding.textviewDescription.getContext(), overview, lastEditSeconds)); // show title showTitle = cursor.getString(DetailsQuery.SHOW_TITLE); // release date, also build release time and day boolean isReleased; String timeText; if (episodeReleaseTime != -1) { Date actualRelease = TimeTools.applyUserOffset(requireContext(), episodeReleaseTime); isReleased = TimeTools.isReleased(actualRelease); binding.textviewReleaseDate.setText( TimeTools.formatToLocalDateAndDay(requireContext(), actualRelease)); String dateTime; if (DisplaySettings.isDisplayExactDate(requireContext())) { // "31. October 2010" dateTime = TimeTools.formatToLocalDate(requireContext(), actualRelease); } else { // "in 15 mins" dateTime = TimeTools.formatToLocalRelativeTime(requireContext(), actualRelease); } // append day: "in 15 mins (Fri)" timeText = getString(R.string.format_date_and_day, dateTime, TimeTools.formatToLocalDay(actualRelease)).toUpperCase(Locale.getDefault()); } else { binding.textviewReleaseDate.setText(R.string.unknown); timeText = getString(R.string.episode_firstaired_unknown); isReleased = false; } // absolute number (e.g. relevant for Anime): "ABSOLUTE 142" int absoluteNumber = cursor.getInt(DetailsQuery.NUMBER_ABSOLUTE); String absoluteNumberText = null; if (absoluteNumber > 0) { absoluteNumberText = NumberFormat.getIntegerInstance().format(absoluteNumber); } binding.textviewReleaseTime.setText(TextTools.dotSeparate(timeText, absoluteNumberText)); // dim text color for title if not released TextViewCompat.setTextAppearance(binding.textviewTitle, isReleased ? R.style.TextAppearance_SeriesGuide_Headline6 : R.style.TextAppearance_SeriesGuide_Headline6_Dim); if (!isReleased) { TextViewCompat.setTextAppearance(binding.textviewReleaseTime, R.style.TextAppearance_SeriesGuide_Caption_Dim); } // guest stars ViewTools.setLabelValueOrHide(binding.textviewGuestStarsLabel, binding.textviewGuestStars, TextTools.splitAndKitTVDBStrings(cursor.getString(DetailsQuery.GUESTSTARS)) ); // DVD episode number ViewTools.setLabelValueOrHide(binding.textviewDvdLabel, binding.textviewDvd, cursor.getDouble(DetailsQuery.NUMBER_DVD)); // directors ViewTools.setValueOrPlaceholder(binding.textviewDirectors, TextTools.splitAndKitTVDBStrings(cursor.getString(DetailsQuery.DIRECTORS))); // writers ViewTools.setValueOrPlaceholder(binding.textviewWriters, TextTools.splitAndKitTVDBStrings(cursor.getString(DetailsQuery.WRITERS))); // ratings bindingRatings.getRoot().setOnClickListener(v -> rateEpisode()); CheatSheet.setup(bindingRatings.getRoot(), R.string.action_rate); // trakt rating bindingRatings.textViewRatingsValue.setText( TraktTools.buildRatingString(cursor.getDouble(DetailsQuery.RATING_GLOBAL))); bindingRatings.textViewRatingsVotes .setText(TraktTools.buildRatingVotesString(requireContext(), cursor.getInt(DetailsQuery.RATING_VOTES))); // user rating bindingRatings.textViewRatingsUser .setText(TraktTools.buildUserRatingString(requireContext(), cursor.getInt(DetailsQuery.RATING_USER))); // episode image final String imagePath = cursor.getString(DetailsQuery.IMAGE); binding.containerImage.setOnClickListener(v -> { Intent intent = new Intent(requireActivity(), FullscreenImageActivity.class); intent.putExtra(FullscreenImageActivity.EXTRA_IMAGE, TvdbImageTools.artworkUrl(imagePath)); Utils.startActivityWithAnimation(requireActivity(), intent, v); }); loadImage(imagePath, hideDetails); // Buttons. updatePrimaryButtons(cursor); updateSecondaryButtons(cursor); binding.getRoot().setVisibility(View.VISIBLE); loadDetails(); } private void updatePrimaryButtons(Cursor cursor) { // Check in button. bindingButtons.buttonEpisodeCheckin.setOnClickListener(v -> CheckInDialogFragment .show(requireContext(), getParentFragmentManager(), episodeTvdbId)); CheatSheet.setup(bindingButtons.buttonEpisodeCheckin); // hide check-in if not connected to trakt or hexagon is enabled boolean isConnectedToTrakt = TraktCredentials.get(requireContext()).hasCredentials(); boolean displayCheckIn = isConnectedToTrakt && !HexagonSettings.isEnabled(requireContext()); bindingButtons.buttonEpisodeCheckin .setVisibility(displayCheckIn ? View.VISIBLE : View.GONE); // Watched up to button. boolean isWatched = EpisodeTools.isWatched(episodeFlag); boolean displayWatchedUpTo = !isWatched; bindingButtons.buttonEpisodeWatchedUpTo .setVisibility(displayWatchedUpTo ? View.VISIBLE : View.GONE); bindingButtons.buttonEpisodeWatchedUpTo .setNextFocusUpId(displayCheckIn ? R.id.buttonCheckIn : R.id.buttonEpisodeWatched); bindingButtons.buttonEpisodeWatchedUpTo.setOnClickListener(v -> DialogTools.safeShow( EpisodeWatchedUpToDialog.newInstance(showTvdbId, episodeReleaseTime, episodeNumber), getParentFragmentManager(), "EpisodeWatchedUpToDialog" )); // Streaming search button. int streamingSearchNextFocusUpId; if (displayWatchedUpTo) { streamingSearchNextFocusUpId = R.id.buttonEpisodeWatchedUpTo; } else if (displayCheckIn) { streamingSearchNextFocusUpId = R.id.buttonCheckIn; } else { streamingSearchNextFocusUpId = R.id.buttonEpisodeWatched; } bindingButtons.buttonEpisodeStreamingSearch.setNextFocusUpId(streamingSearchNextFocusUpId); // hide streaming search if turned off boolean displayStreamingSearch = !StreamingSearch.isTurnedOff(requireContext()); bindingButtons.buttonEpisodeStreamingSearch .setVisibility(displayStreamingSearch ? View.VISIBLE : View.GONE); bindingButtons.dividerEpisodeButtons.setVisibility(displayCheckIn || displayStreamingSearch ? View.VISIBLE : View.GONE); // watched button if (isWatched) { ViewTools.setVectorDrawableTop(bindingButtons.buttonEpisodeWatched, R.drawable.ic_watched_24dp); } else { ViewTools.setVectorDrawableTop(bindingButtons.buttonEpisodeWatched, R.drawable.ic_watch_black_24dp); } bindingButtons.buttonEpisodeWatched.setOnClickListener(v -> onToggleWatched()); bindingButtons.buttonEpisodeWatched .setText(isWatched ? R.string.state_watched : R.string.action_watched); CheatSheet.setup(bindingButtons.buttonEpisodeWatched, isWatched ? R.string.action_unwatched : R.string.action_watched); // collected button collected = cursor.getInt(DetailsQuery.COLLECTED) == 1; if (collected) { ViewTools.setVectorDrawableTop(bindingButtons.buttonEpisodeCollected, R.drawable.ic_collected_24dp); } else { ViewTools.setVectorDrawableTop(bindingButtons.buttonEpisodeCollected, R.drawable.ic_collect_black_24dp); } bindingButtons.buttonEpisodeCollected.setOnClickListener(v -> onToggleCollected()); bindingButtons.buttonEpisodeCollected.setText(collected ? R.string.state_in_collection : R.string.action_collection_add); CheatSheet.setup(bindingButtons.buttonEpisodeCollected, collected ? R.string.action_collection_remove : R.string.action_collection_add); // skip button if (isWatched) { // if watched do not allow skipping bindingButtons.buttonEpisodeSkip.setVisibility(View.INVISIBLE); } else { bindingButtons.buttonEpisodeSkip.setVisibility(View.VISIBLE); boolean isSkipped = EpisodeTools.isSkipped(episodeFlag); if (isSkipped) { ViewTools.setVectorDrawableTop(bindingButtons.buttonEpisodeSkip, R.drawable.ic_skipped_24dp); } else { ViewTools.setVectorDrawableTop(bindingButtons.buttonEpisodeSkip, R.drawable.ic_skip_black_24dp); } bindingButtons.buttonEpisodeSkip.setOnClickListener(v -> onToggleSkipped()); bindingButtons.buttonEpisodeSkip .setText(isSkipped ? R.string.state_skipped : R.string.action_skip); CheatSheet.setup(bindingButtons.buttonEpisodeSkip, isSkipped ? R.string.action_dont_skip : R.string.action_skip); } } private void updateSecondaryButtons(Cursor cursor) { // trakt String traktLink = TraktTools.buildEpisodeUrl(episodeTvdbId); ViewTools.openUriOnClick(bindingBottom.buttonEpisodeTrakt, traktLink); ClipboardTools.copyTextToClipboardOnLongClick(bindingBottom.buttonEpisodeTrakt, traktLink); // IMDb String imdbId = cursor.getString(DetailsQuery.IMDBID); if (TextUtils.isEmpty(imdbId)) { // fall back to show IMDb id imdbId = cursor.getString(DetailsQuery.SHOW_IMDBID); } ServiceUtils.setUpImdbButton(imdbId, bindingBottom.buttonEpisodeImdb); // TVDb seasonTvdbId = cursor.getInt(DetailsQuery.SEASON_ID); String tvdbLink = TvdbLinks.episode(showTvdbSlug, showTvdbId, seasonTvdbId, episodeTvdbId); ViewTools.openUriOnClick(bindingBottom.buttonEpisodeTvdb, tvdbLink); ClipboardTools.copyTextToClipboardOnLongClick(bindingBottom.buttonEpisodeTvdb, tvdbLink); // trakt comments bindingBottom.buttonEpisodeComments.setOnClickListener(v -> { Intent intent = new Intent(requireActivity(), TraktCommentsActivity.class); intent.putExtras(TraktCommentsActivity.createInitBundleEpisode(episodeTitle, episodeTvdbId)); Utils.startActivityWithAnimation(requireActivity(), intent, v); }); } private void loadDetails() { // update trakt ratings if (ratingsTask == null || ratingsTask.getStatus() == AsyncTask.Status.FINISHED) { ratingsTask = new TraktRatingsTask(requireContext(), showTvdbId, episodeTvdbId, seasonNumber, episodeNumber); ratingsTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } } private void rateEpisode() { RateDialogFragment.newInstanceEpisode(episodeTvdbId) .safeShow(getContext(), getParentFragmentManager()); } private void shareEpisode() { if (episodeTitle == null || showTitle == null) { return; } ShareUtils.shareEpisode(requireActivity(), showTvdbSlug, showTvdbId, seasonTvdbId, episodeTvdbId, seasonNumber, episodeNumber, showTitle, episodeTitle); } private void loadImage(String imagePath, boolean hideDetails) { // immediately hide container if there is no image if (TextUtils.isEmpty(imagePath)) { binding.containerImage.setVisibility(View.GONE); return; } if (hideDetails) { // show image placeholder binding.imageviewScreenshot.setScaleType(ImageView.ScaleType.CENTER_INSIDE); binding.imageviewScreenshot.setImageResource(R.drawable.ic_photo_gray_24dp); } else { // try loading image binding.containerImage.setVisibility(View.VISIBLE); ServiceUtils.loadWithPicasso(requireContext(), TvdbImageTools.artworkUrl(imagePath)) .error(R.drawable.ic_photo_gray_24dp) .into(binding.imageviewScreenshot, new Callback() { @Override public void onSuccess() { binding.imageviewScreenshot .setScaleType(ImageView.ScaleType.CENTER_CROP); } @Override public void onError(Exception e) { binding.imageviewScreenshot .setScaleType(ImageView.ScaleType.CENTER_INSIDE); } } ); } } private LoaderManager.LoaderCallbacks<List<Action>> actionsLoaderCallbacks = new LoaderManager.LoaderCallbacks<List<Action>>() { @Override public Loader<List<Action>> onCreateLoader(int id, Bundle args) { int episodeTvdbId = args.getInt(KEY_EPISODE_TVDB_ID); return new EpisodeActionsLoader(requireContext(), episodeTvdbId); } @Override public void onLoadFinished(@NonNull Loader<List<Action>> loader, List<Action> data) { if (!isAdded()) { return; } if (data == null) { Timber.e("onLoadFinished: did not receive valid actions for %s", episodeTvdbId); } else { Timber.d("onLoadFinished: received %s actions for %s", data.size(), episodeTvdbId); } ActionsHelper.populateActions(requireActivity().getLayoutInflater(), requireActivity().getTheme(), bindingActions.containerEpisodeActions, data); } @Override public void onLoaderReset(@NonNull Loader<List<Action>> loader) { // do nothing, we are not holding onto the actions list } }; public void loadEpisodeActions() { Bundle args = new Bundle(); args.putInt(KEY_EPISODE_TVDB_ID, episodeTvdbId); LoaderManager.getInstance(this) .restartLoader(EpisodesActivity.ACTIONS_LOADER_ID, args, actionsLoaderCallbacks); } Runnable actionsRunnable = this::loadEpisodeActions; public void loadEpisodeActionsDelayed() { handler.removeCallbacks(actionsRunnable); handler.postDelayed(actionsRunnable, EpisodeActionsContract.ACTION_LOADER_DELAY_MILLIS); } interface DetailsQuery { String[] PROJECTION = new String[]{ Tables.EPISODES + "." + Episodes._ID, Episodes.NUMBER, Episodes.ABSOLUTE_NUMBER, Episodes.DVDNUMBER, Seasons.REF_SEASON_ID, Episodes.SEASON, Episodes.IMDBID, Episodes.TITLE, Episodes.OVERVIEW, Episodes.FIRSTAIREDMS, Episodes.DIRECTORS, Episodes.GUESTSTARS, Episodes.WRITERS, Episodes.IMAGE, Tables.EPISODES + "." + Episodes.RATING_GLOBAL, Episodes.RATING_VOTES, Episodes.RATING_USER, Episodes.WATCHED, Episodes.COLLECTED, Episodes.LAST_EDITED, Shows.REF_SHOW_ID, Shows.IMDBID, Shows.TITLE, Shows.RUNTIME, Shows.LANGUAGE, Shows.SLUG }; int _ID = 0; int NUMBER = 1; int NUMBER_ABSOLUTE = 2; int NUMBER_DVD = 3; int SEASON_ID = 4; int SEASON = 5; int IMDBID = 6; int TITLE = 7; int OVERVIEW = 8; int FIRST_RELEASE_MS = 9; int DIRECTORS = 10; int GUESTSTARS = 11; int WRITERS = 12; int IMAGE = 13; int RATING_GLOBAL = 14; int RATING_VOTES = 15; int RATING_USER = 16; int WATCHED = 17; int COLLECTED = 18; int LAST_EDITED = 19; int SHOW_ID = 20; int SHOW_IMDBID = 21; int SHOW_TITLE = 22; int SHOW_RUNTIME = 23; int SHOW_LANGUAGE = 24; int SHOW_SLUG = 25; } }
42.695937
104
0.663259
e7dd27ad9064d09a3ff1e499dbe4d71029ae2107
3,465
package org.example.ztree.utils; import org.example.ztree.domain.TreeNodeEntity; import org.example.ztree.dto.ZTreeJsonNode; import java.util.List; /** * Description : TODO(TreeNodeEntity -> ZTreeJsonNode 转换工具,注意非事物状态下,递归方法,返回值的写法) * Description : TODO(ztree 本身不提供节点排序功能,按照返回的节点顺序排序,所以需要待转换的 TreeNodeEntity 事先排好序) * User: h819 * Date: 2016/2/3 * Time: 13:38 * To change this template use File | Settings | File Templates. */ public class ZTreeUtils { private ZTreeUtils() { } /** * 把 TreeNodeEntity 类型转换为 ZTreeJsonNode 类型 * * @param treeNode 待转换的对象 * @return */ public static ZTreeJsonNode getJsonData(TreeNodeEntity treeNode) { ZTreeJsonNode parentTemp = new ZTreeJsonNode("temp"); //创建一个临时的变量,用于保存转换结果。 convertToJsonData(parentTemp, treeNode); return parentTemp.getChildren().get(0); // parentTemp 只有一个子元素,为待转换的 treeNode } /** * 把 TreeNodeEntity 类型转换为 ZTreeJsonNode 类型,并返回其子节点 * * @param treeNode 待转换的对象 * @return */ public static List<ZTreeJsonNode> getJsonDataChildren(TreeNodeEntity treeNode) { return getJsonData(treeNode).getChildren(); } /** * 根据已有的节点(可以有子节点),创建一个相同的新的节点。可以递归创建 * <p> * 该方法不能象 getJsonData() 方法一样,通过临时创建的 父对象返回,因为即使是临时创建 new ,在事务中也会创建表记录。 * * @param currentNode 已有节点,是数据库里一条数据,可以有子节点。在数据库中创建一个新的记录,如果有子节点,可以递归创建。在事务环境中,new 操作会自动创建表记录 * @param parent 已有节点的父节点,最终的结果是,parent 中新生成了一个新的和 currentNode 一样的子节点。parent 参数需要外部提供。 */ public static void createCopyNode(TreeNodeEntity parent, TreeNodeEntity currentNode) { //生成 currentNode 节点本身,在数据库中对应一条新的记录 TreeNodeEntity newTree = new TreeNodeEntity(currentNode.getType(), currentNode.getName(), currentNode.getIndex(), currentNode.isParentNode(), parent); newTree.setUrl(currentNode.getUrl()); newTree.setCss(currentNode.getCss()); parent.addChildToLastIndex(newTree); // 添加到所有子节点的尾部 parent.setParentNode(true); //生成 currentNode 节点的子节点 if (!currentNode.getChildren().isEmpty()) { for (TreeNodeEntity child : currentNode.getChildren()) createCopyNode(newTree, child); // 递归 } } /** * 把 TreeNodeEntity 类型转换为 ZTreeJsonNode 类型,把其值用 parent 带回 * * @param zTreeJsonNodeParentTemp 通过此参数,保存转换后的结果。因为利用了递归,可以通过参数传回转换后的结果 * @param treeNodeEntity 待转换的对象 */ private static void convertToJsonData(ZTreeJsonNode zTreeJsonNodeParentTemp, TreeNodeEntity treeNodeEntity) { if (treeNodeEntity == null || zTreeJsonNodeParentTemp == null) return; long id = treeNodeEntity.getId(); long pId = 0; if (!treeNodeEntity.isRoot()) pId = treeNodeEntity.getParent().getId(); // System.out.println(String.format("%d",pId)); String name = treeNodeEntity.getName(); String url = treeNodeEntity.getUrl(); boolean open = false; //展开有子节点的父节点 if (!treeNodeEntity.getChildren().isEmpty()) open = true; boolean isParent = treeNodeEntity.isParentNode(); ZTreeJsonNode zTreeNode = new ZTreeJsonNode(id, name, url, open, isParent); zTreeJsonNodeParentTemp.addChild(zTreeNode); if (!treeNodeEntity.getChildren().isEmpty()) for (TreeNodeEntity child : treeNodeEntity.getChildren()) convertToJsonData(zTreeNode, child); } }
31.788991
158
0.666955
365d77ec324d4ffc84ba8e4addea6daa6b965700
12,777
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.hyracks.algebricks.core.algebra.operators.logical; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.apache.commons.lang3.mutable.Mutable; import org.apache.commons.lang3.mutable.MutableObject; import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException; import org.apache.hyracks.algebricks.common.utils.Pair; import org.apache.hyracks.algebricks.core.algebra.base.ILogicalExpression; import org.apache.hyracks.algebricks.core.algebra.base.ILogicalOperator; import org.apache.hyracks.algebricks.core.algebra.base.ILogicalPlan; import org.apache.hyracks.algebricks.core.algebra.base.LogicalExpressionTag; import org.apache.hyracks.algebricks.core.algebra.base.LogicalOperatorTag; import org.apache.hyracks.algebricks.core.algebra.base.LogicalVariable; import org.apache.hyracks.algebricks.core.algebra.expressions.IVariableTypeEnvironment; import org.apache.hyracks.algebricks.core.algebra.expressions.VariableReferenceExpression; import org.apache.hyracks.algebricks.core.algebra.properties.TypePropagationPolicy; import org.apache.hyracks.algebricks.core.algebra.properties.VariablePropagationPolicy; import org.apache.hyracks.algebricks.core.algebra.typing.ITypeEnvPointer; import org.apache.hyracks.algebricks.core.algebra.typing.ITypingContext; import org.apache.hyracks.algebricks.core.algebra.typing.OpRefTypeEnvPointer; import org.apache.hyracks.algebricks.core.algebra.typing.PropagatingTypeEnvironment; import org.apache.hyracks.algebricks.core.algebra.visitors.ILogicalExpressionReferenceTransform; import org.apache.hyracks.algebricks.core.algebra.visitors.ILogicalOperatorVisitor; public class GroupByOperator extends AbstractOperatorWithNestedPlans { // If the LogicalVariable in a pair is null, it means that the GroupBy is // only grouping by the expression, without producing a new variable. private final List<Pair<LogicalVariable, Mutable<ILogicalExpression>>> gByList; private final List<Pair<LogicalVariable, Mutable<ILogicalExpression>>> decorList; // In decorList, if the variable (first member of the pair) is null, the // second member of the pair is variable reference which is propagated. private boolean groupAll = false; private boolean global = true; public GroupByOperator() { super(); gByList = new ArrayList<>(); decorList = new ArrayList<>(); } public GroupByOperator(List<Pair<LogicalVariable, Mutable<ILogicalExpression>>> groupByList, List<Pair<LogicalVariable, Mutable<ILogicalExpression>>> decorList, List<ILogicalPlan> nestedPlans) { this(groupByList, decorList, nestedPlans, false); } public GroupByOperator(List<Pair<LogicalVariable, Mutable<ILogicalExpression>>> groupByList, List<Pair<LogicalVariable, Mutable<ILogicalExpression>>> decorList, List<ILogicalPlan> nestedPlans, boolean groupAll) { super(nestedPlans); this.decorList = decorList; this.gByList = groupByList; this.groupAll = groupAll; checkGroupAll(groupAll); } public void addGbyExpression(LogicalVariable variable, ILogicalExpression expression) { this.gByList.add(new Pair<>(variable, new MutableObject<>(expression))); } public void addDecorExpression(LogicalVariable variable, ILogicalExpression expression) { this.decorList.add(new Pair<>(variable, new MutableObject<>(expression))); } @Override public LogicalOperatorTag getOperatorTag() { return LogicalOperatorTag.GROUP; } public List<Pair<LogicalVariable, Mutable<ILogicalExpression>>> getGroupByList() { return gByList; } public List<LogicalVariable> getGbyVarList() { List<LogicalVariable> varList = new ArrayList<>(gByList.size()); for (Pair<LogicalVariable, Mutable<ILogicalExpression>> ve : gByList) { ILogicalExpression expr = ve.second.getValue(); if (expr.getExpressionTag() == LogicalExpressionTag.VARIABLE) { VariableReferenceExpression v = (VariableReferenceExpression) expr; varList.add(v.getVariableReference()); } } return varList; } public static String veListToString(List<Pair<LogicalVariable, Mutable<ILogicalExpression>>> vePairList) { StringBuilder sb = new StringBuilder(); sb.append("["); boolean fst = true; for (Pair<LogicalVariable, Mutable<ILogicalExpression>> ve : vePairList) { if (fst) { fst = false; } else { sb.append("; "); } if (ve.first != null) { sb.append(ve.first + " := " + ve.second); } else { sb.append(ve.second.getValue()); } } sb.append("]"); return sb.toString(); } @Override public void recomputeSchema() { super.recomputeSchema(); for (Pair<LogicalVariable, Mutable<ILogicalExpression>> p : gByList) { schema.add(p.first); } for (Pair<LogicalVariable, Mutable<ILogicalExpression>> p : decorList) { schema.add(getDecorVariable(p)); } } @Override public void getProducedVariablesExceptNestedPlans(Collection<LogicalVariable> vars) { for (Pair<LogicalVariable, Mutable<ILogicalExpression>> p : gByList) { if (p.first != null) { vars.add(p.first); } } for (Pair<LogicalVariable, Mutable<ILogicalExpression>> p : decorList) { if (p.first != null) { vars.add(p.first); } } } @Override public void getUsedVariablesExceptNestedPlans(Collection<LogicalVariable> vars) { for (Pair<LogicalVariable, Mutable<ILogicalExpression>> g : gByList) { g.second.getValue().getUsedVariables(vars); } for (Pair<LogicalVariable, Mutable<ILogicalExpression>> g : decorList) { g.second.getValue().getUsedVariables(vars); } } @Override public VariablePropagationPolicy getVariablePropagationPolicy() { return new VariablePropagationPolicy() { @Override public void propagateVariables(IOperatorSchema target, IOperatorSchema... sources) throws AlgebricksException { for (Pair<LogicalVariable, Mutable<ILogicalExpression>> p : gByList) { ILogicalExpression expr = p.second.getValue(); if (p.first != null) { target.addVariable(p.first); } else { if (expr.getExpressionTag() != LogicalExpressionTag.VARIABLE) { throw new AlgebricksException("hash group-by expects variable references."); } VariableReferenceExpression v = (VariableReferenceExpression) expr; target.addVariable(v.getVariableReference()); } } for (Pair<LogicalVariable, Mutable<ILogicalExpression>> p : decorList) { ILogicalExpression expr = p.second.getValue(); if (expr.getExpressionTag() != LogicalExpressionTag.VARIABLE) { throw new AlgebricksException("pre-sorted group-by expects variable references."); } VariableReferenceExpression v = (VariableReferenceExpression) expr; LogicalVariable decor = v.getVariableReference(); if (p.first != null) { target.addVariable(p.first); } else { target.addVariable(decor); } } } }; } @Override public boolean acceptExpressionTransform(ILogicalExpressionReferenceTransform visitor) throws AlgebricksException { boolean b = false; for (Pair<LogicalVariable, Mutable<ILogicalExpression>> p : gByList) { if (visitor.transform(p.second)) { b = true; } } for (Pair<LogicalVariable, Mutable<ILogicalExpression>> p : decorList) { if (visitor.transform(p.second)) { b = true; } } return b; } @Override public <R, T> R accept(ILogicalOperatorVisitor<R, T> visitor, T arg) throws AlgebricksException { return visitor.visitGroupByOperator(this, arg); } public static LogicalVariable getDecorVariable(Pair<LogicalVariable, Mutable<ILogicalExpression>> p) { if (p.first != null) { return p.first; } else { VariableReferenceExpression e = (VariableReferenceExpression) p.second.getValue(); return e.getVariableReference(); } } public List<Pair<LogicalVariable, Mutable<ILogicalExpression>>> getDecorList() { return decorList; } @Override public IVariableTypeEnvironment computeOutputTypeEnvironment(ITypingContext ctx) throws AlgebricksException { int n = 0; for (ILogicalPlan p : nestedPlans) { n += p.getRoots().size(); } ITypeEnvPointer[] envPointers = new ITypeEnvPointer[n]; int i = 0; for (ILogicalPlan p : nestedPlans) { for (Mutable<ILogicalOperator> r : p.getRoots()) { envPointers[i] = new OpRefTypeEnvPointer(r, ctx); i++; } } IVariableTypeEnvironment env = new PropagatingTypeEnvironment(ctx.getExpressionTypeComputer(), ctx.getMissableTypeComputer(), ctx.getMetadataProvider(), TypePropagationPolicy.ALL, envPointers); ILogicalOperator child = inputs.get(0).getValue(); IVariableTypeEnvironment env2 = ctx.getOutputTypeEnvironment(child); for (Pair<LogicalVariable, Mutable<ILogicalExpression>> p : getGroupByList()) { ILogicalExpression expr = p.second.getValue(); if (p.first != null) { env.setVarType(p.first, env2.getType(expr)); if (expr.getExpressionTag() == LogicalExpressionTag.VARIABLE) { LogicalVariable v1 = ((VariableReferenceExpression) expr).getVariableReference(); env.setVarType(v1, env2.getVarType(v1)); } } else { VariableReferenceExpression vre = (VariableReferenceExpression) p.second.getValue(); LogicalVariable v2 = vre.getVariableReference(); env.setVarType(v2, env2.getVarType(v2)); } } for (Pair<LogicalVariable, Mutable<ILogicalExpression>> p : getDecorList()) { ILogicalExpression expr = p.second.getValue(); if (p.first != null) { env.setVarType(p.first, env2.getType(expr)); } else { VariableReferenceExpression vre = (VariableReferenceExpression) p.second.getValue(); LogicalVariable v2 = vre.getVariableReference(); env.setVarType(v2, env2.getVarType(v2)); } } return env; } public boolean isGroupAll() { return groupAll; } public void setGroupAll(boolean groupAll) { this.groupAll = groupAll; checkGroupAll(groupAll); } public boolean isGlobal() { return global; } public void setGlobal(boolean global) { this.global = global; } // The groupAll flag can only be set if group by columns are empty. private void checkGroupAll(boolean groupAll) { if (groupAll && !gByList.isEmpty()) { throw new IllegalStateException("Conflicting parameters for GROUP BY: there should be no GROUP BY keys " + "when the GROUP ALL flag is set to true"); } } }
42.029605
119
0.645378
db3f21ce7d1d5ea99505039027507555ded4afa4
8,823
package datawave.query.jexl.visitors; import datawave.data.type.Type; import datawave.query.config.ShardQueryConfiguration; import datawave.query.exceptions.DatawaveFatalQueryException; import datawave.query.exceptions.EmptyUnfieldedTermExpansionException; import datawave.query.jexl.JexlNodeFactory; import datawave.query.jexl.lookups.IndexLookup; import datawave.query.jexl.lookups.ShardIndexQueryTableStaticMethods; import datawave.query.jexl.nodes.QueryPropertyMarker; import datawave.query.tables.ScannerFactory; import datawave.query.util.MetadataHelper; import datawave.webservice.common.logging.ThreadConfigurableLogger; import datawave.webservice.query.exception.DatawaveErrorCode; import datawave.webservice.query.exception.NotFoundQueryException; import org.apache.accumulo.core.client.TableNotFoundException; import org.apache.commons.jexl2.parser.ASTAndNode; import org.apache.commons.jexl2.parser.ASTEQNode; import org.apache.commons.jexl2.parser.ASTERNode; import org.apache.commons.jexl2.parser.ASTGENode; import org.apache.commons.jexl2.parser.ASTGTNode; import org.apache.commons.jexl2.parser.ASTLENode; import org.apache.commons.jexl2.parser.ASTLTNode; import org.apache.commons.jexl2.parser.ASTNENode; import org.apache.commons.jexl2.parser.ASTNRNode; import org.apache.commons.jexl2.parser.ASTOrNode; import org.apache.commons.jexl2.parser.ASTReferenceExpression; import org.apache.commons.jexl2.parser.JexlNode; import org.apache.commons.jexl2.parser.JexlNodes; import org.apache.log4j.Logger; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Visits a Jexl tree, looks for unfielded terms, and replaces them with fielded terms from the index */ public class UnfieldedIndexExpansionVisitor extends RegexIndexExpansionVisitor { private static final Logger log = ThreadConfigurableLogger.getLogger(UnfieldedIndexExpansionVisitor.class); protected Set<String> expansionFields; protected Set<Type<?>> allTypes; // The constructor should not be made public so that we can ensure that the executor is setup and shutdown correctly protected UnfieldedIndexExpansionVisitor(ShardQueryConfiguration config, ScannerFactory scannerFactory, MetadataHelper helper) throws TableNotFoundException, IllegalAccessException, InstantiationException { super(config, scannerFactory, helper, null, "FieldNameIndexExpansion"); this.expansionFields = helper.getExpansionFields(config.getDatatypeFilter()); if (this.expansionFields == null) { this.expansionFields = new HashSet<>(); } this.allTypes = helper.getAllDatatypes(); } /** * Visits the Jexl script, looks for unfielded terms, and replaces them with fielded terms from the index * * @param config * the query configuration, not null * @param scannerFactory * the scanner factory, not null * @param helper * the metadata helper, not null * @param script * the Jexl script to expand, not null * @param <T> * the Jexl node type * @return a rebuilt Jexl tree with it's unfielded terms expanded * @throws IllegalAccessException * if we fail to retrieve all data types from the metadata helper * @throws TableNotFoundException * if we fail to retrieve fields from the metadata helper * @throws InstantiationException * if we fail to retrieve all data types from the metadata helper */ public static <T extends JexlNode> T expandUnfielded(ShardQueryConfiguration config, ScannerFactory scannerFactory, MetadataHelper helper, T script) throws IllegalAccessException, TableNotFoundException, InstantiationException { // if not expanding fields or values, then this is a noop if (config.isExpandFields() || config.isExpandValues()) { UnfieldedIndexExpansionVisitor visitor = new UnfieldedIndexExpansionVisitor(config, scannerFactory, helper); return ensureTreeNotEmpty(visitor.expand(script)); } else { return script; } } private static <T extends JexlNode> T ensureTreeNotEmpty(T script) throws EmptyUnfieldedTermExpansionException { if (script.jjtGetNumChildren() == 0) { NotFoundQueryException qe = new NotFoundQueryException(DatawaveErrorCode.NO_UNFIELDED_TERM_EXPANSION_MATCH); log.warn(qe); throw new EmptyUnfieldedTermExpansionException(qe); } return script; } @Override public Object visit(ASTOrNode node, Object data) { List<JexlNode> children = visitChildren(node, data); switch (children.size()) { case 0: return null; case 1: return children.get(0); default: return JexlNodeFactory.createUnwrappedOrNode(children); } } protected List<JexlNode> visitChildren(JexlNode node, Object data) { List<JexlNode> children = new ArrayList<>(); for (int i = 0; i < node.jjtGetNumChildren(); i++) { JexlNode newChild = (JexlNode) node.jjtGetChild(i).jjtAccept(this, data); // keep the child as long as it's not an empty AND/OR node if (newChild != null && !((newChild instanceof ASTOrNode || newChild instanceof ASTAndNode) && newChild.jjtGetNumChildren() == 0)) { children.add(newChild); } } return children; } @Override public Object visit(ASTAndNode node, Object data) { // ignore already marked expressions if (QueryPropertyMarker.findInstance(node).isAnyType()) { return node; } List<JexlNode> children = visitChildren(node, data); switch (children.size()) { case 0: return null; case 1: return children.get(0); default: return JexlNodeFactory.createUnwrappedAndNode(children); } } @Override public Object visit(ASTEQNode node, Object data) { return buildIndexLookup(node, true, negated, () -> createLookup(node)); } @Override public Object visit(ASTNENode node, Object data) { toggleNegation(); try { return buildIndexLookup(node, true, negated, () -> createLookup(node)); } finally { toggleNegation(); } } @Override public Object visit(ASTERNode node, Object data) { return buildIndexLookup(node, true, negated, () -> createLookup(node)); } @Override public Object visit(ASTNRNode node, Object data) { toggleNegation(); try { return buildIndexLookup(node, true, negated, () -> createLookup(node)); } finally { toggleNegation(); } } @Override public Object visit(ASTLTNode node, Object data) { return buildIndexLookup(node, true, negated, () -> createLookup(node)); } @Override public Object visit(ASTLENode node, Object data) { return buildIndexLookup(node, true, negated, () -> createLookup(node)); } @Override public Object visit(ASTGTNode node, Object data) { return buildIndexLookup(node, true, negated, () -> createLookup(node)); } @Override public Object visit(ASTGENode node, Object data) { return buildIndexLookup(node, true, negated, () -> createLookup(node)); } @Override public Object visit(ASTReferenceExpression node, Object data) { ASTReferenceExpression ref = (ASTReferenceExpression) super.visit(node, data); if (JexlNodes.children(ref).length == 0) { return null; } else { return ref; } } /** * Expand if we have an unfielded identifier * * @param node * the node to consider * @return true if contains an unfielded identifier */ @Override protected boolean shouldExpand(JexlNode node) { return (!negated || expandUnfieldedNegations) && hasUnfieldedIdentifier(node); } @Override protected IndexLookup createLookup(JexlNode node) { try { // Using the datatype filter when expanding this term isn't really // necessary return ShardIndexQueryTableStaticMethods.normalizeQueryTerm(node, config, scannerFactory, expansionFields, allTypes, helper, executor); } catch (TableNotFoundException e) { throw new DatawaveFatalQueryException(e); } } }
38.528384
152
0.665307
e71796490ab5a2838b142736b43f3f36b28879fe
1,172
package authoring_actionconditions; import java.util.Arrays; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.geometry.Orientation; import javafx.scene.control.Separator; /** * ActionConditionTabUtil--contains a few useful methods for doing things in the actionConditionTab * @author Owen Smith * */ public class ActionConditionTabUtil { private static final String SPLITTER = ","; /** * makeVerticalSeparator--makes a vertical separtor used in the vboxes and topHBox * @return */ protected static Separator makeVerticalSeparator() { Separator separator = new Separator(); separator.setOrientation(Orientation.VERTICAL); return separator; } /** * convertToObservableList--takes a comma separated string from resources and converts it into an observable list * @param resourceString--the resourceString that needs to be converted into an observable list * @return */ protected static ObservableList<String> convertToObservableList(String resourceString) { String[] optionsSplit = resourceString.split(SPLITTER); return FXCollections.observableList(Arrays.asList(optionsSplit)); } }
30.842105
114
0.78413
98b05b4ea8ff69562ff49fd0cbc9c0434933f101
1,214
package org.insightech.er.editor.controller.command.category; import org.insightech.er.editor.controller.command.AbstractCommand; import org.insightech.er.editor.model.ERDiagram; import org.insightech.er.editor.model.settings.CategorySetting; public class ChangeShowReferredTablesCommand extends AbstractCommand { private ERDiagram diagram; private boolean oldShowReferredTables; private boolean newShowReferredTables; private CategorySetting categorySettings; public ChangeShowReferredTablesCommand(ERDiagram diagram, boolean isShowReferredTables) { this.diagram = diagram; this.categorySettings = this.diagram.getDiagramContents().getSettings() .getCategorySetting(); this.newShowReferredTables = isShowReferredTables; this.oldShowReferredTables = this.categorySettings.isFreeLayout(); } /** * {@inheritDoc} */ @Override protected void doExecute() { this.categorySettings.setShowReferredTables(this.newShowReferredTables); this.diagram.changeAll(); } /** * {@inheritDoc} */ @Override protected void doUndo() { this.categorySettings.setShowReferredTables(this.oldShowReferredTables); this.diagram.changeAll(); } }
26.977778
75
0.766063
68ce48627f79fed73b39f782ae8a04efa0c1ec30
409
package com.upresent.user.service; import org.springframework.http.ResponseEntity; import org.springframework.web.multipart.MultipartFile; import com.upresent.user.exception.UserException; import java.io.IOException; public interface FileService { public String uploadUserImage(MultipartFile file) throws UserException; public ResponseEntity<byte[]> getUserImage(String filename) throws IOException; }
27.266667
80
0.836186
fa7e2ce24eb8db6a6d0c69f841f984e6f4f9cfd9
2,454
package org.echocat.kata.java.part1.items; import lombok.extern.slf4j.Slf4j; import org.echocat.kata.java.part1.authors.Author; import org.echocat.kata.java.part1.authors.AuthorRepository; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.Optional; @Slf4j public class ItemFactory { public static Item createBook(String[] data, AuthorRepository authorRepository) { //data format: title;isbn;authors;description String isbn = data[1]; Item item = createItem(isbn, data[0], ItemTypes.Book); item.setBookInformation(createBookInformation(data[3], isbn)); addAuthors(authorRepository, item, data[2]); return item; } public static Item createMagazine(String[] data, AuthorRepository authorRepository) { //data format: title;isbn;authors;publishedAt String isbn = data[1]; Item item = createItem(isbn, data[0], ItemTypes.Magazine); item.setMagazineInformation(createMagazineInformation(data[3], isbn)); addAuthors(authorRepository, item, data[2]); return item; } private static Item createItem(String isbn, String datum, ItemTypes book) { Item item = new Item(); item.setIsbn(isbn); item.setTitle(datum); item.setType(book); return item; } private static MagazineInformation createMagazineInformation(String datum, String isbn) { MagazineInformation magazineInformation = new MagazineInformation(); magazineInformation.setMagazineIsbn(isbn); magazineInformation.setPublishedAt(getDate(datum)); return magazineInformation; } private static LocalDate getDate(String date) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d.MM.yyyy"); return LocalDate.parse(date, formatter); } private static BookInformation createBookInformation(String datum, String isbn) { BookInformation bookInformation = new BookInformation(); bookInformation.setBookIsbn(isbn); bookInformation.setDescription(datum); return bookInformation; } private static void addAuthors(AuthorRepository authorRepository, Item item, String datum) { for (String authorEmail : datum.split(",")) { Optional<Author> author = authorRepository.findById(authorEmail); author.ifPresent(value -> item.getAuthors().add(value)); } } }
34.083333
96
0.698452
0b5c17a3933bfed70ed4ce34dc1a246743219a34
479
package com.ewyboy.worldspawn.json.objects; public class Spawn { private int min_y; private int max_y; public Spawn(int min_y, int max_y) { this.min_y = min_y; this.max_y = max_y; } public int getMin_y() { return min_y; } public void setMin_y(int min_y) { this.min_y = min_y; } public int getMax_y() { return max_y; } public void setMax_y(int max_y) { this.max_y = max_y; } }
16.517241
43
0.572025
72466494209077f4843bf6561d56888fb963e729
220
package com.github.thiagolocatelli.stripe.sample; public class ApplicationData { public static final String CLIENT_ID = ""; public static final String SECRET_KEY = ""; public static final String CALLBACK_URL = ""; }
27.5
49
0.768182
4d16357d3b2286c2212332b7d80c3fffc95babdd
535
package io.logz.guice.jersey.resources; import org.glassfish.jersey.server.ManagedAsync; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.container.AsyncResponse; import javax.ws.rs.container.Suspended; @Path(AsyncResource.PATH) public class AsyncResource { public static final String PATH = "async"; public static final String MESSAGE = "Async Response"; @GET @ManagedAsync public void asyncResource(@Suspended AsyncResponse asyncResponse) { asyncResponse.resume(MESSAGE); } }
23.26087
71
0.749533
2d15828b3a2e354986ada898f596040657de008b
6,556
package executor; import capstone.Capstone; import elfutils.Elf; import elfutils.SectionHeader; import pojos.AsmNode; import utils.Arithmetic; import utils.Logs; import utils.Mapping; import utils.SysUtils; import java.io.File; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class BinParser { public static ArrayList<AsmNode> parse(String inp) { Logs.infoLn(" + Analyzing " + inp + " ..."); try { Elf e = new Elf(new File(inp)); SectionHeader[] sections = e.sectionHeaders; int beginCodeSection = -1; int endCodeSection = -1; for (int i = 0; i < sections.length; i++) { SectionHeader sh = sections[i]; if (sh.getName().equals(".init")) beginCodeSection = i; if (sh.getName().equals(".fini")) endCodeSection = i; } byte[] totalByteArray = new byte[0]; for (int i = beginCodeSection; i <= endCodeSection; i++) { SectionHeader sh = sections[i]; ByteBuffer buff = e.getSection(sh); byte[] arr = new byte[buff.remaining()]; buff.get(arr); totalByteArray = SysUtils.concatByteArray(totalByteArray, arr); } return parse(totalByteArray); } catch (Exception ex) { Logs.infoLn("-> Cannot read header section. File might be corrupted."); return null; } } public static ArrayList<AsmNode> parse(byte[] bytes) { ArrayList<AsmNode> asmNodes = new ArrayList<>(); int label = 0; int instrSize = 4; for (int i = 0; (i + 3) < bytes.length; i += instrSize) { byte[] bs = {bytes[i], bytes[i + 1], bytes[i + 2], bytes[i + 3]}; Capstone cs = new Capstone(Capstone.CS_ARCH_ARM, Capstone.CS_MODE_ARM); Capstone.CsInsn[] insn = cs.disasm(bs, label); for (Capstone.CsInsn csInsn : insn) { String opcode = csInsn.mnemonic; String condSuffix = ""; if (opcode.length() >= 3) { String temp = opcode.substring(opcode.length() - 2); if (Mapping.condStrToChar.get(temp.toUpperCase()) != null) { condSuffix = temp; opcode = opcode.substring(0, opcode.length() - 2); } } boolean updateFlag = opcode.endsWith("s"); if (updateFlag) opcode = opcode.substring(0, opcode.length() - 1); StringBuilder params = new StringBuilder(); String[] paramsArr = csInsn.opStr.split("\\,"); for (int p = 0; p < paramsArr.length; p++) { params.append(paramsArr[p].trim()); if (p < paramsArr.length - 1) { params.append(","); } } AsmNode n = new AsmNode(String.valueOf(csInsn.address), opcode, condSuffix, params.toString(), updateFlag); asmNodes.add(n); label += instrSize; } } return asmNodes; } public static ArrayList<AsmNode> expand(ArrayList<AsmNode> asmNodes) { ArrayList<AsmNode> expandedNodes = new ArrayList<>(); for (AsmNode an : asmNodes) { String label = an.getLabel(); String opcode = an.getOpcode(); String condSuffix = an.getCondSuffix(); List<String> branches = Arrays.asList("b", "bx", "bl", "blx"); if (label != null && opcode != null && condSuffix != null && !condSuffix.equals("") && !branches.contains(opcode)) { AsmNode originNode = new AsmNode(an); originNode.setCondSuffix(""); String newOriginLabel = Integer.parseInt(label) + "-2"; originNode.setLabel(newOriginLabel); expandedNodes.add(originNode); expandedNodes.add(new AsmNode(label, "b", condSuffix, newOriginLabel, false)); expandedNodes.add(new AsmNode(Integer.parseInt(label) + "+2", "b", "", "0x" + Arithmetic.intToHex(Integer.parseInt(label) + 4), false)); } else { expandedNodes.add(an); } } return expandedNodes; } public static ArrayList<AsmNode> parseObjDump(String inp) { Logs.infoLn(" + Parsing " + inp + " ..."); String disassembleCmd = "arm-elf-objdump -D -b binary -marm "; String execResult = SysUtils.execCmd(disassembleCmd + inp); if (execResult == null) { Logs.infoLn("-> Parsing binary file error !"); return null; } String[] resultLines = execResult.split("\n"); ArrayList<AsmNode> asmNodes = new ArrayList<>(); for (String line : resultLines) { line = line.trim().replaceAll(" +", " "); if (line.contains(";")) { line = line.split("\\;")[0]; } if (line.contains("\t")) { line = line.replace("\t", " "); line = line.replaceAll(" +", " "); String[] parts = line.split("\\:"); String label = parts[0]; String[] contents = parts[1].split("\\s+"); if (contents.length > 3) { String opcode = contents[2]; String condSuffix = ""; if (opcode.length() >= 3) { String temp = opcode.substring(opcode.length() - 2); if (Mapping.condStrToChar.get(temp.toUpperCase()) != null) { condSuffix = temp; opcode = opcode.substring(0, opcode.length() - 2); } } StringBuilder params = new StringBuilder(); for (int i = 3; i < contents.length; i++) { params.append(contents[i]).append(" "); } boolean updateFlag = opcode.endsWith("s"); if (updateFlag) { opcode = opcode.substring(0, opcode.length() - 1); } AsmNode n = new AsmNode(label, opcode, condSuffix, params.toString().trim(), updateFlag); asmNodes.add(n); } } } return asmNodes; } }
42.571429
128
0.502288
0634cd1e3578967e646f98329643982b5d78b37f
1,703
package ir.ac.iust.dml.kg.knowledge.store.access.dao; import ir.ac.iust.dml.kg.knowledge.commons.PagingList; import ir.ac.iust.dml.kg.knowledge.store.access.entities.Triple; import ir.ac.iust.dml.kg.knowledge.store.access.entities.TripleState; import ir.ac.iust.dml.kg.knowledge.store.access.stats.KeyCount; import org.bson.types.ObjectId; import java.util.List; /** * Farsi Knowledge Graph Project * Iran University of Science and Technology (Year 2017) * Developed by HosseiN Khademi khaledi * * Interface for read and write triples */ @Deprecated public interface ITripleDao { void write(Triple... triples); void delete(Triple... triples); Triple read(ObjectId id); Triple read(String context, String subject, String predicate, String object); List<Triple> randomTripleForExpert(String notModule, String notExpert, int count); List<Triple> randomSubjectForExpert(String isSourceModule, String neModule, String neExpert, String subjectRegex, String subject, Integer size); PagingList<KeyCount> searchSubjectForExpert(String isSourceModule, String neModule, String neExpert, String subject, int page, int pageSize); PagingList<Triple> search(String context, String subject, String predicate, String object, int page, int pageSize); PagingList<Triple> search( String context, boolean useRegexForContext, String subject, boolean useRegexForSubject, String predicate, boolean useRegexForPredicate, String object, boolean useRegexForObject, int page, int pageSize); PagingList<Triple> read(TripleState state, Long after, int page, int pageSize); }
37.021739
145
0.734586
b4be0f2378dff03f244eedae9497acd8b00c569c
1,202
package ch.bernmobil.vibe.dataaccesslayer.converter; import com.google.gson.JsonObject; import org.junit.Test; import org.postgresql.util.PGobject; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; public class JsonObjectConverterTest { @Test public void pgObjectToJson() throws Exception { JsonObject expected = new JsonObject(); expected.addProperty("testProp", "value"); PGobject obj = new PGobject(); obj.setType("json"); obj.setValue(expected.toString()); JsonObjectConverter converter = new JsonObjectConverter(); JsonObject actual = converter.convertToEntityAttribute(obj); assertThat(actual, is(expected)); } @Test public void jsonToPgObject() throws Exception { JsonObject json = new JsonObject(); json.addProperty("testProp", "value"); PGobject expected = new PGobject(); expected.setType("json"); expected.setValue(json.toString()); JsonObjectConverter converter = new JsonObjectConverter(); PGobject actual = (PGobject)converter.convertToDatabaseColumn(json); assertThat(actual, is(expected)); } }
30.820513
76
0.688852
9d2f974cce84d22f0f291f1640d01bc0b00d4262
2,401
package com.ak.learning.blogsapp.models; import com.fasterxml.jackson.annotation.JsonIgnore; import javax.persistence.*; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.util.List; @Entity public class Author { @Id @GeneratedValue private Long id; @NotNull @Size(min = 1, max = 50) private String firstname; @NotNull @Size(min = 1, max = 50) private String lastname; @Size(min = 5, max = 50) @Column(unique = true, nullable = false) private String email; @Column(length = 1) private int deleted; @OneToMany(mappedBy = "author") @JsonIgnore private List<Post> posts; private Author() {} public Author(String firstname, String lastname) { this.firstname = firstname; this.lastname = lastname; } public Long getId() { return id; } public Author setId(Long id) { this.id = id; return this; } public String getFirstname() { return firstname; } public Author setFirstname(String firstname) { this.firstname = firstname; return this; } public String getLastname() { return lastname; } public Author setLastname(String lastname) { this.lastname = lastname; return this; } public List<Post> getPosts() { return posts; } public Author setPosts(List<Post> posts) { this.posts = posts; return this; } public String getEmail() { return email; } public Author setEmail(String email) { this.email = email; return this; } public int getDeleted() { return deleted; } public Author setDeleted(int deleted) { this.deleted = deleted; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Author author = (Author) o; if (id != null ? !id.equals(author.id) : author.id != null) return false; if (!firstname.equals(author.firstname)) return false; if (!lastname.equals(author.lastname)) return false; return email != null ? email.equals(author.email) : author.email == null; } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + firstname.hashCode(); result = 31 * result + lastname.hashCode(); result = 31 * result + (email != null ? email.hashCode() : 0); return result; } }
20.176471
77
0.650979
f525cfababaa83737d49e2fe8fcdf9f4391dd727
1,403
package com.tintinkung; public class Main { public static void main(String[] args) { /* * * MultiDiemsional Array * - Array with dimention */ int fallafel[][] = new int[4][5]; /* 5 column 4 rows [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] */ System.out.println("{1} = {"); for(int i = 0; i < 4; i++) { System.out.print("\t"); // for 1 row for(int k = 0; k < 5; k++) { fallafel[i][k] = (i + 1) + (100 * (k + 1)); System.out.print("[" + fallafel[i][k] + "] "); // in 1 5 columns } System.out.println(); } System.out.println("}"); /* 3 dimentional */ int fallefel[][][] = new int[6][4][5]; System.out.println("{2} = {"); for(int i = 0; i < 6; i++) { System.out.print("\t"); for(int j = 0; j < 4; j++) { System.out.print("\t"); for(int k = 0; k < 5; k++) { fallefel[i][j][k] = (i + 1) + (100 * (k + 1)); System.out.print("[" + fallefel[i][j][k] + "] "); } } System.out.println(); } System.out.println("}"); } }
26.471698
80
0.332145
6f5167ab8a5e3390ac5b694b125d115bc6852091
863
package top.lrshuai.nacos; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScans; import top.lrshuai.cloud.commons.annotation.EnableExceptionHandler; @ComponentScans(value = { @ComponentScan(value="top.lrshuai.shiro.**"), @ComponentScan(value = "top.lrshuai.cloud.commons.**") }) @EnableDiscoveryClient @SpringBootApplication @EnableFeignClients @EnableExceptionHandler public class ConsumerApplication { public static void main(String[] args) { SpringApplication.run(ConsumerApplication.class, args); } }
37.521739
72
0.812283
4d62193429e80ad855b8a9a15c9b75e122a1f76b
141
package ru.trickyfoxy.lab8.utils; import java.util.Locale; public interface LanguageSwitchble { void refreshLanguage(Locale locale); }
17.625
40
0.787234
5406b2a010027e22ad7c833caf071bda772c0749
10,213
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.datafactory.v2018_06_01; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; import com.microsoft.rest.serializer.JsonFlatten; import com.microsoft.azure.management.datafactory.v2018_06_01.implementation.LinkedServiceInner; /** * Linked service for MongoDb data source. */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", defaultImpl = MongoDbLinkedService.class) @JsonTypeName("MongoDb") @JsonFlatten public class MongoDbLinkedService extends LinkedServiceInner { /** * The IP address or server name of the MongoDB server. Type: string (or * Expression with resultType string). */ @JsonProperty(value = "typeProperties.server", required = true) private Object server; /** * The authentication type to be used to connect to the MongoDB database. * Possible values include: 'Basic', 'Anonymous'. */ @JsonProperty(value = "typeProperties.authenticationType") private MongoDbAuthenticationType authenticationType; /** * The name of the MongoDB database that you want to access. Type: string * (or Expression with resultType string). */ @JsonProperty(value = "typeProperties.databaseName", required = true) private Object databaseName; /** * Username for authentication. Type: string (or Expression with resultType * string). */ @JsonProperty(value = "typeProperties.username") private Object username; /** * Password for authentication. */ @JsonProperty(value = "typeProperties.password") private SecretBase password; /** * Database to verify the username and password. Type: string (or * Expression with resultType string). */ @JsonProperty(value = "typeProperties.authSource") private Object authSource; /** * The TCP port number that the MongoDB server uses to listen for client * connections. The default value is 27017. Type: integer (or Expression * with resultType integer), minimum: 0. */ @JsonProperty(value = "typeProperties.port") private Object port; /** * Specifies whether the connections to the server are encrypted using SSL. * The default value is false. Type: boolean (or Expression with resultType * boolean). */ @JsonProperty(value = "typeProperties.enableSsl") private Object enableSsl; /** * Specifies whether to allow self-signed certificates from the server. The * default value is false. Type: boolean (or Expression with resultType * boolean). */ @JsonProperty(value = "typeProperties.allowSelfSignedServerCert") private Object allowSelfSignedServerCert; /** * The encrypted credential used for authentication. Credentials are * encrypted using the integration runtime credential manager. Type: string * (or Expression with resultType string). */ @JsonProperty(value = "typeProperties.encryptedCredential") private Object encryptedCredential; /** * Get the IP address or server name of the MongoDB server. Type: string (or Expression with resultType string). * * @return the server value */ public Object server() { return this.server; } /** * Set the IP address or server name of the MongoDB server. Type: string (or Expression with resultType string). * * @param server the server value to set * @return the MongoDbLinkedService object itself. */ public MongoDbLinkedService withServer(Object server) { this.server = server; return this; } /** * Get the authentication type to be used to connect to the MongoDB database. Possible values include: 'Basic', 'Anonymous'. * * @return the authenticationType value */ public MongoDbAuthenticationType authenticationType() { return this.authenticationType; } /** * Set the authentication type to be used to connect to the MongoDB database. Possible values include: 'Basic', 'Anonymous'. * * @param authenticationType the authenticationType value to set * @return the MongoDbLinkedService object itself. */ public MongoDbLinkedService withAuthenticationType(MongoDbAuthenticationType authenticationType) { this.authenticationType = authenticationType; return this; } /** * Get the name of the MongoDB database that you want to access. Type: string (or Expression with resultType string). * * @return the databaseName value */ public Object databaseName() { return this.databaseName; } /** * Set the name of the MongoDB database that you want to access. Type: string (or Expression with resultType string). * * @param databaseName the databaseName value to set * @return the MongoDbLinkedService object itself. */ public MongoDbLinkedService withDatabaseName(Object databaseName) { this.databaseName = databaseName; return this; } /** * Get username for authentication. Type: string (or Expression with resultType string). * * @return the username value */ public Object username() { return this.username; } /** * Set username for authentication. Type: string (or Expression with resultType string). * * @param username the username value to set * @return the MongoDbLinkedService object itself. */ public MongoDbLinkedService withUsername(Object username) { this.username = username; return this; } /** * Get password for authentication. * * @return the password value */ public SecretBase password() { return this.password; } /** * Set password for authentication. * * @param password the password value to set * @return the MongoDbLinkedService object itself. */ public MongoDbLinkedService withPassword(SecretBase password) { this.password = password; return this; } /** * Get database to verify the username and password. Type: string (or Expression with resultType string). * * @return the authSource value */ public Object authSource() { return this.authSource; } /** * Set database to verify the username and password. Type: string (or Expression with resultType string). * * @param authSource the authSource value to set * @return the MongoDbLinkedService object itself. */ public MongoDbLinkedService withAuthSource(Object authSource) { this.authSource = authSource; return this; } /** * Get the TCP port number that the MongoDB server uses to listen for client connections. The default value is 27017. Type: integer (or Expression with resultType integer), minimum: 0. * * @return the port value */ public Object port() { return this.port; } /** * Set the TCP port number that the MongoDB server uses to listen for client connections. The default value is 27017. Type: integer (or Expression with resultType integer), minimum: 0. * * @param port the port value to set * @return the MongoDbLinkedService object itself. */ public MongoDbLinkedService withPort(Object port) { this.port = port; return this; } /** * Get specifies whether the connections to the server are encrypted using SSL. The default value is false. Type: boolean (or Expression with resultType boolean). * * @return the enableSsl value */ public Object enableSsl() { return this.enableSsl; } /** * Set specifies whether the connections to the server are encrypted using SSL. The default value is false. Type: boolean (or Expression with resultType boolean). * * @param enableSsl the enableSsl value to set * @return the MongoDbLinkedService object itself. */ public MongoDbLinkedService withEnableSsl(Object enableSsl) { this.enableSsl = enableSsl; return this; } /** * Get specifies whether to allow self-signed certificates from the server. The default value is false. Type: boolean (or Expression with resultType boolean). * * @return the allowSelfSignedServerCert value */ public Object allowSelfSignedServerCert() { return this.allowSelfSignedServerCert; } /** * Set specifies whether to allow self-signed certificates from the server. The default value is false. Type: boolean (or Expression with resultType boolean). * * @param allowSelfSignedServerCert the allowSelfSignedServerCert value to set * @return the MongoDbLinkedService object itself. */ public MongoDbLinkedService withAllowSelfSignedServerCert(Object allowSelfSignedServerCert) { this.allowSelfSignedServerCert = allowSelfSignedServerCert; return this; } /** * Get the encrypted credential used for authentication. Credentials are encrypted using the integration runtime credential manager. Type: string (or Expression with resultType string). * * @return the encryptedCredential value */ public Object encryptedCredential() { return this.encryptedCredential; } /** * Set the encrypted credential used for authentication. Credentials are encrypted using the integration runtime credential manager. Type: string (or Expression with resultType string). * * @param encryptedCredential the encryptedCredential value to set * @return the MongoDbLinkedService object itself. */ public MongoDbLinkedService withEncryptedCredential(Object encryptedCredential) { this.encryptedCredential = encryptedCredential; return this; } }
34.271812
189
0.687359
7f81cb1f57cf99598f1821980cab61bd73ba3164
1,345
package sk.upjs.ics.paz1c.nemocnica; import java.util.Scanner; public class Lekar { private int id; private String meno; private String priezvisko; private String specializacia; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getMeno() { return meno; } public void setMeno(String meno) { this.meno = meno; } public String getPriezvisko() { return priezvisko; } public void setPriezvisko(String priezvisko) { this.priezvisko = priezvisko; } public String getSpecializacia() { return specializacia; } public void setSpecializacia(String specializacia) { this.specializacia = specializacia; } @Override public String toString() { return meno + " " + priezvisko + " " +specializacia; } /* public String toFileLine() { return id + "\t" + menoL + "\t" + priezviskoL + "\t" + specializacia; } public Lekar(String fileLine) { Scanner sc = new Scanner(fileLine); sc.useDelimiter("\t"); id = sc.nextInt(); menoL = sc.next(); priezviskoL = sc.next(); specializacia = sc.next(); } */ }
22.04918
78
0.547955
4de28384bb7f6565142a4a5c1e5808cc388679df
1,767
// Generated by esidl 0.4.0. package org.w3c.dom.html; import org.w3c.dom.Document; public interface HTMLObjectElement extends HTMLElement { // HTMLObjectElement public String getData(); public void setData(String data); public String getType(); public void setType(String type); public boolean getTypeMustMatch(); public void setTypeMustMatch(boolean typeMustMatch); public String getName(); public void setName(String name); public String getUseMap(); public void setUseMap(String useMap); public HTMLFormElement getForm(); public String getWidth(); public void setWidth(String width); public String getHeight(); public void setHeight(String height); public Document getContentDocument(); public Window getContentWindow(); public boolean getWillValidate(); public ValidityState getValidity(); public String getValidationMessage(); public boolean checkValidity(); public void setCustomValidity(String error); // HTMLObjectElement-27 public String getAlign(); public void setAlign(String align); public String getArchive(); public void setArchive(String archive); public String getBorder(); public void setBorder(String border); public String getCode(); public void setCode(String code); public String getCodeBase(); public void setCodeBase(String codeBase); public String getCodeType(); public void setCodeType(String codeType); public boolean getDeclare(); public void setDeclare(boolean declare); public int getHspace(); public void setHspace(int hspace); public String getStandby(); public void setStandby(String standby); public int getVspace(); public void setVspace(int vspace); }
32.722222
56
0.72326
888f16653950811bf223384f4a5d0889bc8c3efc
8,975
package org.seng302.project.web_layer.controller; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.NullAndEmptySource; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import org.seng302.project.AbstractInitializer; import org.seng302.project.repository_layer.model.User; import org.seng302.project.repository_layer.repository.UserRepository; import org.seng302.project.service_layer.dto.keyword.AddKeywordDTO; import org.seng302.project.service_layer.dto.keyword.AddKeywordResponseDTO; import org.seng302.project.service_layer.exceptions.NotAcceptableException; import org.seng302.project.service_layer.service.KeywordService; import org.seng302.project.web_layer.authentication.AppUserDetails; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; 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.RequestBuilder; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import java.util.List; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** * Test class for performing unit tests for the KeywordController class and its methods. */ @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @AutoConfigureMockMvc class KeywordControllerTest extends AbstractInitializer { @Autowired private ObjectMapper objectMapper; @Autowired private MockMvc mockMvc; @MockBean private KeywordService keywordService; private User testUser; @MockBean private UserRepository userRepository; /** * Initialises entities from AbstractInitializer */ @BeforeEach void setup() { this.initialise(); testUser = this.getTestUser(); // Mock user repository to return the logged in user when(userRepository.findByEmail(getTestUser().getEmail())).thenReturn(List.of(getTestUser())); when(userRepository.findByEmail(getTestSystemAdmin().getEmail())).thenReturn(List.of(getTestSystemAdmin())); } /** * Tests that attempting to add a new keyword when not logged in results in a 401 response. */ @Test void addKeyword_notLoggedIn_returnStatus401() throws Exception { AddKeywordDTO dto = new AddKeywordDTO("test-keyword"); RequestBuilder request = MockMvcRequestBuilders .post("/keywords") .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(dto)) .accept(MediaType.APPLICATION_JSON); mockMvc.perform(request) .andExpect(status().isUnauthorized()); } /** * Tests that attempting to add a keyword with invalid name results in a 400 response. */ @ParameterizedTest @NullAndEmptySource @ValueSource(strings = {"kw", "KeywordKeywordKeywordKeywordKeyword"}) void addKeyword_invalidName_returnStatus400(String string) throws Exception { AddKeywordDTO dto = new AddKeywordDTO(string); RequestBuilder request = MockMvcRequestBuilders .post("/keywords") .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(dto)) .accept(MediaType.APPLICATION_JSON) .with(user(new AppUserDetails(testUser))); mockMvc.perform(request) .andExpect(status().isBadRequest()); } /** * Tests that attempting to add a valid keyword results in success. */ @Test void addKeyword_validKeyword_success() throws Exception { Mockito.when(keywordService.addKeyword(Mockito.any(String.class))) .thenReturn(new AddKeywordResponseDTO(1)); AddKeywordDTO dto = new AddKeywordDTO("new-keyword"); RequestBuilder request = MockMvcRequestBuilders .post("/keywords") .content(objectMapper.writeValueAsString(dto)) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .with(user(new AppUserDetails(testUser))); mockMvc.perform(request) .andExpect(status().isCreated()); } /** * Tests that we get a 200 response when searching for keywords */ @Test void keywordSearch_success200() throws Exception { RequestBuilder searchKeywordRequest = MockMvcRequestBuilders .get("/keywords/search?searchQuery=fruit") .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .with(user(new AppUserDetails(getTestUser()))); mockMvc.perform(searchKeywordRequest) .andExpect(MockMvcResultMatchers.status().isOk()); } /** * Tests that we get a 401 response when searching for keywords, * and not logged in */ @Test void keywordSearch_notLoggedIn401() throws Exception { RequestBuilder searchKeywordRequest = MockMvcRequestBuilders .get("/keywords/search?searchQuery=fruit") .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON); mockMvc.perform(searchKeywordRequest) .andExpect(MockMvcResultMatchers.status().isUnauthorized()); } /** * Tests we get a 401 response when deleting and not logged in */ @Test void deleteKeyword_notLoggedIn401() throws Exception { mockMvc.perform(MockMvcRequestBuilders .delete("/keywords/1")) .andExpect(MockMvcResultMatchers.status().isUnauthorized()); } /** * Tests we get a 403 response when a non admin makes the request */ @Test void deleteKeyword_nonAdmin403() throws Exception { mockMvc.perform(MockMvcRequestBuilders .delete("/keywords/1") .with(user(new AppUserDetails(getTestUser())))) .andExpect(MockMvcResultMatchers.status().isForbidden()); } /** * Tests we get a 400 response when given a non numeric id */ @Test void deleteKeyword_nonNumericId400() throws Exception { mockMvc.perform(MockMvcRequestBuilders .delete("/keywords/hi") .with(user(new AppUserDetails(getTestSystemAdmin())))) .andExpect(MockMvcResultMatchers.status().isBadRequest()); } /** * Tests we get a 406 response when the keyword doesn't exist */ @Test void deleteKeyword_nonExistentId406() throws Exception { // Mock keyword service to throw a NotAcceptableException doThrow(NotAcceptableException.class) .when(keywordService) .deleteKeyword(any(Integer.class)); mockMvc.perform(MockMvcRequestBuilders .delete("/keywords/1") .with(user(new AppUserDetails(getTestSystemAdmin())))) .andExpect(MockMvcResultMatchers.status().isNotAcceptable()); } /** * Tests we get a 200 response when an existent keyword is provided */ @Test void deleteKeyword_existentId200() throws Exception { mockMvc.perform(MockMvcRequestBuilders .delete("/keywords/1") .with(user(new AppUserDetails(getTestSystemAdmin())))) .andExpect(MockMvcResultMatchers.status().isOk()); } /** * Tests the deleteKeyword method on the keywordService is called when an existent keyword is provided */ @Test void deleteKeyword_existentId_callsDeleteMethod() throws Exception { mockMvc.perform(MockMvcRequestBuilders .delete("/keywords/1") .with(user(new AppUserDetails(getTestSystemAdmin())))); // Capture the integer passed to the keywordService deleteKeyword method ArgumentCaptor<Integer> cardArgumentCaptor = ArgumentCaptor.forClass(Integer.class); verify(keywordService).deleteKeyword(cardArgumentCaptor.capture()); Integer keywordId = cardArgumentCaptor.getValue(); // Check the id passed to the service was correct Assertions.assertEquals(1, keywordId); } }
37.869198
116
0.692925
c6f2f7be9ff00bdc7d7f1b1c1e2242223850d784
4,193
package net.sqs2.omr.result.servlet.writer; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import net.sqs2.omr.master.FormMaster; import net.sqs2.omr.model.MarkAreaAnswer; import net.sqs2.omr.model.MarkAreaAnswerItem; import net.sqs2.omr.model.PageAreaResult; import net.sqs2.omr.model.Row; import net.sqs2.omr.model.TextAreaAnswer; import net.sqs2.omr.result.context.ResultBrowserContext; import org.apache.commons.codec.binary.Base64; public abstract class FormAreaContentsJSONWriter extends SimpleContentsWriter { protected boolean isMSIE; protected PrintWriter w; protected boolean hasStartedRow = false; public FormAreaContentsJSONWriter(PrintWriter w, ResultBrowserContext contentSelection) throws IOException { super(sessionSource); this.w = w; } void printRowSeparator() { if (this.hasStartedRow) { this.w.print(','); } else { this.hasStartedRow = true; } } protected String createQueryParamString(int masterIndex, int tableIndex, int rowIndex, int columnIndex) { StringBuilder sb = new StringBuilder(); sb.append("/i?m="); sb.append(masterIndex); sb.append("&t="); sb.append(tableIndex); sb.append("&r="); sb.append(rowIndex); sb.append("&q="); sb.append(columnIndex); sb.append("&sid="); sb.append(this.sessionSource.getSessionID()); return sb.toString(); } public void writeMarkAreaAnswer(MarkAreaAnswer markAreaAnswer, List<PageAreaResult> pageAreaResultListParRow, int formAreaIndex, String queryParamString, float densityThreshold) { if (pageAreaResultListParRow == null) { this.w.print("{}"); } MarkAreaAnswerItem[] itemArray = markAreaAnswer.getMarkAreaAnswerItemArray(); this.w.print("{"); if (markAreaAnswer.isManualMode()) { this.w.print("'M':1,"); } this.w.print("'i':["); boolean hasMarkAreaPrinted = false; int itemIndex = 0; int numMarked = 0; for (MarkAreaAnswerItem item : itemArray) { if (hasMarkAreaPrinted) { this.w.print(','); } else { hasMarkAreaPrinted = true; } if (item == null) { this.w.print("{d:1}"); continue; } this.w.print("{"); if (markAreaAnswer.isManualMode()) { if (item.isManualSelected()) { this.w.print("'M':1,"); } else { this.w.print("'M':0,"); } } PageAreaResult pageAreaResult = pageAreaResultListParRow.get(formAreaIndex); if (pageAreaResult != null) { this.w.print("s:\'"); if (this.isMSIE) { this.w.print(queryParamString); this.w.print("&i="); this.w.print(itemIndex); } else { writeBase64Data(this.w, pageAreaResult); } this.w.print("',"); } this.w.print("d:"); if (item.getDensity() < densityThreshold) { numMarked++; } this.w.print(item.getDensity()); this.w.print("}"); formAreaIndex++; itemIndex++; } this.w.print("]}"); } protected void writeTextAreaAnswer(TextAreaAnswer textAreaAnswer, List<PageAreaResult> pageAreaResultList, int formAreaIndex, String queryParamString) { String value = textAreaAnswer.getValue(); this.w.print("{"); if (value != null) { this.w.print("v:'"); this.w.print(value.replace("'", "\\'")); this.w.print("',"); } else { this.w.print("v:null,"); } this.w.print("s:\'"); if (this.isMSIE) { this.w.print(queryParamString); } else { writeBase64Data(this.w, pageAreaResultList.get(formAreaIndex)); } this.w.print("'"); this.w.print("}"); } void writeBase64Data(PrintWriter w, PageAreaResult pageAreaResult) { String type = pageAreaResult.getImageType(); byte[] bytes = pageAreaResult.getImageByteArray(); if (bytes == null) { return; } this.w.print("data:image/"); this.w.print(type); this.w.print(";base64,"); for (byte b : Base64.encodeBase64(bytes)) { this.w.write(b); } } protected void startRow() { this.w.print("[");// start row } protected void endRow() { this.w.print("]");// end row } protected boolean isErrorRow(FormMaster master, Row row, List<PageAreaResult> pageAreaResultListParRow) { // pageAreaResultListParRow.size() != master.getFormAreaList().size() // || row == null || return row == null || row.getTaskErrorMultiHashMap() != null; } }
26.537975
180
0.676604
40372164c28b1719cd2518c571e450eb5075fc5d
100
package com.github.steveice10.mc.protocol.data.game.values.entity; public interface ObjectData { }
20
66
0.81