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
44b8f4d19c594a96a170b5af7bcc1fc050aaccbf
1,020
package org.seckill.dao; import org.junit.Test; import org.junit.runner.RunWith; import org.seckill.entity.SuccessKilled; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.annotation.Resource; import static org.junit.Assert.*; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"classpath:spring/spring-dao.xml"}) public class SuccessKillDaoTest { @Resource private SuccessKillDao successKillDao; @Test public void insertSuccessKilled() { long id = 1000L; long phone = 15811049556L; int insertCount = successKillDao.insertSuccessKilled(id, phone); System.out.println("insertCount = " + insertCount); } @Test public void queryByIdWithSeckill() { long id= 1000L; long phone = 15811049556L; SuccessKilled successKilled = successKillDao.queryByIdWithSeckill(id, phone); System.out.println(successKilled); System.out.println(successKilled.getSeckill()); } }
28.333333
81
0.770588
a10f73d403e1b3b1bc4f8ccec5974ee1a81b0f32
5,393
/* * Copyright 2010 Fae Hutter * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package net.sparktank.glyph.model; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import net.sparktank.glyph.Activator; import net.sparktank.glyph.helpers.ClassPathHelper; import net.sparktank.glyph.helpers.ClassPathHelper.FileProcessor; import org.osgi.framework.Bundle; public class QuestionHelper { // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - private static final String GLYPH_EXT = ".glyph"; private static final String GROUP = "group="; private static final String COMMENT = "#"; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /** * Search for .glyph files and parse them. * Search this bundle and the system classpath. */ static public Collection<QuestionGroup> getAllQuestionGroups () throws IOException { final List<QuestionGroup> ret = new LinkedList<QuestionGroup>(); Bundle bundle = Activator.getDefault().getBundle(); @SuppressWarnings("unchecked") Enumeration<URL> entries = bundle.findEntries("/", "*" + GLYPH_EXT, true); while (entries.hasMoreElements()) { URL element = entries.nextElement(); InputStream is = element.openStream(); ret.addAll(loadData(new BufferedReader(new InputStreamReader(is)))); } ClassPathHelper.searchAndProcessFiles(new FileProcessor() { @Override public boolean acceptFile(File file) { return file.getName().toLowerCase().endsWith(GLYPH_EXT); } @Override public boolean acceptFile(String filename) { return filename.toLowerCase().endsWith(GLYPH_EXT); } @Override public void procFile(File file) { try { ret.addAll(loadData(file)); } catch (IOException e) { throw new RuntimeException(e); } } @Override public void procStream(InputStream is) { try { ret.addAll(loadData(new BufferedReader(new InputStreamReader(is)))); } catch (IOException e) { throw new RuntimeException(e); } } }); Collections.sort(ret, new Comparator<QuestionGroup>() { @Override public int compare(QuestionGroup o1, QuestionGroup o2) { return o1.getSymbolicName().compareTo(o2.getSymbolicName()); }; }); return Collections.unmodifiableCollection(ret); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - static Collection<QuestionGroup> loadData (File dataFile) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(dataFile)); return loadData(reader); } /** * This method will close the stream when it is finished with it. * @param reader * @return * @throws IOException */ static Collection<QuestionGroup> loadData (BufferedReader reader) throws IOException { List<String> groupLines = new LinkedList<String>(); List<String> dataLines = new LinkedList<String>(); String line = null; try { while ((line = reader.readLine()) != null) { if (line.length() > 0) { if (line.startsWith(GROUP)) { groupLines.add(line); } else if (!line.startsWith(COMMENT) && line.contains("=")) { dataLines.add(line); } } } } finally { reader.close(); } Map<String, QuestionGroup> questionGroups = new HashMap<String, QuestionGroup>(); int groupFlagLength = GROUP.length(); for (String groupLine : groupLines) { String groupData = groupLine.substring(groupFlagLength); String[] parts = groupData.split("\\|"); if (parts.length < 2) throw new IllegalArgumentException("Data line is manformed: '"+groupData+"'."); QuestionGroup qg = new QuestionGroup(parts[0], parts[1]); questionGroups.put(qg.getSymbolicName(), qg); } for (String dataLine : dataLines) { int x = dataLine.indexOf("="); if (x > 0) { String questionData = dataLine.substring(x+1); String[] parts = questionData.split("\\|"); if (parts.length >= 2) { String questionGroupSymbol = dataLine.substring(0, x); QuestionGroup questionGroup = questionGroups.get(questionGroupSymbol); if (questionGroup != null) { Collection<String> answers = new LinkedList<String>(); for (int i = 1; i < parts.length; i++) { answers.add(parts[i]); } Question question = new Question(parts[0], answers); questionGroup.addQuestion(question); } } } } return questionGroups.values(); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
30.128492
104
0.652327
5f75c53fccf5a5d6400ac720cdbb3ec75302cc7d
1,977
package com.goo.dal.domain; import org.springframework.data.annotation.CreatedBy; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedBy; import org.springframework.data.annotation.LastModifiedDate; import javax.persistence.*; import java.time.ZonedDateTime; /** * Created by DongPT1 on 6/16/2017. */ public class AbstractEntity { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Version @Column(columnDefinition = "int default 1", nullable = false) private Long version = 1L; @CreatedBy @Column(name = "created_by_id") private Long createdBy; @CreatedDate private ZonedDateTime createdDate; @LastModifiedBy @Column(name = "last_modified_by_id") private Long lastModifiedBy; @LastModifiedDate private ZonedDateTime lastModifiedDate; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getVersion() { return version; } public void setVersion(Long version) { this.version = version; } public Long getCreatedBy() { return createdBy; } public void setCreatedBy(Long createdBy) { this.createdBy = createdBy; } public ZonedDateTime getCreatedDate() { return createdDate; } public void setCreatedDate(ZonedDateTime createdDate) { this.createdDate = createdDate; } public Long getLastModifiedBy() { return lastModifiedBy; } public void setLastModifiedBy(Long lastModifiedBy) { this.lastModifiedBy = lastModifiedBy; } public ZonedDateTime getLastModifiedDate() { return lastModifiedDate; } public void setLastModifiedDate(ZonedDateTime lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; } }
22.988372
70
0.655033
b5da52c61e359dd03cb3d0938d82740de7b76183
3,541
/* * Copyright 2012 Jim Guistwite * * 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.jgui.ttscrape; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.HashMap; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The <code>TextualShowWriter</code> writes shows to a results * folder flagged by the post processors. * * @author jguistwite */ public class TextualShowWriter implements ShowWriter { private Logger logger = LoggerFactory.getLogger(TextualShowWriter.class); private HashMap<String, Writer> writers; class Writer { public FileWriter writer; public boolean includeSubtitle; public Writer(String name, boolean includeSubtitle) throws IOException { File f = new File("results/" + name + ".txt"); f.getParentFile().mkdirs(); writer = new FileWriter(f); this.includeSubtitle = includeSubtitle; } } public TextualShowWriter() { writers = new HashMap<String, Writer>(); } @Override public void establishWriter(String writerName, boolean includeSubtitle) { try { Writer writer = new Writer(writerName, includeSubtitle); writers.put(writerName, writer); } catch (IOException ex) { logger.error("failed to establish writer", ex); } } @Override public void closeWriter(String writerName) { try { Writer w = writers.get(writerName); if (w != null) { w.writer.close(); } } catch (IOException ex) { } } /** * Append the show the show file. Write the title, subtitle * rating and date/time. * @param writerName name of the writer previously established * @param s show to be written. */ @Override public void writeShow(String writerName, Show s) { try { Writer w = writers.get(writerName); if (w == null) { logger.error("writer {} not found", writerName); } else { StringBuffer sb = new StringBuffer(); int titlePad = 35; String str = s.getTitle(); if (s.getStars() > 0) { str = str + " (" + s.getStars() + ")"; } if (w.includeSubtitle && (s.getSubtitle() != null)) { str = str + " " + s.getSubtitle(); titlePad += 10; } sb.append(StringUtils.rightPad(str, titlePad)); sb.append("\t"); DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm"); sb.append(StringUtils.rightPad(df.format(s.getStartTime()), 20)); sb.append("\t"); sb.append(s.getChannelName() + " " + s.getChannelNumber()); w.writer.write(sb.toString()); w.writer.write("\n"); if (w.includeSubtitle) { // write an extra newline to separate w.writer.write("\n"); } w.writer.flush(); } } catch (IOException ex) { logger.error("failed to write", ex); } } }
27.664063
76
0.637391
d71694bdd484e87c0e4655ea122bcfc0dcc5210f
5,407
package com.chain.ds.deque; import java.util.ConcurrentModificationException; import java.util.NoSuchElementException; import com.chain.ds.Iterator; /** * 链表双端队列 * * @author Chain * * @param <E> */ public class LinkedDeque<E> extends AbstractDeque<E> { // 没有额外的控制节点 private DequeNode headNode; private DequeNode tailNode; private int count; @Override public boolean offerFirst(E e) { if (isEmpty()) { initDeque(e); return true; } DequeNode node = new DequeNode(e); headNode.prevNode = node; node.nextNode = headNode; headNode = node; count++; return true; } private void initDeque(E e) { DequeNode node = new DequeNode(e); headNode = tailNode = node; count++; } // Deque中的pollFirst相当于Queue中的poll @Override public E pollFirst() { return poll(); } // Deque中的peekFirst相当于Queue中的peek @Override public E peekFirst() { return peek(); } // Deque中的offerLast相当于Queue中的offer @Override public boolean offerLast(E e) { return offer(e); } @Override public E pollLast() { if (isEmpty()) return null; E value = tailNode.value; tailNode = tailNode.prevNode; if (tailNode != null) tailNode.nextNode = null; count--; if (isEmpty()) { headNode = null; tailNode = null; } return value; } @Override public E peekLast() { if (isEmpty()) return null; E value = tailNode.value; return value; } @Override public boolean offer(E e) { if (isEmpty()) { initDeque(e); return true; } DequeNode node = new DequeNode(e); tailNode.nextNode = node; node.prevNode = tailNode; tailNode = node; count++; return true; } @Override public E poll() { if (isEmpty()) return null; E value = headNode.value; headNode = headNode.nextNode; if (headNode != null) headNode.prevNode = null; count--; if (isEmpty()) { headNode = null; tailNode = null; } return value; } @Override public E peek() { if (isEmpty()) return null; E value = headNode.value; return value; } @Override public Iterator<E> iterator() { return new Itr(); } @Override public boolean isEmpty() { return size() == 0; } @Override public int size() { return count; } @Override public void clear() { headNode = tailNode = null; count = 0; } /** * 链表双端队列的节点 * * @author Chain * */ @SuppressWarnings("unused") private class DequeNode { private E value; private DequeNode prevNode; private DequeNode nextNode; public DequeNode(E value) { super(); this.value = value; } public E getValue() { return value; } public void setValue(E value) { this.value = value; } public DequeNode getPrevNode() { return prevNode; } public void setPrevNode(DequeNode prevNode) { this.prevNode = prevNode; } public DequeNode getNextNode() { return nextNode; } public void setNextNode(DequeNode nextNode) { this.nextNode = nextNode; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + getOuterType().hashCode(); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } @SuppressWarnings("unchecked") @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DequeNode other = (DequeNode) obj; if (!getOuterType().equals(other.getOuterType())) return false; if (value == null) { if (other.value != null) return false; } else if (!value.equals(other.value)) return false; return true; } @SuppressWarnings("rawtypes") private LinkedDeque getOuterType() { return LinkedDeque.this; } @Override public String toString() { return value.toString(); } } /** * 链表双端队列的迭代器 * * @author Chain * */ private class Itr implements Iterator<E> { DequeNode cursor; DequeNode lastRet; int expectCount; { cursor = headNode; expectCount = count; } @Override public boolean hasNext() { return cursor != null; } @Override public E next() { checkForComodification(); // 提取出来先写在前面主要为了线程访问安全 // 也用来记录cursor的历史值 DequeNode i = cursor; // 在使用next之前需要先调用一下hasNext if (!hasNext()) throw new NoSuchElementException(); // 不能直接使用cursor++ cursor = i.nextNode; return (lastRet = i).value; } @Override public void remove() { // 必须在使用了next时才能使用remove if (lastRet == null) throw new IllegalStateException(); checkForComodification(); // 在队列中元素是有序的 // 双端队列的首尾元素是可以被移除的 // LinkedList最灵活,功能最强大 if (lastRet == headNode) { try { // 迭代器中使用抛出异常的remove LinkedDeque.this.remove(); cursor = lastRet; lastRet = null; expectCount = count; } catch (Exception e) { throw new ConcurrentModificationException(); } } else if (lastRet == tailNode) { try { // 迭代器中使用抛出异常的removeLast LinkedDeque.this.removeLast(); cursor = lastRet; lastRet = null; expectCount = count; } catch (Exception e) { throw new ConcurrentModificationException(); } } else { throw new ConcurrentModificationException(); } } final void checkForComodification() { // 如果队列中的元素和迭代器中存储的数量不一致,则代表在迭代过程进行了增加或者删除操作。 if (expectCount != count) { throw new ConcurrentModificationException(); } } } }
17.165079
70
0.642131
2b4611055fb8031bdfdd17b7fc3492b35cd1d71f
2,655
package org.antonakospanos.movierama.web.security.filters; import org.antonakospanos.movierama.web.security.authentication.MovieRamaAuthenticationDetailsSource; import org.antonakospanos.movierama.web.security.authentication.MovieRamaAuthenticationToken; import org.antonakospanos.movierama.web.security.authentication.AuthenticationDetails; import org.antonakospanos.movierama.web.security.authentication.AuthenticationDetails; import org.antonakospanos.movierama.web.security.authentication.MovieRamaAuthenticationDetailsSource; import org.antonakospanos.movierama.web.security.authentication.MovieRamaAuthenticationToken; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.filter.GenericFilterBean; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import java.io.IOException; public class AuthenticationFilter extends GenericFilterBean { private MovieRamaAuthenticationDetailsSource movieramaAuthenticationDetailsSource; private AuthenticationManager authenticationManager; public AuthenticationFilter(AuthenticationManager authManager) { this.authenticationManager = authManager; this.movieramaAuthenticationDetailsSource = new MovieRamaAuthenticationDetailsSource(); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; if (authenticate(httpRequest)) { chain.doFilter(request, response); } } private boolean authenticate(HttpServletRequest request) { // Build AuthenticationDetails parsing HTTP Authorization header AuthenticationDetails authDetails = this.movieramaAuthenticationDetailsSource.buildDetails(request); // Build movieramaAuthenticationToken using AuthenticationDetails MovieRamaAuthenticationToken authToken = new MovieRamaAuthenticationToken(); authToken.setDetails(authDetails); // Authenticate request using the list of the authentication manager's authentication providers (movieramaAuthenticationProvider) Authentication authResult = this.authenticationManager.authenticate(authToken); SecurityContextHolder.getContext().setAuthentication(authResult); return true; } }
47.410714
137
0.818079
389da31da7a50b0f63ff1a8b5cf1f587b242d32d
1,662
package no.nav.tps.forvalteren.service.command.exceptions; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import no.nav.tps.forvalteren.domain.service.tps.ResponseStatus; @RunWith(JUnit4.class) public class ExceptionTpsServiceRutineMessageCreatorTest { private static final String STATUS = "08"; private static final String MELDING = "En feil er oppstått"; private static final String UTFYLLENDE_MELDING = "Utfyllende feilmelding"; @Test(expected = IllegalAccessException.class) public void cannotInstantiatePrivate() throws Exception { Class clazz = Class.forName( "no.nav.tps.forvalteren.service.command.exceptions.ExceptionTpsServiceRutineMessageCreator"); clazz.getDeclaredConstructor().newInstance(); } @Test public void executeOk() throws Exception { String status = ExceptionTpsServiceRutineMessageCreator.execute(buildResponseStatus()); System.out.println(status); assertThat(status, containsString("{Kode=" + STATUS + " - ERROR}")); assertThat(status, containsString("{Melding=" + MELDING + "}")); assertThat(status, containsString("{UtfyllendeMelding=" + UTFYLLENDE_MELDING + "}")); } private ResponseStatus buildResponseStatus() { ResponseStatus responseStatus = new ResponseStatus(); responseStatus.setKode(STATUS); responseStatus.setMelding(MELDING); responseStatus.setUtfyllendeMelding(UTFYLLENDE_MELDING); return responseStatus; } }
36.130435
109
0.732852
2ede4d55f42353faa53dd09b4092de59b9a18100
410
import java.util.Scanner; class VolumeOfSphere { public static void main(String args[]) { Scanner s= new Scanner(System.in); System.out.println("Enter the radius of sphere:"); double r=s.nextDouble(); double volume= (4*22*r*r*r)/(3*7); System.out.println("Volume is:" +volume); } }
20.5
60
0.492683
70ee1e74fb4e080fca41a73ae4eed130613e5957
2,129
/* * * Copyright (c) 2012-2016 "FlockData LLC" * * This file is part of FlockData. * * FlockData is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * FlockData is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with FlockData. If not, see <http://www.gnu.org/licenses/>. */ package org.flockdata.test.engine.mvc; import org.junit.Test; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; public class TestAPISecurity extends MvcBase { @Test public void invokeSecureAPIWithoutAPIKey_shouldThrowError() throws Exception { mvc().perform(MockMvcRequestBuilders .get(MvcBase.apiPath + "/fortress/") .with(noUser())) .andExpect(MockMvcResultMatchers.status().isUnauthorized()) .andReturn(); } @Test public void invokeSecureAPIWithoutAPIKeyButAfterValidLogin_shouldReturnOk() throws Exception { makeDataAccessProfile("invokeSecureAPIWithoutAPIKeyButAfterValidLogin_shouldReturnOk", sally_admin); mvc() .perform(MockMvcRequestBuilders .get(MvcBase.apiPath + "/fortress/") .with(sally()) ) .andExpect(MockMvcResultMatchers.status().isOk()).andReturn(); } @Test public void invokeSecureAPIWithAPIKeyWithoutLogin_shouldReturnOk() throws Exception { String apikey = suMike.getApiKey(); setSecurityEmpty(); mvc().perform( MockMvcRequestBuilders.get(MvcBase.apiPath + "/fortress/").header("api-key", apikey) .with(noUser())) .andExpect(MockMvcResultMatchers.status().isOk()).andReturn(); } }
32.257576
104
0.710662
a384663aa348822205e13b4f297fc5069b0e64d6
22,275
/** * NOTE: This class is auto generated by the swagger code generator program (3.0.21). * https://github.com/swagger-api/swagger-codegen * Do not edit the class manually. */ package org.coredb.api; import org.coredb.model.LabelEntry; import org.springframework.core.io.Resource; import org.coredb.model.StoreStatus; import org.coredb.model.SubjectAsset; import org.coredb.model.Asset; import org.coredb.model.SubjectTag; import org.coredb.model.SubjectEntry; import org.coredb.model.SubjectView; import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.bind.annotation.CookieValue; import org.springframework.core.io.InputStreamResource; import javax.validation.Valid; import javax.validation.constraints.*; import java.util.List; import java.util.Map; @Api(value = "show", description = "the show API") public interface ShowApi { @ApiOperation(value = "", nickname = "addSubject", notes = "Add a new subject", response = SubjectEntry.class, tags={ "show", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = SubjectEntry.class), @ApiResponse(code = 403, message = "access denied"), @ApiResponse(code = 404, message = "not found") }) @RequestMapping(value = "/show/subjects", produces = { "application/json" }, method = RequestMethod.POST) ResponseEntity<SubjectEntry> addSubject(@NotNull @ApiParam(value = "share service token", required = true) @Valid @RequestParam(value = "token", required = true) String token ,@ApiParam(value = "schema of subject") @Valid @RequestParam(value = "schema", required = false) String schema ); @ApiOperation(value = "", nickname = "addSubjectAsset", notes = "Add asset to subject", response = Asset.class, tags={ "show", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Asset.class), @ApiResponse(code = 403, message = "access denied"), @ApiResponse(code = 404, message = "not found") }) @RequestMapping(value = "/show/subjects/{subjectId}/assets", produces = { "application/json" }, consumes = { "multipart/form-data" }, method = RequestMethod.POST) ResponseEntity<Asset> addSubjectAsset(@ApiParam(value = "new asset entry" ,required=true ) @Valid @RequestParam("file") MultipartFile file,@NotNull @ApiParam(value = "share token with Service service", required = true) @Valid @RequestParam(value = "token", required = true) String token ,@NotNull @ApiParam(value = "asset transformations 0. BIN pass through 1. MP4 -vf scale=720:-1 -vcodec libx264 -crf 27 -preset veryfast -acodec aac 2. MP4 -vf scale=1280:-1 -vcodec libx264 -crf 27 -preset veryfast -acodec aac 3. MP4 -vf scale=1920:-1 -vcodec libx264 -crf 27 -preset veryfast -acodec aac 4. MP3 -codec:a libmp3lame -qscale:a 6 5. MP3 -codec:a libmp3lame -qscale:a 2 6. MP3 -codec:a libmp3lame -qscale:a 0 7. JPG -resize 1280x720\\> 8. JPG -resize 2688x1520\\> 9. JPG -resize 3840x2160\\>", required = true) @Valid @RequestParam(value = "transforms", required = true) List<String> transforms ,@ApiParam(value = "id of subject",required=true) @PathVariable("subjectId") String subjectId ); @ApiOperation(value = "", nickname = "addSubjectLabel", notes = "Assign a label to a subject entry", response = SubjectEntry.class, tags={ "show", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = SubjectEntry.class), @ApiResponse(code = 401, message = "unknown token"), @ApiResponse(code = 404, message = "attribute not found"), @ApiResponse(code = 405, message = "permission not granted for token"), @ApiResponse(code = 423, message = "account locked"), @ApiResponse(code = 500, message = "internal server error") }) @RequestMapping(value = "/show/subjects/{subjectId}/labels/{labelId}", produces = { "application/json" }, method = RequestMethod.POST) ResponseEntity<SubjectEntry> addSubjectLabel(@NotNull @ApiParam(value = "share token with service", required = true) @Valid @RequestParam(value = "token", required = true) String token ,@ApiParam(value = "id of attribute",required=true) @PathVariable("subjectId") String subjectId ,@ApiParam(value = "id of label",required=true) @PathVariable("labelId") String labelId ); @ApiOperation(value = "", nickname = "setSubjectLabels", notes = "Set label association", response = SubjectEntry.class, responseContainer = "List", tags={ "index", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = SubjectEntry.class, responseContainer = "List"), @ApiResponse(code = 401, message = "unknown token"), @ApiResponse(code = 404, message = "subject not found"), @ApiResponse(code = 405, message = "permission not granted for token"), @ApiResponse(code = 423, message = "account locked"), @ApiResponse(code = 500, message = "internal server error") }) @RequestMapping(value = "/show/subjects/{subjectId}/labels", produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.PUT) ResponseEntity<SubjectEntry> setSubjectLabels(@NotNull @ApiParam(value = "share token", required = true) @Valid @RequestParam(value = "token", required = true) String token, @ApiParam(value = "referenced subject entry",required=true) @PathVariable("subjectId") String subjectId, @ApiParam(value = "" ) @Valid @RequestBody List<String> body); @ApiOperation(value = "", nickname = "clearSubjectLabel", notes = "Remove label assignment from subject entry", response = SubjectEntry.class, tags={ "show", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = SubjectEntry.class), @ApiResponse(code = 401, message = "unknown token"), @ApiResponse(code = 404, message = "attribute not found"), @ApiResponse(code = 405, message = "permission not granted for token"), @ApiResponse(code = 423, message = "account locked"), @ApiResponse(code = 500, message = "internal server error") }) @RequestMapping(value = "/show/subjects/{subjectId}/labels/{labelId}", produces = { "application/json" }, method = RequestMethod.DELETE) ResponseEntity<SubjectEntry> clearSubjectLabel(@NotNull @ApiParam(value = "share token with service", required = true) @Valid @RequestParam(value = "token", required = true) String token ,@ApiParam(value = "id of subject",required=true) @PathVariable("subjectId") String subjectId ,@ApiParam(value = "id of label",required=true) @PathVariable("labelId") String labelId ); @ApiOperation(value = "", nickname = "filterSubjects", notes = "Retrieve filtered set of subjects", response = SubjectEntry.class, responseContainer = "List", tags={ "show", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = SubjectEntry.class, responseContainer = "List"), @ApiResponse(code = 401, message = "unknown token"), @ApiResponse(code = 405, message = "permission not granted for token"), @ApiResponse(code = 423, message = "account locked"), @ApiResponse(code = 500, message = "internal server error") }) @RequestMapping(value = "/show/subjects/filter", produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.POST) ResponseEntity<List<SubjectEntry>> filterSubjects(@NotNull @ApiParam(value = "share token", required = true) @Valid @RequestParam(value = "token", required = true) String token ,@ApiParam(value = "show editing subjects") @Valid @RequestParam(value = "editing", required = false) Boolean editing ,@ApiParam(value = "show pending subjects") @Valid @RequestParam(value = "pending", required = false) Boolean pending ,@ApiParam(value = "" ) @Valid @RequestBody List<String> body ); @ApiOperation(value = "", nickname = "getShowLabels", notes = "Retrieve list of labels. (functionally the same as /group/labels)", response = LabelEntry.class, responseContainer = "List", tags={ "show", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = LabelEntry.class, responseContainer = "List"), @ApiResponse(code = 401, message = "unknown token"), @ApiResponse(code = 405, message = "permission not granted for token"), @ApiResponse(code = 423, message = "account locked"), @ApiResponse(code = 500, message = "internal server error") }) @RequestMapping(value = "/show/labels", produces = { "application/json" }, method = RequestMethod.GET) ResponseEntity<List<LabelEntry>> getShowLabels(@NotNull @ApiParam(value = "token assigned to service", required = true) @Valid @RequestParam(value = "token", required = true) String token ); @ApiOperation(value = "", nickname = "getShowRevision", notes = "Retrieve revision of show module", response = Integer.class, tags={ "show", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Integer.class), @ApiResponse(code = 403, message = "access denied") }) @RequestMapping(value = "/show/revision", produces = { "application/json" }, method = RequestMethod.GET) ResponseEntity<Integer> getShowRevision(@NotNull @ApiParam(value = "service access token", required = true) @Valid @RequestParam(value = "token", required = true) String token ); @ApiOperation(value = "", nickname = "getShowStatus", notes = "Retrieve store status", response = StoreStatus.class, tags={ "show", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = StoreStatus.class), @ApiResponse(code = 403, message = "access denied") }) @RequestMapping(value = "/show/status", produces = { "application/json" }, method = RequestMethod.GET) ResponseEntity<StoreStatus> getShowStatus(@NotNull @ApiParam(value = "service access token", required = true) @Valid @RequestParam(value = "token", required = true) String token ); @ApiOperation(value = "", nickname = "getSubject", notes = "Retrieve specified subject", response = SubjectEntry.class, tags={ "show", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = SubjectEntry.class), @ApiResponse(code = 403, message = "access denied"), @ApiResponse(code = 404, message = "not found") }) @RequestMapping(value = "/show/subjects/{subjectId}", produces = { "application/json" }, method = RequestMethod.GET) ResponseEntity<SubjectEntry> getSubject(@NotNull @ApiParam(value = "share service token", required = true) @Valid @RequestParam(value = "token", required = true) String token ,@ApiParam(value = "id of subject",required=true) @PathVariable("subjectId") String subjectId ); @ApiOperation(value = "", nickname = "getSubjectAsset", notes = "Retrieve specified asset", response = InputStreamResource.class, tags={ "show", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = InputStreamResource.class), @ApiResponse(code = 403, message = "access denied"), @ApiResponse(code = 404, message = "token or id not found") }) @RequestMapping(value = "/show/subjects/{subjectId}/assets/{assetId}", produces = { "application/octet-stream" }, method = RequestMethod.GET) ResponseEntity<InputStreamResource> getSubjectAsset(@NotNull @ApiParam(value = "share token for service", required = true) @Valid @RequestParam(value = "token", required = true) String token ,@ApiParam(value = "id of subject",required=true) @PathVariable("subjectId") String subjectId ,@ApiParam(value = "id of asset",required=true) @PathVariable("assetId") String assetId ); @ApiOperation(value = "", nickname = "removeSubject", notes = "Remove specified subject", tags={ "show", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation"), @ApiResponse(code = 403, message = "access denied"), @ApiResponse(code = 404, message = "not found") }) @RequestMapping(value = "/show/subjects/{subjectId}", method = RequestMethod.DELETE) ResponseEntity<Void> removeSubject(@NotNull @ApiParam(value = "share service token", required = true) @Valid @RequestParam(value = "token", required = true) String token ,@ApiParam(value = "id of subject",required=true) @PathVariable("subjectId") String subjectId ); @ApiOperation(value = "", nickname = "removeSubjectAsset", notes = "Delete asset from subject", response = SubjectEntry.class, tags={ "show", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = SubjectEntry.class), @ApiResponse(code = 403, message = "access denied"), @ApiResponse(code = 404, message = "not found") }) @RequestMapping(value = "/show/subjects/{subjectId}/assets/{assetId}", produces = { "application/json" }, method = RequestMethod.DELETE) ResponseEntity<SubjectEntry> removeSubjectAsset(@NotNull @ApiParam(value = "service access token", required = true) @Valid @RequestParam(value = "token", required = true) String token ,@ApiParam(value = "id of subject",required=true) @PathVariable("subjectId") String subjectId ,@ApiParam(value = "id of asset",required=true) @PathVariable("assetId") String assetId ); @ApiOperation(value = "", nickname = "updateSubjectAccess", notes = "Update specified subject data", response = SubjectEntry.class, tags={ "show", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = SubjectEntry.class), @ApiResponse(code = 403, message = "access denied"), @ApiResponse(code = 404, message = "not found") }) @RequestMapping(value = "/show/subjects/{subjectId}/access", produces = { "application/json" }, method = RequestMethod.PUT) ResponseEntity<SubjectEntry> updateSubjectAccess(@NotNull @ApiParam(value = "share service token", required = true) @Valid @RequestParam(value = "token", required = true) String token ,@ApiParam(value = "id of subject",required=true) @PathVariable("subjectId") String subjectId ,@NotNull @ApiParam(value = "set if subject is to be shared", required = true) @Valid @RequestParam(value = "share", required = true) Boolean share ); @ApiOperation(value = "", nickname = "updateSubjectData", notes = "Update specified subject data", response = SubjectEntry.class, tags={ "show", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = SubjectEntry.class), @ApiResponse(code = 403, message = "access denied"), @ApiResponse(code = 404, message = "not found") }) @RequestMapping(value = "/show/subjects/{subjectId}/data", produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.PUT) ResponseEntity<SubjectEntry> updateSubjectData(@NotNull @ApiParam(value = "share service token", required = true) @Valid @RequestParam(value = "token", required = true) String token ,@NotNull @ApiParam(value = "schema of subject", required = true) @Valid @RequestParam(value = "schema", required = true) String schema ,@ApiParam(value = "id of subject",required=true) @PathVariable("subjectId") String subjectId ,@ApiParam(value = "payload of subject" ) @Valid @RequestBody String body ); @ApiOperation(value = "", nickname = "updateSubjectExpire", notes = "Update specified subject expiration", response = SubjectEntry.class, tags={ "show", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = SubjectEntry.class), @ApiResponse(code = 403, message = "access denied"), @ApiResponse(code = 404, message = "not found") }) @RequestMapping(value = "/show/subjects/{subjectId}/expire", produces = { "application/json" }, method = RequestMethod.PUT) ResponseEntity<SubjectEntry> updateSubjectExpire(@NotNull @ApiParam(value = "share service token", required = true) @Valid @RequestParam(value = "token", required = true) String token ,@ApiParam(value = "id of subject",required=true) @PathVariable("subjectId") String subjectId ,@ApiParam(value = "set if subject is to expire") @Valid @RequestParam(value = "expire", required = false) Long expire ); @ApiOperation(value = "", nickname = "viewSubjects", notes = "Retrieve subject label association", response = SubjectView.class, responseContainer = "List", tags={ "show", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = SubjectView.class, responseContainer = "List"), @ApiResponse(code = 401, message = "unknown token"), @ApiResponse(code = 405, message = "permission not granted for token"), @ApiResponse(code = 423, message = "account locked"), @ApiResponse(code = 500, message = "internal server error") }) @RequestMapping(value = "/show/subjects/view", produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.POST) ResponseEntity<List<SubjectView>> viewSubjects(@NotNull @ApiParam(value = "share token", required = true) @Valid @RequestParam(value = "token", required = true) String token ,@ApiParam(value = "" ) @Valid @RequestBody List<String> body ); @ApiOperation(value = "", nickname = "getSubjectTags", notes = "Retrieve tags attached to specified subject", response = SubjectTag.class, tags={ "show", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = SubjectTag.class), @ApiResponse(code = 401, message = "unknown token"), @ApiResponse(code = 405, message = "permission not granted for token"), @ApiResponse(code = 423, message = "account locked"), @ApiResponse(code = 500, message = "internal server error") }) @RequestMapping(value = "/show/subjects/{subjectId}/tags", produces = { "application/json" }, method = RequestMethod.GET) ResponseEntity<SubjectTag> getSubjectTags(@NotNull @ApiParam(value = "token assigned to service", required = true) @Valid @RequestParam(value = "token", required = true) String token ,@ApiParam(value = "id of subject",required=true) @PathVariable("subjectId") String subjectId ,@ApiParam(value = "type of tags to retrieve") @Valid @RequestParam(value = "schema", required = false) String schema ,@ApiParam(value = "order by earliest first") @Valid @RequestParam(value = "descending", required = false) Boolean descending ); @ApiOperation(value = "", nickname = "addSubjectTag", notes = "Retrieve tags attached to specified subject", response = SubjectTag.class, tags={ "show", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = SubjectTag.class), @ApiResponse(code = 401, message = "unknown token"), @ApiResponse(code = 405, message = "permission not granted for token"), @ApiResponse(code = 423, message = "account locked"), @ApiResponse(code = 500, message = "internal server error") }) @RequestMapping(value = "/show/subjects/{subjectId}/tags", produces = { "application/json" }, consumes = { "application/json" }, method = RequestMethod.POST) ResponseEntity<SubjectTag> addSubjectTag(@NotNull @ApiParam(value = "token assigned to service", required = true) @Valid @RequestParam(value = "token", required = true) String token ,@ApiParam(value = "id of subject",required=true) @PathVariable("subjectId") String subjectId ,@ApiParam(value = "type of tags to add") @Valid @RequestParam(value = "schema", required = false) String schema ,@ApiParam(value = "order by earliest first") @Valid @RequestParam(value = "descending", required = false) Boolean descending ,@ApiParam(value = "stringified data object" ) @Valid @RequestBody String body ); @ApiOperation(value = "", nickname = "removeSubjectTag", notes = "Remove tag attached to subject", response = SubjectTag.class, tags={ "show", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = SubjectTag.class), @ApiResponse(code = 401, message = "unknown token"), @ApiResponse(code = 404, message = "tag not found"), @ApiResponse(code = 405, message = "permission not granted for token"), @ApiResponse(code = 423, message = "account locked"), @ApiResponse(code = 500, message = "internal server error") }) @RequestMapping(value = "/show/subjects/{subjectId}/tags/{tagId}", produces = { "application/json" }, method = RequestMethod.DELETE) ResponseEntity<SubjectTag> removeSubjectTag(@NotNull @ApiParam(value = "token assigned to service", required = true) @Valid @RequestParam(value = "token", required = true) String token ,@ApiParam(value = "id of subject",required=true) @PathVariable("subjectId") String subjectId ,@ApiParam(value = "id of tag",required=true) @PathVariable("tagId") String tagId ,@ApiParam(value = "type of tags to retrieve") @Valid @RequestParam(value = "schema", required = false) String schema ,@ApiParam(value = "order by earliest first") @Valid @RequestParam(value = "descending", required = false) Boolean descending ); }
65.514706
606
0.691852
644b477f54d92cd7915e3f3bb8dc75a3168dad68
5,030
package net.minecraft.item; import net.minecraft.advancements.CriteriaTriggers; import net.minecraft.block.BlockEndPortalFrame; import net.minecraft.block.properties.IProperty; import net.minecraft.block.state.IBlockState; import net.minecraft.block.state.pattern.BlockPattern; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.Entity; import net.minecraft.entity.item.EntityEnderEye; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.init.Blocks; import net.minecraft.init.SoundEvents; import net.minecraft.stats.StatList; import net.minecraft.util.ActionResult; import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.EnumParticleTypes; import net.minecraft.util.SoundCategory; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.world.World; import net.minecraft.world.WorldServer; public class ItemEnderEye extends Item { public ItemEnderEye() { setCreativeTab(CreativeTabs.MISC); } public EnumActionResult onItemUse(EntityPlayer stack, World playerIn, BlockPos worldIn, EnumHand pos, EnumFacing hand, float facing, float hitX, float hitY) { IBlockState iblockstate = playerIn.getBlockState(worldIn); ItemStack itemstack = stack.getHeldItem(pos); if (stack.canPlayerEdit(worldIn.offset(hand), hand, itemstack) && iblockstate.getBlock() == Blocks.END_PORTAL_FRAME && !((Boolean)iblockstate.getValue((IProperty)BlockEndPortalFrame.EYE)).booleanValue()) { if (playerIn.isRemote) return EnumActionResult.SUCCESS; playerIn.setBlockState(worldIn, iblockstate.withProperty((IProperty)BlockEndPortalFrame.EYE, Boolean.valueOf(true)), 2); playerIn.updateComparatorOutputLevel(worldIn, Blocks.END_PORTAL_FRAME); itemstack.func_190918_g(1); for (int i = 0; i < 16; i++) { double d0 = (worldIn.getX() + (5.0F + itemRand.nextFloat() * 6.0F) / 16.0F); double d1 = (worldIn.getY() + 0.8125F); double d2 = (worldIn.getZ() + (5.0F + itemRand.nextFloat() * 6.0F) / 16.0F); double d3 = 0.0D; double d4 = 0.0D; double d5 = 0.0D; playerIn.spawnParticle(EnumParticleTypes.SMOKE_NORMAL, d0, d1, d2, 0.0D, 0.0D, 0.0D, new int[0]); } playerIn.playSound(null, worldIn, SoundEvents.field_193781_bp, SoundCategory.BLOCKS, 1.0F, 1.0F); BlockPattern.PatternHelper blockpattern$patternhelper = BlockEndPortalFrame.getOrCreatePortalShape().match(playerIn, worldIn); if (blockpattern$patternhelper != null) { BlockPos blockpos = blockpattern$patternhelper.getFrontTopLeft().add(-3, 0, -3); for (int j = 0; j < 3; j++) { for (int k = 0; k < 3; k++) playerIn.setBlockState(blockpos.add(j, 0, k), Blocks.END_PORTAL.getDefaultState(), 2); } playerIn.playBroadcastSound(1038, blockpos.add(1, 0, 1), 0); } return EnumActionResult.SUCCESS; } return EnumActionResult.FAIL; } public ActionResult<ItemStack> onItemRightClick(World itemStackIn, EntityPlayer worldIn, EnumHand playerIn) { ItemStack itemstack = worldIn.getHeldItem(playerIn); RayTraceResult raytraceresult = rayTrace(itemStackIn, worldIn, false); if (raytraceresult != null && raytraceresult.typeOfHit == RayTraceResult.Type.BLOCK && itemStackIn.getBlockState(raytraceresult.getBlockPos()).getBlock() == Blocks.END_PORTAL_FRAME) return new ActionResult(EnumActionResult.PASS, itemstack); worldIn.setActiveHand(playerIn); if (!itemStackIn.isRemote) { BlockPos blockpos = ((WorldServer)itemStackIn).getChunkProvider().getStrongholdGen(itemStackIn, "Stronghold", new BlockPos((Entity)worldIn), false); if (blockpos != null) { EntityEnderEye entityendereye = new EntityEnderEye(itemStackIn, worldIn.posX, worldIn.posY + (worldIn.height / 2.0F), worldIn.posZ); entityendereye.moveTowards(blockpos); itemStackIn.spawnEntityInWorld((Entity)entityendereye); if (worldIn instanceof EntityPlayerMP) CriteriaTriggers.field_192132_l.func_192239_a((EntityPlayerMP)worldIn, blockpos); itemStackIn.playSound(null, worldIn.posX, worldIn.posY, worldIn.posZ, SoundEvents.ENTITY_ENDEREYE_LAUNCH, SoundCategory.NEUTRAL, 0.5F, 0.4F / (itemRand.nextFloat() * 0.4F + 0.8F)); itemStackIn.playEvent(null, 1003, new BlockPos((Entity)worldIn), 0); if (!worldIn.capabilities.isCreativeMode) itemstack.func_190918_g(1); worldIn.addStat(StatList.getObjectUseStats(this)); return new ActionResult(EnumActionResult.SUCCESS, itemstack); } } return new ActionResult(EnumActionResult.SUCCESS, itemstack); } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\item\ItemEnderEye.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
52.947368
209
0.731014
f6bba4e91643fdf6fb0e2de58ade563b86570d50
3,494
package com.aliyun.dts.subscribe.clients.common; import java.util.NoSuchElementException; import java.util.Objects; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; /** * Copy code from java.util.Optional, the only difference is NullableOptional consider null as a normal value. * So the NullableOptional.ofNullable(null).isPresent() should be true. */ public final class NullableOptional<T> { private static final NullableOptional<?> EMPTY = new NullableOptional(); private final T value; private final boolean isPresent; private NullableOptional() { this.isPresent = false; this.value = null; } public static <T> NullableOptional<T> empty() { NullableOptional value = EMPTY; return value; } private NullableOptional(T value) { this.value = value; this.isPresent = true; } public static <T> NullableOptional<T> of(T value) { Objects.requireNonNull(value); return new NullableOptional(value); } public static <T> NullableOptional<T> ofNullable(T value) { return new NullableOptional<>(value); } public T get() { if (!this.isPresent()) { throw new NoSuchElementException("No value present"); } else { return this.value; } } public boolean isPresent() { return this.isPresent; } public void ifPresent(Consumer<? super T> consumer) { if (this.isPresent()) { consumer.accept(this.value); } } public NullableOptional<T> filter(Predicate<? super T> filterFunction) { Objects.requireNonNull(filterFunction); if (!this.isPresent()) { return this; } else { return filterFunction.test(this.value) ? this : empty(); } } public <U> NullableOptional<U> map(Function<? super T, ? extends U> function) { Objects.requireNonNull(function); return !this.isPresent() ? empty() : ofNullable(function.apply(this.value)); } public <U> NullableOptional<U> flatMap(Function<? super T, NullableOptional<U>> mapper) { Objects.requireNonNull(mapper); return !this.isPresent() ? empty() : (NullableOptional) Objects.requireNonNull(mapper.apply(this.value)); } public T orElse(T defaultValue) { return this.isPresent() ? this.value : defaultValue; } public T orElseGet(Supplier<? extends T> defaultValueSupplier) { return this.isPresent() ? this.value : defaultValueSupplier.get(); } public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X { if (this.isPresent()) { return this.value; } else { throw exceptionSupplier.get(); } } public boolean equals(Object var1) { if (this == var1) { return true; } else if (!(var1 instanceof NullableOptional)) { return false; } else { NullableOptional var2 = (NullableOptional) var1; return Objects.equals(this.isPresent, var2.isPresent) && Objects.equals(this.value, var2.value); } } public int hashCode() { return Objects.hash(this.isPresent, this.value); } public String toString() { return this.isPresent() ? String.format("Optional[%s]", this.value) : "Optional.empty"; } }
30.382609
113
0.630796
22cc27ff5cf78cecf1a1b82e8ef72da136c53fa4
371
package mx.com.mentoringit.interfaces; import java.util.List; public interface IGenericDAO<T> { public Integer save(T emp) throws Exception; public void edit(T emp) throws Exception; public T find(Class<T> clase,int idEntity) throws Exception; public Boolean delete(T emp) throws Exception; public List<T> findAll(Class<T> clase) throws Exception; }
28.538462
62
0.746631
5e9cadb424c4870b86b00e6c93cb9f36d0f8f258
490
package com.cjburkey.mod.wonderland.packet; import com.cjburkey.mod.wonderland.ModInfo; import net.minecraftforge.fml.common.network.NetworkRegistry; import net.minecraftforge.fml.common.network.simpleimpl.SimpleNetworkWrapper; import net.minecraftforge.fml.relauncher.Side; public final class ModPackets { public static SimpleNetworkWrapper network; public static void commonPreinit() { network = NetworkRegistry.INSTANCE.newSimpleChannel(ModInfo.ID + "_channel_wrapper"); } }
30.625
87
0.820408
ffb02ad99e27b58b4cf6b5ff678b146be3ac4394
2,669
package br.com.zupacademy.enricco.proposta.events.handlers; import br.com.zupacademy.enricco.proposta.events.ClassifyProposalEvent; import br.com.zupacademy.enricco.proposta.models.ClientProposal; import br.com.zupacademy.enricco.proposta.repositories.ClientProposalRepository; import br.com.zupacademy.enricco.proposta.utils.clients.TransactionClient; import br.com.zupacademy.enricco.proposta.utils.clients.request.ProposalToBeClassified; import br.com.zupacademy.enricco.proposta.utils.clients.response.ClassifiedProposal; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import feign.FeignException; import org.apache.tomcat.util.json.JSONParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationListener; import org.springframework.context.event.EventListener; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.stereotype.Component; import org.springframework.transaction.event.TransactionalEventListener; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.transaction.Transactional; import java.net.URI; @Component public class ClassifyProposalEventListener { private Logger logger = LoggerFactory.getLogger(ClassifyProposalEventListener.class); @Autowired private ClientProposalRepository repository; @Autowired private TransactionClient httpClient; @Value("${classify.url}") private String url; @EventListener @Async public void onApplicationEvent(ClassifyProposalEvent classifyProposalEvent) throws JsonProcessingException { ClientProposal proposal = classifyProposalEvent.getProposal(); ClassifiedProposal classifiedProposal; try { classifiedProposal = httpClient.classifyProposal(URI.create(url),new ProposalToBeClassified(proposal)); }catch (FeignException.FeignClientException e){ if(e.status()!=422){ logger.error(e.getMessage()); return; } ObjectMapper objectMapper = new ObjectMapper(); classifiedProposal = objectMapper.readValue( e.contentUTF8(), ClassifiedProposal.class); }catch (Exception e){ logger.error(e.getMessage()); return; } ClientProposal classified = classifiedProposal.toModel(repository); repository.save(classified); } }
39.835821
115
0.778194
4d65540ba6d191f263b300e615b90d790ec1a7cf
6,271
package kr.plurly.daily.collection.adapter; import android.databinding.DataBindingUtil; import android.graphics.drawable.BitmapDrawable; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.squareup.picasso.Picasso; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.Locale; import kr.plurly.daily.R; import kr.plurly.daily.collection.listener.OnItemClickListener; import kr.plurly.daily.component.activity.DailyView; import kr.plurly.daily.databinding.LayoutItemEventThumbnailBinding; import kr.plurly.daily.domain.Event; import kr.plurly.daily.inject.component.ActivityComponent; import kr.plurly.daily.inject.module.AppModule; import kr.plurly.daily.util.Constraints; class EventThumbnailViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { private static final String EVENT_PHOTO_FORMAT = "%s/events/%s/photo"; private final LayoutItemEventThumbnailBinding binding; private OnItemClickListener<Event> listener; void setOnItemClickListener(OnItemClickListener<Event> listener) { this.listener = listener; } EventThumbnailViewHolder(LayoutItemEventThumbnailBinding binding) { super(binding.getRoot()); this.binding = binding; this.binding.getRoot().setOnClickListener(this); } void bind(Event event) { binding.setEvent(event); binding.setExpanded(false); if (!TextUtils.isEmpty(event.getPath())) { Picasso.with(binding.getRoot().getContext()) .load(String.format(Locale.getDefault(), EVENT_PHOTO_FORMAT, AppModule.URL, event.getUUID())) .placeholder(new BitmapDrawable(binding.getRoot().getResources(), event.getPath())) .resize(300, 160) .into(binding.imageViewContent); } } void setPosition(int position) { binding.setPosition(position); } void setSize(int size) { binding.setSize(size); } @Override public void onClick(View v) { boolean expanded = binding.getExpanded(); binding.setExpanded(!expanded); if (listener != null) { Event event = binding.getEvent(); listener.onClick(event); } } } public class EventThumbnailAdapter extends RecyclerView.Adapter<EventThumbnailViewHolder> implements OnItemClickListener<Event>, Comparator<Event> { private OnItemClickListener<Event> listener; public OnItemClickListener<Event> getOnItemClickListener() { return listener; } public void setOnItemClickListener(OnItemClickListener<Event> listener) { this.listener = listener; } private List<Event> events = new ArrayList<>(); public void add(Event event) { add(event, true); } public void addAll(Collection<Event> items) { for (Event item : items) add(item, false); invalidate(); } private void add(Event event, boolean refresh) { if (events.contains(event)) { update(event, refresh); return; } events.add(0, event); if (refresh) invalidate(); } public void update(Event event) { update(event, true); } private void update(Event event, boolean refresh) { int index = events.indexOf(event); if (index == -1) return; events.set(index, event); if (refresh && (!isSorted() || event.isSynced())) invalidate(); } public void remove(Event event) { int index = events.indexOf(event); if (index == -1) return; events.remove(event); invalidate(); } private void invalidate() { Collections.sort(events, this); notifyDataSetChanged(); } private boolean isSorted() { boolean isSorted = true; Event pointer = null; for (Event event : events) { if (pointer != null && compare(pointer, event) > 0) { isSorted = false; break; } pointer = event; } return isSorted; } public Date getReference() { Date date = null; for (Event event : events) { if (date == null || !event.isSynced() && event.getCreatedAt().before(date)) { date = event.getCreatedAt(); } } return date != null ? date : latest(); } private Date latest() { Date date = null; for (Event event : events) { if (date == null || event.getCreatedAt().after(date)) { date = event.getCreatedAt(); } } return date != null ? date : Constraints.DEFAULT_FETCH_DATE; } @Override public int compare(Event e1, Event e2) { Date d1 = e1.getCreatedAt(); Date d2 = e2.getCreatedAt(); return d1.before(d2) ? 1 : -1; } public EventThumbnailAdapter(DailyView view) { ActivityComponent component = view.getActivityComponent(); component.inject(this); } @Override public EventThumbnailViewHolder onCreateViewHolder(ViewGroup parent, int type) { LayoutItemEventThumbnailBinding binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.layout_item_event_thumbnail, parent, false); binding.setExpanded(false); EventThumbnailViewHolder holder = new EventThumbnailViewHolder(binding); holder.setOnItemClickListener(this); return holder; } @Override public void onBindViewHolder(EventThumbnailViewHolder holder, int position) { Event event = events.get(position); holder.setPosition(position); holder.setSize(events.size()); holder.bind(event); } @Override public int getItemCount() { return events.size(); } @Override public void onClick(Event event) { if (listener != null) listener.onClick(event); } }
24.212355
169
0.634349
092e9712d9448ddcad49af0ef3fa1bd305769cbc
1,781
/* * File: ZHCollection.java */ package zhstructures; import java.util.Iterator; /** * The root interface in the Ziegler/Holey collection hierarchy, which * is a simplified version of the Java collection hierarchy. * A collection represents a group of objects, known as its elements. * Some collections allow duplicate elements and others do not. * Some are ordered and others unordered. * As with the JDK, we do not provide any direct implementations of this * interface; we provide implementations of more specific sub-interfaces * like ZHSet and ZHList. * This interface is typically used to pass collections around and * manipulate them where maximum generality is desired. * * A ZHCollection is more general than the Java Collection in that it does * not specify any means for adding, removing or updating elements of the * collection. * * @author J. Andrew Holey * @version August 7, 2008 */ public interface ZHCollection<ElementType> extends Iterable<ElementType> { /** * Returns true if this collection contains no elements. * * @return true if this collection contains no elements */ public boolean isEmpty(); /** * Returns true if this collection contains the specified element, * that is, if it contains an element equal to the specified element * under the equals () method. * Note that unlike the Java Collection interface, only elements * matching the template type may be tested. * * @param element the element for which presence in this collection * is to be tested * @return true if this collection contains the specified element */ public boolean contains(ElementType element); /* (non-Javadoc) * @see java.lang.Iterable#iterator() */ public Iterator<ElementType> iterator(); }
31.245614
74
0.737226
52d68dd60e7a02c4af3735a2432e46b6db65412d
881
package com.vinsguru.saga.config; import com.vinsguru.dto.OrchestratorRequestDTO; import com.vinsguru.dto.OrchestratorResponseDTO; import com.vinsguru.saga.service.OrchestratorService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import reactor.core.publisher.Flux; import java.util.function.Function; @Configuration public class OrchestratorConfig { @Autowired private OrchestratorService orchestratorService; @Bean public Function<Flux<OrchestratorRequestDTO>, Flux<OrchestratorResponseDTO>> processor(){ return flux -> flux .flatMap(dto -> this.orchestratorService.orderProduct(dto)) .doOnNext(dto -> System.out.println("Status : " + dto.getStatus())); } }
32.62963
96
0.745743
242eac6022f6cf01b3e3d3fdc871c5d4aa2b9392
1,265
package com.qa.ims.services; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; import com.qa.ims.persistence.dao.Dao; import com.qa.ims.persistence.domain.Customer; @RunWith(MockitoJUnitRunner.class) public class CustomerServicesTest { @Mock private Dao<Customer> customerDao; @InjectMocks private CustomerServices customerServices; @Test public void customerServicesCreate() { Customer customer = new Customer("Jonny Test", "123 Test St", "TE53 6TY"); customerServices.create(customer); Mockito.verify(customerDao, Mockito.times(1)).create(customer); } @Test public void customerServicesRead() { customerServices.readAll(); Mockito.verify(customerDao, Mockito.times(1)).readAll(); } @Test public void customerServicesUpdate() { Customer customer = new Customer("Minerva Brownbury", "21 Greenfield Ave", "LS72 3HA"); customerServices.update(customer); Mockito.verify(customerDao, Mockito.times(1)).update(customer); } @Test public void customerServicesDelete() { customerServices.delete(1L); Mockito.verify(customerDao, Mockito.times(1)).delete(1L); } }
25.816327
89
0.764427
c8af83f77da80a682f05b287f072a4a8a3c61530
1,655
/* * Copyright 2016 Faisal Thaheem <[email protected]>. * * 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.computedsynergy.hurtrade.sharedcomponents.models.pojos; import java.util.Date; import java.util.List; /** * * @author Faisal Thaheem <[email protected]> */ public class Schedule { private int id; private int dayofweek; private String schedule; private Date ended; private Date created; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getDayofweek() { return dayofweek; } public void setDayofweek(int dayofweek) { this.dayofweek = dayofweek; } public Date getEnded() { return ended; } public void setEnded(Date ended) { this.ended = ended; } public Date getCreated() { return created; } public void setCreated(Date created) { this.created = created; } public String getSchedule() { return schedule; } public void setSchedule(String schedule) { this.schedule = schedule; } }
21.776316
75
0.656193
82049d7a86ced21ec7adabb522bc34227b2776ee
2,412
/* * Copyright 2014 Davy Maddelein. * * 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 autoupdater; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.Enumeration; import java.util.Properties; import java.util.jar.JarEntry; import java.util.jar.JarFile; /** * implementation of jar file to handle the niceties maven adds to a jar * * @author Davy Maddelein */ public class MavenJarFile extends JarFile { private Properties mavenProperties = new Properties(); private String absoluteFilePath; private URI jarPath; /** * Create a new MavenJarFile object. * * @param jarPath the path to the jar file * @throws IOException */ public MavenJarFile(URI jarPath) throws IOException { super(new File(jarPath)); this.jarPath = jarPath; this.absoluteFilePath = new File(jarPath).getAbsolutePath(); Enumeration<JarEntry> entries = this.entries(); //no cleaner way to do this without asking for the group and artifact id, which defeats the point while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (entry.getName().contains("pom.properties")) { mavenProperties.load(this.getInputStream(entry)); break; } } } public MavenJarFile(File aJarFile) throws IOException { this(aJarFile.toURI()); } public String getArtifactId() { return mavenProperties.getProperty("artifactId"); } public String getGroupId() { return mavenProperties.getProperty("groupId"); } public String getVersionNumber() { return mavenProperties.getProperty("version"); } public String getAbsoluteFilePath() { return absoluteFilePath; } public URI getJarPath() { return jarPath; } }
28.376471
105
0.672471
3584d0b0dcc8c7d1ee708702e09f657cd42d5582
6,167
// @@author A0163996J package seedu.taskit.model.task; import java.util.Objects; import seedu.taskit.commons.exceptions.IllegalValueException; import seedu.taskit.model.tag.UniqueTagList; import seedu.taskit.model.task.Date; import static seedu.taskit.commons.core.Messages.MESSAGE_INVALID_START_DATE; import static seedu.taskit.logic.parser.CliSyntax.DONE; public class Task implements ReadOnlyTask, Comparable<Task>{ protected Title title; protected Date start; protected Date end; protected Priority priority; protected UniqueTagList tags; private boolean isDone; private boolean isOverdue; /** * Constructor for tasks * @throws IllegalValueException */ public Task(Title title, Date start, Date end, Priority priority, UniqueTagList tags) throws IllegalValueException { this.title = title; if (!start.isStartValidComparedToEnd(end)) { throw new IllegalValueException(MESSAGE_INVALID_START_DATE); } this.start = start; this.end = end; this.priority = priority; this.tags = new UniqueTagList(tags); // protect internal tags from changes in the arg list this.isDone = false; this.isOverdue = checkOverdue(); } /** * Creates a copy of the given Task. */ public Task(ReadOnlyTask source) { this.title = source.getTitle(); this.start = source.getStart(); this.end = source.getEnd(); this.priority = source.getPriority(); this.tags = new UniqueTagList(source.getTags()); this.isDone = source.isDone(); this.isOverdue = source.isOverdue(); } public void setTitle(Title title) { assert title != null; this.title = title; } public Title getTitle() { return title; } public void setStart(Date start) { this.start = start; } public Date getStart() { if (start == null) { return new Date(); } return start; } public void setEnd(Date end) { this.end = end; } public Date getEnd() { if (end == null) { return new Date(); } return end; } public void setPriority(Priority priority) { this.priority = priority; } public Priority getPriority() { return priority; } /** * The returned TagList is a deep copy of the internal TagList, * changes on the returned list will not affect the task's internal tags. */ public UniqueTagList getTags() { return new UniqueTagList(tags); } /** * Replaces this task's tags with the tags in the argument tag list. */ public void setTags(UniqueTagList replacement) { tags.setTags(replacement); } /** * Updates this task with the details of {@code replacement}. */ public void resetData(ReadOnlyTask replacement) { assert replacement != null; this.setTitle(replacement.getTitle()); this.setStart(replacement.getStart()); this.setEnd(replacement.getEnd()); this.setPriority(replacement.getPriority()); this.setTags(replacement.getTags()); } @Override public int compareTo(Task o) { int priorityComparison = this.priority.compareTo(o.priority); if (priorityComparison == 0) { int startComparison = this.getStart().compareTo(o.getStart()); if (startComparison == 0) { return this.getEnd().compareTo(o.getEnd()); } return startComparison; } return priorityComparison; } public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof Task // instanceof handles nulls && this.isSameStateAs((Task) other)); } /** * Returns true if both have the same state. (interfaces cannot override .equals) */ public boolean isSameStateAs(Task other) { return other == this // short circuit if same object || (other != null // this is first to avoid NPE below && other.getTitle().equals(this.getTitle()) && other.getStart().equals(this.getStart()) && other.getEnd().equals(this.getEnd()) && other.getPriority().equals(this.getPriority()) && other.getTags().equals(this.getTags())); } @Override public int hashCode() { // use this method for custom fields hashing instead of implementing your own return Objects.hash(title, tags); } public String toString() { return getAsText(); } /** * Formats the task as text, showing all details. */ public String getAsText() { final StringBuilder builder = new StringBuilder(); builder.append(getTitle() + " ") .append("Start: ") .append(getStart() + " ") .append("End: ") .append(getEnd() + " ") .append("Priority: ") .append(getPriority().toString()+" ") .append(" Tags: "); getTags().forEach(builder::append); return builder.toString(); } //@@author A0141872E @Override public boolean isDone() { return this.isDone; } public void setDone(String status) { if(status.equals(DONE)) { isDone = true; } else { isDone = false; } } public void setOverdue() { this.isOverdue = checkOverdue(); } @Override public boolean isOverdue() { setOverdue(); return isOverdue; } private boolean checkOverdue() { return this.end.isEndTimePassCurrentTime()== true && isDone == false; } @Override public boolean isFloating() { return this.end.date == null; } @Override public boolean isEvent() { return this.start.date != null && this.end.date != null; } @Override public boolean isDeadline() { return this.start.date == null && this.end.date != null; } }
27.408889
120
0.590887
012e3b5bb24877a2dfdda88c7c7ed83d92c46263
8,772
package raytracer; import static com.google.common.truth.Truth.assertThat; import java.io.IOException; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) // Feature: OBJ File Parser public class ObjFileTest { @Test // Scenario: Ignoring unrecognized lines public void ignoreUnrecognizedLines() throws IOException, ObjFile.ParsingException { String input = String.join( "\n", "There was a young lady named Bright", "who traveled much faster than light.", "She set out one day", "in a relative way,", "and came back the previous night."); ObjFile objFile = ObjFile.parseContent(input); assertThat(objFile.ignoredCommandCount()).isEqualTo(5); } @Test // Scenario: Vertex records public void vertexRecords() throws Exception { String input = String.join("\n", "v -1 1 0", "v -1.0000 0.5000 0.0000", "v 1 0 0", "v 1 1 0"); ObjFile objFile = ObjFile.parseContent(input); assertThat(objFile.ignoredCommandCount()).isEqualTo(0); assertThat(objFile.getVertexCount()).isEqualTo(4); assertThat(objFile.getVertex(1)).isEqualTo(Tuple.point(-1, 1, 0)); assertThat(objFile.getVertex(2)).isEqualTo(Tuple.point(-1, 0.5, 0)); assertThat(objFile.getVertex(3)).isEqualTo(Tuple.point(1, 0, 0)); assertThat(objFile.getVertex(4)).isEqualTo(Tuple.point(1, 1, 0)); } @Test // Scenario: Parsing triangle faces public void triangleFaces() throws Exception { String input = String.join("\n", "v -1 1 0", "v -1 0 0", "v 1 0 0", "v 1 1 0", "", "f 1 2 3", "f 1 3 4"); ObjFile objFile = ObjFile.parseContent(input); assertThat(objFile.ignoredCommandCount()).isEqualTo(0); ObjFile.TriangleGroup group = objFile.getDefaultGroup(); assertThat(group.getTriangleCount()).isEqualTo(2); Triangle triangle1 = group.getTriangle(1); Triangle triangle2 = group.getTriangle(2); assertThat(triangle1.p1()).isEqualTo(objFile.getVertex(1)); assertThat(triangle1.p2()).isEqualTo(objFile.getVertex(2)); assertThat(triangle1.p3()).isEqualTo(objFile.getVertex(3)); assertThat(triangle2.p1()).isEqualTo(objFile.getVertex(1)); assertThat(triangle2.p2()).isEqualTo(objFile.getVertex(3)); assertThat(triangle2.p3()).isEqualTo(objFile.getVertex(4)); } @Test // Scenario: Triangulating polygons public void trianglulatePolygon() throws Exception { String input = String.join( "\n", "v -1 1 0", "v -1 0 0", "v 1 0 0", "v 1 1 0", "v 0 2 0", "", "f 1 2 3 4 5"); ObjFile objFile = ObjFile.parseContent(input); assertThat(objFile.ignoredCommandCount()).isEqualTo(0); ObjFile.TriangleGroup group = objFile.getDefaultGroup(); assertThat(group.getTriangleCount()).isEqualTo(3); Triangle triangle1 = group.getTriangle(1); assertThat(triangle1.p1()).isEqualTo(objFile.getVertex(1)); assertThat(triangle1.p2()).isEqualTo(objFile.getVertex(2)); assertThat(triangle1.p3()).isEqualTo(objFile.getVertex(3)); Triangle triangle2 = group.getTriangle(2); assertThat(triangle2.p1()).isEqualTo(objFile.getVertex(1)); assertThat(triangle2.p2()).isEqualTo(objFile.getVertex(3)); assertThat(triangle2.p3()).isEqualTo(objFile.getVertex(4)); Triangle triangle3 = group.getTriangle(3); assertThat(triangle3.p1()).isEqualTo(objFile.getVertex(1)); assertThat(triangle3.p2()).isEqualTo(objFile.getVertex(4)); assertThat(triangle3.p3()).isEqualTo(objFile.getVertex(5)); } @Test // Scenario: Triangles in groups public void groups() throws Exception { ObjFile objFile = ObjFile.parseResource("/triangles.obj"); assertThat(objFile.ignoredCommandCount()).isEqualTo(0); ObjFile.TriangleGroup group1 = objFile.getGroup("FirstGroup"); assertThat(group1).isNotNull(); assertThat(group1.getTriangleCount()).isEqualTo(1); Triangle triangle1 = group1.getTriangle(1); assertThat(triangle1.p1()).isEqualTo(objFile.getVertex(1)); assertThat(triangle1.p2()).isEqualTo(objFile.getVertex(2)); assertThat(triangle1.p3()).isEqualTo(objFile.getVertex(3)); ObjFile.TriangleGroup group2 = objFile.getGroup("SecondGroup"); assertThat(group2).isNotNull(); assertThat(group2.getTriangleCount()).isEqualTo(1); Triangle triangle2 = group2.getTriangle(1); assertThat(triangle2.p1()).isEqualTo(objFile.getVertex(1)); assertThat(triangle2.p2()).isEqualTo(objFile.getVertex(3)); assertThat(triangle2.p3()).isEqualTo(objFile.getVertex(4)); } @Test // Scenario: Converting an OBJ file to a group public void asShape() throws Exception { ObjFile objFile = ObjFile.parseResource("/triangles.obj"); assertThat(objFile.ignoredCommandCount()).isEqualTo(0); Shape topShape = objFile.asShape(); // peek inside topShape assertThat(topShape).isInstanceOf(Group.class); List<Shape> innerShapes = ((Group) topShape).shapes(); assertThat(innerShapes.size()).isEqualTo(2); assertSingleTriangleGroup(innerShapes.get(0)); assertSingleTriangleGroup(innerShapes.get(1)); } public void assertSingleTriangleGroup(Shape shape) { assertThat(shape).isInstanceOf(Group.class); List<Shape> innerShapes = ((Group) shape).shapes(); assertThat(innerShapes.size()).isEqualTo(1); assertThat(innerShapes.get(0)).isInstanceOf(GeometryShape.class); GeometryShape geometryShape = (GeometryShape) innerShapes.get(0); assertThat(geometryShape.geometry()).isInstanceOf(Triangle.class); } @Test // Scenario: Vertex normal records public void vertexNormal() throws Exception { String input = String.join("\n", "vn 0 0 1", "vn 0.707 0 -0.707", "vn 1 2 3"); ObjFile objFile = ObjFile.parseContent(input); assertThat(objFile.ignoredCommandCount()).isEqualTo(0); assertThat(objFile.getNormalCount()).isEqualTo(3); assertThat(objFile.getNormal(1)).isEqualTo(Tuple.vector(0, 0, 1)); assertThat(objFile.getNormal(2)).isEqualTo(Tuple.vector(0.707, 0, -0.707)); assertThat(objFile.getNormal(3)).isEqualTo(Tuple.vector(1, 2, 3)); } @Test // Scenario: Faces with normals public void faceNormal() throws Exception { String input = String.join( "\n", "v 0 1 0", "v -1 0 0", "v 1 0 0", "", "vn -1 0 0", "vn 1 0 0", "vn 0 1 0", "", "f 1//3 2//1 3//2", "f 1/0/3 2/102/1 3/14/2"); ObjFile objFile = ObjFile.parseContent(input); assertThat(objFile.ignoredCommandCount()).isEqualTo(0); ObjFile.TriangleGroup group = objFile.getDefaultGroup(); assertThat(group.getTriangleCount()).isEqualTo(2); Triangle triangle1 = group.getTriangle(1); assertThat(triangle1.p1()).isEqualTo(objFile.getVertex(1)); assertThat(triangle1.p2()).isEqualTo(objFile.getVertex(2)); assertThat(triangle1.p3()).isEqualTo(objFile.getVertex(3)); assertThat(triangle1.n1()).isEqualTo(objFile.getNormal(3)); assertThat(triangle1.n2()).isEqualTo(objFile.getNormal(1)); assertThat(triangle1.n3()).isEqualTo(objFile.getNormal(2)); Triangle triangle2 = group.getTriangle(2); assertThat(triangle2.p1()).isEqualTo(objFile.getVertex(1)); assertThat(triangle2.p2()).isEqualTo(objFile.getVertex(2)); assertThat(triangle2.p3()).isEqualTo(objFile.getVertex(3)); assertThat(triangle2.n1()).isEqualTo(objFile.getNormal(3)); assertThat(triangle2.n2()).isEqualTo(objFile.getNormal(1)); assertThat(triangle2.n3()).isEqualTo(objFile.getNormal(2)); } /* @Test // Scenario: Bounding box public void boundingBox() throws Exception { String input = String.join("\n", "v 0 0 0", "v 0 0 1", "v 1 0 1", "v 1 1 0", "f 1 2 3", "f 2 3 4"); ObjFile objFile = ObjFile.parseContent(input); Shape box = objFile.boundingBox(); Ray xRay = Ray.create(Tuple.point(-1, 0.5, 0.5), Tuple.vector(1, 0, 0)); Intersections xxs = box.intersect(xRay); assertThat(xxs.length()).isEqualTo(2); assertThat(xxs.get(0).t()).isWithin(EPSILON).of(1); assertThat(xxs.get(1).t()).isWithin(EPSILON).of(2); Ray yRay = Ray.create(Tuple.point(0.5, -1, 0.5), Tuple.vector(0, 1, 0)); Intersections yxs = box.intersect(yRay); assertThat(yxs.length()).isEqualTo(2); assertThat(yxs.get(0).t()).isWithin(EPSILON).of(1); assertThat(yxs.get(1).t()).isWithin(EPSILON).of(2); Ray zRay = Ray.create(Tuple.point(0.5, 0.5, -1), Tuple.vector(0, 0, 1)); Intersections zxs = box.intersect(zRay); assertThat(zxs.length()).isEqualTo(2); assertThat(zxs.get(0).t()).isWithin(EPSILON).of(1); assertThat(zxs.get(1).t()).isWithin(EPSILON).of(2); } */ }
40.990654
98
0.678751
098b9d12f5de22230d7b9d2ca4625f47735c8618
366
package com.gong.url.exception; import com.gong.url.response.GlobalResponseCodeEnum; import java.util.Map; /** * 请求参数不合法异常 * * @author gongjunbing * @date 2020/03/12 23:46 **/ public class BadRequestException extends BaseException { public BadRequestException(Map<String, String> data) { super(GlobalResponseCodeEnum.BAD_REQUEST, data); } }
19.263158
58
0.729508
02bddfd082df6c28f37ffbb05dd40c35bb2edc08
812
package net.japan.kana.hakana.db; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import net.japan.kana.hakana.core.Const; import net.japan.kana.hakana.db.tables.Kana; /** * Author Vitalii Lebedynskyi * Date 10/24/14 */ public class SQLiteDBHelper extends SQLiteOpenHelper { public static final int VERSION = Const.DB.VERSION; public static final String NAME = Const.DB.NAME; public SQLiteDBHelper(Context context) { super(context, NAME, null, VERSION); } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { sqLiteDatabase.execSQL(Kana.CREATE_QUERY); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) { } }
25.375
90
0.740148
63e803860e88ae208d55822da7ba2014535bc1ed
1,470
import initializer.SimpleChatClientInitializer; import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import java.io.BufferedReader; import java.io.InputStreamReader; public class SimpleChatClient { private final String HOST_NAME; private final int PORT; public static void main(String[] args) { try { new SimpleChatClient("127.0.0.1", 8081).connect(); } catch (Exception e) { e.printStackTrace(); } } public SimpleChatClient(String HOST_NAME, int PORT) { this.HOST_NAME = HOST_NAME; this.PORT = PORT; } public void connect() throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group) .channel(NioSocketChannel.class) .remoteAddress(HOST_NAME, PORT) .handler(new SimpleChatClientInitializer()); Channel channel = bootstrap.connect().sync().channel(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); while (true) { channel.writeAndFlush(in.readLine() + "\r\n"); } } finally { group.shutdownGracefully().sync(); } } }
30
85
0.62449
76637b11347f39fd8b86be8dd51de3adb025748d
347
package commands; import exceptions.EndOfStackException; import exceptions.InvalidSyntaxException; import exceptions.SlogoException; public abstract class GuiCommand extends Command { /** * @param numberOfParameters * Creates GuiCommand */ public GuiCommand(int numberOfParameters) { super(numberOfParameters, "gui"); } }
17.35
50
0.760807
687e79404b94954ec19b1cc5773c3adb20365aed
1,755
/* * Copyright (C) 2019 sea * * 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 top.srsea.torque.sequence; import top.srsea.torque.function.Function2; import java.util.Iterator; public class Zip<T, U, R> extends Sequence<R> { private final Sequence<T> sequence; private final Iterable<U> other; private final Function2<? super T, ? super U, ? extends R> zipper; public Zip(Sequence<T> sequence, Iterable<U> other, Function2<? super T, ? super U, ? extends R> zipper) { this.sequence = sequence; this.other = other; this.zipper = zipper; } @Override public Iterator<R> iterator() { return new Iterator<R>() { final Iterator<T> iterator = sequence.iterator(); final Iterator<U> otherIterator = other.iterator(); @Override public boolean hasNext() { return iterator.hasNext() && otherIterator.hasNext(); } @Override public R next() { return zipper.invoke(iterator.next(), otherIterator.next()); } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }
30.789474
110
0.62906
0d4a5baca170f978a5a0a47fbfe13e432a44614f
6,655
package de.moliso.shelxle; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.sql.Date; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Properties; import android.app.AlertDialog; import android.app.ListActivity; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.os.Environment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; //import java.io.FileDescriptor; //import android.util.Log; public class SimpleExplorer extends ListActivity { private class Item { String item; String path; public Item(String it, String pt) { item = it; path = pt; } } private List<Item> pice; private String root = "/"; private TextView myPath; private Properties setting; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); myPath = (TextView) findViewById(R.id.path); setting = new Properties(); File sdcard = Environment.getExternalStorageDirectory(); try { setting.load(new FileInputStream(sdcard.getAbsolutePath() + "/.ShelXle/config")); } catch (IOException e) {// don't care if it don't work to load. } if (setting.containsKey("LASTDIR")) { getDir(setting.getProperty("LASTDIR")); } else getDir(sdcard.getAbsolutePath()); } private void getDir(String dirPath) { myPath.setText("Location: " + dirPath); pice = new ArrayList<Item>(); File f = new File(dirPath); File[] files = f.listFiles(); if (!dirPath.equals(root)) { pice.add(new Item(root, root)); pice.add(new Item("../", f.getParent())); } for (int i = 0; i < files.length; i++) { File file = files[i]; if (file.isDirectory()) { pice.add(new Item(file.getName().concat("/"), file.getPath())); } else if ((file.getName().endsWith(".res")) || (file.getName().endsWith(".ins"))) { Date lastModDate = new Date(file.lastModified()); String size = String.valueOf(file.length() / 1024) + "kB"; pice.add(new Item(String.format("%-30s %12s %20s", file.getName(), lastModDate.toString(), size), file .getPath())); } } Collections.sort(pice, new Comparator<Item>() { @Override public int compare(Item i1, Item i2) { if (i1.item == "/") return -900000; if (i2.item == "/") return 900000; if ((i1.item.contains("/") && (!i2.item.contains("/")))) return -1000+i1.item.compareToIgnoreCase(i2.item); else if ((i2.item.contains("/") && (!i1.item.contains("/")))) return 1000-i1.item.compareToIgnoreCase(i2.item); return i1.item.compareToIgnoreCase(i2.item); } }); ArrayList<String> item = new ArrayList<String>(); for (int i = 0; i < pice.size(); i++) item.add(pice.get(i).item); MyCustomAdapter fileList = new MyCustomAdapter(); fileList.setData(item); setListAdapter(fileList); } private class MyCustomAdapter extends BaseAdapter { private ArrayList<String> mData = new ArrayList<String>(); private LayoutInflater mInflater; public MyCustomAdapter() { mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public void setData(ArrayList<String> data) { mData = data; } @Override public int getCount() { return mData.size(); } @Override public String getItem(int position) { return mData.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { //System.out.println("getView " + position + " " + convertView); ViewHolder holder = null; //if (convertView == null) { convertView = mInflater.inflate(R.layout.row, null); holder = new ViewHolder(); if (mData.get(position).contains("res")) { convertView = mInflater.inflate(R.layout.row, null); holder.textView = (TextView) convertView .findViewById(R.id.rowtext1); }else if (mData.get(position).contains("/")) { convertView = mInflater.inflate(R.layout.dirrow, null); holder.textView = (TextView) convertView .findViewById(R.id.rowtext3); } else { convertView = mInflater.inflate(R.layout.altrow, null); holder.textView = (TextView) convertView .findViewById(R.id.rowtext2); } convertView.setTag(holder); //} else { // holder = (ViewHolder) convertView.getTag(); //} holder.textView.setText(mData.get(position)); return convertView; } } public static class ViewHolder { public TextView textView; } @Override protected void onListItemClick(ListView l, View v, int position, long id) { File file = new File(pice.get(position).path); if (file.isDirectory()) { if (file.canRead()) { try { setting.setProperty("LASTDIR", pice.get(position).path); File sdcard = Environment.getExternalStorageDirectory(); File dir = new File(sdcard, ".ShelXle/"); if (!dir.exists()) dir.mkdir(); setting.store(new FileOutputStream(sdcard.getAbsolutePath() + "/.ShelXle/config"), null); } catch (IOException e) { AlertDialog.Builder adb = new AlertDialog.Builder(this); adb.setTitle("Error!"); adb.setMessage(e.getMessage()); adb.setCancelable(true); adb.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); adb.create(); adb.show(); } getDir(pice.get(position).path); } else { new AlertDialog.Builder(this) .setIcon(R.drawable.ic_launcher) .setTitle( "[" + file.getName() + "] folder can't be read!") .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).show(); } } else { // resultFile=file.getAbsolutePath(); Intent returnIntent = getIntent(); returnIntent.putExtra("result", file.getAbsolutePath()); File sdcard = Environment.getExternalStorageDirectory(); try { setting.store(new FileOutputStream(sdcard.getAbsolutePath() + "/.ShelXle/config"), null); } catch (IOException e) { } setResult(RESULT_OK, returnIntent); finish(); } } }
27.962185
82
0.664914
091a9bba6f11523638d6ca36bb3b15ce50d54b31
3,853
/* * Copyright © 02.10.2015 by O.I.Mudannayake. All Rights Reserved. */ package database.sql.type; import database.sql.SQL; import java.sql.SQLException; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.table.DefaultTableModel; import entity.item.type.SRNItem; import entity.note.type.SRN; /** * * @author Ivantha */ public class SalesReturnSQL extends SQL { public String generateNewID() { String preID = this.getLastValue("srn", "srn_no"); String idX = String.format("%07d", Integer.parseInt(preID.substring(3, 10)) + 1); result = "sn." + idX; return result; } public void newSRN(SRN srn) { query = "INSERT INTO srn(srn_no, date, invoice_no, description, payment, employee) VALUES (" + "'" + srn.getSrnNo() + "'," + "'" + srn.getDate() + "'," + "'" + srn.getInvoiceNo() + "'," + "'" + srn.getDescription() + "'," + "'" + srn.getPayment().getId() + "'," + "'" + srn.getEmployee().getEmployeeID() + "')"; c.setQuery(query); } public void newSRNItemList(String prnNo, SRNItem srnItem) { query = "INSERT INTO srn_item_list(srn_no, item_no, unit_price, qty) VALUES (" + "'" + prnNo + "'," + "'" + srnItem.getItemNo() + "'," + "'" + srnItem.getUnitPrice() + "'," + "'" + srnItem.getQty() + "')"; c.setQuery(query); } public void getInvoiceDetail(String invoiceNo, DefaultTableModel dtm) { query = "SELECT item.item_no, item.name, invoice_item_list.qty, invoice_item_list.unit_price FROM item, invoice_item_list WHERE item.item_no = invoice_item_list.item_no AND invoice_item_list.invoice_no = '" + invoiceNo + "'"; rs = c.getQuery(query); try { while (rs.next()) { String itemNo = rs.getString("item_no"); String itemName = rs.getString("name"); int itemQty = Integer.parseInt(rs.getString("qty")); double unitPrice = Double.parseDouble(rs.getString("unit_price")); dtm.addRow(new Object[]{itemNo, itemName, itemQty, unitPrice}); } } catch (SQLException ex) { Logger.getLogger(ItemManagementSQL.class.getName()).log(Level.SEVERE, null, ex); } } public void getInvoiceList(ArrayList<String> invoiceList) { query = "SELECT invoice_no FROM invoice ORDER BY row ASC"; rs = c.getQuery(query); try { while (rs.next()) { String invoiceNo = rs.getString("invoice_no"); invoiceList.add(invoiceNo); } } catch (SQLException ex) { Logger.getLogger(GoodReceiveSQL.class.getName()).log(Level.SEVERE, null, ex); } } public void showSRN(DefaultTableModel dtm) { query = "SELECT srn.srn_no, srn.date, srn.invoice_no, payment.amount, employee.name FROM srn " + "LEFT JOIN payment ON srn.payment = payment.payment_id " + "LEFT JOIN employee ON srn.employee = employee.employee_id"; rs = c.getQuery(query); try { while (rs.next()) { String srnNo = rs.getString("srn.srn_no"); String date = rs.getString("srn.date"); String invoiceNo = rs.getString("srn.invoice_no"); String payment = rs.getString("payment.amount"); String employee = rs.getString("employee.name"); dtm.addRow(new Object[]{srnNo, date, invoiceNo, payment, employee}); } } catch (SQLException ex) { Logger.getLogger(EmployeeManagementSQL.class.getName()).log(Level.SEVERE, null, ex); } } }
37.77451
233
0.57306
c010a494c6260ae5b287aafdd36389531a5b5299
1,177
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) // Source File Name: AttributesRenderer.java package com.ecap.log4j.or.sax; import com.ecap.log4j.or.ObjectRenderer; import org.xml.sax.Attributes; public class AttributesRenderer implements ObjectRenderer { public AttributesRenderer() { } public String doRender(Object obj) { if(obj instanceof Attributes) { StringBuffer stringbuffer = new StringBuffer(); Attributes attributes = (Attributes)obj; int i = attributes.getLength(); boolean flag = true; for(int j = 0; j < i; j++) { if(flag) flag = false; else stringbuffer.append(", "); stringbuffer.append(attributes.getQName(j)); stringbuffer.append('='); stringbuffer.append(attributes.getValue(j)); } return stringbuffer.toString(); } else { return obj.toString(); } } }
26.155556
62
0.558199
fa6c7d2b644f999f61c6ba7dd7f43f05442d9028
435
package com.iflytek.gulimall.product.vo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; import java.util.List; /** * 二级分类 */ @Data @ToString @NoArgsConstructor @AllArgsConstructor public class Catalog2Vo { private String catalog1Id;//1级分类id即父id private String id;//2级分类id private String name;//分类名称 private List<Catalog3Vo> catalog3List;//三级分类list }
18.913043
52
0.770115
3c2d0ef7b9adf891b3c8c159273b6fce7566ec56
4,194
/** Copyright 2015 Osiris Project Team 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.fhc25.percepcion.osiris.mapviewer.ui.application; import android.app.Application; import android.os.Bundle; import com.fhc25.percepcion.osiris.mapviewer.R; import com.fhc25.percepcion.osiris.mapviewer.common.data.IBackendCaller; import com.fhc25.percepcion.osiris.mapviewer.common.data.OsirisBackendCaller; import com.fhc25.percepcion.osiris.mapviewer.data.IOsirisEndpoint; import com.fhc25.percepcion.osiris.mapviewer.data.OsirisEndpoint; import com.fhc25.percepcion.osiris.mapviewer.manager.ApplicationManager; import com.fhc25.percepcion.osiris.mapviewer.manager.IApplicationManagerProvider; import com.fhc25.percepcion.osiris.mapviewer.model.location.MetaData; import com.fhc25.percepcion.osiris.mapviewer.model.states.InternalState; import com.fhc25.percepcion.osiris.mapviewer.model.states.InternalStatePersistor; import com.fhc25.percepcion.osiris.mapviewer.model.states.InternalViewState; import com.fhc25.percepcion.osiris.mapviewer.model.states.api.IInternalState; import com.fhc25.percepcion.osiris.mapviewer.model.states.api.IInternalStateManager; import com.fhc25.percepcion.osiris.mapviewer.model.states.api.IInternalStatePersistor; import com.fhc25.percepcion.osiris.mapviewer.model.states.api.IInternalViewState; public class OsirisApplication extends Application implements IApplicationManagerProvider, IInternalStateManager { private static final String TAG = OsirisApplication.class.getName(); private ApplicationManager applicationManager; private IInternalState internalState; private IInternalViewState internalViewState; private IBackendCaller backendCaller; private IOsirisEndpoint endpoint; private IInternalStatePersistor internalStatePersistor; @Override public void onCreate() { String appHost = getResources().getString(R.string.osiris_app_host); String appId = getResources().getString(R.string.osiris_app_id); createApplicationManager(appId, appHost); internalStatePersistor = new InternalStatePersistor(getBaseContext(), this); } @Override public ApplicationManager getApplicationManager() { return applicationManager; } private void createApplicationManager(String appId, String host) { endpoint = new OsirisEndpoint(host); internalState = new InternalState(); internalViewState = new InternalViewState(internalState); backendCaller = new OsirisBackendCaller(); applicationManager = new ApplicationManager(getApplicationContext(), internalState, endpoint, backendCaller, appId); } @Override public IInternalViewState getViewState() { return internalViewState; } @Override public void saveToBundle(Bundle instanceState) { applicationManager.getBundleInternalStateManager().saveInternalState(instanceState, internalState); } @Override public void loadFromBundle(Bundle instanceState) { applicationManager.getBundleInternalStateManager().loadInternalState(instanceState, internalState); } @Override public void persistInternalStatePersistent() { internalStatePersistor.persistInternalStatePersistent(internalState); } @Override public void persistInternalStateVariable() { internalStatePersistor.persistInternalStateVariable(internalState); } @Override public void loadInternalState() { internalStatePersistor.loadInternalState(internalState); } @Override public MetaData persistedDataExists() { return internalStatePersistor.persistedDataExists(); } }
37.783784
124
0.779447
0dc2e7255e1ed3eea7f81ddd6f858ed7722da80a
2,126
package in.cleartax.dropwizard.sharding.utils.exception; import com.google.common.base.Verify; import org.checkerframework.checker.nullness.qual.Nullable; /** * Created on 2019-01-15 */ public class Preconditions { private Preconditions() { } /** * Ensures the truth of an expression involving one or more parameters to the calling method. * * @param expression a boolean expression * @param errorMessage the exception message to use if the check fails; will be converted to a * string using {@link String#valueOf(Object)} * @throws InvalidTenantArgumentException if {@code expression} is false */ public static void checkArgument(boolean expression, @Nullable Object errorMessage) { if (!expression) { throw new InvalidTenantArgumentException(String.valueOf(errorMessage)); } } /** * Ensures that an object reference passed as a parameter to the calling method is not null. * * @param reference an object reference * @return the non-null reference that was validated * @throws NullPointerException if {@code reference} is null * @see Verify#verifyNotNull Verify.verifyNotNull() */ public static <T> T checkNotNull(T reference) { if (reference == null) { throw new NullPointerException(); } return reference; } /** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * * @param expression a boolean expression * @param errorMessage the exception message to use if the check fails; will be converted to a * string using {@link String#valueOf(Object)} * @throws InvalidTenantStateException if {@code expression} is false * @see Verify#verify Verify.verify() */ public static void checkState(boolean expression, @Nullable Object errorMessage) { if (!expression) { throw new InvalidTenantStateException(String.valueOf(errorMessage)); } } }
36.655172
98
0.667451
6a852ebd3bd7287acc41e2df529b29f0d9361a16
2,568
/** * Copyright 2020 Webank. * * <p>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 * * <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. */ package com.webank.blockchain.gov.acct.vo; import com.webank.blockchain.gov.acct.enums.RequestEnum; import java.math.BigInteger; import lombok.Data; import lombok.experimental.Accessors; import lombok.extern.slf4j.Slf4j; import org.fisco.bcos.sdk.abi.datatypes.generated.tuples.generated.Tuple8; /** * VoteRequestInfo @Description: VoteRequestInfo * * @author maojiayu * @data Jul 24, 2020 6:13:55 PM */ @Data @Accessors(chain = true) @Slf4j public class VoteRequestInfo { private BigInteger requestId; private String requestAddress = ""; private int threshold; private int weight; private int txType; private int status; private String newAddress = ""; private int newValue; public VoteRequestInfo forward( Tuple8< BigInteger, String, BigInteger, BigInteger, BigInteger, BigInteger, String, BigInteger> t) { this.requestId = t.getValue1(); this.requestAddress = t.getValue2(); this.threshold = t.getValue3().intValue(); this.weight = t.getValue4().intValue(); this.txType = t.getValue5().intValue(); this.status = t.getValue6().intValue(); this.newAddress = t.getValue7(); this.newValue = t.getValue8().intValue(); return this; } public void print() { log.info( "the current vote info: \n -------------------------------------- \n request id [ {} ] \n request address is [ {} ] \n vote type: [ {} ] \n threshod is [ {} ] \n weight is [ {} ] \n vote passed? [ {} ] \n", requestId, requestAddress, RequestEnum.getNameByStatics(txType), threshold, weight, status == 1); } }
34.24
222
0.583333
371bfee5840e9b5d3411fa9efc2ad0143764cb26
18,579
/* * Copyright (c) 2019 Im2be <https://github.com/Im2be> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 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 OWNER 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 net.runelite.client.plugins.cerberus; import com.google.common.collect.ComparisonChain; import com.google.inject.Provides; import java.util.ArrayList; import java.util.List; import java.util.Set; import javax.annotation.Nullable; import javax.inject.Inject; import javax.inject.Singleton; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import net.runelite.api.Actor; import net.runelite.api.Client; import net.runelite.api.GameState; import net.runelite.api.InventoryID; import net.runelite.api.Item; import net.runelite.api.ItemContainer; import net.runelite.api.NPC; import net.runelite.api.Player; import net.runelite.api.Prayer; import net.runelite.api.Projectile; import net.runelite.api.Skill; import net.runelite.api.coords.WorldPoint; import net.runelite.api.events.AnimationChanged; import net.runelite.api.events.GameStateChanged; import net.runelite.api.events.GameTick; import net.runelite.api.events.NpcDespawned; import net.runelite.api.events.NpcSpawned; import net.runelite.api.events.ProjectileSpawned; import net.runelite.client.config.ConfigManager; import net.runelite.client.eventbus.Subscribe; import net.runelite.client.game.ItemManager; import net.runelite.client.plugins.Plugin; import net.runelite.client.plugins.PluginDescriptor; import net.runelite.client.plugins.cerberus.domain.Cerberus; import net.runelite.client.plugins.cerberus.domain.CerberusAttack; import net.runelite.client.plugins.cerberus.domain.Ghost; import net.runelite.client.plugins.cerberus.domain.Phase; import net.runelite.client.plugins.cerberus.overlays.CurrentAttackOverlay; import net.runelite.client.plugins.cerberus.overlays.PrayerOverlay; import net.runelite.client.plugins.cerberus.overlays.SceneOverlay; import net.runelite.client.plugins.cerberus.overlays.UpcomingAttackOverlay; import net.runelite.client.ui.overlay.OverlayManager; import net.runelite.http.api.item.ItemEquipmentStats; import net.runelite.http.api.item.ItemStats; import org.pf4j.Extension; @Slf4j @Singleton @Extension @PluginDescriptor( name = "Cerberus", enabledByDefault = false, description = "A plugin for the Cerberus boss.", tags = {"cerberus", "hellhound"} ) public class CerberusPlugin extends Plugin { private static final int ANIMATION_ID_IDLE = -1; private static final int ANIMATION_ID_STAND_UP = 4486; private static final int ANIMATION_ID_SIT_DOWN = 4487; private static final int ANIMATION_ID_FLINCH = 4489; private static final int ANIMATION_ID_RANGED = 4490; private static final int ANIMATION_ID_MELEE = 4491; private static final int ANIMATION_ID_LAVA = 4493; private static final int ANIMATION_ID_GHOSTS = 4494; private static final int ANIMATION_ID_DEATH = 4495; private static final int PROJECTILE_ID_MAGIC = 1242; private static final int PROJECTILE_ID_RANGE = 1245; private static final int GHOST_PROJECTILE_ID_RANGE = 34; private static final int GHOST_PROJECTILE_ID_MAGIC = 100; private static final int GHOST_PROJECTILE_ID_MELEE = 1248; private static final int PROJECTILE_ID_NO_FUCKING_IDEA = 15; private static final int PROJECTILE_ID_LAVA = 1247; private static final Set<Integer> REGION_IDS = Set.of(4883, 5140, 5395); @Inject private Client client; @Inject private CerberusConfig config; @Inject private ItemManager itemManager; @Inject private OverlayManager overlayManager; @Inject private SceneOverlay sceneOverlay; @Inject private PrayerOverlay prayerOverlay; @Inject private CurrentAttackOverlay currentAttackOverlay; @Inject private UpcomingAttackOverlay upcomingAttackOverlay; @Getter private final List<NPC> ghosts = new ArrayList<>(); @Getter private final List<CerberusAttack> upcomingAttacks = new ArrayList<>(); private final List<Long> tickTimestamps = new ArrayList<>(); @Getter @Nullable private Prayer prayer = Prayer.PROTECT_FROM_MAGIC; @Getter @Nullable private Cerberus cerberus; @Getter private int gameTick; private int tickTimestampIndex; @Getter private long lastTick; private boolean inArena; @Provides CerberusConfig getConfig(final ConfigManager configManager) { return configManager.getConfig(CerberusConfig.class); } @Override protected void startUp() { if (client.getGameState() != GameState.LOGGED_IN || !inCerberusRegion()) { return; } init(); } private void init() { inArena = true; overlayManager.add(sceneOverlay); overlayManager.add(prayerOverlay); overlayManager.add(currentAttackOverlay); overlayManager.add(upcomingAttackOverlay); } @Override protected void shutDown() { inArena = false; overlayManager.remove(sceneOverlay); overlayManager.remove(prayerOverlay); overlayManager.remove(currentAttackOverlay); overlayManager.remove(upcomingAttackOverlay); ghosts.clear(); upcomingAttacks.clear(); tickTimestamps.clear(); prayer = Prayer.PROTECT_FROM_MAGIC; cerberus = null; gameTick = 0; tickTimestampIndex = 0; lastTick = 0; } @Subscribe private void onGameStateChanged(final GameStateChanged event) { final GameState gameState = event.getGameState(); switch (gameState) { case LOGGED_IN: if (inCerberusRegion()) { if (!inArena) { init(); } } else { if (inArena) { shutDown(); } } break; case HOPPING: case LOGIN_SCREEN: if (inArena) { shutDown(); } break; default: break; } } @Subscribe private void onGameTick(final GameTick event) { if (cerberus == null) { return; } if (tickTimestamps.size() <= tickTimestampIndex) { tickTimestamps.add(System.currentTimeMillis()); } else { tickTimestamps.set(tickTimestampIndex, System.currentTimeMillis()); } long min = 0; for (int i = 0; i < tickTimestamps.size(); ++i) { if (min == 0) { min = tickTimestamps.get(i) + 600 * ((tickTimestampIndex - i + 5) % 5); } else { min = Math.min(min, tickTimestamps.get(i) + 600 * ((tickTimestampIndex - i + 5) % 5)); } } tickTimestampIndex = (tickTimestampIndex + 1) % 5; lastTick = min; ++gameTick; if (config.calculateAutoAttackPrayer() && gameTick % 10 == 3) { setAutoAttackPrayer(); } calculateUpcomingAttacks(); if (ghosts.size() > 1) { /* * First, sort by the southernmost ghost (e.g with lowest y). * Then, sort by the westernmost ghost (e.g with lowest x). * This will give use the current wave and order of the ghosts based on what ghost will attack first. */ ghosts.sort((a, b) -> ComparisonChain.start() .compare(a.getLocalLocation().getY(), b.getLocalLocation().getY()) .compare(a.getLocalLocation().getX(), b.getLocalLocation().getX()) .result()); } } @Subscribe private void onProjectileSpawned(final ProjectileSpawned event) { if (cerberus == null) { return; } final Projectile projectile = event.getProjectile(); final int hp = cerberus.getHp(); final Phase expectedAttack = cerberus.getNextAttackPhase(1, hp); switch (projectile.getId()) { case PROJECTILE_ID_MAGIC: log.debug("gameTick={}, attack={}, cerbHp={}, expectedAttack={}, cerbProjectile={}", gameTick, cerberus.getPhaseCount() + 1, hp, expectedAttack, "MAGIC"); if (expectedAttack != Phase.TRIPLE) { cerberus.nextPhase(Phase.AUTO); } else { cerberus.setLastTripleAttack(Cerberus.Attack.MAGIC); } cerberus.doProjectileOrAnimation(gameTick, Cerberus.Attack.MAGIC); break; case PROJECTILE_ID_RANGE: log.debug("gameTick={}, attack={}, cerbHp={}, expectedAttack={}, cerbProjectile={}", gameTick, cerberus.getPhaseCount() + 1, hp, expectedAttack, "RANGED"); if (expectedAttack != Phase.TRIPLE) { cerberus.nextPhase(Phase.AUTO); } else { cerberus.setLastTripleAttack(Cerberus.Attack.RANGED); } cerberus.doProjectileOrAnimation(gameTick, Cerberus.Attack.RANGED); break; case GHOST_PROJECTILE_ID_RANGE: if (!ghosts.isEmpty()) { log.debug("gameTick={}, attack={}, cerbHp={}, expectedAttack={}, ghostProjectile={}", gameTick, cerberus.getPhaseCount() + 1, hp, expectedAttack, "RANGED"); } break; case GHOST_PROJECTILE_ID_MAGIC: if (!ghosts.isEmpty()) { log.debug("gameTick={}, attack={}, cerbHp={}, expectedAttack={}, ghostProjectile={}", gameTick, cerberus.getPhaseCount() + 1, hp, expectedAttack, "MAGIC"); } break; case GHOST_PROJECTILE_ID_MELEE: if (!ghosts.isEmpty()) { log.debug("gameTick={}, attack={}, cerbHp={}, expectedAttack={}, ghostProjectile={}", gameTick, cerberus.getPhaseCount() + 1, hp, expectedAttack, "MELEE"); } break; case PROJECTILE_ID_NO_FUCKING_IDEA: case PROJECTILE_ID_LAVA: //Lava default: break; } } @Subscribe private void onAnimationChanged(final AnimationChanged event) { if (cerberus == null) { return; } final Actor actor = event.getActor(); final NPC npc = cerberus.getNpc(); if (npc == null || actor != npc) { return; } final int animationId = npc.getAnimation(); final int hp = cerberus.getHp(); final Phase expectedAttack = cerberus.getNextAttackPhase(1, hp); switch (animationId) { case ANIMATION_ID_MELEE: log.debug("gameTick={}, attack={}, cerbHp={}, expectedAttack={}, cerbAnimation={}", gameTick, cerberus.getPhaseCount() + 1, hp, expectedAttack, "MELEE"); cerberus.setLastTripleAttack(null); cerberus.nextPhase(expectedAttack); cerberus.doProjectileOrAnimation(gameTick, Cerberus.Attack.MELEE); break; case ANIMATION_ID_LAVA: log.debug("gameTick={}, attack={}, cerbHp={}, expectedAttack={}, cerbAnimation={}", gameTick, cerberus.getPhaseCount() + 1, hp, expectedAttack, "LAVA"); cerberus.nextPhase(Phase.LAVA); cerberus.doProjectileOrAnimation(gameTick, Cerberus.Attack.LAVA); break; case ANIMATION_ID_GHOSTS: log.debug("gameTick={}, attack={}, cerbHp={}, expectedAttack={}, cerbAnimation={}", gameTick, cerberus.getPhaseCount() + 1, hp, expectedAttack, "GHOSTS"); cerberus.nextPhase(Phase.GHOSTS); cerberus.setLastGhostYellTick(gameTick); cerberus.setLastGhostYellTime(System.currentTimeMillis()); cerberus.doProjectileOrAnimation(gameTick, Cerberus.Attack.GHOSTS); break; case ANIMATION_ID_SIT_DOWN: case ANIMATION_ID_STAND_UP: cerberus = new Cerberus(cerberus.getNpc()); gameTick = 0; lastTick = System.currentTimeMillis(); upcomingAttacks.clear(); tickTimestamps.clear(); tickTimestampIndex = 0; cerberus.doProjectileOrAnimation(gameTick, Cerberus.Attack.SPAWN); break; case ANIMATION_ID_IDLE: case ANIMATION_ID_FLINCH: case ANIMATION_ID_RANGED: break; case ANIMATION_ID_DEATH: cerberus = null; ghosts.clear(); break; default: log.debug("gameTick={}, animationId={} (UNKNOWN)", gameTick, animationId); break; } } @Subscribe private void onNpcSpawned(final NpcSpawned event) { final NPC npc = event.getNpc(); if (cerberus == null && npc != null && npc.getName() != null && npc.getName().toLowerCase().contains("cerberus")) { log.debug("onNpcSpawned name={}, id={}", npc.getName(), npc.getId()); cerberus = new Cerberus(npc); gameTick = 0; tickTimestampIndex = 0; lastTick = System.currentTimeMillis(); upcomingAttacks.clear(); tickTimestamps.clear(); } if (cerberus == null) { return; } final Ghost ghost = Ghost.fromNPC(npc); if (ghost != null) { ghosts.add(npc); } } @Subscribe private void onNpcDespawned(final NpcDespawned event) { final NPC npc = event.getNpc(); if (npc != null && npc.getName() != null && npc.getName().toLowerCase().contains("cerberus")) { cerberus = null; ghosts.clear(); log.debug("onNpcDespawned name={}, id={}", npc.getName(), npc.getId()); } if (cerberus == null && !ghosts.isEmpty()) { ghosts.clear(); return; } ghosts.remove(event.getNpc()); } private void calculateUpcomingAttacks() { upcomingAttacks.clear(); final Cerberus.Attack lastCerberusAttack = cerberus.getLastAttack(); if (lastCerberusAttack == null) { return; } final int lastCerberusAttackTick = cerberus.getLastAttackTick(); final int hp = cerberus.getHp(); final Phase expectedPhase = cerberus.getNextAttackPhase(1, hp); final Phase lastPhase = cerberus.getLastAttackPhase(); int tickDelay = 0; if (lastPhase != null) { tickDelay = lastPhase.getTickDelay(); } for (int tick = gameTick + 1; tick <= gameTick + 10; ++tick) { if (ghosts.size() == 3) { final Ghost ghost; if (cerberus.getLastGhostYellTick() == tick - 13) { ghost = Ghost.fromNPC(ghosts.get(ghosts.size() - 3)); } else if (cerberus.getLastGhostYellTick() == tick - 15) { ghost = Ghost.fromNPC(ghosts.get(ghosts.size() - 2)); } else if (cerberus.getLastGhostYellTick() == tick - 17) { ghost = Ghost.fromNPC(ghosts.get(ghosts.size() - 1)); } else { ghost = null; } if (ghost != null) { switch (ghost.getType()) { case ATTACK: upcomingAttacks.add(new CerberusAttack(tick, Cerberus.Attack.GHOST_MELEE)); break; case RANGED: upcomingAttacks.add(new CerberusAttack(tick, Cerberus.Attack.GHOST_RANGED)); break; case MAGIC: upcomingAttacks.add(new CerberusAttack(tick, Cerberus.Attack.GHOST_MAGIC)); break; } continue; } } if (expectedPhase == Phase.TRIPLE) { if (cerberus.getLastTripleAttack() == Cerberus.Attack.MAGIC) { if (lastCerberusAttackTick + 4 == tick) { upcomingAttacks.add(new CerberusAttack(tick, Cerberus.Attack.RANGED)); } else if (lastCerberusAttackTick + 7 == tick) { upcomingAttacks.add(new CerberusAttack(tick, Cerberus.Attack.MELEE)); } } else if (cerberus.getLastTripleAttack() == Cerberus.Attack.RANGED) { if (lastCerberusAttackTick + 4 == tick) { upcomingAttacks.add(new CerberusAttack(tick, Cerberus.Attack.MELEE)); } } else if (cerberus.getLastTripleAttack() == null) { if (lastCerberusAttackTick + tickDelay + 2 == tick) { upcomingAttacks.add(new CerberusAttack(tick, Cerberus.Attack.MAGIC)); } else if (lastCerberusAttackTick + tickDelay + 5 == tick) { upcomingAttacks.add(new CerberusAttack(tick, Cerberus.Attack.RANGED)); } } } else if (expectedPhase == Phase.AUTO) { if (lastCerberusAttackTick + tickDelay + 1 == tick) { if (prayer == Prayer.PROTECT_FROM_MAGIC) { upcomingAttacks.add(new CerberusAttack(tick, Cerberus.Attack.MAGIC)); } else if (prayer == Prayer.PROTECT_FROM_MISSILES) { upcomingAttacks.add(new CerberusAttack(tick, Cerberus.Attack.RANGED)); } else if (prayer == Prayer.PROTECT_FROM_MELEE) { upcomingAttacks.add(new CerberusAttack(tick, Cerberus.Attack.MELEE)); } } } } } private void setAutoAttackPrayer() { int defenseStab = 0, defenseMagic = 0, defenseRange = 0; final ItemContainer itemContainer = client.getItemContainer(InventoryID.EQUIPMENT); if (itemContainer != null) { final Item[] items = itemContainer.getItems(); for (final Item item : items) { if (item == null) { continue; } final ItemStats itemStats = itemManager.getItemStats(item.getId(), false); if (itemStats == null) { continue; } final ItemEquipmentStats itemStatsEquipment = itemStats.getEquipment(); if (itemStatsEquipment == null) { continue; } defenseStab += itemStatsEquipment.getDstab(); defenseMagic += itemStatsEquipment.getDmagic(); defenseRange += itemStatsEquipment.getDrange(); } } final int magicLvl = client.getBoostedSkillLevel(Skill.MAGIC); final int defenseLvl = client.getBoostedSkillLevel(Skill.DEFENCE); final int magicDefenseTotal = (int) (((double) magicLvl) * 0.7 + ((double) defenseLvl) * 0.3) + defenseMagic; final int rangeDefenseTotal = defenseLvl + defenseRange; int meleeDefenseTotal = defenseLvl + defenseStab; final Player player = client.getLocalPlayer(); if (player != null) { final WorldPoint worldPointPlayer = client.getLocalPlayer().getWorldLocation(); final WorldPoint worldPointCerberus = cerberus.getNpc().getWorldLocation(); if (worldPointPlayer.getX() < worldPointCerberus.getX() - 1 || worldPointPlayer.getX() > worldPointCerberus.getX() + 5 || worldPointPlayer.getY() < worldPointCerberus.getY() - 1 || worldPointPlayer.getY() > worldPointCerberus.getY() + 5) { meleeDefenseTotal = Integer.MAX_VALUE; } } if (magicDefenseTotal <= rangeDefenseTotal && magicDefenseTotal <= meleeDefenseTotal) { prayer = Prayer.PROTECT_FROM_MAGIC; } else if (rangeDefenseTotal <= meleeDefenseTotal) { prayer = Prayer.PROTECT_FROM_MISSILES; } else { prayer = Prayer.PROTECT_FROM_MELEE; } } private boolean inCerberusRegion() { for (final int regionId : client.getMapRegions()) { if (REGION_IDS.contains(regionId)) { return true; } } return false; } }
26.465812
161
0.701706
0c059cc3ff8896c6833fde9fe212bbf7da31e770
496
package cn.lab212.mall.auth.service; import cn.lab212.mall.common.domain.UserDto; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; /** * @author yinck * @version 1.0 * @date 2021-09-29 15:26 */ @FeignClient("mall-portal") public interface UmsMemberService { @GetMapping("/sso/loadByUsername") UserDto loadUserByUsername(@RequestParam String username); }
26.105263
62
0.778226
625d8609bfeb98c7914f8e3f4c3bf0676f5061fd
1,910
package com.qiniu.service.media; import java.io.*; import java.net.URL; import java.util.ArrayList; import java.util.List; public class M3U8Manager { public List<VideoTS> getVideoTSListByUrl(String m3u8Url) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new URL(m3u8Url).openStream())); String rootUrl = m3u8Url.substring(0, m3u8Url.indexOf("/", 8) + 1); List<VideoTS> ret = getVideoTSList(bufferedReader, rootUrl); bufferedReader.close(); return ret; } public List<VideoTS> getVideoTSListByFile(String rootUrl, String m3u8FilePath) throws IOException { FileReader fileReader = new FileReader(new File(m3u8FilePath)); BufferedReader bufferedReader = new BufferedReader(fileReader); List<VideoTS> ret = getVideoTSList(bufferedReader, rootUrl); bufferedReader.close(); return ret; } public List<VideoTS> getVideoTSList(BufferedReader bufferedReader, String rootUrl) throws IOException { List<VideoTS> ret = new ArrayList<>(); String line; float seconds = 0; while ((line = bufferedReader.readLine()) != null) { if (line.startsWith("#")) { if (line.startsWith("#EXTINF:")) { line = line.substring(8, line.indexOf(",")); seconds = Float.parseFloat(line); } continue; } String url = line.startsWith("http") ? line : line.startsWith("/") ? rootUrl + line.substring(1) : rootUrl + line; if (line.endsWith(".m3u8")) { List<VideoTS> tsList = getVideoTSListByUrl(url); ret.addAll(tsList); } else { ret.add(new VideoTS(url, seconds)); } seconds = 0; } return ret; } }
31.833333
113
0.593717
85e3a2ff075310a8cb8d105ad8f83c0f045decd2
1,546
package com.galaxysoft.photogallery.web.config; import org.springframework.web.filter.CharacterEncodingFilter; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; import javax.servlet.Filter; import javax.servlet.ServletRegistration; /** * Created by Illia IZOTOV on 20/08/15. */ public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected String[] getServletMappings() { return new String[]{"/"}; } @Override protected Class<?>[] getRootConfigClasses() { return new Class<?>[]{ApplicationConfig.class, RepositoryConfig.class/*, SecurityConfig.class*/}; } @Override protected Class<?>[] getServletConfigClasses() { return new Class<?>[]{WebMvcConfig.class}; } @Override protected Filter[] getServletFilters() { CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter(); characterEncodingFilter.setEncoding("UTF-8"); characterEncodingFilter.setForceEncoding(true); //DelegatingFilterProxy securityFilterChain = new DelegatingFilterProxy("springSecurityFilterChain"); return new Filter[]{characterEncodingFilter/*, securityFilterChain*/}; } @Override protected void customizeRegistration(ServletRegistration.Dynamic registration) { registration.setInitParameter("defaultHtmlEscape", "true"); registration.setInitParameter("spring.profiles.active", "default"); } }
33.608696
109
0.73674
aaa3e382833aac2afcf0b3f66b8f760922bf0781
1,492
package com.alibaba.simpleimage.analyze.testbed; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import javax.imageio.ImageIO; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import com.alibaba.simpleimage.analyze.sift.SIFT; import com.alibaba.simpleimage.analyze.sift.render.RenderImage; /** * Unit test for simple App. */ public class AppTest extends TestCase { /** * Create the test case * * @param testName * name of the test case */ public AppTest(String testName) { super(testName); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite(AppTest.class); } /** * Rigourous Test :-) * * @throws IOException * @throws */ public void testApp() throws IOException { String url = "https://cloud.githubusercontent.com/assets/8112710/7214699/be4689ca-e5e9-11e4-8502-48a92ff7827c.jpg"; HttpURLConnection conn = (HttpURLConnection) new URL(url) .openConnection(); InputStream in = conn.getInputStream(); BufferedImage src = ImageIO.read(in); in.close(); conn.disconnect(); RenderImage ri = new RenderImage(src); SIFT sift = new SIFT(); sift.detectFeatures(ri.toPixelFloatArray(null)); System.out.println("detect points:" + sift.getGlobalKDFeaturePoints()); } }
25.288136
118
0.696381
4717bdd2ceeda2efb3e6f1e20b71d2c840c28dc0
1,896
package cert.aiops.pega.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import java.util.HashMap; @Component public class ProvinceUtil { private Logger logger= LoggerFactory.getLogger(ProvinceUtil.class); private HashMap<String,String> provinces; private final String __NONAME="unknown"; public ProvinceUtil(){ provinces=new HashMap<>(); init(); } private void init(){ provinces.put("国家", "gj"); provinces.put("北京","bj"); provinces.put("上海","sh"); provinces.put("江苏","js"); provinces.put("浙江","zj"); provinces.put("安徽","ah"); provinces.put("福建","fj"); provinces.put("江西","jx"); provinces.put("湖南","hnx"); provinces.put("山东","sd"); provinces.put("河南","hny"); provinces.put("内蒙","nmg"); provinces.put("湖北","hbe"); provinces.put("宁夏","nx"); provinces.put("新疆","xj"); provinces.put("广东","gd"); provinces.put("西藏","xz"); provinces.put("海南","hnq"); provinces.put("广西","gx"); provinces.put("四川","sc"); provinces.put("河北","hbj"); provinces.put("贵州","gz"); provinces.put("重庆","cq"); provinces.put("山西","sxj"); provinces.put("云南","yn"); provinces.put("辽宁","ln"); provinces.put("陕西","sxq"); provinces.put("吉林","jl"); provinces.put("甘肃","gs"); provinces.put("黑龙","hlj"); provinces.put("青海","qh"); provinces.put("台湾","tw"); provinces.put("香港","xg"); provinces.put("澳门","am"); } public String getShortName(String key){ String value=provinces.get(key); if(value!=null) return value; logger.info("ProvinceUtil: find no key in provinces, key={}",key); return __NONAME; } }
28.727273
74
0.55116
3ceba955c714f7790003021475a6422529b5d5df
1,599
package net.infstudio.goki.common.stats.special.leaper; import net.infstudio.goki.common.utils.DataHelper; import net.infstudio.goki.common.stats.StatSpecial; import net.infstudio.goki.common.stats.StatSpecialBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.client.resources.I18n; public abstract class StatLeaper extends StatSpecialBase implements StatSpecial { public StatLeaper(int id, String key, int limit) { super(id, key, limit); } @Override public float getBonus(int level) { return getFinalBonus((float) Math.pow(level, 1.065D) * 0.0195F); } @Override public float getSecondaryBonus(int level) { return getFinalBonus((float) Math.pow(level, 1.1D) * 0.0203F); } @Override public float[] getAppliedDescriptionVar(EntityPlayer player) { // TODO speical return new float[] {DataHelper.trimDecimals(getBonus(getPlayerStatLevel(player)) * 100, 1), DataHelper.trimDecimals(getSecondaryBonus(getPlayerStatLevel(player)) * 100, 1)}; // return "Jump " + // Helper.trimDecimals(getBonus(getPlayerStatLevel(player)) * 100, 1) + // "% higher and " + // Helper.trimDecimals(getSecondaryBonus(getPlayerStatLevel(player)) * // 100, 1) + "% farther when sprinting."; } @Override public String getLocalizedDes(EntityPlayer player) { return I18n.format(this.key + ".des", this.getAppliedDescriptionVar(player)[0], this.getAppliedDescriptionVar(player)[1]); } }
37.186047
165
0.671044
f3bd755eb93349caef7b38fc64fb98e4bec1ed30
239
package com.shekhargulati.controller; public class ProcessingFailureException extends Exception { public String getMessage() { return "Error occur during the process of requests starting with the tag \"/control\"."; } }
23.9
96
0.732218
e72ea0374494bcbfd8735636ada3f9e5ce6519c9
2,435
/* * Copyright 2018 Blockchain Innovation Foundation <https://blockchain-innovation.org> * * 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.blockchain_innovation.factom.client.api.model.response.factomd; import java.io.Serializable; import java.util.List; public class ReceiptResponse implements Serializable { private Receipt receipt; public Receipt getReceipt() { return receipt; } public static class Receipt implements Serializable { private Entry entry; private List<MerkleBranch> merklebranch; private String entryblockkeymr; private String directoryblockkeymr; private String bitcointransactionhash; private String bitcoinblockhash; public Entry getEntry() { return entry; } public List<MerkleBranch> getMerkleBranch() { return merklebranch; } public String getEntryBlockKeyMR() { return entryblockkeymr; } public String getDirectoryBlockKeyMR() { return directoryblockkeymr; } public String getBitcoinTransactionHash() { return bitcointransactionhash; } public String getBitcoinBlockHash() { return bitcoinblockhash; } public static class Entry implements Serializable { private String entryhash; public String getEntryHash() { return entryhash; } } public static class MerkleBranch implements Serializable { private String left; private String right; private String top; public String getLeft() { return left; } public String getRight() { return right; } public String getTop() { return top; } } } }
27.359551
86
0.627926
61f8f5cba9bff6270f81e6f67e426646ec933e29
1,111
package cn.hkxj.platform.pojo; import com.google.common.base.MoreObjects; import java.util.ArrayList; import java.util.List; /** * @author junrong.chen */ public class AllGradeAndCourse { private List<List<GradeAndCourse>> list = new ArrayList<>(); public void addGradeAndCourse(List<GradeAndCourse> gradeAndCourse){ list.add(gradeAndCourse); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("list", list) .toString(); } /** * 获取当前学期的成绩 * @return 当前学期成绩的列表 */ public List<GradeAndCourse> getCurrentTermGrade(){ return list.get(list.size() -1); } public static class GradeAndCourse { private Grade grade; private Course course; public Grade getGrade() { return grade; } public void setGrade(Grade grade) { this.grade = grade; } public Course getCourse() { return course; } public void setCourse(Course course) { this.course = course; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("grade", grade) .add("course", course) .toString(); } } }
17.919355
68
0.684968
dce4b7dcd3da8949840efb100ba2f076ac1cfcdd
4,049
package com.rongji.dfish.misc.docpreview.parser; import com.rongji.dfish.misc.docpreview.DocumentParser; import com.rongji.dfish.misc.docpreview.data.*; import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.model.PicturesTable; import org.apache.poi.hwpf.usermodel.Picture; import org.apache.poi.hwpf.usermodel.Range; import org.apache.poi.hwpf.usermodel.Section; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; /** * word 97 文件解析,后缀名是.doc * */ public class DocParser extends DocumentParser { @Override public Document parse(InputStream is) { HWPFDocument hwpfDocument = null; List<DocumentElement> contents = new ArrayList<>(); try { hwpfDocument = new HWPFDocument(is); } catch (IOException e) { e.printStackTrace(); } Range range = hwpfDocument.getRange(); //FIXME 这里忽略了table//FIXME 这里忽略了table PicturesTable pics=hwpfDocument.getPicturesTable(); for (int i = 0; i < range.numParagraphs(); i++) { org.apache.poi.hwpf.usermodel.Paragraph paragraph = range.getParagraph(i); // 段元素 Paragraph p = new Paragraph(); // p.setAlignment("center");//FIXME p.setIndentation(paragraph.getFirstLineIndent()==-1?null:paragraph.getFirstLineIndent() ); // 行内元素 int characterNum = paragraph.numCharacterRuns(); //FIXME 这里忽略了Drawing if (characterNum>0){ p.setBody(new ArrayList<>()); } for (int j = 0; j < characterNum; j++) { CharacterRun cr = new CharacterRun(); org.apache.poi.hwpf.usermodel.CharacterRun characterRun = paragraph.getCharacterRun(j); cr.setText(characterRun.text()); cr.setBold(characterRun.isBold()); cr.setItalic(characterRun.isItalic()); cr.setFontSize(characterRun.getFontSize()/2); cr.setFontFamily(characterRun.getFontName()); cr.setColor(getHexColor(characterRun.getIco24())); if( characterRun.getUnderlineCode()==1){// 下划线代号 cr.setStrikeType(CharacterRun.STRIKE_UNDERLINE); }else if(characterRun.isDoubleStrikeThrough()){ cr.setStrikeType(CharacterRun.STRIKE_DOUBLE_THROUGH); }else if(characterRun.isStrikeThrough()){ cr.setStrikeType(CharacterRun.STRIKE_LINE_THROUGH); } if(pics.hasPicture(characterRun)){ Picture pic=pics.extractPicture(characterRun, false); if (pic != null && pic.getRawContent() != null) { String ext=pic.suggestFileExtension(); byte[] data= pic.getRawContent(); Drawing drawing=new Drawing(); savePic(data,ext,drawing); p.getBody().add(drawing); } } if(cr.getText()!=null&&!"".equals(cr.getText().trim())){ p.getBody().add(cr); } } contents.add(p); } Document doc=new Document(); doc.setBody(contents); return doc; } private static char[] HEX_CHARS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; /** * word 97 颜色格式可以由这种RGB来表示 * @param color int * @return String */ protected static String getHexColor(int color) { if(color==-1){ return null; } char[] cs = new char[7]; cs[0] = '#'; cs[1] = HEX_CHARS[color >> 4 & 0xF]; cs[2] = HEX_CHARS[color & 0xF]; cs[3] = HEX_CHARS[color >> 12 & 0xF]; cs[4] = HEX_CHARS[color >> 8 & 0xF]; cs[5] = HEX_CHARS[color >> 20 & 0xF]; cs[6] = HEX_CHARS[color >> 16 & 0xF]; return new String(cs); } }
37.146789
119
0.555446
895fcc7dab7552b3732f998f2b5dca42cfd47daf
1,518
package Camunda.TravelGuide; import java.util.LinkedList; import org.camunda.bpm.engine.delegate.DelegateExecution; import org.camunda.bpm.engine.delegate.JavaDelegate; import org.json.JSONObject; import Camunda.utils.JSONWorker; public class GarbageCollector implements JavaDelegate { @Override public void execute(DelegateExecution execution) throws Exception { // TODO Auto-generated method stub System.out.println("Collector begins to fill with itself"); LinkedList<String> varVals = new LinkedList<String>(); varVals.add(JSONWorker.getValFromExec("HappyDuckAppearsHappy", execution)); varVals.add(JSONWorker.getValFromExec("UrbanDef", execution)); LinkedList<Integer> usedInts = new LinkedList<Integer>(); JSONObject names = new JSONObject(); while (usedInts.size() != varVals.size()) { int i = (int) (Math.random() * varVals.size()); if (!usedInts.contains(i)) { names = JSONWorker.addToJO(names, varVals.get(i)); usedInts.add(i); System.out.println(i + " = " + varVals.get(i)); } } names = JSONWorker.addToJO(names, "<br><br>the crazyness factor is about:" + this.getCrazyness(varVals) * 100 + "%"); execution.setVariable("vals", names.toString()); } public double getCrazyness(LinkedList<String> data) { double a = 0; double b = 0; for(String str: data) { for(char c: str.toCharArray()) { if(c == 'a') { a +=1; }else if (c == 'b') { b+=1; } } } return a/b; } }
29.192308
120
0.664032
0f4839715063c03c7308ba3e04e244fd61f9dd08
335
package com.or.heuristic.core.algo.hc; import lombok.Builder; import lombok.Getter; /** * This class contains all the configurations for the hill climbing algorithm. * * @author Kunlei Lian */ @Getter @Builder public class HcConfig { private int maxIter; private int maxIterNoImprove; private final int maxRuntimeInSecs; }
18.611111
78
0.758209
cb271d1523f0884c2af21613ac39c73ec9b21cbe
405
package stu.napls.clouderweb.config.property; import lombok.Getter; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; /** * @Author Tei Michael * @Date 1/13/2020 */ @Component @Getter public class StaticServer { @Value("${staticserver.url}") private String url; @Value("${staticserver.root-path}") private String rootPath; }
20.25
58
0.735802
f11b4328ce35e738d88790a2a64d2d567aff86d1
5,421
package org.warmsheep.encoder.bean; import org.warmsheep.encoder.enums.KeyLengthType; public class MUCommandBean extends CommandBean{ //MU指令相关 private static final int MSG_BLOCK_LENGTH = 1; //报文块标志域长度 private static final int KEY_TYPE_LENGTH = 1; //密钥类型域长度 private static final int KEY_LENGTH_TYPE_LENGTH = 1; //密钥长度类型域长度 private static final int MSG_TYPE_LENGTH = 1; //数据类型域长度 private static final int DOUBLE_KEY_ADD_ONE_LENGTH = 33;//双倍长密钥域长度33(带X) private static final int DOUBLE_KEY_LENGTH = 32; //双倍长密钥域长度32(不带X) private static final int SINGLE_KEY_LENGTH = 16; //单倍长密钥域长度 public static MUCommandBean build(String header,String commandType,String commandContent){ MUCommandBean muCommandBean = new MUCommandBean(); muCommandBean.setCommandHeader(header); muCommandBean.setCommandType(commandType); int subIndex = 0; muCommandBean.setMsgBlock(commandContent.substring(subIndex, subIndex += MSG_BLOCK_LENGTH)); muCommandBean.setKeyType(commandContent.substring(subIndex, subIndex += KEY_TYPE_LENGTH)); muCommandBean.setKeyLengthType(commandContent.substring(subIndex, subIndex += KEY_LENGTH_TYPE_LENGTH)); muCommandBean.setMsgType(commandContent.substring(subIndex, subIndex += MSG_TYPE_LENGTH)); if(muCommandBean.getKeyLengthType().equals(KeyLengthType.DOUBLE_LENGTH.getKey())){ //双倍长密钥,以X开头 if(commandContent.substring(subIndex,subIndex + 1).equalsIgnoreCase("X")){ muCommandBean.setKeyValue(commandContent.substring(subIndex, subIndex += DOUBLE_KEY_ADD_ONE_LENGTH)); } //双倍长密钥,标准长度 else { muCommandBean.setKeyValue(commandContent.substring(subIndex, subIndex += DOUBLE_KEY_LENGTH)); } } //单倍长密钥 else { muCommandBean.setKeyValue(commandContent.substring(subIndex, subIndex += SINGLE_KEY_LENGTH)); } muCommandBean.setEncryptDataLength(Integer.valueOf(commandContent.substring(subIndex, subIndex += DATA_LENGTH), 16).toString()); muCommandBean.setEncryptDataValue(commandContent.substring(subIndex, subIndex+= (Integer.valueOf(muCommandBean.getEncryptDataLength()) * 2) ) ); return muCommandBean; } private String msgBlock; //报文块标志 0唯一块 1第一块 2中间块 3最后块 private String keyType; //密钥类型 0TAK 1ZAK private String keyLengthType; //密钥长度类型 0 8字节单倍长 1 16字节双倍长 private String msgType; //数据类型 0二进制 1扩展十六进制 private String keyValue; //密钥值 private String encryptDataLength; //待加密的数据长度 private String encryptDataValue; //待加密的数据 /** * 报文块标志 0唯一块 1第一块 2中间块 3最后块 * @return */ public String getMsgBlock() { return msgBlock; } /** * 报文块标志 0唯一块 1第一块 2中间块 3最后块 * @param msgBlock */ public void setMsgBlock(String msgBlock) { this.msgBlock = msgBlock; } /** * 密钥类型 0TAK 1ZAK * @return */ public String getKeyType() { return keyType; } /** * 密钥类型 0TAK 1ZAK * @param keyType */ public void setKeyType(String keyType) { this.keyType = keyType; } /** * 密钥长度类型 0 8字节单倍长 1 16字节双倍长 * @return */ public String getKeyLengthType() { return keyLengthType; } /** * 密钥长度类型 0 8字节单倍长 1 16字节双倍长 * @param keyLengthType */ public void setKeyLengthType(String keyLengthType) { this.keyLengthType = keyLengthType; } /** * 数据类型 0二进制 1扩展十六进制 * @return */ public String getMsgType() { return msgType; } /** * 数据类型 0二进制 1扩展十六进制 * @param msgType */ public void setMsgType(String msgType) { this.msgType = msgType; } /** * 密钥值 * @return */ public String getKeyValue() { return keyValue; } /** * 密钥值 * @param keyValue */ public void setKeyValue(String keyValue) { this.keyValue = keyValue; } /** * 待加密的数据长度 * @return */ public String getEncryptDataLength() { return encryptDataLength; } /** * 待加密的数据长度 * @param encryptDataLength */ public void setEncryptDataLength(String encryptDataLength) { this.encryptDataLength = encryptDataLength; } /** * 待加密的数据 * @return */ public String getEncryptDataValue() { return encryptDataValue; } /** * 待加密的数据 * @param encryptDataValue */ public void setEncryptDataValue(String encryptDataValue) { this.encryptDataValue = encryptDataValue; } public String toString(){ StringBuilder sb = new StringBuilder(); sb.append("[").append("CommandHeader").append("]:\t[").append("命令头").append("]:\t[").append(this.getCommandHeader()).append("]\n"); sb.append("[").append("CommandType").append("]:\t\t[").append("命令类型").append("]:\t[").append(this.getCommandType()).append("]\n"); sb.append("[").append("MsgBlock").append("]:\t\t[").append("报文块标志").append("]:\t[").append(this.getMsgBlock()).append("]\n"); sb.append("[").append("KeyType").append("]:\t\t[").append("密钥类型").append("]:\t[").append(this.getKeyType()).append("]\n"); sb.append("[").append("KeyLengthType").append("]:\t[").append("密钥长度").append("]:\t[").append(this.getKeyLengthType()).append("]\n"); sb.append("[").append("MsgType").append("]:\t\t[").append("数据类型").append("]:\t[").append(this.getMsgType()).append("]\n"); sb.append("[").append("KeyValue").append("]:\t\t[").append("密钥值").append("]:\t[").append(this.getKeyValue()).append("]\n"); sb.append("[").append("EncryptDataLength").append("]:\t[").append("数据长度").append("]:\t[").append(this.getEncryptDataLength()).append("]\n"); sb.append("[").append("EncryptDataValue").append("]:\t[").append("数据值").append("]:\t[").append(this.getEncryptDataValue()).append("]\n"); return sb.toString(); } }
29.785714
146
0.698026
2bea6ca97aa80173448b01f6fb84b1b9f5d847d0
5,970
/* * WorldEdit, a Minecraft world manipulation toolkit * Copyright (C) sk89q <http://www.sk89q.com> * Copyright (C) WorldEdit team and contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.sk89q.worldedit.regions.shape; import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.world.biome.BiomeType; import com.sk89q.worldedit.world.biome.BiomeTypes; import java.util.BitSet; /** * Generates solid and hollow shapes according to materials returned by the * {@link #getBiome} method. */ public abstract class ArbitraryBiomeShape { private final Region extent; private final int cacheOffsetX; private final int cacheOffsetY; private final int cacheOffsetZ; @SuppressWarnings("FieldCanBeLocal") private final int cacheSizeX; private final int cacheSizeY; private final int cacheSizeZ; //FAWE start /** * Cache entries. * null = unknown * OUTSIDE = outside * else = inside */ //FAWE end private final BiomeType[] cache; private final BitSet isCached; public ArbitraryBiomeShape(Region extent) { this.extent = extent; BlockVector3 min = extent.getMinimumPoint(); BlockVector3 max = extent.getMaximumPoint(); cacheOffsetX = min.getBlockX() - 1; cacheOffsetY = min.getBlockY() - 1; cacheOffsetZ = min.getBlockZ() - 1; cacheSizeX = max.getX() - cacheOffsetX + 2; cacheSizeY = max.getY() - cacheOffsetY + 2; cacheSizeZ = max.getZ() - cacheOffsetZ + 2; cache = new BiomeType[cacheSizeX * cacheSizeY * cacheSizeZ]; isCached = new BitSet(cache.length); } protected Iterable<BlockVector3> getExtent() { return extent; } /** * Override this function to specify the shape to generate. * * @param x X coordinate to be queried * @param z Z coordinate to be queried * @param defaultBaseBiome The default biome for the current column. * @return material to place or null to not place anything. */ protected abstract BiomeType getBiome(int x, int y, int z, BiomeType defaultBaseBiome); private BiomeType getBiomeCached(int x, int y, int z, BiomeType baseBiome) { final int index = (y - cacheOffsetY) + (z - cacheOffsetZ) * cacheSizeY + (x - cacheOffsetX) * cacheSizeY * cacheSizeZ; if (!isCached.get(index)) { final BiomeType material = getBiome(x, y, z, baseBiome); isCached.set(index); cache[index] = material; return material; } return cache[index]; } //FAWE start private boolean isInsideCached(int x, int y, int z, BiomeType baseBiome) { final int index = (y - cacheOffsetY) + (z - cacheOffsetZ) * cacheSizeY + (x - cacheOffsetX) * cacheSizeY * cacheSizeZ; final BiomeType cacheEntry = cache[index]; if (cacheEntry == null) { // unknown block, meaning they must be outside the extent at this stage, but might still be inside the shape return getBiomeCached(x, y, z, baseBiome) != null; } return cacheEntry != BiomeTypes.THE_VOID; } //FAWE end private boolean isOutside(int x, int y, int z, BiomeType baseBiome) { return getBiomeCached(x, y, z, baseBiome) == null; } /** * Generates the shape. * * @param editSession The EditSession to use. * @param baseBiome The default biome type. * @param hollow Specifies whether to generate a hollow shape. * @return number of affected blocks. */ public int generate(EditSession editSession, BiomeType baseBiome, boolean hollow) { int affected = 0; for (BlockVector3 position : getExtent()) { int x = position.getBlockX(); int y = position.getBlockY(); int z = position.getBlockZ(); if (!hollow) { final BiomeType material = getBiome(x, y, z, baseBiome); if (material != null) { editSession.getWorld().setBiome(position, material); ++affected; } continue; } final BiomeType material = getBiomeCached(x, y, z, baseBiome); if (material == null) { continue; } if (!shouldDraw(x, y, z, material)) { continue; } editSession.getWorld().setBiome(position, material); ++affected; } return affected; } private boolean shouldDraw(int x, int y, int z, BiomeType material) { // we should draw this if the surrounding blocks fall outside the shape, // this position will form an edge of the hull if (isOutside(x + 1, y, z, material)) { return true; } if (isOutside(x - 1, y, z, material)) { return true; } if (isOutside(x, y, z + 1, material)) { return true; } if (isOutside(x, y, z - 1, material)) { return true; } if (isOutside(x, y + 1, z, material)) { return true; } return isOutside(x, y - 1, z, material); } }
32.622951
126
0.6134
8ed6249ec35240679bef497866fc2e46ea2d697e
12,310
// // ======================================================================== // Copyright (c) 1995-2014 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // All rights reserved. This program and the accompanying materials // are made available under the terms of the Eclipse Public License v1.0 // and Apache License v2.0 which accompanies this distribution. // // The Eclipse Public License is available at // http://www.eclipse.org/legal/epl-v10.html // // The Apache License v2.0 is available at // http://www.opensource.org/licenses/apache2.0.php // // You may elect to redistribute this code under either of these licenses. // ======================================================================== // package org.eclipse.jetty.server.nio; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.nio.channels.SelectionKey; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import org.eclipse.jetty.continuation.Continuation; import org.eclipse.jetty.io.AsyncEndPoint; import org.eclipse.jetty.io.ConnectedEndPoint; import org.eclipse.jetty.io.Connection; import org.eclipse.jetty.io.EndPoint; import org.eclipse.jetty.io.nio.AsyncConnection; import org.eclipse.jetty.io.nio.SelectChannelEndPoint; import org.eclipse.jetty.io.nio.SelectorManager; import org.eclipse.jetty.io.nio.SelectorManager.SelectSet; import org.eclipse.jetty.server.AsyncHttpConnection; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.util.thread.ThreadPool; /* ------------------------------------------------------------------------------- */ /** * Selecting NIO connector. * <p> * This connector uses efficient NIO buffers with a non blocking threading model. Direct NIO buffers * are used and threads are only allocated to connections with requests. Synchronization is used to * simulate blocking for the servlet API, and any unflushed content at the end of request handling * is written asynchronously. * </p> * <p> * This connector is best used when there are a many connections that have idle periods. * </p> * <p> * When used with {@link org.eclipse.jetty.continuation.Continuation}, threadless waits are supported. * If a filter or servlet returns after calling {@link Continuation#suspend()} or when a * runtime exception is thrown from a call to {@link Continuation#undispatch()}, Jetty will * will not send a response to the client. Instead the thread is released and the Continuation is * placed on the timer queue. If the Continuation timeout expires, or it's * resume method is called, then the request is again allocated a thread and the request is retried. * The limitation of this approach is that request content is not available on the retried request, * thus if possible it should be read after the continuation or saved as a request attribute or as the * associated object of the Continuation instance. * </p> * * @org.apache.xbean.XBean element="nioConnector" description="Creates an NIO based socket connector" */ public class SelectChannelConnector extends AbstractNIOConnector { protected ServerSocketChannel _acceptChannel; private int _lowResourcesConnections; private int _lowResourcesMaxIdleTime; private int _localPort=-1; private final SelectorManager _manager = new ConnectorSelectorManager(); /* ------------------------------------------------------------------------------- */ /** * Constructor. * */ public SelectChannelConnector() { _manager.setMaxIdleTime(getMaxIdleTime()); addBean(_manager,true); setAcceptors(Math.max(1,(Runtime.getRuntime().availableProcessors()+3)/4)); } @Override public void setThreadPool(ThreadPool pool) { super.setThreadPool(pool); // preserve start order removeBean(_manager); addBean(_manager,true); } /* ------------------------------------------------------------ */ @Override public void accept(int acceptorID) throws IOException { ServerSocketChannel server; synchronized(this) { server = _acceptChannel; } if (server!=null && server.isOpen() && _manager.isStarted()) { SocketChannel channel = server.accept(); channel.configureBlocking(false); Socket socket = channel.socket(); configure(socket); _manager.register(channel); } } /* ------------------------------------------------------------ */ public void close() throws IOException { synchronized(this) { if (_acceptChannel != null) { removeBean(_acceptChannel); if (_acceptChannel.isOpen()) _acceptChannel.close(); } _acceptChannel = null; _localPort=-2; } } /* ------------------------------------------------------------------------------- */ @Override public void customize(EndPoint endpoint, Request request) throws IOException { request.setTimeStamp(System.currentTimeMillis()); endpoint.setMaxIdleTime(_maxIdleTime); super.customize(endpoint, request); } /* ------------------------------------------------------------------------------- */ @Override public void persist(EndPoint endpoint) throws IOException { AsyncEndPoint aEndp = ((AsyncEndPoint)endpoint); aEndp.setCheckForIdle(true); super.persist(endpoint); } /* ------------------------------------------------------------ */ public SelectorManager getSelectorManager() { return _manager; } /* ------------------------------------------------------------ */ public synchronized Object getConnection() { return _acceptChannel; } /* ------------------------------------------------------------------------------- */ public int getLocalPort() { synchronized(this) { return _localPort; } } /* ------------------------------------------------------------ */ public void open() throws IOException { synchronized(this) { if (_acceptChannel == null) { // Create a new server socket _acceptChannel = ServerSocketChannel.open(); // Set to blocking mode _acceptChannel.configureBlocking(true); // Bind the server socket to the local host and port _acceptChannel.socket().setReuseAddress(getReuseAddress()); InetSocketAddress addr = getHost()==null?new InetSocketAddress(getPort()):new InetSocketAddress(getHost(),getPort()); _acceptChannel.socket().bind(addr,getAcceptQueueSize()); _localPort=_acceptChannel.socket().getLocalPort(); if (_localPort<=0) throw new IOException("Server channel not bound"); addBean(_acceptChannel); } } } /* ------------------------------------------------------------ */ @Override public void setMaxIdleTime(int maxIdleTime) { _manager.setMaxIdleTime(maxIdleTime); super.setMaxIdleTime(maxIdleTime); } /* ------------------------------------------------------------ */ /** * @return the lowResourcesConnections */ public int getLowResourcesConnections() { return _lowResourcesConnections; } /* ------------------------------------------------------------ */ /** * Set the number of connections, which if exceeded places this manager in low resources state. * This is not an exact measure as the connection count is averaged over the select sets. * @param lowResourcesConnections the number of connections * @see #setLowResourcesMaxIdleTime(int) */ public void setLowResourcesConnections(int lowResourcesConnections) { _lowResourcesConnections=lowResourcesConnections; } /* ------------------------------------------------------------ */ /** * @return the lowResourcesMaxIdleTime */ @Override public int getLowResourcesMaxIdleTime() { return _lowResourcesMaxIdleTime; } /* ------------------------------------------------------------ */ /** * Set the period in ms that a connection is allowed to be idle when this there are more * than {@link #getLowResourcesConnections()} connections. This allows the server to rapidly close idle connections * in order to gracefully handle high load situations. * @param lowResourcesMaxIdleTime the period in ms that a connection is allowed to be idle when resources are low. * @see #setMaxIdleTime(int) */ @Override public void setLowResourcesMaxIdleTime(int lowResourcesMaxIdleTime) { _lowResourcesMaxIdleTime=lowResourcesMaxIdleTime; super.setLowResourcesMaxIdleTime(lowResourcesMaxIdleTime); } /* ------------------------------------------------------------ */ /* * @see org.eclipse.jetty.server.server.AbstractConnector#doStart() */ @Override protected void doStart() throws Exception { _manager.setSelectSets(getAcceptors()); _manager.setMaxIdleTime(getMaxIdleTime()); _manager.setLowResourcesConnections(getLowResourcesConnections()); _manager.setLowResourcesMaxIdleTime(getLowResourcesMaxIdleTime()); super.doStart(); } /* ------------------------------------------------------------ */ protected SelectChannelEndPoint newEndPoint(SocketChannel channel, SelectSet selectSet, SelectionKey key) throws IOException { SelectChannelEndPoint endp= new SelectChannelEndPoint(channel,selectSet,key, SelectChannelConnector.this._maxIdleTime); endp.setConnection(selectSet.getManager().newConnection(channel,endp, key.attachment())); return endp; } /* ------------------------------------------------------------------------------- */ protected void endPointClosed(SelectChannelEndPoint endpoint) { connectionClosed(endpoint.getConnection()); } /* ------------------------------------------------------------------------------- */ protected AsyncConnection newConnection(SocketChannel channel,final AsyncEndPoint endpoint) { return new AsyncHttpConnection(SelectChannelConnector.this,endpoint,getServer()); } /* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */ /* ------------------------------------------------------------ */ private final class ConnectorSelectorManager extends SelectorManager { @Override public boolean dispatch(Runnable task) { ThreadPool pool=getThreadPool(); if (pool==null) pool=getServer().getThreadPool(); return pool.dispatch(task); } @Override protected void endPointClosed(final SelectChannelEndPoint endpoint) { SelectChannelConnector.this.endPointClosed(endpoint); } @Override protected void endPointOpened(SelectChannelEndPoint endpoint) { // TODO handle max connections and low resources connectionOpened(endpoint.getConnection()); } @Override protected void endPointUpgraded(ConnectedEndPoint endpoint, Connection oldConnection) { connectionUpgraded(oldConnection,endpoint.getConnection()); } @Override public AsyncConnection newConnection(SocketChannel channel,AsyncEndPoint endpoint, Object attachment) { return SelectChannelConnector.this.newConnection(channel,endpoint); } @Override protected SelectChannelEndPoint newEndPoint(SocketChannel channel, SelectSet selectSet, SelectionKey sKey) throws IOException { return SelectChannelConnector.this.newEndPoint(channel,selectSet,sKey); } } }
36.746269
133
0.57303
4597bda3d44478597116bb5f3222ed17cfef9649
1,029
package com.sandwich.util.io.directories; import java.io.File; abstract public class DirectorySet { private static final String BIN_DIR = "bin"; private static final String APP_DIR = "app"; private static final String LIB_DIR = "lib"; private static final String DATA_DIR = "data"; private static final String I18N_DIR = "i18n"; private static final String CONFIG_DIR = "config"; private static final String BASE_DIR = createBaseDir(); abstract String getSourceDir(); abstract String getProjectDir(); public String getBaseDir(){ return BASE_DIR; } public String getBinaryDir(){ return BIN_DIR; } public String getLibrariesDir(){ return LIB_DIR; } public String getI18nDir(){ return I18N_DIR; } public String getAppDir(){ return APP_DIR; } public String getConfigDir() { return CONFIG_DIR; } public String getDataDir(){ return DATA_DIR; } private static String createBaseDir() { return new File("").getAbsoluteFile().getParentFile().getAbsolutePath(); } }
20.58
74
0.720117
71a4aa8c1d5d1bf75eba1f89b97b56bb2d2aec87
910
package com.damon.appwheel.ui.rlPart.base; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.View; /** * Created by stephen on 2017/8/13. */ public class BaseMyHolder<DT> extends RecyclerView.ViewHolder { public Context mContext; public BaseAdapter.OnClickListener mOnClickListener; public String tag; public BaseMyHolder(View itemView) { super(itemView); } public BaseMyHolder(View itemView,Context context){ this(itemView); mContext = context; } public void bind(int position, AdapterDataOperation<DT> ado){} public void setOnClickListener(BaseAdapter.OnClickListener onClickListener) { this.mOnClickListener = onClickListener; } public BaseAdapter.OnClickListener getOnClickListener() { return mOnClickListener; } }
23.947368
81
0.687912
acad1101bf0504757b03e2860f8d17f21d76be07
2,143
package frc.robot.commands; import edu.wpi.first.math.controller.PIDController; import edu.wpi.first.wpilibj2.command.CommandBase; import frc.robot.subsystems.LimeLightSubsystem; import frc.robot.subsystems.SwerveDriveSubsystem; public class AutoSearchRight extends CommandBase { private SwerveDriveSubsystem swerveDriveSubsystem; private LimeLightSubsystem limeLightSubsystem; private boolean isFinished = false; private double margin = 0.05; // margin of degrees private PIDController angleController; private int pipeline; public AutoSearchRight(SwerveDriveSubsystem swerveDriveSubsystem, LimeLightSubsystem limeLightSubsystem, int pipeline) { this.swerveDriveSubsystem = swerveDriveSubsystem; this.limeLightSubsystem = limeLightSubsystem; addRequirements(swerveDriveSubsystem, limeLightSubsystem); this.pipeline = pipeline; } @Override public void execute() { double rotateCommand; if (!limeLightSubsystem.hasTarget()) { rotateCommand = -0.2; swerveDriveSubsystem.drive(0, 0, rotateCommand * -1); } if (limeLightSubsystem.hasTarget()) { double currentAngle = limeLightSubsystem.getTxRad(); rotateCommand = angleController.calculate(currentAngle) * -1; if (rotateCommand > 0.4) { rotateCommand = 0.4; } else if (rotateCommand < -0.4) { rotateCommand = -0.4; } //SmartDashboard.putNumber("ROTATE", rotateCommand); swerveDriveSubsystem.drive(0, 0, rotateCommand); if (Math.abs(limeLightSubsystem.getTxRad()) < margin) { isFinished = true; } } } @Override public boolean isFinished() { return isFinished; } @Override public void initialize() { limeLightSubsystem.setPipeline(pipeline); angleController = new PIDController(.3, 0, 0); angleController.setSetpoint(0); } @Override public void end(boolean interrupted) { swerveDriveSubsystem.stop(); } }
31.985075
108
0.656556
6f36650021444fe31797080f9f2fe10c3ea8dd68
44,703
package com.agsw.FabricView; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.DashPathEffect; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.RectF; import android.os.SystemClock; import android.util.AttributeSet; import android.util.TypedValue; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.view.View; import android.widget.Toast; import com.agsw.FabricView.DrawableObjects.CBitmap; import com.agsw.FabricView.DrawableObjects.CDrawable; import com.agsw.FabricView.DrawableObjects.CPath; import com.agsw.FabricView.DrawableObjects.CRotation; import com.agsw.FabricView.DrawableObjects.CScale; import com.agsw.FabricView.DrawableObjects.CText; import com.agsw.FabricView.DrawableObjects.CTransform; import com.agsw.FabricView.DrawableObjects.CTranslation; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import java.util.Vector; /** * Created by antwan on 10/3/2015. * A library for creating graphics on an object model on top of canvas. * How to use: * <H1>Layout</H1> * Create a view in your layout, like this: <pre> &lt;com.agsw.FabricView.FabricView android:id="@+id/my_fabric_view" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="20dp" android:text="@string/my_fabric_view_title" /&gt;</pre> * <H1>Activity code</H1> * Retrieve and configure your FabricView: <pre> FabricView myFabricView = (FabricView) parent.findViewById(R.id.my_fabric_view); //Retrieve by ID //Configuration. All of which is optional. Defaults are marked with an asterisk here. myFabricView.setBackgroundMode(BACKGROUND_STYLE_BLANK); //Set the background style (BACKGROUND_STYLE_BLANK*, BACKGROUND_STYLE_NOTEBOOK_PAPER, BACKGROUND_STYLE_GRAPH_PAPER) myFabricView.setInteractionMode(FabricView.DRAW_MODE); //Set its draw mode (DRAW_MODE*, SELECT_MODE, ROTATE_MODE, LOCKED_MODE) myFabricView.setDeleteIcon(deleteIcon); //If you don't like the default delete icon myFabricView.setColor(R.color.purple); //Line color myFabricView.setSize(10); //Line width myFabricView.setSelectionColor(R.color.lightergray); //Selection box color //To be notified of any deletion: myFabricView.setDeletionListener(new FabricView.DeletionListener() { public void deleted(CDrawable drawable) { doSomethingAboutThis(drawable); } }); //Manipulations... The following functions could be attached to buttons of your choosing: myFabricView.cleanPage(); //Erases everything. myFabricView.undo(); //Cancels the last operation. myFabricView.redo(); //Reinstates the last undone operation. myFabricView.selectLastDrawn(); //Mark the last drawn object as selected. myFabricView.deSelect(); //Unmark all objects for selection. myFabricView.deleteSelection(); //Removes all selected objects and its transforms. myFabricView.deleteDrawable(); //Removes a single object and its transforms. //Retrieving the picture from the view: Bitmap fullResult = myFabricView.getCanvasBitmap(); //Gets a copy of the whole view. This includes decorations such as selection rectangle. So make sure you switch to LOCKED_MODE before calling. Bitmap croppedResult = myFabricView.getCroppedCanvasBitmap(); //Same as previous, except with no margin around the picture. List&lt;CDrabable&gt; drawablesList = myFabricView.getDrawablesList(); //Returns all the drawables of the view. See next sections. CDrawable currentSelection = myFabricView.getSelection(); //Save point functions boolean everythingIsSaved = myFabricView.isSaved(); //true = there were no operations added or undone after the last call to markSaved(). markSaved(); //Indicates that everything was saved. You can save the bitmap or the drawable objects. (See previous section.) revertUnsaved(); //Restore the drawables to the last save point. List&lt;CDrabable&gt; unsavedDrawablesList = getUnsavedDrawablesList(); //Returns all the drawables that were not saved yet.</pre> * <H1>Drawables and Transforms</H1> * The list of visible objects inside the view is a stack. There are two kinds: CDrawable and CTransform (subclass of the latter). * A CDrawable is an object that can be "drawn" on the canvas. A CTransform represents a modification of a CDrawable. * A CDrawable is linked to its CTransforms (see getTransforms() and hasTransforms()), and each CTransform is aware of its * CDrawable (see getDrawable()). * * The subclasses of CDrawable are CPath (a set of continuous lines), CBitmap, and CText. Another subclass is CTransform, and this one * has its one subclasses which are CRotation, CScale, and CTranslation. * * The rotate mode allows both rotation and scaling. The rotate mode must be set by you. * It can be triggered by an external mean (e.g. a button) or by a pinch gesture internally. * If you want to use a pinch gesture to start the rotate mode, use setRotationListener() * and in the listener's startRotate() return 'true'. */ public class FabricView extends View { /**********************************************************************************************/ /************************************* Vars *******************************************/ /*********************************************************************************************/ // painting objects and properties private ArrayList<CDrawable> mDrawableList = new ArrayList<>(); private ArrayList<CDrawable> mUndoList = new ArrayList<>(); private CDrawable selected = null; private long pressStartTime; private float pressedX; private float pressedY; private CDrawable hovering = null; private CTranslation hoveringTranslation = null; private int mColor = Color.BLACK; private int savePoint = -1; private Bitmap deleteIcon; private RectF deleteIconPosition = new RectF(-1, -1, -1, -1); private DeletionListener deletionListener = null; private DeletionConfirmationListener deletionConfirmationListener = null; // Canvas interaction modes private int mInteractionMode = DRAW_MODE; //Mode prior to rotation. private Integer mOldInteractionMode = null; // background color of the library private int mBackgroundColor = Color.WHITE; // default style for the library private Paint.Style mStyle = Paint.Style.STROKE; // default stroke size for the library private float mSize = 5f; // flag indicating whether or not the background needs to be redrawn private boolean mRedrawBackground; // background mode for the library, default to blank private int mBackgroundMode = BACKGROUND_STYLE_BLANK; /** * Default Notebook left line color. Value = Color.Red. */ public static final int NOTEBOOK_LEFT_LINE_COLOR = Color.RED; // Flag indicating that we are waiting for a location for the text private boolean mTextExpectTouch; //This handles gestures for the PinchGestureListener and ROTATE_MODE. private ScaleRotationGestureDetector mScaleDetector; //This is a listener for pinching gestures. private ScaleRotateListener mScaleRotateListener; //During a rotation gesture, this is the rotation of the selected object. private CRotation mCurrentRotation; //During a rotation gesture, this is the scale of the selected object. private CScale mCurrentScale; // Vars to decrease dirty area and increase performance private float lastTouchX, lastTouchY; private final RectF dirtyRect = new RectF(); // keep track of path and paint being in use CPath currentPath; Paint currentPaint; Paint selectionPaint; private int selectionColor = Color.DKGRAY; private static final int MAX_CLICK_DURATION = 1000; private static final int MAX_CLICK_DISTANCE = 15; /*********************************************************************************************/ /************************************ FLAGS *******************************************/ /*********************************************************************************************/ //Background modes: /** * Background mode, used in setBackgroundMode(). No lines will be drawn on the background. This is the default. */ public static final int BACKGROUND_STYLE_BLANK = 0; /** * Background mode, used in setBackgroundMode(). Will draw blue lines horizontally and a red line on the left vertically. */ public static final int BACKGROUND_STYLE_NOTEBOOK_PAPER = 1; /** * Background mode, used in setBackgroundMode(). Will draw blue lines horizontally and vertically. */ public static final int BACKGROUND_STYLE_GRAPH_PAPER = 2; //Interactive Modes: /** * Interactive modes: Will let the user draw. This is the default. */ public static final int DRAW_MODE = 0; /** * Interactive modes: Will let the user select objects. */ public static final int SELECT_MODE = 1; /** * Interactive modes: Will let the user rotate and scale objects. */ public static final int ROTATE_MODE = 2; /** * Interactive modes: Will remove all decorations and the user won't be able to modify anything. This is the mode to use when retrieving the bitmaps with getCroppedCanvasBitmap() or getCanvasBitmap(). */ public static final int LOCKED_MODE = 3; /*********************************************************************************************/ /********************************** CONSTANTS *****************************************/ /*********************************************************************************************/ /** * Number of pixels that will be on the left side of the red line when in BACKGROUND_STYLE_GRAPH_PAPER background mode. */ public static final int NOTEBOOK_LEFT_LINE_PADDING = 120; private static final int SELECTION_LINE_WIDTH = 2; /*********************************************************************************************/ /************************************ TO-DOs ******************************************/ /*********************************************************************************************/ private float mZoomLevel = 1.0f; //TODO Support Zoom private float mHorizontalOffset = 1, mVerticalOffset = 1; // TODO Support Offset and Viewport /** * Unused at this time. */ public int mAutoscrollDistance = 100; // TODO Support Autoscroll private Rect cropBounds = null; /** * Constructor, sets defaut values. * * @param context the activity that containts the view * @param attrs view attributes */ public FabricView(Context context, AttributeSet attrs) { super(context, attrs); setWillNotDraw(false); setFocusable(true); setFocusableInTouchMode(true); this.setBackgroundColor(mBackgroundColor); mTextExpectTouch = false; selectionPaint = new Paint(); selectionPaint.setAntiAlias(true); selectionPaint.setColor(selectionColor); selectionPaint.setStyle(Paint.Style.STROKE); selectionPaint.setStrokeJoin(Paint.Join.ROUND); selectionPaint.setStrokeWidth(SELECTION_LINE_WIDTH); selectionPaint.setPathEffect(new DashPathEffect(new float[]{10, 20}, 0)); deleteIcon = BitmapFactory.decodeResource(context.getResources(), android.R.drawable.ic_menu_delete); mScaleDetector = new ScaleRotationGestureDetector(context, new ScaleRotationGestureDetector.OnScaleRotationGestureListener() { @Override public void onScaleEnd(ScaleGestureDetector detector) { handleScaleEnd(); } @Override public boolean onScaleBegin(ScaleGestureDetector detector) { return handleScaleBegin((ScaleRotationGestureDetector) detector); } @Override public boolean onScale(ScaleGestureDetector detector) { return handleScale((ScaleRotationGestureDetector) detector); } @Override public boolean onRotate(ScaleRotationGestureDetector detector) { return handleScale((ScaleRotationGestureDetector) detector); } }); } private boolean handleScaleBegin(ScaleRotationGestureDetector detector) { boolean consumed = false; if(mScaleRotateListener != null && selected != null) { try { consumed = mScaleRotateListener.startRotate(); if(consumed) { mOldInteractionMode = mInteractionMode; setInteractionMode(ROTATE_MODE); mCurrentRotation = new CRotation(selected, selected.getLastBounds().centerX(), selected.getLastBounds().centerY()); mCurrentScale = new CScale(selected, selected.getLastBounds().centerX(), selected.getLastBounds().centerY()); selected.addTransform(mCurrentRotation); mDrawableList.add(mCurrentRotation); selected.addTransform(mCurrentScale); mDrawableList.add(mCurrentScale); handleScale(detector); } } catch(Exception e) { //Do nothing. } } return consumed; } private void handleScaleEnd() { if(mScaleRotateListener != null) { try { mScaleRotateListener.endRotate(); if(mOldInteractionMode != null) { setInteractionMode(mOldInteractionMode); mOldInteractionMode = null; } mCurrentScale = null; mCurrentRotation = null; } catch(Exception e) { //Do nothing. } } } public void setScaleRotateListener(ScaleRotateListener listener) { mScaleRotateListener = listener; } /** * This interface is used to decide what to do when the user does a pinch gesture for * rotating and resizing. */ public interface ScaleRotateListener { /** * If you want FabricView to hanlde rotations and resizing, return true. * @return true if the rotation will be handled by the FabricView. false to ignore the guesture. */ boolean startRotate(); /** * Called when the rotation gesture is done. */ void endRotate(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); // int minHeight = getSuggestedMinimumHeight() + getPaddingTop() + getPaddingBottom(); // int minWidth = getSuggestedMinimumWidth() + getPaddingLeft() + getPaddingRight(); // // if (minHeight > 0 && MeasureSpec.getSize(heightMeasureSpec) < minHeight) { // minHeight = // //heightMeasureSpec = MeasureSpec.makeMeasureSpec(minHeight, MeasureSpec.EXACTLY); // } // if (minWidth > 0 && MeasureSpec.getSize(widthMeasureSpec) < minWidth) { // widthMeasureSpec = MeasureSpec.makeMeasureSpec(minWidth, MeasureSpec.EXACTLY); // } // //super.onMeasure(widthMeasureSpec, heightMeasureSpec); int minw = getPaddingLeft() + getPaddingRight() + getSuggestedMinimumWidth(); int w = resolveSizeAndState(minw, widthMeasureSpec, 1); // Whatever the width ends up being, ask for a height that would let the pie // get as big as it can int minh = getPaddingTop() + getPaddingBottom() + getSuggestedMinimumHeight(); int h = resolveSizeAndState(minh, heightMeasureSpec, 1); setMeasuredDimension(w, h); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); } /** * Called when there is the canvas is being re-drawn. */ @Override protected void onDraw(Canvas canvas) { // check if background needs to be redrawn drawBackground(canvas, mBackgroundMode); Rect totalBounds = new Rect(canvas.getWidth(), canvas.getHeight(), 0, 0); // go through each item in the list and draw it for (int i = 0; i < mDrawableList.size(); i++) { try { CDrawable d = mDrawableList.get(i); if (d instanceof CTransform) { continue; } Rect bounds = d.computeBounds(); totalBounds.union(bounds); d.draw(canvas); if (mInteractionMode == SELECT_MODE && d.equals(selected)) { growRect(bounds, SELECTION_LINE_WIDTH); canvas.drawRect(new RectF(bounds), selectionPaint); deleteIconPosition = new RectF(); deleteIconPosition.left = bounds.right - (deleteIcon.getWidth() / 2); deleteIconPosition.top = bounds.top - (deleteIcon.getHeight() / 2); deleteIconPosition.right = deleteIconPosition.left + deleteIcon.getWidth(); deleteIconPosition.bottom = deleteIconPosition.top + deleteIcon.getHeight(); canvas.drawBitmap(deleteIcon, deleteIconPosition.left, deleteIconPosition.top, d.getPaint()); } } catch (Exception ex) { ex.printStackTrace(); } } if(totalBounds.width() <= 0) { //No bounds cropBounds = null; } else { cropBounds = totalBounds; } } private void growRect(Rect rect, int amount) { rect.left -= amount; rect.top -= amount; rect.bottom += amount; rect.right += amount; } /*********************************************************************************************/ /******************************* Handling User Touch **********************************/ /*********************************************************************************************/ /** * Handles user touch events. * * @param event the user's motion event * @return true, the event is consumed. */ @Override public boolean onTouchEvent(MotionEvent event) { //ROTATE_MODE is processed inside this: mScaleDetector.onTouchEvent(event); if(mScaleDetector.isInProgress()) { return true; } // delegate action to the correct method if (getInteractionMode() == DRAW_MODE) return onTouchDrawMode(event); if (getInteractionMode() == SELECT_MODE) return onTouchSelectMode(event); // if none of the above are selected, delegate to locked mode return onTouchLockedMode(event); } /** * Handles touch event if the mode is set to locked * * @param event the event to handle * @return false, shouldn't do anything with it for now */ private boolean onTouchLockedMode(MotionEvent event) { // return false since we don't want to do anything so far return false; } /** * Takes care of scaling and rotating. * @return true if the scaling gesture is consumed. */ private boolean handleScale(ScaleRotationGestureDetector detector) { if(mInteractionMode != ROTATE_MODE) { return false; } mCurrentScale.setFactor(detector.getScaleFactor(), Math.min(getWidth(), getHeight())); mCurrentRotation.setRotation((int)detector.getRotation()); invalidate(); return true; } private static final float TOUCH_TOLERANCE = 4; /** * Handles the touch input if the mode is set to draw * * @param event the touch event * @return the result of the action */ public boolean onTouchDrawMode(MotionEvent event) { // get location of touch float eventX = event.getX(); float eventY = event.getY(); if (eventX < 0) { eventX = 0; } if (eventY < 0) { eventY = 0; } if (eventX > getWidth()) { eventX = getWidth(); } if (eventY > getHeight()) { eventY = getHeight(); } // based on the users action, start drawing switch (event.getAction()) { case MotionEvent.ACTION_DOWN: // create new path and paint currentPath = new CPath(); currentPaint = new Paint(); currentPaint.setAntiAlias(true); currentPaint.setColor(mColor); currentPaint.setStyle(mStyle); currentPaint.setStrokeJoin(Paint.Join.ROUND); currentPaint.setStrokeWidth(mSize); currentPath.setPaint(currentPaint); currentPath.moveTo(eventX, eventY); // capture touched locations lastTouchX = eventX; lastTouchY = eventY; mDrawableList.add(currentPath); mUndoList.clear(); getParent().requestDisallowInterceptTouchEvent(true); break; case MotionEvent.ACTION_CANCEL: getParent().requestDisallowInterceptTouchEvent(false); break; case MotionEvent.ACTION_MOVE: float dx = Math.abs(eventX - lastTouchX); float dy = Math.abs(eventY - lastTouchY); if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) { currentPath.quadTo(lastTouchX, lastTouchY, (eventX + lastTouchX) / 2, (eventY + lastTouchY) / 2); lastTouchX = eventX; lastTouchY = eventY; } // int historySize = event.getHistorySize(); // for (int i = 0; i < historySize; i++) { // float historicalX = event.getHistoricalX(i); // float historicalY = event.getHistoricalY(i); // currentPath.lineTo(historicalX, historicalY); // } // After replaying history, connect the line to the touch point. // currentPath.lineTo(eventX, eventY); dirtyRect.left = Math.min(currentPath.getXcoords(), dirtyRect.left); dirtyRect.right = Math.max(currentPath.getXcoords() + currentPath.getWidth(), dirtyRect.right); dirtyRect.top = Math.min(currentPath.getYcoords(), dirtyRect.top); dirtyRect.bottom = Math.max(currentPath.getYcoords() + currentPath.getHeight(), dirtyRect.bottom); // After replaying history, connect the line to the touch point. cleanDirtyRegion(eventX, eventY); break; case MotionEvent.ACTION_UP: currentPath.lineTo(eventX, eventY); getParent().requestDisallowInterceptTouchEvent(false); break; default: return false; } // Include some padding to ensure nothing is clipped invalidate(); // (int) (dirtyRect.left - 20), // (int) (dirtyRect.top - 20), // (int) (dirtyRect.right + 20), // (int) (dirtyRect.bottom + 20)); // register most recent touch locations lastTouchX = eventX; lastTouchY = eventY; return true; } /** * Handles the touch input if the mode is set to select * * @param event the touch event */ private boolean onTouchSelectMode(MotionEvent event) { ListIterator<CDrawable> li = mDrawableList.listIterator(mDrawableList.size()); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: hovering = null; pressStartTime = SystemClock.uptimeMillis(); pressedX = event.getX(); pressedY = event.getY(); while (li.hasPrevious()) { CDrawable d = li.previous(); if (d instanceof CTransform) { continue; } Rect rect = d.computeBounds(); if (rect.contains((int)pressedX, (int)pressedY)) { hovering = d; break; } } if(hovering != null) { getParent().requestDisallowInterceptTouchEvent(true); } return true; case MotionEvent.ACTION_MOVE: if(hovering == null) { break; //Nothing is being dragged. } updateHoveringPosition(event); invalidate(); return true; case MotionEvent.ACTION_UP: if(hovering != null) { getParent().requestDisallowInterceptTouchEvent(false); } long pressDuration = SystemClock.uptimeMillis() - pressStartTime; double distance = Math.sqrt(Math.pow((event.getX() - pressedX), 2) + Math.pow((event.getY() - pressedY), 2)); if (pressDuration < MAX_CLICK_DURATION && distance < MAX_CLICK_DISTANCE) { //It was a click not a drag. if (hovering == null && deleteIconPosition.contains(event.getX(), event.getY())) { deleteSelection(); return true; } selected = hovering; if(hovering != null) { hovering.removeTransform(hoveringTranslation); mDrawableList.remove(hoveringTranslation); } } else if (distance > MAX_CLICK_DISTANCE) { //It was a drag. Move the object there. if (hovering != null) { updateHoveringPosition(event); } } invalidate(); hovering = null; hoveringTranslation = null; return true; case MotionEvent.ACTION_CANCEL: if(hovering != null) { getParent().requestDisallowInterceptTouchEvent(false); hovering.removeTransform(hoveringTranslation); mDrawableList.remove(hoveringTranslation); hovering = null; hoveringTranslation = null; } return true; } return false; } private void updateHoveringPosition(MotionEvent event) { double distance = Math.sqrt(Math.pow((event.getX() - pressedX), 2) + Math.pow((event.getY() - pressedY), 2)); if (distance < MAX_CLICK_DISTANCE) { return; //Movement too small } if(hoveringTranslation == null) { hoveringTranslation = new CTranslation(hovering); Vector<Integer> v = new Vector<>(2); v.add((int) (event.getX() - pressedX)); v.add((int) (event.getY() - pressedY)); hoveringTranslation.setDirection(v); hovering.addTransform(hoveringTranslation); mDrawableList.add(hoveringTranslation); mUndoList.clear(); } else { //Last transform was a translation. Replace translation with new coordinates. Vector<Integer> v = new Vector<>(2); v.add((int) (event.getX() - pressedX)); v.add((int) (event.getY() - pressedY)); hoveringTranslation.setDirection(v); } } /******************************************* * Drawing Events ******************************************/ /** * Draw the background on the canvas * * @param canvas the canvas to draw on * @param backgroundMode one of BACKGROUND_STYLE_GRAPH_PAPER, BACKGROUND_STYLE_NOTEBOOK_PAPER, BACKGROUND_STYLE_BLANK */ public void drawBackground(Canvas canvas, int backgroundMode) { if(mBackgroundColor != Color.TRANSPARENT) { canvas.drawColor(mBackgroundColor); } if (backgroundMode != BACKGROUND_STYLE_BLANK) { Paint linePaint = new Paint(); linePaint.setColor(Color.argb(50, 0, 0, 0)); linePaint.setStyle(mStyle); linePaint.setStrokeJoin(Paint.Join.ROUND); linePaint.setStrokeWidth(mSize - 2f); switch (backgroundMode) { case BACKGROUND_STYLE_GRAPH_PAPER: drawGraphPaperBackground(canvas, linePaint); break; case BACKGROUND_STYLE_NOTEBOOK_PAPER: drawNotebookPaperBackground(canvas, linePaint); default: break; } } mRedrawBackground = false; } /** * Draws a graph paper background on the view * * @param canvas the canvas to draw on * @param paint the paint to use */ private void drawGraphPaperBackground(Canvas canvas, Paint paint) { int i = 0; boolean doneH = false, doneV = false; // while we still need to draw either H or V while (!(doneH && doneV)) { // check if there is more H lines to draw if (i < canvas.getHeight()) canvas.drawLine(0, i, canvas.getWidth(), i, paint); else doneH = true; // check if there is more V lines to draw if (i < canvas.getWidth()) canvas.drawLine(i, 0, i, canvas.getHeight(), paint); else doneV = true; // declare as done i += 75; } } /** * Draws a notebook paper background on the view * * @param canvas the canvas to draw on * @param paint the paint to use */ private void drawNotebookPaperBackground(Canvas canvas, Paint paint) { int i = 0; boolean doneV = false; // draw horizental lines while (!(doneV)) { if (i < canvas.getHeight()) canvas.drawLine(0, i, canvas.getWidth(), i, paint); else doneV = true; i += 75; } // change line color paint.setColor(NOTEBOOK_LEFT_LINE_COLOR); // draw side line canvas.drawLine(NOTEBOOK_LEFT_LINE_PADDING, 0, NOTEBOOK_LEFT_LINE_PADDING, canvas.getHeight(), paint); } /** * Draw text on the screen * * @param text the text to draw * @param x the x location of the text * @param y the y location of the text * @param p the paint to use. This is used for the TextSize, color. If null, the defaut is black with 20sp size. */ public void drawText(String text, int x, int y, Paint p) { if(p==null) { int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 20, getContext().getResources().getDisplayMetrics()); p = new Paint(); p.setTextSize(px); p.setColor(Color.BLACK); } mDrawableList.add(new CText(text, x, y, p)); mUndoList.clear(); invalidate(); } /** * Capture Text from the keyboard and draw it on the screen * //TODO Implement the method */ private void drawTextFromKeyboard() { Toast.makeText(getContext(), "Touch where you want the text to be", Toast.LENGTH_LONG).show(); //TODO mTextExpectTouch = true; } /** * Retrieve the region needing to be redrawn * * @param eventX The current x location of the touch * @param eventY the current y location of the touch */ private void cleanDirtyRegion(float eventX, float eventY) { // figure out the sides of the dirty region dirtyRect.left = Math.min(lastTouchX, eventX); dirtyRect.right = Math.max(lastTouchX, eventX); dirtyRect.top = Math.min(lastTouchY, eventY); dirtyRect.bottom = Math.max(lastTouchY, eventY); } /** * Cancels the last operation. Works on both CDrawable and CTransform. */ public void undo() { if (mDrawableList.size() > 0) { CDrawable toUndo = mDrawableList.get(mDrawableList.size() - 1); mUndoList.add(toUndo); mDrawableList.remove(mDrawableList.size() - 1); if(toUndo instanceof CTransform) { CTransform t = (CTransform)toUndo; t.getDrawable().removeTransform(t); } invalidate(); } } /** * Re-instates the last undone operation. */ public void redo() { if (mUndoList.size() > 0) { CDrawable toRedo = mUndoList.get(mUndoList.size() - 1); mDrawableList.add(toRedo); mDrawableList.addAll(toRedo.getTransforms()); mUndoList.remove(toRedo); if(toRedo instanceof CTransform) { CTransform t = (CTransform)toRedo; t.getDrawable().addTransform(t); } invalidate(); } } /** * Clean the canvas, remove everything drawn on the canvas. * WARNING: Before calling this, ask the user to confirm because <b>this cannot be undone</b>. */ public void cleanPage() { // remove everything from the list mDrawableList.clear(); currentPath = null; mUndoList.clear(); savePoint = -1; // request to redraw the canvas invalidate(); } /** * Draws an image on the canvas * * @param x location of the image * @param y location of the image * @param width the width of the image * @param height the height of the image * @param pic the image itself */ public void drawImage(int x, int y, int width, int height, Bitmap pic) { CBitmap bitmap = new CBitmap(pic, x, y); bitmap.setWidth(width); bitmap.setHeight(height); mDrawableList.add(bitmap); mUndoList.clear(); invalidate(); } /******************************************* * Getters and Setters ******************************************/ /** * Gets what has been drawn on the canvas so far as a bitmap * * @return Bitmap of the canvas. */ public Bitmap getCanvasBitmap() { // build drawing cache of the canvas, use it to create a new bitmap, then destroy it. buildDrawingCache(); Bitmap mCanvasBitmap = Bitmap.createBitmap(getDrawingCache()); destroyDrawingCache(); // return the created bitmap. return mCanvasBitmap; } /** * Gets what has been drawn on the canvas so far as a bitmap. Removes any margin around the drawn objects. * * @return Bitmap of the canvas, cropped. */ public Bitmap getCroppedCanvasBitmap() { if(cropBounds == null) { //No pixels at all return null; } Bitmap mCanvasBitmap = getCanvasBitmap(); Rect size = new Rect(cropBounds); if(size.left < 0) { size.left = 0; } if(size.top < 0) { size.top = 0; } if(size.right > mCanvasBitmap.getWidth()) { size.right = mCanvasBitmap.getWidth(); } if(size.bottom > mCanvasBitmap.getHeight()) { size.bottom = mCanvasBitmap.getHeight(); } Bitmap cropped = Bitmap.createBitmap(mCanvasBitmap, size.left, size.top, size.width(), size.height()); return cropped; } /** * @return the drawing line color. Default is Color.BLACK. */ public int getColor() { return mColor; } /** * Setter for the the drawing line color. * @param mColor The new color. */ public void setColor(int mColor) { this.mColor = mColor; } /** * @return the background color. Default is Color.WHITE. */ public int getBackgroundColor() { return mBackgroundColor; } /** * Setter for the background color. * @param mBackgroundColor The new background color. */ public void setBackgroundColor(int mBackgroundColor) { this.mBackgroundColor = mBackgroundColor; } /** * @return the background decorations mode. Default is BACKGROUND_STYLE_BLANK. */ public int getBackgroundMode() { return mBackgroundMode; } /** * Setter for the background decorations mode. Can be BACKGROUND_STYLE_BLANK*, BACKGROUND_STYLE_NOTEBOOK_PAPER, or BACKGROUND_STYLE_GRAPH_PAPER. * @param mBackgroundMode */ public void setBackgroundMode(int mBackgroundMode) { this.mBackgroundMode = mBackgroundMode; invalidate(); } /** * @return The drawing style. Can be Paint.Style.FILL, Paint.Style.STROKE, or Paint.Style.FILL_AND_STROKE. Default is Paint.Style.STROKE. */ public Paint.Style getStyle() { return mStyle; } /** * Setter for the drawing style. * @param mStyle The new drawing style. Can be Can be FILL, STROKE, or FILL_AND_STROKE. */ public void setStyle(Paint.Style mStyle) { this.mStyle = mStyle; } /** * @return The width of the line for drawing. */ public float getSize() { return mSize; } /** * Setter for the line width. The default is 5. * @param mSize The new width for the line. */ public void setSize(float mSize) { this.mSize = mSize; } /** * @return The interaction mode. The default is DRAW_MODE. */ public int getInteractionMode() { return mInteractionMode; } /** * Setter for the interaction mode. Can be DRAW_MODE, SELECT_MODE, ROTATE_MODE, or LOCKED_MODE. * @param interactionMode */ public void setInteractionMode(int interactionMode) { // if the value passed is not any of the flags, set the library to locked mode if (interactionMode > LOCKED_MODE) interactionMode = LOCKED_MODE; else if (interactionMode < DRAW_MODE) interactionMode = LOCKED_MODE; this.mInteractionMode = interactionMode; invalidate(); } /** * @return the list of all CDrawables in order of insertion. */ public List<CDrawable> getDrawablesList() { return mDrawableList; } /** * Indicates that all CDrawables in the list have been saved. */ public void markSaved() { savePoint = mDrawableList.size()-1; } /** * @return true if there were no new operations done after the last call to markSaved(). */ public boolean isSaved() { return savePoint < mDrawableList.size(); } /** * @return The list of all CDrawables that have been added after the last call to markSaved(). */ public List<CDrawable> getUnsavedDrawablesList() { if (savePoint >= mDrawableList.size()) { //Some things were deleted. return new ArrayList<>(); } return mDrawableList.subList(savePoint+1, mDrawableList.size()); } /** * Deletes all CDrawables that were added after the last call to markSaved(). * Does not trigger DeletionConfirmationListener. */ public void revertUnsaved() { List<CDrawable> unsaved = new ArrayList<>(getUnsavedDrawablesList()); for (CDrawable d : unsaved) { deletionConfirmed(d); } } /** * Marks the last inserted CDrawable as the selected object. */ public void selectLastDrawn() { if (mDrawableList.isEmpty()) { return; } ListIterator<CDrawable> li = mDrawableList.listIterator(mDrawableList.size()); while (li.hasPrevious()) { CDrawable d = li.previous(); if (d instanceof CTransform) { continue; } selected = d; break; } invalidate(); } /** * @return The currently selected CDrawable. */ public CDrawable getSelection() { return selected; } /** * Cancels all selection. No object will be selected. */ public void deSelect() { selected = null; invalidate(); } /** * Deletes the currently selected object. No object will be selected after that. */ public void deleteSelection() { if (selected == null) { return; } deleteDrawable(selected); selected = null; } /** * Removes a specific CDrawable, with confirmation if required. * @param drawable The object to remove. */ public void deleteDrawable(CDrawable drawable) { if (drawable == null) { return; } if (deletionConfirmationListener != null) { try { deletionConfirmationListener.confirmDeletion(drawable); } catch(Exception e) { //Do nothing } return; } deletionConfirmed(drawable); } /** * Removes a specific CDrawable, without confirmation. Must be called by your * DeletionConfirmationListener.confirmDeletion() to finish the deletion. * @param drawable The object to remove. */ public void deletionConfirmed(CDrawable drawable) { if (drawable == null) { return; } ArrayList<CDrawable> toDelete = new ArrayList<>(); toDelete.add(drawable); toDelete.addAll(drawable.getTransforms()); for (CDrawable d : toDelete) { if(mDrawableList.indexOf(d) <= savePoint) { savePoint--; } mDrawableList.remove(d); } mUndoList.add(drawable); if (deletionListener != null) { try { deletionListener.deleted(drawable); } catch(Exception e) { //Do nothing } } invalidate(); } /** * Setter for the "delete" icon. The default is android.R.drawable.ic_menu_delete. * @param newIcon The new delete icon. */ public void setDeleteIcon(Bitmap newIcon) { deleteIcon = newIcon; } /** * Setter for the deletion event listener. Refer to the Observer pattern. * @param newListener The listener for any deletion event. */ public void setDeletionListener(DeletionListener newListener) { deletionListener = newListener; } /** * This interface must be implemented by your deletion event listener. */ public interface DeletionListener { /** * This method will be called after a CDrawable is deleted. * @param drawable The object that was deleted. */ void deleted(CDrawable drawable); } /** * Setter for the listener that will confirm deletion. Refer to the Observer pattern. * @param newListener The listener for any deletion confirmation request. */ public void setDeletionConfirmationListener(DeletionConfirmationListener newListener) { deletionConfirmationListener = newListener; } /** * This interface must be implemented by a listener for confirming deletion. If confirmed, * the listener must call confirmDeletion(CDrawable). */ public interface DeletionConfirmationListener { /** * This method will be called before a CDrawable is deleted in order to confirm the deletion. * If the deletion is allowed, call FabricView.deletionConfirmed(CDrawable). * @param drawable The object that's about to be deleted. */ void confirmDeletion(CDrawable drawable); } /** * @return The current selection rectangle color. The default is Color.DKGRAY. */ public int getSelectionColor() { return selectionColor; } /** * Setter for the selection rectangle color. * @param selectionColor The new selection rectangle color. */ public void setSelectionColor(int selectionColor) { this.selectionColor = selectionColor; } }
36.079903
204
0.587634
f5c849572b1ea5891a497c190e5ef557d18ee051
16,467
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 DECL|package|org.apache.hadoop.yarn.client package|package name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|client package|; end_package begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|conf operator|. name|Configuration import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|io operator|. name|Text import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|security operator|. name|UserGroupInformation import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|util operator|. name|StringUtils import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|api operator|. name|ApplicationClientProtocol import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|api operator|. name|protocolrecords operator|. name|GetNewApplicationRequest import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|conf operator|. name|HAUtil import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|conf operator|. name|YarnConfiguration import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|ipc operator|. name|HadoopYarnProtoRPC import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|ipc operator|. name|YarnRPC import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|yarn operator|. name|util operator|. name|Records import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Assert import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Test import|; end_import begin_import import|import name|java operator|. name|io operator|. name|IOException import|; end_import begin_import import|import name|java operator|. name|net operator|. name|InetSocketAddress import|; end_import begin_import import|import name|java operator|. name|security operator|. name|PrivilegedExceptionAction import|; end_import 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|assertNotNull import|; end_import begin_import import|import static name|org operator|. name|junit operator|. name|Assert operator|. name|assertTrue import|; end_import begin_class DECL|class|TestClientRMProxy specifier|public class|class name|TestClientRMProxy block|{ annotation|@ name|Test DECL|method|testGetRMDelegationTokenService () specifier|public name|void name|testGetRMDelegationTokenService parameter_list|() block|{ name|String name|defaultRMAddress init|= name|YarnConfiguration operator|. name|DEFAULT_RM_ADDRESS decl_stmt|; name|YarnConfiguration name|conf init|= operator|new name|YarnConfiguration argument_list|() decl_stmt|; comment|// HA is not enabled name|Text name|tokenService init|= name|ClientRMProxy operator|. name|getRMDelegationTokenService argument_list|( name|conf argument_list|) decl_stmt|; name|String index|[] name|services init|= name|tokenService operator|. name|toString argument_list|() operator|. name|split argument_list|( literal|"," argument_list|) decl_stmt|; name|assertEquals argument_list|( literal|1 argument_list|, name|services operator|. name|length argument_list|) expr_stmt|; for|for control|( name|String name|service range|: name|services control|) block|{ name|assertTrue argument_list|( literal|"Incorrect token service name" argument_list|, name|service operator|. name|contains argument_list|( name|defaultRMAddress argument_list|) argument_list|) expr_stmt|; block|} comment|// HA is enabled name|conf operator|. name|setBoolean argument_list|( name|YarnConfiguration operator|. name|RM_HA_ENABLED argument_list|, literal|true argument_list|) expr_stmt|; name|conf operator|. name|set argument_list|( name|YarnConfiguration operator|. name|RM_HA_IDS argument_list|, literal|"rm1,rm2" argument_list|) expr_stmt|; name|conf operator|. name|set argument_list|( name|HAUtil operator|. name|addSuffix argument_list|( name|YarnConfiguration operator|. name|RM_HOSTNAME argument_list|, literal|"rm1" argument_list|) argument_list|, literal|"0.0.0.0" argument_list|) expr_stmt|; name|conf operator|. name|set argument_list|( name|HAUtil operator|. name|addSuffix argument_list|( name|YarnConfiguration operator|. name|RM_HOSTNAME argument_list|, literal|"rm2" argument_list|) argument_list|, literal|"0.0.0.0" argument_list|) expr_stmt|; name|tokenService operator|= name|ClientRMProxy operator|. name|getRMDelegationTokenService argument_list|( name|conf argument_list|) expr_stmt|; name|services operator|= name|tokenService operator|. name|toString argument_list|() operator|. name|split argument_list|( literal|"," argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|2 argument_list|, name|services operator|. name|length argument_list|) expr_stmt|; for|for control|( name|String name|service range|: name|services control|) block|{ name|assertTrue argument_list|( literal|"Incorrect token service name" argument_list|, name|service operator|. name|contains argument_list|( name|defaultRMAddress argument_list|) argument_list|) expr_stmt|; block|} block|} annotation|@ name|Test DECL|method|testGetAMRMTokenService () specifier|public name|void name|testGetAMRMTokenService parameter_list|() block|{ name|String name|defaultRMAddress init|= name|YarnConfiguration operator|. name|DEFAULT_RM_SCHEDULER_ADDRESS decl_stmt|; name|YarnConfiguration name|conf init|= operator|new name|YarnConfiguration argument_list|() decl_stmt|; comment|// HA is not enabled name|Text name|tokenService init|= name|ClientRMProxy operator|. name|getAMRMTokenService argument_list|( name|conf argument_list|) decl_stmt|; name|String index|[] name|services init|= name|tokenService operator|. name|toString argument_list|() operator|. name|split argument_list|( literal|"," argument_list|) decl_stmt|; name|assertEquals argument_list|( literal|1 argument_list|, name|services operator|. name|length argument_list|) expr_stmt|; for|for control|( name|String name|service range|: name|services control|) block|{ name|assertTrue argument_list|( literal|"Incorrect token service name" argument_list|, name|service operator|. name|contains argument_list|( name|defaultRMAddress argument_list|) argument_list|) expr_stmt|; block|} comment|// HA is enabled name|conf operator|. name|setBoolean argument_list|( name|YarnConfiguration operator|. name|RM_HA_ENABLED argument_list|, literal|true argument_list|) expr_stmt|; name|conf operator|. name|set argument_list|( name|YarnConfiguration operator|. name|RM_HA_IDS argument_list|, literal|"rm1,rm2" argument_list|) expr_stmt|; name|conf operator|. name|set argument_list|( name|HAUtil operator|. name|addSuffix argument_list|( name|YarnConfiguration operator|. name|RM_HOSTNAME argument_list|, literal|"rm1" argument_list|) argument_list|, literal|"0.0.0.0" argument_list|) expr_stmt|; name|conf operator|. name|set argument_list|( name|HAUtil operator|. name|addSuffix argument_list|( name|YarnConfiguration operator|. name|RM_HOSTNAME argument_list|, literal|"rm2" argument_list|) argument_list|, literal|"0.0.0.0" argument_list|) expr_stmt|; name|tokenService operator|= name|ClientRMProxy operator|. name|getAMRMTokenService argument_list|( name|conf argument_list|) expr_stmt|; name|services operator|= name|tokenService operator|. name|toString argument_list|() operator|. name|split argument_list|( literal|"," argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|2 argument_list|, name|services operator|. name|length argument_list|) expr_stmt|; for|for control|( name|String name|service range|: name|services control|) block|{ name|assertTrue argument_list|( literal|"Incorrect token service name" argument_list|, name|service operator|. name|contains argument_list|( name|defaultRMAddress argument_list|) argument_list|) expr_stmt|; block|} block|} comment|/** * Verify that the RPC layer is always created using the correct UGI from the * RMProxy. It should always use the UGI from creation in subsequent uses, * even outside of a doAs. * * @throws Exception an Exception occurred */ annotation|@ name|Test DECL|method|testProxyUserCorrectUGI () specifier|public name|void name|testProxyUserCorrectUGI parameter_list|() throws|throws name|Exception block|{ specifier|final name|YarnConfiguration name|conf init|= operator|new name|YarnConfiguration argument_list|() decl_stmt|; name|conf operator|. name|setBoolean argument_list|( name|YarnConfiguration operator|. name|RM_HA_ENABLED argument_list|, literal|true argument_list|) expr_stmt|; name|conf operator|. name|set argument_list|( name|YarnConfiguration operator|. name|RM_HA_IDS argument_list|, literal|"rm1,rm2" argument_list|) expr_stmt|; name|conf operator|. name|set argument_list|( name|HAUtil operator|. name|addSuffix argument_list|( name|YarnConfiguration operator|. name|RM_HOSTNAME argument_list|, literal|"rm1" argument_list|) argument_list|, literal|"0.0.0.0" argument_list|) expr_stmt|; name|conf operator|. name|set argument_list|( name|HAUtil operator|. name|addSuffix argument_list|( name|YarnConfiguration operator|. name|RM_HOSTNAME argument_list|, literal|"rm2" argument_list|) argument_list|, literal|"0.0.0.0" argument_list|) expr_stmt|; name|conf operator|. name|setLong argument_list|( name|YarnConfiguration operator|. name|CLIENT_FAILOVER_MAX_ATTEMPTS argument_list|, literal|2 argument_list|) expr_stmt|; name|conf operator|. name|setLong argument_list|( name|YarnConfiguration operator|. name|RESOURCEMANAGER_CONNECT_MAX_WAIT_MS argument_list|, literal|2 argument_list|) expr_stmt|; name|conf operator|. name|setLong argument_list|( name|YarnConfiguration operator|. name|RESOURCEMANAGER_CONNECT_RETRY_INTERVAL_MS argument_list|, literal|2 argument_list|) expr_stmt|; comment|// Replace the RPC implementation with one that will capture the current UGI name|conf operator|. name|setClass argument_list|( name|YarnConfiguration operator|. name|IPC_RPC_IMPL argument_list|, name|UGICapturingHadoopYarnProtoRPC operator|. name|class argument_list|, name|YarnRPC operator|. name|class argument_list|) expr_stmt|; name|UserGroupInformation name|realUser init|= name|UserGroupInformation operator|. name|getCurrentUser argument_list|() decl_stmt|; name|UserGroupInformation name|proxyUser init|= name|UserGroupInformation operator|. name|createProxyUserForTesting argument_list|( literal|"proxy" argument_list|, name|realUser argument_list|, operator|new name|String index|[] block|{ literal|"group1" block|} argument_list|) decl_stmt|; comment|// Create the RMProxy using the proxyUser name|ApplicationClientProtocol name|rmProxy init|= name|proxyUser operator|. name|doAs argument_list|( operator|new name|PrivilegedExceptionAction argument_list|< name|ApplicationClientProtocol argument_list|> argument_list|() block|{ annotation|@ name|Override specifier|public name|ApplicationClientProtocol name|run parameter_list|() throws|throws name|Exception block|{ return|return name|ClientRMProxy operator|. name|createRMProxy argument_list|( name|conf argument_list|, name|ApplicationClientProtocol operator|. name|class argument_list|) return|; block|} block|} argument_list|) decl_stmt|; comment|// It was in a doAs, so the UGI should be correct name|assertUGI argument_list|() expr_stmt|; comment|// Try to use the RMProxy, which should trigger the RPC again name|GetNewApplicationRequest name|request init|= name|Records operator|. name|newRecord argument_list|( name|GetNewApplicationRequest operator|. name|class argument_list|) decl_stmt|; name|UGICapturingHadoopYarnProtoRPC operator|. name|lastCurrentUser operator|= literal|null expr_stmt|; try|try block|{ name|rmProxy operator|. name|getNewApplication argument_list|( name|request argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|IOException name|ioe parameter_list|) block|{ comment|// ignore - RMs are not running so this is expected to fail block|} comment|// This time it was outside a doAs, but make sure the UGI was still correct name|assertUGI argument_list|() expr_stmt|; block|} DECL|method|assertUGI () specifier|private name|void name|assertUGI parameter_list|() throws|throws name|IOException block|{ name|UserGroupInformation name|lastCurrentUser init|= name|UGICapturingHadoopYarnProtoRPC operator|. name|lastCurrentUser decl_stmt|; name|assertNotNull argument_list|( name|lastCurrentUser argument_list|) expr_stmt|; name|assertEquals argument_list|( literal|"proxy" argument_list|, name|lastCurrentUser operator|. name|getShortUserName argument_list|() argument_list|) expr_stmt|; name|Assert operator|. name|assertEquals argument_list|( name|UserGroupInformation operator|. name|AuthenticationMethod operator|. name|PROXY argument_list|, name|lastCurrentUser operator|. name|getAuthenticationMethod argument_list|() argument_list|) expr_stmt|; name|assertEquals argument_list|( name|UserGroupInformation operator|. name|getCurrentUser argument_list|() argument_list|, name|lastCurrentUser operator|. name|getRealUser argument_list|() argument_list|) expr_stmt|; comment|// Reset UGICapturingHadoopYarnProtoRPC name|UGICapturingHadoopYarnProtoRPC operator|. name|lastCurrentUser operator|= literal|null expr_stmt|; block|} comment|/** * Subclass of {@link HadoopYarnProtoRPC} which captures the current UGI in * a static variable. Used by {@link #testProxyUserCorrectUGI()}. */ DECL|class|UGICapturingHadoopYarnProtoRPC specifier|public specifier|static class|class name|UGICapturingHadoopYarnProtoRPC extends|extends name|HadoopYarnProtoRPC block|{ DECL|field|lastCurrentUser specifier|static name|UserGroupInformation name|lastCurrentUser init|= literal|null decl_stmt|; annotation|@ name|Override DECL|method|getProxy (Class protocol, InetSocketAddress addr, Configuration conf) specifier|public name|Object name|getProxy parameter_list|( name|Class name|protocol parameter_list|, name|InetSocketAddress name|addr parameter_list|, name|Configuration name|conf parameter_list|) block|{ name|UserGroupInformation name|currentUser init|= literal|null decl_stmt|; try|try block|{ name|currentUser operator|= name|UserGroupInformation operator|. name|getCurrentUser argument_list|() expr_stmt|; block|} catch|catch parameter_list|( name|IOException name|ioe parameter_list|) block|{ name|Assert operator|. name|fail argument_list|( literal|"Unable to get current user\n" operator|+ name|StringUtils operator|. name|stringifyException argument_list|( name|ioe argument_list|) argument_list|) expr_stmt|; block|} name|lastCurrentUser operator|= name|currentUser expr_stmt|; return|return name|super operator|. name|getProxy argument_list|( name|protocol argument_list|, name|addr argument_list|, name|conf argument_list|) return|; block|} block|} block|} end_class end_unit
15.549575
814
0.809133
1567e53c16d4cffc59f0bbd3d039c306f7f8b22f
85
package edu.asu.plp.tool.backend.plpisa.sim.stages; public class wb_stage_temp { }
14.166667
51
0.776471
26f75e5c9ed800d356f7b7bd07a8c3a014a3bf15
711
public class App { public static void main(String[] args) throws Exception { test(new Bagno(Sesso.MASCHIO)); test(new BagnoEquo(Sesso.MASCHIO)); } private static void test(Bagno b) { System.out.println("Test of " + b); new Persona(Sesso.FEMMINA, b).start(); new Persona(Sesso.MASCHIO, b).start(); for (int i = 0; i < 5; i++) { new Persona(b.getSesso(), b).start(); } while (Thread.activeCount() > 1) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("End of test of " + b); } }
29.625
61
0.510549
12550cf58a637658f1ff64e26403511b1f510595
8,063
package com.dynamsoft.readadriverlicense; import androidx.appcompat.app.AppCompatActivity; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.TextView; import com.dynamsoft.dbr.BarcodeReader; import com.dynamsoft.dbr.BarcodeReaderException; import com.dynamsoft.dbr.DBRLicenseVerificationListener; import com.dynamsoft.dbr.EnumBarcodeFormat; import com.dynamsoft.dbr.EnumBarcodeFormat_2; import com.dynamsoft.dbr.EnumConflictMode; import com.dynamsoft.dbr.EnumIntermediateResultType; import com.dynamsoft.dbr.ImageData; import com.dynamsoft.dbr.PublicRuntimeSettings; import com.dynamsoft.dbr.TextResult; import com.dynamsoft.dbr.TextResultListener; import com.dynamsoft.dce.CameraEnhancer; import com.dynamsoft.dce.CameraEnhancerException; import com.dynamsoft.dce.DCECameraView; import java.util.HashMap; public class MainActivity extends AppCompatActivity { DCECameraView cameraView; private TextView mFlash; BarcodeReader reader; CameraEnhancer mCameraEnhancer; private boolean isFinished = false; @SuppressLint("HandlerLeak") private final Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); TextResult[] results = (TextResult[]) msg.obj; if (isFinished) return; for (TextResult result : results) { if (DBRDriverLicenseUtil.ifDriverLicense(result.barcodeText)) { isFinished = true; HashMap<String, String> resultMaps = DBRDriverLicenseUtil.readUSDriverLicense(result.barcodeText); Intent intent = new Intent(MainActivity.this, ResultActivity.class); DriverLicense driverLicense = new DriverLicense(); driverLicense.documentType = "DL"; driverLicense.firstName = resultMaps.get(DBRDriverLicenseUtil.FIRST_NAME); driverLicense.middleName = resultMaps.get(DBRDriverLicenseUtil.MIDDLE_NAME); driverLicense.lastName = resultMaps.get(DBRDriverLicenseUtil.LAST_NAME); driverLicense.gender = resultMaps.get(DBRDriverLicenseUtil.GENDER); driverLicense.addressStreet = resultMaps.get(DBRDriverLicenseUtil.STREET); driverLicense.addressCity = resultMaps.get(DBRDriverLicenseUtil.CITY); driverLicense.addressState = resultMaps.get(DBRDriverLicenseUtil.STATE); driverLicense.addressZip = resultMaps.get(DBRDriverLicenseUtil.ZIP); driverLicense.licenseNumber = resultMaps.get(DBRDriverLicenseUtil.LICENSE_NUMBER); driverLicense.issueDate = resultMaps.get(DBRDriverLicenseUtil.ISSUE_DATE); driverLicense.expiryDate = resultMaps.get(DBRDriverLicenseUtil.EXPIRY_DATE); driverLicense.birthDate = resultMaps.get(DBRDriverLicenseUtil.BIRTH_DATE); driverLicense.issuingCountry = resultMaps.get(DBRDriverLicenseUtil.ISSUING_COUNTRY); intent.putExtra("DriverLicense", driverLicense); startActivity(intent); } } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); cameraView = findViewById(R.id.cameraView); mFlash = findViewById(R.id.tv_flash); // Initialize license for Dynamsoft Barcode Reader. // The license string here is a time-limited trial license. Note that network connection is required for this license to work. // You can also request an extension for your trial license in the customer portal: https://www.dynamsoft.com/customer/license/trialLicense?product=dbr&utm_source=installer&package=android BarcodeReader.initLicense("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9", new DBRLicenseVerificationListener() { @Override public void DBRLicenseVerificationCallback(boolean isSuccessful, Exception e) { runOnUiThread(() -> { if (!isSuccessful) { e.printStackTrace(); showErrorDialog(e.getMessage()); } }); } }); try { // Create an instance of Dynamsoft Barcode Reader. reader = new BarcodeReader(); initBarcodeReader(); // Get the TestResult object from the callback TextResultListener mTextResultCallback = new TextResultListener() { @Override public void textResultCallback(int id, ImageData imageData, TextResult[] textResults) { if (textResults == null || textResults.length == 0) return; Message message = handler.obtainMessage(); message.obj = textResults; handler.sendMessage(message); } }; //Create a camera module for video barcode scanning. mCameraEnhancer = new CameraEnhancer(MainActivity.this); mCameraEnhancer.setCameraView(cameraView); // Bind the Camera Enhancer instance to the Barcode Reader instance. reader.setCameraEnhancer(mCameraEnhancer); // Make this setting to get the result. The result will be an object that contains text result and other barcode information. reader.setTextResultListener(mTextResultCallback); } catch (BarcodeReaderException e) { e.printStackTrace(); } } @Override public void onResume() { isFinished = false; try { mCameraEnhancer.open(); } catch (CameraEnhancerException e) { e.printStackTrace(); } reader.startScanning(); super.onResume(); } @Override public void onPause() { try { mCameraEnhancer.close(); } catch (CameraEnhancerException e) { e.printStackTrace(); } reader.stopScanning(); super.onPause(); } private boolean mIsFlashOn = false; public void onFlashClick(View v) { if (mCameraEnhancer == null) return; try { if (!mIsFlashOn) { mCameraEnhancer.turnOnTorch(); mIsFlashOn = true; mFlash.setText("Flash OFF"); } else { mCameraEnhancer.turnOffTorch(); mIsFlashOn = false; mFlash.setText("Flash ON"); } } catch (CameraEnhancerException e) { e.printStackTrace(); } } void initBarcodeReader() throws BarcodeReaderException { PublicRuntimeSettings runtimeSettings = reader.getRuntimeSettings(); runtimeSettings.barcodeFormatIds = EnumBarcodeFormat.BF_ALL; runtimeSettings.barcodeFormatIds_2 = EnumBarcodeFormat_2.BF2_NULL; runtimeSettings.timeout = 3000; runtimeSettings.intermediateResultTypes = EnumIntermediateResultType.IRT_TYPED_BARCODE_ZONE; if (reader != null) { reader.initRuntimeSettingsWithString("{\"ImageParameter\":{\"Name\":\"Balance\",\"DeblurLevel\":5,\"ExpectedBarcodesCount\":512,\"LocalizationModes\":[{\"Mode\":\"LM_CONNECTED_BLOCKS\"},{\"Mode\":\"LM_SCAN_DIRECTLY\"}]}}", EnumConflictMode.CM_OVERWRITE); reader.updateRuntimeSettings(runtimeSettings); } } private void showErrorDialog(String message) { AlertDialog.Builder dialog = new AlertDialog.Builder(this); dialog.setTitle(R.string.error_dialog_title) .setPositiveButton("OK",null) .setMessage(message) .show(); } }
41.561856
266
0.643185
9f80fab44c060b466d8b19d1e9d81525fb0f3672
13,154
package net.minecraft.world.inventory; import java.util.Iterator; import java.util.Map; import net.minecraft.network.chat.ChatComponentText; import net.minecraft.tags.Tag; import net.minecraft.tags.TagsBlock; import net.minecraft.world.entity.player.EntityHuman; import net.minecraft.world.entity.player.PlayerInventory; import net.minecraft.world.item.ItemEnchantedBook; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.item.enchantment.Enchantment; import net.minecraft.world.item.enchantment.EnchantmentManager; import net.minecraft.world.level.block.BlockAnvil; import net.minecraft.world.level.block.state.IBlockData; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; // CraftBukkit start import org.bukkit.craftbukkit.inventory.CraftInventoryView; // CraftBukkit end public class ContainerAnvil extends ContainerAnvilAbstract { private static final Logger LOGGER = LogManager.getLogger(); private static final boolean DEBUG_COST = false; public static final int MAX_NAME_LENGTH = 50; private int repairItemCountCost; public String itemName; public final ContainerProperty cost; private static final int COST_FAIL = 0; private static final int COST_BASE = 1; private static final int COST_ADDED_BASE = 1; private static final int COST_REPAIR_MATERIAL = 1; private static final int COST_REPAIR_SACRIFICE = 2; private static final int COST_INCOMPATIBLE_PENALTY = 1; private static final int COST_RENAME = 1; // CraftBukkit start public int maximumRepairCost = 40; private CraftInventoryView bukkitEntity; // CraftBukkit end public ContainerAnvil(int i, PlayerInventory playerinventory) { this(i, playerinventory, ContainerAccess.NULL); } public ContainerAnvil(int i, PlayerInventory playerinventory, ContainerAccess containeraccess) { super(Containers.ANVIL, i, playerinventory, containeraccess); this.cost = ContainerProperty.standalone(); this.addDataSlot(this.cost); } @Override protected boolean isValidBlock(IBlockData iblockdata) { return iblockdata.is((Tag) TagsBlock.ANVIL); } @Override protected boolean mayPickup(EntityHuman entityhuman, boolean flag) { return (entityhuman.getAbilities().instabuild || entityhuman.experienceLevel >= this.cost.get()) && this.cost.get() > 0; } @Override protected void onTake(EntityHuman entityhuman, ItemStack itemstack) { if (!entityhuman.getAbilities().instabuild) { entityhuman.giveExperienceLevels(-this.cost.get()); } this.inputSlots.setItem(0, ItemStack.EMPTY); if (this.repairItemCountCost > 0) { ItemStack itemstack1 = this.inputSlots.getItem(1); if (!itemstack1.isEmpty() && itemstack1.getCount() > this.repairItemCountCost) { itemstack1.shrink(this.repairItemCountCost); this.inputSlots.setItem(1, itemstack1); } else { this.inputSlots.setItem(1, ItemStack.EMPTY); } } else { this.inputSlots.setItem(1, ItemStack.EMPTY); } this.cost.set(0); this.access.execute((world, blockposition) -> { IBlockData iblockdata = world.getBlockState(blockposition); if (!entityhuman.getAbilities().instabuild && iblockdata.is((Tag) TagsBlock.ANVIL) && entityhuman.getRandom().nextFloat() < 0.12F) { IBlockData iblockdata1 = BlockAnvil.damage(iblockdata); if (iblockdata1 == null) { world.removeBlock(blockposition, false); world.levelEvent(1029, blockposition, 0); } else { world.setBlock(blockposition, iblockdata1, 2); world.levelEvent(1030, blockposition, 0); } } else { world.levelEvent(1030, blockposition, 0); } }); } @Override public void createResult() { ItemStack itemstack = this.inputSlots.getItem(0); this.cost.set(1); int i = 0; byte b0 = 0; byte b1 = 0; if (itemstack.isEmpty()) { org.bukkit.craftbukkit.event.CraftEventFactory.callPrepareAnvilEvent(getBukkitView(), ItemStack.EMPTY); // CraftBukkit this.cost.set(0); } else { ItemStack itemstack1 = itemstack.copy(); ItemStack itemstack2 = this.inputSlots.getItem(1); Map<Enchantment, Integer> map = EnchantmentManager.getEnchantments(itemstack1); int j = b0 + itemstack.getBaseRepairCost() + (itemstack2.isEmpty() ? 0 : itemstack2.getBaseRepairCost()); this.repairItemCountCost = 0; if (!itemstack2.isEmpty()) { boolean flag = itemstack2.is(Items.ENCHANTED_BOOK) && !ItemEnchantedBook.getEnchantments(itemstack2).isEmpty(); int k; int l; int i1; if (itemstack1.isDamageableItem() && itemstack1.getItem().isValidRepairItem(itemstack, itemstack2)) { k = Math.min(itemstack1.getDamageValue(), itemstack1.getMaxDamage() / 4); if (k <= 0) { org.bukkit.craftbukkit.event.CraftEventFactory.callPrepareAnvilEvent(getBukkitView(), ItemStack.EMPTY); // CraftBukkit this.cost.set(0); return; } for (i1 = 0; k > 0 && i1 < itemstack2.getCount(); ++i1) { l = itemstack1.getDamageValue() - k; itemstack1.setDamageValue(l); ++i; k = Math.min(itemstack1.getDamageValue(), itemstack1.getMaxDamage() / 4); } this.repairItemCountCost = i1; } else { if (!flag && (!itemstack1.is(itemstack2.getItem()) || !itemstack1.isDamageableItem())) { org.bukkit.craftbukkit.event.CraftEventFactory.callPrepareAnvilEvent(getBukkitView(), ItemStack.EMPTY); // CraftBukkit this.cost.set(0); return; } if (itemstack1.isDamageableItem() && !flag) { k = itemstack.getMaxDamage() - itemstack.getDamageValue(); i1 = itemstack2.getMaxDamage() - itemstack2.getDamageValue(); l = i1 + itemstack1.getMaxDamage() * 12 / 100; int j1 = k + l; int k1 = itemstack1.getMaxDamage() - j1; if (k1 < 0) { k1 = 0; } if (k1 < itemstack1.getDamageValue()) { itemstack1.setDamageValue(k1); i += 2; } } Map<Enchantment, Integer> map1 = EnchantmentManager.getEnchantments(itemstack2); boolean flag1 = false; boolean flag2 = false; Iterator iterator = map1.keySet().iterator(); while (iterator.hasNext()) { Enchantment enchantment = (Enchantment) iterator.next(); if (enchantment != null) { int l1 = (Integer) map.getOrDefault(enchantment, 0); int i2 = (Integer) map1.get(enchantment); i2 = l1 == i2 ? i2 + 1 : Math.max(i2, l1); boolean flag3 = enchantment.canEnchant(itemstack); if (this.player.getAbilities().instabuild || itemstack.is(Items.ENCHANTED_BOOK)) { flag3 = true; } Iterator iterator1 = map.keySet().iterator(); while (iterator1.hasNext()) { Enchantment enchantment1 = (Enchantment) iterator1.next(); if (enchantment1 != enchantment && !enchantment.isCompatibleWith(enchantment1)) { flag3 = false; ++i; } } if (!flag3) { flag2 = true; } else { flag1 = true; if (i2 > enchantment.getMaxLevel()) { i2 = enchantment.getMaxLevel(); } map.put(enchantment, i2); int j2 = 0; switch (enchantment.getRarity()) { case COMMON: j2 = 1; break; case UNCOMMON: j2 = 2; break; case RARE: j2 = 4; break; case VERY_RARE: j2 = 8; } if (flag) { j2 = Math.max(1, j2 / 2); } i += j2 * i2; if (itemstack.getCount() > 1) { i = 40; } } } } if (flag2 && !flag1) { org.bukkit.craftbukkit.event.CraftEventFactory.callPrepareAnvilEvent(getBukkitView(), ItemStack.EMPTY); // CraftBukkit this.cost.set(0); return; } } } if (StringUtils.isBlank(this.itemName)) { if (itemstack.hasCustomHoverName()) { b1 = 1; i += b1; itemstack1.resetHoverName(); } } else if (!this.itemName.equals(itemstack.getHoverName().getString())) { b1 = 1; i += b1; itemstack1.setHoverName(new ChatComponentText(this.itemName)); } this.cost.set(j + i); if (i <= 0) { itemstack1 = ItemStack.EMPTY; } if (b1 == i && b1 > 0 && this.cost.get() >= maximumRepairCost) { // CraftBukkit this.cost.set(maximumRepairCost - 1); // CraftBukkit } if (this.cost.get() >= maximumRepairCost && !this.player.getAbilities().instabuild) { // CraftBukkit itemstack1 = ItemStack.EMPTY; } if (!itemstack1.isEmpty()) { int k2 = itemstack1.getBaseRepairCost(); if (!itemstack2.isEmpty() && k2 < itemstack2.getBaseRepairCost()) { k2 = itemstack2.getBaseRepairCost(); } if (b1 != i || b1 == 0) { k2 = calculateIncreasedRepairCost(k2); } itemstack1.setRepairCost(k2); EnchantmentManager.setEnchantments(map, itemstack1); } org.bukkit.craftbukkit.event.CraftEventFactory.callPrepareAnvilEvent(getBukkitView(), itemstack1); // CraftBukkit sendAllDataToRemote(); // CraftBukkit - SPIGOT-6686: Always send completed inventory to stay in sync with client this.broadcastChanges(); } } public static int calculateIncreasedRepairCost(int i) { return i * 2 + 1; } public void setItemName(String s) { this.itemName = s; if (this.getSlot(2).hasItem()) { ItemStack itemstack = this.getSlot(2).getItem(); if (StringUtils.isBlank(s)) { itemstack.resetHoverName(); } else { itemstack.setHoverName(new ChatComponentText(this.itemName)); } } this.createResult(); } public int getCost() { return this.cost.get(); } // CraftBukkit start @Override public CraftInventoryView getBukkitView() { if (bukkitEntity != null) { return bukkitEntity; } org.bukkit.craftbukkit.inventory.CraftInventory inventory = new org.bukkit.craftbukkit.inventory.CraftInventoryAnvil( access.getLocation(), this.inputSlots, this.resultSlots, this); bukkitEntity = new CraftInventoryView(this.player.getBukkitEntity(), inventory, this); return bukkitEntity; } // CraftBukkit end }
39.981763
144
0.515965
05aa9ec7a12f407cbc12565085afe14d64305c86
830
package com.iwaodev.application.mapper; import com.iwaodev.application.dto.review.ProductDTO; import com.iwaodev.application.dto.review.ReviewDTO; import com.iwaodev.application.dto.review.UserDTO; import com.iwaodev.infrastructure.model.Product; import com.iwaodev.infrastructure.model.Review; import com.iwaodev.infrastructure.model.User; import com.iwaodev.ui.criteria.review.ReviewCriteria; import org.mapstruct.Mapper; import org.mapstruct.factory.Mappers; @Mapper public interface ReviewMapper { ReviewMapper INSTANCE = Mappers.getMapper( ReviewMapper.class ); ReviewDTO toReviewDTO(Review review); Review toReviewEntityFromReviewCriteria(ReviewCriteria review); // for sub entity esp for /users/{userId}/review to find a review. UserDTO toUserDTO(User user); ProductDTO toProductDTO(Product product); }
29.642857
68
0.814458
56bb7649ed81411db8a174d9684145d708a37eb4
260
package pl.dahdev.managementapp.exception; public class ActivationException extends Exception { public static final String ACTIVATION_NOT_FOUND = "Activation not found!"; public ActivationException(String message) { super(message); } }
21.666667
78
0.746154
846a82f652e6443b161b90a9aa546b2c8c74a9f2
2,581
package shadows.apotheosis.ench.objects; import java.util.List; import java.util.Map; import java.util.Random; import com.google.common.collect.Lists; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.enchantment.Enchantment; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.item.BookItem; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.Items; import net.minecraft.item.Rarity; import net.minecraft.util.math.MathHelper; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TranslationTextComponent; import net.minecraft.world.World; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.event.AnvilUpdateEvent; import shadows.apotheosis.Apotheosis; public class ScrappingTomeItem extends BookItem { static Random rand = new Random(); public ScrappingTomeItem() { super(new Item.Properties().group(Apotheosis.APOTH_GROUP)); this.setRegistryName(Apotheosis.MODID, "scrap_tome"); } @Override public boolean isEnchantable(ItemStack stack) { return false; } @Override @OnlyIn(Dist.CLIENT) public void addInformation(ItemStack stack, World world, List<ITextComponent> tooltip, ITooltipFlag flagIn) { if (stack.isEnchanted()) return; tooltip.add(new TranslationTextComponent("info.apotheosis.scrap_tome")); tooltip.add(new TranslationTextComponent("info.apotheosis.scrap_tome2")); } @Override public Rarity getRarity(ItemStack stack) { return !stack.isEnchanted() ? super.getRarity(stack) : Rarity.UNCOMMON; } public static boolean updateAnvil(AnvilUpdateEvent ev) { ItemStack weapon = ev.getLeft(); ItemStack book = ev.getRight(); if (!(book.getItem() instanceof ScrappingTomeItem) || book.isEnchanted() || !weapon.isEnchanted()) return false; Map<Enchantment, Integer> wepEnch = EnchantmentHelper.getEnchantments(weapon); int size = MathHelper.ceil(wepEnch.size() / 2D); List<Enchantment> keys = Lists.newArrayList(wepEnch.keySet()); long seed = 1831; for (Enchantment e : keys) { seed ^= e.getRegistryName().hashCode(); } seed ^= ev.getPlayer().getXPSeed(); rand.setSeed(seed); while (wepEnch.keySet().size() > size) { Enchantment lost = keys.get(rand.nextInt(keys.size())); wepEnch.remove(lost); keys.remove(lost); } ItemStack out = new ItemStack(Items.ENCHANTED_BOOK); EnchantmentHelper.setEnchantments(wepEnch, out); ev.setMaterialCost(1); ev.setCost(wepEnch.size() * 10); ev.setOutput(out); return true; } }
32.670886
114
0.76637
be8b44309e91c1bdd3b9a48c2237792950c0d541
151
package com.github.monsterhxw.chapter02.section04; /** * @author XueweiHuang * @created 2022-03-28 */ public class HashSetAndTreeSetComparison { }
16.777778
50
0.754967
8213598fd160f229431aa4708a95f27650fdebdf
2,004
package javacard.security; /** * The <code>Key</code> interface is the base interface for all keys. * <p> * <p> * A <code>Key</code> object sets its initialized state to true only when all * the associated <code>Key</code> object parameters have been set at least * once since the time the initialized state was set to false. * <p> * A newly created <code>Key</code> object sets its initialized state to * false. Invocation of the <code>clearKey()</code> method sets the * initialized state to false. A key with transient key data sets its * initialized state to false on the associated clear events. * * @see KeyBuilder KeyBuilder */ public interface Key { /** * Reports the initialized state of the key. Keys must be initialized before * being used. * <p> * A <code>Key</code> object sets its initialized state to true only when * all the associated <code>Key</code> object parameters have been set at * least once since the time the initialized state was set to false. * <p> * A newly created <code>Key</code> object sets its initialized state to * false. Invocation of the <code>clearKey()</code> method sets the * initialized state to false. A key with transient key data sets its * initialized state to false on the associated clear events. * * @return <code>true</code> if the key has been initialized */ boolean isInitialized(); /** * Clears the key and sets its initialized state to false. */ void clearKey(); /** * Returns the key interface type. * * @return the key interface type. Valid codes listed in <code>TYPE_*</code> * constants See * {@link KeyBuilder#TYPE_DES_TRANSIENT_RESET TYPE_DES_TRANSIENT_RESET}. * <p> * @see KeyBuilder KeyBuilder */ byte getType(); /** * Returns the key size in number of bits. * * @return the key size in number of bits */ short getSize(); }
32.322581
84
0.657186
a27427e24a2a7e05af4ab246bdc521acfaaeafd6
4,066
/* * Copyright (c) 2020 Rin (https://www.levelrin.com) * * This file has been created under the terms of the MIT License. * See the details at https://github.com/levelrin/jws-server/blob/main/LICENSE */ package com.levelrin.jwsserver; import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; /** * Tests. */ @SuppressWarnings("PMD.CloseResource") final class OnRequestLinesTest { @Test @SuppressWarnings("RegexpSingleline") public void shouldReadRequestLines() throws IOException { final Socket socket = Mockito.mock(Socket.class); final InputStream inputStream = new FakeInputStream( """ GET /path/to/websocket/endpoint HTTP/1.1 Host: localhost Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: xqBt3ImNzJbYqRINxEFlkg== Origin: http://localhost Sec-WebSocket-Version: 13 """ ); Mockito.when(socket.getInputStream()).thenReturn(inputStream); Mockito.when(socket.getOutputStream()).thenReturn(Mockito.mock(OutputStream.class)); final List<String> actual = new ArrayList<>(); new OnRequestLines( socket, ioException -> { throw new IllegalStateException( "Exception should not occur in this test.", ioException ); }, lines -> { actual.addAll(lines); return Mockito.mock(WsServer.class); } ).start(); MatcherAssert.assertThat( actual, Matchers.containsInRelativeOrder( "GET /path/to/websocket/endpoint HTTP/1.1", "Host: localhost", "Upgrade: websocket", "Connection: Upgrade", "Sec-WebSocket-Key: xqBt3ImNzJbYqRINxEFlkg==", "Origin: http://localhost", "Sec-WebSocket-Version: 13" ) ); } @Test public void shouldCatchIoException() throws IOException { final Socket socket = Mockito.mock(Socket.class); Mockito.when(socket.getInputStream()).thenThrow(IOException.class); final AtomicBoolean caught = new AtomicBoolean(false); new OnRequestLines( socket, ioException -> caught.set(true), lines -> { throw new IllegalStateException( "IOException should've occurred before reaching here." ); } ).start(); MatcherAssert.assertThat( caught.get(), CoreMatchers.equalTo(true) ); } /** * We can inject a fake message for testing. */ private static final class FakeInputStream extends InputStream { /** * The fake message that we are going to use. */ private final String message; /** * It is used to return the correct byte of the fake message. */ private int index; /** * Constructor. * @param message See {@link FakeInputStream#message}. */ FakeInputStream(final String message) { super(); this.message = message; } @Override public int read() { final byte[] bytes = this.message.getBytes(StandardCharsets.UTF_8); final byte value; if (this.index < bytes.length) { value = bytes[this.index]; this.index = this.index + 1; } else { value = -1; } return value; } } }
29.897059
92
0.567142
4c8825a5907a2bfb29f9f74655e58c4d187460e5
140
package procul.studios.delta; public class BuildManifest { public Integer[] version; public boolean dev; public String exec; }
17.5
29
0.721429
ccfd78ba83b8f29d7e238bc561dd9bae120895fe
1,355
package de.vorb.sokrates.generator; import org.springframework.stereotype.Component; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import static java.nio.file.Files.newByteChannel; @Component public class Sha1ChecksumCalculator { public byte[] calculateChecksum(Path file) { final MessageDigest sha1Hash = createSha1Hash(); final ByteBuffer buffer = ByteBuffer.allocateDirect(8 * 1024); try (final ReadableByteChannel byteChannel = newByteChannel(file, StandardOpenOption.READ)) { int bytesRead = 0; while (bytesRead != -1) { bytesRead = byteChannel.read(buffer); if (bytesRead > 0) { sha1Hash.update(buffer); buffer.clear(); } } return sha1Hash.digest(); } catch (IOException e) { return null; } } private MessageDigest createSha1Hash() { try { return MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new AssertionError("JVM does not support SHA-1"); } } }
30.795455
101
0.639852
d44015c1310965aacf30680788e255f4e1b26ddc
3,571
/* * The MIT License (MIT) * * Copyright (c) 2013 Milad Naseri. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.mmnaseri.dragonfly.sample; import com.mmnaseri.dragonfly.dialect.DatabaseDialect; import com.mmnaseri.dragonfly.dialect.impl.Mysql5Dialect; import com.mmnaseri.dragonfly.runtime.analysis.JpaApplicationDesignAdvisor; import com.mmnaseri.dragonfly.runtime.config.JpaDataConfiguration; import com.mmnaseri.dragonfly.runtime.ext.audit.api.UserContext; import com.mmnaseri.dragonfly.runtime.ext.audit.impl.AuditInterceptor; import org.apache.commons.dbcp.BasicDataSource; import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.core.io.ClassPathResource; import javax.sql.DataSource; /** * @author Milad Naseri ([email protected]) * @since 1.0 (14/8/13 AD, 16:39) */ @Configuration @Import(JpaDataConfiguration.class) @ComponentScan("com.mmnaseri.dragonfly.sample") public class Config { @Bean public DatabaseDialect databaseDialect() { return new Mysql5Dialect(); } @Bean public DataSource dataSource(DatabaseDialect dialect, @Value("${db.username}") String username, @Value("${db.password}") String password, @Value("${db.database}") String database) { final BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(dialect.getDriverClassName()); dataSource.setUrl("jdbc:mysql://localhost/" + database); dataSource.setUsername(username); dataSource.setPassword(password); dataSource.setMaxActive(200); dataSource.setMaxIdle(100); dataSource.setMaxWait(1500); return dataSource; } @Bean public JpaApplicationDesignAdvisor designAdvisor() { return new JpaApplicationDesignAdvisor(); } @Bean public PropertyPlaceholderConfigurer placeholderConfigurer() { final PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer(); configurer.setLocation(new ClassPathResource("db.properties")); return configurer; } @Bean public AuditInterceptor defaultAuditInterceptor(UserContext userContext) { return new AuditInterceptor(userContext); } }
40.579545
185
0.761411
0e625686a518d84ed9dad00365373b9163debc28
933
package com.qouteall.immersive_portals.mixin_client.sync; import com.qouteall.immersive_portals.ducks.IEPlayerMoveC2SPacket; import net.minecraft.client.Minecraft; import net.minecraft.network.play.client.CPlayerPacket; import net.minecraft.world.dimension.DimensionType; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; @Mixin(CPlayerPacket.class) public class MixinPlayerMoveC2SPacket_C { @Inject( method = "<init>(Z)V", at = @At("RETURN") ) private void onConstruct(boolean boolean_1, CallbackInfo ci) { DimensionType dimension = Minecraft.getInstance().player.dimension; ((IEPlayerMoveC2SPacket) this).setPlayerDimension(dimension); assert dimension == Minecraft.getInstance().world.dimension.getType(); } }
38.875
78
0.773848
b4d2ece9bc684547a523580fd75ec3a96ca917b9
4,432
/****************************************************************************** * Copyright (c) 2014, AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************************/ package org.alljoyn.ns.transport.producer; import org.alljoyn.about.AboutServiceImpl; import org.alljoyn.bus.BusException; import org.alljoyn.bus.BusObject; import org.alljoyn.bus.Status; import org.alljoyn.ns.NotificationServiceException; import org.alljoyn.ns.commons.GenericLogger; import org.alljoyn.ns.commons.NativePlatform; import org.alljoyn.ns.transport.TaskManager; import org.alljoyn.ns.transport.Transport; import org.alljoyn.ns.transport.interfaces.NotificationProducer; /** * The class implements the {@link NotificationProducer} interface and by this realizes the Notification producer * proprietary logic */ class NotificationProducerImpl implements NotificationProducer { private static final String TAG = "ioe" + NotificationProducerImpl.class.getSimpleName(); /** * The Sender transport */ private SenderTransport senderTransport; /** * The reference to the platform dependent object */ private NativePlatform nativePlatform; /** * Constructor * @param senderTransport The Sender transport * @param nativePlatform The reference to the platform dependent object */ public NotificationProducerImpl(SenderTransport senderTransport, NativePlatform nativePlatform) { this.senderTransport = senderTransport; this.nativePlatform = nativePlatform; } /** * Initializes the object <br> * Register {@link BusObject}, if failed to register the {@link NotificationServiceException} is thrown * @throws NotificationServiceException */ public void init() throws NotificationServiceException { Status status = Transport.getInstance().getBusAttachment().registerBusObject(this, OBJ_PATH); nativePlatform.getNativeLogger().debug(TAG, "NotificationProducer BusObject: '" + OBJ_PATH + "' was registered on the bus, Status: '" + status + "'"); if ( status != Status.OK ) { throw new NotificationServiceException("Failed to register BusObject: '" + OBJ_PATH + "', Error: '" + status + "'"); } //Add the object description to be sent in the Announce signal AboutServiceImpl.getInstance().addObjectDescription(OBJ_PATH, new String[] {IFNAME}); }//init /** * @see org.alljoyn.ns.transport.interfaces.NotificationProducer#dismiss(int) */ @Override public void dismiss(final int msgId) throws BusException { GenericLogger logger = nativePlatform.getNativeLogger(); logger.debug(TAG, "Received Dismiss for notifId: '" + msgId + "', delegating to be executed"); Transport.getInstance().getBusAttachment().enableConcurrentCallbacks(); TaskManager.getInstance().enqueue(new Runnable() { @Override public void run() { senderTransport.dismiss(msgId); } }); }//dismiss /** * @see org.alljoyn.ns.transport.interfaces.NotificationProducer#getVersion() */ @Override public short getVersion() throws BusException { return VERSION; }//getVersion /** * Cleans the object resources */ public void clean() { nativePlatform.getNativeLogger().debug(TAG, "Cleaning the NotificationProducerImpl"); Transport.getInstance().getBusAttachment().unregisterBusObject(this); //Remove the object description from being sent in the Announce signal AboutServiceImpl.getInstance().removeObjectDescription(OBJ_PATH, new String[] {IFNAME}); senderTransport = null; nativePlatform = null; }//clean }
36.933333
153
0.702843
e38ffa3aeada96b503bc063131dc0a824763cde2
410
package com.smcb.simulatedstock.page; import com.smcb.simulatedstock.base.BaseFragment; /** * Created by Administrator on 2017/3/10. */ public class SellStockFragment extends BaseFragment { public static BaseFragment getInstance() { BuyStockFragment fragment = new BuyStockFragment(); fragment.INDEX = 2; fragment.type = BuyStockFragment.SELL; return fragment; } }
24.117647
59
0.709756
c7f8cb65405bfb60febc17a6a933b0cd29c7079b
13,799
package se.kth.castor.pankti.extract.processors; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import se.kth.castor.pankti.extract.launchers.PanktiLauncher; import se.kth.castor.pankti.extract.runners.PanktiMain; import spoon.MavenLauncher; import spoon.reflect.CtModel; import spoon.reflect.code.*; import spoon.reflect.declaration.CtMethod; import spoon.reflect.visitor.filter.TypeFilter; import java.net.URISyntaxException; import java.nio.file.Path; import static org.junit.jupiter.api.Assertions.*; public class CandidateTaggerTest { static PanktiMain panktiMain; static PanktiLauncher panktiLauncher; static MavenLauncher mavenLauncher; static CtModel testModel; static MethodProcessor methodProcessor; static CandidateTagger candidateTagger; @BeforeAll public static void setUpLauncherAndModel() throws URISyntaxException { methodProcessor = new MethodProcessor(true); panktiMain = new PanktiMain(Path.of("src/test/resources/jitsi-videobridge"), false); panktiLauncher = new PanktiLauncher(); mavenLauncher = panktiLauncher.getMavenLauncher(panktiMain.getProjectPath().toString(), panktiMain.getProjectPath().getFileName().toString()); testModel = panktiLauncher.buildSpoonModel(mavenLauncher); testModel.processWith(methodProcessor); panktiLauncher.addMetaDataToCandidateMethods(methodProcessor.getCandidateMethods()); candidateTagger = new CandidateTagger(); testModel.processWith(candidateTagger); } // Test the number of extracted methods that return a value @Test public void testNumberOfMethodsRetuningAValue() { assertEquals(214, candidateTagger.methodsReturningAValue.size(), "214 extracted methods in test resource should return a value"); } // Test that some extracted methods are void @Test public void testSomeExtractedMethodsDoNotReturnAValue() { assertEquals(methodProcessor.candidateMethods.size() - candidateTagger.methodsReturningAValue.size(), candidateTagger.methodsNotReturningAValue.size(), "Some extracted methods in test resource are void"); } // Test that an extracted method found to return a value actually does so @Test public void testMethodRetuningAValue() { CtMethod<?> methodReturningAValue = candidateTagger.methodsReturningAValue.get(0); assertTrue((methodReturningAValue.getElements(new TypeFilter<>(CtReturn.class)).size() > 0 && !methodReturningAValue.getType().getSimpleName().equals("void") && (methodReturningAValue.getType().isPrimitive() || !methodReturningAValue.getType().isPrimitive())), "Method should have a return statement, and return a primitive or an object, " + "and its return type cannot be void"); } // Test that an extracted method returning a value is tagged as such @Test public void testTagOfMethodRetuningAValue() { CtMethod<?> methodReturningAValue = candidateTagger.methodsReturningAValue.get(0); assertTrue((candidateTagger.allMethodTags.get(methodReturningAValue).get("returns")), "returns tag should be true for method"); } // Test that some extracted methods are void @Test public void testNumberOfMethodsNotReturningAValue() { assertFalse(candidateTagger.methodsNotReturningAValue.isEmpty(), "some extracted methods in test resource are void"); } // Test the number of extracted methods returning a primitive @Test public void testNumberOfMethodsReturningPrimitives() { assertEquals(65, candidateTagger.methodsReturningAPrimitive.size(), "65 extracted methods in test resource return a primitive value"); } // Test that an extracted method found to return a primitive actually does so @Test public void testMethodRetuningAPrimitive() { CtMethod<?> methodReturningAPrimitive = candidateTagger.methodsReturningAPrimitive.get(0); assertTrue((methodReturningAPrimitive.getElements(new TypeFilter<>(CtReturn.class)).size() > 0 && !methodReturningAPrimitive.getType().getSimpleName().equals("void") && methodReturningAPrimitive.getType().isPrimitive()), "Method should have a return statement, and return a primitive, " + "and its return type cannot be void"); } // Test that an extracted method returning a primitive is tagged as such @Test public void testTagOfMethodRetuningAPrimitive() { CtMethod<?> methodReturningAPrimitive = candidateTagger.methodsReturningAPrimitive.get(0); assertTrue((candidateTagger.allMethodTags.get(methodReturningAPrimitive).get("returns_primitives")), "returns_primitives tag should be true for method"); } // Test the number of extracted methods not returning a primitive @Test public void testNumberOfMethodsNotReturningPrimitives() { assertEquals(149, candidateTagger.methodsReturningAValue.size() - candidateTagger.methodsReturningAPrimitive.size(), "149 extracted methods in test resource return an object"); } // Test that an extracted method found to not return a primitive actually does not @Test public void testMethodRetuningNotAPrimitive() { for (CtMethod<?> methodReturningAValue : candidateTagger.methodsReturningAValue) { if (!candidateTagger.methodsReturningAPrimitive.contains(methodReturningAValue)) { assertTrue((methodReturningAValue.getElements(new TypeFilter<>(CtReturn.class)).size() > 0 && !methodReturningAValue.getType().getSimpleName().equals("void") && !methodReturningAValue.getType().isPrimitive()), "Method should have a return statement, and return an object, " + "and its return type cannot be void"); break; } } } // Test that an extracted method not returning a primitive is tagged as such @Test public void testTagOfMethodNotRetuningAPrimitive() { for (CtMethod<?> methodReturningAValue : candidateTagger.methodsReturningAValue) { if (!candidateTagger.methodsReturningAPrimitive.contains(methodReturningAValue)) { assertFalse(candidateTagger.allMethodTags.get(methodReturningAValue).get("returns_primitives"), "returns_primitives tag should be false for method"); break; } } } // Test the number of extracted methods with if conditions @Test public void testNumberOfMethodsWithIfConditions() { assertEquals(160, candidateTagger.methodsWithIfConditions.size(), "160 extracted methods in test resource have an if condition"); } // Test that an extracted method found to have if condition(s) actually does so @Test public void testMethodsWithIfCondition() { CtMethod<?> methodWithIfCondition = candidateTagger.methodsWithIfConditions.get(0); assertTrue(methodWithIfCondition.getElements(new TypeFilter<>(CtIf.class)).size() > 0, "Method should have an if condition"); } // Test that an extracted method having if condition(s) is tagged as such @Test public void testTagOfMethodWithIfCondition() { CtMethod<?> methodWithIfCondition = candidateTagger.methodsWithIfConditions.get(0); assertTrue(candidateTagger.allMethodTags.get(methodWithIfCondition).get("ifs"), "ifs tag should be true for method"); } // Test the number of extracted methods with conditional operators @Test public void testNumberOfMethodsWithConditionals() { assertEquals(10, candidateTagger.methodsWithConditionalOperators.size(), "10 extracted methods in test resource use a conditional operator"); } // Test that an extracted method found to have conditional operator(s) actually does so @Test public void testMethodWithConditionals() { CtMethod<?> methodWithIfCondition = candidateTagger.methodsWithConditionalOperators.get(0); assertTrue(methodWithIfCondition.getElements(new TypeFilter<>(CtConditional.class)).size() > 0, "Method should have a conditional operator"); } // Test that an extracted method with conditional operator(s) is tagged as such @Test public void testTagOfMethodWithConditionals() { CtMethod<?> methodWithConditional = candidateTagger.methodsWithConditionalOperators.get(0); assertTrue(candidateTagger.allMethodTags.get(methodWithConditional).get("conditionals"), "conditionals tag should be true for method"); } // Test the number of extracted methods with loops @Test public void testNumberOfMethodsWithLoops() { assertEquals(28, candidateTagger.methodsWithLoops.size(), "28 extracted method in test resource have a loop"); } // Test the number of extracted methods with switch statements @Test public void testNumberOfMethodsWithSwitchStatements() { assertEquals(5, candidateTagger.methodsWithSwitchStatements.size(), "5 extracted methods in test resource have switch statements"); } // Test that an extracted method found to have switch statement(s) actually does so @Test public void testMethodWithSwitchStatements() { CtMethod<?> methodWithSwitchStatements = candidateTagger.methodsWithSwitchStatements.get(0); assertTrue(methodWithSwitchStatements.getElements(new TypeFilter<>(CtSwitch.class)).size() > 0, "Method should have a conditional operator"); } // Test that an extracted method with switch statement(s) is tagged as such @Test public void testTagOfMethodWithSwitchStatements() { CtMethod<?> methodWithSwitchStatements = candidateTagger.methodsWithSwitchStatements.get(0); assertTrue(candidateTagger.allMethodTags.get(methodWithSwitchStatements).get("switches"), "switches tag should be true for method"); } // Test the number of extracted methods with parameters @Test public void testNumberOfMethodsWithParameters() { assertEquals(229, candidateTagger.methodsWithParameters.size(), "229 extracted methods in test resource have parameters"); } // Test that an extracted method found to have parameters actually does so @Test public void testMethodWithParameters() { CtMethod<?> methodWithParameters = candidateTagger.methodsWithParameters.get(0); assertTrue(methodWithParameters.getParameters().size() > 0, "Method should have a conditional operator"); } // Test that an extracted method with parameters is tagged as such @Test public void testTagOfMethodWithParameters() { CtMethod<?> methodWithParameters = candidateTagger.methodsWithParameters.get(0); assertTrue(candidateTagger.allMethodTags.get(methodWithParameters).get("parameters"), "parameters tag should be true for method"); } // Test the number of extracted methods with multiple statements @Test public void testNumberOfMethodsWithMultipleStatements() { assertEquals(191, candidateTagger.methodsWithMultipleStatements.size(), "191 extracted methods in test resource have multiple statements"); } // Test that an extracted method found to have multiple statements actually does so @Test public void testMethodWithMultipleStatements() { CtMethod<?> methodWithMultipleStatements = candidateTagger.methodsWithMultipleStatements.get(0); assertTrue(methodWithMultipleStatements.getBody().getStatements().size() > 0, "Method should have multiple statements"); } // Test that an extracted method with multiple statements is tagged as such @Test public void testTagOfMethodWithMultipleStatements() { CtMethod<?> methodWithMultipleStatements = candidateTagger.methodsWithMultipleStatements.get(0); assertTrue(candidateTagger.allMethodTags.get(methodWithMultipleStatements).get("multiple_statements"), "multiple_statements tag should be true for method"); } // Test the number of methods with local variables @Test public void testNumberOfMethodsWithLocalVariables() { assertEquals(161, candidateTagger.methodsWithLocalVariables.size(), "161 extracted methods in test resource define local variables"); } // Test that an extracted method found to have local variables actually does so @Test public void testMethodWithLocalVariables() { CtMethod<?> methodWithLocalVariables = candidateTagger.methodsWithLocalVariables.get(0); assertTrue(methodWithLocalVariables.getElements(new TypeFilter<>(CtLocalVariable.class)).size() > 0, "Method should have local variables"); } // Test that an extracted method defining local variables is tagged as such @Test public void testTagOfMethodWithLocalVariables() { CtMethod<?> methodWithLocalVariables = candidateTagger.methodsWithLocalVariables.get(0); assertTrue(candidateTagger.allMethodTags.get(methodWithLocalVariables).get("local_variables"), "local_variables tag should be true for method"); } }
46.618243
123
0.696572
f86c9486d336679d05ce9330546f18d0f3793f41
653
package com.appsmith.server.repositories; import com.appsmith.server.repositories.ce.CustomNewPageRepositoryCEImpl; import lombok.extern.slf4j.Slf4j; import org.springframework.data.mongodb.core.ReactiveMongoOperations; import org.springframework.data.mongodb.core.convert.MongoConverter; import org.springframework.stereotype.Component; @Component @Slf4j public class CustomNewPageRepositoryImpl extends CustomNewPageRepositoryCEImpl implements CustomNewPageRepository { public CustomNewPageRepositoryImpl(ReactiveMongoOperations mongoOperations, MongoConverter mongoConverter) { super(mongoOperations, mongoConverter); } }
34.368421
112
0.840735
16bc85a28135ab79257529bf529e8799e450f477
803
package seedu.addressbook.commands; import seedu.addressbook.data.exception.IllegalValueException; import seedu.addressbook.data.person.*; import seedu.addressbook.data.tag.Tag; import java.util.HashSet; import java.util.Set; public class SortCommand extends Command { public static final String COMMAND_WORD = "sort"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Sorts the address book based on names (first priority)." + "If users have the same name, sorting will be based on the contact numbers." + "Example: " + COMMAND_WORD; public static final String MESSAGE_SUCCESS = "AddressBook Sorted!"; @Override public CommandResult execute() { addressBook.sortAddressBook(); return new CommandResult(MESSAGE_SUCCESS); } }
34.913043
123
0.729763
fdc341a6071ff0772460087aadfddc6edd8e5475
704
package com.github.shaigem.linkgem.fx.popup.quickinfo; import javafx.scene.Cursor; import javafx.scene.text.Text; /** * Helper class for creating nodes with a quick information popup. * * @author Ronnie Tran */ public final class QuickInfoIcon { /** * Create a icon node that will display a quick info popup when hovered over. * * @param infoText the text that the popup will show * @param icon the icon which will be displayed * @return the icon */ public static Text create(final String infoText, final Text icon) { icon.setCursor(Cursor.DEFAULT); QuickInfoPopup.install(icon, new QuickInfoPopup(infoText)); return icon; } }
27.076923
81
0.683239
f548d047c639f56bc19b667829fa4026fd0f8865
3,002
/* Copyright (c) 2001-2009, The HSQL Development Group * 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. * * Neither the name of the HSQL Development Group nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * 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 HSQL DEVELOPMENT GROUP, HSQLDB.ORG, * 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.hsqldb_voltpatches.util; /** * ConnectionSetting represents the various parameters of a data source * connection. * * @author lonbinder@users */ public class ConnectionSetting implements java.io.Serializable { private String name, driver, url, user, pw; String getName() { return name; } String getDriver() { return driver; } String getUrl() { return url; } String getUser() { return user; } String getPassword() { return pw; } // Constructors private ConnectionSetting() {} ; ConnectionSetting(String name, String driver, String url, String user, String pw) { this.name = name; this.driver = driver; this.url = url; this.user = user; this.pw = pw; } public boolean equals(Object obj) { if (!(obj instanceof ConnectionSetting)) { return false; } ConnectionSetting other = (ConnectionSetting) obj; if (getName() == other.getName()) { return true; } if (getName() == null) { return false; } return getName().trim().equals(other.getName().trim()); } public int hashCode() { return getName() == null ? 0 : getName().trim().hashCode(); } }
29.431373
80
0.663225
38a562ab045ee466f46f5956c4857242174e1dd0
810
package com.coder.lock; class Consumer { private Depot depot; public Consumer(Depot depot) { this.depot = depot; } public void consume(int no) { new Thread(() -> depot.consume(no), no + " consume thread").start(); } } class Producer { private Depot depot; public Producer(Depot depot) { this.depot = depot; } public void produce(int no) { new Thread(() -> depot.produce(no), no + " produce thread").start(); } } public class ReentrantLockDemo { public static void main(String[] args) throws InterruptedException { Depot depot = new Depot(500); new Producer(depot).produce(500); new Producer(depot).produce(200); new Consumer(depot).consume(500); new Consumer(depot).consume(200); } }
23.142857
76
0.609877
44aaf9a9baa36ec5a8e0a177cb2c81855d467052
11,983
package org.eft.evol.model; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; import org.eft.evol.stats.UnitAction; import org.eft.evol.stats.UnitState; import org.etf.provider.ConfigProvider; import cern.jet.random.Uniform; public abstract class AbstractUnit implements Unit { protected static final float TRANSACTION_COST = 4.0f; protected static final byte MODIFIER = 1; byte[] character; byte[] preference; int ID = 0; float cash = BASE_CASH; float investment = cash; // protected float sumGradient = 0.0f; int[] etfs; Map<Integer,Byte> cache = new HashMap<>(10); List<UnitAction> actions = new LinkedList<>(); // List<UnitState> stateList = new ArrayList<>(); UnitState currentState; public AbstractUnit(int ETF_SIZE, int index) { this.character = new byte[3]; this.preference = new byte[ETF_SIZE]; this.etfs = new int[ETF_SIZE]; this.ID = index; init(); initState(); } public int[] getEtfs() { return etfs; } public AbstractUnit(int index, byte[] character, byte[] buyPreference) { this.character = Arrays.copyOf(character, character.length); this.preference = Arrays.copyOf(buyPreference, buyPreference.length); Map<Byte, List<Integer>> prefMap = new HashMap<>(buyPreference.length); for(int i = 0;i < this.preference.length;i++){ if(!prefMap.containsKey(this.preference[i])){ prefMap.put(this.preference[i], new ArrayList<Integer>()); } prefMap.get(preference[i]).add(i); } List<Byte> keys = new ArrayList<Byte>(prefMap.keySet()); Collections.sort(keys, Collections.reverseOrder()); for(Byte key : keys){ List<Integer> etfIndexes = prefMap.get(key); for(Integer etfIndex : etfIndexes){ if(cache.size() <= 10){ cache.put(etfIndex, key); } } } this.ID = index; this.etfs = new int[buyPreference.length]; Arrays.fill(etfs, 0); initState(); } private void init() { for (int i = 0; i < 3; i++) { character[i] = (byte) Uniform.staticNextIntFromTo(0, 100); } for (int i = 0; i < preference.length; i++) { preference[i] = (byte) Uniform.staticNextIntFromTo(0, 99); } Map<Byte, List<Integer>> prefMap = new HashMap<>(preference.length); for(int i = 0;i < this.preference.length;i++){ if(!prefMap.containsKey(this.preference[i])){ prefMap.put(this.preference[i], new ArrayList<Integer>()); } prefMap.get(preference[i]).add(i); } List<Byte> keys = new ArrayList<Byte>(prefMap.keySet()); Collections.sort(keys, Collections.reverseOrder()); for(Byte key : keys){ List<Integer> etfIndexes = prefMap.get(key); for(Integer etfIndex : etfIndexes){ if(cache.size() <= 10){ cache.put(etfIndex, key); } } } Arrays.fill(etfs, 0); } private void initState() { this.currentState = new UnitState(); currentState.nav = this.cash; currentState.iteration = 0; currentState.cycle = 0; setStateFromArrays(); } public void appendHistory(int it, int cycle, float[][] etfValueMap) { if (this.currentState == null) { this.currentState = new UnitState(); } currentState.nav = this.netAssetValue(cycle, etfValueMap); currentState.iteration = it; currentState.cycle = cycle; setStateFromArrays(); // this.stateList.add(currentState); } private void setStateFromArrays() { currentState.character = Arrays.copyOf(character, character.length); currentState.buyPreference = Arrays.copyOf(preference, preference.length); if (etfs != null) { currentState.etfs = Arrays.copyOf(this.etfs, this.etfs.length); } } protected void addGradientToAction(int cycle, float[][] etfValueMap, UnitAction sellAction) { if (this.currentState == null) { sellAction.gradient = 0.0f; } else { sellAction.gradient = netAssetValue(cycle, etfValueMap) - this.currentState.nav; } } @Override public void hold(int iteration, int cycle, float[][] etfValueMap) { UnitAction holdAction = new UnitAction(); holdAction.actionType = ActionType.HOLD; holdAction.cycle = cycle; holdAction.iteration = iteration; addGradientToAction(cycle, etfValueMap, holdAction); actions.add(holdAction); } @Override public byte buyProb() { return character[INDEX_BUY]; } @Override public byte sellProb() { return character[INDEX_SELL]; } @Override public byte holdProb() { return character[INDEX_HOLD]; } @Override public float netAssetValue(int day, float[][] etfValueMap) { float sum = cash; if (this.etfs != null) { for (int etf_index = 0; etf_index < etfs.length; etf_index++) { if (etfs[etf_index] == 0) { continue; } float nav = getNavValueByIndex(day, etfValueMap, etf_index); if (nav == 0.0f) { continue; } sum += ((float) etfs[etf_index]) * nav; } } return sum; } private Float getNavValueByIndex(int day, float[][] etf_values, int etf_index) { if (etf_values[day][etf_index] > 0.0f) { return etf_values[day][etf_index]; } while (day > 0) { if (etf_values[day][etf_index] > 0.0f) { return etf_values[day][etf_index]; } day--; } return 0.0f; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("[["); builder.append(ID); builder.append("],"); builder.append(Arrays.toString(character)); builder.append(','); for (int etf_index = 0; etf_index < preference.length; etf_index++) { builder.append(ETFMap.getInstance(preference.length).getEtfName(etf_index)); builder.append('='); builder.append(preference[etf_index]); builder.append(','); } builder.append(",["); builder.append(cash); builder.append("],["); for (int etf_index = 0; etf_index < preference.length; etf_index++) { if (etfs[etf_index] == 0) { continue; } builder.append(ETFMap.getInstance().getEtfName(etf_index)); builder.append('='); builder.append(etfs[etf_index]); builder.append(','); } builder.append(']'); return builder.toString(); } @Override public void resetAssets(int iteration) { this.cash = BASE_CASH; this.investment = this.cash; int size = this.etfs.length; this.etfs = new int[size]; Arrays.fill(etfs, 0); // this.sumGradient = 0.0f; initState(); } @Override public int getID() { return this.ID; } public abstract String getDir(int iteration); @Override public synchronized void logToFile(int iteration) { String directory = getDirectoryName(iteration); File dir = new File(directory); File actionLogFile = new File(getActionLogFileName(directory)); File historyLogFile = new File(getHistoryLogFileName(directory)); File gradientLogFile = new File(getGradientLogFIleName(directory)); if (actionLogFile.exists() || historyLogFile.exists() || gradientLogFile.exists()) { return; } if (!Files.exists(dir.toPath())) { try { Files.createDirectories(dir.toPath()); } catch (IOException e) { e.printStackTrace(); return; } } if (!Files.exists(actionLogFile.toPath())) { try { Files.createFile(actionLogFile.toPath()); } catch (IOException e) { e.printStackTrace(); return; } } if (!Files.exists(historyLogFile.toPath())) { try { Files.createFile(historyLogFile.toPath()); } catch (IOException e) { e.printStackTrace(); return; } } try { for (UnitAction action : actions) { Files.write(actionLogFile.toPath(), action.toString().getBytes(), StandardOpenOption.APPEND); } Files.write(historyLogFile.toPath(), currentStateString().getBytes(), StandardOpenOption.APPEND); StringBuilder builder = new StringBuilder(); builder.append("Total investment:"); builder.append(investment); builder.append('\n'); Files.write(historyLogFile.toPath(), builder.toString().getBytes(), StandardOpenOption.APPEND); // builder = new StringBuilder(); // builder.append("Total gradient:"); // builder.append(sumGradient); // builder.append('\n'); // Files.write(historyLogFile.toPath(), // builder.toString().getBytes(),StandardOpenOption.APPEND); } catch (IOException e) { e.printStackTrace(); } } private String getGradientLogFIleName(String directory) { StringBuilder builder = new StringBuilder(); builder.append(directory); builder.append('/'); builder.append(this.ID); builder.append("_gradient.log"); return builder.toString(); } private String getHistoryLogFileName(String directory) { StringBuilder builder = new StringBuilder(); builder.append(directory); builder.append('/'); builder.append(this.ID); builder.append("_history.log"); return builder.toString(); } private String getActionLogFileName(String directory) { StringBuilder builder = new StringBuilder(); builder.append(directory); builder.append('/'); builder.append(this.ID); builder.append("_action.log"); return builder.toString(); } private String getDirectoryName(int iteration) { StringBuilder builder = new StringBuilder(); builder.append(ConfigProvider.DIR); builder.append('/'); builder.append(getDir(iteration)); builder.append('/'); builder.append(this.currentState.nav); return builder.toString(); } protected String currentStateString() { return currentState.toString(); } @Override public void resetLogs() { // this.actions.clear(); } @Override public void addCash(float cash) { this.cash += cash; this.investment += cash; } @Override public byte[] getCharacter() { return this.character; } @Override public byte[] getBuyPreferenceMap() { return this.preference; } @Override public void mutate() { int mutateIndexCharacter = Uniform.staticNextIntFromTo(0, this.character.length - 1); int mutateIndexPreference = Uniform.staticNextIntFromTo(0, this.preference.length - 1); this.character[mutateIndexCharacter] = (byte) Uniform.staticNextIntFromTo(0, 99); this.preference[mutateIndexPreference] = (byte) Uniform.staticNextIntFromTo(0, 99); } @Override public float getInvesment() { return this.investment; } @Override public void performAction(float[][] navValues, int it, int cycle) { boolean actionPerformed = false; while (!actionPerformed) { if (holdProb() >= Uniform.staticNextIntFromTo(0, 100)) { hold(it, cycle, navValues); actionPerformed = true; continue; } // if (sellProb() >= Uniform.staticNextIntFromTo(0, 100)) { // actionPerformed = true; // sell(it, cycle, navValues); // } if (buyProb() >= Uniform.staticNextIntFromTo(0, 100)) { actionPerformed = true; buy(it, cycle, navValues); } } } protected byte[] crossOverCharacter(Unit other) { int crossIndexCharacter = Uniform.staticNextIntFromTo(0, this.character.length - 1); byte[] nCharacter = new byte[this.character.length]; byte[] otherCharacter = other.getCharacter(); for (int i = 0; i < this.character.length; i++) { if (i <= crossIndexCharacter) { nCharacter[i] = this.character[i]; } else { nCharacter[i] = otherCharacter[i]; } } return nCharacter; } protected byte[] crossoverPreference(Unit other, byte[] preferenceMap, int actionType) { int crossIndex = Uniform.staticNextIntFromTo(0, preferenceMap.length - 1); byte[] nPreference = Arrays.copyOf(preferenceMap, preferenceMap.length); byte[] otherMap = other.getBuyPreferenceMap(); for (int etf_index = crossIndex; etf_index < otherMap.length; etf_index++) { nPreference[etf_index] = otherMap[etf_index]; } return nPreference; } protected void incrementPreference(int index, byte[] preference2) { // if (preference2[index] + MODIFIER < 100) { // preference2[index] += MODIFIER; // cache.put(index, preference2[index]); // } cache.put(index, preference2[index]); } }
24.912682
100
0.688475
52c22eff05974f9101f67d23edd282ed47f3662d
2,020
package fr.tduf.libunlimited.low.files.banks.mapping.rw; import com.esotericsoftware.minlog.Log; import fr.tduf.libunlimited.common.helper.FilesHelper; import fr.tduf.libunlimited.low.files.banks.mapping.domain.BankMap; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.io.IOException; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; class MapParserTest { private static final Class<MapParserTest> thisClass = MapParserTest.class; @BeforeEach void setUp() { Log.set(Log.LEVEL_INFO); } @Test void load_whenProvidedContents_shouldReturnParserInstance() throws Exception { //GIVEN byte[] mapData = {0x0, 0x1, 0x2, 0x3}; //WHEN MapParser mapParser = MapParser.load(mapData); //THEN assertThat(mapParser).isNotNull(); } @Test void parse_whenRealFiles_shouldFillStore_andReadAllEntries() throws IOException { // GIVEN byte[] mapContents = FilesHelper.readBytesFromResourceFile("/banks/Bnk1.map"); // WHEN MapParser mapParser = MapParser.load(mapContents); BankMap actualBankMap = mapParser.parse(); Log.debug(thisClass.getSimpleName(), "Dumped contents:\n" + mapParser.dump()); // THEN byte[] separatorBytes = {0x0, (byte) 0xFE, 0x12, 0x0}; assertThat(actualBankMap).isNotNull(); assertThat(actualBankMap.getEntrySeparator()).isEqualTo(separatorBytes); assertThat(actualBankMap.getEntries()).hasSize(4); assertThat(actualBankMap.getEntries()).extracting("hash").containsAll(asList(858241L, 1507153L, 1521845L, 1572722L)); assertThat(actualBankMap.getEntries()).extracting("size1").containsAll(asList(0L, 0L, 0L, 0L)); assertThat(actualBankMap.getEntries()).extracting("size2").containsAll(asList(0L, 0L, 0L, 0L)); assertThat(mapParser.getDataStore().size()).isEqualTo(16); // = 4*(Hash+Size1+Size2+End) } }
33.666667
125
0.69901
8a5708ea73a09374a49dc80ca1ffb1a914eab2a0
1,417
package org.sitemesh.config; /** * Responsible for instantiating objects - converting from strings in a config file to a real instance. * * <p>Typically you would use the {@link ObjectFactory.Default} implementation, * but this can be replaced. e.g. To connect to a dependency injection framework, lookup from * a registry, do custom classloading, etc.</p> * * @see org.sitemesh.config.ObjectFactory.Default * @author Joe Walnes */ public interface ObjectFactory { Object create(String name) throws IllegalArgumentException; /** * Default implementation of {@link ObjectFactory} that treats the object * name as a class name, loading it from the current ClassLoader and instantiating * with the default constructor. */ public static class Default implements ObjectFactory { public Object create(String name) { try { Class<?> cls = Class.forName(name); return cls.newInstance(); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not instantiate " + name, e); } catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + name, e); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not instantiate " + name, e); } } } }
38.297297
103
0.658433
f1876ac33c6926f8d51c12918997d9c03c4d5031
7,596
package com.exx.dzj.controller.stock; import com.exx.dzj.constant.CommonConstant; import com.exx.dzj.entity.dictionary.DictionaryInfo; import com.exx.dzj.entity.stock.StockBean; import com.exx.dzj.entity.stock.StockNumPrice; import com.exx.dzj.entity.stock.StockQuery; import com.exx.dzj.facade.stock.StockFacade; import com.exx.dzj.result.Result; import com.exx.dzj.unique.SingletonGeneratorConfig; import com.exx.dzj.util.JsonUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Arrays; import java.util.List; /** * @Author * @Date 2019/1/12 0012 17:17 * @Description 存货 */ @RestController @RequestMapping("stock/") public class StockController { @Autowired private StockFacade stockFacade; /** * 获取存货列表 * @param request * @param response * @return */ @GetMapping("queryStockList") public Result queryStockList(HttpServletRequest request, HttpServletResponse response, String query) { Result result = Result.responseSuccess(); StockQuery queryParam = JsonUtils.jsonToPojo(query, StockQuery.class); int pageNum = queryParam != null ? queryParam.getPage() : CommonConstant.DEFAULT_PAGE_NUM; int pageSize = queryParam != null ? queryParam.getLimit() : CommonConstant.DEFAULT_PAGE_SIZE; result = stockFacade.queryStockList(pageNum, pageSize, queryParam); return result; } @GetMapping("queryStockWarningList") public Result queryStockWarningList(HttpServletRequest request, HttpServletResponse response, String query) { Result result = Result.responseSuccess(); StockQuery queryParam = JsonUtils.jsonToPojo(query, StockQuery.class); int pageNum = queryParam != null ? queryParam.getPage() : CommonConstant.DEFAULT_PAGE_NUM; int pageSize = queryParam != null ? queryParam.getLimit() : CommonConstant.DEFAULT_PAGE_SIZE; result = stockFacade.queryStockWarningList(pageNum, pageSize, queryParam); return result; } /** * 获取存货信息 * @param request * @param response * @param stockCode * @return */ @GetMapping("queryStockInfo") public Result queryStockInfo(HttpServletRequest request, HttpServletResponse response, @RequestParam String stockCode) { Result result = Result.responseSuccess(); result = stockFacade.queryStockInfo(stockCode); return result; } /** * 更新存货信息 * @param request * @param response * @return */ @PostMapping("saveStockInfo") public Result saveStockInfo(HttpServletRequest request, HttpServletResponse response, @RequestBody StockBean bean) { return stockFacade.saveStockInfo(bean); } /** * 删除存货信息 * @return */ @PostMapping("delStockInfo") public Result delStockInfo(HttpServletRequest request, HttpServletResponse response, @RequestParam(value="stockCode") String stockCode) { Result result = Result.responseSuccess(); if(!StringUtils.isNotBlank(stockCode)){ result.setCode(400); result.setMsg("请选择要删除的数据!"); return result; } return stockFacade.delStockInfo(stockCode); } /** * 上架-下架 * @param request * @param response * @param stockCode * @param isShelves * @return */ @PostMapping("shelvesStock/{isShelves}") public Result shelvesStock(HttpServletRequest request, HttpServletResponse response, @RequestParam String stockCode, @PathVariable("isShelves") Integer isShelves) { return stockFacade.shelvesStock(isShelves, stockCode); } /** * @description 存货编码生成 * @author yangyun * @date 2019/1/19 0019 * @param * @return com.exx.dzj.result.Result */ @GetMapping("generatorstockcode") public Result generatorStockCode(){ Result result = Result.responseSuccess(); String saleCode = "STOCKCODE" + SingletonGeneratorConfig.getSingleton().next(); result.setData(saleCode); return result; } /** * @description * @author yangyun * @date 2019/1/19 0019 * @param request * @param response * @param stockBean * @return com.exx.dzj.result.Result */ @PostMapping("addinventoryservice") public Result addInventoryService(HttpServletRequest request, HttpServletResponse response, @RequestBody StockBean stockBean){ Result result = Result.responseSuccess(); stockFacade.insertStockInfo(stockBean); return result; } /** * @description 新增销售单查询多仓库 * @author yangyun * @date 2019/5/31 0031 * @param stockCodeList * @return com.exx.dzj.result.Result */ @GetMapping("querymultiplestocks/{stockCodeList}") public Result queryMultipleStocks (@PathVariable("stockCodeList") String stockCodeList){ Result result = Result.responseSuccess(); List<String> stockCodes = Arrays.asList(stockCodeList.split("&")); List<DictionaryInfo> data = stockFacade.queryMultipleStocks(stockCodes); result.setData(data); return result; } @GetMapping("querystocknumpircklist") public Result queryStockNumPirckList ( StockNumPrice stockNumPrice){ Result result = Result.responseSuccess(); StockNumPrice snp = stockFacade.queryStockNumPirck(stockNumPrice); result.setData(snp); return result; } @GetMapping("checkStockCode") public Result checkStockCode(String stockCode) { return stockFacade.checkStockCode(stockCode); } @GetMapping("checkStockName") public Result checkStockName(String stockName) { return stockFacade.checkStockName(stockName); } @GetMapping("querySelectStockList") public Result querySelectStockList(HttpServletRequest request, HttpServletResponse response, String query) { Result result = Result.responseSuccess(); StockQuery queryParam = JsonUtils.jsonToPojo(query, StockQuery.class); int pageNum = queryParam != null ? queryParam.getPage() : CommonConstant.DEFAULT_PAGE_NUM; int pageSize = queryParam != null ? queryParam.getLimit() : CommonConstant.DEFAULT_PAGE_SIZE; result = stockFacade.querySelectStockList(pageNum, pageSize, queryParam); return result; } /** * @description: 销售单新增时,过滤已下架产品 * @author yangyun * @date 2019/10/7 0007 * @param request * @param response * @param query * @return com.exx.dzj.result.Result */ @GetMapping("querySelectStockList2") public Result querySelectStockList2(HttpServletRequest request, HttpServletResponse response, String query) { Result result = Result.responseSuccess(); StockQuery queryParam = JsonUtils.jsonToPojo(query, StockQuery.class); int pageNum = queryParam != null ? queryParam.getPage() : CommonConstant.DEFAULT_PAGE_NUM; int pageSize = queryParam != null ? queryParam.getLimit() : CommonConstant.DEFAULT_PAGE_SIZE; result = stockFacade.querySelectStockList2(pageNum, pageSize, queryParam); return result; } @Deprecated @GetMapping("querystockgoodsinventory") public Result queryStockGoodsInventory (StockNumPrice stockNumPrice){ Result result = Result.responseSuccess(); return result; } }
35.166667
141
0.687994
f86cf7c72c80ca93d9177edea42b90474a14c510
1,446
package com.cassava.core; import com.datastax.driver.core.Session; import com.datastax.driver.core.exceptions.InvalidQueryException; import org.junit.Test; import static org.junit.Assert.*; /** * Created by yan.dai on 4/11/2015. */ public class CassandraClusterTest { @Test public void testCassandraClusterSetup() { String keyspace = "mytest"; CassandraCluster cluster = CassandraCluster.get(keyspace, "C:\\Dev\\cassava\\src\\test\\resources\\cassandra-cluster.properties"); try { cluster.getCluster().connect("test"); } catch (InvalidQueryException e) { assertTrue(true); } cluster.dropKeyspace(keyspace); } @Test public void testCassandraClusterSetup2() { String keyspace = "mytest"; CassandraCluster cluster = CassandraCluster.get(keyspace, "C:\\Dev\\cassava\\src\\test\\resources\\cassandra-cluster.properties"); try { Session session = cluster.getCluster().connect(keyspace); assertTrue(cluster.hasKeyspace(keyspace)); assertNotNull(session); } catch (InvalidQueryException e) { assertTrue(true); } cluster.dropKeyspace(keyspace); try { cluster.getCluster().connect(keyspace); assertFalse(cluster.hasKeyspace(keyspace)); } catch (InvalidQueryException e) { assertTrue(true); } } }
30.765957
138
0.637621
06a91849c431e8654a2a6338f0579f92a4227816
1,252
package es.uniovi.asw.parser; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import jxl.Sheet; import jxl.Workbook; import jxl.read.biff.BiffException; public class ParserXLS implements Parser { public List<Map<String,String>> leerDatos(File fichero){ List<Map<String,String>> usuarios = new LinkedList<Map<String,String>>(); Workbook wB = null; try { wB = Workbook.getWorkbook(fichero); } catch (BiffException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Sheet censos = wB.getSheet("Censos"); for(int i=1;i<censos.getRows();i++){ Map<String,String> datosUsuarios = new HashMap<String,String>(); String nombre = censos.getCell(0,i).getContents(); String NIF = censos.getCell(1,i).getContents(); String email = censos.getCell(2,i).getContents(); String codigoMesa = censos.getCell(3,i).getContents(); datosUsuarios.put("nombre", nombre); datosUsuarios.put("NIF", NIF); datosUsuarios.put("email", email); datosUsuarios.put("codigoMesa", codigoMesa); usuarios.add(datosUsuarios); } return usuarios; } }
21.964912
75
0.682907
85e4ad91c8face98f8dae6773e93ec120c2d42ea
2,922
package dk.silverbullet.telemed.questionnaire.node; import com.google.gson.annotations.Expose; import dk.silverbullet.telemed.bloodsugar.ContinuousBloodSugarMeasurement; import dk.silverbullet.telemed.bloodsugar.ContinuousBloodSugarMeasurements; import dk.silverbullet.telemed.questionnaire.Questionnaire; import dk.silverbullet.telemed.questionnaire.R; import dk.silverbullet.telemed.questionnaire.element.TextViewElement; import dk.silverbullet.telemed.questionnaire.element.TwoButtonElement; import dk.silverbullet.telemed.questionnaire.expression.Variable; import dk.silverbullet.telemed.questionnaire.expression.VariableLinkFailedException; import dk.silverbullet.telemed.utils.Util; import java.util.Date; import java.util.Map; public class ContinuousBloodSugarTestDeviceNode extends DeviceNode { private TextViewElement infoElement; @Expose private Variable<ContinuousBloodSugarMeasurements> bloodSugarMeasurements; @Expose String text; public ContinuousBloodSugarTestDeviceNode(Questionnaire questionnaire, String nodeName) { super(questionnaire, nodeName); } @Override public void enter() { clearElements(); addElement(new TextViewElement(this, text)); infoElement = new TextViewElement(this); updateInfoElement("Simuleret CGM"); addElement(infoElement); TwoButtonElement be = new TwoButtonElement(this); be.setLeftNextNode(getNextFailNode()); be.setLeftText(Util.getString(R.string.default_omit, questionnaire)); be.setRightNextNode(getNextNode()); be.setRightText(Util.getString(R.string.default_next, questionnaire)); addElement(be); super.enter(); } @Override public void linkVariables(Map<String, Variable<?>> variablePool) throws VariableLinkFailedException { super.linkVariables(variablePool); bloodSugarMeasurements = Util.linkVariable(variablePool, bloodSugarMeasurements); } public void deviceLeave() { ContinuousBloodSugarMeasurements measurements = new ContinuousBloodSugarMeasurements(); measurements.serialNumber = "123456"; measurements.transferTime = new Date(); for (int i=0; i<1000; i++) { ContinuousBloodSugarMeasurement measurement = new ContinuousBloodSugarMeasurement(); measurement.recordId = i; measurement.timeOfMeasurement = new Date(System.currentTimeMillis() - i*(1000 * 60 * 5)); measurement.value = (5 + 50*Math.sin(i / 100d)) + ""; measurements.measurements.add(measurement); } bloodSugarMeasurements.setValue(measurements); } private void updateInfoElement(final String text) { questionnaire.getActivity().runOnUiThread(new Runnable() { @Override public void run() { infoElement.setText(text); } }); } }
37.461538
105
0.721424
701ba9a8f78c918f2e515086dc2a8b9dfb999cfe
3,506
package com.foxinmy.weixin4j.server.xml; import java.io.IOException; import java.io.StringWriter; import java.lang.reflect.Field; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.TypeReference; import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.serializer.NameFilter; import com.foxinmy.weixin4j.server.util.Consts; import com.foxinmy.weixin4j.util.StringUtil; /** * 对 后缀为_$n 的 xml节点序列化 * * @className ListsuffixResultSerializer * @author jy * @date 2015年3月24日 * @since JDK 1.6 * @see */ public class ListsuffixResultSerializer { /** * 序列化为json * * @param object * @return json */ public static JSONObject serializeToJSON(Object object) { JSONObject result = (JSONObject) JSON.toJSON(object); Map<Field, String[]> listsuffixFields = ListsuffixResultDeserializer .getListsuffixFields(object.getClass()); if (!listsuffixFields.isEmpty()) { JSONField jsonField = null; Object value = null; for (Field field : listsuffixFields.keySet()) { jsonField = field.getAnnotation(JSONField.class); if (jsonField != null && StringUtil.isNotBlank(jsonField.name())) { result.remove(jsonField.name()); } else { result.remove(field.getName()); } try { field.setAccessible(true); value = field.get(object); } catch (Exception e) { ;// } if (value != null && value instanceof List) { result.putAll(listsuffixConvertMap((List<?>) value)); } } } return result; } /** * list对象转换为map的$n形式 * * @param listsuffix * @return */ public static Map<String, String> listsuffixConvertMap(List<?> listsuffix) { Map<String, String> listMap = new HashMap<String, String>(); if (listsuffix != null && !listsuffix.isEmpty()) { for (int i = 0; i < listsuffix.size(); i++) { listMap.putAll(JSON.parseObject(JSON.toJSONString( listsuffix.get(i), new ListsuffixEndNameFilter(i)), new TypeReference<Map<String, String>>() { })); } } return listMap; } private static class ListsuffixEndNameFilter implements NameFilter { private final int index; public ListsuffixEndNameFilter(int index) { this.index = index; } @Override public String process(Object object, String name, Object value) { return String.format("%s_%d", name, index); } } /** * 序列化为xml * * @param object * @return xml */ public static String serializeToXML(Object object) { JSONObject obj = serializeToJSON(object); StringWriter sw = new StringWriter(); XMLStreamWriter xw = null; try { xw = XMLOutputFactory.newInstance().createXMLStreamWriter(sw); xw.writeStartDocument(Consts.UTF_8.name(), "1.0"); xw.writeStartElement("xml"); for (String key : obj.keySet()) { if (StringUtil.isBlank(obj.getString(key))) { continue; } xw.writeStartElement(key); xw.writeCData(obj.getString(key)); xw.writeEndElement(); } xw.writeEndElement(); xw.writeEndDocument(); } catch (XMLStreamException e) { e.printStackTrace(); } finally { if (xw != null) { try { xw.close(); } catch (XMLStreamException e) { ; } } try { sw.close(); } catch (IOException e) { ; } } return sw.getBuffer().toString(); } }
24.517483
77
0.677125
2f74cb7a1bb9fa0543d4ca69ea71d33e8c5f09ad
194
package com.baidu.mapp.developer.bean.templatemessage; import cn.hutool.core.annotation.Alias; import lombok.Data; @Data public class MsgKey { @Alias("msg_key") private long msgKey; }
17.636364
54
0.752577
06a75c0ae809aaa2dee4693746b02647435eefa9
2,124
package basemod.patches.com.megacrit.cardcrawl.cards.AbstractCard; import com.evacipated.cardcrawl.modthespire.lib.*; import com.megacrit.cardcrawl.cards.AbstractCard; import com.megacrit.cardcrawl.localization.LocalizedStrings; import javassist.CtBehavior; import java.util.ArrayList; // This fixes an issue that is present in the base game. In the separate logic for Chinese-language text parsing, // if the first word of a card description is a keyword, the first line of card text ends up being the empty string. // In Traditional Chinese, LocalizedString.PERIOD is also the empty string, which causes the logic that tries to fix // cases like this to crash due to try to access array index -1. (I suspect the logic is intended for fixing periods at // the end of the description that would otherwise spill over to their own line, which explains why it doesn't account // for finding lines like this at the start of the string). // Simplified Chinese does not have this issue because LocalizedString.PERIOD is 。(in theory, if a card description // started with a 。, the same problem would happen). // To fix this, we insert our own code to remove lines at the start of the description that equal the localized period // string. That removes the meaningless lines and lets the rest of the logic run without crashing for all Chinese text. @SpirePatch(clz = AbstractCard.class, method = "initializeDescriptionCN") public class PreventCrashDueToKeywordAtStartOfCardTextForTraditionalChinesePatch { @SpireInsertPatch(locator = Locator.class) public static void preventCrash(AbstractCard __instance) { while (__instance.description.size() > 0 && __instance.description.get(0).text.equals(LocalizedStrings.PERIOD)) { __instance.description.remove(0); } } private static class Locator extends SpireInsertLocator { @Override public int[] Locate(CtBehavior ctBehavior) throws Exception { Matcher finalMatcher = new Matcher.MethodCallMatcher(ArrayList.class, "size"); return LineFinder.findInOrder(ctBehavior, finalMatcher); } } }
57.405405
121
0.764124
2203aeda5b50df29870e59df4a79c28b111d4984
1,684
package org.open918.lib.encodings; import org.open918.lib.domain.GenericTicketDetails; import org.open918.lib.domain.TicketField; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * Converter for the 'EOSU' standard - used in Hamburg by transport company HVV (and others?) * Only one sample was available for this type of ticket, support is limited */ public class EosuConverter extends TicketConverter { public EosuConverter(List<TicketField> fields) { super(fields); } @Override public String toText() { StringBuilder lines = new StringBuilder(); Collections.sort(fields, new TicketFieldLineComparator()); for (TicketField f : fields) { lines.append(f.getText()); lines.append("\r\n"); } return lines.toString(); } @Override public GenericTicketDetails toDetails() { GenericTicketDetails ticket = new GenericTicketDetails(); for (TicketField f : fields) { if (f.getLine() == 0) { ticket.setPassengerName(f.getText()); } else if (f.getLine() == 1) { ticket.setTicketTitle(f.getText()); } else if (f.getLine() == 2) { ticket.setRouteDetails(f.getText()); } else if (f.getLine() == 3) { ticket.setValidity(f.getText()); } } return ticket; } private static class TicketFieldLineComparator implements Comparator<TicketField> { @Override public int compare(TicketField o1, TicketField o2) { return o1.getLine() - o2.getLine(); } } }
28.066667
93
0.609264
a5e30348b1818ce6b648163272b7608cc6ef3405
388
package net.varanus.sdncontroller.qosrouting; import net.varanus.sdncontroller.qosrouting.internal.QoSRoutingManager; import net.varanus.sdncontroller.util.module.AbstractServiceableModule; /** * */ public final class QoSRoutingModule extends AbstractServiceableModule { public QoSRoutingModule() { super(new QoSRoutingManager(), IQoSRoutingService.class); } }
21.555556
71
0.778351
cc0a15aa8e214af5286eac3692e967c60a490d9e
2,260
package com.jlfex.hermes.service.pojo; import java.io.Serializable; public class UserInfo implements Serializable { private static final long serialVersionUID = -6137546174092886755L; /** 编号 */ private String id; /** 昵称 */ private String account; /** 手机号码 */ private String cellphone; /** 姓名 */ private String realName; /** 总金额 */ private String total; /** 冻结金额 */ private String freeze; /** 可用金额 */ private String free; /** 用户类型 */ private String type; /** * 读取 * * @return * @see #id */ public String getId() { return id; } /** * 设置 * * @param id * @see #id */ public void setId(String id) { this.id = id; } /** * 读取 * * @return * @see #account */ public String getAccount() { return account; } /** * 设置 * * @param account * @see #account */ public void setAccount(String account) { this.account = account; } /** * 读取 * * @return * @see #cellphone */ public String getCellphone() { return cellphone; } /** * 设置 * * @param cellphone * @see #cellphone */ public void setCellphone(String cellphone) { this.cellphone = cellphone; } /** * 读取 * * @return * @see #realName */ public String getRealName() { return realName; } /** * 设置 * * @param realName * @see #realName */ public void setRealName(String realName) { this.realName = realName; } /** * 读取 * * @return * @see #total */ public String getTotal() { return total; } /** * 设置 * * @param total * @see #total */ public void setTotal(String total) { this.total = total; } /** * 读取 * * @return * @see #freeze */ public String getFreeze() { return freeze; } /** * 设置 * * @param freeze * @see #freeze */ public void setFreeze(String freeze) { this.freeze = freeze; } /** * 读取 * * @return * @see #free */ public String getFree() { return free; } /** * 设置 * * @param free * @see #free */ public void setFree(String free) { this.free = free; } /** * 读取 * * @return * @see #type */ public String getType() { return type; } /** * 设置 * * @param type * @see #type */ public void setType(String type) { this.type = type; } }
12.021277
68
0.554867
24f731401dbd710ce4f06f7f2ab15195abc280ab
5,370
package example; import com.luciad.imageio.webp.WebPReadParam; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.stream.FileImageInputStream; import java.awt.image.BufferedImage; import java.io.File; import java.util.ArrayList; public class ImageReverse { public static ArrayList<String> files = new ArrayList<String>(); public static ArrayList<String> files_9 = new ArrayList<String>(); public static void main(String[] args) { String fileDir = "/Users/cuiweicong/Desktop/需要反色"; getFiles(fileDir); if (files != null && files.size() > 0) { for (String filePath : files) { BufferedImage bi = file2img(filePath); //读取图片 BufferedImage bii = img_inverse(bi,false); String filePathName = getFileName(filePath); String newFile = "/Users/cuiweicong/Desktop/图片反色/" + filePathName; createFile(newFile); img2file(bii, filePath.split("\\.")[1], newFile); //生成图片 } } } //图片反色 public static BufferedImage img_inverse(BufferedImage imgsrc, boolean isNice) { try { //创建一个不透明度的图片 BufferedImage back = new BufferedImage(imgsrc.getWidth(), imgsrc.getHeight(), BufferedImage.TYPE_INT_ARGB); int width = imgsrc.getWidth(); int height = imgsrc.getHeight(); for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { int pixel = imgsrc.getRGB(j, i); int alpha = (pixel >> 24) & 0x00FFFFFF; int red = (pixel >> 16) & 0x0ff; int green = (pixel >> 8) & 0x0ff; int blue = pixel & 0x0ff; System.out.println("i=" + i + ",j=" + j + ",pixel=" + pixel + " ,alpha = " + alpha + ",red = " + red + ",green = " + green + ",blue = " + blue); // back.setRGB(j,i,0xFFFFFF-pixel); red = 255 - red; green = 255 - green; blue = 255 - blue; // int result = (0xFFFFFF - pixel); int result = (alpha << 24) | (red << 16) | (green << 8) | blue; System.out.println("result = " + result + ",red = " + red + ",green = " + green + ",blue = " + blue); if(isNice && (i == 0 || i == (height-1) || j == 0| j == (width-1))){ back.setRGB(j, i, pixel); }else { back.setRGB(j, i, result); } } } return back; } catch (Exception e) { e.printStackTrace(); return null; } } //获取文件夹下的所有文件 public static ArrayList<String> getFiles(String path) { File file = new File(path); File[] tempList = file.listFiles(); for (int i = 0; i < tempList.length; i++) { if (tempList[i].isFile()) { System.out.println("文 件:" + tempList[i]); if(getFileName(tempList[i].toString()).contains(".9")){ files_9.add(tempList[i].toString()); }else{ files.add(tempList[i].toString()); } } if (tempList[i].isDirectory()) { System.out.println("文件夹:" + tempList[i]); } } return files; } //获取文件名 public static String getFileName(String path) { File tempFile = new File(path.trim()); String fileName = tempFile.getName(); return fileName; } //创建文件 public static void createFile(String path) { /**//*查找目录,如果不存在,就创建*/ try{ File dirFile = new File(path); if (!dirFile.exists()) { if (!dirFile.mkdir()) System.out.println("目录不存在,创建失败!"); } /**//*查找文件,如果不存在,就创建*/ File file = new File(path); if (!file.exists()) if (!file.createNewFile()) System.out.println("文件不存在,创建失败!"); }catch(Exception e){ } } //读取图片 public static BufferedImage file2img(String imgpath) { try { BufferedImage bufferedImage; if (imgpath.endsWith("webp")) { // Configure decoding parameters ImageReader reader = ImageIO.getImageReadersByMIMEType("image/webp").next(); // Configure decoding parameters WebPReadParam readParam = new WebPReadParam(); readParam.setBypassFiltering(true); reader.setInput(new FileImageInputStream(new File(imgpath))); bufferedImage = reader.read(0, readParam); } else { bufferedImage = ImageIO.read(new File(imgpath)); } return bufferedImage; } catch (Exception e) { e.printStackTrace(); return null; } } //保存图片,extent为格式,"jpg"、"png"等 public static void img2file(BufferedImage img, String extent, String newfile) { try { ImageIO.write(img, extent, new File(newfile)); } catch (Exception e) { e.printStackTrace(); } } }
34.645161
168
0.498138
569121e8fcc2a2b0b7beeb3e58699d8e51aa758b
2,136
/* * vriUVpDisp.java * * Used in the Virtual Radio Interferometer. * * 06/Jan/1998 Nuria McKay - Extracted from vriGreyDisp.java * */ import java.applet.Applet; class vriUVpDisp extends vriGreyDisp { public vriUVpDisp(int x, int y, int w, int h, Applet app) { super(x, y, w, h, app); message = new String("No current transform"); } public void fft() { if(dat == null) return; message = new String("Fourier transforming..."); repaint(); int[] nn = new int[2]; nn[0] = imsize; nn[1] = imsize; System.out.print("Doing forward transform... "); fft = new float[dat.length]; for(int i = 0; i < dat.length; i++) fft[i] = dat[i]; Fourier.fourn(fft, nn, 2, 1); System.out.println("done."); fftToImg(); } public void fftToImg() { fftToPix(); pixToImg(); message = null; repaint(); } public void applyUVc(vriUVcDisp uv) { // Applies the UV coverage (from the UVcDisp class) to the FFT // (the fft[] array). System.out.println("applyUVc"); if(fft == null) { System.err.println("applyUVc: fft[] array empty"); return; } message = new String("Applying UV coverage..."); repaint(); // Get square array of floating point numbers with the taper // function on pixels with UV coverage and 0 on those without float[] cov = uv.uvCoverage(imsize); for(int y = 0; y < imsize; y++) { for(int x = 0; x < imsize; x++) { int x1, y1; x1 = x - imsize/2; y1 = y - imsize/2; if (x1 < 0) x1 += imsize; if (y1 < 0) y1 += imsize; fft[y1*imsize*2 + x1*2] *= cov[y*imsize+x]; // Real fft[y1*imsize*2 + x1*2 + 1] *= cov[y*imsize+x]; // Imaginary } } fftToPix(); pixToImg(); message = null; repaint(); } } //####################################################################//
25.129412
74
0.482678
a1e34f0fb0651d1648ee038c2521d27328c9b318
2,665
package ykooze.ayaseruri.codesslib.io; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import android.content.Context; import io.reactivex.ObservableEmitter; import io.reactivex.ObservableOnSubscribe; import io.reactivex.functions.Consumer; import ykooze.ayaseruri.codesslib.rx.RxUtils; /** * @author zhangxl * @className SerializeUtils * @create 2014年4月16日 上午11:31:07 * @description 序列化工具类,可用于序列化对象到文件或从文件反序列化对象 */ public class SerializeUtils { /** * 从文件反序列化对象 * * @param tag * @return * @throws RuntimeException if an error occurs */ public static Object deserializationSync(final Context context, final String tag, final boolean delete) { try(FileInputStream fileInputStream = context.openFileInput(tag); ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream)){ Object object = objectInputStream.readObject(); if (delete) { context.deleteFile(tag); } return object; } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } /** * 序列化对象到文件,默认异步 * * @param tag * @param obj * @return * @throws RuntimeException if an error occurs */ public static void serialization(final Context context, final String tag, final Object obj) { io.reactivex.Observable.create(new ObservableOnSubscribe<Boolean>() { @Override public void subscribe(ObservableEmitter<Boolean> e) throws Exception { e.onNext(true); e.onComplete(); } }).subscribeOn(RxUtils.getSchedulers()).subscribe(new Consumer<Boolean>() { @Override public void accept(Boolean b) throws Exception { } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { } }); } //同步序列化 public static void serializationSync(Context context, final String tag, final Object obj) { if(null == obj){ return; } try(FileOutputStream fileOutputStream = context.openFileOutput(tag, Context.MODE_PRIVATE); ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream)) { objectOutputStream.writeObject(obj); } catch (IOException e) { e.printStackTrace(); } } }
30.284091
109
0.634522
b5decd79ad455d66bab028ffb438f40591253223
9,792
/* * 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.pdfbox.util; import java.awt.geom.AffineTransform; /** * This class will be used for matrix manipulation. * * @author <a href="mailto:[email protected]">Ben Litchfield</a> * @version $Revision: 1.14 $ */ public class Matrix implements Cloneable { private float[] single = { 1,0,0, 0,1,0, 0,0,1 }; /** * Constructor. */ public Matrix() { //default constructor } /** * Create an affine transform from this matrix's values. * * @return An affine transform with this matrix's values. */ public AffineTransform createAffineTransform() { AffineTransform retval = new AffineTransform( single[0], single[1], single[3], single[4], single[6], single[7] ); return retval; } /** * Set the values of the matrix from the AffineTransform. * * @param af The transform to get the values from. */ public void setFromAffineTransform( AffineTransform af ) { single[0] = (float)af.getScaleX(); single[1] = (float)af.getShearY(); single[3] = (float)af.getShearX(); single[4] = (float)af.getScaleY(); single[6] = (float)af.getTranslateX(); single[7] = (float)af.getTranslateY(); } /** * This will get a matrix value at some point. * * @param row The row to get the value from. * @param column The column to get the value from. * * @return The value at the row/column position. */ public float getValue( int row, int column ) { return single[row*3+column]; } /** * This will set a value at a position. * * @param row The row to set the value at. * @param column the column to set the value at. * @param value The value to set at the position. */ public void setValue( int row, int column, float value ) { single[row*3+column] = value; } /** * Return a single dimension array of all values in the matrix. * * @return The values ot this matrix. */ public float[][] getValues() { float[][] retval = new float[3][3]; retval[0][0] = single[0]; retval[0][1] = single[1]; retval[0][2] = single[2]; retval[1][0] = single[3]; retval[1][1] = single[4]; retval[1][2] = single[5]; retval[2][0] = single[6]; retval[2][1] = single[7]; retval[2][2] = single[8]; return retval; } /** * Return a single dimension array of all values in the matrix. * * @return The values ot this matrix. */ public double[][] getValuesAsDouble() { double[][] retval = new double[3][3]; retval[0][0] = single[0]; retval[0][1] = single[1]; retval[0][2] = single[2]; retval[1][0] = single[3]; retval[1][1] = single[4]; retval[1][2] = single[5]; retval[2][0] = single[6]; retval[2][1] = single[7]; retval[2][2] = single[8]; return retval; } /** * This will take the current matrix and multipy it with a matrix that is passed in. * * @param b The matrix to multiply by. * * @return The result of the two multiplied matrices. */ public Matrix multiply( Matrix b ) { Matrix result = new Matrix(); if (b != null && b.single != null) { float[] bMatrix = b.single; float[] resultMatrix = result.single; resultMatrix[0] = single[0] * bMatrix[0] + single[1] * bMatrix[3] + single[2] * bMatrix[6]; resultMatrix[1] = single[0] * bMatrix[1] + single[1] * bMatrix[4] + single[2] * bMatrix[7]; resultMatrix[2] = single[0] * bMatrix[2] + single[1] * bMatrix[5] + single[2] * bMatrix[8]; resultMatrix[3] = single[3] * bMatrix[0] + single[4] * bMatrix[3] + single[5] * bMatrix[6]; resultMatrix[4] = single[3] * bMatrix[1] + single[4] * bMatrix[4] + single[5] * bMatrix[7]; resultMatrix[5] = single[3] * bMatrix[2] + single[4] * bMatrix[5] + single[5] * bMatrix[8]; resultMatrix[6] = single[6] * bMatrix[0] + single[7] * bMatrix[3] + single[8] * bMatrix[6]; resultMatrix[7] = single[6] * bMatrix[1] + single[7] * bMatrix[4] + single[8] * bMatrix[7]; resultMatrix[8] = single[6] * bMatrix[2] + single[7] * bMatrix[5] + single[8] * bMatrix[8]; } return result; } /** * Create a new matrix with just the scaling operators. * * @return A new matrix with just the scaling operators. */ public Matrix extractScaling() { Matrix retval = new Matrix(); retval.single[0] = this.single[0]; retval.single[4] = this.single[4]; return retval; } /** * Convenience method to create a scaled instance. * * @param x The xscale operator. * @param y The yscale operator. * @return A new matrix with just the x/y scaling */ public static Matrix getScaleInstance( float x, float y) { Matrix retval = new Matrix(); retval.single[0] = x; retval.single[4] = y; return retval; } /** * Create a new matrix with just the translating operators. * * @return A new matrix with just the translating operators. */ public Matrix extractTranslating() { Matrix retval = new Matrix(); retval.single[6] = this.single[6]; retval.single[7] = this.single[7]; return retval; } /** * Convenience method to create a translating instance. * * @param x The x translating operator. * @param y The y translating operator. * @return A new matrix with just the x/y translating. */ public static Matrix getTranslatingInstance( float x, float y) { Matrix retval = new Matrix(); retval.single[6] = x; retval.single[7] = y; return retval; } /** * Clones this object. * @return cloned matrix as an object. */ public Object clone() { Matrix clone = new Matrix(); System.arraycopy( single, 0, clone.single, 0, 9 ); return clone; } /** * This will copy the text matrix data. * * @return a matrix that matches this one. */ public Matrix copy() { return (Matrix) clone(); } /** * This will return a string representation of the matrix. * * @return The matrix as a string. */ public String toString() { StringBuffer result = new StringBuffer( "" ); result.append( "[[" ); result.append( single[0] + "," ); result.append( single[1] + "," ); result.append( single[2] + "]["); result.append( single[3] + "," ); result.append( single[4] + "," ); result.append( single[5] + "]["); result.append( single[6] + "," ); result.append( single[7] + "," ); result.append( single[8] + "]]"); return result.toString(); } /** * Get the xscaling factor of this matrix. * @return The x-scale. */ public float getXScale() { float xScale = single[0]; /** * BM: if the trm is rotated, the calculation is a little more complicated * * The rotation matrix multiplied with the scaling matrix is: * ( x 0 0) ( cos sin 0) ( x*cos x*sin 0) * ( 0 y 0) * (-sin cos 0) = (-y*sin y*cos 0) * ( 0 0 1) ( 0 0 1) ( 0 0 1) * * So, if you want to deduce x from the matrix you take * M(0,0) = x*cos and M(0,1) = x*sin and use the theorem of Pythagoras * * sqrt(M(0,0)^2+M(0,1)^2) = * sqrt(x2*cos2+x2*sin2) = * sqrt(x2*(cos2+sin2)) = <- here is the trick cos2+sin2 is one * sqrt(x2) = * abs(x) */ if( !(single[1]==0.0f && single[3]==0.0f) ) { xScale = (float)Math.sqrt(Math.pow(single[0], 2)+ Math.pow(single[1], 2)); } return xScale; } /** * Get the y scaling factor of this matrix. * @return The y-scale factor. */ public float getYScale() { float yScale = single[4]; if( !(single[1]==0.0f && single[3]==0.0f) ) { yScale = (float)Math.sqrt(Math.pow(single[3], 2)+ Math.pow(single[4], 2)); } return yScale; } /** * Get the x position in the matrix. * @return The x-position. */ public float getXPosition() { return single[6]; } /** * Get the y position. * @return The y position. */ public float getYPosition() { return single[7]; } }
28.884956
103
0.543301
71ded59852782fcfaf1befeaffafebce480e07e9
3,497
package org.immopoly.android.fragments; import org.immopoly.android.R; import org.immopoly.android.app.ImmopolyActivity; import org.immopoly.android.app.UserDataListener; import org.immopoly.android.app.UserDataManager; import org.immopoly.android.constants.Const; import org.immopoly.android.helper.TrackingManager; import org.immopoly.android.model.Flat; import org.immopoly.android.model.Flats; import org.immopoly.android.model.ImmopolyUser; import org.immopoly.android.widget.ImmoscoutPlacesOverlay; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import com.google.android.apps.analytics.GoogleAnalyticsTracker; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapView; public class PortfolioMapFragment extends Fragment implements UserDataListener { private MapView mMapView; private ImmoscoutPlacesOverlay flatsOverlay; private Flats mFlats; private GoogleAnalyticsTracker mTracker; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mTracker = GoogleAnalyticsTracker.getInstance(); // Start the tracker in manual dispatch mode... mTracker.startNewSession(TrackingManager.UA_ACCOUNT, Const.ANALYTICS_INTERVAL, getActivity().getApplicationContext()); mTracker.trackPageView(TrackingManager.VIEW_PORTFOLIO_MAP); Log.i(Const.LOG_TAG, "PortfolioMapFragment.onCreateView"); View layout = inflater.inflate(R.layout.portfolio_map, null, false); ImmopolyUser user = ImmopolyUser.getInstance(); mFlats = user.getPortfolio(); mMapView = ((ImmopolyActivity) getActivity()).acquireMapView(this); flatsOverlay = new ImmoscoutPlacesOverlay(this, mMapView, inflater, true); flatsOverlay.setFlats(mFlats); mMapView.getOverlays().add(flatsOverlay); FrameLayout mapFrame = (FrameLayout) layout.findViewById(R.id.pf_map_frame); mapFrame.addView(mMapView, 0); layout.findViewById(R.id.portfolio_btn_list).setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Log.i("IMPO", "PortfolioMapFragment show listg"); ((ImmopolyActivity) getActivity()).getTabManager().onTabChanged("portfolio"); } }); UserDataManager.instance.addUserDataListener(this); // set map to show all flats double minLat = Double.MAX_VALUE, maxLat = Double.MIN_VALUE, minLon = Double.MAX_VALUE, maxLon = Double.MIN_VALUE; for (Flat f : mFlats) { if ( f.lat < minLat ) minLat = f.lat; if ( f.lat > maxLat ) maxLat = f.lat; if ( f.lng < minLon ) minLon = f.lng; if ( f.lng > maxLon ) maxLon = f.lng; } Log.i( Const.LOG_TAG, "LAT MIN: " + minLat + " MAX: " + maxLat ); Log.i( Const.LOG_TAG, "LON MIN: " + minLon + " MAX: " + maxLon ); mMapView.getController().setCenter( new GeoPoint( (int) ((minLat+maxLat)/2 * 1E6), (int) ((minLon+maxLon)/2*1E6) )); mMapView.getController().zoomToSpan( (int) ((maxLat-minLat) * 1E6 * 1.1), (int) ((maxLon-minLon) * 1E6 * 1.1)); return layout; } @Override public void onDestroyView() { mTracker.stopSession(); ((ImmopolyActivity) getActivity()).releaseMapView(this); super.onDestroyView(); } @Override public void onUserDataUpdated() { // TODO check my vilibility mFlats = ImmopolyUser.getInstance().getPortfolio(); flatsOverlay.hideBubble(); flatsOverlay.setFlats(mFlats); mMapView.invalidate(); } }
36.051546
118
0.756649
ceac01561bb72ab9fe1fc42a323bbf453f0e8691
2,132
package org.openxava.util; import java.io.*; import java.net.*; import java.util.*; /** * Reads properties files. <p> * * @author: Javier Paniza */ public class PropertiesReader { private Class theClass; private String propertiesFileURL; private Properties properties; /** * @param propertiesFileURL Cannot be null * @param theClass Class from obtain the <code>ClassLoader</code> used to read the file. Cannot be nul */ public PropertiesReader(Class theClass, String propertiesFileURL) { Assert.arg(theClass, propertiesFileURL); this.theClass = theClass; this.propertiesFileURL = propertiesFileURL; } // Adds properties in url to p. private void add(Properties p, URL url) throws IOException { // assert(p, url); InputStream is = url.openStream(); Properties properties = new Properties(); properties.load(is); p.putAll(properties); try { is.close(); } catch (IOException ex) {} } /** * Returns properties associated to indicated file. <p> * * Read all files in classpath with the property file name used in constructor. * The result is a mix of all properties of this files. <br> * Only read the first time. <br> * * @return Not null */ public Properties get() throws IOException { if (properties == null) { Enumeration e = theClass.getClassLoader().getResources(propertiesFileURL); properties = new Properties(); List urls = new ArrayList(); List priorityURLs = new ArrayList(); while (e.hasMoreElements()) { URL url = (URL) e.nextElement(); // We give priority to WEB-INF/classes, we do not trust in the classloader configuration of the application server boolean priority = Strings.noLastToken(url.toExternalForm(), "/").endsWith("/WEB-INF/classes/"); if (priority) priorityURLs.add(url); else urls.add(url); } Collections.reverse(urls); Collections.reverse(priorityURLs); urls.addAll(priorityURLs); for (Iterator it = urls.iterator(); it.hasNext(); ) { URL url = (URL) it.next(); add(properties, url); } } return properties; } }
26.65
118
0.674484
e84f644658b3563384ea7205ee014de035e89f5d
572
package com.newhopemail.coupon.service; import com.baomidou.mybatisplus.extension.service.IService; import com.newhopemail.common.to.SkuReductionTO; import com.newhopemail.common.utils.PageUtils; import com.newhopemail.coupon.entity.SkuFullReductionEntity; import java.util.Map; /** * 商品满减信息 * * @author zao * @email [email protected] * @date 2021-04-26 02:50:56 */ public interface SkuFullReductionService extends IService<SkuFullReductionEntity> { PageUtils queryPage(Map<String, Object> params); void saveInfo(SkuReductionTO skuFullReduction); }
23.833333
83
0.786713
6efd832f7c916df937a9710a4cd3c6e2feb32bb0
917
package de.fh.rosenheim.aline.model.dtos.seminar; import com.fasterxml.jackson.annotation.JsonView; import de.fh.rosenheim.aline.model.dtos.json.view.View; import de.fh.rosenheim.aline.util.SwaggerTexts; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import java.util.Date; @Data public class SeminarDTO extends SeminarBasicsDTO { @JsonView({View.SeminarDetailsView.class, View.SeminarIdView.class}) private long id; /** * The number of non-denied bookings (meaning all granted and requested bookings) */ @JsonView(View.SeminarDetailsView.class) @ApiModelProperty(notes = SwaggerTexts.ACTIVE_BOOKINGS) private int activeBookings; @JsonView(View.SeminarDetailsView.class) private Date created; @JsonView(View.SeminarDetailsView.class) private boolean billGenerated; @JsonView(View.SeminarDetailsView.class) private Date updated; }
27.787879
85
0.76663