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
fc6b0ce2a21c7324dc926cdf74e47c9fa6cae8b1
565
package org.springframework.jms.listener.adapter; import java.io.Serializable; import java.util.Map; import javax.jms.BytesMessage; import javax.jms.MapMessage; import javax.jms.ObjectMessage; import javax.jms.TextMessage; /** * See the MessageListenerAdapterTests class for usage. * * @author Rick Evans */ public interface ResponsiveMessageDelegate { String handleMessage(TextMessage message); Map<String, Object> handleMessage(MapMessage message); byte[] handleMessage(BytesMessage message); Serializable handleMessage(ObjectMessage message); }
20.178571
55
0.79646
18650c8165853c6db8bc82cf2cf3f3fa234e5459
538
package cn.org.hentai.simulator.web.entity; import org.springframework.stereotype.Component; import java.lang.annotation.*; /** * Created by matrixy when 2018-04-23. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Documented @Component public @interface Mapper { /** * The value may indicate a suggestion for a logical component when, * to be turned into a Spring bean in case of an autodetected component. * @return the suggested component when, if any */ String value() default ""; }
22.416667
76
0.719331
909cba3789341acd137f7a8644cfb441e737cab2
1,596
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.huawei.streaming.process.sort; import java.io.Serializable; import java.util.Comparator; import com.huawei.streaming.common.MultiKey; /** * <多值比较代理类> * */ public class ProxyComparator implements Comparator<Object>, Serializable { /** * 序列化ID */ private static final long serialVersionUID = -444751756877854804L; /** * 多值比较类对象 */ private final MultiKeyComparator comparator; /** * <默认构造函数> *@param comparator 多值比较器 */ public ProxyComparator(MultiKeyComparator comparator) { this.comparator = comparator; } /** * {@inheritDoc} */ @Override public int compare(Object o1, Object o2) { return comparator.compare((MultiKey)o1, (MultiKey)o2); } }
26.163934
75
0.68985
49493bc894af1fc1de87dee4fdffea0aa0131d2f
4,538
package com.sgcc.web.controller.sql; import com.sgcc.common.annotation.Log; import com.sgcc.common.core.controller.BaseController; import com.sgcc.common.core.domain.AjaxResult; import com.sgcc.common.core.page.TableDataInfo; import com.sgcc.common.enums.BusinessType; import com.sgcc.common.utils.poi.ExcelUtil; import com.sgcc.sql.domain.TotalQuestionTable; import com.sgcc.sql.service.ITotalQuestionTableService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; /** * 问题及命令Controller * * @author 韦亚宁 * @date 2021-12-14 */ @RestController @RequestMapping("/sql/total_question_table") public class TotalQuestionTableController extends BaseController { @Autowired private ITotalQuestionTableService totalQuestionTableService; public static List<Long> longList; /** * @method: 根据交换机信息查询 扫描问题的 命令ID * @Param: [] * @return: java.util.List<java.lang.Long> * @Author: 天幕顽主 * @E-mail: WeiYaNing97@163.com */ @GetMapping(value = "/commandIdByInformation") public List<Long> commandIdByInformation()//String brand,String type,String firewareVersion { TotalQuestionTable totalQuestionTable = new TotalQuestionTable(); /*totalQuestionTable.setBrand(brand); totalQuestionTable.setType(type); totalQuestionTable.setFirewareVersion(firewareVersion);*/ totalQuestionTable.setBrand(Global.deviceBrand); totalQuestionTable.setType(Global.deviceModel); totalQuestionTable.setFirewareVersion(Global.firmwareVersion); totalQuestionTable.setSubVersion(Global.subversionNumber); List<TotalQuestionTable> totalQuestionTables = totalQuestionTableService.selectTotalQuestionTableList(totalQuestionTable); if (totalQuestionTables!=null){ List<Long> longList = new ArrayList<>(); for (TotalQuestionTable pojo:totalQuestionTables){ longList.add(pojo.getCommandId()); } this.longList=longList; return longList; }else { return null; } } /** * 查询问题及命令列表 */ @PreAuthorize("@ss.hasPermi('sql:total_question_table:list')") @GetMapping("/list") public TableDataInfo list(TotalQuestionTable totalQuestionTable) { startPage(); List<TotalQuestionTable> list = totalQuestionTableService.selectTotalQuestionTableList(totalQuestionTable); return getDataTable(list); } /** * 导出问题及命令列表 */ @PreAuthorize("@ss.hasPermi('sql:total_question_table:export')") @Log(title = "问题及命令", businessType = BusinessType.EXPORT) @GetMapping("/export") public AjaxResult export(TotalQuestionTable totalQuestionTable) { List<TotalQuestionTable> list = totalQuestionTableService.selectTotalQuestionTableList(totalQuestionTable); ExcelUtil<TotalQuestionTable> util = new ExcelUtil<TotalQuestionTable>(TotalQuestionTable.class); return util.exportExcel(list, "问题及命令数据"); } /** * 获取问题及命令详细信息 */ @PreAuthorize("@ss.hasPermi('sql:total_question_table:query')") @GetMapping(value = "/{id}") public AjaxResult getInfo(@PathVariable("id") Long id) { return AjaxResult.success(totalQuestionTableService.selectTotalQuestionTableById(id)); } /** * 新增问题及命令 */ @PreAuthorize("@ss.hasPermi('sql:total_question_table:add')") @Log(title = "问题及命令", businessType = BusinessType.INSERT) @PostMapping public AjaxResult add(@RequestBody TotalQuestionTable totalQuestionTable) { return toAjax(totalQuestionTableService.insertTotalQuestionTable(totalQuestionTable)); } /** * 修改问题及命令 */ @PreAuthorize("@ss.hasPermi('sql:total_question_table:edit')") @Log(title = "问题及命令", businessType = BusinessType.UPDATE) @PutMapping public AjaxResult edit(@RequestBody TotalQuestionTable totalQuestionTable) { return toAjax(totalQuestionTableService.updateTotalQuestionTable(totalQuestionTable)); } /** * 删除问题及命令 */ @PreAuthorize("@ss.hasPermi('sql:total_question_table:remove')") @Log(title = "问题及命令", businessType = BusinessType.DELETE) @DeleteMapping("/{ids}") public AjaxResult remove(@PathVariable Long[] ids) { return toAjax(totalQuestionTableService.deleteTotalQuestionTableByIds(ids)); } }
34.641221
130
0.710004
d140d8ab41dc7959445c0813d7bd46b56929033e
3,188
// Copyright 2010 The Apache Software Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.apache.tapestry5.func; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Set; /** * An implementation of {@link Flow} for empty flows. This allows for some easy optimizations. * * @since 5.2.0 */ class EmptyFlow<T> extends AbstractFlow<T> { @Override public T first() { return null; } @Override public boolean isEmpty() { return true; } @Override public Flow<T> rest() { return this; } /** Does nothing; returns this empty list. */ @Override public Flow<T> each(Worker<? super T> worker) { return this; } /** Does nothing; returns this empty list. */ @Override public Flow<T> filter(Predicate<? super T> predicate) { return this; } /** Does nothing; returns this empty list. */ @Override public Flow<T> remove(Predicate<? super T> predicate) { return this; } /** Does nothing; returns this empty list (as a Flow<X>). */ @Override public <X> Flow<X> map(Mapper<T, X> mapper) { return F.emptyFlow(); } /** Does nothing; returns the initial value. */ @Override public <A> A reduce(Reducer<A, T> reducer, A initial) { return initial; } /** Does nothing; returns this empty list. */ @Override public Flow<T> reverse() { return this; } /** Does nothing; returns this empty list. */ @Override public Flow<T> sort() { return this; } /** Does nothing; returns this empty list. */ @Override public Flow<T> sort(Comparator<T> comparator) { return this; } /** Returns the empty list. */ @Override public List<T> toList() { return Collections.emptyList(); } /** Returns the other list (i.e. empty ++ other == other). */ @Override @SuppressWarnings("unchecked") public Flow<T> concat(Flow<? extends T> other) { return (Flow<T>) other; } @Override public <X> Flow<X> mapcat(Mapper<T, Flow<X>> mapper) { return F.emptyFlow(); } @Override public int count() { return 0; } @Override public Flow<T> take(int length) { return this; } @Override public Flow<T> drop(int length) { return this; } @Override public Set<T> toSet() { return Collections.emptySet(); } @Override public Flow<T> removeNulls() { return this; } }
20.701299
94
0.595358
10fff7599af482dc0d72d546f695ec8bcb7f09b1
1,814
package com.loror.lororUtil.http.api.chain; import com.loror.lororUtil.http.api.Observable; /** * Date: 2020/6/4 8:58 * Description: Create By Loror */ public class ObserverChain { private ObserverChain.Builder builder; public interface OnErrorCollection { void onError(Throwable throwable); } public interface OnComplete { void onComplete(); } public static class Builder { private OnErrorCollection onErrorCollection; private OnComplete onComplete; public Builder setOnErrorCollection(OnErrorCollection onErrorCollection) { this.onErrorCollection = onErrorCollection; return this; } public Builder setOnComplete(OnComplete onComplete) { this.onComplete = onComplete; return this; } protected OnComplete getOnComplete() { return onComplete; } protected OnErrorCollection getOnErrorCollection() { return onErrorCollection; } public ObserverChain build() { ObserverChain chain = new ObserverChain(); chain.builder = this; return chain; } } public <T> ChainNode<T> begin(Observable<T> observable) { return new ChainNode<T>(builder, observable); } private ChainNode<?> chainNode; public <T> ObserverChain add(Observable<T> observable, ChainNode.OnResult<T> onResult) { if (chainNode == null) { chainNode = new ChainNode<T>(builder, observable).onResult(onResult); } else { chainNode = chainNode.next(observable).onResult(onResult); } return this; } public void execute() { if (chainNode != null) { chainNode.load(); } } }
25.194444
92
0.612459
59f542c1ad28d6f98a6e74c0e751e175989413d2
652
package de.peteral.softplc.model; import javafx.collections.ObservableList; /** * This interface defines a symbol table of a CPU. * <p> * A symbol table translates symbolic names to physical addresses. * * @author peteral * */ public interface SymbolTable { /** * * @return observable list of all symbols - elements can be added, removed * and modified */ ObservableList<Symbol> getAllSymbols(); /** * Translates symbolic name to an address * * @param name * symbolic name * @return hardware address, null when symbol is not defined */ String getAddress(String name); }
21.733333
76
0.65184
27c0d7b0d5de5b4af465e6ba552255429c2c3b30
3,743
package com.thedeanda.util.convert; import com.thedeanda.util.convert.fileinfo.*; import org.junit.Before; import org.junit.Test; import java.io.File; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import static org.junit.Assert.*; public class TestFileInfo { private FileConverter fc; @Before public void setup() { fc = new FileConverter(); fc.setTempDir(new File("tmp")); } @Test public void testPlainText() throws InterruptedException, TimeoutException, ExecutionException { FileInfo fileInfo = null; File file = new File("src/test/resources/lorem.txt"); fileInfo = fc.readFileInfo(file).get(10, TimeUnit.SECONDS); assertNotNull(fileInfo); assertEquals(file, fileInfo.getFile()); TextFileInfo fi = (TextFileInfo) fileInfo; // TODO: finish } @Test public void testPng() throws InterruptedException, TimeoutException, ExecutionException { FileInfo fileInfo = null; File file = new File("src/test/resources/mini_r8_car.png"); fileInfo = fc.readFileInfo(file).get(10, TimeUnit.SECONDS); assertNotNull(fileInfo); assertTrue(fileInfo instanceof ImageFileInfo); assertEquals(file, fileInfo.getFile()); ImageFileInfo fi = (ImageFileInfo) fileInfo; assertEquals(400, fi.getWidth()); assertEquals(322, fi.getHeight()); assertEquals("png", fi.getThumbExtension()); assertEquals("png", fi.getExtension()); } @Test public void testJpg() throws InterruptedException, TimeoutException, ExecutionException { FileInfo fileInfo = null; File file = new File("src/test/resources/Baby-taco.jpg"); fileInfo = fc.readFileInfo(file).get(10, TimeUnit.SECONDS); assertNotNull(fileInfo); assertTrue(fileInfo instanceof ImageFileInfo); assertEquals(file, fileInfo.getFile()); ImageFileInfo fi = (ImageFileInfo) fileInfo; assertEquals(600, fi.getWidth()); assertEquals(703, fi.getHeight()); assertEquals("jpg", fi.getThumbExtension()); assertEquals("jpg", fi.getExtension()); } @Test public void testGif() throws InterruptedException, TimeoutException, ExecutionException { FileInfo fileInfo = null; File file = new File( "src/test/resources/0fd479da894756522251fc29f1af2bd1.gif"); fileInfo = fc.readFileInfo(file).get(10, TimeUnit.SECONDS); assertNotNull(fileInfo); assertTrue(fileInfo instanceof ImageFileInfo); assertEquals(file, fileInfo.getFile()); ImageFileInfo fi = (ImageFileInfo) fileInfo; assertEquals(506, fi.getWidth()); assertEquals(900, fi.getHeight()); assertEquals("gif", fi.getThumbExtension()); assertEquals("gif", fi.getExtension()); } @Test public void testMp3() throws InterruptedException, TimeoutException, ExecutionException { FileInfo fileInfo = null; File file = new File("src/test/resources/06-Radiohead-FaustArp.mp3"); fileInfo = fc.readFileInfo(file).get(10, TimeUnit.SECONDS); assertNotNull(fileInfo); assertTrue(fileInfo instanceof AudioFileInfo); assertEquals(file, fileInfo.getFile()); AudioFileInfo fi = (AudioFileInfo) fileInfo; assertEquals("mp3", fi.getExtension()); assertEquals(AudioEncoding.MP3, fi.getEncoding()); } @Test public void testOggVorbis() throws InterruptedException, TimeoutException, ExecutionException { FileInfo fileInfo = null; File file = new File("src/test/resources/Beck-DeadWildCat.ogg"); fileInfo = fc.readFileInfo(file).get(10, TimeUnit.SECONDS); assertNotNull(fileInfo); assertTrue(fileInfo instanceof AudioFileInfo); assertEquals(file, fileInfo.getFile()); AudioFileInfo fi = (AudioFileInfo) fileInfo; assertEquals("ogg", fi.getExtension()); assertEquals(AudioEncoding.VORBIS, fi.getEncoding()); } }
29.944
96
0.753139
d6ecd2e08d901603063af1dec7aa5d8ebec8e31f
3,329
package cn.miozus.gulimall.product.controller; import cn.miozus.gulimall.common.utils.R; import cn.miozus.gulimall.product.entity.BrandEntity; import cn.miozus.gulimall.product.entity.CategoryBrandRelationEntity; import cn.miozus.gulimall.product.service.CategoryBrandRelationService; import cn.miozus.gulimall.product.vo.BrandVo; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * 品牌分类关联 * * @author SuDongpo * @email miozus@outlook.com * @date 2021-08-06 23:57:18 */ @RestController @RequestMapping("product/categorybrandrelation") public class CategoryBrandRelationController { @Autowired private CategoryBrandRelationService categoryBrandRelationService; /** * 列表:当前品牌关联的所有分类列表 */ @GetMapping("/catalog/list") public R catalogList(@RequestParam("brandId") Long brandId) { List<CategoryBrandRelationEntity> data = categoryBrandRelationService.list( new QueryWrapper<CategoryBrandRelationEntity>().eq("brand_id", brandId) ); return R.ok().put("data", data); } /** * 品牌关系列表 * 职责分工(C 三句话) * Controller > Service > Controller * 处理请求,接受和校验数据 接收数据,业务处理 封装页面指定vo * * @param catId catId * @return {@link R} * @see R */ @GetMapping("/brands/list") public R relationBrandList(@RequestParam("catId") Long catId) { // 接收数据和数据校验 // 奇怪的设定:不直接从关联表查,非要做中转; 老师说为了方便其他人抄家(品牌表查全) // 传递给 Service List<BrandEntity> vos = categoryBrandRelationService.getBrandListByCatId(catId); // 封装页面指定Vo List<BrandVo> data = vos.stream().map(vo -> { // 品牌表:name 关联表:brandName 因此不是能做属性拷贝 BrandVo brandVo = new BrandVo(); brandVo.setBrandId(vo.getBrandId()); brandVo.setBrandName(vo.getName()); return brandVo; } ).collect(Collectors.toList()); return R.ok().put("data", data); } /** * 信息 */ @RequestMapping("/info/{id}") public R info(@PathVariable("id") Long id) { CategoryBrandRelationEntity categoryBrandRelation = categoryBrandRelationService.getById(id); return R.ok().put("categoryBrandRelation", categoryBrandRelation); } /** * 保存 */ @RequestMapping("/save") public R save(@RequestBody CategoryBrandRelationEntity categoryBrandRelation) { // 前端只传2个字段,未传入其他字段(冗余字段),所以不用原生方法 // 而且导致每次从其他表关联查询,性能影响大 // 电商系统的大表数据,从不做关联!哪怕一点一点查,也不用关联。 categoryBrandRelationService.saveDetails(categoryBrandRelation); return R.ok(); } /** * 修改 */ @RequestMapping("/update") public R update(@RequestBody CategoryBrandRelationEntity categoryBrandRelation) { categoryBrandRelationService.updateById(categoryBrandRelation); return R.ok(); } /** * 删除 */ @RequestMapping("/delete") public R delete(@RequestBody Long[] ids) { categoryBrandRelationService.removeByIds(Arrays.asList(ids)); return R.ok(); } }
29.201754
101
0.649444
350769dd77388a868791a8fc72d8bde265a64c3d
955
/****************************************************************************** * Copyright (C) 2019 Eric Pogue. * * This file and the Thunderbird application is licensed under the * BSD-3-Clause. * * You may use any part of the file as long as you give credit in your * source code. * * This application utilizes the HttpRequest.java library developed by * Eric Pogue * * Version: 1.3 *****************************************************************************/ // Modified from Original // Modifier: Nathin Wacher // Modified Version: 1.2 // Todo: Rename the following class to Thunderbird. // NW - Fully implemented. public class Thunderbird { public static void main(String[] args) { // Todo: Update the following line so that it reflects the name change to // Thunderbird. // NW - Fully implemented. System.out.println("Thunderbird Starting...\n"); new ThunderbirdFrame(); } }
29.84375
81
0.559162
56567eae6da9402705c2fa6ef72799dbc41e88a6
470
package utils.suites; import com.google.inject.Inject; import org.testng.TestNG; import java.util.ArrayList; import java.util.List; public class Runner { private final TestNG runner = new TestNG(); private final List<String> suiteFiles = new ArrayList<>(); @Inject public Runner() { } public void runSuite(String suiteFilePath) { suiteFiles.add(suiteFilePath); runner.setTestSuites(suiteFiles); runner.run(); } }
20.434783
62
0.680851
47450042e00c588c910ad0371a3bf963ae49299e
3,538
package main; import java.io.IOException; import java.nio.ByteBuffer; import java.util.*; import org.apache.cassandra.hadoop.ConfigHelper; import org.apache.cassandra.hadoop.cql3.CqlConfigHelper; import org.apache.cassandra.hadoop.cql3.CqlOutputFormat; import org.apache.cassandra.hadoop.cql3.CqlPagingInputFormat; import org.apache.cassandra.utils.ByteBufferUtil; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.log4j.BasicConfigurator; public class WordCountCassandra { public static class TokenizerMapper extends Mapper<Map<String, ByteBuffer>, Map<String, ByteBuffer>, Text, IntWritable> { private final static IntWritable one = new IntWritable(1); private Text word = new Text(); public void map(Map<String, ByteBuffer> keys, Map<String, ByteBuffer> columns, Context context ) throws IOException, InterruptedException { ByteBuffer agentBytes = columns.get("agent"); String agent = agentBytes == null ? "-" : ByteBufferUtil.string(agentBytes); word.set(agent); context.write(word, one); } } public static class IntSumReducer extends Reducer<Text, IntWritable, Map<String, ByteBuffer>, List<ByteBuffer>> { private IntWritable result = new IntWritable(); public void reduce(Text key, Iterable<IntWritable> values, Context context ) throws IOException, InterruptedException { int sum = 0; for (IntWritable val : values) { sum += val.get(); } result.set(sum); Map<String, ByteBuffer> keys = new LinkedHashMap<String, ByteBuffer>(); keys.put("name", ByteBufferUtil.bytes(key.toString())); List<ByteBuffer> variables = new ArrayList<ByteBuffer>(); variables.add(ByteBufferUtil.bytes(sum)); context.write(keys, variables); } } public static void main(String[] args) throws Exception { BasicConfigurator.configure(); Configuration conf = new Configuration(); Job job = Job.getInstance(conf, "word count cassandra"); job.setJarByClass(WordCountCassandra.class); job.setMapperClass(TokenizerMapper.class); job.setReducerClass(IntSumReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); ConfigHelper.setInputInitialAddress(job.getConfiguration(), "206.189.16.183"); ConfigHelper.setInputColumnFamily(job.getConfiguration(), "nyao", "visitors"); ConfigHelper.setInputPartitioner(job.getConfiguration(), "Murmur3Partitioner"); CqlConfigHelper.setInputCQLPageRowSize(job.getConfiguration(), "200"); job.setInputFormatClass(CqlPagingInputFormat.class); job.setOutputFormatClass(CqlOutputFormat.class); ConfigHelper.setOutputColumnFamily(job.getConfiguration(), "nyao", "count"); String query = "UPDATE count SET msg = ?"; CqlConfigHelper.setOutputCql(job.getConfiguration(), query); ConfigHelper.setOutputInitialAddress(job.getConfiguration(), "206.189.16.183"); ConfigHelper.setOutputPartitioner(job.getConfiguration(), "Murmur3Partitioner"); System.exit(job.waitForCompletion(true) ? 0 : 1); } }
41.623529
102
0.689373
d3fbf8f3645daff82595b3242a47b823669d0981
1,527
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.prelude.fastsearch.test.fs4mock; import com.yahoo.fs4.mplex.Backend; import com.yahoo.fs4.mplex.FS4Channel; /** * @author bratseth */ public class MockBackend extends Backend { private String hostname; private final long activeDocumentsInBackend; private final boolean working; /** Created lazily as we want to have just one but it depends on the channel */ private MockFSChannel channel = null; public MockBackend() { this("", 0L, true); } public MockBackend(String hostname, long activeDocumentsInBackend, boolean working) { super(); this.hostname = hostname; this.activeDocumentsInBackend = activeDocumentsInBackend; this.working = working; } @Override public FS4Channel openChannel() { if (channel == null) channel = working ? new MockFSChannel(activeDocumentsInBackend, this) : new NonWorkingMockFSChannel(this); return channel; } @Override public FS4Channel openPingChannel() { return openChannel(); } @Override public String getHost() { return hostname; } /** Returns the channel in use or null if no channel has been used yet */ public MockFSChannel getChannel() { return channel; } public void shutdown() {} @Override public boolean probeConnection() { return working; } }
28.277778
118
0.671906
6d57285d02ce3ecb4c76448c3b56607ef20015cb
1,499
package com.woshidaniu.socket.code; import java.nio.charset.Charset; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.CumulativeProtocolDecoder; import org.apache.mina.filter.codec.ProtocolDecoderOutput; public class DataDecoder extends CumulativeProtocolDecoder{ Charset charset =null; IoBuffer buf = IoBuffer.allocate(100).setAutoExpand(true); public DataDecoder(String encoding){ charset = Charset.forName(encoding); } @Override public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput output) throws Exception { while(in.hasRemaining()){ byte b = in.get(); if(b == '\n'){ buf.flip(); byte[] bytes = new byte[buf.limit()]; buf.get(bytes); String message = new String(bytes,charset); buf = IoBuffer.allocate(100).setAutoExpand(true); output.write(message); }else{ buf.put(b); } } } @Override public void dispose(IoSession arg0) throws Exception { } @Override public void finishDecode(IoSession arg0, ProtocolDecoderOutput arg1) throws Exception { } @Override protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception { return false; } }
26.767857
84
0.621081
24d3e30ed0cc997896669be15ac764b6b8e8ff0c
888
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See the LICENSE file in the project root for full license information. package com.microsoft.store.partnercenter.customers.servicecosts; import com.microsoft.store.partnercenter.IPartnerComponent; import com.microsoft.store.partnercenter.genericoperations.IEntityGetOperations; import com.microsoft.store.partnercenter.models.servicecosts.ServiceCostsSummary; import com.microsoft.store.partnercenter.models.utils.Tuple; /** * Holds the operations related to a customer's service costs. */ public interface IServiceCostSummary extends IPartnerComponent<Tuple<String, String>>, IEntityGetOperations<ServiceCostsSummary> { /** * Retrieves the customer's service cost summary. * * @return The customer's service cost summary. */ ServiceCostsSummary get(); }
38.608696
105
0.788288
bf039e2ce4993a2ddebe84bd4cfb61d21d2f6447
10,960
package com.cy.controller; import com.cy.bean.*; import com.cy.biz.AlarmService; import com.cy.biz.PhamacyService; import com.github.pagehelper.PageInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.stereotype.Repository; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @Controller @RequestMapping("/alarm") public class AlarmController { private Map<String,Object> map = new HashMap<>(); @Autowired private AlarmService alarmService; @Autowired private AlarmStyle alarmStyle; @Autowired private Alarm alarm; //药品低限查询 @RequestMapping("/alarmAllDrugs") @ResponseBody public Map<String, Object> alarmNumAllDrugsDrugs(HttpServletRequest request,String num ,String adminName){ Map<String,Object>alarmPage =new HashMap<String,Object>(); //查询低限数量药品 List<PhamacyDrug> alarmPhamacyNumList = alarmService.selectAlarmNum(map); if(alarmPhamacyNumList.size()!=0){ Admin loginAdminList = alarmService.selectRoleName(adminName); //报警类型添加数据 Alarm alarm4 = new Alarm(); alarm4.setAlarmRole(loginAdminList.getAdminRoleId()); alarm4.setAlarmStyleId(1); alarm4.setAlarmDetails("药品数量已低于限制"); Boolean flag1 = alarmService.addAlarm(alarm4); if(flag1) { System.out.println("添加低限报警表成功"); alarmPage.put("numTrue", true); return alarmPage; }else { return alarmPage; } }else{ alarmPage.put("numFalse",false); return alarmPage; } } //药库药品低限查询 @RequestMapping("/alarmDrugStroe") @ResponseBody public Map<String, Object> alarmDrugStroe(HttpServletRequest request,String num ,String adminName){ Map<String,Object>alarmPage =new HashMap<String,Object>(); //查询低限数量药品 List<DrugStore> alarmPhamacyNumList = alarmService.selectDrugStoreNum(map); if(alarmPhamacyNumList.size()!=0){ Admin loginAdminList = alarmService.selectRoleName(adminName); //报警类型添加数据 Alarm alarm4 = new Alarm(); alarm4.setAlarmRole(loginAdminList.getAdminRoleId()); alarm4.setAlarmStyleId(1); alarm4.setAlarmDetails("药品数量已低于限制"); Boolean flag1 = alarmService.addAlarm(alarm4); if(flag1) { System.out.println("添加药库低限报警成功"); alarmPage.put("storeSuss", true); return alarmPage; }else { return alarmPage; } }else{ alarmPage.put("storeFalse",false); return alarmPage; } } //药品过期报警 @RequestMapping("/alarmPhamacyDate") @ResponseBody public Map<String, Object> alarmPhamacyDate(HttpServletRequest request,String num ,String adminName){ Map<String,Object>alarmPhamacyDatePage =new HashMap<String,Object>(); //分页查询低限数量药品 List<PhamacyDrug> alarmPhamacyDateList = alarmService.selectAlarmExpired(map); if(alarmPhamacyDateList.size()!=0){ Admin loginAdminList = alarmService.selectRoleName(adminName); //报警类型添加数据 Alarm alarm3 = new Alarm(); alarm3.setAlarmRole(loginAdminList.getAdminRoleId()); alarm3.setAlarmStyleId(3); alarm3.setAlarmDetails("药品日期已过期"); Boolean flag2 = alarmService.addAlarm(alarm3); if(flag2) { System.out.println("添加过期报警表成功"); alarmPhamacyDatePage.put("dateTrue", true); return alarmPhamacyDatePage; }else { return alarmPhamacyDatePage; } }else{ alarmPhamacyDatePage.put("dateFalse",false); return alarmPhamacyDatePage; } } //药品滞销报警 @RequestMapping("/alarmUnsalable") @ResponseBody public Map<String, Object> alarmUnsalable(HttpServletRequest request,String num ,String adminName){ Map<String,Object>alarmUnsalablePage =new HashMap<String,Object>(); List<PhamacyDrug> alarmUnsalable = alarmService.selectAlarmUnsalable(map); if(alarmUnsalable.size()!=0){ Admin loginAdminList = alarmService.selectRoleName(adminName); //报警类型添加数据 Alarm alarm2 = new Alarm(); alarm2.setAlarmRole(loginAdminList.getAdminRoleId()); alarm2.setAlarmStyleId(2); alarm2.setAlarmDetails("药品超过一个月未售出"); Boolean flag3 = alarmService.addAlarm(alarm2); if(flag3) { System.out.println("添加滞销报警表成功"); alarmUnsalablePage.put("usalable", true); return alarmUnsalablePage; }else { return alarmUnsalablePage; } }else{ alarmUnsalablePage.put("usalablefailure",false); return alarmUnsalablePage; } } //显示警报消息 @RequestMapping("/alarmAllList") public String alarmAllList(HttpServletRequest request,String pageNum,String alarmRole){ //分页查询报警数据 PageInfo drugpage = alarmService.selectAlarmListPageInfo(map, pageNum, 5, alarmRole); if (drugpage != null) { List<AlarmStyle> alarmStyleShow = alarmService.selectAllStyle(); request.setAttribute("alarmStyleShowList", alarmStyleShow); request.setAttribute("alarmRole", alarmRole); HttpSession session = request.getSession(); session.setAttribute("alarmRoleList", alarmRole); session.setAttribute("alarmPageList", drugpage); if(alarmRole.contains("4")|| alarmRole.contains("5")){ return "/pharmacyPage/alarmAllListStroe"; }else { return "/pharmacyPage/alarmAllList"; } } else { return "error"; } } //药品信息提示 @RequestMapping("/alarmManage") public String alarmManage(HttpServletRequest request,int alarmId,int alarmStyleId,String alarmRole,String pageNum){ //药品低限数据 if(alarmRole.contains("4")|| alarmRole.contains("5")){ PageInfo alarmNumPageInfo = alarmService.selectDrugStorePageInfo(map, pageNum, 5); request.setAttribute("alarmStyleIdList", alarmStyleId); request.setAttribute("alarmIdList", alarmId); request.setAttribute("alarmRole", alarmRole); request.setAttribute("alarmManageList", alarmNumPageInfo); return "pharmacyPage/alarmStroe"; } else { if (alarmStyleId == 1) { PageInfo alarmNumPageInfo = alarmService.selectAlarmNumPageInfo(map, pageNum, 5); request.setAttribute("alarmStyleIdList", alarmStyleId); request.setAttribute("alarmIdList", alarmId); request.setAttribute("alarmRole", alarmRole); request.setAttribute("alarmManageList", alarmNumPageInfo); return "pharmacyPage/alarmManage"; } //药品滞销数据 else if (alarmStyleId == 2) { PageInfo alarmNumPageInfo = alarmService.selectAlarmUnsalablePageInfo(map, pageNum, 5); request.setAttribute("alarmStyleIdList", alarmStyleId); request.setAttribute("alarmIdList", alarmId); request.setAttribute("alarmRole", alarmRole); request.setAttribute("alarmManageList", alarmNumPageInfo); return "pharmacyPage/alarmUnsalable"; } //药品日期数据 else if (alarmStyleId == 3) { PageInfo alarmNumPageInfo = alarmService.selectAlarmExpiredPageInfo(map, pageNum, 5); request.setAttribute("alarmStyleIdList", alarmStyleId); request.setAttribute("alarmIdList", alarmId); request.setAttribute("alarmRole", alarmRole); request.setAttribute("alarmManageList", alarmNumPageInfo); return "pharmacyPage/alarmManageDate"; } else { return "pharmacyPage/alarmManage"; } } } //显示警报提示 @RequestMapping("/alarmTable") public String alarmTable(){ return "/pharmacyPage/alarmTable"; } //更改报警信息状态 @RequestMapping("/alarmSeeDetails") public String alarmSeeDetails(HttpServletRequest request,String pageNum,int alarmId,String alarmRole){ alarmService.seeDetails(alarmId); PageInfo drugpage = alarmService.selectAlarmListPageInfo(map,pageNum,5,alarmRole); System.out.println(pageNum); if(drugpage!=null) { List<AlarmStyle> alarmStyleShow = alarmService.selectAllStyle(); request.setAttribute("alarmStyleShowList",alarmStyleShow); request.setAttribute("alarmRole",alarmRole); HttpSession session = request.getSession(); session.setAttribute("alarmPageList", drugpage); if(alarmRole.contains("4")|| alarmRole.contains("5")){ return "/pharmacyPage/alarmAllListStroe"; } return "/pharmacyPage/alarmAllList"; } else { return "error"; } } //显示警报类型 @RequestMapping("/alarmStyleShow") public String alarmStyleShow(HttpServletRequest request){ List<AlarmStyle> alarmStyleShow = alarmService.selectAllStyle(); request.setAttribute("alarmStyleShowList",alarmStyleShow); return "/pharmacyPage/alarmAllList"; } //ajax 返回页面报警信息 @RequestMapping("/alarmStyleShowList") public String alarmStyleShowList(HttpServletRequest request,String pageNum,String alarmStyleId,String alarmRole){ System.out.println("alarmRole"+alarmRole); //分页查询报警数据 PageInfo drugpage = alarmService.selectAlarmStyleListPageInfo(map,pageNum,5,alarmStyleId); if(drugpage!=null) { List<AlarmStyle> alarmStyleShow = alarmService.selectAllStyle(); request.setAttribute("alarmStyleShowList",alarmStyleShow); request.setAttribute("alarmRole",alarmRole); request.setAttribute("alarmStyleId",alarmStyleId); request.setAttribute("alarmPageList", drugpage); //request.setAttribute("alarmServiceShowList",drugpage); return "/pharmacyPage/alarmAllListStyle"; } else { return "error"; } } public Map<String, Object> getMap() { return map; } public void setMap(Map<String, Object> map) { this.map = map; } }
40.14652
119
0.628558
6d1bd87fb8226f666777356de805c2bf43c7bcfc
4,334
package tests.service; import android.content.Context; import androidx.test.platform.app.InstrumentationRegistry; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.nio.charset.Charset; import java.util.Arrays; import java.util.List; import java.util.UUID; import helper.CompressionHelper; import helper.FileHelper; import io.split.android.client.utils.Base64Util; import io.split.android.client.utils.CompressionUtil; import io.split.android.client.utils.Gzip; import io.split.android.client.utils.StringHelper; import io.split.android.client.utils.Zlib; public class CompressionTest { CompressionUtil zlib; CompressionUtil gzip; CompressionHelper helper; Context mContext; @Before public void setup() { mContext = InstrumentationRegistry.getInstrumentation().getContext(); zlib = new Zlib(); gzip = new Gzip(); helper = new CompressionHelper(); } @Test public void zlibBasicDecompress() { String toComp = "0123456789_0123456789"; byte[] compressed = helper.compressZlib(toComp.getBytes(StringHelper.defaultCharset())); byte[] dec = zlib.decompress(compressed); Assert.assertEquals(toComp, new String(dec, 0, dec.length)); } @Test public void zlibManyDecompress() { for(int i = 0; i < 20; i++) { String toComp = generateString(); byte[] compressed = helper.compressZlib(toComp.getBytes(StringHelper.defaultCharset())); byte[] dec = zlib.decompress(compressed); Assert.assertEquals(toComp, new String(dec, 0, dec.length)); } } @Test public void zlibLoremIpsum() { List<String> params = loadFileContent(); for(String p : params) { byte[] compressed = helper.compressZlib(p.getBytes(StringHelper.defaultCharset())); byte[] dec = zlib.decompress(compressed); Assert.assertEquals(p, new String(dec, 0, dec.length)); } } @Test public void zlibBase64Decompression() { for(int i = 0; i < 20; i++) { String toComp = Base64Util.encode(generateString()); byte[] compressed = helper.compressZlib(toComp.getBytes(StringHelper.defaultCharset())); byte[] dec = zlib.decompress(compressed); Assert.assertEquals(toComp, new String(dec, 0, dec.length)); } } @Test public void gzipBasicDecompress() { String toComp = "0123456789_0123456789"; byte[] compressed = helper.compressGzip(toComp.getBytes(StringHelper.defaultCharset())); byte[] dec = gzip.decompress(compressed); Assert.assertEquals(toComp, new String(dec, 0, dec.length)); } @Test public void gzipManyDecompress() { for(int i = 0; i < 20; i++) { String toComp = generateString(); byte[] compressed = helper.compressGzip(toComp.getBytes(StringHelper.defaultCharset())); byte[] dec = gzip.decompress(compressed); Assert.assertEquals(toComp, new String(dec, 0, dec.length)); } } @Test public void gzipLoremIpsum() { List<String> params = loadFileContent(); for(String p : params) { byte[] compressed = helper.compressGzip(p.getBytes(StringHelper.defaultCharset())); byte[] dec = gzip.decompress(compressed); Assert.assertEquals(p, new String(dec, 0, dec.length)); } } @Test public void gzipBase64Decompression() { for(int i = 0; i < 20; i++) { String toComp = Base64Util.encode(generateString()); byte[] compressed = helper.compressGzip(toComp.getBytes(StringHelper.defaultCharset())); byte[] dec = gzip.decompress(compressed); Assert.assertEquals(toComp, new String(dec, 0, dec.length)); } } private String generateString() { StringBuilder str = new StringBuilder(); for(int i = 0; i < 20; i++) { str.append(UUID.randomUUID()); } return str.toString(); } private List<String> loadFileContent() { FileHelper fileHelper = new FileHelper(); String content = fileHelper.loadFileContent(mContext, "lorem_ipsum.txt"); return Arrays.asList(content.split("\n")); } }
33.083969
100
0.637517
9ae31336a04b8bdbf54ceb956fbbf6e23de92a83
14,221
package com.kiyasul.android.fiftyx; import android.os.Handler; import android.util.Log; import com.google.android.things.pio.I2cDevice; import com.google.android.things.pio.PeripheralManagerService; import java.io.IOException; /** * Created by kiyasul on 02/01/18. */ public class I2cRpi3ToPic implements Runnable{ private static final String TAG = "SingletonClass"; private static final int POLLING_DELAY_DEFAULT = 2000; // Default Polling Freq. private static volatile I2cRpi3ToPic i2cInstance = null; private I2cDevice mI2cToPicDevice; private Handler mHandler; // Polling Delay private boolean mEnabled; // I2C Device Bus Name private static final String I2C_DEVICE_NAME = "I2C1"; // I2C Slave Address private static final int I2C_ADDRESS = 0x08; /** * PWM Address Registers in PIC */ private static final int PWM3_ADDRESS = 0x00; private static final int PWM4_ADDRESS = 0x01; private static final int PWM5_ADDRESS = 0x02; private static final int PWM6_ADDRESS = 0x03; /** * DAC Address Registers in PIC */ private static final int DAC1_ADDRESS = 0x04; /** * ADC Address Registers in PIC */ private static final int ADA5_ADDRESS = 0x05; private static final int ADC3_ADDRESS = 0x07; private static final int ADC4_ADDRESS = 0x09; private static final int ADC5_ADDRESS = 0x0b; // ## Internal Temp Tested Successfully ## // // private static final int ADC_TEMP_DIE = 0x0d; /** * Firebase reference */ DatabaseReference Firebase = FirebaseDatabase.getInstance().getReference(); DatabaseReference mADA5 = null; DatabaseReference mADC3 = null; DatabaseReference mADC4 = null; DatabaseReference mADC5 = null; /** * Converted Values from the ADC Channels (Byte to Int) */ private int adcA5 ; private int adcC3 ; private int adcC4 ; private int adcC5 ; /** * Analog Channel to which TMP36 sensor is connected */ private int TMP36_CHANNEL; private float TMP36_VALUE; // Private Constructor private I2cRpi3ToPic() { //Prevent form the reflection api. if (i2cInstance != null){ throw new RuntimeException("Use getI2cInstance() method to get the single instance of this class."); } mHandler = new Handler(); } public static I2cRpi3ToPic getI2cInstance() { //If there is no instance available... create new one if (i2cInstance == null) { synchronized (I2cRpi3ToPic.class) { if (i2cInstance == null) i2cInstance = new I2cRpi3ToPic(); } } return i2cInstance; } /** * Setup Firebase Reference for this class * Only ADC references from Firebase */ public void setupFirebaseADCReferences(String ADA5IN, String ADC3IN, String ADC4IN, String ADC5IN, int TMP36IN){ mADA5 = Firebase.child(ADA5IN.trim()); mADC3 = Firebase.child(ADC3IN.trim()); mADC4 = Firebase.child(ADC4IN.trim()); mADC5 = Firebase.child(ADC5IN.trim()); TMP36_CHANNEL = (TMP36IN >= 1 && TMP36IN <= 4) ? TMP36IN : 1; } /** * I2C Connection to PIC is established */ public void connectToPic() { PeripheralManagerService manager = new PeripheralManagerService(); try { mI2cToPicDevice = manager.openI2cDevice(I2C_DEVICE_NAME,I2C_ADDRESS); } catch (IOException e) { e.printStackTrace(); } } /** * Disconnects the Bus from PIC */ public void DisconnectFromPic() { if(mI2cToPicDevice != null){ try{ mI2cToPicDevice.close(); mI2cToPicDevice = null; } catch (IOException e){ e.printStackTrace(); } } } /** * * @param dutycycle - dutycycle of the PWM3 pin in the PIC * @throws IOException */ public void setPWM3DutyCycle(int dutycycle) throws IOException { Log.w(TAG,"Green inside"); setPWM3DutyCycle(mI2cToPicDevice,PWM3_ADDRESS,dutycycle); } /** * * @param dutycycle - dutycycle of the PWM4 pin in the PIC * @throws IOException */ public void setPWM4DutyCycle(int dutycycle) throws IOException { setPWM4DutyCycle(mI2cToPicDevice,PWM4_ADDRESS,dutycycle); } /** * * @param dutycycle - dutycycle of the PWM5 pin in the PIC * @throws IOException */ public void setPWM5DutyCycle(int dutycycle) throws IOException { setPWM5DutyCycle(mI2cToPicDevice,PWM5_ADDRESS,dutycycle); } /** * * @param dutycycle - dutycycle of the PWM6 pin in the PIC * @throws IOException */ public void setPWM6DutyCycle(int dutycycle) throws IOException { setPWM6DutyCycle(mI2cToPicDevice,PWM6_ADDRESS,dutycycle); } /** * * @param dac1OutputValue - 5-bit resolution DAC * @throws IOException */ public void setDAC1OutputValue(int dac1OutputValue) throws IOException { setDAC1OutputValue(mI2cToPicDevice,DAC1_ADDRESS,dac1OutputValue); Log.w(TAG,"DAC Value going to change"); } public int readA2DChannelA5()throws IOException { adcA5 = readA2DChannelA5(mI2cToPicDevice,ADA5_ADDRESS ); return adcA5; } public int readA2DChannelC3()throws IOException { adcC3 = readA2DChannelC3(mI2cToPicDevice,ADC3_ADDRESS ); return adcC3; } public int readA2DChannelC4() throws IOException { adcC4 = readA2DChannelC4(mI2cToPicDevice,ADC4_ADDRESS ); return adcC4; } public int readA2DChannelC5() throws IOException { adcC5 = readA2DChannelC5(mI2cToPicDevice,ADC5_ADDRESS ); return adcC5; } /** * * @param device - I2C device object reference * @param address - Write value to this register in PIC * @param dutycycle - PWM3 pin dutycycle * @throws IOException */ private void setPWM3DutyCycle(I2cDevice device, int address, int dutycycle) throws IOException { Log.w(TAG,"Green byte sent..."); dutycycle = dutyCycleBoundaryCheck(dutycycle); byte value = (byte) dutycycle; // Write the dutycycle value to slave device.writeRegByte(address, value); } /** * * @param device - I2C device object reference * @param address - Write value to this register in PIC * @param dutycycle - PWM4 pin dutycycle * @throws IOException */ private void setPWM4DutyCycle(I2cDevice device, int address, int dutycycle) throws IOException { dutycycle = dutyCycleBoundaryCheck(dutycycle); byte value = (byte) dutycycle; // Write the dutycycle value to slave device.writeRegByte(address, value); } /** * * @param device - I2C device object reference * @param address - Write value to this register in PIC * @param dutycycle - PWM5 pin dutycycle * @throws IOException */ private void setPWM5DutyCycle(I2cDevice device, int address, int dutycycle) throws IOException { dutycycle = dutyCycleBoundaryCheck(dutycycle); byte value = (byte) dutycycle; // Write the dutycycle value to slave device.writeRegByte(address, value); } /** * * @param device - I2C device object reference * @param address - Write value to this register in PIC * @param dutycycle - PWM6 pin dutycycle * @throws IOException */ private void setPWM6DutyCycle(I2cDevice device, int address, int dutycycle) throws IOException { dutycycle = dutyCycleBoundaryCheck(dutycycle); byte value = (byte) dutycycle; // Write the dutycycle value to slave device.writeRegByte(address, value); } /** * * @param device - I2C device object reference * @param address - Write value to this register in PIC * @param dac1OutputValue - 5-bit resolution analog output * @throws IOException */ private void setDAC1OutputValue(I2cDevice device, int address, int dac1OutputValue) throws IOException { dac1OutputValue = DAC1OutputBoundaryCheck(dac1OutputValue); byte value = (byte) dac1OutputValue; Log.w(TAG,"DAC Value byte written"); // Write the Analog Output Voltage Equivalent Value device.writeRegByte(address, value); } private int readA2DChannelA5(I2cDevice device, int startAddress)throws IOException { // Read three consecutive register values byte[] data = new byte[2]; device.readRegBuffer(startAddress, data, data.length); return byteToInt(data); } private int readA2DChannelC3(I2cDevice device, int startAddress)throws IOException { // Read three consecutive register values byte[] data = new byte[2]; device.readRegBuffer(startAddress, data, data.length); return byteToInt(data); } private int readA2DChannelC4(I2cDevice device, int startAddress) throws IOException { // Read three consecutive register values byte[] data = new byte[2]; device.readRegBuffer(startAddress, data, data.length); return byteToInt(data); } private int readA2DChannelC5(I2cDevice device, int startAddress) throws IOException { // Read three consecutive register values byte[] data = new byte[2]; device.readRegBuffer(startAddress, data, data.length); return byteToInt(data); } /** * * @param dutycycle - Exception inputs from user * @return - modified dutycycle if boundary conditions met */ private int dutyCycleBoundaryCheck(int dutycycle) { if(dutycycle > 100) { dutycycle = 100; } else if(dutycycle < 0) { dutycycle = 0; } return dutycycle; } /** * * @param dac1OutputValue - Exception inputs from user * @return - modified dac output if boundary conditions met */ private int DAC1OutputBoundaryCheck(int dac1OutputValue) { if(dac1OutputValue > 31) { dac1OutputValue = 31; } else if(dac1OutputValue < 0) { dac1OutputValue = 0; } return dac1OutputValue; } /** * * @param byte_value - byte value from the I2C read api * @return - byte value converted to int */ private int byteToInt(byte[] byte_value){ return ((byte_value[1] & 0xff) << 8) | (byte_value[0] & 0xff); } /* Handler Controls */ /** * Start Routine */ public void threadUpdateADC() { if(mHandler != null) { mEnabled = true; mHandler.postDelayed(this, POLLING_DELAY_DEFAULT); } } /** * call on destroy() method - for best practices */ public void stopADCThread(){ if(mHandler != null){ mEnabled = false; } } /** * Thread kicks off */ @Override public void run() { if(!mEnabled) return; try { readA2DChannelA5(); readA2DChannelC3(); readA2DChannelC4(); readA2DChannelC5(); } catch (IOException e) { e.printStackTrace(); } // Loop program loop(); } private void loop(){ calibrateAndUpdateFirebase(); // handler to loop in the specified delay mHandler.postDelayed(this, POLLING_DELAY_DEFAULT); } /** * Case statements based on the selection of the TMP36 analog channel */ private void calibrateAndUpdateFirebase() { switch (TMP36_CHANNEL){ case 1: TMP36_VALUE = calibrateTMP36(adcA5); mADA5.setValue(TMP36_VALUE); mADC3.setValue(adcC3); mADC4.setValue(adcC4); mADC5.setValue(adcC5); logDebugADC(); break; case 2: TMP36_VALUE = calibrateTMP36(adcC3); mADA5.setValue(adcA5); mADC3.setValue(TMP36_VALUE); mADC4.setValue(adcC4); mADC5.setValue(adcC5); logDebugADC(); break; case 3: TMP36_VALUE = calibrateTMP36(adcC4); mADA5.setValue(adcA5); mADC3.setValue(adcC3); mADC4.setValue(TMP36_VALUE); mADC5.setValue(adcC5); logDebugADC(); break; case 4: TMP36_VALUE = calibrateTMP36(adcC5); mADA5.setValue(adcA5); mADC3.setValue(adcC3); mADC4.setValue(adcC4); mADC5.setValue(TMP36_VALUE); logDebugADC(); break; default: TMP36_VALUE = calibrateTMP36(adcA5); mADA5.setValue(TMP36_VALUE); mADC3.setValue(adcC3); mADC4.setValue(adcC4); mADC5.setValue(adcC5); logDebugADC(); } } /** * * @param adc_value - uncalibrated TMP36 adc_value * @return - calibrated value in float (°C) * * Temperature (in °C) = ( ( ( (ADC_VALUE) * (FVR / 1024) ) - 500 ) / 10 ) * SETUP FVR = 2.048 V * MEASURED FVR = 1.98 V * ADC_VALUE - raw adc value from PIC */ private float calibrateTMP36(int adc_value){ return (float) (((adc_value * 1.933) - 500 ) / 10); } private void logDebugADC(){ Log.d(TAG,"ADC A5 = " + String.valueOf(adcA5)); Log.d(TAG,"ADC C3 = " + String.valueOf(adcC3)); Log.d(TAG,"ADC C3 = " + String.valueOf(adcC4)); Log.d(TAG,"ADC C3 = " + String.valueOf(adcC5)); } /** * Getters * @return - adc values */ public int getAdcA5(){ return adcA5; } public int getAdc3() { return adcC3; } public int getAdc4() { return adcC4; } public int getAdc5() { return adcC5; } }
27.560078
116
0.601786
2b4006257303c44b2183b2a561089493c50044ee
418
package cn.iflyapi.design.pattern.factory.entity; /** * @author: flyhero * @date: 2018-07-28 上午10:24 */ public class XiaoMiPhone extends Phone { public XiaoMiPhone() { name = "小米"; price = 1599d; } @Override public void brand() { System.out.println("品牌:" + name + " 价格:" + price); } @Override public void run() { System.out.println("开启小米手机"); } }
17.416667
58
0.562201
faff9fbe5816608ba1be89b5a5eafac20a5892d8
545
package org.kyojo.schemaorg.m3n3.doma.core.clazz; import org.seasar.doma.ExternalDomain; import org.seasar.doma.jdbc.domain.DomainConverter; import org.kyojo.schemaorg.m3n3.core.impl.CITY_HALL; import org.kyojo.schemaorg.m3n3.core.Clazz.CityHall; @ExternalDomain public class CityHallConverter implements DomainConverter<CityHall, String> { @Override public String fromDomainToValue(CityHall domain) { return domain.getNativeValue(); } @Override public CityHall fromValueToDomain(String value) { return new CITY_HALL(value); } }
23.695652
77
0.801835
5249077540fe0b657fc97a7da59c4b827243548f
1,931
/* * Copyright 2012-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.uengine.zuul.ratelimit.support; import org.apache.commons.lang.StringUtils; import org.uengine.zuul.ratelimit.config.RateLimitKeyGenerator; import org.uengine.zuul.ratelimit.config.RateLimitUtils; import org.uengine.zuul.ratelimit.config.properties.RateLimitProperties; import org.uengine.zuul.ratelimit.config.properties.RateLimitProperties.Policy; import lombok.RequiredArgsConstructor; import org.springframework.cloud.netflix.zuul.filters.Route; import javax.servlet.http.HttpServletRequest; import java.util.StringJoiner; @RequiredArgsConstructor public class DefaultRateLimitKeyGenerator implements RateLimitKeyGenerator { private final RateLimitProperties properties; private final RateLimitUtils rateLimitUtils; @Override public String key(final HttpServletRequest request, final Route route, final Policy policy) { final StringJoiner joiner = new StringJoiner(":"); joiner.add(properties.getKeyPrefix()); if (route != null) { joiner.add(route.getId()); } policy.getType().forEach(matchType -> { String key = matchType.key(request, route, rateLimitUtils); if (StringUtils.isNotEmpty(key)) { joiner.add(key); } }); return joiner.toString(); } }
37.134615
97
0.733817
b97d88a7465247ff3f6ce9c49e5d659792b4ab2a
2,511
/* * 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.asterix.api.http.server; import static org.apache.asterix.api.http.server.ServletConstants.RESULTSET_ATTR; import java.util.List; import java.util.Map; import org.apache.asterix.app.result.ResultReader; import org.apache.asterix.common.api.IApplicationContext; import org.apache.asterix.common.metadata.DataverseName; import org.apache.hyracks.api.client.IHyracksClientConnection; import org.apache.hyracks.api.result.IResultSet; import org.apache.hyracks.client.result.ResultSet; import org.apache.hyracks.http.api.IServletRequest; public class ServletUtil { static IResultSet getResultSet(IHyracksClientConnection hcc, IApplicationContext appCtx, final Map<String, Object> ctx) throws Exception { IResultSet resultSet = (IResultSet) ctx.get(RESULTSET_ATTR); if (resultSet == null) { synchronized (ctx) { resultSet = (IResultSet) ctx.get(RESULTSET_ATTR); if (resultSet == null) { resultSet = new ResultSet(hcc, appCtx.getServiceContext().getControllerService().getNetworkSecurityManager() .getSocketChannelFactory(), appCtx.getCompilerProperties().getFrameSize(), ResultReader.NUM_READERS); ctx.put(RESULTSET_ATTR, resultSet); } } } return resultSet; } public static DataverseName getDataverseName(IServletRequest request, String dataverseParameterName) { List<String> values = request.getParameterValues(dataverseParameterName); return !values.isEmpty() ? DataverseName.create(values) : null; } }
43.293103
106
0.704898
7fce7ef420afb9ebc36e1f5547fde89b6cd4e3d0
1,430
package me.yokeyword.sample.demo_zhihu.ui.fragment.second; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import me.yokeyword.sample.R; import me.yokeyword.sample.demo_zhihu.base.BaseLazyMainFragment; import me.yokeyword.sample.demo_zhihu.ui.fragment.second.child.ViewPagerFragment; /** * Created by YoKeyword on 16/6/3. */ public class ZhihuSecondFragment extends BaseLazyMainFragment { public static ZhihuSecondFragment newInstance() { Bundle args = new Bundle(); ZhihuSecondFragment fragment = new ZhihuSecondFragment(); fragment.setArguments(args); return fragment; } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.zhihu_fragment_second, container, false); initView(savedInstanceState); return view; } private void initView(Bundle savedInstanceState) { if (savedInstanceState == null) { loadRootFragment(R.id.fl_second_container, ViewPagerFragment.newInstance()); } } @Override protected void initLazyView(@Nullable Bundle savedInstanceState) { // 这里可以不用懒加载,因为Adapter的场景下,Adapter内的子Fragment只有在父Fragment是show状态时,才会被Attach,Create } }
31.086957
123
0.741259
f8692b5c7d90f83e05bbb98853024b637516c67e
3,050
/** Challenge Activity 3 - Simple English to Yoda translator. * * This activity will translate an English sentence (of up to 4 words) into * Yoda-Speak https://en.wikipedia.org/wiki/Yoda * * The rules behind Yoda-Speak are complicated so in this version we've * simplified them to these 4 cases: * 1 word sentence = same * 2 word sentence = swap words * 3 word sentence = place last word in the beginning of the sentence * 4 work sentence = exchange the first two words with the last two words * * Your goal is to implement the English2Yoda() method in this program by taking * the array of words and placing them in the proper order depending on the * number of words in the sentence. * * SAMPLE RUN: * * ---=== English-Yoda Translator 1.0 ===--- * This will translate any English sentence of up to 4 words into Yoda-Speak. * Press type 'yoda' to quit * English : hi * Yoda : hi * English : eat cheese * Yoda : cheese eat * English : you are stubborn * Yoda : stubborn you are * English : you must try harder * Yoda : try harder you must * English : yoda * */ package english2yoda; import java.util.Scanner; import java.util.Arrays; public class English2YodaRun { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("---=== English-Yoda Translator 1.0 ===---\n"); System.out.print("This will translate any English sentence of up to 4 words into Yoda-Speak.\n"); System.out.print("Press type 'yoda' to quit\n"); while (true) { System.out.print ("English : "); String english = input.nextLine(); if (english.equals("yoda")) break; String yoda = English2Yoda(english); System.out.printf("Yoda : %s\n", yoda); } } /** * Parses a sentence into an array of words * @param sentence the string sentence to parse * @return an array of words (in the sentence) */ public static String[] GetWords(String sentence) { return sentence.split("[ ]+"); } /** * Combines the words back into a sentence * @param words an array of strings * @return those strings, in order as once sentence. */ public static String CombineWords(String[] words) { String sentence = ""; for (String w : words) { sentence += w + " "; } return sentence; } /** * Translates from english to yoda * @param english a string sentence in english * @return the same sentence translated into yoda */ public static String English2Yoda(String english) { String[] words = GetWords(english); String yoda =""; // TODO: Write Code to complete this method below // note: how you translate depends on the number of words (size of the array) // once you manipulate the words[] array, use CombineWords() to put // in back into a sentence. return yoda; } }
33.152174
104
0.624262
42e8073dc30239c21ad618da3955b77c4fc4a78b
1,218
package fun.liwudi.graduatedesignuserinfomanage.service.impl; import fun.liwudi.graduatedesignuserinfomanage.domain.UserInfo; import fun.liwudi.graduatedesignuserinfomanage.mapper.UserManageMapper; import fun.liwudi.graduatedesignuserinfomanage.service.UserManageService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * @author 李武第 */ @Service public class UserManageServiceImpl implements UserManageService { @Autowired private UserManageMapper userManageMapper; @Override public void addCompanyConf(UserInfo userInfo) { userManageMapper.addUserInfo(userInfo); } @Override public void deleteUserInfo(UserInfo userInfo) { userManageMapper.deleteUserInfo(userInfo); } @Override public void updateUserInfo(UserInfo userInfo) { userManageMapper.updateUserInfo(userInfo); } @Override public UserInfo selectUserInfo(UserInfo userInfo) { return userManageMapper.selectUserInfo(userInfo); } @Override public List<UserInfo> selectUserInfos(UserInfo userInfo) { return userManageMapper.selectUserInfos(userInfo); } }
27.066667
73
0.766831
8040d9693db85fb92d594ad106bc8a2eafe7e879
1,806
package pw.kaboom.weapons.commands; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; public final class CommandWeapons implements CommandExecutor { private void addWeapon(final Inventory inventory, final Material material, final String name) { final ItemStack item = new ItemStack(material, 1); final ItemMeta itemMeta = item.getItemMeta(); itemMeta.setDisplayName(name); item.setItemMeta(itemMeta); inventory.addItem(item); } @Override public boolean onCommand(final CommandSender sender, final Command cmd, final String label, final String[] args) { if (sender instanceof ConsoleCommandSender) { sender.sendMessage("Command has to be run by a player"); } else { final Player player = (Player) sender; final Inventory inventory = Bukkit.createInventory(null, 18, "Weapons"); addWeapon(inventory, Material.ANVIL, "§rAnvil Dropper"); addWeapon(inventory, Material.SPECTRAL_ARROW, "§rArcher"); addWeapon(inventory, Material.FIRE_CHARGE, "§rArmageddon"); addWeapon(inventory, Material.MAGMA_CREAM, "§rBlobinator"); addWeapon(inventory, Material.EGG, "§rGrenade"); addWeapon(inventory, Material.BLAZE_POWDER, "§rLaser"); addWeapon(inventory, Material.STICK, "§rLightning Stick"); addWeapon(inventory, Material.GOLDEN_HORSE_ARMOR, "§rMachine Gun"); addWeapon(inventory, Material.BLAZE_ROD, "§rNuker"); addWeapon(inventory, Material.IRON_HORSE_ARMOR, "§rSniper"); player.openInventory(inventory); } return true; } }
38.425532
115
0.770764
6f13a4e0a5bde5c546e0ffce5b7ad12bc0c1f676
5,907
/* * Copyright (c) 2016 Paysafe * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.paysafe.directdebit; import com.google.gson.annotations.Expose; import com.paysafe.common.impl.DomainObject; import com.paysafe.common.impl.GenericBuilder; import com.paysafe.common.impl.NestedBuilder; // TODO: Auto-generated Javadoc /** * The Class BACS. * @author bhushan.patil * @since 04-04-2016. */ public class SEPA implements DomainObject { /** The payment token. */ @Expose private String paymentToken; /** The mandate reference. */ @Expose private String mandateReference; /** The account holder name. */ @Expose private String accountHolderName; /** The iban. */ @Expose private String iban; /** The last digits. */ @Expose private String lastDigits; /** * Gets the payment token. * * @return the payment token */ public String getPaymentToken() { return paymentToken; } /** * Sets the payment token. * * @param paymentToken the new payment token */ public void setPaymentToken(final String paymentToken) { this.paymentToken = paymentToken; } /** * Gets the account holder name. * * @return the account holder name */ public String getAccountHolderName() { return accountHolderName; } /** * Sets the account holder name. * * @param accountHolderName the new account holder name */ public void setAccountHolderName(final String accountHolderName) { this.accountHolderName = accountHolderName; } /** * Gets the last digits. * * @return the last digits */ public String getLastDigits() { return lastDigits; } /** * Sets the last digits. * * @param lastDigits the new last digits */ public void setLastDigits(final String lastDigits) { this.lastDigits = lastDigits; } /** * Gets the iban. * * @return the iban */ public String getIban() { return iban; } /** * Sets the iban. * * @param iban the new iban */ public void setIban(final String iban) { this.iban = iban; } /** * Gets the mandate reference. * * @return the mandate reference */ public String getMandateReference() { return mandateReference; } /** * Sets the mandate reference. * * @param mandateReference the new mandate reference */ public void setMandateReference(final String mandateReference) { this.mandateReference = mandateReference; } /** * The sub-builder class for SEPA. * * @param <BLDRT> the parent builder */ public static class SEPABuilder<BLDRT extends GenericBuilder> extends NestedBuilder<SEPA, BLDRT> { /** The sepa. */ private final SEPA SEPA = new SEPA(); /** * Instantiates a new SEPA builder. * * @param parent the parent */ public SEPABuilder(final BLDRT parent) { super(parent); } /** * Build this SEPA object. * * @return SEPA */ @Override public final SEPA build() { return SEPA; } /** * Set the paymentToken property. * * @param paymentToken the payment token * @return SEPABuilder< BLDRT > */ public final SEPABuilder<BLDRT> paymentToken(final String paymentToken) { SEPA.setPaymentToken(paymentToken); return this; } /** * Set the mandateReference property. * * @param mandateReference the mandate reference * @return SEPABuilder< BLDRT > */ public final SEPABuilder<BLDRT> mandateReference(final String mandateReference) { SEPA.setMandateReference(mandateReference); return this; } /** * Set the accountHolderName property. * * @param accountHolderName the account holder name * @return SEPABuilder< BLDRT > */ public final SEPABuilder<BLDRT> accountHolderName(final String accountHolderName) { SEPA.setAccountHolderName(accountHolderName); return this; } /** * Set the iban property. * * @param iban the iban * @return SEPABuilder< BLDRT > */ public final SEPABuilder<BLDRT> iban(final String iban) { SEPA.setIban(iban); return this; } /** * Set the lastDigits property. * * @param lastDigits the last digits * @return SEPABuilder< BLDRT > */ public final SEPABuilder<BLDRT> lastDigits(final String lastDigits) { SEPA.setLastDigits(lastDigits); return this; } } }
25.571429
100
0.619265
153a8d33a78e0379d82ee545928ee6f314b343dc
11,604
package com.zarbosoft.coroutines; import com.zarbosoft.coroutinescore.SuspendExecution; import com.zarbosoft.rendaw.common.Common; import org.junit.Test; import java.util.*; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.Matchers.greaterThan; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; public class TestRWCriticalSection { private final TestCriticalSection.Gate gate; private final ManualExecutor executor; private final RWCriticalSection critical; public TestRWCriticalSection() { this.gate = new TestCriticalSection.Gate(); this.executor = new ManualExecutor(); this.critical = new RWCriticalSection(); } public int invokeRead(int arg) throws SuspendExecution { return (Integer) critical.read(executor, () -> { assertThat(arg, greaterThan(4)); gate.stop(arg); return arg * 2; }); } public int invokeWrite(int arg) throws SuspendExecution { return (Integer) critical.write(executor, () -> { assertThat(arg, greaterThan(4)); gate.stop(arg); return arg * 2; }); } public boolean invokeTryUniqueWrite(int arg) throws SuspendExecution { return critical.tryUniqueWrite(executor, () -> { assertThat(arg, greaterThan(4)); gate.stop(arg); }); } @Test public void testOneReader() { final Coroutine coroutine1 = new Coroutine(() -> { assertThat(invokeRead(13), equalTo(26)); }); coroutine1.process(); gate.start(13); assertTrue(coroutine1.isFinished()); } @Test public void testOneReaderNoSuspend() { final Coroutine coroutine1 = new Coroutine(() -> { assertThat(critical.read(executor, () -> 26), equalTo(26)); }); coroutine1.process(); assertTrue(coroutine1.isFinished()); } @Test public void testSequentialReaders() { Common.Mutable<Integer> value = new Common.Mutable<>(0); final Coroutine coroutine1 = new Coroutine(() -> { assertThat(invokeRead(13), equalTo(26)); assertThat(invokeRead(14), equalTo(28)); value.value = 3; }); coroutine1.process(); gate.start(13); gate.start(14); assertThat(value.value, equalTo(3)); assertTrue(coroutine1.isFinished()); } @Test public void testParallelReaders() { List<Integer> value = new ArrayList<>(); final Coroutine coroutine1 = new Coroutine(() -> { assertThat(invokeRead(13), equalTo(26)); value.add(3); }); final Coroutine coroutine2 = new Coroutine(() -> { assertThat(invokeRead(14), equalTo(28)); value.add(4); }); coroutine1.process(); coroutine2.process(); gate.start(14); gate.start(13); assertThat(value, equalTo(Arrays.asList(4, 3))); assertTrue(coroutine1.isFinished()); assertTrue(coroutine2.isFinished()); } @Test public void testOneWriter() { Common.Mutable<Integer> value = new Common.Mutable<>(0); final Coroutine coroutine1 = new Coroutine(() -> { assertThat(invokeWrite(13), equalTo(26)); value.value = 3; }); coroutine1.process(); gate.start(13); assertThat(value.value, equalTo(3)); assertTrue(coroutine1.isFinished()); } @Test public void testOneWriterNoSuspend() { final Coroutine coroutine1 = new Coroutine(() -> { assertThat(critical.write(executor, () -> 26), equalTo(26)); }); coroutine1.process(); assertTrue(coroutine1.isFinished()); } @Test public void testSequentialWriters() { List<Integer> value = new ArrayList<>(); final Coroutine coroutine1 = new Coroutine(() -> { assertThat(invokeWrite(13), equalTo(26)); value.add(3); }); final Coroutine coroutine2 = new Coroutine(() -> { assertThat(invokeWrite(14), equalTo(28)); value.add(4); }); coroutine1.process(); gate.start(13); coroutine2.process(); gate.start(14); assertTrue(coroutine1.isFinished()); assertTrue(coroutine2.isFinished()); assertThat(value, equalTo(Arrays.asList(3, 4))); } @Test public void testBlockingWriters() { List<Integer> value = new ArrayList<>(); final Coroutine coroutine1 = new Coroutine(() -> { assertThat(invokeWrite(13), equalTo(26)); value.add(3); }); final Coroutine coroutine2 = new Coroutine(() -> { assertThat(invokeWrite(14), equalTo(28)); value.add(4); }); coroutine1.process(); coroutine2.process(); gate.start(13); gate.start(14); assertTrue(coroutine1.isFinished()); assertTrue(coroutine2.isFinished()); assertThat(value, equalTo(Arrays.asList(3, 4))); } @Test(expected = TestCriticalSection.NotAtGateFailure.class) public void testBlockingWritersBlocked() { List<Integer> value = new ArrayList<>(); final Coroutine coroutine1 = new Coroutine(() -> { assertThat(invokeWrite(13), equalTo(26)); value.add(3); }); final Coroutine coroutine2 = new Coroutine(() -> { assertThat(invokeWrite(14), equalTo(28)); value.add(4); }); coroutine1.process(); coroutine2.process(); gate.start(14); } @Test public void testTryWritePass() { final Coroutine coroutine1 = new Coroutine(() -> { assertThat(invokeTryUniqueWrite(8), is(true)); }); coroutine1.process(); gate.start(8); assertTrue(coroutine1.isFinished()); } @Test public void testWriteTryWriteBlocked() { List<Integer> value = new ArrayList<>(); final Coroutine coroutine1 = new Coroutine(() -> { assertThat(invokeTryUniqueWrite(7), is(true)); value.add(3); }); final Coroutine coroutine2 = new Coroutine(() -> { assertThat(invokeTryUniqueWrite(9), is(false)); value.add(4); }); coroutine1.process(); coroutine2.process(); assertTrue(coroutine2.isFinished()); gate.start(7); assertTrue(coroutine1.isFinished()); assertThat(value, equalTo(Arrays.asList(4, 3))); } @Test public void testReadBlockWrite() { List<Integer> value = new ArrayList<>(); final Coroutine coroutine1 = new Coroutine(() -> { assertThat(invokeRead(13), equalTo(26)); value.add(3); }); final Coroutine coroutine2 = new Coroutine(() -> { assertThat(invokeWrite(14), equalTo(28)); value.add(4); }); coroutine1.process(); coroutine2.process(); gate.start(13); gate.start(14); assertThat(value, equalTo(Arrays.asList(3, 4))); assertTrue(coroutine1.isFinished()); assertTrue(coroutine2.isFinished()); } @Test(expected = TestCriticalSection.NotAtGateFailure.class) public void testReadBlockWriteBlocked() { List<Integer> value = new ArrayList<>(); final Coroutine coroutine1 = new Coroutine(() -> { assertThat(invokeRead(13), equalTo(26)); value.add(3); }); final Coroutine coroutine2 = new Coroutine(() -> { assertThat(invokeWrite(14), equalTo(28)); value.add(4); }); coroutine1.process(); coroutine2.process(); gate.start(14); } @Test public void testReadTryWritePass() { List<Integer> value = new ArrayList<>(); final Coroutine coroutine1 = new Coroutine(() -> { assertThat(invokeRead(13), equalTo(26)); value.add(3); }); final Coroutine coroutine2 = new Coroutine(() -> { assertThat(invokeTryUniqueWrite(14), is(true)); value.add(4); }); coroutine1.process(); coroutine2.process(); gate.start(13); gate.start(14); assertTrue(coroutine1.isFinished()); assertTrue(coroutine2.isFinished()); assertThat(value, equalTo(Arrays.asList(3, 4))); } @Test public void testReadTryWriteBlocked() { List<Integer> value = new ArrayList<>(); final Coroutine coroutine1 = new Coroutine(() -> { assertThat(invokeRead(13), equalTo(26)); value.add(3); }); final Coroutine coroutine2 = new Coroutine(() -> { assertThat(invokeWrite(14), equalTo(28)); value.add(4); }); final Coroutine coroutine3 = new Coroutine(() -> { assertThat(invokeTryUniqueWrite(15), is(false)); value.add(5); }); coroutine1.process(); coroutine2.process(); coroutine3.process(); assertTrue(coroutine3.isFinished()); gate.start(13); assertTrue(coroutine1.isFinished()); gate.start(14); assertTrue(coroutine2.isFinished()); assertThat(value, equalTo(Arrays.asList(5, 3, 4))); } /** * Additional reads will run while a read is in progress even if write blocked. */ @Test public void testAdditionalReadBlockWrite() { List<Integer> value = new ArrayList<>(); final Coroutine coroutine1 = new Coroutine(() -> { assertThat(invokeRead(13), equalTo(26)); value.add(3); }); final Coroutine coroutine2 = new Coroutine(() -> { assertThat(invokeWrite(14), equalTo(28)); value.add(4); }); final Coroutine coroutine3 = new Coroutine(() -> { assertThat(invokeRead(15), equalTo(30)); value.add(5); }); coroutine1.process(); coroutine2.process(); coroutine3.process(); gate.start(13); gate.start(15); gate.start(14); assertThat(value, equalTo(Arrays.asList(3, 5, 4))); assertTrue(coroutine1.isFinished()); assertTrue(coroutine2.isFinished()); assertTrue(coroutine3.isFinished()); } @Test public void testWriteBlockRead() { List<Integer> value = new ArrayList<>(); final Coroutine coroutine1 = new Coroutine(() -> { assertThat(invokeRead(13), equalTo(26)); value.add(3); }); final Coroutine coroutine2 = new Coroutine(() -> { assertThat(invokeWrite(14), equalTo(28)); value.add(4); }); coroutine2.process(); coroutine1.process(); gate.start(14); gate.start(13); assertThat(value, equalTo(Arrays.asList(4, 3))); assertTrue(coroutine1.isFinished()); assertTrue(coroutine2.isFinished()); } @Test(expected = TestCriticalSection.NotAtGateFailure.class) public void testWriteBlockReadBlocked() { List<Integer> value = new ArrayList<>(); final Coroutine coroutine1 = new Coroutine(() -> { assertThat(invokeRead(13), equalTo(26)); value.add(3); }); final Coroutine coroutine2 = new Coroutine(() -> { assertThat(invokeWrite(14), equalTo(28)); value.add(4); }); coroutine2.process(); coroutine1.process(); gate.start(13); } @Test public void testReadBetweenWrites() { List<Integer> value = new ArrayList<>(); final Coroutine coroutine1 = new Coroutine(() -> { assertThat(invokeWrite(13), equalTo(26)); value.add(3); }); final Coroutine coroutine2 = new Coroutine(() -> { assertThat(invokeWrite(14), equalTo(28)); value.add(4); }); final Coroutine coroutine3 = new Coroutine(() -> { assertThat(invokeRead(15), equalTo(30)); value.add(5); }); coroutine1.process(); coroutine2.process(); coroutine3.process(); gate.start(13); gate.start(15); gate.start(14); assertThat(value, equalTo(Arrays.asList(3, 5, 4))); assertTrue(coroutine1.isFinished()); assertTrue(coroutine2.isFinished()); assertTrue(coroutine3.isFinished()); } /** * Move to additional reads block write state after initial write finishes. */ @Test public void testTransitionReadBlockWrite() { List<Integer> value = new ArrayList<>(); final Coroutine coroutine1 = new Coroutine(() -> { assertThat(invokeWrite(13), equalTo(26)); value.add(3); }); final Coroutine coroutine2 = new Coroutine(() -> { assertThat(invokeWrite(14), equalTo(28)); value.add(4); }); final Coroutine coroutine3 = new Coroutine(() -> { assertThat(invokeRead(15), equalTo(30)); value.add(5); }); final Coroutine coroutine4 = new Coroutine(() -> { assertThat(invokeRead(16), equalTo(32)); value.add(6); }); coroutine1.process(); coroutine2.process(); coroutine3.process(); gate.start(13); coroutine4.process(); gate.start(16); gate.start(15); gate.start(14); assertThat(value, equalTo(Arrays.asList(3, 6, 5, 4))); assertTrue(coroutine1.isFinished()); assertTrue(coroutine2.isFinished()); assertTrue(coroutine3.isFinished()); assertTrue(coroutine4.isFinished()); } }
27.432624
80
0.684247
cb227b8e5e12bbf42d18fd3d4d15b2bbb8ec972a
3,468
/* * Copyright (c) 2012-2020, Peter Abeles. All Rights Reserved. * * This file is part of DDogleg (http://ddogleg.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ddogleg.clustering; import org.ddogleg.clustering.misc.ListAccessor; import org.ddogleg.struct.DogArray_I32; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * @author Peter Abeles */ public class BenchmarkStabilityInitialization { int DOF = 2; Random rand = new Random(234); List<double[]> points = new ArrayList<>(); List<double[]> centers = new ArrayList<>(); DogArray_I32 membership = new DogArray_I32(); DogArray_I32 clusterSize = new DogArray_I32(); int totalClusters = 0; public void addCluster( double x , double y , double sigmaX , double sigmaY , int N ) { centers.add( new double[]{x,y}); for (int i = 0; i < N; i++) { double[] p = new double[2]; p[0] = x + rand.nextGaussian()*sigmaX; p[1] = y + rand.nextGaussian()*sigmaY; points.add(p); membership.add(totalClusters); } totalClusters++; clusterSize.add(N); } public void bencharkAll() { addCluster(10,12,1,2,200); addCluster(-1,5,0.5,0.2,500); addCluster(5,7,0.3,0.3,100); ConfigKMeans config = new ConfigKMeans(); config.reseedAfterIterations = 1000; config.maxIterations = 1000; config.convergeTol = 1e-8; System.out.println("Lower errors the better....\n"); config.initializer = KMeansInitializers.STANDARD; evaluate(FactoryClustering.kMeans(config,DOF, double[].class)); config.initializer = KMeansInitializers.PLUS_PLUS; evaluate(FactoryClustering.kMeans(config,DOF, double[].class)); evaluate(FactoryClustering.gaussianMixtureModelEM_F64(1000,1000,1e-8,DOF)); } public void evaluate( ComputeClusters<double[]> clusterer ) { clusterer.initialize(32454325); ListAccessor<double[]> accessor = new ListAccessor<>(points, (src, dst) -> System.arraycopy(src, 0, dst, 0, DOF), double[].class); int numTrials = 500; double totalSizeError = 0; for (int i = 0; i < numTrials; i++) { clusterer.process(accessor,3); AssignCluster<double[]> assign = clusterer.getAssignment(); int[] counts = new int[totalClusters]; for (int j = 0; j < points.size(); j++) { int found = assign.assign(points.get(j)); counts[found]++; } totalSizeError += computeSizeError(assign,counts); } System.out.println("average size error = "+(totalSizeError/numTrials)); } private double computeSizeError(AssignCluster<double[]> assign , int[] counts) { double error = 0; for (int i = 0; i < totalClusters; i++) { int closest = assign.assign(centers.get(i)); int foundSize = counts[closest]; int expectedSize = clusterSize.get(i); error += Math.abs(foundSize-expectedSize); } return error/totalClusters; } public static void main(String[] args) { BenchmarkStabilityInitialization app = new BenchmarkStabilityInitialization(); app.bencharkAll(); } }
28.9
88
0.70271
4cb1085ab5ca4a0d03af6e3e758bfbe7c65a1274
699
//Hierarchical Inheritance example class A { public void methodA() { System.out.println("method of Class A"); } } class B extends A { public void methodB() { System.out.println("method of Class B"); } } class C extends A { public void methodC() { System.out.println("method of Class C"); } } class D extends A { public void methodD() { System.out.println("method of Class D"); } } class HierarchicalInheritance { public static void main(String args[]) { B obj1 = new B(); C obj2 = new C(); D obj3 = new D(); //All classes can access the method of class A obj1.methodA(); obj2.methodA(); obj3.methodA(); } }
16.642857
51
0.600858
c61b932c46b48c84ff84fc3a6221f071ac777a79
6,417
package cn; import java.util.ArrayList; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CLabel; import org.eclipse.swt.graphics.Cursor; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.layout.RowLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; /** * 自定义消息框 * * @author liuzhuomin * */ public class MyMessageBox { private Shell mainShell; private Composite mainComposite; private Image image; private String title = ""; private String message = ""; private static Font defaultFont = SWTResourceManager.getFont("Microsoft YaHei UI", 10, SWT.NORMAL); private List<Button> buttons = new ArrayList<>(); private static final Image DEFAULT_IMAGE = new Image(Display.getCurrent(), MyMessageBox.class.getResourceAsStream("/icon/提示(3).png")); private static Integer result; private Composite buttonComposite; private boolean canClose; private CLabel titleLabel; private Text messageText; public MyMessageBox() { initAnyThings(); } public MyMessageBox(String title) { super(); this.title = title; initAnyThings(); } public MyMessageBox(Image image, String message) { super(); this.image = image; this.message = message; } public MyMessageBox(String title, String message) { super(); this.title = title; this.message = message; } public MyMessageBox(Image image) { super(); this.image = image; } private void initAnyThings() { init(); createTop(); createMiddle(); createBotoom(); } public MyMessageBox(Image image, String title, String message) { super(); this.image = image; this.title = title; this.message = message; initAnyThings(); } public MyMessageBox init() { synchronized (MyMessageBox.class) { if (mainShell == null) { mainShell = new Shell(Display.getCurrent(), SWT.APPLICATION_MODAL | SWT.BORDER); int[] xy = WindowUtils.getXYWH(WindowStatics.MESSAGE_WIDTH, WindowStatics.MESSAGE_HEIGHT); mainShell.setBounds(xy[0], xy[1], WindowStatics.MESSAGE_WIDTH, WindowStatics.MESSAGE_HEIGHT); mainShell.setLayout(new FillLayout()); mainShell.setBackground(WindowStatics.WHITE); mainShell.setBackgroundMode(SWT.INDETERMINATE); mainShell.addListener(SWT.Close, e -> { e.doit = canClose; }); createMainCompo(); } return this; } } private void createMainCompo() { mainComposite = new Composite(mainShell, SWT.None); GridLayout gridLayout = new GridLayout(10, false); gridLayout.marginWidth = 0; gridLayout.marginHeight = 0; mainComposite.setLayout(gridLayout); } private void createTop() { titleLabel = new CLabel(mainComposite, SWT.NONE); Image systemImage = this.image == null ? DEFAULT_IMAGE : this.image; titleLabel.setImage(systemImage); titleLabel.setText(this.title); GridData gridData = new GridData(SWT.LEFT, SWT.TOP, false, false, 10, 1); titleLabel.setLayoutData(gridData); // 这个是上面的水平线 new Label(mainComposite, SWT.SEPARATOR | SWT.HORIZONTAL) .setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, true, 10, 1)); } private void createMiddle() { CLabel messageLabel = new CLabel(mainComposite, SWT.NONE); // messageLabel.setImage(this.image == null ? DEFAULT_IMAGE : this.image); messageLabel.setImage(Display.getCurrent().getSystemImage(SWT.ICON_WARNING)); messageLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true, true, 2, 5)); messageText = new Text(mainComposite, SWT.WRAP); messageText.setEditable(false); messageText.setDoubleClickEnabled(false); messageText.setTouchEnabled(false); messageText.setFont(defaultFont); messageText.setText(getMessage()); messageText.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true, 8, 5)); } private void createBotoom() { // 这个是下面的水平线 new Label(mainComposite, SWT.SEPARATOR | SWT.HORIZONTAL) .setLayoutData(new GridData(SWT.FILL, SWT.BOTTOM, true, true, 10, 1)); buttonComposite = new Composite(mainComposite, SWT.None); buttonComposite.setLayoutData(new GridData(SWT.FILL, SWT.BOTTOM, true, false, 10, 1)); RowLayout layout = new RowLayout(SWT.HORIZONTAL); layout.wrap = true; layout.fill = false; layout.justify = true; buttonComposite.setLayout(layout); if (buttons.size() == 0) { Button shure = new Button(buttonComposite, SWT.NONE); shure.setText("确认"); Cursor cursor = SWTResourceManager.getCursor(SWT.CURSOR_HAND); shure.setCursor(cursor); Button cancle = new Button(buttonComposite, SWT.NONE); cancle.setText("取消"); cancle.setCursor(cursor); shure.addListener(SWT.Selection, e -> { result = SWT.OK; mainShell.dispose(); }); cancle.addListener(SWT.Selection, e -> { result = SWT.NO; mainShell.dispose(); }); } mainShell.addListener(SWT.KeyDown, e -> { if (e.character == SWT.CR) { result = SWT.OK; mainShell.dispose(); } }); } public Integer open() { Display.getCurrent().beep(); messageText.setText(this.message); titleLabel.setText(this.title); if (this.image != null) { titleLabel.setImage(this.image); mainShell.setImage(this.image); } mainComposite.getChildren(); mainShell.setFocus(); this.mainShell.open(); this.mainShell.layout(); while (!mainShell.isDisposed()) { if (!Display.getCurrent().readAndDispatch()) { Display.getCurrent().sleep(); } } return result; } public Image getImage() { return image; } public void setImage(Image image) { this.image = image; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public static Font getDefaultFont() { return defaultFont; } public static void setDefaultFont(Font defaultFont) { MyMessageBox.defaultFont = defaultFont; } public List<Button> getButtons() { return buttons; } public void setButtons(List<Button> buttons) { this.buttons = buttons; } public Composite getButtonComposite() { return buttonComposite; } }
25.066406
100
0.717781
096fb9e2ba696b67a098facf0315a26ba61d812a
2,412
package de.youtclubstage.virtualyouthclub.controller; import de.youtclubstage.virtualyouthclub.controller.model.StateDto; import de.youtclubstage.virtualyouthclub.entity.Agreement; import de.youtclubstage.virtualyouthclub.service.AgreementService; import de.youtclubstage.virtualyouthclub.service.CheckService; import de.youtclubstage.virtualyouthclub.service.StateService; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.web.bind.annotation.*; import java.util.List; @Slf4j @RestController @RequestMapping("/api") public class StateController { private final StateService stateService; private final CheckService checkService; private final AgreementService agreementService; public StateController(StateService stateService, CheckService checkService, AgreementService agreementService){ this.stateService = stateService; this.checkService = checkService; this.agreementService = agreementService; } @RequestMapping(method = RequestMethod.GET, value={"/state","/public/state"},produces = "application/json") ResponseEntity<Boolean> isOpen(){ return ResponseEntity.ok(stateService.isOpen()); } @RequestMapping(method = RequestMethod.GET, value="/extendedState",produces = "application/json") ResponseEntity<StateDto> isOpenOrAdmin(){ return ResponseEntity.ok(new StateDto(checkService.getState())); } @RequestMapping(method = RequestMethod.GET, value="/admin",produces = "application/json") ResponseEntity<Boolean> Admin(){ return ResponseEntity.ok(checkService.isAdmin()); } @RequestMapping(method = RequestMethod.POST, value="/agreement") ResponseEntity<Void> setAgreement(){ agreementService.createAgreement(); return ResponseEntity.ok().build(); } @RequestMapping(method = RequestMethod.POST, value="/state") ResponseEntity<Void> isOpen(@RequestBody boolean open){ if(!checkService.isAdmin()){ return ResponseEntity.status(HttpStatus.FORBIDDEN).build(); } stateService.setOpen(open); return ResponseEntity.ok().build(); } }
36.545455
111
0.737562
253b8d1a46886a7cce93448dd434bf0a8d8cd907
2,695
package com.bitshares.bitshareswallet; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.Window; import android.view.WindowManager; import com.akexorcist.localizationactivity.ui.LocalizationActivity; import com.good.code.starts.here.ColorUtils; public class ModelSelectActivity extends LocalizationActivity { private Toolbar mToolbar; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); //if(preferences.contains("locale")) setLanguage(preferences.getString("locale", "ru")); setContentView(R.layout.activity_model_select); mToolbar = findViewById(R.id.toolbar); setSupportActionBar(mToolbar); int color = ColorUtils.getMainColor(this); mToolbar.setBackgroundColor(color); mToolbar.getRootView().setBackgroundColor(color); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Window window = getWindow(); window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setStatusBarColor(ColorUtils.manipulateColor(color, 0.75f)); } mToolbar.setNavigationOnClickListener(v -> finish()); getSupportActionBar().setDisplayHomeAsUpEnabled(true); findViewById(R.id.textViewAccountModel).setOnClickListener(v -> { Intent intent = new Intent(ModelSelectActivity.this, ImportActivity.class); intent.putExtra("model", ImportActivity.ACCOUNT_MODEL); startActivity(intent); }); findViewById(R.id.textViewWalletModelWifKey).setOnClickListener(v -> { Intent intent = new Intent(ModelSelectActivity.this, ImportActivity.class); intent.putExtra("model", ImportActivity.WALLET_MODEL_WIF_KEY); startActivity(intent); }); findViewById(R.id.textViewWalletModelBin).setOnClickListener(v -> { Intent intent = new Intent(ModelSelectActivity.this, ImportActivity.class); intent.putExtra("model", ImportActivity.WALLET_MODEL_BIN_FILE); startActivity(intent); }); findViewById(R.id.textViewWalletModelBrainKey).setOnClickListener(v -> { Intent intent = new Intent(ModelSelectActivity.this, ImportActivity.class); intent.putExtra("model", ImportActivity.WALLET_MODEL_BRAIN_KEY); startActivity(intent); }); } }
42.777778
96
0.709833
cfc6cf84cef19c10a3ce77670a24cb1af8b49397
152
package com.datapath.kg.risks.api.dto; import lombok.Data; @Data public class SortingOptionDTO { private String field; private String type; }
15.2
38
0.743421
a1283611a84cf9d6c2eba490c8411ce64d9d9d81
1,934
// This file is auto-generated, don't edit it. Thanks. package com.antgroup.antchain.openapi.goodschain.models; import com.aliyun.tea.*; public class TraceInfoDTO extends TeaModel { // 操作描述 @NameInMap("operate_type_desc") @Validation(required = true) public String operateTypeDesc; // 操作时间,时间戳 @NameInMap("operate_time") @Validation(required = true) public Long operateTime; // 操作人id @NameInMap("operator_id") @Validation(required = true) public String operatorId; // 操作人名称 @NameInMap("operator_name") @Validation(required = true) public String operatorName; // 操作内容 @NameInMap("content") @Validation(required = true) public String content; public static TraceInfoDTO build(java.util.Map<String, ?> map) throws Exception { TraceInfoDTO self = new TraceInfoDTO(); return TeaModel.build(map, self); } public TraceInfoDTO setOperateTypeDesc(String operateTypeDesc) { this.operateTypeDesc = operateTypeDesc; return this; } public String getOperateTypeDesc() { return this.operateTypeDesc; } public TraceInfoDTO setOperateTime(Long operateTime) { this.operateTime = operateTime; return this; } public Long getOperateTime() { return this.operateTime; } public TraceInfoDTO setOperatorId(String operatorId) { this.operatorId = operatorId; return this; } public String getOperatorId() { return this.operatorId; } public TraceInfoDTO setOperatorName(String operatorName) { this.operatorName = operatorName; return this; } public String getOperatorName() { return this.operatorName; } public TraceInfoDTO setContent(String content) { this.content = content; return this; } public String getContent() { return this.content; } }
24.794872
85
0.658738
875d4c4ff437e7fca95525ae42b8cab8590687e2
3,802
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Networks.ChatApplication; import java.awt.Color; import java.awt.FlowLayout; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.InetAddress; import java.net.Socket; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; /** * * @author mankank */ class Client_ extends JFrame implements MouseListener { //constants private static final int WINDOW_WIDTH = 300; private static final int WINDOW_HEIGHT = 300; private static final String WINDOW_TITLE = "Nithin"; private static final int TEXT_FIELD_MAX_CHAR = 20; private static final String SEND_LABEL = "Send"; private JTextField inputField; private JButton sendButton; private Socket socket; private BufferedReader rw_1; private PrintWriter pw_1; private JLabel datalabel; public Client_() { buildJFrame(); initializeComponents(); addComponents(); addListeners(); } private void buildJFrame() { this.setVisible(true); this.setResizable(false); this.setSize(WINDOW_WIDTH, WINDOW_HEIGHT); this.setTitle(WINDOW_TITLE); this.getContentPane().setBackground(Color.CYAN); this.setLayout(new FlowLayout()); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } private void initializeComponents() { this.inputField = new JTextField(TEXT_FIELD_MAX_CHAR); this.sendButton = new JButton(SEND_LABEL); } private void addComponents() { this.add(inputField); this.add(sendButton); } private void addListeners() { this.sendButton.addMouseListener(this); } public void initializeSocket() throws IOException { socket = new Socket(InetAddress.getLocalHost(), 2500); } public void initializeIO() throws IOException { this.rw_1 = new BufferedReader(new InputStreamReader(socket.getInputStream())); this.pw_1 = new PrintWriter(socket.getOutputStream()); } public void listen() throws IOException { while (true) { String msg = rw_1.readLine(); this.datalabel = new JLabel(); this.add(datalabel); datalabel.setText(msg); } } @Override public void mouseClicked(MouseEvent e) { String input = inputField.getText(); this.pw_1.println(input); this.pw_1.flush(); } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } } public class _2JFrameChatClient { public static void main(String[] args) throws IOException { Client_ client = new Client_(); client.initializeSocket(); client.initializeIO(); client.listen(); } }
29.703125
95
0.580221
54461e118e9ab34754ee23c1734a57179a0b305e
7,838
package com.lumivote.lumivote.ui; import android.content.res.Configuration; import android.os.Bundle; import android.support.design.widget.NavigationView; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.GravityCompat; import android.support.v4.view.ViewPager; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import com.lumivote.lumivote.R; import com.lumivote.lumivote.ui.about_tab.AboutFragment; import com.lumivote.lumivote.ui.bills_tab.BillsFragment; import com.lumivote.lumivote.ui.candidate_tab.CandidatePartyFragment; import com.lumivote.lumivote.ui.legislators_tab.LegislatorsFragment; import com.lumivote.lumivote.ui.settings_tab.SettingsPrefFragment; import com.lumivote.lumivote.ui.starred_tab.StarredFragment; import com.lumivote.lumivote.ui.timeline_tab.TimelineFragment; import com.lumivote.lumivote.ui.votes_tab.VotesFragment; import java.util.ArrayList; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; public class MainActivity extends AppCompatActivity { ActionBarDrawerToggle drawerToggle; @Bind(R.id.navigation) NavigationView navigation; @Bind(R.id.toolbar) Toolbar toolbar; @Bind(R.id.drawerLayout) DrawerLayout drawerLayout; @Bind(R.id.viewpager) ViewPager mViewPager; @Bind(R.id.tabLayout) TabLayout tabLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); setSupportActionBar(toolbar); initInstances(); setupDrawerContent(navigation); setupViewPager(mViewPager); initTabLayout(); //defaults to drawer open with the timeline fragment instantiated drawerLayout.openDrawer(Gravity.LEFT); Fragment fragment = null; try { fragment = TimelineFragment.class.newInstance(); } catch (Exception e) { e.printStackTrace(); } FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit(); setTitle(getResources().getString(R.string.timeline_title)); } private void initInstances() { drawerToggle = new ActionBarDrawerToggle(MainActivity.this, drawerLayout, R.string.hello_world, R.string.hello_world); drawerLayout.setDrawerListener(drawerToggle); getSupportActionBar().setHomeButtonEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } private void setupViewPager(ViewPager viewpager){ TabsFragmentPagerAdapter pagerAdapter = new TabsFragmentPagerAdapter(getSupportFragmentManager()); pagerAdapter.addFragment(CandidatePartyFragment.newInstance(1), "Democrats"); pagerAdapter.addFragment(CandidatePartyFragment.newInstance(2), "Republicans"); mViewPager.setAdapter(pagerAdapter); } private void initTabLayout() { tabLayout.setupWithViewPager(mViewPager); mViewPager.setVisibility(View.GONE); tabLayout.setVisibility(View.GONE); } private void setupDrawerContent(NavigationView navigationView) { navigationView.setNavigationItemSelectedListener( new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(MenuItem menuItem) { selectDrawerItem(menuItem); return true; } }); } public void selectDrawerItem(MenuItem menuItem) { Fragment fragment = null; Class fragmentClass; switch (menuItem.getItemId()) { case R.id.timeline: fragmentClass = TimelineFragment.class; break; case R.id.candidates: fragmentClass = CandidatePartyFragment.class; break; case R.id.starred: fragmentClass = StarredFragment.class; break; case R.id.legislators: fragmentClass = LegislatorsFragment.class; break; case R.id.bills: fragmentClass = BillsFragment.class; break; case R.id.votes: fragmentClass = VotesFragment.class; break; case R.id.settings: fragmentClass = SettingsPrefFragment.class; break; case R.id.about: fragmentClass = AboutFragment.class; break; default: fragmentClass = TimelineFragment.class; } try { fragment = (Fragment) fragmentClass.newInstance(); } catch (Exception e) { e.printStackTrace(); } // Insert the fragment by replacing any existing fragment FragmentManager fragmentManager = getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit(); menuItem.setChecked(true); setTitle(menuItem.getTitle()); drawerLayout.closeDrawers(); } @Override public void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); drawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); drawerToggle.onConfigurationChanged(newConfig); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (drawerToggle.onOptionsItemSelected(item)) return true; // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { if (drawerLayout.isDrawerOpen(GravityCompat.START)) drawerLayout.closeDrawers(); else super.onBackPressed(); } public static class TabsFragmentPagerAdapter extends FragmentPagerAdapter { private final List<Fragment> mFragments = new ArrayList<>(); private final List<String> mFragmentTitles = new ArrayList<>(); public TabsFragmentPagerAdapter(FragmentManager fm) { super(fm); } public void addFragment(Fragment fragment, String title) { mFragments.add(fragment); mFragmentTitles.add(title); } @Override public int getCount() { return mFragments.size(); } @Override public Fragment getItem(int position) { return mFragments.get(position); } @Override public CharSequence getPageTitle(int position) { return mFragmentTitles.get(position); } } }
33.353191
126
0.666114
d98a5df04ed28dba88fc6b5b13a4e9a499a4aca8
2,841
package js.web.dom; import js.lang.Promise; import js.util.collections.Array; import js.util.collections.ReadonlyArray; import js.util.function.JsConsumer; import js.util.iterable.JsIterable; import js.web.beacon.NavigatorBeacon; import js.web.credentialmanagement.CredentialsContainer; import js.web.gamepad.Gamepad; import js.web.geolocation.Geolocation; import js.web.mediastreams.*; import js.web.permissions.Permissions; import js.web.serviceworker.ServiceWorkerContainer; import js.web.storage.NavigatorStorage; import js.web.webvr.VRDisplay; import org.teavm.jso.JSBody; import org.teavm.jso.JSByRef; import org.teavm.jso.JSProperty; import javax.annotation.Nullable; /** * The state and the identity of the user agent. It allows scripts to query it and to register themselves to carry on some activities. */ public interface Navigator extends NavigatorAutomationInformation, NavigatorBeacon, NavigatorConcurrentHardware, NavigatorContentUtils, NavigatorCookies, NavigatorID, NavigatorLanguage, NavigatorOnLine, NavigatorPlugins, NavigatorStorage { @JSBody(script = "return Navigator.prototype") static Navigator prototype() { throw new UnsupportedOperationException("Available only in JavaScript"); } @JSBody(script = "return new Navigator()") static Navigator create() { throw new UnsupportedOperationException("Available only in JavaScript"); } @JSProperty ReadonlyArray<VRDisplay> getActiveVRDisplays(); @JSProperty Clipboard getClipboard(); @JSProperty CredentialsContainer getCredentials(); @JSProperty @Nullable String getDoNotTrack(); @JSProperty Geolocation getGeolocation(); @JSProperty int getMaxTouchPoints(); @JSProperty MediaDevices getMediaDevices(); @JSProperty boolean isMsManipulationViewsEnabled(); @JSProperty int getMsMaxTouchPoints(); @JSProperty boolean isMsPointerEnabled(); @JSProperty Permissions getPermissions(); @JSProperty boolean isPointerEnabled(); @JSProperty ServiceWorkerContainer getServiceWorker(); Array<Gamepad> getGamepads(); void getUserMedia(MediaStreamConstraints constraints, JsConsumer<MediaStream> successCallback, JsConsumer<MediaStreamError> errorCallback); Promise<Array<VRDisplay>> getVRDisplays(); Promise<MediaKeySystemAccess> requestMediaKeySystemAccess(String keySystem, MediaKeySystemConfiguration... supportedConfigurations); Promise<MediaKeySystemAccess> requestMediaKeySystemAccess(String keySystem, Array<MediaKeySystemConfiguration> supportedConfigurations); Promise<MediaKeySystemAccess> requestMediaKeySystemAccess(String keySystem, JsIterable<MediaKeySystemConfiguration> supportedConfigurations); boolean vibrate(int pattern); boolean vibrate(int... pattern); }
30.223404
239
0.778951
f51433328cca6c268a16c8346d2175fccb4c71ab
1,201
package com.tehang.common.utility; import lombok.AccessLevel; import lombok.NoArgsConstructor; import javax.validation.constraints.NotNull; import java.util.function.Function; import java.util.function.Supplier; @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class NullUtils { /** * @param getMethod * 注意不可使用 <code>Class::method</code> 的形式调用 * <p> * 只能用 <code>() -> object.method()</code> */ public static <T> T getOrNull(Supplier<T> getMethod) { return getOrElse(getMethod, null); } /** * @param getMethod * 注意不可使用 <code>Class::method</code> 的形式调用 * <p> * 只能用 <code>() -> object.method()</code> */ public static <T> T getOrElse(Supplier<T> getMethod, T defaultValue) { return getOrElseGet(getMethod, (ex) -> defaultValue); } /** * @param getMethod * 注意不可使用 <code>Class::method</code> 的形式调用 * <p> * 只能用 <code>() -> object.method()</code> */ public static <T> T getOrElseGet(Supplier<T> getMethod, @NotNull Function<NullPointerException, T> defaultGetMethod) { try { return getMethod.get(); } catch (NullPointerException exception) { return defaultGetMethod.apply(exception); } } }
25.020833
120
0.666944
24c798df7153c42270ef985a57d15fcdbed41b94
2,218
package com.noahcharlton.wgpuj.jni; import com.noahcharlton.wgpuj.util.WgpuJavaStruct; import jnr.ffi.Runtime; import jnr.ffi.Struct; /** NOTE: THIS FILE WAS PRE-GENERATED BY JNR_GEN! */ public class WgpuSwapChainDescriptor extends WgpuJavaStruct { private final Struct.Unsigned32 usage = new Struct.Unsigned32(); private final Struct.Enum<WgpuTextureFormat> format = new Struct.Enum<>(WgpuTextureFormat.class); private final Struct.Unsigned32 width = new Struct.Unsigned32(); private final Struct.Unsigned32 height = new Struct.Unsigned32(); private final Struct.Enum<WgpuPresentMode> presentMode = new Struct.Enum<>(WgpuPresentMode.class); private WgpuSwapChainDescriptor(){} @Deprecated public WgpuSwapChainDescriptor(Runtime runtime){ super(runtime); } /** * Creates this struct on the java heap. * In general, this should <b>not</b> be used because these structs * cannot be directly passed into native code. */ public static WgpuSwapChainDescriptor createHeap(){ return new WgpuSwapChainDescriptor(); } /** * Creates this struct in direct memory. * This is how most structs should be created (unless, they * are members of a nothing struct) * * @see WgpuJavaStruct#useDirectMemory */ public static WgpuSwapChainDescriptor createDirect(){ var struct = new WgpuSwapChainDescriptor(); struct.useDirectMemory(); return struct; } public long getUsage(){ return usage.get(); } public void setUsage(long x){ this.usage.set(x); } public WgpuTextureFormat getFormat(){ return format.get(); } public void setFormat(WgpuTextureFormat x){ this.format.set(x); } public long getWidth(){ return width.get(); } public void setWidth(long x){ this.width.set(x); } public long getHeight(){ return height.get(); } public void setHeight(long x){ this.height.set(x); } public WgpuPresentMode getPresentMode(){ return presentMode.get(); } public void setPresentMode(WgpuPresentMode x){ this.presentMode.set(x); } }
25.790698
102
0.665464
8544fbe72f0c26513ab70afa92fc4be715660db9
1,202
package vg.civcraft.mc.namelayer.events; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; import vg.civcraft.mc.namelayer.group.Group; public class GroupDeleteEvent extends Event implements Cancellable{ private static final HandlerList handlers = new HandlerList(); private Group group; private boolean cancelled; private boolean finished; public GroupDeleteEvent(Group group, boolean finished){ this.group = group; this.finished = finished; } /** * Sets the group to be deleted. * @param group- The group to be deleted. */ public void setGroup(Group group){ this.group = group; } /** * Gets the group that is deleted. * @return Returns the group that is to be deleted. */ public Group getGroup(){ return group; } public boolean isCancelled() { return cancelled; } public void setCancelled(boolean value) { cancelled = value; } @Override public HandlerList getHandlers() { return handlers; } public static HandlerList getHandlerList() { return handlers; } public void setHasFinished(boolean value){ finished = value; } public boolean hasFinished(){ return finished; } }
20.372881
67
0.727121
0d309e387541dc30a8abf1d85690b3021d22306b
3,069
package com.faforever.moderatorclient.ui; import com.faforever.moderatorclient.api.domain.PermissionService; import com.faforever.moderatorclient.ui.data_cells.StringListCell; import com.faforever.moderatorclient.ui.domain.UserGroupFX; import javafx.fxml.FXML; import javafx.scene.control.ListView; import javafx.scene.control.SelectionMode; import javafx.scene.control.TextField; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.stage.Stage; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import org.springframework.util.Assert; import java.util.List; import java.util.function.Consumer; import java.util.stream.Collectors; @Component @Scope(BeanDefinition.SCOPE_PROTOTYPE) @Slf4j @RequiredArgsConstructor public class GroupAddChildController implements Controller<Pane> { private final PermissionService permissionService; public VBox root; public TextField affectedGroupTextField; public ListView<UserGroupFX> groupChildrenListView; @Getter private UserGroupFX userGroupFX; private Consumer<List<UserGroupFX>> addedListener; public void addAddedListener(Consumer<List<UserGroupFX>> listener) { this.addedListener = listener; } @FXML public void initialize() { permissionService.getAllUserGroups().thenAccept(userGroups -> groupChildrenListView.getItems().addAll(userGroups.stream() .filter(userGroup -> !userGroup.equals(userGroupFX) && !userGroupFX.getChildren().contains(userGroup)) .collect(Collectors.toList()))); groupChildrenListView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); groupChildrenListView.setCellFactory(param -> new StringListCell<>(UserGroupFX::getTechnicalName)); } @Override public Pane getRoot() { return root; } public void setGroup(UserGroupFX userGroupFX) { Assert.notNull(userGroupFX, "Group must not be null"); this.userGroupFX = userGroupFX; affectedGroupTextField.textProperty().bind(userGroupFX.technicalNameProperty()); } public void onSave() { List<UserGroupFX> childrenToAdd = groupChildrenListView.getSelectionModel().getSelectedItems(); Assert.notNull(userGroupFX, "You can't save if userGroupFX is null."); if (!childrenToAdd.isEmpty()) { childrenToAdd.forEach(childGroup -> { childGroup.setParent(userGroupFX); permissionService.patchUserGroup(childGroup); }); if (addedListener != null) { addedListener.accept(childrenToAdd); } } close(); } public void onAbort() { close(); } private void close() { Stage stage = (Stage) root.getScene().getWindow(); stage.close(); } }
33
126
0.714239
1cde25a1733bfb2b4bc361cc16140ff802081dac
1,377
package org.usfirst.frc2337.TalonSRXwithMagEncoder.subsystems; import org.usfirst.frc2337.TalonSRXwithMagEncoder.RobotMap; import org.usfirst.frc2337.TalonSRXwithMagEncoder.commands.*; import edu.wpi.first.wpilibj.CANTalon; import edu.wpi.first.wpilibj.command.Subsystem; /** * */ public class Retractor extends Subsystem { private final CANTalon motorA = RobotMap.retractorMotorA; // Put methods for controlling this subsystem // here. Call these from Commands. public void initDefaultCommand() { // Set the default command for a subsystem here. setDefaultCommand(new DoNothing()); } public void set(double target) { set(target); } public void methods() { this.motorA.setEncPosition(1); this.motorA.setAllowableClosedLoopErr(400); this.motorA.setEncPosition(1); this.motorA.setPosition(0); this.motorA.setPulseWidthPosition(0); this.motorA.setSetpoint(0); this.motorA.configEncoderCodesPerRev(360); this.motorA.disable(); this.motorA.enable(); this.motorA.pidGet(); } public void setControlModeTest() { //case statement this.motorA.changeControlMode(CANTalon.TalonControlMode.Position); this.motorA.changeControlMode(CANTalon.TalonControlMode.PercentVbus); } }
21.184615
74
0.681191
40daf278e687a7b53e044771bab181d6ba494179
1,557
package ichttt.mods.mcpaint.client.gui.button; import com.mojang.blaze3d.matrix.MatrixStack; import ichttt.mods.mcpaint.MCPaint; import ichttt.mods.mcpaint.client.gui.drawutil.EnumDrawType; import net.minecraft.client.gui.widget.button.Button; import net.minecraft.client.resources.I18n; import net.minecraft.util.text.TranslationTextComponent; import java.awt.*; import java.util.Locale; public class GuiButtonTextToggle extends Button { private final int color; public final EnumDrawType type; public boolean toggled = true; public GuiButtonTextToggle(int x, int y, int widthIn, int heightIn, EnumDrawType type, IPressable pressable) { super(x, y, widthIn, heightIn, new TranslationTextComponent(MCPaint.MODID + ".gui." + type.toString().toLowerCase(Locale.ENGLISH)), pressable); this.color = Color.GREEN.getRGB(); this.type = type; } @Override public void render(MatrixStack stack, int mouseX, int mouseY, float partialTicks) { if (this.visible) { //GuiHollowButton if (toggled) { this.vLine(stack, this.x - 1, this.y - 1, this.y + this.height, this.color); this.vLine(stack, this.x + this.width, this.y - 1, this.y + this.height, this.color); this.hLine(stack, this.x - 1, this.x + this.width, this.y - 1, this.color); this.hLine(stack, this.x - 1, this.x + this.width, this.y + this.height, this.color); } super.render(stack, mouseX, mouseY, partialTicks); } } }
40.973684
151
0.668593
f4acb2819a814c37ffc9e1db2ff9e03a22a80808
4,940
package com.hedera.hashgraph.sdk; import com.google.protobuf.InvalidProtocolBufferException; import com.hedera.hashgraph.sdk.proto.ContractDeleteTransactionBody; import com.hedera.hashgraph.sdk.proto.SchedulableTransactionBody; import com.hedera.hashgraph.sdk.proto.SmartContractServiceGrpc; import com.hedera.hashgraph.sdk.proto.TransactionBody; import com.hedera.hashgraph.sdk.proto.TransactionResponse; import io.grpc.MethodDescriptor; import javax.annotation.Nullable; import java.util.LinkedHashMap; import java.util.Objects; /** * Marks a contract as deleted, moving all its current hbars to another account. */ public final class ContractDeleteTransaction extends Transaction<ContractDeleteTransaction> { @Nullable private ContractId contractId = null; @Nullable private ContractId transferContractId = null; @Nullable private AccountId transferAccountId = null; public ContractDeleteTransaction() { } ContractDeleteTransaction(LinkedHashMap<TransactionId, LinkedHashMap<AccountId, com.hedera.hashgraph.sdk.proto.Transaction>> txs) throws InvalidProtocolBufferException { super(txs); initFromTransactionBody(); } ContractDeleteTransaction(com.hedera.hashgraph.sdk.proto.TransactionBody txBody) { super(txBody); initFromTransactionBody(); } @Nullable public ContractId getContractId() { return contractId; } /** * Sets the contract ID which should be deleted. * * @param contractId The ContractId to be set * @return {@code this} */ public ContractDeleteTransaction setContractId(ContractId contractId) { Objects.requireNonNull(contractId); requireNotFrozen(); this.contractId = contractId; return this; } @Nullable public AccountId getTransferAccountId() { return transferAccountId; } /** * Sets the account ID which will receive all remaining hbars. * <p> * This is mutually exclusive with {@link #setTransferContractId(ContractId)}. * * @param transferAccountId The AccountId to be set * @return {@code this} */ public ContractDeleteTransaction setTransferAccountId(AccountId transferAccountId) { Objects.requireNonNull(transferAccountId); requireNotFrozen(); this.transferAccountId = transferAccountId; return this; } @Nullable public ContractId getTransferContractId() { return transferContractId; } /** * Sets the contract ID which will receive all remaining hbars. * <p> * This is mutually exclusive with {@link #setTransferAccountId(AccountId)}. * * @param transferContractId The ContractId to be set * @return {@code this} */ public ContractDeleteTransaction setTransferContractId(ContractId transferContractId) { Objects.requireNonNull(transferContractId); requireNotFrozen(); this.transferContractId = transferContractId; return this; } @Override void validateChecksums(Client client) throws BadEntityIdException { if (contractId != null) { contractId.validateChecksum(client); } if (transferContractId != null) { transferContractId.validateChecksum(client); } if (transferAccountId != null) { transferAccountId.validateChecksum(client); } } @Override MethodDescriptor<com.hedera.hashgraph.sdk.proto.Transaction, TransactionResponse> getMethodDescriptor() { return SmartContractServiceGrpc.getDeleteContractMethod(); } void initFromTransactionBody() { var body = sourceTransactionBody.getContractDeleteInstance(); if (body.hasContractID()) { contractId = ContractId.fromProtobuf(body.getContractID()); } if (body.hasTransferContractID()) { transferContractId = ContractId.fromProtobuf(body.getTransferContractID()); } if (body.hasTransferAccountID()) { transferAccountId = AccountId.fromProtobuf(body.getTransferAccountID()); } } ContractDeleteTransactionBody.Builder build() { var builder = ContractDeleteTransactionBody.newBuilder(); if (contractId != null) { builder.setContractID(contractId.toProtobuf()); } if (transferAccountId != null) { builder.setTransferAccountID(transferAccountId.toProtobuf()); } if (transferContractId != null) { builder.setTransferContractID(transferContractId.toProtobuf()); } return builder; } @Override void onFreeze(TransactionBody.Builder bodyBuilder) { bodyBuilder.setContractDeleteInstance(build()); } @Override void onScheduled(SchedulableTransactionBody.Builder scheduled) { scheduled.setContractDeleteInstance(build()); } }
31.069182
173
0.689676
475cd0994d8667f487bf418e1fe6017b84c6ad80
2,395
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.workbench.services.verifier.core.checks.base; import org.drools.workbench.services.verifier.api.client.configuration.AnalyzerConfiguration; import org.drools.workbench.services.verifier.api.client.maps.InspectorList; import org.drools.workbench.services.verifier.api.client.reporting.CheckType; import org.drools.workbench.services.verifier.core.cache.RuleInspectorCache; import org.drools.workbench.services.verifier.core.cache.inspectors.RuleInspector; public abstract class OneToManyCheck extends SingleCheck { private final InspectorList<RuleInspector> ruleInspectors; private RuleInspectorCache.Filter filter; public OneToManyCheck( final RuleInspector ruleInspector, final RuleInspectorCache.Filter filter, final AnalyzerConfiguration configuration, final CheckType checkType ) { this( ruleInspector, configuration, checkType ); this.filter = filter; } public OneToManyCheck( final RuleInspector ruleInspector, final AnalyzerConfiguration configuration, final CheckType checkType ) { super( ruleInspector, checkType ); ruleInspectors = new InspectorList<>( configuration ); } protected boolean thereIsAtLeastOneRow() { return getOtherRows().size() >= 1; } public RuleInspector getRuleInspector() { return ruleInspector; } public InspectorList<RuleInspector> getOtherRows() { ruleInspectors.clear(); ruleInspectors.addAll( ruleInspector.getCache() .all( filter ) ); return ruleInspectors; } }
36.287879
93
0.683925
8c5ff7b87e6638c598bf37b8c9136aec1a59ab5d
605
package de.zalando.zally.configuration; import de.zalando.zally.rule.ApiValidator; import de.zalando.zally.rule.CompositeRulesValidator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; @Configuration public class RulesValidatorConfiguration { @Autowired private CompositeRulesValidator compositeValidator; @Bean @Primary public ApiValidator validator() { return compositeValidator; } }
27.5
62
0.808264
1b662fd570dbf5852a99f9b0139de346d2b8bdc4
811
package modelo.edificios.plazacentral; import modelo.juego.Oro; import modelo.edificios.Edificio; import modelo.unidades.aldeano.Aldeano; public class EstadoPlazaCentralCreada implements EstadoPlazaCentral{ private static final String NOMBRE_ESTADO = "Disponible"; @Override public Aldeano crearAldeano(Oro oro) { return new Aldeano(oro); } @Override public void reparar(Edificio plaza) { plaza.incrementarVida(); } @Override public void recibirDanio(Edificio plazaCentral, int danio) { plazaCentral.reducirVida(danio); } @Override public void avanzarTurno(Edificio plazaCentral) { // Plaza central creada no maneja turnos } @Override public String getNombreEstado() { return NOMBRE_ESTADO; } }
22.527778
68
0.696671
11fdc01d72c4c8f280611c432ebe331b297b6f98
3,749
package gg.projecteden.nexus.features.commands; import gg.projecteden.nexus.features.minigames.Minigames; import gg.projecteden.nexus.framework.commands.models.CustomCommand; import gg.projecteden.nexus.framework.commands.models.annotations.Aliases; import gg.projecteden.nexus.framework.commands.models.annotations.Arg; import gg.projecteden.nexus.framework.commands.models.annotations.Description; import gg.projecteden.nexus.framework.commands.models.annotations.Path; import gg.projecteden.nexus.framework.commands.models.annotations.Permission; import gg.projecteden.nexus.framework.commands.models.annotations.Permission.Group; import gg.projecteden.nexus.framework.commands.models.events.CommandEvent; import gg.projecteden.nexus.models.back.Back; import gg.projecteden.nexus.models.back.BackService; import gg.projecteden.nexus.models.nerd.Rank; import gg.projecteden.nexus.utils.CitizensUtils; import gg.projecteden.nexus.utils.JsonBuilder; import lombok.NoArgsConstructor; import org.bukkit.Location; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause; import java.text.DecimalFormat; @Aliases("return") @NoArgsConstructor @Description("Return to your previous location after teleporting") public class BackCommand extends CustomCommand implements Listener { private final BackService service = new BackService(); private Back back; public BackCommand(CommandEvent event) { super(event); back = service.get(player()); } @Path("[count]") void back(@Arg(value = "1", permission = Group.STAFF, min = 1, max = 10) int count) { Location location = null; if (back.getLocations().size() >= count) location = back.getLocations().get(count - 1); if (location == null) error("You have no back location"); player().teleportAsync(location, TeleportCause.COMMAND); } @Path("locations [player]") @Permission(Group.STAFF) void view(@Arg("self") Back back) { if (back.getLocations() == null || back.getLocations().size() == 0) error("You have no back locations"); int i = 0; JsonBuilder json = json(PREFIX + "Locations (&eClick to go&3):"); for (Location location : back.getLocations()) { ++i; int x = (int) location.getX(), y = (int) location.getY(), z = (int) location.getZ(), yaw = (int) location.getYaw(), pitch = (int) location.getPitch(); json.group().newline() .next("&3" + new DecimalFormat("#00").format(i) + " &e" + location.getWorld().getName() + " &7/ &e" + x + " &7/ &e" + y + " &7/ &e" + z) .command("/tppos " + x + " " + y + " " + z + " " + yaw + " " + pitch + " " + location.getWorld().getName()) .hover("&eClick to teleport"); } send(json); } @EventHandler(priority = EventPriority.MONITOR) public void onTeleport(PlayerTeleportEvent event) { if (event.isCancelled()) return; Player player = event.getPlayer(); Location location = event.getFrom(); if (CitizensUtils.isNPC(player)) return; if (TeleportCause.COMMAND != event.getCause()) return; if (!Rank.of(player).isStaff()) if (Minigames.isMinigameWorld(player.getWorld())) return; Back back = new BackService().get(player); back.add(location); new BackService().save(back); } @EventHandler public void onDeath(EntityDeathEvent event) { if (!(event.getEntity() instanceof Player player)) return; if (!Rank.of(player).isStaff()) return; if (CitizensUtils.isNPC(player)) return; Back back = new BackService().get(player); back.add(player.getLocation()); new BackService().save(back); } }
35.367925
112
0.727127
794daf1b6c960161fa1bc19a9ea2fedeb41b3980
797
package br.com.arbo.org.springframework.boot.builder; import java.util.stream.Stream; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.boot.context.event.ApplicationPreparedEvent; import org.springframework.context.ApplicationListener; class SingletonsPrepare implements ApplicationListener<ApplicationPreparedEvent> { SingletonsPrepare(Stream<Object> singletons) { this.singletons = singletons; } @Override public void onApplicationEvent(ApplicationPreparedEvent event) { ConfigurableListableBeanFactory beanFactory = event.getApplicationContext().getBeanFactory(); singletons.forEach( bean -> beanFactory.registerSingleton( bean.getClass().getName(), bean)); } private final Stream<Object> singletons; }
25.709677
80
0.814304
b1fd1a349bcf35dd8f5c1ee5e00d91327d72cfbb
3,918
/** * Copyright (C) 2010-2018 Gordon Fraser, Andrea Arcuri and EvoSuite * contributors * * This file is part of EvoSuite. * * EvoSuite 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 3.0 of the License, or * (at your option) any later version. * * EvoSuite 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 Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with EvoSuite. If not, see <http://www.gnu.org/licenses/>. */ /** * */ package org.evosuite.instrumentation.mutation; import org.evosuite.coverage.mutation.Mutation; import org.evosuite.coverage.mutation.MutationPool; import org.evosuite.graphs.cfg.BytecodeInstruction; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.JumpInsnNode; import org.objectweb.asm.tree.LabelNode; import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.analysis.Frame; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; /** * <p>NegateCondition class.</p> * * @author Gordon Fraser */ public class NegateCondition implements MutationOperator { private static Map<Integer, Integer> opcodeMap = new HashMap<Integer, Integer>(); public static final String NAME = "NegateCondition"; static { opcodeMap.put(Opcodes.IF_ACMPEQ, Opcodes.IF_ACMPNE); opcodeMap.put(Opcodes.IF_ACMPNE, Opcodes.IF_ACMPEQ); opcodeMap.put(Opcodes.IF_ICMPEQ, Opcodes.IF_ICMPNE); opcodeMap.put(Opcodes.IF_ICMPGE, Opcodes.IF_ICMPLT); opcodeMap.put(Opcodes.IF_ICMPGT, Opcodes.IF_ICMPLE); opcodeMap.put(Opcodes.IF_ICMPLE, Opcodes.IF_ICMPGT); opcodeMap.put(Opcodes.IF_ICMPLT, Opcodes.IF_ICMPGE); opcodeMap.put(Opcodes.IF_ICMPNE, Opcodes.IF_ICMPEQ); opcodeMap.put(Opcodes.IFEQ, Opcodes.IFNE); opcodeMap.put(Opcodes.IFGE, Opcodes.IFLT); opcodeMap.put(Opcodes.IFGT, Opcodes.IFLE); opcodeMap.put(Opcodes.IFLE, Opcodes.IFGT); opcodeMap.put(Opcodes.IFLT, Opcodes.IFGE); opcodeMap.put(Opcodes.IFNE, Opcodes.IFEQ); opcodeMap.put(Opcodes.IFNONNULL, Opcodes.IFNULL); opcodeMap.put(Opcodes.IFNULL, Opcodes.IFNONNULL); } /* (non-Javadoc) * @see org.evosuite.cfg.instrumentation.MutationOperator#apply(org.objectweb.asm.tree.MethodNode, java.lang.String, java.lang.String, org.evosuite.cfg.BytecodeInstruction) */ /** {@inheritDoc} */ @Override public List<Mutation> apply(MethodNode mn, String className, String methodName, BytecodeInstruction instruction, Frame frame) { List<Mutation> mutations = new LinkedList<Mutation>(); JumpInsnNode node = (JumpInsnNode) instruction.getASMNode(); LabelNode target = node.label; // insert mutation into bytecode with conditional JumpInsnNode mutation = new JumpInsnNode(getOpposite(node.getOpcode()), target); // insert mutation into pool Mutation mutationObject = MutationPool.addMutation(className, methodName, NAME, instruction, mutation, Mutation.getDefaultInfectionDistance()); mutations.add(mutationObject); return mutations; } private static int getOpposite(int opcode) { return opcodeMap.get(opcode); } /* (non-Javadoc) * @see org.evosuite.cfg.instrumentation.mutation.MutationOperator#isApplicable(org.evosuite.cfg.BytecodeInstruction) */ /** {@inheritDoc} */ @Override public boolean isApplicable(BytecodeInstruction instruction) { return instruction.isBranch(); } }
35.297297
173
0.713374
9fb30dd6bee348010b97c7d886f7b717ee6065db
2,081
package tinyapps.apptemplate.base.util.wip; /** * Created by TheFinestArtist on 2014. 9. 2.. */ public class LanguageDetector { // public static boolean isEnglish(CharSequence charSequence) { // boolean isEnglish = true; // for (char c : charSequence.toString().toCharArray()) { // if (Character.UnicodeBlock.of(c) != Character.UnicodeBlock.BASIC_LATIN) { // isEnglish = false; // break; // } // } // // return isEnglish; // } // // public static boolean hasKorean(CharSequence charSequence) { // boolean hasKorean = false; // for (char c : charSequence.toString().toCharArray()) { // if (Character.UnicodeBlock.of(c) == Character.UnicodeBlock.HANGUL_JAMO // || Character.UnicodeBlock.of(c) == Character.UnicodeBlock.HANGUL_COMPATIBILITY_JAMO // || Character.UnicodeBlock.of(c) == Character.UnicodeBlock.HANGUL_SYLLABLES) { // hasKorean = true; // break; // } // } // // return hasKorean; // } // // public static boolean hasJapanese(CharSequence charSequence) { // boolean hasJapanese = false; // for (char c : charSequence.toString().toCharArray()) { // if (Character.UnicodeBlock.of(c) == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS // || Character.UnicodeBlock.of(c) == Character.UnicodeBlock.HIRAGANA // || Character.UnicodeBlock.of(c) == Character.UnicodeBlock.KATAKANA // || Character.UnicodeBlock.of(c) == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS // || Character.UnicodeBlock.of(c) == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS // || Character.UnicodeBlock.of(c) == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION) { // hasJapanese = true; // break; // } // } // // return hasJapanese; // } // // public enum Language {Korean, Japanese, English} }
39.264151
110
0.586257
992d50e56192ad2ffa1be7c7828a7183c9474701
1,487
package chapter2.section2; /** * Created by Rene Argento on 19/02/17. */ //This implementation uses the third mergesort improvement: //Improvement #3 - Avoid array copy during merge by switching arguments public class Exercise23_Improvements3_AvoidCopy { public static void mergeSort(Comparable[] array) { //Improvement #3 - Eliminate the copy to the auxiliary array on merge Comparable[] aux = array.clone(); sort(aux, array, 0, array.length - 1); } private static void sort(Comparable[] array, Comparable[] aux, int low, int high) { if(high <= low) { return; } int middle = low + (high - low) / 2; sort(aux, array, low, middle); sort(aux, array, middle + 1, high); merge(array, aux, low, middle, high); } @SuppressWarnings("unchecked") private static void merge(Comparable[] array, Comparable[] aux, int low, int middle, int high) { int indexLeft = low; int indexRight = middle + 1; for (int i = low; i <= high; i++) { if (indexLeft > middle) { aux[i] = array[indexRight++]; } else if (indexRight > high) { aux[i] = array[indexLeft++]; } else if (array[indexLeft].compareTo(array[indexRight]) < 0) { aux[i] = array[indexLeft++]; // to ensure stability } else { aux[i] = array[indexRight++]; } } } }
30.346939
100
0.562878
1e588df0ea71a527cbfa3b75ff15a38f804fcfcb
21,212
package org.carlspring.strongbox.providers.io; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URI; import java.nio.channels.FileChannel; import java.nio.channels.SeekableByteChannel; import java.nio.file.AccessMode; import java.nio.file.CopyOption; import java.nio.file.DirectoryStream; import java.nio.file.DirectoryStream.Filter; import java.nio.file.FileStore; import java.nio.file.FileSystem; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.NoSuchFileException; import java.nio.file.OpenOption; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.StandardCopyOption; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.FileAttribute; import java.nio.file.attribute.FileAttributeView; import java.nio.file.spi.FileSystemProvider; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Consumer; import java.util.stream.Collectors; import javax.inject.Inject; import org.apache.commons.io.output.ProxyOutputStream; import org.carlspring.strongbox.storage.repository.Repository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.FileSystemUtils; /** * This class decorates storage {@link FileSystemProvider}. * <br> * Note that almost all {@link Path} operations in this implementation must * delegate invocations into {@link Files} utility class with {@link RepositoryPath}'s target as parameters. * * TODO: we need a proper implementation against Service Provider Interface (SPI) specification * * @author Sergey Bespalov */ public abstract class StorageFileSystemProvider extends FileSystemProvider { public static final String STRONGBOX_SCHEME = "strongbox"; private static final Logger logger = LoggerFactory.getLogger(StorageFileSystemProvider.class); private FileSystemProvider target; @Inject private RepositoryPathLock repositoryPathLock; public StorageFileSystemProvider(FileSystemProvider target) { super(); this.target = target; } public String getScheme() { return STRONGBOX_SCHEME; } public FileSystem newFileSystem(URI uri, Map<String, ?> env) throws IOException { throw new UnsupportedOperationException(); } public FileSystem getFileSystem(URI uri) { throw new UnsupportedOperationException(); } public Path getPath(URI uri) { throw new UnsupportedOperationException(); } public SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) throws IOException { return getTarget().newByteChannel(unwrap(path), options, attrs); } @Override public FileChannel newFileChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) throws IOException { return getTarget().newFileChannel(unwrap(path), options, attrs); } public DirectoryStream<Path> newDirectoryStream(Path dir, Filter<? super Path> filter) throws IOException { DirectoryStream<Path> ds = getTarget().newDirectoryStream(unwrap(dir), filter); if (!(dir instanceof RepositoryPath)) { return ds; } RepositoryPath repositoryDir = (RepositoryPath) dir; return new DirectoryStream<Path>() { @Override public void close() throws IOException { ds.close(); } @Override public Iterator<Path> iterator() { return createRepositoryDsIterator(repositoryDir.getFileSystem(), ds.iterator()); } }; } protected Iterator<Path> createRepositoryDsIterator(LayoutFileSystem rfs, Iterator<Path> iterator) { return new Iterator<Path>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public Path next() { return new RepositoryPath(iterator.next(), rfs); } @Override public void remove() { iterator.remove(); } @Override public void forEachRemaining(Consumer<? super Path> action) { iterator.forEachRemaining(action); } }; } public void createDirectory(Path dir, FileAttribute<?>... attrs) throws IOException { getTarget().createDirectory(unwrap(dir), attrs); } public void delete(Path path) throws IOException { delete(path, false); } public void delete(Path path, boolean force) throws IOException { if (!(path instanceof RepositoryPath)) { getTarget().delete(path); return; } RepositoryPath repositoryPath = (RepositoryPath) path; if (!Files.exists(repositoryPath.getTarget())) { throw new NoSuchFileException(unwrap(repositoryPath).toString()); } if (!Files.isDirectory(repositoryPath)) { doDeletePath(repositoryPath, force, true); } else { Files.walkFileTree(repositoryPath, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { // Checksum files will be deleted during directory walking doDeletePath((RepositoryPath) file, force, false); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { Files.delete(unwrap(dir)); return FileVisitResult.CONTINUE; } }); } } protected void doDeletePath(RepositoryPath repositoryPath, boolean force, boolean deleteChecksum) throws IOException { doDeletePath(repositoryPath, force); if (!deleteChecksum) { return; } for (RepositoryPath checksumPath : resolveChecksumPathMap(repositoryPath).values()) { if (!Files.exists(unwrap(checksumPath))) { continue; } doDeletePath(checksumPath, force); } } public Map<String, RepositoryPath> resolveChecksumPathMap(RepositoryPath repositoryPath) { Map<String, RepositoryPath> result = new HashMap<>(); for (String digestAlgorithm : repositoryPath.getFileSystem().getDigestAlgorithmSet()) { // it creates Checksum file extension name form Digest algorithm // name: SHA-1->sha1 String extension = digestAlgorithm.replaceAll("-", "").toLowerCase(); result.put(digestAlgorithm, repositoryPath.resolveSibling(repositoryPath.getFileName() + "." + extension)); } return result; } protected void doDeletePath(RepositoryPath repositoryPath, boolean force) throws IOException { Repository repository = repositoryPath.getFileSystem().getRepository(); if (!repository.isTrashEnabled()) { Files.deleteIfExists(repositoryPath.getTarget()); return; } RepositoryPath trashPath = getTrashPath(repositoryPath); Files.move(repositoryPath.getTarget(), trashPath.getTarget(), StandardCopyOption.REPLACE_EXISTING); if (force && repository.allowsForceDeletion()) { deleteTrash(repositoryPath); } } public void undelete(RepositoryPath path) throws IOException { Repository repository = path.getFileSystem().getRepository(); if (!repository.isTrashEnabled()) { return; } RepositoryPath trashPath = getTrashPath(path); if (!Files.exists(trashPath.getTarget())) { return; } if (!Files.isDirectory(trashPath.getTarget())) { Files.move(trashPath.getTarget(), path.getTarget(), StandardCopyOption.REPLACE_EXISTING); } else { Files.walkFileTree(trashPath.getTarget(), new MoveDirectoryVisitor(trashPath.getTarget(), path.getTarget(), StandardCopyOption.REPLACE_EXISTING)); } } public RepositoryPath moveFromTemporaryDirectory(TempRepositoryPath tempPath) throws IOException { RepositoryPath path = tempPath.getTempTarget(); if (!Files.exists(tempPath.getTarget())) { return null; } if (!Files.exists(unwrap(path).getParent())) { Files.createDirectories(unwrap(path).getParent()); } Files.move(tempPath.getTarget(), path.getTarget(), StandardCopyOption.REPLACE_EXISTING); //path.artifactEntry = tempPath.artifactEntry; return path; } public void deleteTrash(RepositoryPath path) throws IOException { Repository repository = path.getFileSystem().getRepository(); if (!repository.isTrashEnabled()) { return; } RepositoryPath trashPath = getTrashPath(path); if (!Files.exists(trashPath.getTarget())) { return; } else { FileSystemUtils.deleteRecursively(trashPath.getTarget()); Files.createDirectories(trashPath); } } protected RepositoryPath getTrashPath(RepositoryPath path) throws IOException { if (RepositoryFiles.isTrash(path)) { return path; } RepositoryPath trashBasePath = path.getFileSystem().getTrashPath(); RepositoryPath trashPath = rebase(path, trashBasePath); if (!Files.exists(trashPath.getParent().getTarget())) { logger.debug(String.format("Creating: dir-[%s]", trashPath.getParent())); Files.createDirectories(trashPath.getParent().getTarget()); } return trashPath; } protected static RepositoryPath rebase(RepositoryPath source, RepositoryPath targetBase) { String sourceRelative = source.getRoot().relativize(source.getTarget()).toString(); // XXX[SBESPALOV]: We try to convert path from source to target // FileSystem and need to check this on different // Storage types. // Note that this is only draft implementation, and probably in the // future we will need something like separate // `FileSystemPathConverter` to convert Paths from one FileSystem to // another. Such a `FileSystemPathConverter` // can be provided by the `RepositoryFileSystem` instance. String sTargetPath = sourceRelative; return targetBase.resolve(sTargetPath).toAbsolutePath(); } @Override public InputStream newInputStream(Path path, OpenOption... options) throws IOException { return repositoryPathLock.lockInputStream((RepositoryPath) path, () -> super.newInputStream(unwrap(path), options)); } @Override public OutputStream newOutputStream(Path path, OpenOption... options) throws IOException { TempRepositoryPath temp = RepositoryFiles.temporary((RepositoryPath) path); return new TempOutputStream(temp, options); } public void copy(Path source, Path target, CopyOption... options) throws IOException { getTarget().copy(unwrap(source), unwrap(target), options); } public void move(Path source, Path target, CopyOption... options) throws IOException { getTarget().move(unwrap(source), unwrap(target), options); } public boolean isSameFile(Path path, Path path2) throws IOException { return getTarget().isSameFile(unwrap(path), unwrap(path2)); } public boolean isHidden(Path path) throws IOException { return getTarget().isHidden(unwrap(path)); } public FileStore getFileStore(Path path) throws IOException { return getTarget().getFileStore(unwrap(path)); } public void checkAccess(Path path, AccessMode... modes) throws IOException { getTarget().checkAccess(unwrap(path), modes); } public <V extends FileAttributeView> V getFileAttributeView(Path path, Class<V> type, LinkOption... options) { return getTarget().getFileAttributeView(unwrap(path), type, options); } public <A extends BasicFileAttributes> A readAttributes(Path path, Class<A> type, LinkOption... options) throws IOException { if (RepositoryFileAttributes.class.isAssignableFrom(type) && !RepositoryPath.class.isInstance(path)) { throw new IOException(String.format("Requested path is not [%s].", RepositoryPath.class.getSimpleName())); } BasicFileAttributes targetAttributes = getTarget().readAttributes(unwrap(path), BasicFileAttributes.class, options); if (!RepositoryFileAttributes.class.isAssignableFrom(type)) { return (A) targetAttributes; } RepositoryFileAttributes repositoryFileAttributes = new RepositoryFileAttributes(targetAttributes, getRepositoryFileAttributes((RepositoryPath) path, RepositoryFiles.parseAttributes("*") .toArray(new RepositoryFileAttributeType[] {}))); return (A) repositoryFileAttributes; } public Map<String, Object> readAttributes(Path path, String attributes, LinkOption... options) throws IOException { if (!RepositoryPath.class.isInstance(path)) { return getTarget().readAttributes(path, attributes, options); } RepositoryPath repositoryPath = (RepositoryPath) path; Map<String, Object> result = new HashMap<>(); if (!attributes.startsWith(STRONGBOX_SCHEME)) { result.putAll(getTarget().readAttributes(unwrap(path), attributes, options)); if (!attributes.equals("*")) { return result; } } Set<RepositoryFileAttributeType> targetRepositoryAttributes = new HashSet<>( RepositoryFiles.parseAttributes(attributes)); final Map<RepositoryFileAttributeType, Object> repositoryFileAttributes = new HashMap<>(); for (Iterator<RepositoryFileAttributeType> iterator = targetRepositoryAttributes.iterator(); iterator.hasNext();) { RepositoryFileAttributeType repositoryFileAttributeType = iterator.next(); Optional.ofNullable(repositoryPath.cachedAttributes.get(repositoryFileAttributeType)) .ifPresent(v -> { repositoryFileAttributes.put(repositoryFileAttributeType, v); iterator.remove(); }); } if (!targetRepositoryAttributes.isEmpty()) { Map<RepositoryFileAttributeType, Object> newAttributes = getRepositoryFileAttributes(repositoryPath, targetRepositoryAttributes.toArray(new RepositoryFileAttributeType[targetRepositoryAttributes.size()])); newAttributes.entrySet() .stream() .forEach(e -> { repositoryFileAttributes.put(e.getKey(), e.getValue()); repositoryPath.cachedAttributes.put(e.getKey(), e.getValue()); }); } result.putAll(repositoryFileAttributes.entrySet() .stream() .collect(Collectors.toMap(e -> e.getKey() .getName(), e -> e.getValue()))); return result; } protected abstract Map<RepositoryFileAttributeType, Object> getRepositoryFileAttributes(RepositoryPath repositoryRelativePath, RepositoryFileAttributeType... attributeTypes) throws IOException; public void setAttribute(Path path, String attribute, Object value, LinkOption... options) throws IOException { getTarget().setAttribute(unwrap(path), attribute, value, options); } private Path unwrap(Path path) { return path instanceof RepositoryPath ? ((RepositoryPath) path).getTarget() : path; } private FileSystemProvider getTarget() { return target; } public static class MoveDirectoryVisitor extends SimpleFileVisitor<Path> { private final Path fromPath; private final Path toPath; private final CopyOption copyOption; public MoveDirectoryVisitor(Path fromPath, Path toPath, CopyOption copyOption) { this.fromPath = fromPath; this.toPath = toPath; this.copyOption = copyOption; } @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { Path targetPath = toPath.resolve(fromPath.relativize(dir)); if (!Files.exists(targetPath)) { Files.createDirectory(targetPath); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.move(file, toPath.resolve(fromPath.relativize(file)), copyOption); return FileVisitResult.CONTINUE; } } private class TempOutputStream extends ProxyOutputStream { private TempRepositoryPath path; public TempOutputStream(TempRepositoryPath path, OpenOption... options) throws IOException { super(StorageFileSystemProvider.super.newOutputStream(unwrap(path), options)); this.path = path; } @Override public void close() throws IOException { super.close(); try { moveFromTemporaryDirectory(path); } finally { if (Files.exists(path)) { Files.delete(path.getTarget()); } } } } }
32.090772
201
0.554309
391df6494e6890bfbba1bb216d63d55496cbaf09
499
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.ostrichemulators.jfxhacc.mapper; import com.ostrichemulators.jfxhacc.model.IDable; import org.openrdf.model.URI; /** * * @author ryan * @param <T> */ public interface MapperListener<T extends IDable> { public void added( T t ); public void updated( T t ); public void removed( URI uri ); }
20.791667
79
0.723447
00a3eaff587065cca4838987b3f76246fc042316
1,205
package com.binance.dex.api.client.domain.ws; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; @JsonIgnoreProperties(ignoreUnknown = true) public class OutboundAccountInfo { @JsonProperty("e") private String eventType; public String getEventType() { return eventType; } public void setEventType(String eventType) { this.eventType = eventType; } @Override public String toString() { return "OutboundAccountInfo{" + "eventType='" + eventType + '\'' + ", eventHeight=" + eventHeight + ", balances=" + balances + '}'; } public Long getEventHeight() { return eventHeight; } public void setEventHeight(Long eventHeight) { this.eventHeight = eventHeight; } public List<AssertBalance> getBalances() { return balances; } public void setBalances(List<AssertBalance> balances) { this.balances = balances; } @JsonProperty("E") private Long eventHeight; @JsonProperty("B") private List<AssertBalance> balances; }
23.627451
61
0.635685
2d298aebc2cd235d7f31879f8f8518749ddcb5b9
243
package com.jackz314.colorpicker.renderer; import android.graphics.Canvas; public class ColorWheelRenderOption { public int density; public float maxRadius; public float cSize, strokeWidth, alpha, lightness; public Canvas targetCanvas; }
24.3
51
0.814815
61b37ffc56f0bd25a3516e7af87cd79e4aeb8507
3,733
package cn.felord.wepay.ali.sdk.api.domain; import cn.felord.wepay.ali.sdk.api.AlipayObject; import cn.felord.wepay.ali.sdk.api.internal.mapping.ApiField; /** * 个体工商户经营者信息 * * @author auto create * @version $Id: $Id */ public class OperatorInfo extends AlipayObject { private static final long serialVersionUID = 7537517617511285653L; /** * 个体工商户经营者证件到期日,格式为YYYY-MM-DD */ @ApiField("operator_cert_indate") private String operatorCertIndate; /** * 个体工商户经营者证件号码 */ @ApiField("operator_cert_no") private String operatorCertNo; /** * 个体工商户经营者证件照片背面图片(如证件类型为身份证则上传国徽面图片) */ @ApiField("operator_cert_pic_back") private String operatorCertPicBack; /** * 个体工商户经营者证件正面照片(如证件类型为身份证则需要上传头像面图片) */ @ApiField("operator_cert_pic_front") private String operatorCertPicFront; /** * 个体工商户经营者证件类型,支持传入的类型为:RESIDENT(居民身份证)括号中为每种类型的释义,不需要将括号中的内容当参数内容传入。 */ @ApiField("operator_cert_type") private String operatorCertType; /** * 张三 */ @ApiField("operator_name") private String operatorName; /** * <p>Getter for the field <code>operatorCertIndate</code>.</p> * * @return a {@link java.lang.String} object. */ public String getOperatorCertIndate() { return this.operatorCertIndate; } /** * <p>Setter for the field <code>operatorCertIndate</code>.</p> * * @param operatorCertIndate a {@link java.lang.String} object. */ public void setOperatorCertIndate(String operatorCertIndate) { this.operatorCertIndate = operatorCertIndate; } /** * <p>Getter for the field <code>operatorCertNo</code>.</p> * * @return a {@link java.lang.String} object. */ public String getOperatorCertNo() { return this.operatorCertNo; } /** * <p>Setter for the field <code>operatorCertNo</code>.</p> * * @param operatorCertNo a {@link java.lang.String} object. */ public void setOperatorCertNo(String operatorCertNo) { this.operatorCertNo = operatorCertNo; } /** * <p>Getter for the field <code>operatorCertPicBack</code>.</p> * * @return a {@link java.lang.String} object. */ public String getOperatorCertPicBack() { return this.operatorCertPicBack; } /** * <p>Setter for the field <code>operatorCertPicBack</code>.</p> * * @param operatorCertPicBack a {@link java.lang.String} object. */ public void setOperatorCertPicBack(String operatorCertPicBack) { this.operatorCertPicBack = operatorCertPicBack; } /** * <p>Getter for the field <code>operatorCertPicFront</code>.</p> * * @return a {@link java.lang.String} object. */ public String getOperatorCertPicFront() { return this.operatorCertPicFront; } /** * <p>Setter for the field <code>operatorCertPicFront</code>.</p> * * @param operatorCertPicFront a {@link java.lang.String} object. */ public void setOperatorCertPicFront(String operatorCertPicFront) { this.operatorCertPicFront = operatorCertPicFront; } /** * <p>Getter for the field <code>operatorCertType</code>.</p> * * @return a {@link java.lang.String} object. */ public String getOperatorCertType() { return this.operatorCertType; } /** * <p>Setter for the field <code>operatorCertType</code>.</p> * * @param operatorCertType a {@link java.lang.String} object. */ public void setOperatorCertType(String operatorCertType) { this.operatorCertType = operatorCertType; } /** * <p>Getter for the field <code>operatorName</code>.</p> * * @return a {@link java.lang.String} object. */ public String getOperatorName() { return this.operatorName; } /** * <p>Setter for the field <code>operatorName</code>.</p> * * @param operatorName a {@link java.lang.String} object. */ public void setOperatorName(String operatorName) { this.operatorName = operatorName; } }
24.083871
71
0.705599
a23384edf959f5b79ee312a1df386a6a5ee70921
2,255
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package programmingcontest.MICS2008Data; import java.io.File; import java.util.Scanner; import java.util.*; //import zhstructures.ZHTreeMap; /** * * @author awzurn */ public class Problem8 { private ArrayList<String> stringList = new ArrayList<String>(); private TreeMap<Double, ArrayList<String>> treeMap = new TreeMap<Double, ArrayList<String>>(); public Problem8(ArrayList<Integer> front, ArrayList<Integer> back){ Double num; for(Integer fr: front){ for(Integer ba: back){ num = new Double((double) fr/ba); /*ArrayList<String>*/ stringList = new ArrayList<String>(); stringList.add(fr.toString() + ":" + ba.toString()); if(treeMap.containsKey(num)){ stringList = treeMap.get(num); if(stringList.contains(fr.toString() + ":" + ba.toString())){ treeMap.put(num,stringList); } else{ stringList.add(fr.toString() + ":" + ba.toString()); treeMap.put(num, stringList); } } else{ treeMap.put(num, stringList); } } } for(Double numb: treeMap.keySet()){ for(String str: treeMap.get(numb)){ System.out.println(str); } } } public static void main(String args[]) throws Exception{ Scanner sc = new Scanner(new File("input8.txt")); ArrayList<Integer> front = new ArrayList<Integer>(); ArrayList<Integer> back = new ArrayList<Integer>(); front.add(sc.nextInt()); front.add(sc.nextInt()); front.add(sc.nextInt()); back.add(sc.nextInt()); back.add(sc.nextInt()); back.add(sc.nextInt()); back.add(sc.nextInt()); back.add(sc.nextInt()); back.add(sc.nextInt()); back.add(sc.nextInt()); back.add(sc.nextInt()); back.add(sc.nextInt()); Problem8 problem8 = new Problem8(front, back); } }
32.214286
98
0.527716
0d0bc3e583d6eb756caef1152811c2758c28bc59
4,788
package com.nickli.scheduleapp.emailStaff; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.nickli.scheduleapp.MainActivity; import com.nickli.scheduleapp.R; import java.util.ArrayList; public class EmailActivity extends AppCompatActivity implements EmailAdapter.StaffClickListener{ // Define variables private RecyclerView emailView; Button tvBack3; TextView staffEmail; private EmailAdapter adapter; private ArrayList<EmailUpload> list; FirebaseAuth auth; @Override // When activity is created protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Set frontend to activity_email layout setContentView(R.layout.activity_email); // Get user authentication and define database path auth = FirebaseAuth.getInstance(); String location = "staff/"; DatabaseReference root = FirebaseDatabase.getInstance().getReference(location); tvBack3 = findViewById(R.id.tv_back3); staffEmail = findViewById(R.id.staffEmail); EditText searchStaff = findViewById(R.id.searchStaff); // Implementing search text searchStaff.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { // Calls function filter(s.toString()); } }); emailView = findViewById(R.id.email_view); emailView.setHasFixedSize(true); emailView.setLayoutManager(new LinearLayoutManager(this)); list = new ArrayList<>(); // Connect to EmailAdapter to retrieve data from realtime database adapter = new EmailAdapter(this , list, this::selectedStaff); emailView.setAdapter(adapter); tvBack3.setOnClickListener(view -> { startActivity(new Intent(EmailActivity.this, MainActivity.class)); }); // Add all email information onto RecyclerView root.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { for (DataSnapshot dataSnapshot : snapshot.getChildren()){ EmailUpload emailUpload = dataSnapshot.getValue(EmailUpload.class); list.add(emailUpload); } adapter.notifyDataSetChanged(); } @Override public void onCancelled(@NonNull DatabaseError error) { } }); } // Changes RecyclerView based on text inside search private void filter(String text) { ArrayList<EmailUpload> filteredList = new ArrayList<>(); for (EmailUpload item : list) { if (item.getStaffName().toLowerCase().contains(text.toLowerCase())) { filteredList.add(item); } } adapter.filterList(filteredList); } @Override // When the Recycler View for a staff or teacher is pressed public void selectedStaff(EmailUpload emailUpload){ // Obtain the staff email from the Firebase Realtime Database String email = emailUpload.getStaffEmail(); // Convert the String email into an array String[] emails = email.split(","); // Create new activity to email staff or teacher Intent intent = new Intent(Intent.ACTION_SEND); // Enter the array of email(s) in the TO: section of the email client intent.putExtra(Intent.EXTRA_EMAIL, emails); // Shows an activity to select an email client intent.setType("message/rfc822"); // Opens the email client that is selected from the previous activity startActivity(Intent.createChooser(intent, "Choose an email client: ")); } }
34.695652
96
0.675856
ee57cf4905fc32944d4eb3486fd46d44e427abb2
208
package com.github.yusufcanb.micromamba4j; import lombok.Data; @Data public class MambaPackage { private String name; private String version; private String build; private String channel; }
17.333333
42
0.745192
d53ef2d937f776f0c59386b2257eeab6f7798783
926
class Person { String name; int grade_test1; int grade_test2; int grade_test3; public Person(String studentName, int grade1, int grade2, int grade3) { this.name = studentName; this.grade_test1 = grade1; this.grade_test2 = grade2; this.grade_test3 = grade3; } public String getName() { return name; } public float getAvg_grade() { float avg_grade = ((float) grade_test1 + grade_test2 + grade_test3) / 3; return avg_grade; } public static void main(String[] args) { Person jaden = new Person("Jaden", 75, 91, 69); Person alaina = new Person("Alaina", 91, 95, 79); System.out.println("Student " + jaden.getName() + "'s" + " average grade is " + jaden.getAvg_grade()); System.out.println("Student " + alaina.getName() + "'s" + " average grade is " + alaina.getAvg_grade()); } }
27.235294
112
0.595032
dc583dea2e83277669a9d723cc9d1df09bc98ae8
195
package org.ada.school.user.config; public interface Constants { String CLAIMS_ROLES_KEY = "claims_roles_key"; int TOKEN_DURATION_MINUTES = 60; String COOKIE_NAME = "cookie_name"; }
21.666667
49
0.748718
e37f4208c28ee99a1f087c4773c6870c8a8679e7
848
/* * 30-ago-2016: I18nManager.java */ package com.borjapintos.timezzz.util; import java.util.Locale; import java.util.ResourceBundle; /** * The Class I18nManager. * * @author Borja Pintos */ public class I18nManager { private static Locale currentLocale = null; private static ResourceBundle messages = null; private static void init(){ final String language = System.getProperty("user.country"); final String country = System.getProperty("user.language"); currentLocale = new Locale(language, country); messages = ResourceBundle.getBundle("Timezzz", currentLocale); } /** * Gets the value. * * @param key the key * @return the value */ public static String getValue(String key){ if (messages == null){ init(); } return messages.getString(key); } }
21.74359
68
0.659198
f4b8a3663b42552dcb84813b0e92b32666ffcb6b
3,198
package com.sldlt.navps.resource; import java.math.BigDecimal; import java.time.LocalDate; import java.util.List; import java.util.Map; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort.Direction; import org.springframework.data.util.Pair; import org.springframework.data.web.PageableDefault; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.format.annotation.DateTimeFormat.ISO; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.sldlt.navps.dto.NAVPSEntryDto; import com.sldlt.navps.dto.NAVPSPredictionDto; import com.sldlt.navps.service.NAVPSPredictionService; import com.sldlt.navps.service.NAVPSService; @RestController public class NAVPSResource { @Autowired private NAVPSService navpsService; @Autowired private NAVPSPredictionService navpsPredictionService; @GetMapping("/api/navps") public Page<NAVPSEntryDto> getNAVPS(@RequestParam(name = "fund", required = false) String fund, @DateTimeFormat(iso = ISO.DATE) @RequestParam(name = "dateFrom", required = false) LocalDate dateFrom, @DateTimeFormat(iso = ISO.DATE) @RequestParam(name = "dateTo", required = false) LocalDate dateTo, @PageableDefault(sort = { "date" }, direction = Direction.DESC) Pageable page) { return navpsService.listNAVPS(fund, dateFrom, dateTo, page); } @GetMapping("/api/navps/all") public List<NAVPSEntryDto> getNAVPS(@RequestParam("fund") String fund) { return navpsService.listAllNAVPS(fund); } @GetMapping("/api/navps/correlations") public Map<String, Map<String, BigDecimal>> getNAVPSCorrelations( @DateTimeFormat(iso = ISO.DATE) @RequestParam(name = "dateFrom", required = false) LocalDate dateFrom) { return navpsService.listAllCorrelations(dateFrom); } @GetMapping("/api/navps/scatter") public List<Pair<BigDecimal, BigDecimal>> getScatterNAVPS(@RequestParam("fundX") String fundX, @RequestParam("fundY") String fundY, @DateTimeFormat(iso = ISO.DATE) @RequestParam(name = "dateFrom") LocalDate dateFrom, @DateTimeFormat(iso = ISO.DATE) @RequestParam(name = "dateTo") LocalDate dateTo) { return navpsService.listNAVPSPaired(fundX, fundY, dateFrom, dateTo); } @GetMapping("/api/navps/predictions") public Map<LocalDate, Set<NAVPSPredictionDto>> getNAVPSPredictions(@RequestParam(name = "type") String type, @RequestParam(name = "fund") String fund, @DateTimeFormat(iso = ISO.DATE) @RequestParam(name = "dateFrom") LocalDate dateFrom, @DateTimeFormat(iso = ISO.DATE) @RequestParam(name = "dateTo") LocalDate dateTo) { return navpsPredictionService.getPredictions(fund, type, dateFrom, dateTo); } @GetMapping("/api/navps/predictions/types") public Set<String> getNAVPSPredictionTypes() { return navpsPredictionService.getPredictionsTypes(); } }
43.216216
135
0.749844
aa19a5d36908fe9432f476f9af6876e96cd83890
9,860
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ end_comment begin_package DECL|package|org.apache.camel.component.mllp package|package name|org operator|. name|apache operator|. name|camel operator|. name|component operator|. name|mllp package|; end_package begin_import import|import name|java operator|. name|util operator|. name|concurrent operator|. name|TimeUnit import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|CamelContext import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|EndpointInject import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|LoggingLevel import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|builder operator|. name|RouteBuilder import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|component operator|. name|mock operator|. name|MockEndpoint import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|impl operator|. name|DefaultCamelContext import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|test operator|. name|AvailablePortFinder import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|test operator|. name|junit operator|. name|rule operator|. name|mllp operator|. name|MllpClientResource import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|test operator|. name|junit4 operator|. name|CamelTestSupport import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|test operator|. name|mllp operator|. name|Hl7TestMessageGenerator import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|camel operator|. name|test operator|. name|mllp operator|. name|PassthroughProcessor import|; end_import begin_import import|import name|org operator|. name|hamcrest operator|. name|CoreMatchers import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Assert import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Rule import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Test import|; end_import begin_class DECL|class|MllpTcpServerConsumerMulitpleTcpPacketTest specifier|public class|class name|MllpTcpServerConsumerMulitpleTcpPacketTest extends|extends name|CamelTestSupport block|{ annotation|@ name|Rule DECL|field|mllpClient specifier|public name|MllpClientResource name|mllpClient init|= operator|new name|MllpClientResource argument_list|() decl_stmt|; annotation|@ name|EndpointInject argument_list|( literal|"mock://result" argument_list|) DECL|field|result name|MockEndpoint name|result decl_stmt|; annotation|@ name|Override DECL|method|createCamelContext () specifier|protected name|CamelContext name|createCamelContext parameter_list|() throws|throws name|Exception block|{ name|DefaultCamelContext name|context init|= operator|( name|DefaultCamelContext operator|) name|super operator|. name|createCamelContext argument_list|() decl_stmt|; name|context operator|. name|setUseMDCLogging argument_list|( literal|true argument_list|) expr_stmt|; name|context operator|. name|setName argument_list|( name|this operator|. name|getClass argument_list|() operator|. name|getSimpleName argument_list|() argument_list|) expr_stmt|; return|return name|context return|; block|} annotation|@ name|Override DECL|method|createRouteBuilder () specifier|protected name|RouteBuilder name|createRouteBuilder parameter_list|() block|{ specifier|final name|int name|groupInterval init|= literal|1000 decl_stmt|; specifier|final name|boolean name|groupActiveOnly init|= literal|false decl_stmt|; name|mllpClient operator|. name|setMllpHost argument_list|( literal|"localhost" argument_list|) expr_stmt|; name|mllpClient operator|. name|setMllpPort argument_list|( name|AvailablePortFinder operator|. name|getNextAvailable argument_list|() argument_list|) expr_stmt|; return|return operator|new name|RouteBuilder argument_list|() block|{ name|String name|routeId init|= literal|"mllp-receiver" decl_stmt|; annotation|@ name|Override specifier|public name|void name|configure parameter_list|() throws|throws name|Exception block|{ name|onCompletion argument_list|() operator|. name|log argument_list|( name|LoggingLevel operator|. name|INFO argument_list|, name|routeId argument_list|, literal|"Test route complete" argument_list|) expr_stmt|; name|fromF argument_list|( literal|"mllp://%s:%d" argument_list|, name|mllpClient operator|. name|getMllpHost argument_list|() argument_list|, name|mllpClient operator|. name|getMllpPort argument_list|() argument_list|) operator|. name|routeId argument_list|( name|routeId argument_list|) operator|. name|process argument_list|( operator|new name|PassthroughProcessor argument_list|( literal|"Before send to result" argument_list|) argument_list|) operator|. name|to argument_list|( name|result argument_list|) operator|. name|toF argument_list|( literal|"log://%s?level=INFO&groupInterval=%d&groupActiveOnly=%b" argument_list|, name|routeId argument_list|, name|groupInterval argument_list|, name|groupActiveOnly argument_list|) operator|. name|log argument_list|( name|LoggingLevel operator|. name|DEBUG argument_list|, name|routeId argument_list|, literal|"Test route received message" argument_list|) expr_stmt|; block|} block|} return|; block|} annotation|@ name|Test DECL|method|testReceiveSingleMessage () specifier|public name|void name|testReceiveSingleMessage parameter_list|() throws|throws name|Exception block|{ name|mllpClient operator|. name|connect argument_list|() expr_stmt|; name|String name|message init|= name|Hl7TestMessageGenerator operator|. name|generateMessage argument_list|() decl_stmt|; name|result operator|. name|expectedBodiesReceived argument_list|( name|message argument_list|) expr_stmt|; name|mllpClient operator|. name|sendFramedDataInMultiplePackets argument_list|( name|message argument_list|, operator|( name|byte operator|) literal|'\r' argument_list|) expr_stmt|; name|String name|acknowledgement init|= name|mllpClient operator|. name|receiveFramedData argument_list|() decl_stmt|; name|assertMockEndpointsSatisfied argument_list|( literal|10 argument_list|, name|TimeUnit operator|. name|SECONDS argument_list|) expr_stmt|; name|Assert operator|. name|assertThat argument_list|( literal|"Should be acknowledgment for message 1" argument_list|, name|acknowledgement argument_list|, name|CoreMatchers operator|. name|containsString argument_list|( name|String operator|. name|format argument_list|( literal|"MSA|AA|00001" argument_list|) argument_list|) argument_list|) expr_stmt|; block|} annotation|@ name|Test DECL|method|testReceiveMultipleMessages () specifier|public name|void name|testReceiveMultipleMessages parameter_list|() throws|throws name|Exception block|{ name|int name|sendMessageCount init|= literal|100 decl_stmt|; name|result operator|. name|expectedMessageCount argument_list|( name|sendMessageCount argument_list|) expr_stmt|; name|mllpClient operator|. name|setSoTimeout argument_list|( literal|10000 argument_list|) expr_stmt|; name|mllpClient operator|. name|connect argument_list|() expr_stmt|; for|for control|( name|int name|i init|= literal|1 init|; name|i operator|<= name|sendMessageCount condition|; operator|++ name|i control|) block|{ name|String name|testMessage init|= name|Hl7TestMessageGenerator operator|. name|generateMessage argument_list|( name|i argument_list|) decl_stmt|; name|result operator|. name|message argument_list|( name|i operator|- literal|1 argument_list|) operator|. name|body argument_list|() operator|. name|isEqualTo argument_list|( name|testMessage argument_list|) expr_stmt|; name|mllpClient operator|. name|sendFramedDataInMultiplePackets argument_list|( name|testMessage argument_list|, operator|( name|byte operator|) literal|'\r' argument_list|) expr_stmt|; name|String name|acknowledgement init|= name|mllpClient operator|. name|receiveFramedData argument_list|() decl_stmt|; name|Assert operator|. name|assertThat argument_list|( literal|"Should be acknowledgment for message " operator|+ name|i argument_list|, name|acknowledgement argument_list|, name|CoreMatchers operator|. name|containsString argument_list|( name|String operator|. name|format argument_list|( literal|"MSA|AA|%05d" argument_list|, name|i argument_list|) argument_list|) argument_list|) expr_stmt|; block|} name|assertMockEndpointsSatisfied argument_list|( literal|10 argument_list|, name|TimeUnit operator|. name|SECONDS argument_list|) expr_stmt|; block|} block|} end_class end_unit
15.030488
810
0.810142
ce8e931e7a1b396c8e68a5ac65793d359f218edc
12,999
/* * Copyright 2020 Google LLC * * 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 * * https://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.spez.core; import com.google.auth.oauth2.GoogleCredentials; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.spez.common.AuthConfig; import com.google.spez.common.StackdriverConfig; import com.google.spez.spanner.Settings; import com.typesafe.config.Config; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @SuppressWarnings("PMD.BeanMembersShouldSerialize") public class SpezConfig { private static final Logger log = LoggerFactory.getLogger(SpezConfig.class); public static final String BASE_NAME = "spez"; public static final String PROJECT_ID_KEY = "spez.project_id"; public static final String AUTH_CLOUD_SECRETS_DIR_KEY = "spez.auth.cloud_secrets_dir"; public static final String AUTH_CREDENTIALS_KEY = "spez.auth.credentials"; public static final String AUTH_SCOPES_KEY = "spez.auth.scopes"; public static final String LOGLEVEL_DEFAULT_KEY = "spez.loglevel.default"; public static final String LOGLEVEL_CDC_KEY = "spez.loglevel.cdc"; public static final String LOGLEVEL_CORE_KEY = "spez.loglevel.core"; public static final String LOGLEVEL_NETTY_KEY = "spez.loglevel.netty"; public static final String LOGLEVEL_SPANNERCLIENT_KEY = "spez.loglevel.spannerclient"; public static final String PUBSUB_PROJECT_ID_KEY = "spez.pubsub.project_id"; public static final String PUBSUB_TOPIC_KEY = "spez.pubsub.topic"; public static final String PUBSUB_BUFFER_TIMEOUT_KEY = "spez.pubsub.buffer_timeout"; public static final String SINK_PROJECT_ID_KEY = "spez.sink.project_id"; public static final String SINK_CUSTOM_CLIENT_KEY = "spez.sink.use_custom_client"; public static final String SINK_INSTANCE_KEY = "spez.sink.instance"; public static final String SINK_DATABASE_KEY = "spez.sink.database"; public static final String SINK_TABLE_KEY = "spez.sink.table"; public static final String SINK_UUID_COLUMN_KEY = "spez.sink.uuid_column"; public static final String SINK_TIMESTAMP_COLUMN_KEY = "spez.sink.timestamp_column"; public static final String LPTS_CUSTOM_CLIENT_KEY = "spez.lpts.use_custom_client"; public static final String LPTS_PROJECT_ID_KEY = "spez.lpts.project_id"; public static final String LPTS_INSTANCE_KEY = "spez.lpts.instance"; public static final String LPTS_DATABASE_KEY = "spez.lpts.database"; public static final String LPTS_TABLE_KEY = "spez.lpts.table"; public static final String SINK_UUID_KEY = "spez.sink.uuid"; public static final String SINK_TIMESTAMP_KEY = "spez.sink.commit_timestamp"; public static final String SINK_POLL_RATE_KEY = "spez.sink.poll_rate"; public static class PubSubConfig { private final String projectId; private final String topic; private final int bufferTimeout; /** PubSubConfig value object constructor. */ public PubSubConfig(String projectId, String topic, int bufferTimeout) { this.projectId = projectId; this.topic = topic; this.bufferTimeout = bufferTimeout; } /** PubSubConfig value object parser. */ public static PubSubConfig parse(Config config) { return new PubSubConfig( config.getString(PUBSUB_PROJECT_ID_KEY), config.getString(PUBSUB_TOPIC_KEY), config.getInt(PUBSUB_BUFFER_TIMEOUT_KEY)); } /** projectId getter. */ public String getProjectId() { return projectId; } /** topic getter. */ public String getTopic() { return topic; } /** bufferTimeout getter. */ public int getBufferTimeout() { return bufferTimeout; } } public static class SinkConfig { private final String projectId; private final String instance; private final String database; private final String table; private final String uuidColumn; private final String timestampColumn; private final int pollRate; private final boolean useCustomClient; private final GoogleCredentials credentials; /** SinkConfig value object constructor. */ public SinkConfig( String projectId, String instance, String database, String table, String uuidColumn, String timestampColumn, int pollRate, boolean useCustomClient, GoogleCredentials credentials) { this.projectId = projectId; this.instance = instance; this.database = database; this.table = table; this.uuidColumn = uuidColumn; this.timestampColumn = timestampColumn; this.pollRate = pollRate; this.useCustomClient = useCustomClient; this.credentials = credentials; } /** SinkConfig value object parser. */ public static SinkConfig parse(Config config, GoogleCredentials credentials) { return new SinkConfig( config.getString(SINK_PROJECT_ID_KEY), config.getString(SINK_INSTANCE_KEY), config.getString(SINK_DATABASE_KEY), config.getString(SINK_TABLE_KEY), config.getString(SINK_UUID_COLUMN_KEY), config.getString(SINK_TIMESTAMP_COLUMN_KEY), config.getInt(SINK_POLL_RATE_KEY), config.getBoolean(SINK_CUSTOM_CLIENT_KEY), credentials); } /** projectId getter. */ public String getProjectId() { return projectId; } /** instance getter. */ public String getInstance() { return instance; } /** database getter. */ public String getDatabase() { return database; } /** table getter. */ public String getTable() { return table; } /** settings getter. */ public Settings getSettings() { return Settings.newBuilder() .setProjectId(projectId) .setInstance(instance) .setDatabase(database) .setCredentials(credentials) .build(); } /** uuidColumn getter. */ public String getUuidColumn() { return uuidColumn; } /** timestampColumn getter. */ public String getTimestampColumn() { return timestampColumn; } /** pollRate getter. */ public int getPollRate() { return pollRate; } /** databasePath getter. */ public String databasePath() { return new StringBuilder() .append("projects/") .append(projectId) .append("/instances/") .append(instance) .append("/databases/") .append(database) .toString(); } /** tablePath getter. */ public String tablePath() { return new StringBuilder().append(databasePath()).append("/tables/").append(table).toString(); } public boolean useCustomClient() { return useCustomClient; } } public static class LptsConfig { private final String projectId; private final String instance; private final String database; private final String table; private final boolean useCustomClient; private final GoogleCredentials credentials; /** LptsConfig value object constructor. */ public LptsConfig( String projectId, String instance, String database, String table, boolean useCustomClient, GoogleCredentials credentials) { this.projectId = projectId; this.instance = instance; this.database = database; this.table = table; this.useCustomClient = useCustomClient; this.credentials = credentials; } /** LptsConfig value object parser. */ public static LptsConfig parse(Config config, GoogleCredentials credentials) { return new LptsConfig( config.getString(LPTS_PROJECT_ID_KEY), config.getString(LPTS_INSTANCE_KEY), config.getString(LPTS_DATABASE_KEY), config.getString(LPTS_TABLE_KEY), config.getBoolean(LPTS_CUSTOM_CLIENT_KEY), credentials); } /** projectId getter. */ public String getProjectId() { return projectId; } /** instance getter. */ public String getInstance() { return instance; } /** database getter. */ public String getDatabase() { return database; } /** table getter. */ public String getTable() { return table; } /** settings getter. */ public Settings getSettings() { return Settings.newBuilder() .setProjectId(projectId) .setInstance(instance) .setDatabase(database) .setCredentials(credentials) .build(); } /** databasePath getter. */ public String databasePath() { return new StringBuilder() .append("projects/") .append(projectId) .append("/instances/") .append(instance) .append("/databases/") .append(database) .toString(); } /** tablePath getter. */ public String tablePath() { return new StringBuilder().append(databasePath()).append("/tables/").append(table).toString(); } public boolean useCustomClient() { return useCustomClient; } } private final AuthConfig auth; private final PubSubConfig pubsub; private final SinkConfig sink; private final StackdriverConfig stackdriver; private final LptsConfig lpts; /** SpezConfig value object constructor. */ public SpezConfig( AuthConfig auth, PubSubConfig pubsub, SinkConfig sink, StackdriverConfig stackdriver, LptsConfig lpts) { this.auth = auth; this.pubsub = pubsub; this.sink = sink; this.stackdriver = stackdriver; this.lpts = lpts; } /** SpezConfig log helper. */ public static void logParsedValues(Config config, List<String> configKeys) { log.info("============================================="); log.info("Spez configured with the following properties"); for (var key : configKeys) { if (key.equals(AUTH_SCOPES_KEY)) { log.info("{}={}", key, config.getStringList(key)); } else { log.info("{}={}", key, config.getString(key)); } } log.info("============================================="); } /** SpezConfig value object parser. */ public static SpezConfig parse(Config config) { List<String> configKeys = Lists.newArrayList( PROJECT_ID_KEY, AUTH_CLOUD_SECRETS_DIR_KEY, AUTH_CREDENTIALS_KEY, AUTH_SCOPES_KEY, LOGLEVEL_DEFAULT_KEY, LOGLEVEL_CDC_KEY, LOGLEVEL_CORE_KEY, LOGLEVEL_NETTY_KEY, LOGLEVEL_SPANNERCLIENT_KEY, PUBSUB_PROJECT_ID_KEY, PUBSUB_TOPIC_KEY, PUBSUB_BUFFER_TIMEOUT_KEY, SINK_CUSTOM_CLIENT_KEY, SINK_PROJECT_ID_KEY, SINK_INSTANCE_KEY, SINK_DATABASE_KEY, SINK_TABLE_KEY, SINK_UUID_COLUMN_KEY, SINK_TIMESTAMP_COLUMN_KEY, SINK_POLL_RATE_KEY, LPTS_CUSTOM_CLIENT_KEY, LPTS_PROJECT_ID_KEY, LPTS_INSTANCE_KEY, LPTS_DATABASE_KEY, LPTS_TABLE_KEY); AuthConfig.Parser authParser = AuthConfig.newParser(BASE_NAME); StackdriverConfig.Parser stackdriverParser = StackdriverConfig.newParser(BASE_NAME); configKeys.addAll(authParser.configKeys()); configKeys.addAll(stackdriverParser.configKeys()); logParsedValues(config, configKeys); AuthConfig auth = authParser.parse(config); PubSubConfig pubsub = PubSubConfig.parse(config); SinkConfig sink = SinkConfig.parse(config, auth.getCredentials()); StackdriverConfig stackdriver = stackdriverParser.parse(config); LptsConfig lpts = LptsConfig.parse(config, auth.getCredentials()); return new SpezConfig(auth, pubsub, sink, stackdriver, lpts); } public AuthConfig getAuth() { return auth; } public PubSubConfig getPubSub() { return pubsub; } public SinkConfig getSink() { return sink; } public StackdriverConfig getStackdriver() { return stackdriver; } public LptsConfig getLpts() { return lpts; } /** baseMetadata getter. */ public Map<String, String> getBaseMetadata() { Map<String, String> base = Maps.newHashMap(); base.put(SINK_INSTANCE_KEY, sink.getInstance()); base.put(SINK_DATABASE_KEY, sink.getDatabase()); base.put(SINK_TABLE_KEY, sink.getTable()); base.put(PUBSUB_TOPIC_KEY, pubsub.getTopic()); return base; } }
31.938575
100
0.672129
7616f7266b4dbcdaff52d2966d7c60c7c6e70d7a
730
package net.frozenorb; public class ReusableByteArray { private final ThreadLocal<byte[]> arrays; public ReusableByteArray(final int initialSize) { arrays = new ThreadLocal<byte[]>() { @Override protected byte[] initialValue() { return new byte[initialSize]; } }; } /** * Returns a (thread local) byte array of at least minSize * @param minSize Minimum size of returned array * @return byte array */ public byte[] get(int minSize) { byte[] array = arrays.get(); if (array.length < minSize) { array = new byte[minSize]; arrays.set(array); } return array; } }
24.333333
62
0.554795
762acff12e01203ee4e000afa92255a2e9271135
7,741
/* * Copyright 2012-2018 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.auth; import com.amazonaws.AmazonClientException; import com.amazonaws.SDKGlobalConfiguration; import com.amazonaws.SdkClientException; import com.amazonaws.internal.CredentialsEndpointProvider; import com.amazonaws.internal.EC2CredentialsUtils; import com.amazonaws.util.EC2MetadataUtils; import java.io.Closeable; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Credentials provider implementation that loads credentials from the Amazon EC2 Instance Metadata Service. * * <p>When using {@link InstanceProfileCredentialsProvider} with asynchronous refreshing it is * <b>strongly</b> recommended to explicitly call {@link #close()} to release the async thread.</p> */ public class InstanceProfileCredentialsProvider implements AWSCredentialsProvider, Closeable { private static final Log LOG = LogFactory.getLog(InstanceProfileCredentialsProvider.class); /** * The wait time, after which the background thread initiates a refresh to * load latest credentials if needed. */ private static final int ASYNC_REFRESH_INTERVAL_TIME_MINUTES = 1; /** * The default InstanceProfileCredentialsProvider that can be shared by * multiple CredentialsProvider instance threads to shrink the amount of * requests to EC2 metadata service. */ private static final InstanceProfileCredentialsProvider INSTANCE = new InstanceProfileCredentialsProvider(); private final EC2CredentialsFetcher credentialsFetcher; /** * The executor service used for refreshing the credentials in the * background. */ private volatile ScheduledExecutorService executor; private volatile boolean shouldRefresh = false; /** * @deprecated for the singleton method {@link #getInstance()}. */ @Deprecated public InstanceProfileCredentialsProvider() { this(false); } /** * Spins up a new thread to refresh the credentials asynchronously if * refreshCredentialsAsync is set to true, otherwise the credentials will be * refreshed from the instance metadata service synchronously, * * <p>It is <b>strongly</b> recommended to reuse instances of this credentials provider, especially * when async refreshing is used since a background thread is created.</p> * * @param refreshCredentialsAsync * true if credentials needs to be refreshed asynchronously else * false. */ public InstanceProfileCredentialsProvider(boolean refreshCredentialsAsync) { this(refreshCredentialsAsync, true); } /** * Spins up a new thread to refresh the credentials asynchronously. * * <p>It is <b>strongly</b> recommended to reuse instances of this credentials provider, especially * when async refreshing is used since a background thread is created.</p> * * @param eagerlyRefreshCredentialsAsync * when set to false will not attempt to refresh credentials asynchronously * until after a call has been made to {@link #getCredentials()} - ensures that * {@link EC2CredentialsFetcher#getCredentials()} is only hit when this CredentialProvider is actually required */ public static InstanceProfileCredentialsProvider createAsyncRefreshingProvider(final boolean eagerlyRefreshCredentialsAsync) { return new InstanceProfileCredentialsProvider(true, eagerlyRefreshCredentialsAsync); } private InstanceProfileCredentialsProvider(boolean refreshCredentialsAsync, final boolean eagerlyRefreshCredentialsAsync) { credentialsFetcher = new EC2CredentialsFetcher(new InstanceMetadataCredentialsEndpointProvider()); if (!SDKGlobalConfiguration.isEc2MetadataDisabled()) { if (refreshCredentialsAsync) { executor = Executors.newScheduledThreadPool(1); executor.scheduleWithFixedDelay(new Runnable() { @Override public void run() { try { if (shouldRefresh) credentialsFetcher.getCredentials(); } catch (AmazonClientException ace) { handleError(ace); } catch (RuntimeException re) { handleError(re); } } }, 0, ASYNC_REFRESH_INTERVAL_TIME_MINUTES, TimeUnit.MINUTES); } } } /** * Returns a singleton {@link InstanceProfileCredentialsProvider} that does not refresh credentials asynchronously. * * <p> * See {@link #InstanceProfileCredentialsProvider(boolean)} or {@link #createAsyncRefreshingProvider(boolean)} for * asynchronous credentials refreshing. * </p> */ public static InstanceProfileCredentialsProvider getInstance() { return INSTANCE; } private void handleError(Throwable t) { refresh(); LOG.error(t.getMessage(), t); } @Override protected void finalize() throws Throwable { if (executor != null) { executor.shutdownNow(); } } /** * {@inheritDoc} * * @throws AmazonClientException if {@link SDKGlobalConfiguration#isEc2MetadataDisabled()} is true */ @Override public AWSCredentials getCredentials() { if (SDKGlobalConfiguration.isEc2MetadataDisabled()) { throw new AmazonClientException("AWS_EC2_METADATA_DISABLED is set to true, not loading credentials from EC2 Instance " + "Metadata service"); } AWSCredentials creds = credentialsFetcher.getCredentials(); shouldRefresh = true; return creds; } @Override public void refresh() { if (credentialsFetcher != null) { credentialsFetcher.refresh(); } } @Override public void close() throws IOException { if (executor != null) { executor.shutdownNow(); executor = null; } } private static class InstanceMetadataCredentialsEndpointProvider extends CredentialsEndpointProvider { @Override public URI getCredentialsEndpoint() throws URISyntaxException, IOException { String host = EC2MetadataUtils.getHostAddressForEC2MetadataService(); String securityCredentialsList = EC2CredentialsUtils.getInstance().readResource(new URI(host + EC2MetadataUtils.SECURITY_CREDENTIALS_RESOURCE)); String[] securityCredentials = securityCredentialsList.trim().split("\n"); if (securityCredentials.length == 0) { throw new SdkClientException("Unable to load credentials path"); } return new URI(host + EC2MetadataUtils.SECURITY_CREDENTIALS_RESOURCE + securityCredentials[0]); } } }
38.899497
156
0.684279
2b5a34affb7250eb4443c41d6abc54c438103369
1,704
package com.twu.biblioteca; import java.util.ArrayList; import java.util.HashMap; /*** * normal user class * limited privileges */ public class Borrower extends User { private String name; private String email; private int phone; //private ArrayList<Item> itemsLoaned; private UserMenu menu; public Borrower(String username, String password, Inventory collection, String name, String email, int phone) { super(username, password, collection); this.name = name; this.email = email; this.phone = phone; //this.itemsLoaned = new ArrayList<Item>(); this.menu = new UserMenu(collection); } public void getMenu() { System.out.println("Welcome " + toString()); while (true) menu.show(); } public String toString() { return this.name +"\n"+ "email: " + this.email+ "\nphone:" + this.phone; } /* public boolean borrow(Item i) { //Item i = this.collection.get(itemID); if (i.checkOut()) { i.setAvailable(false); itemsLoaned.add(i); System.out.println("Thank you! Enjoy the book"); return true; } else { System.out.println("Sorry that book is not available"); return false; } }*/ public boolean returnItem(Item i) { //Item i = this.collection.get(itemID); if (i != null && !i.isAvailable()) { i.setAvailable(true); System.out.println("Thank you for returning the book"); return true; } else { System.out.println("That is not a valid book to return"); return false; } } }
27.047619
115
0.576291
9eba9d0f8ac478166adf873cd5034fa4091565a7
2,623
/* * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.vm.ci.meta; /** * Provides memory access operations for the target VM. */ public interface MemoryAccessProvider { /** * Reads a primitive value using a base address and a displacement. * * @param kind the {@link JavaKind} of the returned {@link JavaConstant} object * @param base the base address from which the value is read * @param displacement the displacement within the object in bytes * @param bits the number of bits to read from memory * @return the read value encapsulated in a {@link JavaConstant} object of {@link JavaKind} kind * @throws IllegalArgumentException if the read is out of bounds of the object or {@code kind} * is {@link JavaKind#Void} or not {@linkplain JavaKind#isPrimitive() primitive} * kind or {@code bits} is not 8, 16, 32 or 64 */ JavaConstant readPrimitiveConstant(JavaKind kind, Constant base, long displacement, int bits) throws IllegalArgumentException; /** * Reads a Java {@link Object} value using a base address and a displacement. * * @param base the base address from which the value is read * @param displacement the displacement within the object in bytes * @return the read value encapsulated in a {@link Constant} object * @throws IllegalArgumentException if the address computed from {@code base} and * {@code displacement} does not denote a location holding an {@code Object} value */ JavaConstant readObjectConstant(Constant base, long displacement); }
47.690909
130
0.715974
40bfe2ce6150e730a1a8736117858090ece84431
3,818
package dDCF.runtime; import dDCF.lib.Work; import dDCF.lib.internal.Config; import dDCF.lib.internal.InterConnects.InterConnects; import dDCF.lib.internal.JarByteClassLoader; import dDCF.lib.internal.Utils; import dDCF.lib.internal.Worker; import dDCF.runtime.Utils.CmdLineParser; import dDCF.runtime.Utils.Reflection; import org.apache.commons.cli.ParseException; import java.io.IOException; public class main { public static void main(String[] args) { Config cfg = null; CmdLineParser parser = new CmdLineParser(); try { cfg = parser.parse(args); } catch (ParseException e) { System.out.println("Parse Error: " + e.getMessage()); parser.showUsage(); return; } // cache jar file (master) if (cfg.isMaster) { try { cfg.jarByteCode = Utils.readFile(cfg.jarName); } catch (IOException e) { System.out.println("Jar File Reading Error: " + e.getMessage()); } } InterConnects cons; try { cons = new InterConnects(cfg); } catch (IOException e) { Utils.debugPrint(() -> "InterConnects IOException." + e.getMessage()); return; } // master's work if (cfg.isMaster) { try { Object[] works = Reflection.getWork(cfg.jarByteCode).toArray(); if (works.length != 0) { for (Object obj : works) { Work work = (Work) obj; work.starter(); Worker.startWorkers(cons); } } else { System.out.println("Couldn't find valid work."); System.exit(-1); } } catch (IOException e) { e.printStackTrace(); } } // worker's work if (!cfg.isMaster) { byte[] jarCode = cons.getJarCode(); cfg.jarByteCode = jarCode; if (jarCode == null) System.out.println("failed getJarCode"); else System.out.println("jarCode:" + jarCode.length); try { JarByteClassLoader.loadJarFile(jarCode); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } Worker.startWorkers(cons); /* ***** Socket Benchmark ***** */ /* int count; Scanner scanner = new Scanner(System.in); count = scanner.nextInt(); long start = System.currentTimeMillis(); for (int i = 0; i < count; i++) { cons.stealTask(); } System.out.println("time:" + Long.toString(System.currentTimeMillis() - start)); */ /* ***** Serialization Benchmark ***** */ /* Message msg = MessageFactory.newMessage(MESSAGE_TYPE.JOB_REQUEST); ObjectMapper objectMapper = new ObjectMapper(new MessagePackFactory()); MessageSerializer messageSerializer = new MessageSerializer(); final int count = 1000000; byte[] bytes = null; for (int i = 0; i < count; i++) { try { bytes = objectMapper.writeValueAsBytes(msg); objectMapper.readValue(bytes, Message.class); } catch (Exception e) { e.printStackTrace(); } } for (int i = 0; i < count; i++) { try { bytes = messageSerializer.serialize(msg); messageSerializer.deserialize(bytes); } catch (IOException e) { e.printStackTrace(); } } long start = System.currentTimeMillis(); for (int i = 0; i < count; i++) { try { bytes = objectMapper.writeValueAsBytes(msg); objectMapper.readValue(bytes, Message.class); } catch (Exception e) { e.printStackTrace(); } } System.out.println("time:" + Long.toString(System.currentTimeMillis() - start)); System.out.println("len:" + Integer.toString(bytes.length)); start = System.currentTimeMillis(); for (int i = 0; i < count; i++) { try { bytes = messageSerializer.serialize(msg); messageSerializer.deserialize(bytes); } catch (IOException e) { e.printStackTrace(); } } System.out.println("time:" + Long.toString(System.currentTimeMillis() - start)); System.out.println("len:" + Integer.toString(bytes.length)); */ } return; } }
25.118421
83
0.641959
31b1a4ca171b0401737ec4a0b42584dcc4337bb9
1,764
import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class FicherosTexto1 { public static void escribirFichero(String[] lista) { // Escribir en un fichero. try { // 1. Crear Fichero. File fichero = new File("FicheroNombres.txt"); FileWriter ficheroEscritura = new FileWriter(fichero); // 2. Escribir nombre. for (int i = 0; i < lista.length; i++) { ficheroEscritura.write(lista[i]); } // 3. Cerrar el fichero ficheroEscritura.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void leerFichero(String[] lista) { try { // 1.Crear Fichero. File fichero = new File("FicheroNombres.txt"); FileReader ficheroLectura = new FileReader(fichero); // 2. Leer fichero. char[] nombre = new char[4]; int res, i=0; res = ficheroLectura.read(nombre); while(res != -1) { lista[i] = String.valueOf(nombre); res = ficheroLectura.read(nombre); i++; } // 3. Cerrar fichero. ficheroLectura.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void imprimirTabla(String[] lista) { System.out.println("Contenido de la tabla: "); for (int i = 0; i < lista.length; i++) { System.out.println("Posicion " + i + " : " + lista[i]); } } public static void inicializarTabla(String[] lista) { for (int i = 0; i < lista.length; i++) { lista[i]=""; } } public static void main(String[] args) { String[] lista = {"Pepe","Ana","Juan"}; escribirFichero(lista); inicializarTabla(lista); leerFichero(lista); imprimirTabla(lista); } }
22.329114
58
0.643424
09f52d0363fc8e6949c8a17c65ed2b5d05e739b3
15,846
package org.dew.oauth2; import java.lang.reflect.Array; import java.net.URLEncoder; import java.util.*; /** * Utilities. */ public class Utils { public static String encode(Object value) { if(value == null) return ""; String sValue = toString(value, ""); try { return URLEncoder.encode(sValue, "UTF-8"); } catch(Exception ex) { return sValue; } } public static void appendParam(StringBuilder sb, String parameterName, Object value) { if(value == null) return; if(sb.length() == 0) { sb.append(parameterName + "=" + encode(value)); } else { sb.append("&" + parameterName + "=" + encode(value)); } } public static String toQueryString(Map<String, Object> map) { if(map == null || map.isEmpty()) { return ""; } StringBuilder sb = new StringBuilder(map.size() * 2 * 8); Iterator<Map.Entry<String, Object>> iterator = map.entrySet().iterator(); while(iterator.hasNext()) { Map.Entry<String, Object> entry = iterator.next(); String key = entry.getKey(); Object val = entry.getValue(); appendParam(sb, key, val); } return sb.toString(); } @SuppressWarnings("unchecked") public static String toHeaderValue(Map<String, Object> map) { if(map == null) { return ""; } StringBuilder sb = new StringBuilder(map.size() * 2 * 8); Iterator<Map.Entry<String, Object>> iterator = map.entrySet().iterator(); while(iterator.hasNext()) { Map.Entry<String, Object> entry = iterator.next(); String key = entry.getKey(); Object val = entry.getValue(); if(val == null) { continue; } else if(val instanceof String) { sb.append(" " + key + "=" + toJSON((String)val)); } else if(val instanceof Number) { sb.append(" " + key + "=" + val); } else if(val instanceof Boolean) { sb.append(" " + key + "=" + val); } else if(val instanceof Date) { sb.append(" " + key + "=\"" + formatDate((Date) val) + "\""); } else if(val instanceof Calendar) { sb.append(" " + key + "=\"" + formatDate((Calendar) val) + "\""); } else if(val instanceof Map) { sb.append(" " + key + "=" + toJSON((Map<String, Object>) val)); } else if(val instanceof Collection) { sb.append(" " + key + "=" + toJSON((Collection<?>) val)); } else if(val.getClass().isArray()) { sb.append(" " + key + "=" + toJSONArray(val)); } else if(val instanceof IOAuthObject) { sb.append(" " + key + "=" + ((IOAuthObject)val).toJSON()); } else { sb.append(" " + key + "=" + toJSON(val.toString())); } } if(sb.length() == 0) return ""; return sb.substring(1); } /** * Library independent JSON object serialization implementation. * * @param map Map<String, Object> * @return JSON representation */ @SuppressWarnings("unchecked") public static String toJSON(Map<String, Object> map) { if(map == null) { return "null"; } StringBuilder sb = new StringBuilder(map.size() * 2 * 8); Iterator<Map.Entry<String, Object>> iterator = map.entrySet().iterator(); while(iterator.hasNext()) { Map.Entry<String, Object> entry = iterator.next(); String key = entry.getKey(); Object val = entry.getValue(); if(val == null) { continue; } else if(val instanceof String) { sb.append(",\"" + key + "\":" + toJSON((String)val)); } else if(val instanceof Number) { sb.append(",\"" + key + "\":" + val); } else if(val instanceof Boolean) { sb.append(",\"" + key + "\":" + val); } else if(val instanceof Date) { sb.append(",\"" + key + "\":\"" + formatDate((Date) val) + "\""); } else if(val instanceof Calendar) { sb.append(",\"" + key + "\":\"" + formatDate((Calendar) val) + "\""); } else if(val instanceof Map) { sb.append(",\"" + key + "\":" + toJSON((Map<String, Object>) val)); } else if(val instanceof Collection) { sb.append(",\"" + key + "\":" + toJSON((Collection<?>) val)); } else if(val.getClass().isArray()) { sb.append(",\"" + key + "\":" + toJSONArray(val)); } else if(val instanceof IOAuthObject) { sb.append(",\"" + key + "\":" + ((IOAuthObject)val).toJSON()); } else { sb.append(",\"" + key + "\":" + toJSON(val.toString())); } } if(sb.length() == 0) return "{}"; return "{" + sb.substring(1) + "}"; } /** * Library independent JSON array serialization implementation. * * @param col Collection<?> * @return JSON representation */ @SuppressWarnings("unchecked") public static String toJSON(Collection<?> col) { if(col == null) { return "null"; } if(col.size() == 0) { return "[]"; } StringBuilder sb = new StringBuilder(col.size() * 8); Iterator<?> iterator = col.iterator(); while(iterator.hasNext()) { Object val = iterator.next(); if(val == null) { sb.append(",null"); } else if(val instanceof String) { sb.append("," + toJSON((String) val)); } else if(val instanceof Number) { sb.append("," + val); } else if(val instanceof Boolean) { sb.append("," + val); } else if(val instanceof Date) { sb.append(",\"" + formatDate((Date) val) + "\""); } else if(val instanceof Calendar) { sb.append(",\"" + formatDate((Calendar) val) + "\""); } else if(val instanceof Map) { sb.append("," + toJSON((Map<String, Object>) val)); } else if(val instanceof Collection) { sb.append("," + toJSON((Collection<?>) val)); } else if(val.getClass().isArray()) { sb.append("," + toJSONArray(val)); } else if(val instanceof IOAuthObject) { sb.append("," + ((IOAuthObject)val).toJSON()); } else { sb.append("," + toJSON(val.toString())); } } if(sb.length() == 0) return "[]"; return "[" + sb.substring(1) + "]"; } /** * Library independent JSON array serialization implementation. * * @param object Object * @return JSON representation */ @SuppressWarnings("unchecked") public static String toJSONArray(Object object) { if(object == null) { return "null"; } if(object instanceof Collection) { return toJSON((Collection<?>) object); } if(!object.getClass().isArray()) { ArrayList<Object> arrayList = new ArrayList<Object>(1); arrayList.add(object); return toJSON((Collection<?>) object); } int length = Array.getLength(object); StringBuilder sb = new StringBuilder(length * 8); for(int i = 0; i < length; i++) { Object val = Array.get(object, i); if(val == null) { sb.append(",null"); } else if(val instanceof String) { sb.append("," + toJSON((String) val)); } else if(val instanceof Number) { sb.append("," + val); } else if(val instanceof Boolean) { sb.append("," + val); } else if(val instanceof Date) { sb.append(",\"" + formatDate((Date) val) + "\""); } else if(val instanceof Calendar) { sb.append(",\"" + formatDate((Calendar) val) + "\""); } else if(val instanceof Map) { sb.append("," + toJSON((Map<String, Object>) val)); } else if(val instanceof Collection) { sb.append("," + toJSON((Collection<?>) val)); } else if(val.getClass().isArray()) { sb.append("," + toJSONArray(val)); } else if(val instanceof IOAuthObject) { sb.append("," + ((IOAuthObject)val).toJSON()); } else { sb.append("," + toJSON(val.toString())); } } if(sb.length() == 0) return "[]"; return "[" + sb.substring(1) + "]"; } /** * Library independent JSON string serialization implementation. * * @param string String * @return JSON representation */ public static String toJSON(String string) { if(string == null) { return "null"; } if(string.length() == 0) { return "\"\""; } char b; char c = 0; String hhhh; int i; int len = string.length(); StringBuilder sb = new StringBuilder(len + 2); sb.append('"'); for(i = 0; i < len; i += 1) { b = c; c = string.charAt(i); switch(c) { case '\\': case '"': sb.append('\\'); sb.append(c); break; case '/': if(b == '<') { sb.append('\\'); } sb.append(c); break; case '\b': sb.append("\\b"); break; case '\t': sb.append("\\t"); break; case '\n': sb.append("\\n"); break; case '\f': sb.append("\\f"); break; case '\r': sb.append("\\r"); break; default: if(c < ' ' ||(c >= '\u0080' && c < '\u00a0') ||(c >= '\u2000' && c < '\u2100')) { sb.append("\\u"); hhhh = Integer.toHexString(c); sb.append("0000", 0, 4 - hhhh.length()); sb.append(hhhh); } else { sb.append(c); } } } sb.append('"'); return sb.toString(); } public static String getJSONVal(String jsonObject, String key, String defaultValue) { if(jsonObject == null || jsonObject.length() == 0 || jsonObject.indexOf('{') < 0) { return defaultValue; } if(key == null || key.length() == 0) { return defaultValue; } // Find key int k = jsonObject.indexOf("\"" + key + "\""); if(k < 0) { return defaultValue; } // Separator key-value int s = jsonObject.indexOf(':', k + key.length() + 2); if(s < 0) { return defaultValue; } // Find end value int e = -1; // Previous char char cp = '\0'; // String delimiter char char cs = '\0'; // Is string? boolean jsonString = false; for(int i = s; i < jsonObject.length() - 1; i++) { char c = jsonObject.charAt(i); if(c == '"' && cp != '\\') { if(jsonString) { if(cs == '"') { // End string jsonString = false; } } else { // Start string jsonString = true; cs = '"'; } } else if(c == '\'' && cp != '\\') { if(jsonString) { if(cs == '\'') { // End string jsonString = false; } } else { // Start string jsonString = true; cs = '\''; } } else if(c == ',' || c == '}') { if(!jsonString) { // End value found e = i; break; } } // Set previous char cp = c; } if(e < 0) { e = jsonObject.length(); } String value = jsonObject.substring(s + 1, e).trim(); if(value.equals("null")) { return defaultValue; } // Strip string if(value.startsWith("\"") && value.endsWith("\"") && value.length() > 1) { value = value.substring(1, value.length() - 1); } else if(value.startsWith("'") && value.endsWith("'") && value.length() > 1) { value = value.substring(1, value.length() - 1); } // Replace escape characters return value.replace("\\\"", "\"").replace("\\'", "'").replace("\\n", "\n").replace("\\t", "\t"); } public static String toString(Object value) { if(value == null) { return null; } if(value instanceof String) { return (String) value; } if(value instanceof Calendar) { return formatDate((Calendar) value); } if(value instanceof Date) { return formatDate((Date) value); } return value.toString(); } public static String toString(Object value, String sDefault) { if(value == null) { return sDefault; } if(value instanceof String) { return (String) value; } if(value instanceof Calendar) { return formatDate((Calendar) value); } if(value instanceof Date) { return formatDate((Date) value); } return value.toString(); } public static int toInt(Object value) { if(value == null) { return 0; } if(value instanceof String) { int iValue = 0; try { iValue = Integer.parseInt(((String) value).trim()); } catch(Exception ex) {} return iValue; } if(value instanceof Number) { return ((Number) value).intValue(); } if(value instanceof Calendar) { return calendarToInt((Calendar) value); } if(value instanceof Date) { return dateToInt((Date) value); } String sValue = value.toString(); if(sValue == null) return 0; int iValue = 0; try { iValue = Integer.parseInt(sValue.trim()); } catch(Exception ex) {} return iValue; } public static int toInt(Object value, int iDefault) { if(value == null) { return iDefault; } if(value instanceof String) { int iValue = iDefault; try { iValue = Integer.parseInt(((String) value).trim()); } catch(Exception ex) {} return iValue; } if(value instanceof Number) { return ((Number) value).intValue(); } if(value instanceof Calendar) { return calendarToInt((Calendar) value); } if(value instanceof Date) { return dateToInt((Date) value); } String sValue = value.toString(); if(sValue == null) return 0; int iValue = iDefault; try { iValue = Integer.parseInt(sValue.trim()); } catch(Exception ex) {} return iValue; } public static boolean toBoolean(Object value) { if(value == null) { return false; } if(value instanceof Boolean) { return ((Boolean) value).booleanValue(); } if(value instanceof String) { String s = (String) value; if(s.length() == 0) return false; return ("1TtYySs").indexOf(s.charAt(0)) >= 0; } if(value instanceof Number) { int i = ((Number) value).intValue(); return i != 0; } return false; } public static String formatDate(Calendar cal) { if(cal == null) return ""; int iYear = cal.get(Calendar.YEAR); int iMonth = cal.get(Calendar.MONTH) + 1; int iDay = cal.get(Calendar.DATE); String sYear = String.valueOf(iYear); String sMonth = iMonth < 10 ? "0" + iMonth : String.valueOf(iMonth); String sDay = iDay < 10 ? "0" + iDay : String.valueOf(iDay); return sYear + "-" + sMonth + "-" + sDay; } public static String formatDate(Date date) { if(date == null) return ""; Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(date.getTime()); int iYear = cal.get(Calendar.YEAR); int iMonth = cal.get(Calendar.MONTH) + 1; int iDay = cal.get(Calendar.DATE); String sYear = String.valueOf(iYear); String sMonth = iMonth < 10 ? "0" + iMonth : String.valueOf(iMonth); String sDay = iDay < 10 ? "0" + iDay : String.valueOf(iDay); return sYear + "-" + sMonth + "-" + sDay; } public static int calendarToInt(Calendar cal) { if(cal == null) return 0; long timeInMillis = cal.getTimeInMillis(); return (int) (timeInMillis / 1000); } public static int dateToInt(Date date) { if(date == null) return 0; long timeInMillis = date.getTime(); return (int) (timeInMillis / 1000); } }
26.322259
101
0.521015
93857537d845d0839eec53af25244e65b97d1c87
7,331
/******************************************************************************* * ENdoSnipe 5.0 - (https://github.com/endosnipe) * * The MIT License (MIT) * * Copyright (c) 2012 Acroquest Technology Co.,Ltd. * * 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 jp.co.acroquest.endosnipe.web.dashboard.controller; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import jp.co.acroquest.endosnipe.common.util.MessageUtil; import jp.co.acroquest.endosnipe.web.dashboard.constants.ResponseConstants; import jp.co.acroquest.endosnipe.web.dashboard.dto.ResponseDto; import jp.co.acroquest.endosnipe.web.dashboard.dto.SignalDefinitionDto; import jp.co.acroquest.endosnipe.web.dashboard.entity.SignalInfo; import jp.co.acroquest.endosnipe.web.dashboard.manager.ResourceSender; import jp.co.acroquest.endosnipe.web.dashboard.service.SignalService; import net.arnx.jsonic.JSON; 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.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.wgp.manager.WgpDataManager; /** * 閾値判定機能のコントローラークラス。 * * @author miyasaka * */ @Controller @RequestMapping("/signal") public class SignalController { /** Wgpのデータを管理するクラス。 */ @Autowired protected WgpDataManager wgpDataManager; /** リソースを送信するクラスのオブジェクト。 */ @Autowired protected ResourceSender resourceSender; /** シグナル定義のサービスクラスのオブジェクト。 */ @Autowired protected SignalService signalService; /** * コンストラクタ。 */ public SignalController() { } /** * 閾値判定の定義をすべて取得する。 * * @return 全ての閾値判定の定義 */ @RequestMapping(value = "/getAllDefinition", method = RequestMethod.POST) @ResponseBody public List<SignalDefinitionDto> getAllDefinition() { List<SignalDefinitionDto> signalDefinitionDtos = new ArrayList<SignalDefinitionDto>(); signalDefinitionDtos = signalService.getAllSignal(); return signalDefinitionDtos; } /** * 閾値判定の定義を新規に追加する。 * * @param signalDefinition * 閾値判定の定義のJSONデータ * @return 追加した閾値判定の定義 */ @RequestMapping(value = "/add", method = RequestMethod.POST) @ResponseBody public ResponseDto add(@RequestParam(value = "signalDefinition") final String signalDefinition) { ResponseDto responseDto = new ResponseDto(); SignalDefinitionDto signalDefinitionDto = JSON.decode(signalDefinition, SignalDefinitionDto.class); String signalName = signalDefinitionDto.getSignalName(); boolean hasSameSignalName = this.signalService.hasSameSignalName(signalName); if (hasSameSignalName) { String errorMessage = MessageUtil.getMessage("WEWD0131", signalName); responseDto.setResult(ResponseConstants.RESULT_FAIL); responseDto.setMessage(errorMessage); return responseDto; } SignalInfo signalInfo = this.signalService.convertSignalInfo(signalDefinitionDto); // DBに追加する SignalDefinitionDto addedDefinitionDto = this.signalService.insertSignalInfo(signalInfo); responseDto.setData(addedDefinitionDto); responseDto.setResult(ResponseConstants.RESULT_SUCCESS); return responseDto; } /** * 閾値判定の定義を取得する。 * @param signalName 閾値判定の定義を一意に取得するためのシグナル名 * @return 閾値判定の定義 */ @RequestMapping(value = "/getDefinition", method = RequestMethod.POST) @ResponseBody public SignalDefinitionDto get(@RequestParam(value = "signalName") final String signalName) { SignalDefinitionDto signalDefinition = this.signalService.getSignalInfo(signalName); return signalDefinition; } /** * 閾値判定の定義を編集する。 * * @param signalDefinition * 閾値判定の定義のJSONデータ * @return 編集後の閾値判定の定義 */ @RequestMapping(value = "/edit", method = RequestMethod.POST) @ResponseBody public ResponseDto edit(@RequestParam(value = "signalDefinition") final String signalDefinition) { ResponseDto responseDto = new ResponseDto(); SignalDefinitionDto signalDefinitionDto = JSON.decode(signalDefinition, SignalDefinitionDto.class); long signalId = signalDefinitionDto.getSignalId(); String signalName = signalDefinitionDto.getSignalName(); boolean hasSameSignalName = this.signalService.hasSameSignalName(signalId, signalName); if (hasSameSignalName) { String errorMessage = MessageUtil.getMessage("WEWD0131", signalName); responseDto.setResult(ResponseConstants.RESULT_FAIL); responseDto.setMessage(errorMessage); return responseDto; } SignalInfo signalInfo = this.signalService.convertSignalInfo(signalDefinitionDto); // DBに登録されている定義を更新する SignalDefinitionDto updatedDefinitionDto = this.signalService.updateSignalInfo(signalInfo); responseDto.setResult(ResponseConstants.RESULT_SUCCESS); responseDto.setData(updatedDefinitionDto); return responseDto; } /** * 閾値判定のシグナルを削除する。 * * @param signalName * 閾値判定のシグナル名 * @return 削除した閾値判定のシグナル名 */ @RequestMapping(value = "/delete", method = RequestMethod.POST) @ResponseBody public ResponseDto delete(@RequestParam(value = "signalName") final String signalName) { this.signalService.deleteSignalInfo(signalName); Map<String, Object> map = new HashMap<String, Object>(); map.put("signalName", signalName); ResponseDto responseDto = new ResponseDto(); responseDto.setResult(ResponseConstants.RESULT_SUCCESS); responseDto.setData(map); return responseDto; } }
36.655
101
0.678898
410e0329b58db42299b2aa11d4f3423b54d9228c
781
package nortantis.editor; import java.awt.Color; import java.io.Serializable; @SuppressWarnings("serial") public class RegionEdit implements Serializable { public Color color; public int regionId; public RegionEdit( int regionId, Color color) { this.color = color; this.regionId = regionId; } @Override public int hashCode() { return regionId; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; RegionEdit other = (RegionEdit) obj; if (color == null) { if (other.color != null) return false; } else if (!color.equals(other.color)) return false; if (regionId != other.regionId) return false; return true; } }
16.978261
47
0.674776
96f249a07da3cf020e40edf480c693a4aed8641d
144
package com.heyongrui.module; import com.heyongrui.base.app.BaseApplication; public class ModuleLaunchApplication extends BaseApplication { }
20.571429
62
0.840278
6f13676d64b240fff1a44b0f3a2028182fc9f1ce
1,059
/** * <html> * <body> * <P> Copyright 1994-2018. JasonInternational.</p> * <p> All rights reserved.</p> * <p> Created by Jason</p> * </body> * </html> */ package cn.ucaner.fastdfs.test; import static org.junit.Assert.assertEquals; import org.apache.commons.configuration.ConfigurationException; import org.junit.Test; import cn.ucaner.fastdfs.FastdfsClientConfig; /** * @Package:cn.ucaner.fastdfs.test * @ClassName:FastdfsClientConfigTest * @Description: <p> FastdfsClientConfigTest</p> * @Author: - Jason * @CreatTime:2018年3月14日 上午10:33:37 * @Modify By: * @ModifyTime: 2018年3月14日 * @Modify marker: * @version V1.0 */ public class FastdfsClientConfigTest { @Test public void testFastdfsClientConfigString() throws ConfigurationException { FastdfsClientConfig fastdfsClientConfig = new FastdfsClientConfig("dfs/fastDFSClient.properties"); assertEquals(5*1000, fastdfsClientConfig.getConnectTimeout()); assertEquals(30*1000,fastdfsClientConfig.getNetworkTimeout()); } }
26.475
101
0.705382
12b656dcb0837a67b33beda5743d303786a92581
3,077
package com.e16din.handyholder.settings; import android.support.v7.widget.RecyclerView; import android.view.View; import com.e16din.handyholder.listeners.click.OnClickListener; import com.e16din.handyholder.listeners.click.OnViewsClickListener; import java.util.List; public class ClickBox<ADAPTER extends RecyclerView.Adapter, HOLDER extends RecyclerView.ViewHolder, MODEL> extends BaseBox<ADAPTER, HOLDER, MODEL> { private OnClickListener<MODEL> mClickListener; private OnViewsClickListener<MODEL> mViewsClickListener; private List<Integer> mClickableViewsList; private int[] mClickableViewsArray; public void updateClickListeners(final MODEL item, final int position) { vRoot.setOnClickListener(null); if (mClickListener != null) { vRoot.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mClickListener.onClick(item, position); } }); } if (mViewsClickListener != null) { if (mClickableViewsList != null) { for (final int viewId : mClickableViewsList) { updateItemChildViewClickListener(item, viewId, position); } } if (mClickableViewsArray != null) { for (final int viewId : mClickableViewsArray) { updateItemChildViewClickListener(item, viewId, position); } } } } private void updateItemChildViewClickListener(final MODEL item, final int viewId, final int position) { final View view = vRoot.findViewById(viewId); if (view == null) return;//wait for async inflating view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mViewsClickListener.onClick(viewId, item, position); } }); } public OnClickListener<MODEL> getClickListener() { return mClickListener; } public OnViewsClickListener<MODEL> getViewsClickListener() { return mViewsClickListener; } public List<Integer> getClickableViewsList() { return mClickableViewsList; } public int[] getClickableViewsArray() { return mClickableViewsArray; } public void setClickListener(OnClickListener<MODEL> clickListener) { mClickListener = clickListener; } public void setViewsClickListener(OnViewsClickListener<MODEL> viewsClickListener) { mViewsClickListener = viewsClickListener; } public void setClickableViewsArray(int[] clickableViewsArray) { mClickableViewsArray = clickableViewsArray; } public void setClickableViewsList(List<Integer> clickableViewsList) { mClickableViewsList = clickableViewsList; } @Override public void onBind(HOLDER holder, MODEL item, int position) { super.onBind(holder, item, position); updateClickListeners(item, position); } }
31.080808
107
0.657459
45f24909371d11dee8a9c911bcef47074e439f8f
3,084
package il.org.spartan.spartanizer.tippers; import static il.org.spartan.Utils.*; import static il.org.spartan.lisp.*; import static il.org.spartan.spartanizer.ast.factory.make.*; import static org.eclipse.jdt.core.dom.InfixExpression.Operator.*; import java.util.*; import org.eclipse.jdt.core.dom.*; import org.eclipse.jdt.core.dom.rewrite.*; import org.eclipse.text.edits.*; import static il.org.spartan.spartanizer.ast.navigate.step.*; import static il.org.spartan.spartanizer.ast.navigate.extract.*; import il.org.spartan.spartanizer.ast.factory.*; import il.org.spartan.spartanizer.ast.safety.*; import il.org.spartan.spartanizer.dispatch.*; import il.org.spartan.spartanizer.engine.*; import il.org.spartan.spartanizer.tipping.*; /** convert an expression such as * * <pre> * 1 * i * </pre> * * or * * <pre> * i * 1 * </pre> * * to * * <pre> * i * </i> * or * <pre> * i * 1 * jasLiteral * </pre> * * to * * <pre> * i * j * </pre> * * @author Matteo Orrù * @since 2016 */ public final class InfixFactorNegatives extends CarefulTipper<InfixExpression> implements TipperCategory.Sorting { private static List<Expression> gather(final Expression x, final List<Expression> $) { if (x instanceof InfixExpression) return gather(az.infixExpression(x), $); $.add(x); return $; } private static List<Expression> gather(final InfixExpression ¢) { return gather(¢, new ArrayList<Expression>()); } private static List<Expression> gather(final InfixExpression x, final List<Expression> $) { if (x == null) return $; if (!in(x.getOperator(), TIMES, DIVIDE)) { $.add(x); return $; } gather(core(left(x)), $); gather(core(right(x)), $); if (x.hasExtendedOperands()) gather(extendedOperands(x), $); return $; } private static List<Expression> gather(final List<Expression> xs, final List<Expression> $) { for (final Expression ¢ : xs) gather(¢, $); return $; } @Override public String description(final InfixExpression ¢) { return "Use at most one arithmetical negation, for first factor of " + ¢.getOperator(); } @Override public Tip tip(final InfixExpression x, final ExclusionManager exclude) { final List<Expression> es = gather(x); if (es.size() < 2) return null; final int totalNegation = minus.level(x); if (totalNegation == 0 || totalNegation == 1 && minus.level(left(x)) == 1) return null; if (exclude != null) exclude.exclude(x); return new Tip(description(x), x, this.getClass()) { @Override public void go(final ASTRewrite r, final TextEditGroup g) { final Expression first = totalNegation % 2 == 0 ? null : first(es); for (final Expression ¢ : es) if (¢ != first && minus.level(¢) > 0) r.replace(¢, plant(duplicate.of(minus.peel(¢))).into(¢.getParent()), g); if (first != null) r.replace(first, plant(subject.operand(minus.peel(first)).to(PrefixExpression.Operator.MINUS)).into(first.getParent()), g); } }; } }
27.783784
133
0.649157
9069f319672567216050361d0c6123a2418f1359
4,578
/******************************************************************************* * Copyright 2012 Yuriy Lagodiuk * * 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.lagodiuk.ga; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.WeakHashMap; public class GeneticAlgorithm<C extends Chromosome<C>, T extends Comparable<T>> { private static final int ALL_PARENTAL_CHROMOSOMES = Integer.MAX_VALUE; private class ChromosomesComparator implements Comparator<C> { private final Map<C, T> cache = new WeakHashMap<C, T>(); @Override public int compare(C chr1, C chr2) { T fit1 = this.fit(chr1); T fit2 = this.fit(chr2); int ret = fit1.compareTo(fit2); return ret; } public T fit(C chr) { T fit = this.cache.get(chr); if (fit == null) { fit = GeneticAlgorithm.this.fitnessFunc.calculate(chr); this.cache.put(chr, fit); } return fit; }; public void clearCache() { this.cache.clear(); } } private final ChromosomesComparator chromosomesComparator; private final Fitness<C, T> fitnessFunc; private Population<C> population; // listeners of genetic algorithm iterations (handle callback afterwards) private final List<IterartionListener<C, T>> iterationListeners = new LinkedList<IterartionListener<C, T>>(); private boolean terminate = false; // number of parental chromosomes, which survive (and move to new // population) private int parentChromosomesSurviveCount = ALL_PARENTAL_CHROMOSOMES; private int iteration = 0; public GeneticAlgorithm(Population<C> population, Fitness<C, T> fitnessFunc) { this.population = population; this.fitnessFunc = fitnessFunc; this.chromosomesComparator = new ChromosomesComparator(); this.population.sortPopulationByFitness(this.chromosomesComparator); } public void evolve() { int parentPopulationSize = this.population.getSize(); Population<C> newPopulation = new Population<C>(); for (int i = 0; (i < parentPopulationSize) && (i < this.parentChromosomesSurviveCount); i++) { newPopulation.addChromosome(this.population.getChromosomeByIndex(i)); } for (int i = 0; i < parentPopulationSize; i++) { C chromosome = this.population.getChromosomeByIndex(i); C mutated = chromosome.mutate(); C otherChromosome = this.population.getRandomChromosome(); List<C> crossovered = chromosome.crossover(otherChromosome); newPopulation.addChromosome(mutated); for (C c : crossovered) { newPopulation.addChromosome(c); } } newPopulation.sortPopulationByFitness(this.chromosomesComparator); newPopulation.trim(parentPopulationSize); this.population = newPopulation; } public void evolve(int count) { this.terminate = false; for (int i = 0; i < count; i++) { if (this.terminate) { break; } this.evolve(); this.iteration = i; for (IterartionListener<C, T> l : this.iterationListeners) { l.update(this); } } } public int getIteration() { return this.iteration; } public void terminate() { this.terminate = true; } public Population<C> getPopulation() { return this.population; } public C getBest() { return this.population.getChromosomeByIndex(0); } public C getWorst() { return this.population.getChromosomeByIndex(this.population.getSize() - 1); } public void setParentChromosomesSurviveCount(int parentChromosomesCount) { this.parentChromosomesSurviveCount = parentChromosomesCount; } public int getParentChromosomesSurviveCount() { return this.parentChromosomesSurviveCount; } public void addIterationListener(IterartionListener<C, T> listener) { this.iterationListeners.add(listener); } public void removeIterationListener(IterartionListener<C, T> listener) { this.iterationListeners.remove(listener); } public T fitness(C chromosome) { return this.chromosomesComparator.fit(chromosome); } public void clearCache() { this.chromosomesComparator.clearCache(); } }
27.914634
110
0.709043
76f3cd344c2ea718f39d10fe190fd522179014c2
1,584
package net.boomerangplatform.repository.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class Issues { @JsonProperty("total") private Integer total; @JsonProperty("blocker") private Integer blocker; @JsonProperty("critical") private Integer critical; @JsonProperty("major") private Integer major; @JsonProperty("minor") private Integer minor; @JsonProperty("info") private Integer info; @JsonProperty("filesAnalyzed") private Integer filesAnalyzed; public Issues() { // Do nothing } public Integer getTotal() { return total; } public void setTotal(Integer total) { this.total = total; } public Integer getBlocker() { return blocker; } public void setBlocker(Integer blocker) { this.blocker = blocker; } public Integer getCritical() { return critical; } public void setCritical(Integer critical) { this.critical = critical; } public Integer getMajor() { return major; } public void setMajor(Integer major) { this.major = major; } public Integer getMinor() { return minor; } public void setMinor(Integer minor) { this.minor = minor; } public Integer getInfo() { return info; } public void setInfo(Integer info) { this.info = info; } public Integer getFilesAnalyzed() { return filesAnalyzed; } public void setFilesAnalyzed(Integer filesAnalyzed) { this.filesAnalyzed = filesAnalyzed; } }
17.6
61
0.693813
f97bf9ae9c65db8af7f643ca59c7a6555def9215
728
package ru.job4j.list.linkedlist.stack; import ru.job4j.list.linkedlist.PlainLinkedList; public class SimpleStack<E> { private PlainLinkedList<E> linkedStore = new PlainLinkedList<>(); /** * poll last element. * @return - element. */ public E poll() { E result = linkedStore.get(linkedStore.getLastIndexFromList()); linkedStore.deleteLastElement(); return result; } /** * "add" element to stack. * @param item - received element. */ public void push(E item) { linkedStore.add(item); } /** * Getter. * @return - linkedStore. */ public PlainLinkedList<E> getLinkedStore() { return linkedStore; } }
20.8
72
0.597527
762e633645838873340102265c6196fcc98848a7
4,029
package seedu.address.logic.commands.person; import static java.util.Objects.requireNonNull; import java.util.HashSet; import java.util.List; import java.util.Set; import seedu.address.commons.core.Messages; import seedu.address.commons.core.index.Index; import seedu.address.logic.EditTaskDescriptor; import seedu.address.logic.commands.Command; import seedu.address.logic.commands.CommandResult; import seedu.address.logic.commands.task.exceptions.CommandException; import seedu.address.model.Model; import seedu.address.model.name.Name; import seedu.address.model.person.Person; import seedu.address.model.tag.Tag; import seedu.address.model.task.Date; import seedu.address.model.task.EndTime; import seedu.address.model.task.StartTime; import seedu.address.model.task.Task; /** * Deletes a person identified using it's displayed index from the address book. */ public class DeletePersonCommand extends Command { public static final String COMMAND_WORD = "del-p"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Deletes the person identified by the index number used in the displayed person list.\n" + "Parameters: INDEX (must be a positive integer)\n" + "Example: " + COMMAND_WORD + " 1"; public static final String MESSAGE_DELETE_PERSON_SUCCESS = "Deleted Person: %1$s"; private final Index targetIndex; public DeletePersonCommand(Index targetIndex) { this.targetIndex = targetIndex; } @Override public CommandResult execute(Model model) throws CommandException { requireNonNull(model); List<Person> lastShownPersonList = model.getFilteredPersonList(); List<Task> unfilteredTaskList = model.getUnfilteredTaskList(); if (targetIndex.getZeroBased() >= lastShownPersonList.size()) { throw new CommandException(Messages.MESSAGE_INVALID_PERSON_DISPLAYED_INDEX); } Person personToDelete = lastShownPersonList.get(targetIndex.getZeroBased()); // update tasks after the deletion of person for (Task task: unfilteredTaskList) { if (task.getPersons().contains(personToDelete.getName())) { EditTaskDescriptor editTaskDescriptor = new EditTaskDescriptor(); Set<Name> persons = new HashSet<>(task.getPersons()); persons.remove(personToDelete.getName()); editTaskDescriptor.setPersons(persons); Task editedTask = createEditedTask(task, editTaskDescriptor); model.setTask(task, editedTask); } } model.deletePerson(personToDelete); return new CommandResult(String.format(MESSAGE_DELETE_PERSON_SUCCESS, personToDelete)); } /** * Creates and returns a {@code Task} with the details of {@code taskToEdit} * edited with {@code editTaskDescriptor}. */ public static Task createEditedTask(Task taskToEdit, EditTaskDescriptor editTaskDescriptor) { assert taskToEdit != null; Name updatedName = editTaskDescriptor.getName().orElse(taskToEdit.getName()); Date updatedDate = editTaskDescriptor.getDate().orElse(taskToEdit.getDate()); StartTime updatedStartTime = editTaskDescriptor.getStartTime().orElse(taskToEdit.getStartTime()); EndTime updatedEndTime = editTaskDescriptor.getEndTime().orElse(taskToEdit.getEndTime()); Set<Tag> updatedTags = editTaskDescriptor.getTags().orElse(taskToEdit.getTags()); Set<Name> updatedPersons = editTaskDescriptor.getPersons().orElse(taskToEdit.getPersons()); return new Task(updatedName, updatedDate, updatedStartTime, updatedEndTime, updatedTags, updatedPersons); } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof DeletePersonCommand // instanceof handles nulls && targetIndex.equals(((DeletePersonCommand) other).targetIndex)); // state check } }
42.410526
105
0.712087
1a0a3cfa26a15bcda4daa39c3569a987478a4ed9
890
package Linked_List1_07; public class TestSLinkedList { public static void main(String[] args) { SLinkedList newLinkedList = new SLinkedList(); System.out.println(newLinkedList.listSize); // 0 newLinkedList.insertFront("Milk"); newLinkedList.insertFront("Orange juice"); newLinkedList.insertFront("Apple juice"); while (newLinkedList.head.next != null){ System.out.println("new linked list size: " + newLinkedList.listSize); System.out.println("new linked list item: " + newLinkedList.head.item); newLinkedList.head = newLinkedList.head.next; if(newLinkedList.head.next == null){ System.out.println("new linked list size: " + newLinkedList.listSize); System.out.println("new linked list item: " + newLinkedList.head.item); } } } }
40.454545
87
0.631461
3c79035a6fe0cf2609af388ebf9d3688fb35902b
293
package distrubition; import java.util.HashMap; import java.util.concurrent.ThreadPoolExecutor; /** * @author zero * @created 2019/10/25 */ public class Test { public static void main(String[] args) { System.out.format("二进制输出=%s\n", Integer.toBinaryString(1 << 31)); } }
18.3125
73
0.675768
17045750bbfae553d2cbf103b5c3b4c1461708cb
2,844
package com.tourcool.ui.kitchen; import android.os.Bundle; import android.widget.TextView; import com.frame.library.core.widget.titlebar.TitleBarView; import com.tourcool.core.widget.HtmlWebView; import com.tourcool.smartcity.R; import com.tourcool.ui.base.BaseCommonTitleActivity; /** * @author :JenkinsZhou * @description : * @company :翼迈科技股份有限公司 * @date 2020年02月11日9:47 * @Email: 971613168@qq.com */ public class ProtocolActivity extends BaseCommonTitleActivity { private TextView htmlWebView; @Override public int getContentLayout() { return R.layout.activity_webview_protocol_layout; } @Override public void setTitleBar(TitleBarView titleBar) { super.setTitleBar(titleBar); titleBar.setTitleMainText("用户服务协议"); } @Override public void initView(Bundle savedInstanceState) { htmlWebView = findViewById(R.id.htmlWebView); String content = "一、服务条款确认\n" + "用户应当同意本协议的条款并按照页面上的提示完成全部的注册程序。用户在进行注册程序过程中点击\"同意\"按钮即表示用户与本单位达成协议,完全接受本协议项下的全部条款。\n" + "二、服务条款修改\n" + "本系统在必要时可修改服务条款,并在系统上进行更新,一经发布,立即生效。如您继续使用服务,则视为您已接受修订的服务条款。\n" + "三、用户注册\n" + "考虑到本系统用户服务的重要性,您同意在注册时提供真实、完整及准确的个人资料,并及时更新。盗用他人身份信息注册本系统所引发起的一切不当后果与本系统无关,本系统不承担因此造成的任何法律责任。以此身份信息办理的一切事务与本系统无关,本系统不承担因此造成的任何法律责任。\n" + "用户注册成功后,本系统将给予每个用户一个用户帐号及相应的密码,该用户帐号和密码由用户负责保管;用户应当对以其用户帐号进行的所有活动和事件负法律责任。\n" + "本系统有权对您提供的资料进行核验,核验结果仅适用于您在本系统办理注册以及查询本人相关信息业务;如您提供的资料不准确,或无法通过本系统核验,或本系统有合理的理由认为该资料不真实、不完整、不准确,本系统有权暂停或终止您的注册身份及资料,并拒绝您使用本系统的服务。\n" + "四、用户资料及保密\n" + "注册时,请您按页面提示提交相关信息。您负有对用户名和密码保密的义务,并对该用户名和密码下发生的所有活动承担责任。\n" + "实名认证就等于授权e宜兴显示个人的相关信息,但是个人信息只有登录后个人才能看到。如果不想让e宜兴显示个人信息,请自行选择是否使用e宜兴。\n" + "为更为有效地向您提供服务,您同意,本单位有权将您注册及使用本服务过程中所提供、形成的信息提供给本系统对接的相关政府部门或公用事业单位等合作单位,本系统不会向您所使用服务所涉及合作单位之外的其他方公开或透露您的个人资料,法律法规规定除外。\n" + "五、责任范围及责任限制\n" + "为本系统提供服务的相关政府或公共事业单位等合作单位,所提供之服务品质及内容由该合作单位自行负责,本系统不保证该信息之准确、及时和完整。\n" + "六、外部链接\n本系统含有到其他网站的链接,但本系统对其他网站的隐私保护措施不负任何责任。本系统可能在任何需要的时候增加商业伙伴或共用品牌的网站。\n" + "七、保障\n" + "您同意保障和维护本系统的利益,并承担您或其他人使用您的用户资料造成本系统或任何第三方的损失或损害的赔偿责任。"; loadRichText(content); } private void loadRichText(String richText){ htmlWebView.setText(richText); } /* htmlWebView.imageClick((imageUrls, position) -> { //imageUrls是所有图片地址的list ///position是点击位置 }) .urlClick(url -> { //url为链接跳转地址 //返回true为自己处理跳转,false为webview自行跳转 return false; }) .imageLongClick(imageUrl->{ //imageUrl为长按图片的地址 }) .setHtml(richText);//html富文本的字符串 }*/ }
40.056338
153
0.657876
390bb766ab810009508fa031314f9876ee25b196
2,923
/* * Copyright (C) 2019 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.android.overlaytest; import static java.util.concurrent.TimeUnit.SECONDS; import android.app.UiAutomation; import android.content.res.Resources; import android.os.ParcelFileDescriptor; import androidx.test.InstrumentationRegistry; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.concurrent.Executor; import java.util.concurrent.FutureTask; class LocalOverlayManager { private static final long TIMEOUT = 30; public static void setEnabledAndWait(Executor executor, final String packageName, boolean enable) throws Exception { final String pattern = (enable ? "[x]" : "[ ]") + " " + packageName; if (executeShellCommand("cmd overlay list").contains(pattern)) { // nothing to do, overlay already in the requested state return; } final Resources res = InstrumentationRegistry.getContext().getResources(); final String[] oldApkPaths = res.getAssets().getApkPaths(); FutureTask<Boolean> task = new FutureTask<>(() -> { while (true) { if (!Arrays.equals(oldApkPaths, res.getAssets().getApkPaths())) { return true; } Thread.sleep(10); } }); executor.execute(task); executeShellCommand("cmd overlay " + (enable ? "enable " : "disable ") + packageName); task.get(TIMEOUT, SECONDS); } private static String executeShellCommand(final String command) throws Exception { final UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation(); final ParcelFileDescriptor pfd = uiAutomation.executeShellCommand(command); try (InputStream in = new ParcelFileDescriptor.AutoCloseInputStream(pfd)) { final BufferedReader reader = new BufferedReader( new InputStreamReader(in, StandardCharsets.UTF_8)); StringBuilder str = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { str.append(line); } return str.toString(); } } }
37.474359
94
0.66507
e04feffce22309bb6f526f3ff092541feb5c6aa4
2,772
package com.mosi.jpa.entity; import java.time.ZonedDateTime; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.PrePersist; /** * Feedback Entity class which represent stored object. * <p> * Object contains user's name with feedback message. ID and CreateDate is * assigned automatically on creation * </p> * * @author Martin * */ @Entity public class FeedbackEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(nullable = false) private String user; @Column(nullable = false) private String message; @Column private ZonedDateTime createDate; public FeedbackEntity() { } public FeedbackEntity(String user, String message) { this.user = user; this.message = message; } @PrePersist protected void onCreate() { createDate = ZonedDateTime.now(); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public void setCreateDate(ZonedDateTime createDate) { this.createDate = createDate; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public ZonedDateTime getCreateDate() { return createDate; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((createDate == null) ? 0 : createDate.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((message == null) ? 0 : message.hashCode()); result = prime * result + ((user == null) ? 0 : user.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; FeedbackEntity other = (FeedbackEntity) obj; if (createDate == null) { if (other.createDate != null) return false; } else if (!createDate.equals(other.createDate)) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (message == null) { if (other.message != null) return false; } else if (!message.equals(other.message)) return false; if (user == null) { if (other.user != null) return false; } else if (!user.equals(other.user)) return false; return true; } @Override public String toString() { return "FeedbackEntity [id=" + id + ", user=" + user + ", message=" + message + ", createDate=" + createDate + "]"; } }
20.842105
110
0.670274
46ad50cecb22077ea7bef11e5dd78bd1ba4c0f52
401
package com.clean.architecture.domain.entities; public class OrderItem { public String idItem; public double price; public int quantity; public OrderItem(String idItem, double price, int quantity){ this.idItem = idItem; this.price = price; this.quantity = quantity; } public double getTotal(){ return this.price * this.quantity; } }
21.105263
64
0.645885
4a27931698951e732d10f92031c6af51aa172195
7,416
/* * Copyright © 2016 Cask Data, 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 co.cask.cdap.internal.app.runtime; import ch.qos.logback.core.Context; import ch.qos.logback.core.joran.util.ConfigurationWatchListUtil; import co.cask.cdap.app.guice.ClusterMode; import co.cask.cdap.app.runtime.Arguments; import co.cask.cdap.app.runtime.ProgramOptions; import co.cask.cdap.app.runtime.ProgramRunner; import co.cask.cdap.common.app.RunIds; import co.cask.cdap.common.io.Locations; import co.cask.cdap.proto.id.ArtifactId; import co.cask.cdap.proto.id.KerberosPrincipalId; import com.google.common.base.Preconditions; import com.google.common.base.Splitter; import com.google.common.base.Strings; import com.google.common.io.ByteStreams; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.Service; import org.apache.hadoop.security.UserGroupInformation; import org.apache.twill.api.RunId; import org.apache.twill.filesystem.Location; import org.slf4j.ILoggerFactory; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.security.PrivilegedExceptionAction; import java.util.Map; import java.util.concurrent.Callable; import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; import javax.annotation.Nullable; /** * Utility class to provide common functionality that shares among different {@link ProgramRunner}. */ public final class ProgramRunners { /** * Impersonates as the given user to start a guava service * * @param user user to impersonate * @param service guava service start start */ public static void startAsUser(String user, final Service service) throws IOException, InterruptedException { runAsUser(user, new Callable<ListenableFuture<Service.State>>() { @Override public ListenableFuture<Service.State> call() throws Exception { return service.start(); } }); } /** * Impersonates as the given user to perform an action. * * @param user user to impersonate * @param callable action to perform */ public static <T> T runAsUser(String user, final Callable<T> callable) throws IOException, InterruptedException { return UserGroupInformation.createRemoteUser(user) .doAs(new PrivilegedExceptionAction<T>() { @Override public T run() throws Exception { return callable.call(); } }); } /** * Updates the given arguments to always have the logical start time set. * * @param arguments the runtime arguments * @return the logical start time */ public static long updateLogicalStartTime(Map<String, String> arguments) { String value = arguments.get(ProgramOptionConstants.LOGICAL_START_TIME); try { // value is only empty/null in in some unit tests long logicalStartTime = Strings.isNullOrEmpty(value) ? System.currentTimeMillis() : Long.parseLong(value); arguments.put(ProgramOptionConstants.LOGICAL_START_TIME, Long.toString(logicalStartTime)); return logicalStartTime; } catch (NumberFormatException e) { throw new IllegalArgumentException(String.format( "%s is set to an invalid value %s. Please ensure it is a timestamp in milliseconds.", ProgramOptionConstants.LOGICAL_START_TIME, value)); } } /** * Returns the {@link RunId} stored inside the given {@link ProgramOptions#getArguments()}. * * @throws IllegalArgumentException if the given options doesn't contain run id. */ public static RunId getRunId(ProgramOptions programOptions) { String id = programOptions.getArguments().getOption(ProgramOptionConstants.RUN_ID); Preconditions.checkArgument(id != null, "Missing " + ProgramOptionConstants.RUN_ID + " in program options"); return RunIds.fromString(id); } /** * Returns the application principal if there is one. * * @param programOptions the program options to extract information from * @return the application principal or {@code null} if no application principal is available. */ @Nullable public static KerberosPrincipalId getApplicationPrincipal(ProgramOptions programOptions) { Arguments systemArgs = programOptions.getArguments(); boolean hasAppPrincipal = Boolean.parseBoolean(systemArgs.getOption(ProgramOptionConstants.APP_PRINCIPAL_EXISTS)); return hasAppPrincipal ? new KerberosPrincipalId(systemArgs.getOption(ProgramOptionConstants.PRINCIPAL)) : null; } /** * Same as {@link #createLogbackJar(Location)} except this method uses local {@link File} instead. */ @Nullable public static File createLogbackJar(File targetFile) throws IOException { Location logbackJar = createLogbackJar(Locations.toLocation(targetFile)); return logbackJar == null ? null : new File(logbackJar.toURI()); } /** * Creates a jar that contains a logback.xml configured for the current process * * @param targetLocation the jar location * @return the {@link Location} where the jar was created to or {@code null} if "logback.xml" is not found * in the current ClassLoader. * @throws IOException if failed in reading the logback xml or writing out the jar */ @Nullable public static Location createLogbackJar(Location targetLocation) throws IOException { ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory(); if (!(loggerFactory instanceof Context)) { return null; } URL logbackURL = ConfigurationWatchListUtil.getMainWatchURL((Context) loggerFactory); if (logbackURL == null) { return null; } try (InputStream input = logbackURL.openStream()) { try (JarOutputStream output = new JarOutputStream(targetLocation.getOutputStream())) { output.putNextEntry(new JarEntry("logback.xml")); ByteStreams.copy(input, output); } return targetLocation; } } /** * Returns the {@link ArtifactId} stored inside the given {@link ProgramOptions#getArguments()}. */ public static ArtifactId getArtifactId(ProgramOptions programOptions) { String id = programOptions.getArguments().getOption(ProgramOptionConstants.ARTIFACT_ID); Preconditions.checkArgument(id != null, "Missing " + ProgramOptionConstants.ARTIFACT_ID + " in program options"); return ArtifactId.fromIdParts(Splitter.on(':').split(id)); } /** * Returns the {@link ClusterMode} stored inside the given {@link ProgramOptions#getArguments()}. */ public static ClusterMode getClusterMode(ProgramOptions programOptions) { String clusterMode = programOptions.getArguments().getOption(ProgramOptionConstants.CLUSTER_MODE); // Default to ON_PREMISE for backward compatibility. return clusterMode == null ? ClusterMode.ON_PREMISE : ClusterMode.valueOf(clusterMode); } private ProgramRunners() { // no-op } }
38.42487
118
0.740291
6c94e977cefa2fbfa97dd9ee66dc25c875cacbd1
1,801
/******************************************************************************* * Copyright 2012-2014 Analog Devices, 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 com.analog.lyric.dimple.solvers.sumproduct.customFactors; import com.analog.lyric.dimple.model.domains.Domain; import com.analog.lyric.dimple.model.factors.Factor; import com.analog.lyric.dimple.model.variables.Variable; // Same as CustomMultivariateGaussianSum, except the second edge is treated as the output instead of the first public class CustomMultivariateGaussianSubtract extends CustomMultivariateGaussianSum { public CustomMultivariateGaussianSubtract(Factor factor) { super(factor); _sumIndex = 1; // Port that is the sum of all the others } // Utility to indicate whether or not a factor is compatible with the requirements of this custom factor public static boolean isFactorCompatible(Factor factor) { for (int i = 0, end = factor.getSiblingCount(); i < end; i++) { Variable v = factor.getSibling(i); Domain domain = v.getDomain(); // Must be unbounded multivariate real if (!domain.isRealJoint() || domain.isBounded()) { return false; } } return true; } }
36.755102
110
0.678512
2cb2d0125007b1c426df5e76134ca7094055e825
653
package com.javaalgorithms.sorts; public class SortingUtils { /** * Helper method for swapping places in array * * @param array The array which elements we want to swap * @param idx index of the first element * @param idy index of the second element */ static <T> boolean swap(T[] array, int idx, int idy){ try { T temp = array[idx]; array[idx] = array[idy]; array[idy] = temp; return true; }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Array Index out of bounds" + e.getMessage()); throw e; } } }
28.391304
77
0.569678
eddc61c5f9f5df38c19c46ac02489bd4a608d6fe
1,267
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package com.irobot.home.model.rest; public class RegisterCustomer { public RegisterCustomer(String s, boolean flag, String s1, String s2, String s3) { // 0 0:aload_0 // 1 1:invokespecial #16 <Method void Object()> email = s; // 2 4:aload_0 // 3 5:aload_1 // 4 6:putfield #18 <Field String email> promoOptIn = flag; // 5 9:aload_0 // 6 10:iload_2 // 7 11:putfield #20 <Field boolean promoOptIn> country = s2; // 8 14:aload_0 // 9 15:aload 4 // 10 17:putfield #22 <Field String country> postalCode = s1; // 11 20:aload_0 // 12 21:aload_3 // 13 22:putfield #24 <Field String postalCode> language = s3; // 14 25:aload_0 // 15 26:aload 5 // 16 28:putfield #26 <Field String language> // 17 31:return } public String country; public String email; public String language; public String postalCode; public boolean promoOptIn; }
28.795455
81
0.5588
81708a73809d0a3b9e930dfc1a12f8f5b2cdd0fe
1,531
/* * Copyright (c) 2008-2016, GigaSpaces Technologies, 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.gigaspaces.internal.query; import com.gigaspaces.internal.client.spaceproxy.IDirectSpaceProxy; import com.gigaspaces.internal.transport.IEntryPacket; import com.gigaspaces.internal.transport.ITemplatePacket; /** * @author Niv Ingberg * @since 10.0 */ @com.gigaspaces.api.InternalApi public class RawEntryConverter { private final IDirectSpaceProxy spaceProxy; private final ITemplatePacket queryPacket; private final boolean returnRawEntry; public RawEntryConverter(IDirectSpaceProxy spaceProxy, ITemplatePacket queryPacket, boolean returnRawEntry) { this.spaceProxy = spaceProxy; this.queryPacket = queryPacket; this.returnRawEntry = returnRawEntry; } public Object toObject(RawEntry rawEntry) { return spaceProxy.getTypeManager().convertQueryResult((IEntryPacket) rawEntry, queryPacket, returnRawEntry); } }
34.795455
116
0.760941
b28a1e2c8599bbd954765136fa884ae12ef00349
2,723
/* * Copyright 2013 Google 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.google.openbidder.http.util; import static org.junit.Assert.assertEquals; import org.junit.Test; /** * Tests for {@link HttpUtil}. */ public class HttpUtilTest { @Test public void buildUri() { HttpUtil.buildUri("http://a.io/path"); } @Test(expected = IllegalArgumentException.class) public void buildUri_bad() { HttpUtil.buildUri("this is not a uri"); } @Test public void concatPaths_nothing_root() { assertEquals("/", HttpUtil.concatPaths()); } @Test public void concatPaths_empty_root() { assertEquals("/", HttpUtil.concatPaths("")); } @Test public void concatPaths_root_root() { assertEquals("/", HttpUtil.concatPaths("/")); } @Test public void concatPaths_something_slashAdded() { assertEquals("/foo", HttpUtil.concatPaths("foo")); } @Test public void concatPaths_trailingSlash_slashRemoved() { assertEquals("/foo", HttpUtil.concatPaths("foo/")); } @Test public void concatPaths_internalSlash_slashUnchanged() { assertEquals("/foo/bar", HttpUtil.concatPaths("foo/bar")); } @Test public void concatPaths_emptyPlusSomething_something() { assertEquals("/foo", HttpUtil.concatPaths("", "foo")); } @Test public void concatPaths_emptyPlusSlashSomething_something() { assertEquals("/foo", HttpUtil.concatPaths("", "/foo")); } @Test public void concatPaths_emptyPlusSomethingSlash_something() { assertEquals("/foo", HttpUtil.concatPaths("", "foo/")); } @Test public void concatPaths_twoSomethings_something() { assertConcat("/foo/bar", "foo", "bar"); assertConcat("/foo/bar", "/foo", "bar"); assertConcat("/foo/bar", "foo/", "bar"); assertConcat("/foo/bar", "/foo/", "bar"); } private void assertConcat(String expected, String prefix, String suffix) { assertEquals(expected, HttpUtil.concatPaths(prefix, suffix)); assertEquals(expected, HttpUtil.concatPaths(prefix, "/" + suffix)); assertEquals(expected, HttpUtil.concatPaths(prefix, suffix + "/")); assertEquals(expected, HttpUtil.concatPaths(prefix, "/" + suffix + "/")); } }
27.785714
77
0.695189
032ae473bc94935cac560c1ba49d4dea6dbb94da
1,670
/* * Copyright 2021 Christopher Sieh (stelzo@steado.de) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.dofusdu.dto; import de.dofusdu.entity.Bonus; import de.dofusdu.entity.BonusType; import de.dofusdu.entity.Item; import de.dofusdu.entity.Offering; import de.dofusdu.util.DateConverter; import javax.json.bind.annotation.JsonbProperty; import java.time.LocalDate; public class CreateOfferingDTO { public String date; @JsonbProperty("item_quantity") public Integer itemQuantity; public String item; @JsonbProperty("description") public String bonus; @JsonbProperty("bonus") public String bonusType; @JsonbProperty("item_picture_url") public String itemPicture; public String language; public Offering toOffering(String language, String url) { return new Offering(DateConverter.toDate(DateConverter.fromString(date)), itemQuantity, new Bonus(bonus, language, new BonusType(bonusType, language)), new Item(item, language, itemPicture, url)); } public LocalDate getDate() { return DateConverter.fromString(date); } }
30.363636
81
0.722754
0b95c555c28e3c53afead04586856c83ebadbc93
10,613
package org.vaadin.touchmenu.client; import com.google.gwt.dom.client.Style; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.MouseDownEvent; import com.google.gwt.event.dom.client.MouseMoveEvent; import com.google.gwt.event.dom.client.MouseOutEvent; import com.google.gwt.event.dom.client.MouseUpEvent; import com.google.gwt.event.dom.client.TouchEndEvent; import com.google.gwt.event.dom.client.TouchEvent; import com.google.gwt.event.dom.client.TouchMoveEvent; import com.google.gwt.event.dom.client.TouchStartEvent; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.ui.AbsolutePanel; import com.google.gwt.user.client.ui.Button; import com.vaadin.client.VConsole; import org.vaadin.touchmenu.client.button.TouchMenuButtonWidget; import org.vaadin.touchmenu.client.flow.AbstractFlowView; import org.vaadin.touchmenu.client.flow.HorizontalFlowView; import org.vaadin.touchmenu.client.flow.VerticalFlowView; import java.util.LinkedList; import java.util.List; /** * @author Mikael Grankvist - Vaadin }> */ public class TouchMenuWidget extends AbsolutePanel { private static final String BASE_NAME = "touchmenu"; public static final String CLASSNAME = "c-" + BASE_NAME; private Button navigateLeft, navigateRight; private AbsolutePanel touchView; private AbstractFlowView touchArea; protected Direction buttonDirection = Direction.IN_FROM_SAME; private List<HandlerRegistration> domHandlers = new LinkedList<HandlerRegistration>(); private ScrollDirection flowView = ScrollDirection.HORIZONTAL; public TouchMenuWidget() { super(); getElement().getStyle().setPosition(Style.Position.RELATIVE); setStyleName(CLASSNAME); navigateLeft = new Button(); navigateRight = new Button(); navigateLeft.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { switch (buttonDirection) { case IN_FROM_OPPOSITE: touchArea.firstVisibleColumn++; break; case IN_FROM_SAME: touchArea.firstVisibleColumn--; break; } touchArea.transitionToColumn(); } }); navigateRight.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { switch (buttonDirection) { case IN_FROM_OPPOSITE: touchArea.firstVisibleColumn--; break; case IN_FROM_SAME: touchArea.firstVisibleColumn++; break; } touchArea.transitionToColumn(); } }); navigateLeft.getElement().setClassName("left-navigation"); navigateRight.getElement().setClassName("right-navigation"); navigateLeft.getElement().getStyle().setPosition(Style.Position.ABSOLUTE); navigateLeft.getElement().getStyle().setWidth(40, Style.Unit.PX); navigateRight.getElement().getStyle().setPosition(Style.Position.ABSOLUTE); navigateRight.getElement().getStyle().setWidth(40, Style.Unit.PX); touchView = new AbsolutePanel(); touchView.getElement().getStyle().setOverflow(Style.Overflow.HIDDEN); touchView.setHeight("100%"); setFlowView(flowView); add(navigateLeft); add(touchView); add(navigateRight); positionElements(); } protected void positionElements() { navigateLeft.getElement().getStyle().setLeft(0, Style.Unit.PX); navigateLeft.getElement().getStyle().setTop(0, Style.Unit.PX); if(flowView.equals(ScrollDirection.HORIZONTAL)) { navigateLeft.getElement().getStyle().setHeight(100, Style.Unit.PCT); navigateLeft.getElement().getStyle().setWidth(40, Style.Unit.PX); }else{ navigateLeft.getElement().getStyle().setWidth(100, Style.Unit.PCT); navigateLeft.getElement().getStyle().setHeight(40, Style.Unit.PX); } if(flowView.equals(ScrollDirection.HORIZONTAL)) { touchView.getElement().getStyle().setWidth(getOffsetWidth() - 80, Style.Unit.PX); touchView.getElement().getStyle().setHeight(getOffsetHeight(), Style.Unit.PX); touchView.getElement().getStyle().setLeft(40, Style.Unit.PX); touchView.getElement().getStyle().setTop(0, Style.Unit.PX); }else{ touchView.getElement().getStyle().setHeight(getOffsetHeight() - 80, Style.Unit.PX); touchView.getElement().getStyle().setWidth(getOffsetWidth(), Style.Unit.PX); touchView.getElement().getStyle().setLeft(0, Style.Unit.PX); touchView.getElement().getStyle().setTop(40, Style.Unit.PX); } if(flowView.equals(ScrollDirection.HORIZONTAL)) { navigateRight.getElement().getStyle().setRight(0, Style.Unit.PX); navigateRight.getElement().getStyle().clearLeft(); navigateRight.getElement().getStyle().setTop(0, Style.Unit.PX); navigateRight.getElement().getStyle().setHeight(100, Style.Unit.PCT); navigateRight.getElement().getStyle().setWidth(40, Style.Unit.PX); }else{ navigateRight.getElement().getStyle().setLeft(0, Style.Unit.PX); navigateRight.getElement().getStyle().clearRight(); navigateRight.getElement().getStyle().setTop(getOffsetHeight()-40, Style.Unit.PX); navigateRight.getElement().getStyle().setWidth(100, Style.Unit.PCT); navigateRight.getElement().getStyle().setHeight(40, Style.Unit.PX); } } public void setUseArrows(boolean useArrows) { touchArea.useArrows = useArrows; // TODO: Check for direction if navigation on top-bottom or on the sides if (useArrows) { positionElements(); navigateLeft.getElement().getStyle().setVisibility(Style.Visibility.VISIBLE); navigateRight.getElement().getStyle().setVisibility(Style.Visibility.VISIBLE); } else { touchView.getElement().getStyle().setLeft(0, Style.Unit.PX); touchView.getElement().getStyle().setTop(0, Style.Unit.PX); touchView.getElement().getStyle().setHeight(getOffsetHeight(), Style.Unit.PX); touchView.getElement().getStyle().setWidth(getOffsetWidth(), Style.Unit.PX); navigateLeft.getElement().getStyle().setVisibility(Style.Visibility.HIDDEN); navigateRight.getElement().getStyle().setVisibility(Style.Visibility.HIDDEN); } touchArea.layoutWidgets(); touchArea.transitionToColumn(); } public void setColumns(int columns) { touchArea.setColumns(columns); } public void setRows(int rows) { touchArea.setRows(rows); } public void setUseDefinedSizes(boolean useDefinedButtonSize) { touchArea.definedSizes = useDefinedButtonSize; touchArea.layoutWidgets(); touchArea.transitionToColumn(); } public void clear() { touchArea.clear(); } public void add(TouchMenuButtonWidget widget) { touchArea.add(widget); } public void setDirection(Direction direction) { buttonDirection = direction; touchArea.setDirection(direction); } public void validateRows() { touchArea.validateRows(); } public void validateColumns() { touchArea.validateColumns(); } public void layoutWidgets() { touchArea.layoutWidgets(); } @Override protected void onAttach() { super.onAttach(); touchArea.layoutWidgets(); } public void setDefinedWidth(int definedWidth) { touchArea.definedWidth = definedWidth; } public void setDefinedHeight(int definedHeight) { touchArea.definedHeight = definedHeight; } public void setAnimate(boolean animate) { touchArea.animate = animate; } public void setFlowView(ScrollDirection flowView) { this.flowView = flowView; if (touchArea != null) { touchView.remove(touchArea); } for (HandlerRegistration handler : domHandlers) { handler.removeHandler(); } domHandlers.clear(); positionElements(); switch (flowView) { case HORIZONTAL: touchArea = new HorizontalFlowView(touchView); navigateLeft.getElement().removeClassName("up-navigation"); navigateRight.getElement().removeClassName("down-navigation"); navigateLeft.getElement().setClassName("left-navigation"); navigateRight.getElement().setClassName("right-navigation"); break; case VERTICAL: touchArea = new VerticalFlowView(touchView); navigateLeft.getElement().removeClassName("left-navigation"); navigateRight.getElement().removeClassName("right-navigation"); navigateLeft.getElement().setClassName("up-navigation"); navigateRight.getElement().setClassName("down-navigation"); break; } touchArea.navigateLeft = navigateLeft; touchArea.navigateRight = navigateRight; touchArea.transparentFirst(); // Add mouse event handlers domHandlers.add(touchView.addDomHandler(touchArea, MouseDownEvent.getType())); domHandlers.add(touchView.addDomHandler(touchArea, MouseMoveEvent.getType())); domHandlers.add(touchView.addDomHandler(touchArea, MouseUpEvent.getType())); domHandlers.add(touchView.addDomHandler(touchArea, MouseOutEvent.getType())); domHandlers.add(touchView.addDomHandler(touchArea, ClickEvent.getType())); if (TouchEvent.isSupported()) { // Add touch event handlers domHandlers.add(touchView.addDomHandler(touchArea, TouchStartEvent.getType())); domHandlers.add(touchView.addDomHandler(touchArea, TouchMoveEvent.getType())); domHandlers.add(touchView.addDomHandler(touchArea, TouchEndEvent.getType())); } touchView.add(touchArea); VConsole.log(" === added area"); touchArea.layoutWidgets(); } public ScrollDirection getScrollDirection() { return flowView; } }
39.018382
95
0.649958
1b65c0a0fee17028824e9ae9f29eee1854635b70
23,083
package com.serenegiant.screenrecordingsample; /* * ScreenRecordingSample * Sample project to cature and save audio from internal and video from screen as MPEG4 file. * * Copyright (c) 2015 saki t_saki@serenegiant.com * * File name: MainActivity.java * * 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. * * All files in the folder are under this Apache License, Version 2.0. */ import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.concurrent.TimeUnit; import android.Manifest; import android.annotation.SuppressLint; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.graphics.SurfaceTexture; import android.hardware.camera2.CameraAccessException; import android.hardware.camera2.CameraCaptureSession; import android.hardware.camera2.CameraCharacteristics; import android.hardware.camera2.CameraDevice; import android.hardware.camera2.CameraManager; import android.hardware.camera2.CaptureRequest; import android.hardware.camera2.params.StreamConfigurationMap; import android.media.projection.MediaProjectionManager; import android.os.Build; import android.os.Bundle; import android.os.CountDownTimer; import android.os.Handler; import android.os.HandlerThread; import android.support.annotation.NonNull; import android.support.v4.content.ContextCompat; import android.util.Log; import android.util.Size; import android.util.SparseArray; import android.util.SparseIntArray; import android.view.Surface; import android.view.TextureView; import android.view.View; import android.widget.Button; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.TextView; import android.widget.Toast; import android.widget.ToggleButton; import com.serenegiant.dialog.MessageDialogFragment; import com.serenegiant.service.ScreenRecorderService; import com.serenegiant.utils.BuildCheck; import com.serenegiant.utils.HandlerThreadHandler; import com.serenegiant.utils.PermissionCheck; import org.w3c.dom.Text; public final class MainActivity extends Activity implements MessageDialogFragment.MessageDialogListener { private static final int REQUEST_CAMERA_PERMISSION_RESULT = 0; private static final boolean DEBUG = false; private static final String TAG = "MainActivity"; private static final int REQUEST_CODE_SCREEN_CAPTURE = 1; private ToggleButton mRecordButton; private ToggleButton mPauseButton; private Button mStopButton; private MyBroadcastReceiver mReceiver; private TextView question; private TextView warn; private TextView left_time; private TextureView mTextureView; private CountDownTimer preTimer; private CountDownTimer recTimer; private ArrayList<String> questions = new ArrayList<>(); private int question_number = 0; private TextureView.SurfaceTextureListener mSurfaceTextureListener = new TextureView.SurfaceTextureListener() { @Override public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) { setupCamera(width, height); connectCamera(); } @Override public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int width, int height) { } @Override public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) { return false; } @Override public void onSurfaceTextureUpdated(SurfaceTexture surface) { } }; private CameraDevice mCameraDevice; private CameraDevice.StateCallback mCameraDeviceStateCallback = new CameraDevice.StateCallback(){ @Override public void onOpened(CameraDevice camera){ mCameraDevice = camera; startPreview(); // Toast.makeText(getApplicationContext(), // "Камера подключена!", Toast.LENGTH_SHORT).show(); } @Override public void onDisconnected(CameraDevice camera){ camera.close(); mCameraDevice = null; } @Override public void onError(CameraDevice camera, int error){ } }; private HandlerThread mBackgroundHandlerThread; private Handler mBackgroundHandler; private String mCameraId; private Size mPreviewSize; private CaptureRequest.Builder mCaptureRequestBuilder; private static SparseIntArray ORIENTATIONS = new SparseIntArray(); static { ORIENTATIONS.append(Surface.ROTATION_0, 0); ORIENTATIONS.append(Surface.ROTATION_90, 90); ORIENTATIONS.append(Surface.ROTATION_180, 180); ORIENTATIONS.append(Surface.ROTATION_270, 270); } @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (DEBUG) Log.v(TAG, "onCreate:"); setContentView(R.layout.activity_main); mRecordButton = (ToggleButton)findViewById(R.id.record_button); mPauseButton = (ToggleButton)findViewById(R.id.pause_button); mStopButton = (Button)findViewById(R.id.stop_button); question = (TextView) findViewById(R.id.question); left_time = (TextView) findViewById(R.id.left_time); warn = (TextView) findViewById(R.id.warn); updateRecording(false, false); if (mReceiver == null) { mReceiver = new MyBroadcastReceiver(this); } mTextureView = (TextureView) findViewById(R.id.textureView); questions.add("Вопрос 1: Как Вы можете охарактеризовать себя в двух словах?"); questions.add("Вопрос 2: Есть ли у Вас свой девиз, миссия?"); questions.add("Вопрос 3: В чем заключается главная экспертиза человека Вашего уровня?"); questions.add("Вопрос 4: Почему вы выбрали naimi.kz?"); questions.add("Вопрос 5: Где живешь?"); startQuestion(question_number); mStopButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { recTimer.cancel(); recTimer.onFinish(); } }); } private void startQuestion(int i) { question.setText(questions.get(i)); warn.setText(R.string.warn); preTimer = new CountDownTimer(10000, 1000) { public void onTick(long millisUntilFinished) { left_time.setText("" + String.format("%d сек", TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished))); } public void onFinish() { if (question_number ==0){ mRecordButton.toggle(); } else { mPauseButton.toggle(); } warn.setText(R.string.left); mStopButton.setVisibility(View.VISIBLE); recTimer = new CountDownTimer(120000, 1000) { public void onTick(long millisUntilFinished) { left_time.setText("" + String.format("%d:%d", TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished), TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)))); } public void onFinish() { if (question_number < questions.size()-1) { mPauseButton.toggle(); startQuestion(++question_number); } else { mRecordButton.toggle(); } mStopButton.setVisibility(View.INVISIBLE); } }.start(); } }.start(); } @Override public void onWindowFocusChanged(boolean hasFocas){ super.onWindowFocusChanged(hasFocas); View decorView = getWindow().getDecorView(); if (hasFocas){ decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION); } } private static class CompareSizeByArea implements Comparator<Size> { @Override public int compare(Size lhs, Size rhs) { return Long.signum((long) lhs.getWidth() * lhs.getHeight() / (long) rhs.getWidth() * rhs.getHeight()); } } private void setupCamera(int width, int height){ CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE); try { for (String cameraId : cameraManager.getCameraIdList()){ CameraCharacteristics cameraCharacteristics = cameraManager.getCameraCharacteristics(cameraId); if (cameraCharacteristics.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_BACK){ continue; } StreamConfigurationMap map = cameraCharacteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); int deviceOrientation = getWindowManager().getDefaultDisplay().getRotation(); int totalRotation = sensorToDeviceRotation(cameraCharacteristics, deviceOrientation); boolean swapRotation = totalRotation == 90 || totalRotation == 270; int rotatedWidth = width; int rotatedHeight = height; if (swapRotation) { rotatedWidth = height; rotatedHeight = width; } mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), rotatedWidth, rotatedHeight); mCameraId = cameraId; return; } } catch (CameraAccessException e){ e.printStackTrace(); } } private void connectCamera(){ CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE); try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) { cameraManager.openCamera(mCameraId, mCameraDeviceStateCallback, mBackgroundHandler); } else { if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)){ Toast.makeText(this, "Требуется разрешение на камеру", Toast.LENGTH_SHORT).show(); } requestPermissions(new String[] {Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION_RESULT); } } else { cameraManager.openCamera(mCameraId, mCameraDeviceStateCallback, mBackgroundHandler); } } catch (CameraAccessException e){ e.printStackTrace(); } } private void startPreview(){ SurfaceTexture surfaceTexture = mTextureView.getSurfaceTexture(); surfaceTexture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight()); Surface previewSurface = new Surface(surfaceTexture); try{ mCaptureRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW); mCaptureRequestBuilder.addTarget(previewSurface); mCameraDevice.createCaptureSession(Arrays.asList(previewSurface), new CameraCaptureSession.StateCallback() { @Override public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) { try { cameraCaptureSession.setRepeatingRequest(mCaptureRequestBuilder.build(), null, mBackgroundHandler); } catch (CameraAccessException e) { e.printStackTrace(); } } @Override public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) { Toast.makeText(getApplicationContext(), "Ошибка настройки камеры", Toast.LENGTH_SHORT).show(); } }, null); } catch (CameraAccessException e) { e.printStackTrace(); } } private void closeCamera(){ if (mCameraDevice !=null ){ mCameraDevice.close(); mCameraDevice = null; } } private void startBackgroundThread(){ mBackgroundHandlerThread = new HandlerThread("Camera2VideoImage"); mBackgroundHandlerThread.start(); mBackgroundHandler = new Handler (mBackgroundHandlerThread.getLooper()); } private void stopBackgroundThread(){ mBackgroundHandlerThread.quitSafely(); try { mBackgroundHandlerThread.join(); mBackgroundHandlerThread=null; mBackgroundHandler = null; } catch (InterruptedException e) { e.printStackTrace(); } } private static int sensorToDeviceRotation(CameraCharacteristics cameraCharacteristics, int deviceOrientation){ int sensorOrientation = cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION); deviceOrientation = ORIENTATIONS.get(deviceOrientation); return (sensorOrientation + deviceOrientation + 360) % 360; } private static Size chooseOptimalSize(Size[] choices, int width, int height){ List<Size> bigEnough = new ArrayList<Size>(); for (Size option : choices) { if (option.getHeight() == option.getWidth() * height / width && option.getWidth() >= width && option.getHeight() >= height) { bigEnough.add(option); } } if (bigEnough.size()> 0) { return Collections.min(bigEnough, new CompareSizeByArea()); } else { return choices[0]; } } public void setRequestCameraPermissionResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == REQUEST_CAMERA_PERMISSION_RESULT) { if (grantResults[0] != PackageManager.PERMISSION_GRANTED){ Toast.makeText(getApplicationContext(), "Приложение не будет работать без сервисов камеры", Toast.LENGTH_SHORT).show(); } } } @Override protected void onResume() { super.onResume(); if (DEBUG) Log.v(TAG, "onResume:"); startBackgroundThread(); if (mTextureView.isAvailable()){ setupCamera(mTextureView.getWidth(), mTextureView.getHeight()); connectCamera(); } else { mTextureView.setSurfaceTextureListener(mSurfaceTextureListener); } final IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(ScreenRecorderService.ACTION_QUERY_STATUS_RESULT); registerReceiver(mReceiver, intentFilter); queryRecordingStatus(); } @Override protected void onPause() { if (DEBUG) Log.v(TAG, "onPause:"); unregisterReceiver(mReceiver); closeCamera(); stopBackgroundThread(); super.onPause(); } @Override protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) { if (DEBUG) Log.v(TAG, "onActivityResult:resultCode=" + resultCode + ",data=" + data); super.onActivityResult(requestCode, resultCode, data); if (REQUEST_CODE_SCREEN_CAPTURE == requestCode) { if (resultCode != Activity.RESULT_OK) { // when no permission Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show(); return; } startScreenRecorder(resultCode, data); } } private final OnCheckedChangeListener mOnCheckedChangeListener = new OnCheckedChangeListener() { @Override public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) { switch (buttonView.getId()) { case R.id.record_button: if (checkPermissionWriteExternalStorage() && checkPermissionAudio()) { if (isChecked) { final MediaProjectionManager manager = (MediaProjectionManager)getSystemService(Context.MEDIA_PROJECTION_SERVICE); final Intent permissionIntent = manager.createScreenCaptureIntent(); startActivityForResult(permissionIntent, REQUEST_CODE_SCREEN_CAPTURE); } else { final Intent intent = new Intent(MainActivity.this, ScreenRecorderService.class); intent.setAction(ScreenRecorderService.ACTION_STOP); startService(intent); } } else { mRecordButton.setOnCheckedChangeListener(null); try { mRecordButton.setChecked(false); } finally { mRecordButton.setOnCheckedChangeListener(mOnCheckedChangeListener); } } break; case R.id.pause_button: if (isChecked) { final Intent intent = new Intent(MainActivity.this, ScreenRecorderService.class); intent.setAction(ScreenRecorderService.ACTION_PAUSE); startService(intent); } else { final Intent intent = new Intent(MainActivity.this, ScreenRecorderService.class); intent.setAction(ScreenRecorderService.ACTION_RESUME); startService(intent); } break; } } }; private void queryRecordingStatus() { if (DEBUG) Log.v(TAG, "queryRecording:"); final Intent intent = new Intent(this, ScreenRecorderService.class); intent.setAction(ScreenRecorderService.ACTION_QUERY_STATUS); startService(intent); } private void startScreenRecorder(final int resultCode, final Intent data) { final Intent intent = new Intent(this, ScreenRecorderService.class); intent.setAction(ScreenRecorderService.ACTION_START); intent.putExtra(ScreenRecorderService.EXTRA_RESULT_CODE, resultCode); intent.putExtras(data); startService(intent); } private void updateRecording(final boolean isRecording, final boolean isPausing) { if (DEBUG) Log.v(TAG, "updateRecording:isRecording=" + isRecording + ",isPausing=" + isPausing); mRecordButton.setOnCheckedChangeListener(null); mPauseButton.setOnCheckedChangeListener(null); try { mRecordButton.setChecked(isRecording); mPauseButton.setEnabled(isRecording); mPauseButton.setChecked(isPausing); } finally { mRecordButton.setOnCheckedChangeListener(mOnCheckedChangeListener); mPauseButton.setOnCheckedChangeListener(mOnCheckedChangeListener); } } private static final class MyBroadcastReceiver extends BroadcastReceiver { private final WeakReference<MainActivity> mWeakParent; public MyBroadcastReceiver(final MainActivity parent) { mWeakParent = new WeakReference<MainActivity>(parent); } @Override public void onReceive(final Context context, final Intent intent) { if (DEBUG) Log.v(TAG, "onReceive:" + intent); final String action = intent.getAction(); if (ScreenRecorderService.ACTION_QUERY_STATUS_RESULT.equals(action)) { final boolean isRecording = intent.getBooleanExtra(ScreenRecorderService.EXTRA_QUERY_RESULT_RECORDING, false); final boolean isPausing = intent.getBooleanExtra(ScreenRecorderService.EXTRA_QUERY_RESULT_PAUSING, false); final MainActivity parent = mWeakParent.get(); if (parent != null) { parent.updateRecording(isRecording, isPausing); } } } } //================================================================================ // methods related to new permission model on Android 6 and later //================================================================================ /** * Callback listener from MessageDialogFragmentV4 * @param dialog * @param requestCode * @param permissions * @param result */ @SuppressLint("NewApi") @Override public void onMessageDialogResult(final MessageDialogFragment dialog, final int requestCode, final String[] permissions, final boolean result) { if (result) { // request permission(s) when user touched/clicked OK if (BuildCheck.isMarshmallow()) { requestPermissions(permissions, requestCode); return; } } // check permission and call #checkPermissionResult when user canceled or not Android6(and later) for (final String permission: permissions) { checkPermissionResult(requestCode, permission, PermissionCheck.hasPermission(this, permission)); } } /** * callback method when app(Fragment) receive the result of permission result from ANdroid system * @param requestCode * @param permissions * @param grantResults */ @Override public void onRequestPermissionsResult(final int requestCode, @NonNull final String[] permissions, @NonNull final int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); // 何もしてないけど一応呼んどく final int n = Math.min(permissions.length, grantResults.length); for (int i = 0; i < n; i++) { checkPermissionResult(requestCode, permissions[i], grantResults[i] == PackageManager.PERMISSION_GRANTED); } } /** * check the result of permission request * if app still has no permission, just show Toast * @param requestCode * @param permission * @param result */ protected void checkPermissionResult(final int requestCode, final String permission, final boolean result) { // show Toast when there is no permission if (Manifest.permission.RECORD_AUDIO.equals(permission)) { onUpdateAudioPermission(result); if (!result) { Toast.makeText(this, R.string.permission_audio, Toast.LENGTH_SHORT).show(); } } if (Manifest.permission.WRITE_EXTERNAL_STORAGE.equals(permission)) { onUpdateExternalStoragePermission(result); if (!result) { Toast.makeText(this, R.string.permission_ext_storage, Toast.LENGTH_SHORT).show(); } } if (Manifest.permission.INTERNET.equals(permission)) { onUpdateNetworkPermission(result); if (!result) { Toast.makeText(this, R.string.permission_network, Toast.LENGTH_SHORT).show(); } } } /** * called when user give permission for audio recording or canceled * @param hasPermission */ protected void onUpdateAudioPermission(final boolean hasPermission) { } /** * called when user give permission for accessing external storage or canceled * @param hasPermission */ protected void onUpdateExternalStoragePermission(final boolean hasPermission) { } /** * called when user give permission for accessing network or canceled * this will not be called * @param hasPermission */ protected void onUpdateNetworkPermission(final boolean hasPermission) { } protected static final int REQUEST_PERMISSION_WRITE_EXTERNAL_STORAGE = 0x01; protected static final int REQUEST_PERMISSION_AUDIO_RECORDING = 0x02; protected static final int REQUEST_PERMISSION_NETWORK = 0x03; /** * check whether this app has write external storage * if this app has no permission, show dialog * @return true this app has permission */ protected boolean checkPermissionWriteExternalStorage() { if (!PermissionCheck.hasWriteExternalStorage(this)) { MessageDialogFragment.showDialog(this, REQUEST_PERMISSION_WRITE_EXTERNAL_STORAGE, R.string.permission_title, R.string.permission_ext_storage_request, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}); return false; } return true; } /** * check whether this app has permission of audio recording * if this app has no permission, show dialog * @return true this app has permission */ protected boolean checkPermissionAudio() { if (!PermissionCheck.hasAudio(this)) { MessageDialogFragment.showDialog(this, REQUEST_PERMISSION_AUDIO_RECORDING, R.string.permission_title, R.string.permission_audio_recording_request, new String[]{Manifest.permission.RECORD_AUDIO}); return false; } return true; } /** * check whether permission of network access * if this app has no permission, show dialog * @return true this app has permission */ protected boolean checkPermissionNetwork() { if (!PermissionCheck.hasNetwork(this)) { MessageDialogFragment.showDialog(this, REQUEST_PERMISSION_NETWORK, R.string.permission_title, R.string.permission_network_request, new String[]{Manifest.permission.INTERNET}); return false; } return true; } }
34.400894
145
0.747823
ae34d570167e57be01604f16b5e8188b496e26f1
467
package com.skyl.commons.model.pojo; import com.skyl.commons.model.base.BaseModel; import io.swagger.annotations.ApiModelProperty; import lombok.Getter; import lombok.Setter; @Getter @Setter public class DinerPoints extends BaseModel { @ApiModelProperty("关联DinerId") private Integer fkDinerId; @ApiModelProperty("积分") private Integer points; @ApiModelProperty(name = "类型",example = "0=签到,1=关注好友,2=添加Feed,3=添加商户评论") private Integer types; }
24.578947
76
0.753747