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
f606089f528a75359bc06b6e76964a580ebc96fa
2,490
package fawc.buptroom.services; import com.alibaba.fastjson.JSONObject; import org.apache.hc.client5.http.classic.methods.HttpGet; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; import org.apache.hc.client5.http.impl.classic.HttpClients; import org.apache.hc.core5.http.io.entity.EntityUtils; import java.util.Map; import java.util.Objects; public class UpdateUrl { public static double getUpdateInfo() { String API_TOKEN = "656c59bd6468ce6ab95b9013a8657b09"; String APP_ID = "5fd0a3edb2eb4609be495aa8"; CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; JSONObject jsonObject = null; HttpGet httpGet = new HttpGet("http://api.bq04.com/apps/latest/" + APP_ID + "?api_token=" + API_TOKEN); try { response = httpClient.execute(httpGet); String response_body = EntityUtils.toString(response.getEntity(), "utf-8"); jsonObject = JSONObject.parseObject(response_body); } catch (Exception e) { e.printStackTrace(); } if (jsonObject != null) { return Double.parseDouble((String) Objects.requireNonNull(jsonObject.get("versionShort"))); } return 0; } public static String getDownloadUrl() { String API_TOKEN = "656c59bd6468ce6ab95b9013a8657b09"; String APP_ID = "5fd0a3edb2eb4609be495aa8"; CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; JSONObject jsonObject = null; HttpGet httpGet = new HttpGet("http://api.bq04.com/apps/" + APP_ID + "/download_token?api_token=" + API_TOKEN); try { response = httpClient.execute(httpGet); String response_body = EntityUtils.toString(response.getEntity(), "utf-8"); jsonObject = JSONObject.parseObject(response_body); } catch (Exception e) { e.printStackTrace(); } if (jsonObject != null) { for (Map.Entry<String, Object> stringObjectEntry : jsonObject.entrySet()) { if (stringObjectEntry.getKey().equals("download_token")) { return "http://download.bq04.com/apps/" + APP_ID + "/install?download_token=" + stringObjectEntry.getValue().toString(); } } } return null; } }
40.819672
140
0.657028
5bb70ea5c4d570fc8fb934a795656312bceac637
1,645
package com.ferreusveritas.dynamictrees.util.json; import com.ferreusveritas.dynamictrees.util.CommonVoxelShapes; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.shapes.VoxelShape; import net.minecraft.util.math.shapes.VoxelShapes; /** * @author Harley O'Connor */ public final class VoxelShapeGetter implements IJsonObjectGetter<VoxelShape> { @Override public ObjectFetchResult<VoxelShape> get(JsonElement jsonElement) { final ObjectFetchResult<VoxelShape> voxelShape = new ObjectFetchResult<>(); JsonHelper.JsonElementReader.of(jsonElement).ifOfType(String.class, string -> voxelShape.setValue(CommonVoxelShapes.SHAPES.getOrDefault(string.toLowerCase(), VoxelShapes.block()))) .elseIfOfType(AxisAlignedBB.class, axisAlignedBB -> voxelShape.setValue(VoxelShapes.create(axisAlignedBB))) .elseIfOfType(JsonArray.class, jsonArray -> { voxelShape.setValue(VoxelShapes.empty()); for (JsonElement element : jsonArray) { JsonHelper.JsonElementReader.of(element).ifOfType(AxisAlignedBB.class, axisAlignedBB -> VoxelShapes.or(voxelShape.getValue(), VoxelShapes.create(axisAlignedBB))) .elseUnsupportedError(voxelShape::addWarning).ifFailed(voxelShape::addWarning); } }).elseUnsupportedError(voxelShape::setErrorMessage).ifFailed(voxelShape::setErrorMessage); return voxelShape; } }
47
126
0.691185
d2c799707aa036907d0568c56305b5f829c12202
1,320
package net.kr9ly.doubler.repository; import net.kr9ly.doubler.Assisted; import net.kr9ly.doubler.providers.SampleProviders; import javax.inject.Inject; /** * Copyright 2015 kr9ly * <br /> * 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 * <br /> * http://www.apache.org/licenses/LICENSE-2.0 * <br /> * 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. */ @SampleProviders public class SampleAssistInjectRepository { private SampleFieldInjectRepository sampleFieldInjectRepository; private String suffix; @Inject public SampleAssistInjectRepository( SampleFieldInjectRepository sampleFieldInjectRepository, @Assisted String suffix ) { this.sampleFieldInjectRepository = sampleFieldInjectRepository; this.suffix = suffix; } public String getDependentAssistedString() { return sampleFieldInjectRepository.getString() + suffix; } }
30.697674
75
0.740152
a43e3f161d86638f71a8a0d232fb4e22d81a2dd2
2,309
package it.colletta.repository.user; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import it.colletta.model.UserModel; import it.colletta.repository.config.MongoConfig; import it.colletta.security.Role; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest @ContextConfiguration(classes = {MongoConfig.class}) public class UsersRepositoryImplTest { @Autowired private MongoTemplate mongoTemplate; private UsersRepositoryImpl usersRepository; private UserModel testUser1; private UserModel testUser2; @Before public void setUp() throws Exception { usersRepository = new UsersRepositoryImpl(mongoTemplate); populateDatabase(); } @After public void tearDown() throws Exception { mongoTemplate.dropCollection("users"); } private void populateDatabase() { UserModel user1 = UserModel.builder().id("1").firstName("Enrico").email("a@a.it").enabled(false) .build(); UserModel user2 = UserModel.builder().id("2").firstName("Francesco").email("b@b.it") .enabled(false).role(Role.ADMIN).build(); testUser1 = mongoTemplate.save(user1); testUser2 = mongoTemplate.save(user2); } @Test public void updateActivateFlagOnly() { usersRepository.updateActivateFlagOnly(testUser1.getId()); Query query = new Query(Criteria.where("_id").is(testUser1.getId())); UserModel updatedUser = mongoTemplate.findOne(query, UserModel.class); assertNotNull(updatedUser); assertTrue(updatedUser.isEnabled()); } @Test public void getAllUsers() { List<UserModel> users = usersRepository.getAllUsers(); assertEquals(users.size(), 1); assertEquals(users.get(0).getId(), "1"); } }
28.506173
100
0.760935
a9e4df3140baabcb0ae91780fdf10d4281987ebc
397
package com.shopify.model; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class ShopifyAccessTokenRoot { private String accessToken; @XmlAttribute(name = "access_token") public String getAccessToken() { return accessToken; } public void setAccessToken(String accessToken) { this.accessToken = accessToken; } }
19.85
49
0.788413
9108ce14f38d349a3bffc8387d4c0a0ade80a83f
2,705
package mams.storage; import static java.util.Objects.requireNonNull; import java.io.IOException; import java.nio.file.Path; import java.util.Optional; import java.util.logging.Logger; import mams.commons.core.LogsCenter; import mams.commons.exceptions.DataConversionException; import mams.commons.exceptions.IllegalValueException; import mams.commons.util.FileUtil; import mams.commons.util.JsonUtil; import mams.logic.history.ReadOnlyCommandHistory; /** * A class to access CommandHistory data stored as a json file on the hard disk. */ public class JsonCommandHistoryStorage implements CommandHistoryStorage { private static final Logger logger = LogsCenter.getLogger(JsonCommandHistoryStorage.class); private Path filePath; public JsonCommandHistoryStorage(Path filePath) { this.filePath = filePath; } public Path getCommandHistoryFilePath() { return filePath; } @Override public Optional<ReadOnlyCommandHistory> readCommandHistory() throws DataConversionException { return readCommandHistory(filePath); } /** * See {@link #readCommandHistory()}. * * @param filePath the location of the data file. must point to a valid file, and cannot be null * @throws DataConversionException if the file is not in the correct format. */ public Optional<ReadOnlyCommandHistory> readCommandHistory(Path filePath) throws DataConversionException { requireNonNull(filePath); Optional<JsonSerializableCommandHistory> jsonCommandHistory = JsonUtil.readJsonFile( filePath, JsonSerializableCommandHistory.class); if (jsonCommandHistory.isEmpty()) { return Optional.empty(); } try { return Optional.of(jsonCommandHistory.get().toLogicType()); } catch (IllegalValueException ive) { logger.info("Illegal values found in " + filePath + ": " + ive.getMessage()); throw new DataConversionException(ive); } } @Override public void saveCommandHistory(ReadOnlyCommandHistory commandHistory) throws IOException { saveCommandHistory(commandHistory, filePath); } /** * See {@link #saveCommandHistory(ReadOnlyCommandHistory)}. * * @param filePath the location of the data file. must point to a valid file, and cannot be null */ public void saveCommandHistory(ReadOnlyCommandHistory commandHistory, Path filePath) throws IOException { requireNonNull(commandHistory); requireNonNull(filePath); FileUtil.createIfMissing(filePath); JsonUtil.saveJsonFile(new JsonSerializableCommandHistory(commandHistory), filePath); } }
33.395062
110
0.720518
473305c5216ec923f426c308f59106e7449b1d80
728
package com.spring.graphexample.model; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import org.junit.jupiter.api.Test; class JobVacancyTest { @Test final void test() { JobVacancy jobVacancy = new JobVacancy(1, "jobCompany", "jobTitle", "jobDescription", "jobLocation", 1); assertEquals(1, jobVacancy.getJobCompanyId()); assertEquals("jobCompany", jobVacancy.getJobCompany()); assertEquals("jobTitle", jobVacancy.getJobTitle()); assertEquals("jobDescription", jobVacancy.getJobDescription()); assertEquals("jobLocation", jobVacancy.getJobLocation()); assertEquals(1, jobVacancy.getJobLevel()); assertNotNull(jobVacancy); } }
30.333333
106
0.770604
2968b9264d30a92dceaecd5f387842d1e7b76c8d
1,891
package com.xeiam.xchange.cryptotrade.dto.marketdata; import java.math.BigDecimal; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.xeiam.xchange.cryptotrade.dto.CryptoTradeBaseResponse; import com.xeiam.xchange.cryptotrade.dto.CryptoTradeTickerDeserializer; @JsonDeserialize(using = CryptoTradeTickerDeserializer.class) public class CryptoTradeTicker extends CryptoTradeBaseResponse { private final BigDecimal last; private final BigDecimal low; private final BigDecimal high; private final BigDecimal volumeTradeCurrency; private final BigDecimal volumePriceCurrency; private final BigDecimal minAsk; private final BigDecimal maxBid; public CryptoTradeTicker(BigDecimal last, BigDecimal low, BigDecimal high, BigDecimal volumeTradeCurrency, BigDecimal volumePriceCurrency, BigDecimal minAsk, BigDecimal maxBid, String status, String error) { super(status, error); this.last = last; this.low = low; this.high = high; this.volumeTradeCurrency = volumeTradeCurrency; this.volumePriceCurrency = volumePriceCurrency; this.minAsk = minAsk; this.maxBid = maxBid; } public BigDecimal getLast() { return last; } public BigDecimal getLow() { return low; } public BigDecimal getHigh() { return high; } public BigDecimal getVolumeTradeCurrency() { return volumeTradeCurrency; } public BigDecimal getVolumePriceCurrency() { return volumePriceCurrency; } public BigDecimal getMinAsk() { return minAsk; } public BigDecimal getMaxBid() { return maxBid; } @Override public String toString() { return "CryptoTradeTicker [last=" + last + ", low=" + low + ", high=" + high + ", volumeTradeCurrency=" + volumeTradeCurrency + ", volumePriceCurrency=" + volumePriceCurrency + ", minAsk=" + minAsk + ", maxBid=" + maxBid + "]"; } }
24.881579
140
0.735061
2fc9454c3923d38cff0da3182c228215a6dda0f8
2,962
package org.newdawn.slick.tests; import org.newdawn.slick.AppGameContainer; import org.newdawn.slick.BasicGame; import org.newdawn.slick.Color; import org.newdawn.slick.Game; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.ShapeFill; import org.newdawn.slick.SlickException; import org.newdawn.slick.fills.GradientFill; import org.newdawn.slick.geom.Polygon; import org.newdawn.slick.geom.Rectangle; import org.newdawn.slick.geom.Shape; public class GradientImageTest extends BasicGame { private Image image1; private Image image2; private GradientFill fill; private Shape shape; private Polygon poly; private GameContainer container; private float ang; private boolean rotating = false; public GradientImageTest() { super("Gradient Image Test"); } public void init(GameContainer container) throws SlickException { this.container = container; this.image1 = new Image("testdata/grass.png"); this.image2 = new Image("testdata/rocks.png"); this.fill = new GradientFill(-64.0F, 0.0F, new Color(1.0F, 1.0F, 1.0F, 1.0F), 64.0F, 0.0F, new Color(0, 0, 0, 0)); this.shape = (Shape)new Rectangle(336.0F, 236.0F, 128.0F, 128.0F); this.poly = new Polygon(); this.poly.addPoint(320.0F, 220.0F); this.poly.addPoint(350.0F, 200.0F); this.poly.addPoint(450.0F, 200.0F); this.poly.addPoint(480.0F, 220.0F); this.poly.addPoint(420.0F, 400.0F); this.poly.addPoint(400.0F, 390.0F); } public void render(GameContainer container, Graphics g) { g.drawString("R - Toggle Rotationg", 10.0F, 50.0F); g.drawImage(this.image1, 100.0F, 236.0F); g.drawImage(this.image2, 600.0F, 236.0F); g.translate(0.0F, -150.0F); g.rotate(400.0F, 300.0F, this.ang); g.texture(this.shape, this.image2); g.texture(this.shape, this.image1, (ShapeFill)this.fill); g.resetTransform(); g.translate(0.0F, 150.0F); g.rotate(400.0F, 300.0F, this.ang); g.texture((Shape)this.poly, this.image2); g.texture((Shape)this.poly, this.image1, (ShapeFill)this.fill); g.resetTransform(); } public void update(GameContainer container, int delta) { if (this.rotating) this.ang += delta * 0.1F; } public static void main(String[] argv) { try { AppGameContainer container = new AppGameContainer((Game)new GradientImageTest()); container.setDisplayMode(800, 600, false); container.start(); } catch (SlickException e) { e.printStackTrace(); } } public void keyPressed(int key, char c) { if (key == 19) this.rotating = !this.rotating; if (key == 1) this.container.exit(); } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\org\newdawn\slick\tests\GradientImageTest.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
30.854167
144
0.681634
a61d7ec2c706d50a1121d6e9f6f2d623d6e0dc00
3,295
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.file.Files; import java.nio.file.Paths; /** * This class allow us to load a sudoku from a file and print it * It's also used to merge the unsolved sudoku with the values from the CSP */ public class Sudoku { private int[][] values; public static final int SUDOKU_SIZE = 9; public Sudoku() { values = new int[SUDOKU_SIZE][SUDOKU_SIZE]; } public void loadArrays(int[][] val, int[][] assignment) { for (int i = 0; i < Sudoku.SUDOKU_SIZE; ++i) { for (int j = 0; j < Sudoku.SUDOKU_SIZE; ++j) { values[i][j] = assignment[i][j] == 0 ? val[i][j] : assignment[i][j]; } } } public void loadFile(String filename) { try (InputStream in = Files.newInputStream(Paths.get(filename)); BufferedReader reader = new BufferedReader(new InputStreamReader(in))) { String line = null; int lineNumber = 0; while ((line = reader.readLine()) != null) { for (int i = 0; i < line.length(); ++i) values[lineNumber][i] = Integer.parseInt(line.charAt(i) + ""); lineNumber++; } } catch (IOException x) { System.err.println(x); } } public void print() { for (int i = 0; i < SUDOKU_SIZE; ++i) { if (i % 3 == 0 && i != 0) System.out.println("|\n-------------------"); else if (i % 3 == 0) System.out.println("\n-------------------"); else System.out.println("|"); for (int j = 0; j < SUDOKU_SIZE; ++j) { if (j % 3 == 0) System.out.print("|"); else System.out.print(" "); System.out.print(values[i][j]); } } System.out.println("|\n-------------------"); } public boolean isGood() { for (int i = 0; i < Sudoku.SUDOKU_SIZE; ++i) { for (int j = 0; j < Sudoku.SUDOKU_SIZE; ++j) { for (int line = 0; line < Sudoku.SUDOKU_SIZE; ++line) { if (line != j && values[i][j] == values[i][line]) return false; } for (int column = 0; column < Sudoku.SUDOKU_SIZE; ++column) { if (column != i && values[i][j] == values[column][j]) return false; } int minX = (i/3) * 3; int maxX = minX + 3; int minY = (j/3) * 3; int maxY = minY + 3; for (int squareX = minX; squareX < maxX; ++squareX) { for (int squareY = minY; squareY < maxY; ++squareY) { if (squareX != i && squareY != j && values[i][j] == values[squareX][squareY]) { return false; } } } } } return true; } public int[][] getValues() { return values; } public void setValues(int[][] values) { this.values = values; } }
33.969072
103
0.450379
fc076e66745ff0b00d3008753a4c9b7de7252f85
551
package se.jocke.nb.http.bp.core.preferences; import java.util.prefs.Preferences; import org.openide.util.NbPreferences; import se.jocke.nb.http.bp.core.config.ProxyConfig; public class ProxyPreferences { private static final Preferences PREFERENCES = NbPreferences.forModule(ProxyPreferences.class); public static String getBindAddress() { return PREFERENCES.get(ProxyConfig.BIND_ADDRESS.getKey(), "localhost"); } public static int getPort() { return PREFERENCES.getInt(ProxyConfig.PORT.getKey(), 8686); } }
27.55
99
0.747731
fc3db93aa3132e4ff6a25c0c33839198b836a77e
1,371
/* * Copyright 2016 The Netty Project * * The Netty Project 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 io.netty.handler.ssl; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufHolder; /** * A marker interface for PEM encoded values. */ interface PemEncoded extends ByteBufHolder { /** * Returns {@code true} if the PEM encoded value is considered * sensitive information such as a private key. */ boolean isSensitive(); @Override PemEncoded copy(); @Override PemEncoded duplicate(); @Override PemEncoded retainedDuplicate(); @Override PemEncoded replace(ByteBuf content); @Override PemEncoded retain(); @Override PemEncoded retain(int increment); @Override PemEncoded touch(); @Override PemEncoded touch(Object hint); }
24.482143
78
0.706783
bac130d40a74ef0c14771d7a140232dac43d1e92
4,266
/******************************************************************************* * Copyright 2012 Danny Kunz * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package org.omnaest.utils.structure.iterator; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.junit.Test; import org.omnaest.utils.structure.collection.list.ListUtils; import org.omnaest.utils.structure.element.converter.ElementConverter; import org.omnaest.utils.structure.element.converter.ElementConverterIdentitiyCast; import org.omnaest.utils.structure.element.converter.ElementConverterNumberToString; import org.omnaest.utils.structure.element.converter.ElementConverterStringToLong; import org.omnaest.utils.structure.element.factory.Factory; /** * @see IteratorUtils * @author Omnaest */ public class IteratorUtilsTest { @SuppressWarnings({ "unchecked", "rawtypes" }) @Test public void testValueOf() { // final List<String> list0 = Arrays.asList( "a", "b" ); final List<String> list1 = Arrays.asList( "b", "c" ); Iterable[] iterables = new Iterable[] { list0, list1 }; Iterator[] iterators = IteratorUtils.valueOf( iterables ); // assertEquals( 2, iterators.length ); assertEquals( list0, ListUtils.valueOf( iterators[0] ) ); assertEquals( list1, ListUtils.valueOf( iterators[1] ) ); } @Test public void testFactoryBasedIterator() { // final Factory<Iterator<String>> iteratorFactory = new Factory<Iterator<String>>() { /* ********************************************** Variables ********************************************** */ private int counter = 1; /* ********************************************** Methods ********************************************** */ @Override public Iterator<String> newInstance() { // return this.counter++ <= 3 ? Arrays.asList( "a", "b", "c" ).iterator() : null; } }; Iterator<String> iterator = IteratorUtils.factoryBasedIterator( iteratorFactory ); assertNotNull( iterator ); assertEquals( Arrays.asList( "a", "b", "c", "a", "b", "c", "a", "b", "c" ), ListUtils.valueOf( iterator ) ); } @Test public void testAdapter() { // final List<String> sourceList = Arrays.asList( "100", "101", "102" ); final Iterator<String> iterator = sourceList.iterator(); final ElementConverter<String, Long> elementConverterFirst = new ElementConverterStringToLong(); final ElementConverter<Long, Long> elementConverterSecond = new ElementConverterIdentitiyCast<Long, Long>(); final ElementConverter<Number, String> elementConverterThird = new ElementConverterNumberToString(); assertEquals( sourceList, ListUtils.valueOf( IteratorUtils.adapter( iterator, elementConverterFirst, elementConverterSecond, elementConverterThird ) ) ); } @Test public void testDrainTo() { // final Collection<String> collection = new ArrayList<String>(); final int maxNumberOfElements = 2; final ArrayList<String> sourceList = new ArrayList<String>( Arrays.asList( "a", "b", "c" ) ); IteratorUtils.drainTo( sourceList.iterator(), collection, maxNumberOfElements ); // assertEquals( Arrays.asList( "a", "b" ), collection ); assertEquals( Arrays.asList( "c" ), sourceList ); } }
39.137615
129
0.616503
5b3ceac8ebe4df88c26722ada029439fb7803631
401
/** * Copyright (c) 2013-Now http://jeesite.com All rights reserved. */ package com.jeesite.modules.company.dao; import com.jeesite.common.dao.CrudDao; import com.jeesite.common.mybatis.annotation.MyBatisDao; import com.jeesite.modules.company.entity.XsCompany; /** * 单位信息DAO接口 * @author Damon * @version 2019-12-26 */ @MyBatisDao public interface XsCompanyDao extends CrudDao<XsCompany> { }
22.277778
65
0.755611
a31224610d825bac44c01a75fafecc83319325ca
1,150
/* * Copyright (C) 2014 Civilian Framework. * * Licensed under the Civilian License (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.civilian-framework.org/license.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.civilian.samples.crm.web.root.opportunities.id; import org.civilian.samples.crm.db.entity.Opportunity; import org.civilian.samples.crm.web.CrmPathParams; import org.civilian.samples.crm.web.root.opportunities.OpportunitiesController; public abstract class OpportunityController extends OpportunitiesController { protected Opportunity getOpportunity() throws Exception { Integer id = getRequest().getPathParam(CrmPathParams.OPPORTUNITYID); return id != null ? getApplication().getOpportunityService().getOpportunity(id) : null; } }
35.9375
89
0.77913
618762c57972af576b52c0799f3284461985c2ee
598
package br.com.zup.proposta.service; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import br.com.zup.proposta.dto.ResponseConsultaDoSolicitanteDto; import br.com.zup.proposta.requests.ConsultaRequest; @FeignClient(url = "${api.analise}", name = "consulta") public interface ConsultaDadosDoSolicitanteService { @RequestMapping(method = RequestMethod.POST, value = "/solicitacao") public ResponseConsultaDoSolicitanteDto consultar(ConsultaRequest request); }
37.375
76
0.829431
d166c12fbc5f434262bdbb1e8cf53f24d6a60963
701
package io.primeval.reflex.proxy.handler.helper; import io.primeval.reflex.arguments.ArgumentsProvider; import io.primeval.reflex.proxy.CallContext; import io.primeval.reflex.proxy.handler.CharInterceptionHandler; public final class CharInterceptionHelper extends InterceptionHelper { private final CharInterceptionHandler handler; public CharInterceptionHelper(CallContext context, CharInterceptionHandler handler) { super(handler); this.handler = handler; } public <E extends Throwable> char invoke() throws E { return handler.invoke(arguments); } @Override protected ArgumentsProvider argumentsProvider() { return handler; } }
26.961538
89
0.751783
867b5e6a2420ff286cbc7da7d27961ad4083cedc
3,301
package ysoserial.payloads; import com.sun.rowset.JdbcRowSetImpl; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.math.BigInteger; import java.util.Comparator; import java.util.HashMap; import java.util.PriorityQueue; import java.util.TreeMap; import org.apache.commons.beanutils.BeanComparator; import org.apache.commons.dbcp.datasources.InstanceKeyDataSource; import org.apache.commons.dbcp.datasources.SharedPoolDataSource; import sun.misc.Unsafe; import ysoserial.payloads.annotation.Authors; import ysoserial.payloads.annotation.Dependencies; import ysoserial.payloads.util.Gadgets; import ysoserial.payloads.util.PayloadRunner; import ysoserial.payloads.util.Reflections; @SuppressWarnings({ "rawtypes", "unchecked" }) @Dependencies({"commons-beanutils:commons-beanutils:1.9.2", "commons-collections:commons-collections:3.1", "commons-logging:commons-logging:1.2"}) @Authors({ Authors.FROHOFF }) public class CommonsBeanutils1 implements ObjectPayload<Object> { public Object getObject(final String ... command) throws Exception { Object templates = Gadgets.createTemplatesImpl(ReverseShell.class); // final Object templates = Gadgets.createTemplatesImpl(command); // mock method name until armed final BeanComparator comparator = new BeanComparator("activeServers"); return makeTreeMap(templates, comparator); } public static JdbcRowSetImpl makeJNDIRowSet ( String jndiUrl ) throws Exception { JdbcRowSetImpl rs = new JdbcRowSetImpl(); rs.setDataSourceName(jndiUrl); rs.setMatchColumn("foo"); Reflections.getField(javax.sql.rowset.BaseRowSet.class, "listeners").set(rs, null); return rs; } public static PriorityQueue<Object> makeQueue(Object templates, Comparator comparator) throws Exception { // create queue with numbers and basic comparator final PriorityQueue<Object> queue = new PriorityQueue<Object>(2, comparator); // stub data for replacement later queue.add(new BigInteger("1")); queue.add(new BigInteger("1")); // switch method called by comparator Reflections.setFieldValue(comparator, "property", "outputProperties"); // switch contents of queue final Object[] queueArray = (Object[]) Reflections.getFieldValue(queue, "queue"); queueArray[0] = templates; queueArray[1] = templates; return queue; } public static TreeMap<Object, Object> makeTreeMap ( Object tgt, Comparator comparator ) throws Exception { TreeMap<Object, Object> tm = new TreeMap<>(comparator); Class<?> entryCl = Class.forName("java.util.TreeMap$Entry"); Constructor<?> entryCons = entryCl.getDeclaredConstructor(Object.class, Object.class, entryCl); entryCons.setAccessible(true); Field leftF = Reflections.getField(entryCl, "left"); Field rootF = Reflections.getField(TreeMap.class, "root"); Object root = entryCons.newInstance(tgt, tgt, null); leftF.set(root, entryCons.newInstance(tgt, tgt, root)); rootF.set(tm, root); Reflections.setFieldValue(tm, "size", 2); return tm; } public static void main(final String[] args) throws Exception { PayloadRunner.run(CommonsBeanutils1.class, args); } }
40.753086
146
0.729476
da622f77aee033c18201311171e2fcec332f6a26
1,143
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class BSTIterator { //将BST全部放入一个数组里面 //inorder遍历 由于中序遍历会得到从小到大的有序数组 ArrayList<Integer> sortedNode; // declare an ArrayList int index; public BSTIterator(TreeNode root) { this.sortedNode = new ArrayList<Integer>(); this.index = 0; this.inorder(root); } private void inorder(TreeNode root) { if (root == null) return; this.inorder(root.left); this.sortedNode.add(root.val); this.inorder(root.right); } /** @return the next smallest number */ public int next() { return this.sortedNode.get(this.index ++); } /** @return whether we have a next smallest number */ public boolean hasNext() { return this.index < this.sortedNode.size(); } } /** * Your BSTIterator object will be instantiated and called as such: * BSTIterator obj = new BSTIterator(root); * int param_1 = obj.next(); * boolean param_2 = obj.hasNext(); */
24.847826
67
0.6028
2f1c39ffc39501bda8c721cdc308056c1fb0b02c
2,563
package seedu.address.logic.commands; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static seedu.address.logic.commands.CommandTestUtil.DESC_ALICE; import static seedu.address.logic.commands.CommandTestUtil.DESC_BENSON; import static seedu.address.logic.commands.CommandTestUtil.VALID_EMAIL_BENSON; import static seedu.address.logic.commands.CommandTestUtil.VALID_NAME_BENSON; import static seedu.address.logic.commands.CommandTestUtil.VALID_PASSPORT_NUMBER_BENSON; import static seedu.address.logic.commands.CommandTestUtil.VALID_ROOM_NUMBER_BENSON; import static seedu.address.logic.commands.CommandTestUtil.VALID_TAG_BENSON; import org.junit.jupiter.api.Test; import seedu.address.logic.commands.EditCommand.EditGuestDescriptor; import seedu.address.testutil.EditGuestDescriptorBuilder; public class EditGuestDescriptorTest { @Test public void equals() { // same values -> returns true EditGuestDescriptor descriptorWithSameValues = new EditGuestDescriptor(DESC_ALICE); assertTrue(DESC_ALICE.equals(descriptorWithSameValues)); // same object -> returns true assertTrue(DESC_ALICE.equals(DESC_ALICE)); // null -> returns false assertFalse(DESC_ALICE.equals(null)); // different types -> returns false assertFalse(DESC_ALICE.equals(5)); // different values -> returns false assertFalse(DESC_ALICE.equals(DESC_BENSON)); // different name -> returns false EditGuestDescriptor editedAmy = new EditGuestDescriptorBuilder(DESC_ALICE).withName(VALID_NAME_BENSON).build(); assertFalse(DESC_ALICE.equals(editedAmy)); // different email -> returns false editedAmy = new EditGuestDescriptorBuilder(DESC_ALICE).withEmail(VALID_EMAIL_BENSON).build(); assertFalse(DESC_ALICE.equals(editedAmy)); // different tags -> returns false editedAmy = new EditGuestDescriptorBuilder(DESC_ALICE).withTags(VALID_TAG_BENSON).build(); assertFalse(DESC_ALICE.equals(editedAmy)); // different passport number -> returns false editedAmy = new EditGuestDescriptorBuilder(DESC_ALICE).withPassportNumber(VALID_PASSPORT_NUMBER_BENSON).build(); assertFalse(DESC_ALICE.equals(editedAmy)); // different room number -> returns false editedAmy = new EditGuestDescriptorBuilder(DESC_ALICE).withRoomNumber(VALID_ROOM_NUMBER_BENSON).build(); assertFalse(DESC_ALICE.equals(editedAmy)); } }
42.716667
120
0.761217
d753170407201f09cd26a86354ae37593f6c8110
1,569
/* * Copyright 2014, Michael T. Goodrich, Roberto Tamassia, Michael H. Goldwasser * * Developed for use with the book: * * Data Structures and Algorithms in Java, Sixth Edition * Michael T. Goodrich, Roberto Tamassia, and Michael H. Goldwasser * John Wiley & Sons, 2014 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package dsaj.lists; import java.util.Random; import java.util.Iterator; import java.util.ArrayList; public class IteratorDemo { public static void main(String[] args) { int N = 50; Random r = new Random(); ArrayList<Double> data; // populate with random numbers (not shown) data = new ArrayList<>(N); for (int i = 0; i < N; i++) data.add(r.nextGaussian()); Iterator<Double> walk = data.iterator(); while (walk.hasNext()) if (walk.next() < 0.0) walk.remove(); System.out.println("Length of remaining data set: " + data.size()); System.out.println(data); } }
30.764706
79
0.688337
14914794e79dde06be4ed5e9ac2ab5b084a54215
4,165
package com.arenas.droidfan.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.Surface; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.arenas.droidfan.AppContext; import com.arenas.droidfan.R; import com.arenas.droidfan.data.model.DirectMessageModel; import com.arenas.droidfan.main.message.chat.ChatActivity; import com.makeramen.roundedimageview.RoundedImageView; import com.squareup.picasso.Picasso; import java.util.List; /** * Created by Arenas on 2016/7/25. */ public class ConversationListAdapter extends RecyclerView.Adapter<ConversationListAdapter.MessageViewHolder> { private List<DirectMessageModel> mMessage; private Context mContext; public ConversationListAdapter(Context context , List<DirectMessageModel> message) { this.mMessage = message; mContext = context; } @Override public MessageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new MessageViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.dm_list_item , parent ,false)); } @Override public void onBindViewHolder(final MessageViewHolder holder, final int position) { final DirectMessageModel model = mMessage.get(position); holder.username.setText(getConversationUsername(model)); Picasso.with(mContext).load(getProfileAvatarUrl(model)).into(holder.avatar); holder.content.setText(getContentToShow(model)); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ChatActivity.start(mContext ,model.getConversationId() , getChatUsername(model)); } }); holder.itemView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { return true; } }); } private String getChatUsername(DirectMessageModel model){ return model.getSenderScreenName().equals(AppContext.getScreenName()) ? model.getRecipientScreenName() : model.getSenderScreenName(); } @Override public int getItemCount() { return mMessage.size(); } public String getConversationUsername(DirectMessageModel messageModel){ return messageModel.getSenderScreenName().equals(AppContext.getScreenName()) ? messageModel.getRecipientScreenName() : messageModel.getSenderScreenName(); } public String getProfileAvatarUrl(DirectMessageModel messageModel){ return messageModel.getSenderProfileImageUrl().equals(AppContext.getAvatarUrl()) ? messageModel.getRecipientProfileImageUrl() : messageModel.getSenderProfileImageUrl(); } public String getContentToShow(DirectMessageModel messageModel){ return messageModel.getSenderScreenName().equals(AppContext.getScreenName()) ? "我:" + messageModel.getText() : messageModel.getText(); } public void setData(List<DirectMessageModel> data){ mMessage = data; } public void replaceData(List<DirectMessageModel> data){ setData(data); notifyDataSetChanged(); } public DirectMessageModel getDM(int position){ return mMessage.get(position); } class MessageViewHolder extends RecyclerView.ViewHolder{ RoundedImageView avatar; TextView username; // TextView userId; TextView content; public MessageViewHolder(View itemView) { super(itemView); avatar = (RoundedImageView)itemView.findViewById(R.id.iv_avatar); username = (TextView)itemView.findViewById(R.id.tv_username); // userId = (TextView)itemView.findViewById(R.id.user_id); content = (TextView)itemView.findViewById(R.id.tv_content); } } // public interface OnItemClickListener{ // void onItemClick(View view , int position); // void onItemLongClick(int id , int position); // } }
35.598291
126
0.702041
984118b603a3049897feecdee6f1901d1b143835
5,049
/** * 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.geronimo.aries; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import org.osgi.framework.Bundle; /** * The bundle graph, using the class to get the ordered bundles by the dependency relationship among them * * @version $Rev$ $Date$ */ public class BundleGraph { private final Collection<BundleNode> nodes; public BundleGraph(Collection<BundleNode> nodes) { this.nodes = nodes; } /** * Traverse the graph in DFS way * * @param action */ public void traverseDFS(TraverseVisitor action) { clearState(); for(BundleNode node : nodes) { DFS(node, action); } } protected void DFS(BundleNode startNode, TraverseVisitor action) { if(startNode.isVisited) return; // do action before if(action.isVisitBefore()) { action.doVisit(startNode); } startNode.isVisited = true; Collection<BundleNode> requiredBundles = startNode.requiredBundles; if(! requiredBundles.isEmpty()) { for(BundleNode rqBundle : requiredBundles) { DFS(rqBundle, action); } } // do action after if(! action.isVisitBefore()) { action.doVisit(startNode); } } /** * Get the ordered bundles according to the bundle dependencies * * @return */ public List<Bundle> getOrderedBundles() { final List<Bundle> result = new ArrayList<Bundle>(); traverseDFS(new TraverseVisitor() { @Override public void doVisit(BundleNode node) { if(! result.contains(node.value)) { result.add(node.value); } } @Override public boolean isVisitBefore() { return false; } }); return result; } protected void clearState() { for(BundleNode node : nodes) { node.isVisited = false; } } /** * The bundle node in graph * * @version $Rev$ $Date$ */ public static class BundleNode { private final Bundle value; private final Set<BundleNode> requiredBundles; private boolean isVisited; public BundleNode(Bundle value) { this.value = value; requiredBundles = new HashSet<BundleNode>(); } /** * @return the value */ public Bundle getValue() { return value; } /** * @return the isVisited */ public boolean isVisited() { return isVisited; } /** * @return the requiredBundles */ public Set<BundleNode> getRequiredBundles() { return requiredBundles; } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BundleNode other = (BundleNode) obj; if (value == null) { if (other.value != null) return false; } else if (!value.equals(other.value)) return false; return true; } } /** * Do some action when traverse the graph * * @version $Rev$ $Date$ */ public static interface TraverseVisitor { public void doVisit(BundleNode node); public boolean isVisitBefore(); } }
27.145161
105
0.547831
a863fdd1560f81ba637f72d0adc4c7219d7c2258
782
package me.xemor.superheroes2.events; import me.xemor.superheroes2.Superhero; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; public class PlayerLostSuperheroEvent extends Event { private static final HandlerList HANDLERS = new HandlerList(); private Player player; private Superhero hero; public PlayerLostSuperheroEvent(Player player, Superhero hero) { this.player = player; this.hero = hero; } @Override public HandlerList getHandlers() { return HANDLERS; } public static HandlerList getHandlerList() { return HANDLERS; } public Player getPlayer() { return player; } public Superhero getHero() { return hero; } }
21.135135
68
0.684143
20947b266fec7cbd9d34bc21faf8f653f053830d
12,535
package net.dongliu.apk.parser.parser; import net.dongliu.apk.parser.exception.ParserException; import net.dongliu.apk.parser.io.CountingInputStream; import net.dongliu.apk.parser.struct.*; import net.dongliu.apk.parser.struct.resource.*; import net.dongliu.apk.parser.utils.ParseUtils; import java.io.IOException; import java.io.InputStream; import java.util.HashSet; import java.util.Locale; import java.util.Set; /** * parse android resource table file. * see http://justanapplication.wordpress.com/category/android/android-resources/ * * @author dongliu */ public class ResourceTableParser { /** * By default the data in Chunks is in little-endian byte order both at runtime and when stored in files. */ private ByteOrder byteOrder = ByteOrder.LITTLE; private StringPool stringPool; private CountingInputStream in; // the resource table file size private final long size; private ResourceTable resourceTable; private Set<Locale> locales; public ResourceTableParser(InputStream in, long size) { this.in = new CountingInputStream(in, byteOrder); this.locales = new HashSet<Locale>(); this.size = size; } /** * parse resource table file. * * @throws IOException */ public void parse() throws IOException { try { // read resource file header. ResourceTableHeader resourceTableHeader = (ResourceTableHeader) readChunkHeader(); // read string pool chunk stringPool = ParseUtils.readStringPool(in, (StringPoolHeader) readChunkHeader()); resourceTable = new ResourceTable(); resourceTable.stringPool = stringPool; PackageHeader packageHeader = (PackageHeader) readChunkHeader(); for (int i = 0; i < resourceTableHeader.packageCount; i++) { PackageHeader[] packageHeaders = new PackageHeader[1]; ResourcePackage resourcePackage = readPackage(packageHeader, packageHeaders); resourceTable.addPackage(resourcePackage); packageHeader = packageHeaders[0]; } } finally { in.close(); } } // read one package private ResourcePackage readPackage(PackageHeader packageHeader, PackageHeader[] packageHeaders) throws IOException { //read packageHeader ResourcePackage resourcePackage = new ResourcePackage(packageHeader); long beginPos = in.tell(); // read type string pool if (packageHeader.typeStrings > 0) { in.advanceTo(beginPos + packageHeader.typeStrings - packageHeader.headerSize); resourcePackage.typeStringPool = ParseUtils.readStringPool(in, (StringPoolHeader) readChunkHeader()); } //read key string pool if (packageHeader.keyStrings > 0) { in.advanceTo(beginPos + packageHeader.keyStrings - packageHeader.headerSize); resourcePackage.keyStringPool = ParseUtils.readStringPool(in, (StringPoolHeader) readChunkHeader()); } outer: while (in.tell() < size) { ChunkHeader chunkHeader = readChunkHeader(); switch (chunkHeader.chunkType) { case ChunkType.TABLE_TYPE_SPEC: long typeSpecChunkBegin = in.tell(); TypeSpecHeader typeSpecHeader = (TypeSpecHeader) chunkHeader; long[] entryFlags = new long[(int) typeSpecHeader.entryCount]; for (int i = 0; i < typeSpecHeader.entryCount; i++) { entryFlags[i] = in.readUInt(); } TypeSpec typeSpec = new TypeSpec(typeSpecHeader); typeSpec.entryFlags = entryFlags; //id start from 1 typeSpec.name = resourcePackage.typeStringPool.get(typeSpecHeader.id - 1); resourcePackage.addTypeSpec(typeSpec); in.advanceTo(typeSpecChunkBegin + typeSpecHeader.chunkSize - typeSpecHeader.headerSize); break; case ChunkType.TABLE_TYPE: long typeChunkBegin = in.tell(); TypeHeader typeHeader = (TypeHeader) chunkHeader; // read offsets table long[] offsets = new long[(int) typeHeader.entryCount]; for (int i = 0; i < typeHeader.entryCount; i++) { offsets[i] = in.readUInt(); } long entryPos = typeChunkBegin + typeHeader.entriesStart - typeHeader.headerSize; in.advanceTo(entryPos); // read Resource Entries ResourceEntry[] resourceEntries = new ResourceEntry[offsets.length]; for (int i = 0; i < offsets.length; i++) { if (offsets[i] != TypeHeader.NO_ENTRY) { in.advanceTo(entryPos + offsets[i]); resourceEntries[i] = readResourceEntry(resourcePackage.keyStringPool); } else { resourceEntries[i] = null; } } Type type = new Type(typeHeader); type.name = resourcePackage.typeStringPool.get(typeHeader.id - 1); type.resourceEntries = resourceEntries; resourcePackage.addType(type); locales.add(type.locale); in.advanceTo(typeChunkBegin + typeHeader.chunkSize - typeHeader.headerSize); break; case ChunkType.TABLE_PACKAGE: // another package. we should read next package here packageHeaders[0] = (PackageHeader) chunkHeader; break outer; default: throw new ParserException("unexpected chunk type:" + chunkHeader.chunkType); } } return resourcePackage; } private ResourceEntry readResourceEntry(StringPool keyStringPool) throws IOException { long beginPos = in.tell(); ResourceEntry resourceEntry = new ResourceEntry(); // size is always 8(simple), or 16(complex) resourceEntry.size = in.readUShort(); resourceEntry.flags = in.readUShort(); long keyRef = in.readInt(); resourceEntry.key = keyStringPool.get((int) keyRef); if ((resourceEntry.flags & ResourceEntry.FLAG_COMPLEX) != 0) { ResourceMapEntry resourceMapEntry = new ResourceMapEntry(resourceEntry); // Resource identifier of the parent mapping, or 0 if there is none. resourceMapEntry.parent = in.readUInt(); resourceMapEntry.count = in.readUInt(); in.advanceTo(beginPos + resourceEntry.size); //An individual complex Resource entry comprises an entry immediately followed by one or more fields. ResourceTableMap[] resourceTableMaps = new ResourceTableMap[(int) resourceMapEntry.count]; for (int i = 0; i < resourceMapEntry.count; i++) { resourceTableMaps[i] = readResourceTableMap(); } resourceMapEntry.resourceTableMaps = resourceTableMaps; return resourceMapEntry; } else { in.advanceTo(beginPos + resourceEntry.size); resourceEntry.value = ParseUtils.readResValue(in, stringPool); return resourceEntry; } } private ResourceTableMap readResourceTableMap() throws IOException { //TODO: to be implemented. ResourceTableMap resourceTableMap = new ResourceTableMap(); resourceTableMap.nameRef = in.readUInt(); resourceTableMap.resValue = ParseUtils.readResValue(in, stringPool); if ((resourceTableMap.nameRef & 0x02000000) != 0) { //read arrays parseArrays(resourceTableMap); } else if ((resourceTableMap.nameRef & 0x01000000) != 0) { // read attrs parseAttrs(resourceTableMap); } else { } return resourceTableMap; } private void parseArrays(ResourceTableMap resourceTableMap) { } private void parseAttrs(ResourceTableMap resourceTableMap) { switch ((int) resourceTableMap.nameRef) { case ResourceTableMap.MapAttr.TYPE: // String name = "attr"; // String format; // int i = Integer.parseInt(resourceTableMap.resValue.data); // switch (i) { // case ResourceTableMap.AttributeType.BOOLEAN: // format = "bool"; // } // break; default: //resourceTableMap.data = "attr:" + resourceTableMap.nameRef; } } private ChunkHeader readChunkHeader() throws IOException { long begin = in.tell(); int chunkType = in.readUShort(); int headerSize = in.readUShort(); long chunkSize = in.readUInt(); switch (chunkType) { case ChunkType.TABLE: ResourceTableHeader resourceTableHeader = new ResourceTableHeader(chunkType, headerSize, chunkSize); resourceTableHeader.packageCount = in.readUInt(); in.advanceTo(begin + headerSize); return resourceTableHeader; case ChunkType.STRING_POOL: StringPoolHeader stringPoolHeader = new StringPoolHeader(chunkType, headerSize, chunkSize); stringPoolHeader.stringCount = in.readUInt(); stringPoolHeader.styleCount = in.readUInt(); stringPoolHeader.flags = in.readUInt(); stringPoolHeader.stringsStart = in.readUInt(); stringPoolHeader.stylesStart = in.readUInt(); in.advanceTo(begin + headerSize); return stringPoolHeader; case ChunkType.TABLE_PACKAGE: PackageHeader packageHeader = new PackageHeader(chunkType, headerSize, chunkSize); packageHeader.id = in.readUInt(); packageHeader.name = ParseUtils.readStringUTF16(in, 128); packageHeader.typeStrings = in.readUInt(); packageHeader.lastPublicType = in.readUInt(); packageHeader.keyStrings = in.readUInt(); packageHeader.lastPublicKey = in.readUInt(); in.advanceTo(begin + headerSize); return packageHeader; case ChunkType.TABLE_TYPE_SPEC: TypeSpecHeader typeSpecHeader = new TypeSpecHeader(chunkType, headerSize, chunkSize); typeSpecHeader.id = in.readUByte(); typeSpecHeader.res0 = in.readUByte(); typeSpecHeader.res1 = in.readUShort(); typeSpecHeader.entryCount = in.readUInt(); in.advanceTo(begin + headerSize); return typeSpecHeader; case ChunkType.TABLE_TYPE: TypeHeader typeHeader = new TypeHeader(chunkType, headerSize, chunkSize); typeHeader.id = in.readUByte(); typeHeader.res0 = in.readUByte(); typeHeader.res1 = in.readUShort(); typeHeader.entryCount = in.readUInt(); typeHeader.entriesStart = in.readUInt(); typeHeader.config = readResTableConfig(); in.advanceTo(begin + headerSize); return typeHeader; case ChunkType.NULL: //in.skip((int) (chunkSize - headerSize)); default: throw new ParserException("Unexpected chunk Type:" + Integer.toHexString(chunkType)); } } private ResTableConfig readResTableConfig() throws IOException { long beginPos = in.tell(); ResTableConfig config = new ResTableConfig(); long size = in.readUInt(); in.skip(4); //read locale config.language = in.readChars(2); config.country = in.readChars(2); long endPos = in.tell(); in.skip((int) (size - (endPos - beginPos))); return config; } public ResourceTable getResourceTable() { return resourceTable; } public Set<Locale> getLocales() { return this.locales; } }
40.435484
113
0.587874
e4d054a95200fd391c608a95727c931d8ca1d6a9
742
package tests; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.WebDriverWait; import pages.PageGenerator; public class BaseTest { public WebDriver driver; public WebDriverWait wait; public PageGenerator page; @BeforeEach public void classLevelSetup() { driver = new ChromeDriver(); wait = new WebDriverWait(driver,15); page = new PageGenerator(driver); } @AfterEach public void teardown () { driver.quit(); } }
25.586207
52
0.727763
54cd0c4598e74bc64403abae954e9e6379a8cd51
3,010
/* * The MIT License (MIT) * * Copyright (c) 2014-2016 Christian Schudt * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package rocks.xmpp.core.tls.model; import rocks.xmpp.core.stream.model.StreamElement; import rocks.xmpp.core.stream.model.StreamFeature; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSeeAlso; /** * Represents the STARTTLS feature and initiates the TLS negotiation process. * <blockquote> * <p><cite><a href="http://xmpp.org/rfcs/rfc6120.html#tls-process-initiate-command">5.4.2.1. STARTTLS Command</a></cite></p> * <p>In order to begin the STARTTLS negotiation, the initiating entity issues the STARTTLS command (i.e., a {@code <starttls/>} element qualified by the 'urn:ietf:params:xml:ns:xmpp-tls' namespace) to instruct the receiving entity that it wishes to begin a STARTTLS negotiation to secure the stream.</p> * </blockquote> * <p> * This class is unconditionally thread-safe. * * @author Christian Schudt */ @XmlRootElement(name = "starttls") @XmlSeeAlso({Proceed.class, Failure.class}) public final class StartTls extends StreamFeature implements StreamElement { private String required; public StartTls() { } public StartTls(boolean required) { this.required = required ? "" : null; } @Override public final synchronized boolean isMandatory() { return required != null; } public final synchronized void setMandatory(boolean mandatory) { if (mandatory) { required = ""; } else { required = null; } } @Override public final int getPriority() { return 0; } @Override public final String toString() { StringBuilder sb = new StringBuilder("StartTLS"); if (isMandatory()) { sb.append(" (required)"); } return sb.toString(); } }
35.833333
305
0.684718
d3ba7d3a37895b135d4b16b9cfdcd71f24a7e3ba
630
package com.sung.hee.help; /** * Created by SungHere on 2017-05-10. */ //com.sung.hee.help.BoardCheck public class BoardCheck { @Override public String toString() { return "BoardCheck{" + "type=" + type + ", seq=" + seq + '}'; } public BoardCheck() { } private int type = 0; private int seq = 0; public int getType() { return type; } public void setType(int type) { this.type = type; } public int getSeq() { return seq; } public void setSeq(int seq) { this.seq = seq; } }
16.153846
37
0.498413
a3d66047ff32ade7a9de089bc13ab7e284b411c5
2,745
package com.softb.system.repository.config; import liquibase.integration.spring.SpringLiquibase; import org.apache.commons.dbcp2.BasicDataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.orm.jpa.EntityScan; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import javax.sql.DataSource; import java.net.URI; import java.net.URISyntaxException; @Configuration @EnableJpaRepositories(basePackages = { "com.softb.system.security.repository", "com.softb.ipocket.account.repository", "com.softb.ipocket.investment.repository", "com.softb.ipocket.bill.repository", "com.softb.ipocket.budget.repository", "com.softb.ipocket.categorization.repository" }) @EntityScan(basePackages = { "com.softb.system.security.model", "com.softb.ipocket.account.model", "com.softb.ipocket.investment.model", "com.softb.ipocket.bill.model", // "com.softb.ipocket.dashboard.model", "com.softb.ipocket.budget.model", "com.softb.ipocket.general.model", "com.softb.ipocket.categorization.model" }) public class RepositoryConfig { private final Logger logger = LoggerFactory.getLogger(RepositoryConfig.class); @Autowired private Environment environment; @Bean public SpringLiquibase liquibase(DataSource datasource) { SpringLiquibase liquibase = null; // if (!environment.acceptsProfiles(Constants.SPRING_PROFILE_PRODUCTION)) { // logger.debug("Configuring Liquibase"); // liquibase = new SpringLiquibase(); // liquibase.setDataSource(datasource); // liquibase.setChangeLog("classpath:config/liquibase/master.xml"); // liquibase.setContexts("development"); // } return liquibase; } @Bean public BasicDataSource dataSource() throws URISyntaxException { URI dbUri = new URI(environment.getProperty("DATABASE_URL")); String username = dbUri.getUserInfo().split(":")[0]; String password = (dbUri.getUserInfo().split(":").length > 1 ? dbUri.getUserInfo().split(":")[1] : ""); String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + ':' + dbUri.getPort() + dbUri.getPath(); BasicDataSource basicDataSource = new BasicDataSource(); basicDataSource.setUrl(dbUrl); basicDataSource.setUsername(username); basicDataSource.setPassword(password); basicDataSource.setDriverClassName("org.postgresql.Driver"); return basicDataSource; } }
35.649351
111
0.725319
753d6dae66cec81e9060512af94603a45c43dfa8
1,143
package com.aspose.slides.examples.Slides.Shapes; import java.awt.geom.Point2D; import com.aspose.slides.IAutoShape; import com.aspose.slides.IParagraph; import com.aspose.slides.IPortion; import com.aspose.slides.ITextFrame; import com.aspose.slides.Presentation; import com.aspose.slides.examples.Utils; public class GettingPositionCoordinatesOfPortion { public static void main(String[] args) { //ExStart:GettingPositionCoordinatesOfPortion // The path to the documents directory. String dataDir = Utils.getDataDir(GettingPositionCoordinatesOfPortion.class); // Creating new object Presentation pres = new Presentation(dataDir + "HelloWorld.pptx"); // Reshaping the context of presentation IAutoShape shape = (IAutoShape) pres.getSlides().get_Item(0).getShapes().get_Item(0); ITextFrame textFrame = (ITextFrame) shape.getTextFrame(); for (IParagraph paragraph : textFrame.getParagraphs()) { for (IPortion portion : paragraph.getPortions()) { Point2D.Float point = portion.getCoordinates(); System.out.println("X: " + point.x + " Y: " + point.y); } } //ExEnd:GettingPositionCoordinatesOfPortion } }
31.75
87
0.764654
996533a7d0423a33f34b169003f66df1d0fd98d7
4,066
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. 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.logstash.config.ir.graph; import org.junit.Test; import org.logstash.common.ConfigVariableExpanderTest; import org.logstash.config.ir.DSL; import org.logstash.config.ir.InvalidIRException; import org.logstash.config.ir.expression.BooleanExpression; import org.logstash.config.ir.expression.ExpressionSubstitution; import org.logstash.config.ir.expression.binary.Eq; import org.logstash.plugins.ConfigVariableExpander; import java.util.Collections; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.assertThat; import static org.logstash.config.ir.IRHelpers.*; public class IfVertexTest { @Test public void testIfVertexCreation() throws InvalidIRException { testIfVertex(); } @Test(expected = Vertex.InvalidEdgeTypeException.class) public void testDoesNotAcceptNonBooleanEdges() throws InvalidIRException { Graph graph = Graph.empty(); IfVertex ifV = testIfVertex(); Vertex otherV = createTestVertex(); graph.chainVertices(PlainEdge.factory, ifV, otherV); } @Test public void testEdgeTypeHandling() throws InvalidIRException { Graph graph = Graph.empty(); IfVertex ifV = testIfVertex(); graph.addVertex(ifV); Vertex trueV = createTestVertex(); graph.addVertex(trueV); assertThat(ifV.hasEdgeType(true), is(false)); assertThat(ifV.hasEdgeType(false), is(false)); assertThat(ifV.getUnusedOutgoingEdgeFactories().size(), is(2)); graph.chainVertices(BooleanEdge.trueFactory, ifV, trueV); assertThat(ifV.hasEdgeType(true), is(true)); assertThat(ifV.hasEdgeType(false), is(false)); assertThat(ifV.getUnusedOutgoingEdgeFactories().size(), is(1)); assertThat( ifV.getUnusedOutgoingEdgeFactories().stream().findFirst().get(), is(BooleanEdge.falseFactory) ); Vertex falseV = createTestVertex(); graph.chainVertices(BooleanEdge.falseFactory, ifV, falseV); assertThat(ifV.hasEdgeType(false), is(true)); assertThat(ifV.getUnusedOutgoingEdgeFactories().isEmpty(), is(true)); BooleanEdge trueEdge = ifV.outgoingBooleanEdgesByType(true).findAny().get(); BooleanEdge falseEdge = ifV.outgoingBooleanEdgesByType(false).findAny().get(); assertThat(trueEdge.getEdgeType(), is(true)); assertThat(falseEdge.getEdgeType(), is(false)); } public IfVertex testIfVertex() throws InvalidIRException { return new IfVertex(randMeta(), createTestExpression()); } @Test public void testIfVertexWithSecretsIsntLeaked() throws InvalidIRException { BooleanExpression booleanExpression = DSL.eEq(DSL.eEventValue("password"), DSL.eValue("${secret_key}")); ConfigVariableExpander cve = ConfigVariableExpanderTest.getFakeCve( Collections.singletonMap("secret_key", "s3cr3t"), Collections.emptyMap()); IfVertex ifVertex = new IfVertex(randMeta(), (BooleanExpression) ExpressionSubstitution.substituteBoolExpression(cve, booleanExpression)); // Exercise String output = ifVertex.toString(); // Verify assertThat(output, not(containsString("s3cr3t"))); } }
37.302752
112
0.712002
f56300bfb31f620b4932ecd5a2818236e792b057
3,195
/* * Copyright (c) 2016 Spotify 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. */ package com.spotify.helios.system; import com.google.common.collect.Sets; import com.spotify.helios.Polling; import com.spotify.helios.servicescommon.coordination.Paths; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.api.ACLProvider; import org.apache.zookeeper.data.ACL; import org.junit.Test; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import static com.spotify.helios.servicescommon.ZooKeeperAclProviders.heliosAclProvider; import static org.junit.Assert.assertEquals; public class ZooKeeperAclTest extends SystemTestBase { private final ACLProvider aclProvider = heliosAclProvider(MASTER_USER, MASTER_DIGEST, AGENT_USER, AGENT_DIGEST); /** * Verify that the master sets the correct ACLs on the root node on start-up */ @Test public void testMasterSetsRootNodeAcls() throws Exception { startDefaultMaster(); final CuratorFramework curator = zk().curatorWithSuperAuth(); final List<ACL> acls = curator.getACL().forPath("/"); assertEquals( Sets.newHashSet(aclProvider.getAclForPath("/")), Sets.newHashSet(acls)); } /** * Simple test to make sure nodes created by agents use the ACLs provided by the ACL provider. */ @Test public void testAgentCreatedNodesHaveAcls() throws Exception { startDefaultMaster(); startDefaultAgent(TEST_HOST); awaitHostRegistered(TEST_HOST, WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS); final CuratorFramework curator = zk().curatorWithSuperAuth(); final String path = Paths.configHost(TEST_HOST); final List<ACL> acls = curator.getACL().forPath(path); assertEquals( Sets.newHashSet(aclProvider.getAclForPath(path)), Sets.newHashSet(acls)); } /** * Simple test to make sure nodes created by master use the ACLs provided by the ACL provider. */ @Test public void testMasterCreatedNodesHaveAcls() throws Exception { startDefaultMaster(); Polling.await(WAIT_TIMEOUT_SECONDS, TimeUnit.SECONDS, new Callable<Boolean>() { @Override public Boolean call() throws Exception { return defaultClient().listMasters().get().isEmpty() ? null : true; } }); final CuratorFramework curator = zk().curatorWithSuperAuth(); final String path = Paths.statusMasterUp(TEST_MASTER); final List<ACL> acls = curator.getACL().forPath(path); assertEquals( Sets.newHashSet(aclProvider.getAclForPath(path)), Sets.newHashSet(acls)); } }
32.938144
96
0.72144
a5f5d043858f8c80d616ee2912927da4f30534df
7,992
package mitzi; import javax.swing.JFrame; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MitziGUI extends JFrame implements MouseListener, MouseMotionListener { private static final long serialVersionUID = -418000626395118246L; JLayeredPane layeredPane; JPanel chessBoard; JLabel chessPiece; int xAdjustment; int yAdjustment; int start_square; int end_square; private static GameState state = new GameState(); private static boolean mitzis_turn; private static Side mitzis_side =null; Dimension boardSize = new Dimension(800, 800); public Object[] options = { "ok" }; public MitziGUI() { redraw(); } private void redraw() { // Use a Layered Pane for this this application layeredPane = new JLayeredPane(); layeredPane.setPreferredSize(boardSize); layeredPane.addMouseListener(this); layeredPane.addMouseMotionListener(this); // Add a chess board to the Layered Pane chessBoard = new JPanel(); layeredPane.add(chessBoard, JLayeredPane.DEFAULT_LAYER); chessBoard.setLayout(new GridLayout(8, 8)); chessBoard.setPreferredSize(boardSize); chessBoard.setBounds(0, 0, boardSize.width, boardSize.height); // Color it b/w Color black = Color.getHSBColor((float) 0.10, (float) 0.40, (float) 0.80); Color white = Color.getHSBColor((float) 0.15, (float) 0.13, (float) 0.98); for (int i = 0; i < 64; i++) { JPanel square = new JPanel(new BorderLayout()); chessBoard.add(square); square.setBackground((i + i / 8) % 2 == 0 ? white : black); } getContentPane().removeAll(); getContentPane().add(layeredPane); } private int getSquare(int x, int y) { x = x / 100 + 1; y = (800 - y) / 100 + 1; return x * 10 + y; } private Component squareToComponent(int squ) { int row = 8 - squ % 10; int col = ((int) squ / 10) - 1; Component c = chessBoard.getComponent(row * 8 + col); return c; } public void setToFEN(String fen) { redraw(); JPanel panel; String[] fen_parts = fen.split(" "); // populate the squares String[] fen_rows = fen_parts[0].split("/"); char[] pieces; for (int row = 0; row < 8; row++) { int offset = 0; for (int column = 0; column + offset < 8; column++) { pieces = fen_rows[row].toCharArray(); int square = row * 8 + column + offset; JLabel piece; switch (pieces[column]) { case 'P': piece = new JLabel("♙"); break; case 'R': piece = new JLabel("♖"); break; case 'N': piece = new JLabel("♘"); break; case 'B': piece = new JLabel("♗"); break; case 'Q': piece = new JLabel("♕"); break; case 'K': piece = new JLabel("♔"); break; case 'p': piece = new JLabel("♟"); break; case 'r': piece = new JLabel("♜"); break; case 'n': piece = new JLabel("♞"); break; case 'b': piece = new JLabel("♝"); break; case 'q': piece = new JLabel("♛"); break; case 'k': piece = new JLabel("♚"); break; default: piece = new JLabel(""); offset += Character.getNumericValue(pieces[column]) - 1; break; } panel = (JPanel) chessBoard.getComponent(square); piece.setFont(new Font("Serif", Font.PLAIN, 100)); panel.add(piece); } } chessBoard.updateUI(); } public void mousePressed(MouseEvent e) { chessPiece = null; Component c = chessBoard.findComponentAt(e.getX(), e.getY()); if (c instanceof JPanel) return; Point parentLocation = c.getParent().getLocation(); xAdjustment = parentLocation.x - e.getX(); yAdjustment = parentLocation.y - e.getY(); start_square = getSquare(e.getX(), e.getY()); chessPiece = (JLabel) c; chessPiece.setLocation(e.getX() + xAdjustment, e.getY() + yAdjustment); chessPiece.setSize(chessPiece.getWidth(), chessPiece.getHeight()); layeredPane.add(chessPiece, JLayeredPane.DRAG_LAYER); } // Move the chess piece around public void mouseDragged(MouseEvent me) { if (chessPiece == null) return; chessPiece .setLocation(me.getX() + xAdjustment, me.getY() + yAdjustment); } // Drop the chess piece back onto the chess board public void mouseReleased(MouseEvent e) { if (chessPiece == null) return; chessPiece.setVisible(false); end_square = getSquare(e.getX(), e.getY()); // check for promotion IMove move; if (state.getPosition().getPieceFromBoard(start_square) == Piece.PAWN && (SquareHelper.getRow(end_square) == 8 || SquareHelper .getRow(end_square) == 1)) { move = new Move(start_square, end_square, askPromotion()); } else { move = new Move(start_square, end_square); } //if its not your turn, you are not allowed to do anything. if(mitzis_side == state.getPosition().getActiveColor()) { Container parent = (Container) squareToComponent(start_square); parent.add(chessPiece); chessPiece.setVisible(true); return; } //try to do move try { state.doMove(move); } catch (IllegalArgumentException ex) { Container parent = (Container) squareToComponent(start_square); parent.add(chessPiece); chessPiece.setVisible(true); return; } IPosition position = state.getPosition(); setToFEN(position.toFEN()); if (state.getPosition().isMatePosition()) { JOptionPane.showOptionDialog(this, "You Won!","Information", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); return; } if (state.getPosition().isStaleMatePosition()) { JOptionPane.showOptionDialog(this, "Draw","Information", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); return; } mitzis_turn = true; } public void mouseClicked(MouseEvent e) { } public void mouseMoved(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } private Piece askPromotion() { Object[] options = { "Queen", "Rook", "Bishop", "Knight" }; int n = JOptionPane.showOptionDialog(this, "Which piece do you want to promote to?", "Pawn Promotion", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (n == 0) { return Piece.QUEEN; } else if (n == 1) { return Piece.ROOK; } else if (n == 2) { return Piece.BISHOP; } else { return Piece.KNIGHT; } } public static void main(String[] args) { JFrame frame = new MitziGUI(); frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE); frame.pack(); frame.setResizable(false); frame.setLocationRelativeTo(null); frame.setVisible(true); frame.setTitle("Mitzi GUI"); MitziGUI gui = (MitziGUI) frame; Object[] choice = { "You", "Mitzi" }; String initialFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"; state.setToFEN(initialFEN); gui.setToFEN(initialFEN); int n = JOptionPane.showOptionDialog(frame, "Who should start","Question", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, choice, choice[0]); if(n==0) { mitzis_turn = false; mitzis_side = Side.BLACK; } else { mitzis_turn = true; mitzis_side = Side.WHITE; } IBrain mitzi = new MitziBrain(); IMove move; while (true) { System.out.print(""); if(mitzis_turn) { // Mitzis turn mitzi.set(state); move = mitzi.search(5000, 5000, 6, true, null); state.doMove(move); gui.setToFEN(state.getPosition().toFEN()); if (state.getPosition().isMatePosition()) { JOptionPane.showOptionDialog(frame, "Mitzi Won!","Information", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, gui.options, gui.options[0]); return; } if (state.getPosition().isStaleMatePosition()) { JOptionPane.showOptionDialog(frame, "Draw!","Information", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, gui.options, gui.options[0]); return; } mitzis_turn=false; } } } }
24.743034
81
0.652277
beff0690ef624dba3d30f30eb931506bf7f65b28
1,971
package backtracking; import java.util.*; public class TSP1 { static final int INF = 1000000; public static void main(String[] args) { Random rand = new Random(1); for (int steps = 0; steps < 10000; steps++) { int n = rand.nextInt(10) + 1; int[][] edgeCost = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { edgeCost[i][j] = edgeCost[j][i] = rand.nextInt(100); } } // edgeCost[0][1] = edgeCost[1][0] = 1; // edgeCost[0][2] = edgeCost[2][0] = 10; // edgeCost[1][2] = edgeCost[2][1] = 1; int res1 = doDynamic(n, edgeCost); int res2 = doBruteForce(n, edgeCost); if (res1 != res2) { System.out.println(res1 + " " + res2); } } } public static boolean nextPermutation(int[] p) { int a = p.length - 2; while (a >= 0 && p[a] >= p[a + 1]) { a--; } if (a == -1) { return false; } int b = p.length - 1; while (p[b] <= p[a]) { b--; } int t = p[a]; p[a] = p[b]; p[b] = t; for (int i = a + 1, j = p.length - 1; i < j; i++, j--) { t = p[i]; p[i] = p[j]; p[j] = t; } return true; } static int doBruteForce(int n, int[][] edgeCost) { int[] p = new int[n]; for (int i = 0; i < n; i++) { p[i] = i; } int best = Integer.MAX_VALUE; do { int res = edgeCost[p[n - 1]][p[0]]; for (int i = 0; i + 1 < n; i++) { res += edgeCost[p[i]][p[i + 1]]; } best = Math.min(best, res); } while (nextPermutation(p)); return best; } static int doDynamic(int n, int[][] edgeCost) { int[][] dp = new int[n][1 << n]; for (int i = 0; i < n; i++) { Arrays.fill(dp[i], INF); } dp[0][0] = 0; for (int mask = 0; mask < 1 << n; mask++) { for (int next = 0; next < n; next++) { if ((mask & 1 << next) == 0) { for (int cur = 0; cur < n; cur++) { dp[next][mask | 1 << next] = Math.min(dp[next][mask | 1 << next], edgeCost[next][cur] + dp[cur][mask]); } } } } return dp[0][(1 << n) - 1]; } }
22.918605
91
0.483511
52843146490633d5c5477619c7fe367418fa5b21
1,573
package top.kylewang.bos.web.controller.system; import org.apache.shiro.SecurityUtils; import org.apache.shiro.subject.Subject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import top.kylewang.bos.domain.system.Menu; import top.kylewang.bos.domain.system.User; import top.kylewang.bos.service.system.MenuService; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; /** * @author Kyle.Wang * 2018/1/10 0010 21:20 */ @Controller public class MenuController { @Autowired private MenuService menuService; /** * 菜单列表查询 * @return */ @RequestMapping("/menu_list.action") @ResponseBody public List<Menu> list(){ List<Menu> list = menuService.findAll(); return list; } /** * 菜单添加 * @return */ @RequestMapping("/menu_save.action") public void save(Menu menu,HttpServletResponse response) throws IOException { menuService.save(menu); response.sendRedirect("./pages/system/menu.html"); } /** * 根据用户显示菜单 * @return */ @RequestMapping("/menu_showMenu.action") @ResponseBody public List<Menu> showMenu(){ Subject subject = SecurityUtils.getSubject(); User user = (User) subject.getPrincipal(); List<Menu> menuList = menuService.findByUser(user); return menuList; } }
25.370968
81
0.694215
e373aab1b2b50d3bf582e057dfee8eb23e755da1
2,617
/* * Copyright 2013 MovingBlocks * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.terasology.engine; import org.terasology.engine.modes.GameState; /** * The game engine is the core of Terasology. It maintains a stack of game states, that drive the behaviour of * Terasology in different modes (Main Menu, ingame, dedicated server, etc) * * @author Immortius */ public interface GameEngine { /** * Initialises the engine */ void init(); /** * Runs the engine, which will block the thread. * Invalid for a disposed engine */ void run(GameState initialState); /** * Request the engine to stop running */ void shutdown(); /** * Cleans up the engine. Can only be called after shutdown. * This method should not throw exceptions. */ void dispose(); /** * @return Whether the engine is running */ boolean isRunning(); /** * @return Whether the engine has been disposed */ boolean isDisposed(); /** * @return The current state of the engine */ GameState getState(); /** * Clears all states, replacing them with newState * * @param newState */ void changeState(GameState newState); // TODO: Move task system elsewhere? Need to support saving queued/unfinished tasks too, when the world // shuts down /** * Submits a task to be run concurrent with the main thread * * @param name * @param task */ void submitTask(String name, Runnable task); boolean isHibernationAllowed(); void setHibernationAllowed(boolean allowed); // TODO: This probably should be elsewhere? /** * @return Whether the game window currently has focus */ boolean hasFocus(); /** * @return Whether the game window controls if the mouse is captured. */ boolean hasMouseFocus(); void setFocus(boolean focused); void subscribeToStateChange(StateChangeSubscriber subscriber); void unsubscribeToStateChange(StateChangeSubscriber subscriber); }
24.231481
110
0.663737
6403bf0674399460aeda9e35c57f50f009d27cef
3,171
/* * Copyright 2017-2020 Alfresco Software, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.activiti.cloud.starter.messages.hazelcast; import org.activiti.cloud.services.messages.core.config.MessagesCoreAutoConfiguration; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; //import org.springframework.boot.data.geode.autoconfigure.ClientCacheAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.integration.hazelcast.lock.HazelcastLockRegistry; import org.springframework.integration.hazelcast.metadata.HazelcastMetadataStore; import org.springframework.integration.hazelcast.store.HazelcastMessageStore; import org.springframework.integration.metadata.ConcurrentMetadataStore; import org.springframework.integration.store.MessageGroupStore; import org.springframework.integration.support.locks.LockRegistry; import org.springframework.transaction.PlatformTransactionManager; import com.hazelcast.config.Config; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.spring.transaction.HazelcastTransactionManager; @Configuration @AutoConfigureBefore({MessagesCoreAutoConfiguration.class}) @ConditionalOnClass(HazelcastInstance.class) public class HazelcastMessageStoreAutoConfiguration { @Bean @ConditionalOnMissingBean public Config hazelcastConfig() { Config config = new Config(); config.getCPSubsystemConfig() .setCPMemberCount(3); return config; } @Bean @ConditionalOnMissingBean public PlatformTransactionManager transactionManager(HazelcastInstance hazelcastInstance) { return new HazelcastTransactionManager(hazelcastInstance); } @Bean @ConditionalOnMissingBean public MessageGroupStore messageStore(HazelcastInstance hazelcastInstance) { HazelcastMessageStore messageStore = new HazelcastMessageStore(hazelcastInstance); messageStore.setLazyLoadMessageGroups(false); return messageStore; } @Bean @ConditionalOnMissingBean public ConcurrentMetadataStore metadataStore(HazelcastInstance hazelcastInstance) { return new HazelcastMetadataStore(hazelcastInstance); } @Bean @ConditionalOnMissingBean public LockRegistry lockRegistry(HazelcastInstance hazelcastInstance) { return new HazelcastLockRegistry(hazelcastInstance); } }
39.148148
95
0.79281
89b3682f231df869559ea0b65fc7fba03553cbee
4,642
package cn.vertxup.crud.api; import io.vertx.core.Future; import io.vertx.core.buffer.Buffer; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.tp.crud.cv.Addr; import io.vertx.tp.crud.cv.em.ApiSpec; import io.vertx.tp.crud.refine.Ix; import io.vertx.tp.crud.uca.desk.IxMod; import io.vertx.tp.crud.uca.desk.IxPanel; import io.vertx.tp.crud.uca.desk.IxWeb; import io.vertx.tp.crud.uca.input.Pre; import io.vertx.tp.crud.uca.next.Co; import io.vertx.tp.crud.uca.op.Agonic; import io.vertx.tp.crud.uca.trans.Tran; import io.vertx.tp.ke.atom.specification.KModule; import io.vertx.tp.plugin.excel.ExcelClient; import io.vertx.up.annotations.Address; import io.vertx.up.annotations.Plugin; import io.vertx.up.annotations.Queue; import io.vertx.up.atom.query.engine.Qr; import io.vertx.up.commune.Envelop; import io.vertx.up.commune.element.TypeAtom; import io.vertx.up.eon.KName; import io.vertx.up.log.Annal; import io.vertx.up.unity.Ux; import io.vertx.up.util.Ut; import java.util.List; @Queue @SuppressWarnings("all") public class FileActor { private static final Annal LOGGER = Annal.get(FileActor.class); @Plugin private transient ExcelClient client; @Address(Addr.File.IMPORT) public Future<Envelop> importFile(final Envelop envelop) { /* * Import Data from file here * Extract `filename` as file */ final IxWeb request = IxWeb.create(ApiSpec.BODY_STRING).build(envelop); final IxPanel panel = IxPanel.on(request); final Co co = Co.nextJ(request.active(), true); return Pre.excel(this.client).inJAAsync(request.dataF(), request.active()).compose(data -> panel .input( Tran.initial()::inAAsync, /* Initial */ Tran.fabric(true)::inAAsync, /* Dict */ Tran.map(true)::inAAsync /* Mapping */ ) .next(in -> co::next) .output(co::ok) .passion(Agonic.file()::runAAsync) .runA(data) ); } @Address(Addr.File.EXPORT) public Future<Envelop> exportFile(final Envelop envelop) { /* Search full column and it will be used in another method */ final IxWeb request = IxWeb.create(ApiSpec.BODY_JSON).build(envelop); /* Exported columns here for future calculation */ final JsonObject condition = request.dataJ(); final JsonArray projection = Ut.sureJArray(condition.getJsonArray(KName.Ui.COLUMNS)); final List<String> columnList = Ut.toList(projection); /* Remove columns here and set criteria as condition * Here extract query by `criteria` node, it will be synced with * dynamic exporting here. **/ JsonObject criteria = Ut.sureJObject(condition.getJsonObject(Qr.KEY_CRITERIA)); final IxPanel panel = IxPanel.on(request); final IxMod mod = request.active(); return T.fetchFull(request).runJ(request.dataV()) /* * Data Processing */ .compose(columns -> panel .input( Pre.codex()::inJAsync /* Rule Vrify */ ) .passion(Agonic.fetch()::runJAAsync, null) .<JsonArray, JsonObject, JsonArray>runJ(criteria) /* Dict Transfer to Export */ .compose(data -> Tran.map(false).inAAsync(data, mod)) /* Map */ .compose(data -> Tran.fabric(false).inAAsync(data, mod)) /* Dict */ .compose(data -> Tran.tree(false).inAAsync(data, mod)) /* Tree */ .compose(data -> Pre.auditorBy().inAAsync(data, mod)) /* Auditor */ .compose(data -> Co.endE(columnList).ok(data, columns)) .compose(data -> { /* * Data Extraction for file buffer here */ if (data instanceof JsonArray) { final IxMod active = mod; final KModule in = active.module(); /* * The system will calculate the type definition of static module */ final TypeAtom atom = Ix.onAtom(active, (JsonArray) columns); return this.client.exportAsync(in.getTable(), (JsonArray) data, atom); } else { return Ux.future(Buffer.buffer()); } }) ).compose(buffer -> Ux.future(Envelop.success(buffer))); } }
40.365217
104
0.589186
6d238cc0a3132b648db4dc78a839ef9091184402
2,945
package org.infinispan.protostream.annotations.impl; import static org.junit.Assert.assertEquals; import org.infinispan.protostream.annotations.ProtoReserved; import org.infinispan.protostream.annotations.ProtoSchemaBuilderException; import org.infinispan.protostream.annotations.impl.types.ReflectionClassFactory; import org.infinispan.protostream.annotations.impl.types.XClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; /** * @author anistor@redhat.com * @since 4.3 */ public class ReservedProcessorTest { // TODO [anistor] things to also test: // empty field name // duplicate field name // illegal field name eg. "--?77fff" // 45 to 45 // 45 to 5 // messages from protoc: // test.proto:3:9: Field name "field2222" is reserved multiple times // test.proto: Reserved range 13 to 13 overlaps with already defined range 13 to 536870911. @Rule public ExpectedException expectedException = ExpectedException.none(); @Test public void testEmpty() { XClass classToTest = new ReflectionClassFactory().fromClass(Integer.class); ReservedProcessor rp = new ReservedProcessor(); rp.scan(classToTest); IndentWriter iw = new IndentWriter(); rp.generate(iw); assertEquals("", iw.toString()); } @ProtoReserved(numbers = {1, 2}, ranges = @ProtoReserved.Range(from = 3, to = 7), names = {"a", "b"}) private static class TestingReserved { } @Test public void testReservedNumbers() { XClass classToTest = new ReflectionClassFactory().fromClass(TestingReserved.class); ReservedProcessor rp = new ReservedProcessor(); rp.scan(classToTest); IndentWriter iw = new IndentWriter(); rp.generate(iw); assertEquals("//reserved 1 to 7;\n//reserved \"a\", \"b\";\n", iw.toString()); } @ProtoReserved({1, 2, 1}) private static class DuplicateNumber { } @Test public void testDuplicateReservedNumber() { expectedException.expect(ProtoSchemaBuilderException.class); expectedException.expectMessage("Found duplicate @ProtoReserved number 1 in org.infinispan.protostream.annotations.impl.ReservedProcessorTest.DuplicateNumber"); XClass classToTest = new ReflectionClassFactory().fromClass(DuplicateNumber.class); new ReservedProcessor().scan(classToTest); } @ProtoReserved(names = {"triceratops", "valociraptor", "triceratops"}) private static class DuplicateName { } @Test public void testDuplicateReservedName() { expectedException.expect(ProtoSchemaBuilderException.class); expectedException.expectMessage("Found duplicate @ProtoReserved name \"triceratops\" in org.infinispan.protostream.annotations.impl.ReservedProcessorTest.DuplicateName"); XClass classToTest = new ReflectionClassFactory().fromClass(DuplicateName.class); new ReservedProcessor().scan(classToTest); } }
32.722222
176
0.724278
96236962b3ad35044c9fe5cee2cd6621549768ea
2,876
/** * */ package site.franksite.service.body; import site.franksite.pojo.ArticleEntity; /** * 文章回传体 * @author Frank * */ public class ArticleBody { private String shortcut; //摘要 private String publishdate; //发表日期 private long readTimes; // 阅读次数 private long commentcount; // 评论数 private ArticleEntity article; // 文章实体 private String content; // 内容 /** * @return the shortcut */ public String getShortcut() { return shortcut; } /** * @param shortcut the shortcut to set */ public void setShortcut(String shortcut) { this.shortcut = shortcut; } /** * @return the publishdate */ public String getPublishdate() { return publishdate; } /** * @param publishdate the publishdate to set */ public void setPublishdate(String publishdate) { this.publishdate = publishdate; } /** * @return the readTimes */ public long getReadTimes() { return readTimes; } /** * @param readTimes the readTimes to set */ public void setReadTimes(long readTimes) { this.readTimes = readTimes; } /** * @return the commentcount */ public long getCommentcount() { return commentcount; } /** * @param commentcount the commentcount to set */ public void setCommentcount(long commentcount) { this.commentcount = commentcount; } /** * @return the article */ public ArticleEntity getArticle() { return article; } /** * @param article the article to set */ public void setArticle(ArticleEntity article) { this.article = article; } /** * @return the content */ public String getContent() { return content; } /** * @param content the content to set */ public void setContent(String content) { this.content = content; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "ArticleBody [" + (shortcut != null ? "shortcut=" + shortcut + ", " : "") + (publishdate != null ? "publishdate=" + publishdate + ", " : "") + "readTimes=" + readTimes + ", commentcount=" + commentcount + ", " + (article != null ? "article=" + article + ", " : "") + (content != null ? "content=" + content : "") + "]"; } /** * @param shortcut 文章摘要 * @param publishdate 发表日期 * @param readTimes 阅读次数 * @param commentcount 评论数 * @param article 文章实体 * @param content 文章内容 */ public ArticleBody(String shortcut, String publishdate, long readTimes, long commentcount, ArticleEntity article, String content) { super(); this.shortcut = shortcut; this.publishdate = publishdate; this.readTimes = readTimes; this.commentcount = commentcount; this.article = article; this.content = content; } /** * 默认构造函数 */ public ArticleBody() { super(); } }
19.432432
116
0.614047
736e05c4c54f838a1e5e1660bc6cd027df5b91b7
618
/** * */ package ch.hslu.oop.sw6; import static org.junit.Assert.*; import org.junit.Test; /** * @author silvan * */ public class CalculatorTest { @Test public void testAdditionNormal() { CalculatorService calc1 = new Calculator(); int res = calc1.addition(3, 4); assertEquals(7,res); } @Test public void testAdditionZero() { Calculator calc2 = new Calculator(); int res2 = calc2.addition(0,0); assertEquals(0,res2); } @Test public void testAdditionNegative() { Calculator calc3 = new Calculator(); int res3 = calc3.addition(-4, -10); assertEquals(-14, res3); } }
14.714286
45
0.653722
a23b641e6e68c7509a6d6234ed5348fc2a7e25cc
613
package com.junhua.algorithm.offer; public class Nowcoder1 { static public boolean Find(int target, int[][] array) { if (array == null || array.length == 0 || array[0].length == 0) return false; int m = array.length, n = array[0].length; int i = 0, j = n - 1; if (target > array[m - 1][n - 1] || target < array[0][0]) return false; while (i < m && j >= 0) { if (target == array[i][j]) return true; if (target > array[i][j]) { i++; } else { j--; } } return false; } }
29.190476
85
0.45677
f860318ec524d811a93abcd57a32898fa96585c4
3,903
import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; public class GamePanel extends JPanel implements Runnable { static final int GAME_WIDTH =1000; static final int GAME_HEIGHT =(int) (GAME_WIDTH*(0.5555)); static final Dimension SCREEN_SIZE = new Dimension(GAME_WIDTH,GAME_HEIGHT); static final int BALL_DIAMETER =20; static final int PADDLE_WIDTH = 25; static final int PADDLE_HEIGHT = 100; Thread gameThread; Image image; Graphics graphics; Random random; Paddle paddle1; Paddle paddle2; Ball ball; Score score; GamePanel(){ newPaddles(); newBall(); score = new Score(GAME_WIDTH,GAME_HEIGHT); this.setFocusable(true); this.addKeyListener(new AL()); this.setPreferredSize(SCREEN_SIZE); gameThread = new Thread(this); gameThread.start(); } public void newBall() { random = new Random(); ball = new Ball((GAME_WIDTH/2)-(BALL_DIAMETER/2),random.nextInt(GAME_HEIGHT-BALL_DIAMETER),BALL_DIAMETER,BALL_DIAMETER); } public void newPaddles() { paddle1 = new Paddle(0,(GAME_HEIGHT/2)-(PADDLE_HEIGHT/2),PADDLE_WIDTH,PADDLE_HEIGHT,1); paddle2 = new Paddle(GAME_WIDTH-PADDLE_WIDTH,(GAME_HEIGHT/2)-(PADDLE_HEIGHT/2),PADDLE_WIDTH,PADDLE_HEIGHT,2); } public void paint(Graphics g) { image = createImage(getWidth(),getHeight()); graphics = image.getGraphics(); draw(graphics); g.drawImage(image,0,0,this); } public void draw(Graphics g) { paddle1.draw(g); paddle2.draw(g); ball.draw(g); score.draw(g); Toolkit.getDefaultToolkit().sync(); } public void move() { paddle1.move(); paddle2.move(); ball.move(); } public void checkCollision() { //bounce ball off top & bottom window edges if(ball.y <=0) { ball.setYDirection(-ball.yVelocity); } if(ball.y >= GAME_HEIGHT-BALL_DIAMETER) { ball.setYDirection(-ball.yVelocity); } //bounce ball off paddles if(ball.intersects(paddle1)) { ball.xVelocity = Math.abs(ball.xVelocity); ball.xVelocity++; //optional for more difficulty if(ball.yVelocity>0) ball.yVelocity++; //optional for more difficulty else ball.yVelocity--; ball.setXDirection(ball.xVelocity); ball.setYDirection(ball.yVelocity); } if(ball.intersects(paddle2)) { ball.xVelocity = Math.abs(ball.xVelocity); ball.xVelocity++; //optional for more difficulty if(ball.yVelocity>0) ball.yVelocity++; //optional for more difficulty else ball.yVelocity--; ball.setXDirection(-ball.xVelocity); ball.setYDirection(ball.yVelocity); } //stop paddle at window edges if(paddle1.y<=0) paddle1.y=0; if(paddle1.y >= (GAME_HEIGHT-PADDLE_HEIGHT)) paddle1.y = GAME_HEIGHT-PADDLE_HEIGHT; if(paddle2.y<=0) paddle2.y=0; if(paddle2.y >= (GAME_HEIGHT-PADDLE_HEIGHT)) paddle2.y = GAME_HEIGHT-PADDLE_HEIGHT; //give a player 1 point and creates new paddles & ball if(ball.x <=0) { score.player2++; newPaddles(); newBall(); System.out.println("Player 2: "+score.player2); } if(ball.x >= GAME_WIDTH-BALL_DIAMETER) { score.player1++; newPaddles(); newBall(); System.out.println("Player 1: "+score.player1); } } public void run() { //game loop long lastTime = System.nanoTime(); double amountOfTicks = 60.0; double ns = 1000000000/amountOfTicks; double delta = 0; while(true){ long now =System.nanoTime(); delta += (now - lastTime)/ns; lastTime = now; if(delta >=1) { move(); checkCollision(); repaint(); delta--; System.out.println(""); } } } public class AL extends KeyAdapter{ public void keyPressed(KeyEvent e) { paddle1.keyPressed(e); paddle2.keyPressed(e); } public void keyReleased(KeyEvent e) { paddle1.keyReleased(e); paddle2.keyReleased(e); } } }
23.371257
122
0.661542
c4dbef6b3ae977b060b2aa3a7ce5e3dac589b516
1,358
/* TableColumnImpl.java Purpose: Description: History: Dec 9, 2014 7:05:44 PM, Created by henrichen Copyright (C) 2014 Potix Corporation. All Rights Reserved. */ package org.zkoss.zss.model.impl; import java.io.Serializable; import org.zkoss.zss.model.SCellStyle; import org.zkoss.zss.model.STableColumn; /** * Table column. * @author henri * @since 3.8.0 */ public class TableColumnImpl implements STableColumn, Serializable { private static final long serialVersionUID = 4333495215409538027L; String _name; String _totalsRowLabel; String _totalsRowFormula; STotalsRowFunction _totalsRowFunction; public TableColumnImpl(String name) { _name = name; } @Override public String getName() { return _name; } @Override public String getTotalsRowLabel() { return _totalsRowLabel; } @Override public STotalsRowFunction getTotalsRowFunction() { return _totalsRowFunction; } @Override public void setName(String name) { _name = name; } @Override public void setTotalsRowLabel(String label) { _totalsRowLabel = label; } @Override public void setTotalsRowFunction(STotalsRowFunction func) { _totalsRowFunction = func; } @Override public String getTotalsRowFormula() { return _totalsRowFormula; } @Override public void setTotalsRowFormula(String formula) { _totalsRowFormula = formula; } }
18.351351
68
0.751105
42d3f69d1dfc45faaa93557443d25f04c5242a9d
1,840
// Copyright (C) 2017 The Android Open Source 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. package com.google.gerrit.server.git; import java.io.IOException; import java.util.Map; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.RefDatabase; import org.eclipse.jgit.transport.BaseReceivePack; import org.eclipse.jgit.transport.ServiceMayNotContinueException; /** Static utilities for writing git protocol hooks. */ public class HookUtil { /** * Scan and advertise all refs in the repo if refs have not already been advertised; otherwise, * just return the advertised map. * * @param rp receive-pack handler. * @return map of refs that were advertised. * @throws ServiceMayNotContinueException if a problem occurred. */ public static Map<String, Ref> ensureAllRefsAdvertised(BaseReceivePack rp) throws ServiceMayNotContinueException { Map<String, Ref> refs = rp.getAdvertisedRefs(); if (refs != null) { return refs; } try { refs = rp.getRepository().getRefDatabase().getRefs(RefDatabase.ALL); } catch (ServiceMayNotContinueException e) { throw e; } catch (IOException e) { throw new ServiceMayNotContinueException(e); } rp.setAdvertisedRefs(refs, rp.getAdvertisedObjects()); return refs; } private HookUtil() {} }
34.716981
97
0.730435
3c8ae96197f20570ed22ca42d10c4622faa5dff1
4,148
/* * Copyright (c) 1998-2018 University Corporation for Atmospheric Research/Unidata * See LICENSE for license information. */ package ucar.nc2.dods; import ucar.nc2.*; import ucar.nc2.constants._Coordinate; import java.util.*; import java.io.IOException; /** * A DODS Grid. * A Grid has a Variable and associated coordinate variables, called maps. * * @see ucar.nc2.Variable * @author caron */ public class DODSGrid extends DODSVariable { private static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(DODSGrid.class); DODSGrid(DODSNetcdfFile dodsfile, Group parentGroup, Structure parentStructure, String dodsShortName, DodsV dodsV) throws IOException { super(dodsfile, parentGroup, parentStructure, dodsShortName, dodsV); DodsV array = dodsV.children.get(0); /* * if (!shortName.equals(array.bt.getName())) { * this.shortName = shortName + "-" + array.bt.getName(); // LOOK whats this ?? * } * // so we just map the netcdf grid variable to the dods grid.array * this.dodsShortName = shortName + "." + array.bt.getName(); */ // the common case is that the map vectors already exist as a top level variables List<Dimension> dims = new ArrayList<Dimension>(); Formatter sbuff = new Formatter(); for (int i = 1; i < dodsV.children.size(); i++) { DodsV map = dodsV.children.get(i); String name = DODSNetcdfFile.makeShortName(map.bt.getEncodedName()); Dimension dim = parentGroup.findDimension(name); if (dim == null) { logger.warn("DODSGrid cant find dimension = <" + name + ">"); } else { dims.add(dim); sbuff.format("%s ", name); } } setDimensions(dims); setDataType(array.getDataType()); /* * if (DODSNetcdfFile.isUnsigned( array.bt)) { * addAttribute(new Attribute(CDM.UNSIGNED, "true")); * } */ DODSAttribute att = new DODSAttribute(_Coordinate.Axes, sbuff.toString()); this.addAttribute(att); } // for section, slice @Override protected Variable copy() { return new DODSGrid(this); } private DODSGrid(DODSGrid from) { super(from); } /* * private void connectMaps(Group parentGroup, List maps) { * * // first one is the array, the rest are maps * DODSVariable array = (DODSVariable) vars.get(0); * List maps = vars.subList(1, vars.size()); * * // do the maps first - LOOK for now assume that they are 1D coord vars * ArrayList mapDimensions = new ArrayList(); * for (int i=0; i<maps.size(); i++) { * DODSVariable map = (DODSVariable) maps.get(i); * * // see if it already exists LOOK not general case; assume names are unique! * DODSVariable existingMap = (DODSVariable) parentGroup.findVariable( map.getShortName()); * Dimension dim; * if (existingMap != null) { * dim = existingMap.getDimension( 0); * if (DODSNetcdfFile.debugConstruct) System.out.println(" already have coordinate map = "+map.getName()); * } else { * dim = convertToCoordinateVariable( map); * parentGroup.addDimension( dim); * parentGroup.addVariable( map); * if (DODSNetcdfFile.debugConstruct) System.out.println(" added coordinate map = "+map.getName()); * } * * mapDimensions.add( dim); * array.replaceDimension(dim); * } * * StringBuffer sbuff = new StringBuffer(); * for (int i=0; i<mapDimensions.size(); i++) { * Dimension d = (Dimension) mapDimensions.get(i); * if (i > 0) sbuff.append(" "); * sbuff.append(d.getName()); * } * setDimensions( array.getDimensions()); * setDataType( array.getDataType()); * * DODSAttribute att = new DODSAttribute("_coordinateSystem", sbuff.toString()); * this.addAttribute( att); * } * * private Dimension convertToCoordinateVariable ( DODSVariable v) { * Dimension oldDimension = v.getDimension(0); * Dimension newDimension = new Dimension( v.getShortName(), oldDimension.getLength(), true); * newDimension.setCoordinateVariable( v); * v.setDimension( 0, newDimension); * v.calcIsCoordinateVariable(); * * return newDimension; * * } */ }
32.40625
116
0.655256
3b7331d700198c5216b0f0c4cbb2d16c69523e01
3,515
package net.osmand.plus.backup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.util.ArrayList; import java.util.List; import java.util.Map; public class BackupListeners { private final List<OnDeleteFilesListener> deleteFilesListeners = new ArrayList<>(); private final List<OnRegisterUserListener> registerUserListeners = new ArrayList<>(); private final List<OnRegisterDeviceListener> registerDeviceListeners = new ArrayList<>(); public interface OnDeleteFilesListener { void onFilesDeleteStarted(@NonNull List<RemoteFile> files); void onFileDeleteProgress(@NonNull RemoteFile file, int progress); void onFilesDeleteDone(@NonNull Map<RemoteFile, String> errors); void onFilesDeleteError(int status, @NonNull String message); } public interface OnRegisterUserListener { void onRegisterUser(int status, @Nullable String message, @Nullable BackupError error); } public interface OnRegisterDeviceListener { void onRegisterDevice(int status, @Nullable String message, @Nullable BackupError error); } public interface OnUpdateSubscriptionListener { void onUpdateSubscription(int status, @Nullable String message, @Nullable String error); } public interface OnDownloadFileListListener { void onDownloadFileList(int status, @Nullable String message, @NonNull List<RemoteFile> remoteFiles); } public interface OnCollectLocalFilesListener { void onFileCollected(@NonNull LocalFile localFile); void onFilesCollected(@NonNull List<LocalFile> localFiles); } public interface OnGenerateBackupInfoListener { void onBackupInfoGenerated(@Nullable BackupInfo backupInfo, @Nullable String error); } public interface OnUploadFileListener { void onFileUploadStarted(@NonNull String type, @NonNull String fileName, int work); void onFileUploadProgress(@NonNull String type, @NonNull String fileName, int progress, int deltaWork); void onFileUploadDone(@NonNull String type, @NonNull String fileName, long uploadTime, @Nullable String error); boolean isUploadCancelled(); } public interface OnDownloadFileListener { void onFileDownloadStarted(@NonNull String type, @NonNull String fileName, int work); void onFileDownloadProgress(@NonNull String type, @NonNull String fileName, int progress, int deltaWork); void onFileDownloadDone(@NonNull String type, @NonNull String fileName, @Nullable String error); boolean isDownloadCancelled(); } public List<OnDeleteFilesListener> getDeleteFilesListeners() { return deleteFilesListeners; } public void addDeleteFilesListener(@NonNull OnDeleteFilesListener listener) { deleteFilesListeners.add(listener); } public void removeDeleteFilesListener(@NonNull OnDeleteFilesListener listener) { deleteFilesListeners.remove(listener); } public List<OnRegisterUserListener> getRegisterUserListeners() { return registerUserListeners; } public void addRegisterUserListener(@NonNull OnRegisterUserListener listener) { registerUserListeners.add(listener); } public void removeRegisterUserListener(@NonNull OnRegisterUserListener listener) { registerUserListeners.remove(listener); } public List<OnRegisterDeviceListener> getRegisterDeviceListeners() { return registerDeviceListeners; } public void addRegisterDeviceListener(@NonNull OnRegisterDeviceListener listener) { registerDeviceListeners.add(listener); } public void removeRegisterDeviceListener(@NonNull OnRegisterDeviceListener listener) { registerDeviceListeners.remove(listener); } }
32.546296
113
0.807397
5d4061e56e597f0d543411df75e0b8331542b5a0
1,618
package com.perforce.team.core.mergequest; import com.perforce.team.core.mergequest.model.registry.BranchRegistry; import org.eclipse.core.runtime.Plugin; import org.osgi.framework.BundleContext; /** * The activator class controls the plug-in life cycle */ public class P4BranchGraphCorePlugin extends Plugin { /** * The plug-in ID */ public static final String PLUGIN_ID = "com.perforce.team.core.mergequest"; //$NON-NLS-1$ // The shared instance private static P4BranchGraphCorePlugin plugin; private BranchRegistry branchRegistry; /** * The constructor */ public P4BranchGraphCorePlugin() { } /** * @see org.eclipse.core.runtime.Plugin#start(org.osgi.framework.BundleContext) */ @Override public void start(BundleContext context) throws Exception { super.start(context); plugin = this; } /** * @see org.eclipse.core.runtime.Plugin#stop(org.osgi.framework.BundleContext) */ @Override public void stop(BundleContext context) throws Exception { plugin = null; super.stop(context); } /** * Get branch registry * * @return branch registry */ public BranchRegistry getBranchRegistry() { if (branchRegistry == null) { branchRegistry = new BranchRegistry(PLUGIN_ID + ".elements"); //$NON-NLS-1$ } return branchRegistry; } /** * Returns the shared instance * * @return the shared instance */ public static P4BranchGraphCorePlugin getDefault() { return plugin; } }
23.449275
93
0.642769
f2a5e26ca8b035805cfebb9658909f44603fc473
2,578
/* * (C) Copyright IBM Corp. 2021. * * 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.ibm.cloud.iaesdk.ibm_analytics_engine_api.v2.model; import com.ibm.cloud.iaesdk.ibm_analytics_engine_api.v2.model.AnalyticsEngineLoggingNodeSpec; import com.ibm.cloud.iaesdk.ibm_analytics_engine_api.v2.utils.TestUtilities; import com.ibm.cloud.sdk.core.service.model.FileWithMetadata; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import org.testng.annotations.Test; import static org.testng.Assert.*; /** * Unit test class for the AnalyticsEngineLoggingNodeSpec model. */ public class AnalyticsEngineLoggingNodeSpecTest { final HashMap<String, InputStream> mockStreamMap = TestUtilities.createMockStreamMap(); final List<FileWithMetadata> mockListFileWithMetadata = TestUtilities.creatMockListFileWithMetadata(); @Test public void testAnalyticsEngineLoggingNodeSpec() throws Throwable { AnalyticsEngineLoggingNodeSpec analyticsEngineLoggingNodeSpecModel = new AnalyticsEngineLoggingNodeSpec.Builder() .nodeType("management") .components(new java.util.ArrayList<String>(java.util.Arrays.asList("ambari-server"))) .build(); assertEquals(analyticsEngineLoggingNodeSpecModel.nodeType(), "management"); assertEquals(analyticsEngineLoggingNodeSpecModel.components(), new java.util.ArrayList<String>(java.util.Arrays.asList("ambari-server"))); String json = TestUtilities.serialize(analyticsEngineLoggingNodeSpecModel); AnalyticsEngineLoggingNodeSpec analyticsEngineLoggingNodeSpecModelNew = TestUtilities.deserialize(json, AnalyticsEngineLoggingNodeSpec.class); assertTrue(analyticsEngineLoggingNodeSpecModelNew instanceof AnalyticsEngineLoggingNodeSpec); assertEquals(analyticsEngineLoggingNodeSpecModelNew.nodeType(), "management"); } @Test(expectedExceptions = IllegalArgumentException.class) public void testAnalyticsEngineLoggingNodeSpecError() throws Throwable { new AnalyticsEngineLoggingNodeSpec.Builder().build(); } }
46.872727
146
0.8045
428df80529149c67c58f8af672b0da023c4e8536
1,349
/** * ADOBE SYSTEMS INCORPORATED * Copyright 2009-2013 Adobe Systems Incorporated * All Rights Reserved. * * NOTICE: Adobe permits you to use, modify, and distribute * this file in accordance with the terms of the MIT license, * a copy of which can be found in the LICENSE.txt file or at * http://opensource.org/licenses/MIT. */ package runtime.intrinsic.demo.processing; import processing.core.PMatrix3D; import runtime.intrinsic.IntrinsicLambda; import runtime.rep.Tuple; /** * Demo support, Processing hook */ public final class _prmatmult extends IntrinsicLambda { public static final _prmatmult INSTANCE = new _prmatmult(); public static final String NAME = "prmatmult"; public String getName() { return NAME; } public Object apply(final Object arg) { final Tuple args = (Tuple)arg; return invoke(args.get(0), (Double)args.get(1), (Double)args.get(2), (Double)args.get(3)); } public static Tuple invoke(final Object arg0, final double x, final double y, final double z) { final PMatrix3D mat = (PMatrix3D)arg0; final float[] in = new float[]{(float)x, (float)y, (float)z}; final float[] out = new float[3]; mat.mult(in, out); return Tuple.from((double)out[0], (double)out[1], (double)out[2]); } }
27.530612
76
0.661972
33ef47aae575e67b2d641b9ecd8d31db29bfb402
2,658
/* * Decompiled with CFR 0.150. */ package me.independed.inceptice.modules; import me.independed.inceptice.modules.Module; import me.independed.inceptice.modules.ModuleManager; public enum Module$Category { MOVEMENT("MOVEMENT"), COMBAT("COMBAT"), RENDER("RENDER"), PLAYER("PLAYER"), WORLD("MISC"), GHOST("GHOST"), HUD("HUD"); public int moduleIndex; public String name; public static int placeInListPlayer(Module module) { int n = 2; for (Module module2 : ModuleManager.getModuleList()) { if (module2.getCategory().equals((Object)PLAYER) && !module2.equals(module)) { ++n; continue; } if (!module2.getCategory().equals((Object)PLAYER) || !module2.equals(module)) continue; return n; } return 2; } public static int size(Module$Category module$Category) { int n = 0; for (Module module : ModuleManager.getModuleList()) { if (module.getCategory() != module$Category) continue; ++n; } return n; } public static int placeInListMovement(Module module) { int n = 2; for (Module module2 : ModuleManager.getModuleList()) { if (module2.getCategory().equals((Object)MOVEMENT) && !module2.equals(module)) { ++n; continue; } if (!module2.getCategory().equals((Object)MOVEMENT) || !module2.equals(module)) continue; return n; } return 2; } /* * WARNING - Possible parameter corruption * WARNING - void declaration */ private Module$Category() { void var3_1; this.name = var3_1; } public static int placeInListCombat(Module module) { int n = 2; for (Module module2 : ModuleManager.getModuleList()) { if (module2.getCategory().equals((Object)COMBAT) && !module2.equals(module)) { ++n; continue; } if (!module2.getCategory().equals((Object)COMBAT) || !module2.equals(module)) continue; return n; } return 2; } public static int placeInListRender(Module module) { int n = 2; for (Module module2 : ModuleManager.getModuleList()) { if (module2.getCategory().equals((Object)RENDER) && !module2.equals(module)) { ++n; continue; } if (!module2.getCategory().equals((Object)RENDER) || !module2.equals(module)) continue; return n; } return 2; } }
28.891304
101
0.554176
bd213608fb01bc3b898c59348ddebc8e27e956c2
11,429
/* * Copyright 2017-2019 Ivan Krizsan * * 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 se.ivankrizsan.springintegration.messagechannels.pollable; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.integration.IntegrationMessageHeaderAccessor; import org.springframework.integration.channel.PriorityChannel; import org.springframework.integration.config.EnableIntegration; import org.springframework.integration.support.MessageBuilder; import org.springframework.messaging.Message; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import se.ivankrizsan.springintegration.shared.EmptyConfiguration; import se.ivankrizsan.springintegration.shared.SpringIntegrationExamplesConstants; import java.util.Comparator; /** * Exercises demonstrating the use of Spring Integration priority message channels. * A priority message channel is a queue channel that supports messages with different * priority. * * @author Ivan Krizsan * @see PriorityChannel */ @SpringBootTest @EnableIntegration @SpringJUnitConfig(classes = { EmptyConfiguration.class }) public class PriorityChannelTests implements SpringIntegrationExamplesConstants { /* Constant(s): */ protected static final Log LOGGER = LogFactory.getLog(PriorityChannelTests.class); /* Instance variable(s): */ /** * Tests creating a priority message channel and sending * a message to the channel. * * Expected result: There should be a message when the message channel * is polled and and the message payload should be identical to the * payload of the sent message. */ @Test public void successfullyPollingMessageTest() { final PriorityChannel thePriorityChannel; final Message<String> theInputMessage; final Message<?> theOutputMessage; theInputMessage = MessageBuilder .withPayload(GREETING_STRING) .build(); // <editor-fold desc="Answer Section" defaultstate="collapsed"> thePriorityChannel = new PriorityChannel(); /* Set the name of the channel which will be included in exceptions and log messages. */ thePriorityChannel.setComponentName(PRIORITY_CHANNEL_NAME); thePriorityChannel.send(theInputMessage); // </editor-fold> theOutputMessage = thePriorityChannel.receive(RECEIVE_TIMEOUT_5000_MILLISECONDS); Assertions.assertNotNull( theOutputMessage, "A message should be available from the message channel"); final Object theOutputMessagePayload = theOutputMessage.getPayload(); Assertions.assertEquals( GREETING_STRING, theOutputMessagePayload, "Input and output payloads should be the same"); } /** * Tests creating a priority message channel and sending two messages * to the channel. The second message sent has a higher priority. * * Expected result: The second message, having a higher priority, should * be received before the first message. */ @Test public void messagesWithDifferentPriority() { final PriorityChannel thePriorityChannel; final Message<String> theInputMessage1; final Message<String> theInputMessage2; final Message<?> theOutputMessage1; final Message<?> theOutputMessage2; /* * Second message has higher priority than first message. * Default priority comparision mechanism is used. */ theInputMessage1 = MessageBuilder .withPayload("1") .setPriority(1) .build(); theInputMessage2 = MessageBuilder .withPayload("2") .setPriority(2) .build(); // <editor-fold desc="Answer Section" defaultstate="collapsed"> thePriorityChannel = new PriorityChannel(); /* Set the name of the channel which will be included in exceptions and log messages. */ thePriorityChannel.setComponentName(PRIORITY_CHANNEL_NAME); thePriorityChannel.send(theInputMessage1); thePriorityChannel.send(theInputMessage2); // </editor-fold> theOutputMessage1 = thePriorityChannel.receive(RECEIVE_TIMEOUT_5000_MILLISECONDS); theOutputMessage2 = thePriorityChannel.receive(RECEIVE_TIMEOUT_5000_MILLISECONDS); final Object theOutputMessagePayload1 = theOutputMessage1.getPayload(); final Object theOutputMessagePayload2 = theOutputMessage2.getPayload(); Assertions.assertEquals( "2", theOutputMessagePayload1, "Message with higher priority should be received first"); Assertions.assertEquals( "1", theOutputMessagePayload2, "Message with lower priority should be received second"); } /** * Tests creating a priority message channel configured with a custom * message priority comparator. The custom priority comparator examines * a custom priority header for a string and determines priority based * on the alphabetical ordering of the custom priority header strings. * Send two messages to the channel, which use different strings in * the priority header value. * * Expected result: The message with the priority-string being first * in alphabetical order should be received first, the other message * afterwards. */ @Test public void messagesWithDifferentPriorityCustomPriorityComparator() { final PriorityChannel thePriorityChannel; final Message<String> theInputMessage1; final Message<String> theInputMessage2; final Message<?> theOutputMessage1; final Message<?> theOutputMessage2; /* * Second message has higher priority than first message. * Default priority comparision mechanism is used. */ theInputMessage1 = MessageBuilder .withPayload("1") .setHeader(CUSTOM_PRIORITY_HEADER, "orange") .build(); theInputMessage2 = MessageBuilder .withPayload("2") .setHeader(CUSTOM_PRIORITY_HEADER, "banana") .build(); // <editor-fold desc="Answer Section" defaultstate="collapsed"> /* * Create the custom message priority comparator that retrieves message priority from * a custom header and assumes that priority values are strings. */ final Comparator<Message<?>> theMessagePriorityComparator = (inMessage1, inMessage2) -> { final String thePriority1 = (String)new IntegrationMessageHeaderAccessor(inMessage1).getHeader( CUSTOM_PRIORITY_HEADER); final String thePriority2 = (String)new IntegrationMessageHeaderAccessor(inMessage2).getHeader( CUSTOM_PRIORITY_HEADER); return thePriority1.compareTo(thePriority2); }; thePriorityChannel = new PriorityChannel(theMessagePriorityComparator); /* Set the name of the channel which will be included in exceptions and log messages. */ thePriorityChannel.setComponentName(PRIORITY_CHANNEL_NAME); thePriorityChannel.send(theInputMessage1); thePriorityChannel.send(theInputMessage2); // </editor-fold> theOutputMessage1 = thePriorityChannel.receive(RECEIVE_TIMEOUT_5000_MILLISECONDS); Assertions.assertNotNull( theOutputMessage1, "A first message should be available from the message channel"); theOutputMessage2 = thePriorityChannel.receive(RECEIVE_TIMEOUT_5000_MILLISECONDS); Assertions.assertNotNull( theOutputMessage2, "A second message should be available from the message channel"); final Object theOutputMessagePayload1 = theOutputMessage1.getPayload(); final Object theOutputMessagePayload2 = theOutputMessage2.getPayload(); Assertions.assertEquals( "2", theOutputMessagePayload1, "Message with higher priority should be received first"); Assertions.assertEquals( "1", theOutputMessagePayload2, "Message with lower priority should be received second"); } /** * Tests creating a priority message channel and sending two messages * to the channel. Both messages have the same priority. * * Expected result: The messages should be received in the same order * they were sent. */ @Test public void messagesWithSamePriority() { final PriorityChannel thePriorityChannel; final Message<String> theInputMessage1; final Message<String> theInputMessage2; final Message<?> theOutputMessage1; final Message<?> theOutputMessage2; /* * Second message has higher priority than first message. * Default priority comparision mechanism is used. */ theInputMessage1 = MessageBuilder .withPayload("1") .setPriority(1) .build(); theInputMessage2 = MessageBuilder .withPayload("2") .setPriority(1) .build(); // <editor-fold desc="Answer Section" defaultstate="collapsed"> thePriorityChannel = new PriorityChannel(); /* Set the name of the channel which will be included in exceptions and log messages. */ thePriorityChannel.setComponentName(PRIORITY_CHANNEL_NAME); thePriorityChannel.send(theInputMessage1); thePriorityChannel.send(theInputMessage2); // </editor-fold> theOutputMessage1 = thePriorityChannel.receive(RECEIVE_TIMEOUT_5000_MILLISECONDS); Assertions.assertNotNull( theOutputMessage1, "A first message should be available from the message channel"); theOutputMessage2 = thePriorityChannel.receive(RECEIVE_TIMEOUT_5000_MILLISECONDS); Assertions.assertNotNull( theOutputMessage2, "A second message should be available from the message channel"); final Object theOutputMessagePayload1 = theOutputMessage1.getPayload(); final Object theOutputMessagePayload2 = theOutputMessage2.getPayload(); Assertions.assertEquals( "1", theOutputMessagePayload1, "Message with same priority should be received in order sent"); Assertions.assertEquals( "2", theOutputMessagePayload2, "Message with same priority should be received in order sent"); } }
40.242958
96
0.681424
dde5c56b42cb70d8a41726652b8d8ae68d9cf228
800
package ru.jts.tests.parser; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import ru.jts.data.holder.CursedWeaponDataHolder; import ru.jts.data.holder.cursedweapondata.CursedWeapon; import ru.jts.data.parser.CursedWeaponDataParser; /** * @author : Camelion * @date : 26.08.12 21:34 */ public class CursedWeaponDataParserTest extends Assert { @Before public void setUp() throws Exception { CursedWeaponDataParser.getInstance().load(); } @Test public void test() { CursedWeaponDataHolder holder = CursedWeaponDataHolder.getInstance(); assertFalse(holder.getCursedWeapons().size() == 0); for (CursedWeapon weapon : holder.getCursedWeapons()) { assertFalse(weapon.item_name.isEmpty()); } } }
25.806452
77
0.7
b6a5487a1f03481b1fca8a97e0342cf5396d02fe
589
package sfrerichs.web.rest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * HomeResource controller */ @RestController @RequestMapping("/api/home") public class HomeResource { private final Logger log = LoggerFactory.getLogger(HomeResource.class); /** * GET showInfo */ @GetMapping("/show-info") public String showInfo() { return "showInfo"; } }
21.814815
75
0.736842
83deeefb6610424ca60603756ced83ed69f8c71e
1,830
package defaultData; import io.ebean.Finder; import models.users.Company; import java.util.Date; public class DefaultCompanies { private Long firstCompanyId = 1L; private Long secondCompanyId = 2L; private String firstName = "Example1"; private String secondName = "Example2"; private String firstPhone = "0"; private String secondPhone = "1"; private String firstEmail = "company1@example.com"; private String secondEmail = "company2@example.com"; private String firstTaxNumber = "1"; private String secondTaxNumber = "2"; private String address = "Street 1"; private String city = "City"; private String state = "State"; private String country = "country"; private String postalCode = "1"; public void createCompanies(){ createCompany(this.firstCompanyId,this.firstName, this.firstPhone, this.firstEmail, this.firstTaxNumber); createCompany(this.secondCompanyId, this.secondName, this.secondPhone, this.secondEmail, this.secondTaxNumber); } public void deleteCompanies(){ Finder<Long, Company> finder = new Finder<Long, Company>(Company.class); finder.all().forEach(company -> company.delete()); } private void createCompany(Long id, String name, String phone, String email, String taxNumber){ Company company = new Company(); company.id = id; company.createdAt = new Date(); company.updatedAt = new Date(); company.name = name; company.email = email; company.phone = phone; company.taxNumber = taxNumber; company.address = this.address; company.city = this.city; company.state = this.state; company.country = this.country; company.postalCode = this.postalCode; company.save(); } }
28.59375
119
0.668306
3aaa815e49e5068b1c0f11a2770700e34cee1185
1,570
package io.openex.service; import io.openex.database.model.Inject; import io.openex.database.model.InjectDocument; import io.openex.database.repository.InjectDocumentRepository; import io.openex.database.repository.InjectRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.stream.Stream; @Service public class InjectService { private InjectDocumentRepository injectDocumentRepository; private InjectRepository injectRepository; @Autowired public void setInjectDocumentRepository(InjectDocumentRepository injectDocumentRepository) { this.injectDocumentRepository = injectDocumentRepository; } @Autowired public void setInjectRepository(InjectRepository injectRepository) { this.injectRepository = injectRepository; } public void cleanInjectsDocExercise(String exerciseId, String documentId) { // Delete document from all exercise injects List<Inject> exerciseInjects = injectRepository.findAllForExerciseAndDoc(exerciseId, documentId); List<InjectDocument> updatedInjects = exerciseInjects.stream().flatMap(inject -> { @SuppressWarnings("UnnecessaryLocalVariable") Stream<InjectDocument> filterDocuments = inject.getDocuments().stream() .filter(document -> document.getDocument().getId().equals(documentId)); return filterDocuments; }).toList(); injectDocumentRepository.deleteAll(updatedInjects); } }
38.292683
105
0.761783
e89543ef669cb3c75b26e67f6966e2cb565015a1
3,340
package controllers; import java.util.List; import javax.persistence.PersistenceException; import models.BlogPost; import models.Member; import models.Subscriber; import com.avaje.ebean.Ebean; import com.fasterxml.jackson.databind.node.ObjectNode; import play.data.DynamicForm; import play.libs.Json; import play.mvc.Controller; import play.mvc.Result; import play.mvc.Security; import tools.StringUtil; public class Admin extends Controller { private static final DynamicForm form = play.data.Form.form(); public static Result index(int page) { Member member = Membership.getUser(); int goPage = Math.max(1, page); return ok(views.html.admin.index.render(member,null,goPage)); } @Security.Authenticated(Secured.class) public static Result indexNewsletter() { return ok(views.html.admin.newsletter.render()); } @Security.Authenticated(AjaxSecured.class) public static Result addPost() { Member member = Membership.getUser(); DynamicForm dynForm = form.bindFromRequest(); BlogPost post = getBlogFromRequest(dynForm); ObjectNode jsonResponse = Json.newObject(); if ( post != null) { try { post = Member.addPost(member, post); jsonResponse.put("id", post.id); return ok(jsonResponse); } catch (PersistenceException e) { return internalServerError("DB error"); } } return badRequest("parameter missing"); } @Security.Authenticated(AjaxSecured.class) public static Result updatePost(Long postId) { BlogPost oldPost = BlogPost.findBlogById(postId); DynamicForm dynForm = form.bindFromRequest(); BlogPost newPost = getBlogFromRequest(dynForm); if ( newPost != null) { try { BlogPost.updatePost(oldPost, newPost); return ok(); } catch (PersistenceException e) { System.out.println("DB error :" + e.getLocalizedMessage()); return internalServerError("DB error"); } } return badRequest("parameter missing"); } @Security.Authenticated(Secured.class) public static Result editPost(Long postId) { Member member = Membership.getUser(); BlogPost post = BlogPost.findBlogById(postId); return ok(views.html.admin.index.render(member,post,0)); } private static BlogPost getBlogFromRequest(DynamicForm form) { try { String title = form.get("title"); String body = form.get("body"); String bodyhtml = StringUtil.cleanHtml( form.get("bodyhtml") ) ; String pubdate = form.get("pubdate"); String[] dates = pubdate.split(" "); Integer pubday = Integer.parseInt(dates[0]); int pubmonth = Integer.parseInt(dates[1]); int pubyear = Integer.parseInt(dates[2]); Integer date = pubyear * 10000 + pubmonth * 100 + pubday; boolean isOnline = "true".equals(form.get("isonline")); return new BlogPost(title,body, bodyhtml, date,isOnline); } catch (Exception e) { //System.out.println("getBlog error : " + e.getMessage() ); } return null; } }
28.547009
73
0.620359
d529bbe5152e3c52e28ae6e6af39d318cd1d001c
3,653
package utils; import com.google.inject.Inject; import com.google.inject.Singleton; import domainmodel.User; import lombok.Getter; import lombok.ToString; import spark.Redirect; import spark.Spark; import java.nio.file.Paths; @Singleton public class RoutesRegistrar { @Inject private TemplateRenderer templateRenderer; @Inject private AuthenticationManager authenticationManager; @Inject public void init() { this.registerStaticResources(); this.registerLoginRoute(); this.registerLoginProcessingRoute(); this.registrerLogoutProcessingRoute(); this.registerInstantStateRoute(); this.registerAvailableDevicesRoute(); } private void registerStaticResources() { Spark.staticFileLocation("/public"); } private void registerLoginRoute() { Spark.get(Paths.INDEX.getPath(), (request, response) -> { User user = this.authenticationManager.isUserAuthentified(request); if (user != null) { response.redirect(Paths.AVAILABLE_DEVICES.getPath()); return null; } else return this.templateRenderer.login(); }, TemplateRenderer.THYMELEAF_TEMPLATE_ENGINE); } private void registerLoginProcessingRoute() { Spark.post(Paths.LOGIN_PROCESSING.getPath(), (request, response) -> { User user = this.authenticationManager.isUserAuthentified(request); if (user != null) response.redirect(Paths.AVAILABLE_DEVICES.getPath()); else { String email = request.queryParams("email"); String password = request.queryParams("password"); this.authenticationManager.authenticateUser(request, new User(email, password)); response.redirect(Paths.INDEX.getPath()); } return null; }); } private void registrerLogoutProcessingRoute() { Spark.get(Paths.LOGOUT_PROCESSING.getPath(), (request, response) -> { this.authenticationManager.unAuthenticateUser(request); response.redirect(Paths.INDEX.getPath()); return null; }); } private void registerInstantStateRoute() { Spark.get(Paths.INSTANT_STATE.getPath(), (request, response) -> { User user = this.authenticationManager.isUserAuthentified(request); if (user != null) { return this.templateRenderer.instantState(user, request); } else { response.redirect(Paths.INDEX.getPath()); return null; } }, TemplateRenderer.THYMELEAF_TEMPLATE_ENGINE); } private void registerAvailableDevicesRoute() { Spark.get(Paths.AVAILABLE_DEVICES.getPath(), (request, response) -> { User user = this.authenticationManager.isUserAuthentified(request); if (user != null) { return this.templateRenderer.availableDevices(user, request); } else { response.redirect(Paths.INDEX.getPath()); return null; } }, TemplateRenderer.THYMELEAF_TEMPLATE_ENGINE); } @Getter @ToString enum Paths { INDEX("/"), LOGIN_PROCESSING("/login-processing"), LOGOUT_PROCESSING("/logout-processing"), INSTANT_STATE("/dashboard/instant-state"), AVAILABLE_DEVICES("/dashboard/available-devices"); private String path; Paths(String path) { this.path = path; } } }
28.76378
96
0.610183
a37a9e2324a1b7af107b5dcd0870eedde4cb2acc
6,137
package net.ensode.jasperbook.dbaccess.base; import java.lang.Comparable; import java.io.Serializable; /** * This is an object that contains data related to the aircraft_engines table. * Do not modify this class because it will be overwritten if the configuration * file related to this class is modified. * * @hibernate.class table="aircraft_engines" */ public abstract class BaseAircraftEngines implements Comparable, Serializable { public static String REF = "AircraftEngines"; public static String PROP_MODEL = "Model"; public static String PROP_AIRCRAFT_ENGINE_TYPE_ID = "AircraftEngineTypeId"; public static String PROP_FUEL_CONSUMED = "FuelConsumed"; public static String PROP_HORSEPOWER = "Horsepower"; public static String PROP_THRUST = "Thrust"; public static String PROP_MANUFACTURER = "Manufacturer"; public static String PROP_ID = "Id"; // constructors public BaseAircraftEngines() { initialize(); } /** * Constructor for primary key */ public BaseAircraftEngines(java.lang.String id) { this.setId(id); initialize(); } /** * Constructor for required fields */ public BaseAircraftEngines(java.lang.String id, java.lang.String manufacturer, java.lang.String model, java.lang.String aircraftEngineTypeId, java.lang.String horsepower, java.lang.String thrust, java.math.BigDecimal fuelConsumed) { this.setId(id); this.setManufacturer(manufacturer); this.setModel(model); this.setAircraftEngineTypeId(aircraftEngineTypeId); this.setHorsepower(horsepower); this.setThrust(thrust); this.setFuelConsumed(fuelConsumed); initialize(); } protected void initialize() { } private int hashCode = Integer.MIN_VALUE; // primary key private java.lang.String id; // fields private java.lang.String manufacturer; private java.lang.String model; private java.lang.String aircraftEngineTypeId; private java.lang.String horsepower; private java.lang.String thrust; private java.math.BigDecimal fuelConsumed; /** * Return the unique identifier of this class * * @hibernate.id generator-class="sequence" column="aircraft_engine_code" */ public java.lang.String getId() { return id; } /** * Set the unique identifier of this class * * @param id * the new ID */ public void setId(java.lang.String id) { this.id = id; this.hashCode = Integer.MIN_VALUE; } /** * Return the value associated with the column: manufacturer */ public java.lang.String getManufacturer() { return manufacturer; } /** * Set the value related to the column: manufacturer * * @param manufacturer * the manufacturer value */ public void setManufacturer(java.lang.String manufacturer) { this.manufacturer = manufacturer; } /** * Return the value associated with the column: model */ public java.lang.String getModel() { return model; } /** * Set the value related to the column: model * * @param model * the model value */ public void setModel(java.lang.String model) { this.model = model; } /** * Return the value associated with the column: aircraft_engine_type_id */ public java.lang.String getAircraftEngineTypeId() { return aircraftEngineTypeId; } /** * Set the value related to the column: aircraft_engine_type_id * * @param aircraftEngineTypeId * the aircraft_engine_type_id value */ public void setAircraftEngineTypeId(java.lang.String aircraftEngineTypeId) { this.aircraftEngineTypeId = aircraftEngineTypeId; } /** * Return the value associated with the column: horsepower */ public java.lang.String getHorsepower() { return horsepower; } /** * Set the value related to the column: horsepower * * @param horsepower * the horsepower value */ public void setHorsepower(java.lang.String horsepower) { this.horsepower = horsepower; } /** * Return the value associated with the column: thrust */ public java.lang.String getThrust() { return thrust; } /** * Set the value related to the column: thrust * * @param thrust * the thrust value */ public void setThrust(java.lang.String thrust) { this.thrust = thrust; } /** * Return the value associated with the column: fuel_consumed */ public java.math.BigDecimal getFuelConsumed() { return fuelConsumed; } /** * Set the value related to the column: fuel_consumed * * @param fuelConsumed * the fuel_consumed value */ public void setFuelConsumed(java.math.BigDecimal fuelConsumed) { this.fuelConsumed = fuelConsumed; } public boolean equals(Object obj) { if (null == obj) return false; if (!(obj instanceof net.ensode.jasperbook.dbaccess.AircraftEngines)) return false; else { net.ensode.jasperbook.dbaccess.AircraftEngines aircraftEngines = (net.ensode.jasperbook.dbaccess.AircraftEngines) obj; if (null == this.getId() || null == aircraftEngines.getId()) return false; else return (this.getId().equals(aircraftEngines.getId())); } } public int hashCode() { if (Integer.MIN_VALUE == this.hashCode) { if (null == this.getId()) return super.hashCode(); else { String hashStr = this.getClass().getName() + ":" + this.getId().hashCode(); this.hashCode = hashStr.hashCode(); } } return this.hashCode; } public int compareTo(Object obj) { if (obj.hashCode() > hashCode()) return 1; else if (obj.hashCode() < hashCode()) return -1; else return 0; } public String toString() { return super.toString(); } }
23.603846
125
0.636141
ed291c77dbe41061c3dfdf88c4cbd934bada5248
1,129
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.xray.metrics; import com.amazonaws.xray.entities.Segment; /** * Writes EMF formatted structured logs to stdout for testing. */ public class StdoutMetricEmitter implements MetricEmitter { private MetricFormatter formatter; public StdoutMetricEmitter() { formatter = new EMFMetricFormatter(); } @SuppressWarnings("checkstyle:Regexp") @Override public void emitMetric(final Segment segment) { String output = formatter.formatSegment(segment); System.out.println(output); } }
29.710526
76
0.725421
652ae678790c013164e60f356c3eaa79c33b270b
1,801
package com.xuegao.netty_chat_room_server.Netty进阶之路.第五章; import io.netty.bootstrap.Bootstrap; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; /** * <br/> @PackageName:com.xuegao.netty_chat_room_server.Netty进阶之路.第五章 * <br/> @ClassName:y5_1_1 * <br/> @Description: * <br/> @author:xuegao * <br/> @date:2020/12/29 21:27 */ public class y5_1_1 { static final String HOST = System.getProperty("host", "127.0.0.1"); static final int PORT = Integer.parseInt(System.getProperty("port", "18085")); @SuppressWarnings({"unchecked", "deprecation"}) public static void main(String[] args) throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group) .channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 10 * 1024 * 1024) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); // p.addLast(new LoadRunnerClientHandler()); p.addLast(new LoadRunnerWaterClientHandler()); // p.addLast(new LoadRunnerSleepClientHandler()); } }); ChannelFuture f = b.connect(HOST, PORT).sync(); f.channel().closeFuture().sync(); } finally { group.shutdownGracefully(); } } }
40.931818
89
0.592449
5d8d3a3a3f77ac417c9b5bbfab2fe5521627aa4e
1,241
package pl.timsixth.databasesapi.database.async; import pl.timsixth.databasesapi.database.ISQLDataBase; import java.sql.ResultSet; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public abstract class AbstractAsyncQuery<T extends ISQLDataBase> implements IAsyncQuery { private final T database; public AbstractAsyncQuery(T database) { this.database = database; } @Override public synchronized int update(String query) throws ExecutionException, InterruptedException { ExecutorService executorService = Executors.newCachedThreadPool(); Future<Integer> future = executorService.submit(() -> database.query(query).executeUpdate()); executorService.shutdown(); return future.get(); } @Override public synchronized ResultSet query(String query) throws ExecutionException, InterruptedException { ExecutorService executorService = Executors.newCachedThreadPool(); Future<ResultSet> future = executorService.submit(() -> database.query(query).executeQuery()); executorService.shutdown(); return future.get(); } }
34.472222
103
0.747784
031a40969f8f615b080d585276b9d0d6530a45e3
778
package io.subutai.core.metric.impl.pojo; import java.util.List; import io.subutai.core.metric.api.pojo.P2PInfo; public class P2PInfoPojo implements P2PInfo { private String rhId; private int p2pStatus; private List<String> state; @Override public String getRhId() { return rhId; } public void setRhId( final String rhId ) { this.rhId = rhId; } @Override public int getP2pStatus() { return p2pStatus; } public void setP2pStatus( final int p2pStatus ) { this.p2pStatus = p2pStatus; } @Override public List<String> getState() { return state; } public void setState( final List<String> state ) { this.state = state; } }
14.407407
52
0.602828
a6825c03eefb3a6cc2b169c3cd350aa37679e54a
210
package org.nakedobjects.example.expenses.employee; import java.util.List; public interface EmployeeRepository { List<Employee> findEmployeeByName(final String name); Employee me(); }
16.153846
58
0.719048
63011705c1d38a1946f56d7b74624a922677e7c1
5,671
/* * 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.tamaya.events; import org.apache.tamaya.Configuration; import org.apache.tamaya.ConfigurationSnapshot; import org.apache.tamaya.TypeLiteral; import org.apache.tamaya.spi.ConfigurationContext; import java.io.Serializable; import java.util.*; /** * /** * Configuration implementation that stores all current values of a given (possibly dynamic, contextual and non server * capable instance) and is fully serializable. Note that hereby only the scannable key/createValue pairs are considered. * @deprecated Use {@link org.apache.tamaya.spisupport.DefaultConfigurationSnapshot} */ @Deprecated public final class FrozenConfiguration implements Configuration, Serializable { private static final long serialVersionUID = -6373137316556444172L; /** * The properties frozen. */ private ConfigurationSnapshot snapshot; private UUID id = UUID.randomUUID(); /** * Constructor. * * @param snapshot The snapshot. */ private FrozenConfiguration(ConfigurationSnapshot snapshot) { this.snapshot = snapshot; } /** * Creates a new FrozenConfiguration instance based on the current Configuration. * * @param keys the keys, not null. * @return the frozen Configuration. * @see Configuration#current() */ public static FrozenConfiguration ofCurrent(String... keys) { return new FrozenConfiguration(Configuration.current().getSnapshot(Arrays.asList(keys))); } /** * Creates a new FrozenConfiguration instance based on a Configuration given. * * @param config the configuration to be frozen, not null. * @param keys the keys, not null. * @return the frozen Configuration. */ public static FrozenConfiguration of(Configuration config, String... keys) { return new FrozenConfiguration(config.getSnapshot(Arrays.asList(keys))); } /** * Creates a new FrozenConfiguration instance based on a Configuration given. * * @param config the configuration to be frozen, not null. * @param keys the keys, not null. * @return the frozen Configuration. */ public static FrozenConfiguration of(Configuration config, Set<String> keys) { return new FrozenConfiguration(config.getSnapshot(keys)); } /** * Get the evaluated keys of this frozen coinfiguration. * @return the keys, not null. */ public Set<String> getKeys() { return snapshot.getKeys(); } @Override public String get(String key) { return this.snapshot.get(key); } @Override public String getOrDefault(String key, String defaultValue) { return this.snapshot.getOrDefault(key, defaultValue); } @Override public <T> T getOrDefault(String key, Class<T> type, T defaultValue) { return this.snapshot.getOrDefault(key, type, defaultValue); } @SuppressWarnings("unchecked") @Override public <T> T get(String key, Class<T> type) { return snapshot.get(key, type); } @Override public <T> T get(String key, TypeLiteral<T> type) { return snapshot.get(key, type); } @Override public <T> T getOrDefault(String key, TypeLiteral<T> type, T defaultValue) { return snapshot.getOrDefault(key, type, defaultValue); } @Override public Map<String, String> getProperties() { return snapshot.getProperties(); } @Override public ConfigurationContext getContext() { return snapshot.getContext(); } @Override public ConfigurationSnapshot getSnapshot(Iterable<String> keys) { return this.snapshot.getSnapshot(keys); } /** * <p>Returns the moment in time when this frozen configuration has been created.</p> * * <p>The time is taken from {@linkplain System#currentTimeMillis()}</p> * * @see System#currentTimeMillis() * @return the moment in time when this configuration has been created */ public long getFrozenAt() { return snapshot.getTimestamp(); } /** * <p>Returns the unique id of this frozen configuration.</p> * * @return the unique id of this frozen configuration, never {@code null} */ public UUID getId() { return id; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } FrozenConfiguration that = (FrozenConfiguration) o; return Objects.equals(id, that.id); } @Override public int hashCode() { return Objects.hash(snapshot); } @Override public String toString() { return "FrozenConfiguration{" + "snapshot=" + snapshot + "," + '}'; } }
29.847368
121
0.663904
76933a9de1fbb8b8f4daf6595f674dac38b35a17
3,726
package inesc_id.pt.motivandroid.motviAPIClient.responses.WeatherResponse.response; import java.io.Serializable; /** * Weather * * (C) 2017-2020 - The Woorti app is a research (non-commercial) application that was * developed in the context of the European research project MoTiV (motivproject.eu). The * code was developed by partner INESC-ID with contributions in graphics design by partner * TIS. The Woorti app development was one of the outcomes of a Work Package of the MoTiV * project. * The Woorti app was originally intended as a tool to support data collection regarding * mobility patterns from city and country-wide campaigns and provide the data and user * management to campaign managers. * * The Woorti app development followed an agile approach taking into account ongoing * feedback of partners and testing users while continuing under development. This has * been carried out as an iterative process deploying new app versions. Along the * timeline, various previously unforeseen requirements were identified, some requirements * Were revised, there were requests for modifications, extensions, or new aspects in * functionality or interaction as found useful or interesting to campaign managers and * other project partners. Most stemmed naturally from the very usage and ongoing testing * of the Woorti app. Hence, code and data structures were successively revised in a * way not only to accommodate this but, also importantly, to maintain compatibility with * the functionality, data and data structures of previous versions of the app, as new * version roll-out was never done from scratch. * The code developed for the Woorti app is made available as open source, namely to * contribute to further research in the area of the MoTiV project, and the app also makes * use of open source components as detailed in the Woorti app license. * This project has received funding from the European Union’s Horizon 2020 research and * innovation programme under grant agreement No. 770145. * This file is part of the Woorti app referred to as SOFTWARE. */ public class Weather implements Serializable { private Integer id; private String main; private String description; private String icon; /** * No args constructor for use in serialization * */ public Weather() { } /** * * @param id * @param icon * @param description * @param main */ public Weather(Integer id, String main, String description, String icon) { super(); this.id = id; this.main = main; this.description = description; this.icon = icon; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getMain() { return main; } public void setMain(String main) { this.main = main; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(" ID: " + id + "\n"); stringBuilder.append(" Main: " + main + "\n"); stringBuilder.append(" Description: " + description + "\n"); stringBuilder.append(" Icon: "+ icon + "\n"); return stringBuilder.toString(); } }
34.5
91
0.673913
e7d6b54aece15b0cce4521bd235a03a1322cb083
356
package com.chanse.code.text_blocks; public class TextBlocks { public static void main(String[] args) { var str = """ <html> <body> <h1>Hello World</h1> </body> </html> """; System.out.println(str); } }
22.25
48
0.384831
49c700eb75939fcdc15a420083c1392f56f49a0d
8,109
package org.openended.recommender; import java.util.concurrent.ScheduledExecutorService; import javax.sql.DataSource; import org.apache.mahout.cf.taste.impl.model.jdbc.MySQLJDBCDataModel; import org.apache.mahout.cf.taste.impl.model.jdbc.ReloadFromJDBCDataModel; import org.apache.mahout.cf.taste.impl.model.jdbc.SQL92JDBCDataModel; import org.apache.mahout.cf.taste.impl.recommender.GenericItemBasedRecommender; import org.apache.mahout.cf.taste.impl.recommender.NullRescorer; import org.apache.mahout.cf.taste.impl.similarity.CachingItemSimilarity; import org.apache.mahout.cf.taste.impl.similarity.LogLikelihoodSimilarity; import org.apache.mahout.cf.taste.model.DataModel; import org.apache.mahout.cf.taste.recommender.ItemBasedRecommender; import org.apache.mahout.cf.taste.recommender.Rescorer; import org.apache.mahout.cf.taste.similarity.ItemSimilarity; import org.apache.mahout.common.LongPair; import org.openended.recommender.migration.MigrationRepository; import org.openended.recommender.migration.MigrationRepositoryImpl; import org.openended.recommender.preference.PreferenceRepository; import org.openended.recommender.preference.PreferenceRepositoryImpl; import org.openended.recommender.preference.PreferenceService; import org.openended.recommender.preference.PreferenceServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.scheduling.annotation.SchedulingConfigurer; import org.springframework.scheduling.config.IntervalTask; import org.springframework.scheduling.config.ScheduledTaskRegistrar; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; @Configuration @EnableConfigurationProperties(RecommenderProperties.class) @RequiredArgsConstructor public class RecommenderAutoConfiguration { @NonNull private final RecommenderProperties recommenderProperties; @NonNull private final DatabaseConfiguration databaseConfiguration; @Bean @ConditionalOnMissingBean public ItemSimilarity itemSimilarity() { ItemSimilarity similarity = new LogLikelihoodSimilarity(databaseConfiguration.dataModel()); return new CachingItemSimilarity(similarity, recommenderProperties.getMaxCacheSize()); } @Bean @ConditionalOnMissingBean public ItemBasedRecommender recommender() { return new GenericItemBasedRecommender(databaseConfiguration.dataModel(), itemSimilarity()); } @Bean @ConditionalOnMissingBean public Rescorer<LongPair> rescorer() { return NullRescorer.getItemItemPairInstance(); } @Bean @ConditionalOnMissingBean public RecommenderRefresher recommenderRefresher() { return new RecommenderRefresher(recommender()); } @Bean @ConditionalOnMissingBean public PreferenceService preferenceService() { return new PreferenceServiceImpl(databaseConfiguration.preferenceRepository(), databaseConfiguration.migrationRepository()); } @Bean @ConditionalOnMissingBean public RecommenderService recommenderService() { return new RecommenderServiceImpl(recommenderProperties, recommender(), rescorer(), databaseConfiguration.migrationRepository()); } @Bean @ConditionalOnProperty(value = "recommender.endpoint.enabled", havingValue = "true", matchIfMissing = true) public RecommenderEndpoint recommenderEndpoint() { return new RecommenderEndpoint(recommenderProperties, recommenderService()); } @Bean @ConditionalOnClass(HealthIndicator.class) public RecommenderHealthIndicator recommenderHealthIndicator() { return new RecommenderHealthIndicator(recommender()); } interface DatabaseConfiguration { DataModel dataModel(); MigrationRepository migrationRepository(); PreferenceRepository preferenceRepository(); } @Configuration("databaseConfiguration") @ConditionalOnClass(name = "com.mysql.jdbc.Driver") @ConditionalOnMissingClass("org.h2.Driver") @RequiredArgsConstructor static class MySQLConfiguration implements DatabaseConfiguration { @NonNull private final DataSource dataSource; @Bean @ConditionalOnMissingBean(DataModel.class) @SneakyThrows @Override public DataModel dataModel() { return new ReloadFromJDBCDataModel(new MySQLJDBCDataModel(dataSource)); } @Bean @ConditionalOnMissingBean(MigrationRepository.class) @Override public MigrationRepository migrationRepository() { return new MigrationRepositoryImpl(new NamedParameterJdbcTemplate(dataSource)) .withSqlSave("insert ignore into taste_id_migration (long_id, string_id) values (:id, :uuid)"); } @Bean @ConditionalOnMissingBean(PreferenceRepository.class) @Override public PreferenceRepository preferenceRepository() { return new PreferenceRepositoryImpl(new NamedParameterJdbcTemplate(dataSource)) .withSqlSave("insert ignore into taste_preferences (user_id, item_id, preference, timestamp) values (:userId, :itemId, :preference, :timestamp)"); } } @Configuration("databaseConfiguration") @ConditionalOnClass(name = "org.h2.Driver") @RequiredArgsConstructor static class H2Configuration implements DatabaseConfiguration { @NonNull private final DataSource dataSource; @Bean @ConditionalOnMissingBean(DataModel.class) @SneakyThrows @Override public DataModel dataModel() { return new ReloadFromJDBCDataModel(new SQL92JDBCDataModel(dataSource)); } @Bean @ConditionalOnMissingBean(MigrationRepository.class) @Override public MigrationRepository migrationRepository() { return new MigrationRepositoryImpl(new NamedParameterJdbcTemplate(dataSource)) .withSqlSave("merge into taste_id_migration (long_id, string_id) key(long_id) values (:id, :uuid)"); } @Bean @ConditionalOnMissingBean(PreferenceRepository.class) @Override public PreferenceRepository preferenceRepository() { return new PreferenceRepositoryImpl(new NamedParameterJdbcTemplate(dataSource)) .withSqlSave("merge into taste_preferences (user_id, item_id, preference, timestamp) key(user_id, item_id) values (:userId, :itemId, :preference, :timestamp)"); } } @Configuration @RequiredArgsConstructor static class RefresherConfiguration implements SchedulingConfigurer { @NonNull private final RecommenderProperties recommenderProperties; @NonNull private final RecommenderRefresher recommenderRefresher; @Autowired(required = false) private ScheduledExecutorService scheduledExecutorService; @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { if (scheduledExecutorService != null) { taskRegistrar.setScheduler(scheduledExecutorService); taskRegistrar.addFixedRateTask(refreshTask()); } } private IntervalTask refreshTask() { long interval = recommenderProperties.getRefresherRate() * 1_000L; return new IntervalTask(recommenderRefresher::refresh, interval, interval); } } }
39.556098
180
0.755457
fb537c1124a5a8c2d038f515cec0e450a911bd0f
879
package org.jpoi.qianjinExcel; /** * Created by wangqianjin on 2017/8/4. */ public class fncodeuserdevtest { public String getFunctionCode() { return functionCode; } public void setFunctionCode(String functionCode) { this.functionCode = functionCode; } public String getUsercode() { return usercode; } public void setUsercode(String usercode) { this.usercode = usercode; } public String getDever() { return dever; } public void setDever(String dever) { this.dever = dever; } public String getTester() { return tester; } public void setTester(String tester) { this.tester = tester; } private String functionCode; private String usercode; private String dever; private String tester; public fncodeuserdevtest() { } }
18.702128
54
0.625711
4bb096b6cd3d3f819fa2945a309c916e0a097912
2,607
package de.metanome.input.ind; import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; import de.metanome.algorithm_integration.configuration.ConfigurationRequirement; import de.metanome.algorithm_integration.configuration.ConfigurationRequirementListBox; import de.metanome.algorithm_integration.configuration.ConfigurationRequirementString; import de.metanome.algorithm_integration.input.RelationalInputGenerator; import de.metanome.algorithm_integration.input.TableInputGenerator; import java.util.List; public class InclusionDependencyInputConfigurationRequirements { private static final String ALGORITHM = "ind-input-algorithm"; private static final String CONFIGURATION = "ind-input-configuration"; public static List<ConfigurationRequirement<?>> indInput() { final List<String> names = getAvailableAlgorithmNames(); final ConfigurationRequirementListBox algorithms = new ConfigurationRequirementListBox( ALGORITHM, names, 1, 1); algorithms.setDefaultValues(new String[]{names.get(0)}); final ConfigurationRequirementString configuration = new ConfigurationRequirementString( CONFIGURATION, 1); configuration.setRequired(false); return asList(algorithms, configuration); } public static List<String> getAvailableAlgorithmNames() { return getAvailableAlgorithms().stream().map(AlgorithmType::name).collect(toList()); } public static List<AlgorithmType> getAvailableAlgorithms() { return asList(AlgorithmType.values()); } public static boolean acceptListBox(final String identifier, final String[] selectedValues, final InclusionDependencyParameters parameters) { if (identifier.equals(ALGORITHM)) { final AlgorithmType algorithm = AlgorithmType.valueOf(selectedValues[0]); parameters.setAlgorithmType(algorithm); return true; } return false; } public static boolean acceptString(final String identifier, final String[] values, final InclusionDependencyParameters parameters) { if (identifier.equals(CONFIGURATION)) { parameters.setConfigurationString(values[0]); return true; } return false; } public static void acceptTableInputGenerator(final TableInputGenerator[] values, final InclusionDependencyParameters parameters) { parameters.setTableInputGenerators(asList(values)); } public static void acceptRelationalInputGenerators(final RelationalInputGenerator[] values, final InclusionDependencyParameters parameters) { parameters.setRelationalInputGenerators(asList(values)); } }
34.76
93
0.784043
66910b81ebf1f650f0bed9f3c10415fca6e3ea9a
4,998
package graphql.language; import graphql.PublicApi; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Function; import java.util.stream.Collectors; import static graphql.Assert.assertNotEmpty; import static graphql.Assert.assertTrue; import static graphql.language.NodeChildrenContainer.newNodeChildrenContainer; import static java.util.stream.Collectors.groupingBy; import static java.util.stream.Collectors.mapping; import static java.util.stream.Collectors.toList; /** * A collection of {@link AstZipper} sharing all the same root node. * It is used to track multiple changes at once, while {@link AstZipper} focus on one Node. */ @PublicApi public class AstMultiZipper { private final Node commonRoot; private final List<AstZipper> zippers; public AstMultiZipper(Node commonRoot, List<AstZipper> zippers) { this.commonRoot = commonRoot; this.zippers = new ArrayList<>(zippers); } public Node toRootNode() { if (zippers.size() == 0) { return commonRoot; } List<AstZipper> curZippers = new ArrayList<>(zippers); while (curZippers.size() > 1) { List<AstZipper> deepestZippers = getDeepestZippers(curZippers); Map<Node, List<AstZipper>> sameParent = zipperWithSameParent(deepestZippers); List<AstZipper> newZippers = new ArrayList<>(); for (Map.Entry<Node, List<AstZipper>> entry : sameParent.entrySet()) { AstZipper newZipper = moveUp(entry.getKey(), entry.getValue()); Optional<AstZipper> zipperToBeReplaced = curZippers.stream().filter(zipper -> zipper.getCurNode() == entry.getKey()).findFirst(); zipperToBeReplaced.ifPresent(curZippers::remove); newZippers.add(newZipper); } curZippers.removeAll(deepestZippers); curZippers.addAll(newZippers); } assertTrue(curZippers.size() == 1, "unexpected state: all zippers must share the same root node"); return curZippers.get(0).toRoot(); } public Node getCommonRoot() { return commonRoot; } public List<AstZipper> getZippers() { return new ArrayList<>(zippers); } public AstMultiZipper withReplacedZippers(List<AstZipper> zippers) { return new AstMultiZipper(commonRoot, zippers); } public AstMultiZipper withNewZipper(AstZipper newZipper) { List<AstZipper> newZippers = getZippers(); newZippers.add(newZipper); return new AstMultiZipper(commonRoot, newZippers); } public AstMultiZipper withReplacedZipper(AstZipper oldZipper, AstZipper newZipper) { int index = zippers.indexOf(oldZipper); assertTrue(index >= 0, "oldZipper not found"); List<AstZipper> newZippers = new ArrayList<>(zippers); newZippers.set(index, newZipper); return new AstMultiZipper(commonRoot, newZippers); } private List<AstZipper> getDeepestZippers(List<AstZipper> zippers) { Map<Integer, List<AstZipper>> grouped = zippers .stream() .collect(groupingBy(astZipper -> astZipper.getBreadcrumbs().size(), LinkedHashMap::new, mapping(Function.identity(), toList()))); Integer maxLevel = Collections.max(grouped.keySet()); return grouped.get(maxLevel); } private AstZipper moveUp(Node parent, List<AstZipper> sameParent) { assertNotEmpty(sameParent, "expected at least one zipper"); Map<String, List<Node>> childrenMap = parent.getNamedChildren().getChildren(); for (AstZipper zipper : sameParent) { NodeLocation location = zipper.getBreadcrumbs().get(0).getLocation(); childrenMap.computeIfAbsent(location.getName(), (key) -> new ArrayList<>()); List<Node> childrenList = childrenMap.get(location.getName()); if (childrenList.size() > location.getIndex()) { childrenList.set(location.getIndex(), zipper.getCurNode()); } else { childrenList.add(zipper.getCurNode()); } } Node newNode = parent.withNewChildren(newNodeChildrenContainer(childrenMap).build()); List<AstBreadcrumb> newBreadcrumbs = sameParent.get(0).getBreadcrumbs().subList(1, sameParent.get(0).getBreadcrumbs().size()); return new AstZipper(newNode, newBreadcrumbs); } private Map<Node, List<AstZipper>> zipperWithSameParent(List<AstZipper> zippers) { return zippers.stream().collect(groupingBy(AstZipper::getParent, LinkedHashMap::new, mapping(Function.identity(), Collectors.toList()))); } @Override public String toString() { return "AstMultiZipper{" + "commonRoot=" + commonRoot.getClass() + ", zippersCount=" + zippers.size() + '}'; } }
39.046875
145
0.665666
99d220870bfab20cdf552ff3f544fe15690bc947
1,344
package org.onlab.jdvue; import org.junit.Test; import org.onlab.jdvue.Catalog; import org.onlab.jdvue.JavaPackage; import org.onlab.jdvue.JavaSource; import java.io.IOException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; /** * Unit test for the source catalog. * * @author Thomas Vachuska */ public class CatalogTest { @Test public void basics() throws IOException { Catalog cat = new Catalog(); cat.load("src/test/resources/catalog.db"); cat.analyze(); assertEquals("incorrect package count", 12, cat.getPackages().size()); assertEquals("incorrect source count", 14, cat.getSources().size()); JavaPackage pkg = cat.getPackage("k"); assertNotNull("package should be found", pkg); JavaSource src = cat.getSource("k.K"); assertNotNull("source should be found", src); assertEquals("incorrect package source count", 1, pkg.getSources().size()); assertEquals("incorrect package dependency count", 1, pkg.getDependencies().size()); assertEquals("incorrect package cycle count", 3, cat.getPackageCycles(pkg).size()); assertEquals("incorrect segment count", 11, cat.getCycleSegments().size()); assertEquals("incorrect cycle count", 5, cat.getCycles().size()); } }
30.545455
92
0.680804
215e1d5624207a9183ea1a1862308d9edb3d18d6
508
package com.juc.lock.volatiled; /** * @author: @zyz */ public class VolatileDemo { static volatile int conunt=0; public static void main (String[] args) throws InterruptedException { Thread thread1 = new Thread (() -> { for (int i = 0 ; i < 10000 ; i++) { conunt++; } }); Thread thread = new Thread (() -> { for (int i = 0 ; i < 10000 ; i++) { conunt++; } }); thread.start (); thread1.start (); thread.join (); thread1.join (); System.out.println (conunt); } }
18.814815
70
0.568898
70d5f62b9fe1a2a94bc024e121ff1c2e0e796692
1,864
package org.gbif.nub.lookup; import org.gbif.api.model.checklistbank.NameUsageMatch; import org.gbif.api.model.common.LinneanClassification; import org.gbif.api.service.checklistbank.NameUsageMatchingService; import org.gbif.checklistbank.service.mybatis.guice.ChecklistBankServiceMyBatisModule; import org.gbif.utils.file.properties.PropertiesUtil; import java.io.IOException; import java.util.Properties; import com.google.inject.Guice; import com.google.inject.Injector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class NubMatchingServiceTestManual { private static final Logger LOG = LoggerFactory.getLogger(NubMatchingServiceTestManual.class); private final NameUsageMatchingService matcher; public NubMatchingServiceTestManual() throws IOException { LOG.info("Load clb properties"); Properties properties = PropertiesUtil.loadProperties("checklistbank.properties"); LOG.info("Create guice injector"); Injector inj = Guice.createInjector(new ChecklistBankServiceMyBatisModule(properties), new NubMatchingModule()); LOG.info("Create matching service"); matcher = inj.getInstance(NameUsageMatchingService.class); LOG.info("Nub Matching setup complete"); } public void testMatching() throws IOException { LinneanClassification cl = new NameUsageMatch(); // test identical matcher.match("Animalia", null, cl, true, true); matcher.match("Animals", null, cl, true, true); matcher.match("Insects", null, cl, true, true); cl.setKingdom("Animalia"); matcher.match("Puma concolor", null, cl, true, true); cl.setKingdom("Plantae"); matcher.match("Puma concolor", null, cl, true, true); } public static void main (String[] args) throws IOException { NubMatchingServiceTestManual test = new NubMatchingServiceTestManual(); test.testMatching(); } }
33.285714
116
0.765021
9e286ed77022c925cceb31cae6b6b0e2e46133bc
470
/* * Java * * Copyright 2019 Andy Poudret. All rights reserved. */ package com.choupom.forgik.rulebook; import com.choupom.forgik.rule.Rule; public class Rulebook { private final String name; private final Rule[] rules; public Rulebook(String name, Rule[] rules) { this.name = name; this.rules = rules.clone(); } public String getName() { return this.name; } public Rule[] getRules() { return this.rules.clone(); } }
16.785714
53
0.644681
42dbdcf60bb521232a8dfc960ac76d64b04180d6
786
package br.com.brazilcode.cb.purchase.exception; import br.com.brazilcode.cb.purchase.service.PriceQuotationService; /** * Classe responsável por configurar uma exceção personalizada para a classe {@link PriceQuotationService}. * * @author Brazil Code - Gabriel Guarido * @since 8 de mar de 2020 17:48:52 * @version 1.0 */ public class PriceQuotationServiceException extends Exception { private static final long serialVersionUID = -1535937550574563389L; public PriceQuotationServiceException() { super(); } public PriceQuotationServiceException(String message) { super(message); } public PriceQuotationServiceException(String message, Throwable cause) { super(message, cause); } public PriceQuotationServiceException(Throwable cause) { super(cause); } }
23.818182
107
0.773537
3c4e114d2811bc391bf9e4e1f42f10d5024eba80
423
class Parent { int a = 0; public Parent(int a) { this.a = a; } // public Parent() // { // this.a = 0; // } } class Child extends Parent { public Child() { } public int getA() { return this.a; } } public class Test { public static void main (String [] args) { Child c = new Child(); System.out.println(c.getA()); } }
14.1
44
0.458629
2073ea2f072c469150c311d82423b40c8086ae84
1,561
package org.kiwiproject.security; import lombok.Getter; /** * Protocols thar can be used when calling {@link javax.net.ssl.SSLContext#getInstance(String)}. * * @implNote These are from the Java 11 documentation, specifically from * "Java Security Standard Algorithm Names" except protocols that are no longer supported such as SSL (any version). */ public enum SSLContextProtocol { /** * Supports some version of TLS; may support other SSL/TLS versions */ TLS("TLS"), /** * Supports RFC 2246; TLS version 1.0; may support other SSL/TLS versions */ TLS_1("TLSv1"), /** * Supports RFC 4346; TLS version 1.1; may support other SSL/TLS versions */ TLS_1_1("TLSv1.1."), /** * Supports RFC 5246; TLS version 1.2; may support other SSL/TLS versions */ TLS_1_2("TLSv1.2"), /** * Supports RFC 8446; TLS version 1.3; may support other SSL/TLS versions */ TLS_1_3("TLSv1.3"), /** * Supports the default provider-dependent versions of DTLS versions */ DTLS("DTLS"), /** * Supports RFC 4347; DTLS version 1.0; may support other DTLS versions */ DTLS_1_0("DTLSv1.0"), /** * Supports RFC 6347; DTLS version 1.2; may support other DTLS versions */ DTLS_1_2("DTLSv1.2"); /** * The protocol name that can be directly supplied to {@link javax.net.ssl.SSLContext#getInstance(String)}. */ @Getter public final String value; SSLContextProtocol(String value) { this.value = value; } }
24.777778
116
0.63549
7fba9928db1e736e61e2f161c850e4fbdaed89d1
5,069
package com.donations.controllers; import com.donations.model.About; import com.donations.model.Blog; import com.donations.model.Donation; import com.donations.services.AboutService; import com.donations.services.BlogService; import com.donations.services.DonationService; import com.donations.services.LoginService; import com.donations.services.SessionService; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; /** * * @author user */ @Controller public class MobileController { @RequestMapping(value = "/mobilehome", method = RequestMethod.GET) public String getAllDonationsMob(ModelMap model, DonationService donationService) { List<Donation> allDonationsMob = donationService.getNewDonations(); model.addAttribute("allDonationsMob", allDonationsMob); return "mobilehome"; } @RequestMapping(method = RequestMethod.GET, value = "/mobiledetail") public String mobiledetail(SessionService sessionService, LoginService loginService, HttpServletRequest request, ModelMap model, DonationService donationService) { if (request.getParameterNames().hasMoreElements()) { Donation donation = new Donation(); String theid = request.getParameter("donationId"); donation.setId(Integer.parseInt(theid)); Donation currentDonation = donationService.findDonationbyId(Integer.parseInt(theid)); model.addAttribute("currentTitle", currentDonation.getTitle()); model.addAttribute("currentDonationUrl", currentDonation.getDonationUrl()); model.addAttribute("currentDescription", currentDonation.getDescription()); model.addAttribute("currentImageSource", currentDonation.getImageSource()); model.addAttribute("currentStartDate", currentDonation.getStartDate()); model.addAttribute("currentEndDate", currentDonation.getEndDate()); model.addAttribute("currentPriority", currentDonation.getPriority()); model.addAttribute("currentUserId", currentDonation.getUser().getId()); model.addAttribute("currentCategoryId", currentDonation.getCategory().getId()); model.addAttribute("currentTypeId", currentDonation.getType().getId()); model.addAttribute("currentDonationPhone", currentDonation.getPhones().isEmpty() ? "No Phone" : currentDonation.getPhones().get(currentDonation.getPhones().size() - 1).getNumber()); model.addAttribute("currentDonationAccount", currentDonation.getAccounts().isEmpty() ? "No Account" : currentDonation.getAccounts().get(currentDonation.getAccounts().size() - 1).getNumber().toString()); return "mobiledetail"; } return "mobiledetail"; } @RequestMapping(value = "/mobilearchive", method = RequestMethod.GET) public String getAllDonationsMobArchive(ModelMap model, DonationService donationService) { List<Donation> allDonationsMob = donationService.getAllOldDonations(); model.addAttribute("allDonationsMobOld", allDonationsMob); return "mobilearchive"; } @RequestMapping(value = "/mobileaboutus") public String Aboutus(ModelMap model, AboutService aboutService) { List<About> abouts = aboutService.getAbout(); model.addAttribute("abouts", abouts); return "mobileaboutus"; } @RequestMapping(method = RequestMethod.GET, value = "/mobileblog") public String blog(BlogService blogService, ModelMap model) { List<Blog> allBlogs = blogService.getOrderedBlogsByPostDate(); model.addAttribute("allBlogs", allBlogs); return "mobileblog"; } @RequestMapping(method = RequestMethod.GET, value = "/mobileblogdetail") public String blogDetail(@RequestParam(value = "blogId", required = false) String blogId, SessionService sessionService, LoginService loginService, HttpServletRequest request, BlogService blogService, ModelMap model, DonationService donationService) { if (request.getParameterNames().hasMoreElements()) { String theid = request.getParameter("blogId"); Blog detailBlog = blogService.findBlogById(Integer.parseInt(blogId)); model.addAttribute("blogTitle", detailBlog.getTitle()); model.addAttribute("blogPostDate", detailBlog.getPostDate()); model.addAttribute("blogShortDescription", detailBlog.getShortDescription()); model.addAttribute("blogLongDescription", detailBlog.getLongDescription()); model.addAttribute("blogUserUsername", detailBlog.getUser().getUsername()); return "mobileblogdetail"; } else { return "mobileblogdetail"; } } }
46.081818
255
0.721444
3251aa5845679c429af3c2c48ac70820a31fabd2
1,773
package mono.com.google.android.exoplayer2.drm; public class ExoMediaDrm_OnKeyStatusChangeListenerImplementor extends java.lang.Object implements mono.android.IGCUserPeer, com.google.android.exoplayer2.drm.ExoMediaDrm.OnKeyStatusChangeListener { /** @hide */ public static final String __md_methods; static { __md_methods = "n_onKeyStatusChange:(Lcom/google/android/exoplayer2/drm/ExoMediaDrm;[BLjava/util/List;Z)V:GetOnKeyStatusChange_Lcom_google_android_exoplayer2_drm_ExoMediaDrm_arrayBLjava_util_List_ZHandler:Com.Google.Android.Exoplayer2.Drm.IExoMediaDrmOnKeyStatusChangeListenerInvoker, ExoPlayer.Core\n" + ""; mono.android.Runtime.register ("Com.Google.Android.Exoplayer2.Drm.IExoMediaDrmOnKeyStatusChangeListenerImplementor, ExoPlayer.Core", ExoMediaDrm_OnKeyStatusChangeListenerImplementor.class, __md_methods); } public ExoMediaDrm_OnKeyStatusChangeListenerImplementor () { super (); if (getClass () == ExoMediaDrm_OnKeyStatusChangeListenerImplementor.class) mono.android.TypeManager.Activate ("Com.Google.Android.Exoplayer2.Drm.IExoMediaDrmOnKeyStatusChangeListenerImplementor, ExoPlayer.Core", "", this, new java.lang.Object[] { }); } public void onKeyStatusChange (com.google.android.exoplayer2.drm.ExoMediaDrm p0, byte[] p1, java.util.List p2, boolean p3) { n_onKeyStatusChange (p0, p1, p2, p3); } private native void n_onKeyStatusChange (com.google.android.exoplayer2.drm.ExoMediaDrm p0, byte[] p1, java.util.List p2, boolean p3); private java.util.ArrayList refList; public void monodroidAddReference (java.lang.Object obj) { if (refList == null) refList = new java.util.ArrayList (); refList.add (obj); } public void monodroidClearReferences () { if (refList != null) refList.clear (); } }
36.183673
292
0.79075
7f8f831081f5477be1fc335067710b382b7eb811
16,138
/* * JBoss, Home of Professional Open Source. * Copyright 2014, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.domain.controller.operations; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.INCLUDES; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.LOCAL_DESTINATION_OUTBOUND_SOCKET_BINDING; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PROFILE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.REMOTE_DESTINATION_OUTBOUND_SOCKET_BINDING; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SOCKET_BINDING; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SOCKET_BINDING_GROUP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Set; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationContext.AttachmentKey; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.OperationStepHandler; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.registry.Resource; import org.jboss.as.controller.registry.Resource.ResourceEntry; import org.jboss.as.host.controller.logging.HostControllerLogger; import org.jboss.dmr.ModelNode; /** * Handler validating that "including" resources don't involve cycles * and that including resources don't involve children that override the included resources. * * @author Emanuel Muckenhuber * @author Kabir Khan */ public class DomainModelIncludesValidator implements OperationStepHandler { private static DomainModelIncludesValidator INSTANCE = new DomainModelIncludesValidator(); private static final AttachmentKey<DomainModelIncludesValidator> KEY = AttachmentKey.create(DomainModelIncludesValidator.class); private DomainModelIncludesValidator() { } public static void addValidationStep(OperationContext context, ModelNode operation) { assert !context.getProcessType().isServer() : "Not a host controller"; if (!context.isBooting()) { // This does not need to get executed on boot the domain controller service does that once booted // by calling validateAtBoot(). Otherwise we get issues with the testsuite, which only partially sets up the model if (context.attachIfAbsent(KEY, DomainModelIncludesValidator.INSTANCE) == null) { context.addStep(DomainModelIncludesValidator.INSTANCE, OperationContext.Stage.MODEL); } } } public static void validateAtBoot(OperationContext context, ModelNode operation) { assert !context.getProcessType().isServer() : "Not a host controller"; assert context.isBooting() : "Should only be called at boot"; assert operation.require(OP).asString().equals("validate"); //Should only be called by the domain controller service //Only validate once if (context.attachIfAbsent(KEY, DomainModelIncludesValidator.INSTANCE) == null) { context.addStep(DomainModelIncludesValidator.INSTANCE, OperationContext.Stage.MODEL); } } @Override public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException { // Validate validate(context); } public void validate(final OperationContext context) throws OperationFailedException { final Resource domain = context.readResourceFromRoot(PathAddress.EMPTY_ADDRESS); final Set<String> missingProfiles = new HashSet<>(); final Set<String> missingSocketBindingGroups = new HashSet<>(); checkProfileIncludes(domain, missingProfiles); checkSocketBindingGroupIncludes(domain, missingSocketBindingGroups); } private Set<String> checkProfileIncludes(Resource domain, Set<String> missingProfiles) throws OperationFailedException { ProfileIncludeValidator validator = new ProfileIncludeValidator(); for (ResourceEntry entry : domain.getChildren(PROFILE)) { validator.processResource(entry); } validator.validate(missingProfiles); return validator.resourceIncludes.keySet(); } private Set<String> checkSocketBindingGroupIncludes(Resource domain, Set<String> missingSocketBindingGroups) throws OperationFailedException { SocketBindingGroupIncludeValidator validator = new SocketBindingGroupIncludeValidator(); for (ResourceEntry entry : domain.getChildren(SOCKET_BINDING_GROUP)) { validator.processResource(entry); } validator.validate(missingSocketBindingGroups); return new HashSet<>(validator.resourceIncludes.keySet()); } private abstract static class AbstractIncludeValidator { protected final Set<String> seen = new HashSet<>(); protected final Set<String> onStack = new HashSet<>(); protected final Map<String, String> linkTo = new HashMap<>(); protected final Map<String, Set<String>> resourceIncludes = new HashMap<>(); protected final Map<String, Set<String>> resourceChildren = new HashMap<>(); protected final List<String> post = new ArrayList<>(); void processResource(ResourceEntry resourceEntry) throws OperationFailedException{ ModelNode model = resourceEntry.getModel(); final Set<String> includes; if (model.hasDefined(INCLUDES)) { includes = new HashSet<>(); for (ModelNode include : model.get(INCLUDES).asList()) { includes.add(include.asString()); } } else { includes = Collections.emptySet(); } resourceIncludes.put(resourceEntry.getName(), includes); } void validate(Set<String> missingEntries) throws OperationFailedException { //Look for cycles for (String resourceName : resourceIncludes.keySet()) { if (!seen.contains(resourceName)) { dfsForMissingOrCyclicIncludes(resourceName, missingEntries); } } if (missingEntries.size() > 0) { //We are missing some entries, don't continue with the validation since it has failed return; } //Check that children are not overridden, by traversing them in the order child->parent //using the reverse post-order of the dfs seen.clear(); for (ListIterator<String> it = post.listIterator(post.size()) ; it.hasPrevious() ; ) { String resourceName = it.previous(); if (seen.contains(resourceName)) { continue; } List<String> stack = new ArrayList<>(); Map<String, List<String>> reachableChildren = new HashMap<>(); validateChildrenNotOverridden(resourceName, reachableChildren, stack); } } void validateChildrenNotOverridden(String resourceName, Map<String, List<String>> reachableChildren, List<String> stack) throws OperationFailedException { stack.add(resourceName); try { seen.add(resourceName); Set<String> includes = resourceIncludes.get(resourceName); Set<String> children = resourceChildren.get(resourceName); if (includes.size() == 0 && children.size() == 0) { return; } for (String child : resourceChildren.get(resourceName)) { List<String> existingChildParentStack = reachableChildren.get(child); if (existingChildParentStack != null) { logError(resourceName, stack, child, existingChildParentStack); } reachableChildren.put(child, new ArrayList<>(stack)); } for (String include : includes) { validateChildrenNotOverridden(include, reachableChildren, stack); } } finally { stack.remove(stack.size() - 1); } } private void logError(String resourceName, List<String> stack, String child, List<String> existingChildParentStack) throws OperationFailedException { //Now figure out if this is a direct override, or no override but including two parents //with the same child for (ListIterator<String> it = stack.listIterator(stack.size()) ; it.hasPrevious() ; ) { String commonParent = it.previous(); if (existingChildParentStack.contains(commonParent)) { if (!getLastElement(existingChildParentStack).equals(commonParent)) { //This is not an override but 'commonParent' includes two parents with the same child throw twoParentsWithSameChild(commonParent, getLastElement(stack), getLastElement(existingChildParentStack), child); } } } //It is a direct override //Alternatively, something went wrong when trying to determine the cause, in which case this message //will not be 100% correct, but it is better to get an error than not. throw attemptingToOverride(getLastElement(existingChildParentStack), child, resourceName); } private String getLastElement(List<String> list) { return list.get(list.size() - 1); } protected abstract OperationFailedException twoParentsWithSameChild(String commonParent, String include1, String include2, String child); void dfsForMissingOrCyclicIncludes(String resourceName, Set<String> missingEntries) throws OperationFailedException { onStack.add(resourceName); try { seen.add(resourceName); Set<String> includes = resourceIncludes.get(resourceName); if (includes == null) { missingEntries.add(resourceName); return; } for (String include : includes) { if (!seen.contains(include)) { linkTo.put(include, resourceName); dfsForMissingOrCyclicIncludes(include, missingEntries); } else if (onStack.contains(include)) { throw involvedInACycle(include); } } } finally { onStack.remove(resourceName); } post.add(resourceName); } abstract OperationFailedException attemptingToOverride(String parentOfExistingChild, String child, String resourceName); abstract OperationFailedException involvedInACycle(String profile); } private static class ProfileIncludeValidator extends AbstractIncludeValidator { void processResource(ResourceEntry profileEntry) throws OperationFailedException { super.processResource(profileEntry); final Set<String> subsystems; if (profileEntry.hasChildren(SUBSYSTEM)) { subsystems = new HashSet<>(); subsystems.addAll(profileEntry.getChildrenNames(SUBSYSTEM)); } else { subsystems = Collections.emptySet(); } resourceChildren.put(profileEntry.getName(), subsystems); } @Override OperationFailedException attemptingToOverride(String parentOfExistingChild, String child, String resourceName) { return HostControllerLogger.ROOT_LOGGER.profileAttemptingToOverrideSubsystem(parentOfExistingChild, child, resourceName); } @Override OperationFailedException involvedInACycle(String include) { return HostControllerLogger.ROOT_LOGGER.profileInvolvedInACycle(include); } @Override protected OperationFailedException twoParentsWithSameChild(String commonParent, String include1, String include2, String child) { return HostControllerLogger.ROOT_LOGGER.profileIncludesSameSubsystem(commonParent, include1, include2, child); } } private static class SocketBindingGroupIncludeValidator extends AbstractIncludeValidator { void processResource(ResourceEntry groupEntry) throws OperationFailedException{ //Remote and local outbound socket binding names must be unique or we get a DuplicateServiceException //Tighten this up to also make the 'normal' ones unique, to make the validation a bit easier. super.processResource(groupEntry); final Set<String> bindings; if (groupEntry.hasChildren(SOCKET_BINDING) || groupEntry.hasChildren(LOCAL_DESTINATION_OUTBOUND_SOCKET_BINDING) || groupEntry.hasChildren(REMOTE_DESTINATION_OUTBOUND_SOCKET_BINDING)) { bindings = new HashSet<>(); addBindings(groupEntry, bindings, SOCKET_BINDING); addBindings(groupEntry, bindings, LOCAL_DESTINATION_OUTBOUND_SOCKET_BINDING); addBindings(groupEntry, bindings, REMOTE_DESTINATION_OUTBOUND_SOCKET_BINDING); bindings.addAll(groupEntry.getChildrenNames(SUBSYSTEM)); } else { bindings = Collections.emptySet(); } resourceChildren.put(groupEntry.getName(), bindings); } private void addBindings(ResourceEntry groupEntry, Set<String> bindings, String bindingType) throws OperationFailedException{ if (groupEntry.hasChildren(bindingType)) { for (String name : groupEntry.getChildrenNames(bindingType)) { if (!bindings.add(name)) { throw HostControllerLogger.ROOT_LOGGER.bindingNameNotUnique(name, groupEntry.getName()); } } } } @Override OperationFailedException attemptingToOverride(String parentOfExistingChild, String child, String resourceName) { return HostControllerLogger.ROOT_LOGGER.socketBindingGroupAttemptingToOverrideSocketBinding(parentOfExistingChild, child, resourceName); } @Override OperationFailedException involvedInACycle(String include) { return HostControllerLogger.ROOT_LOGGER.socketBindingGroupInvolvedInACycle(include); } @Override protected OperationFailedException twoParentsWithSameChild(String commonParent, String include1, String include2, String child) { return HostControllerLogger.ROOT_LOGGER.socketBindingGroupIncludesSameSocketBinding(commonParent, include1, include2, child); } } }
48.755287
157
0.673999
dae6852db80a3601461b47cad9832170ba998480
372
package pl.Wojtek.util; /** * */ public class State { private String name; public State(String s) { this.name = s; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "State(" + this.getName() + ")"; } }
14.88
47
0.52957
8bd4bf97f72aece11c237b8253785eedb4fe97ea
2,680
/** * Copyright 2014 Netflix, Inc. * * 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 rx.operators; import rx.Observable; import rx.Subscriber; import rx.Subscription; import rx.android.observables.Assertions; import rx.android.subscriptions.AndroidSubscriptions; import rx.functions.Action0; import android.text.Editable; import android.text.TextWatcher; import android.widget.EditText; /** * @deprecated Use {@link rx.operators.OperatorTextViewInput} instead. */ @Deprecated public class OperatorEditTextInput implements Observable.OnSubscribe<String> { private final EditText input; private final boolean emitInitialValue; public OperatorEditTextInput(final EditText input, final boolean emitInitialValue) { this.input = input; this.emitInitialValue = emitInitialValue; } @Override public void call(final Subscriber<? super String> observer) { Assertions.assertUiThread(); final TextWatcher watcher = new SimpleTextWatcher() { @Override public void afterTextChanged(final Editable editable) { observer.onNext(editable.toString()); } }; final Subscription subscription = AndroidSubscriptions.unsubscribeInUiThread(new Action0() { @Override public void call() { input.removeTextChangedListener(watcher); } }); if (emitInitialValue) { observer.onNext(input.getEditableText().toString()); } input.addTextChangedListener(watcher); observer.add(subscription); } private static class SimpleTextWatcher implements TextWatcher { @Override public void beforeTextChanged(final CharSequence sequence, final int start, final int count, final int after) { // nothing to do } @Override public void onTextChanged(final CharSequence sequence, final int start, final int before, final int count) { // nothing to do } @Override public void afterTextChanged(final Editable editable) { // nothing to do } } }
31.904762
119
0.679851
3d89e851a91220f68640ae7bc8199c7d0f31b4e8
952
package com.educational.platform.course.enrollments.course; import com.educational.platform.common.domain.AggregateRoot; import com.educational.platform.course.enrollments.course.create.CreateCourseCommand; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import java.util.UUID; /** * Represents course domain model. */ @Entity(name = "enroll_course") public class EnrollCourse implements AggregateRoot { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private UUID uuid; // for JPA private EnrollCourse() { } public EnrollCourse(CreateCourseCommand createCourseCommand) { this.uuid = createCourseCommand.getUuid(); } public Integer getId() { return id; } public UUID toReference() { return uuid; } }
23.219512
86
0.701681
854573628f1cc1e1c5d296a009cfe3e573684b4d
12,813
package com.cloudmusic.controller.cloudMusic; import com.cloudmusic.api.CloudMusicApiUrl; import com.cloudmusic.request.cloudMusic.CreateWebRequest; import com.cloudmusic.result.Result; import org.json.JSONObject; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import java.util.HashMap; import java.util.Map; /** * 接口功能:需要登陆才能操作的API接口 * Created by xuzijia * 2018/5/23 21:15 * 该接口的所有API需要登陆后才能操作 */ @RestController public class UserController { /** * 获取每天推荐歌曲(需要登陆) * * @param request * @return 每日推荐歌曲 */ @RequestMapping("/user/recommend") public String getUserRecommend(HttpServletRequest request) { return CreateWebRequest.createWebPostRequest(CloudMusicApiUrl.userRecommendUrl, new HashMap<>(), CreateWebRequest.getCookie(request)); } /** * 添加或者移除歌曲到喜欢的音乐歌单(需要登陆) * @param id *歌曲id 必传 * @param action 操作类型(true:添加 false:移除 默认值:true) * @param request * @return 是否操作成功 */ @RequestMapping("/song/like") public String getUserRecommend(String id,String action,HttpServletRequest request) { if (id == null || id.trim().equals("")) { return new JSONObject(new Result(0, "缺少必填参数")).toString(); } action=action==null? "true":action; Map<String, Object> data = new HashMap<>(); data.put("trackId", id); data.put("like", action); String url = CloudMusicApiUrl.likeSongUrl.replace("{alg}","itembased").replace("{trackId}",id).replace("{time}","25"); return CreateWebRequest.createWebPostRequest(url, data, CreateWebRequest.getCookie(request)); } /** * 获取每天推荐歌单(需要登陆) * * @param request * @return 每日推荐歌单 */ @RequestMapping("/playlist/recommend") public String getPlaylistRecommend(HttpServletRequest request) { return CreateWebRequest.createWebPostRequest(CloudMusicApiUrl.playlistRecommendUrl, new HashMap<>(), CreateWebRequest.getCookie(request)); } /** * 获取用户私人FM(需要登陆) * * @param request * @return 上一首 当前 下一首 三首歌曲信息 */ @RequestMapping("/user/personal_fm") public String getUserPersonalFm(HttpServletRequest request) { return CreateWebRequest.createWebPostRequest(CloudMusicApiUrl.userPersonalFmUrl, new HashMap<>(), CreateWebRequest.getCookie(request)); } /** * 把音乐从私人 FM 中移除至垃圾桶(需要登陆) * * @param id *歌曲id 必传 * @param request * @return 是否移除成功 */ @RequestMapping("/user/fm_trash") public String getUserPersonalFm(String id,HttpServletRequest request) { if (id == null || id.trim().equals("")) { return new JSONObject(new Result(0, "缺少必填参数")).toString(); } Map<String, Object> data = new HashMap<>(); data.put("songId", id); String url = CloudMusicApiUrl.fmTrashUrl.replace("{alg}","RT").replace("{songId}",id).replace("{id}","25"); return CreateWebRequest.createWebPostRequest(url, data, CreateWebRequest.getCookie(request)); } /** * 每日签到(需要登陆) * * @param type 0为安卓端签到 1为web/pc端签到 (默认值:0) * @param request * @return 是否签到成功 */ @RequestMapping("/user/signin") public String DailySignin(String type, HttpServletRequest request) { type = type == null ? "0" : type; Map<String, Object> data = new HashMap<>(); data.put("type", type); return CreateWebRequest.createWebPostRequest(CloudMusicApiUrl.userDailySigninUrl, data, CreateWebRequest.getCookie(request)); } /** * 获取云盘数据(需要登陆) * * @param limit 歌曲数量(默认值:20) * @param offset 偏移量(默认值:0) * @param request * @return 云盘数据 */ @RequestMapping("/user/cloud") public String getUserCloud(Integer limit, Integer offset, HttpServletRequest request) { limit = limit == null ? 20 : limit; offset = offset == null ? 0 : offset; Map<String, Object> data = new HashMap<>(); data.put("limit", limit); data.put("offset", offset); return CreateWebRequest.createWebPostRequest(CloudMusicApiUrl.userCloudUrl, data, CreateWebRequest.getCookie(request)); } /** * 获取指定用户信息 * * @param id *用户id 必传 * @param request * @return 用户详情 */ @RequestMapping("/user/detail") public String getUserDetail(String id, HttpServletRequest request) { if (id == null || id.trim().equals("")) { return new JSONObject(new Result(0, "缺少必填参数")).toString(); } return CreateWebRequest.createWebPostRequest(CloudMusicApiUrl.userDetailUrl.replace("{id}", id), new HashMap<>(), CreateWebRequest.getCookie(request)); } /** * 获取登陆用户信息, 歌单,收藏,mv, dj 数量(需要登陆) * * @param request * @return 用户信息, 歌单,收藏,mv, dj 数量 */ @RequestMapping("/user/subcount") public String getUserSubCount(HttpServletRequest request) { return CreateWebRequest.createWebPostRequest(CloudMusicApiUrl.userSubcountUrl, new HashMap<>(), CreateWebRequest.getCookie(request)); } /** * 更新用户歌单(需要登陆) todo 该接口有问题 * * @param id *歌单id 必传 * @param name 歌单名字 * @param desc 歌单描述 * @param tags 歌单标签 * @param request * @return 是否更新成功 */ @RequestMapping("/user/update_playlist") public String updatePlaylist(String id, String name, String desc, String tags, HttpServletRequest request) { if (id == null || id.trim().equals("")) { return new JSONObject(new Result(0, "缺少必填参数")).toString(); } Map<String, Object> data = new HashMap<>(); name = name == null ? "" : name; desc = desc == null ? "" : desc; tags = tags == null ? "" : tags; //封装请求数据 data.put("/api/playlist/desc/update", "{id:" + id + ",desc:" + desc + "}"); data.put("/api/playlist/tags/update", "{id:" + id + ",tags:" + tags + "}"); data.put("/api/playlist/update/name", "{id:" + id + ",name:" + name + "}"); return CreateWebRequest.createWebPostRequest(CloudMusicApiUrl.userUpdatePlaylistUrl, data, CreateWebRequest.getCookie(request)); } /** * 发送私信(需要登陆) * * @param ids *用户id,多个逗号隔开 必传 * @param msg *要发送的消息 必传 * @param request * @return 是否发送成功 */ @RequestMapping("/send/msg") public String sendMsg(String ids,String msg, HttpServletRequest request) { if (ids == null || ids.trim().equals("")) { return new JSONObject(new Result(0, "缺少必填参数")).toString(); } if (msg == null || msg.trim().equals("")) { return new JSONObject(new Result(0, "缺少必填参数")).toString(); } Map<String, Object> data = new HashMap<>(); data.put("type","text");//私信类型:消息类型 data.put("msg",msg); data.put("userIds","["+ids+"]"); return CreateWebRequest.createWebPostRequest(CloudMusicApiUrl.sendMsgUrl, data, CreateWebRequest.getCookie(request)); } /** * 发送私信(带歌单)(需要登陆) * * @param ids *用户id,多个逗号隔开 必传 * @param msg *要发送的消息 必传 * @param playlist *要发送的歌单 * @param request * @return 是否发送成功 */ @RequestMapping("/send/playlist") public String sendMsg(String ids,String msg,String playlist, HttpServletRequest request) { if (ids == null || ids.trim().equals("")) { return new JSONObject(new Result(0, "缺少必填参数")).toString(); } if (msg == null || msg.trim().equals("")) { return new JSONObject(new Result(0, "缺少必填参数")).toString(); } if (playlist == null || playlist.trim().equals("")) { return new JSONObject(new Result(0, "缺少必填参数")).toString(); } Map<String, Object> data = new HashMap<>(); data.put("type","playlist");//私信类型:歌单类型 data.put("msg",msg); data.put("userIds","["+ids+"]"); data.put("id",playlist); return CreateWebRequest.createWebPostRequest(CloudMusicApiUrl.sendMsgUrl, data, CreateWebRequest.getCookie(request)); } /** * 更新用户信息(需要登陆) * * @param gender gender为0表示保密,1为男性,2为女性 * @param birthday 生日 时间戳 * @param nickname 用户名 * @param province 省份(编码格式) * @param city 城市(编码格式) * @param signature 签名 * @param request */ @RequestMapping("/user/update") public String updateUser(String gender, String birthday, String nickname, String province, String city, String signature, HttpServletRequest request) { Map<String, Object> data = new HashMap<>(); data.put("avatarImgId", "0");//暂时不实现头像修改 data.put("birthday", birthday); data.put("gender", gender); data.put("nickname", nickname); data.put("province", province); data.put("city", city); data.put("signature", signature); return CreateWebRequest.createWebPostRequest(CloudMusicApiUrl.userUpdateUrl, data, CreateWebRequest.getCookie(request)); } /** * 获取用户关注列表 * * @param id *用户id 必传 * @param limit 用户数量(默认值:20) * @param offset 偏移量(默认值:0) * @return 用户关注列表 */ @RequestMapping("/user/follows") public String getUserFollows(String id,Integer limit,Integer offset) { if (id == null || id.trim().equals("")) { return new JSONObject(new Result(0, "缺少必填参数")).toString(); } Map<String,Object> data=new HashMap<>(); limit = limit == null ? 20 : limit; offset = offset == null ? 0 : offset; data.put("limit", limit); data.put("offset", offset); return CreateWebRequest.createWebPostRequest(CloudMusicApiUrl.userFollowsUrl.replace("{id}",id), data,new HashMap<>()); } /** * 获取用户粉丝列表 * * @param id *用户id 必传 * @param limit 粉丝数量(默认值:20) * @param offset 偏移量(默认值:0) * @return 用户粉丝列表 */ @RequestMapping("/user/followeds") public String getUserFolloweds(String id,Integer limit,Integer offset) { if (id == null || id.trim().equals("")) { return new JSONObject(new Result(0, "缺少必填参数")).toString(); } Map<String,Object> data=new HashMap<>(); limit = limit == null ? 20 : limit; offset = offset == null ? 0 : offset; data.put("userId", id); data.put("limit", limit); data.put("offset", offset); return CreateWebRequest.createWebPostRequest(CloudMusicApiUrl.userFollowedsUrl, data,new HashMap<>()); } /** * 获取用户动态 * * @param id *用户id 必传 * @return 用户动态 */ @RequestMapping("/user/event") public String getUserEvent(String id,Integer limit,Integer offset) { if (id == null || id.trim().equals("")) { return new JSONObject(new Result(0, "缺少必填参数")).toString(); } Map<String,Object> data=new HashMap<>(); limit = limit == null ? 20 : limit; offset = offset == null ? 0 : offset; data.put("time",-1); data.put("getcounts",true); data.put("limit",limit); data.put("offset",offset); return CreateWebRequest.createWebPostRequest(CloudMusicApiUrl.userEventUrl.replace("{id}",id), data,new HashMap<>()); } /** * 获取用户播放记录(某些用户关闭查看隐私,则无权限查看) * * @param id *用户id 必传 * @param type type=1 时只返回 weekData, type=0 时返回 allData(默认值:1) * @return 用户播放记录 */ @RequestMapping("/user/play_record") public String getUserPlayRecord(String id,String type) { if (id == null || id.trim().equals("")) { return new JSONObject(new Result(0, "缺少必填参数")).toString(); } Map<String,Object> data=new HashMap<>(); type = type == null ? "1" : type; data.put("uid",id); data.put("type",type); return CreateWebRequest.createWebPostRequest(CloudMusicApiUrl.userPlayRecordUrl, data,new HashMap<>()); } /** * 获取登陆用户动态消息 (需要登陆) * 可获取各种动态 , 对应网页版网易云,朋友界面里的各种动态消息 ,如分享的视频,音乐,照片等! * @param request * @return 动态消息 */ @RequestMapping("/event") public String getUserPlayRecord(HttpServletRequest request) { Map<String,Object> data=new HashMap<>(); return CreateWebRequest.createWebPostRequest(CloudMusicApiUrl.evnetUrl,data,CreateWebRequest.getCookie(request)); } /** * 获取登独家放送 * @param request * @return 独家放送 */ @RequestMapping("/privatecontent") public String getPrivatecontentPersonalized(HttpServletRequest request) { Map<String,Object> data=new HashMap<>(); return CreateWebRequest.createWebPostRequest(CloudMusicApiUrl.privatecontentPersonalizedUrl,new HashMap<>(),CreateWebRequest.getCookie(request)); } }
34.817935
159
0.610786
639eac24591ce944c851077e183cd0f9a3ea1631
418
package com.ssafy.happyhouse.repo; import java.sql.SQLException; import com.ssafy.happyhouse.dto.UserInfo; public interface UserInfoRepo { public UserInfo login(String userid, String userpwd) throws SQLException; public UserInfo getUser(String id); public int insert(UserInfo user); public String findPwd(String id, String name); public int modifyUser(UserInfo user); public int deleteUser(String id); }
20.9
74
0.787081
fc4f22e48d6cb64e314ec5aa19e1e0ae376c4dd6
1,382
/*************************************************************************** * Copyright (c) 2012-2013 VMware, Inc. 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.vmware.aurora.composition.concurrent; /** * A simple object to hold the result of execution result of a stored procedure, which is * executed by a {@link Transaction}. * * {@link StoredProcedureThreadPoolExecutor} and its background pool threads orchestrate execution of * multiple stored procedures in parallel. * * @author Xin Li (xinli) * */ public class ExecutionResult { final public boolean finished; final public Throwable throwable; public ExecutionResult(boolean finished, Throwable throwable) { this.finished = finished; this.throwable = throwable; } }
37.351351
101
0.659913
89351d36c223f6cf009d6ee68bb0f5900aeb7e02
1,442
package com.woshidaniu.shiro.cas; import org.apache.shiro.authc.AuthenticationException; import com.woshidaniu.shiro.SubjectUtils; import com.woshidaniu.shiro.token.ZfSsoToken; import com.woshidaniu.web.context.WebContext; import com.woshidaniu.web.utils.WebRequestUtils; import com.woshidaniu.web.utils.WebUtils; import com.woshidaniu.niuca.tp.cas.client.ZfssoBean; import com.woshidaniu.niuca.tp.cas.client.ZfssoSetsessionService; public class ZfssoShiroWebSession implements ZfssoSetsessionService { /* * 检测SESSION里面的用户是否存在,存在返回TRUE,反之为FALSE * * @see * com.woshidaniu.niuca.tp.cas.client.ZfssoSetsessionService#chkUserSession(com. * woshidaniu.niuca.tp.cas.client.ZfssoBean) */ public Boolean chkUserSession(ZfssoBean zfssobean) { return SubjectUtils.getWebSubject().isAuthenticated(); } /* * 验证用户是否存在,存在则读取权限并返回TRUE,反之为FALSE * * @see * com.woshidaniu.niuca.tp.cas.client.ZfssoSetsessionService#setUserSession(com. * woshidaniu.niuca.tp.cas.client.ZfssoBean) */ public Boolean setUserSession(ZfssoBean zfssobean) { Boolean res = false; try { ZfSsoToken token = new ZfSsoToken(); token.setUsername(zfssobean.getYhm()); //token.setRememberMe(true); token.setHost(WebRequestUtils.getRemoteAddr(WebUtils.toHttp(WebContext.getRequest()))); SubjectUtils.getWebSubject().login(token); res = true; } catch (AuthenticationException e) { e.printStackTrace(); } return res; } }
29.428571
90
0.771151
b009f4e4157ae4fb8b2e2762a222be6ca6b0ce50
1,846
import java.io.*; import java.util.*; public class Solution { public static int solution(int[] height) { int n = height.length; if(n == 0) return 0; Stack<Integer> left = new Stack<Integer>(); Stack<Integer> right = new Stack<Integer>(); int[] width = new int[n];// widths of intervals. Arrays.fill(width, 1);// all intervals should at least be 1 unit wide. for(int i = 0; i < n; i++){ // count # of consecutive higher bars on the left of the (i+1)th bar while(!left.isEmpty() && height[i] <= height[left.peek()]){ // while there are bars stored in the stack, we check the bar on the top of the stack. left.pop(); } if(left.isEmpty()){ // all elements on the left are larger than height[i]. width[i] += i; } else { // bar[left.peek()] is the closest shorter bar. width[i] += i - left.peek() - 1; } left.push(i); } for (int i = n-1; i >=0; i--) { while(!right.isEmpty() && height[i] <= height[right.peek()]){ right.pop(); } if(right.isEmpty()){ // all elements to the right are larger than height[i] width[i] += n - 1 - i; } else { width[i] += right.peek() - i - 1; } right.push(i); } int max = Integer.MIN_VALUE; for(int i = 0; i < n; i++){ // find the maximum value of all rectangle areas. max = Math.max(max, width[i] * height[i]); } return max; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int height[] = new int[n]; for (int i = 0; i < n; i++) height[i] = in.nextInt(); System.out.println(solution(height)); } }
27.552239
98
0.511376
5e265aa7db550978400f707d2e21d5b16427c811
8,811
// Copyright (c) 2016, the R8 project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. package com.android.tools.r8; import static com.android.tools.r8.TestCondition.R8_COMPILER; import static com.android.tools.r8.TestCondition.match; import static com.android.tools.r8.utils.FileUtils.JAR_EXTENSION; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import com.android.tools.r8.R8RunArtTestsTest.CompilerUnderTest; import com.android.tools.r8.R8RunArtTestsTest.DexTool; import com.android.tools.r8.ToolHelper.DexVm; import com.android.tools.r8.errors.Unreachable; import com.android.tools.r8.shaking.ProguardRuleParserException; import com.android.tools.r8.utils.FileUtils; import com.android.tools.r8.utils.JarBuilder; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ExecutionException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class R8RunExamplesTest { private static final String EXAMPLE_DIR = ToolHelper.EXAMPLES_BUILD_DIR; // For local testing on a specific Art version(s) change this set. e.g. to // ImmutableSet.of(DexVm.ART_DEFAULT) or pass the option -Ddex_vm=<version> to the Java VM. private static final Set<DexVm> artVersions = ToolHelper.getArtVersions(); // Tests failing to run. private static final Map<String, TestCondition> failingRun = new ImmutableMap.Builder<String, TestCondition>() .put("memberrebinding2.Test", match(R8_COMPILER)) // b/38187737 .build(); private static final Map<String, TestCondition> outputNotIdenticalToJVMOutput = new ImmutableMap.Builder<String, TestCondition>() // Traverses stack frames that contain Art specific frames. .put("throwing.Throwing", TestCondition.any()) // Early art versions incorrectly print Float.MIN_VALUE. .put( "filledarray.FilledArray", TestCondition.match( TestCondition.runtimes(DexVm.ART_6_0_1, DexVm.ART_5_1_1, DexVm.ART_4_4_4))) .build(); @Parameters(name = "{0}_{1}_{2}_{3}") public static Collection<String[]> data() { String[] tests = { "arithmetic.Arithmetic", "arrayaccess.ArrayAccess", "barray.BArray", "bridge.BridgeMethod", "cse.CommonSubexpressionElimination", "constants.Constants", "controlflow.ControlFlow", "conversions.Conversions", "floating_point_annotations.FloatingPointValuedAnnotationTest", "filledarray.FilledArray", "hello.Hello", "ifstatements.IfStatements", "instancevariable.InstanceVariable", "instanceofstring.InstanceofString", "invoke.Invoke", "jumbostring.JumboString", "loadconst.LoadConst", "newarray.NewArray", "regalloc.RegAlloc", "returns.Returns", "staticfield.StaticField", "stringbuilding.StringBuilding", "switches.Switches", "sync.Sync", "throwing.Throwing", "trivial.Trivial", "trycatch.TryCatch", "nestedtrycatches.NestedTryCatches", "trycatchmany.TryCatchMany", "invokeempty.InvokeEmpty", "regress.Regress", "regress2.Regress2", "regress_37726195.Regress", "regress_37658666.Regress", "regress_37875803.Regress", "regress_37955340.Regress", "regress_62300145.Regress", "memberrebinding2.Memberrebinding", "memberrebinding3.Memberrebinding", "minification.Minification", "enclosingmethod.Main", "interfaceinlining.Main", "switchmaps.Switches", }; List<String[]> fullTestList = new ArrayList<>(tests.length * 2); for (String test : tests) { fullTestList.add(makeTest(DexTool.NONE, CompilerUnderTest.D8, CompilationMode.DEBUG, test)); fullTestList.add(makeTest(DexTool.NONE, CompilerUnderTest.R8, CompilationMode.RELEASE, test)); fullTestList.add(makeTest(DexTool.DX, CompilerUnderTest.R8, CompilationMode.RELEASE, test)); } return fullTestList; } private static String[] makeTest( DexTool tool, CompilerUnderTest compiler, CompilationMode mode, String clazz) { String pkg = clazz.substring(0, clazz.lastIndexOf('.')); return new String[]{pkg, tool.name(), compiler.name(), mode.name(), clazz}; } @Rule public TemporaryFolder temp = ToolHelper.getTemporaryFolderForTest(); private final DexTool tool; private final CompilerUnderTest compiler; private final CompilationMode mode; private final String pkg; private final String mainClass; public R8RunExamplesTest( String pkg, String tool, String compiler, String mode, String mainClass) { this.pkg = pkg; this.tool = DexTool.valueOf(tool); this.compiler = CompilerUnderTest.valueOf(compiler); this.mode = CompilationMode.valueOf(mode); this.mainClass = mainClass; } private Path getInputFile() { if (tool == DexTool.NONE) { return getOriginalJarFile(); } assert tool == DexTool.DX; return getOriginalDexFile(); } public Path getOriginalJarFile() { return Paths.get(EXAMPLE_DIR, pkg + JAR_EXTENSION); } private Path getOriginalDexFile() { return Paths.get(EXAMPLE_DIR, pkg, FileUtils.DEFAULT_DEX_FILENAME); } @Rule public ExpectedException thrown = ExpectedException.none(); @Before public void compile() throws IOException, ProguardRuleParserException, ExecutionException, CompilationException { Path out = temp.getRoot().toPath(); switch (compiler) { case D8: { ToolHelper.runD8(D8Command.builder() .addProgramFiles(getInputFile()) .setOutputPath(out) .setMode(mode) .build()); break; } case R8: { ToolHelper.runR8(R8Command.builder() .addProgramFiles(getInputFile()) .setOutputPath(out) .setMode(mode) .build()); break; } default: throw new Unreachable(); } } @Test public void outputIsIdentical() throws IOException, InterruptedException, ExecutionException { if (!ToolHelper.artSupported()) { return; } String original = getOriginalDexFile().toString(); File generated; // Collect the generated dex files. File[] outputFiles = temp.getRoot().listFiles((File file) -> file.getName().endsWith(".dex")); if (outputFiles.length == 1) { // Just run Art on classes.dex. generated = outputFiles[0]; } else { // Run Art on JAR file with multiple dex files. generated = temp.getRoot().toPath().resolve(pkg + ".jar").toFile(); JarBuilder.buildJar(outputFiles, generated); } ToolHelper.ProcessResult javaResult = ToolHelper.runJava(ImmutableList.of(getOriginalJarFile().toString()), mainClass); if (javaResult.exitCode != 0) { fail("JVM failed for: " + mainClass); } // TODO(ager): Once we have a bot running using dalvik (version 4.4.4) we should remove // this explicit loop to get rid of repeated testing on the buildbots. for (DexVm version : artVersions) { TestCondition condition = failingRun.get(mainClass); if (condition != null && condition.test(tool, compiler, version, mode)) { thrown.expect(Throwable.class); } else { thrown = ExpectedException.none(); } // Check output against Art output on original dex file. String output = ToolHelper.checkArtOutputIdentical(original, generated.toString(), mainClass, version); // Check output against JVM output. if (shouldMatchJVMOutput(version)) { String javaOutput = javaResult.stdout; assertEquals( "JVM and Art output differ:\n" + "JVM:\n" + javaOutput + "\nArt:\n" + output, output, javaOutput); } } } private boolean shouldMatchJVMOutput(DexVm version) { TestCondition condition = outputNotIdenticalToJVMOutput.get(mainClass); return condition == null || !condition.test(tool, compiler, version, mode); } }
34.826087
100
0.682783
fc3bf86927b897dec911b841f5029036a92d190c
4,165
package me.bayang.reader.mobilizer; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ResourceBundle; import java.util.concurrent.TimeUnit; import javax.annotation.PostConstruct; import javax.annotation.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import com.fasterxml.jackson.databind.ObjectMapper; import javafx.concurrent.Task; import me.bayang.reader.backend.inoreader.ConnectServer; import me.bayang.reader.controllers.RssController; import okhttp3.HttpUrl; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; @Service public class MercuryMobilizer { private static Logger LOGGER = LoggerFactory.getLogger(MercuryMobilizer.class); @Value("${mercury.key}") private String appKey; // https://mercury.postlight.com/parser?url= private static final String APP_URL = "https://mercury.postlight.com/parser"; private static final HttpUrl APP_HTTP_URL = HttpUrl.parse(APP_URL); private OkHttpClient okClient; private ResourceBundle bundle = ResourceBundle.getBundle("i18n.translations"); @Resource(name="mapper") private ObjectMapper mapper; @PostConstruct public void initClient() { okClient = new OkHttpClient.Builder() .followRedirects(true) .followSslRedirects(true) .readTimeout(1, TimeUnit.MINUTES) .connectTimeout(1, TimeUnit.MINUTES) .build(); } public MercuryResult getMercuryResult(String url) { HttpUrl parameterUrl = APP_HTTP_URL.newBuilder() .setQueryParameter("url", url) .build(); Request request = new Request.Builder() .url(parameterUrl) .addHeader("x-api-key", appKey) .addHeader("Content-Type", "application/json") .build(); try { Response r = okClient.newCall(request).execute(); if (r.isSuccessful()) { BufferedReader reader = new BufferedReader(new InputStreamReader(r.body().source().inputStream(), "utf-8")); MercuryResult m = mapper.readValue(reader, MercuryResult.class); ConnectServer.closeReader(reader); return m; } else { RssController.snackbarNotify(bundle.getString("connectionFailure")); r.close(); LOGGER.debug("mercury mobilizer error code {} for {}",r.code(), request.url()); } } catch (IOException e) { RssController.snackbarNotify(bundle.getString("connectionFailure")); } return null; } public Task<MercuryResult> getMercuryResultTask(String url) { Task<MercuryResult> t = new Task<MercuryResult>() { @Override protected MercuryResult call() throws Exception { LOGGER.debug("starting to fetch mercury for url {}", url); return getMercuryResult(url); } }; return t; } public static String formatContent(String imgUrl, String pageUrl, String content) { StringBuilder sb = new StringBuilder(); sb.append("<style> p { padding: 5px 50px 5px 50px; } font { font: 400 18px/1.62 Helvetica, Tahoma, Arial, STXihei, \"华文细黑\", \"Microsoft YaHei\", \"微软雅黑\", SimSun, \"宋体\", Heiti, \"黑体\", sans-serif; } img { border-radius: 10px; max-width: 100%; height: auto; } </style> <body><font>"); sb.append("<div><img src=\""); sb.append(imgUrl); sb.append("\"></img>"); sb.append("</div>"); if (! pageUrl.startsWith("/")) { sb.append("<div><a href=\""); sb.append(pageUrl); sb.append("\">"); sb.append(pageUrl); sb.append("</a>\""); sb.append("</div>"); } sb.append(content); sb.append("</font></body>"); return sb.toString(); } }
35.598291
293
0.612725
83230d2fc8797be67a87870c6d804f85017799b8
2,421
package net.mofancy.security.admin.rest; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import net.mofancy.security.admin.biz.UserBiz; import net.mofancy.security.common.msg.ObjectRestResponse; import net.mofancy.security.common.msg.TableResultResponse; import net.mofancy.security.admin.biz.ElementBiz; import net.mofancy.security.admin.entity.Element; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import net.mofancy.security.common.rest.BaseController; import java.util.List; /** * <p> * 前端控制器 * </p> * * @author zhangweiqi * @since 2019-11-04 */ @RestController @RequestMapping("element") public class ElementController extends BaseController<ElementBiz, Element> { @Autowired private UserBiz userBiz; @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public TableResultResponse<Element> page(@RequestParam(defaultValue = "10") int limit, @RequestParam(defaultValue = "1") int offset, String name, @RequestParam(defaultValue = "0") int menuId) { QueryWrapper<Element> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("menu_id", menuId); if(StringUtils.isNotBlank(name)){ queryWrapper.like("name", "%" + name + "%"); } List<Element> elements = baseBiz.selectByExample(queryWrapper); return new TableResultResponse<Element>(elements.size(), elements); } @RequestMapping(value = "/user", method = RequestMethod.GET) @ResponseBody public ObjectRestResponse<Element> getAuthorityElement(String menuId) { int userId = userBiz.getUserByUsername(getCurrentUserName()).getId(); List<Element> elements = baseBiz.getAuthorityElementByUserId(userId + "",menuId); return new ObjectRestResponse<List<Element>>().data(elements); } @RequestMapping(value = "/user/menu", method = RequestMethod.GET) @ResponseBody public ObjectRestResponse<Element> getAuthorityElement() { int userId = userBiz.getUserByUsername(getCurrentUserName()).getId(); List<Element> elements = baseBiz.getAuthorityElementByUserId(userId + ""); return new ObjectRestResponse<List<Element>>().data(elements); } }
39.048387
152
0.697646
05e8549a930023df4d3822b6695be84986357b81
9,161
package com.web.basePrice.controller; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.app.base.control.WebController; import com.app.base.data.ApiResponseResult; import com.web.basePrice.entity.PriceComm; import com.web.basePrice.service.PriceCommService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; @Api("物料通用价格维护模块") @CrossOrigin @ControllerAdvice @Controller @RequestMapping(value = "basePrice/priceComm") public class PriceCommController extends WebController{ private String module = "物料通用价格维护"; @Autowired private PriceCommService priceCommService; @ApiOperation(value = "物料通用价格维护表结构", notes = "物料通用价格维护结构"+ PriceComm.TABLE_NAME) @RequestMapping(value = "/getPriceComm", method = RequestMethod.GET) @ResponseBody public PriceComm getPriceComm(){ return new PriceComm(); } @ApiOperation(value = "物料通用价格维护列表页", notes = "物料通用价格维护列表页", hidden = true) @RequestMapping(value = "/toPriceComm") public String toPriceComm(){ return "/web/basePrice/price_comm"; } @ApiOperation(value = "获取物料通用价格维护列表", notes = "获取物料通用价格维护列表",hidden = true) @RequestMapping(value = "/getList", method = RequestMethod.GET) @ResponseBody public ApiResponseResult getList(String keyword) { String method = "basePrice/priceComm/getList";String methodName ="获取物料通用价格维护列表"; try { System.out.println(keyword); Sort sort = new Sort(Sort.Direction.DESC, "id"); ApiResponseResult result = priceCommService.getList(keyword, super.getPageRequest(sort)); logger.debug("获取物料通用价格维护列表=getList:"); getSysLogService().success(module,method, methodName, null); return result; } catch (Exception e) { e.printStackTrace(); logger.error("获取物料通用价格维护列表失败!", e); getSysLogService().error(module,method, methodName, e.toString()); return ApiResponseResult.failure("获取物料通用价格维护列表失败!"); } } @ApiOperation(value = "新增物料通用价格维护", notes = "新增物料通用价格维护",hidden = true) @RequestMapping(value = "/add", method = RequestMethod.POST) @ResponseBody public ApiResponseResult add(@RequestBody PriceComm priceComm) { String method = "basePrice/priceComm/add";String methodName ="新增物料通用价格维护"; try{ ApiResponseResult result = priceCommService.add(priceComm); logger.debug("新增物料通用价格维护=add:"); getSysLogService().success(module,method, methodName, null); return result; }catch(Exception e){ e.printStackTrace(); logger.error("物料通用价格维护新增失败!", e); getSysLogService().error(module,method, methodName, e.toString()); return ApiResponseResult.failure("物料通用价格维护新增失败!"); } } @ApiOperation(value = "编辑物料通用价格维护", notes = "编辑物料通用价格维护",hidden = true) @RequestMapping(value = "/edit", method = RequestMethod.POST) @ResponseBody public ApiResponseResult edit(@RequestBody PriceComm priceComm){ String method = "basePrice/priceComm/edit";String methodName ="编辑物料通用价格维护"; try{ ApiResponseResult result = priceCommService.edit(priceComm); logger.debug("编辑物料通用价格维护=edit:"); getSysLogService().success(module,method, methodName, null); return result; }catch(Exception e){ e.printStackTrace(); logger.error("编辑物料通用价格维护失败!", e); getSysLogService().error(module,method, methodName, e.toString()); return ApiResponseResult.failure("编辑物料通用价格维护失败!"); } } @ApiOperation(value = "删除物料通用价格维护", notes = "删除物料通用价格维护",hidden = true) @RequestMapping(value = "/delete", method = RequestMethod.POST) @ResponseBody public ApiResponseResult delete(@RequestBody Map<String, Object> params){ String method = "basePrice/priceComm/delete";String methodName ="删除物料通用价格维护"; try{ long id = Long.parseLong(params.get("id").toString()) ; ApiResponseResult result = priceCommService.delete(id); logger.debug("删除物料通用价格维护=delete:"); getSysLogService().success(module,method, methodName, null); return result; }catch(Exception e){ e.printStackTrace(); logger.error("删除物料通用价格维护失败!", e); getSysLogService().error(module,method, methodName, e.toString()); return ApiResponseResult.failure("删除物料通用价格维护失败!"); } } @ApiOperation(value = "设置正常/禁用", notes = "设置正常/禁用", hidden = true) @RequestMapping(value = "/doStatus", method = RequestMethod.POST) @ResponseBody public ApiResponseResult doStatus(@RequestBody Map<String, Object> params) throws Exception{ //Long id, Integer deStatus String method = "basePrice/priceComm/doStatus";String methodName ="设置正常/禁用"; try{ long id = Long.parseLong(params.get("id").toString()) ; Integer bsStatus=Integer.parseInt(params.get("checkStatus").toString()); ApiResponseResult result = priceCommService.doStatus(id, bsStatus); logger.debug("设置正常/禁用=doStatus:"); getSysLogService().success(module,method, methodName, params); return result; }catch (Exception e){ e.printStackTrace(); logger.error("设置正常/禁用失败!", e); getSysLogService().error(module,method, methodName, params+";"+e.toString()); return ApiResponseResult.failure("设置正常/禁用失败!"); } } @ApiOperation(value = "获取单位下拉列表", notes = "获取单位下拉列表",hidden = true) @RequestMapping(value = "/getUnitList", method = RequestMethod.GET) @ResponseBody public ApiResponseResult getUnitList() { String method = "basePrice/priceComm/getUnitList";String methodName ="获取单位下拉列表"; try { ApiResponseResult result = priceCommService.getUnitList(); logger.debug("获取单位下拉列表=getUnitList:"); getSysLogService().success(module,method, methodName, null); return result; } catch (Exception e) { e.printStackTrace(); logger.error("获取单位下拉列表失败!", e); getSysLogService().error(module,method, methodName, e.toString()); return ApiResponseResult.failure("获取单位下拉列表失败!"); } } @ApiOperation(value = "获取物料下拉列表", notes = "获取物料下拉列表",hidden = true) @RequestMapping(value = "/getItemList", method = RequestMethod.GET) @ResponseBody public ApiResponseResult getItemList(String keyword) { String method = "basePrice/priceComm/getItemList";String methodName ="获取物料下拉列表"; try { Sort sort = Sort.unsorted(); ApiResponseResult result = priceCommService.getItemList(keyword,super.getPageRequest(sort)); logger.debug("获取单位下拉列表=getUnitList:"); getSysLogService().success(module,method, methodName, null); return result; } catch (Exception e) { e.printStackTrace(); logger.error("获取物料下拉列表失败!", e); getSysLogService().error(module,method, methodName, e.toString()); return ApiResponseResult.failure("获取物料下拉列表失败!"); } } @ApiOperation(value = "导入", notes = "导入", hidden = true) @RequestMapping(value = "/doExcel", method = RequestMethod.POST) @ResponseBody public ApiResponseResult doExcel(MultipartFile[] file) throws Exception{ String method = "/basePrice/priceComm/doExcel";String methodName ="导入"; try{ ApiResponseResult result = priceCommService.doExcel(file); logger.debug("导入=doExcel:"); getSysLogService().success(module,method, methodName, null); return result; }catch (Exception e){ e.printStackTrace(); logger.error("导入失败!", e); getSysLogService().error(module,method, methodName, e.toString()); return ApiResponseResult.failure("导入失败!"); } } @ApiOperation(value = "导出", notes = "导出", hidden = true) @RequestMapping(value = "/export", method = RequestMethod.GET) @ResponseBody public void export(HttpServletResponse response, String keyword) throws Exception{ String method = "/basePrice/priceComm/export";String methodName ="导出"; try{ priceCommService.exportExcel(response,keyword); }catch (Exception e){ e.printStackTrace(); logger.error("导出失败!", e); } } }
42.808411
104
0.659426
4aad896003a064273ae207a78016c5323b136e16
247
package com.alibaba.doris.dataserver.action.data; import com.alibaba.doris.dataserver.action.ActionType; /** * @author ajun Email:jack.yuj@alibaba-inc.com */ public interface ActionData { public ActionType getActionType(); }
19
55
0.720648
2a83b7cfacd02703abe2595278cc0fa8dc05822c
6,017
package com.jfinalshop.controller.admin; import net.hasor.core.Inject; import org.apache.commons.lang3.StringUtils; import com.jfinal.ext.route.ControllerBind; import com.jfinalshop.Pageable; import com.jfinalshop.model.Member; import com.jfinalshop.model.Message; import com.jfinalshop.service.MemberService; import com.jfinalshop.service.MessageService; /** * Controller - 消息 * * */ @ControllerBind(controllerKey = "/admin/message") public class MessageController extends BaseController { @Inject private MessageService messageService; @Inject private MemberService memberService; /** * 检查用户名是否合法 */ public void checkUsername() { String username = getPara("draftMessage.username"); if (StringUtils.isEmpty(username)) { renderJson(false); return; } renderJson(memberService.usernameExists(username)); } /** * 发送 */ public void send() { Long draftMessageId = getParaToLong("draftMessageId"); Message draftMessage = messageService.find(draftMessageId); if (draftMessage != null && draftMessage.getIsDraft() && draftMessage.getSender() == null) { setAttr("draftMessage", draftMessage); } render("/admin/message/send.ftl"); } /** * 发送 */ public void sendSubmit() { Long draftMessageId = getParaToLong("draftMessageId"); String username = getPara("draftMessage.username"); String title = getPara("draftMessage.title"); String content = getPara("draftMessage.content"); Boolean isDraft = getParaToBoolean("isDraft", false); Message draftMessage = messageService.find(draftMessageId); if (draftMessage != null && draftMessage.getIsDraft() && draftMessage.getSender() == null) { messageService.delete(draftMessage); } Member receiver = null; if (StringUtils.isNotEmpty(username)) { receiver = memberService.findByUsername(username); if (receiver == null) { redirect(ERROR_VIEW); return; } } Message message = new Message(); message.setTitle(title); message.setContent(content); message.setIp(getRequest().getRemoteAddr()); message.setIsDraft(isDraft); message.setSenderRead(true); message.setReceiverRead(false); message.setSenderDelete(false); message.setReceiverDelete(false); message.setSender(null); message.setReceiver(receiver); message.setForMessage(null); message.setReplyMessages(null); messageService.save(message); if (isDraft) { addFlashMessage(com.jfinalshop.Message.success("admin.message.saveDraftSuccess")); redirect("/admin/message/draft.jhtml"); } else { addFlashMessage(com.jfinalshop.Message.success("admin.message.sendSuccess")); redirect("/admin/message/list.jhtml"); } } /** * 查看 */ public void view() { Long id = getParaToLong("id"); Message message = messageService.find(id); if (message == null || message.getIsDraft() || message.getForMessage() != null) { redirect(ERROR_VIEW); return; } if ((message.getSenderId() != null && message.getReceiverId() != null) || (message.getReceiverId() == null && message.getReceiverDelete()) || (message.getSenderId() == null && message.getSenderDelete())) { redirect(ERROR_VIEW); return; } if (message.getReceiverId() == null) { message.setReceiverRead(true); } else { message.setSenderRead(true); } messageService.update(message); setAttr("adminMessage", message); render("/admin/message/view.ftl"); } /** * 回复 */ public void reply() { Long id = getParaToLong("adminMessage.id"); String content = getPara("content"); Message forMessage = messageService.find(id); if (forMessage == null || forMessage.getIsDraft() || forMessage.getForMessage() != null) { redirect(ERROR_VIEW); return; } if ((forMessage.getSenderId() != null && forMessage.getReceiverId() != null) || (forMessage.getReceiver() == null && forMessage.getReceiverDelete()) || (forMessage.getSender() == null && forMessage.getSenderDelete())) { redirect(ERROR_VIEW); return; } Message message = new Message(); message.setTitle("reply: " + forMessage.getTitle()); message.setContent(content); message.setIp(getRequest().getRemoteAddr()); message.setIsDraft(false); message.setSenderRead(true); message.setReceiverRead(false); message.setSenderDelete(false); message.setReceiverDelete(false); message.setSenderId(null); message.setReceiverId(forMessage.getReceiverId() == null ? forMessage.getSenderId() : forMessage.getReceiverId()); if ((forMessage.getReceiverId() == null && !forMessage.getSenderDelete()) || (forMessage.getSender() == null && !forMessage.getReceiverDelete())) { message.setForMessage(forMessage); } message.setReplyMessages(null); messageService.save(message); if (forMessage.getSenderId() == null) { forMessage.setSenderRead(true); forMessage.setReceiverRead(false); } else { forMessage.setSenderRead(false); forMessage.setReceiverRead(true); } messageService.update(forMessage); if ((forMessage.getReceiverId() == null && !forMessage.getSenderDelete()) || (forMessage.getSenderId() == null && !forMessage.getReceiverDelete())) { addFlashMessage(SUCCESS_MESSAGE); redirect("/admin/message/view.jhtml?id=" + forMessage.getId()); } else { addFlashMessage(com.jfinalshop.Message.success("admin.message.replySuccess")); redirect("/admin/message/list.jhtml"); } } /** * 列表 */ public void list() { Pageable pageable = getBean(Pageable.class); setAttr("pageable", pageable); setAttr("page", messageService.findPage(null, pageable, null)); render("/admin/message/list.ftl"); } /** * 草稿箱 */ public void draft() { Pageable pageable = getBean(Pageable.class); setAttr("pageable", pageable); setAttr("page", messageService.findDraftPage(null, pageable)); render("/admin/message/draft.ftl"); } /** * 删除 */ public void delete() { Long[] ids = getParaValuesToLong("ids"); System.out.println("ids<<<<<<"+ids); if (ids != null) { for (Long id : ids) { messageService.delete(id, null); } } renderJson(SUCCESS_MESSAGE); } }
29.495098
221
0.705335
b1ea1afa6fa7d1ee6da3779aaa21bcbeb6cc8e62
825
package co.aurasphere.facebot.model.threadsettings; import java.io.Serializable; import javax.validation.constraints.NotNull; import com.google.gson.annotations.SerializedName; /** * Base request for a Thread Setting configuration. * * @see <a href= * "https://developers.facebook.com/docs/messenger-platform/thread-settings" * >Facebook's Messenger Platform Thread Settings Documentation</a> * * @author Donato Rimenti * @date Aug 08, 2016 */ public abstract class ThreadSettingRequest implements Serializable { private static final long serialVersionUID = 1L; /** * The type of setting to change. */ @NotNull @SerializedName("setting_type") protected SettingType type; public SettingType getType() { return type; } public void setType(SettingType type) { this.type = type; } }
21.710526
81
0.73697
f274c8a7986d8ef00fe8f8cd41e371f0bfd6c082
850
package com.opm.eis.utils; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class DateUtils { public String getDateToday() { Date date = Calendar.getInstance().getTime(); SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); return sdf.format(date); } public String sendDate(){ String dateToday = new String(); dateToday = getDateToday().toString(); return dateToday; } /* public Date changeDate(){ Date date = Calendar.getInstance().getTime(); SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); Date dateString = sdf.format(date); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/mm/dd"); Date convertedDate = dateFormat.parse(dateString); return convertedDate; } */ }
22.972973
71
0.676471
94b4c2f786d2ae4eae728b9d67a2ba9d453f4e8f
3,583
/* */ package com.google.gson.internal.bind; /* */ /* */ import com.google.gson.Gson; /* */ import com.google.gson.TypeAdapter; /* */ import com.google.gson.TypeAdapterFactory; /* */ import com.google.gson.internal.LinkedTreeMap; /* */ import com.google.gson.reflect.TypeToken; /* */ import com.google.gson.stream.JsonReader; /* */ import com.google.gson.stream.JsonToken; /* */ import com.google.gson.stream.JsonWriter; /* */ import java.io.IOException; /* */ import java.util.ArrayList; /* */ import java.util.List; /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public final class ObjectTypeAdapter /* */ extends TypeAdapter<Object> /* */ { /* 38 */ public static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() /* */ { /* */ public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { /* 41 */ if (type.getRawType() == Object.class) { /* 42 */ return new ObjectTypeAdapter(gson); /* */ } /* 44 */ return null; /* */ } /* */ }; /* */ /* */ private final Gson gson; /* */ /* */ ObjectTypeAdapter(Gson gson) { /* 51 */ this.gson = gson; /* */ } public Object read(JsonReader in) throws IOException { /* */ List<Object> list; /* */ LinkedTreeMap<String, Object> linkedTreeMap; /* 55 */ JsonToken token = in.peek(); /* 56 */ switch (token) { /* */ case BEGIN_ARRAY: /* 58 */ list = new ArrayList(); /* 59 */ in.beginArray(); /* 60 */ while (in.hasNext()) { /* 61 */ list.add(read(in)); /* */ } /* 63 */ in.endArray(); /* 64 */ return list; /* */ /* */ case BEGIN_OBJECT: /* 67 */ linkedTreeMap = new LinkedTreeMap(); /* 68 */ in.beginObject(); /* 69 */ while (in.hasNext()) { /* 70 */ linkedTreeMap.put(in.nextName(), read(in)); /* */ } /* 72 */ in.endObject(); /* 73 */ return linkedTreeMap; /* */ /* */ case STRING: /* 76 */ return in.nextString(); /* */ /* */ case NUMBER: /* 79 */ return Double.valueOf(in.nextDouble()); /* */ /* */ case BOOLEAN: /* 82 */ return Boolean.valueOf(in.nextBoolean()); /* */ /* */ case NULL: /* 85 */ in.nextNull(); /* 86 */ return null; /* */ } /* */ /* 89 */ throw new IllegalStateException(); /* */ } /* */ /* */ /* */ /* */ public void write(JsonWriter out, Object value) throws IOException { /* 95 */ if (value == null) { /* 96 */ out.nullValue(); /* */ /* */ return; /* */ } /* 100 */ TypeAdapter<Object> typeAdapter = this.gson.getAdapter(value.getClass()); /* 101 */ if (typeAdapter instanceof ObjectTypeAdapter) { /* 102 */ out.beginObject(); /* 103 */ out.endObject(); /* */ /* */ return; /* */ } /* 107 */ typeAdapter.write(out, value); /* */ } /* */ } /* Location: C:\Users\Main\AppData\Roaming\StreamCraf\\updates\Launcher.jar!\com\google\gson\internal\bind\ObjectTypeAdapter.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
31.156522
143
0.455763
3e583a700675291172fbfdbcc0a30791b7a2e253
4,870
package cc.mrbird.febs.dca.service.impl; import cc.mrbird.febs.common.domain.QueryRequest; import cc.mrbird.febs.common.utils.SortUtil; import cc.mrbird.febs.dca.entity.DcaBPersonalsummary; import cc.mrbird.febs.dca.dao.DcaBPersonalsummaryMapper; import cc.mrbird.febs.dca.service.IDcaBPersonalsummaryService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import java.util.Date; import java.util.Arrays; import java.util.List; import java.util.UUID; import java.time.LocalDate; /** * <p> * 个人总结 服务实现类 * </p> * * @author viki * @since 2020-09-16 */ @Slf4j @Service("IDcaBPersonalsummaryService") @Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class) public class DcaBPersonalsummaryServiceImpl extends ServiceImpl<DcaBPersonalsummaryMapper, DcaBPersonalsummary> implements IDcaBPersonalsummaryService { @Override public IPage<DcaBPersonalsummary> findDcaBPersonalsummarys(QueryRequest request, DcaBPersonalsummary dcaBPersonalsummary){ try{ LambdaQueryWrapper<DcaBPersonalsummary> queryWrapper=new LambdaQueryWrapper<>(); queryWrapper.eq(DcaBPersonalsummary::getIsDeletemark, 1);//1是未删 0是已删 if (StringUtils.isNotBlank(dcaBPersonalsummary.getUserAccount())) { queryWrapper.and(wrap-> wrap.eq(DcaBPersonalsummary::getUserAccount, dcaBPersonalsummary.getUserAccount()).or() .like(DcaBPersonalsummary::getUserAccountName, dcaBPersonalsummary.getUserAccount())); } if (dcaBPersonalsummary.getState()!=null) { queryWrapper.eq(DcaBPersonalsummary::getState, dcaBPersonalsummary.getState()); } if (StringUtils.isNotBlank(dcaBPersonalsummary.getCreateTimeFrom()) && StringUtils.isNotBlank(dcaBPersonalsummary.getCreateTimeTo())) { queryWrapper .ge(DcaBPersonalsummary::getCreateTime, dcaBPersonalsummary.getCreateTimeFrom()) .le(DcaBPersonalsummary::getCreateTime, dcaBPersonalsummary.getCreateTimeTo()); } if (StringUtils.isNotBlank(dcaBPersonalsummary.getModifyTimeFrom()) && StringUtils.isNotBlank(dcaBPersonalsummary.getModifyTimeTo())) { queryWrapper .ge(DcaBPersonalsummary::getModifyTime, dcaBPersonalsummary.getModifyTimeFrom()) .le(DcaBPersonalsummary::getModifyTime, dcaBPersonalsummary.getModifyTimeTo()); } Page<DcaBPersonalsummary> page=new Page<>(); SortUtil.handlePageSort(request,page,false);//true 是属性 false是数据库字段可两个 return this.page(page,queryWrapper); }catch(Exception e){ log.error("获取字典信息失败" ,e); return null; } } @Override public IPage<DcaBPersonalsummary> findDcaBPersonalsummaryList (QueryRequest request, DcaBPersonalsummary dcaBPersonalsummary){ try{ Page<DcaBPersonalsummary> page=new Page<>(); SortUtil.handlePageSort(request,page,false);//true 是属性 false是数据库字段可两个 return this.baseMapper.findDcaBPersonalsummary(page,dcaBPersonalsummary); }catch(Exception e){ log.error("获取个人总结失败" ,e); return null; } } @Override @Transactional public void createDcaBPersonalsummary(DcaBPersonalsummary dcaBPersonalsummary){ dcaBPersonalsummary.setId(UUID.randomUUID().toString()); dcaBPersonalsummary.setCreateTime(new Date()); dcaBPersonalsummary.setIsDeletemark(1); this.save(dcaBPersonalsummary); } @Override @Transactional public void updateDcaBPersonalsummary(DcaBPersonalsummary dcaBPersonalsummary){ dcaBPersonalsummary.setModifyTime(new Date()); this.baseMapper.updateDcaBPersonalsummary(dcaBPersonalsummary); } @Override @Transactional public void deleteDcaBPersonalsummarys(String[]Ids){ List<String> list=Arrays.asList(Ids); this.baseMapper.deleteBatchIds(list); } @Override @Transactional public void deleteByuseraccount(String userAccount){ this.baseMapper.deleteByAccount(userAccount); } }
43.873874
167
0.701643
2136656d4417affbfe9790b4b8bd668e9c3c2b31
1,520
/* * Copyright (c) 2018 Zhang Hai <Dreaming.in.Code.ZH@Gmail.com> * All Rights Reserved. */ package me.zhanghai.android.douya.item.content; import android.app.Dialog; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatDialogFragment; import me.zhanghai.android.douya.R; public class ConfirmUncollectItemDialogFragment extends AppCompatDialogFragment { /** * @deprecated Use {@link #newInstance()} instead. */ public ConfirmUncollectItemDialogFragment() {} public static ConfirmUncollectItemDialogFragment newInstance() { //noinspection deprecation return new ConfirmUncollectItemDialogFragment(); } @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { return new AlertDialog.Builder(getActivity(), getTheme()) .setMessage(R.string.item_uncollect_confirm) .setPositiveButton(R.string.ok, (dialog, which) -> getListener().uncollect()) .setNegativeButton(R.string.cancel, null) .create(); } private Listener getListener() { return (Listener) getParentFragment(); } public static void show(Fragment fragment) { ConfirmUncollectItemDialogFragment.newInstance() .show(fragment.getChildFragmentManager(), null); } public interface Listener { void uncollect(); } }
29.230769
93
0.696053