hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
---|---|---|---|---|---|
80d7aeb23cced035e18ff2aa31a7f540a5a315de | 309 | package com.newMedia.service;
import com.newMedia.dto.BuyInfo;
public interface BuyPService {
// 购买商品
BuyInfo buyProduct(int productId, Long buyerPhone, String buyerOpenid, String buyerMessage, int receiveMethod, int payMethod);
// 给商品添加评价 TODO
int addComment();
// 获取当前已购买的商品
}
| 20.6 | 130 | 0.718447 |
dba09959131c3880c75397c867b1bdeb3c1df835 | 1,294 | package com.reading.start.presentation.mvp.holders;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class ChildInformationViewHolder {
private View mActionBar;
private RecyclerView mRecyclerView;
private ImageView mPhoto;
private TextView mName;
private TextView mChildInfo;
private View mEdit;
public ChildInformationViewHolder(View actionBar, RecyclerView recyclerView, ImageView photo,
TextView name, TextView childInfo, View edit) {
mActionBar = actionBar;
mRecyclerView = recyclerView;
mPhoto = photo;
mName = name;
mChildInfo = childInfo;
mEdit = edit;
}
public View getActionBar() {
return mActionBar;
}
public RecyclerView getRecyclerView() {
return mRecyclerView;
}
public void setRecyclerView(RecyclerView recyclerView) {
mRecyclerView = recyclerView;
}
public ImageView getPhoto() {
return mPhoto;
}
public TextView getName() {
return mName;
}
public TextView getChildInfo() {
return mChildInfo;
}
public View getEdit() {
return mEdit;
}
}
| 21.566667 | 97 | 0.653787 |
e13d4941d7dfcdd77850702192c788c97442e700 | 4,126 | package com.qsd.bookstore.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.qsd.bookstore.po.Admin;
import com.qsd.bookstore.po.Category;
import com.qsd.bookstore.po.Commodity;
import com.qsd.bookstore.po.Global;
import com.qsd.bookstore.service.AdminService;
import com.qsd.bookstore.service.CategoryService;
import com.qsd.bookstore.service.CommodityService;
import com.qsd.bookstore.service.ResourceService;
import com.qsd.bookstore.vo.BaseVo;
import cn.hutool.crypto.digest.DigestUtil;
/**
* @Description
* @Author Esion
* @Data 2020年6月7日
*/
@RestController
@RequestMapping("admin/opera")
public class AdminOperaController {
@Autowired
private Global global;
@Autowired
private AdminService adminService;
@Autowired
private CommodityService commodityService;
@Autowired
private ResourceService resourceService;
@Autowired
private CategoryService categoryService;
@RequestMapping("login")
public ModelAndView login(Admin admin, HttpServletRequest request) {
ModelAndView modelAndView = new ModelAndView();
//管理员验证
//密码加密
String password = admin.getPassword();
password = DigestUtil.md5Hex(password);
admin.setPassword(password);
boolean result = adminService.login(admin);
if (result) {
HttpSession session = request.getSession();
session.setAttribute("admin", admin);
modelAndView.setViewName("redirect:/admin/index");
}else {
modelAndView.setViewName("redirect:/login.html");
}
return modelAndView;
}
@GetMapping("exit")
public BaseVo exit(HttpServletRequest request) {
HttpSession session = request.getSession();
session.removeAttribute("admin");
return new BaseVo(200, "管理员退出成功");
}
@GetMapping("setNotice")
public BaseVo setNotice(String notice) {
global.setNotice(notice);
return new BaseVo(200, "设置公告成功");
}
@RequestMapping("setIndexImage")
public BaseVo setIndexImage(@RequestParam("images") MultipartFile images) {
String filename = images.getOriginalFilename();
System.err.println(filename);
return new BaseVo(200, "成功");
}
@GetMapping("enableSell")
public BaseVo enableSell(int commodityId, boolean status) {
Integer result = commodityService.setSellStatus(commodityId, status);
if (result == -1) {
return new BaseVo(404, "商品不存在");
}else if (result == 0) {
return new BaseVo(400, "操作失败");
}
return new BaseVo(200, "操作成功");
}
@PostMapping("newCommodityWithfeild")
public BaseVo newCommodityWithfeild(Commodity commodity) {
commodity.setStatus(true);
int result = commodityService.newCommodity(commodity);
if (result > 0) {
return new BaseVo(200, "success");
}else {
return new BaseVo(400, "error");
}
}
@RequestMapping("newCommodityWithImage")
public BaseVo newCommodityWithImage(@RequestParam("image") MultipartFile image) {
int result = -1;
result = resourceService.uploadCommodityImage(image);
if (result > 0) {
return new BaseVo(200, "success");
}else {
return new BaseVo(400, "error");
}
}
@RequestMapping("newCommodityWithFile")
public BaseVo newCommodityWithFile(@RequestParam("file") MultipartFile file) {
int result = -1;
result = resourceService.uploadCommodityFile(file);
if (result > 0) {
return new BaseVo(200, "success");
}else {
return new BaseVo(400, "error");
}
}
@GetMapping("newCategory")
public BaseVo newCategory(Category category) {
categoryService.addCategory(category);
return new BaseVo(200, "success");
}
@GetMapping("deleteCategory")
public BaseVo deleteCategory(String name) {
categoryService.deleteCategory(name);
return new BaseVo(200, "success");
}
}
| 28.853147 | 82 | 0.75618 |
fda1db0388be6068efac69c12ff475d7850033da | 7,579 | /**
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
*
* The Apereo Foundation licenses this file to you under the Educational
* Community 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://opensource.org/licenses/ecl2.txt
*
* 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.opencastproject.mediapackage;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.opencastproject.mediapackage.MediaPackageElement.Type;
import org.opencastproject.mediapackage.identifier.IdImpl;
import org.opencastproject.mediapackage.track.TrackImpl;
import org.opencastproject.mediapackage.track.VideoStreamImpl;
import org.opencastproject.util.Checksum;
import org.opencastproject.util.ChecksumType;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
public class MediaPackageJaxbSerializationTest {
@Test
public void testManifestSerialization() throws Exception {
MediaPackageBuilderFactory builderFactory = MediaPackageBuilderFactory.newInstance();
MediaPackageBuilder mediaPackageBuilder = builderFactory.newMediaPackageBuilder();
URL rootUrl = getClass().getResource("/");
mediaPackageBuilder.setSerializer(new DefaultMediaPackageSerializerImpl(rootUrl));
// Load the simple media package
MediaPackage mediaPackage = null;
InputStream is = null;
try {
is = getClass().getResourceAsStream("/manifest-simple.xml");
mediaPackage = mediaPackageBuilder.loadFromXml(is);
assertEquals(0, mediaPackage.getTracks().length);
assertEquals(1, mediaPackage.getCatalogs().length);
assertEquals(0, mediaPackage.getAttachments().length);
assertEquals("dublincore/episode", mediaPackage.getCatalogs()[0].getFlavor().toString());
} finally {
IOUtils.closeQuietly(is);
}
}
@Test
public void testJaxbSerialization() throws Exception {
// Build a media package
MediaPackageElementBuilder elementBuilder = MediaPackageElementBuilderFactory.newInstance().newElementBuilder();
MediaPackage mp = new MediaPackageImpl(new IdImpl("123"));
Attachment attachment = (Attachment) elementBuilder.elementFromURI(
new URI("http://opencastproject.org/index.html"), Type.Attachment, Attachment.FLAVOR);
attachment.setChecksum(Checksum.create(ChecksumType.DEFAULT_TYPE, "123456abcd"));
mp.add(attachment);
Catalog cat1 = (Catalog) elementBuilder.elementFromURI(new URI("http://opencastproject.org/index.html"),
Catalog.TYPE, MediaPackageElements.EPISODE);
cat1.setChecksum(Checksum.create(ChecksumType.DEFAULT_TYPE, "7891011abcd"));
mp.add(cat1);
Catalog cat2 = (Catalog) elementBuilder.elementFromURI(new URI("http://opencastproject.org/index.html"),
Catalog.TYPE, MediaPackageElements.EPISODE);
cat2.setChecksum(Checksum.create(ChecksumType.DEFAULT_TYPE, "7891011abcd"));
mp.addDerived(cat2, cat1);
TrackImpl track = (TrackImpl) elementBuilder.elementFromURI(new URI("http://opencastproject.org/video.mpg"),
Track.TYPE, MediaPackageElements.PRESENTER_SOURCE);
track.addStream(new VideoStreamImpl("video-stream-1"));
track.addStream(new VideoStreamImpl("video-stream-2"));
mp.add(track);
// Serialize the media package
String xml = MediaPackageParser.getAsXml(mp);
assertNotNull(xml);
// Serialize the media package as JSON
String json = MediaPackageParser.getAsJSON(mp);
assertNotNull(json);
// Deserialize the media package
MediaPackage deserialized = MediaPackageBuilderFactory.newInstance().newMediaPackageBuilder()
.loadFromXml(IOUtils.toInputStream(xml, "UTF-8"));
// Ensure that the deserialized mediapackage is correct
assertEquals(2, deserialized.getCatalogs().length);
assertEquals(1, deserialized.getAttachments().length);
assertEquals(1, deserialized.getTracks().length);
assertEquals(2, deserialized.getTracks()[0].getStreams().length);
assertEquals(1, deserialized.getCatalogs(new MediaPackageReferenceImpl(cat1)).length);
}
/**
* JAXB produces xml with an xsi:type="" attribute on the root element. Be sure that we can unmarshall objects without
* that attribute.
*/
@Test
public void testJaxbWithoutXsi() throws Exception {
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><mediapackage start=\"0\" id=\"123\" duration=\"0\" xmlns=\"http://mediapackage.opencastproject.org\"><metadata><catalog type=\"dublincore/episode\"><mimetype>text/xml</mimetype><tags/><checksum type=\"md5\">7891011abcd</checksum><url>http://opencastproject.org/index.html</url></catalog></metadata><attachments><attachment id=\"attachment-1\"><tags/><checksum type=\"md5\">123456abcd</checksum><url>http://opencastproject.org/index.html</url></attachment></attachments></mediapackage>";
MediaPackage deserialized = MediaPackageBuilderFactory.newInstance().newMediaPackageBuilder()
.loadFromXml(IOUtils.toInputStream(xml, "UTF-8"));
assertEquals(2, deserialized.getElements().length);
String elementXml = "<track xmlns=\"http://mediapackage.opencastproject.org\" id=\"track-1\" type=\"presentation/source\"><mimetype>video/mpeg</mimetype>"
+ "<url>http://localhost:8080/workflow/samples/screen.mpg</url></track>";
MediaPackageElement element = MediaPackageElementParser.getFromXml(elementXml);
assertEquals("track-1", element.getIdentifier());
assertEquals(MediaPackageElements.PRESENTATION_SOURCE, element.getFlavor());
assertEquals("http://localhost:8080/workflow/samples/screen.mpg", element.getURI().toString());
}
@Test
public void testJaxbUnmarshallingFromFile() throws Exception {
InputStream in = null;
try {
in = this.getClass().getResourceAsStream("/manifest.xml");
MediaPackage mp = MediaPackageBuilderFactory.newInstance().newMediaPackageBuilder().loadFromXml(in);
assertEquals(2, mp.getTracks().length);
assertTrue(mp.getTracks()[0].hasVideo());
assertTrue(!mp.getTracks()[0].hasAudio());
assertTrue(mp.getTracks()[1].hasAudio());
assertTrue(!mp.getTracks()[1].hasVideo());
assertEquals(3, mp.getCatalogs().length);
assertEquals(2, mp.getAttachments().length);
assertEquals(1, mp.getPublications().length);
} finally {
IOUtils.closeQuietly(in);
}
}
@Test
public void testUmlaut() throws Exception {
String title = "Ökologie";
MediaPackageBuilder builder = MediaPackageBuilderFactory.newInstance().newMediaPackageBuilder();
MediaPackage original = builder.createNew();
original.setTitle(title);
original.setSeriesTitle("s1");
String xml = MediaPackageParser.getAsXml(original);
assertTrue(xml.indexOf(title) > 0);
MediaPackage unmarshalled = builder.loadFromXml(xml);
assertEquals(title, unmarshalled.getTitle());
assertEquals("s1", unmarshalled.getSeriesTitle());
}
}
| 45.933333 | 566 | 0.740599 |
c1627e60c9c09559310a72aac1984740feeb8944 | 2,705 | package fr.insee.arc.utils.files;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.file.CopyOption;
import java.nio.file.Files;
import java.nio.file.Path;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import fr.insee.arc.utils.utils.LoggerHelper;
public class FileUtils {
public static final String EXTENSION_ZIP = ".zip";
public static final String EXTENSION_CSV = ".csv";
private static final Logger LOGGER = LogManager.getLogger(FileUtils.class);
public static final char SEMICOLON = ';';
private FileUtils() {
throw new IllegalStateException("Utility class");
}
public static boolean isCompletelyWritten(File file) {
RandomAccessFile stream = null;
try {
stream = new RandomAccessFile(file, "rw");
return true;
} catch (Exception e) {
LoggerHelper.warnAsComment(LOGGER, e, "Le fichier", file.getName(), "est en cours d'écriture.");
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {}
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// Silent catch
}
return false;
}
/**
* Copie le fichier de chemin {@code cheminFichierSource} dans le fichier de
* chemin {@code cheminFichierCible}. Le chemin du fichier cible est créé
* dynamiquement.
*
* @param cheminFichierSource
* @param cheminFichierCible
* @param options
* @throws IOException
*/
public static void copy(Path cheminFichierSource, Path cheminFichierCible, CopyOption... options)
throws IOException {
mkDirs(cheminFichierCible.getParent());
Files.copy(cheminFichierSource, cheminFichierCible, options);
}
/**
* Déplace le fichier de chemin {@code cheminFichierSource} dans le fichier de
* chemin {@code cheminFichierCible}. Le chemin du fichier cible est créé
* dynamiquement.
*
* @param cheminFichierSource
* @param cheminFichierCible
* @param options
* @throws IOException
*/
public static void move(Path cheminFichierSource, Path cheminFichierCible, CopyOption... options)
throws IOException {
mkDirs(cheminFichierCible.getParent());
Files.move(cheminFichierSource, cheminFichierCible, options);
}
/**
* Crée récursivement l'arborescence de répertoires {@code aPath}.
*
* @param aPath
* @throws IOException
*/
public static void mkDirs(Path aPath) throws IOException {
if (!aPath.getParent().toFile().exists()) {
mkDirs(aPath.getParent());
}
if (!aPath.toFile().exists()) {
Files.createDirectory(aPath);
}
}
}
| 28.177083 | 108 | 0.680591 |
9e20747146e49af8cb280fa313b6292b7cfa6929 | 2,408 | package com.spinyowl.spinygui.core.system.event.listener;
import static com.spinyowl.spinygui.core.node.NodeBuilder.frame;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.spinyowl.spinygui.core.event.WindowIconifyEvent;
import com.spinyowl.spinygui.core.event.processor.EventProcessor;
import com.spinyowl.spinygui.core.node.Frame;
import com.spinyowl.spinygui.core.system.event.SystemWindowIconifyEvent;
import com.spinyowl.spinygui.core.time.TimeService;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
class SystemWindowIconifyEventListenerTest {
@Mock private EventProcessor eventProcessor;
@Mock private TimeService timeService;
private SystemEventListener<SystemWindowIconifyEvent> listener;
@BeforeEach
void setUp() {
listener =
SystemWindowIconifyEventListener.builder()
.eventProcessor(eventProcessor)
.timeService(timeService)
.build();
}
@Test
void process_generatesEvent() {
// Arrange
var frame = frame();
var timestamp = 1D;
when(timeService.getCurrentTime()).thenReturn(timestamp);
var sourceEvent = createEvent(frame);
var expectedEvent =
WindowIconifyEvent.builder()
.source(frame)
.target(frame)
.timestamp(timestamp)
.iconified(true)
.build();
doNothing().when(eventProcessor).push(expectedEvent);
// Act
listener.process(sourceEvent, frame);
// Verify
verify(timeService).getCurrentTime();
verify(eventProcessor).push(expectedEvent);
}
@Test
void process_throwsNPE_ifFrameIsNull() {
SystemWindowIconifyEvent event = createEvent(frame());
Assertions.assertThrows(NullPointerException.class, () -> listener.process(event, null));
}
@Test
void process_throwsNPE_ifEventIsNull() {
Frame frame = frame();
Assertions.assertThrows(NullPointerException.class, () -> listener.process(null, frame));
}
private SystemWindowIconifyEvent createEvent(Frame frame) {
return SystemWindowIconifyEvent.builder().frame(frame).iconified(true).build();
}
}
| 31.272727 | 93 | 0.739618 |
46f3a3d1fbe008a6d900c80e358f45f21e8142d8 | 3,737 | package club.imemory.app.http;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import club.imemory.app.listener.HttpCallbackListener;
import okhttp3.Authenticator;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.Route;
/**
* @Author: 张杭
* @Date: 2017/3/23 18:41
*/
public class HttpManager {
//OkHttpClient为重量级的
private static OkHttpClient client = new OkHttpClient();
/**
* 使用HttpURLConnection的GET方式发送HTTP请求
*/
public static void sendHttpRequest(final String address, final HttpCallbackListener listener) {
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
try {
URL url = new URL(address);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
connection.setDoInput(true);
connection.setDoOutput(true);
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
if (listener != null) {
listener.onFinish(response.toString());
}
} catch (Exception e) {
if (listener != null) {
listener.onError(e);
}
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}).start();
}
/**
* 使用OKHttp发送HTTP请求,获取服务器数据(默认get方式)
*/
public static void sendOKHttpRequest(String address, Callback callback) {
Request request = new Request.Builder()
.url(address)
.build();
client.newCall(request).enqueue(callback);
}
/**
* 向服务器提交数据
*/
public static void submitOKHttp(String address, RequestBody requestBody, Callback callback) {
Request request = new Request.Builder()
.url(address)
.post(requestBody)
.build();
client.newCall(request).enqueue(callback);
}
/**
* 使用OKHttp发送HTTP请求,获取服务器数据(默认get方式)
* 没有进行调
*/
public static String sendOKHttpRequest(String address) {
Request request = new Request.Builder()
.url(address)
.build();
try {
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 使用OKHttp发送HTTP请求,获取服务器数据(默认get方式)
* 包含授权信息
*/
public static void sendOKHttpRequest(String address, String authenticator, Callback callback) {
Request request = new Request.Builder()
.url(address)
.header("Authorization",authenticator)
.build();
client.newCall(request).enqueue(callback);
}
}
| 31.141667 | 99 | 0.548568 |
8433fc171fd141c36dd18e5bb3f9feeb34660353 | 9,307 | package com.bv.eidss.web;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.util.Xml;
import com.bv.eidss.web.BaseReferenceRaw;
import com.bv.eidss.web.BaseReferenceTranslationRaw;
import com.bv.eidss.web.GisBaseReferenceRaw;
import com.bv.eidss.web.GisBaseReferenceTranslationRaw;
import com.bv.eidss.web.VectorBaseReferenceRaw;
import com.bv.eidss.web.VectorBaseReferenceTranslationRaw;
import com.bv.eidss.web.VectorGisBaseReferenceRaw;
import com.bv.eidss.web.VectorGisBaseReferenceTranslationRaw;
import com.bv.eidss.model.BaseReferenceType;
import com.bv.eidss.model.GisBaseReferenceType;
public class RefDeserializer {
public static Object[] parseAll(InputStream input) throws XmlPullParserException, IOException, ParseException{
Object[] ret = new Object[5];
XmlPullParser parser = Xml.newPullParser();
parser.setInput(input, null);
int eventType = parser.getEventType();
boolean done = false;
while (eventType != XmlPullParser.END_DOCUMENT && !done){
switch (eventType){
case XmlPullParser.START_DOCUMENT:
break;
case XmlPullParser.START_TAG:
String name = parser.getName();
if (name.equalsIgnoreCase("references")){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
ret[0] = format.parse(parser.getAttributeValue("", "date").replace('T', ' '));
}
if (name.equalsIgnoreCase("refs")){
ret[1] = parseReferences(parser);
}
else if (name.equalsIgnoreCase("refsLang")){
ret[2] = parseReferenceTranslations(parser);
}
else if (name.equalsIgnoreCase("giss")){
ret[3] = parseGisReferences(parser);
}
else if (name.equalsIgnoreCase("gissLang")){
ret[4] = parseGisReferenceTranslations(parser);
}
break;
case XmlPullParser.END_TAG:
name = parser.getName();
if (name.equalsIgnoreCase("references")){
done = true;
}
break;
}
eventType = parser.next();
}
return ret;
}
private static VectorBaseReferenceRaw parseReferences(XmlPullParser parser) throws XmlPullParserException, IOException{
VectorBaseReferenceRaw allref = new VectorBaseReferenceRaw();
AddRefType(allref, BaseReferenceType.rftDiagnosis);
AddRefType(allref, BaseReferenceType.rftHumanAgeType);
AddRefType(allref, BaseReferenceType.rftHumanGender);
AddRefType(allref, BaseReferenceType.rftFinalState);
AddRefType(allref, BaseReferenceType.rftHospStatus);
AddRefType(allref, BaseReferenceType.rftCaseType);
AddRefType(allref, BaseReferenceType.rftCaseReportType);
AddRefType(allref, BaseReferenceType.rftSpeciesList);
int eventType = parser.next();
while (eventType != XmlPullParser.END_DOCUMENT){
switch (eventType){
case XmlPullParser.START_TAG:
String name = parser.getName();
if (name.equalsIgnoreCase("ref")){
BaseReferenceRaw r = new BaseReferenceRaw();
r.idfsBaseReference = Long.parseLong(parser.getAttributeValue("", "id"));
r.idfsReferenceType = Long.parseLong(parser.getAttributeValue("", "type"));
r.intHACode = Integer.parseInt(parser.getAttributeValue("", "ha"));
r.strDefault = parser.getAttributeValue("", "val");
allref.add(r);
}
break;
case XmlPullParser.END_TAG:
name = parser.getName();
if (name.equalsIgnoreCase("refs")){
return allref;
}
break;
}
eventType = parser.next();
}
return allref;
}
public static VectorBaseReferenceTranslationRaw parseReferenceTranslations(XmlPullParser parser) throws XmlPullParserException, IOException{
VectorBaseReferenceTranslationRaw allref = new VectorBaseReferenceTranslationRaw();
int eventType = parser.next();
while (eventType != XmlPullParser.END_DOCUMENT){
switch (eventType){
case XmlPullParser.START_TAG:
String name = parser.getName();
if (name.equalsIgnoreCase("refLang")){
BaseReferenceTranslationRaw r = new BaseReferenceTranslationRaw();
r.idfsBaseReference = Long.parseLong(parser.getAttributeValue("", "id"));
r.strLanguage = parser.getAttributeValue("", "lang");
r.strTranslation = parser.getAttributeValue("", "val");
allref.add(r);
}
break;
case XmlPullParser.END_TAG:
name = parser.getName();
if (name.equalsIgnoreCase("refsLang")){
return allref;
}
break;
}
eventType = parser.next();
}
return allref;
}
public static VectorGisBaseReferenceRaw parseGisReferences(XmlPullParser parser) throws XmlPullParserException, IOException{
VectorGisBaseReferenceRaw allref = new VectorGisBaseReferenceRaw();
AddGisRefType(allref, GisBaseReferenceType.rftCountry);
AddGisRefType(allref, GisBaseReferenceType.rftRegion);
AddGisRefType(allref, GisBaseReferenceType.rftRayon);
AddGisRefType(allref, GisBaseReferenceType.rftSettlement);
int eventType = parser.next();
while (eventType != XmlPullParser.END_DOCUMENT){
switch (eventType){
case XmlPullParser.START_TAG:
String name = parser.getName();
if (name.equalsIgnoreCase("gis")){
GisBaseReferenceRaw r = new GisBaseReferenceRaw();
r.idfsBaseReference = Long.parseLong(parser.getAttributeValue("", "id"));
r.idfsReferenceType = Long.parseLong(parser.getAttributeValue("", "type"));
r.idfsCountry = Long.parseLong(parser.getAttributeValue("", "cn"));
r.idfsRegion = Long.parseLong(parser.getAttributeValue("", "rg"));
r.idfsRayon = Long.parseLong(parser.getAttributeValue("", "rn"));
r.strDefault = parser.getAttributeValue("", "val");
allref.add(r);
}
break;
case XmlPullParser.END_TAG:
name = parser.getName();
if (name.equalsIgnoreCase("giss")){
return allref;
}
break;
}
eventType = parser.next();
}
return allref;
}
public static VectorGisBaseReferenceTranslationRaw parseGisReferenceTranslations(XmlPullParser parser) throws XmlPullParserException, IOException{
VectorGisBaseReferenceTranslationRaw allref = new VectorGisBaseReferenceTranslationRaw();
int eventType = parser.next();
while (eventType != XmlPullParser.END_DOCUMENT){
switch (eventType){
case XmlPullParser.START_TAG:
String name = parser.getName();
if (name.equalsIgnoreCase("gisLang")){
GisBaseReferenceTranslationRaw r = new GisBaseReferenceTranslationRaw();
r.idfsBaseReference = Long.parseLong(parser.getAttributeValue("", "id"));
r.strLanguage = parser.getAttributeValue("", "lang");
r.strTranslation = parser.getAttributeValue("", "val");
allref.add(r);
}
break;
case XmlPullParser.END_TAG:
name = parser.getName();
if (name.equalsIgnoreCase("gissLang")){
return allref;
}
break;
}
eventType = parser.next();
}
return allref;
}
private static void AddRefType(VectorBaseReferenceRaw ref, long type) {
BaseReferenceRaw r = new BaseReferenceRaw();
r.idfsBaseReference = 0;
r.idfsReferenceType = type;
r.intHACode = -1;
r.strDefault = "";
ref.add(r);
}
private static void AddGisRefType(VectorGisBaseReferenceRaw ref, long type) {
GisBaseReferenceRaw r = new GisBaseReferenceRaw();
r.idfsBaseReference = 0;
r.idfsReferenceType = type;
r.strDefault = "";
ref.add(r);
}
}
| 43.694836 | 148 | 0.573654 |
ce0a8aadbdfe6e37597972b987b1b3bf9fa3f161 | 3,651 | /*
* Copyright (C) 2014 RoboVM AB
*
* 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.
*
* Portions of this code is based on Apple Inc's Tabster sample (v1.6)
* which is copyright (C) 2011-2014 Apple Inc.
*/
package org.robovm.samples.tabster.ui;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.robovm.apple.foundation.NSIndexPath;
import org.robovm.apple.uikit.UIColor;
import org.robovm.apple.uikit.UITableView;
import org.robovm.apple.uikit.UITableViewCell;
import org.robovm.apple.uikit.UITableViewCellAccessoryType;
import org.robovm.apple.uikit.UITableViewCellStyle;
import org.robovm.apple.uikit.UITableViewController;
import org.robovm.apple.uikit.UITableViewDataSourceAdapter;
import org.robovm.apple.uikit.UITableViewDelegateAdapter;
public class OneViewController extends UITableViewController {
private final List<String> dataList;
private SubLevelViewController subLevelViewController;
public OneViewController () {
dataList = new ArrayList<>(Arrays.asList("Mac Pro", "Mac mini", "iMac", "MacBook", "MacBook Pro", "MacBook Air"));
subLevelViewController = new SubLevelViewController();
UITableView tableView = getTableView();
tableView.setAlwaysBounceVertical(true);
tableView.setBackgroundColor(UIColor.white());
tableView.setDataSource(new UITableViewDataSourceAdapter() {
@Override
public long getNumberOfRowsInSection (UITableView tableView, long section) {
return dataList.size();
}
@Override
public UITableViewCell getCellForRow (UITableView tableView, NSIndexPath indexPath) {
final String cellID = "cellID";
UITableViewCell cell = tableView.dequeueReusableCell(cellID);
if (cell == null) {
cell = new UITableViewCell(UITableViewCellStyle.Default, cellID);
cell.setAccessoryType(UITableViewCellAccessoryType.DisclosureIndicator);
}
cell.getTextLabel().setText(dataList.get((int)indexPath.getRow()));
return cell;
}
});
tableView.setDelegate(new UITableViewDelegateAdapter() {
@Override
public void didSelectRow (UITableView tableView, NSIndexPath indexPath) {
UITableViewCell cell = tableView.getCellForRow(indexPath);
subLevelViewController.setTitle(cell.getTextLabel().getText());
getNavigationController().pushViewController(subLevelViewController, true);
}
});
}
@Override
public void viewDidLoad () {
super.viewDidLoad();
getNavigationItem().setTitle("One");
}
@Override
public void viewWillAppear (boolean animated) {
super.viewWillAppear(animated);
// this UIViewController is about to re-appear, make sure we remove the current selection in our table view
NSIndexPath tableSelection = getTableView().getIndexPathForSelectedRow();
getTableView().deselectRow(tableSelection, false);
}
}
| 38.03125 | 122 | 0.691865 |
cc46a28058df1155d1a5e643624bb77b7968877e | 576 | package PocketGems;
public class StrStr {
public int strStr(String haystack, String needle) {
int l1 = haystack.length(), l2 = needle.length();
if (l1 < l2) {
return -1;
} else if (l2 == 0) {
return 0;
}
int threshold = l1 - l2;
for (int i = 0; i <= threshold; ++i) {
if (haystack.substring(i,i+l2).equals(needle)) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
| 22.153846 | 61 | 0.482639 |
8350ebe5825f043c70589f954ab04fe1b035bc06 | 2,635 | import java.io.File;
import java.util.Scanner;
class Valg{
public static void main(String[] args) throws Exception{
Scanner filLeser = new Scanner(new File("stemmer.txt"));
String[] valg = new String[456];
int[] stemmer = new int[4];
//Lagre alle stemmer i en string array
for(int i = 0; filLeser.hasNextLine(); i++){
valg[i] = filLeser.nextLine();
}
//Bruker en lokke for å gå gjennom array lagrer antall stemmer forhvert parti
for(int i = 0; i < valg.length; i++){
if(valg[i].equals("Sp")){
stemmer[0]++;
}else if(valg[i].equals("Ap")){
stemmer[1]++;
}else if(valg[i].equals("KrF")){
stemmer[2]++;
}else if(valg[i].equals("h")){
stemmer[3]++;
}
}
System.out.println("Senterpartiet har: " + stemmer[0] + " stemmer. ");
//Kaller på metode finneProsent og sender med tallet som ble skrevet ut ovenfor
double prosentAvStemmer = prosent(456,135);
//Skriver ut prosentAndel av stemmer
System.out.println("SP: Utgjor " + prosentAvStemmer + "% av valg stemmene. ");
System.out.println(" ");
//Skriver ut antall stemmer for Ap
System.out.println("Arbeiderpartiet har: " + stemmer[1] + " stemmer. ");
//Kaller på metode finneProsent og sender med tallet som ble skrevet ut ovenfor
double prosentAvStemmer2 = prosent(456, 159);
//Skriver ut prosentAndel av stemmer
System.out.println("AP: Utgjor " + prosentAvStemmer2 + "% av valg stemmene. ");
System.out.println(" ");
//Skriver ut antall stemmer for KrF
System.out.println("Kristligfolkeparti har: " + stemmer[2] + " stemmer. ");
//Kaller på metode finneProsent og sender med tallet som ble skrevet ut ovenfor
double prosentAvStemmer3 = prosent(456, 36);
//Skriver ut prosentAndel av stemmer
System.out.println("KrF: Utgjor " + prosentAvStemmer3 + "% av valg stemmene. ");
System.out.println(" ");
//Skriver ut antall stemmer for hoyre
System.out.println("Hoyre har: " + stemmer[3] + " stemmer. ");
//Kaller på metode finneProsent og sender med tallet som ble skrevet ut ovenfor
double prosentAvStemmer4 = prosent(456, 126);
//Skriver ut prosentAndel av stemmer
System.out.println("H: Utgjor " + prosentAvStemmer4 + "% av valg stemmene. ");
System.out.println(" ");
//Utksrift av valgets vinner
System.out.println("Valgets vinner er Arbeiderpartiet");
}
//Metode for å finne prosent
public static double prosent(double tall, double tall1){
double sum = (tall1/tall) * 100;
return sum;
}
}
| 41.825397 | 86 | 0.63833 |
a62e40d62b687d02dd9e7fd5070e731ad4042cff | 5,221 | package com.purbon.kafka.topology.backend;
import com.purbon.kafka.topology.BackendController.Mode;
import com.purbon.kafka.topology.model.cluster.ServiceAccount;
import com.purbon.kafka.topology.roles.TopologyAclBinding;
import com.purbon.kafka.topology.utils.JSON;
import java.io.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class FileBackend implements Backend {
private static final Logger LOGGER = LogManager.getLogger(FileBackend.class);
public static final String STATE_FILE_NAME = ".cluster-state";
private RandomAccessFile writer;
private String expression =
"^\\'(\\S+)\\',\\s*\\'(\\S+)\\',\\s*\\'(\\S+)\\',\\s*\\'(\\S+)\\',\\s*\\'(\\S+)\\',\\s*\\'(\\S+)\\'";
private Pattern regexp;
public FileBackend() {
this.regexp = Pattern.compile(expression);
this.writer = null;
}
@Override
public void createOrOpen() {
createOrOpen(Mode.APPEND);
}
@Override
public void createOrOpen(Mode mode) {
try {
writer = new RandomAccessFile(STATE_FILE_NAME, "rw");
Path path = Paths.get(STATE_FILE_NAME);
if (path.toFile().exists()) {
writer.seek(0);
if (mode.equals(Mode.TRUNCATE)) {
writer.getChannel().truncate(0);
}
}
} catch (IOException e) {
LOGGER.error(e);
}
}
public Set<TopologyAclBinding> loadBindings() throws IOException {
if (writer == null) {
throw new IOException("state file does not exist");
}
File file = new File(STATE_FILE_NAME);
return load(file.toURI());
}
public Set<TopologyAclBinding> load(URI uri) throws IOException {
Path filePath = Paths.get(uri);
Set<TopologyAclBinding> bindings = new LinkedHashSet<>();
BufferedReader in = new BufferedReader(new FileReader(filePath.toFile()));
String type = in.readLine();
String line = null;
while ((line = in.readLine()) != null) {
TopologyAclBinding binding = null;
if (line.equalsIgnoreCase("ServiceAccounts")) {
// process service accounts, should break from here.
break;
}
if (type.equalsIgnoreCase("acls")) {
binding = buildAclBinding(line);
} else {
throw new IOException("Binding type ( " + type + " )not supported.");
}
bindings.add(binding);
}
return bindings;
}
public Set<ServiceAccount> loadServiceAccounts() throws IOException {
if (writer == null) {
throw new IOException("state file does not exist");
}
Path filePath = Paths.get(STATE_FILE_NAME);
Set<ServiceAccount> accounts = new HashSet<>();
BufferedReader in = new BufferedReader(new FileReader(filePath.toFile()));
String line = null;
while ((line = in.readLine()) != null) {
if (line.equalsIgnoreCase("ServiceAccounts")) {
// process service accounts, should break from here.
break;
}
}
if (line != null && line.equalsIgnoreCase("ServiceAccounts")) {
while ((line = in.readLine()) != null) {
ServiceAccount account = (ServiceAccount) JSON.toObject(line, ServiceAccount.class);
accounts.add(account);
}
}
return accounts;
}
private TopologyAclBinding buildRBACBinding(String line) {
return null;
}
private TopologyAclBinding buildAclBinding(String line) throws IOException {
// 'TOPIC', 'topicB', '*', 'READ', 'User:Connect1', 'LITERAL'
Matcher matches = regexp.matcher(line);
if (matches.groupCount() != 6 || !matches.matches()) {
throw new IOException(("line (" + line + ") does not match"));
}
return TopologyAclBinding.build(
matches.group(1), // resourceType
matches.group(2), // resourceName
matches.group(3), // host
matches.group(4), // operation
matches.group(5), // principal
matches.group(6) // pattern
);
}
public void saveType(String type) {
try {
writer.writeBytes(type);
writer.writeBytes("\n");
} catch (IOException e) {
LOGGER.error(e);
}
}
@Override
public void saveBindings(Set<TopologyAclBinding> bindings) {
bindings.stream()
.sorted()
.forEach(
binding -> {
try {
writer.writeBytes(binding.toString());
writer.writeBytes("\n");
} catch (IOException e) {
LOGGER.error(e);
}
});
}
@Override
public void saveAccounts(Set<ServiceAccount> accounts) {
accounts.forEach(
account -> {
try {
writer.writeBytes(JSON.asString(account));
writer.writeBytes("\n");
} catch (IOException e) {
LOGGER.error(e);
}
});
}
@Override
public void close() {
try {
writer.close();
} catch (IOException e) {
LOGGER.error(e);
}
}
}
| 29.005556 | 107 | 0.623444 |
28ff06906b2c9928ba3dbf4cbd1f0f4979c58caf | 1,045 | package tyrfing.common.struct;
public class Grid<T> {
private T grid[][];
private int width;
private int height;
@SuppressWarnings("unchecked")
public Grid(int width, int height)
{
this.width = width;
this.height = height;
this.grid = (T[][]) new Object[width][height];
}
public int getWidth()
{
return width;
}
public int getHeight()
{
return height;
}
public T getItem(int x, int y)
{
if (checkBounds(x,y))
{
return grid[x][y];
}
return null;
}
public T getItem(Coord2 coord)
{
return getItem(coord.x, coord.y);
}
public void setItem(int x, int y, T item)
{
grid[x][y] = item;
}
public void setItem(Coord2 coord, T item)
{
setItem(coord.x, coord.y, item);
}
public boolean checkBounds(int x, int y)
{
if (x >= 0 && y >= 0)
{
if (x < width && y < height)
{
return true;
}
}
return false;
}
public void writeNull()
{
for (int x = 0; x < width; x++)
{
for (int y = 0; y < width; y++)
{
grid[x][y] = null;
}
}
}
}
| 13.397436 | 48 | 0.566507 |
f78469cd81c6d1763884f4f21c236196369c221f | 878 | package edu.fiuba.algo3.controllers;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
import java.net.URL;
import java.util.ResourceBundle;
public class ControladorFotoDeCiudad implements Initializable {
@FXML private Pane PanelImagen;
@FXML private ImageView ImagenPais;
private String URL_PAISES = "file:src/main/resources/fotos/paises/";
private Image img;
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
}
public void mostrarImagen(String ciudad){
img = new Image(URL_PAISES+ciudad+".jpg");
ImagenPais.setImage(img);
}
public void ocultar(){
this.PanelImagen.setVisible(false);
}
public void mostrar(){
this.PanelImagen.setVisible(true);
}
}
| 24.388889 | 72 | 0.719818 |
bb267a4a23c4e92e67978561dc0a695bdc78add5 | 1,027 | package cn.abelib.biz.vo;
import java.math.BigDecimal;
import java.util.List;
/**
*
* @author abel
* @date 2017/9/11
*/
public class CartVo {
private List<CartProductVo> cartProductVoList;
private BigDecimal cartTotal;
private Boolean allChecked;
private String imageHost;
public List<CartProductVo> getCartProductVoList() {
return cartProductVoList;
}
public void setCartProductVoList(List<CartProductVo> cartProductVoList) {
this.cartProductVoList = cartProductVoList;
}
public BigDecimal getCartTotal() {
return cartTotal;
}
public void setCartTotal(BigDecimal cartTotal) {
this.cartTotal = cartTotal;
}
public String getImageHost() {
return imageHost;
}
public void setImageHost(String imageHost) {
this.imageHost = imageHost;
}
public void setAllChecked(Boolean allChecked) {
this.allChecked = allChecked;
}
public Boolean getAllChecked() {
return allChecked;
}
}
| 20.959184 | 77 | 0.672833 |
2493bba89fb42edfb1cd7b1024845cfc360fea0c | 1,048 | package com.example.criminalintent.Database;
import android.content.Context;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.example.criminalintent.Database.crimeDBSchema.crimeTable;
public class crimeBaseHelper extends SQLiteOpenHelper {
public static final int version = 1;
public static final String Db_name = "crime.db";
public crimeBaseHelper(@Nullable Context context) {
super(context, Db_name, null, version);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL("create table "+ crimeTable.Name+"(_id integer primary key autoincrement,"+crimeTable.Cols.uuid+","+crimeTable.Cols.title+","+crimeTable.Cols.date+","+crimeTable.Cols.solved+","+crimeTable.Cols.suspect+")");
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
}
| 28.324324 | 238 | 0.758588 |
e8aed7a9481ef20fdd4ea919b35e24cd070af3bd | 2,719 | /**
*
* Copyright 2017 Florian Erhard
*
* 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 gedi.core.data.annotation;
import java.io.IOException;
import gedi.app.Config;
import gedi.util.io.randomaccess.BinaryReader;
import gedi.util.io.randomaccess.BinaryWriter;
import gedi.util.io.randomaccess.serialization.BinarySerializable;
public class NarrowPeakAnnotation implements BinarySerializable, ScoreProvider {
private String name;
private double score;
private double enrichment;
private double pvalue;
private double qvalue;
private int summit;
public NarrowPeakAnnotation() {
}
public NarrowPeakAnnotation(String name, double score, double enrichment,
double pvalue, double qvalue, int summit) {
this.name = name;
this.score = score;
this.enrichment = enrichment;
this.pvalue = pvalue;
this.qvalue = qvalue;
this.summit = summit;
}
@Override
public void serialize(BinaryWriter out) throws IOException {
out.putString(name);
out.putDouble(score);
out.putDouble(enrichment);
out.putDouble(pvalue);
out.putDouble(qvalue);
out.putInt(summit);
}
@Override
public void deserialize(BinaryReader in) throws IOException {
name = in.getString();
score = in.getDouble();
enrichment = in.getDouble();
pvalue = in.getDouble();
qvalue = in.getDouble();
summit = in.getInt();
}
@Override
public String toString() {
return String.format("%s("+Config.getInstance().getRealFormat()+")",name,score);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
public double getEnrichment() {
return enrichment;
}
public void setEnrichment(double enrichment) {
this.enrichment = enrichment;
}
public double getPvalue() {
return pvalue;
}
public void setPvalue(double pvalue) {
this.pvalue = pvalue;
}
public double getQvalue() {
return qvalue;
}
public void setQvalue(double qvalue) {
this.qvalue = qvalue;
}
public int getSummit() {
return summit;
}
public void setSummit(int summit) {
this.summit = summit;
}
}
| 21.752 | 82 | 0.716072 |
f93bdee462605ef25d9bdfc88e1ca95041a80827 | 887 | package pl.roentgen.util.model;
import javafx.scene.paint.Paint;
public class Point {
private int id;
private int x;
private int y;
private boolean visible;
private Paint fill;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public boolean isVisible() {
return visible;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
public Paint getFill() {
return fill;
}
public void setFill(Paint fill) {
this.fill = fill;
}
}
| 14.306452 | 45 | 0.520857 |
52c17a7afb2e83e0e74e83b163ccb4e7e79ffa8e | 6,264 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.eas.designer.explorer.files.wizard;
import com.eas.designer.application.indexer.IndexerQuery;
import com.eas.util.StringUtils;
import java.awt.Component;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.*;
import javax.swing.JComponent;
import javax.swing.event.ChangeListener;
import org.netbeans.api.project.FileOwnerQuery;
import org.netbeans.api.project.Project;
import org.netbeans.spi.project.ui.templates.support.Templates;
import org.openide.WizardDescriptor;
import org.openide.filesystems.FileObject;
import org.openide.loaders.DataFolder;
import org.openide.loaders.DataObject;
import org.openide.util.NbBundle;
/**
*
* @author mg
*/
public class NewApplicationElementWizardIterator implements WizardDescriptor.InstantiatingIterator<WizardDescriptor> {
public static final String PLATYPUS_APP_ELEMENT_NAME_PARAM_NAME = "appElementName";
public NewApplicationElementWizardIterator() {
super();
}
public static NewApplicationElementWizardIterator createIterator() {
return new NewApplicationElementWizardIterator();
}
protected int index;
protected WizardDescriptor.Panel<WizardDescriptor>[] panels;
protected WizardDescriptor wiz;
@Override
public Set instantiate() throws IOException {
FileObject dir = Templates.getTargetFolder(wiz);
String targetName = Templates.getTargetName(wiz);
DataFolder df = DataFolder.findFolder(dir);
FileObject template = Templates.getTemplate(wiz);
DataObject dTemplate = DataObject.find(template);
Project project = FileOwnerQuery.getOwner(dir);
DataObject dobj = dTemplate.createFromTemplate(df, targetName, achieveParameters(project, wiz));
FileObject createdFile = dobj.getPrimaryFile();
return Collections.singleton(createdFile);
}
/**
* Generates new application element's name.
* New name will be generated using the provided initial name, unsupported symbols will be replaced
* and it will be ensured that new name is unique.
* @param project Application's project
* @param str Initial name
* @return New name
*/
public static String getNewValidAppElementName(Project project, String str) {
assert str != null;
assert !str.isEmpty();
String appElementName = StringUtils.replaceUnsupportedSymbols(str.trim());
String s = appElementName;
int i = 0;
while (IndexerQuery.appElementId2File(project, s) != null) {
s = String.format("%s_%d", appElementName, ++i); // NOI18N
}
return s;
}
@Override
public void initialize(WizardDescriptor aWiz) {
wiz = aWiz;
index = 0;
panels = createPanels(wiz);
// Make sure list of steps is accurate.
String[] steps = createSteps();
for (int i = 0; i < panels.length; i++) {
Component c = panels[i].getComponent();
if (steps[i] == null) {
// Default step name to component name of panel.
// Mainly useful for getting the name of the target
// chooser to appear in the list of steps.
steps[i] = c.getName();
}
if (c instanceof JComponent) { // assume Swing components
JComponent jc = (JComponent) c;
// Step №.
jc.putClientProperty(WizardDescriptor.PROP_CONTENT_SELECTED_INDEX, new Integer(i));
// Step name (actually the whole list for reference)
jc.putClientProperty(WizardDescriptor.PROP_CONTENT_DATA, steps);
// Turn on subtitle creation on each step
jc.putClientProperty(WizardDescriptor.PROP_AUTO_WIZARD_STYLE, Boolean.TRUE);
// Show steps on the left side with the image on the background
jc.putClientProperty(WizardDescriptor.PROP_CONTENT_DISPLAYED, Boolean.TRUE);
// Turn on numbering of all steps
jc.putClientProperty(WizardDescriptor.PROP_CONTENT_NUMBERED, Boolean.TRUE);
}
}
}
@Override
public void uninitialize(WizardDescriptor wd) {
Templates.setTargetName(wiz, null);
panels = null;
wiz = null;
}
@Override
public String name() {
return MessageFormat.format("{0} of {1}",
new Object[]{index + 1, panels.length});
}
@Override
public boolean hasNext() {
return index < panels.length - 1;
}
@Override
public boolean hasPrevious() {
return index > 0;
}
@Override
public void nextPanel() {
if (!hasNext()) {
throw new NoSuchElementException();
}
index++;
}
@Override
public void previousPanel() {
if (!hasPrevious()) {
throw new NoSuchElementException();
}
index--;
}
@Override
public WizardDescriptor.Panel<WizardDescriptor> current() {
return panels[index];
}
// If nothing unusual changes in the middle of the wizard, simply:
@Override
public final void addChangeListener(ChangeListener l) {
}
@Override
public final void removeChangeListener(ChangeListener l) {
}
protected Map<String, String> achieveParameters(Project project, WizardDescriptor aWiz) {
Map<String, String> parameters = new HashMap<>();
parameters.put(
PLATYPUS_APP_ELEMENT_NAME_PARAM_NAME,
getNewValidAppElementName(project, Templates.getTargetName(wiz)));
return parameters;
}
protected WizardDescriptor.Panel[] createPanels(WizardDescriptor wiz) {
return new WizardDescriptor.Panel[]{
new NewApplicationElementWizardNamePanel()
};
}
protected String[] createSteps() {
return new String[]{
NbBundle.getMessage(NewApplicationElementWizardIterator.class, "LBL_ChooseFileTypeStep"), NbBundle.getMessage(NewApplicationElementWizardIterator.class, "LBL_CreateApplicationElementStep")
};
}
}
| 34.229508 | 208 | 0.653097 |
45b9ba6294db843383abfd15795dbfd1713e374b | 343 | package com.richard.printer.enumerate;
/**
* author Richard
* date 2020/8/18 10:49
* version V1.0
* description: 打印机相关错误码
*/
public enum ErrorCode {
OpenPortFailed,
OpenPortSuccess,
ClosePortFailed,
ClosePortSuccess,
WriteDataFailed,
WriteDataSuccess,
ReadDataSuccess,
ReadDataFailed,
UnknownError;
}
| 17.15 | 38 | 0.702624 |
7670eec4faa670b4aad8f9011d7c900f66c0dbd9 | 5,400 | /*
*Copyright (c) 2005-2010, 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.esb.samples.test.miscellaneous;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.carbon.automation.engine.annotations.ExecutionEnvironment;
import org.wso2.carbon.automation.engine.annotations.SetEnvironment;
import org.wso2.carbon.esb.samples.test.util.ESBSampleIntegrationTest;
import org.wso2.esb.integration.common.utils.common.ServerConfigurationManager;
import org.wso2.esb.integration.common.utils.common.TestConfigurationProvider;
import java.io.File;
import java.io.UnsupportedEncodingException;
public class Sample653TestCase extends ESBSampleIntegrationTest {
private ServerConfigurationManager serverManager = null;
@BeforeClass(alwaysRun = true)
public void startJMSBrokerAndConfigureESB() throws Exception {
super.init();
serverManager = new ServerConfigurationManager(context);
//setting <parameter name="priorityConfigFile" locked="false">samples/service-bus/resources/priority/priority-configuration.xml</parameter>
serverManager.applyConfiguration(new File(
TestConfigurationProvider.getResourceLocation() + File.separator + "artifacts" + File.separator + "ESB"
+ File.separator + "priority" + File.separator + "axis2.xml"));
super.init();
loadSampleESBConfiguration(150);
}
@AfterClass(alwaysRun = true)
public void destroy() throws Exception {
//reverting the changes done to esb sever
super.cleanup();
Thread.sleep(5000);
if (serverManager != null) {
serverManager.restoreToLastConfiguration();
}
}
@SetEnvironment(executionEnvironments = { ExecutionEnvironment.STANDALONE })
@Test(groups = { "wso2.esb" }, description = "NHTTP Transport Priority Based Dispatching ")
public void testPriorityBasedMessages() throws Exception {
Sender senderIBM = new Sender();
senderIBM.init("IBM", "1");
Sender senderMSTF = new Sender();
senderMSTF.init("MSTF", "10");
senderIBM.start();
senderMSTF.start();
Thread.sleep(15000);
Assert.assertTrue(senderMSTF.getResponseTime() >= senderIBM.getResponseTime(),
"Symbol with higher priority header took more time than Symbol with lower priority");
}
class Sender extends Thread {
private DefaultHttpClient client = new DefaultHttpClient();
private ResponseHandler<String> response = new BasicResponseHandler();
private long responseTime = 0L;
private HttpPost httpget = new HttpPost(getProxyServiceURLHttp("StockQuoteProxy"));
public void init(String symbol, String priority) {
String soapRequest = "<?xml version='1.0' encoding='UTF-8'?>"
+ "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\""
+ " xmlns:ser=\"http://services.samples\" xmlns:xsd=\"http://services.samples/xsd\">"
+ " <soapenv:Header/>" + " <soapenv:Body>"
+ " <m0:getQuote xmlns:m0=\"http://services.samples\">\n" + " <m0:request>\n"
+ " <m0:symbol>" + symbol + "</m0:symbol>\n" + " </m0:request>\n"
+ " </m0:getQuote>" + " </soapenv:Body>" + "</soapenv:Envelope>";
httpget.addHeader("SOAPAction", "getQuote");
httpget.addHeader("priority", priority);
StringEntity stringEntity = null;
try {
stringEntity = new StringEntity(soapRequest);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
stringEntity.setContentType("text/xml; charset=utf-8");
httpget.setEntity(stringEntity);
}
@Override
public void run() {
long currentTime = System.currentTimeMillis();
for (int i = 0; i < 2000; i++) {
try {
client.execute(httpget, response);
} catch (Exception e) {
e.printStackTrace();
}
}
long afterTime = System.currentTimeMillis();
responseTime += (afterTime - currentTime);
}
public long getResponseTime() {
return responseTime;
}
}
}
| 38.848921 | 147 | 0.649259 |
f4ae876c44678f4e1aba4089416e1e743635223e | 169 | /**
* Simple convenient creation of plots.
*
* For examples see the demo package net.finmath.plots.demo.
*
* @author Christian Fries
*/
package net.finmath.plots;
| 18.777778 | 60 | 0.710059 |
49e178f9ea555b3367dcaba711c2270ba4025768 | 520 | package org.owasp.appsensor.rpc.thrift;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AppSensorApiServer {
public static void main(String[] args) {
@SuppressWarnings("resource")
AbstractApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
AppSensorThriftSslServer server = context.getBean(AppSensorThriftSslServer.class);
server.start();
}
}
| 28.888889 | 100 | 0.805769 |
c9d0eaed08dc25ec21f234d72ead956e632a4609 | 3,400 | /*
* smart-doc
*
* Copyright (C) 2016-2021 smart-doc
*
* 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 com.power.doc.utils;
import com.power.common.util.FileUtil;
import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.ClasspathResourceLoader;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/**
* Beetl template handle util
*
* @author sunyu on 2016/12/6.
*/
public class BeetlTemplateUtil {
/**
* Get Beetl template by file name
*
* @param templateName template name
* @return Beetl Template Object
*/
public static Template getByName(String templateName) {
try {
ClasspathResourceLoader resourceLoader = new ClasspathResourceLoader("/template/");
Configuration cfg = Configuration.defaultConfiguration();
cfg.add("/smart-doc-beetl.properties");
GroupTemplate gt = new GroupTemplate(resourceLoader, cfg);
return gt.getTemplate(templateName);
} catch (IOException e) {
throw new RuntimeException("Can't get Beetl template.");
}
}
/**
* Batch bind binding value to Beetl templates and return all file rendered,
* Map key is file name,value is file content
*
* @param path path
* @param params params
* @return map
*/
public static Map<String, String> getTemplatesRendered(String path, Map<String, Object> params) {
Map<String, String> templateMap = new HashMap<>();
File[] files = FileUtil.getResourceFolderFiles(path);
GroupTemplate gt = getGroupTemplate(path);
for (File f : files) {
if (f.isFile()) {
String fileName = f.getName();
Template tp = gt.getTemplate(fileName);
if (Objects.nonNull(params)) {
tp.binding(params);
}
templateMap.put(fileName, tp.render());
}
}
return templateMap;
}
/**
* @param path
* @return
*/
private static GroupTemplate getGroupTemplate(String path) {
try {
ClasspathResourceLoader resourceLoader = new ClasspathResourceLoader("/" + path + "/");
Configuration cfg = Configuration.defaultConfiguration();
GroupTemplate gt = new GroupTemplate(resourceLoader, cfg);
return gt;
} catch (IOException e) {
throw new RuntimeException("Can't found Beetl template.");
}
}
}
| 33.009709 | 101 | 0.650294 |
aa160c4ffe6c9e8c9110810a37c50ad6cc55c13c | 9,500 | /*
* Copyright 2015 SIB Visions GmbH
*
* 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.sibvisions.kitchensink.samples.model;
import java.math.BigDecimal;
import java.util.Date;
import javax.rad.genui.celleditor.UICheckBoxCellEditor;
import javax.rad.genui.celleditor.UIChoiceCellEditor;
import javax.rad.genui.celleditor.UILinkedCellEditor;
import javax.rad.genui.celleditor.UITextCellEditor;
import javax.rad.genui.component.UILabel;
import javax.rad.genui.component.UIToggleButton;
import javax.rad.genui.container.UIPanel;
import javax.rad.genui.container.UISplitPanel;
import javax.rad.genui.control.UIEditor;
import javax.rad.genui.control.UITable;
import javax.rad.genui.layout.UIBorderLayout;
import javax.rad.genui.layout.UIFormLayout;
import javax.rad.model.ColumnDefinition;
import javax.rad.model.IDataBook;
import javax.rad.model.IDataRow;
import javax.rad.model.ModelException;
import javax.rad.model.datatype.BigDecimalDataType;
import javax.rad.model.datatype.BooleanDataType;
import javax.rad.model.datatype.StringDataType;
import javax.rad.model.datatype.TimestampDataType;
import javax.rad.model.reference.ReferenceDefinition;
import javax.rad.ui.container.IPanel;
import com.sibvisions.kitchensink.ISample;
import com.sibvisions.kitchensink.samples.AbstractSample;
import com.sibvisions.rad.model.mem.MemDataBook;
/**
* Demonstrates the data binding capabilities of JVx.
*
* @author Robert Zenz
*/
public class DataBindingSample extends AbstractSample implements ISample
{
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Interface implementation
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/**
* {@inheritDoc}
*/
@Override
public String getCategory()
{
return "Model";
}
/**
* {@inheritDoc}
*/
@Override
public IPanel getContent() throws Throwable
{
BooleanDataType booleanDataType = new BooleanDataType();
booleanDataType.setCellEditor(new UICheckBoxCellEditor(Boolean.TRUE, Boolean.FALSE));
Object[] allowedValues = new Object[] { "favorite", "important", "readonly", "unreadable" };
String[] imageNames = new String[] {
getImagePath("emblem-favorite.png"),
getImagePath("emblem-important.png"),
getImagePath("emblem-readonly.png"),
getImagePath("emblem-unreadable.png")
};
UIChoiceCellEditor choiceCellEditor = new UIChoiceCellEditor(allowedValues, imageNames, getImagePath("emblem-favorite.png"));
IDataBook typeDataBook = new MemDataBook();
typeDataBook.getRowDefinition().addColumnDefinition(new ColumnDefinition("ID", new BigDecimalDataType()));
typeDataBook.getRowDefinition().addColumnDefinition(new ColumnDefinition("NAME", new StringDataType(new UITextCellEditor())));
typeDataBook.getRowDefinition().addColumnDefinition(new ColumnDefinition("DESCRIPTION", new StringDataType(new UITextCellEditor())));
typeDataBook.setName("TYPES");
typeDataBook.open();
typeDataBook.insert(false);
typeDataBook.setValue("ID", BigDecimal.valueOf(1));
typeDataBook.setValue("NAME", "Primitive");
typeDataBook.setValue("DESCRIPTION", "Some primitive type.");
typeDataBook.insert(false);
typeDataBook.setValue("ID", BigDecimal.valueOf(2));
typeDataBook.setValue("NAME", "Extended");
typeDataBook.setValue("DESCRIPTION", "Type extended by unknown people in the interwebs.");
typeDataBook.insert(false);
typeDataBook.setValue("ID", BigDecimal.valueOf(3));
typeDataBook.setValue("NAME", "Hyper");
typeDataBook.setValue("DESCRIPTION", "Basically classified.");
typeDataBook.saveAllRows();
ReferenceDefinition referenceDefinition = new ReferenceDefinition(new String[] { "TYPE_ID", "TYPE_NAME" }, typeDataBook, new String[] { "ID", "NAME" });
IDataBook dataBook = new MemDataBook();
dataBook.getRowDefinition().addColumnDefinition(new ColumnDefinition("ID", new BigDecimalDataType()));
dataBook.getRowDefinition().addColumnDefinition(new ColumnDefinition("STRING", new StringDataType()));
dataBook.getRowDefinition().addColumnDefinition(new ColumnDefinition("PASSWORD", new StringDataType(new UITextCellEditor(UITextCellEditor.TEXT_PLAIN_PASSWORD))));
dataBook.getRowDefinition().addColumnDefinition(new ColumnDefinition("BOOLEAN", booleanDataType));
dataBook.getRowDefinition().addColumnDefinition(new ColumnDefinition("CHOICE", new StringDataType(choiceCellEditor)));
dataBook.getRowDefinition().addColumnDefinition(new ColumnDefinition("DATETIME", new TimestampDataType()));
dataBook.getRowDefinition().addColumnDefinition(new ColumnDefinition("NUMBER", new BigDecimalDataType()));
dataBook.getRowDefinition().addColumnDefinition(new ColumnDefinition("TYPE_ID", new BigDecimalDataType()));
dataBook.getRowDefinition().addColumnDefinition(new ColumnDefinition("TYPE_NAME", new StringDataType(new UILinkedCellEditor(referenceDefinition))));
dataBook.setName("DATABINDING");
dataBook.getRowDefinition().getColumnDefinition("ID").setNullable(false);
dataBook.getRowDefinition().getColumnDefinition("BOOLEAN").setNullable(false);
dataBook.getRowDefinition().getColumnDefinition("STRING").setNullable(false);
dataBook.getRowDefinition().getColumnDefinition("PASSWORD").setNullable(false);
dataBook.open();
dataBook.insert(false);
dataBook.setValue("ID", BigDecimal.valueOf(1));
dataBook.setValue("BOOLEAN", Boolean.TRUE);
dataBook.setValue("STRING", "This is the actual value of the column.");
dataBook.setValue("PASSWORD", "Some secret.");
dataBook.setValue("CHOICE", null);
dataBook.setValue("DATETIME", new Date());
dataBook.setValue("TYPE_ID", BigDecimal.valueOf(1));
dataBook.setValue("TYPE_NAME", "Primitive");
dataBook.setValue("NUMBER", BigDecimal.valueOf(88956));
dataBook.insert(false);
dataBook.setValue("ID", BigDecimal.valueOf(2));
dataBook.setValue("BOOLEAN", Boolean.FALSE);
dataBook.setValue("STRING", "This is the second row.");
dataBook.setValue("PASSWORD", "Some secret.");
dataBook.setValue("CHOICE", "important");
dataBook.setValue("DATETIME", null);
dataBook.setValue("TYPE_ID", BigDecimal.valueOf(3));
dataBook.setValue("TYPE_NAME", "Hyper");
dataBook.setValue("NUMBER", BigDecimal.valueOf(47.2366));
dataBook.saveAllRows();
dataBook.setSelectedRow(0);
UIFormLayout editorsPaneLayout = new UIFormLayout();
editorsPaneLayout.setNewlineCount(2);
UIPanel editorsPane = new UIPanel();
editorsPane.setLayout(editorsPaneLayout);
addEditor(editorsPane, dataBook, "ID");
addEditor(editorsPane, dataBook, "BOOLEAN");
addEditor(editorsPane, dataBook, "STRING");
addEditor(editorsPane, dataBook, "PASSWORD");
addEditor(editorsPane, dataBook, "CHOICE");
addEditor(editorsPane, dataBook, "DATETIME");
addEditor(editorsPane, dataBook, "NUMBER");
addEditor(editorsPane, dataBook, "TYPE_ID");
addEditor(editorsPane, dataBook, "TYPE_NAME");
UISplitPanel tableSplitPanel = new UISplitPanel(UISplitPanel.SPLIT_TOP_BOTTOM);
tableSplitPanel.setFirstComponent(new UITable(dataBook));
tableSplitPanel.setSecondComponent(new UITable(dataBook));
UISplitPanel splitPanel = new UISplitPanel(UISplitPanel.SPLIT_LEFT_RIGHT);
splitPanel.setDividerAlignment(UISplitPanel.DIVIDER_BOTTOM_RIGHT);
splitPanel.setFirstComponent(tableSplitPanel);
splitPanel.setSecondComponent(editorsPane);
UIToggleButton readOnlyToggleButton = new UIToggleButton("Read-Only");
readOnlyToggleButton.eventAction().addListener((pActionEvent) ->
{
try
{
dataBook.setReadOnly(readOnlyToggleButton.isSelected());
}
catch (Exception e)
{
e.printStackTrace();
}
});
UIFormLayout controlsLayout = new UIFormLayout();
UIPanel controls = new UIPanel();
controls.setLayout(controlsLayout);
controls.add(readOnlyToggleButton, controlsLayout.getConstraints(0, 0));
UIPanel content = new UIPanel();
content.setLayout(new UIBorderLayout());
content.add(splitPanel, UIBorderLayout.CENTER);
content.add(controls, UIBorderLayout.SOUTH);
return content;
}
/**
* {@inheritDoc}
*/
@Override
public String getName()
{
return "DataBinding";
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// User-defined methods
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/**
* Adds the editor.
*
* @param pPanel the panel.
* @param pDataRow the data row.
* @param pColumnName the column name.
* @throws ModelException the model exception
*/
private void addEditor(UIPanel pPanel, IDataRow pDataRow, String pColumnName) throws ModelException
{
UIEditor editor = new UIEditor(pDataRow, pColumnName);
editor.setPlaceholderVisible(true);
pPanel.add(new UILabel(pColumnName));
pPanel.add(editor);
}
} // DataBindingSample
| 39.583333 | 165 | 0.723895 |
3089fe0d2fcb65c4ff4a593e98fb6002b5d0054d | 74 | package com.kaznowski.hugh.raftservice;
public enum RaftMessageType {
}
| 12.333333 | 39 | 0.797297 |
3484bfd2a19294df55d7c5a73566819e1966e89e | 184 | package com.avatech.edi.mdm.bo;
/**
* @author Fancy
* @date 2018/9/6
*/
public interface IMDMMasterData {
String getUniqueKey();
void setUniqueKey(String uniqueKey);
}
| 14.153846 | 40 | 0.673913 |
f01051c8475160c4d5ebd10ca3f8f4feb62fdbdc | 13,112 | package abdi.andreas.grideous.game;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Point;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;
import java.util.Random;
import abdi.andreas.grideous.R;
import abdi.andreas.grideous.engine.Direction;
import abdi.andreas.grideous.engine.RefreshHandler;
import abdi.andreas.grideous.engine.TileGameView;
public class GrideousView extends TileGameView {
private static final String TAG = "GrideousView";
//Drawable configurations
private static final int RED_BLOCK = 1;
private static final int GREEN_BLOCK = 2;
private static final int BLUE_BLOCK = 3;
//graphics redraw handling.
private RefreshHandler refreshHandler = new RefreshHandler(this);
//Views
private TextView statusView;
private View arrowsView;
private View backgroundView;
//game data
private Mode currentMode = Mode.READY;
private Direction currentDirection = Direction.UP;
private Direction nextDirection = Direction.UP;
private int shiftRubble = 0;
private long score = 0;
private long moveDelay = 600;
private long lastMove;
private boolean[][] rubble;
private Block currentBlock = null;
/**
* game logic pseudo code.
* a fall direction is set.
* blocks fall in the fall direction. (1 - 3 blocks).
* if the next block that generates cannot move
* If there is a row/ column full of the blocks, that wave is cleared.
* If it still cannot move, then check if any part of it is out of borders, and block it out.
**/
private static final Random RNG = new Random();
private void setTileTypes(Resources resources) {
resetTileTypes(4);
//TODO: if update > 21 change to (resource, null) get drawable calls.
setTileType(RED_BLOCK, resources.getDrawable(R.drawable.redblock));
setTileType(BLUE_BLOCK, resources.getDrawable(R.drawable.greenblock));
setTileType(GREEN_BLOCK, resources.getDrawable(R.drawable.blueblock));
}
private void constructorDelegate(Context context) {
setFocusable(true);
Resources resources = this.getContext().getResources();
setTileTypes(resources);
}
public GrideousView(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
constructorDelegate(context);
}
public GrideousView(Context context, AttributeSet attributeSet, int defStyle) {
super(context, attributeSet, defStyle);
}
public void resumeGame() {
setMode(Mode.RUNNING);
update();
}
public void initializeGame() {
initializeGameData();
resumeGame();
}
public void setDependentViews(TextView textView, View arrowsView, View backgroundView) {
this.statusView = textView;
this.arrowsView = arrowsView;
this.backgroundView = backgroundView;
}
public void setMode(Mode mode) {
Mode oldMode = this.currentMode;
this.currentMode = mode;
if(mode == Mode.RUNNING && oldMode != Mode.RUNNING) {
statusView.setVisibility(View.INVISIBLE);
arrowsView.setVisibility(View.VISIBLE);
backgroundView.setVisibility(View.VISIBLE);
return;
}
Resources resources = getContext().getResources();
CharSequence string = "";
switch(mode) {
case RUNNING:
return;
case PAUSED:
string = resources.getText(R.string.mode_paused);
break;
case READY:
string = resources.getText(R.string.mode_ready);
break;
case LOSING:
string = resources.getString(R.string.mode_losing, score);
break;
}
arrowsView.setVisibility(View.GONE);
backgroundView.setVisibility(View.GONE);
statusView.setText(string);
statusView.setVisibility(View.VISIBLE);
}
public Mode getCurrentMode() {
return this.currentMode;
}
public void moveCurrentBlock(Direction direction) {
nextDirection = direction;
}
public void update(){
if(currentMode == Mode.RUNNING) {
long currentTime = System.currentTimeMillis();
if(currentTime - lastMove > moveDelay) {
performUpdate();
lastMove = currentTime;
}
refreshHandler.sleep(moveDelay);
}
}
private void performUpdate() {
clearGrid();
runGameTick();
drawComponents();
}
public static Block generateBlock( Point maxPosition) {
Block block = new Block();
int blockType = 1 + RNG.nextInt(2);
//generate up to 3 block vertically/horizontally
Point center = new Point(
(int) Math.floor(maxPosition.x/2),
(int) Math.floor(maxPosition.y/2));
for(int x = -1; x < 2; x++) {
for(int y = -1; y < 2; y++) {
boolean generateBlock = RNG.nextBoolean();
if(generateBlock) {
Point part = new Point(
center.x + x,
center.y + y
);
block.parts.add(part);
}
}
}
if(block.parts.size() == 0) {
block.parts.add(center);
}
return block;
}
private void runGameTick() {
if(currentBlock == null) {
currentBlock = generateCurrentBlock();
}
doRubbleClearing();
if(shiftRubble == 0) {
shiftRubbleInDirection();
shiftRubble = 10;
}
shiftRubble--;
currentDirection = nextDirection;
Block nextPosition = generateNextCurrentBlockPosition();
if(blockCollidesWithWall(nextPosition)||blockCollidesWithRubble(nextPosition)) {
setCurrentBlockToRubble();
Block newCurrentBlock = generateCurrentBlock();
if(newCurrentBlock == null) {
setMode(Mode.LOSING);
} else {
this.currentBlock = newCurrentBlock;
}
} else {
currentBlock = nextPosition;
}
}
private void shiftRubbleInDirection() {
int xShift = 0;
int yShift = 0;
switch(currentDirection) {
case RIGHT:
xShift = 1;
for(int x = xTileCount -1; x >= 0; x--) {
for(int y = 0; y < yTileCount; y++) {
shiftSingleRubble(
new Point(xShift, yShift),
new Point(x,y)
);
}
}
break;
case LEFT:
xShift = -1;
for(int x = 0; x < xTileCount; x++) {
for(int y = 0; y < yTileCount; y++) {
shiftSingleRubble(
new Point(xShift, yShift),
new Point(x,y)
);
}
}
break;
case UP:
yShift = -1;
for(int y = 0; y < yTileCount; y++) {
for(int x = 0; x < xTileCount; x++) {
shiftSingleRubble(
new Point(xShift, yShift),
new Point(x,y)
);
}
}
break;
case DOWN:
yShift = 1;
for(int y = yTileCount -1; y >= 0; y--) {
for(int x = 0; x < xTileCount; x++) {
shiftSingleRubble(
new Point(xShift, yShift),
new Point(x,y)
);
}
}
break;
}
}
private void shiftSingleRubble(Point shift, Point point) {
//check the position below each rock to see if it is valid.
if(!rubble[point.x][point.y]) {
return;
}
int newX = point.x + shift.x;
int newY = point.y + shift.y;
Point newPoint = new Point(newX, newY);
if(pointCollidesWithWall(newPoint) || rubble[newX][newY]) {
return;
}
rubble[point.x][point.y] = false;
rubble[newX][newY] = true;
}
private Block generateCurrentBlock() {
Block newCurrentBlock = generateBlock(new Point(xTileCount, yTileCount));
if(blockCollidesWithRubble(newCurrentBlock)) {
return null;
}
return newCurrentBlock;
}
private void setCurrentBlockToRubble() {
for(Point part : currentBlock.parts) {
rubble[part.x][part.y] = true;
}
}
private void doRubbleClearing() {
doRowRubbleClearing();
doColumnRubbleClearing();
}
private void doRowRubbleClearing() {
for(int y = 1; y < yTileCount-1; y++) {
boolean rowFilled = true;
for(int x = 1; x < xTileCount-1; x++) {
if(!rubble[x][y]) {
rowFilled = false;
break;
}
}
if(rowFilled) {
for(int x = 1; x < xTileCount-1; x++) {
rubble[x][y] = false;
}
handleScoreUp();
}
}
}
private void doColumnRubbleClearing() {
for(int x = 1; x < yTileCount-1; x++) {
boolean columnFilled = true;
for(int y = 1; y < xTileCount-1; y++) {
columnFilled = false;
break;
}
if(columnFilled) {
for(int y = 1; y < yTileCount-1; y++) {
rubble[x][y] = false;
}
handleScoreUp();
}
}
}
private void drawComponents() {
drawWalls();
drawRubble();
drawCurrentBlock();
}
private void drawWalls(){
for(int x = 0; x < xTileCount; x++) {
setGridTile(GREEN_BLOCK, x, 0);
setGridTile(GREEN_BLOCK, x, yTileCount - 1);
}
for(int y = 0; y < yTileCount; y++){
setGridTile(GREEN_BLOCK, 0, y);
setGridTile(GREEN_BLOCK, xTileCount -1, y);
}
}
private void drawCurrentBlock() {
for(Point parts : currentBlock.parts) {
setGridTile(RED_BLOCK, parts.x, parts.y);
}
}
private void drawRubble() {
for(int x = 0; x < xTileCount; x++) {
for(int y = 0; y < yTileCount; y++) {
if(rubble[x][y]) {
setGridTile(BLUE_BLOCK, x,y);
}
}
}
}
private Point generateNextBlockPartPosition(Point point) {
switch(currentDirection) {
case UP:
return new Point(point.x, point.y - 1);
case DOWN:
return new Point(point.x, point.y + 1);
case LEFT:
return new Point(point.x - 1, point.y);
case RIGHT:
return new Point(point.x + 1, point.y);
default:
return point;
}
}
private Block generateNextCurrentBlockPosition() {
Block block = new Block();
for(Point part : currentBlock.parts) {
Point newPart = generateNextBlockPartPosition(part);
block.parts.add(newPart);
}
return block;
}
private boolean blockCollidesWithWall(Block block) {
for(Point part : block.parts) {
if(pointCollidesWithWall(part)) {
return true;
}
}
return false;
}
private boolean pointCollidesWithWall(Point point) {
boolean pointCollidesWithWall = false;
pointCollidesWithWall = pointCollidesWithWall || point.x < 1;
pointCollidesWithWall = pointCollidesWithWall || point.y < 1;
pointCollidesWithWall = pointCollidesWithWall || point.x > xTileCount - 2;
pointCollidesWithWall = pointCollidesWithWall || point.y > yTileCount - 2;
return pointCollidesWithWall;
}
private boolean blockCollidesWithRubble(Block block) {
for(Point part : block.parts) {
if(rubble[part.x][part.y]) {
return true;
}
}
return false;
}
private void handleScoreUp() {
score++;
moveDelay *= 0.9;
}
private void initializeGameData() {
rubble = new boolean[xTileCount][yTileCount];
moveDelay = 600;
score = 0;
}
@Override
public void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
this.rubble = new boolean[xTileCount][yTileCount];
}
}
| 30.004577 | 97 | 0.527608 |
dba08548db50205328f75a8678f9d408fa7e3f62 | 789 | package com.eshop.cart.entity;
import java.util.HashMap;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "cart")
public class Cart
{
@Id
private String cartId;
private HashMap<String, Long> productsInCart;
private String cartStatus;
public String getCartId() {
return cartId;
}
public void setCartId(String cartId) {
this.cartId = cartId;
}
public HashMap<String, Long> getProductsInCart() {
return productsInCart;
}
public void setProductsInCart(HashMap<String, Long> productsInCart) {
this.productsInCart = productsInCart;
}
public String getCartStatus() {
return cartStatus;
}
public void setCartStatus(String cartStatus) {
this.cartStatus = cartStatus;
}
}
| 19.725 | 70 | 0.751584 |
aebef97eaf6acf9c1cb00113d0a8539a7d563726 | 2,505 | package com.ruoyi.system.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.system.mapper.HyMaintenanceunitMapper;
import com.ruoyi.system.domain.HyMaintenanceunit;
import com.ruoyi.system.service.IHyMaintenanceunitService;
import com.ruoyi.common.core.text.Convert;
/**
* 保养单位Service业务层处理
*
* @author Administrator
* @date 2021-05-11
*/
@Service
public class HyMaintenanceunitServiceImpl implements IHyMaintenanceunitService
{
@Autowired
private HyMaintenanceunitMapper hyMaintenanceunitMapper;
/**
* 查询保养单位
*
* @param id 保养单位ID
* @return 保养单位
*/
@Override
public HyMaintenanceunit selectHyMaintenanceunitById(Long id)
{
return hyMaintenanceunitMapper.selectHyMaintenanceunitById(id);
}
/**
* 查询保养单位列表
*
* @param hyMaintenanceunit 保养单位
* @return 保养单位
*/
@Override
public List<HyMaintenanceunit> selectHyMaintenanceunitList(HyMaintenanceunit hyMaintenanceunit)
{
return hyMaintenanceunitMapper.selectHyMaintenanceunitList(hyMaintenanceunit);
}
/**
* 新增保养单位
*
* @param hyMaintenanceunit 保养单位
* @return 结果
*/
@Transactional(rollbackFor = Exception.class)
@Override
public int insertHyMaintenanceunit(HyMaintenanceunit hyMaintenanceunit)
{
return hyMaintenanceunitMapper.insertHyMaintenanceunit(hyMaintenanceunit);
}
/**
* 修改保养单位
*
* @param hyMaintenanceunit 保养单位
* @return 结果
*/
@Transactional(rollbackFor = Exception.class)
@Override
public int updateHyMaintenanceunit(HyMaintenanceunit hyMaintenanceunit)
{
return hyMaintenanceunitMapper.updateHyMaintenanceunit(hyMaintenanceunit);
}
/**
* 删除保养单位对象
*
* @param ids 需要删除的数据ID
* @return 结果
*/
@Transactional(rollbackFor = Exception.class)
@Override
public int deleteHyMaintenanceunitByIds(String ids)
{
return hyMaintenanceunitMapper.deleteHyMaintenanceunitByIds(Convert.toStrArray(ids));
}
/**
* 删除保养单位信息
*
* @param id 保养单位ID
* @return 结果
*/
@Transactional(rollbackFor = Exception.class)
@Override
public int deleteHyMaintenanceunitById(Long id)
{
return hyMaintenanceunitMapper.deleteHyMaintenanceunitById(id);
}
}
| 25.05 | 99 | 0.700998 |
6982400b66b8df54c474dcd0cb97de7a387efdef | 3,330 | /*
* The MIT License (MIT)
*
* Copyright (c) 2021 Roger L. Whitcomb.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Simple command-line utility to check if the (one) argument is a directory or not.
*
* Change History:
* 27-Dec-2021 (rlwhitcomb)
* Coding.
*/
package info.rlwhitcomb.tools;
import java.io.File;
import info.rlwhitcomb.util.ExceptionUtil;
/**
* Test if the given (one) argument is a directory or not.
* <p>Process exit code is:
* <ul>
* <li>0 (Success) if the path IS a directory</li>
* <li>1 (Error) if the path is something else (regular file, pipe, etc.)</li>
* <li>2 (also Error) if there is no argument given</li>
* <li>or 3 (Error) if the path is non-existent as it was spelled (typo?)</li>
* </ul>
*/
public class IsDir
{
private static final int NOT_DIRECTORY = 1;
private static final int ARG_ERROR = 2;
private static final int PATH_NOT_EXIST = 3;
private static final String[] HELP = {
"",
"Usage: isdir _path_",
"",
" Exit code will be 0 if the given _path_ really exists and is a directory",
" 1 if the _path_ is some other kind of file",
" 2 if there were either none or too many arguments given",
" 3 if the _path_ does not exist as typed",
""
};
private static final void usage() {
for (String help : HELP) {
System.err.println(help);
}
}
/**
* Input is a single file path. The program will set the process exit code (test with {@code ERRORLEVEL}
* on Windows or {@code $?} on other O/Ses).
*
* @param args The parsed command line argument array, which should have one path values.
*/
public static void main(String[] args) {
if (args.length == 0) {
System.err.println("Error: one path name is required!");
usage();
System.exit(ARG_ERROR);
}
else if (args.length > 1) {
System.err.println("Error: too many arguments given!");
usage();
System.exit(ARG_ERROR);
}
String arg = args[0];
File f = new File(arg);
if (f.exists()) {
if (f.isDirectory()) {
return;
}
else {
System.exit(NOT_DIRECTORY);
}
}
else {
System.err.format("Cannot find the requested path: \"%1$s\"!%n", arg);
System.exit(PATH_NOT_EXIST);
}
}
}
| 31.714286 | 106 | 0.663664 |
e09647a883655782308e8ebc7eb8447158ac7e68 | 542 | package GFG.Dynamic;
import java.util.HashMap;
class Solution {
HashMap<Integer,Integer>memo=null;
Solution(){
this.memo=new HashMap<Integer,Integer>();
}
public int fib(int n) {
if(memo.containsKey(n)){
return memo.get(n);
}
else if(n==2 ||n==1) return 1;
else if(n==0) return 0;
else{
memo.put(n,(fib(n-1)+fib(n-2)));
}
return memo.get(n);
}
}
public class Fibonacci{
public static void main(String[] args){
}
} | 20.074074 | 49 | 0.527675 |
64bb2308bfbb3fe11ac045f6d307d9c9619501ef | 4,438 | package com.thestudygroup.celebrityquiz.adapter;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.thestudygroup.celebrityquiz.R;
import com.thestudygroup.celebrityquiz.vo.QuestionVO;
import java.util.List;
import java.util.Objects;
public class SolutionAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>
{
private final List<QuestionVO> questions;
public SolutionAdapter(@NonNull final List<QuestionVO> questions) {
this.questions = questions;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull final ViewGroup viewGroup, int viewType) {
final LayoutInflater inflater = (LayoutInflater) viewGroup.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View view = inflater.inflate(R.layout.item_solution, viewGroup, false);
return new RecyclerView.ViewHolder(view) {};
}
@Override
public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder viewHolder, final int position) {
if (questions.isEmpty()) {
return;
}
final TextView viewQuestion = viewHolder.itemView.findViewById(R.id.item_sol_text_content);
final ImageView imageView = viewHolder.itemView.findViewById(R.id.item_sol_image);
final RadioGroup radioGroup = viewHolder.itemView.findViewById(R.id.item_sol_radio_group);
final RadioButton radioButton1 = viewHolder.itemView.findViewById(R.id.item_sol_radio1);
final RadioButton radioButton2 = viewHolder.itemView.findViewById(R.id.item_sol_radio2);
final RadioButton radioButton3 = viewHolder.itemView.findViewById(R.id.item_sol_radio3);
final RadioButton radioButton4 = viewHolder.itemView.findViewById(R.id.item_sol_radio4);
final EditText textAnswer = viewHolder.itemView.findViewById(R.id.item_sol_answer_right);
final EditText textUser = viewHolder.itemView.findViewById(R.id.item_sol_answer_user);
final QuestionVO quiz = questions.get(position);
viewQuestion.setText(String.format("%s. %s", position + 1, quiz.question));
Glide.with(imageView.getContext()).load(quiz.imageUrl).into(imageView);
if (quiz.correctAnswer != 0) {
textAnswer.setVisibility(View.GONE);
textUser.setVisibility(View.GONE);
radioButton1.setText(quiz.one);
radioButton2.setText(quiz.two);
radioButton3.setText(quiz.three);
radioButton4.setText(quiz.four);
RadioButton r = null;
if (quiz.correctAnswer == 1) r = radioButton1;
if (quiz.correctAnswer == 2) r = radioButton2;
if (quiz.correctAnswer == 3) r = radioButton3;
if (quiz.correctAnswer == 4) r = radioButton4;
if (r == null) return;
r.setTextColor(Color.parseColor("#FF0BA512"));
if (quiz.userAnswer == quiz.correctAnswer) {
r.setChecked(true);
} else {
RadioButton u = null;
if (quiz.userAnswer == 1) u = radioButton1;
if (quiz.userAnswer == 2) u = radioButton2;
if (quiz.userAnswer == 3) u = radioButton3;
if (quiz.userAnswer == 4) u = radioButton4;
if (u != null) {
u.setChecked(true);
u.setTextColor(Color.RED);
}
}
} else {
radioGroup.setVisibility(View.GONE);
textAnswer.setTextColor(Color.parseColor("#FF0BA512"));
textUser.setTextColor(Color.RED);
textAnswer.setText(quiz.one);
textUser.setText(quiz.two);
if (Objects.equals(quiz.one.toLowerCase(), quiz.two.toLowerCase())) {
textUser.setVisibility(View.GONE);
}
}
}
@Override
public int getItemCount() {
return questions.size();
}
@Override
public int getItemViewType(int position) {
return position;
}
}
| 39.981982 | 130 | 0.661334 |
5041b9d0c599f74732ef24f909fe9b1dfe851c3e | 16,662 | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|ws
operator|.
name|rm
package|;
end_package
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|ArrayList
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Collection
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|Bus
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|binding
operator|.
name|Binding
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|endpoint
operator|.
name|Endpoint
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|interceptor
operator|.
name|Fault
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|message
operator|.
name|Exchange
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|message
operator|.
name|Message
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|phase
operator|.
name|Phase
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|ws
operator|.
name|policy
operator|.
name|AssertionInfo
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|ws
operator|.
name|policy
operator|.
name|AssertionInfoMap
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|cxf
operator|.
name|ws
operator|.
name|policy
operator|.
name|PolicyAssertion
import|;
end_import
begin_import
import|import
name|org
operator|.
name|easymock
operator|.
name|EasyMock
import|;
end_import
begin_import
import|import
name|org
operator|.
name|easymock
operator|.
name|IMocksControl
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|After
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|Before
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|Test
import|;
end_import
begin_import
import|import static
name|org
operator|.
name|junit
operator|.
name|Assert
operator|.
name|assertEquals
import|;
end_import
begin_import
import|import static
name|org
operator|.
name|junit
operator|.
name|Assert
operator|.
name|assertFalse
import|;
end_import
begin_import
import|import static
name|org
operator|.
name|junit
operator|.
name|Assert
operator|.
name|assertNull
import|;
end_import
begin_import
import|import static
name|org
operator|.
name|junit
operator|.
name|Assert
operator|.
name|assertSame
import|;
end_import
begin_import
import|import static
name|org
operator|.
name|junit
operator|.
name|Assert
operator|.
name|fail
import|;
end_import
begin_comment
comment|/** * */
end_comment
begin_class
specifier|public
class|class
name|AbstractRMInterceptorTest
block|{
specifier|private
name|IMocksControl
name|control
decl_stmt|;
annotation|@
name|Before
specifier|public
name|void
name|setUp
parameter_list|()
block|{
name|control
operator|=
name|EasyMock
operator|.
name|createNiceControl
argument_list|()
expr_stmt|;
block|}
annotation|@
name|After
specifier|public
name|void
name|tearDown
parameter_list|()
block|{
name|control
operator|.
name|verify
argument_list|()
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testAccessors
parameter_list|()
block|{
name|RMInterceptor
name|interceptor
init|=
operator|new
name|RMInterceptor
argument_list|()
decl_stmt|;
name|assertEquals
argument_list|(
name|Phase
operator|.
name|PRE_LOGICAL
argument_list|,
name|interceptor
operator|.
name|getPhase
argument_list|()
argument_list|)
expr_stmt|;
name|Bus
name|bus
init|=
name|control
operator|.
name|createMock
argument_list|(
name|Bus
operator|.
name|class
argument_list|)
decl_stmt|;
name|RMManager
name|busMgr
init|=
name|control
operator|.
name|createMock
argument_list|(
name|RMManager
operator|.
name|class
argument_list|)
decl_stmt|;
name|EasyMock
operator|.
name|expect
argument_list|(
name|bus
operator|.
name|getExtension
argument_list|(
name|RMManager
operator|.
name|class
argument_list|)
argument_list|)
operator|.
name|andReturn
argument_list|(
name|busMgr
argument_list|)
expr_stmt|;
name|RMManager
name|mgr
init|=
name|control
operator|.
name|createMock
argument_list|(
name|RMManager
operator|.
name|class
argument_list|)
decl_stmt|;
name|control
operator|.
name|replay
argument_list|()
expr_stmt|;
name|assertNull
argument_list|(
name|interceptor
operator|.
name|getBus
argument_list|()
argument_list|)
expr_stmt|;
name|interceptor
operator|.
name|setBus
argument_list|(
name|bus
argument_list|)
expr_stmt|;
name|assertSame
argument_list|(
name|bus
argument_list|,
name|interceptor
operator|.
name|getBus
argument_list|()
argument_list|)
expr_stmt|;
name|assertSame
argument_list|(
name|busMgr
argument_list|,
name|interceptor
operator|.
name|getManager
argument_list|()
argument_list|)
expr_stmt|;
name|interceptor
operator|.
name|setManager
argument_list|(
name|mgr
argument_list|)
expr_stmt|;
name|assertSame
argument_list|(
name|mgr
argument_list|,
name|interceptor
operator|.
name|getManager
argument_list|()
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testHandleMessageSequenceFaultNoBinding
parameter_list|()
block|{
name|RMInterceptor
name|interceptor
init|=
operator|new
name|RMInterceptor
argument_list|()
decl_stmt|;
name|Message
name|message
init|=
name|control
operator|.
name|createMock
argument_list|(
name|Message
operator|.
name|class
argument_list|)
decl_stmt|;
name|SequenceFault
name|sf
init|=
name|control
operator|.
name|createMock
argument_list|(
name|SequenceFault
operator|.
name|class
argument_list|)
decl_stmt|;
name|interceptor
operator|.
name|setSequenceFault
argument_list|(
name|sf
argument_list|)
expr_stmt|;
name|Exchange
name|ex
init|=
name|control
operator|.
name|createMock
argument_list|(
name|Exchange
operator|.
name|class
argument_list|)
decl_stmt|;
name|EasyMock
operator|.
name|expect
argument_list|(
name|message
operator|.
name|getExchange
argument_list|()
argument_list|)
operator|.
name|andReturn
argument_list|(
name|ex
argument_list|)
operator|.
name|anyTimes
argument_list|()
expr_stmt|;
name|Endpoint
name|e
init|=
name|control
operator|.
name|createMock
argument_list|(
name|Endpoint
operator|.
name|class
argument_list|)
decl_stmt|;
name|EasyMock
operator|.
name|expect
argument_list|(
name|ex
operator|.
name|getEndpoint
argument_list|()
argument_list|)
operator|.
name|andReturn
argument_list|(
name|e
argument_list|)
expr_stmt|;
name|EasyMock
operator|.
name|expect
argument_list|(
name|e
operator|.
name|getBinding
argument_list|()
argument_list|)
operator|.
name|andReturn
argument_list|(
literal|null
argument_list|)
expr_stmt|;
name|control
operator|.
name|replay
argument_list|()
expr_stmt|;
try|try
block|{
name|interceptor
operator|.
name|handleMessage
argument_list|(
name|message
argument_list|)
expr_stmt|;
name|fail
argument_list|(
literal|"Expected Fault not thrown."
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|Fault
name|f
parameter_list|)
block|{
name|assertSame
argument_list|(
name|sf
argument_list|,
name|f
operator|.
name|getCause
argument_list|()
argument_list|)
expr_stmt|;
block|}
block|}
annotation|@
name|Test
specifier|public
name|void
name|testHandleMessageSequenceFault
parameter_list|()
block|{
name|RMInterceptor
name|interceptor
init|=
operator|new
name|RMInterceptor
argument_list|()
decl_stmt|;
name|Message
name|message
init|=
name|control
operator|.
name|createMock
argument_list|(
name|Message
operator|.
name|class
argument_list|)
decl_stmt|;
name|SequenceFault
name|sf
init|=
name|control
operator|.
name|createMock
argument_list|(
name|SequenceFault
operator|.
name|class
argument_list|)
decl_stmt|;
name|interceptor
operator|.
name|setSequenceFault
argument_list|(
name|sf
argument_list|)
expr_stmt|;
name|Exchange
name|ex
init|=
name|control
operator|.
name|createMock
argument_list|(
name|Exchange
operator|.
name|class
argument_list|)
decl_stmt|;
name|EasyMock
operator|.
name|expect
argument_list|(
name|message
operator|.
name|getExchange
argument_list|()
argument_list|)
operator|.
name|andReturn
argument_list|(
name|ex
argument_list|)
operator|.
name|anyTimes
argument_list|()
expr_stmt|;
name|Endpoint
name|e
init|=
name|control
operator|.
name|createMock
argument_list|(
name|Endpoint
operator|.
name|class
argument_list|)
decl_stmt|;
name|EasyMock
operator|.
name|expect
argument_list|(
name|ex
operator|.
name|getEndpoint
argument_list|()
argument_list|)
operator|.
name|andReturn
argument_list|(
name|e
argument_list|)
expr_stmt|;
name|Binding
name|b
init|=
name|control
operator|.
name|createMock
argument_list|(
name|Binding
operator|.
name|class
argument_list|)
decl_stmt|;
name|EasyMock
operator|.
name|expect
argument_list|(
name|e
operator|.
name|getBinding
argument_list|()
argument_list|)
operator|.
name|andReturn
argument_list|(
name|b
argument_list|)
expr_stmt|;
name|RMManager
name|mgr
init|=
name|control
operator|.
name|createMock
argument_list|(
name|RMManager
operator|.
name|class
argument_list|)
decl_stmt|;
name|interceptor
operator|.
name|setManager
argument_list|(
name|mgr
argument_list|)
expr_stmt|;
name|BindingFaultFactory
name|bff
init|=
name|control
operator|.
name|createMock
argument_list|(
name|BindingFaultFactory
operator|.
name|class
argument_list|)
decl_stmt|;
name|EasyMock
operator|.
name|expect
argument_list|(
name|mgr
operator|.
name|getBindingFaultFactory
argument_list|(
name|b
argument_list|)
argument_list|)
operator|.
name|andReturn
argument_list|(
name|bff
argument_list|)
expr_stmt|;
name|Fault
name|fault
init|=
name|control
operator|.
name|createMock
argument_list|(
name|Fault
operator|.
name|class
argument_list|)
decl_stmt|;
name|EasyMock
operator|.
name|expect
argument_list|(
name|bff
operator|.
name|createFault
argument_list|(
name|sf
argument_list|,
name|message
argument_list|)
argument_list|)
operator|.
name|andReturn
argument_list|(
name|fault
argument_list|)
expr_stmt|;
name|EasyMock
operator|.
name|expect
argument_list|(
name|bff
operator|.
name|toString
argument_list|(
name|fault
argument_list|)
argument_list|)
operator|.
name|andReturn
argument_list|(
literal|"f"
argument_list|)
expr_stmt|;
name|control
operator|.
name|replay
argument_list|()
expr_stmt|;
try|try
block|{
name|interceptor
operator|.
name|handleMessage
argument_list|(
name|message
argument_list|)
expr_stmt|;
name|fail
argument_list|(
literal|"Expected Fault not thrown."
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|Fault
name|f
parameter_list|)
block|{
name|assertSame
argument_list|(
name|f
argument_list|,
name|fault
argument_list|)
expr_stmt|;
block|}
block|}
annotation|@
name|Test
specifier|public
name|void
name|testHandleMessageRMException
parameter_list|()
block|{
name|RMInterceptor
name|interceptor
init|=
operator|new
name|RMInterceptor
argument_list|()
decl_stmt|;
name|Message
name|message
init|=
name|control
operator|.
name|createMock
argument_list|(
name|Message
operator|.
name|class
argument_list|)
decl_stmt|;
name|RMException
name|rme
init|=
name|control
operator|.
name|createMock
argument_list|(
name|RMException
operator|.
name|class
argument_list|)
decl_stmt|;
name|interceptor
operator|.
name|setRMException
argument_list|(
name|rme
argument_list|)
expr_stmt|;
name|control
operator|.
name|replay
argument_list|()
expr_stmt|;
try|try
block|{
name|interceptor
operator|.
name|handleMessage
argument_list|(
name|message
argument_list|)
expr_stmt|;
name|fail
argument_list|(
literal|"Expected Fault not thrown."
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|Fault
name|f
parameter_list|)
block|{
name|assertSame
argument_list|(
name|rme
argument_list|,
name|f
operator|.
name|getCause
argument_list|()
argument_list|)
expr_stmt|;
block|}
block|}
annotation|@
name|Test
specifier|public
name|void
name|testAssertReliability
parameter_list|()
block|{
name|RMInterceptor
name|interceptor
init|=
operator|new
name|RMInterceptor
argument_list|()
decl_stmt|;
name|Message
name|message
init|=
name|control
operator|.
name|createMock
argument_list|(
name|Message
operator|.
name|class
argument_list|)
decl_stmt|;
name|EasyMock
operator|.
name|expect
argument_list|(
name|message
operator|.
name|get
argument_list|(
name|AssertionInfoMap
operator|.
name|class
argument_list|)
argument_list|)
operator|.
name|andReturn
argument_list|(
literal|null
argument_list|)
expr_stmt|;
name|AssertionInfoMap
name|aim
init|=
name|control
operator|.
name|createMock
argument_list|(
name|AssertionInfoMap
operator|.
name|class
argument_list|)
decl_stmt|;
name|Collection
argument_list|<
name|AssertionInfo
argument_list|>
name|ais
init|=
operator|new
name|ArrayList
argument_list|<>
argument_list|()
decl_stmt|;
name|EasyMock
operator|.
name|expect
argument_list|(
name|message
operator|.
name|get
argument_list|(
name|AssertionInfoMap
operator|.
name|class
argument_list|)
argument_list|)
operator|.
name|andReturn
argument_list|(
name|aim
argument_list|)
operator|.
name|times
argument_list|(
literal|2
argument_list|)
expr_stmt|;
name|PolicyAssertion
name|a
init|=
name|control
operator|.
name|createMock
argument_list|(
name|PolicyAssertion
operator|.
name|class
argument_list|)
decl_stmt|;
name|AssertionInfo
name|ai
init|=
operator|new
name|AssertionInfo
argument_list|(
name|a
argument_list|)
decl_stmt|;
name|EasyMock
operator|.
name|expectLastCall
argument_list|()
expr_stmt|;
name|control
operator|.
name|replay
argument_list|()
expr_stmt|;
name|interceptor
operator|.
name|assertReliability
argument_list|(
name|message
argument_list|)
expr_stmt|;
name|assertFalse
argument_list|(
name|ai
operator|.
name|isAsserted
argument_list|()
argument_list|)
expr_stmt|;
name|aim
operator|.
name|put
argument_list|(
name|RM10Constants
operator|.
name|RMASSERTION_QNAME
argument_list|,
name|ais
argument_list|)
expr_stmt|;
name|interceptor
operator|.
name|assertReliability
argument_list|(
name|message
argument_list|)
expr_stmt|;
name|assertFalse
argument_list|(
name|ai
operator|.
name|isAsserted
argument_list|()
argument_list|)
expr_stmt|;
name|ais
operator|.
name|add
argument_list|(
name|ai
argument_list|)
expr_stmt|;
name|interceptor
operator|.
name|assertReliability
argument_list|(
name|message
argument_list|)
expr_stmt|;
block|}
class|class
name|RMInterceptor
extends|extends
name|AbstractRMInterceptor
argument_list|<
name|Message
argument_list|>
block|{
specifier|private
name|SequenceFault
name|sequenceFault
decl_stmt|;
specifier|private
name|RMException
name|rmException
decl_stmt|;
name|void
name|setSequenceFault
parameter_list|(
name|SequenceFault
name|sf
parameter_list|)
block|{
name|sequenceFault
operator|=
name|sf
expr_stmt|;
block|}
name|void
name|setRMException
parameter_list|(
name|RMException
name|rme
parameter_list|)
block|{
name|rmException
operator|=
name|rme
expr_stmt|;
block|}
annotation|@
name|Override
specifier|protected
name|void
name|handle
parameter_list|(
name|Message
name|msg
parameter_list|)
throws|throws
name|SequenceFault
throws|,
name|RMException
block|{
if|if
condition|(
literal|null
operator|!=
name|sequenceFault
condition|)
block|{
throw|throw
name|sequenceFault
throw|;
block|}
elseif|else
if|if
condition|(
literal|null
operator|!=
name|rmException
condition|)
block|{
throw|throw
name|rmException
throw|;
block|}
block|}
block|}
block|}
end_class
end_unit
| 13.491498 | 810 | 0.803745 |
f9213ff962380cc94447831af27e4b0a623da99c | 2,722 | package org.pipecraft.infra.io;
/**
* Encapsulates file writing settings, with defaults.
*
* @author Eyal Schneider
*/
public class FileWriteOptions {
private boolean isAppend = false;
private int bufferSize = 8192;
private Compression compression = Compression.NONE;
private int compressionLevel;
private boolean isTemp = false;
/**
* Sets the append flag (by default it's false)
* @return this instance
*/
public FileWriteOptions append() {
this.isAppend = true;
return this;
}
/**
* @return The compression
*/
public Compression getCompression() {
return compression;
}
/**
* @return The compression level to use, if compression is set. Specific to the selected compression algorithm.
*/
public int getCompressionLevel() {
return compressionLevel;
}
/**
* Sets the compression of the file
*
* @param compression the compression of the file
* @return the file write options
*/
public FileWriteOptions setCompression(Compression compression) {
setCompression(compression, compression.getDefaultCompressionLevel());
return this;
}
/**
* Sets the compression of the file
*
* @param compression the compression of the file
* @return the file write options
*/
public FileWriteOptions setCompression(Compression compression, int compressionLevel) {
this.compression = compression;
this.compressionLevel = compressionLevel;
return this;
}
/**
* Sets the buffer size (default = 8192)
* @param bufferSize The write buffer size, in bytes
* @return this instance
*/
public FileWriteOptions buffer(int bufferSize) {
this.bufferSize = bufferSize;
return this;
}
/**
* Sets the file to be temporary, meaning that it will be deleted once the JVM exits gracefully (by default it's false)
* @return this instance
*/
public FileWriteOptions temp() {
this.isTemp = true;
return this;
}
/**
* if true, sets compression the flag on file write options.
*
* @param temp True for temporary file, false for otherwise. Temporary files are deleted at graceful JVM shutdown.
* @return the file write options
*/
public FileWriteOptions temp(boolean temp) {
this.isTemp = temp;
return this;
}
/**
* @return True for appending to an existing file, false for overriding
*/
public boolean isAppend() {
return isAppend;
}
/**
* @return The write buffer size, in bytes
*/
public int getBufferSize() {
return bufferSize;
}
/**
* @return True for temporary file, false for otherwise. Temporary files are deleted at graceful JVM shutdown.
*/
public boolean isTemp() {
return isTemp;
}
}
| 24.303571 | 121 | 0.682586 |
b6468514d55edc88908b679763808f13c8c67b6c | 2,389 | package code.elif.controller;
import code.elif.model.TodoData;
import code.elif.model.TodoItem;
import code.elif.service.TodoService;
import code.elif.util.AttributeNames;
import code.elif.util.Mappings;
import code.elif.util.Views;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.time.LocalDate;
@Slf4j
@Controller
public class TodoItemController {
private final TodoService todoService;
@Autowired
public TodoItemController(TodoService todoService) {
this.todoService = todoService;
}
@ModelAttribute
public TodoData todoData() {
return todoService.getData();
}
@GetMapping(Mappings.ITEMS)
public String items() {
return Views.ITEMS_LIST;
}
@GetMapping(Mappings.ITEM)
public String getItem(@RequestParam int id, Model model) {
TodoItem todoItem = todoService.getItem(id);
model.addAttribute(AttributeNames.TODO_ITEM, todoItem);
return Views.VIEW_ITEM;
}
@GetMapping(Mappings.ADD_ITEM)
public String addEditItem(@RequestParam(required = false,
defaultValue = "-1") int id, Model model) {
log.info("editing id : {}", id);
TodoItem todoItem = todoService.getItem(id);
if (todoItem == null) {
todoItem = new TodoItem("", "", LocalDate.now());
}
model.addAttribute(AttributeNames.TODO_ITEM, todoItem);
return Views.ADD_ITEMS;
}
@PostMapping(Mappings.ADD_ITEM)
public String processItem(@ModelAttribute(name = AttributeNames.TODO_ITEM) TodoItem todoItem) {
log.info("todoItem from form : {}", todoItem);
if (todoItem.getId() == 0) {
todoService.addItem(todoItem);
} else {
todoService.updateItem(todoItem);
}
return "redirect:/" + Mappings.ITEMS;
}
@GetMapping(Mappings.DELETE_ITEM)
public String deleteItem(@RequestParam int id){
todoService.removeItem(id);
return "redirect:/" + Mappings.ITEMS;
}
}
| 30.240506 | 99 | 0.696107 |
6da0bc31fd02dd710b8e171012e0501a0791b33b | 3,685 |
package com.android.example.templatechooser.ui.list;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModel;
import android.support.annotation.Nullable;
import android.support.annotation.VisibleForTesting;
import com.android.example.templatechooser.repository.DesignRepository;
import com.android.example.templatechooser.vo.Design;
import com.android.example.templatechooser.vo.Resource;
import java.util.List;
import javax.inject.Inject;
public class DesignsListViewModel extends ViewModel {
private LiveData<Resource<List<String>>> designUrls;
private DesignRepository designRepository;
@Inject
DesignsListViewModel(DesignRepository designRepository) {
this.designRepository = designRepository;
loadDesignUrls();
}
@VisibleForTesting
public LiveData<Resource<List<String>>> getDesignUrls() {
return designUrls;
}
@VisibleForTesting
public LiveData<Resource<Design>> getDesign(String designId) {
return designRepository.loadDesign(designId);
}
public void loadDesignUrls() {
designUrls = designRepository.getDesignUrls();
}
static class LoadMoreState {
private final boolean running;
private final String errorMessage;
private boolean handledError = false;
LoadMoreState(boolean running, String errorMessage) {
this.running = running;
this.errorMessage = errorMessage;
}
boolean isRunning() {
return running;
}
String getErrorMessage() {
return errorMessage;
}
String getErrorMessageIfNotHandled() {
if (handledError) {
return null;
}
handledError = true;
return errorMessage;
}
}
@VisibleForTesting
static class NextPageHandler implements Observer<Resource<Boolean>> {
@Nullable
private LiveData<Resource<Boolean>> nextPageLiveData;
private final MutableLiveData<LoadMoreState> loadMoreState = new MutableLiveData<>();
private final DesignRepository repository;
@VisibleForTesting
boolean hasMore;
@VisibleForTesting
NextPageHandler(DesignRepository repository) {
this.repository = repository;
reset();
}
@Override
public void onChanged(@Nullable Resource<Boolean> result) {
if (result == null) {
reset();
} else {
switch (result.status) {
case SUCCESS:
hasMore = Boolean.TRUE.equals(result.data);
unregister();
loadMoreState.setValue(new LoadMoreState(false, null));
break;
case ERROR:
hasMore = true;
unregister();
loadMoreState.setValue(new LoadMoreState(false,
result.message));
break;
}
}
}
private void unregister() {
if (nextPageLiveData != null) {
nextPageLiveData.removeObserver(this);
nextPageLiveData = null;
}
}
private void reset() {
unregister();
hasMore = true;
loadMoreState.setValue(new LoadMoreState(false, null));
}
MutableLiveData<LoadMoreState> getLoadMoreState() {
return loadMoreState;
}
}
}
| 29.246032 | 93 | 0.6 |
bd2bd0cd149d2062c2343534d84473bdccbde8e2 | 195 | package com.dragovorn.mccw.exceptions;
public class SchematicNotFoundException extends RuntimeException {
public SchematicNotFoundException(String message) {
super(message);
}
} | 24.375 | 66 | 0.769231 |
7c98435e3e7e9a22f1d35b49c18e3492a1024250 | 3,810 | package eu.diversify.ffbpg.evolution;
import eu.diversify.ffbpg.BPGraph;
import eu.diversify.ffbpg.Platform;
import eu.diversify.ffbpg.evolution.platforms.PlatformEvolutionOperator;
import eu.diversify.ffbpg.random.RandomUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;
/**
*
* @author ffl
*/
public abstract class PlatformServicesEvolutionScenario extends EvolutionScenario{
protected static Hashtable<String, PlatformServicesEvolutionScenario> prototypes = new Hashtable<String, PlatformServicesEvolutionScenario>();
protected static ArrayList<String> prototypes_names = new ArrayList<String>();
static {
PlatformServicesEvolutionScenario s;
s = new NoPlatformServicesEvolutionScenario(); prototypes.put(s.getName(), s);prototypes_names.add(s.getName());
s = new GuidedPlatformServicesEvolutionScenario(); prototypes.put(s.getName(), s);prototypes_names.add(s.getName());
s = new RandomPlatformServicesEvolutionScenario1(); prototypes.put(s.getName(), s);prototypes_names.add(s.getName());
s = new ChangePlatformServicesForPopularEvolutionScenario(); prototypes.put(s.getName(), s);prototypes_names.add(s.getName());
s = new ChangePlatformServicesForSpecializedEvolutionScenario(); prototypes.put(s.getName(), s);prototypes_names.add(s.getName());
s = new ChangePlatformServicesForPopularAndSpecializedEvolutionScenario(90); prototypes.put(s.getName(), s);prototypes_names.add(s.getName());
s = new ChangePlatformServicesForPopularAndSpecializedEvolutionScenario(75); prototypes.put(s.getName(), s);prototypes_names.add(s.getName());
s = new ChangePlatformServicesForPopularAndSpecializedEvolutionScenario(50); prototypes.put(s.getName(), s);prototypes_names.add(s.getName());
}
public static Object[] getAllScenarioNames() {
return prototypes_names.toArray();
}
public static PlatformServicesEvolutionScenario getScenarioByName(String name) {
return prototypes.get(name);
}
PlatformEvolutionOperator remove_srv_op;
PlatformEvolutionOperator add_srv_op;
String name;
public PlatformServicesEvolutionScenario(String name, PlatformEvolutionOperator remove_srv_op, PlatformEvolutionOperator add_srv_op) {
this.remove_srv_op = remove_srv_op;
this.add_srv_op = add_srv_op;
this.name = name;
}
public void step(BPGraph graph) {
List<Platform> plats = (ArrayList<Platform>)graph.getPlatforms().clone();
Collections.shuffle(plats, RandomUtils.getRandom());
//plats = plats.subList(0, plats.size()/10); // Only 1 of 10 platforms is evolved
int removed = 0;
int added = 0;
for(Platform p : plats) {
if (remove_srv_op.execute(graph, p)) {
removed++;
}
}
Collections.shuffle(plats, RandomUtils.getRandom());
// Add just as many links as has been removed
boolean finished = (removed == 0);
while (!finished) {
Collections.shuffle(plats, RandomUtils.getRandom());
for(Platform p : plats) {
if (add_srv_op.execute(graph, p)) {
added++;
if (added == removed) {
finished = true;
break;
}
}
}
}
System.out.println("Step complete removed services = " + removed + " added services = " + added);
}
@Override
public String getName() {
return name;
}
}
| 39.278351 | 154 | 0.644619 |
fa1ecf6eb134e0d683a73754366d489336013a1e | 510 | package no.nav.vedtak.felles.integrasjon.jms.precond;
import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
import org.junit.jupiter.api.Test;
public class AlwaysTruePreconditionCheckerTest {
@Test
public void test_isFulfilled() {
var checker = new AlwaysTruePreconditionChecker();
var checkerResult = checker.check();
assertThat(checkerResult.isFulfilled()).isTrue();
assertThat(checkerResult.getErrorMessage().isPresent()).isFalse();
}
}
| 28.333333 | 74 | 0.739216 |
880a6637b180c00a9e8e3596dbd342ed150fd029 | 911 | package com.dihanov.musiq.ui.detail.detail_fragments.detail_fragments_top_tracks;
import com.dihanov.musiq.interfaces.HorizontalBarChartGettable;
import com.dihanov.musiq.models.Artist;
import com.dihanov.musiq.ui.BasePresenter;
import com.dihanov.musiq.ui.BaseView;
import com.dihanov.musiq.ui.detail.ArtistDetails;
import com.github.mikephil.charting.charts.HorizontalBarChart;
/**
* Created by dimitar.dihanov on 2/26/2018.
*/
public interface ArtistSpecificsTopTracksContract {
interface View extends BaseView<ArtistSpecificsTopTracksContract.Presenter>, HorizontalBarChartGettable{
HorizontalBarChart getHorizontalBarChart();
ArtistDetails getDetailActivity();
}
interface Presenter extends BasePresenter<ArtistSpecificsTopTracksContract.View>{
void loadArtistTopTracks(ArtistSpecificsTopTracksContract.View view);
void setArtist(Artist artist);
}
}
| 33.740741 | 108 | 0.803513 |
dce57cf8c9afdd7a7a6a2c6f1befd05d4dd2917d | 1,948 | /*
* 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 com.iso.Users.Login;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author nevil
*/
@WebServlet(name = "Logout", urlPatterns = {"/Logout"})
public class Logout extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
response.setContentType("text/html");
String msg = "You are successfully logged out...!!!";
request.setAttribute("msg", msg);
request.getRequestDispatcher("index.jsp").include(request, response);
HttpSession session = request.getSession(false);
session.invalidate();
out.close();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
response.setContentType("text/html");
String msg = "You are successfully logged out...!!!";
request.setAttribute("msg", msg);
request.getRequestDispatcher("index.jsp").include(request, response);
HttpSession session = request.getSession(false);
session.invalidate();
out.close();
}
}
}
| 34.175439 | 83 | 0.662731 |
0e599f4c6f44ac165f73eb6044f4abecd21e91cd | 2,011 | package timus;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Timus_2002 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Map<String, String> users = new HashMap<>();
Map<String, Boolean> logging = new HashMap<>();
int n = sc.nextInt();
for (int i = 0; i <= n; i++) {
String line = sc.nextLine();
String[] strs = line.split(" ");
if (strs[0].equals("register")) {
if (users.containsKey(strs[1])) {
System.out.println("fail: user already exists");
} else {
users.put(strs[1], strs[2]);
logging.put(strs[1], false);
System.out.println("success: new user added");
}
} else if (strs[0].equals("login")) {
if (!users.containsKey(strs[1])) {
System.out.println("fail: no such user");
} else if (!users.get(strs[1]).equals(strs[2])) {
System.out.println("fail: incorrect password");
} else {
if (logging.get(strs[1])) {
System.out.println("fail: already logged in");
} else {
System.out.println("success: user logged in");
logging.put(strs[1], true);
}
}
} else if (strs[0].equals("logout")) {
if (users.containsKey(strs[1])) {
if (logging.get(strs[1])) {
System.out.println("success: user logged out");
logging.put(strs[1], false);
} else {
System.out.println("fail: already logged out");
}
} else {
System.out.println("fail: no such user");
}
}
}
}
}
| 38.673077 | 71 | 0.438588 |
e3b68a51408dc79b04b0ccd01334595917905a2b | 360 | /* Copyright (C) 2006 Versant Inc. http://www.db4o.com */
package com.db4o.cs.internal;
import com.db4o.foundation.*;
import com.db4o.internal.*;
/**
* @exclude
*/
public class DebugCS {
public static ClientObjectContainer clientStream;
public static LocalObjectContainer serverStream;
public static Queue4 clientMessageQueue;
}
| 18.947368 | 60 | 0.711111 |
e9d02f2ed206fd049948a37ee6ce84627b41e427 | 679 | package org.loadtest4j.drivers.jmeter.util;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
public final class Consumers {
private Consumers() {}
public static <T> Consumer<T> compose(Consumer<T>... consumers) {
return new ConsumerChain<>(Arrays.asList(consumers));
}
private static class ConsumerChain<T> implements Consumer<T> {
private final List<Consumer<T>> consumers;
private ConsumerChain(List<Consumer<T>> consumers) {
this.consumers = consumers;
}
@Override
public void accept(T t) {
consumers.forEach(c -> c.accept(t));
}
}
}
| 24.25 | 69 | 0.642121 |
37ac28f5181e9e63aafc549daed6d2fc5e7709b5 | 1,974 | package com.example.boundserviceexample;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
Button btnDisplayDate;
TextView tvDisplay;
MyService service;
boolean isBound = false;
ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
MyService.LocalBinder binder = (MyService.LocalBinder) iBinder;
service = binder.getService();
isBound = true;
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
isBound = false;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnDisplayDate = findViewById(R.id.btnDisplayDate);
tvDisplay = findViewById(R.id.textView);
btnDisplayDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (isBound) {
Date date = service.getDate();
tvDisplay.setText(date.toString());
}
}
});
}
@Override
protected void onStart() {
super.onStart();
Intent intent = new Intent(MainActivity.this, MyService.class);
bindService(intent, connection, BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
super.onStop();
if (isBound) {
unbindService(connection);
isBound = false;
}
}
} | 28.2 | 86 | 0.643364 |
22f65cd1998959fb00b0473e1eeb8342e489f99e | 986 | package org.checkerframework.checker.test.junit;
// Test case for issue 723.
// https://github.com/typetools/checker-framework/issues/723
// This exists to just run the I18nFormatterLubGlbChecker.
import org.checkerframework.checker.testchecker.lubglb.I18nFormatterLubGlbChecker;
import org.checkerframework.framework.test.CheckerFrameworkPerDirectoryTest;
import org.junit.runners.Parameterized.Parameters;
import java.io.File;
import java.util.List;
public class I18nFormatterLubGlbCheckerTest extends CheckerFrameworkPerDirectoryTest {
/**
* Create an I18nFormatterLubGlbCheckerTest.
*
* @param testFiles the files containing test code, which will be type-checked
*/
public I18nFormatterLubGlbCheckerTest(List<File> testFiles) {
super(testFiles, I18nFormatterLubGlbChecker.class, "", "-AcheckPurityAnnotations");
}
@Parameters
public static String[] getTestDirs() {
return new String[] {"i18n-formatter-lubglb"};
}
}
| 32.866667 | 91 | 0.764706 |
69720aeda0a919b738656be9a5d6abef221ffb56 | 657 | package com.imwyw.spbatis.controller;
import com.imwyw.spbatis.dao.ConfigDao;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
* @author wangyuanwei
* @title: ConfigController
* @projectName springboot-demo
* @description: 描述
* @date 2021/4/26 9:37
*/
@RestController
@RequestMapping("config")
public class ConfigController {
@Resource
private ConfigDao configDao;
@GetMapping("getId")
public String getId() {
return configDao.getDataId();
}
}
| 22.655172 | 62 | 0.753425 |
dab37a86fd19aa0ae22fed0831566edea7a5d8a4 | 2,313 | package org.usfirst.frc4946.AlphaDogs2015Robot.commands.autonomous;
import org.usfirst.frc4946.AlphaDogs2015Robot.RobotConstants;
import org.usfirst.frc4946.AlphaDogs2015Robot.commands.elevator.ElevatorMoveToPosition;
import org.usfirst.frc4946.AlphaDogs2015Robot.commands.elevator.SetElevatorMode;
import org.usfirst.frc4946.AlphaDogs2015Robot.commands.strafedropper.ActuateStrafeSolenoid;
import edu.wpi.first.wpilibj.command.CommandGroup;
/**
*
*/
public class RecyclingContainerAutonomousScript extends CommandGroup {
public RecyclingContainerAutonomousScript() {
// /open the arms
addSequential(new OpenGrabberArms());
addSequential(new Wait(RobotConstants.AUTONOMOUS_DELAY_ACTUATE_ARMS));
// Lower the elevator to just beneath the lip of the RC
addSequential(new SetElevatorMode(true));
addSequential(new ElevatorMoveToPosition(RobotConstants.AUTONOMOUS_ELEVATOR_PICKUP_CONTAINER_HEIGHT));
// Close the grabber arms in order to grasp recycling container
addSequential(new CloseGrabberArms());
addSequential(new Wait(RobotConstants.AUTONOMOUS_DELAY_ACTUATE_ARMS));
// Lift the RC just off of the ground
addSequential(new ElevatorMoveToPosition(RobotConstants.AUTONOMOUS_ELEVATOR_CARRY_CONTAINER_HEIGHT));
addSequential(new ActuateStrafeSolenoid(false));
addSequential(new Wait(RobotConstants.AUTONOMOUS_DELAY_ACTUATE_STRAFE));
addSequential(new SimpleAutoDrive(0.0, 1, 0.0), 0.5);
addSequential(new Wait(RobotConstants.AUTONOMOUS_DELAY_AFTER_DRIVE));
addSequential(new ActuateStrafeSolenoid(true));
addSequential(new Wait(RobotConstants.AUTONOMOUS_DELAY_ACTUATE_STRAFE));
//Drive forwards 12 feet in order to enter the Auto zone
addParallel(new ElevatorMoveToPosition(RobotConstants.AUTONOMOUS_ELEVATOR_TRANSPORT_HEIGHT));
addSequential(new SimpleAutoDrive(RobotConstants.AUTONOMOUS_DRIVE_INTO_ZONE_SPEED, 0.0, 0.0), RobotConstants.AUTONOMOUS_DRIVE_INTO_ZONE_TIMEOUT);
// Place the tote stack on the ground. Open the grabber arms to full size
addSequential(new ElevatorMoveToPosition(RobotConstants.AUTONOMOUS_ELEVATOR_PICKUP_HEIGHT));
addSequential(new OpenGrabberArms());
addSequential(new Wait(RobotConstants.AUTONOMOUS_DELAY_ACTUATE_ARMS));
// End
addSequential(new SimpleAutoDrive(0.0, 0.0, 0.0)); // Will run forever
}
}
| 39.87931 | 147 | 0.821876 |
156cbdf196109df000b9b62f89c03a1d7f0c0a77 | 579 | package com.bitcoin.indexer;
import com.bitcoin.indexer.blockchain.domain.Block;
import com.bitcoin.indexer.repository.BlockRepository;
import io.reactivex.Maybe;
import io.reactivex.Single;
public class FakeBlockRepo implements BlockRepository {
@Override
public Single<Block> saveBlock(Block block) {
return Single.just(block);
}
@Override
public Single<Long> saveHeight(Long currentHeight) {
return null;
}
@Override
public Single<Long> currentHeight() {
return null;
}
@Override
public Maybe<Block> getBlock(String hash) {
return Maybe.empty();
}
}
| 19.3 | 55 | 0.761658 |
9f6d177355302c2954fa094231707a8dd52c0ad6 | 545 | package com.vigorous.asynchronized.network.api;
import com.vigorous.asynchronized.network.data.request.ExampleRequestParam;
import com.vigorous.asynchronized.network.data.response.ExampleEntity;
import io.reactivex.Observable;
import retrofit2.http.Body;
import retrofit2.http.POST;
/**
* service统一接口数据
*/
public interface HttpRequestService {
/**
* post example
* @param once_no
* @return
*/
@POST("AppFiftyToneGraph/videoLink")
Observable<ExampleEntity> getAllVedio(@Body ExampleRequestParam once_no);
}
| 22.708333 | 77 | 0.755963 |
58f111e0963692bb120f937f6f55a882e42cbef9 | 293 | package dreme.macros;
import dreme.Environment;
import dreme.Identifier;
import dreme.SchemeObject;
public class SetMacro extends BindingMacro {
protected void bind(Environment environment, Identifier identifier, SchemeObject value) {
environment.set(identifier, value);
}
}
| 24.416667 | 93 | 0.774744 |
cd771ee85ecb4c0dba4225143f187a3374fec385 | 11,373 | /*
* Copyright 2021 Andreas Textor
*
* 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.atextor.owlcli.diagram;
import de.atextor.owlcli.diagram.graph.Edge;
import de.atextor.owlcli.diagram.graph.Graph;
import de.atextor.owlcli.diagram.graph.GraphElement;
import de.atextor.owlcli.diagram.graph.Node;
import de.atextor.owlcli.diagram.graph.node.ClosedClass;
import de.atextor.owlcli.diagram.graph.node.Complement;
import de.atextor.owlcli.diagram.graph.node.Datatype;
import de.atextor.owlcli.diagram.graph.node.Intersection;
import de.atextor.owlcli.diagram.graph.node.Union;
import de.atextor.owlcli.diagram.mappers.OWLDataMapper;
import org.junit.jupiter.api.Test;
import org.semanticweb.owlapi.model.AxiomType;
import org.semanticweb.owlapi.model.OWLDataComplementOf;
import org.semanticweb.owlapi.model.OWLDataIntersectionOf;
import org.semanticweb.owlapi.model.OWLDataOneOf;
import org.semanticweb.owlapi.model.OWLDataPropertyAssertionAxiom;
import org.semanticweb.owlapi.model.OWLDataPropertyRangeAxiom;
import org.semanticweb.owlapi.model.OWLDataRange;
import org.semanticweb.owlapi.model.OWLDataSomeValuesFrom;
import org.semanticweb.owlapi.model.OWLDataUnionOf;
import org.semanticweb.owlapi.model.OWLEquivalentClassesAxiom;
import org.semanticweb.owlapi.model.OWLLiteral;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
public class OWLDataMapperTest extends MapperTestBase {
private final OWLDataMapper mapper = new OWLDataMapper( createTestMappingConfiguration() );
@Test
public void testOWLDataComplementOf() {
final String ontology = """
:name a owl:DatatypeProperty .
:Dog a owl:Class ;
owl:equivalentClass [
a owl:Restriction ;
owl:onProperty :name ;
owl:someValuesFrom [
a rdfs:Datatype ;
owl:datatypeComplementOf xsd:string
]
] .
""";
final OWLEquivalentClassesAxiom axiom = getAxiom( ontology, AxiomType.EQUIVALENT_CLASSES );
final OWLDataSomeValuesFrom someValuesFrom = (OWLDataSomeValuesFrom) axiom.getOperandsAsList().get( 1 );
final OWLDataComplementOf owlDataOneOf = (OWLDataComplementOf) someValuesFrom.getFiller();
final String complementId = "complementNode";
testIdentifierMapper.pushAnonId( new Node.Id( complementId ) );
final Graph graph = mapper.visit( owlDataOneOf );
assertThat( graph.getNode().getClass() ).isEqualTo( Complement.class );
final Set<GraphElement> remainingElements = graph.getOtherElements().collect( Collectors.toSet() );
assertThat( remainingElements ).isNotEmpty();
final List<Node> nodes = nodes( remainingElements );
assertThat( nodes ).hasSize( 2 );
assertThat( nodes ).anyMatch( isNodeWithId( "string" ) );
assertThat( nodes ).anyMatch( isNodeWithId( complementId ) );
final List<Edge> edges = edges( remainingElements );
assertThat( edges ).hasSize( 1 );
assertThat( edges ).anyMatch( isEdgeWithFromAndTo( complementId, "string" ) );
}
@Test
public void testOWLDataOneOf() {
final String ontology = """
:name a owl:DatatypeProperty .
:Dog a owl:Class ;
owl:equivalentClass [
a owl:Restriction ;
owl:onProperty :name ;
owl:someValuesFrom [
a rdfs:Datatype ;
owl:oneOf ( "Fido" "Bello" )
]
] .
""";
final OWLEquivalentClassesAxiom axiom = getAxiom( ontology, AxiomType.EQUIVALENT_CLASSES );
final OWLDataSomeValuesFrom someValuesFrom = (OWLDataSomeValuesFrom) axiom.getOperandsAsList().get( 1 );
final OWLDataOneOf owlDataOneOf = (OWLDataOneOf) someValuesFrom.getFiller();
final String restrictionNodeId = "restrictionNode";
testIdentifierMapper.pushAnonId( new Node.Id( "Fido", iri( "Fido" ) ) );
testIdentifierMapper.pushAnonId( new Node.Id( "Bello", iri( "Bello" ) ) );
testIdentifierMapper.pushAnonId( new Node.Id( restrictionNodeId ) );
final Graph graph = mapper.visit( owlDataOneOf );
final Node restrictionNode = graph.getNode();
assertThat( restrictionNode ).isInstanceOf( ClosedClass.class );
final Set<GraphElement> remainingElements = graph.getOtherElements().collect( Collectors.toSet() );
assertThat( remainingElements ).isNotEmpty();
final List<Node> nodes = nodes( remainingElements );
assertThat( nodes ).hasSize( 2 );
assertThat( nodes ).anyMatch( isNodeWithId( "Fido" ) );
assertThat( nodes ).anyMatch( isNodeWithId( "Bello" ) );
final List<Edge> edges = edges( remainingElements );
assertThat( edges ).hasSize( 2 );
assertThat( edges ).anyMatch( isEdgeWithFromAndTo( restrictionNodeId, "Fido" ) );
assertThat( edges ).anyMatch( isEdgeWithFromAndTo( restrictionNodeId, "Bello" ) );
}
@Test
public void testOWLDataIntersectionOf() {
final String ontology = """
:numberOfWings a owl:DatatypeProperty .
:Dog a owl:Class ;
owl:equivalentClass [
a owl:Restriction ;
owl:onProperty :numberOfWings ;
owl:someValuesFrom [
a rdfs:Datatype ;
owl:intersectionOf ( xsd:nonNegativeInteger xsd:nonPositiveInteger )
]
] .
""";
final OWLEquivalentClassesAxiom axiom = getAxiom( ontology, AxiomType.EQUIVALENT_CLASSES );
final OWLDataSomeValuesFrom someValuesFrom = (OWLDataSomeValuesFrom) axiom.getOperandsAsList().get( 1 );
final OWLDataIntersectionOf intersection = (OWLDataIntersectionOf) someValuesFrom.getFiller();
final String intersectionId = "intersectionNode";
testIdentifierMapper.pushAnonId( new Node.Id( intersectionId ) );
final Graph graph = mapper.visit( intersection );
assertThat( graph.getNode().getClass() ).isEqualTo( Intersection.class );
final Set<GraphElement> remainingElements = graph.getOtherElements().collect( Collectors.toSet() );
assertThat( remainingElements ).isNotEmpty();
final List<Node> nodes = nodes( remainingElements );
assertThat( nodes ).hasSize( 3 );
assertThat( nodes ).anyMatch( isNodeWithId( "nonNegativeInteger" ) );
assertThat( nodes ).anyMatch( isNodeWithId( "nonPositiveInteger" ) );
assertThat( nodes ).anyMatch( isNodeWithId( intersectionId ) );
final List<Edge> edges = edges( remainingElements );
assertThat( edges ).hasSize( 2 );
assertThat( edges ).anyMatch( isEdgeWithFromAndTo( intersectionId, "nonNegativeInteger" ) );
assertThat( edges ).anyMatch( isEdgeWithFromAndTo( intersectionId, "nonPositiveInteger" ) );
}
@Test
public void testOWLDataUnionOf() {
final String ontology = """
:numberOfWings a owl:DatatypeProperty .
:Dog a owl:Class ;
owl:equivalentClass [
a owl:Restriction ;
owl:onProperty :numberOfWings ;
owl:someValuesFrom [
a rdfs:Datatype ;
owl:unionOf ( xsd:nonNegativeInteger xsd:nonPositiveInteger )
]
] .
""";
final OWLEquivalentClassesAxiom axiom = getAxiom( ontology, AxiomType.EQUIVALENT_CLASSES );
final OWLDataSomeValuesFrom someValuesFrom = (OWLDataSomeValuesFrom) axiom.getOperandsAsList().get( 1 );
final OWLDataUnionOf intersection = (OWLDataUnionOf) someValuesFrom.getFiller();
final String intersectionId = "intersectionNode";
testIdentifierMapper.pushAnonId( new Node.Id( intersectionId ) );
final Graph graph = mapper.visit( intersection );
assertThat( graph.getNode().getClass() ).isEqualTo( Union.class );
final Set<GraphElement> remainingElements = graph.getOtherElements().collect( Collectors.toSet() );
assertThat( remainingElements ).isNotEmpty();
final List<Node> nodes = nodes( remainingElements );
assertThat( nodes ).hasSize( 3 );
assertThat( nodes ).anyMatch( isNodeWithId( "nonNegativeInteger" ) );
assertThat( nodes ).anyMatch( isNodeWithId( "nonPositiveInteger" ) );
assertThat( nodes ).anyMatch( isNodeWithId( intersectionId ) );
final List<Edge> edges = edges( remainingElements );
assertThat( edges ).hasSize( 2 );
assertThat( edges ).anyMatch( isEdgeWithFromAndTo( intersectionId, "nonNegativeInteger" ) );
assertThat( edges ).anyMatch( isEdgeWithFromAndTo( intersectionId, "nonPositiveInteger" ) );
}
@Test
public void testOWLDatatypeRestriction() {
final String ontology = """
:foo a owl:DatatypeProperty ;
rdfs:range [
a rdfs:Datatype ;
owl:onDatatype xsd:int ;
owl:withRestrictions (
[ xsd:minExclusive "4"^^xsd:int ] [ xsd:maxInclusive "10"^^xsd:int ]
)
] .
""";
final OWLDataPropertyRangeAxiom axiom = getAxiom( ontology, AxiomType.DATA_PROPERTY_RANGE );
final OWLDataRange range = axiom.getRange();
final Graph graph = range.accept( mapper );
final Set<GraphElement> elements = graph.getElementSet();
assertThat( edges( elements ) ).isEmpty();
final List<Node> nodes = nodes( elements );
assertThat( nodes ).hasSize( 1 );
final Node node = nodes.get( 0 );
assertThat( node.getClass() ).isEqualTo( Datatype.class );
assertThat( node.as( Datatype.class ).getName() ).matches( ".*\\[> 4, <= 10]" );
}
@Test
public void testOWLFacetRestriction() {
}
@Test
public void testOWLDatatype() {
}
@Test
public void testOWLLiteral() {
final String ontology = """
:Dog a owl:Class .
:name a owl:DatatypeProperty .
:Bello a :Dog ;
:name "Bello" .
""";
final OWLDataPropertyAssertionAxiom axiom = getAxiom( ontology, AxiomType.DATA_PROPERTY_ASSERTION );
final OWLLiteral object = axiom.getObject();
final String literalId = "literalNode";
testIdentifierMapper.pushAnonId( new Node.Id( literalId ) );
final Graph graph = mapper.visit( object );
assertThat( graph.getNode() ).matches( isNodeWithId( literalId ) );
assertThat( graph.getOtherElements() ).isEmpty();
}
}
| 43.079545 | 112 | 0.651631 |
54d793a71bde85f32edd46d05cbd01b68a132b0b | 1,289 | package com.alipay.api.domain;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* 留学缴费-订单状态模型
*
* @author auto create
* @since 1.0, 2021-08-16 15:52:31
*/
public class TuitionISVOrderStatusDTO extends AlipayObject {
private static final long serialVersionUID = 8212178577264264182L;
/**
* 错误码
*/
@ApiField("error_code")
private String errorCode;
/**
* 错误信息
*/
@ApiField("error_message")
private String errorMessage;
/**
* 状态码
*/
@ApiField("status_code")
private String statusCode;
/**
* 状态描述
*/
@ApiField("status_desc")
private String statusDesc;
public String getErrorCode() {
return this.errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public String getErrorMessage() {
return this.errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public String getStatusCode() {
return this.statusCode;
}
public void setStatusCode(String statusCode) {
this.statusCode = statusCode;
}
public String getStatusDesc() {
return this.statusDesc;
}
public void setStatusDesc(String statusDesc) {
this.statusDesc = statusDesc;
}
}
| 18.681159 | 68 | 0.680372 |
65042ee12913423d607a8fce7d1b546dd5f948bb | 1,645 | /*-
* #%L
* Proof Utility Library
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2014 - 2017 Live Ontologies Project
* %%
* 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.
* #L%
*/
package org.liveontologies.puli;
import java.util.List;
public class DelegatingProofStep<C> extends Delegator<ProofStep<C>>
implements ProofStep<C> {
private int hashCode_ = 0;
protected DelegatingProofStep(ProofStep<C> delegate) {
super(delegate);
}
@Override
public String getName() {
return getDelegate().getName();
}
@Override
public ProofNode<C> getConclusion() {
return getDelegate().getConclusion();
}
@Override
public List<? extends ProofNode<C>> getPremises() {
return getDelegate().getPremises();
}
@Override
public Inference<? extends C> getInference() {
return getDelegate().getInference();
}
@Override
public boolean equals(Object o) {
return Inferences.equals(this, o);
}
@Override
public synchronized int hashCode() {
if (hashCode_ == 0) {
hashCode_ = Inferences.hashCode(this);
}
return hashCode_;
}
@Override
public String toString() {
return Inferences.toString(this);
}
}
| 22.22973 | 75 | 0.706991 |
994bd1552f1913490c7c355de717fd552ca98ba2 | 936 | package com.zxcs.printtemplate.model;
import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
import java.util.Date;
/**
* 打印模板-文档表
* Created by zfh on 2018/12/12
*/
@Data
@ToString
public class PrinterTemplateDocumentDO implements Serializable {
private static final long serialVersionUID = 5061220291589710884L;
/**
* 主键
*/
private Integer id;
/**
* 模板文档名称
*/
private String name;
/**
* 文档类型
*/
private Integer documentType;
/**
* 模板预览图
*/
private String url;
/**
* 模板状态:0-删除 1-启用 2-禁用
*/
private Integer status;
/**
* 店铺id
*/
private Integer shopId;
/**
* 创建者id
*/
private Integer creatorId;
/**
* 创建者姓名
*/
private String creatorName;
/**
* 添加时间
*/
private Date createTime;
/**
* 更新时间
*/
private Date updateTime;
}
| 13.565217 | 70 | 0.558761 |
98d52f1122da5acc221a25ce946e363c938c0d78 | 5,400 | package org.apache.lucene.index;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.util.ArrayList;
import java.util.Iterator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.lucene.search.Query;
import org.apache.lucene.util.PriorityQueue;
import org.apache.lucene.index.BufferedDeletesStream.QueryAndLimit;
class CoalescedDeletes {
final Map<Query,Integer> queries = new HashMap<Query,Integer>();
final List<Iterable<Term>> iterables = new ArrayList<Iterable<Term>>();
@Override
public String toString() {
// note: we could add/collect more debugging information
return "CoalescedDeletes(termSets=" + iterables.size() + ",queries=" + queries.size() + ")";
}
void update(FrozenBufferedDeletes in) {
iterables.add(in.termsIterable());
for(int queryIdx=0;queryIdx<in.queries.length;queryIdx++) {
final Query query = in.queries[queryIdx];
queries.put(query, BufferedDeletes.MAX_INT);
}
}
public Iterable<Term> termsIterable() {
return new Iterable<Term>() {
public Iterator<Term> iterator() {
ArrayList<Iterator<Term>> subs = new ArrayList<Iterator<Term>>(iterables.size());
for (Iterable<Term> iterable : iterables) {
subs.add(iterable.iterator());
}
return mergedIterator(subs);
}
};
}
public Iterable<QueryAndLimit> queriesIterable() {
return new Iterable<QueryAndLimit>() {
public Iterator<QueryAndLimit> iterator() {
return new Iterator<QueryAndLimit>() {
private final Iterator<Map.Entry<Query,Integer>> iter = queries.entrySet().iterator();
public boolean hasNext() {
return iter.hasNext();
}
public QueryAndLimit next() {
final Map.Entry<Query,Integer> ent = iter.next();
return new QueryAndLimit(ent.getKey(), ent.getValue());
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
/** provides a merged view across multiple iterators */
static Iterator<Term> mergedIterator(final List<Iterator<Term>> iterators) {
return new Iterator<Term>() {
Term current;
TermMergeQueue queue = new TermMergeQueue(iterators.size());
SubIterator[] top = new SubIterator[iterators.size()];
int numTop;
{
int index = 0;
for (Iterator<Term> iterator : iterators) {
if (iterator.hasNext()) {
SubIterator sub = new SubIterator();
sub.current = iterator.next();
sub.iterator = iterator;
sub.index = index++;
queue.add(sub);
}
}
}
public boolean hasNext() {
if (queue.size() > 0) {
return true;
}
for (int i = 0; i < numTop; i++) {
if (top[i].iterator.hasNext()) {
return true;
}
}
return false;
}
public Term next() {
// restore queue
pushTop();
// gather equal top fields
if (queue.size() > 0) {
pullTop();
} else {
current = null;
}
return current;
}
public void remove() {
throw new UnsupportedOperationException();
}
private void pullTop() {
// extract all subs from the queue that have the same top term
assert numTop == 0;
while (true) {
top[numTop++] = queue.pop();
if (queue.size() == 0
|| !(queue.top()).current.equals(top[0].current)) {
break;
}
}
current = top[0].current;
}
private void pushTop() {
// call next() on each top, and put back into queue
for (int i = 0; i < numTop; i++) {
if (top[i].iterator.hasNext()) {
top[i].current = top[i].iterator.next();
queue.add(top[i]);
} else {
// no more terms
top[i].current = null;
}
}
numTop = 0;
}
};
}
private static class SubIterator {
Iterator<Term> iterator;
Term current;
int index;
}
private static class TermMergeQueue extends PriorityQueue<SubIterator> {
TermMergeQueue(int size) {
initialize(size);
}
@Override
protected boolean lessThan(SubIterator a, SubIterator b) {
final int cmp = a.current.compareTo(b.current);
if (cmp != 0) {
return cmp < 0;
} else {
return a.index < b.index;
}
}
}
}
| 28.877005 | 96 | 0.59 |
86f41a35112d6553b1ec402bbbb12e8c34abd7d3 | 704 | /**
@author Farheen Bano
Reference-
https://www.geeksforgeeks.org/unbounded-knapsack-repetition-items-allowed/
*/
import java.io.*;
import java.util.*;
import java.lang.*;
class Solution{
static int knapSack(int N, int W, int val[], int wt[]) {
int dp[][]=new int[N+1][W+1];
for(int i=0;i<=N;i++){
for(int j=0;j<=W;j++){
if(i==0||j==0){
dp[i][j]=0;
}
else if(wt[i-1]<=j){
dp[i][j]=Math.max(val[i-1]+dp[i][j-wt[i-1]], dp[i-1][j]);
}
else
dp[i][j]=dp[i-1][j];
}
}
return dp[N][W];
}
}
| 22.709677 | 77 | 0.410511 |
26f4201f2ba1f4fe34fd82de0b7b10c2caf6c2f9 | 2,229 | /*
* Copyright (C) 2014 Bob Browning
*
* 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.kogitune.intellij.codeinsight.postfix.templates.surround;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.PsiShortNamesCache;
import com.kogitune.intellij.codeinsight.postfix.utils.AndroidPostfixTemplatesUtils;
import org.jetbrains.annotations.NotNull;
import static com.kogitune.intellij.codeinsight.postfix.utils.AndroidClassName.LOG;
/**
* Postfix template for android Log.
*
* @author takahirom
*/
public class LogDTemplate extends LogTemplate {
public LogDTemplate() {
this("logd");
}
public LogDTemplate(@NotNull String alias) {
super(alias, "if(BuildConfig.DEBUG) Log.d(TAG, expr);", AndroidPostfixTemplatesUtils.IS_NON_NULL);
}
@Override
public String getTemplateString(@NotNull PsiElement element) {
Project project = element.getProject();
final GlobalSearchScope resolveScope = element.getResolveScope();
PsiClass[] buildConfigClasses = PsiShortNamesCache.getInstance(project).getClassesByName("BuildConfig", resolveScope);
String buildConfigDebug = "BuildConfig.DEBUG";
if (buildConfigClasses.length != 0) {
// Get BuildConfig QualifiedName
PsiClass buildConfig = buildConfigClasses[0];
String qualifiedName = buildConfig.getQualifiedName();
buildConfigDebug = qualifiedName + ".DEBUG";
}
return "if (" + buildConfigDebug + ") " + getStaticPrefix(LOG, "d", element) + "($TAG$, $expr$)$END$";
}
}
| 36.540984 | 126 | 0.723643 |
f52c2c83643e99ba8e1e9dae3c8459c3a4471adf | 451 | import java.io.*;
class SumDigit{
public static void main(String[] args) throws IOException {
int r, sum=0,num;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a Number:");
num=Integer.parseInt(br.readLine());
while(num>0){
r=num%10;
sum+=r;
num/=10;
}
System.out.println("Sum of Digits is:"+sum);
}
} | 30.066667 | 79 | 0.567627 |
932f8bf152c0f5f76fbd97e1a01f3806fbd40f04 | 1,078 | import java.util.*;
public class Main {
public static void main(String[] args) {
GenericTreeImplementation tree= new GenericTreeImplementation();
}
}
class GenericTreeImplementation {
class Node {
int d;
ArrayList<Node> child;
Node(int d) {
this.d = d;
child = new ArrayList<>();
}
}
private Node r;
GenericTreeImplementation() {
Scanner s = new Scanner(System.in);
this.r = good(s, null, 0);
}
private Node good(Scanner s, Node parent, int i) {
if (parent == null) {
System.out.println("Enter info for root node");
} else {
System.out.println("Enter info for " + i + "th child of " + parent.d);
}
int d = s.nextInt();
Node node = new Node(d);
System.out.println("Enter the number of child for" + node.d);
int n = s.nextInt();
for (int k = 0; k < n; k++) {
Node children = good(s, node, k);
node.child.add(children);
}
return node;
}
}
| 24.5 | 82 | 0.526902 |
2367317b49b485156c797d6dc9aedbac5945bfa0 | 2,994 | package greeter;
import static org.junit.Assert.assertEquals;
import greeter.api.Greeter;
import java.io.File;
import java.util.ServiceLoader;
import org.apache.commons.io.FileUtils;
import org.jboss.modules.LocalModuleLoader;
import org.jboss.modules.Module;
import org.jboss.modules.ModuleClassLoader;
import org.jboss.modules.ModuleUnloader;
import org.junit.BeforeClass;
import org.junit.Test;
public class Test5_UnloadAndDeleteModuleError2 {
@BeforeClass
public static void copyRepo() throws Exception {
FileUtils.deleteQuietly(new File("repo_copy"));
FileUtils.copyDirectory(new File("repo"), new File("repo_copy"));
}
@Test
public void test() throws Exception {
try (LocalModuleLoader moduleLoader = new LocalModuleLoader(new File[] { new File("repo_copy") })) {
// load the module
Module module = moduleLoader.loadModule("greeter.english");
ModuleClassLoader classLoader = module.getClassLoader();
// use the module via ServiceLoader
ServiceLoader<Greeter> greeters = module.loadService(Greeter.class);
int loops = 0;
for (Greeter greeter : greeters) {
loops++;
assertEquals("Hello World!", greeter.sayHello("World"));
}
assertEquals("module not found by ServiceLoader", 1, loops);
// but even if we unload the module with the hacks...
ModuleUnloader.unload(moduleLoader, module);
classLoader.close();
System.gc();
// ... it is not possible to remove the directory because the module jar is still locked by ServiceLoader
FileUtils.deleteDirectory(new File("repo_copy/greeter/english"));
}
}
}
// Using http://file-leak-detector.kohsuke.org/ we can get this stack
// JVM args example: -javaagent:C:\Java\file-leak-detector-1.8-jar-with-dependencies.jar=http=19999
// #4 C:\dev\Perso\Eclipse\modules-demo\greeter-app\repo_copy\greeter\english\lib\greeter-impl-1.0-SNAPSHOT.jar by thread:main on Sun Dec 17 15:51:36 CET 2017
// at java.util.zip.ZipFile.<init>(Unknown Source)
// at java.util.jar.JarFile.<init>(Unknown Source)
// at java.util.jar.JarFile.<init>(Unknown Source)
// at sun.net.www.protocol.jar.URLJarFile.<init>(Unknown Source)
// at sun.net.www.protocol.jar.URLJarFile.getJarFile(Unknown Source)
// at sun.net.www.protocol.jar.JarFileFactory.get(Unknown Source)
// at sun.net.www.protocol.jar.JarURLConnection.connect(Unknown Source)
// at sun.net.www.protocol.jar.JarURLConnection.getInputStream(Unknown Source)
// at java.net.URL.openStream(Unknown Source)
// at java.util.ServiceLoader.parse(Unknown Source)
// at java.util.ServiceLoader.access$200(Unknown Source)
// at java.util.ServiceLoader$LazyIterator.hasNextService(Unknown Source)
// at java.util.ServiceLoader$LazyIterator.hasNext(Unknown Source)
// at java.util.ServiceLoader$1.hasNext(Unknown Source)
// at greeter.Test5_UnloadAndDeleteModuleError2.test(Test5_UnloadAndDeleteModuleError2.java:32)
// It seems to me that Lucene is doing a heavy use of ServiceLoader. To be checked.
| 41.013699 | 160 | 0.751837 |
e92a89327547c1c31c9c8ee8d31fec0c0cd493c1 | 727 | /*
* Copyright 2021 Marcin Bukowiecki.
* Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package io.vacuum.livetemplates;
import com.intellij.codeInsight.template.TemplateActionContext;
import com.intellij.codeInsight.template.TemplateContextType;
import org.jetbrains.annotations.NotNull;
/**
* @author Marcin Bukowiecki
*/
public class VacuumAWSContext extends TemplateContextType {
protected VacuumAWSContext() {
super("VacuumAWS", "Vacuum AWS Templates");
}
@Override
public boolean isInContext(@NotNull TemplateActionContext templateActionContext) {
return templateActionContext.getFile().getName().endsWith(".go");
}
}
| 27.961538 | 103 | 0.753783 |
3d6939f5c98e0484a88fc163e95c0be5342bbc84 | 8,144 | /*
* Copyright © 2018-2021 VMware, Inc. All Rights Reserved.
* SPDX-License-Identifier: BSD-2
*/
package com.vmware.dcm.backend.ortools;
import com.google.ortools.sat.CpModel;
import com.google.ortools.sat.CpSolver;
import com.google.ortools.sat.CpSolverStatus;
import com.google.ortools.sat.IntVar;
import com.google.ortools.sat.IntervalVar;
import com.google.ortools.sat.LinearExpr;
import com.vmware.dcm.Model;
import com.vmware.dcm.SolverException;
import org.jooq.DSLContext;
import org.jooq.impl.DSL;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
public class CoreTest {
static {
// Causes or-tools JNI library to be loaded
new OrToolsSolver.Builder().build();
}
@Test
public void assumptionsTest() {
final CpModel model = new CpModel();
final IntVar i1 = model.newIntVar(0, 5, "i1");
final IntVar i2 = model.newIntVar(0, 5, "i2");
final IntVar v1 = model.newBoolVar("v1");
final IntVar v2 = model.newBoolVar("v2");
final IntVar v3 = model.newBoolVar("v3");
model.addGreaterOrEqual(LinearExpr.sum(new IntVar[]{i1, i2}), 11).onlyEnforceIf(v1); // can't be satisfied
model.addLessOrEqual(LinearExpr.sum(new IntVar[]{i1, i2}), 5).onlyEnforceIf(v2);
model.addEquality(v3, 1);
model.addAssumption(v1);
model.addAssumption(v2);
model.addAssumption(v3);
final CpSolver solver = new CpSolver();
solver.getParameters().setNumSearchWorkers(1);
final CpSolverStatus status = solver.solve(model);
assertEquals(CpSolverStatus.INFEASIBLE, status);
assertTrue(solver.sufficientAssumptionsForInfeasibility()
.stream()
.map(e -> model.getBuilder().getVariables(e).getName())
.collect(Collectors.toList())
.contains("v1"));
}
@Test
public void cumulative() {
final CpModel model = new CpModel();
final IntVar origin = model.newIntVar(0, 5, "i1");
final IntVar i1 = model.newIntVar(0, 5, "i1o");
final IntVar assumptionVar1 = model.newBoolVar("Assumption 1");
model.addEquality(origin, i1).onlyEnforceIf(assumptionVar1);
model.addDifferent(origin, i1).onlyEnforceIf(assumptionVar1.not());
final IntervalVar[] tasksIntervals = new IntervalVar[1];
tasksIntervals[0] = model.newOptionalIntervalVar(i1, model.newConstant(1), model.newConstant(1),
assumptionVar1, "");
// Can't be satisfied
model.addCumulative(tasksIntervals, new IntVar[]{model.newConstant(11)}, model.newConstant(10));
model.addAssumption(assumptionVar1);
final IntVar i2 = model.newIntVar(0, 5, "i2");
final IntVar i3 = model.newIntVar(0, 5, "i3");
final IntVar assumptionVar2 = model.newBoolVar("Assumption 2");
final IntVar assumptionVar3 = model.newBoolVar("Assumption 3");
// Can't be satisfied
model.addGreaterOrEqual(LinearExpr.sum(new IntVar[]{i2, i3}), 11).onlyEnforceIf(assumptionVar2);
model.addLessOrEqual(LinearExpr.sum(new IntVar[]{i2, i3}), 5).onlyEnforceIf(assumptionVar3);
model.addAssumption(assumptionVar2);
model.addAssumption(assumptionVar3);
final CpSolver solver = new CpSolver();
solver.getParameters().setNumSearchWorkers(1);
final CpSolverStatus status = solver.solve(model);
assertEquals(CpSolverStatus.INFEASIBLE, status);
assertTrue(solver.sufficientAssumptionsForInfeasibility()
.stream()
.map(e -> model.getBuilder().getVariables(e).getName())
.collect(Collectors.toList())
.contains("Assumption 1"));
}
@Test
public void assumptionsTestWithOps() {
final CpModel model = new CpModel();
final StringEncoding encoding = new StringEncoding();
final Ops o = new Ops(model, encoding);
final IntVar i1 = model.newIntVar(0, 5, "i1");
final IntVar i2 = model.newIntVar(0, 5, "i2");
final IntVar i3 = model.newIntVar(0, 5, "i2");
o.assume(o.eq(i1, 3), "i1 constraint_all_different");
o.assume(model.newConstant(1), "i2 constraint_all_different");
o.assume(model.newConstant(1), "i3 constraint_all_different");
o.assume(o.and(o.leq(i1, 2), o.geq(i1, 1)), "i1 constraint_domain");
o.assume(o.and(o.leq(i2, 2), o.geq(i2, 1)), "i2 constraint_domain");
o.assume(o.and(o.leq(i3, 2), o.geq(i3, 1)), "i3 constraint_domain");
final CpSolver solver = new CpSolver();
solver.getParameters().setLogSearchProgress(true);
solver.getParameters().setNumSearchWorkers(1);
final CpSolverStatus status = solver.solve(model);
assertEquals(CpSolverStatus.INFEASIBLE, status);
assertTrue(solver.sufficientAssumptionsForInfeasibility()
.stream()
.map(e -> model.getBuilder().getVariables(e).getName())
.collect(Collectors.toList())
.containsAll(List.of("i1 constraint_all_different", "i1 constraint_domain")));
}
@Test
public void allDifferentInfeasibility() {
final DSLContext conn = DSL.using("jdbc:h2:mem:");
conn.execute("create table t1(id integer, controllable__var integer)");
conn.execute("insert into t1 values (1, null)");
conn.execute("insert into t1 values (2, null)");
conn.execute("insert into t1 values (3, null)");
// Unsatisfiable
final String allDifferent = "create constraint constraint_all_different as " +
"select * from t1 check all_different(controllable__var) = true";
// Unsatisfiable
final String domain1 = "create constraint constraint_domain_1 as " +
"select * from t1 check controllable__var >= 1 and controllable__var <= 2";
// Satisfiable
final String domain2 = "create constraint constraint_domain_2 as " +
"select * from t1 check id != 1 or controllable__var = 1";
final Model model = Model.build(conn, List.of(allDifferent, domain1, domain2));
try {
model.solve("T1");
fail();
} catch (final SolverException exception) {
System.out.println(exception.core());
assertTrue(exception.core().containsAll(List.of("CONSTRAINT_ALL_DIFFERENT", "CONSTRAINT_DOMAIN_1")));
assertFalse(exception.core().contains("CONSTRAINT_DOMAIN_2"));
}
}
@Test
public void sumInfeasibility() {
final DSLContext conn = DSL.using("jdbc:h2:mem:");
conn.execute("create table t1(id integer, controllable__var integer)");
conn.execute("insert into t1 values (1, null)");
conn.execute("insert into t1 values (2, null)");
conn.execute("insert into t1 values (3, null)");
// Unsatisfiable
final String sum = "create constraint constraint_sum as " +
"select * from t1 check sum(controllable__var) = 7";
// Unsatisfiable
final String domain1 = "create constraint constraint_domain_1 as " +
"select * from t1 check controllable__var >= 1 and controllable__var <= 2";
// Satisfiable
final String domain2 = "create constraint constraint_domain_2 as " +
"select * from t1 check id != 1 or controllable__var = 1";
final Model model = Model.build(conn, List.of(sum, domain1, domain2));
try {
model.solve("T1");
fail();
} catch (final SolverException exception) {
System.out.println(exception.core());
assertTrue(exception.core().containsAll(List.of("CONSTRAINT_SUM", "CONSTRAINT_DOMAIN_1")));
assertFalse(exception.core().contains("CONSTRAINT_DOMAIN_2"));
}
}
}
| 42.638743 | 114 | 0.645138 |
e47eb354fd3d201470c5fd74b70758ac7340f7c7 | 521 | package bot.config;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import bot.clients.GuildWars2ApiClient;
import bot.services.gw2.AccountService;
@Configuration
@EnableFeignClients(basePackageClasses = GuildWars2ApiClient.class)
public class ApiClientConfig {
@Bean
protected AccountService accountService(GuildWars2ApiClient client) {
return new AccountService(client);
}
}
| 26.05 | 71 | 0.833013 |
2c891a77c613b7e07619ba735e3fd6e693600d25 | 18,550 | /*
* Copyright 2016-2018 Axioma srl.
*
* 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.holonplatform.vaadin.flow.internal.components.support;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Supplier;
import com.holonplatform.core.Validator;
import com.holonplatform.core.i18n.Localizable;
import com.holonplatform.core.internal.utils.ObjectUtils;
import com.holonplatform.core.property.PropertyRenderer;
import com.holonplatform.vaadin.flow.components.Input;
import com.holonplatform.vaadin.flow.components.ItemListing.EditorComponentGroup;
import com.holonplatform.vaadin.flow.components.ValidationStatusHandler;
import com.holonplatform.vaadin.flow.components.ValueHolder.ValueChangeListener;
import com.holonplatform.vaadin.flow.components.builders.ItemListingConfigurator.ColumnAlignment;
import com.holonplatform.vaadin.flow.components.events.GroupValueChangeEvent;
import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.grid.SortOrderProvider;
import com.vaadin.flow.data.renderer.Renderer;
import com.vaadin.flow.function.ValueProvider;
/**
* Default {@link ItemListingColumn} implementation.
*
* @param <T> Item type
* @param <P> Item property type
* @param <V> Property value type
*
* @since 5.2.0
*/
public class DefaultItemListingColumn<P, T, V> implements ItemListingColumn<P, T, V> {
private static final long serialVersionUID = 8922982578042556430L;
private final P property;
private final String columnKey;
private boolean readOnly = false;
private boolean visible = true;
private boolean resizable = false;
private boolean frozen = false;
private SortMode sortMode = SortMode.DEFAULT;
private int flexGrow = 1;
private ColumnAlignment alignment;
private String width = null;
private boolean autoWidth = false;
private Localizable headerText;
private Component headerComponent;
private Localizable footerText;
private Component footerComponent;
private Renderer<T> renderer;
private ValueProvider<T, String> valueProvider;
private Function<T, String> styleNameGenerator;
private Comparator<T> comparator;
private SortOrderProvider sortOrderProvider;
private List<P> sortProperties;
private List<Validator<V>> validators;
private PropertyRenderer<Input<V>, V> editorInputRenderer;
private Function<T, ? extends Component> editorComponent;
private ValidationStatusHandler<Input<V>> validationStatusHandler;
private boolean required;
private Localizable requiredMessage;
private Supplier<V> defaultValueProvider;
private List<ValueChangeListener<V, GroupValueChangeEvent<V, P, Input<?>, EditorComponentGroup<P, T>>>> valueChangeListeners = new LinkedList<>();
/**
* Constructor.
* @param property Item property id (not null)
* @param columnKey Column key (not null)
* @param readOnly Whether the column is read-only by default
*/
public DefaultItemListingColumn(P property, String columnKey, boolean readOnly) {
super();
ObjectUtils.argumentNotNull(property, "Item property id must be not null");
ObjectUtils.argumentNotNull(columnKey, "Column keymust be not null");
this.property = property;
this.columnKey = columnKey;
this.readOnly = readOnly;
}
/*
* (non-Javadoc)
* @see com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#getProperty()
*/
@Override
public P getProperty() {
return property;
}
/*
* (non-Javadoc)
* @see com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#isReadOnly()
*/
@Override
public boolean isReadOnly() {
return readOnly;
}
/*
* (non-Javadoc)
* @see com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#setReadOnly(boolean)
*/
@Override
public void setReadOnly(boolean readOnly) {
this.readOnly = readOnly;
}
/*
* (non-Javadoc)
* @see com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#getColumnKey()
*/
@Override
public String getColumnKey() {
return columnKey;
}
/*
* (non-Javadoc)
* @see com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#isVisible()
*/
@Override
public boolean isVisible() {
return visible;
}
/*
* (non-Javadoc)
* @see com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#setVisible(boolean)
*/
@Override
public void setVisible(boolean visible) {
this.visible = visible;
}
/*
* (non-Javadoc)
* @see com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#isResizable()
*/
@Override
public boolean isResizable() {
return resizable;
}
/*
* (non-Javadoc)
* @see com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#setResizable(boolean)
*/
@Override
public void setResizable(boolean resizable) {
this.resizable = resizable;
}
/*
* (non-Javadoc)
* @see com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#isFrozen()
*/
@Override
public boolean isFrozen() {
return frozen;
}
/*
* (non-Javadoc)
* @see com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#setFrozen(boolean)
*/
@Override
public void setFrozen(boolean frozen) {
this.frozen = frozen;
}
/*
* (non-Javadoc)
* @see com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#getWidth()
*/
@Override
public Optional<String> getWidth() {
return Optional.ofNullable(width);
}
/*
* (non-Javadoc)
* @see com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#setWidth(java.lang.String)
*/
@Override
public void setWidth(String width) {
this.width = width;
}
/*
* (non-Javadoc)
* @see com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#getFlexGrow()
*/
@Override
public int getFlexGrow() {
return flexGrow;
}
/*
* (non-Javadoc)
* @see com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#setFlexGrow(int)
*/
@Override
public void setFlexGrow(int flexGrow) {
this.flexGrow = flexGrow;
}
@Override
public boolean isAutoWidth() {
return autoWidth;
}
@Override
public void setAutoWidth(boolean autoWidth) {
this.autoWidth = autoWidth;
}
/*
* (non-Javadoc)
* @see com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#getAlignment()
*/
@Override
public Optional<ColumnAlignment> getAlignment() {
return Optional.ofNullable(alignment);
}
/*
* (non-Javadoc)
* @see
* com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#setAlignment(com.holonplatform.vaadin
* .flow.components.builders.ItemListingConfigurator.ColumnAlignment)
*/
@Override
public void setAlignment(ColumnAlignment alignment) {
this.alignment = alignment;
}
/*
* (non-Javadoc)
* @see com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#getHeaderText()
*/
@Override
public Optional<Localizable> getHeaderText() {
return Optional.ofNullable(headerText);
}
/*
* (non-Javadoc)
* @see
* com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#setHeaderText(com.holonplatform.core.
* i18n.Localizable)
*/
@Override
public void setHeaderText(Localizable text) {
this.headerText = text;
}
/*
* (non-Javadoc)
* @see com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#getHeaderComponent()
*/
@Override
public Optional<Component> getHeaderComponent() {
return Optional.ofNullable(headerComponent);
}
/*
* (non-Javadoc)
* @see
* com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#setHeaderComponent(com.vaadin.flow.
* component.Component)
*/
@Override
public void setHeaderComponent(Component component) {
this.headerComponent = component;
}
/*
* (non-Javadoc)
* @see com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#getFooterComponent()
*/
@Override
public Optional<Component> getFooterComponent() {
return Optional.ofNullable(footerComponent);
}
/*
* (non-Javadoc)
* @see com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#getFooterText()
*/
@Override
public Optional<Localizable> getFooterText() {
return Optional.ofNullable(footerText);
}
/*
* (non-Javadoc)
* @see
* com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#setFooterText(com.holonplatform.core.
* i18n.Localizable)
*/
@Override
public void setFooterText(Localizable text) {
this.footerText = text;
}
/*
* (non-Javadoc)
* @see
* com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#setFooterComponent(com.vaadin.flow.
* component.Component)
*/
@Override
public void setFooterComponent(Component component) {
this.footerComponent = component;
}
/*
* (non-Javadoc)
* @see com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#getRenderer()
*/
@Override
public Optional<Renderer<T>> getRenderer() {
return Optional.ofNullable(renderer);
}
/*
* (non-Javadoc)
* @see
* com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#setRenderer(com.vaadin.flow.data.
* renderer.Renderer)
*/
@Override
public void setRenderer(Renderer<T> renderer) {
this.renderer = renderer;
}
/*
* (non-Javadoc)
* @see com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#getValueProvider()
*/
@Override
public Optional<ValueProvider<T, String>> getValueProvider() {
return Optional.ofNullable(valueProvider);
}
/*
* (non-Javadoc)
* @see
* com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#setValueProvider(com.vaadin.flow.
* function.ValueProvider)
*/
@Override
public void setValueProvider(ValueProvider<T, String> valueProvider) {
this.valueProvider = valueProvider;
}
/*
* (non-Javadoc)
* @see com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#getStyleNameGenerator()
*/
@Override
public Optional<Function<T, String>> getStyleNameGenerator() {
return Optional.ofNullable(styleNameGenerator);
}
/*
* (non-Javadoc)
* @see com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#setStyleNameGenerator(java.util.
* function.Function)
*/
@Override
public void setStyleNameGenerator(Function<T, String> styleNameGenerator) {
this.styleNameGenerator = styleNameGenerator;
}
/*
* (non-Javadoc)
* @see com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#getSortMode()
*/
@Override
public SortMode getSortMode() {
return sortMode;
}
/*
* (non-Javadoc)
* @see
* com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#setSortMode(com.holonplatform.vaadin.
* flow.internal.components.support.ItemListingColumn.SortMode)
*/
@Override
public void setSortMode(SortMode sortMode) {
this.sortMode = (sortMode != null) ? sortMode : SortMode.DEFAULT;
}
/*
* (non-Javadoc)
* @see com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#getComparator()
*/
@Override
public Optional<Comparator<T>> getComparator() {
return Optional.ofNullable(comparator);
}
/*
* (non-Javadoc)
* @see
* com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#setComparator(java.util.Comparator)
*/
@Override
public void setComparator(Comparator<T> comparator) {
this.comparator = comparator;
if (comparator != null) {
setSortMode(SortMode.ENABLED);
}
}
/*
* (non-Javadoc)
* @see com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#getSortOrderProvider()
*/
@Override
public Optional<SortOrderProvider> getSortOrderProvider() {
return Optional.ofNullable(sortOrderProvider);
}
/*
* (non-Javadoc)
* @see
* com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#setSortOrderProvider(com.vaadin.flow.
* component.grid.SortOrderProvider)
*/
@Override
public void setSortOrderProvider(SortOrderProvider provider) {
this.sortOrderProvider = provider;
if (provider != null) {
setSortMode(SortMode.ENABLED);
}
}
/*
* (non-Javadoc)
* @see com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#getSortProperties()
*/
@Override
public List<P> getSortProperties() {
return (sortProperties != null) ? sortProperties : Collections.emptyList();
}
/*
* (non-Javadoc)
* @see
* com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#setSortProperties(java.util.List)
*/
@Override
public void setSortProperties(List<P> sortProperties) {
this.sortProperties = sortProperties;
if (sortProperties != null && !sortProperties.isEmpty() && getSortMode() != SortMode.DISABLED) {
setSortMode(SortMode.ENABLED);
}
}
/*
* (non-Javadoc)
* @see com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#setEditorInputRenderer(com.
* holonplatform.vaadin.flow.components.Input.InputPropertyRenderer)
*/
@Override
public void setEditorInputRenderer(PropertyRenderer<Input<V>, V> editorInputRenderer) {
this.editorInputRenderer = editorInputRenderer;
if (editorInputRenderer != null && isReadOnly()) {
setReadOnly(false);
}
}
/*
* (non-Javadoc)
* @see com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#getEditorInputRenderer()
*/
@Override
public Optional<PropertyRenderer<Input<V>, V>> getEditorInputRenderer() {
return Optional.ofNullable(editorInputRenderer);
}
/*
* (non-Javadoc)
* @see
* com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#setEditorComponent(java.util.function
* .Function)
*/
@Override
public void setEditorComponent(Function<T, ? extends Component> editorComponent) {
this.editorComponent = editorComponent;
if (editorComponent != null && isReadOnly()) {
setReadOnly(false);
}
}
/*
* (non-Javadoc)
* @see com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#getEditorComponent()
*/
@Override
public Optional<Function<T, ? extends Component>> getEditorComponent() {
return Optional.ofNullable(editorComponent);
}
/*
* (non-Javadoc)
* @see
* com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#addValidator(com.holonplatform.core.
* Validator)
*/
@Override
public void addValidator(Validator<V> validator) {
ObjectUtils.argumentNotNull(validator, "Validator must be not null");
if (validators == null) {
validators = new LinkedList<>();
}
validators.add(validator);
}
/*
* (non-Javadoc)
* @see com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#getValidators()
*/
@Override
public List<Validator<V>> getValidators() {
return (validators != null) ? validators : Collections.emptyList();
}
/*
* (non-Javadoc)
* @see com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#setValidationStatusHandler(com.
* holonplatform.vaadin.flow.components.ValidationStatusHandler)
*/
@Override
public void setValidationStatusHandler(ValidationStatusHandler<Input<V>> validationStatusHandler) {
this.validationStatusHandler = validationStatusHandler;
}
/*
* (non-Javadoc)
* @see com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#getValidationStatusHandler()
*/
@Override
public Optional<ValidationStatusHandler<Input<V>>> getValidationStatusHandler() {
return Optional.ofNullable(validationStatusHandler);
}
/*
* (non-Javadoc)
* @see com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#isRequired()
*/
@Override
public boolean isRequired() {
return required;
}
/*
* (non-Javadoc)
* @see com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#setRequired(boolean)
*/
@Override
public void setRequired(boolean required) {
this.required = required;
}
/*
* (non-Javadoc)
* @see com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#getRequiredMessage()
*/
@Override
public Optional<Localizable> getRequiredMessage() {
return Optional.ofNullable(requiredMessage);
}
/*
* (non-Javadoc)
* @see
* com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#setRequiredMessage(com.holonplatform.
* core.i18n.Localizable)
*/
@Override
public void setRequiredMessage(Localizable requiredMessage) {
this.requiredMessage = requiredMessage;
}
/*
* (non-Javadoc)
* @see com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#getDefaultValueProvider()
*/
@Override
public Optional<Supplier<V>> getDefaultValueProvider() {
return Optional.ofNullable(defaultValueProvider);
}
/*
* (non-Javadoc)
* @see
* com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#setDefaultValueProvider(java.util.
* function.Supplier)
*/
@Override
public void setDefaultValueProvider(Supplier<V> defaultValueProvider) {
this.defaultValueProvider = defaultValueProvider;
}
/*
* (non-Javadoc)
* @see com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#getValueChangeListeners()
*/
@Override
public List<ValueChangeListener<V, GroupValueChangeEvent<V, P, Input<?>, EditorComponentGroup<P, T>>>> getValueChangeListeners() {
return valueChangeListeners;
}
/*
* (non-Javadoc)
* @see com.holonplatform.vaadin.flow.internal.components.support.ItemListingColumn#addValueChangeListener(com.
* holonplatform.vaadin.flow.components.ValueHolder.ValueChangeListener)
*/
@Override
public void addValueChangeListener(
ValueChangeListener<V, GroupValueChangeEvent<V, P, Input<?>, EditorComponentGroup<P, T>>> valueChangeListener) {
ObjectUtils.argumentNotNull(valueChangeListener, "ValueChangeListener must be not null");
this.valueChangeListeners.add(valueChangeListener);
}
}
| 28.538462 | 147 | 0.755633 |
a3ae0fed9381dc515c5987835d4f33f406671e03 | 935 | package io.irontest.auth;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
public class AuthResponseFilter implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
// this is to prevent browser native basic auth dialog from popping up on 401 response
if (responseContext.getStatusInfo() == Response.Status.UNAUTHORIZED) {
MultivaluedMap<String, Object> headers = responseContext.getHeaders();
headers.putSingle(HttpHeaders.WWW_AUTHENTICATE,
((String) headers.getFirst(HttpHeaders.WWW_AUTHENTICATE)).replace("Basic", "xBasic"));
}
}
}
| 44.52381 | 106 | 0.75615 |
091acf13d6647925daf2a5164320bd2edba8bf30 | 1,406 | /**
*
*/
package chapter_1;
/**
* Question 1.6: Implement a method to perform basic string compression using
* the counts of repeated characters. For example, the string aabcccccaaa would
* become a2b1c5a3. If the "compressed" string would not become smaller than the
* original string, your method should return the original string. You can
* assume the string has only uppercase and lowercase letters (a-z).
*
* @author Sudharsanan Muralidharan
*/
public class StringCompression {
/**
* Compresses the input string and returns the shorter of the two strings
* <p>
* Complexity: O(n), Additional Space: O(1)
*
* @param input
* @return compressedString
*/
public String compressString(String input) {
StringBuilder builder = new StringBuilder();
int i = 0, counter = 1;
for (i = 0; i < input.length() - 1; i++) {
if (input.charAt(i) == input.charAt(i + 1)) {
counter++;
} else {
builder.append(input.charAt(i)).append(counter);
counter = 1;
}
}
// append the counter value for the last sequence of characters
builder.append(input.charAt(i)).append(counter);
// return the shorter of the compressed and original string
return (builder.length() < input.length()) ? builder.toString() : input;
}
}
| 30.565217 | 80 | 0.618777 |
bd0f8fcadafb914e2363c4de61d0b03bc398cb79 | 2,859 | package mage.cards.b;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.Mode;
import mage.abilities.SpellAbility;
import mage.abilities.common.SimpleStaticAbility;
import mage.abilities.effects.common.cost.CostModificationEffectImpl;
import mage.abilities.keyword.FlyingAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.*;
import mage.game.Game;
import mage.target.Target;
import mage.util.CardUtil;
import java.util.Collection;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class BorealElemental extends CardImpl {
public BorealElemental(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{4}{U}");
this.subtype.add(SubType.ELEMENTAL);
this.power = new MageInt(3);
this.toughness = new MageInt(4);
// Flying
this.addAbility(FlyingAbility.getInstance());
// Spells your opponents cast that target Boreal Elemental cost {2} more to cast.
this.addAbility(new SimpleStaticAbility(new BorealElementalCostIncreaseEffect()));
}
private BorealElemental(final BorealElemental card) {
super(card);
}
@Override
public BorealElemental copy() {
return new BorealElemental(this);
}
}
class BorealElementalCostIncreaseEffect extends CostModificationEffectImpl {
BorealElementalCostIncreaseEffect() {
super(Duration.WhileOnBattlefield, Outcome.Benefit, CostModificationType.INCREASE_COST);
staticText = "Spells your opponents cast that target {this} cost {2} more to cast";
}
private BorealElementalCostIncreaseEffect(BorealElementalCostIncreaseEffect effect) {
super(effect);
}
@Override
public boolean apply(Game game, Ability source, Ability abilityToModify) {
SpellAbility spellAbility = (SpellAbility) abilityToModify;
CardUtil.adjustCost(spellAbility, -2);
return true;
}
@Override
public boolean applies(Ability abilityToModify, Ability source, Game game) {
if (!(abilityToModify instanceof SpellAbility)
|| !game.getOpponents(source.getControllerId()).contains(abilityToModify.getControllerId())) {
return false;
}
return abilityToModify
.getModes()
.getSelectedModes()
.stream()
.map(uuid -> abilityToModify.getModes().get(uuid))
.map(Mode::getTargets)
.flatMap(Collection::stream)
.map(Target::getTargets)
.flatMap(Collection::stream)
.anyMatch(uuid -> uuid.equals(source.getSourceId()));
}
@Override
public BorealElementalCostIncreaseEffect copy() {
return new BorealElementalCostIncreaseEffect(this);
}
}
| 31.417582 | 110 | 0.684155 |
7ef93ae5d4981e591af9956cb65cdb91dc40f558 | 2,430 | package cmps252.HW4_2.UnitTesting;
import static org.junit.jupiter.api.Assertions.*;
import java.io.FileNotFoundException;
import java.util.List;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import cmps252.HW4_2.Customer;
import cmps252.HW4_2.FileParser;
@Tag("37")
class Record_1262 {
private static List<Customer> customers;
@BeforeAll
public static void init() throws FileNotFoundException {
customers = FileParser.getCustomers(Configuration.CSV_File);
}
@Test
@DisplayName("Record 1262: FirstName is Cecile")
void FirstNameOfRecord1262() {
assertEquals("Cecile", customers.get(1261).getFirstName());
}
@Test
@DisplayName("Record 1262: LastName is Lorey")
void LastNameOfRecord1262() {
assertEquals("Lorey", customers.get(1261).getLastName());
}
@Test
@DisplayName("Record 1262: Company is Capitol Publishing Co")
void CompanyOfRecord1262() {
assertEquals("Capitol Publishing Co", customers.get(1261).getCompany());
}
@Test
@DisplayName("Record 1262: Address is 24 E 81st St")
void AddressOfRecord1262() {
assertEquals("24 E 81st St", customers.get(1261).getAddress());
}
@Test
@DisplayName("Record 1262: City is New York")
void CityOfRecord1262() {
assertEquals("New York", customers.get(1261).getCity());
}
@Test
@DisplayName("Record 1262: County is New York")
void CountyOfRecord1262() {
assertEquals("New York", customers.get(1261).getCounty());
}
@Test
@DisplayName("Record 1262: State is NY")
void StateOfRecord1262() {
assertEquals("NY", customers.get(1261).getState());
}
@Test
@DisplayName("Record 1262: ZIP is 10028")
void ZIPOfRecord1262() {
assertEquals("10028", customers.get(1261).getZIP());
}
@Test
@DisplayName("Record 1262: Phone is 212-288-7268")
void PhoneOfRecord1262() {
assertEquals("212-288-7268", customers.get(1261).getPhone());
}
@Test
@DisplayName("Record 1262: Fax is 212-288-9684")
void FaxOfRecord1262() {
assertEquals("212-288-9684", customers.get(1261).getFax());
}
@Test
@DisplayName("Record 1262: Email is [email protected]")
void EmailOfRecord1262() {
assertEquals("[email protected]", customers.get(1261).getEmail());
}
@Test
@DisplayName("Record 1262: Web is http://www.cecilelorey.com")
void WebOfRecord1262() {
assertEquals("http://www.cecilelorey.com", customers.get(1261).getWeb());
}
}
| 25.3125 | 75 | 0.730041 |
ff45436cefbf84d5e8c0c5c8361fccd2169582e9 | 5,564 | package com.instructure.loginapi.login.adapter;
import android.app.Activity;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import com.instructure.canvasapi2.models.AccountDomain;
import com.instructure.loginapi.login.R;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
@Deprecated
public class AccountAdapter extends BaseAdapter implements Filterable {
private LayoutInflater layoutInflater;
private Activity activity;
private List<AccountDomain> locationAccounts = new ArrayList<>();
private List<AccountDomain> originalAccounts = new ArrayList<>();
private List<AccountDomain> displayAccounts = new ArrayList<>();
private Filter filter;
public AccountAdapter(Activity activity, List<AccountDomain> originalAccounts, ArrayList<AccountDomain> locationAccounts) {
this.activity = activity;
this.layoutInflater = activity.getLayoutInflater();
this.originalAccounts = originalAccounts;
this.locationAccounts = locationAccounts;
}
@Override
public boolean areAllItemsEnabled() {
return true;
}
@Override
public int getCount() {
if(displayAccounts == null) {
return 0;
}
return displayAccounts.size();
}
@Override
public Object getItem(int position) {
return displayAccounts.get(position);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
final ViewHolder viewHolder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.accounts_adapter_item, null);
viewHolder = new ViewHolder();
viewHolder.name = (TextView) convertView.findViewById(R.id.name);
viewHolder.distance = (TextView) convertView.findViewById(R.id.distance);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder)convertView.getTag();
}
final AccountDomain account = displayAccounts.get(position);
final Double distance = account.getDistance();
viewHolder.name.setText(account.getName());
if(distance == null) {
viewHolder.distance.setText("");
viewHolder.distance.setVisibility(View.GONE);
} else {
//distance is in meters
//We calculate this in miles because the USA is dumb and still uses miles
//At the time of this most of our customers are in the USA
double distanceInMiles = (distance* 0.000621371192237334);
double distanceInKm = distance / 1000;
String distanceText = "";
if(distanceInMiles < 1) {
distanceText = activity.getString(R.string.lessThanOne);
} else if(distanceInMiles - 1 < .1) {
//we're 1 mile away
distanceText = activity.getString(R.string.oneMile);
} else {
distanceText = String.format("%.1f", distanceInMiles) + " " + activity.getString(R.string.miles) + ", " + String.format("%.1f", distanceInKm) + " " + activity.getString(R.string.kilometers);
}
viewHolder.distance.setText(distanceText);
viewHolder.distance.setVisibility(View.VISIBLE);
}
return convertView;
}
@Override
public Filter getFilter() {
if(filter == null) {
filter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
final Locale locale = Locale.getDefault();
final String toMatch = constraint.toString().toLowerCase(locale);
final FilterResults filterResults = new FilterResults();
if(!TextUtils.isEmpty(toMatch)) {
ArrayList<AccountDomain> accountContains = new ArrayList<>();
for(AccountDomain account : originalAccounts) {
if(account.getName().toLowerCase(locale).contains(toMatch) ||
toMatch.contains(account.getName().toLowerCase(locale)) ||
account.getDomain().toLowerCase(locale).contains(toMatch) ||
toMatch.contains(account.getDomain().toLowerCase(locale))) {
accountContains.add(account);
}
}
filterResults.count = accountContains.size();
filterResults.values = accountContains;
} else {
filterResults.count = locationAccounts.size();
filterResults.values = locationAccounts;
}
return filterResults;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
displayAccounts = (ArrayList<AccountDomain>) results.values;
notifyDataSetChanged();
}
};
}
return filter;
}
public static class ViewHolder {
TextView name;
TextView distance;
}
} | 36.12987 | 206 | 0.601186 |
67527d864da58272b4aff9af27f418dd9bb3581c | 1,093 | package com.yunpan.service.impl;
import java.util.List;
import com.yunpan.dao.IDiskInfoDao;
import com.yunpan.dao.impl.DiskInfoDaoImpl;
import com.yunpan.entity.DiskInfo;
import com.yunpan.service.IDiskInfoService;
/**
* 网盘操作类
* @author pamgo
* @version v1.0
*/
public class DiskInfoServiceImpl implements IDiskInfoService {
/**
* 获取用户网盘使用情况
*/
@Override
public DiskInfo load(int userid) {
IDiskInfoDao diskInfoDao = new DiskInfoDaoImpl();
return diskInfoDao.load(userid);
}
/**
* 根据用户上传文件更新网盘信息
*/
@Override
public boolean updateDiskSize(long used_size, int filenumber,
int userid) {
IDiskInfoDao diskInfoDao = new DiskInfoDaoImpl();
return diskInfoDao.updateDiskSize(used_size, filenumber, userid);
}
/**
* 查询网盘所有信息
*/
@Override
public List<DiskInfo> findDiskInfo() {
IDiskInfoDao diskInfoDao = new DiskInfoDaoImpl();
return diskInfoDao.findDiskInfo();
}
/**
* 根据用户id更新网盘信息
*/
@Override
public boolean updateDisk(long size, int id) {
IDiskInfoDao diskInfoDao = new DiskInfoDaoImpl();
return diskInfoDao.updateDisk(size, id);
}
}
| 20.240741 | 67 | 0.732845 |
7de842b67bfad5c6134df7e279edf8568d76724c | 15,810 | package com.wanhive.iot.dao;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Random;
import javax.naming.NamingException;
import org.apache.commons.validator.routines.EmailValidator;
import com.wanhive.iot.Constants;
import com.wanhive.iot.IotApplication;
import com.wanhive.iot.bean.PagedList;
import com.wanhive.iot.bean.User;
import com.wanhive.iot.provider.DataSourceProvider;
public class UserDao {
public static PagedList list(long limit, long offset, String order, String orderBy, int type, int status)
throws SQLException, NamingException {
if (limit < 0 || limit > Constants.getSettings().getMaxItemsInList()) {
throw new IllegalArgumentException("Invalid limit");
}
if (offset < 0) {
throw new IllegalArgumentException("Invalid offset");
}
StringBuilder queryBuilder = new StringBuilder();
queryBuilder.append(
"select uid, createdon, modifiedon, alias, email, type, status, flag, count(*) over() as totalrecords from wh_user ");
if (type > -1 || status > -1) { // apply filter
queryBuilder.append("where ");
int filters = 0;
if (type > -1) {
queryBuilder.append("type=?");
filters += 1;
}
if (status > -1) {
queryBuilder.append(filters > 0 ? " and " : " ");
queryBuilder.append("status=?");
}
}
String sqlParam = "email".equalsIgnoreCase(orderBy) ? "email"
: "createdon".equalsIgnoreCase(orderBy) ? "createdon" : "uid";
queryBuilder.append(" order by ");
queryBuilder.append(sqlParam);
sqlParam = "desc".equalsIgnoreCase(order) ? "desc" : "asc";
queryBuilder.append(" ");
queryBuilder.append(sqlParam);
queryBuilder.append(" limit ");
queryBuilder.append(limit);
queryBuilder.append(" offset ");
queryBuilder.append(offset);
try (Connection conn = DataSourceProvider.get().getConnection();
PreparedStatement ps = conn.prepareStatement(queryBuilder.toString());) {
int index = 1;
if (type > -1) {
ps.setInt(index++, type);
}
if (status > -1) {
ps.setInt(index, status);
}
List<User> list = new ArrayList<>();
long totalRecords = 0;
try (ResultSet rs = ps.executeQuery();) {
while (rs.next()) {
User subject = new User();
subject.setUid(rs.getLong(1));
subject.setCreatedOn(rs.getObject(2, OffsetDateTime.class));
subject.setModifiedOn(rs.getObject(3, OffsetDateTime.class));
subject.setAlias(rs.getString(4));
subject.setEmail(rs.getString(5));
subject.setType(rs.getInt(6));
subject.setStatus(rs.getInt(7));
subject.setFlag(rs.getInt(8));
totalRecords = rs.getLong(9);
list.add(subject);
}
}
PagedList pl = new PagedList();
pl.setRecordsTotal(totalRecords);
pl.setRecordsFiltered(list.size());
pl.setData(list);
return pl;
}
}
public static PagedList search(String keyword, long limit, long offset, String order, String orderBy, int type,
int status) throws SQLException, NamingException {
if (limit < 0 || limit > Constants.getSettings().getMaxItemsInList()) {
throw new IllegalArgumentException("Invalid limit");
}
if (offset < 0) {
throw new IllegalArgumentException("Invalid offset");
}
if (keyword == null || keyword.length() < Constants.getSettings().getMinSearchKeywordLength()
|| keyword.length() > Constants.getSettings().getMaxSearchKeywordLength()) {
throw new IllegalArgumentException("Invalid keyword");
}
keyword = "%" + keyword.toLowerCase() + "%";
StringBuilder queryBuilder = new StringBuilder();
queryBuilder.append(
"select uid, createdon, modifiedon, alias, email, type, status, flag, count(*) over() as totalrecords from wh_user where (lower(alias) like ? or lower(email) like ?) ");
if (type > -1 || status > -1) { // apply filter
if (type > -1) {
queryBuilder.append(" and ");
queryBuilder.append("type=?");
}
if (status > -1) {
queryBuilder.append(" and ");
queryBuilder.append("status=?");
}
}
String sqlParam = "email".equalsIgnoreCase(orderBy) ? "email"
: "createdon".equalsIgnoreCase(orderBy) ? "createdon" : "uid";
queryBuilder.append(" order by ");
queryBuilder.append(sqlParam);
sqlParam = "desc".equalsIgnoreCase(order) ? "desc" : "asc";
queryBuilder.append(" ");
queryBuilder.append(sqlParam);
queryBuilder.append(" limit ");
queryBuilder.append(limit);
queryBuilder.append(" offset ");
queryBuilder.append(offset);
try (Connection conn = DataSourceProvider.get().getConnection();
PreparedStatement ps = conn.prepareStatement(queryBuilder.toString());) {
int index = 1;
ps.setString(index++, keyword);
ps.setString(index++, keyword);
if (type > -1) {
ps.setInt(index++, type);
}
if (status > -1) {
ps.setInt(index, status);
}
List<User> list = new ArrayList<>();
long totalRecords = 0;
try (ResultSet rs = ps.executeQuery();) {
while (rs.next()) {
User subject = new User();
subject.setUid(rs.getLong(1));
subject.setCreatedOn(rs.getObject(2, OffsetDateTime.class));
subject.setModifiedOn(rs.getObject(3, OffsetDateTime.class));
subject.setAlias(rs.getString(4));
subject.setEmail(rs.getString(5));
subject.setType(rs.getInt(6));
subject.setStatus(rs.getInt(7));
subject.setFlag(rs.getInt(8));
totalRecords = rs.getLong(9);
list.add(subject);
}
}
PagedList pl = new PagedList();
pl.setRecordsTotal(totalRecords);
pl.setRecordsFiltered(list.size());
pl.setData(list);
return pl;
}
}
public static long count() throws SQLException, NamingException {
long count = 0;
String query = "select count(uid) from wh_user";
try (Connection conn = DataSourceProvider.get().getConnection();
PreparedStatement ps = conn.prepareStatement(query);) {
try (ResultSet rs = ps.executeQuery();) {
if (rs.next()) {
count = rs.getLong(1);
}
}
return count;
}
}
public static User info(long uid) throws SQLException, NamingException {
String query = "select uid, createdon, modifiedon, alias, email, type, status, flag from wh_user where uid = ?";
try (Connection conn = DataSourceProvider.get().getConnection();
PreparedStatement ps = conn.prepareStatement(query);) {
ps.setLong(1, uid);
User subject = null;
try (ResultSet rs = ps.executeQuery();) {
if (rs.next()) {
subject = new User();
subject.setUid(rs.getLong(1));
subject.setCreatedOn(rs.getObject(2, OffsetDateTime.class));
subject.setModifiedOn(rs.getObject(3, OffsetDateTime.class));
subject.setAlias(rs.getString(4));
subject.setEmail(rs.getString(5));
subject.setType(rs.getInt(6));
subject.setStatus(rs.getInt(7));
subject.setFlag(rs.getInt(8));
}
}
if (subject != null) {
return subject;
} else {
throw new NoSuchElementException("Not found");
}
}
}
public static long create(String alias, String email) throws SQLException, NamingException {
if (alias == null || alias.length() == 0) {
throw new IllegalArgumentException("Invalid alias");
}
if (!EmailValidator.getInstance().isValid(email)) {
throw new IllegalArgumentException("Invalid email");
}
String query = "insert into wh_user (alias, email, token, tokentimestamp) values(?, ?, MD5(random()::text), now()) returning uid, token";
try (Connection conn = DataSourceProvider.get().getConnection();
PreparedStatement ps = conn.prepareStatement(query);) {
ps.setString(1, alias);
ps.setString(2, email);
long uid = 0;
try (ResultSet rs = ps.executeQuery();) {
if (rs.next()) {
uid = rs.getLong(1);
IotApplication.sendEmail(email, "Wanhive IoT platform: New account",
"Your security token: " + rs.getString(2));
}
}
return uid;
}
}
public static void update(long uid, String alias, String password, int type, int status, int flag)
throws SQLException, NamingException {
StringBuilder queryBuilder = new StringBuilder();
int params = 0;
queryBuilder.append("update wh_user set modifiedon= now(),");
if (alias != null && alias.length() > 0) {
queryBuilder.append(params > 0 ? " , " : " ");
queryBuilder.append("alias=?");
params += 1;
}
if (password != null && password.length() > 0) {
queryBuilder.append(params > 0 ? " , " : " ");
queryBuilder.append("password=crypt(? , gen_salt('bf'))");
params += 1;
}
if (type > -1) {
queryBuilder.append(params > 0 ? " , " : " ");
queryBuilder.append("type=?");
params += 1;
}
if (status > -1) {
queryBuilder.append(params > 0 ? " , " : " ");
queryBuilder.append("status=?");
params += 1;
}
if (flag > -1) {
queryBuilder.append(params > 0 ? " , " : " ");
queryBuilder.append("flag=?");
params += 1;
}
queryBuilder.append(" where uid=?");
if (params == 0) {
throw new IllegalArgumentException("Invalid parameters");
}
try (Connection conn = DataSourceProvider.get().getConnection();
PreparedStatement ps = conn.prepareStatement(queryBuilder.toString());) {
int index = 1;
if (alias != null && alias.length() > 0) {
ps.setString(index++, alias);
}
if (password != null && password.length() > 0) {
ps.setString(index++, password);
}
if (type > -1) {
ps.setInt(index++, type);
}
if (status > -1) {
ps.setInt(index++, status);
}
if (flag > -1) {
ps.setInt(index++, flag);
}
ps.setLong(index, uid);
ps.executeUpdate();
}
}
public static void activate(String context, String challenge, String secret) throws SQLException, NamingException {
if (context == null || context.length() == 0 || challenge == null || challenge.length() == 0 || secret == null
|| secret.length() == 0) {
throw new IllegalArgumentException("Invalid parameters");
}
String query = "update wh_user set modifiedon= now(), password=crypt(? , gen_salt('bf')), status= 1 where email=? and token=? and (status=0 or status=1) and now() < tokentimestamp + interval '900 seconds'";
try (Connection conn = DataSourceProvider.get().getConnection();
PreparedStatement ps = conn.prepareStatement(query);) {
ps.setString(1, secret);
ps.setString(2, context);
ps.setString(3, challenge);
if (ps.executeUpdate() > 0) {
IotApplication.sendEmail(context, "Wanhive IoT platform: Account activated",
"Your account has been activated.");
} else {
throw new NoSuchElementException("Not found");
}
}
}
/*
* Generate a challenge for the given user.
*/
public static void generateChallenge(String email) throws SQLException, NamingException {
if (email == null || email.length() == 0) {
throw new IllegalArgumentException("Invalid parameters");
}
String query = "update wh_user set token=MD5(random()::text), tokentimestamp=now() where email=? returning token";
try (Connection conn = DataSourceProvider.get().getConnection();
PreparedStatement ps = conn.prepareStatement(query);) {
ps.setString(1, email);
try (ResultSet rs = ps.executeQuery();) {
if (rs.next()) {
IotApplication.sendEmail(email, "Wanhive IoT: Reset password",
"Your security token (valid for 15 minutes): " + rs.getString(1));
}
}
}
}
public static void changePassword(long userUid, String oldPassword, String password)
throws SQLException, NamingException {
if (oldPassword == null || oldPassword.length() == 0 || password == null || password.length() == 0) {
throw new IllegalArgumentException("Invalid parameters");
}
String query = "update wh_user set modifiedon= now(), password=crypt(? , gen_salt('bf')) where uid=? and password = crypt(?, password)";
try (Connection conn = DataSourceProvider.get().getConnection();
PreparedStatement ps = conn.prepareStatement(query);) {
ps.setString(1, password);
ps.setLong(2, userUid);
ps.setString(3, oldPassword);
if (ps.executeUpdate() > 0) {
return;
} else {
throw new NoSuchElementException("Not found");
}
}
}
/*
* Generates a new token string for the given user UID
*/
public static String generateToken(long uid) throws SQLException, NamingException {
String query = "insert into wh_user_token (uid, token) values (?, ?) on conflict(uid) do update set token = ?, modifiedon=now()";
try (Connection conn = DataSourceProvider.get().getConnection();
PreparedStatement ps = conn.prepareStatement(query);) {
Random random = new SecureRandom();
String token = new BigInteger(256, random).toString(16);
ps.setLong(1, uid);
ps.setString(2, token);
ps.setString(3, token);
ps.executeUpdate();
return token;
}
}
/*
* Deletes existing token associated with the given user UID
*/
public static void removeToken(long uid) throws SQLException, NamingException {
String query = "delete from wh_user_token where uid=?";
try (Connection conn = DataSourceProvider.get().getConnection();
PreparedStatement ps = conn.prepareStatement(query);) {
ps.setLong(1, uid);
ps.executeUpdate();
}
}
/*
* Deletes all the existing tokens
*/
public static void purgeTokens() throws SQLException, NamingException {
String query = "truncate wh_user_token";
try (Connection conn = DataSourceProvider.get().getConnection();
PreparedStatement ps = conn.prepareStatement(query);) {
ps.executeUpdate();
}
}
public static User verifyUser(String email, String password) throws SQLException, NamingException {
if (email == null || email.length() == 0 || password == null || password.length() == 0) {
throw new IllegalArgumentException("Invalid parameters");
}
// Status: not activated (0), active(1), deactivated(2)
String query = "select uid, createdon, modifiedon, alias, email, type, status, flag from wh_user where email=? and status=1 and password = crypt(?, password)";
try (Connection conn = DataSourceProvider.get().getConnection();
PreparedStatement ps = conn.prepareStatement(query);) {
ps.setString(1, email);
ps.setString(2, password);
User user = null;
try (ResultSet rs = ps.executeQuery();) {
while (rs.next()) {
user = new User();
user.setUid(rs.getLong(1));
user.setCreatedOn(rs.getObject(2, OffsetDateTime.class));
user.setModifiedOn(rs.getObject(3, OffsetDateTime.class));
user.setAlias(rs.getString(4));
user.setEmail(rs.getString(5));
user.setType(rs.getInt(6));
user.setStatus(rs.getInt(7));
user.setFlag(rs.getInt(8));
}
}
if (user != null) {
user.setToken(generateToken(user.getUid()));
return user;
} else {
throw new NoSuchElementException("Not found");
}
}
}
public static User verifyToken(String token) throws SQLException, NamingException {
if (token == null || token.length() == 0) {
throw new IllegalArgumentException("Invalid token");
}
String query = "update wh_user_token set usedon=now() from wh_user where wh_user_token.token = ? and wh_user.uid=wh_user_token.uid and wh_user.status=1 and now() > wh_user_token.usedon + interval '50 milliseconds' and now() < wh_user_token.modifiedon + interval '1 hour' returning wh_user.uid, wh_user.type";
try (Connection conn = DataSourceProvider.get().getConnection();
PreparedStatement ps = conn.prepareStatement(query);) {
ps.setString(1, token);
User user = null;
try (ResultSet rs = ps.executeQuery();) {
while (rs.next()) {
user = new User();
user.setUid(rs.getLong(1));
user.setType(rs.getInt(2));
}
}
if (user != null) {
return user;
} else {
throw new NoSuchElementException("Not found");
}
}
}
}
| 32.530864 | 310 | 0.66907 |
b82b309ca0096f3826a4d6009a727376bf5ae9be | 1,341 | package org.dvare.expression.operation.logical;
import org.dvare.annotations.Operation;
import org.dvare.binding.data.InstancesBinding;
import org.dvare.binding.model.ContextsBinding;
import org.dvare.exceptions.interpreter.InterpretException;
import org.dvare.exceptions.parser.ExpressionParseException;
import org.dvare.expression.Expression;
import org.dvare.expression.literal.BooleanLiteral;
import org.dvare.expression.literal.LiteralExpression;
import org.dvare.expression.operation.LogicalOperationExpression;
import org.dvare.expression.operation.OperationType;
import java.util.Stack;
/**
* @author Muhammad Hammad
* @since 2016-06-30
*/
@Operation(type = OperationType.NOT)
public class Not extends LogicalOperationExpression {
public Not() {
super(OperationType.NOT);
}
@Override
public Integer parse(String[] tokens, int pos, Stack<Expression> stack, ContextsBinding contexts) throws ExpressionParseException {
int i = findNextExpression(tokens, pos + 1, stack, contexts);
this.rightOperand = stack.pop();
stack.push(this);
return i;
}
@Override
public LiteralExpression<?> interpret(InstancesBinding instancesBinding) throws InterpretException {
return new BooleanLiteral(!toBoolean(this.rightOperand.interpret(instancesBinding)));
}
} | 31.928571 | 135 | 0.767338 |
5420e6ba8f4afaa753e74cb4b6fe277fcf0d21b6 | 289 | package com.kagito.service.impl;
import com.kagito.service.DemoService;
/**
* 告诉spring这是一个需要被管理的bean(放入spring容器)
*/
public class DemoServiceImpl implements DemoService {
@Override
public String sayHello(String name) {
System.out.println("Hello, " + name);
return "success";
}
}
| 19.266667 | 53 | 0.743945 |
089fc5c4f19e7e904b21325f3b05a85429f821e6 | 5,233 | /*
* 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.aliyuncs.scdn.model.v20171115;
import java.util.List;
import java.util.Map;
import com.aliyuncs.AcsResponse;
import com.aliyuncs.scdn.transform.v20171115.DescribeScdnServiceResponseUnmarshaller;
import com.aliyuncs.transform.UnmarshallerContext;
/**
* @author auto create
* @version
*/
public class DescribeScdnServiceResponse extends AcsResponse {
private String requestId;
private String instanceId;
private String openTime;
private String endTime;
private String protectType;
private String protectTypeValue;
private String bandwidth;
private String ccProtection;
private String dDoSBasic;
private String domainCount;
private String elasticProtection;
private String bandwidthValue;
private String ccProtectionValue;
private String dDoSBasicValue;
private String domainCountValue;
private String elasticProtectionValue;
private String priceType;
private String pricingCycle;
private List<LockReason> operationLocks;
public String getRequestId() {
return this.requestId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
public String getInstanceId() {
return this.instanceId;
}
public void setInstanceId(String instanceId) {
this.instanceId = instanceId;
}
public String getOpenTime() {
return this.openTime;
}
public void setOpenTime(String openTime) {
this.openTime = openTime;
}
public String getEndTime() {
return this.endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
}
public String getProtectType() {
return this.protectType;
}
public void setProtectType(String protectType) {
this.protectType = protectType;
}
public String getProtectTypeValue() {
return this.protectTypeValue;
}
public void setProtectTypeValue(String protectTypeValue) {
this.protectTypeValue = protectTypeValue;
}
public String getBandwidth() {
return this.bandwidth;
}
public void setBandwidth(String bandwidth) {
this.bandwidth = bandwidth;
}
public String getCcProtection() {
return this.ccProtection;
}
public void setCcProtection(String ccProtection) {
this.ccProtection = ccProtection;
}
public String getDDoSBasic() {
return this.dDoSBasic;
}
public void setDDoSBasic(String dDoSBasic) {
this.dDoSBasic = dDoSBasic;
}
public String getDomainCount() {
return this.domainCount;
}
public void setDomainCount(String domainCount) {
this.domainCount = domainCount;
}
public String getElasticProtection() {
return this.elasticProtection;
}
public void setElasticProtection(String elasticProtection) {
this.elasticProtection = elasticProtection;
}
public String getBandwidthValue() {
return this.bandwidthValue;
}
public void setBandwidthValue(String bandwidthValue) {
this.bandwidthValue = bandwidthValue;
}
public String getCcProtectionValue() {
return this.ccProtectionValue;
}
public void setCcProtectionValue(String ccProtectionValue) {
this.ccProtectionValue = ccProtectionValue;
}
public String getDDoSBasicValue() {
return this.dDoSBasicValue;
}
public void setDDoSBasicValue(String dDoSBasicValue) {
this.dDoSBasicValue = dDoSBasicValue;
}
public String getDomainCountValue() {
return this.domainCountValue;
}
public void setDomainCountValue(String domainCountValue) {
this.domainCountValue = domainCountValue;
}
public String getElasticProtectionValue() {
return this.elasticProtectionValue;
}
public void setElasticProtectionValue(String elasticProtectionValue) {
this.elasticProtectionValue = elasticProtectionValue;
}
public String getPriceType() {
return this.priceType;
}
public void setPriceType(String priceType) {
this.priceType = priceType;
}
public String getPricingCycle() {
return this.pricingCycle;
}
public void setPricingCycle(String pricingCycle) {
this.pricingCycle = pricingCycle;
}
public List<LockReason> getOperationLocks() {
return this.operationLocks;
}
public void setOperationLocks(List<LockReason> operationLocks) {
this.operationLocks = operationLocks;
}
public static class LockReason {
private String lockReason;
public String getLockReason() {
return this.lockReason;
}
public void setLockReason(String lockReason) {
this.lockReason = lockReason;
}
}
@Override
public DescribeScdnServiceResponse getInstance(UnmarshallerContext context) {
return DescribeScdnServiceResponseUnmarshaller.unmarshall(this, context);
}
}
| 22.080169 | 85 | 0.737818 |
097c7a14d6bf0cf4c789c28d1884ae2b76ba63e0 | 489 | package com.mindata.blockchain.core.repository;
import com.mindata.blockchain.core.model.MessageEntity;
/**
* @author wuweifeng wrote on 2017/10/25.
*/
public interface MessageRepository extends BaseRepository<MessageEntity> {
/**
* 删除一条记录
* @param messageId messageId
*/
void deleteByMessageId(String messageId);
/**
* 查询一个
* @param messageId messageId
* @return MessageEntity
*/
MessageEntity findByMessageId(String messageId);
}
| 22.227273 | 74 | 0.693252 |
302a54bc54347d7a6d1d74a5f3ce9ce4c642168b | 8,628 | /**
* 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.ambari.server.controller.internal;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import com.google.gson.JsonSyntaxException;
import com.google.inject.Injector;
import org.apache.ambari.server.AmbariException;
import org.apache.ambari.server.configuration.ComponentSSLConfiguration;
import org.apache.ambari.server.controller.spi.Predicate;
import org.apache.ambari.server.controller.spi.PropertyProvider;
import org.apache.ambari.server.controller.spi.Request;
import org.apache.ambari.server.controller.spi.Resource;
import org.apache.ambari.server.controller.spi.SystemException;
import org.apache.ambari.server.controller.utilities.PropertyHelper;
import org.apache.ambari.server.controller.utilities.StreamProvider;
import org.apache.ambari.server.state.Cluster;
import org.apache.ambari.server.state.Clusters;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
/**
* Property provider that is used to read HTTP data from another server.
*/
public class HttpProxyPropertyProvider extends BaseProvider implements PropertyProvider {
protected final static Logger LOG =
LoggerFactory.getLogger(HttpProxyPropertyProvider.class);
private static final Map<String, String> URL_TEMPLATES = new HashMap<String, String>();
private static final Map<String, String> MAPPINGS = new HashMap<String, String>();
private static final Map<String, String> PROPERTIES_TO_FILTER = new HashMap<String, String>();
private static final String COMPONENT_RESOURCEMANAGER = "RESOURCEMANAGER";
private static final String CONFIG_YARN_SITE = "yarn-site";
private static final String CONFIG_CORE_SITE = "core-site";
private static final String PROPERTY_YARN_HTTP_POLICY = "yarn.http.policy";
private static final String PROPERTY_HADOOP_SSL_ENABLED = "hadoop.ssl.enabled";
private static final String PROPERTY_YARN_HTTP_POLICY_VALUE_HTTPS_ONLY = "HTTPS_ONLY";
private static final String PROPERTY_HADOOP_SSL_ENABLED_VALUE_TRUE = "true";
static {
URL_TEMPLATES.put(COMPONENT_RESOURCEMANAGER, "http://%s:8088/ws/v1/cluster/info");
MAPPINGS.put(COMPONENT_RESOURCEMANAGER, PropertyHelper.getPropertyId("HostRoles", "ha_state"));
PROPERTIES_TO_FILTER.put(COMPONENT_RESOURCEMANAGER, "clusterInfo/haState");
}
private final ComponentSSLConfiguration configuration;
private StreamProvider streamProvider = null;
// !!! not yet used, but make consistent
private String clusterNamePropertyId = null;
private String hostNamePropertyId = null;
private String componentNamePropertyId = null;
private Injector injector;
private Clusters clusters;
public HttpProxyPropertyProvider(
StreamProvider stream,
ComponentSSLConfiguration configuration,
Injector inject,
String clusterNamePropertyId,
String hostNamePropertyId,
String componentNamePropertyId) {
super(new HashSet<String>(MAPPINGS.values()));
this.streamProvider = stream;
this.configuration = configuration;
this.clusterNamePropertyId = clusterNamePropertyId;
this.hostNamePropertyId = hostNamePropertyId;
this.componentNamePropertyId = componentNamePropertyId;
this.injector = inject;
this.clusters = injector.getInstance(Clusters.class);
}
/**
* This method only checks if an HTTP-type property should be fulfilled. No
* modification is performed on the resources.
*/
@Override
public Set<Resource> populateResources(Set<Resource> resources,
Request request, Predicate predicate) throws SystemException {
Set<String> ids = getRequestPropertyIds(request, predicate);
if (0 == ids.size())
return resources;
for (Resource resource : resources) {
Object hostName = resource.getPropertyValue(hostNamePropertyId);
Object componentName = resource.getPropertyValue(componentNamePropertyId);
Object clusterName = resource.getPropertyValue(clusterNamePropertyId);
if (null != hostName && null != componentName &&
MAPPINGS.containsKey(componentName.toString()) &&
URL_TEMPLATES.containsKey(componentName.toString())) {
String template = getTemplate(componentName.toString(), clusterName.toString());
String propertyId = MAPPINGS.get(componentName.toString());
String url = String.format(template, hostName);
getHttpResponse(resource, url, propertyId);
}
}
return resources;
}
private String getTemplate(String componentName, String clusterName) throws SystemException {
String template = URL_TEMPLATES.get(componentName);
if (componentName.equals(COMPONENT_RESOURCEMANAGER)) {
try {
Cluster cluster = this.clusters.getCluster(clusterName);
Map<String, String> yarnConfigProperties = cluster.getDesiredConfigByType(CONFIG_YARN_SITE).getProperties();
Map<String, String> coreConfigProperties = cluster.getDesiredConfigByType(CONFIG_CORE_SITE).getProperties();
String yarnHttpPolicy = yarnConfigProperties.get(PROPERTY_YARN_HTTP_POLICY);
String hadoopSslEnabled = coreConfigProperties.get(PROPERTY_HADOOP_SSL_ENABLED);
if ((yarnHttpPolicy != null && yarnHttpPolicy.equals(PROPERTY_YARN_HTTP_POLICY_VALUE_HTTPS_ONLY)) ||
hadoopSslEnabled != null && hadoopSslEnabled.equals(PROPERTY_HADOOP_SSL_ENABLED_VALUE_TRUE)) {
template = template.replace("http", "https");
}
} catch (AmbariException e) {
LOG.debug(String.format("Could not load cluster with name %s. %s", clusterName, e.getMessage()));
throw new SystemException(String.format("Could not load cluster with name %s.", clusterName),e);
}
}
return template;
}
private Object getPropertyValueToSet(Map<String, Object> propertyValueFromJson, Object componentName) throws SystemException {
Object result = propertyValueFromJson;
//TODO need refactoring for universalization
try {
if (PROPERTIES_TO_FILTER.get(componentName) != null) {
for (String key : PROPERTIES_TO_FILTER.get(componentName).split("/")) {
result = ((Map)result).get(key);
}
}
} catch (ClassCastException e) {
LOG.error(String.format("Error getting property value for %s. %s", PROPERTIES_TO_FILTER.get(componentName),
e.getMessage()));
throw new SystemException(String.format("Error getting property value for %s.",
PROPERTIES_TO_FILTER.get(componentName)),e);
}
return result;
}
private void getHttpResponse(Resource r, String url, String propertyIdToSet) throws SystemException {
InputStream in = null;
try {
in = streamProvider.readFrom(url);
Type mapType = new TypeToken<Map<String, Object>>(){}.getType();
Map<String, Object> propertyValueFromJson = new Gson().fromJson(IOUtils.toString(in, "UTF-8"), mapType);
Object propertyValueToSet = getPropertyValueToSet(propertyValueFromJson,
r.getPropertyValue(componentNamePropertyId));
r.setProperty(propertyIdToSet, propertyValueToSet);
}
catch (IOException ioe) {
LOG.debug("Error reading HTTP response from " + url);
r.setProperty(propertyIdToSet, null);
} catch (JsonSyntaxException jse) {
LOG.error("Error parsing HTTP response from " + url);
r.setProperty(propertyIdToSet, null);
} finally {
if (in != null) {
try {
in.close();
}
catch (IOException ioe) {
LOG.error("Error closing HTTP response stream " + url);
}
}
}
}
}
| 41.282297 | 128 | 0.733774 |
4e900b08f5b51c0e57af7aaa9a44fa452dae7678 | 588 | package leetcode_explore.trees.recurcive;
import java.util.ArrayList;
import java.util.List;
public class PostOrderTraversal {
private List<Integer> postOrderList = new ArrayList<>();
public List<Integer> postorderTraversal(TreeNode root) {
if (root != null) {
postorderTraversal(root.left);
postorderTraversal(root.right);
postOrderList.add(root.val);
}
return postOrderList;
}
public static class TreeNode {
private int val;
private TreeNode left;
private TreeNode right;
}
}
| 22.615385 | 60 | 0.644558 |
3c5e3c4e956edd5e7b700d242efbb7b8330771bf | 5,686 | /*
* (c) Copyright Christian P. Fries, Germany. Contact: [email protected].
*
* Created on 15.02.2004
*/
package net.finmath.montecarlo.interestrate.products;
import java.util.Set;
import net.finmath.exception.CalculationException;
import net.finmath.montecarlo.RandomVariable;
import net.finmath.montecarlo.interestrate.LIBORModelMonteCarloSimulationInterface;
import net.finmath.montecarlo.interestrate.products.components.AbstractProductComponent;
import net.finmath.stochastic.RandomVariableInterface;
/**
* Implements the pricing of a portfolio of AbstractLIBORMonteCarloProduct products
* under a AbstractLIBORMarketModel. The products can be scaled by weights.
*
* The value of the portfolio is that of
* \( \sum_{i=0}^{n} weights\[i\] \cdot products\[i\] \text{.} \)
*
* Note: Currently the products have to be of the same currency.
*
* @author Christian Fries
* @date 08.09.2006
* @version 1.2
*/
public class Portfolio extends AbstractProductComponent {
private static final long serialVersionUID = -1360506093081238482L;
private AbstractLIBORMonteCarloProduct[] products;
private double[] weights;
/**
* Creates a portfolio consisting of a single product and a weight.
*
* The currency of this portfolio is the currency of the product.
*
* @param product A product.
* @param weight A weight.
*/
public Portfolio(AbstractLIBORMonteCarloProduct product, double weight) {
super(product.getCurrency());
this.products = new AbstractLIBORMonteCarloProduct[] { product };
this.weights = new double[] { weight };
}
/**
* Creates a portfolio consisting of a set of products and a weights.
*
* Note: Currently the products have to be of the same currency.
*
* @param products An array of products.
* @param weights An array of weights (having the same lengths as the array of products).
*/
public Portfolio(AbstractLIBORMonteCarloProduct[] products, double[] weights) {
super();
String currency = products[0].getCurrency();
for(AbstractLIBORMonteCarloProduct product : products) {
if(!currency.equals(product.getCurrency())) {
throw new IllegalArgumentException("Product currencies do not match. Please use a constructor providing the currency of the result.");
}
}
this.products = products;
this.weights = weights;
}
/**
* Creates a portfolio consisting of a set of products and a weights.
*
* Note: Currently the products have to be of the same currency, namely the one provided.
*
* @param currency The currency of the value of this portfolio when calling <code>getValue</code>.
* @param products An array of products.
* @param weights An array of weights (having the same lengths as the array of products).
*/
public Portfolio(String currency, AbstractLIBORMonteCarloProduct[] products, double[] weights) {
super(currency);
for(AbstractLIBORMonteCarloProduct product : products) {
if(!currency.equals(product.getCurrency())) {
throw new IllegalArgumentException("Product currencies do not match. Currency conversion (via model FX) is not supported yet.");
}
}
this.products = products;
this.weights = weights;
}
@Override
public String getCurrency() {
// @TODO: We report only the currency of the first item, because mixed currency portfolios are currently not allowed.
return (products != null && products.length > 0) ? products[0].getCurrency() : null;
}
@Override
public Set<String> queryUnderlyings() {
Set<String> underlyingNames = null;
for(AbstractLIBORMonteCarloProduct product : products) {
Set<String> productUnderlyingNames;
if(product instanceof AbstractProductComponent) {
productUnderlyingNames = ((AbstractProductComponent)product).queryUnderlyings();
} else {
throw new IllegalArgumentException("Underlying cannot be queried for underlyings.");
}
if(productUnderlyingNames != null) {
if(underlyingNames == null) {
underlyingNames = productUnderlyingNames;
} else {
underlyingNames.addAll(productUnderlyingNames);
}
}
}
return underlyingNames;
}
/**
* This method returns the value random variable of the product within the specified model, evaluated at a given evalutationTime.
* Note: For a lattice this is often the value conditional to evalutationTime, for a Monte-Carlo simulation this is the (sum of) value discounted to evaluation time.
* Cashflows prior evaluationTime are not considered.
*
* @TODO The conversion between different currencies is currently not performed.
* @param evaluationTime The time on which this products value should be observed.
* @param model The model used to price the product.
* @return The random variable representing the value of the product discounted to evaluation time
* @throws net.finmath.exception.CalculationException Thrown if the valuation fails, specific cause may be available via the <code>cause()</code> method.
*/
@Override
public RandomVariableInterface getValue(double evaluationTime, LIBORModelMonteCarloSimulationInterface model) throws CalculationException {
RandomVariableInterface values = new RandomVariable(0.0);
for(int productIndex = 0; productIndex < products.length; productIndex++) {
RandomVariableInterface valueOfProduct = products[productIndex].getValue(evaluationTime, model);
double weightOfProduct = weights[productIndex];
values = values.addProduct(valueOfProduct, weightOfProduct);
}
return values;
}
/**
* @return the products
*/
public AbstractLIBORMonteCarloProduct[] getProducts() {
return products.clone();
}
/**
* @return the weights
*/
public double[] getWeights() {
return weights.clone();
}
}
| 35.761006 | 166 | 0.745339 |
5d74d6693d20ac48e6e7a1208f25943aed5fb000 | 137 | package cat.nyaa.ecore;
public enum TransactionStatus {
SUCCESS,
INSUFFICIENT_BALANCE,
UPSTREAM_FAILURE,
UNKNOWN_ERROR
} | 17.125 | 31 | 0.744526 |
c6b5a4ffa107e0f99c4baad5d014b162fe2e0a20 | 7,867 | /*
* Copyright 2018 The Bazel Authors. 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 com.google.idea.blaze.android.projectsystem;
import com.android.SdkConstants;
import com.android.tools.idea.project.ModuleBasedClassFileFinder;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.idea.blaze.android.sync.model.AndroidResourceModuleRegistry;
import com.google.idea.blaze.base.command.buildresult.OutputArtifactResolver;
import com.google.idea.blaze.base.ideinfo.ArtifactLocation;
import com.google.idea.blaze.base.ideinfo.LibraryArtifact;
import com.google.idea.blaze.base.ideinfo.TargetIdeInfo;
import com.google.idea.blaze.base.ideinfo.TargetMap;
import com.google.idea.blaze.base.io.VirtualFileSystemProvider;
import com.google.idea.blaze.base.model.BlazeProjectData;
import com.google.idea.blaze.base.sync.data.BlazeProjectDataManager;
import com.google.idea.blaze.base.sync.workspace.ArtifactLocationDecoder;
import com.google.idea.blaze.base.targetmaps.TransitiveDependencyMap;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.vfs.JarFileSystem;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.ex.temp.TempFileSystem;
import java.io.File;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nullable;
/**
* Blaze-specific implementation of the {@link com.android.tools.idea.projectsystem.ClassFileFinder}
* interface. TransitiveClosureClassFileFinder searches for class files by looking at the output
* jars belonging to each Blaze target in the transitive closure of the target corresponding to each
* resource module.
*
* <p>TODO: Prevent duplicate checking of Blaze targets. The findClassFileInModule method gets
* called for every module in the project since they all transitively depend on each other, and the
* corresponding Blaze targets have many overlapping transitive dependencies.
*/
public class TransitiveClosureClassFileFinder extends ModuleBasedClassFileFinder
implements BlazeClassFileFinder {
public static final String CLASS_FINDER_KEY = "TransitiveClosureClassFileFinder";
private final AtomicBoolean pendingJarsRefresh;
public TransitiveClosureClassFileFinder(Module module) {
super(module);
pendingJarsRefresh = new AtomicBoolean(false);
}
@Override
public boolean shouldSkipResourceRegistration() {
return false;
}
@Override
@Nullable
protected VirtualFile findClassFileInModule(Module module, String className) {
VirtualFile classFile = super.findClassFileInModule(module, className);
if (classFile != null) {
return classFile;
}
BlazeProjectData blazeProjectData =
BlazeProjectDataManager.getInstance(module.getProject()).getBlazeProjectData();
if (blazeProjectData == null) {
return null;
}
TargetMap targetMap = blazeProjectData.getTargetMap();
ArtifactLocationDecoder decoder = blazeProjectData.getArtifactLocationDecoder();
AndroidResourceModuleRegistry registry =
AndroidResourceModuleRegistry.getInstance(module.getProject());
TargetIdeInfo target = blazeProjectData.getTargetMap().get(registry.getTargetKey(module));
if (target == null || target.getJavaIdeInfo() == null) {
return null;
}
// As a potential optimization, we could choose an arbitrary android_binary target
// that depends on the library to provide a single complete resource jar,
// instead of having to rely on dynamic class generation.
// TODO: benchmark to see if optimization is worthwhile.
String classNamePath = className.replace('.', File.separatorChar) + SdkConstants.DOT_CLASS;
List<LibraryArtifact> jarsToSearch = Lists.newArrayList(target.getJavaIdeInfo().getJars());
jarsToSearch.addAll(
TransitiveDependencyMap.getInstance(module.getProject())
.getTransitiveDependencies(target.getKey())
.stream()
.map(targetMap::get)
.filter(Objects::nonNull)
.flatMap(TransitiveClosureClassFileFinder::getNonResourceJars)
.collect(Collectors.toList()));
List<File> missingClassJars = Lists.newArrayList();
for (LibraryArtifact jar : jarsToSearch) {
if (jar.getClassJar() == null || jar.getClassJar().isSource()) {
continue;
}
ArtifactLocation classJar = jar.getClassJar();
File classJarFile =
Preconditions.checkNotNull(
OutputArtifactResolver.resolve(module.getProject(), decoder, classJar),
"Fail to find file %s",
classJar.getRelativePath());
VirtualFile classJarVF =
VirtualFileSystemProvider.getInstance().getSystem().findFileByIoFile(classJarFile);
if (classJarVF == null) {
if (classJarFile.exists()) {
missingClassJars.add(classJarFile);
}
continue;
}
classFile = findClassInJar(classJarVF, classNamePath);
if (classFile != null) {
return classFile;
}
}
maybeRefreshJars(missingClassJars, pendingJarsRefresh);
return null;
}
public static Stream<LibraryArtifact> getNonResourceJars(TargetIdeInfo target) {
if (target.getJavaIdeInfo() == null) {
return null;
}
Stream<LibraryArtifact> jars = target.getJavaIdeInfo().getJars().stream();
if (target.getAndroidIdeInfo() != null) {
jars = jars.filter(jar -> !jar.equals(target.getAndroidIdeInfo().getResourceJar()));
}
return jars;
}
@Nullable
private static VirtualFile findClassInJar(final VirtualFile classJar, String classNamePath) {
VirtualFile jarRoot = getJarRootForLocalFile(classJar);
if (jarRoot == null) {
return null;
}
return jarRoot.findFileByRelativePath(classNamePath);
}
private static VirtualFile getJarRootForLocalFile(VirtualFile file) {
return ApplicationManager.getApplication().isUnitTestMode()
? TempFileSystem.getInstance().findFileByPath(file.getPath() + JarFileSystem.JAR_SEPARATOR)
: JarFileSystem.getInstance().getJarRootForLocalFile(file);
}
private static void maybeRefreshJars(Collection<File> missingJars, AtomicBoolean pendingRefresh) {
// We probably need to refresh the virtual file system to find these files, but we can't refresh
// here because we're in a read action. We also can't use the async refreshIoFiles since it
// still tries to refresh the IO files synchronously. A global async refresh can't find new
// files in the ObjFS since we're not watching it.
// We need to do our own asynchronous refresh, and guard it with a flag to prevent the event
// queue from overflowing.
if (!missingJars.isEmpty() && !pendingRefresh.getAndSet(true)) {
ApplicationManager.getApplication()
.invokeLater(
() -> {
LocalFileSystem.getInstance().refreshIoFiles(missingJars);
pendingRefresh.set(false);
},
ModalityState.NON_MODAL);
}
}
}
| 41.405263 | 100 | 0.739926 |
1f5ca72f47b5e8b458f3366ae49a8cf956f09def | 847 | package com.google.android.gms.drive.internal;
import android.os.Parcel;
import android.os.Parcelable.Creator;
import com.google.android.gms.common.internal.safeparcel.SafeParcelable;
import java.util.List;
public class CancelPendingActionsRequest implements SafeParcelable {
public static final Creator<CancelPendingActionsRequest> CREATOR = new zze();
final int mVersionCode;
final List<String> zzanK;
CancelPendingActionsRequest(int versionCode, List<String> trackingTags) {
this.mVersionCode = versionCode;
this.zzanK = trackingTags;
}
public CancelPendingActionsRequest(List<String> trackingTags) {
this(1, trackingTags);
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
zze.zza(this, dest, flags);
}
}
| 28.233333 | 81 | 0.724911 |
d4921a5c8d4e73374b216abd14745ea30d1c0943 | 793 | package com.fafabtc.data.model.vo;
import java.util.List;
/**
* Created by jastrelax on 2018/1/14.
*/
public class AssetsStatisticsHolder {
private AssetsStatisticsHeader assetsStatisticsHeader;
private List<AssetsStatistics> assetsStatisticsList;
public AssetsStatisticsHeader getAssetsStatisticsHeader() {
return assetsStatisticsHeader;
}
public void setAssetsStatisticsHeader(AssetsStatisticsHeader assetsStatisticsHeader) {
this.assetsStatisticsHeader = assetsStatisticsHeader;
}
public List<AssetsStatistics> getAssetsStatisticsList() {
return assetsStatisticsList;
}
public void setAssetsStatisticsList(List<AssetsStatistics> assetsStatisticsList) {
this.assetsStatisticsList = assetsStatisticsList;
}
}
| 25.580645 | 90 | 0.761665 |
fc27e7f6e1fa44c7dfb4735da3a01eae97a76dd5 | 827 | package io.molr.mole.server.main;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Import;
import io.molr.mole.core.conf.LocalSuperMoleConfiguration;
import io.molr.mole.server.conf.SingleMoleRestServiceConfiguration;
import io.molr.mole.server.demo.DemoConfiguration;
@SpringBootApplication
@Import({LocalSuperMoleConfiguration.class, SingleMoleRestServiceConfiguration.class, DemoConfiguration.class})
public class DemoMolrServerMain {
@SuppressWarnings("resource")
public static void main(String... args) {
if (System.getProperty("server.port") == null) {
System.setProperty("server.port", "8800");
}
SpringApplication.run(DemoMolrServerMain.class);
}
}
| 34.458333 | 111 | 0.779927 |
7072506961bc708f535d8708cd8012e45ccd38d7 | 252 | package net.cpollet.gallery.domain.albums;
import java.util.List;
public interface Albums {
Album create(AlbumName name);
Album findById(long id);
Album loadById(long id);
List<Album> findAll();
List<CachedAlbum> loadAll();
}
| 15.75 | 42 | 0.694444 |
7619cc14758cc2797482b0ba3eba9ede80009b4d | 11,710 | /*
* 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.camel.component.aws.sns;
import com.amazonaws.regions.Regions;
import org.apache.camel.component.aws.sqs.AmazonSQSClientMock;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;
public class SnsComponentConfigurationTest extends CamelTestSupport {
@Test
public void createEndpointWithMinimalConfiguration() throws Exception {
AmazonSNSClientMock mock = new AmazonSNSClientMock();
context.getRegistry().bind("amazonSNSClient", mock);
SnsComponent component = new SnsComponent(context);
SnsEndpoint endpoint = (SnsEndpoint) component.createEndpoint("aws-sns://MyTopic?amazonSNSClient=#amazonSNSClient&accessKey=xxx&secretKey=yyy");
assertEquals("MyTopic", endpoint.getConfiguration().getTopicName());
assertEquals("xxx", endpoint.getConfiguration().getAccessKey());
assertEquals("yyy", endpoint.getConfiguration().getSecretKey());
assertNotNull(endpoint.getConfiguration().getAmazonSNSClient());
assertNull(endpoint.getConfiguration().getTopicArn());
assertNull(endpoint.getConfiguration().getSubject());
assertNull(endpoint.getConfiguration().getPolicy());
}
@Test
public void createEndpointWithOnlyAccessKeyAndSecretKey() throws Exception {
SnsComponent component = new SnsComponent(context);
SnsEndpoint endpoint = (SnsEndpoint) component.createEndpoint("aws-sns://MyTopic?accessKey=xxx&secretKey=yyy");
assertEquals("MyTopic", endpoint.getConfiguration().getTopicName());
assertEquals("xxx", endpoint.getConfiguration().getAccessKey());
assertEquals("yyy", endpoint.getConfiguration().getSecretKey());
assertNull(endpoint.getConfiguration().getAmazonSNSClient());
assertNull(endpoint.getConfiguration().getTopicArn());
assertNull(endpoint.getConfiguration().getSubject());
assertNull(endpoint.getConfiguration().getPolicy());
}
@Test
public void createEndpointWithMinimalArnConfiguration() throws Exception {
AmazonSNSClientMock mock = new AmazonSNSClientMock();
context.getRegistry().bind("amazonSNSClient", mock);
SnsComponent component = new SnsComponent(context);
SnsEndpoint endpoint = (SnsEndpoint) component.createEndpoint("aws-sns://arn:aws:sns:us-east-1:account:MyTopic?amazonSNSClient=#amazonSNSClient&accessKey=xxx&secretKey=yyy");
assertNull(endpoint.getConfiguration().getTopicName());
assertEquals("arn:aws:sns:us-east-1:account:MyTopic", endpoint.getConfiguration().getTopicArn());
}
@Test
public void createEndpointWithMinimalConfigurationAndProvidedClient() throws Exception {
AmazonSNSClientMock mock = new AmazonSNSClientMock();
context.getRegistry().bind("amazonSNSClient", mock);
SnsComponent component = new SnsComponent(context);
SnsEndpoint endpoint = (SnsEndpoint) component.createEndpoint("aws-sns://MyTopic?amazonSNSClient=#amazonSNSClient");
assertEquals("MyTopic", endpoint.getConfiguration().getTopicName());
assertNull(endpoint.getConfiguration().getAccessKey());
assertNull(endpoint.getConfiguration().getSecretKey());
assertNull(endpoint.getConfiguration().getTopicArn());
assertNull(endpoint.getConfiguration().getSubject());
assertNull(endpoint.getConfiguration().getPolicy());
endpoint.start();
assertEquals("arn:aws:sns:us-east-1:541925086079:MyTopic", endpoint.getConfiguration().getTopicArn());
endpoint.stop();
}
@Test
public void createEndpointWithMaximalConfiguration() throws Exception {
AmazonSNSClientMock mock = new AmazonSNSClientMock();
context.getRegistry().bind("amazonSNSClient", mock);
SnsComponent component = new SnsComponent(context);
SnsEndpoint endpoint = (SnsEndpoint) component.createEndpoint("aws-sns://MyTopic?amazonSNSClient=#amazonSNSClient&accessKey=xxx&secretKey=yyy"
+ "&policy=%7B%22Version%22%3A%222008-10-17%22,%22Statement%22%3A%5B%7B%22Sid%22%3A%221%22,%22Effect%22%3A%22Allow%22,%22Principal%22%3A%7B%22AWS%22%3A%5B%22*%22%5D%7D,"
+ "%22Action%22%3A%5B%22sns%3ASubscribe%22%5D%7D%5D%7D&subject=The+subject+message");
assertEquals("MyTopic", endpoint.getConfiguration().getTopicName());
assertEquals("xxx", endpoint.getConfiguration().getAccessKey());
assertEquals("yyy", endpoint.getConfiguration().getSecretKey());
assertNull(endpoint.getConfiguration().getTopicArn());
assertNotNull(endpoint.getConfiguration().getAmazonSNSClient());
assertEquals("The subject message", endpoint.getConfiguration().getSubject());
assertEquals(
"{\"Version\":\"2008-10-17\",\"Statement\":[{\"Sid\":\"1\",\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"sns:Subscribe\"]}]}",
endpoint.getConfiguration().getPolicy());
}
@Test
public void createEndpointWithSQSSubscription() throws Exception {
AmazonSNSClientMock mock = new AmazonSNSClientMock();
AmazonSQSClientMock mockSQS = new AmazonSQSClientMock();
context.getRegistry().bind("amazonSNSClient", mock);
context.getRegistry().bind("amazonSQSClient", mockSQS);
SnsComponent component = new SnsComponent(context);
SnsEndpoint endpoint = (SnsEndpoint) component.createEndpoint("aws-sns://MyTopic?amazonSNSClient=#amazonSNSClient&"
+ "accessKey=xxx&secretKey=yyy&amazonSQSClient=#amazonSQSClient&queueUrl=arn:aws:sqs:us-east-1:541925086079:MyQueue&subscribeSNStoSQS=true");
assertEquals("MyTopic", endpoint.getConfiguration().getTopicName());
assertEquals("xxx", endpoint.getConfiguration().getAccessKey());
assertEquals("yyy", endpoint.getConfiguration().getSecretKey());
assertEquals("arn:aws:sqs:us-east-1:541925086079:MyQueue", endpoint.getConfiguration().getQueueUrl());
assertNotNull(endpoint.getConfiguration().getAmazonSNSClient());
assertNotNull(endpoint.getConfiguration().getAmazonSQSClient());
assertNull(endpoint.getConfiguration().getTopicArn());
assertNull(endpoint.getConfiguration().getSubject());
assertNull(endpoint.getConfiguration().getPolicy());
}
@Test(expected = IllegalArgumentException.class)
public void createEndpointWithSQSSubscriptionIllegalArgument() throws Exception {
AmazonSNSClientMock mock = new AmazonSNSClientMock();
AmazonSQSClientMock mockSQS = new AmazonSQSClientMock();
context.getRegistry().bind("amazonSNSClient", mock);
context.getRegistry().bind("amazonSQSClient", mockSQS);
SnsComponent component = new SnsComponent(context);
SnsEndpoint endpoint = (SnsEndpoint) component.createEndpoint("aws-sns://MyTopic?amazonSNSClient=#amazonSNSClient&accessKey=xxx"
+ "&secretKey=yyy&amazonSQSClient=#amazonSQSClient&subscribeSNStoSQS=true");
assertEquals("MyTopic", endpoint.getConfiguration().getTopicName());
assertEquals("xxx", endpoint.getConfiguration().getAccessKey());
assertEquals("yyy", endpoint.getConfiguration().getSecretKey());
assertNull(endpoint.getConfiguration().getQueueUrl());
assertNotNull(endpoint.getConfiguration().getAmazonSNSClient());
assertNotNull(endpoint.getConfiguration().getAmazonSQSClient());
assertNull(endpoint.getConfiguration().getTopicArn());
assertNull(endpoint.getConfiguration().getSubject());
assertNull(endpoint.getConfiguration().getPolicy());
endpoint.start();
}
@Test(expected = IllegalArgumentException.class)
public void createEndpointWithoutAccessKeyConfiguration() throws Exception {
SnsComponent component = new SnsComponent(context);
component.createEndpoint("aws-sns://MyTopic?secretKey=yyy");
}
@Test(expected = IllegalArgumentException.class)
public void createEndpointWithoutSecretKeyConfiguration() throws Exception {
SnsComponent component = new SnsComponent(context);
component.createEndpoint("aws-sns://MyTopic?accessKey=xxx");
}
@Test
public void createEndpointWithComponentElements() throws Exception {
SnsComponent component = new SnsComponent(context);
component.setAccessKey("XXX");
component.setSecretKey("YYY");
SnsEndpoint endpoint = (SnsEndpoint)component.createEndpoint("aws-sns://MyTopic");
assertEquals("MyTopic", endpoint.getConfiguration().getTopicName());
assertEquals("XXX", endpoint.getConfiguration().getAccessKey());
assertEquals("YYY", endpoint.getConfiguration().getSecretKey());
}
@Test
public void createEndpointWithComponentAndEndpointElements() throws Exception {
SnsComponent component = new SnsComponent(context);
component.setAccessKey("XXX");
component.setSecretKey("YYY");
component.setRegion(Regions.US_WEST_1.toString());
SnsEndpoint endpoint = (SnsEndpoint)component.createEndpoint("aws-sns://MyTopic?accessKey=xxxxxx&secretKey=yyyyy®ion=US_EAST_1");
assertEquals("MyTopic", endpoint.getConfiguration().getTopicName());
assertEquals("xxxxxx", endpoint.getConfiguration().getAccessKey());
assertEquals("yyyyy", endpoint.getConfiguration().getSecretKey());
assertEquals("US_EAST_1", endpoint.getConfiguration().getRegion());
}
@Test
public void createEndpointWithoutAutocreation() throws Exception {
SnsComponent component = new SnsComponent(context);
component.setAccessKey("XXX");
component.setSecretKey("YYY");
component.setRegion(Regions.US_WEST_1.toString());
SnsEndpoint endpoint = (SnsEndpoint)component.createEndpoint("aws-sns://MyTopic?accessKey=xxxxxx&secretKey=yyyyy®ion=US_EAST_1&autoCreateTopic=false");
assertEquals("MyTopic", endpoint.getConfiguration().getTopicName());
assertEquals("xxxxxx", endpoint.getConfiguration().getAccessKey());
assertEquals("yyyyy", endpoint.getConfiguration().getSecretKey());
assertEquals("US_EAST_1", endpoint.getConfiguration().getRegion());
assertEquals(false, endpoint.getConfiguration().isAutoCreateTopic());
}
@Test
public void createEndpointWithoutSecretKeyAndAccessKeyConfiguration() throws Exception {
AmazonSNSClientMock mock = new AmazonSNSClientMock();
context.getRegistry().bind("amazonSNSClient", mock);
SnsComponent component = new SnsComponent(context);
component.createEndpoint("aws-sns://MyTopic?amazonSNSClient=#amazonSNSClient");
}
}
| 52.044444 | 185 | 0.707942 |
066cb07ba886f06e2a7f876cfed5957772f2659c | 998 | package fi.evident.carpenter.utils;
import org.junit.Test;
import static fi.evident.carpenter.utils.CollectionUtils.concat;
import static fi.evident.carpenter.utils.CollectionUtils.map;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class CollectionUtilsTest {
@Test
public void concatenation() {
assertThat(concat(emptyList(), emptyList()), is(emptyList()));
assertThat(concat(asList("foo", "bar", "baz"), emptyList()), is(asList("foo", "bar", "baz")));
assertThat(concat(emptyList(), asList("foo", "bar", "baz")), is(asList("foo", "bar", "baz")));
assertThat(concat(asList("foo", "bar", "baz"), asList("quux", "xyzzy")), is(asList("foo", "bar", "baz", "quux", "xyzzy")));
}
@Test
public void mapping() {
assertThat(map(asList("foo", "xyzzy", "quux"), String::length), is(asList(3, 5, 4)));
}
}
| 36.962963 | 131 | 0.666333 |
fbd839c67eafe6a2eff4ff0bcaefce75a4232680 | 1,328 | package io.github.takzhanov.umbrella.hw02;
import org.junit.Assert;
import org.junit.Test;
import static io.github.takzhanov.umbrella.hw02.ObjectSizeAnalyzer.getDeepObjectSize;
import static io.github.takzhanov.umbrella.hw02.ObjectSizeAnalyzer.getObjectSize;
//тесты работают только с агентом в опциях
//-javaagent:target/hw02-sizeof.jar
public class ObjectSizeAnalyzerTest {
@Test
public void sizeOfNull() {
Assert.assertEquals(0, getObjectSize(null));
Assert.assertEquals(0, getDeepObjectSize(null));
}
@Test
public void testLink() {
Assert.assertTrue(getObjectSize(new Object()) >= 8);
Assert.assertEquals(getDeepObjectSize(new Object()), getDeepObjectSize(new A()));
Assert.assertTrue(getDeepObjectSize(new AWithLink()) <= getDeepObjectSize(new A()) + 8);
AWithLink aWithLink = new AWithLink();
AWithLink bWithLink = new AWithLink();
aWithLink.link = bWithLink;
bWithLink.link = aWithLink;
getDeepObjectSize(aWithLink);
}
@Test
public void testPrivate() {
getDeepObjectSize(new BWithPrivateField());
}
public static class A {
}
public static class AWithLink {
Object link;
}
public static class BWithPrivateField {
private Object o = new Object();
}
} | 28.869565 | 96 | 0.6875 |
431f93f668c456995348c033b4a2e72562f5df54 | 73 | public aspect SimpleAspect {
before(): staticinitialization(*) {
}
} | 14.6 | 36 | 0.684932 |
ea5fefc55fde5a0f511b17bf2765e2c9a6b8329f | 12,597 | /*
* Copyright 2014-2020 Rudy De Busscher (https://www.atbash.be)
*
* 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 be.atbash.ee.oauth2.sdk;
import be.atbash.ee.oauth2.sdk.auth.ClientAuthentication;
import be.atbash.ee.oauth2.sdk.auth.ClientSecretBasic;
import be.atbash.ee.oauth2.sdk.auth.Secret;
import be.atbash.ee.oauth2.sdk.http.CommonContentTypes;
import be.atbash.ee.oauth2.sdk.http.HTTPRequest;
import be.atbash.ee.oauth2.sdk.id.ClientID;
import be.atbash.ee.oauth2.sdk.token.AccessToken;
import be.atbash.ee.oauth2.sdk.token.BearerAccessToken;
import be.atbash.ee.oauth2.sdk.token.RefreshToken;
import be.atbash.ee.oauth2.sdk.token.Token;
import be.atbash.ee.oauth2.sdk.util.URLUtils;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests the token revocation request.
*/
public class TokenRevocationRequestTest {
@Test
public void testWithAccessToken_publicClient()
throws Exception {
URI endpointURI = new URI("https://c2id.com/token/revoke");
Token token = new BearerAccessToken();
TokenRevocationRequest request = new TokenRevocationRequest(endpointURI, new ClientID("123"), token);
assertThat(request.getEndpointURI()).isEqualTo(endpointURI);
assertThat(request.getClientAuthentication()).isNull();
assertThat(request.getClientID()).isEqualTo(new ClientID("123"));
assertThat(request.getToken()).isEqualTo(token);
HTTPRequest httpRequest = request.toHTTPRequest();
assertThat(httpRequest.getMethod()).isEqualTo(HTTPRequest.Method.POST);
assertThat(httpRequest.getURL().toString()).isEqualTo(endpointURI.toURL().toString());
assertThat(httpRequest.getContentType().toString()).isEqualTo(CommonContentTypes.APPLICATION_URLENCODED.toString());
assertThat(httpRequest.getAuthorization()).isNull();
assertThat(httpRequest.getQueryParameters().get("token")).isEqualTo(Collections.singletonList(token.getValue()));
assertThat(httpRequest.getQueryParameters().get("token_type_hint")).isEqualTo(Collections.singletonList("access_token"));
assertThat(httpRequest.getQueryParameters().get("client_id")).isEqualTo(Collections.singletonList("123"));
assertThat(httpRequest.getQueryParameters()).hasSize(3);
request = TokenRevocationRequest.parse(httpRequest);
assertThat(request.getEndpointURI()).isEqualTo(endpointURI);
assertThat(request.getClientAuthentication()).isNull();
assertThat(request.getClientID()).isEqualTo(new ClientID("123"));
assertThat(request.getToken().getValue()).isEqualTo(token.getValue());
assertThat(request.getToken()).isInstanceOf(AccessToken.class);
}
@Test
public void testWithAccessToken_confidentialClient()
throws Exception {
URI endpointURI = new URI("https://c2id.com/token/revoke");
Token token = new BearerAccessToken();
ClientSecretBasic clientAuth = new ClientSecretBasic(new ClientID("123"), new Secret("secret"));
TokenRevocationRequest request = new TokenRevocationRequest(endpointURI, clientAuth, token);
assertThat(request.getEndpointURI()).isEqualTo(endpointURI);
assertThat(request.getClientAuthentication()).isEqualTo(clientAuth);
assertThat(request.getClientID()).isNull();
assertThat(request.getToken()).isEqualTo(token);
HTTPRequest httpRequest = request.toHTTPRequest();
assertThat(httpRequest.getMethod()).isEqualTo(HTTPRequest.Method.POST);
assertThat(httpRequest.getURL().toString()).isEqualTo(endpointURI.toURL().toString());
assertThat(httpRequest.getContentType().toString()).isEqualTo(CommonContentTypes.APPLICATION_URLENCODED.toString());
assertThat(httpRequest.getQueryParameters().get("token")).isEqualTo(Collections.singletonList(token.getValue()));
assertThat(httpRequest.getQueryParameters().get("token_type_hint")).isEqualTo(Collections.singletonList("access_token"));
assertThat(httpRequest.getQueryParameters()).hasSize(2);
ClientSecretBasic basicAuth = ClientSecretBasic.parse(httpRequest.getAuthorization());
assertThat(basicAuth.getClientID().getValue()).isEqualTo("123");
assertThat(basicAuth.getClientSecret().getValue()).isEqualTo("secret");
request = TokenRevocationRequest.parse(httpRequest);
assertThat(request.getEndpointURI()).isEqualTo(endpointURI);
assertThat(request.getClientAuthentication().getClientID()).isEqualTo(clientAuth.getClientID());
assertThat(((ClientSecretBasic)request.getClientAuthentication()).getClientSecret()).isEqualTo(clientAuth.getClientSecret());
assertThat(request.getClientID()).isNull();
assertThat(request.getToken().getValue()).isEqualTo(token.getValue());
assertThat(request.getToken()).isInstanceOf(AccessToken.class);
}
@Test
public void testWithRefreshToken_publicClient()
throws Exception {
URI endpointURI = new URI("https://c2id.com/token/revoke");
Token token = new RefreshToken();
TokenRevocationRequest request = new TokenRevocationRequest(endpointURI, new ClientID("123"), token);
assertThat(request.getEndpointURI()).isEqualTo(endpointURI);
assertThat(request.getClientAuthentication()).isNull();
assertThat(request.getToken()).isEqualTo(token);
HTTPRequest httpRequest = request.toHTTPRequest();
assertThat(httpRequest.getMethod()).isEqualTo(HTTPRequest.Method.POST);
assertThat(httpRequest.getURL().toString()).isEqualTo(endpointURI.toURL().toString());
assertThat(httpRequest.getContentType().toString()).isEqualTo(CommonContentTypes.APPLICATION_URLENCODED.toString());
assertThat(httpRequest.getAuthorization()).isNull();
assertThat(httpRequest.getQueryParameters().get("token")).isEqualTo(Collections.singletonList(token.getValue()));
assertThat(httpRequest.getQueryParameters().get("token_type_hint")).isEqualTo(Collections.singletonList("refresh_token"));
assertThat(httpRequest.getQueryParameters().get("client_id")).isEqualTo(Collections.singletonList("123"));
assertThat(httpRequest.getQueryParameters()).hasSize(3);
request = TokenRevocationRequest.parse(httpRequest);
assertThat(request.getEndpointURI()).isEqualTo(endpointURI);
assertThat(request.getClientAuthentication()).isNull();
assertThat(request.getClientID()).isEqualTo(new ClientID("123"));
assertThat(request.getToken().getValue()).isEqualTo(token.getValue());
assertThat(request.getToken()).isInstanceOf(RefreshToken.class);
}
@Test
public void testWithRefreshToken_confidentialClient()
throws Exception {
URI endpointURI = new URI("https://c2id.com/token/revoke");
Token token = new RefreshToken();
ClientSecretBasic clientAuth = new ClientSecretBasic(new ClientID("123"), new Secret("secret"));
TokenRevocationRequest request = new TokenRevocationRequest(endpointURI, clientAuth, token);
assertThat(request.getEndpointURI()).isEqualTo(endpointURI);
assertThat(request.getClientAuthentication()).isEqualTo(clientAuth);
assertThat(request.getToken()).isEqualTo(token);
HTTPRequest httpRequest = request.toHTTPRequest();
assertThat(httpRequest.getMethod()).isEqualTo(HTTPRequest.Method.POST);
assertThat(httpRequest.getURL().toString()).isEqualTo(endpointURI.toURL().toString());
assertThat(httpRequest.getContentType().toString()).isEqualTo(CommonContentTypes.APPLICATION_URLENCODED.toString());
assertThat(httpRequest.getQueryParameters().get("token")).isEqualTo(Collections.singletonList(token.getValue()));
assertThat(httpRequest.getQueryParameters().get("token_type_hint")).isEqualTo(Collections.singletonList("refresh_token"));
assertThat(httpRequest.getQueryParameters()).hasSize(2);
ClientSecretBasic basicAuth = ClientSecretBasic.parse(httpRequest.getAuthorization());
assertThat(basicAuth.getClientID().getValue()).isEqualTo("123");
assertThat(basicAuth.getClientSecret().getValue()).isEqualTo("secret");
request = TokenRevocationRequest.parse(httpRequest);
assertThat(request.getEndpointURI()).isEqualTo(endpointURI);
assertThat(request.getClientAuthentication().getClientID()).isEqualTo(clientAuth.getClientID());
assertThat(((ClientSecretBasic)request.getClientAuthentication()).getClientSecret()).isEqualTo(clientAuth.getClientSecret());
assertThat(request.getClientID()).isNull();
assertThat(request.getToken().getValue()).isEqualTo(token.getValue());
assertThat(request.getToken()).isInstanceOf(RefreshToken.class);
}
@Test
public void testWithUnknownToken_publicClient()
throws Exception {
HTTPRequest httpRequest = new HTTPRequest(HTTPRequest.Method.POST, new URL("https://c2id.com/token/revoke"));
httpRequest.setContentType(CommonContentTypes.APPLICATION_URLENCODED);
Map<String, List<String>> queryParams = new HashMap<>();
queryParams.put("token", Collections.singletonList("abc"));
queryParams.put("client_id", Collections.singletonList("123"));
httpRequest.setQuery(URLUtils.serializeParameters(queryParams));
TokenRevocationRequest request = TokenRevocationRequest.parse(httpRequest);
assertThat(request.getToken().getValue()).isEqualTo("abc");
assertThat(request.getToken()).isNotInstanceOf(AccessToken.class);
assertThat(request.getToken()).isNotInstanceOf(RefreshToken.class);
assertThat(request.getClientAuthentication()).isNull();
assertThat(request.getClientID()).isEqualTo(new ClientID("123"));
}
@Test
public void testWithUnknownToken_confidentialClient()
throws Exception {
HTTPRequest httpRequest = new HTTPRequest(HTTPRequest.Method.POST, new URL("https://c2id.com/token/revoke"));
httpRequest.setAuthorization(new ClientSecretBasic(new ClientID("123"), new Secret("secret")).toHTTPAuthorizationHeader());
httpRequest.setContentType(CommonContentTypes.APPLICATION_URLENCODED);
Map<String, List<String>> queryParams = new HashMap<>();
queryParams.put("token", Collections.singletonList("abc"));
httpRequest.setQuery(URLUtils.serializeParameters(queryParams));
TokenRevocationRequest request = TokenRevocationRequest.parse(httpRequest);
assertThat(request.getToken().getValue()).isEqualTo("abc");
assertThat(request.getToken()).isNotInstanceOf(AccessToken.class);
assertThat(request.getToken()).isNotInstanceOf(RefreshToken.class);
assertThat(request.getClientAuthentication().getClientID()).isEqualTo(new ClientID("123"));
assertThat(((ClientSecretBasic)request.getClientAuthentication()).getClientSecret()).isEqualTo(new Secret("secret"));
assertThat(request.getClientID()).isNull();
}
@Test
public void testConstructorRequireClientAuthentication() {
IllegalArgumentException exception = Assertions.assertThrows(IllegalArgumentException.class, () -> new TokenRevocationRequest(URI.create("https://c2id.com/token"), (ClientAuthentication) null, new BearerAccessToken()));
assertThat(exception.getMessage()).isEqualTo("The client authentication must not be null");
}
@Test
public void testConstructorRequireClientID() {
IllegalArgumentException exception = Assertions.assertThrows(IllegalArgumentException.class, () -> new TokenRevocationRequest(URI.create("https://c2id.com/token"), (ClientID) null, new BearerAccessToken()));
assertThat(exception.getMessage()).isEqualTo("The client ID must not be null");
}
@Test
public void testParseMissingClientIdentification()
throws MalformedURLException {
HTTPRequest httpRequest = new HTTPRequest(HTTPRequest.Method.POST, new URL("https://c2id.com/token/revoke"));
httpRequest.setContentType(CommonContentTypes.APPLICATION_URLENCODED);
Map<String, List<String>> queryParams = new HashMap<>();
queryParams.put("token", Collections.singletonList("abc"));
httpRequest.setQuery(URLUtils.serializeParameters(queryParams));
OAuth2JSONParseException exception = Assertions.assertThrows(OAuth2JSONParseException.class, () -> TokenRevocationRequest.parse(httpRequest));
assertThat(exception.getMessage()).isEqualTo("Invalid token revocation request: No client authentication or client_id parameter found");
}
}
| 48.637066 | 227 | 0.784314 |
15009a0429bb3bc316a4f1f32cf0c16b57fe12da | 568 | package com.builtbroken.mc.prefab.gui.components;
import com.builtbroken.mc.lib.transform.vector.Point;
/**
* Created by robert on 4/23/2015.
*/
public class GuiCButton extends GuiComponent
{
public Point size;
public String name;
public GuiCButton(){}
public GuiCButton(Point pos)
{
super(pos);
}
public GuiCButton(Point pos, Point size)
{
this(pos);
this.size = size;
}
public GuiCButton(Point pos, Point size, String name)
{
this(pos, size);
this.name = name;
}
}
| 17.212121 | 57 | 0.612676 |
1cd806751a4ad399a2cf0edfba0e29190ed24e82 | 361 | package me.zeroX150.cornos.features.module.impl.external;
import me.zeroX150.cornos.features.module.Module;
import me.zeroX150.cornos.features.module.ModuleType;
public class AntiPacketKick extends Module {
public AntiPacketKick() {
super("AntiPacketKick", "Prevents you from being affected by chunk bans or similar", ModuleType.EXPLOIT);
}
}
| 32.818182 | 113 | 0.772853 |
8ea826d3e4a907d3af5ea9af463aba4c4296b841 | 2,877 | /*
Copyright 2013 the original author or authors.
Licensed under the Apache License, Version 2.0 the "License";
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package io.neba.core.util;
import org.apache.commons.lang3.builder.HashCodeBuilder;
/**
* Represents the result of a lookup of a {@link io.neba.api.annotations.ResourceModel} for
* a {@link org.apache.sling.api.resource.Resource}. Provides the found model as an {@link OsgiModelSource}
* and the resource type the model was found for. The resource type may be any type within the resource's
* resource type or node type hierarchy.
*
* @author Olaf Otto
*/
public class ResolvedModelSource<T> {
private final OsgiModelSource<T> source;
private final String resourceType;
private final int hashCode;
/**
* @param source must not be <code>null</code>
* @param resourceType must not be <code>null</code>
*/
public ResolvedModelSource(OsgiModelSource<T> source, String resourceType) {
if (source == null) {
throw new IllegalArgumentException("Method argument source must not be null.");
}
if (resourceType == null) {
throw new IllegalArgumentException("Method argument resourceType must not be null.");
}
this.source = source;
this.resourceType = resourceType;
this.hashCode = new HashCodeBuilder().append(source).append(resourceType).toHashCode();
}
public OsgiModelSource<T> getSource() {
return source;
}
/**
* The resource type for which this model was resolved. May be any type within the
* mapped resource's {@link io.neba.core.resourcemodels.registration.MappableTypeHierarchy}.
*
* @return never <code>null</code>.
*/
public String getResolvedResourceType() {
return resourceType;
}
@Override
public String toString() {
return this.resourceType + " -> [" + this.source + "]";
}
@Override
public int hashCode() {
return this.hashCode;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj == null || obj.getClass() != getClass()) {
return false;
}
ResolvedModelSource<?> other = (ResolvedModelSource<?>) obj;
return this.source.equals(other.source) &&
this.resourceType.equals(other.resourceType);
}
}
| 31.966667 | 107 | 0.664581 |
78299716dcdb8f451af4e3d18009c3298c50da58 | 1,945 | package java.net;
/*
* #%L
* Matos
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2010 - 2014 Orange SA
* %%
* 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.
* #L%
*/
public abstract class URLStreamHandler
{
// Constructors
public URLStreamHandler(){
}
// Methods
protected boolean equals(URL arg1, URL arg2){
return false;
}
protected int hashCode(URL arg1){
return 0;
}
protected abstract URLConnection openConnection(URL arg1) throws java.io.IOException;
protected URLConnection openConnection(URL arg1, Proxy arg2) throws java.io.IOException{
return (URLConnection) null;
}
protected int getDefaultPort(){
return 0;
}
protected InetAddress getHostAddress(URL arg1){
return (InetAddress) null;
}
protected void parseURL(URL arg1, java.lang.String arg2, int arg3, int arg4){
}
protected boolean sameFile(URL arg1, URL arg2){
return false;
}
protected java.lang.String toExternalForm(URL arg1){
return (java.lang.String) null;
}
protected boolean hostsEqual(URL arg1, URL arg2){
return false;
}
protected void setURL(URL arg1, java.lang.String arg2, java.lang.String arg3, int arg4, java.lang.String arg5, java.lang.String arg6){
}
protected void setURL(URL arg1, java.lang.String arg2, java.lang.String arg3, int arg4, java.lang.String arg5, java.lang.String arg6, java.lang.String arg7, java.lang.String arg8, java.lang.String arg9){
}
}
| 29.469697 | 205 | 0.713625 |
4c2df00b0e6b59b214473b7368d333b7b4659690 | 2,741 | package de.tum.in.www1.artemis.repository;
import static org.springframework.data.jpa.repository.EntityGraph.EntityGraphType.LOAD;
import java.time.ZonedDateTime;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import de.tum.in.www1.artemis.domain.Course;
/**
* Spring Data JPA repository for the Course entity.
*/
@SuppressWarnings("unused")
@Repository
public interface CourseRepository extends JpaRepository<Course, Long> {
@Query("select distinct course.teachingAssistantGroupName from Course course")
Set<String> findAllTeachingAssistantGroupNames();
@Query("select distinct course.instructorGroupName from Course course")
Set<String> findAllInstructorGroupNames();
@EntityGraph(type = LOAD, attributePaths = { "lectures", "lectures.attachments", "exams" })
@Query("select distinct course from Course course where (course.startDate <= :#{#now} or course.startDate is null) and (course.endDate >= :#{#now} or course.endDate is null)")
List<Course> findAllActiveWithLecturesAndExams(@Param("now") ZonedDateTime now);
@EntityGraph(type = LOAD, attributePaths = { "lectures", "lectures.attachments", "exams" })
Optional<Course> findWithEagerLecturesAndExamsById(long courseId);
// Note: this is currently only used for testing purposes
@Query("select distinct course from Course course left join fetch course.exercises exercises left join fetch course.lectures lectures left join fetch lectures.attachments left join fetch exercises.categories where (course.startDate <= :#{#now} or course.startDate is null) and (course.endDate >= :#{#now} or course.endDate is null)")
List<Course> findAllActiveWithEagerExercisesAndLectures(@Param("now") ZonedDateTime now);
@EntityGraph(type = LOAD, attributePaths = { "exercises", "exercises.categories", "exercises.teamAssignmentConfig" })
Course findWithEagerExercisesById(long courseId);
@EntityGraph(type = LOAD, attributePaths = { "exercises", "lectures" })
Course findWithEagerExercisesAndLecturesById(long courseId);
@Query("select distinct course from Course course where course.startDate <= :#{#now} and course.endDate >= :#{#now} and course.onlineCourse = false and course.registrationEnabled = true")
List<Course> findAllCurrentlyActiveAndNotOnlineAndEnabled(@Param("now") ZonedDateTime now);
List<Course> findAllByShortName(String shortName);
Optional<Course> findById(long courseId);
}
| 48.946429 | 337 | 0.772711 |
224e7f8071b8c41fec9bf34def9c5004d5f8c684 | 1,418 | package org.jenkinsci.plugins.ParameterizedRemoteTrigger.utils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.jenkinsci.plugins.ParameterizedRemoteTrigger.BasicBuildContext;
import org.jenkinsci.plugins.tokenmacro.MacroEvaluationException;
import org.jenkinsci.plugins.tokenmacro.TokenMacro;
public class TokenMacroUtils
{
public static String applyTokenMacroReplacements(String input, BasicBuildContext context) throws IOException
{
try {
if (isUseTokenMacro(context)) {
return TokenMacro.expandAll(context.run, context.workspace, context.listener, input);
}
}
catch (MacroEvaluationException e) {
throw new IOException(e);
}
catch (InterruptedException e) {
throw new IOException(e);
}
return input;
}
public static List<String> applyTokenMacroReplacements(List<String> inputs, BasicBuildContext context) throws IOException
{
List<String> outputs = new ArrayList<String>();
for (String input : inputs) {
outputs.add(applyTokenMacroReplacements(input, context));
}
return outputs;
}
public static boolean isUseTokenMacro(BasicBuildContext context)
{
return context != null && context.run != null && context.workspace != null && context.listener != null;
}
}
| 31.511111 | 125 | 0.685472 |
be98bc64d82553120f73cb085c14851ed64a6b67 | 5,853 | package com.microsoft.azure.practices.nvadaemon.config;
import static org.mockito.Mockito.*;
import com.microsoft.azure.management.network.NetworkInterface;
import com.microsoft.azure.practices.nvadaemon.AzureClient;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class NvaConfigurationTest {
@Test
void test_null_probe_network_interface() {
Assertions.assertThrows(IllegalArgumentException.class,
() -> new NvaConfiguration(null, null, null));
}
@Test
void test_empty_probe_network_interface() {
Assertions.assertThrows(IllegalArgumentException.class,
() -> new NvaConfiguration("", null, null));
}
@Test
void test_null_probe_port() {
Assertions.assertThrows(NullPointerException.class,
() -> new NvaConfiguration("probe-network-interface", null, null));
}
@Test
void test_zero_probe_port() {
Assertions.assertThrows(IllegalArgumentException.class,
() -> new NvaConfiguration("probe-network-interface", 0, null));
}
@Test
void test_negative_probe_port() {
Assertions.assertThrows(IllegalArgumentException.class,
() -> new NvaConfiguration("probe-network-interface", -1, null));
}
@Test
void test_null_network_interfaces() {
Assertions.assertThrows(NullPointerException.class,
() -> new NvaConfiguration("probe-network-interface", 1234, null));
}
@Test
void test_empty_network_interfaces() {
Assertions.assertThrows(IllegalArgumentException.class,
() -> new NvaConfiguration("probe-network-interface", 1234, new ArrayList<>()));
}
@Test
void test_duplicate_network_interface_ids() {
List<NamedResourceId> networkInterfaces = new ArrayList<>();
networkInterfaces.add(new NamedResourceId("nic1", "nic1-id"));
networkInterfaces.add(new NamedResourceId("nic2", "nic1-id"));
Assertions.assertThrows(IllegalArgumentException.class,
() -> new NvaConfiguration("probe-network-interface", 1234, networkInterfaces));
}
@Test
void test_duplicate_network_interface_names() {
List<NamedResourceId> networkInterfaces = new ArrayList<>();
networkInterfaces.add(new NamedResourceId("nic1", "nic1-id"));
networkInterfaces.add(new NamedResourceId("nic1", "nic2-id"));
Assertions.assertThrows(IllegalArgumentException.class,
() -> new NvaConfiguration("probe-network-interface", 1234, networkInterfaces));
}
@Test
void test_validate_null_azure_client() {
NvaConfiguration nvaConfiguration = new NvaConfiguration("probe-network-interface",
1234, Arrays.asList(new NamedResourceId("nic1", "nic1-id")));
Assertions.assertThrows(NullPointerException.class,
() -> nvaConfiguration.validate(null));
}
@Test
void test_validate_invalid_network_interfaces() {
AzureClient azureClient = mock(AzureClient.class);
List<NamedResourceId> networkInterfaces = new ArrayList<>();
networkInterfaces.add(new NamedResourceId("nic1", "nic1-id"));
NvaConfiguration nvaConfiguration = new NvaConfiguration("probe-network-interface",
1234, networkInterfaces);
when(azureClient.checkExistenceById(anyString()))
.thenReturn(false);
Assertions.assertThrows(ConfigurationException.class,
() -> nvaConfiguration.validate(azureClient));
}
@Test
void test_validate_invalid_probe_network_interfaces() {
AzureClient azureClient = mock(AzureClient.class);
List<NamedResourceId> networkInterfaces = new ArrayList<>();
networkInterfaces.add(new NamedResourceId("nic1", "nic1-id"));
NvaConfiguration nvaConfiguration = new NvaConfiguration("probe-network-interface",
1234, networkInterfaces);
when(azureClient.checkExistenceById(anyString()))
.thenReturn(true);
when(azureClient.getNetworkInterfaceById(anyString()))
.thenReturn(null);
Assertions.assertThrows(ConfigurationException.class,
() -> nvaConfiguration.validate(azureClient));
}
@Test
void test_validate_valid_probe_network_interfaces() throws ConfigurationException {
Integer probePort = 1234;
String probeNetworkInterfacePrimaryPrivateIp = "127.0.0.1";
List<NamedResourceId> networkInterfaces = new ArrayList<>();
networkInterfaces.add(new NamedResourceId("nic1", "nic1-id"));
NvaConfiguration nvaConfiguration = new NvaConfiguration("probe-network-interface",
probePort, networkInterfaces);
AzureClient azureClient = mock(AzureClient.class);
when(azureClient.checkExistenceById(anyString()))
.thenReturn(true);
NetworkInterface probeNetworkInterface = mock(NetworkInterface.class);
when(probeNetworkInterface.primaryPrivateIp())
.thenReturn(probeNetworkInterfacePrimaryPrivateIp);
when(azureClient.getNetworkInterfaceById(anyString()))
.thenReturn(probeNetworkInterface);
nvaConfiguration.validate(azureClient);
Assertions.assertEquals(networkInterfaces, nvaConfiguration.getNetworkInterfaces());
InetSocketAddress probeSocketAddress =
(InetSocketAddress)nvaConfiguration.getProbeSocketAddress();
Assertions.assertNotNull(probeSocketAddress);
Assertions.assertEquals(probePort.intValue(), probeSocketAddress.getPort());
Assertions.assertEquals(probeNetworkInterfacePrimaryPrivateIp,
probeSocketAddress.getAddress().getHostAddress());
}
}
| 41.510638 | 92 | 0.700495 |
cfa01eebe16969ea4732a2fa811511c6d7815319 | 9,909 | package com.nascentdigital.pipeline;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
public class MaxTest extends PipelineTest {
// region empty source
@Test
public void emptySource_shouldReturnNull_forBytes() {
// create empty array
final Byte[] source = new Byte[0];
// use pipeline
Byte value = Pipeline.from(source)
.maxByte(i -> i);
// assert
assertNull(value);
}
@Test
public void emptySource_shouldReturnNull_forShorts() {
// create empty array
final Short[] source = new Short[0];
// use pipeline
Short value = Pipeline.from(source)
.maxShort(i -> i);
// assert
assertNull(value);
}
@Test
public void emptySource_shouldReturnNull_forIntegers() {
// create empty array
final Integer[] source = new Integer[0];
// use pipeline
Integer value = Pipeline.from(source)
.maxInteger(i -> i);
// assert
assertNull(value);
}
@Test
public void emptySource_shouldReturnNull_forLongs() {
// create empty array
final Long[] source = new Long[0];
// use pipeline
Long value = Pipeline.from(source)
.maxLong(i -> i);
// assert
assertNull(value);
}
@Test
public void emptySource_shouldReturnNull_forFloats() {
// create empty array
final Float[] source = new Float[0];
// use pipeline
Float value = Pipeline.from(source)
.maxFloat(i -> i);
// assert
assertNull(value);
}
@Test
public void emptySource_shouldReturnNull_forDoubles() {
// create empty array
final Double[] source = new Double[0];
// use pipeline
Double value = Pipeline.from(source)
.maxDouble(i -> i);
// assert
assertNull(value);
}
// endregion
// region singleton source
@Test
public void singleSource_shouldReturnSame_forBytes() {
// create empty array
final Byte[] source = new Byte[1];
int count = 0;
for (byte n = -1; n <= 2; ++n) {
// update source
source[0] = n;
// use pipeline
Byte value = Pipeline.from(source)
.maxByte(i -> i);
// assert
assertNotNull(value);
assertEquals(n, value.byteValue());
// increment count
++count;
}
// ensure looped as expected
assertEquals(count, 4);
}
@Test
public void singleSource_shouldReturnSame_forShorts() {
// create empty array
final Short[] source = new Short[1];
int count = 0;
for (short n = -1; n <= 2; ++n) {
// update source
source[0] = n;
// use pipeline
Short value = Pipeline.from(source)
.maxShort(i -> i);
// assert
assertNotNull(value);
assertEquals(n, value.shortValue());
// increment count
++count;
}
// ensure looped as expected
assertEquals(count, 4);
}
@Test
public void singleSource_shouldReturnSame_forIntegers() {
// create empty array
final Integer[] source = new Integer[1];
int count = 0;
for (int n = -1; n <= 2; ++n) {
// update source
source[0] = n;
// use pipeline
Integer value = Pipeline.from(source)
.maxInteger(i -> i);
// assert
assertNotNull(value);
assertEquals(n, value.intValue());
// increment count
++count;
}
// ensure looped as expected
assertEquals(count, 4);
}
@Test
public void singleSource_shouldReturnSame_forLongs() {
// create empty array
final Long[] source = new Long[1];
int count = 0;
for (long n = -1; n <= 2; ++n) {
// update source
source[0] = n;
// use pipeline
Long value = Pipeline.from(source)
.maxLong(i -> i);
// assert
assertNotNull(value);
assertEquals(n, value.longValue());
// increment count
++count;
}
// ensure looped as expected
assertEquals(count, 4);
}
@Test
public void singleSource_shouldReturnSame_forFloats() {
// create empty array
final Float[] source = new Float[1];
int count = 0;
for (float n = -1; n <= 2; n += 1) {
// update source
source[0] = n;
// use pipeline
Float value = Pipeline.from(source)
.maxFloat(i -> i);
// assert
assertNotNull(value);
assertEquals(n, value, 0);
// increment count
++count;
}
// ensure looped as expected
assertEquals(count, 4);
}
@Test
public void singleSource_shouldReturnZero_forDoubles() {
// create empty array
final Double[] source = new Double[1];
int count = 0;
for (double n = -1; n <= 2; n += 1) {
// update source
source[0] = n;
// use pipeline
Double value = Pipeline.from(source)
.maxDouble(i -> i);
// assert
assertNotNull(value);
assertEquals(n, value, 0);
// increment count
++count;
}
// ensure looped as expected
assertEquals(count, 4);
}
// endregion
// region many source
@Test
public void manySource_shouldReturnBiggest_forBytes() {
// create array
final Byte[] source = new Byte[] {
-8,
9,
0,
null,
12
};
// calculate expected
Byte max = Byte.MIN_VALUE;
for (Byte value : source) {
if (value != null && value > max) {
max = value;
}
}
// use pipeline
Byte value = Pipeline.from(source)
.maxByte(i -> i);
// assert
assertNotNull(value);
assertEquals(max, value);
}
@Test
public void manySource_shouldReturnBiggest_forShorts() {
// create array
final Short[] source = new Short[] {
-8,
9,
0,
null,
12
};
// calculate expected
Short max = Short.MIN_VALUE;
for (Short value : source) {
if (value != null && value > max) {
max = value;
}
}
// use pipeline
Short value = Pipeline.from(source)
.maxShort(i -> i);
// assert
assertNotNull(value);
assertEquals(max, value);
}
@Test
public void manySource_shouldReturnBiggest_forIntegers() {
// create array
final Integer[] source = new Integer[] {
-8,
9,
0,
null,
12
};
// calculate expected
Integer max = Integer.MIN_VALUE;
for (Integer value : source) {
if (value != null && value > max) {
max = value;
}
}
// use pipeline
Integer value = Pipeline.from(source)
.maxInteger(i -> i);
// assert
assertNotNull(value);
assertEquals(max, value);
}
@Test
public void manySource_shouldReturnBiggest_forLongs() {
// create array
final Long[] source = new Long[] {
-8L,
9L,
0L,
null,
12L
};
// calculate expected
Long max = Long.MIN_VALUE;
for (Long value : source) {
if (value != null && value > max) {
max = value;
}
}
// use pipeline
Long value = Pipeline.from(source)
.maxLong(i -> i);
// assert
assertNotNull(value);
assertEquals(max, value);
}
@Test
public void manySource_shouldReturnBiggest_forFloats() {
// create array
final Float[] source = new Float[] {
-8f,
9f,
0f,
null,
12f
};
// calculate expected
Float max = Float.MIN_VALUE;
for (Float value : source) {
if (value != null && value > max) {
max = value;
}
}
// use pipeline
Float value = Pipeline.from(source)
.maxFloat(i -> i);
// assert
assertNotNull(value);
assertEquals(max, value, 0);
}
@Test
public void manySource_shouldReturnBiggest_forDoubles() {
// create array
final Double[] source = new Double[] {
-8.0,
9.0,
0.0,
null,
12.0
};
// calculate expected
Double max = Double.MIN_VALUE;
for (Double value : source) {
if (value != null && value > max) {
max = value;
}
}
// use pipeline
Double value = Pipeline.from(source)
.maxDouble(i -> i);
// assert
assertNotNull(value);
assertEquals(max, value, 0);
}
// endregion
} | 21.971175 | 62 | 0.474316 |
0eff148c2343d04e7c9d9cb06af007be9439a313 | 1,974 | package com.tlh.uncode.schedule.core;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.UndeclaredThrowableException;
import java.util.concurrent.atomic.AtomicInteger;
import com.tlh.uncode.schedule.manager.ConsoleManager;
import com.tlh.uncode.schedule.manager.DynamicTaskManager;
import com.tlh.uncode.schedule.manager.ZKScheduleManager;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ReflectionUtils;
public class ScheduledMethodRunnable implements Runnable {
private final TaskDefine taskDefine;
private AtomicInteger count = new AtomicInteger();
public ScheduledMethodRunnable(TaskDefine taskDefine) {
this.taskDefine = taskDefine;
}
public int getRunTimes(){
return count.get();
}
public TaskDefine getTaskDefine() {
return taskDefine;
}
@Override
public void run() {
Object bean = null;
Method method = null;
try {
bean = ZKScheduleManager.getApplicationcontext().getBean(taskDefine.getTargetBean());
if(taskDefine.getParams() != null){
method = DynamicTaskManager.getMethod(bean, taskDefine.getTargetMethod(), String.class);
}else{
method = DynamicTaskManager.getMethod(bean, taskDefine.getTargetMethod());
}
ReflectionUtils.makeAccessible(method);
if(taskDefine.getParams() != null){
method.invoke(bean, taskDefine.getParams());
}else{
method.invoke(bean);
}
count.incrementAndGet();
if(StringUtils.isBlank(taskDefine.getCronExpression())
&& taskDefine.getDelay() == 0 && taskDefine.getPeriod() == 0){
try {
ConsoleManager.getScheduleManager().getScheduleDataManager().delTask(taskDefine);
} catch (Exception e) {
e.printStackTrace();
}
}
}
catch (InvocationTargetException ex) {
ReflectionUtils.rethrowRuntimeException(ex.getTargetException());
}
catch (IllegalAccessException ex) {
throw new UndeclaredThrowableException(ex);
}
}
}
| 27.416667 | 92 | 0.747214 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.