hexsha
stringlengths 40
40
| size
int64 3
1.05M
| ext
stringclasses 1
value | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 5
1.02k
| max_stars_repo_name
stringlengths 4
126
| max_stars_repo_head_hexsha
stringlengths 40
78
| max_stars_repo_licenses
sequence | max_stars_count
float64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 5
1.02k
| max_issues_repo_name
stringlengths 4
114
| max_issues_repo_head_hexsha
stringlengths 40
78
| max_issues_repo_licenses
sequence | max_issues_count
float64 1
92.2k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 5
1.02k
| max_forks_repo_name
stringlengths 4
136
| max_forks_repo_head_hexsha
stringlengths 40
78
| max_forks_repo_licenses
sequence | max_forks_count
float64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | avg_line_length
float64 2.55
99.9
| max_line_length
int64 3
1k
| alphanum_fraction
float64 0.25
1
| index
int64 0
1M
| content
stringlengths 3
1.05M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9243834873a3f62b39bfdb705e9795b6cd3d736f | 2,917 | java | Java | jugevents/src/main/java/it/jugpadova/controllers/JCaptchaController.java | jugevents/jugevents | e2a59bae342a0e772e28ab60526d2d68835d468f | [
"Apache-2.0"
] | null | null | null | jugevents/src/main/java/it/jugpadova/controllers/JCaptchaController.java | jugevents/jugevents | e2a59bae342a0e772e28ab60526d2d68835d468f | [
"Apache-2.0"
] | null | null | null | jugevents/src/main/java/it/jugpadova/controllers/JCaptchaController.java | jugevents/jugevents | e2a59bae342a0e772e28ab60526d2d68835d468f | [
"Apache-2.0"
] | null | null | null | 36.4625 | 91 | 0.731231 | 1,002,679 | // Copyright 2006-2008 The Parancoe 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 it.jugpadova.controllers;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.octo.captcha.service.image.ImageCaptchaService;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* A controller for managing jcaptcha verification.
*
* @author lucio
*/
@Controller
@RequestMapping("/jcaptcha/*.html")
public class JCaptchaController {
private static final Logger logger = Logger.getLogger(
JCaptchaController.class);
@Autowired
private ImageCaptchaService captchaService;
@RequestMapping
public void image(HttpServletRequest req, HttpServletResponse res)
throws IOException {
byte[] captchaChallengeAsJpeg = null;
// the output stream to render the captcha image as jpeg into
ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
// get the session id that will identify the generated captcha.
//the same id must be used to validate the res, the session id is a good candidate!
String captchaId = req.getSession().getId();
// call the ImageCaptchaService getChallenge method
BufferedImage challenge = captchaService.getImageChallengeForID(
captchaId, req.getLocale());
// a jpeg encoder
JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(
jpegOutputStream);
jpegEncoder.encode(challenge);
captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
// flush it in the res
res.setHeader("Cache-Control", "no-store");
res.setHeader("Pragma", "no-cache");
res.setDateHeader("Expires", 0);
res.setContentType("image/jpeg");
ServletOutputStream resOutputStream = res.getOutputStream();
resOutputStream.write(captchaChallengeAsJpeg);
resOutputStream.flush();
resOutputStream.close();
}
}
|
924383777edc16860bfbeed9d5adb8c8afafe335 | 360 | java | Java | src/edu/columbia/cs/psl/vmvm/VMState.java | Programming-Systems-Lab/archived-VMVM | 64f3438acd6ffc0949757e15fd7159bb0f33e3a5 | [
"Unlicense",
"MIT"
] | null | null | null | src/edu/columbia/cs/psl/vmvm/VMState.java | Programming-Systems-Lab/archived-VMVM | 64f3438acd6ffc0949757e15fd7159bb0f33e3a5 | [
"Unlicense",
"MIT"
] | null | null | null | src/edu/columbia/cs/psl/vmvm/VMState.java | Programming-Systems-Lab/archived-VMVM | 64f3438acd6ffc0949757e15fd7159bb0f33e3a5 | [
"Unlicense",
"MIT"
] | null | null | null | 16.363636 | 48 | 0.655556 | 1,002,680 | package edu.columbia.cs.psl.vmvm;
public class VMState {
int vmID;
int originalVMID;
public VMState(int state, int originalState) {
this.vmID = state;
this.originalVMID = originalState;
}
void setState(int state) {
this.vmID = state;
}
public void deVM()
{
vmID = originalVMID;
}
public int getState() {
return vmID;
}
}
|
924384001b5e62c719d5356d1e5f1ae98670774f | 2,182 | java | Java | mowang-shop-product/src/main/java/top/mowang/shop/product/controller/AttrAttrgroupRelationController.java | mowangblog/MoWang-Shop | 3631fe6c2417f7524214988559c651f428e22976 | [
"MIT"
] | null | null | null | mowang-shop-product/src/main/java/top/mowang/shop/product/controller/AttrAttrgroupRelationController.java | mowangblog/MoWang-Shop | 3631fe6c2417f7524214988559c651f428e22976 | [
"MIT"
] | null | null | null | mowang-shop-product/src/main/java/top/mowang/shop/product/controller/AttrAttrgroupRelationController.java | mowangblog/MoWang-Shop | 3631fe6c2417f7524214988559c651f428e22976 | [
"MIT"
] | null | null | null | 25.670588 | 95 | 0.722731 | 1,002,681 | package top.mowang.shop.product.controller;
import java.util.Arrays;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import top.mowang.shop.product.entity.AttrAttrgroupRelationEntity;
import top.mowang.shop.product.service.AttrAttrgroupRelationService;
import top.mowang.shop.common.utils.PageUtils;
import top.mowang.shop.common.utils.R;
/**
* 属性&属性分组关联
*
* @author mowang
* @email [email protected]
* @date 2021-11-06 23:40:27
*/
@RestController
@RequestMapping("product/attrattrgrouprelation")
public class AttrAttrgroupRelationController {
@Autowired
private AttrAttrgroupRelationService attrAttrgroupRelationService;
/**
* 列表
*/
@RequestMapping("/list")
public R list(@RequestParam Map<String, Object> params){
PageUtils page = attrAttrgroupRelationService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 信息
*/
@RequestMapping("/info/{id}")
public R info(@PathVariable("id") Long id){
AttrAttrgroupRelationEntity attrAttrgroupRelation = attrAttrgroupRelationService.getById(id);
return R.ok().put("attrAttrgroupRelation", attrAttrgroupRelation);
}
/**
* 保存
*/
@RequestMapping("/save")
public R save(@RequestBody AttrAttrgroupRelationEntity attrAttrgroupRelation){
attrAttrgroupRelationService.save(attrAttrgroupRelation);
return R.ok();
}
/**
* 修改
*/
@RequestMapping("/update")
public R update(@RequestBody AttrAttrgroupRelationEntity attrAttrgroupRelation){
attrAttrgroupRelationService.updateById(attrAttrgroupRelation);
return R.ok();
}
/**
* 删除
*/
@RequestMapping("/delete")
public R delete(@RequestBody Long[] ids){
attrAttrgroupRelationService.removeByIds(Arrays.asList(ids));
return R.ok();
}
}
|
9243841ee1ef203fe108c522da0c4a0a7c56cb1c | 1,591 | java | Java | data-prepper-plugins/peer-forwarder/src/test/java/com/amazon/dataprepper/plugins/prepper/peerforwarder/certificate/file/FileCertificateProviderTest.java | mohitsaxenaknoldus/data-prepper | aaae10daaff45de98c263b04bcf66ea69a83e78f | [
"Apache-2.0"
] | 57 | 2021-04-20T18:07:01.000Z | 2022-03-31T13:19:05.000Z | data-prepper-plugins/peer-forwarder/src/test/java/com/amazon/dataprepper/plugins/prepper/peerforwarder/certificate/file/FileCertificateProviderTest.java | mohitsaxenaknoldus/data-prepper | aaae10daaff45de98c263b04bcf66ea69a83e78f | [
"Apache-2.0"
] | 949 | 2021-04-21T20:51:30.000Z | 2022-03-31T21:35:06.000Z | data-prepper-plugins/peer-forwarder/src/test/java/com/amazon/dataprepper/plugins/prepper/peerforwarder/certificate/file/FileCertificateProviderTest.java | cmanning09/data-prepper | 4e3394859cce8e6d5956e09507f66af73eeec249 | [
"Apache-2.0"
] | 41 | 2021-04-21T19:42:50.000Z | 2022-03-30T21:00:45.000Z | 33.145833 | 132 | 0.782527 | 1,002,682 | /*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/
package com.amazon.dataprepper.plugins.prepper.peerforwarder.certificate.file;
import com.amazon.dataprepper.plugins.prepper.peerforwarder.certificate.model.Certificate;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
@RunWith(MockitoJUnitRunner.class)
public class FileCertificateProviderTest {
private FileCertificateProvider fileCertificateProvider;
@Test
public void getCertificateValidPathSuccess() throws IOException {
final String certificateFilePath = FileCertificateProviderTest.class.getClassLoader().getResource("test-crt.crt").getPath();
fileCertificateProvider = new FileCertificateProvider(certificateFilePath);
final Certificate certificate = fileCertificateProvider.getCertificate();
final Path certFilePath = Path.of(certificateFilePath);
final String certAsString = Files.readString(certFilePath);
assertThat(certificate.getCertificate(), is(certAsString));
}
@Test(expected = RuntimeException.class)
public void getCertificateInvalidPathSuccess() {
final String certificateFilePath = "path_does_not_exit/test_cert.crt";
fileCertificateProvider = new FileCertificateProvider(certificateFilePath);
fileCertificateProvider.getCertificate();
}
}
|
9243844904890fee1f980954f1628a301f5e6260 | 3,946 | java | Java | src/main/java/com/leantaas/graph_representation/GraphNode.java | bovetliu/configured-row-mapper | f19da7c7fa26c8332cbe2a718715ec39053f7335 | [
"Unlicense"
] | null | null | null | src/main/java/com/leantaas/graph_representation/GraphNode.java | bovetliu/configured-row-mapper | f19da7c7fa26c8332cbe2a718715ec39053f7335 | [
"Unlicense"
] | null | null | null | src/main/java/com/leantaas/graph_representation/GraphNode.java | bovetliu/configured-row-mapper | f19da7c7fa26c8332cbe2a718715ec39053f7335 | [
"Unlicense"
] | null | null | null | 29.014706 | 119 | 0.596553 | 1,002,683 | package com.leantaas.graph_representation;
import com.sun.istack.internal.Nullable;
import java.util.function.BiFunction;
/**
* Graph node is not stored in DB
* By default they all handles integer
* Created by boweiliu on 12/11/16.
*/
public class GraphNode {
public final String graphNodeId;
@Nullable protected GraphNode fromNode1;
@Nullable protected GraphNode fromNode2;
@Nullable protected String output;
public BiFunction<String, String, String> biFunction;
public GraphNode(String graphNodeIdParam) {
if (graphNodeIdParam == null || graphNodeIdParam.isEmpty()) {
throw new IllegalArgumentException("graphNodeIdParam cannot be null or empty");
}
graphNodeId = graphNodeIdParam;
}
public void addFromNode(GraphNode oneFromNode) {
if (fromNode1 == null) {
fromNode1 = oneFromNode;
return;
}
if (fromNode2 == null) {
fromNode2 = oneFromNode;
return;
}
throw new IllegalStateException(
String.format("graph node %s has more than two incoming nodes, which is illegal",
graphNodeId));
}
public BiFunction<String, String, String> getBiFunction() {
return biFunction;
}
public void setBiFunction(BiFunction<String, String, String> biFunction) {
if (this.biFunction != null) {
throw new IllegalStateException("one node cannot have two descriptive edge");
}
this.biFunction = biFunction;
}
/**
* Compute output of this node using DFS.
* @return nullable computed string of output of this node
*/
public @Nullable String computeOutput() {
if (fromNode1 == null && fromNode2 == null && output == null) {
throw new IllegalStateException(String.format("input-node: %s has no initial value when doing row mapping",
graphNodeId));
}
if (output == null) {
String outputFromNode1 = fromNode1 != null ? fromNode1.computeOutput() : null;
String outputFromNode2 = fromNode2 != null ? fromNode2.computeOutput() : null;
output = biFunction.apply(outputFromNode1, outputFromNode2);
}
return output;
}
// directed-first-search clear output
public void clearOutput() {
if (output != null) {
output = null;
if (fromNode1 != null && fromNode1.output != null) {
fromNode1.clearOutput();
}
if (fromNode2 != null && fromNode2.output != null) {
fromNode2.clearOutput();
}
}
}
public void setOutput(@Nullable String nodeOutputParam) {
output = nodeOutputParam;
}
public String prettyPrintNode() {
if (fromNode1 == null && fromNode2 == null) {
return String.format("id %s, input-node", graphNodeId);
}
return String.format("id: %s, fromNodeId1: %s, fromNodeId2: %s",
graphNodeId,
fromNode1 != null ? fromNode1.graphNodeId : "null",
fromNode2 != null ? fromNode2.graphNodeId : "null");
}
public @Nullable GraphNode getFromNode1() {
return fromNode1;
}
public void setFromNode1(GraphNode fromNode1) {
this.fromNode1 = fromNode1;
}
public @Nullable GraphNode getFromNode2() {
return fromNode2;
}
public void setFromNode2(GraphNode fromNode2) {
this.fromNode2 = fromNode2;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof GraphNode)) {
return false;
}
GraphNode graphNode = (GraphNode) o;
return graphNodeId.equals(graphNode.graphNodeId);
}
@Override
public int hashCode() {
return graphNodeId.hashCode();
}
}
|
924384ebff16ec4a0a0ac62de2d0d49548edde15 | 28,056 | java | Java | Minecraft/build/sources/main/java/com/microsoft/Malmo/Schemas/MazeDecorator.java | shaw-wong/Malmo | 2683891206e8ab7f015d5d0feb6b5a967f02c94f | [
"MIT"
] | 1 | 2018-03-21T01:32:21.000Z | 2018-03-21T01:32:21.000Z | Minecraft/build/sources/main/java/com/microsoft/Malmo/Schemas/MazeDecorator.java | shaw-wong/Malmo | 2683891206e8ab7f015d5d0feb6b5a967f02c94f | [
"MIT"
] | 1 | 2018-03-20T04:35:37.000Z | 2018-03-20T04:35:37.000Z | Minecraft/build/sources/main/java/com/microsoft/Malmo/Schemas/MazeDecorator.java | shaw-wong/Malmo | 2683891206e8ab7f015d5d0feb6b5a967f02c94f | [
"MIT"
] | null | null | null | 27.750742 | 114 | 0.523845 | 1,002,684 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2018.05.24 at 02:50:23 PM AEST
//
package com.microsoft.Malmo.Schemas;
import java.math.BigDecimal;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <all>
* <element name="Seed">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <pattern value="random|[0-9]+"/>
* </restriction>
* </simpleType>
* </element>
* <element name="MaterialSeed" minOccurs="0">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <pattern value="random|[0-9]+"/>
* </restriction>
* </simpleType>
* </element>
* <element name="AllowDiagonalMovement" type="{http://www.w3.org/2001/XMLSchema}boolean"/>
* <element name="SizeAndPosition">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <attribute name="width" type="{http://www.w3.org/2001/XMLSchema}int" default="10" />
* <attribute name="length" type="{http://www.w3.org/2001/XMLSchema}int" default="10" />
* <attribute name="height" type="{http://www.w3.org/2001/XMLSchema}int" default="100" />
* <attribute name="scale" type="{http://www.w3.org/2001/XMLSchema}int" default="1" />
* <attribute name="xOrigin" type="{http://www.w3.org/2001/XMLSchema}int" default="0" />
* <attribute name="yOrigin" type="{http://www.w3.org/2001/XMLSchema}int" default="55" />
* <attribute name="zOrigin" type="{http://www.w3.org/2001/XMLSchema}int" default="0" />
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="StartBlock" type="{http://ProjectMalmo.microsoft.com}MazeTerminus"/>
* <element name="EndBlock" type="{http://ProjectMalmo.microsoft.com}MazeTerminus"/>
* <element name="PathBlock" type="{http://ProjectMalmo.microsoft.com}MazeBlock"/>
* <element name="FloorBlock" type="{http://ProjectMalmo.microsoft.com}MazeBlock"/>
* <element name="GapBlock" type="{http://ProjectMalmo.microsoft.com}MazeBlock"/>
* <element name="OptimalPathBlock" type="{http://ProjectMalmo.microsoft.com}MazeBlock" minOccurs="0"/>
* <element name="SubgoalBlock" type="{http://ProjectMalmo.microsoft.com}MazeBlock" minOccurs="0"/>
* <element name="Waypoints" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <choice>
* <element name="WaypointBlock" type="{http://ProjectMalmo.microsoft.com}MazeBlock"/>
* <element name="WaypointItem" type="{http://ProjectMalmo.microsoft.com}BlockOrItemSpec"/>
* </choice>
* <attribute name="quantity" use="required" type="{http://www.w3.org/2001/XMLSchema}int" />
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="GapProbability">
* <complexType>
* <simpleContent>
* <extension base="<http://www.w3.org/2001/XMLSchema>decimal">
* <attribute name="variance" type="{http://www.w3.org/2001/XMLSchema}decimal" default="0" />
* </extension>
* </simpleContent>
* </complexType>
* </element>
* <element name="AddQuitProducer" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <attribute name="description" type="{http://www.w3.org/2001/XMLSchema}string" default="" />
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="AddNavigationObservations" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </all>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
})
@XmlRootElement(name = "MazeDecorator")
public class MazeDecorator {
@XmlElement(name = "Seed", required = true)
protected String seed;
@XmlElement(name = "MaterialSeed")
protected String materialSeed;
@XmlElement(name = "AllowDiagonalMovement", defaultValue = "false")
protected boolean allowDiagonalMovement;
@XmlElement(name = "SizeAndPosition", required = true)
protected MazeDecorator.SizeAndPosition sizeAndPosition;
@XmlElement(name = "StartBlock", required = true)
protected MazeTerminus startBlock;
@XmlElement(name = "EndBlock", required = true)
protected MazeTerminus endBlock;
@XmlElement(name = "PathBlock", required = true)
protected MazeBlock pathBlock;
@XmlElement(name = "FloorBlock", required = true)
protected MazeBlock floorBlock;
@XmlElement(name = "GapBlock", required = true)
protected MazeBlock gapBlock;
@XmlElement(name = "OptimalPathBlock")
protected MazeBlock optimalPathBlock;
@XmlElement(name = "SubgoalBlock")
protected MazeBlock subgoalBlock;
@XmlElement(name = "Waypoints")
protected MazeDecorator.Waypoints waypoints;
@XmlElement(name = "GapProbability", required = true)
protected MazeDecorator.GapProbability gapProbability;
@XmlElement(name = "AddQuitProducer")
protected MazeDecorator.AddQuitProducer addQuitProducer;
@XmlElement(name = "AddNavigationObservations")
protected MazeDecorator.AddNavigationObservations addNavigationObservations;
/**
* Gets the value of the seed property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSeed() {
return seed;
}
/**
* Sets the value of the seed property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSeed(String value) {
this.seed = value;
}
/**
* Gets the value of the materialSeed property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMaterialSeed() {
return materialSeed;
}
/**
* Sets the value of the materialSeed property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMaterialSeed(String value) {
this.materialSeed = value;
}
/**
* Gets the value of the allowDiagonalMovement property.
*
*/
public boolean isAllowDiagonalMovement() {
return allowDiagonalMovement;
}
/**
* Sets the value of the allowDiagonalMovement property.
*
*/
public void setAllowDiagonalMovement(boolean value) {
this.allowDiagonalMovement = value;
}
/**
* Gets the value of the sizeAndPosition property.
*
* @return
* possible object is
* {@link MazeDecorator.SizeAndPosition }
*
*/
public MazeDecorator.SizeAndPosition getSizeAndPosition() {
return sizeAndPosition;
}
/**
* Sets the value of the sizeAndPosition property.
*
* @param value
* allowed object is
* {@link MazeDecorator.SizeAndPosition }
*
*/
public void setSizeAndPosition(MazeDecorator.SizeAndPosition value) {
this.sizeAndPosition = value;
}
/**
* Gets the value of the startBlock property.
*
* @return
* possible object is
* {@link MazeTerminus }
*
*/
public MazeTerminus getStartBlock() {
return startBlock;
}
/**
* Sets the value of the startBlock property.
*
* @param value
* allowed object is
* {@link MazeTerminus }
*
*/
public void setStartBlock(MazeTerminus value) {
this.startBlock = value;
}
/**
* Gets the value of the endBlock property.
*
* @return
* possible object is
* {@link MazeTerminus }
*
*/
public MazeTerminus getEndBlock() {
return endBlock;
}
/**
* Sets the value of the endBlock property.
*
* @param value
* allowed object is
* {@link MazeTerminus }
*
*/
public void setEndBlock(MazeTerminus value) {
this.endBlock = value;
}
/**
* Gets the value of the pathBlock property.
*
* @return
* possible object is
* {@link MazeBlock }
*
*/
public MazeBlock getPathBlock() {
return pathBlock;
}
/**
* Sets the value of the pathBlock property.
*
* @param value
* allowed object is
* {@link MazeBlock }
*
*/
public void setPathBlock(MazeBlock value) {
this.pathBlock = value;
}
/**
* Gets the value of the floorBlock property.
*
* @return
* possible object is
* {@link MazeBlock }
*
*/
public MazeBlock getFloorBlock() {
return floorBlock;
}
/**
* Sets the value of the floorBlock property.
*
* @param value
* allowed object is
* {@link MazeBlock }
*
*/
public void setFloorBlock(MazeBlock value) {
this.floorBlock = value;
}
/**
* Gets the value of the gapBlock property.
*
* @return
* possible object is
* {@link MazeBlock }
*
*/
public MazeBlock getGapBlock() {
return gapBlock;
}
/**
* Sets the value of the gapBlock property.
*
* @param value
* allowed object is
* {@link MazeBlock }
*
*/
public void setGapBlock(MazeBlock value) {
this.gapBlock = value;
}
/**
* Gets the value of the optimalPathBlock property.
*
* @return
* possible object is
* {@link MazeBlock }
*
*/
public MazeBlock getOptimalPathBlock() {
return optimalPathBlock;
}
/**
* Sets the value of the optimalPathBlock property.
*
* @param value
* allowed object is
* {@link MazeBlock }
*
*/
public void setOptimalPathBlock(MazeBlock value) {
this.optimalPathBlock = value;
}
/**
* Gets the value of the subgoalBlock property.
*
* @return
* possible object is
* {@link MazeBlock }
*
*/
public MazeBlock getSubgoalBlock() {
return subgoalBlock;
}
/**
* Sets the value of the subgoalBlock property.
*
* @param value
* allowed object is
* {@link MazeBlock }
*
*/
public void setSubgoalBlock(MazeBlock value) {
this.subgoalBlock = value;
}
/**
* Gets the value of the waypoints property.
*
* @return
* possible object is
* {@link MazeDecorator.Waypoints }
*
*/
public MazeDecorator.Waypoints getWaypoints() {
return waypoints;
}
/**
* Sets the value of the waypoints property.
*
* @param value
* allowed object is
* {@link MazeDecorator.Waypoints }
*
*/
public void setWaypoints(MazeDecorator.Waypoints value) {
this.waypoints = value;
}
/**
* Gets the value of the gapProbability property.
*
* @return
* possible object is
* {@link MazeDecorator.GapProbability }
*
*/
public MazeDecorator.GapProbability getGapProbability() {
return gapProbability;
}
/**
* Sets the value of the gapProbability property.
*
* @param value
* allowed object is
* {@link MazeDecorator.GapProbability }
*
*/
public void setGapProbability(MazeDecorator.GapProbability value) {
this.gapProbability = value;
}
/**
* Gets the value of the addQuitProducer property.
*
* @return
* possible object is
* {@link MazeDecorator.AddQuitProducer }
*
*/
public MazeDecorator.AddQuitProducer getAddQuitProducer() {
return addQuitProducer;
}
/**
* Sets the value of the addQuitProducer property.
*
* @param value
* allowed object is
* {@link MazeDecorator.AddQuitProducer }
*
*/
public void setAddQuitProducer(MazeDecorator.AddQuitProducer value) {
this.addQuitProducer = value;
}
/**
* Gets the value of the addNavigationObservations property.
*
* @return
* possible object is
* {@link MazeDecorator.AddNavigationObservations }
*
*/
public MazeDecorator.AddNavigationObservations getAddNavigationObservations() {
return addNavigationObservations;
}
/**
* Sets the value of the addNavigationObservations property.
*
* @param value
* allowed object is
* {@link MazeDecorator.AddNavigationObservations }
*
*/
public void setAddNavigationObservations(MazeDecorator.AddNavigationObservations value) {
this.addNavigationObservations = value;
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
public static class AddNavigationObservations {
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <attribute name="description" type="{http://www.w3.org/2001/XMLSchema}string" default="" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
public static class AddQuitProducer {
@XmlAttribute(name = "description")
protected String description;
/**
* Gets the value of the description property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDescription() {
if (description == null) {
return "";
} else {
return description;
}
}
/**
* Sets the value of the description property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDescription(String value) {
this.description = value;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <simpleContent>
* <extension base="<http://www.w3.org/2001/XMLSchema>decimal">
* <attribute name="variance" type="{http://www.w3.org/2001/XMLSchema}decimal" default="0" />
* </extension>
* </simpleContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"value"
})
public static class GapProbability {
@XmlValue
protected BigDecimal value;
@XmlAttribute(name = "variance")
protected BigDecimal variance;
/**
* Gets the value of the value property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setValue(BigDecimal value) {
this.value = value;
}
/**
* Gets the value of the variance property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getVariance() {
if (variance == null) {
return new BigDecimal("0");
} else {
return variance;
}
}
/**
* Sets the value of the variance property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setVariance(BigDecimal value) {
this.variance = value;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <attribute name="width" type="{http://www.w3.org/2001/XMLSchema}int" default="10" />
* <attribute name="length" type="{http://www.w3.org/2001/XMLSchema}int" default="10" />
* <attribute name="height" type="{http://www.w3.org/2001/XMLSchema}int" default="100" />
* <attribute name="scale" type="{http://www.w3.org/2001/XMLSchema}int" default="1" />
* <attribute name="xOrigin" type="{http://www.w3.org/2001/XMLSchema}int" default="0" />
* <attribute name="yOrigin" type="{http://www.w3.org/2001/XMLSchema}int" default="55" />
* <attribute name="zOrigin" type="{http://www.w3.org/2001/XMLSchema}int" default="0" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
public static class SizeAndPosition {
@XmlAttribute(name = "width")
protected Integer width;
@XmlAttribute(name = "length")
protected Integer length;
@XmlAttribute(name = "height")
protected Integer height;
@XmlAttribute(name = "scale")
protected Integer scale;
@XmlAttribute(name = "xOrigin")
protected Integer xOrigin;
@XmlAttribute(name = "yOrigin")
protected Integer yOrigin;
@XmlAttribute(name = "zOrigin")
protected Integer zOrigin;
/**
* Gets the value of the width property.
*
* @return
* possible object is
* {@link Integer }
*
*/
public int getWidth() {
if (width == null) {
return 10;
} else {
return width;
}
}
/**
* Sets the value of the width property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setWidth(Integer value) {
this.width = value;
}
/**
* Gets the value of the length property.
*
* @return
* possible object is
* {@link Integer }
*
*/
public int getLength() {
if (length == null) {
return 10;
} else {
return length;
}
}
/**
* Sets the value of the length property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setLength(Integer value) {
this.length = value;
}
/**
* Gets the value of the height property.
*
* @return
* possible object is
* {@link Integer }
*
*/
public int getHeight() {
if (height == null) {
return 100;
} else {
return height;
}
}
/**
* Sets the value of the height property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setHeight(Integer value) {
this.height = value;
}
/**
* Gets the value of the scale property.
*
* @return
* possible object is
* {@link Integer }
*
*/
public int getScale() {
if (scale == null) {
return 1;
} else {
return scale;
}
}
/**
* Sets the value of the scale property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setScale(Integer value) {
this.scale = value;
}
/**
* Gets the value of the xOrigin property.
*
* @return
* possible object is
* {@link Integer }
*
*/
public int getXOrigin() {
if (xOrigin == null) {
return 0;
} else {
return xOrigin;
}
}
/**
* Sets the value of the xOrigin property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setXOrigin(Integer value) {
this.xOrigin = value;
}
/**
* Gets the value of the yOrigin property.
*
* @return
* possible object is
* {@link Integer }
*
*/
public int getYOrigin() {
if (yOrigin == null) {
return 55;
} else {
return yOrigin;
}
}
/**
* Sets the value of the yOrigin property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setYOrigin(Integer value) {
this.yOrigin = value;
}
/**
* Gets the value of the zOrigin property.
*
* @return
* possible object is
* {@link Integer }
*
*/
public int getZOrigin() {
if (zOrigin == null) {
return 0;
} else {
return zOrigin;
}
}
/**
* Sets the value of the zOrigin property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setZOrigin(Integer value) {
this.zOrigin = value;
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <choice>
* <element name="WaypointBlock" type="{http://ProjectMalmo.microsoft.com}MazeBlock"/>
* <element name="WaypointItem" type="{http://ProjectMalmo.microsoft.com}BlockOrItemSpec"/>
* </choice>
* <attribute name="quantity" use="required" type="{http://www.w3.org/2001/XMLSchema}int" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"waypointBlock",
"waypointItem"
})
public static class Waypoints {
@XmlElement(name = "WaypointBlock")
protected MazeBlock waypointBlock;
@XmlElement(name = "WaypointItem")
protected BlockOrItemSpec waypointItem;
@XmlAttribute(name = "quantity", required = true)
protected int quantity;
/**
* Gets the value of the waypointBlock property.
*
* @return
* possible object is
* {@link MazeBlock }
*
*/
public MazeBlock getWaypointBlock() {
return waypointBlock;
}
/**
* Sets the value of the waypointBlock property.
*
* @param value
* allowed object is
* {@link MazeBlock }
*
*/
public void setWaypointBlock(MazeBlock value) {
this.waypointBlock = value;
}
/**
* Gets the value of the waypointItem property.
*
* @return
* possible object is
* {@link BlockOrItemSpec }
*
*/
public BlockOrItemSpec getWaypointItem() {
return waypointItem;
}
/**
* Sets the value of the waypointItem property.
*
* @param value
* allowed object is
* {@link BlockOrItemSpec }
*
*/
public void setWaypointItem(BlockOrItemSpec value) {
this.waypointItem = value;
}
/**
* Gets the value of the quantity property.
*
*/
public int getQuantity() {
return quantity;
}
/**
* Sets the value of the quantity property.
*
*/
public void setQuantity(int value) {
this.quantity = value;
}
}
}
|
92438617f910b21462666dbab05cc3535c4a1fe3 | 616 | java | Java | src/main/java/leetcode/solutions/July Code/MaximumLengthRepeatedSubarray.java | BrahianVT/LeetcodeProblems | 8346f2df6727aff7968419d74b95715954f70029 | [
"RSA-MD"
] | null | null | null | src/main/java/leetcode/solutions/July Code/MaximumLengthRepeatedSubarray.java | BrahianVT/LeetcodeProblems | 8346f2df6727aff7968419d74b95715954f70029 | [
"RSA-MD"
] | null | null | null | src/main/java/leetcode/solutions/July Code/MaximumLengthRepeatedSubarray.java | BrahianVT/LeetcodeProblems | 8346f2df6727aff7968419d74b95715954f70029 | [
"RSA-MD"
] | null | null | null | 19.870968 | 67 | 0.581169 | 1,002,685 |
package leetcode.solutions;
import java.util.*;
/*
Problem : 8
Number leecode problem: 718
https://leetcode.com/problems/maximum-length-of-repeated-subarray/
Time Complexity: O(nm)
Space Complexity: O(nm)
*/
public class MaximumLengthRepeatedSubarray{
public int findLength(int[] nums1, int[] nums2){
int n = nums1.length, m = nums2.length;
int[][] dp = new int[n + 1][m +1];
int res =0;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
if(nums1[i-1] == nums2[j-1]){
dp[i][j] = dp[i-1][j-1] + 1;
res = Math.max(res, dp[i][j]);
}
}
}
return res;
}
} |
9243865288278e6da4025af677c515c948339c71 | 1,485 | java | Java | src/main/java/cn/stranded/config/MyBatisConfig.java | kuwoo/MultiDataSource | 9c8e950cd024412ab2eb8382afae500f81a1a41d | [
"Apache-2.0"
] | null | null | null | src/main/java/cn/stranded/config/MyBatisConfig.java | kuwoo/MultiDataSource | 9c8e950cd024412ab2eb8382afae500f81a1a41d | [
"Apache-2.0"
] | null | null | null | src/main/java/cn/stranded/config/MyBatisConfig.java | kuwoo/MultiDataSource | 9c8e950cd024412ab2eb8382afae500f81a1a41d | [
"Apache-2.0"
] | null | null | null | 37.125 | 132 | 0.803367 | 1,002,686 | package cn.stranded.config;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.annotation.Resource;
import javax.sql.DataSource;
@EnableTransactionManagement
@Configuration
public class MyBatisConfig {
@Resource(name = "myRoutingDataSource")
private DataSource myRoutingDataSource;
/**
* 扫描mybatis下的xml文件
*
* @return
* @throws Exception
*/
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(myRoutingDataSource);
sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/*.xml"));
return sqlSessionFactoryBean.getObject();
}
@Bean
public PlatformTransactionManager platformTransactionManager() {
return new DataSourceTransactionManager(myRoutingDataSource);//由于Spring容器中现在有4个数据源,所以我们需要为事务管理器和MyBatis手动指定一个明确的数据源。
}
}
|
924386927261665256491e8285fff97a4fe5ad0d | 2,282 | java | Java | Java/00-Code/Java-CompilerAPI/JavaCompiler/src/main/java/me/ztiany/compiler/jsr269/ElementVisitProcessor.java | hiloWang/notes | 64a637a86f734e4e80975f4aa93ab47e8d7e8b64 | [
"Apache-2.0"
] | 2 | 2020-10-08T13:22:08.000Z | 2021-07-28T14:45:41.000Z | Java/Java-CompilerAPI/JavaCompiler/src/main/java/me/ztiany/compiler/jsr269/ElementVisitProcessor.java | flyfire/Programming-Notes-Code | 4b1bdd74c1ba0c007c504834e4508ec39f01cd94 | [
"Apache-2.0"
] | null | null | null | Java/Java-CompilerAPI/JavaCompiler/src/main/java/me/ztiany/compiler/jsr269/ElementVisitProcessor.java | flyfire/Programming-Notes-Code | 4b1bdd74c1ba0c007c504834e4508ec39f01cd94 | [
"Apache-2.0"
] | 6 | 2020-08-20T07:19:17.000Z | 2022-03-02T08:16:21.000Z | 34.059701 | 102 | 0.702016 | 1,002,687 | package me.ztiany.compiler.jsr269;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.util.ElementScanner7;
//指定支持的java版本
@SupportedSourceVersion(SourceVersion.RELEASE_7)
//表示该处理器用于处理哪些注解,这里表示处理所有元素
@SupportedAnnotationTypes("*")
public class ElementVisitProcessor extends AbstractProcessor {
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
}
/**
* 该方法是注解处理器处理注解的主要地方,我们需要在这里写扫描和处理注解的代码, 以及最终生成的java文件。其中需要深入的是RoundEnvironment类,该用于查找出程序元素上使用的注解
*/
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
Scanner scanner = new Scanner();
if (!roundEnv.processingOver()) {
for (Element element : roundEnv.getRootElements()) {
scanner.scan(element);
}
}
return true;
}
public class Scanner extends ElementScanner7<Void, Void> {
public Void visitType(TypeElement element, Void p) {
System.out.println("类 " + element.getKind() + ": " + element.getSimpleName());
return super.visitType(element, p);
}
public Void visitExecutable(ExecutableElement element, Void p) {
System.out.println("方法 " + element.getKind() + ": " + element.getSimpleName());
return super.visitExecutable(element, p);
}
public Void visitVariable(VariableElement element, Void p) {
if (element.getEnclosingElement().getKind() == ElementKind.CLASS) {
System.out.println("字段 " + element.getKind() + ": " + element.getSimpleName());
}
return super.visitVariable(element, p);
}
}
}
|
924388ab98b1802b18abd06aaad1b4a5ef232f59 | 546 | java | Java | dtm/dtm-file/src/main/java/org/modelinglab/actiongui/netbeans/dtm/file/package-info.java | modelinglab/actiongui-netbeans-modules | a876c8ca694826a265eeeb9ead939170a696578f | [
"MIT"
] | null | null | null | dtm/dtm-file/src/main/java/org/modelinglab/actiongui/netbeans/dtm/file/package-info.java | modelinglab/actiongui-netbeans-modules | a876c8ca694826a265eeeb9ead939170a696578f | [
"MIT"
] | null | null | null | dtm/dtm-file/src/main/java/org/modelinglab/actiongui/netbeans/dtm/file/package-info.java | modelinglab/actiongui-netbeans-modules | a876c8ca694826a265eeeb9ead939170a696578f | [
"MIT"
] | null | null | null | 42 | 127 | 0.754579 | 1,002,688 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
@TemplateRegistrations(value = {
@TemplateRegistration(folder = "Samples/ActionGUI", content = "example.dtm", displayName = "Example DTM", position = 1000),
@TemplateRegistration(folder = "ActionGUI", content = "empty.dtm", displayName = "Empty DTM", position = 1000)
})
package org.modelinglab.actiongui.netbeans.dtm.file;
import org.netbeans.api.templates.TemplateRegistration;
import org.netbeans.api.templates.TemplateRegistrations;
|
92438921a6b624a615ac9d0906b0815c35cadaac | 4,302 | java | Java | src/test/java/com/thinkgem/jeesite/activiti/ObjectionTest.java | yisheng4666/jeesite-master_hibernate | 7ac50ba022a8d581806d3b072764aeb94ece2d6a | [
"Apache-2.0"
] | null | null | null | src/test/java/com/thinkgem/jeesite/activiti/ObjectionTest.java | yisheng4666/jeesite-master_hibernate | 7ac50ba022a8d581806d3b072764aeb94ece2d6a | [
"Apache-2.0"
] | null | null | null | src/test/java/com/thinkgem/jeesite/activiti/ObjectionTest.java | yisheng4666/jeesite-master_hibernate | 7ac50ba022a8d581806d3b072764aeb94ece2d6a | [
"Apache-2.0"
] | null | null | null | 39.109091 | 139 | 0.70874 | 1,002,689 | package com.thinkgem.jeesite.activiti;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.test.Deployment;
import org.activiti.spring.impl.test.SpringActivitiTestCase;
import org.junit.Test;
import org.springframework.test.context.ContextConfiguration;
@ContextConfiguration("classpath:applicationContext-test-activiti.xml")
public class ObjectionTest extends SpringActivitiTestCase {
/**
* 测试接受响应
*/
@Test
@Deployment(resources = "diagrams/objection.bpmn")
public void testAcceptResult() throws Exception {
// 验证是否部署成功
long count = repositoryService.createProcessDefinitionQuery().processDefinitionKey("objection").count();
assertEquals(1, count);
ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionKey("objection").singleResult();
// 设置当前用户
String currentUserId = "testUserId";
identityService.setAuthenticatedUserId(currentUserId);
// 用于传递参数
Map<String, Object> variables4Process = new HashMap<String, Object>();
variables4Process.put("respondUserId", "respondUserId");
variables4Process.put("judgeUserId", "judgeUserId");
// 启动流程
ProcessInstance processInstance = runtimeService.startProcessInstanceById(processDefinition.getId(),variables4Process);
assertNotNull(processInstance);
// 任务
Task task = taskService.createTaskQuery().taskAssignee("respondUserId").singleResult();
assertNotNull(task);
assertEquals("评分单位响应", task.getName());
taskService.complete(task.getId());
task = taskService.createTaskQuery().taskAssignee("testUserId").singleResult();
assertNotNull(task);
assertEquals("复核响应", task.getName());
variables4Process.clear();
variables4Process.put("acceptResult", true);
taskService.complete(task.getId(),variables4Process);
// 验证流程是否已经结束
ProcessInstance temp = runtimeService.createProcessInstanceQuery().processInstanceId(processInstance.getId()).singleResult();
assertNull(temp);
}
/**
* 测试申请裁定
*/
@Test
@Deployment(resources = "diagrams/objection.bpmn")
public void testJudge() throws Exception {
// 验证是否部署成功
long count = repositoryService.createProcessDefinitionQuery().processDefinitionKey("objection").count();
assertEquals(1, count);
ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionKey("objection").singleResult();
// 设置当前用户
String currentUserId = "testUserId";
identityService.setAuthenticatedUserId(currentUserId);
// 用于传递参数
Map<String, Object> variables4Process = new HashMap<String, Object>();
variables4Process.put("respondUserId", "respondUserId");
variables4Process.put("judgeUserId", "judgeUserId");
// 启动流程
ProcessInstance processInstance = runtimeService.startProcessInstanceById(processDefinition.getId(),variables4Process);
assertNotNull(processInstance);
// 任务
Task task = taskService.createTaskQuery().taskAssignee("respondUserId").singleResult();
assertNotNull(task);
assertEquals("评分单位响应", task.getName());
taskService.complete(task.getId());
task = taskService.createTaskQuery().taskAssignee("testUserId").singleResult();
assertNotNull(task);
assertEquals("复核响应", task.getName());
variables4Process.clear();
variables4Process.put("acceptResult", false);
taskService.complete(task.getId(),variables4Process);
task = taskService.createTaskQuery().taskAssignee("judgeUserId").singleResult();
assertNotNull(task);
assertEquals("裁定", task.getName());
taskService.complete(task.getId());
// 验证流程是否已经结束
ProcessInstance temp = runtimeService.createProcessInstanceQuery().processInstanceId(processInstance.getId()).singleResult();
assertNull(temp);
}
}
|
924389bc41567fbce85d669090d28bb802668103 | 1,948 | java | Java | Recursion/game-of-death-in-a-circle.java | MaunilN/DSA-for-SDE-interview | 026cf3f53b3a252c33ed5cec95f71dd914f62ad5 | [
"MIT"
] | 15 | 2020-06-22T08:37:01.000Z | 2022-02-13T19:27:54.000Z | Recursion/game-of-death-in-a-circle.java | MaunilN/DSA-for-SDE-interview | 026cf3f53b3a252c33ed5cec95f71dd914f62ad5 | [
"MIT"
] | 3 | 2020-09-30T18:45:43.000Z | 2020-09-30T18:59:08.000Z | Recursion/game-of-death-in-a-circle.java | MaunilN/DSA-for-SDE-interview | 026cf3f53b3a252c33ed5cec95f71dd914f62ad5 | [
"MIT"
] | 16 | 2020-08-27T06:59:46.000Z | 2022-01-06T17:40:30.000Z | 29.074627 | 106 | 0.720739 | 1,002,690 | /*
Game of Death in a circle
There are n people standing in a circle (numbered clockwise 1 to n) waiting to be executed.
The counting begins at point 1 in the circle and proceeds around the circle in a fixed
direction (clockwise). In each step, a certain number of people are skipped and the next
person is executed. The elimination proceeds around the circle (which is becoming smaller
and smaller as the executed people are removed), until only the last person remains, who
is given freedom.
Given the total number of persons n and a number k which indicates that k-1 persons are skipped
and kth person is killed in circle. The task is to choose the place in the initial circle so that
you are the last one remaining and so survive.
Consider if n = 5 and k = 2, then the safe position is 3.
Firstly, the person at position 2 is killed, then person at position 4 is killed, then person at
position 1 is killed. Finally, the person at position 5 is killed. So the person at position 3 survives.
Input:
The first line of input contains a single integer T denoting the number of test cases.
Then T test cases follow. The first and only line of each test case consists of two
space separated positive integers denoting n and k.
Output:
Corresponding to each test case, in a new line, print the safe position.
Constraints:
1 ≤ T ≤ 200
1 ≤ n, k ≤ 200
Example:
Input:
3
2 1
4 2
50 10
Output:
2
1
36
Explanation:
Testcase 1: here n = 2 and k = 1, then safe position is 2 as the person at 1st position will be killed. */
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG {
public static void main (String[] args) {
//code
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-->0)
{
int n = sc.nextInt();
int k = sc.nextInt();
System.out.println(executed(n,k));
}
}
static int executed(int n,int k)
{
if(n<=0) return 0;
return (executed(n-1,k)+k-1)%n + 1;
}
} |
92438a418fd9ee90cf40a7236ab36c3c60f7a17a | 22,826 | java | Java | log4j-core/src/test/java/org/apache/logging/log4j/core/layout/Rfc5424LayoutTest.java | sunbenkang/logging-log4j2 | a0b0cddd662b9b231dd296b88a57d1cd951bfd59 | [
"Apache-2.0"
] | 3,034 | 2015-01-19T14:45:09.000Z | 2022-03-31T06:11:10.000Z | log4j-core/src/test/java/org/apache/logging/log4j/core/layout/Rfc5424LayoutTest.java | sunbenkang/logging-log4j2 | a0b0cddd662b9b231dd296b88a57d1cd951bfd59 | [
"Apache-2.0"
] | 559 | 2015-03-11T15:45:08.000Z | 2022-03-31T17:56:24.000Z | log4j-core/src/test/java/org/apache/logging/log4j/core/layout/Rfc5424LayoutTest.java | sunbenkang/logging-log4j2 | a0b0cddd662b9b231dd296b88a57d1cd951bfd59 | [
"Apache-2.0"
] | 1,620 | 2015-01-31T09:10:08.000Z | 2022-03-31T17:42:41.000Z | 43.727969 | 150 | 0.618812 | 1,002,691 | /*
* 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.logging.log4j.core.layout;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.MarkerManager;
import org.apache.logging.log4j.ThreadContext;
import org.apache.logging.log4j.core.Appender;
import org.apache.logging.log4j.core.test.BasicConfigurationFactory;
import org.apache.logging.log4j.core.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.ConfigurationFactory;
import org.apache.logging.log4j.core.net.Facility;
import org.apache.logging.log4j.core.util.KeyValuePair;
import org.apache.logging.log4j.test.junit.UsingAnyThreadContext;
import org.apache.logging.log4j.message.StructuredDataCollectionMessage;
import org.apache.logging.log4j.message.StructuredDataMessage;
import org.apache.logging.log4j.status.StatusLogger;
import org.apache.logging.log4j.core.test.appender.ListAppender;
import org.apache.logging.log4j.core.util.ProcessIdUtil;
import org.apache.logging.log4j.util.Strings;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
@UsingAnyThreadContext
public class Rfc5424LayoutTest {
LoggerContext ctx = LoggerContext.getContext();
Logger root = ctx.getRootLogger();
private static final String PROCESSID = ProcessIdUtil.getProcessId();
private static final String line1 = String.format("ATM %s - [RequestContext@3692 loginId=\"JohnDoe\"] starting mdc pattern test", PROCESSID);
private static final String line2 = String.format("ATM %s - [RequestContext@3692 loginId=\"JohnDoe\"] empty mdc", PROCESSID);
private static final String line3 = String.format("ATM %s - [RequestContext@3692 loginId=\"JohnDoe\"] filled mdc", PROCESSID);
private static final String line4 =
String.format("ATM %s Audit [Transfer@18060 Amount=\"200.00\" FromAccount=\"123457\" ToAccount=\"123456\"]" +
"[RequestContext@3692 ipAddress=\"192.168.0.120\" loginId=\"JohnDoe\"] Transfer Complete", PROCESSID);
private static final String lineEscaped3 =
String.format("ATM %s - [RequestContext@3692 escaped=\"Testing escaping #012 \\\" \\] \\\"\" loginId=\"JohnDoe\"] filled mdc", PROCESSID);
private static final String lineEscaped4 =
String.format("ATM %s Audit [Transfer@18060 Amount=\"200.00\" FromAccount=\"123457\" ToAccount=\"123456\"]" +
"[RequestContext@3692 escaped=\"Testing escaping #012 \\\" \\] \\\"\" ipAddress=\"192.168.0.120\" loginId=\"JohnDoe\"] Transfer Complete",
PROCESSID);
private static final String collectionLine1 = "[Transfer@18060 Amount=\"200.00\" FromAccount=\"123457\" " +
"ToAccount=\"123456\"]";
private static final String collectionLine2 = "[Extra@18060 Item1=\"Hello\" Item2=\"World\"]";
private static final String collectionLine3 = "[RequestContext@3692 ipAddress=\"192.168.0.120\" loginId=\"JohnDoe\"]";
private static final String collectionEndOfLine = "Transfer Complete";
static ConfigurationFactory cf = new BasicConfigurationFactory();
@BeforeAll
public static void setupClass() {
StatusLogger.getLogger().setLevel(Level.OFF);
ConfigurationFactory.setConfigurationFactory(cf);
final LoggerContext ctx = LoggerContext.getContext();
ctx.reconfigure();
}
@AfterAll
public static void cleanupClass() {
ConfigurationFactory.removeConfigurationFactory(cf);
}
/**
* Test case for MDC conversion pattern.
*/
@Test
public void testLayout() throws Exception {
for (final Appender appender : root.getAppenders().values()) {
root.removeAppender(appender);
}
// set up appender
final AbstractStringLayout layout = Rfc5424Layout.createLayout(Facility.LOCAL0, "Event", 3692, true, "RequestContext",
null, null, true, null, "ATM", null, "key1, key2, locale", null, "loginId", null, true, null, null);
final ListAppender appender = new ListAppender("List", null, layout, true, false);
appender.start();
// set appender on root and set level to debug
root.addAppender(appender);
root.setLevel(Level.DEBUG);
ThreadContext.put("loginId", "JohnDoe");
// output starting message
root.debug("starting mdc pattern test");
root.debug("empty mdc");
ThreadContext.put("key1", "value1");
ThreadContext.put("key2", "value2");
root.debug("filled mdc");
ThreadContext.put("ipAddress", "192.168.0.120");
ThreadContext.put("locale", Locale.US.getDisplayName());
try {
final StructuredDataMessage msg = new StructuredDataMessage("Transfer@18060", "Transfer Complete", "Audit");
msg.put("ToAccount", "123456");
msg.put("FromAccount", "123457");
msg.put("Amount", "200.00");
root.info(MarkerManager.getMarker("EVENT"), msg);
List<String> list = appender.getMessages();
assertTrue(list.get(0).endsWith(line1), "Expected line 1 to end with: " + line1 + " Actual " + list.get(0));
assertTrue(list.get(1).endsWith(line2), "Expected line 2 to end with: " + line2 + " Actual " + list.get(1));
assertTrue(list.get(2).endsWith(line3), "Expected line 3 to end with: " + line3 + " Actual " + list.get(2));
assertTrue(list.get(3).endsWith(line4), "Expected line 4 to end with: " + line4 + " Actual " + list.get(3));
for (final String frame : list) {
int length = -1;
final int frameLength = frame.length();
final int firstSpacePosition = frame.indexOf(' ');
final String messageLength = frame.substring(0, firstSpacePosition);
try {
length = Integer.parseInt(messageLength);
// the ListAppender removes the ending newline, so we expect one less size
assertEquals(frameLength, messageLength.length() + length);
}
catch (final NumberFormatException e) {
fail("Not a valid RFC 5425 frame");
}
}
appender.clear();
ThreadContext.remove("loginId");
root.debug("This is a test");
list = appender.getMessages();
assertTrue(list.isEmpty(), "No messages expected, found " + list.size());
} finally {
root.removeAppender(appender);
appender.stop();
}
}
/**
* Test case for MDC conversion pattern.
*/
@Test
public void testCollection() throws Exception {
for (final Appender appender : root.getAppenders().values()) {
root.removeAppender(appender);
}
// set up appender
final AbstractStringLayout layout = Rfc5424Layout.createLayout(Facility.LOCAL0, "Event", 3692, true, "RequestContext",
null, null, true, null, "ATM", null, "key1, key2, locale", null, "loginId", null, true, null, null);
final ListAppender appender = new ListAppender("List", null, layout, true, false);
appender.start();
// set appender on root and set level to debug
root.addAppender(appender);
root.setLevel(Level.DEBUG);
ThreadContext.put("loginId", "JohnDoe");
ThreadContext.put("ipAddress", "192.168.0.120");
ThreadContext.put("locale", Locale.US.getDisplayName());
try {
final StructuredDataMessage msg = new StructuredDataMessage("Transfer@18060", "Transfer Complete", "Audit");
msg.put("ToAccount", "123456");
msg.put("FromAccount", "123457");
msg.put("Amount", "200.00");
final StructuredDataMessage msg2 = new StructuredDataMessage("Extra@18060", null, "Audit");
msg2.put("Item1", "Hello");
msg2.put("Item2", "World");
List<StructuredDataMessage> messages = new ArrayList<>();
messages.add(msg);
messages.add(msg2);
final StructuredDataCollectionMessage collectionMessage = new StructuredDataCollectionMessage(messages);
root.info(MarkerManager.getMarker("EVENT"), collectionMessage);
List<String> list = appender.getMessages();
String result = list.get(0);
assertTrue(
result.contains(collectionLine1), "Expected line to contain " + collectionLine1 + ", Actual " + result);
assertTrue(
result.contains(collectionLine2), "Expected line to contain " + collectionLine2 + ", Actual " + result);
assertTrue(
result.contains(collectionLine3), "Expected line to contain " + collectionLine3 + ", Actual " + result);
assertTrue(
result.endsWith(collectionEndOfLine),
"Expected line to end with: " + collectionEndOfLine + " Actual " + result);
for (final String frame : list) {
int length = -1;
final int frameLength = frame.length();
final int firstSpacePosition = frame.indexOf(' ');
final String messageLength = frame.substring(0, firstSpacePosition);
try {
length = Integer.parseInt(messageLength);
// the ListAppender removes the ending newline, so we expect one less size
assertEquals(frameLength, messageLength.length() + length);
}
catch (final NumberFormatException e) {
fail("Not a valid RFC 5425 frame");
}
}
appender.clear();
} finally {
root.removeAppender(appender);
appender.stop();
}
}
/**
* Test case for escaping newlines and other SD PARAM-NAME special characters.
*/
@Test
public void testEscape() throws Exception {
for (final Appender appender : root.getAppenders().values()) {
root.removeAppender(appender);
}
// set up layout/appender
final AbstractStringLayout layout = Rfc5424Layout.createLayout(Facility.LOCAL0, "Event", 3692, true, "RequestContext",
null, null, true, "#012", "ATM", null, "key1, key2, locale", null, "loginId", null, true, null, null);
final ListAppender appender = new ListAppender("List", null, layout, true, false);
appender.start();
// set appender on root and set level to debug
root.addAppender(appender);
root.setLevel(Level.DEBUG);
ThreadContext.put("loginId", "JohnDoe");
// output starting message
root.debug("starting mdc pattern test");
root.debug("empty mdc");
ThreadContext.put("escaped", "Testing escaping \n \" ] \"");
root.debug("filled mdc");
ThreadContext.put("ipAddress", "192.168.0.120");
ThreadContext.put("locale", Locale.US.getDisplayName());
try {
final StructuredDataMessage msg = new StructuredDataMessage("Transfer@18060", "Transfer Complete", "Audit");
msg.put("ToAccount", "123456");
msg.put("FromAccount", "123457");
msg.put("Amount", "200.00");
root.info(MarkerManager.getMarker("EVENT"), msg);
List<String> list = appender.getMessages();
assertTrue(list.get(0).endsWith(line1), "Expected line 1 to end with: " + line1 + " Actual " + list.get(0));
assertTrue(list.get(1).endsWith(line2), "Expected line 2 to end with: " + line2 + " Actual " + list.get(1));
assertTrue(list.get(2).endsWith(lineEscaped3),
"Expected line 3 to end with: " + lineEscaped3 + " Actual " + list.get(2));
assertTrue(list.get(3).endsWith(lineEscaped4),
"Expected line 4 to end with: " + lineEscaped4 + " Actual " + list.get(3));
appender.clear();
ThreadContext.remove("loginId");
root.debug("This is a test");
list = appender.getMessages();
assertTrue(list.isEmpty(), "No messages expected, found " + list.size());
} finally {
root.removeAppender(appender);
appender.stop();
}
}
/**
* Test case for MDC exception conversion pattern.
*/
@Test
public void testException() throws Exception {
for (final Appender appender : root.getAppenders().values()) {
root.removeAppender(appender);
}
// set up layout/appender
final AbstractStringLayout layout = Rfc5424Layout.createLayout(Facility.LOCAL0, "Event", 3692, true, "RequestContext",
null, null, true, null, "ATM", null, "key1, key2, locale", null, "loginId", "%xEx", true, null, null);
final ListAppender appender = new ListAppender("List", null, layout, true, false);
appender.start();
// set appender on root and set level to debug
root.addAppender(appender);
root.setLevel(Level.DEBUG);
ThreadContext.put("loginId", "JohnDoe");
// output starting message
root.debug("starting mdc pattern test", new IllegalArgumentException("Test"));
try {
final List<String> list = appender.getMessages();
assertTrue(list.size() > 1, "Not enough list entries");
final String string = list.get(1);
assertTrue(string.contains("IllegalArgumentException"), "No Exception in " + string);
appender.clear();
} finally {
root.removeAppender(appender);
appender.stop();
}
}
/**
* Test case for MDC logger field inclusion.
*/
@Test
public void testMDCLoggerFields() throws Exception {
for (final Appender appender : root.getAppenders().values()) {
root.removeAppender(appender);
}
final LoggerFields[] loggerFields = new LoggerFields[] {
LoggerFields.createLoggerFields(new KeyValuePair[] { new KeyValuePair("source", "%C.%M")}, null, null, false),
LoggerFields.createLoggerFields(new KeyValuePair[] { new KeyValuePair("source2", "%C.%M")}, null, null, false)
};
// set up layout/appender
final AbstractStringLayout layout = Rfc5424Layout.createLayout(Facility.LOCAL0, "Event", 3692, true, "RequestContext",
null, null, true, null, "ATM", null, "key1, key2, locale", null, null, null, true, loggerFields, null);
final ListAppender appender = new ListAppender("List", null, layout, true, false);
appender.start();
// set appender on root and set level to debug
root.addAppender(appender);
root.setLevel(Level.DEBUG);
// output starting message
root.info("starting logger fields test");
try {
final List<String> list = appender.getMessages();
assertTrue(list.size() > 0, "Not enough list entries");
assertTrue(list.get(0).contains("Rfc5424LayoutTest.testMDCLoggerFields"), "No class/method");
appender.clear();
} finally {
root.removeAppender(appender);
appender.stop();
}
}
@Test
public void testLoggerFields() {
final String[] fields = new String[] {
"[BAZ@32473 baz=\"org.apache.logging.log4j.core.layout.Rfc5424LayoutTest.testLoggerFields\"]",
"[RequestContext@3692 bar=\"org.apache.logging.log4j.core.layout.Rfc5424LayoutTest.testLoggerFields\"]",
"[SD-ID@32473 source=\"org.apache.logging.log4j.core.layout.Rfc5424LayoutTest.testLoggerFields\"]"
};
final List<String> expectedToContain = Arrays.asList(fields);
for (final Appender appender : root.getAppenders().values()) {
root.removeAppender(appender);
}
final LoggerFields[] loggerFields = new LoggerFields[] {
LoggerFields.createLoggerFields(new KeyValuePair[] { new KeyValuePair("source", "%C.%M")}, "SD-ID",
"32473", false),
LoggerFields.createLoggerFields(new KeyValuePair[] { new KeyValuePair("baz", "%C.%M"),
new KeyValuePair("baz", "%C.%M") }, "BAZ", "32473", false),
LoggerFields.createLoggerFields(new KeyValuePair[] { new KeyValuePair("bar", "%C.%M")}, null, null, false)
};
final AbstractStringLayout layout = Rfc5424Layout.createLayout(Facility.LOCAL0, "Event", 3692, true, "RequestContext",
null, null, true, null, "ATM", null, "key1, key2, locale", null, null, null, false, loggerFields, null);
final ListAppender appender = new ListAppender("List", null, layout, true, false);
appender.start();
root.addAppender(appender);
root.setLevel(Level.DEBUG);
root.info("starting logger fields test");
try {
final List<String> list = appender.getMessages();
assertTrue(list.size() > 0, "Not enough list entries");
final String message = list.get(0);
assertTrue(message.contains("Rfc5424LayoutTest.testLoggerFields"), "No class/method");
for (final String value : expectedToContain) {
assertTrue(message.contains(value), "Message expected to contain " + value + " but did not");
}
appender.clear();
} finally {
root.removeAppender(appender);
appender.stop();
}
}
@Test
public void testDiscardEmptyLoggerFields() {
final String mdcId = "RequestContext";
for (final Appender appender : root.getAppenders().values()) {
root.removeAppender(appender);
}
final LoggerFields[] loggerFields = new LoggerFields[] {
LoggerFields.createLoggerFields(new KeyValuePair[] { new KeyValuePair("dummy", Strings.EMPTY),
new KeyValuePair("empty", Strings.EMPTY)}, "SD-ID", "32473", true),
LoggerFields.createLoggerFields(new KeyValuePair[] { new KeyValuePair("baz", "%C.%M"),
new KeyValuePair("baz", "%C.%M") }, "BAZ", "32473", false),
LoggerFields.createLoggerFields(new KeyValuePair[] { new KeyValuePair("bar", "%C.%M")}, null, null, false)
};
final AbstractStringLayout layout = Rfc5424Layout.createLayout(Facility.LOCAL0, "Event", 3692, true, mdcId,
null, null, true, null, "ATM", null, "key1, key2, locale", null, null, null, false, loggerFields, null);
final ListAppender appender = new ListAppender("List", null, layout, true, false);
appender.start();
root.addAppender(appender);
root.setLevel(Level.DEBUG);
root.info("starting logger fields test");
try {
final List<String> list = appender.getMessages();
assertTrue(list.size() > 0, "Not enough list entries");
final String message = list.get(0);
assertFalse(message.contains("SD-ID"), "SD-ID should have been discarded");
assertTrue(message.contains("BAZ"), "BAZ should have been included");
assertTrue(message.contains(mdcId), mdcId + "should have been included");
appender.clear();
} finally {
root.removeAppender(appender);
appender.stop();
}
}
@Test
public void testSubstituteStructuredData() {
final String mdcId = "RequestContext";
final String expectedToContain = String.format("ATM %s MSG-ID - Message", PROCESSID);
for (final Appender appender : root.getAppenders().values()) {
root.removeAppender(appender);
}
final AbstractStringLayout layout = Rfc5424Layout.createLayout(Facility.LOCAL0, "Event", 3692, false, mdcId,
null, null, true, null, "ATM", "MSG-ID", "key1, key2, locale", null, null, null, false, null, null);
final ListAppender appender = new ListAppender("List", null, layout, true, false);
appender.start();
root.addAppender(appender);
root.setLevel(Level.DEBUG);
root.info("Message");
try {
final List<String> list = appender.getMessages();
assertTrue(list.size() > 0, "Not enough list entries");
final String message = list.get(0);
assertTrue(message.contains(expectedToContain), "Not the expected message received");
appender.clear();
} finally {
root.removeAppender(appender);
appender.stop();
}
}
@Test
public void testParameterizedMessage() {
for (final Appender appender : root.getAppenders().values()) {
root.removeAppender(appender);
}
// set up appender
final AbstractStringLayout layout = Rfc5424Layout.createLayout(Facility.LOCAL0, "Event", 3692, true, "RequestContext",
null, null, true, null, "ATM", null, "key1, key2, locale", null, null, null, true, null, null);
final ListAppender appender = new ListAppender("List", null, layout, true, false);
appender.start();
// set appender on root and set level to debug
root.addAppender(appender);
root.setLevel(Level.DEBUG);
root.info("Hello {}", "World");
try {
final List<String> list = appender.getMessages();
assertTrue(list.size() > 0, "Not enough list entries");
final String message = list.get(0);
assertTrue(message.contains("Hello World"),
"Incorrect message. Expected - Hello World, Actual - " + message);
} finally {
root.removeAppender(appender);
appender.stop();
}
}
}
|
92438cac0dbcd2025d90c9eab592fa4233b59f9d | 207 | java | Java | platform-api/src/main/java/com/platform/dao/ApiGsMapper.java | gitPrivateUsers/newcode | 9258d0842bc375b4c69feefbfeb8803db9ec3b06 | [
"Apache-2.0"
] | null | null | null | platform-api/src/main/java/com/platform/dao/ApiGsMapper.java | gitPrivateUsers/newcode | 9258d0842bc375b4c69feefbfeb8803db9ec3b06 | [
"Apache-2.0"
] | null | null | null | platform-api/src/main/java/com/platform/dao/ApiGsMapper.java | gitPrivateUsers/newcode | 9258d0842bc375b4c69feefbfeb8803db9ec3b06 | [
"Apache-2.0"
] | 1 | 2018-12-28T12:33:41.000Z | 2018-12-28T12:33:41.000Z | 13.733333 | 50 | 0.679612 | 1,002,692 | package com.platform.dao;
import com.platform.entity.Gs;
/**
*
*
* @author lipengjun
* @email [email protected]
* @date 2017-08-11 09:14:25
*/
public interface ApiGsMapper extends BaseDao<Gs> {
}
|
92438d02c8d37f46ef7d7a7234759dc3c8c77801 | 2,503 | java | Java | Android/HelloBallDuktape/src/com/balsamiq/HelloBallDuktape/HelloBallActivity.java | SneakyWhoami/helloball | 939783cc4fdaf8cead13ef4256ce1907945fce8b | [
"MIT"
] | 1 | 2020-01-17T21:48:56.000Z | 2020-01-17T21:48:56.000Z | Android/HelloBallDuktape/src/com/balsamiq/HelloBallDuktape/HelloBallActivity.java | SneakyWhoami/helloball | 939783cc4fdaf8cead13ef4256ce1907945fce8b | [
"MIT"
] | null | null | null | Android/HelloBallDuktape/src/com/balsamiq/HelloBallDuktape/HelloBallActivity.java | SneakyWhoami/helloball | 939783cc4fdaf8cead13ef4256ce1907945fce8b | [
"MIT"
] | 1 | 2021-05-26T16:31:24.000Z | 2021-05-26T16:31:24.000Z | 31.2875 | 118 | 0.664802 | 1,002,693 | package com.balsamiq.HelloBallDuktape;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseArray;
import android.view.ViewTreeObserver;
import android.widget.TextView;
public class HelloBallActivity extends Activity implements IModelObserver {
BallsDrawingView _view;
TextView _fps;
JavaModelWrapper _model;
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
_view = (BallsDrawingView) findViewById(R.id.drawing_view);
_model = new JavaModelWrapper(AssetUtilities.readFromfile(this, "model.js"), this);
_view.setModelWrapper(_model);
_fps = (TextView) findViewById(R.id.fps);
ViewTreeObserver viewTreeObserver = _view.getViewTreeObserver();
if (viewTreeObserver.isAlive()) {
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT < 16) {
removeLayoutListenerPre16(_view, this);
} else {
removeLayoutListenerPost16(_view, this);
}
_model.start(_view.getWidth(), _view.getHeight());
}
});
}
}
@SuppressWarnings("deprecation")
private void removeLayoutListenerPre16(BallsDrawingView view, ViewTreeObserver.OnGlobalLayoutListener listener) {
view.getViewTreeObserver().removeGlobalOnLayoutListener(listener);
}
@TargetApi(16)
private void removeLayoutListenerPost16(BallsDrawingView view, ViewTreeObserver.OnGlobalLayoutListener listener) {
view.getViewTreeObserver().removeOnGlobalLayoutListener(listener);
}
@Override
public void ballCountChanged(int number) {
Log.d("HelloBallActivity.ballCountChanged", "" + number);
}
@Override
public void eventsPerSecond(final int events) {
_fps.setText("" + events);
}
@Override
public void log(String message) {
}
public void displayListChanged(SparseArray<Ball> balls) {
_view.displayListChanged(balls);
}
@Override
protected void onResume() {
super.onResume();
}
}
|
92438d772c3f4f72d3ad729e3ff7326070f80b6d | 11,935 | java | Java | cdm-core/src/main/java/ucar/unidata/geoloc/projection/proj4/TransverseMercatorProjection.java | oxelson/netcdf-java | 07d161eca0e5d9f04e1e95f7f0fcd718ac8c541a | [
"BSD-3-Clause"
] | 83 | 2019-07-04T13:40:24.000Z | 2022-03-03T02:25:16.000Z | cdm-core/src/main/java/ucar/unidata/geoloc/projection/proj4/TransverseMercatorProjection.java | oxelson/netcdf-java | 07d161eca0e5d9f04e1e95f7f0fcd718ac8c541a | [
"BSD-3-Clause"
] | 655 | 2019-06-28T15:08:16.000Z | 2022-03-29T17:12:46.000Z | cdm-core/src/main/java/ucar/unidata/geoloc/projection/proj4/TransverseMercatorProjection.java | oxelson/netcdf-java | 07d161eca0e5d9f04e1e95f7f0fcd718ac8c541a | [
"BSD-3-Clause"
] | 87 | 2019-07-03T18:17:49.000Z | 2022-03-30T01:53:16.000Z | 36.95356 | 119 | 0.650134 | 1,002,694 | /*
* Copyright (c) 1998-2021 John Caron and University Corporation for Atmospheric Research/Unidata
* See LICENSE for license information.
*/
/*
* Copyright 2006 Jerry Huxtable
*
* 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.
*/
/*
* This file was semi-automatically converted from the public-domain USGS PROJ source.
*
* Changes by Bernhard Jenny, May 2007: added missing toString() and
* isEqualArea(); this class now derives from CylindricalProjection instead of
* Projection; removed isRectilinear, which is defined in the new superclass
* CylindricalProjection; and removed trueScaleLatitude that did hide a field
* of the Projection class of the same name.
*/
package ucar.unidata.geoloc.projection.proj4;
import java.util.Formatter;
import javax.annotation.concurrent.Immutable;
import ucar.nc2.constants.CDM;
import ucar.nc2.constants.CF;
import ucar.unidata.geoloc.Earth;
import ucar.unidata.geoloc.EarthEllipsoid;
import ucar.unidata.geoloc.LatLonPoint;
import ucar.unidata.geoloc.LatLonPoints;
import ucar.unidata.geoloc.Projection;
import ucar.unidata.geoloc.projection.AbstractProjection;
import ucar.unidata.geoloc.ProjectionPoint;
/**
* Transverse Mercator Projection algorithm is taken from the USGS PROJ package.
*
* @author [email protected]
*/
@Immutable
public class TransverseMercatorProjection extends AbstractProjection {
public static int getRowFromNearestParallel(double latitude) {
int degrees = (int) MapMath.radToDeg(MapMath.normalizeLatitude(latitude));
if (degrees < -80 || degrees > 84)
return 0;
if (degrees > 80)
return 24;
return (degrees + 80) / 8 + 3;
}
public static int getZoneFromNearestMeridian(double longitude) {
int zone = (int) Math.floor((MapMath.normalizeLongitude(longitude) + Math.PI) * 30.0 / Math.PI) + 1;
if (zone < 1)
zone = 1;
else if (zone > 60)
zone = 60;
return zone;
}
private static final double FC1 = 1.0;
private static final double FC2 = 0.5;
private static final double FC3 = 0.16666666666666666666;
private static final double FC4 = 0.08333333333333333333;
private static final double FC5 = 0.05;
private static final double FC6 = 0.03333333333333333333;
private static final double FC7 = 0.02380952380952380952;
private static final double FC8 = 0.01785714285714285714;
private final double esp;
private final double ml0;
private final double[] en;
private final double projectionLatitude, projectionLongitude;
private final double scaleFactor;
private final double falseEasting, falseNorthing;
private final Earth ellipsoid;
private final double es; // earth.getEccentricitySquared
private final double totalScale; // scale to convert cartesian coords in km
private final boolean spherical;
// values passed in through the constructor
// need for constructCopy
private final double _lat0;
private final double _lon0;
public TransverseMercatorProjection() {
this(EarthEllipsoid.WGS84, 0, 0, 0.9996, 0, 0);
}
public TransverseMercatorProjection(int zone) {
this(EarthEllipsoid.WGS84, Math.toDegrees(((zone - 1) + .5) * Math.PI / 30. - Math.PI), 0, 0.9996, 500000, 0);
}
/**
* Set up a projection suitable for State Plane Coordinates.
* Best used with earth ellipsoid and false-easting/northing in km
*/
public TransverseMercatorProjection(Earth ellipsoid, double lon_0_deg, double lat_0_deg, double k, double falseEast,
double falseNorth) {
super("TransverseMercatorProjection", false);
this._lat0 = lat_0_deg;
this._lon0 = lon_0_deg;
this.ellipsoid = ellipsoid;
projectionLongitude = Math.toRadians(lon_0_deg);
projectionLatitude = Math.toRadians(lat_0_deg);
scaleFactor = k;
falseEasting = falseEast;
falseNorthing = falseNorth;
this.es = ellipsoid.getEccentricitySquared();
this.spherical = ellipsoid.isSpherical();
this.totalScale = ellipsoid.getMajor() * .001; // scale factor for cartesion coords in km.
if (spherical) {
en = null;
esp = scaleFactor;
ml0 = .5 * esp;
} else {
en = MapMath.enfn(es);
ml0 = MapMath.mlfn(projectionLatitude, Math.sin(projectionLatitude), Math.cos(projectionLatitude), en);
esp = es / (1. - es);
}
// parameters
addParameter(CF.GRID_MAPPING_NAME, CF.TRANSVERSE_MERCATOR);
addParameter(CF.LONGITUDE_OF_CENTRAL_MERIDIAN, lon_0_deg);
addParameter(CF.LATITUDE_OF_PROJECTION_ORIGIN, lat_0_deg);
addParameter(CF.SCALE_FACTOR_AT_CENTRAL_MERIDIAN, scaleFactor);
if ((falseEasting != 0.0) || (falseNorthing != 0.0)) {
addParameter(CF.FALSE_EASTING, falseEasting);
addParameter(CF.FALSE_NORTHING, falseNorthing);
addParameter(CDM.UNITS, "km");
}
addParameter(CF.SEMI_MAJOR_AXIS, ellipsoid.getMajor());
addParameter(CF.INVERSE_FLATTENING, 1.0 / ellipsoid.getFlattening());
}
private ProjectionPoint project(double lplam, double lpphi) {
if (spherical) {
double cosphi = Math.cos(lpphi);
double b = cosphi * Math.sin(lplam);
double x = ml0 * scaleFactor * Math.log((1. + b) / (1. - b));
double ty = cosphi * Math.cos(lplam) / Math.sqrt(1. - b * b);
ty = MapMath.acos(ty);
if (lpphi < 0.0)
ty = -ty;
double y = esp * (ty - projectionLatitude);
return ProjectionPoint.create(x, y);
} else {
double al, als, n, t;
double sinphi = Math.sin(lpphi);
double cosphi = Math.cos(lpphi);
t = Math.abs(cosphi) > 1e-10 ? sinphi / cosphi : 0.0;
t *= t;
al = cosphi * lplam;
als = al * al;
al /= Math.sqrt(1. - es * sinphi * sinphi);
n = esp * cosphi * cosphi;
double x = scaleFactor * al * (FC1 + FC3 * als * (1. - t + n
+ FC5 * als * (5. + t * (t - 18.) + n * (14. - 58. * t) + FC7 * als * (61. + t * (t * (179. - t) - 479.)))));
double y = scaleFactor * (MapMath.mlfn(lpphi, sinphi, cosphi, en) - ml0
+ sinphi * al * lplam * FC2 * (1. + FC4 * als * (5. - t + n * (9. + 4. * n) + FC6 * als
* (61. + t * (t - 58.) + n * (270. - 330 * t) + FC8 * als * (1385. + t * (t * (543. - t) - 3111.))))));
return ProjectionPoint.create(x, y);
}
}
private ProjectionPoint projectInverse(double x, double y) {
if (spherical) {
double h = Math.exp(x / scaleFactor);
double g = .5 * (h - 1. / h);
h = Math.cos(projectionLatitude + y / scaleFactor);
double outy = MapMath.asin(Math.sqrt((1. - h * h) / (1. + g * g)));
if (y < 0)
outy = -outy;
double outx = Math.atan2(g, h);
return ProjectionPoint.create(outx, outy);
} else {
double n, con, cosphi, d, ds, sinphi, t;
double outx = 0;
double outy = MapMath.inv_mlfn(ml0 + y / scaleFactor, es, en);
if (Math.abs(y) >= MapMath.HALFPI) {
outy = y < 0. ? -MapMath.HALFPI : MapMath.HALFPI;
return ProjectionPoint.create(outx, outy);
} else {
sinphi = Math.sin(outy);
cosphi = Math.cos(outy);
t = Math.abs(cosphi) > 1e-10 ? sinphi / cosphi : 0.;
n = esp * cosphi * cosphi;
d = x * Math.sqrt(con = 1. - es * sinphi * sinphi) / scaleFactor;
con *= t;
t *= t;
ds = d * d;
outy -= (con * ds / (1. - es)) * FC2
* (1. - ds * FC4
* (5. + t * (3. - 9. * n) + n * (1. - 4 * n) - ds * FC6 * (61. + t * (90. - 252. * n + 45. * t)
+ 46. * n - ds * FC8 * (1385. + t * (3633. + t * (4095. + 1574. * t))))));
outx = d * (FC1 - ds * FC3 * (1. + 2. * t + n - ds * FC5
* (5. + t * (28. + 24. * t + 8. * n) + 6. * n - ds * FC7 * (61. + t * (662. + t * (1320. + 720. * t))))))
/ cosphi;
return ProjectionPoint.create(outx, outy);
}
}
}
public boolean isRectilinear() {
return false;
}
public boolean hasInverse() {
return true;
}
@Override
public Projection constructCopy() {
return new TransverseMercatorProjection(ellipsoid, _lon0, _lat0, scaleFactor, falseEasting, falseNorthing);
}
@Override
public ProjectionPoint latLonToProj(LatLonPoint latLon) {
double fromLat = Math.toRadians(latLon.getLatitude());
double theta = Math.toRadians(latLon.getLongitude());
if (projectionLongitude != 0) {
theta = MapMath.normalizeLongitude(theta - projectionLongitude);
}
ProjectionPoint res = project(theta, fromLat);
return ProjectionPoint.create(totalScale * res.getX() + falseEasting, totalScale * res.getY() + falseNorthing);
}
@Override
public LatLonPoint projToLatLon(ProjectionPoint world) {
double fromX = (world.getX() - falseEasting) / totalScale; // assumes cartesian coords in km
double fromY = (world.getY() - falseNorthing) / totalScale;
ProjectionPoint dst = projectInverse(fromX, fromY);
double toLon = dst.getX();
double toLat = dst.getY();
if (toLon < -Math.PI)
toLon = -Math.PI;
else if (toLon > Math.PI)
toLon = Math.PI;
if (projectionLongitude != 0)
toLon = MapMath.normalizeLongitude(toLon) + projectionLongitude;
return LatLonPoint.create(Math.toDegrees(toLat), Math.toDegrees(toLon));
}
@Override
public boolean crossSeam(ProjectionPoint pt1, ProjectionPoint pt2) {
if (LatLonPoints.isInfinite(pt1) || LatLonPoints.isInfinite(pt2)) {
return true;
}
double y1 = pt1.getY() - falseNorthing;
double y2 = pt2.getY() - falseNorthing;
// opposite signed long lines
return (y1 * y2 < 0) && (Math.abs(y1 - y2) > 2 * ellipsoid.getMajor());
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
TransverseMercatorProjection that = (TransverseMercatorProjection) o;
// if ((this.getDefaultMapArea() == null) != (that.defaultMapArea == null)) return false; // common case is that
// these are null
// if (this.getDefaultMapArea() != null && !this.defaultMapArea.equals(that.defaultMapArea)) return false;
if (Double.compare(that.falseEasting, falseEasting) != 0)
return false;
if (Double.compare(that.falseNorthing, falseNorthing) != 0)
return false;
if (Double.compare(that.projectionLatitude, projectionLatitude) != 0)
return false;
if (Double.compare(that.projectionLongitude, projectionLongitude) != 0)
return false;
if (Double.compare(that.scaleFactor, scaleFactor) != 0)
return false;
return ellipsoid.equals(that.ellipsoid);
}
@Override
public int hashCode() {
int hash = 5;
hash = 97 * hash + (int) (Double.doubleToLongBits(this.projectionLatitude)
^ (Double.doubleToLongBits(this.projectionLatitude) >>> 32));
hash = 97 * hash + (int) (Double.doubleToLongBits(this.projectionLongitude)
^ (Double.doubleToLongBits(this.projectionLongitude) >>> 32));
hash = 97 * hash
+ (int) (Double.doubleToLongBits(this.scaleFactor) ^ (Double.doubleToLongBits(this.scaleFactor) >>> 32));
hash = 97 * hash
+ (int) (Double.doubleToLongBits(this.falseEasting) ^ (Double.doubleToLongBits(this.falseEasting) >>> 32));
hash = 97 * hash
+ (int) (Double.doubleToLongBits(this.falseNorthing) ^ (Double.doubleToLongBits(this.falseNorthing) >>> 32));
hash = 97 * hash + (this.ellipsoid != null ? this.ellipsoid.hashCode() : 0);
return hash;
}
}
|
92438d7fc64661b56f7057afcd03cd22ba7f9162 | 2,353 | java | Java | ids-api/src/main/java/de/fhg/aisec/ids/api/settings/ConnectionSettings.java | ascatox/trusted-connector | 4f2e3c0c710e4e9654889baa78522f576e806654 | [
"Apache-2.0"
] | null | null | null | ids-api/src/main/java/de/fhg/aisec/ids/api/settings/ConnectionSettings.java | ascatox/trusted-connector | 4f2e3c0c710e4e9654889baa78522f576e806654 | [
"Apache-2.0"
] | 7 | 2021-03-09T02:06:41.000Z | 2022-02-26T10:15:25.000Z | ids-api/src/main/java/de/fhg/aisec/ids/api/settings/ConnectionSettings.java | ascatox/trusted-connector | 4f2e3c0c710e4e9654889baa78522f576e806654 | [
"Apache-2.0"
] | null | null | null | 29.78481 | 75 | 0.718232 | 1,002,695 | /*-
* ========================LICENSE_START=================================
* ids-api
* %%
* Copyright (C) 2019 Fraunhofer AISEC
* %%
* 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.
* =========================LICENSE_END==================================
*/
package de.fhg.aisec.ids.api.settings;
import java.io.Serializable;
public final class ConnectionSettings implements Serializable {
private static final long serialVersionUID = 1L;
private final String integrityProtectionAndVerification;
private final String authentication;
private final String serviceIsolation;
private final String integrityProtectionVerificationScope;
private final String appExecutionResources;
private final String dataUsageControlSupport;
private final String auditLogging;
private final String localDataConfidentiality;
public ConnectionSettings() {
integrityProtectionAndVerification = "1";
authentication = "1";
serviceIsolation = "1";
integrityProtectionVerificationScope = "1";
appExecutionResources = "1";
dataUsageControlSupport = "1";
auditLogging = "1";
localDataConfidentiality = "1";
}
public String getIntegrityProtectionAndVerification() {
return integrityProtectionAndVerification;
}
public String getAuthentication() {
return authentication;
}
public String getServiceIsolation() {
return serviceIsolation;
}
public String getIntegrityProtectionVerificationScope() {
return integrityProtectionVerificationScope;
}
public String getAppExecutionResources() {
return appExecutionResources;
}
public String getDataUsageControlSupport() {
return dataUsageControlSupport;
}
public String getAuditLogging() {
return auditLogging;
}
public String getLocalDataConfidentiality() {
return localDataConfidentiality;
}
}
|
92438de0d2da82fb9ee0f57d2b92abace1cbf063 | 877 | java | Java | src/irvine/oeis/a034/A034318.java | gfis/joeis-alt | e89a990e8aed290f5ce52908437da206c7e55304 | [
"Apache-2.0"
] | null | null | null | src/irvine/oeis/a034/A034318.java | gfis/joeis-alt | e89a990e8aed290f5ce52908437da206c7e55304 | [
"Apache-2.0"
] | null | null | null | src/irvine/oeis/a034/A034318.java | gfis/joeis-alt | e89a990e8aed290f5ce52908437da206c7e55304 | [
"Apache-2.0"
] | null | null | null | 30.241379 | 103 | 0.706956 | 1,002,696 | package irvine.oeis.a034;
import irvine.math.group.IntegerField;
import irvine.math.group.PolynomialRingField;
import irvine.math.polynomial.Polynomial;
import irvine.math.z.Z;
import irvine.oeis.Sequence;
/**
* A034318 McKay-Thompson series of class 13A for the Monster group with a(0) = -2.
* @author Sean A. Irvine
*/
public class A034318 implements Sequence {
private static final PolynomialRingField<Z> RING = new PolynomialRingField<>(IntegerField.SINGLETON);
private static final Polynomial<Z> C13 = RING.monomial(Z.ONE, 13);
private int mN = -1;
@Override
public Z next() {
++mN;
final Polynomial<Z> eta = RING.eta(RING.x(), mN);
final Polynomial<Z> eta13 = RING.eta(C13, mN);
return RING.pow(RING.series(eta, eta13, mN), 2, mN).coeff(mN)
.add(RING.pow(RING.series(eta13, eta, mN), 2, mN).shift(2).coeff(mN).multiply(13));
}
}
|
92438e5fbf9cfe9ff75ec2f66f29f44a27d9960c | 5,761 | java | Java | org/apache/xalan/lib/ExsltSets.java | MewX/contendo-viewer-v1.6.3 | 69fba3cea4f9a43e48f43148774cfa61b388e7de | [
"Apache-2.0"
] | 2 | 2021-07-16T10:43:25.000Z | 2021-12-15T13:54:10.000Z | org/apache/xalan/lib/ExsltSets.java | MewX/contendo-viewer-v1.6.3 | 69fba3cea4f9a43e48f43148774cfa61b388e7de | [
"Apache-2.0"
] | 1 | 2021-10-12T22:24:55.000Z | 2021-10-12T22:24:55.000Z | org/apache/xalan/lib/ExsltSets.java | MewX/contendo-viewer-v1.6.3 | 69fba3cea4f9a43e48f43148774cfa61b388e7de | [
"Apache-2.0"
] | null | null | null | 23.805785 | 112 | 0.367471 | 1,002,697 | /* */ package org.apache.xalan.lib;
/* */
/* */ import java.util.Hashtable;
/* */ import org.apache.xml.utils.DOMHelper;
/* */ import org.apache.xpath.NodeSet;
/* */ import org.w3c.dom.Node;
/* */ import org.w3c.dom.NodeList;
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public class ExsltSets
/* */ extends ExsltBase
/* */ {
/* */ public static NodeList leading(NodeList nl1, NodeList nl2) {
/* 59 */ if (nl2.getLength() == 0) {
/* 60 */ return nl1;
/* */ }
/* 62 */ NodeSet ns1 = new NodeSet(nl1);
/* 63 */ NodeSet leadNodes = new NodeSet();
/* 64 */ Node endNode = nl2.item(0);
/* 65 */ if (!ns1.contains(endNode)) {
/* 66 */ return (NodeList)leadNodes;
/* */ }
/* 68 */ for (int i = 0; i < nl1.getLength(); i++) {
/* */
/* 70 */ Node testNode = nl1.item(i);
/* 71 */ if (DOMHelper.isNodeAfter(testNode, endNode) && !DOMHelper.isNodeTheSame(testNode, endNode))
/* */ {
/* 73 */ leadNodes.addElement(testNode); }
/* */ }
/* 75 */ return (NodeList)leadNodes;
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public static NodeList trailing(NodeList nl1, NodeList nl2) {
/* 94 */ if (nl2.getLength() == 0) {
/* 95 */ return nl1;
/* */ }
/* 97 */ NodeSet ns1 = new NodeSet(nl1);
/* 98 */ NodeSet trailNodes = new NodeSet();
/* 99 */ Node startNode = nl2.item(0);
/* 100 */ if (!ns1.contains(startNode)) {
/* 101 */ return (NodeList)trailNodes;
/* */ }
/* 103 */ for (int i = 0; i < nl1.getLength(); i++) {
/* */
/* 105 */ Node testNode = nl1.item(i);
/* 106 */ if (DOMHelper.isNodeAfter(startNode, testNode) && !DOMHelper.isNodeTheSame(startNode, testNode))
/* */ {
/* 108 */ trailNodes.addElement(testNode); }
/* */ }
/* 110 */ return (NodeList)trailNodes;
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public static NodeList intersection(NodeList nl1, NodeList nl2) {
/* 126 */ NodeSet ns1 = new NodeSet(nl1);
/* 127 */ NodeSet ns2 = new NodeSet(nl2);
/* 128 */ NodeSet inter = new NodeSet();
/* */
/* 130 */ inter.setShouldCacheNodes(true);
/* */
/* 132 */ for (int i = 0; i < ns1.getLength(); i++) {
/* */
/* 134 */ Node n = ns1.elementAt(i);
/* */
/* 136 */ if (ns2.contains(n)) {
/* 137 */ inter.addElement(n);
/* */ }
/* */ }
/* 140 */ return (NodeList)inter;
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public static NodeList difference(NodeList nl1, NodeList nl2) {
/* 156 */ NodeSet ns1 = new NodeSet(nl1);
/* 157 */ NodeSet ns2 = new NodeSet(nl2);
/* */
/* 159 */ NodeSet diff = new NodeSet();
/* */
/* 161 */ diff.setShouldCacheNodes(true);
/* */
/* 163 */ for (int i = 0; i < ns1.getLength(); i++) {
/* */
/* 165 */ Node n = ns1.elementAt(i);
/* */
/* 167 */ if (!ns2.contains(n)) {
/* 168 */ diff.addElement(n);
/* */ }
/* */ }
/* 171 */ return (NodeList)diff;
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public static NodeList distinct(NodeList nl) {
/* 188 */ NodeSet dist = new NodeSet();
/* 189 */ dist.setShouldCacheNodes(true);
/* */
/* 191 */ Hashtable stringTable = new Hashtable();
/* */
/* 193 */ for (int i = 0; i < nl.getLength(); i++) {
/* */
/* 195 */ Node currNode = nl.item(i);
/* 196 */ String key = ExsltBase.toString(currNode);
/* */
/* 198 */ if (key == null) {
/* 199 */ dist.addElement(currNode);
/* 200 */ } else if (!stringTable.containsKey(key)) {
/* */
/* 202 */ stringTable.put(key, currNode);
/* 203 */ dist.addElement(currNode);
/* */ }
/* */ }
/* */
/* 207 */ return (NodeList)dist;
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public static boolean hasSameNode(NodeList nl1, NodeList nl2) {
/* 226 */ NodeSet ns1 = new NodeSet(nl1);
/* 227 */ NodeSet ns2 = new NodeSet(nl2);
/* */
/* 229 */ for (int i = 0; i < ns1.getLength(); i++) {
/* */
/* 231 */ if (ns2.contains(ns1.elementAt(i)))
/* 232 */ return true;
/* */ }
/* 234 */ return false;
/* */ }
/* */ }
/* Location: /mnt/r/ConTenDoViewer.jar!/org/apache/xalan/lib/ExsltSets.class
* Java compiler version: 1 (45.3)
* JD-Core Version: 1.1.3
*/ |
924390be90a29744ad02ad0881851f24557927c9 | 1,367 | java | Java | cis/com.b2international.snowowl.snomed.cis/src/com/b2international/snowowl/snomed/cis/internal/SnomedComponentIdentifierValidator.java | eranhash/snow-owl | bee466023647e4512e96269f0a380fa1ff3a785a | [
"Apache-2.0"
] | 259 | 2017-02-03T16:33:21.000Z | 2022-03-31T09:51:25.000Z | cis/com.b2international.snowowl.snomed.cis/src/com/b2international/snowowl/snomed/cis/internal/SnomedComponentIdentifierValidator.java | eranhash/snow-owl | bee466023647e4512e96269f0a380fa1ff3a785a | [
"Apache-2.0"
] | 381 | 2017-02-17T15:07:10.000Z | 2022-03-29T13:13:41.000Z | cis/com.b2international.snowowl.snomed.cis/src/com/b2international/snowowl/snomed/cis/internal/SnomedComponentIdentifierValidator.java | eranhash/snow-owl | bee466023647e4512e96269f0a380fa1ff3a785a | [
"Apache-2.0"
] | 25 | 2017-02-08T10:00:16.000Z | 2022-02-21T10:58:49.000Z | 30.377778 | 86 | 0.772495 | 1,002,698 | /*
* Copyright 2011-2016 B2i Healthcare Pte Ltd, http://b2i.sg
*
* 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.b2international.snowowl.snomed.cis.internal;
import com.b2international.snowowl.core.terminology.ComponentCategory;
import com.b2international.snowowl.snomed.cis.SnomedIdentifierValidator;
import com.b2international.snowowl.snomed.cis.SnomedIdentifiers;
/**
* @since 4.4
*/
public class SnomedComponentIdentifierValidator implements SnomedIdentifierValidator {
private ComponentCategory category;
public SnomedComponentIdentifierValidator(ComponentCategory category) {
this.category = category;
}
@Override
public boolean isValid(String componentId) {
try {
return category.equals(SnomedIdentifiers.getComponentCategory(componentId));
} catch (IllegalArgumentException e) {
return false;
}
}
}
|
924390ca24bbcd92a748ef46c5df3752eb6026a8 | 1,302 | java | Java | addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/tests/ContactViewTests.java | erybak90/java_kurs | a17d487d0655d803590ccebd292d22881ae7a68d | [
"Apache-2.0"
] | null | null | null | addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/tests/ContactViewTests.java | erybak90/java_kurs | a17d487d0655d803590ccebd292d22881ae7a68d | [
"Apache-2.0"
] | null | null | null | addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/tests/ContactViewTests.java | erybak90/java_kurs | a17d487d0655d803590ccebd292d22881ae7a68d | [
"Apache-2.0"
] | null | null | null | 34.263158 | 101 | 0.684332 | 1,002,699 | package ru.stqa.pft.addressbook.tests;
import org.testng.annotations.Test;
import ru.stqa.pft.addressbook.model.ContactData;
import java.util.Arrays;
import java.util.stream.Collectors;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
public class ContactViewTests extends TestBase {
@Test (enabled = false)
public void ContactViewTests() {
ContactData contact = app.contact().all().iterator().next();
ContactData contactInfoFromEditForm = app.contact().infoFromEditForm(contact);
app.goTo().contactsPage();
ContactData contactInfoFromViewForm = app.contact().infoFromViewForm(contact);
assertThat(contact.getAllPhones(), equalTo(mergeAll(contactInfoFromViewForm)));
}
private String mergeAll(ContactData contact) {
return Arrays.asList(contact.getHomephone(), contact.getMobilephone(),
contact.getWorkphone(), contact.getEmail(), contact.getEmail2(), contact.getEmail3())
.stream().filter((s) -> ! s.equals(""))
.map(ContactViewTests::cleaned)
.collect(Collectors.joining("\n"));
}
public static String cleaned(String phone){
return phone.replaceAll("\\s", "").replaceAll("[-()]", "");
}
} |
9243920a4c3071d3b16f4a768d4770e16ed73509 | 2,325 | java | Java | infer/models/java/src/java/io/DataOutputStream.java | ryoon/infer | 7b8dc59386529801f9a7fb67ead94053dbf53b42 | [
"BSD-3-Clause"
] | 1 | 2017-09-14T09:03:44.000Z | 2017-09-14T09:03:44.000Z | infer/models/java/src/java/io/DataOutputStream.java | ryoon/infer | 7b8dc59386529801f9a7fb67ead94053dbf53b42 | [
"BSD-3-Clause"
] | 2 | 2020-11-13T19:42:27.000Z | 2020-11-13T19:49:19.000Z | infer/models/java/src/java/io/DataOutputStream.java | ryoon/infer | 7b8dc59386529801f9a7fb67ead94053dbf53b42 | [
"BSD-3-Clause"
] | null | null | null | 28.353659 | 78 | 0.712688 | 1,002,700 | /*
* Copyright (c) 2013 - present Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package java.io;
import com.facebook.infer.builtins.InferUndefined;
public class DataOutputStream extends FilterOutputStream {
public DataOutputStream(OutputStream out) {
super(out);
}
public void flush() throws IOException {
InferUndefined.can_throw_ioexception_void();
}
public void write(byte b[], int off, int len) throws IOException {
InferUndefined.can_throw_ioexception_void();
}
public void write(byte b[]) throws IOException {
InferUndefined.can_throw_ioexception_void();
}
public void write(int b) throws IOException {
InferUndefined.can_throw_ioexception_void();
}
public final void writeBoolean(boolean v) throws IOException {
InferUndefined.can_throw_ioexception_void();
}
public final void writeByte(int v) throws IOException {
InferUndefined.can_throw_ioexception_void();
}
public final void writeBytes(String s) throws IOException {
InferUndefined.can_throw_ioexception_void();
}
public final void writeChar(int v) throws IOException {
InferUndefined.can_throw_ioexception_void();
}
public final void writeChars(String s) throws IOException {
InferUndefined.can_throw_ioexception_void();
}
public final void writeDouble(double v) throws IOException {
InferUndefined.can_throw_ioexception_void();
}
public final void writeFloat(float v) throws IOException {
InferUndefined.can_throw_ioexception_void();
}
public final void writeInt(int v) throws IOException {
InferUndefined.can_throw_ioexception_void();
}
public final void writeLong(long v) throws IOException {
InferUndefined.can_throw_ioexception_void();
}
public final void writeShort(int v) throws IOException {
InferUndefined.can_throw_ioexception_void();
}
public final void writeUTF(String str) throws IOException {
InferUndefined.can_throw_ioexception_void();
}
}
|
92439361bed5dfab49f786df9a6c6f16df5b8b5d | 1,580 | java | Java | geode-apis-compatible-with-redis/src/main/java/org/apache/geode/redis/internal/data/SizeableObjectSizer.java | gvaldez/incubator-geode | 138d5b8969a70bde07ad729461f1d914aa0b14f8 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | geode-apis-compatible-with-redis/src/main/java/org/apache/geode/redis/internal/data/SizeableObjectSizer.java | gvaldez/incubator-geode | 138d5b8969a70bde07ad729461f1d914aa0b14f8 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | geode-apis-compatible-with-redis/src/main/java/org/apache/geode/redis/internal/data/SizeableObjectSizer.java | gvaldez/incubator-geode | 138d5b8969a70bde07ad729461f1d914aa0b14f8 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | 40.512821 | 100 | 0.768354 | 1,002,701 | /*
* 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.geode.redis.internal.data;
import static org.apache.geode.redis.internal.netty.Coder.narrowLongToInt;
import org.apache.geode.internal.size.ReflectionSingleObjectSizer;
import org.apache.geode.internal.size.SingleObjectSizer;
import org.apache.geode.internal.size.Sizeable;
/**
* A sizer that allows for efficient sizing of objects that implement the {@link Sizeable}
* interface, and delegates to {@link ReflectionSingleObjectSizer} otherwise.
*/
public class SizeableObjectSizer {
private final SingleObjectSizer sizer = new ReflectionSingleObjectSizer();
public int sizeof(Object object) {
if (object instanceof Sizeable) {
return ((Sizeable) object).getSizeInBytes();
} else {
return narrowLongToInt(sizer.sizeof(object));
}
}
}
|
924394063ee986644f1e0717ff75b795d0b3735c | 543 | java | Java | src/main/java/org/loja/controller/subcontroller/jogo/RemoveItem.java | Logcod-informatica/lojavirtualweb | d614105414bb1b9d8f6755ce6cd516b2544019c0 | [
"Apache-2.0"
] | 1 | 2020-03-20T15:15:42.000Z | 2020-03-20T15:15:42.000Z | src/main/java/org/loja/controller/subcontroller/jogo/RemoveItem.java | Logcod-informatica/lojavirtualweb | d614105414bb1b9d8f6755ce6cd516b2544019c0 | [
"Apache-2.0"
] | 2 | 2022-02-16T01:06:15.000Z | 2022-02-16T01:07:38.000Z | src/main/java/org/loja/controller/subcontroller/jogo/RemoveItem.java | Logcod-informatica/lojavirtualweb | d614105414bb1b9d8f6755ce6cd516b2544019c0 | [
"Apache-2.0"
] | null | null | null | 28.578947 | 86 | 0.802947 | 1,002,702 | package org.loja.controller.subcontroller.jogo;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.loja.controller.carro.MeuCarro;
import org.loja.controller.subcontroller.ModelAndView;
public class RemoveItem implements ModelAndView {
MeuCarro mc = new MeuCarro();
public String setViewName(HttpServletRequest request, HttpServletResponse response) {
String value = request.getParameter("value");
mc.remove(value);
return "Controller?operacao=LojaVirtual&acao=jogo";
}
}
|
924395923f51b82727aea2f0e5e3f69b8b33a4ac | 1,122 | java | Java | components/org.wso2.carbon.siddhi.extensions.installer.core/src/main/java/org/wso2/carbon/siddhi/extensions/installer/core/config/mapping/models/UsageType.java | PrabodDunuwila/carbon-analytics | 4d2ec19dbdfa2b71ac8f4953d05ebc673b1737e3 | [
"Apache-2.0"
] | 28 | 2015-02-02T05:48:38.000Z | 2021-06-18T02:43:25.000Z | components/org.wso2.carbon.siddhi.extensions.installer.core/src/main/java/org/wso2/carbon/siddhi/extensions/installer/core/config/mapping/models/UsageType.java | PrabodDunuwila/carbon-analytics | 4d2ec19dbdfa2b71ac8f4953d05ebc673b1737e3 | [
"Apache-2.0"
] | 434 | 2015-01-15T14:45:49.000Z | 2022-03-14T11:11:57.000Z | components/org.wso2.carbon.siddhi.extensions.installer.core/src/main/java/org/wso2/carbon/siddhi/extensions/installer/core/config/mapping/models/UsageType.java | PrabodDunuwila/carbon-analytics | 4d2ec19dbdfa2b71ac8f4953d05ebc673b1737e3 | [
"Apache-2.0"
] | 292 | 2015-01-23T06:31:22.000Z | 2021-11-24T10:57:20.000Z | 37.4 | 116 | 0.729947 | 1,002,703 | /*
* Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.carbon.siddhi.extensions.installer.core.config.mapping.models;
/**
* Denotes the type of the jar (A bundle itself is a jar too, but with some added headers).
* The correct folder inside the base folder (decided based on {@link UsedByType}) - where the jar should be put to,
* will be decided based on this.
* Necessary jar to bundle conversion will be done during pack start-up.
*/
public enum UsageType {
JAR, BUNDLE
}
|
924396d7eec8feb3814772c2a1d31f2a91959345 | 1,873 | java | Java | app/src/main/java/com/wisbalam/server/algoritma/GraphToArray.java | fonysaputra/wisbalam | 5b7e37da5962290e8cb94da603d3a92d2b8a1af8 | [
"MIT"
] | null | null | null | app/src/main/java/com/wisbalam/server/algoritma/GraphToArray.java | fonysaputra/wisbalam | 5b7e37da5962290e8cb94da603d3a92d2b8a1af8 | [
"MIT"
] | null | null | null | app/src/main/java/com/wisbalam/server/algoritma/GraphToArray.java | fonysaputra/wisbalam | 5b7e37da5962290e8cb94da603d3a92d2b8a1af8 | [
"MIT"
] | null | null | null | 24.012821 | 133 | 0.673785 | 1,002,704 | package com.wisbalam.server.algoritma;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
/*
* CONVERT GRAPH FROM DB TO ARRAY
*/
public class GraphToArray {
// DB
SQLiteDatabase db;
protected Cursor cursor;
// Array Graph
String[][] graph = new String[1000][1000];
/* Convert Graph from DB to Array
* parameter mainContext : context MainActivity
* return array String[][]
*/
public String[][] convertToArray(Context mainContext){
// PINDAHKAN GRAPH DARI DB KE GRAPH ARRAY
cursor = db.rawQuery("SELECT * FROM graph order by simpul_awal,simpul_tujuan asc", null);
cursor.moveToFirst();
String temp_index_baris = "";
int index_kolom = 0;
int jml_baris = cursor.getCount();
for(int i = 0; i < jml_baris; i++){
// baris
cursor.moveToPosition(i);
// Cari index kolom
int simpulAwalDB = Integer.parseInt(cursor.getString(1)); // simpul_tujuan
if(temp_index_baris == ""){
temp_index_baris = String.valueOf(simpulAwalDB);
}else{
// simpul_awal berikutnya tidak sama dgn sebelumnya, reset index_kolom = 0
if(Integer.parseInt(temp_index_baris) != simpulAwalDB){
index_kolom = 0;
temp_index_baris = String.valueOf(simpulAwalDB);
}
}
// masukkan ke graph array
String simpulTujuan_dan_Bobot = "";
if(cursor.getString(2).equals("") && cursor.getString(3).equals("") && cursor.getString(4).equals("")){ //tidak ada derajat keluar
simpulTujuan_dan_Bobot = ";";
}
// ada derajat keluar
else{
// example output : 2->789.98
simpulTujuan_dan_Bobot = cursor.getString(2).toString()+"->"+cursor.getString(4).toString(); //simpul_tujuan dan bobot
}
graph[simpulAwalDB][index_kolom] = simpulTujuan_dan_Bobot;
index_kolom++;
}// for
return graph;
}
}
|
9243977f394e296ed7a9a484e83afeeae22de240 | 3,632 | java | Java | modules/core/src/main/java/org/apache/ignite/internal/util/lang/GridClosure3.java | DirectXceriD/gridgain | 093e512a9147e266f83f6fe1cf088c0b037b501c | [
"Apache-2.0",
"CC0-1.0"
] | 1 | 2019-03-11T08:52:37.000Z | 2019-03-11T08:52:37.000Z | modules/core/src/main/java/org/apache/ignite/internal/util/lang/GridClosure3.java | DirectXceriD/gridgain | 093e512a9147e266f83f6fe1cf088c0b037b501c | [
"Apache-2.0",
"CC0-1.0"
] | null | null | null | modules/core/src/main/java/org/apache/ignite/internal/util/lang/GridClosure3.java | DirectXceriD/gridgain | 093e512a9147e266f83f6fe1cf088c0b037b501c | [
"Apache-2.0",
"CC0-1.0"
] | null | null | null | 52.637681 | 107 | 0.736784 | 1,002,705 | /*
* GridGain Community Edition Licensing
* Copyright 2019 GridGain Systems, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License") modified with Commons Clause
* Restriction; 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.
*
* Commons Clause Restriction
*
* The Software is provided to you by the Licensor under the License, as defined below, subject to
* the following condition.
*
* Without limiting other conditions in the License, the grant of rights under the License will not
* include, and the License does not grant to you, the right to Sell the Software.
* For purposes of the foregoing, “Sell” means practicing any or all of the rights granted to you
* under the License to provide to third parties, for a fee or other consideration (including without
* limitation fees for hosting or consulting/ support services related to the Software), a product or
* service whose value derives, entirely or substantially, from the functionality of the Software.
* Any license notice or attribution required by the License must also include this Commons Clause
* License Condition notice.
*
* For purposes of the clause above, the “Licensor” is Copyright 2019 GridGain Systems, Inc.,
* the “License” is the Apache License, Version 2.0, and the Software is the GridGain Community
* Edition software provided with this notice.
*/
package org.apache.ignite.internal.util.lang;
import org.apache.ignite.internal.util.typedef.C3;
/**
* Defines generic {@code for-each} type of closure. Closure is a first-class function that is defined with
* (or closed over) its free variables that are bound to the closure scope at execution. Since
* Java 6 doesn't provide a language construct for first-class function the closures are implemented
* as abstract classes.
* <h2 class="header">Type Alias</h2>
* To provide for more terse code you can use a typedef {@link C3} class or various factory methods in
* {@link GridFunc} class. Note, however, that since typedefs in Java rely on inheritance you should
* not use these type aliases in signatures.
* <h2 class="header">Thread Safety</h2>
* Note that this interface does not impose or assume any specific thread-safety by its
* implementations. Each implementation can elect what type of thread-safety it provides,
* if any.
* @param <E1> Type of the first free variable, i.e. the element the closure is called or closed on.
* @param <E2> Type of the second free variable, i.e. the element the closure is called or closed on.
* @param <E3> Type of the third free variable, i.e. the element the closure is called or closed on.
* @param <R> Type of the closure's return value.
* @see C3
* @see GridFunc
*/
public interface GridClosure3<E1, E2, E3, R> {
/**
* Closure body.
*
* @param e1 First bound free variable, i.e. the element the closure is called or closed on.
* @param e2 Second bound free variable, i.e. the element the closure is called or closed on.
* @param e3 Third bound free variable, i.e. the element the closure is called or closed on.
* @return Optional return value.
*/
public R apply(E1 e1, E2 e2, E3 e3);
} |
924397d1cb94a085c6bf87c552f82ae4eea0c0a3 | 1,344 | java | Java | SurgeryLib/src/utils/RoomDetails.java | TomPoczos/Java-EE-Example | c1b81dbe145d6a50af18d69a23b2fd5351ed94ca | [
"Apache-2.0"
] | null | null | null | SurgeryLib/src/utils/RoomDetails.java | TomPoczos/Java-EE-Example | c1b81dbe145d6a50af18d69a23b2fd5351ed94ca | [
"Apache-2.0"
] | null | null | null | SurgeryLib/src/utils/RoomDetails.java | TomPoczos/Java-EE-Example | c1b81dbe145d6a50af18d69a23b2fd5351ed94ca | [
"Apache-2.0"
] | null | null | null | 23.172414 | 109 | 0.639881 | 1,002,706 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package utils;
/**
*
* @author Tom Poczos
*/
public class RoomDetails implements java.io.Serializable {
private String roomid;
private String roomnumber;
private Boolean hasfirstaidkit;
public RoomDetails(String roomid, String roomnumber, Boolean hasfirstaidkit) {
this.roomid = roomid;
this.roomnumber = roomnumber;
this.hasfirstaidkit = hasfirstaidkit;
}
public String getRoomid() {
return roomid;
}
public String getRoomnumber() {
return roomnumber;
}
public Boolean getHasfirstaidkit() {
return hasfirstaidkit;
}
public void setRoomid(String roomid) {
this.roomid = roomid;
}
public void setRoomnumber(String roomnumber) {
this.roomnumber = roomnumber;
}
public void setHasfirstaidkit(Boolean hasfirstaidkit) {
this.hasfirstaidkit = hasfirstaidkit;
}
@Override
public String toString() {
String hasKit = this.hasfirstaidkit ? "yes" : "no";
return "Room\t" + "ID: " + roomid + "\tRoom Number: " + roomnumber + "\thas firstaid Kit: " + hasKit;
}
}
|
924398c367ae890907b4a82fdf666f69b76ad514 | 516 | java | Java | src/main/java/org/n52/emodnet/eurofleets/feeder/datagram/ThermosalinityDatagram.java | janschulte/eurofleets-feeder | a7ad2dcd40e5ff22946cce24bb8335d07da0238f | [
"Apache-2.0"
] | null | null | null | src/main/java/org/n52/emodnet/eurofleets/feeder/datagram/ThermosalinityDatagram.java | janschulte/eurofleets-feeder | a7ad2dcd40e5ff22946cce24bb8335d07da0238f | [
"Apache-2.0"
] | 1 | 2020-03-17T22:09:02.000Z | 2020-03-17T22:09:02.000Z | src/main/java/org/n52/emodnet/eurofleets/feeder/datagram/ThermosalinityDatagram.java | janschulte/eurofleets-feeder | a7ad2dcd40e5ff22946cce24bb8335d07da0238f | [
"Apache-2.0"
] | 3 | 2020-03-17T22:01:41.000Z | 2020-04-03T15:11:21.000Z | 30.352941 | 79 | 0.718992 | 1,002,707 | package org.n52.emodnet.eurofleets.feeder.datagram;
import org.n52.emodnet.eurofleets.feeder.ObservedProperties;
public class ThermosalinityDatagram extends Datagram {
public ThermosalinityDatagram(String value) throws DatagramParseException {
super(value,
ObservedProperties.SALINITY,
ObservedProperties.WATER_TEMPERATURE,
ObservedProperties.RAW_FLUOROMETRY,
ObservedProperties.CONDUCTIVITY,
ObservedProperties.DENSITY);
}
}
|
92439990345db78e744c3266947fa270db7ffede | 2,140 | java | Java | app/src/main/java/com/example/user/indecisive/adapters/RandomPickAdapter.java | Fanner487/Indecisive | 51ce10996850a0ae8abd87b5d2172cb36ca7fa08 | [
"MIT"
] | null | null | null | app/src/main/java/com/example/user/indecisive/adapters/RandomPickAdapter.java | Fanner487/Indecisive | 51ce10996850a0ae8abd87b5d2172cb36ca7fa08 | [
"MIT"
] | null | null | null | app/src/main/java/com/example/user/indecisive/adapters/RandomPickAdapter.java | Fanner487/Indecisive | 51ce10996850a0ae8abd87b5d2172cb36ca7fa08 | [
"MIT"
] | null | null | null | 23.777778 | 98 | 0.642056 | 1,002,708 | package com.example.user.indecisive.adapters;
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.example.user.indecisive.R;
import com.example.user.indecisive.business.ItemChoice;
import java.util.ArrayList;
/**
* Created by Eamon on 11/11/2016.
*
* Adapter for RandomPick Activity
*/
public class RandomPickAdapter extends ArrayAdapter<ItemChoice>{
final String TAG = RandomPickAdapter.class.getSimpleName();
private Context context;
private ArrayList<ItemChoice> items;
private static LayoutInflater inflater = null;
public RandomPickAdapter(Context context, ArrayList<ItemChoice> objects) {
super(context, 0, objects);
try{
this.context = context;
this.items = objects;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
catch (Exception e){
e.printStackTrace();
}
}
//can add new item later
public static class ViewHolder{
//row layout
public TextView tvItemChoice;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getCount() {
return items.size();
}
@NonNull
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = null;
ViewHolder holder;
try {
if(convertView == null){
row = inflater.inflate(R.layout.row_random_pick_activity_list_item, null);
}
else{
row = convertView;
}
holder = new ViewHolder();
holder.tvItemChoice = (TextView) row.findViewById(R.id.adapter_random_pick_tv_choice);
holder.tvItemChoice.setText(items.get(position).getItem());
}
catch (Exception e){
e.printStackTrace();
}
return row;
}
}
|
92439a32f6cd336c1841856bfff469bd7c7bf486 | 977 | java | Java | src/ec/edu/ups/dao/UsuarioDAO.java | SUyaguari/Practica04-Patron-MVC | 6a9cc100f125beb8401bf40e4c57cc97cf43a172 | [
"MIT"
] | null | null | null | src/ec/edu/ups/dao/UsuarioDAO.java | SUyaguari/Practica04-Patron-MVC | 6a9cc100f125beb8401bf40e4c57cc97cf43a172 | [
"MIT"
] | null | null | null | src/ec/edu/ups/dao/UsuarioDAO.java | SUyaguari/Practica04-Patron-MVC | 6a9cc100f125beb8401bf40e4c57cc97cf43a172 | [
"MIT"
] | null | null | null | 20.787234 | 61 | 0.653019 | 1,002,709 | package ec.edu.ups.dao;
import ec.edu.ups.idao.IUsuarioDAO;
import ec.edu.ups.modelo.Usuario;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
*
* @author Estudiantes
*/
public class UsuarioDAO implements IUsuarioDAO{
private Map<String, Usuario> usuarios;
public UsuarioDAO() {
usuarios = new HashMap<String, Usuario>();
}
@Override
public Collection<Usuario> findAll() {
Collection<Usuario> usuario = this.usuarios.values();
return usuario;
}
@Override
public void create(Usuario usuario) {
usuarios.put(usuario.getCedula(), usuario);
}
@Override
public Usuario read(String cedula) {
return usuarios.get(cedula);
}
@Override
public void update(Usuario usuario) {
usuarios.put(usuario.getCedula(), usuario);
}
@Override
public void delite(Usuario usuario) {
usuarios.remove(usuario.getCedula());
}
}
|
92439b69624cdc350825699e7f1248f753a73f02 | 549 | java | Java | src/main/java/de/gerdrohleder/cocktails/data/service/AssemblyService.java | gRohleder/cocktails | 1c4b36d956dea5120c56ac7ff5da40fad16e32f7 | [
"Unlicense"
] | null | null | null | src/main/java/de/gerdrohleder/cocktails/data/service/AssemblyService.java | gRohleder/cocktails | 1c4b36d956dea5120c56ac7ff5da40fad16e32f7 | [
"Unlicense"
] | null | null | null | src/main/java/de/gerdrohleder/cocktails/data/service/AssemblyService.java | gRohleder/cocktails | 1c4b36d956dea5120c56ac7ff5da40fad16e32f7 | [
"Unlicense"
] | null | null | null | 26.142857 | 69 | 0.808743 | 1,002,710 | package de.gerdrohleder.cocktails.data.service;
import de.gerdrohleder.cocktails.data.entity.Assembly;
import de.gerdrohleder.cocktails.data.entity.Ingredient;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.vaadin.artur.helpers.CrudService;
@Service
@RequiredArgsConstructor
public class AssemblyService extends CrudService<Assembly, Integer> {
private final AssemblyRepository repository;
@Override
protected AssemblyRepository getRepository() {
return repository;
}
}
|
92439b70ab7eb3996ee5329c7d975448def133ce | 8,277 | java | Java | geode-core/src/integrationTest/java/org/apache/geode/internal/cache/PartitionedRegionQueryEvaluatorIntegrationTest.java | nikochiko/geode | 19f55add07d6a652911dc5a5e2116fcf7bf7b2f7 | [
"Apache-2.0"
] | 1,475 | 2016-12-06T06:10:53.000Z | 2022-03-30T09:55:23.000Z | geode-core/src/integrationTest/java/org/apache/geode/internal/cache/PartitionedRegionQueryEvaluatorIntegrationTest.java | nikochiko/geode | 19f55add07d6a652911dc5a5e2116fcf7bf7b2f7 | [
"Apache-2.0"
] | 2,809 | 2016-12-06T19:24:26.000Z | 2022-03-31T22:02:20.000Z | geode-core/src/integrationTest/java/org/apache/geode/internal/cache/PartitionedRegionQueryEvaluatorIntegrationTest.java | nikochiko/geode | 19f55add07d6a652911dc5a5e2116fcf7bf7b2f7 | [
"Apache-2.0"
] | 531 | 2016-12-06T05:48:47.000Z | 2022-03-31T23:06:37.000Z | 34.202479 | 100 | 0.678265 | 1,002,711 | /*
* 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.geode.internal.cache;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import org.apache.geode.cache.ExpirationAttributes;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.Scope;
import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
import org.apache.geode.internal.cache.BucketAdvisor.BucketProfile;
import org.apache.geode.internal.cache.partitioned.RegionAdvisor;
import org.apache.geode.internal.cache.partitioned.RegionAdvisor.PartitionProfile;
import org.apache.geode.internal.util.VersionedArrayList;
/**
* This class is an integration test for {@link PartitionedRegionQueryEvaluator} class.
*/
public class PartitionedRegionQueryEvaluatorIntegrationTest {
@Rule
public TestName name = new TestName();
/**
* Test for the helper method getNodeToBucketMap.
*/
@Test
public void testGetNodeToBucketMap() {
int totalNodes = 100;
String prPrefix = name.getMethodName();
String localMaxMemory = "0";
final int redundancy = 1;
final int totalNoOfBuckets = 5;
PartitionedRegion pr = (PartitionedRegion) PartitionedRegionTestHelper
.createPartitionedRegion(prPrefix, localMaxMemory, redundancy);
HashSet<Integer> bucketsToQuery = new HashSet<Integer>();
for (int i = 0; i < totalNoOfBuckets; i++) {
bucketsToQuery.add(i);
}
final String expectedUnknownHostException = UnknownHostException.class.getName();
pr.getCache().getLogger().info(
"<ExpectedException action=add>" + expectedUnknownHostException + "</ExpectedException>");
final ArrayList nodes = createNodeList(totalNodes);
pr.getCache().getLogger().info("<ExpectedException action=remove>"
+ expectedUnknownHostException + "</ExpectedException>");
// populating bucket2Node of the partition region
// ArrayList<InternalDistributedMember>
final ArrayList dses = createDataStoreList(totalNodes);
populateBucket2Node(pr, dses, totalNoOfBuckets);
populateAllPartitionedRegion(pr, nodes);
// running the algorithm and getting the list of bucktes to grab
PartitionedRegionQueryEvaluator evalr =
new PartitionedRegionQueryEvaluator(pr.getSystem(), pr, null, null, null, null,
bucketsToQuery);
Map n2bMap = null;
try {
n2bMap = evalr.buildNodeToBucketMap();
} catch (Exception ex) {
}
ArrayList buckList = new ArrayList();
for (Iterator itr = n2bMap.entrySet().iterator(); itr.hasNext();) {
Map.Entry entry = (Map.Entry) itr.next();
if (entry.getValue() != null) {
buckList.addAll((List) entry.getValue());
}
}
// checking size of the two lists
assertEquals("Unexpected number of buckets", totalNoOfBuckets, buckList.size());
for (int i = 0; i < totalNoOfBuckets; i++) {
assertTrue(" Bucket with Id = " + i + " not present in bucketList.",
buckList.contains(new Integer(i)));
}
pr.destroyRegion();
}
/**
* This function populates bucket2Node region of the partition region
*/
private void populateBucket2Node(PartitionedRegion pr, List nodes, int numOfBuckets) {
assertEquals(0, pr.getRegionAdvisor().getCreatedBucketsCount());
final RegionAdvisor ra = pr.getRegionAdvisor();
int nodeListCnt = 0;
Random ran = new Random();
HashMap verMap = new HashMap(); // Map tracking version for profile insertion purposes
for (int i = 0; i < numOfBuckets; i++) {
nodeListCnt = setNodeListCnt(nodeListCnt);
for (int j = 0; j < nodeListCnt; j++) {
BucketProfile bp = new BucketProfile();
bp.peerMemberId = (InternalDistributedMember) nodes.get(ran.nextInt(nodes.size()));
Integer v;
if ((v = (Integer) verMap.get(bp.getDistributedMember())) != null) {
bp.version = v.intValue() + 1;
verMap.put(bp.getDistributedMember(), new Integer(bp.version));
} else {
verMap.put(bp.getDistributedMember(), new Integer(0));
bp.version = 0;
}
bp.isHosting = true;
if (j == 0) {
bp.isPrimary = true;
}
bp.scope = Scope.DISTRIBUTED_ACK;
boolean forceBadProfile = true;
assertTrue(ra.getBucket(i).getBucketAdvisor().putProfile(bp, forceBadProfile));
}
}
}
/**
* This function decides number of the nodes in the list of bucket2Node region
*/
private int setNodeListCnt(int i) {
int nListcnt = 0;
switch (i) {
case 0:
nListcnt = 1;
break;
case 1:
nListcnt = 4;
break;
case 2:
nListcnt = 1;
break;
case 3:
nListcnt = 2;
break;
case 4:
nListcnt = 1;
break;
case 5:
nListcnt = 3;
break;
case 6:
nListcnt = 3;
break;
case 7:
nListcnt = 1;
break;
case 8:
nListcnt = 1;
break;
case 9:
nListcnt = 2;
break;
}
return nListcnt;
}
/**
* This functions number of new nodes specified by nCount.
*/
private ArrayList createNodeList(int nCount) {
ArrayList nodeList = new ArrayList(nCount);
for (int i = 0; i < nCount; i++) {
nodeList.add(createNode(i));
}
return nodeList;
}
private ArrayList createDataStoreList(int nCount) {
ArrayList nodeList = new ArrayList(nCount);
for (int i = 0; i < nCount; i++) {
nodeList.add(createDataStoreMember(i));
}
return nodeList;
}
private VersionedArrayList getVersionedNodeList(int nCount, List<Node> nodes) {
VersionedArrayList nodeList = new VersionedArrayList(nCount);
Random ran = new Random();
for (int i = 0; i < nCount; i++) {
nodeList.add(nodes.get(ran.nextInt(nodes.size())));
}
return nodeList;
}
private InternalDistributedMember createDataStoreMember(int i) {
return new InternalDistributedMember("host" + i, 3033);
}
/**
* this function creates new node.
*/
private Node createNode(int i) {
Node node = new Node(new InternalDistributedMember("host" + i, 3033), i);
node.setPRType(Node.DATASTORE);
return node;
}
private void populateAllPartitionedRegion(PartitionedRegion pr, List nodes) {
Region rootReg = PartitionedRegionHelper.getPRRoot(pr.getCache());
PartitionRegionConfig prConf = new PartitionRegionConfig(pr.getPRId(), pr.getFullPath(),
pr.getPartitionAttributes(), pr.getScope(), new EvictionAttributesImpl(),
new ExpirationAttributes(), new ExpirationAttributes(), new ExpirationAttributes(),
new ExpirationAttributes(), Collections.emptySet());
RegionAdvisor ra = pr.getRegionAdvisor();
for (Iterator itr = nodes.iterator(); itr.hasNext();) {
Node n = (Node) itr.next();
prConf.addNode(n);
PartitionProfile pp = (PartitionProfile) ra.createProfile();
pp.peerMemberId = n.getMemberId();
pp.isDataStore = true;
final boolean forceFakeProfile = true;
pr.getRegionAdvisor().putProfile(pp, forceFakeProfile);
}
rootReg.put(pr.getRegionIdentifier(), prConf);
}
}
|
92439d7d8ccbc9f882409bee50974dfd6c4e80a0 | 14,071 | java | Java | cdm/src/main/java/ucar/unidata/io/UncompressInputStream.java | joansmith2/thredds | ac321ce2a15f020f0cdef1ff9a2cf82261d8297c | [
"NetCDF"
] | 1 | 2018-04-24T13:53:46.000Z | 2018-04-24T13:53:46.000Z | cdm/src/main/java/ucar/unidata/io/UncompressInputStream.java | joansmith/thredds | 3e10f07b4d2f6b0f658e86327b8d4a5872fe1aa8 | [
"NetCDF"
] | 16 | 2016-04-11T06:42:41.000Z | 2019-05-03T04:04:50.000Z | cdm/src/main/java/ucar/unidata/io/UncompressInputStream.java | joansmith/thredds | 3e10f07b4d2f6b0f658e86327b8d4a5872fe1aa8 | [
"NetCDF"
] | 1 | 2019-07-22T19:57:26.000Z | 2019-07-22T19:57:26.000Z | 28.555781 | 102 | 0.586376 | 1,002,712 | /*
* Copyright 1998-2014 University Corporation for Atmospheric Research/Unidata
*
* Portions of this software were developed by the Unidata Program at the
* University Corporation for Atmospheric Research.
*
* Access and use of this software shall impose the following obligations
* and understandings on the user. The user is granted the right, without
* any fee or cost, to use, copy, modify, alter, enhance and distribute
* this software, and any derivative works thereof, and its supporting
* documentation for any purpose whatsoever, provided that this entire
* notice appears in all copies of the software, derivative works and
* supporting documentation. Further, UCAR requests that the user credit
* UCAR/Unidata in any publications that result from the use of this
* software or in any product that includes this software. The names UCAR
* and/or Unidata, however, may not be used in any advertising or publicity
* to endorse or promote any products or commercial entity unless specific
* written permission is obtained from UCAR/Unidata. The user also
* understands that UCAR/Unidata is not obligated to provide the user with
* any support, consulting, training or assistance of any kind with regard
* to the use, operation and performance of this software nor to provide
* the user with any updates, revisions, new versions or "bug fixes."
*
* THIS SOFTWARE IS PROVIDED BY UCAR/UNIDATA "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 UCAR/UNIDATA BE LIABLE FOR ANY SPECIAL,
* 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 ACCESS, USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package ucar.unidata.io;
import java.io.*;
/**
* This class decompresses an input stream containing data compressed with
* the unix "compress" utility (LZC, a LZW variant). This code is based
* heavily on the <var>unlzw.c</var> code in <var>gzip-1.2.4</var> (written
* by Peter Jannesen) and the original compress code.
*
*
* <p> This version has been modified from the original 0.3-3 version by the
* Unidata Program Center ([email protected]) to make the constructor
* public and to fix a couple of bugs.
* Also:
* - markSupported() returns false
* - add uncompress() static method
*
* @version 0.3-3 06/05/2001
* @author Ronald Tschalar
* @author Unidata Program Center
*/
public class UncompressInputStream extends FilterInputStream {
// string table stuff
private static final int TBL_CLEAR = 0x100;
private static final int TBL_FIRST = TBL_CLEAR + 1;
private int[] tab_prefix;
private byte[] tab_suffix;
private int[] zeros = new int[256];
private byte[] stack;
// various state
private boolean block_mode;
private int n_bits;
private int maxbits;
private int maxmaxcode;
private int maxcode;
private int bitmask;
private int oldcode;
private byte finchar;
private int stackp;
private int free_ent;
// input buffer
private byte[] data = new byte[10000];
private int bit_pos = 0, end = 0, got = 0;
private boolean eof = false;
private static final int EXTRA = 64;
/**
* @param is the input stream to decompress
* @throws IOException if the header is malformed
*/
public UncompressInputStream(InputStream is) throws IOException {
super(is);
parse_header();
}
private byte[] one = new byte[1];
@Override
public int read() throws IOException {
int b = read(one, 0, 1);
if (b == 1)
return (one[0] & 0xff);
else
return -1;
}
@Override
public int read(byte[] buf, int off, int len)
throws IOException {
if (eof) return -1;
int start = off;
/* Using local copies of various variables speeds things up by as
* much as 30% !
*/
int[] l_tab_prefix = tab_prefix;
byte[] l_tab_suffix = tab_suffix;
byte[] l_stack = stack;
int l_n_bits = n_bits;
int l_maxcode = maxcode;
int l_maxmaxcode = maxmaxcode;
int l_bitmask = bitmask;
int l_oldcode = oldcode;
byte l_finchar = finchar;
int l_stackp = stackp;
int l_free_ent = free_ent;
byte[] l_data = data;
int l_bit_pos = bit_pos;
// empty stack if stuff still left
int s_size = l_stack.length - l_stackp;
if (s_size > 0) {
int num = (s_size >= len) ? len : s_size;
System.arraycopy(l_stack, l_stackp, buf, off, num);
off += num;
len -= num;
l_stackp += num;
}
if (len == 0) {
stackp = l_stackp;
return off - start;
}
// loop, filling local buffer until enough data has been decompressed
main_loop: do {
if (end < EXTRA) fill();
int bit_in = (got > 0) ? (end - end % l_n_bits) << 3 :
(end << 3) - (l_n_bits - 1);
while (l_bit_pos < bit_in) {
// handle 1-byte reads correctly
if (len == 0) {
n_bits = l_n_bits;
maxcode = l_maxcode;
maxmaxcode = l_maxmaxcode;
bitmask = l_bitmask;
oldcode = l_oldcode;
finchar = l_finchar;
stackp = l_stackp;
free_ent = l_free_ent;
bit_pos = l_bit_pos;
return off - start;
}
// check for code-width expansion
if (l_free_ent > l_maxcode) {
int n_bytes = l_n_bits << 3;
l_bit_pos = (l_bit_pos - 1) +
n_bytes - (l_bit_pos - 1 + n_bytes) % n_bytes;
l_n_bits++;
l_maxcode = (l_n_bits == maxbits) ? l_maxmaxcode :
(1 << l_n_bits) - 1;
if (debug)
System.err.println("Code-width expanded to " + l_n_bits);
l_bitmask = (1 << l_n_bits) - 1;
l_bit_pos = resetbuf(l_bit_pos);
continue main_loop;
}
// read next code
int pos = l_bit_pos >> 3;
int code = (((l_data[pos] & 0xFF) | ((l_data[pos + 1] & 0xFF) << 8) |
((l_data[pos + 2] & 0xFF) << 16))
>> (l_bit_pos & 0x7)) & l_bitmask;
l_bit_pos += l_n_bits;
// handle first iteration
if (l_oldcode == -1) {
if (code >= 256)
throw new IOException("corrupt input: " + code +
" > 255");
l_finchar = (byte) (l_oldcode = code);
buf[off++] = l_finchar;
len--;
continue;
}
// handle CLEAR code
if (code == TBL_CLEAR && block_mode) {
System.arraycopy(zeros, 0, l_tab_prefix, 0, zeros.length);
l_free_ent = TBL_FIRST - 1;
int n_bytes = l_n_bits << 3;
l_bit_pos = (l_bit_pos - 1) +
n_bytes - (l_bit_pos - 1 + n_bytes) % n_bytes;
l_n_bits = INIT_BITS;
l_maxcode = (1 << l_n_bits) - 1;
l_bitmask = l_maxcode;
if (debug) System.err.println("Code tables reset");
l_bit_pos = resetbuf(l_bit_pos);
continue main_loop;
}
// setup
int incode = code;
l_stackp = l_stack.length;
// Handle KwK case
if (code >= l_free_ent) {
if (code > l_free_ent)
throw new IOException("corrupt input: code=" + code +
", free_ent=" + l_free_ent);
l_stack[--l_stackp] = l_finchar;
code = l_oldcode;
}
// Generate output characters in reverse order
while (code >= 256) {
l_stack[--l_stackp] = l_tab_suffix[code];
code = l_tab_prefix[code];
}
l_finchar = l_tab_suffix[code];
buf[off++] = l_finchar;
len--;
// And put them out in forward order
s_size = l_stack.length - l_stackp;
int num = (s_size >= len) ? len : s_size;
System.arraycopy(l_stack, l_stackp, buf, off, num);
off += num;
len -= num;
l_stackp += num;
// generate new entry in table
if (l_free_ent < l_maxmaxcode) {
l_tab_prefix[l_free_ent] = l_oldcode;
l_tab_suffix[l_free_ent] = l_finchar;
l_free_ent++;
}
// Remember previous code
l_oldcode = incode;
// if output buffer full, then return
if (len == 0) {
n_bits = l_n_bits;
maxcode = l_maxcode;
bitmask = l_bitmask;
oldcode = l_oldcode;
finchar = l_finchar;
stackp = l_stackp;
free_ent = l_free_ent;
bit_pos = l_bit_pos;
return off - start;
}
}
l_bit_pos = resetbuf(l_bit_pos);
} while (got > 0);
n_bits = l_n_bits;
maxcode = l_maxcode;
bitmask = l_bitmask;
oldcode = l_oldcode;
finchar = l_finchar;
stackp = l_stackp;
free_ent = l_free_ent;
bit_pos = l_bit_pos;
eof = true;
return off - start;
}
// Moves the unread data in the buffer to the beginning and resets the pointers.
// @return 0
private int resetbuf(int bit_pos) {
int pos = bit_pos >> 3;
System.arraycopy(data, pos, data, 0, end - pos);
end -= pos;
return 0;
}
private void fill() throws IOException {
got = in.read(data, end, data.length - 1 - end);
if (got > 0) end += got;
}
@Override
public long skip(long num) throws IOException {
byte[] tmp = new byte[(int) num];
int got = read(tmp, 0, (int) num);
if (got > 0)
return (long) got;
else
return 0L;
}
@Override
public int available() throws IOException {
if (eof) return 0;
// Fred Hansen, 2008
// the old code follows. it fails because read() can return bytes even after exhausting in.read()
// return in.available();
int avail = in.available();
return (avail == 0) ? 1 : avail;
}
private static final int LZW_MAGIC = 0x1f9d;
private static final int MAX_BITS = 16;
private static final int INIT_BITS = 9;
private static final int HDR_MAXBITS = 0x1f;
private static final int HDR_EXTENDED = 0x20;
private static final int HDR_FREE = 0x40;
private static final int HDR_BLOCK_MODE = 0x80;
private void parse_header() throws IOException {
// read in and check magic number
int t = in.read();
if (t < 0) throw new EOFException("Failed to read magic number");
int magic = (t & 0xff) << 8;
t = in.read();
if (t < 0) throw new EOFException("Failed to read magic number");
magic += t & 0xff;
if (magic != LZW_MAGIC)
throw new IOException("Input not in compress format (read " +
"magic number 0x" +
Integer.toHexString(magic) + ")");
// read in header byte
int header = in.read();
if (header < 0) throw new EOFException("Failed to read header");
block_mode = (header & HDR_BLOCK_MODE) > 0;
maxbits = header & HDR_MAXBITS;
if (maxbits > MAX_BITS)
throw new IOException("Stream compressed with " + maxbits +
" bits, but can only handle " + MAX_BITS +
" bits");
if ((header & HDR_EXTENDED) > 0)
throw new IOException("Header extension bit set");
if ((header & HDR_FREE) > 0)
throw new IOException("Header bit 6 set");
if (debug) {
System.err.println("block mode: " + block_mode);
System.err.println("max bits: " + maxbits);
}
// initialize stuff
maxmaxcode = 1 << maxbits;
n_bits = INIT_BITS;
maxcode = (1 << n_bits) - 1;
bitmask = maxcode;
oldcode = -1;
finchar = 0;
free_ent = block_mode ? TBL_FIRST : 256;
tab_prefix = new int[1 << maxbits];
tab_suffix = new byte[1 << maxbits];
stack = new byte[1 << maxbits];
stackp = stack.length;
for (int idx = 255; idx >= 0; idx--)
tab_suffix[idx] = (byte) idx;
}
/**
* This stream does not support mark/reset on the stream.
*
* @return false
*/
@Override
public boolean markSupported() {
return false;
}
static public void uncompress( String fileInName, FileOutputStream out) throws IOException {
long start = System.currentTimeMillis();
InputStream in = new UncompressInputStream( new FileInputStream(fileInName));
int total = 0;
byte[] buffer = new byte[100000];
while (true) {
int bytesRead = in.read(buffer);
if (bytesRead == -1) break;
out.write(buffer, 0, bytesRead);
total += bytesRead;
}
in.close();
out.close();
if (debugTiming) {
long end = System.currentTimeMillis();
System.err.println("Decompressed " + total + " bytes");
System.err.println("Time: " + (end - start) / 1000. + " seconds");
}
}
private static final boolean debug = false, debugTiming = false;
/** test */
public static void main(String args[]) throws Exception {
if (args.length != 1) {
System.err.println("Usage: UncompressInputStream <file>");
System.exit(1);
}
try (InputStream in =
new UncompressInputStream(new FileInputStream(args[0]))) {
byte[] buf = new byte[100000];
int tot = 0;
long beg = System.currentTimeMillis();
while (true) {
int got = in.read(buf);
if (got < 0) break;
System.out.write(buf, 0, got);
tot += got;
}
long end = System.currentTimeMillis();
System.err.println("Decompressed " + tot + " bytes");
System.err.println("Time: " + (end - beg) / 1000. + " seconds");
}
}
}
|
92439e9fe4439eda53b45a2c7679d3959c694258 | 1,269 | java | Java | src/main/java/com/clashsoft/hypercube/instruction/DirectionInstruction.java | Clashsoft/Hypercube | c9b2a1b593b8a2d8d42ffb99ae0aa704998e4917 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/com/clashsoft/hypercube/instruction/DirectionInstruction.java | Clashsoft/Hypercube | c9b2a1b593b8a2d8d42ffb99ae0aa704998e4917 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/com/clashsoft/hypercube/instruction/DirectionInstruction.java | Clashsoft/Hypercube | c9b2a1b593b8a2d8d42ffb99ae0aa704998e4917 | [
"BSD-3-Clause"
] | null | null | null | 20.467742 | 90 | 0.77699 | 1,002,713 | package com.clashsoft.hypercube.instruction;
import com.clashsoft.hypercube.state.Direction;
import com.clashsoft.hypercube.state.ExecutionException;
import com.clashsoft.hypercube.state.ExecutionState;
import com.clashsoft.hypercube.util.I18n;
import javafx.scene.paint.Material;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
public class DirectionInstruction implements Instruction
{
private final byte id;
private final String description;
private final Material material;
private final Direction direction;
public DirectionInstruction(byte id, String desc, Material material, Direction direction)
{
this.id = id;
this.description = desc;
this.material = material;
this.direction = direction;
}
@Override
public byte getID()
{
return this.id;
}
@Override
public void writeData(DataOutput dataOutput) throws IOException
{
}
@Override
public void readData(DataInput dataInput) throws IOException
{
}
@Override
public String getDescription()
{
return I18n.getString(this.description);
}
@Override
public Material getMaterial()
{
return this.material;
}
@Override
public void execute(ExecutionState state) throws ExecutionException
{
state.setDirection(this.direction);
}
}
|
92439ecfbcf25c5dd793d785e96a52fafc4c12c9 | 63 | java | Java | pss/src/test/java/net/es/oscars/pss/ctg/UnitTests.java | StackV/oscars | 23725dfdf42f2eda93799ec3dc9c16fcc9abf3e0 | [
"MIT"
] | 10 | 2015-03-17T19:11:30.000Z | 2018-03-16T13:52:14.000Z | pss/src/test/java/net/es/oscars/pss/ctg/UnitTests.java | esnet/oscars | 2dbc6b484dc537c6fd18bd7c43df31386d82195b | [
"MIT"
] | 41 | 2016-05-17T20:15:36.000Z | 2022-02-26T10:05:08.000Z | pss/src/test/java/net/es/oscars/pss/ctg/UnitTests.java | StackV/oscars | 23725dfdf42f2eda93799ec3dc9c16fcc9abf3e0 | [
"MIT"
] | 4 | 2016-01-19T14:35:28.000Z | 2021-07-22T15:53:31.000Z | 12.6 | 30 | 0.761905 | 1,002,714 | package net.es.oscars.pss.ctg;
public interface UnitTests {
}
|
9243a09d455e7483a52f861b2ab6af6d93612b97 | 258 | java | Java | blog-service/src/main/java/org/zhuqigong/blogservice/model/MinPost.java | chu4j/my-spring-cloud-blog | d1b63dbd5a663fb0740ec8c07062f783adf95564 | [
"Apache-2.0"
] | null | null | null | blog-service/src/main/java/org/zhuqigong/blogservice/model/MinPost.java | chu4j/my-spring-cloud-blog | d1b63dbd5a663fb0740ec8c07062f783adf95564 | [
"Apache-2.0"
] | null | null | null | blog-service/src/main/java/org/zhuqigong/blogservice/model/MinPost.java | chu4j/my-spring-cloud-blog | d1b63dbd5a663fb0740ec8c07062f783adf95564 | [
"Apache-2.0"
] | null | null | null | 17.2 | 51 | 0.72093 | 1,002,715 | package org.zhuqigong.blogservice.model;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
public interface MinPost {
Long getId();
String getTitle();
@JsonFormat(pattern = "yyyy-MM-dd")
Date getPublishTime();
}
|
9243a0f59049b986ffee6e0f5b97eb35e0f1a9e4 | 654 | java | Java | keanu-project/src/main/java/io/improbable/keanu/util/io/EdgeDotLabel.java | rs992214/keanu | f7f9b877aaaf9c9f732604f17da238e15dfdad13 | [
"MIT"
] | 153 | 2018-04-06T13:30:31.000Z | 2022-01-31T10:05:27.000Z | keanu-project/src/main/java/io/improbable/keanu/util/io/EdgeDotLabel.java | shinnlok/keanu | c75b2a00571a0da93c6b1d5e9f0cbe09aebdde4d | [
"MIT"
] | 168 | 2018-04-06T16:37:33.000Z | 2021-09-27T21:43:54.000Z | keanu-project/src/main/java/io/improbable/keanu/util/io/EdgeDotLabel.java | shinnlok/keanu | c75b2a00571a0da93c6b1d5e9f0cbe09aebdde4d | [
"MIT"
] | 46 | 2018-04-10T10:46:01.000Z | 2022-02-24T02:53:50.000Z | 29.727273 | 119 | 0.633028 | 1,002,716 | package io.improbable.keanu.util.io;
import org.apache.commons.lang3.StringUtils;
public class EdgeDotLabel {
private static final String DOT_LABEL_OPENING = " [label=";
private static final String DOT_LABEL_CLOSING = "]";
public static String inDotFormat(GraphEdge edge) {
String dotOutput = "<" + edge.getParentVertex().hashCode() + "> -> <" + edge.getChildVertex().hashCode() + ">";
if (!edge.getLabels().isEmpty()) {
dotOutput += DOT_LABEL_OPENING;
dotOutput += StringUtils.join(edge.getLabels(), ", ");
dotOutput += DOT_LABEL_CLOSING;
}
return dotOutput;
}
}
|
9243a40e036e6eae12f16e8f9f0c2695d7424b27 | 4,626 | java | Java | megaguards/edu.uci.megaguards/src/edu/uci/megaguards/MGNodeOptions.java | securesystemslab/megaguards | 8064db26e1a8a41871048fbf58be965a62690d60 | [
"BSD-3-Clause"
] | 1 | 2018-07-19T21:15:57.000Z | 2018-07-19T21:15:57.000Z | megaguards/edu.uci.megaguards/src/edu/uci/megaguards/MGNodeOptions.java | securesystemslab/megaguards | 8064db26e1a8a41871048fbf58be965a62690d60 | [
"BSD-3-Clause"
] | null | null | null | megaguards/edu.uci.megaguards/src/edu/uci/megaguards/MGNodeOptions.java | securesystemslab/megaguards | 8064db26e1a8a41871048fbf58be965a62690d60 | [
"BSD-3-Clause"
] | null | null | null | 32.125 | 87 | 0.641375 | 1,002,717 | /*
* Copyright (c) 2018, Regents of the University of California
* 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 edu.uci.megaguards;
import java.util.HashMap;
import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary;
public class MGNodeOptions {
private static final HashMap<Integer, MGNodeOptions> nodeOptions = new HashMap<>();
private final static String MGtag = "@mg:";
public final static String OFF = MGtag + "off";
public final static String DD_OFF = MGtag + "ddoff";
public final static String DD_OFF_ALL = MGtag + "ddoff-all";
public final static String REDUCE_ON = MGtag + "reduce-on";
private boolean MGOff;
private boolean ddOff;
private boolean ddOffAll;
private boolean reduceOn;
public MGNodeOptions() {
this.MGOff = false;
this.ddOff = false;
this.ddOffAll = false;
this.reduceOn = false;
}
public void setDDOff(boolean ddOff) {
this.ddOff = ddOff;
}
public void setDDOffAll(boolean ddOffAll) {
this.ddOffAll = ddOffAll;
this.ddOff = this.ddOff || ddOffAll;
}
public boolean isReduceOn() {
return reduceOn;
}
public void setReduceOn(boolean reduceOn) {
this.reduceOn = reduceOn;
}
public void setMGOff(boolean MGOff) {
this.MGOff = MGOff;
}
public boolean isMGOff() {
return MGOff;
}
public boolean isDDOff() {
return ddOff;
}
public boolean isDDOffAll() {
return ddOffAll;
}
public MGNodeOptions merge(MGNodeOptions opt) {
if (opt != null) {
this.MGOff = this.MGOff || opt.MGOff;
this.ddOff = this.ddOff || opt.ddOff || opt.ddOffAll;
this.ddOffAll = this.ddOffAll || opt.ddOffAll;
this.reduceOn = this.reduceOn || opt.reduceOn;
}
return this;
}
@TruffleBoundary
public static boolean hasOptions(int hashCode) {
return nodeOptions.containsKey(hashCode);
}
@TruffleBoundary
public static MGNodeOptions getOptions(int hashCode) {
return nodeOptions.get(hashCode);
}
@TruffleBoundary
public static void addOptions(int hashCode, MGNodeOptions options) {
nodeOptions.put(hashCode, options);
}
@TruffleBoundary
public static void removeOptions(int hashCode) {
nodeOptions.remove(hashCode);
}
public static void processOptions(String s, int hashCode) {
String[] options = s.toLowerCase().split(" ");
boolean set = false;
MGNodeOptions nodeOpts = new MGNodeOptions();
for (String opt : options) {
if (opt.startsWith(MGtag)) {
if (opt.contentEquals(OFF)) {
nodeOpts.setMGOff(true);
set = true;
} else if (opt.contentEquals(DD_OFF)) {
nodeOpts.setDDOff(true);
set = true;
} else if (opt.contentEquals(DD_OFF_ALL)) {
nodeOpts.setDDOffAll(true);
set = true;
} else if (opt.contentEquals(REDUCE_ON)) {
nodeOpts.setReduceOn(true);
set = true;
}
}
}
if (set)
addOptions(hashCode, nodeOpts);
}
}
|
9243a537214f67059988af83aca93d90195045ce | 1,767 | java | Java | base/src/test/java/tv/mechjack/mechjackbot/chatbot/DefaultChatBotConfiguration_TwitchClientConfigurationUnitTests.java | mechjacktv/mechjackbot | 67eae2b3459436036096c9196074fe84b36008d7 | [
"MIT"
] | 1 | 2019-02-13T02:00:01.000Z | 2019-02-13T02:00:01.000Z | base/src/test/java/tv/mechjack/mechjackbot/chatbot/DefaultChatBotConfiguration_TwitchClientConfigurationUnitTests.java | mechjacktv/mechjackbot | 67eae2b3459436036096c9196074fe84b36008d7 | [
"MIT"
] | 59 | 2018-10-20T20:44:52.000Z | 2019-03-04T01:36:43.000Z | base/src/test/java/tv/mechjack/mechjackbot/chatbot/DefaultChatBotConfiguration_TwitchClientConfigurationUnitTests.java | mechjacktv/mechjackbot | 67eae2b3459436036096c9196074fe84b36008d7 | [
"MIT"
] | 1 | 2019-02-20T15:46:54.000Z | 2019-02-20T15:46:54.000Z | 47.756757 | 120 | 0.837578 | 1,002,718 | package tv.mechjack.mechjackbot.chatbot;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import tv.mechjack.platform.application.Application;
import tv.mechjack.platform.application.TestApplicationModule;
import tv.mechjack.platform.utils.scheduleservice.MapHotUpdatePropertiesSource;
import tv.mechjack.platform.utils.scheduleservice.ScheduleService;
import tv.mechjack.platform.utils.scheduleservice.TestScheduleServiceModule;
import tv.mechjack.twitchclient.TwitchClientConfiguration;
import tv.mechjack.twitchclient.TwitchClientConfigurationContractTests;
public class DefaultChatBotConfiguration_TwitchClientConfigurationUnitTests extends
TwitchClientConfigurationContractTests {
@Override
protected void installModules() {
this.testFrameworkRule.registerModule(new TestApplicationModule());
this.testFrameworkRule.registerModule(new TestScheduleServiceModule());
}
@Override
protected TwitchClientConfiguration givenASubjectToTest(Optional<String> clientId) {
final Map<String, String> properties = new HashMap<>();
clientId.ifPresent((value) -> properties.put(DefaultChatBotConfiguration.TWITCH_CLIENT_ID_KEY, value));
properties.put(DefaultChatBotConfiguration.TWITCH_CHANNEL_KEY, this.testFrameworkRule.arbitraryData().getString());
properties.put(DefaultChatBotConfiguration.TWITCH_PASSWORD_KEY, this.testFrameworkRule.arbitraryData().getString());
properties.put(DefaultChatBotConfiguration.TWITCH_LOGIN_KEY, this.testFrameworkRule.arbitraryData().getString());
return new DefaultChatBotConfiguration(this.testFrameworkRule.getInstance(Application.class),
new MapHotUpdatePropertiesSource(properties), this.testFrameworkRule.getInstance(ScheduleService.class));
}
}
|
9243a555bc56697d2be87a3bef108364728822e6 | 1,858 | java | Java | theory/functional/src/test/java/chapter8/AdvancedListsTest.java | spencercjh/codeLife | be27d99380c0a1bdf4bea9a86b0d436deb7e2d2d | [
"Apache-2.0"
] | 5 | 2019-11-06T00:18:53.000Z | 2021-07-08T11:01:37.000Z | theory/functional/src/test/java/chapter8/AdvancedListsTest.java | spencercjh/leetcode | be27d99380c0a1bdf4bea9a86b0d436deb7e2d2d | [
"Apache-2.0"
] | null | null | null | theory/functional/src/test/java/chapter8/AdvancedListsTest.java | spencercjh/leetcode | be27d99380c0a1bdf4bea9a86b0d436deb7e2d2d | [
"Apache-2.0"
] | 1 | 2020-10-22T18:10:01.000Z | 2020-10-22T18:10:01.000Z | 19.557895 | 93 | 0.577503 | 1,002,719 | package chapter8;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@Slf4j
class AdvancedListsTest {
private final Integer[] numbers = new Integer[]{1, 2, 3, 4, 5};
@Test
void flattenResult() {
}
@Test
void sequence() {
}
@Test
void sequenceFilterEmpty() {
}
@Test
void traverse() {
}
@Test
void sequenceWithTraverse() {
}
@Test
void sequenceFilterEmptyWithTraverse() {
}
@Test
void zipWith() {
}
@Test
void lengthMemorized() {
}
@Test
void headOption() {
}
@Test
void lastOption() {
}
@Test
void foldLeft() {
}
@Test
void getAt() {
AdvancedList<Integer> list = AdvancedList.list(numbers);
assertEquals(numbers[0], list.getAt(0).getOrElse(2));
}
@Test
void groupBy() {
AdvancedList<Integer> list = AdvancedList.list(numbers);
Map<String, AdvancedList<Integer>> map = list.groupBy(x -> x % 2 == 0 ? "偶数" : "奇数");
map.forEach((s, integerAdvancedList) ->
log.debug("key: {} values: {}", s, integerAdvancedList.toString()));
assertTrue(map.containsKey("偶数"));
assertEquals(2, map.get("偶数").lengthMemorized());
assertTrue(map.containsKey("奇数"));
assertEquals(3, map.get("奇数").lengthMemorized());
}
@Test
void exists() {
AdvancedList<Integer> list = AdvancedList.list(numbers);
assertTrue(list.exists((Integer x) -> x % 2 == 0));
assertTrue(list.exists((Integer x) -> x % 2 != 0));
}
@Test
void forAll() {
}
@Test
void divide() {
}
@Test
void splitListAt() {
}
} |
9243a589fe0069993ac32ed60b9b3fc579337868 | 768 | java | Java | src/main/java/org/occideas/qsf/response/SurveyOptionResponse.java | DataScientists/OccIDEAS | 0f73e5e8840da15bdc7d7e733380bfefd963fd3c | [
"MIT"
] | 2 | 2019-02-14T04:40:49.000Z | 2019-04-02T11:22:42.000Z | src/main/java/org/occideas/qsf/response/SurveyOptionResponse.java | DataScientists/OccIDEAS | 0f73e5e8840da15bdc7d7e733380bfefd963fd3c | [
"MIT"
] | 9 | 2020-08-16T01:36:38.000Z | 2022-01-30T12:54:42.000Z | src/main/java/org/occideas/qsf/response/SurveyOptionResponse.java | DataScientists/OccIDEAS | 0f73e5e8840da15bdc7d7e733380bfefd963fd3c | [
"MIT"
] | null | null | null | 24.774194 | 56 | 0.733073 | 1,002,720 | package org.occideas.qsf.response;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.occideas.qsf.BaseResponse;
import org.occideas.qsf.payload.SurveyOptionPayload;
public class SurveyOptionResponse extends BaseResponse {
private String requestId;
@JsonProperty("result")
@JsonInclude(JsonInclude.Include.NON_NULL)
private SurveyOptionPayload result;
public String getRequestId() {
return requestId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
public SurveyOptionPayload getResult() {
return result;
}
public void setResult(SurveyOptionPayload result) {
this.result = result;
}
}
|
9243a62fa90d61587ad217f9f93cab9dfac6c12f | 721 | java | Java | src/main/java/service/base/KeepAliveService.java | hazik1024/CipherBook | a74e2cc2185e7a2035d14c2dbaec055dc0632f16 | [
"Apache-2.0"
] | null | null | null | src/main/java/service/base/KeepAliveService.java | hazik1024/CipherBook | a74e2cc2185e7a2035d14c2dbaec055dc0632f16 | [
"Apache-2.0"
] | null | null | null | src/main/java/service/base/KeepAliveService.java | hazik1024/CipherBook | a74e2cc2185e7a2035d14c2dbaec055dc0632f16 | [
"Apache-2.0"
] | null | null | null | 27.730769 | 130 | 0.714286 | 1,002,721 | package service.base;
import enums.ServiceCode;
import enums.ServiceType;
import enums.Topid;
import actions.KeepAliveAction;
import actions.RequestAction;
public class KeepAliveService extends BaseService {
public KeepAliveService() {
super(ServiceType.business, "心跳服务");
}
public Topid getTopid() {
return Topid.keepalive;
}
public void processing(RequestAction requestAction) {
KeepAliveAction action = new KeepAliveAction();
requestAction.setBaseAction(action);
requestAction.setServiceCode(ServiceCode.success);
logger.info(requestAction.getTopid() + ", "+ requestAction.getBufferId() + ", " + requestAction.getData().toJSONString());
}
}
|
9243a728962faaebdc352790d364627bcd63eba0 | 1,899 | java | Java | src/test/java/com/whiteclarkegroup/liquibaselinter/integration/PrimaryKeyNameIntegrationTest.java | dom54/liquibase-linter | 4dba3246f42a09c1ab1b44a90acd259d480871d1 | [
"Apache-2.0"
] | 15 | 2018-08-10T07:41:51.000Z | 2022-03-01T17:10:41.000Z | src/test/java/com/whiteclarkegroup/liquibaselinter/integration/PrimaryKeyNameIntegrationTest.java | dom54/liquibase-linter | 4dba3246f42a09c1ab1b44a90acd259d480871d1 | [
"Apache-2.0"
] | 61 | 2018-08-24T08:00:59.000Z | 2022-02-26T01:37:48.000Z | src/test/java/com/whiteclarkegroup/liquibaselinter/integration/PrimaryKeyNameIntegrationTest.java | dom54/liquibase-linter | 4dba3246f42a09c1ab1b44a90acd259d480871d1 | [
"Apache-2.0"
] | 5 | 2018-11-21T08:20:30.000Z | 2020-08-29T13:05:59.000Z | 45.214286 | 133 | 0.670353 | 1,002,722 | package com.whiteclarkegroup.liquibaselinter.integration;
import com.whiteclarkegroup.liquibaselinter.resolvers.LiquibaseIntegrationTestResolver;
import org.junit.jupiter.api.extension.ExtendWith;
@ExtendWith(LiquibaseIntegrationTestResolver.class)
class PrimaryKeyNameIntegrationTest extends LinterIntegrationTest {
@Override
void registerTests() {
shouldFail(
"Should fail when the table name can't be enforced but the suffix isn't used",
"primary-key-name/primary-key-name-fail-on-suffix.xml",
"primary-key-name/primary-key-name-complex.json",
"Primary key constraint 'NOT_EVEN_CLOSE' must be named, ending with '_PK', and start with table name (unless too long)");
shouldFail(
"Should fail when the table name can be enforced and isn't used",
"primary-key-name/primary-key-name-fail-on-tablename.xml",
"primary-key-name/primary-key-name-complex.json",
"Primary key constraint 'BAZ_PK' must be named, ending with '_PK', and start with table name (unless too long)");
shouldPass(
"Should pass when used correctly",
"primary-key-name/primary-key-name-pass.xml",
"primary-key-name/primary-key-name-complex.json");
shouldFail(
"Should fail when omitted with simple config",
"primary-key-name/primary-key-name-fail-omitted.xml",
"primary-key-name/primary-key-name-simple.json",
"Primary key name is missing or does not follow pattern");
shouldFail(
"Should fail when omitted with complex config",
"primary-key-name/primary-key-name-fail-omitted.xml",
"primary-key-name/primary-key-name-complex.json",
"Primary key constraint '' must be named, ending with '_PK', and start with table name (unless too long)");
}
}
|
9243a86ed14cd22ee3660f9bc686a154ef3dfe5c | 265 | java | Java | Ace IM/src/aceim/app/themeable/dataentity/HistoryMessageItemThemeResource.java | plyhun/aceim | 58c57064caf8a8cf394bf71c02c583ccdd783907 | [
"Apache-2.0"
] | 6 | 2015-01-13T07:05:13.000Z | 2017-07-10T22:44:28.000Z | Ace IM/src/aceim/app/themeable/dataentity/HistoryMessageItemThemeResource.java | plyhun/aceim | 58c57064caf8a8cf394bf71c02c583ccdd783907 | [
"Apache-2.0"
] | 2 | 2017-02-21T08:31:53.000Z | 2017-08-23T07:22:03.000Z | Ace IM/src/aceim/app/themeable/dataentity/HistoryMessageItemThemeResource.java | plyhun/aceim | 58c57064caf8a8cf394bf71c02c583ccdd783907 | [
"Apache-2.0"
] | 5 | 2015-01-13T07:05:12.000Z | 2021-12-09T06:52:36.000Z | 22.083333 | 84 | 0.784906 | 1,002,723 | package aceim.app.themeable.dataentity;
import android.content.Context;
public class HistoryMessageItemThemeResource extends ChatMessageItemThemeResource {
public HistoryMessageItemThemeResource(Context context, int id) {
super(context, id);
}
}
|
9243a8909eae5c4eb2493df7444a159613983009 | 6,415 | java | Java | app/src/main/java/com/onimus/munote/ui/activity/NotesActivity.java | MurilloComino/Munotes | 887934e4b1cbe9579730f1deb71728e268885d1a | [
"Apache-2.0"
] | 1 | 2020-05-31T08:50:11.000Z | 2020-05-31T08:50:11.000Z | app/src/main/java/com/onimus/munote/ui/activity/NotesActivity.java | MurilloComino/Munotes | 887934e4b1cbe9579730f1deb71728e268885d1a | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/onimus/munote/ui/activity/NotesActivity.java | MurilloComino/Munotes | 887934e4b1cbe9579730f1deb71728e268885d1a | [
"Apache-2.0"
] | null | null | null | 33.989418 | 164 | 0.677148 | 1,002,724 | /*
*
* * Created by Murillo Comino on 09/02/19 12:26
* * Github: github.com/MurilloComino
* * StackOverFlow: pt.stackoverflow.com/users/128573
* * Email: [email protected]
* *
* * Copyright (c) 2019 . All rights reserved.
* * Last modified 09/02/19 12:11
*
*/
package com.onimus.munote.ui.activity;
import androidx.lifecycle.ViewModelProviders;
import android.content.Context;
import android.os.Bundle;
import androidx.appcompat.widget.Toolbar;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import com.onimus.munote.R;
import com.onimus.munote.repository.database.HMAuxNotes;
import com.onimus.munote.repository.database.RecordListNotesAdapter;
import com.onimus.munote.repository.dao.NotesDao;
import com.onimus.munote.repository.model.NotesActivityViewModel;
import com.onimus.munote.repository.model.Filters;
import com.onimus.munote.business.MenuToolbar;
import com.onimus.munote.ui.fragments.FilterDialogFragment;
import java.util.Calendar;
import static com.onimus.munote.Constants.*;
import static com.onimus.munote.repository.dao.NotesDao.TOTAL;
import static com.onimus.munote.business.ChangeMonth.changeMonthToExtension;
import static com.onimus.munote.business.ConvertType.convertToLong;
import static com.onimus.munote.business.MoneyTextWatcher.formatTextPrice;
import static com.onimus.munote.business.MoneyTextWatcher.getCurrencySymbol;
public class NotesActivity extends MenuToolbar implements FilterDialogFragment.FilterListener {
private Context context;
private Toolbar toolbar;
private TextView tv_filter;
private TextView tv_sort_by;
private TextView tv_year_month_filter;
private ListView lv_note;
private TextView tv_total;
private TextView tv_symbol1;
//
private FilterDialogFragment mFilterDialog = new FilterDialogFragment( );
private NotesActivityViewModel mViewModel;
private RecordListNotesAdapter adapter;
//
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.note_screen);
startVariables();
startAction();
}
private void startVariables() {
context = getBaseContext();
toolbar = findViewById(R.id.toolbar);
tv_filter = findViewById(R.id.tv_filter);
tv_sort_by = findViewById(R.id.tv_sort_by);
tv_year_month_filter = findViewById(R.id.tv_year_month_filter);
lv_note = findViewById(R.id.lv_note);
tv_total = findViewById(R.id.tv_total);
tv_symbol1 = findViewById(R.id.tv_symbol1);
//
loadAdmob();
}
private void startAction() {
// View model
mViewModel = ViewModelProviders.of(this).get(NotesActivityViewModel.class);
mFilterDialog = new FilterDialogFragment( );
//
toolbar.setTitle(R.string.title_invoice);
setSupportActionBar(toolbar);
//
setActionOnClickActivity(R.id.btn_add, NotesAddActivity.class, -1L);
setActionOnClick(R.id.cv_filter_bar, new OnCardViewClickAction());
setActionOnClick(R.id.btn_clear_filter, new OnClearFilterClickAction());
lv_note.setOnItemClickListener((parent, view, position, id) -> {
HMAuxNotes item = (HMAuxNotes) parent.getItemAtPosition(position);
callListView(NotesViewActivity.class, convertToLong(item.get(NotesDao.ID_NOTES)));
});
}
@Override
protected void onStart() {
super.onStart();
// Aplica os filtros
onFilter(mViewModel.getFilters());
}
@Override
public void onFilter(Filters filters) {
int yearActual = Calendar.getInstance().get(Calendar.YEAR);
int monthActual = (Calendar.getInstance().get(Calendar.MONTH) + 1);
//Envia o texto referente dos filtros para a descrição do filtro na Activity
tv_filter.setText(filters.getSearchDescription(this));
tv_sort_by.setText(filters.getOrderDescription(this));
if (filters.getSearchYearMonthTrue()) {
tv_year_month_filter.setText(filters.getSearchYearMonth(this));
} else {
tv_year_month_filter.setText((context.getString(R.string.text_in) + " " + changeMonthToExtension(monthActual, context) + " " + yearActual));
}
//
NotesDao notesDao = new NotesDao(context);
//
int month = filters.getMonth();
int year = filters.getYear();
long idCard = filters.getIdCard();
int type = filters.getType();
String sortBy = filters.getOrderDescriptionDB();
//Envia os adaptadores atualizados para a ListView
if (year == -2 || month == -2 || idCard == -2L || type == -2) {
adapter = new RecordListNotesAdapter(context, R.layout.cel_listview_notes_layout, notesDao.getListNotes(yearActual, monthActual, -2L, 3, NotesDao.DAY));
lv_note.setAdapter(adapter);
HMAuxNotes text = notesDao.getNotesTotal(yearActual, monthActual, -1L, 3);
String total = text.get(TOTAL);
if (total != null) {
total = formatTextPrice(total);
}
tv_total.setText(total);
} else {
adapter.updateDataChanged(notesDao.getListNotes(year, month, idCard, type, sortBy));
//
HMAuxNotes text = notesDao.getNotesTotal(year, month, idCard, type);
String total = text.get(TOTAL);
if (total != null) {
total = formatTextPrice(total);
}
tv_total.setText(total);
}
//
tv_symbol1.setText(getCurrencySymbol());
mViewModel.setFilters(filters);
}
private class OnCardViewClickAction implements View.OnClickListener {
@Override
public void onClick(View v) {
// Mostra o dialogo que contém o filtro
mFilterDialog.show(getSupportFragmentManager(), TAG_FILTER_DIALOG);
}
}
private class OnClearFilterClickAction implements View.OnClickListener {
@Override
public void onClick(View v) {
//Reseta o filtro
mFilterDialog = new FilterDialogFragment();
onFilter(Filters.getDefault());
}
}
public void onBackPressed() {
callActivity(context, MenuActivity.class);
super.onBackPressed();
}
}
|
9243a8a6f709aea17f76f75c90bee5fd0c2c50fb | 1,540 | java | Java | src/main/java/me/djin/dcore/redis/Cacheable.java | djin-cn/dcore | a460af433e14062ef8e096c626efe0e9b74beb55 | [
"MIT"
] | null | null | null | src/main/java/me/djin/dcore/redis/Cacheable.java | djin-cn/dcore | a460af433e14062ef8e096c626efe0e9b74beb55 | [
"MIT"
] | null | null | null | src/main/java/me/djin/dcore/redis/Cacheable.java | djin-cn/dcore | a460af433e14062ef8e096c626efe0e9b74beb55 | [
"MIT"
] | null | null | null | 19.493671 | 81 | 0.604545 | 1,002,725 | /**
*
*/
package me.djin.dcore.redis;
import java.util.Collection;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;
/**
* @author djin
* 缓存接口
*
* 缓存键生成规则建议:
* 1: 单个Bean缓存建议:服务名+Bean类名+主键
* 2: Map/Collection缓存建议:服务名+Service类名+方法名+条件
* 缓存策略建议:
* 1: 不建议单个键值对存储, 建议通过Map统一存储; 如: 系统配置项
* 2: 建议给所有缓存设置过期时间, 单位统一为10分钟的倍数, 常量类型的配置可以设置较长的过期时间
*/
public interface Cacheable {
/**
* 设置String缓存
* @param key 缓存键
* @param value 缓存值
* @param timeout 过期时间
* @param unit 过期时间单位
*/
void set(String key, Object value, long timeout, TimeUnit unit);
/**
* 设置Hash缓存
*
* @param key 缓存键
* @param value 缓存对象, 类型可以Map对象或者JavaBean对象
* @param timeout 过期时间
* @param unit 过期时间单位
*/
<T> void setMap(String key, T value, long timeout, TimeUnit unit);
/**
* 设置List缓存
* @param key 缓存键
* @param value 缓存对象
* @param timeout 过期时间
* @param unit 过期时间单位
*/
<T> void setList(String key, Collection<T> value, long timeout, TimeUnit unit);
/**
* 获取缓存
* @param key
* @return
*/
Object get(String key);
/**
* 获取Hash缓存
* @param key 缓存键
* @param clazz 缓存转换类型
* @return
*/
<T> T getObject(String key, Class<T> clazz);
/**
* 获取Hash缓存
* @param key
* @return
*/
HashMap<String, Object> getMap(String key);
/**
* 获取缓存列表
* @param key 缓存键
* @param clazz 缓存转换类型
* @return
*/
<T> Collection<T> getList(String key, Class<T> clazz);
/**
* 删除缓存
* @param key 缓存键
*/
void delete(String key);
}
|
9243a8e1d15aa824813971d2fbfbb0ce4ecb09d7 | 1,825 | java | Java | support/cas-server-support-trusted/src/main/java/org/apereo/cas/adaptors/trusted/authentication/principal/PrincipalBearingPrincipalResolver.java | glennjin/cas | b50a668358a6b95b0eedcb8805e0e7f6237919e2 | [
"Apache-2.0"
] | 3 | 2018-10-10T09:05:29.000Z | 2021-02-23T02:29:49.000Z | support/cas-server-support-trusted/src/main/java/org/apereo/cas/adaptors/trusted/authentication/principal/PrincipalBearingPrincipalResolver.java | glennjin/cas | b50a668358a6b95b0eedcb8805e0e7f6237919e2 | [
"Apache-2.0"
] | null | null | null | support/cas-server-support-trusted/src/main/java/org/apereo/cas/adaptors/trusted/authentication/principal/PrincipalBearingPrincipalResolver.java | glennjin/cas | b50a668358a6b95b0eedcb8805e0e7f6237919e2 | [
"Apache-2.0"
] | null | null | null | 38.020833 | 104 | 0.723836 | 1,002,726 | package org.apereo.cas.adaptors.trusted.authentication.principal;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apereo.cas.authentication.Credential;
import org.apereo.cas.authentication.principal.Principal;
import org.apereo.cas.authentication.principal.PrincipalFactory;
import org.apereo.cas.authentication.principal.resolvers.PersonDirectoryPrincipalResolver;
import org.apereo.services.persondir.IPersonAttributeDao;
/**
* Extracts the Principal out of PrincipalBearingCredential. It is very simple
* to resolve PrincipalBearingCredential to a Principal since the credentials
* already bear the ready-to-go Principal.
*
* @author Andrew Petro
* @since 3.0.0
*/
public class PrincipalBearingPrincipalResolver extends PersonDirectoryPrincipalResolver {
public PrincipalBearingPrincipalResolver() {
}
public PrincipalBearingPrincipalResolver(final IPersonAttributeDao attributeRepository,
final PrincipalFactory principalFactory,
final boolean returnNullIfNoAttributes,
final String principalAttributeName) {
super(attributeRepository, principalFactory, returnNullIfNoAttributes, principalAttributeName);
}
@Override
protected String extractPrincipalId(final Credential credential, final Principal currentPrincipal) {
return ((PrincipalBearingCredential) credential).getPrincipal().getId();
}
@Override
public boolean supports(final Credential credential) {
return credential instanceof PrincipalBearingCredential;
}
@Override
public String toString() {
return new ToStringBuilder(this)
.appendSuper(super.toString())
.toString();
}
}
|
9243a94f244b1813488414cdd8084e46b127dd4a | 512 | java | Java | src/main/java/com/lsieben/retroscript/lang/exceptions/errors/InternalCompilerException.java | lsieben97/RetroScript | 872725065fe4c96027c717f692bc1e416d97dbdf | [
"MIT"
] | null | null | null | src/main/java/com/lsieben/retroscript/lang/exceptions/errors/InternalCompilerException.java | lsieben97/RetroScript | 872725065fe4c96027c717f692bc1e416d97dbdf | [
"MIT"
] | null | null | null | src/main/java/com/lsieben/retroscript/lang/exceptions/errors/InternalCompilerException.java | lsieben97/RetroScript | 872725065fe4c96027c717f692bc1e416d97dbdf | [
"MIT"
] | null | null | null | 25.6 | 77 | 0.720703 | 1,002,727 | package com.lsieben.retroscript.lang.exceptions.errors;
import com.lsieben.retroscript.lang.exceptions.RetroScriptCompilerException;
public class InternalCompilerException extends RetroScriptCompilerException {
public InternalCompilerException(String location, String... arguments) {
super(location, arguments);
}
@Override
public String getErrorMessage() {
return "Internal compiler error: $1";
}
@Override
public String getCode() {
return "000";
}
}
|
9243a9dbb22fd894b70de8e4dd868322cba852c2 | 9,761 | java | Java | src/xml/parser/ParentXMLParser.java | vincentliu98/Cell-Society | e1c7ec77b3deb61e8dc185a0713f07d445626d9d | [
"MIT"
] | null | null | null | src/xml/parser/ParentXMLParser.java | vincentliu98/Cell-Society | e1c7ec77b3deb61e8dc185a0713f07d445626d9d | [
"MIT"
] | null | null | null | src/xml/parser/ParentXMLParser.java | vincentliu98/Cell-Society | e1c7ec77b3deb61e8dc185a0713f07d445626d9d | [
"MIT"
] | null | null | null | 36.695489 | 118 | 0.585596 | 1,002,728 | package xml.parser;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import simulation.Cell;
import simulation.CellGraph;
import simulation.Simulator;
import simulation.factory.NeighborUtils;
import simulation.models.SimulationModel;
import utility.ShapeUtils;
import xml.XMLException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.util.*;
import static java.lang.Math.round;
import static xml.writer.XMLWriter.DELIMITER;
/**
* This class handles parsing XML files and returning a completed object.
*
* @author Rhondu Smithwick
* @author Robert C. Duvall
* @author jgp17
* @author Inchan Hwang
*/
public abstract class ParentXMLParser<T> {
// keep only one documentBuilder because it is expensive to make and can reset it before parsing
private static final DocumentBuilder DOCUMENT_BUILDER = getDocumentBuilder();
public static final String VAL_CODE_TAG = "code";
private static ResourceBundle myResources;
public static final String DEFAULT_RESOURCES = "Errors";
private static final String LOAD_AGAIN_KEY = "LoadAgainMsg";
public static final String MODEL_ATTRIBUTE_TAG = "modelName";
public static final String PROB_VALS_TAG = "probVals";
public static final String SHAPE_CODE_TAG = "shapeCode";
public static final String CELL_TAG = "cell";
public static final String MIN_STRING = "min";
public static final String MAX_STRING = "max";
public static final String DEF_STRING = "def";
private static final double MARGIN = 0.5;
public static final String WHITESPACE = "\\s";
public static final String EMPTY = "";
/**
* Create a parser for XML files of given type.
*/
public ParentXMLParser(String language) {
myResources = ResourceBundle.getBundle(DEFAULT_RESOURCES + language);
}
/**
* Get the data contained in this XML file as an object
*/
public abstract Simulator<T> getSimulator(File datafile);
public CellGraph<T> getCellGraph(Element root, SimulationModel<T> model) {
int n = (int) Math.round(Math.sqrt(root.getElementsByTagName(CELL_TAG).getLength()));
ArrayList<ArrayList<T>> cellVals;
if (root.getElementsByTagName(PROB_VALS_TAG).getLength() != 0) {
cellVals = cellValsFromProbs(root, model, n);
} else {
cellVals = cellValsFromList(root, model, n);
}
int shapeCode = getIntValue(root, SHAPE_CODE_TAG, Collections.min(ShapeUtils.shapeCodes()),
Collections.max(ShapeUtils.shapeCodes()), 0);
if (shapeCode == 0) {
return generateRect(n, n, cellVals);
} else {
return generateTri(n, n, cellVals);
}
}
public ArrayList<ArrayList<T>> cellValsFromList(Element root, SimulationModel<T> model, int n) {
NodeList cells = root.getElementsByTagName(CELL_TAG);
ArrayList<ArrayList<T>> cellVals = new ArrayList<>();
for (int i = 0; i < n; i++) {
ArrayList<T> row = new ArrayList<>();
for (int j = 0; j < n; j++) {
Element curCell = (Element) cells.item(i*n+j);
int code = getIntValue(curCell, VAL_CODE_TAG, Collections.min(model.getCodes()),
Collections.max(model.getCodes()), model.getDefaultCode());
row.add(model.getValFromCode(code));
}
cellVals.add(row);
}
return cellVals;
}
public ArrayList<ArrayList<T>> cellValsFromProbs(Element root, SimulationModel<T> model, int n) {
Random rng = new Random();
ArrayList<ArrayList<T>> cellVals = new ArrayList<>();
for (int i = 0; i < n; i++) {
ArrayList<T> row = new ArrayList<>();
for (int j = 0; j < n; j++) {
var val = getRandomVal(getValToProbMap(root, model), rng);
row.add(val);
}
cellVals.add(row);
}
return cellVals;
}
private T getRandomVal(Map<T, Double> valToProbMap, Random rng) {
var x = rng.nextDouble();
for (T v : valToProbMap.keySet()) {
if (x < valToProbMap.get(v)) {
return v;
}
}
return null;
}
public Map<T, Double> getValToProbMap(Element root, SimulationModel<T> model) {
String probStr = getTextValue(root, PROB_VALS_TAG);
List<Double> probList = new ArrayList<>();
String[] probStrArray = probStr.split(DELIMITER);
for (String s : probStrArray) {
probList.add(Double.parseDouble(s));
}
List<Integer> codes = model.getCodes();
if (codes.size() != probList.size()) {
probList.clear();
double inc = 1.0 / codes.size();
for (int c = 0; c < codes.size(); c++) {
probList.add(inc*(c+1));
}
}
Map<T, Double> valToProb = new HashMap<>();
for (int c = 0; c < codes.size(); c++) {
var val = model.getValFromCode(codes.get(c));
valToProb.put(val, probList.get(c));
}
return valToProb;
}
public CellGraph<T> generateRect(int row, int column, ArrayList<ArrayList<T>> vals) {
ArrayList<Cell<T>> cells = new ArrayList<>();
double width = Simulator.SIMULATION_SX / column;
double height = Simulator.SIMULATION_SY / row;
for(int i = 0 ; i < row ; i ++) {
for(int j = 0 ; j < column ; j ++) {
var cell = new Cell<>(vals.get(i).get(j), ShapeUtils.RECTANGLE,
(j+MARGIN)*width, (i+MARGIN)*height,
width, height
);
cells.add(cell);
}
}
return NeighborUtils.rectangularGraph(cells, row, column, NeighborUtils.indicesFor8Rectangle());
}
public CellGraph<T> generateTri(int row, int column, ArrayList<ArrayList<T>> vals) {
ArrayList<Cell<T>> cells = new ArrayList<>();
double width = Simulator.SIMULATION_SX / ((column+1)/2);
double height = Simulator.SIMULATION_SY / row;
for(int i = 0 ; i < row ; i ++) {
for(int j = 0 ; j < column ; j ++) {
var cell = new Cell<>(vals.get(i).get(j), (i+j)%2==0 ? ShapeUtils.TRIANGLE : ShapeUtils.TRIANGLE_FLIP,
(MARGIN*j)*width, (i+MARGIN)*height,
width, height);
cells.add(cell);
}
}
return NeighborUtils.triangularGraph(cells, row, column, NeighborUtils.indicesFor12Triangle());
}
/**
* Get value of Element's text
*/
public static String getTextValue(Element e, String tagName) {
var nodeList = e.getElementsByTagName(tagName);
if (nodeList != null && nodeList.getLength() > 0) {
return nodeList.item(0).getTextContent();
} else {
throw new XMLException(myResources.getString("MissingTagMsg")+ myResources.getString(LOAD_AGAIN_KEY),
e.toString(), tagName);
}
}
/**
*
* @param e
* @param tagName
* @return
*/
public static int getIntValue(Element e, String tagName, int min, int max, int def) {
try {
String str = getTextValue(e, tagName).replaceAll(WHITESPACE, EMPTY);
try {
int i = Integer.parseInt(str);
if (i < min || i > max) {
throw new XMLException(myResources.getString("IntOutOfRangeMsg"), tagName, i, min, max);
}
return i;
} catch (NumberFormatException ex) {
throw new XMLException(myResources.getString("ValueNotIntMsg"), tagName, str);
}
} catch (XMLException ex){
return def;
}
}
/**
*
* @param e
* @param tagName
* @return
*/
public static double getDoubleValue(Element e, String tagName, double min, double max, double def) {
try {
String str = getTextValue(e, tagName).replaceAll(WHITESPACE, EMPTY);
try {
double db = Double.parseDouble(str);
if (db < min || db > max) {
throw new XMLException(myResources.getString("DoubleOutOfRangeMsg"), tagName, db, min, max);
}
return db;
} catch (NumberFormatException ex) {
throw new XMLException(myResources.getString("ValueNotDoubleMsg"), tagName, str);
}
} catch (XMLException ex){
return def;
}
}
/**
* Get root element of an XML file
*
* @param xmlFile
* @return
*/
public static Element getRootElement(File xmlFile) {
try {
DOCUMENT_BUILDER.reset();
var xmlDocument = DOCUMENT_BUILDER.parse(xmlFile);
return xmlDocument.getDocumentElement();
} catch (SAXException | IOException e) {
throw new XMLException(e);
}
}
public static String peekModelName(File xmlFile) {
return getTextValue(getRootElement(xmlFile), MODEL_ATTRIBUTE_TAG);
}
/**
* Boilerplate code needed to make a documentBuilder
*/
public static DocumentBuilder getDocumentBuilder() {
try {
return DocumentBuilderFactory.newInstance().newDocumentBuilder();
} catch (ParserConfigurationException e) {
throw new XMLException(e);
}
}
} |
9243aa3e62147b2c70250511978730b5a60b4d14 | 2,018 | java | Java | LACCPlus/Zookeeper/50_1.java | sgholamian/log-aware-clone-detection | 9993cb081c420413c231d1807bfff342c39aa69a | [
"MIT"
] | null | null | null | LACCPlus/Zookeeper/50_1.java | sgholamian/log-aware-clone-detection | 9993cb081c420413c231d1807bfff342c39aa69a | [
"MIT"
] | null | null | null | LACCPlus/Zookeeper/50_1.java | sgholamian/log-aware-clone-detection | 9993cb081c420413c231d1807bfff342c39aa69a | [
"MIT"
] | null | null | null | 37.37037 | 76 | 0.510902 | 1,002,729 | //,temp,RemoveWatchesTest.java,652,700,temp,RemoveWatchesTest.java,578,611
//,3
public class xxx {
@Test(timeout = 90000)
public void testManyWatchersWhenNoConnection() throws Exception {
int count = 3;
List<MyWatcher> wList = new ArrayList<MyWatcher>(count);
MyWatcher w;
String path = "/node";
// Child watcher
for (int i = 0; i < count; i++) {
String nodePath = path + i;
zk1.create(nodePath, null, Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
nodePath += "/";
}
for (int i = 0; i < count; i++) {
String nodePath = path + i;
w = new MyWatcher(path + i, 2);
wList.add(w);
LOG.info("Adding child watcher {} on path {}", new Object[] { w,
nodePath });
zk1.getChildren(nodePath, w);
nodePath += "/";
}
Assert.assertEquals("Failed to add watchers!", count, zk1
.getChildWatches().size());
// Data watcher
for (int i = 0; i < count; i++) {
String nodePath = path + i;
w = wList.get(i);
LOG.info("Adding data watcher {} on path {}", new Object[] { w,
nodePath });
zk1.getData(nodePath, w, null);
nodePath += "/";
}
Assert.assertEquals("Failed to add watchers!", count, zk1
.getDataWatches().size());
stopServer();
for (int i = 0; i < count; i++) {
final MyWatcher watcher = wList.get(i);
removeWatches(zk1, path + i, watcher, WatcherType.Any, true,
Code.OK);
Assert.assertTrue("Didn't remove watcher", watcher.matches());
}
Assert.assertEquals("Didn't remove watch references!", 0, zk1
.getChildWatches().size());
Assert.assertEquals("Didn't remove watch references!", 0, zk1
.getDataWatches().size());
}
}; |
9243aac7f7236f661eaa20541edd88a63b328623 | 12,639 | java | Java | mconf/src/main/java/cn/ms/mconf/redis/RedisMconf.java | z131031231/mconf | 3d64127748e033032cbcf300edeef3a7de170b53 | [
"MIT"
] | 122 | 2017-04-26T15:09:56.000Z | 2021-05-27T06:11:04.000Z | mconf/src/main/java/cn/ms/mconf/redis/RedisMconf.java | z131031231/mconf | 3d64127748e033032cbcf300edeef3a7de170b53 | [
"MIT"
] | 1 | 2020-03-13T07:53:52.000Z | 2020-03-13T07:53:52.000Z | mconf/src/main/java/cn/ms/mconf/redis/RedisMconf.java | z131031231/mconf | 3d64127748e033032cbcf300edeef3a7de170b53 | [
"MIT"
] | 34 | 2017-06-21T15:52:04.000Z | 2021-04-08T07:13:12.000Z | 28.659864 | 141 | 0.654007 | 1,002,730 | package cn.ms.mconf.redis;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import cn.ms.mconf.support.AbstractMconf;
import cn.ms.mconf.support.Cmd;
import cn.ms.mconf.support.MetaData;
import cn.ms.mconf.support.Notify;
import cn.ms.micro.common.ConcurrentHashSet;
import cn.ms.micro.common.URL;
import cn.ms.micro.extension.SpiMeta;
import cn.ms.micro.threadpool.NamedThreadFactory;
import com.alibaba.fastjson.JSON;
/**
* The base of Redis Mconf.
*
* @author lry
*/
@SpiMeta(name = "redis")
public class RedisMconf extends AbstractMconf {
private static final Logger logger = LoggerFactory.getLogger(RedisMconf.class);
private JedisPool jedisPool;
private long retryPeriod = 10000;
private boolean isSubscribe = true;
private final Map<String, Class<?>> pushClassMap = new ConcurrentHashMap<String, Class<?>>();
@SuppressWarnings("rawtypes")
private final ConcurrentMap<String, Set<Notify>> pushNotifyMap = new ConcurrentHashMap<String, Set<Notify>>();
private final ConcurrentMap<String, Map<String, String>> pushValueMap = new ConcurrentHashMap<String, Map<String, String>>();
@SuppressWarnings("unused")
private ScheduledFuture<?> retryFuture;
private final ScheduledExecutorService retryExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("RedisMconfTimer", true));
@Override
public void connect(URL url) {
super.connect(url);
this.retryPeriod = url.getParameter("retryPeriod", retryPeriod);
JedisPoolConfig config = new JedisPoolConfig();
Map<String, String> parameters = url.getParameters();
if (parameters != null) {
if (!parameters.isEmpty()) {
try {
BeanUtils.copyProperties(config, url.getParameters());
} catch (Exception e) {
logger.error("The copy properties exception.", e);
}
}
}
jedisPool = new JedisPool(config, url.getHost(), url.getPort());
}
@Override
public boolean available() {
return (jedisPool == null) ? false : (!jedisPool.isClosed());
}
@Override
public void addConf(Cmd cmd, Object obj) {
String key = cmd.buildRoot(super.url).getPrefixKey();
String field = cmd.getSuffixKey();
String json = this.obj2Json(obj);
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.hset(key, field, json);
} catch (Exception e) {
logger.error("The add conf exception.", e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
@Override
public void delConf(Cmd cmd) {
String key = cmd.buildRoot(super.url).getPrefixKey();
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
String field = cmd.getSuffixKey();
if (StringUtils.isNotBlank(field)) {
jedis.hdel(key, field);
} else {
jedis.hdel(key);
}
} catch (Exception e) {
logger.error("The delete conf exception.", e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
@Override
public void upConf(Cmd cmd, Object obj) {
this.addConf(cmd, obj);
}
@Override
public <T> T pull(Cmd cmd, Class<T> cls) {
String key = cmd.buildRoot(super.url).getPrefixKey();
String field = cmd.getSuffixKey();
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
String json = jedis.hget(key, field);
return (T) json2Obj(json, cls);
} catch (Exception e) {
logger.error("The pull conf exception.", e);
return null;
} finally {
if (jedis != null) {
jedis.close();
}
}
}
@Override
public <T> List<T> pulls(Cmd cmd, Class<T> cls) {
String key = cmd.buildRoot(super.url).getPrefixKey();
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
Map<String, String> dataMap = jedis.hgetAll(key);
List<T> list = new ArrayList<T>();
for (String tempJson:dataMap.values()) {
list.add(JSON.parseObject(tempJson, cls));
}
return list;
} catch (Exception e) {
logger.error("The pulls conf exception.", e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return null;
}
@SuppressWarnings("rawtypes")
@Override
public <T> void push(Cmd cmd, Class<T> cls, Notify<T> notify) {
if (isSubscribe) {
this.pushSubscribe();
isSubscribe = false;
}
String key = cmd.buildRoot(super.url).getPrefixKey();
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
if (!pushClassMap.containsKey(key)) {
pushClassMap.put(key, cls);
}
Set<Notify> notifies = pushNotifyMap.get(key);
if (notifies == null) {
pushNotifyMap.put(key, notifies = new ConcurrentHashSet<Notify>());
}
notifies.add(notify);
// 第一次拉取式通知
Map<String, String> dataMap = jedis.hgetAll(key);
if (dataMap == null) {
dataMap = new HashMap<String, String>();
}
List<T> list = new ArrayList<T>();
for (String tempJson:dataMap.values()) {
list.add(JSON.parseObject(tempJson, cls));
}
pushValueMap.put(key, dataMap);
notify.notify(list);
} catch (Exception e) {
logger.error("The push conf exception.", e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
@Override
public void unpush(Cmd cmd) {
String key = cmd.buildRoot(super.url).getPrefixKey();
if (pushClassMap.containsKey(key)) {
pushClassMap.remove(key);
}
if (pushNotifyMap.containsKey(key)) {
pushNotifyMap.remove(key);
}
if (pushValueMap.containsKey(key)) {
pushValueMap.remove(key);
}
}
//$NON-NLS-The Node Governor$
@Override
public List<MetaData> getApps() {
List<MetaData> appConfs = new ArrayList<MetaData>();
Map<String, MetaData> appConfMap = new HashMap<String, MetaData>();
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
Set<String> keySet = jedis.keys("/" + super.ROOT + "*");
for (String key:keySet) {
String[] keyArray = key.split("/");
if(keyArray.length == 4){
MetaData metaData = new MetaData();
// build root
URL tempRootURL = URL.valueOf("/" + URL.decode(keyArray[1]));
metaData.setRoot(tempRootURL.getPath());
metaData.setRootAttrs(tempRootURL.getParameters());
// build app
URL tempAppURL = URL.valueOf("/" + URL.decode(keyArray[2]));
metaData.setNode(tempAppURL.getParameter(Cmd.NODE_KEY));
metaData.setApp(tempAppURL.getPath());
metaData.setAppAttrs(tempAppURL.getParameters());
// build others
metaData.setSubNum(jedis.keys("/" + keyArray[1] + "/" + keyArray[2] + "/*").size());
appConfMap.put("/" + keyArray[1] + "/" + keyArray[2], metaData);
}
}
if(!appConfMap.isEmpty()){
appConfs.addAll(appConfMap.values());
}
} catch (Exception e) {
logger.error("The pulls conf exception.", e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return appConfs;
}
@Override
public List<MetaData> getConfs() {
List<MetaData> confConfs = new ArrayList<MetaData>();
Map<String, MetaData> confConfMap = new HashMap<String, MetaData>();
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
Set<String> keySet = jedis.keys("/" + super.ROOT + "*");
for (String key:keySet) {
String[] keyArray = key.split("/");
if(keyArray.length == 4){
MetaData metaData = new MetaData();
// build root
URL tempRootURL = URL.valueOf("/" + URL.decode(keyArray[1]));
metaData.setRoot(tempRootURL.getPath());
metaData.setRootAttrs(tempRootURL.getParameters());
// build app
URL tempAppURL = URL.valueOf("/" + URL.decode(keyArray[2]));
metaData.setNode(tempAppURL.getParameter(Cmd.NODE_KEY));
metaData.setApp(tempAppURL.getPath());
metaData.setAppAttrs(tempAppURL.getParameters());
// build conf
URL tempConfURL = URL.valueOf("/" + URL.decode(keyArray[3]));
metaData.setEnv(tempConfURL.getParameter(Cmd.ENV_KEY));
metaData.setGroup(tempConfURL.getParameter(Cmd.GROUP_KEY));
metaData.setVersion(tempConfURL.getParameter(Cmd.VERSION_KEY));
metaData.setConf(tempConfURL.getPath());
metaData.setConfAttrs(tempConfURL.getParameters());
// build others
metaData.setSubNum(jedis.hkeys(key).size());
confConfMap.put(key, metaData);
}
}
if(!confConfMap.isEmpty()){
confConfs.addAll(confConfMap.values());
}
} catch (Exception e) {
logger.error("The pulls conf exception.", e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return confConfs;
}
@Override
public List<MetaData> getBodys() {
List<MetaData> confConfs = new ArrayList<MetaData>();
Map<String, MetaData> confConfMap = new HashMap<String, MetaData>();
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
Set<String> keySet = jedis.keys("/" + super.ROOT + "*");
for (String key:keySet) {
String[] keyArray = key.split("/");
if(keyArray.length == 4){
Set<String> fieldSet = jedis.hkeys(key);
for (String field:fieldSet) {
String[] fieldArray = field.split("/");
if(fieldArray.length != 2){
continue;
}
MetaData metaData = new MetaData();
// build root
URL tempRootURL = URL.valueOf("/" + URL.decode(keyArray[1]));
metaData.setRoot(tempRootURL.getPath());
metaData.setRootAttrs(tempRootURL.getParameters());
// build app
URL tempAppURL = URL.valueOf("/" + URL.decode(keyArray[2]));
metaData.setNode(tempAppURL.getParameter(Cmd.NODE_KEY));
metaData.setApp(tempAppURL.getPath());
metaData.setAppAttrs(tempAppURL.getParameters());
// build conf
URL tempConfURL = URL.valueOf("/" + URL.decode(keyArray[3]));
metaData.setEnv(tempConfURL.getParameter(Cmd.ENV_KEY));
metaData.setGroup(tempConfURL.getParameter(Cmd.GROUP_KEY));
metaData.setVersion(tempConfURL.getParameter(Cmd.VERSION_KEY));
metaData.setConf(tempConfURL.getPath());
metaData.setConfAttrs(tempConfURL.getParameters());
// build data
URL tempDataURL = URL.valueOf("/" + URL.decode(fieldArray[1]));
metaData.setData(tempDataURL.getPath());
metaData.setDataAttrs(tempDataURL.getParameters());
// build others
metaData.setSubNum(0);
metaData.setJson(jedis.hget(key, field));
metaData.setBody(JSON.parseObject(metaData.getJson(), Map.class));
confConfMap.put(key + field, metaData);
}
}
}
if(!confConfMap.isEmpty()){
confConfs.addAll(confConfMap.values());
}
} catch (Exception e) {
logger.error("The pulls conf exception.", e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return confConfs;
}
/**
* 定时拉取数据
*/
private void pushSubscribe() {
if (!isSubscribe) {
return;
}
this.retryFuture = retryExecutor.scheduleWithFixedDelay(new Runnable() {
@SuppressWarnings({ "unchecked", "rawtypes" })
public void run() {
try {
if (pushClassMap.isEmpty()) {
return;
}
for (Map.Entry<String, Class<?>> entry : pushClassMap.entrySet()) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
Map<String, String> newMap = jedis.hgetAll(entry.getKey());
if (newMap == null) {
newMap = new HashMap<String, String>();
}
Map<String, String> oldMap = pushValueMap.get(entry.getKey());
if (!newMap.equals(oldMap)) {// 已变更
Set<Notify> notifies = pushNotifyMap.get(entry.getKey());
if (notifies == null) {
continue;
} else {
pushValueMap.put(entry.getKey(), newMap);
for (Notify notify : notifies) {
List list = new ArrayList();
for (Map.Entry<String, String> tempEntry : newMap.entrySet()) {
list.add(JSON.parseObject(tempEntry.getValue(), entry.getValue()));
}
notify.notify(list);
}
}
}
} catch (Exception e) {
logger.error("The push conf exception.", e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
} catch (Exception e) { // 防御性容错
logger.error("Unexpected error occur at failed retry, cause: " + e.getMessage(), e);
}
}
}, retryPeriod, retryPeriod, TimeUnit.MILLISECONDS);
}
}
|
9243aad5abe6ded39d089d1a3d6ca6360c71579b | 1,096 | java | Java | libs/kafka-config/src/main/java/no/nav/testnav/libs/kafkaconfig/config/KafkaProperties.java | navikt/testnorge | 8400ad28d37ec5dee87a4fe76e233632d2cfdbd1 | [
"MIT"
] | 3 | 2020-06-30T18:14:44.000Z | 2022-03-07T10:10:48.000Z | libs/kafka-config/src/main/java/no/nav/testnav/libs/kafkaconfig/config/KafkaProperties.java | navikt/testnorge | 8400ad28d37ec5dee87a4fe76e233632d2cfdbd1 | [
"MIT"
] | 1,546 | 2020-05-25T14:39:45.000Z | 2022-03-31T13:41:00.000Z | libs/kafka-config/src/main/java/no/nav/testnav/libs/kafkaconfig/config/KafkaProperties.java | navikt/testnorge | 8400ad28d37ec5dee87a4fe76e233632d2cfdbd1 | [
"MIT"
] | 1 | 2021-11-03T16:02:17.000Z | 2021-11-03T16:02:17.000Z | 36.533333 | 94 | 0.710766 | 1,002,731 | package no.nav.testnav.libs.kafkaconfig.config;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
@Getter
@Configuration
public class KafkaProperties {
private final String bootstrapAddress;
private final String groupId;
private final String schemaregistryServers;
private final String username;
private final String password;
public KafkaProperties(
@Value("${kafka.bootstrapservers}") String bootstrapAddress,
@Value("${kafka.groupid}") String groupId,
@Value("${kafka.schemaregistryservers}") String schemaregistryServers,
@Value("${SERVICEUSER_USERNAME:${serviceuser.username:#{null}}}") String username,
@Value("${SERVICEUSER_PASSWORD:${serviceuser.password:#{null}}}") String password
) {
this.bootstrapAddress = bootstrapAddress;
this.groupId = groupId;
this.schemaregistryServers = schemaregistryServers;
this.username = username;
this.password = password;
}
}
|
9243ab82dcae9a34192e8dbdc932184665897271 | 235 | java | Java | src/main/java/app/web/coralmarketplace/repository/MarketItemRepo.java | Coral-Marketplace/coral-marketplace-backend | 8fb303d8e941b4195a7b3dea3888e5a110ace15d | [
"MIT"
] | null | null | null | src/main/java/app/web/coralmarketplace/repository/MarketItemRepo.java | Coral-Marketplace/coral-marketplace-backend | 8fb303d8e941b4195a7b3dea3888e5a110ace15d | [
"MIT"
] | null | null | null | src/main/java/app/web/coralmarketplace/repository/MarketItemRepo.java | Coral-Marketplace/coral-marketplace-backend | 8fb303d8e941b4195a7b3dea3888e5a110ace15d | [
"MIT"
] | null | null | null | 23.5 | 74 | 0.842553 | 1,002,732 | package app.web.coralmarketplace.repository;
import org.springframework.data.repository.CrudRepository;
import app.web.coralmarketplace.model.MarketItem;
public interface MarketItemRepo extends CrudRepository<MarketItem, Long> {
}
|
9243abbdebb04b099f7ebf168ae5aeed6431d725 | 12,085 | java | Java | biojava/src/org/biojavax/bio/seq/io/RichSequenceFormat.java | rbouadjenek/DQBioinformatics | 088c0e93754257592e3a0725897566af3823a92d | [
"Apache-2.0"
] | null | null | null | biojava/src/org/biojavax/bio/seq/io/RichSequenceFormat.java | rbouadjenek/DQBioinformatics | 088c0e93754257592e3a0725897566af3823a92d | [
"Apache-2.0"
] | null | null | null | biojava/src/org/biojavax/bio/seq/io/RichSequenceFormat.java | rbouadjenek/DQBioinformatics | 088c0e93754257592e3a0725897566af3823a92d | [
"Apache-2.0"
] | null | null | null | 32.140957 | 111 | 0.635168 | 1,002,733 | /*
* BioJava development code
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. If you do not have a copy,
* see:
*
* http://www.gnu.org/copyleft/lesser.html
*
* Copyright for this code is held jointly by the individual
* authors. These should be listed in @author doc comments.
*
* For more information on the BioJava project and its aims,
* or to join the biojava-l mailing list, visit the home page
* at:
*
* http://www.biojava.org/
*
*/
package org.biojavax.bio.seq.io;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import org.biojava.bio.BioException;
import org.biojava.bio.seq.Sequence;
import org.biojava.bio.seq.io.SequenceFormat;
import org.biojava.bio.seq.io.SymbolTokenization;
import org.biojava.bio.symbol.IllegalSymbolException;
import org.biojavax.Namespace;
import org.biojavax.bio.seq.RichSequence;
/**
* Allows a file format to be read/written as RichSequences.
*
* @author Richard Holland
* @since 1.5
*/
public interface RichSequenceFormat extends SequenceFormat {
/**
* Check to see if a given file is in our format. Some formats may be able
* to determine this by filename, whilst others may have to open the file
* and read it to see what format it is in.
*
* @param file the <code>File</code> to check.
* @return true if the file is readable by this format, false if not.
* @throws IOException in case the file is inaccessible.
*/
public boolean canRead(File file) throws IOException;
/**
* On the assumption that the file is readable by this format (not checked),
* attempt to guess which symbol tokenization we should use to read it. For
* formats that only accept one tokenization, just return it without
* checking the file. For formats that accept multiple tokenizations, its up
* to you how you do it.
*
* @param file the <code>File</code> object to guess the format of.
* @return a <code>SymbolTokenization</code> to read the file with.
* @throws IOException if the file is unrecognisable or inaccessible.
*/
public SymbolTokenization guessSymbolTokenization(File file) throws IOException;
/**
* Check to see if a given stream is in our format.
*
* @param stream the <code>BufferedInputStream</code> to check.
* @return true if the stream is readable by this format, false if not.
* @throws IOException in case the stream is inaccessible.
*/
public boolean canRead(BufferedInputStream stream) throws IOException;
/**
* On the assumption that the stream is readable by this format (not
* checked), attempt to guess which symbol tokenization we should use to
* read it. For formats that only accept one tokenization, just return it
* without checking the stream. For formats that accept multiple
* tokenizations, its up to you how you do it.
*
* @param stream the <code>BufferedInputStream</code> object to guess the
* format of.
* @return a <code>SymbolTokenization</code> to read the stream with.
* @throws IOException if the stream is unrecognisable or inaccessible.
*/
public SymbolTokenization guessSymbolTokenization(BufferedInputStream stream) throws IOException;
/**
* Sets the stream to write to.
*
* @param os the PrintStream to write to.
* @throws IOException if writing fails.
*/
public void setPrintStream(PrintStream os);
/**
* Gets the print stream currently being written to.
*
* @return the current print stream.
*/
public PrintStream getPrintStream();
/**
* Informs the writer that we want to start writing. This will do any
* initialisation required, such as writing the opening tags of an XML file
* that groups sequences together.
*
* @throws IOException if writing fails.
*/
public void beginWriting() throws IOException;
/**
* Informs the writer that are done writing. This will do any finalisation
* required, such as writing the closing tags of an XML file that groups
* sequences together.
*
* @throws IOException if writing fails.
*/
public void finishWriting() throws IOException;
/**
* Reads a sequence from the given buffered reader using the given tokenizer
* to parse sequence symbols. Events are passed to the listener, and the
* namespace used for sequences read is the one given. If the namespace is
* null, then the default namespace for the parser is used, which may depend
* on individual implementations of this interface.
*
* @param reader the input source
* @param symParser the tokenizer which understands the sequence being read
* @param listener the listener to send sequence events to
* @param ns the namespace to read sequences into.
* @return true if there is more to read after this, false otherwise.
* @throws BioException in case of parsing errors.
* @throws IllegalSymbolException if the tokenizer couldn't understand one
* of the sequence symbols in the file.
* @throws IOException if there was a read error.
*/
public boolean readRichSequence(BufferedReader reader, SymbolTokenization symParser,
RichSeqIOListener listener, Namespace ns) throws BioException, IllegalSymbolException, IOException;
/**
* Writes a sequence out to the outputstream given by beginWriting() using
* the default format of the implementing class. If namespace is given,
* sequences will be written with that namespace, otherwise they will be
* written with the default namespace of the implementing class (which is
* usually the namespace of the sequence itself). If you pass this method a
* sequence which is not a RichSequence, it will attempt to convert it using
* RichSequence.Tools.enrich(). Obviously this is not going to guarantee a
* perfect conversion, so it's better if you just use RichSequences to start
* with!
*
* @param seq the sequence to write
* @param ns the namespace to write it with
* @throws IOException in case it couldn't write something
*/
public void writeSequence(Sequence seq, Namespace ns) throws IOException;
/**
* Retrive the current line width. Defaults to 80.
*
* @return the line width
*/
public int getLineWidth();
/**
* Set the line width. When writing, the lines of sequence will never be
* longer than the line width. Defaults to 80.
*
* @param width the new line width
*/
public void setLineWidth(int width);
/**
* Use this method to toggle reading of sequence data.
*
* @param elideSymbols set to true if you <em>don't</em> want the sequence
* data.
*/
public void setElideSymbols(boolean elideSymbols);
/**
* Is the format going to emit events when sequence data is read?
*
* @return true if it is <em>not</em> otherwise false (false is default) .
*/
public boolean getElideSymbols();
/**
* Use this method to toggle reading of feature data.
*
* @param elideFeatures set to true if you <em>don't</em> want the feature
* data.
*/
public void setElideFeatures(boolean elideFeatures);
/**
* Is the format going to emit events when feature data is read?
*
* @return true if it is <em>not</em> otherwise false (false is default).
*/
public boolean getElideFeatures();
/**
* Use this method to toggle reading of bibliographic reference data.
*
* @param elideReferences set to true if you <em>don't</em> want the
* bibliographic reference data.
*/
public void setElideReferences(boolean elideReferences);
/**
* Is the format going to emit events when bibliographic reference data is
* read?
*
* @return true if it is <em>not</em> otherwise false (false is default) .
*/
public boolean getElideReferences();
/**
* Use this method to toggle reading of comments data. Will also ignore
* remarks lines in bibliographic references.
*
* @param elideComments set to true if you <em>don't</em> want the comments
* data.
*/
public void setElideComments(boolean elideComments);
/**
* Is the format going to emit events when comments data or remarks from
* bibliographic references are read?
*
* @return true if it is <em>not</em> otherwise false (false is default).
*/
public boolean getElideComments();
/**
* Provides a basic format with simple things like line-widths precoded.
*/
public abstract class BasicFormat implements RichSequenceFormat {
private int lineWidth = 80;
private boolean elideSymbols = false;
private boolean elideFeatures = false;
private boolean elideComments = false;
private boolean elideReferences = false;
private PrintStream os;
/**
* {@inheritDoc}
*/
public boolean canRead(File file) throws IOException {
return false;
}
/**
* {@inheritDoc}
*/
public SymbolTokenization guessSymbolTokenization(File file) throws IOException {
return RichSequence.IOTools.getDNAParser();
}
/**
* {@inheritDoc}
*/
public int getLineWidth() {
return this.lineWidth;
}
/**
* {@inheritDoc}
*/
public void setLineWidth(int width) {
if (width < 1) {
throw new IllegalArgumentException("Width cannot be less than 1");
}
this.lineWidth = width;
}
/**
* {@inheritDoc}
*/
public boolean getElideSymbols() {
return this.elideSymbols;
}
/**
* {@inheritDoc}
*/
public void setElideSymbols(boolean elideSymbols) {
this.elideSymbols = elideSymbols;
}
/**
* {@inheritDoc}
*/
public boolean getElideFeatures() {
return this.elideFeatures;
}
/**
* {@inheritDoc}
*/
public void setElideFeatures(boolean elideFeatures) {
this.elideFeatures = elideFeatures;
}
/**
* {@inheritDoc}
*/
public boolean getElideReferences() {
return this.elideReferences;
}
/**
* {@inheritDoc}
*/
public void setElideReferences(boolean elideReferences) {
this.elideReferences = elideReferences;
}
/**
* {@inheritDoc}
*/
public boolean getElideComments() {
return this.elideComments;
}
/**
* {@inheritDoc}
*/
public void setElideComments(boolean elideComments) {
this.elideComments = elideComments;
}
/**
* {@inheritDoc}
*/
public void setPrintStream(PrintStream os) {
if (os == null) {
throw new IllegalArgumentException("Print stream cannot be null");
}
this.os = os;
}
/**
* {@inheritDoc}
*/
public PrintStream getPrintStream() {
return this.os;
}
}
/**
* Provides the basic implementation required for simple header/footer-less
* files such as Genbank.
*/
public abstract class HeaderlessFormat extends BasicFormat {
/**
* {@inheritDoc}
*/
public void beginWriting() throws IOException {
}
/**
* {@inheritDoc}
*/
public void finishWriting() throws IOException {
}
}
}
|
9243abdbcda834ba8d700b10c726d3c51ce294cc | 1,122 | java | Java | code/PMP/PMP/src/main/java/de/unistuttgart/ipvs/pmp/model/exception/PluginNotFoundException.java | stachch/Privacy_Management_Platform | de78ee0685910d56b64c6accd6b43113f6f5258c | [
"Apache-2.0"
] | 2 | 2015-10-13T10:52:14.000Z | 2018-04-17T07:40:31.000Z | code/PMP/PMP/src/main/java/de/unistuttgart/ipvs/pmp/model/exception/PluginNotFoundException.java | stachch/Privacy_Management_Platform | de78ee0685910d56b64c6accd6b43113f6f5258c | [
"Apache-2.0"
] | null | null | null | code/PMP/PMP/src/main/java/de/unistuttgart/ipvs/pmp/model/exception/PluginNotFoundException.java | stachch/Privacy_Management_Platform | de78ee0685910d56b64c6accd6b43113f6f5258c | [
"Apache-2.0"
] | null | null | null | 34 | 75 | 0.699643 | 1,002,734 | /*
* Copyright 2012 pmp-android development team
* Project: PMP
* Project-Site: https://github.com/stachch/Privacy_Management_Platform
*
* ---------------------------------------------------------------------
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.unistuttgart.ipvs.pmp.model.exception;
import de.unistuttgart.ipvs.pmp.model.assertion.ModelMisuseError;
public class PluginNotFoundException extends ModelMisuseError {
private static final long serialVersionUID = 1370793487506591588L;
public PluginNotFoundException(String text) {
super(text);
}
}
|
9243ad50eeda8bc901edba5a32a69e52edbbccbc | 1,013 | java | Java | PA-Core/src/es/projectalpha/pa/core/utils/FireworkAPI.java | cadox8/PA | 7268d7350f7c43d7ecf726d5ec21fae1f7c4ca4d | [
"Apache-2.0"
] | 3 | 2017-11-13T16:38:41.000Z | 2018-04-24T12:33:04.000Z | PA-Core/src/es/projectalpha/pa/core/utils/FireworkAPI.java | cadox8/PA | 7268d7350f7c43d7ecf726d5ec21fae1f7c4ca4d | [
"Apache-2.0"
] | null | null | null | PA-Core/src/es/projectalpha/pa/core/utils/FireworkAPI.java | cadox8/PA | 7268d7350f7c43d7ecf726d5ec21fae1f7c4ca4d | [
"Apache-2.0"
] | 2 | 2017-11-13T16:39:11.000Z | 2017-11-15T16:09:59.000Z | 33.766667 | 148 | 0.725568 | 1,002,735 | package es.projectalpha.pa.core.utils;
import org.bukkit.Color;
import org.bukkit.FireworkEffect;
import org.bukkit.Location;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Firework;
import org.bukkit.inventory.meta.FireworkMeta;
public class FireworkAPI {
public static Firework spawnFirework(Location l, FireworkEffect.Type type, Color color, Color fade, int power){
return spawnFirework(l, type, color, fade, true, true, power);
}
public static Firework spawnFirework(Location l, FireworkEffect.Type type, Color color, Color fade, boolean trail, boolean flicker, int power) {
Firework fw = (Firework) l.getWorld().spawnEntity(l, EntityType.FIREWORK);
FireworkMeta fwm = fw.getFireworkMeta();
FireworkEffect effect = FireworkEffect.builder().flicker(flicker).withColor(color).withFade(fade).with(type).trail(trail).build();
fwm.addEffect(effect);
fwm.setPower(power);
fw.setFireworkMeta(fwm);
return fw;
}
}
|
9243adf85713855e149b065e07c3790abc243efc | 387 | java | Java | webswing-server/webswing-server-security/src/main/java/org/webswing/server/services/security/api/RolePermissionResolver.java | swing-fly/webswing | c705e993df9aa21521cff7eabaefa61cf4f14bf3 | [
"Apache-2.0"
] | null | null | null | webswing-server/webswing-server-security/src/main/java/org/webswing/server/services/security/api/RolePermissionResolver.java | swing-fly/webswing | c705e993df9aa21521cff7eabaefa61cf4f14bf3 | [
"Apache-2.0"
] | null | null | null | webswing-server/webswing-server-security/src/main/java/org/webswing/server/services/security/api/RolePermissionResolver.java | swing-fly/webswing | c705e993df9aa21521cff7eabaefa61cf4f14bf3 | [
"Apache-2.0"
] | 1 | 2019-05-24T13:45:45.000Z | 2019-05-24T13:45:45.000Z | 27.642857 | 102 | 0.75969 | 1,002,736 | package org.webswing.server.services.security.api;
/**
* Provides a logic to map Roles to Permissions for {@link AbstractWebswingUser#isPermitted(String)}'s
* default implementation.
*/
public interface RolePermissionResolver {
/**
* @param permission permission name
* @return All roles the permission is allowed for
*/
String[] getRolesForPermission(String permission);
}
|
9243ae224cb002cd49c480382a3f75262a30052e | 1,774 | java | Java | src/vulc/luag/editor/map/gui/MapPreview.java | Vulcalien/Java-Lua-Console | b1bdd66a69301d76174f64f66c147b26f5efa5ff | [
"Apache-2.0"
] | 21 | 2019-06-24T22:21:14.000Z | 2022-01-15T02:51:42.000Z | src/vulc/luag/editor/map/gui/MapPreview.java | Vulcalien/Java-Lua-Console | b1bdd66a69301d76174f64f66c147b26f5efa5ff | [
"Apache-2.0"
] | null | null | null | src/vulc/luag/editor/map/gui/MapPreview.java | Vulcalien/Java-Lua-Console | b1bdd66a69301d76174f64f66c147b26f5efa5ff | [
"Apache-2.0"
] | 2 | 2020-08-09T12:45:25.000Z | 2022-01-02T14:53:20.000Z | 28.612903 | 80 | 0.695603 | 1,002,737 | package vulc.luag.editor.map.gui;
import vulc.luag.editor.map.MapEditor;
import vulc.luag.game.Game;
import vulc.luag.gfx.Colors;
import vulc.luag.gfx.Screen;
import vulc.luag.gfx.gui.GUIPanel;
public class MapPreview extends GUIPanel {
private final MapEditor editor;
private final Game game;
private int xPointed, yPointed;
public MapPreview(int x, int y, int w, int h, MapEditor editor) {
super(x, y, w, h);
this.editor = editor;
this.game = editor.editorPanel.game;
background = Colors.BACKGROUND_1;
}
protected void drawComponents() {
super.drawComponents();
game.map.render(this.screen, game, editor.xOffset, editor.yOffset, 1);
String xText = "x: " + xPointed;
String yText = "y: " + yPointed;
int wPanel = Math.max(Screen.FONT.widthOf(xText), Screen.FONT.widthOf(yText));
int hPanel = Screen.FONT.getHeight() * 2 + 1;
screen.fill(w - wPanel, h - hPanel, w, h, Colors.BACKGROUND_1);
screen.write(xText, Colors.FOREGROUND_1,
w - wPanel, h - hPanel);
screen.write(yText, Colors.FOREGROUND_1,
w - wPanel, h - Screen.FONT.getHeight());
}
public void onMouseDown(int xMouse, int yMouse) {
super.onMouseDown(xMouse, yMouse);
int xt = Math.floorDiv(xMouse + editor.xOffset, Game.SPR_SIZE);
int yt = Math.floorDiv(yMouse + editor.yOffset, Game.SPR_SIZE);
if(xt < 0 || yt < 0 || xt >= game.map.width || yt >= game.map.height) return;
if(game.map.getTile(xt, yt) != editor.selectedTile) {
game.map.setTile(xt, yt, editor.selectedTile);
editor.shouldSaveContent = true;
}
}
public void onMouseInside(int xMouse, int yMouse) {
this.xPointed = Math.floorDiv(xMouse + editor.xOffset, Game.SPR_SIZE);
this.yPointed = Math.floorDiv(yMouse + editor.yOffset, Game.SPR_SIZE);
}
}
|
9243af15c773d192f8f756690a5abbdb2c16f2c8 | 154 | java | Java | api-model/src/main/java/no/vegvesen/ixn/federation/api/v1_0/RESTEndpointPaths.java | NordicWayInterchange/interchange | 68e49064651e5eccdc2c8270cdb26985f9484c47 | [
"MIT"
] | 6 | 2019-02-28T16:52:48.000Z | 2021-06-15T08:38:03.000Z | api-model/src/main/java/no/vegvesen/ixn/federation/api/v1_0/RESTEndpointPaths.java | NordicWayInterchange/interchange | 68e49064651e5eccdc2c8270cdb26985f9484c47 | [
"MIT"
] | 8 | 2019-05-07T14:35:48.000Z | 2021-06-01T13:22:25.000Z | api-model/src/main/java/no/vegvesen/ixn/federation/api/v1_0/RESTEndpointPaths.java | NordicWayInterchange/interchange | 68e49064651e5eccdc2c8270cdb26985f9484c47 | [
"MIT"
] | 2 | 2020-10-29T14:24:42.000Z | 2021-04-11T14:32:31.000Z | 19.25 | 64 | 0.792208 | 1,002,738 | package no.vegvesen.ixn.federation.api.v1_0;
public final class RESTEndpointPaths {
public static final String CAPABILITIES_PATH = "/capabilities";
}
|
9243af65605f7d7741dfa0df8000f69c2c0104f3 | 3,735 | java | Java | src/interdroid/swan/sensors/AbstractMemorySensor.java | interdroid/interdroid-swan | aa1d04666a36949f752717f9416d246a5a09e0f7 | [
"BSD-3-Clause"
] | 1 | 2016-04-11T15:37:39.000Z | 2016-04-11T15:37:39.000Z | src/interdroid/swan/sensors/AbstractMemorySensor.java | interdroid/interdroid-swan | aa1d04666a36949f752717f9416d246a5a09e0f7 | [
"BSD-3-Clause"
] | null | null | null | src/interdroid/swan/sensors/AbstractMemorySensor.java | interdroid/interdroid-swan | aa1d04666a36949f752717f9416d246a5a09e0f7 | [
"BSD-3-Clause"
] | null | null | null | 26.118881 | 107 | 0.645248 | 1,002,739 | package interdroid.swan.sensors;
import interdroid.swan.swansong.TimestampedValue;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Abstract class that implements basic functionality for sensors. Descendants
* only have to implement requestReading() and onEntityServiceLevelChange(). The
* rest can be overridden optionally.
*/
public abstract class AbstractMemorySensor extends AbstractSensorBase {
/**
* The map of values for this sensor.
*/
private final Map<String, List<TimestampedValue>> values = new HashMap<String, List<TimestampedValue>>();
private long mReadings = 0;
private long mLastReadingTimestamp = 0;
/**
* @return the values
*/
public final Map<String, List<TimestampedValue>> getValues() {
return values;
}
@Override
public final void init() {
for (String valuePath : VALUE_PATHS) {
expressionIdsPerValuePath.put(valuePath, new ArrayList<String>());
getValues()
.put(valuePath,
Collections
.synchronizedList(new ArrayList<TimestampedValue>()));
}
}
/**
* Trims the values to the given length.
*
* @param history
* the number of items to keep
*/
private final void trimValues(final int history) {
for (String path : VALUE_PATHS) {
if (getValues().get(path).size() >= history) {
getValues().get(path).remove(getValues().get(path).size() - 1);
}
}
}
/**
* Adds a value for the given value path to the history.
*
* @param valuePath
* the value path
* @param now
* the current time
* @param value
* the value
* @param historySize
* the history size
*/
protected final void putValueTrimSize(final String valuePath,
final String id, final long now, final Object value,
final int historySize) {
updateReadings(now);
getValues().get(valuePath).add(0, new TimestampedValue(value, now));
trimValues(historySize);
if (id != null) {
notifyDataChangedForId(id);
} else {
notifyDataChanged(valuePath);
}
}
/**
* Adds a value for the given value path to the history.
*
* @param valuePath
* the value path
* @param now
* the current time
* @param value
* the value
* @param historyLength
* the history length
*/
protected final void putValueTrimTime(final String valuePath,
final String id, final long now, final Object value,
final long historyLength) {
updateReadings(now);
getValues().get(valuePath).add(0, new TimestampedValue(value, now));
trimValueByTime(now - historyLength);
if (id != null) {
notifyDataChangedForId(id);
} else {
notifyDataChanged(valuePath);
}
}
private void updateReadings(long now) {
if (now != mLastReadingTimestamp) {
mReadings++;
mLastReadingTimestamp = now;
}
}
/**
* Trims values past the given expire time.
*
* @param expire
* the time to trim after
*/
private final void trimValueByTime(final long expire) {
for (String valuePath : VALUE_PATHS) {
List<TimestampedValue> values = getValues().get(valuePath);
while ((values.size() > 0 && values.get(values.size() - 1)
.getTimestamp() < expire)) {
values.remove(values.size() - 1);
}
}
}
@Override
public final List<TimestampedValue> getValues(final String id,
final long now, final long timespan) {
return getValuesForTimeSpan(values.get(registeredValuePaths.get(id)),
now, timespan);
}
@Override
public long getReadings() {
return mReadings;
}
}
|
9243afc48a7d148e870a6d016ca91f2823ac34f7 | 1,798 | java | Java | Chapter08/Example2/TesterTwo.java | waldronmatt/object-oriented-application-development-using-java-student-source-code | b1925965839decc323749651b169ab8d82ffa188 | [
"W3C",
"BSD-Source-Code"
] | 1 | 2022-01-29T06:14:10.000Z | 2022-01-29T06:14:10.000Z | Chapter08/Example3/TesterTwo.java | waldronmatt/object-oriented-application-development-using-java-student-source-code | b1925965839decc323749651b169ab8d82ffa188 | [
"W3C",
"BSD-Source-Code"
] | null | null | null | Chapter08/Example3/TesterTwo.java | waldronmatt/object-oriented-application-development-using-java-student-source-code | b1925965839decc323749651b169ab8d82ffa188 | [
"W3C",
"BSD-Source-Code"
] | null | null | null | 33.296296 | 62 | 0.677976 | 1,002,740 | // TesterTwo to test AnnualLease and DailyLease subclasses
import java.util.*;
public class TesterTwo
{
public static void main(String args[])
{
// create and set three dates from calendar
Calendar aCalendar = Calendar.getInstance();
aCalendar.set(2003, Calendar.AUGUST, 28);
Date date1 = aCalendar.getTime();
aCalendar.set(2003, Calendar.SEPTEMBER, 3);
Date date2 = aCalendar.getTime();
aCalendar.set(2003, Calendar.SEPTEMBER, 7);
Date date3 = aCalendar.getTime();
// create two AnnualLeases
AnnualLease firstLease = new AnnualLease(date1, 14, true);
AnnualLease secondLease = new AnnualLease(date2, 16, false);
// create two DailyLeases
DailyLease thirdLease = new DailyLease(date1, date2, 14);
DailyLease fourthLease = new DailyLease(date2, date3, 16);
// retrieve information about the Annual Leases
System.out.println("AnnualLease 1 information is: \n"
+ firstLease.getAmount() + " "
+ firstLease.getStartDate() + " "
+ firstLease.getEndDate() + " "
+ firstLease.getBalanceDue() + " "
+ firstLease.getPayMonthly());
System.out.println("AnnualLease 2 information is: \n"
+ secondLease.getAmount() + " "
+ secondLease.getStartDate() + " "
+ secondLease.getEndDate() + " "
+ secondLease.getBalanceDue() + " "
+ secondLease.getPayMonthly());
// retrieve information about daily leases
System.out.println("DailyLease 1 information is: \n"
+ thirdLease.getAmount() + " "
+ thirdLease.getStartDate() + " "
+ thirdLease.getEndDate() + " "
+ thirdLease.getNumberOfDays());
System.out.println("DailyLease 2 information is: \n"
+ fourthLease.getAmount() + " "
+ fourthLease.getStartDate() + " "
+ fourthLease.getEndDate() + " "
+ fourthLease.getNumberOfDays());
}
}
|
9243b05024f1fcdb8bedbeadfc299a7a1cf5ccb2 | 1,328 | java | Java | AL-Game/src/com/aionemu/gameserver/network/loginserver/serverpackets/SM_LS_PONG.java | karllgiovany/Aion-Lightning-4.9-SRC | 05beede3382ec7dbdabb2eb9f76e4e42d046ff59 | [
"FTL"
] | 1 | 2019-04-05T22:44:56.000Z | 2019-04-05T22:44:56.000Z | AL-Game/src/com/aionemu/gameserver/network/loginserver/serverpackets/SM_LS_PONG.java | korssar2008/Aion-Lightning-4.9 | 05beede3382ec7dbdabb2eb9f76e4e42d046ff59 | [
"FTL"
] | null | null | null | AL-Game/src/com/aionemu/gameserver/network/loginserver/serverpackets/SM_LS_PONG.java | korssar2008/Aion-Lightning-4.9 | 05beede3382ec7dbdabb2eb9f76e4e42d046ff59 | [
"FTL"
] | 1 | 2017-12-28T16:59:47.000Z | 2017-12-28T16:59:47.000Z | 32.390244 | 74 | 0.729669 | 1,002,741 | /**
* This file is part of Aion-Lightning <aion-lightning.org>.
*
* Aion-Lightning 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.
*
* Aion-Lightning 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 Aion-Lightning.
* If not, see <http://www.gnu.org/licenses/>.
*/
package com.aionemu.gameserver.network.loginserver.serverpackets;
import com.aionemu.gameserver.configs.network.NetworkConfig;
import com.aionemu.gameserver.network.loginserver.LoginServerConnection;
import com.aionemu.gameserver.network.loginserver.LsServerPacket;
/**
* @author KID
*/
public class SM_LS_PONG extends LsServerPacket {
private int pid;
public SM_LS_PONG(int pid) {
super(12);
this.pid = pid;
}
@Override
protected void writeImpl(LoginServerConnection con) {
writeC(NetworkConfig.GAMESERVER_ID);
writeD(pid);
}
}
|
9243b0e8005dc41e10ee631e8d99dc0dae86f601 | 703 | java | Java | leopard-boot-lang-parent/leopard-boot-qrcode/src/main/java/io/leopard/boot/qrcode/Logo.java | tanhaichao/leopard-boot | 5b7d03bb59f11b7e48733ab97cf7f1da95abe87f | [
"Apache-2.0"
] | 2 | 2018-10-26T02:30:42.000Z | 2019-08-09T09:48:02.000Z | leopard-boot-lang-parent/leopard-boot-qrcode/src/main/java/io/leopard/boot/qrcode/Logo.java | tanhaichao/leopard-boot | 5b7d03bb59f11b7e48733ab97cf7f1da95abe87f | [
"Apache-2.0"
] | 11 | 2020-03-04T22:17:02.000Z | 2021-04-19T11:17:20.000Z | leopard-boot-lang-parent/leopard-boot-qrcode/src/main/java/io/leopard/boot/qrcode/Logo.java | tanhaichao/leopard-boot | 5b7d03bb59f11b7e48733ab97cf7f1da95abe87f | [
"Apache-2.0"
] | 5 | 2018-10-23T08:46:20.000Z | 2022-01-13T01:17:24.000Z | 11.716667 | 52 | 0.638691 | 1,002,742 | package io.leopard.boot.qrcode;
import java.io.File;
/**
* Logo信息
*
* @author 谭海潮
*
*/
public class Logo {
/**
* 文件
*/
File file;
/**
* 是否压缩
*/
boolean needCompress;
int width = 60;
int height = 60;
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public boolean isNeedCompress() {
return needCompress;
}
public void setNeedCompress(boolean needCompress) {
this.needCompress = needCompress;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
}
|
9243b32d5d6d5311a318cfabfdf1f9e862ffb2e3 | 1,126 | java | Java | app/src/main/java/com/amazonaws/postsapp/Constants.java | anonyome/aws-mobile-appsync-sdk-android | 9bfab0d601c5532de07948a22653e568bda38c19 | [
"Apache-2.0"
] | 108 | 2018-02-14T15:21:23.000Z | 2022-02-16T05:24:05.000Z | app/src/main/java/com/amazonaws/postsapp/Constants.java | anonyome/aws-mobile-appsync-sdk-android | 9bfab0d601c5532de07948a22653e568bda38c19 | [
"Apache-2.0"
] | 258 | 2018-03-11T05:17:33.000Z | 2022-03-28T13:37:47.000Z | app/src/main/java/com/amazonaws/postsapp/Constants.java | anonyome/aws-mobile-appsync-sdk-android | 9bfab0d601c5532de07948a22653e568bda38c19 | [
"Apache-2.0"
] | 65 | 2018-03-28T21:36:56.000Z | 2022-03-23T12:00:10.000Z | 51.181818 | 136 | 0.757549 | 1,002,743 | package com.amazonaws.postsapp;
import com.amazonaws.regions.Regions;
public class Constants {
public static final Regions APPSYNC_REGION = Regions.US_EAST_1; // TODO: Update the region to match the API region
public static final String APPSYNC_API_URL = ""; // TODO: Update the endpoint URL as specified on AppSync console
// API Key Authorization
public static final String APPSYNC_API_KEY = "API-KEY"; // TODO: Copy the API Key specified on the AppSync Console
// IAM based Authorization (Cognito Identity)
public static final String COGNITO_IDENTITY = ""; // TODO: Update the Cognito Identity Pool ID
public static final Regions COGNITO_REGION = Regions.US_EAST_1; // TODO: Update the region to match the Cognito Identity Pool region
// Cognito User Pools Authorization
public static final String USER_POOLS_POOL_ID = "";
public static final String USER_POOLS_CLIENT_ID = "";
public static final String USER_POOLS_CLIENT_SECRET = "";
public static final Regions USER_POOLS_REGION = Regions.US_WEST_2; // TODO: Update the region to match the Cognito User Pools region
}
|
9243b42fa6328c933ec1e81ae30db428844c88f3 | 2,722 | java | Java | webmail/src/main/java/org/moonwave/util/mail/SimpleMail.java | jonathanluo/jsf | 7b5172fb8fd79fa9b485ecea968904beb14f67b9 | [
"Apache-2.0"
] | null | null | null | webmail/src/main/java/org/moonwave/util/mail/SimpleMail.java | jonathanluo/jsf | 7b5172fb8fd79fa9b485ecea968904beb14f67b9 | [
"Apache-2.0"
] | null | null | null | webmail/src/main/java/org/moonwave/util/mail/SimpleMail.java | jonathanluo/jsf | 7b5172fb8fd79fa9b485ecea968904beb14f67b9 | [
"Apache-2.0"
] | 1 | 2019-09-24T09:21:22.000Z | 2019-09-24T09:21:22.000Z | 25.439252 | 96 | 0.585599 | 1,002,744 | package org.moonwave.util.mail;
/**
* A simple mail that does not have attachments
*
*/
@SuppressWarnings("serial")
public class SimpleMail implements java.io.Serializable {
protected String from;
protected String replyTo;
protected String to;
protected String cc;
protected String bcc;
protected String subject;
protected String body;
protected String postscript;
protected boolean htmlMail; // true for html mail, false text mail
protected boolean appendPostscript; // true to apply postscript, false not apply postscript
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getReplyTo() {
return replyTo;
}
public void setReplyTo(String replyTo) {
this.replyTo = replyTo;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getCc() {
return cc;
}
public void setCc(String cc) {
this.cc = cc;
}
public String getBcc() {
return bcc;
}
public void setBcc(String bcc) {
this.bcc = bcc;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getPostscript() {
return postscript;
}
public void setPostscript(String postscript) {
this.postscript = postscript;
}
public boolean isHtmlMail() {
return htmlMail;
}
public void setHtmlMail(boolean htmlMail) {
this.htmlMail = htmlMail;
}
public boolean isAppendPostscript() {
return appendPostscript;
}
public void setAppendPostscript(boolean appendPostscript) {
this.appendPostscript = appendPostscript;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("(from: ").append(from);
sb.append(", replyTo: ").append(replyTo);
sb.append(", to: ").append(to);
sb.append(", cc: ").append(cc);
sb.append(", bcc: ").append(bcc);
sb.append(", subject: ").append(subject);
sb.append(", body: ").append(body);
sb.append(", postscript: ").append(postscript);
sb.append(", htmlMail: ").append(htmlMail).append(")");
sb.append(", appendPostscript: ").append(appendPostscript).append(")");
return sb.toString();
}
}
|
9243b45df469d53fd5544676006d9696764c7077 | 3,175 | java | Java | hw-gae-client_fro/src/main/java/hu/hw/cloud/client/fro/browser/appuser/AppUserBrowserPresenter.java | LetsCloud/hw-gae | e4a55f8fe152ad588156942ddc28e852faf8ebcd | [
"Apache-2.0"
] | null | null | null | hw-gae-client_fro/src/main/java/hu/hw/cloud/client/fro/browser/appuser/AppUserBrowserPresenter.java | LetsCloud/hw-gae | e4a55f8fe152ad588156942ddc28e852faf8ebcd | [
"Apache-2.0"
] | 30 | 2017-12-27T20:52:43.000Z | 2019-02-15T14:15:02.000Z | hw-gae-client_fro/src/main/java/hu/hw/cloud/client/fro/browser/appuser/AppUserBrowserPresenter.java | LetsCloud/hw-gae | e4a55f8fe152ad588156942ddc28e852faf8ebcd | [
"Apache-2.0"
] | 1 | 2018-05-02T07:40:53.000Z | 2018-05-02T07:40:53.000Z | 27.850877 | 113 | 0.767244 | 1,002,745 | /**
*
*/
package hu.hw.cloud.client.fro.browser.appuser;
import java.util.List;
import java.util.logging.Logger;
import javax.inject.Inject;
import com.google.web.bindery.event.shared.EventBus;
import com.gwtplatform.dispatch.rest.delegates.client.ResourceDelegate;
import com.gwtplatform.mvp.client.HasUiHandlers;
import com.gwtplatform.mvp.client.PresenterWidget;
import com.gwtplatform.mvp.client.View;
import com.gwtplatform.mvp.client.presenter.slots.SingleSlot;
import com.gwtplatform.mvp.client.proxy.PlaceManager;
import hu.hw.cloud.client.core.CoreNameTokens;
import hu.hw.cloud.client.core.security.CurrentUser;
import hu.hw.cloud.client.core.util.AbstractAsyncCallback;
import hu.hw.cloud.client.core.util.ErrorHandlerAsyncCallback;
import hu.hw.cloud.client.fro.browser.AbstractBrowserPresenter;
import hu.hw.cloud.shared.api.AppUserResource;
import hu.hw.cloud.shared.dto.common.AppUserDto;
/**
* @author robi
*
*/
public class AppUserBrowserPresenter extends AbstractBrowserPresenter<AppUserDto, AppUserBrowserPresenter.MyView>
implements AppUserBrowserUiHandlers {
private static Logger logger = Logger.getLogger(AppUserBrowserPresenter.class.getName());
public interface MyView extends View, HasUiHandlers<AppUserBrowserUiHandlers> {
void setData(List<AppUserDto> data);
}
public static final SingleSlot<PresenterWidget<?>> SLOT_EDITOR = new SingleSlot<>();
private final ResourceDelegate<AppUserResource> resourceDelegate;
@Inject
AppUserBrowserPresenter(EventBus eventBus, PlaceManager placeManager, MyView view,
ResourceDelegate<AppUserResource> resourceDelegate, CurrentUser currentUser) {
super(eventBus, view, placeManager);
logger.info("AppUserBrowserPresenter()");
this.resourceDelegate = resourceDelegate;
getView().setUiHandlers(this);
}
@Override
protected void loadData() {
resourceDelegate.withCallback(new AbstractAsyncCallback<List<AppUserDto>>() {
@Override
public void onSuccess(List<AppUserDto> result) {
getView().setData(result);
}
}).list();
}
@Override
protected String getCreatorNameToken() {
return CoreNameTokens.USER_EDITOR;
}
@Override
protected String getEditorNameToken() {
return CoreNameTokens.USER_EDITOR;
}
@Override
protected void deleteData(String webSafeKey) {
resourceDelegate.withCallback(new AbstractAsyncCallback<Void>() {
@Override
public void onSuccess(Void result) {
loadData();
}
}).delete(webSafeKey);
}
@Override
public void inviteItem(List<AppUserDto> dtos) {
for (AppUserDto dto : dtos) {
resourceDelegate.withCallback(new ErrorHandlerAsyncCallback<AppUserDto>(this) {
@Override
public void onSuccess(AppUserDto userDto) {
}
@Override
public void onFailure(Throwable caught) {
}
}).invite(dto);
}
}
@Override
public void clearFcmTokens(List<AppUserDto> dtos) {
for (AppUserDto dto : dtos) {
dto.getFcmTokens().clear();
resourceDelegate.withCallback(new ErrorHandlerAsyncCallback<AppUserDto>(this) {
@Override
public void onSuccess(AppUserDto userDto) {
}
@Override
public void onFailure(Throwable caught) {
}
}).saveOrCreate(dto);
}
}
} |
9243b4c75bcedc0fdeb7df770fb6eeaad27eba26 | 911 | java | Java | src/test/java/io/business/results/ChangeStateTest.java | zeroDivisible/kata-business-rules | 6fa8fc944619f37a647ec6e18e55010faec04dbc | [
"MIT"
] | 1 | 2019-09-27T07:14:17.000Z | 2019-09-27T07:14:17.000Z | src/test/java/io/business/results/ChangeStateTest.java | zeroDivisible/kata-business-rules | 6fa8fc944619f37a647ec6e18e55010faec04dbc | [
"MIT"
] | null | null | null | src/test/java/io/business/results/ChangeStateTest.java | zeroDivisible/kata-business-rules | 6fa8fc944619f37a647ec6e18e55010faec04dbc | [
"MIT"
] | null | null | null | 23.973684 | 84 | 0.712404 | 1,002,746 | package io.business.results;
import io.business.Product;
import io.business.properties.State;
import org.omg.PortableInterceptor.ACTIVE;
import org.omg.PortableInterceptor.INACTIVE;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.fest.assertions.Assertions.assertThat;
/**
* @author zerodi
*/
public class ChangeStateTest {
private ChangeState changeStateToActive;
@BeforeMethod
public void setUp() {
changeStateToActive = new ChangeState(new State("ACTIVE"));
}
@Test
public void activatingTheProductShouldChangeItsState() throws Exception {
//given
Product product = new Product();
product.addProperty(new State("INACTIVE"));
// when
changeStateToActive.on(product);
// then
assertThat(product.getProperty(State.class)).isEqualTo(new State("ACTIVE"));
}
}
|
9243b61db00d4ce1ba2534f8d4b2621b502274f7 | 893 | java | Java | _/08/extension/src/extension/client/HideOnHoverConnector.java | paullewallencom/vaadin-978-1-7821-6226-1 | ee8d5a97822834d93c59058b38e35a49055c69a0 | [
"Apache-2.0"
] | null | null | null | _/08/extension/src/extension/client/HideOnHoverConnector.java | paullewallencom/vaadin-978-1-7821-6226-1 | ee8d5a97822834d93c59058b38e35a49055c69a0 | [
"Apache-2.0"
] | null | null | null | _/08/extension/src/extension/client/HideOnHoverConnector.java | paullewallencom/vaadin-978-1-7821-6226-1 | ee8d5a97822834d93c59058b38e35a49055c69a0 | [
"Apache-2.0"
] | null | null | null | 29.766667 | 71 | 0.75252 | 1,002,747 | package extension.client;
import com.google.gwt.event.dom.client.MouseOverEvent;
import com.google.gwt.event.dom.client.MouseOverHandler;
import com.google.gwt.user.client.ui.Widget;
import com.vaadin.client.ComponentConnector;
import com.vaadin.client.ServerConnector;
import com.vaadin.client.extensions.AbstractExtensionConnector;
import com.vaadin.shared.ui.Connect;
import extension.HideOnHover;
@SuppressWarnings("serial")
@Connect(HideOnHover.class)
public class HideOnHoverConnector extends AbstractExtensionConnector {
@Override
protected void extend(ServerConnector target) {
final Widget widget = ((ComponentConnector) target).getWidget();
widget.addHandler(new MouseOverHandler() {
@Override
public void onMouseOver(MouseOverEvent event) {
widget.setVisible(false);
}
}, MouseOverEvent.getType());
}
}
|
9243b66a05064a540fe96506a8da8ad49c39d0cb | 2,212 | java | Java | gulimall-ware/src/main/java/com/atguigu/gulimall/ware/controller/PurchaseController.java | blanker/gulimall | bbf3ee0ebf94e7dd2f8380c6a3a7fe63fd9c65bb | [
"Apache-2.0"
] | null | null | null | gulimall-ware/src/main/java/com/atguigu/gulimall/ware/controller/PurchaseController.java | blanker/gulimall | bbf3ee0ebf94e7dd2f8380c6a3a7fe63fd9c65bb | [
"Apache-2.0"
] | null | null | null | gulimall-ware/src/main/java/com/atguigu/gulimall/ware/controller/PurchaseController.java | blanker/gulimall | bbf3ee0ebf94e7dd2f8380c6a3a7fe63fd9c65bb | [
"Apache-2.0"
] | null | null | null | 24.340659 | 64 | 0.691648 | 1,002,748 | package com.atguigu.gulimall.ware.controller;
import java.util.Arrays;
import java.util.Map;
// import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.atguigu.gulimall.ware.entity.PurchaseEntity;
import com.atguigu.gulimall.ware.service.PurchaseService;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.R;
/**
* 采购信息
*
* @author blank
* @email [email protected]
* @date 2020-08-18 22:17:07
*/
@RestController
@RequestMapping("ware/purchase")
public class PurchaseController {
@Autowired
private PurchaseService purchaseService;
/**
* 列表
*/
@RequestMapping("/list")
//@RequiresPermissions("ware:purchase:list")
public R list(@RequestParam Map<String, Object> params){
PageUtils page = purchaseService.queryPage(params);
return R.ok().put("page", page);
}
/**
* 信息
*/
@RequestMapping("/info/{id}")
//@RequiresPermissions("ware:purchase:info")
public R info(@PathVariable("id") Long id){
PurchaseEntity purchase = purchaseService.getById(id);
return R.ok().put("purchase", purchase);
}
/**
* 保存
*/
@RequestMapping("/save")
//@RequiresPermissions("ware:purchase:save")
public R save(@RequestBody PurchaseEntity purchase){
purchaseService.save(purchase);
return R.ok();
}
/**
* 修改
*/
@RequestMapping("/update")
//@RequiresPermissions("ware:purchase:update")
public R update(@RequestBody PurchaseEntity purchase){
purchaseService.updateById(purchase);
return R.ok();
}
/**
* 删除
*/
@RequestMapping("/delete")
//@RequiresPermissions("ware:purchase:delete")
public R delete(@RequestBody Long[] ids){
purchaseService.removeByIds(Arrays.asList(ids));
return R.ok();
}
}
|
9243b679e3ce62c00772e32fa10e9967e9af2f8c | 326 | java | Java | src/main/java/cn/com/ctrl/yjjy/project/control/broadcast/domain/ShebeiCatType.java | githubZzmh/yjjy | 2f4dc2996198d6b434745a2c00d30cada0787356 | [
"MIT"
] | null | null | null | src/main/java/cn/com/ctrl/yjjy/project/control/broadcast/domain/ShebeiCatType.java | githubZzmh/yjjy | 2f4dc2996198d6b434745a2c00d30cada0787356 | [
"MIT"
] | null | null | null | src/main/java/cn/com/ctrl/yjjy/project/control/broadcast/domain/ShebeiCatType.java | githubZzmh/yjjy | 2f4dc2996198d6b434745a2c00d30cada0787356 | [
"MIT"
] | null | null | null | 20.375 | 61 | 0.736196 | 1,002,749 | package cn.com.ctrl.yjjy.project.control.broadcast.domain;
import cn.com.ctrl.yjjy.project.basis.group.domain.ShebeiCat;
import lombok.Data;
import java.util.List;
/**
* 设备分组类型
*
* @author zzmh
* @date 2018-12-11
*/
@Data
public class ShebeiCatType {
private String type;
private List<ShebeiCat> shebeiCatList;
} |
9243b848ad1ada38f870df574c11bfe8544612e6 | 11,062 | java | Java | src/main/java/com/hpb/bc/controller/ContractController.java | hpb-project/hpb-explorer | ce26dabe961822bac49bce481aa9e42d9596b4ed | [
"Apache-2.0"
] | null | null | null | src/main/java/com/hpb/bc/controller/ContractController.java | hpb-project/hpb-explorer | ce26dabe961822bac49bce481aa9e42d9596b4ed | [
"Apache-2.0"
] | null | null | null | src/main/java/com/hpb/bc/controller/ContractController.java | hpb-project/hpb-explorer | ce26dabe961822bac49bce481aa9e42d9596b4ed | [
"Apache-2.0"
] | 1 | 2020-09-15T06:36:25.000Z | 2020-09-15T06:36:25.000Z | 55.868687 | 211 | 0.746791 | 1,002,750 | /*
* Copyright 2020 HPB Foundation.
*
* 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.hpb.bc.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.hpb.bc.entity.ContractErcStandardInfo;
import com.hpb.bc.entity.result.ResultCode;
import com.hpb.bc.model.ContractErcStandardInfoModel;
import com.hpb.bc.model.ContractInfoModel;
import com.hpb.bc.model.ContractVerifyModel;
import com.hpb.bc.service.ContractErcStandardInfoService;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.github.pagehelper.PageInfo;
import com.hpb.bc.constant.BcConstant;
import com.hpb.bc.constant.ContractConstant;
import com.hpb.bc.entity.ContractEventInfo;
import com.hpb.bc.entity.ContractInfo;
import com.hpb.bc.entity.ContractMethodInfo;
import com.hpb.bc.entity.result.Result;
import com.hpb.bc.service.ContractService;
import io.swagger.annotations.ApiOperation;
@RestController
@RequestMapping("/smart-contract")
public class ContractController extends BaseController {
@Autowired
private ContractService contractService;
@Autowired
private ContractErcStandardInfoService contractErcStandardInfoService;
@ApiOperation(value = "获取智能合约日志方法信息",
notes = "根据智能合约日志事件的HASH获取该日志方法信息, reqStrList [参数1:智能合约日志事件的HASH]")
@PostMapping("/GetContractEventInfoByEventHash")
public List<Object> getContractEventInfoByEventHash(@RequestBody List<String> reqStrList, HttpServletRequest request, HttpServletResponse response) throws Exception {
List<String> paramNames = new ArrayList<String>();
paramNames.add(ContractConstant.EVENT_HASH);
Map<String, String> reqParam = this.parseReqStrList(reqStrList, paramNames);
String eventHash = MapUtils.getString(reqParam, ContractConstant.EVENT_HASH);
Result<List<ContractEventInfo>> result = contractService.getContractEventInfoByEventHash(eventHash);
return result.getValue();
}
@ApiOperation(value = "根据智能合约账户地址获取对应日志方法信息",
notes = "根据智能合约账户地址获取该日志方法信息, reqStrList [参数1:智能合约地址]")
@PostMapping("/GetContractEventInfoByContractAddr")
public List<Object> getContractEventInfoByContractAddr(@RequestBody List<String> reqStrList,
HttpServletRequest request, HttpServletResponse response) throws Exception {
List<String> paramNames = new ArrayList<String>();
paramNames.add(ContractConstant.CONTRACT_ADDR);
Map<String, String> reqParam = this.parseReqStrList(reqStrList, paramNames);
String contractAddr = MapUtils.getString(reqParam, ContractConstant.CONTRACT_ADDR);
Result<List<ContractEventInfo>> result = contractService.getContractEventInfoByContractAddr(contractAddr);
return result.getValue();
}
@ApiOperation(value = "根据智能合约账户地址获取对应方法信息",
notes = "根据智能合约账户地址获取该方法信息, reqStrList [参数1:智能合约地址]")
@PostMapping("/GetContractMethodInfoByContractAddr")
public List<Object> getContractMethodInfoByContractAddr(@RequestBody List<String> reqStrList,
HttpServletRequest request, HttpServletResponse response) throws Exception {
List<String> paramNames = new ArrayList<String>();
paramNames.add(ContractConstant.CONTRACT_ADDR);
Map<String, String> reqParam = this.parseReqStrList(reqStrList, paramNames);
String contractAddr = MapUtils.getString(reqParam, ContractConstant.CONTRACT_ADDR);
Result<List<ContractMethodInfo>> result = contractService.getContractMethodInfoByContractAddr(contractAddr);
return result.getValue();
}
@ApiOperation(value = "根据智能合约methodId获取对应方法信息",
notes = "根据智能合约methodId获取该方法信息, reqStrList [参数1:智能合约方法ID]")
@PostMapping("/GetContractMethodInfoByMethodId")
public List<Object> getContractMethodInfoByMethodId(@RequestBody List<String> reqStrList,
HttpServletRequest request, HttpServletResponse response) throws Exception {
List<String> paramNames = new ArrayList<String>();
paramNames.add(ContractConstant.METHOD_ID);
Map<String, String> reqParam = this.parseReqStrList(reqStrList, paramNames);
String methodId = MapUtils.getString(reqParam, ContractConstant.METHOD_ID);
Result<List<ContractMethodInfo>> result = contractService.getContractMethodInfoByMethodId(methodId);
return result.getValue();
}
@ApiOperation(value = "根据智能合约账户地址获取对应智能合约详细信息",
notes = "根据智能合约账户地址获取对应智能合约详细信息, reqStrList [参数1:智能合约地址]")
@PostMapping("/GetContractInfoByContractAddr")
public List<Object> getContractInfoByContractAddr(@RequestBody List<String> reqStrList,
HttpServletRequest request, HttpServletResponse response) throws Exception {
List<String> paramNames = new ArrayList<String>();
paramNames.add(ContractConstant.CONTRACT_ADDR);
Map<String, String> reqParam = this.parseReqStrList(reqStrList, paramNames);
String contractAddr = MapUtils.getString(reqParam, ContractConstant.CONTRACT_ADDR);
Result<ContractInfo> result = contractService.getContractInfoByContractAddr(contractAddr);
return result.getValue();
}
@ApiOperation(value = "获取智能合约详细信息",
notes = "根据智能合约名称获取智能合约详细信息, reqStrList [参数1:智能合约名称]")
@PostMapping("/GetContractInfoByName")
public List<Object> getContractInfoByName(@RequestBody List<String> reqStrList,
HttpServletRequest request, HttpServletResponse response) throws Exception {
List<String> paramNames = new ArrayList<String>();
paramNames.add(ContractConstant.CONTRACT_NAME);
Map<String, String> reqParam = this.parseReqStrList(reqStrList, paramNames);
String contractName = MapUtils.getString(reqParam, ContractConstant.CONTRACT_NAME);
int pageNum = MapUtils.getIntValue(reqParam, BcConstant.PAGENUM, 1);
int pageSize = MapUtils.getIntValue(reqParam, BcConstant.PAGESIZE, BcConstant.PAGESIZE_DEFAULT);
Result<PageInfo<ContractInfo>> result = contractService.getContractInfoByName(contractName, pageNum, pageSize);
return result.getValue();
}
@ApiOperation(value = "验证并开源智能合约代码",
notes = "验证并开源智能合约代码, reqStrList [参数1:智能合约地址,参数2:合约源代码,参数3:合约ABI,参数3:合约BIN]")
@PostMapping("/ValidateContractInfo")
public List<Object> validateContractInfo(@RequestBody List<String> reqStrList, HttpServletRequest request, HttpServletResponse response) throws Exception {
List<String> paramNames = new ArrayList<String>();
paramNames.add(ContractConstant.TX_HASH);
paramNames.add(ContractConstant.CONTRACT_ADDR);
paramNames.add(ContractConstant.CONTRACT_NAME);
paramNames.add(ContractConstant.CONTRACT_COMPILER_TYPE);
paramNames.add(ContractConstant.CONTRACT_COMPILER_VERSION);
paramNames.add(ContractConstant.CONTRACT_SRC);
paramNames.add(ContractConstant.CONTRACT_ABI);
paramNames.add(ContractConstant.CONTRACT_BIN);
paramNames.add(ContractConstant.OPTIMIZE_FLAG);
paramNames.add(ContractConstant.CONTRACT_LIBRARY_NAME_ADDRESS_LIST);
Map<String, String> reqParam = this.parseReqStrList(reqStrList, paramNames);
String txHash = MapUtils.getString(reqParam, ContractConstant.TX_HASH);
String contractAddr = MapUtils.getString(reqParam, ContractConstant.CONTRACT_ADDR);
String contractSrc = MapUtils.getString(reqParam, ContractConstant.CONTRACT_NAME);
String contractCompilerType = MapUtils.getString(reqParam, ContractConstant.CONTRACT_COMPILER_TYPE);
String contractCompilerVersion = MapUtils.getString(reqParam, ContractConstant.CONTRACT_COMPILER_VERSION);
String contractName = MapUtils.getString(reqParam, ContractConstant.CONTRACT_SRC);
String contractAbi = MapUtils.getString(reqParam, ContractConstant.CONTRACT_ABI);
String contractBin = MapUtils.getString(reqParam, ContractConstant.CONTRACT_BIN);
String optimizeFlag = MapUtils.getString(reqParam, ContractConstant.OPTIMIZE_FLAG);
String contractLibraryAddress = MapUtils.getString(reqParam, ContractConstant.CONTRACT_LIBRARY_NAME_ADDRESS_LIST);
Result<ContractInfo> result = contractService.validateContractInfo(txHash, contractAddr, contractName, contractSrc, contractAbi, contractBin, optimizeFlag, contractCompilerType, contractCompilerVersion);
return result.getValue();
}
@ApiOperation(value = "发布智能合约的交易,根据发布合约的交易hash,获取智能合约地址", notes = "to address 为空的时候,调用该方法")
@GetMapping("/contractAddress/{address}")
public List<Object> getContractAddress(@PathVariable("address") String address) {
ContractErcStandardInfo contractErcStandardInfo = contractErcStandardInfoService.getContractErcStandardInfoByContractAddress(address);
Result<ContractErcStandardInfo> result = new Result<>(ResultCode.SUCCESS, contractErcStandardInfo);
return result.getValue();
}
@ApiOperation(value = "ERC20合约列表", notes = "查询ERC20列表信息")
@PostMapping("/contractAddressList")
public List<Object> contractAddressList(@RequestBody ContractErcStandardInfoModel model) {
ContractErcStandardInfo record = new ContractErcStandardInfo();
BeanUtils.copyProperties(model, record);
PageInfo<ContractErcStandardInfo> pageInfo = contractErcStandardInfoService.queryPageContractErcStandardInfo(record, model.getCurrentPage(), model.getPageSize());
Result<PageInfo<ContractErcStandardInfo>> result = new Result<>(ResultCode.SUCCESS, pageInfo);
return result.getValue();
}
@ApiOperation(value = "已经验证合约列表", notes = "已经验证合约列表")
@PostMapping("/validated/contractAddressList")
public List<Object> validatedContractAddressList(@RequestBody ContractInfoModel model) {
PageInfo<ContractInfo> pageInfo = contractService.queryPageContractInfoList(model);
Result<PageInfo<ContractInfo>> result = new Result<>(ResultCode.SUCCESS, pageInfo);
return result.getValue();
}
} |
9243b914a4d7d12b19c4546c38a86c2ed83e8ab7 | 1,363 | java | Java | week_3/HW4/src/Utils.java | beratbayram/patika-homework | 551e93bb652a33621d55d565e3429fd28cf2ea7c | [
"MIT"
] | null | null | null | week_3/HW4/src/Utils.java | beratbayram/patika-homework | 551e93bb652a33621d55d565e3429fd28cf2ea7c | [
"MIT"
] | null | null | null | week_3/HW4/src/Utils.java | beratbayram/patika-homework | 551e93bb652a33621d55d565e3429fd28cf2ea7c | [
"MIT"
] | 1 | 2022-03-20T18:40:34.000Z | 2022-03-20T18:40:34.000Z | 45.433333 | 179 | 0.280264 | 1,002,751 | package src;
import static src.Utils.Header.Notebook;
public class Utils {
enum Header {
Notebook,
MobilePhone
}
static void println(String str) {
System.out.println(str);
}
static void printHeader(Header header) {
switch (header) {
case Notebook -> {
Utils.println("----------------------------------------------------------------------------------------------------------");
Utils.println("| ID | Product Name | Price | Brand | Storage | Screen Size | RAM |");
Utils.println("----------------------------------------------------------------------------------------------------------");
}
case MobilePhone -> {
Utils.println("-------------------------------------------------------------------------------------------------------------------------------------------------");
Utils.println("| ID | Product Name | Price | Brand | Storage | Screen Size | Camera | Battery | RAM | COLOR |");
Utils.println("-------------------------------------------------------------------------------------------------------------------------------------------------");
}
}
}
}
|
9243b9b183a55d8ad62174d0b7b5b58e01bf0ca2 | 1,773 | java | Java | src/main/java/org/apache/maven/plugins/ear/EarPluginException.java | rbhusal/java-test | e01c2f7b4331d694b5903c065226f3215709cfd1 | [
"Apache-2.0"
] | 10 | 2019-01-12T02:58:36.000Z | 2022-01-18T03:31:22.000Z | src/main/java/org/apache/maven/plugins/ear/EarPluginException.java | rbhusal/java-test | e01c2f7b4331d694b5903c065226f3215709cfd1 | [
"Apache-2.0"
] | 37 | 2020-02-23T18:05:58.000Z | 2021-06-25T15:33:08.000Z | src/main/java/org/apache/maven/plugins/ear/EarPluginException.java | slachiewicz/maven-ear-plugin | 1d71b41246fbc6696927e95a92003dce540f5e03 | [
"Apache-2.0"
] | 24 | 2018-07-20T13:13:02.000Z | 2022-03-01T12:29:50.000Z | 26.088235 | 72 | 0.636415 | 1,002,752 | package org.apache.maven.plugins.ear;
/*
* 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.
*/
/**
* The base exception of the EAR plugin.
*
* @author <a href="[email protected]">Stephane Nicoll</a>
*/
public class EarPluginException
extends Exception
{
/**
*
*/
private static final long serialVersionUID = -5540929953103327928L;
/**
* Create an instance.
*/
public EarPluginException()
{
}
/**
* @param message The message for the exception.
*/
public EarPluginException( String message )
{
super( message );
}
/**
* @param cause {@link Throwable}
*/
public EarPluginException( Throwable cause )
{
super( cause );
}
/**
* @param message The message to emit.
* @param cause {@link Throwable}
*/
public EarPluginException( String message, Throwable cause )
{
super( message, cause );
}
}
|
9243badaacd5f8e0e4f32b3b5ce2fa2e758abe65 | 1,885 | java | Java | common-starter/src/test/java/com/zst/test/concurrent/examples/InduceLockOrder.java | zest-bridge/Spring-Cloud-Learn | 5a1137179d48db4c8a1c93d0cd0556a96103e7db | [
"Apache-2.0"
] | 2 | 2019-09-18T02:59:40.000Z | 2019-09-25T08:47:37.000Z | common-starter/src/test/java/com/zst/test/concurrent/examples/InduceLockOrder.java | zest-bridge/Spring-Cloud-Learn | 5a1137179d48db4c8a1c93d0cd0556a96103e7db | [
"Apache-2.0"
] | null | null | null | common-starter/src/test/java/com/zst/test/concurrent/examples/InduceLockOrder.java | zest-bridge/Spring-Cloud-Learn | 5a1137179d48db4c8a1c93d0cd0556a96103e7db | [
"Apache-2.0"
] | 2 | 2018-12-29T06:32:03.000Z | 2019-09-18T02:59:43.000Z | 27.318841 | 70 | 0.509284 | 1,002,753 | package com.zst.test.concurrent.examples;
/**
* InduceLockOrder
*
* Inducing a lock order to avoid deadlock
*
* @author Brian Goetz and Tim Peierls
*/
public class InduceLockOrder {
private static final Object tieLock = new Object();
public void transferMoney(final Account fromAcct,
final Account toAcct,
final DollarAmount amount)
throws InsufficientFundsException {
class Helper {
public void transfer() throws InsufficientFundsException {
if (fromAcct.getBalance().compareTo(amount) < 0)
throw new InsufficientFundsException();
else {
fromAcct.debit(amount);
toAcct.credit(amount);
}
}
}
int fromHash = System.identityHashCode(fromAcct);
int toHash = System.identityHashCode(toAcct);
if (fromHash < toHash) {
synchronized (fromAcct) {
synchronized (toAcct) {
new Helper().transfer();
}
}
} else if (fromHash > toHash) {
synchronized (toAcct) {
synchronized (fromAcct) {
new Helper().transfer();
}
}
} else {
synchronized (tieLock) {
synchronized (fromAcct) {
synchronized (toAcct) {
new Helper().transfer();
}
}
}
}
}
interface DollarAmount extends Comparable<DollarAmount> {
}
interface Account {
void debit(DollarAmount d);
void credit(DollarAmount d);
DollarAmount getBalance();
int getAcctNo();
}
class InsufficientFundsException extends Exception {
}
}
|
9243baed0fce4caf882f6637cbfa71421a7e86f9 | 1,326 | java | Java | test/jdk/java/lang/Package/Foo.java | 1690296356/jdk | eaf668d1510c28d51e26c397b582b66ebdf7e263 | [
"Apache-2.0"
] | 2 | 2018-06-19T05:43:32.000Z | 2018-06-23T10:04:56.000Z | test/jdk/java/lang/Package/Foo.java | desiyonan/OpenJDK8 | 74d4f56b6312c303642e053e5d428b44cc8326c5 | [
"MIT"
] | null | null | null | test/jdk/java/lang/Package/Foo.java | desiyonan/OpenJDK8 | 74d4f56b6312c303642e053e5d428b44cc8326c5 | [
"MIT"
] | null | null | null | 37.885714 | 76 | 0.726244 | 1,002,754 | /*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package foo;
public class Foo {
/**
* Returns all Packages visible to the class loader defining by
* this Foo class. Package.getPackages() is caller-sensitive.
*/
public static Package[] getPackages() {
return Package.getPackages();
}
}
|
9243bb3485836fe73c5df86bcd7a081f0ed10311 | 1,615 | java | Java | src/persistence/DAO.java | Benjames01/KioskSystem | b6c479fa25111174cbff1ea0e9da678c799a9751 | [
"blessing"
] | null | null | null | src/persistence/DAO.java | Benjames01/KioskSystem | b6c479fa25111174cbff1ea0e9da678c799a9751 | [
"blessing"
] | null | null | null | src/persistence/DAO.java | Benjames01/KioskSystem | b6c479fa25111174cbff1ea0e9da678c799a9751 | [
"blessing"
] | null | null | null | 23.071429 | 90 | 0.720743 | 1,002,755 | package persistence;
import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DAO {
protected static Connection connection;
static String databasePath;
static String databaseURL;
static String databaseDriver = "org.sqlite.JDBC";
public DAO() throws SQLException, ClassNotFoundException {
setupConnection();
}
/*
* Create the connection to the database that will be shared by all DAOs
*/
private static void setupConnection() {
if (connection == null) {
databasePath = new JFileChooser().getFileSystemView().getDefaultDirectory().toString();
databasePath = databasePath + File.separatorChar + "KioskSystem";
try {
Files.createDirectories(Paths.get(databasePath));
System.out.println(databasePath);
databaseURL = "jdbc:sqlite:" + databasePath + File.separatorChar + "database.db";
System.out.println(databaseURL);
Class.forName(databaseDriver);
connection = DriverManager.getConnection(databaseURL);
} catch (IOException | ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
}
/*
* Return the current connection if existing or a new connection if not
*/
public Connection getConnection() {
try {
if (connection != null && !connection.isClosed()) {
return connection;
} else {
return connection = DriverManager.getConnection(databaseURL);
}
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
}
|
9243bb3530a7f5722185ab06a80c7be6a2652ffa | 859 | java | Java | rect-manipulation.java | T-Lind/java-opencv | 0d0a68e46d57ce38bdd42329f6af980bf8cc4f16 | [
"CC0-1.0"
] | null | null | null | rect-manipulation.java | T-Lind/java-opencv | 0d0a68e46d57ce38bdd42329f6af980bf8cc4f16 | [
"CC0-1.0"
] | null | null | null | rect-manipulation.java | T-Lind/java-opencv | 0d0a68e46d57ce38bdd42329f6af980bf8cc4f16 | [
"CC0-1.0"
] | null | null | null | 34.36 | 63 | 0.600698 | 1,002,756 | import org.opencv.core.RotatedRect;
import org.opencv.core.Point;
import org.opencv.core.Size;
class rect-manipulation {
public static void main(String[] args) {
double[] center = new double[]{3, 100};
RotatedRect rect = new RotatedRect(center);
System.out.println(rect.toString());
Point center1 = rect.center;
Size size = rect.size;
String s = size.toString();
s = s.substring(0, s.indexOf("x"));
int width = (int) Double.parseDouble(s);
System.out.println(width);
String c = center1.toString();
c = c.substring(1, c.length()-1);
int index = c.indexOf(",");
int x = (int) Double.parseDouble(c.substring(0,index));
int y = (int) Double.parseDouble(c.substring(index+1));
System.out.println(x);
System.out.println(y);
}
}
|
9243bb5a643672e4cd28ed8cbaf2908d5b291954 | 1,990 | java | Java | src/main/java/com/microsoft/graph/requests/extensions/IGroupPolicyConfigurationCollectionRequestBuilder.java | isabella232/msgraph-beta-sdk-java | 7d2b929d5c99c01ec1af1a251f4bf5876ca95ed8 | [
"MIT"
] | null | null | null | src/main/java/com/microsoft/graph/requests/extensions/IGroupPolicyConfigurationCollectionRequestBuilder.java | isabella232/msgraph-beta-sdk-java | 7d2b929d5c99c01ec1af1a251f4bf5876ca95ed8 | [
"MIT"
] | 1 | 2021-02-23T20:48:12.000Z | 2021-02-23T20:48:12.000Z | src/main/java/com/microsoft/graph/requests/extensions/IGroupPolicyConfigurationCollectionRequestBuilder.java | isabella232/msgraph-beta-sdk-java | 7d2b929d5c99c01ec1af1a251f4bf5876ca95ed8 | [
"MIT"
] | null | null | null | 42.340426 | 152 | 0.737186 | 1,002,757 | // ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.requests.extensions;
import com.microsoft.graph.http.IRequestBuilder;
import com.microsoft.graph.core.ClientException;
import com.microsoft.graph.concurrency.ICallback;
import com.microsoft.graph.models.extensions.DeviceManagement;
import com.microsoft.graph.models.extensions.GroupPolicyConfiguration;
import com.microsoft.graph.models.extensions.GroupPolicyConfigurationAssignment;
import com.microsoft.graph.models.extensions.GroupPolicyDefinitionValue;
import java.util.Arrays;
import java.util.EnumSet;
import com.microsoft.graph.requests.extensions.IGroupPolicyConfigurationRequestBuilder;
import com.microsoft.graph.requests.extensions.IGroupPolicyConfigurationCollectionRequest;
import com.microsoft.graph.http.IBaseCollectionPage;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The interface for the Group Policy Configuration Collection Request Builder.
*/
public interface IGroupPolicyConfigurationCollectionRequestBuilder extends IRequestBuilder {
/**
* Creates the request
*
* @param requestOptions the options for this request
* @return the IUserRequest instance
*/
IGroupPolicyConfigurationCollectionRequest buildRequest(final com.microsoft.graph.options.Option... requestOptions);
/**
* Creates the request
*
* @param requestOptions the options for this request
* @return the IUserRequest instance
*/
IGroupPolicyConfigurationCollectionRequest buildRequest(final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions);
IGroupPolicyConfigurationRequestBuilder byId(final String id);
}
|
9243bd51b219fc2797dcc249741761bc5eff3f51 | 785 | java | Java | caiwei-web/src/main/java/xyz/lius/web/config/AppHandlerExceptionResolver.java | lbzhello/caiwei | 3e0495b87a3ece517c05747af6c26564b75b1914 | [
"MIT"
] | 1 | 2019-09-22T15:23:33.000Z | 2019-09-22T15:23:33.000Z | caiwei-web/src/main/java/xyz/lius/web/config/AppHandlerExceptionResolver.java | lbzhello/boot-groups | 3e0495b87a3ece517c05747af6c26564b75b1914 | [
"MIT"
] | 7 | 2020-09-07T13:31:54.000Z | 2022-02-18T12:38:15.000Z | caiwei-web/src/main/java/xyz/lius/web/config/AppHandlerExceptionResolver.java | lbzhello/caiwei | 3e0495b87a3ece517c05747af6c26564b75b1914 | [
"MIT"
] | null | null | null | 34.130435 | 130 | 0.76051 | 1,002,758 | package xyz.lius.web.config;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class AppHandlerExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
ModelAndView mav = new ModelAndView();
mav.addObject("message", ex.getMessage());
// 可以设置视图名导向错误页面
mav.setViewName("/error");
// 直接返回视图
// 如果返回 null,则会调用下一个 HandlerExceptionResolver
return mav;
}
}
|
9243bddf86684fd4f5682764237a8992c5484048 | 87 | java | Java | data/CBCustomRequestData.java | rakar/cyborgCore | 4e8500647d43e1ecdd06ef0fe9a82383ecd73a6b | [
"MIT"
] | null | null | null | data/CBCustomRequestData.java | rakar/cyborgCore | 4e8500647d43e1ecdd06ef0fe9a82383ecd73a6b | [
"MIT"
] | null | null | null | data/CBCustomRequestData.java | rakar/cyborgCore | 4e8500647d43e1ecdd06ef0fe9a82383ecd73a6b | [
"MIT"
] | null | null | null | 14.5 | 47 | 0.816092 | 1,002,759 | package org.montclairrobotics.cyborg.core.data;
public class CBCustomRequestData {
}
|
9243be550c1ba468f288af93a2e4ddb43a9eb6aa | 1,494 | java | Java | src/org/ralapanawa/mobile/helpers/RestHelper.java | dewmal/Ralapanawa.Mobile.Module | 82cf2e902fbf458f4ff6801cdb7d990f22c65fe1 | [
"MIT"
] | 1 | 2022-02-26T06:27:35.000Z | 2022-02-26T06:27:35.000Z | src/org/ralapanawa/mobile/helpers/RestHelper.java | dewmal/Ralapanawa.Mobile.Module | 82cf2e902fbf458f4ff6801cdb7d990f22c65fe1 | [
"MIT"
] | null | null | null | src/org/ralapanawa/mobile/helpers/RestHelper.java | dewmal/Ralapanawa.Mobile.Module | 82cf2e902fbf458f4ff6801cdb7d990f22c65fe1 | [
"MIT"
] | null | null | null | 35.571429 | 111 | 0.802544 | 1,002,760 | package org.ralapanawa.mobile.helpers;
import java.io.IOException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import android.content.Context;
import android.net.ConnectivityManager;
import android.util.Log;
public class RestHelper {
public static HttpEntity rest(List<NameValuePair> nameValuePairs)
throws ClientProtocolException, IOException, JSONException {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://" + ProjectSettingsHandler.getIp() + "/Ralapanawa_REST/RalaWS.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
Log.i("DATASEND", "FINISH");
return response.getEntity();
}
public static boolean checkdataAVB(Context context) {
ConnectivityManager connec = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
android.net.NetworkInfo wifi = connec
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo mobile = connec
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
return mobile.isConnected();
}
}
|
9243be9c26c9e39ece296c9a40e1fea48d6bbd41 | 1,441 | java | Java | src/com/licslan/week01/queue/ArrayQueue.java | ailin-licslan/basic-algorithm-ds | cb6f4ac0597c87ed1058c85ca8fd2b33c5dbc458 | [
"MIT"
] | null | null | null | src/com/licslan/week01/queue/ArrayQueue.java | ailin-licslan/basic-algorithm-ds | cb6f4ac0597c87ed1058c85ca8fd2b33c5dbc458 | [
"MIT"
] | null | null | null | src/com/licslan/week01/queue/ArrayQueue.java | ailin-licslan/basic-algorithm-ds | cb6f4ac0597c87ed1058c85ca8fd2b33c5dbc458 | [
"MIT"
] | null | null | null | 23.622951 | 63 | 0.554476 | 1,002,761 | package com.licslan.week01.queue;
/**
* @author LICSLAN 下定决心学算法与数据结构
* */
public class ArrayQueue<E> implements Queue<E> {
//私有的成员变量
private Array<E> array;
//构造函数 有容量的
public ArrayQueue(int capacity){
this.array=new Array(capacity);
}
//无参构造函数 没有容量的
public ArrayQueue(){
this.array=new Array();
}
//获取队列的容量
public int getCapacity(){
return this.array.getCapacity();
}
@Override//O(1)
public int getSize() {
return this.array.getSize();
}
@Override//O(1)
public boolean isEmpty() {
return this.array.isEmpty();
}
@Override//O(1)
public void enqueue(E o) {
this.array.addLast(o);
}
@Override//O(N) 如果100万条数据 是不是要挪动100万次呢? 循环队列解决 均摊 O(1)
public E dequeue() {
return this.array.removeFirst();
}
@Override//O(1)
public E getFront() {
return this.array.getFirst();
}
//覆盖父类的toString()
@Override
public String toString(){
StringBuilder res = new StringBuilder();
res.append(String.format("Queue: "));
res.append("Front [");//队首
for (int i = 0; i < array.getSize(); i++) {
res.append(array.get(i));
//判断是不是数组最后一个元素
if(i != array.getSize() -1)
res.append(",");
}
res.append("] Tail"); //队列尾部 用户不需要关注栈中的其他元素 只需要关注栈顶的元素
return res.toString();
}
}
|
9243c015e100a93dc1a4779c87f82da96264e28d | 1,716 | java | Java | app/src/main/java/me/murks/filmchecker/background/RmStoreQueryTask.java | felixwoestmann/filmchecker | 1ee3b95c17ae14bff1cc2af67429aee2c388c598 | [
"MIT"
] | 10 | 2017-05-31T18:07:08.000Z | 2021-11-13T17:54:03.000Z | app/src/main/java/me/murks/filmchecker/background/RmStoreQueryTask.java | felixwoestmann/filmchecker | 1ee3b95c17ae14bff1cc2af67429aee2c388c598 | [
"MIT"
] | 31 | 2016-10-13T19:49:39.000Z | 2021-02-11T17:35:17.000Z | app/src/main/java/me/murks/filmchecker/background/RmStoreQueryTask.java | felixwoestmann/filmchecker | 1ee3b95c17ae14bff1cc2af67429aee2c388c598 | [
"MIT"
] | 2 | 2016-12-07T15:46:30.000Z | 2020-03-03T14:36:42.000Z | 27.677419 | 102 | 0.705128 | 1,002,762 | package me.murks.filmchecker.background;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import me.murks.filmchecker.R;
import me.murks.filmchecker.activities.AddFilmWizardActivity;
import me.murks.filmchecker.io.RossmannApi;
import me.murks.filmchecker.model.RmQueryModel;
import me.murks.filmchecker.model.RmStoreModel;
/**
* Task to query the endpoint of rm store
* @author zouroboros
*/
public class RmStoreQueryTask extends AsyncTask<URL, Void, RmQueryModel> {
private final ProgressDialog dialog;
private final AddFilmWizardActivity wizard;
private final RmStoreModel rmModel;
public RmStoreQueryTask(AddFilmWizardActivity filmWizard, RmStoreModel model) {
dialog = new ProgressDialog(filmWizard);
wizard = filmWizard;
rmModel = model;
}
protected void onPreExecute() {
super.onPreExecute();
dialog.setMessage(dialog.getContext().getResources().getString(R.string.query_store_methods));
dialog.show();
}
@Override
protected RmQueryModel doInBackground(URL... strings) {
try {
return new RossmannApi().queryStoreQueryMethod(strings[0]);
} catch (IOException | URISyntaxException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(RmQueryModel result) {
super.onPostExecute(result);
rmModel.setRmQueryModel(result);
wizard.jumpToLastStep(rmModel, result);
dialog.dismiss();
}
@Override
protected void onCancelled(RmQueryModel result) {
dialog.dismiss();
}
}
|
9243c1156ce1af8b20dfaf3eb4d8d6eddcd7e8d2 | 3,236 | java | Java | kie-wb-common-stunner/kie-wb-common-stunner-core/kie-wb-common-stunner-commons/kie-wb-common-stunner-core-common/src/main/java/org/kie/workbench/common/stunner/core/graph/util/ParentsTypeMatcher.java | alepintus/kie-wb-common | 52f4225b6fa54d04435c8f5f59bee5894af23b7e | [
"Apache-2.0"
] | null | null | null | kie-wb-common-stunner/kie-wb-common-stunner-core/kie-wb-common-stunner-commons/kie-wb-common-stunner-core-common/src/main/java/org/kie/workbench/common/stunner/core/graph/util/ParentsTypeMatcher.java | alepintus/kie-wb-common | 52f4225b6fa54d04435c8f5f59bee5894af23b7e | [
"Apache-2.0"
] | 2 | 2018-01-26T09:30:16.000Z | 2018-02-26T14:09:27.000Z | kie-wb-common-stunner/kie-wb-common-stunner-core/kie-wb-common-stunner-commons/kie-wb-common-stunner-core-common/src/main/java/org/kie/workbench/common/stunner/core/graph/util/ParentsTypeMatcher.java | alepintus/kie-wb-common | 52f4225b6fa54d04435c8f5f59bee5894af23b7e | [
"Apache-2.0"
] | null | null | null | 39.950617 | 114 | 0.661928 | 1,002,763 | /*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* 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.kie.workbench.common.stunner.core.graph.util;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.BiPredicate;
import org.kie.workbench.common.stunner.core.api.DefinitionManager;
import org.kie.workbench.common.stunner.core.definition.adapter.binding.BindableAdapterUtils;
import org.kie.workbench.common.stunner.core.graph.Edge;
import org.kie.workbench.common.stunner.core.graph.Element;
import org.kie.workbench.common.stunner.core.graph.Node;
import org.kie.workbench.common.stunner.core.graph.content.view.View;
/**
* A predicate that checks if two nodes are using sharing the same parent
* for a given type of Definition.
*/
public class ParentsTypeMatcher
implements BiPredicate<Node<? extends View<?>, ? extends Edge>, Node<? extends View<?>, ? extends Edge>> {
private final ParentsTypeMatchPredicate parentsTypeMatch;
public ParentsTypeMatcher(final DefinitionManager definitionManager) {
this.parentsTypeMatch = new ParentsTypeMatchPredicate(new ParentByDefinitionIdProvider(definitionManager),
new GraphUtils.HasParentPredicate());
}
public ParentsTypeMatcher forParentType(final Class<?> parentType) {
this.parentsTypeMatch.forParentType(parentType);
return this;
}
@Override
public boolean test(final Node<? extends View<?>, ? extends Edge> node,
final Node<? extends View<?>, ? extends Edge> node2) {
return parentsTypeMatch.test(node,
node2);
}
static class ParentByDefinitionIdProvider
implements BiFunction<Node<? extends View<?>, ? extends Edge>, Class<?>, Optional<Element<?>>> {
final DefinitionManager definitionManager;
ParentByDefinitionIdProvider(final DefinitionManager definitionManager) {
this.definitionManager = definitionManager;
}
@Override
public Optional<Element<?>> apply(final Node<? extends View<?>, ? extends Edge> node,
final Class<?> parentType) {
return null != node ?
GraphUtils.getParentByDefinitionId(definitionManager,
node,
getDefinitionIdByTpe(parentType)) :
Optional.empty();
}
static String getDefinitionIdByTpe(final Class<?> type) {
return BindableAdapterUtils.getDefinitionId(type);
}
}
}
|
9243c2967f1c408df2d8fbb830c239331cb9ba94 | 1,871 | java | Java | src/main/java/com/kushtrimh/tomorr/user/repository/UserJooqRepository.java | kushtrimh/tomorr | 16652aa24013d5c794afb9bdcac3428e083b2550 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/kushtrimh/tomorr/user/repository/UserJooqRepository.java | kushtrimh/tomorr | 16652aa24013d5c794afb9bdcac3428e083b2550 | [
"Apache-2.0"
] | 3 | 2022-01-26T03:17:49.000Z | 2022-03-10T03:27:08.000Z | src/main/java/com/kushtrimh/tomorr/user/repository/UserJooqRepository.java | kushtrimh/tomorr | 16652aa24013d5c794afb9bdcac3428e083b2550 | [
"Apache-2.0"
] | null | null | null | 27.514706 | 108 | 0.68573 | 1,002,764 | package com.kushtrimh.tomorr.user.repository;
import com.kushtrimh.tomorr.dal.tables.records.AppUserRecord;
import org.jooq.DSLContext;
import org.springframework.stereotype.Repository;
import java.util.Objects;
import static com.kushtrimh.tomorr.dal.Tables.*;
/**
* @author Kushtrim Hajrizi
*/
@Repository
public class UserJooqRepository implements UserRepository<AppUserRecord> {
private final DSLContext create;
public UserJooqRepository(DSLContext create) {
this.create = create;
}
@Override
public int count() {
return create.selectCount().from(APP_USER).fetchOne(0, int.class);
}
@Override
public AppUserRecord findById(String id) {
return create.fetchOne(APP_USER, APP_USER.ID.eq(id));
}
@Override
public AppUserRecord findByAddress(String address) {
return create.fetchOne(APP_USER, APP_USER.ADDRESS.eq(address));
}
@Override
public AppUserRecord save(AppUserRecord user) {
Objects.requireNonNull(user);
var record = create.newRecord(APP_USER, user);
record.store();
return record;
}
@Override
public void deleteById(String id) {
create.delete(APP_USER).where(APP_USER.ID.eq(id)).execute();
}
@Override
public void associate(String userId, String artistId) {
Objects.requireNonNull(userId);
Objects.requireNonNull(artistId);
var record = create.newRecord(ARTIST_APP_USER);
record.setAppUserId(userId);
record.setArtistId(artistId);
record.store();
}
@Override
public boolean associationExists(String userId, String artistId) {
return create.fetchExists(create.selectOne()
.from(ARTIST_APP_USER)
.where(ARTIST_APP_USER.APP_USER_ID.eq(userId).and(ARTIST_APP_USER.ARTIST_ID.eq(artistId))));
}
}
|
9243c2d1e8be3a936189999e12cf37a89b8e255a | 1,139 | java | Java | AndroidAnnotations/androidannotations-api/src/main/java/org/androidannotations/annotations/sharedpreferences/DefaultInt.java | PerfectCarl/androidannotations | 04469986967a7e20206420ac4630641407b99916 | [
"Apache-2.0"
] | 2 | 2015-12-21T14:13:38.000Z | 2016-10-31T03:35:40.000Z | AndroidAnnotations/androidannotations-api/src/main/java/org/androidannotations/annotations/sharedpreferences/DefaultInt.java | PerfectCarl/androidannotations | 04469986967a7e20206420ac4630641407b99916 | [
"Apache-2.0"
] | null | null | null | AndroidAnnotations/androidannotations-api/src/main/java/org/androidannotations/annotations/sharedpreferences/DefaultInt.java | PerfectCarl/androidannotations | 04469986967a7e20206420ac4630641407b99916 | [
"Apache-2.0"
] | null | null | null | 33.5 | 80 | 0.760316 | 1,002,765 | /**
* Copyright (C) 2010-2013 eBusiness Information, Excilys Group
*
* 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.androidannotations.annotations.sharedpreferences;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Use on methods in {@link SharedPref} annotated class to specified the default
* value of this preference.
* <p/>
* The annotation value must be an <code>int</code>.
*/
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.METHOD)
public @interface DefaultInt {
int value();
}
|
9243c358984a425856d3312032ec68d6b0f49e5b | 4,136 | java | Java | alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/solver/heuristics/GeneralizedDependencyDrivenHeuristic.java | alpha-asp/Alpha | d42818a997c7da36d8798acd43a1e3f2f36a6d7e | [
"BSD-2-Clause"
] | 45 | 2017-06-14T08:43:45.000Z | 2022-03-10T13:03:59.000Z | alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/solver/heuristics/GeneralizedDependencyDrivenHeuristic.java | alpha-asp/Alpha | d42818a997c7da36d8798acd43a1e3f2f36a6d7e | [
"BSD-2-Clause"
] | 277 | 2017-04-12T16:08:16.000Z | 2022-03-08T22:00:06.000Z | alpha-core/src/main/java/at/ac/tuwien/kr/alpha/core/solver/heuristics/GeneralizedDependencyDrivenHeuristic.java | alpha-asp/Alpha | d42818a997c7da36d8798acd43a1e3f2f36a6d7e | [
"BSD-2-Clause"
] | 11 | 2017-11-21T14:44:20.000Z | 2022-02-25T06:03:26.000Z | 44.956522 | 185 | 0.778772 | 1,002,766 | /**
* Copyright (c) 2017 Siemens AG
* 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 HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package at.ac.tuwien.kr.alpha.core.solver.heuristics;
import at.ac.tuwien.kr.alpha.core.common.Assignment;
import at.ac.tuwien.kr.alpha.core.common.NoGood;
import at.ac.tuwien.kr.alpha.core.solver.ChoiceManager;
import at.ac.tuwien.kr.alpha.core.solver.heuristics.activity.BodyActivityProviderFactory.BodyActivityType;
import static at.ac.tuwien.kr.alpha.core.atoms.Literals.atomOf;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
/**
* {@link DependencyDrivenHeuristic} needs to know a lot about the structure of nogoods, i.e. the role their members play in rules.
* However, the solving component of Alpha usually deals only with nogoods and cannot naturally access this information.
* Therefore, {@link GeneralizedDependencyDrivenHeuristic} both generalizes and simplifies {@link DependencyDrivenHeuristic}
* by redefining the set of atoms dependent on a choice point.
* This set is constructed by adding to it, every time a new nogood containing a choice point is added to the stack,
* all other atoms in the nogood.
* To choose an atom, {@link GeneralizedDependencyDrivenHeuristic} then proceeds as {@link DependencyDrivenHeuristic}.
* Because {@link GeneralizedDependencyDrivenHeuristic} does not know the head belonging to a choice point,
* it just uses the {@link BerkMin} method to choose a truth value.
* Copyright (c) 2017 Siemens AG
*
*/
public class GeneralizedDependencyDrivenHeuristic extends DependencyDrivenHeuristic {
public GeneralizedDependencyDrivenHeuristic(Assignment assignment, ChoiceManager choiceManager, int decayPeriod, double decayFactor, Random random, BodyActivityType bodyActivityType) {
super(assignment, choiceManager, decayPeriod, decayFactor, random, bodyActivityType);
}
public GeneralizedDependencyDrivenHeuristic(Assignment assignment, ChoiceManager choiceManager, Random random, BodyActivityType bodyActivityType) {
super(assignment, choiceManager, random, bodyActivityType);
}
public GeneralizedDependencyDrivenHeuristic(Assignment assignment, ChoiceManager choiceManager, Random random) {
super(assignment, choiceManager, random);
}
@Override
protected void recordAtomRelationships(NoGood noGood) {
// TODO: use HeapOfActiveChoicePoints.recordAtomRelationships, which does similar things
int body = DEFAULT_CHOICE_ATOM;
Set<Integer> others = new HashSet<>();
for (int literal : noGood) {
int atom = atomOf(literal);
if (body == DEFAULT_CHOICE_ATOM && choiceManager.isAtomChoice(atom)) {
body = atom;
} else {
others.add(atom);
}
}
for (Integer atom : others) {
atomsToBodiesAtoms.put(atom, body);
bodyAtomToLiterals.put(body, atom);
}
}
@Override
protected int getAtomForChooseSign(int atom) {
return atom;
}
}
|
9243c35a5358a3bc9b9537bd2eec3239b05e0f98 | 1,170 | java | Java | src/XMLParser.java | Batzee/Android-Signature-View | d861b4748c8b8b8426989744f096304bd7787325 | [
"Apache-2.0"
] | 5 | 2016-08-24T09:22:19.000Z | 2021-05-27T15:33:54.000Z | src/XMLParser.java | Batzee/Android-Signature-View | d861b4748c8b8b8426989744f096304bd7787325 | [
"Apache-2.0"
] | null | null | null | src/XMLParser.java | Batzee/Android-Signature-View | d861b4748c8b8b8426989744f096304bd7787325 | [
"Apache-2.0"
] | 5 | 2017-04-11T17:30:04.000Z | 2021-05-27T15:34:01.000Z | 25.434783 | 82 | 0.65641 | 1,002,767 | package com.batzeesappstudio.pocketsignatureview;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Amalan Dhananjayan on 4/29/2016.
* v0.1.5
*/
public class XMLParser extends DefaultHandler {
List<String> list=null;
StringBuilder builder;
@Override
public void startDocument() throws SAXException {
list = new ArrayList<String>();
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
builder=new StringBuilder();
if(localName.equals("path")){
list.add( attributes.getValue("d"));
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if(localName.equals("path")){
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
String tempString=new String(ch, start, length);
builder.append(tempString);
}
}
|
9243c38aaaeb8992a811051cf4b26ba4c05c2e65 | 1,759 | java | Java | core/src/test/java/org/pentaho/di/core/BlockingListeningRowSetTest.java | hzy1992/pentaho-kettle | 5762bc329aea7d56c50fe797de2febdef9b6d7b2 | [
"Apache-2.0"
] | 5,903 | 2015-01-07T01:32:02.000Z | 2022-03-31T03:55:32.000Z | core/src/test/java/org/pentaho/di/core/BlockingListeningRowSetTest.java | hzy1992/pentaho-kettle | 5762bc329aea7d56c50fe797de2febdef9b6d7b2 | [
"Apache-2.0"
] | 5,944 | 2015-01-02T21:07:48.000Z | 2022-03-28T14:53:13.000Z | core/src/test/java/org/pentaho/di/core/BlockingListeningRowSetTest.java | hzy1992/pentaho-kettle | 5762bc329aea7d56c50fe797de2febdef9b6d7b2 | [
"Apache-2.0"
] | 3,097 | 2015-01-01T19:57:19.000Z | 2022-03-31T09:08:57.000Z | 35.18 | 82 | 0.598636 | 1,002,768 | /*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com
*
*******************************************************************************
*
* 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.pentaho.di.core;
import org.junit.Test;
import org.pentaho.di.core.row.RowMeta;
import static org.junit.Assert.*;
public class BlockingListeningRowSetTest {
@Test
public void testClass() {
BlockingListeningRowSet rowSet = new BlockingListeningRowSet( 1 );
assertEquals( 0, rowSet.size() );
final Object[] row = new Object[]{};
final RowMeta meta = new RowMeta();
rowSet.putRow( meta, row );
assertSame( meta, rowSet.getRowMeta() );
assertEquals( 1, rowSet.size() );
assertFalse( rowSet.isBlocking() );
assertSame( row, rowSet.getRow() );
assertEquals( 0, rowSet.size() );
rowSet.putRow( meta, row );
assertSame( row, rowSet.getRowImmediate() );
rowSet.putRow( meta, row );
assertEquals( 1, rowSet.size() );
rowSet.clear();
assertEquals( 0, rowSet.size() );
}
}
|
9243c3f5ce870d95002017e20978daa7fb6f4b04 | 1,486 | java | Java | LibraryRoom/src/main/java/com/reber/database/room/dao/UserDao.java | Reber-Han/RDatabase | 9a522d0217f35b28a307e961c42cef9420f66ce0 | [
"Apache-2.0"
] | null | null | null | LibraryRoom/src/main/java/com/reber/database/room/dao/UserDao.java | Reber-Han/RDatabase | 9a522d0217f35b28a307e961c42cef9420f66ce0 | [
"Apache-2.0"
] | null | null | null | LibraryRoom/src/main/java/com/reber/database/room/dao/UserDao.java | Reber-Han/RDatabase | 9a522d0217f35b28a307e961c42cef9420f66ce0 | [
"Apache-2.0"
] | null | null | null | 19.051282 | 56 | 0.62786 | 1,002,769 | package com.reber.database.room.dao;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import androidx.room.Update;
import com.reber.database.room.entity.Product;
import com.reber.database.room.entity.User;
import java.util.List;
/**
* @author reber
* <p>
* 对数据库中的PRODUCT表的增删改查操作
* <p>
* Update 和 Detele 操作是根据定义的主键进行
*/
@Dao
public interface UserDao {
/**
* 插入一条新数据
*
* @apiNote onConflict 添加冲突策略
* OnConflictStrategy.REPLACE 取代旧数据同时继续事务
* @param user entity/user
* @return userId 返回当前的User的userId
*/
@Insert(onConflict = OnConflictStrategy.REPLACE)
long insert(User user);
/**
* 插入数据列表
*
* @apiNote onConflict 添加冲突策略
* @return 返沪插入成功后的userId[]数组
*/
@Insert(onConflict = OnConflictStrategy.REPLACE)
long[] insertList(List<User> userList);
/**
* 返回所有的product数据
*/
@Query("SELECT * FROM USER")
List<User> getAllUser();
/**
* 根据指定字段查询
*/
@Query("SELECT * FROM USER WHERE user_id = :userId")
User findByUserId(long userId);
/**
* 更新数据
*
* @apiNote onConflict 添加冲突策略
*/
@Update(onConflict = OnConflictStrategy.REPLACE)
int update(User user);
/**
* 删除数据
*/
@Delete
int delete(User user);
/**
* 删除一个列表数据
*/
@Delete()
int deleteList(List<User> productList);
}
|
9243c40d58e9988ba7f9ea00130028131aff74ad | 3,389 | java | Java | src/test/java/com/github/se307/SongTest.java | declanvk/m-u-s-i-c | a29f4f5ac1805c4af74bafe205f5b7bfc1dafacb | [
"MIT"
] | null | null | null | src/test/java/com/github/se307/SongTest.java | declanvk/m-u-s-i-c | a29f4f5ac1805c4af74bafe205f5b7bfc1dafacb | [
"MIT"
] | 45 | 2018-10-01T18:51:16.000Z | 2018-12-06T23:42:26.000Z | src/test/java/com/github/se307/SongTest.java | declanvk/m-u-s-i-c | a29f4f5ac1805c4af74bafe205f5b7bfc1dafacb | [
"MIT"
] | 1 | 2018-10-01T18:37:53.000Z | 2018-10-01T18:37:53.000Z | 27.330645 | 65 | 0.61139 | 1,002,770 | package com.github.se307;
import static org.junit.Assert.*;
import org.junit.Test;
/**
* @author Maxence Weyrich
*
*/
public class SongTest {
@Test
public void testCreateNewSong() {
Song.SongBuilder sb = new Song.SongBuilder();
Song s = sb.setSongName("Dye")
.setArtistName("Tycho")
.setAlbumName("Awake")
.setSongLength(126)
.setGenreID(0)
.setSongYear(2012)
.setBPM(null)
.setNotes("This is the song used in all the tests")
.setURL(null)
.build();
long songKey = s.getId();
Song o = new Song(songKey);
assertTrue(s.getSongName().equals(o.getSongName()) &&
s.getArtistName().equals(o.getArtistName()) &&
s.getAlbumName().equals(o.getAlbumName()) &&
s.getSongLength().equals(o.getSongLength()) &&
s.getGenreId().equals(o.getGenreId()) &&
s.getSongYear().equals(o.getSongYear()) &&
s.getBpm() == o.getBpm() &&
s.getAdditionalNotes().equals(o.getAdditionalNotes()) &&
s.getSongUrl() == o.getSongUrl());
s.deleteSong();
}
@Test
public void testChangeSongFields() {
Song.SongBuilder sb = new Song.SongBuilder();
Song s1 = sb.setSongName("Dye")
.setArtistName("Tycho")
.setAlbumName("Awake")
.setSongLength(126)
.setGenreID(0)
.setSongYear(2012)
.setBPM(null)
.setNotes("This is the song used in all the tests")
.setURL(null)
.build();
s1.setSongName("Awake");
s1.setSongYear(2014);
s1.setAdditionalNotes(null);
Song other = new Song(s1.getId());
assertTrue(other.getSongName().equals("Awake") &&
other.getArtistName().equals("Tycho") &&
other.getAlbumName().equals("Awake") &&
other.getSongLength().equals(126) &&
other.getGenreId().equals(0) &&
other.getSongYear().equals(2014) &&
other.getBpm() == null &&
other.getAdditionalNotes() == null &&
other.getSongUrl() == null);
s1.deleteSong();
}
@Test
public void testChangeSongFieldsTwo() {
Song.SongBuilder sb = new Song.SongBuilder();
Song s1 = sb.setSongName("Dye")
.setArtistName("Tycho")
.setAlbumName("Awake")
.setSongLength(126)
.setGenreID(0)
.setSongYear(2012)
.setBPM(null)
.setNotes("This is the song used in all the tests")
.setURL(null)
.build();
s1.setSongName("Abrasive");
s1.setArtistName("Ratatat");
s1.setAlbumName("Magnifique");
s1.setSongLength(243);
s1.setGenreList(1);
s1.setSongYear(2015);
s1.setBpm(120);
s1.setAdditionalNotes("these have changed");
s1.setSongMusicKey(3);
s1.setSongMusicKeyMode(0);
s1.setLiked(true);
s1.setSongUrl("http://www.google.com");
Song other = new Song(s1.getId());
assertTrue(other.getSongName().equals("Abrasive") &&
other.getArtistName().equals("Ratatat") &&
other.getAlbumName().equals("Magnifique") &&
other.getSongLength().equals(243) &&
other.getGenreId().equals(1) &&
other.getSongYear().equals(2015) &&
other.getBpm().equals(120) &&
other.getAdditionalNotes().equals("these have changed") &&
other.getSongUrl().equals("http://www.google.com") &&
other.getSongKey().equals(3) &&
other.getSongKeyMode().equals(0) &&
other.getLiked() == true);
s1.deleteSong();
}
}
|
9243c48f40738699219a0be1568c2d6e45117b61 | 1,701 | java | Java | src/main/java/com/wuest/prefab/structures/config/enums/AdvancedHorseStableOptions.java | jtljac/MC-Prefab | 47f89c980b943e17573f1ea7034ff33cda62562f | [
"MIT"
] | null | null | null | src/main/java/com/wuest/prefab/structures/config/enums/AdvancedHorseStableOptions.java | jtljac/MC-Prefab | 47f89c980b943e17573f1ea7034ff33cda62562f | [
"MIT"
] | null | null | null | src/main/java/com/wuest/prefab/structures/config/enums/AdvancedHorseStableOptions.java | jtljac/MC-Prefab | 47f89c980b943e17573f1ea7034ff33cda62562f | [
"MIT"
] | null | null | null | 36.978261 | 86 | 0.439741 | 1,002,771 | package com.wuest.prefab.structures.config.enums;
import net.minecraft.core.Direction;
public class AdvancedHorseStableOptions extends BaseOption {
public static AdvancedHorseStableOptions Default = new AdvancedHorseStableOptions(
"item.prefab.advanced.horse.stable",
"assets/prefab/structures/advanced_horse_stable.zip",
"textures/gui/advanced_horse_stable_topdown.png",
Direction.SOUTH,
8,
17,
34,
1,
8,
0,
false,
false);
protected AdvancedHorseStableOptions(String translationString,
String assetLocation,
String pictureLocation,
Direction direction,
int height,
int width,
int length,
int offsetParallelToPlayer,
int offsetToLeftOfPlayer,
int heightOffset,
boolean hasBedColor,
boolean hasGlassColor) {
super(
translationString,
assetLocation,
pictureLocation,
direction,
height,
width,
length,
offsetParallelToPlayer,
offsetToLeftOfPlayer,
heightOffset,
hasBedColor,
hasGlassColor);
}
} |
9243c4f6d48b9d801b50d3e6b7248e0b4704d74a | 3,543 | java | Java | core/src/test/java/crm/hoprxi/core/domain/model/card/ValidityPeriodTest.java | guantemp/crm | f92a237f9bdd1c186262d8506a3182ed7531fe63 | [
"Apache-2.0"
] | null | null | null | core/src/test/java/crm/hoprxi/core/domain/model/card/ValidityPeriodTest.java | guantemp/crm | f92a237f9bdd1c186262d8506a3182ed7531fe63 | [
"Apache-2.0"
] | null | null | null | core/src/test/java/crm/hoprxi/core/domain/model/card/ValidityPeriodTest.java | guantemp/crm | f92a237f9bdd1c186262d8506a3182ed7531fe63 | [
"Apache-2.0"
] | null | null | null | 43.740741 | 115 | 0.725092 | 1,002,772 | /*
* Copyright (c) 2020. www.hoprxi.com All Rights Reserved.
*
* 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 crm.hoprxi.core.domain.model.card;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.time.LocalDate;
/***
* @author <a href="www.hoprxi.com/authors/guan xiangHuan">guan xiangHuang</a>
* @since JDK8.0
* @version 0.0.2 2020-06-13
*/
public class ValidityPeriodTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void test() {
ValidityPeriod permanent = ValidityPeriod.PERMANENCE;
Assert.assertTrue(permanent.isValidityPeriod());
ValidityPeriod permanent1 = permanent.broughtForwardExpiryDate(LocalDate.now().plusDays(2));
Assert.assertTrue(permanent1 == permanent);
permanent1 = permanent.postponeExpiryDate(LocalDate.now().plusDays(20));
Assert.assertTrue(permanent1 == permanent);
ValidityPeriod validityPeriod = new ValidityPeriod(LocalDate.now(), LocalDate.now());
Assert.assertTrue(validityPeriod.isValidityPeriod());
validityPeriod = new ValidityPeriod(LocalDate.now(), LocalDate.now().plusDays(30));
Assert.assertTrue(validityPeriod.isValidityPeriod());
validityPeriod = validityPeriod.postponeExpiryDate(LocalDate.now().plusDays(60));
Assert.assertTrue(validityPeriod.isValidityPeriod());
Assert.assertEquals(validityPeriod.expiryDate(), LocalDate.now().plusDays(60));
//do nothing
Assert.assertTrue(validityPeriod == validityPeriod.postponeExpiryDate(LocalDate.now().plusDays(50)));
validityPeriod = validityPeriod.broughtForwardExpiryDate(LocalDate.now().plusDays(45));
Assert.assertTrue(validityPeriod.isValidityPeriod());
Assert.assertEquals(validityPeriod.expiryDate(), LocalDate.now().plusDays(45));
//do nothing
Assert.assertTrue(validityPeriod == validityPeriod.broughtForwardExpiryDate(LocalDate.now().plusDays(50)));
validityPeriod = validityPeriod.postponeStartDate(LocalDate.now().plusDays(30));
Assert.assertFalse(validityPeriod.isValidityPeriod());
Assert.assertEquals(validityPeriod.startDate(), LocalDate.now().plusDays(30));
validityPeriod = validityPeriod.broughtForwardStartDate(LocalDate.now().plusDays(5));
Assert.assertFalse(validityPeriod.isValidityPeriod());
Assert.assertEquals(validityPeriod.startDate(), LocalDate.now().plusDays(5));
validityPeriod = ValidityPeriod.getInstance(LocalDate.of(2015, 3, 26), LocalDate.of(2015, 3, 26));
Assert.assertTrue(validityPeriod == ValidityPeriod.PERMANENCE);
ValidityPeriod threeYears = ValidityPeriod.threeYears();
System.out.println(threeYears.startDate());
System.out.println(threeYears.expiryDate());
thrown.expect(IllegalArgumentException.class);
new ValidityPeriod(LocalDate.now(), LocalDate.now().minusDays(1));
}
} |
9243c605852a345b1f7331ee34cb59f26703f7a2 | 1,506 | java | Java | smithy-diff/src/main/java/software/amazon/smithy/diff/DiffEvaluator.java | rschmitt/smithy | e480e6f856c21e8837b139b3e4eae96fbcc0b605 | [
"Apache-2.0"
] | 903 | 2019-06-18T21:07:54.000Z | 2022-03-28T07:13:30.000Z | smithy-diff/src/main/java/software/amazon/smithy/diff/DiffEvaluator.java | rschmitt/smithy | e480e6f856c21e8837b139b3e4eae96fbcc0b605 | [
"Apache-2.0"
] | 277 | 2019-06-19T17:10:48.000Z | 2022-03-28T20:19:39.000Z | smithy-diff/src/main/java/software/amazon/smithy/diff/DiffEvaluator.java | rschmitt/smithy | e480e6f856c21e8837b139b3e4eae96fbcc0b605 | [
"Apache-2.0"
] | 90 | 2019-06-19T20:08:34.000Z | 2022-03-21T23:04:22.000Z | 34.227273 | 76 | 0.740372 | 1,002,773 | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.smithy.diff;
import java.util.List;
import software.amazon.smithy.model.validation.ValidationEvent;
/**
* Interface used to evaluate two models and their normalized
* differences and return {@link ValidationEvent}s that are relative to
* the new model.
*
* <p>For example, a ValidationEvent is emitted when an operation is
* removed from a service or resource.
*
* <p>Implementations of this interface are found using Java SPI and
* automatically applied to the detected differences when creating a
* {@link ModelDiff}.
*/
@FunctionalInterface
public interface DiffEvaluator {
/**
* Returns validation events given two models and the detected
* differences between them.
*
* @param differences Detected differences.
* @return Returns validation events that are relative to the new model.
*/
List<ValidationEvent> evaluate(Differences differences);
}
|
9243c797a4785260c6ce6c752f7174beed5bab71 | 851 | java | Java | src/main/java/com/keildraco/config/interfaces/IStateParser.java | jriwanek/simple-java-config | e9ae09da84c879067d41a65d0a5646d22a6f234e | [
"BSD-2-Clause"
] | 1 | 2018-08-03T06:53:34.000Z | 2018-08-03T06:53:34.000Z | src/main/java/com/keildraco/config/interfaces/IStateParser.java | jriwanek/simple-java-config | e9ae09da84c879067d41a65d0a5646d22a6f234e | [
"BSD-2-Clause"
] | null | null | null | src/main/java/com/keildraco/config/interfaces/IStateParser.java | jriwanek/simple-java-config | e9ae09da84c879067d41a65d0a5646d22a6f234e | [
"BSD-2-Clause"
] | 1 | 2018-07-30T23:12:59.000Z | 2018-07-30T23:12:59.000Z | 13.725806 | 55 | 0.596945 | 1,002,774 | package com.keildraco.config.interfaces;
import com.keildraco.config.factory.TypeFactory;
import com.keildraco.config.tokenizer.Tokenizer;
/**
*
* @author Daniel Hazelton
*
*/
public interface IStateParser {
/**
*
* @param factoryIn
*/
void setFactory(TypeFactory factoryIn);
/**
*
* @return
*/
TypeFactory getFactory();
/**
*
* @param tokenizer
* @return
*/
ParserInternalTypeBase getState(Tokenizer tokenizer);
/**
*
* @param parentIn
*/
void setParent(ParserInternalTypeBase parentIn);
/**
*
* @return
*/
ParserInternalTypeBase getParent();
/**
*
* @param nameIn
*/
void setName(String nameIn);
/**
*
* @return
*/
String getName();
/**
*
* @param factory
*/
void registerTransitions(TypeFactory factory);
}
|
9243c8b8caaefc0672f2bed55eb6ab1e11da7fba | 7,911 | java | Java | app/src/main/java/com/function/karaoke/interaction/utils/Billing.java | natanginsberg/shira | ca1d39d1130a288cb727d0ff723df3be8eec7e71 | [
"MIT"
] | null | null | null | app/src/main/java/com/function/karaoke/interaction/utils/Billing.java | natanginsberg/shira | ca1d39d1130a288cb727d0ff723df3be8eec7e71 | [
"MIT"
] | null | null | null | app/src/main/java/com/function/karaoke/interaction/utils/Billing.java | natanginsberg/shira | ca1d39d1130a288cb727d0ff723df3be8eec7e71 | [
"MIT"
] | null | null | null | 41.418848 | 144 | 0.66515 | 1,002,775 | package com.function.karaoke.interaction.utils;
import android.app.Activity;
import android.widget.Toast;
import androidx.annotation.NonNull;
import com.android.billingclient.api.AcknowledgePurchaseResponseListener;
import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.BillingClientStateListener;
import com.android.billingclient.api.BillingFlowParams;
import com.android.billingclient.api.BillingResult;
import com.android.billingclient.api.ConsumeParams;
import com.android.billingclient.api.ConsumeResponseListener;
import com.android.billingclient.api.Purchase;
import com.android.billingclient.api.PurchasesUpdatedListener;
import com.android.billingclient.api.SkuDetails;
import com.android.billingclient.api.SkuDetailsParams;
import java.util.ArrayList;
import java.util.List;
public class Billing {
private final BillingClient billingClient;
private final Activity activity;
private final boolean displayProducts;
// private final ConsumeResponseListener consumeResponseListener;
private AcknowledgePurchaseResponseListener acknowledgePurchaseResponseListener = new AcknowledgePurchaseResponseListener() {
@Override
public void onAcknowledgePurchaseResponse(@NonNull BillingResult billingResult) {
}
};
private int counter = 0;
private List<SkuDetails> skuDetailsList;
private ConsumeResponseListener consumerResponseListener;
public Billing(Activity activity, PurchasesUpdatedListener purchasesUpdatedListener, boolean displayProducts, ReadyListener readyListener) {
this.activity = activity;
// this.consumeResponseListener = consumeResponseListener;
this.displayProducts = displayProducts;
billingClient = BillingClient.newBuilder(activity)
.setListener(purchasesUpdatedListener)
.enablePendingPurchases()
.build();
connect(readyListener);
}
private void connect(ReadyListener readyListener) {
billingClient.startConnection(new BillingClientStateListener() {
@Override
public void onBillingSetupFinished(BillingResult billingResult) {
if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
// The BillingClient is ready. You can query purchases here.
getAllInAppProducts();
if (displayProducts)
getProducts();
else
acknowledgePreviousOrders();
readyListener.ready();
}
}
@Override
public void onBillingServiceDisconnected() {
counter++;
if (counter < 1000) {
connect(readyListener);
} else {
showToastUnableToConnect();
}
// Try to restart the connection on the next request to
// Google Play by calling the startConnection() method.
}
});
}
public void subscribeListener(AcknowledgePurchaseResponseListener acknowledgePurchaseResponseListener) {
this.acknowledgePurchaseResponseListener = acknowledgePurchaseResponseListener;
}
public void subscribeInAppListener(ConsumeResponseListener consumeResponseListener) {
this.consumerResponseListener = consumeResponseListener;
}
public void getAllInAppProducts() {
List<String> skuList = new ArrayList<>();
skuList.add("daily_buy");
skuList.add("monthly_buy");
SkuDetailsParams.Builder params = SkuDetailsParams.newBuilder();
params.setSkusList(skuList).setType(BillingClient.SkuType.INAPP);
billingClient.querySkuDetailsAsync(params.build(),
this::onSkuDetailsResponse);
}
public void startInAppFlow(int subscriptionNumber) {
BillingFlowParams billingFlowParams = BillingFlowParams.newBuilder()
.setSkuDetails(skuDetailsList.get(subscriptionNumber))
.build();
int responseCode = billingClient.launchBillingFlow(activity, billingFlowParams).getResponseCode();
}
private void acknowledgePreviousOrders() {
Purchase.PurchasesResult allPurchases = billingClient.queryPurchases(BillingClient.SkuType.INAPP);
if (allPurchases.getPurchasesList() != null)
for (Purchase purchase : allPurchases.getPurchasesList()) {
if (purchase.getPurchaseState() == Purchase.PurchaseState.PURCHASED)
handlePurchase(purchase);
}
}
public boolean isSubscribed() {
Purchase.PurchasesResult allPurchases = billingClient.queryPurchases(BillingClient.SkuType.SUBS);
if (allPurchases.getPurchasesList() != null)
for (Purchase purchase : allPurchases.getPurchasesList()) {
if (purchase.getPurchaseState() == Purchase.PurchaseState.PURCHASED)
return true;
}
return false;
}
private void showToastUnableToConnect() {
Toast.makeText(activity.getBaseContext(), "Unable to connect", Toast.LENGTH_SHORT).show();
}
private void getProducts() {
List<String> skuList = new ArrayList<>();
skuList.add("yearly_1");
skuList.add("monthly_1");
SkuDetailsParams.Builder params = SkuDetailsParams.newBuilder();
params.setSkusList(skuList).setType(BillingClient.SkuType.SUBS);
billingClient.querySkuDetailsAsync(params.build(),
this::onSkuDetailsResponse);
}
public void startFlow(int subscriptionNumber) {
BillingFlowParams billingFlowParams = BillingFlowParams.newBuilder()
.setSkuDetails(skuDetailsList.get(subscriptionNumber))
.build();
int responseCode = billingClient.launchBillingFlow(activity, billingFlowParams).getResponseCode();
}
public void handlePurchase(Purchase purchase) {
// Purchase retrieved from BillingClient#queryPurchases or your PurchasesUpdatedListener.
// Verify the purchase.
// Ensure entitlement was not already granted for this purchaseToken.
// Grant entitlement to the user.
// if (!purchase.isAcknowledged()) {
// AcknowledgePurchaseParams acknowledgePurchaseParams =
// AcknowledgePurchaseParams.newBuilder()
// .setPurchaseToken(purchase.getPurchaseToken())
// .build();
// billingClient.acknowledgePurchase(acknowledgePurchaseParams, acknowledgePurchaseResponseListener);
// }
if (!purchase.isAcknowledged()) {
ConsumeParams consumeParams =
ConsumeParams.newBuilder()
.setPurchaseToken(purchase.getPurchaseToken())
.build();
// ConsumeResponseListener listener = new ConsumeResponseListener() {
// @Override
// public void onConsumeResponse(BillingResult billingResult, String purchaseToken) {
// if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
// // Handle the success of the consume operation.
// }
// }
// };
billingClient.consumeAsync(consumeParams, consumerResponseListener);
}
}
private void onSkuDetailsResponse(BillingResult billingResult, List<SkuDetails> skuDetailsList) {
if (skuDetailsList.size() != 0) {
this.skuDetailsList = skuDetailsList;
// startFlow(skuDetailsList);
} else {
Toast.makeText(activity.getBaseContext(), "No items for sale at the moment", Toast.LENGTH_LONG).show();
}
}
public interface ReadyListener {
void ready();
}
}
|
9243c90bcf7f159cb7b0afab87f97817ab6ca017 | 1,310 | java | Java | kendzi3d-buildings/src/main/java/kendzi/kendzi3d/buildings/builder/dto/TextureQuadIndex.java | filedos9ig1d/kendzi0 | 6722da8fca52d5fbc1f1a8e20772d74f6f4b7641 | [
"BSD-3-Clause"
] | 45 | 2015-04-05T07:24:05.000Z | 2022-02-17T17:29:54.000Z | kendzi3d-buildings/src/main/java/kendzi/kendzi3d/buildings/builder/dto/TextureQuadIndex.java | filedos9ig1d/kendzi0 | 6722da8fca52d5fbc1f1a8e20772d74f6f4b7641 | [
"BSD-3-Clause"
] | 56 | 2015-01-18T17:24:19.000Z | 2022-03-09T22:21:52.000Z | kendzi3d-buildings/src/main/java/kendzi/kendzi3d/buildings/builder/dto/TextureQuadIndex.java | filedos9ig1d/kendzi0 | 6722da8fca52d5fbc1f1a8e20772d74f6f4b7641 | [
"BSD-3-Clause"
] | 15 | 2015-03-09T03:35:44.000Z | 2022-02-15T23:25:05.000Z | 15.783133 | 68 | 0.469466 | 1,002,776 | /*
* This software is provided "AS IS" without a warranty of any kind.
* You use it on your own risk and responsibility!!!
*
* This file is shared under BSD v3 license.
* See readme.txt and BSD3 file for details.
*
*/
package kendzi.kendzi3d.buildings.builder.dto;
/**
* Texture indexes for quad.
*
* @author kendzi
*
*/
public class TextureQuadIndex {
private int ld;
private int rd;
private int rt;
private int lt;
/**
* @return the ld
*/
public int getLd() {
return ld;
}
/**
* @param ld
* the ld to set
*/
public void setLd(int ld) {
this.ld = ld;
}
/**
* @return the rd
*/
public int getRd() {
return rd;
}
/**
* @param rd
* the rd to set
*/
public void setRd(int rd) {
this.rd = rd;
}
/**
* @return the rt
*/
public int getRt() {
return rt;
}
/**
* @param rt
* the rt to set
*/
public void setRt(int rt) {
this.rt = rt;
}
/**
* @return the lt
*/
public int getLt() {
return lt;
}
/**
* @param lt
* the lt to set
*/
public void setLt(int lt) {
this.lt = lt;
}
} |
9243c92af866a23e828c998934b55cbf414d36bf | 5,570 | java | Java | app/src/main/java/eni/baptistedixneuf/fr/lokacarproject/fragment/contrat/ContractFragment.java | LokaCarProject/AndroidAppli | 5f970988f8914f8bb0d988decac80afe2e868aed | [
"Apache-2.0"
] | null | null | null | app/src/main/java/eni/baptistedixneuf/fr/lokacarproject/fragment/contrat/ContractFragment.java | LokaCarProject/AndroidAppli | 5f970988f8914f8bb0d988decac80afe2e868aed | [
"Apache-2.0"
] | null | null | null | app/src/main/java/eni/baptistedixneuf/fr/lokacarproject/fragment/contrat/ContractFragment.java | LokaCarProject/AndroidAppli | 5f970988f8914f8bb0d988decac80afe2e868aed | [
"Apache-2.0"
] | null | null | null | 35.477707 | 109 | 0.686715 | 1,002,777 | package eni.baptistedixneuf.fr.lokacarproject.fragment.contrat;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import java.util.Date;
import eni.baptistedixneuf.fr.lokacarproject.R;
import eni.baptistedixneuf.fr.lokacarproject.adaptater.contract.ContratAdaptater;
import eni.baptistedixneuf.fr.lokacarproject.adaptater.contract.ContratContent;
import eni.baptistedixneuf.fr.lokacarproject.bo.Categorie;
import eni.baptistedixneuf.fr.lokacarproject.bo.Client;
import eni.baptistedixneuf.fr.lokacarproject.bo.Contrat;
import eni.baptistedixneuf.fr.lokacarproject.bo.Voiture;
import eni.baptistedixneuf.fr.lokacarproject.dao.ContratDao;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link ContractFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link ContractFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class ContractFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
private ListView listeContrats;
private Button buttonAjoutContrat;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment ContractFragment.
*/
// TODO: Rename and change types and number of parameters
public static ContractFragment newInstance(String param1, String param2) {
ContractFragment fragment = new ContractFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
fragment.setArguments(args);
return fragment;
}
public ContractFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_contract, container, false);
listeContrats = (ListView) view.findViewById(R.id.fragement_contrats_listView);
ContratDao dao = new ContratDao(getActivity());
ContratContent.ITEMS = dao.getAll();
ContratAdaptater adapter = new ContratAdaptater(getActivity(), ContratContent.ITEMS);
listeContrats.setAdapter(adapter);
listeContrats.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
DetailContratFragment fragment = new DetailContratFragment();
Bundle bundle = new Bundle();
bundle.putSerializable(DetailContratFragment.ARG_PARAM1, ContratContent.ITEMS.get(position));
fragment.setArguments(bundle);
getFragmentManager().beginTransaction()
.addToBackStack(null)
.replace(R.id.container, fragment)
.commit();
}
});
buttonAjoutContrat = (Button) view.findViewById(R.id.fragement_contrats_button);
buttonAjoutContrat.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.addToBackStack(null);
ft.replace(R.id.container, new AjoutContratFragment(), "NewFragmentTag");
ft.commit();
}
});
// Inflate the layout for this fragment
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
}
|
9243cbc6924493ebbc12d7b2e34a865c0bdbc69b | 1,938 | java | Java | Service/SourceCode/DormitoryManagement/src/main/java/com/wsm/DormitoryManagement/daoImpl/TeacherDaoImpl.java | wsmeng/DormitoryManager.wsmeng.io | e717b4db6a6ee9489bf69d4ccc4fa323df0d5e0d | [
"Apache-2.0"
] | null | null | null | Service/SourceCode/DormitoryManagement/src/main/java/com/wsm/DormitoryManagement/daoImpl/TeacherDaoImpl.java | wsmeng/DormitoryManager.wsmeng.io | e717b4db6a6ee9489bf69d4ccc4fa323df0d5e0d | [
"Apache-2.0"
] | 4 | 2020-01-07T02:01:25.000Z | 2020-01-07T02:01:26.000Z | Service/SourceCode/DormitoryManagement/src/main/java/com/wsm/DormitoryManagement/daoImpl/TeacherDaoImpl.java | wsmeng/DormitoryManager.wsmeng.io | e717b4db6a6ee9489bf69d4ccc4fa323df0d5e0d | [
"Apache-2.0"
] | null | null | null | 30.28125 | 95 | 0.733746 | 1,002,778 | package com.wsm.DormitoryManagement.daoImpl;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import com.wsm.DormitoryManagement.RowMapper.TeacherBeanRowMapper;
import com.wsm.DormitoryManagement.bean.TeacherBean;
import com.wsm.DormitoryManagement.dao.TeacherDao;
public class TeacherDaoImpl extends JdbcDaoSupport implements TeacherDao {
public int insert(final TeacherBean bean) {
String sql = "insert into teacher(teacher_seq.nextval, ?, ?, ?, ?, ?)";
return getJdbcTemplate().update(sql, new PreparedStatementSetter(){
public void setValues(PreparedStatement ps) throws SQLException {
ps.setString(1, bean.getTeacherName());
ps.setString(2, bean.getTeacherPassword());
ps.setString(3, bean.getTeacherNo());
ps.setInt(4, bean.getTeacherSex());
ps.setString(5, bean.getTeacherTel());
ps.execute();
}
});
}
public int delete(final TeacherBean bean) {
String sql = "delete from teacher where teacher_id = ?";
return getJdbcTemplate().update(sql, new PreparedStatementSetter(){
public void setValues(PreparedStatement ps) throws SQLException {
ps.setInt(1, bean.getTeacherID());
ps.execute();
}
});
}
public int change(final TeacherBean bean) {
String sql = "update teacher set teacher_password = ?, teacher_tel = ? where teacher_id = ?";
return getJdbcTemplate().update(sql, new PreparedStatementSetter(){
public void setValues(PreparedStatement ps) throws SQLException {
ps.setString(1, bean.getTeacherPassword());
ps.setString(2, bean.getTeacherTel());
ps.setInt(3, bean.getTeacherID());
ps.execute();
}
});
}
public List<TeacherBean> findAll() {
String sql = "select * from teacher";
return getJdbcTemplate().query(sql, new TeacherBeanRowMapper());
}
}
|
Subsets and Splits