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
789809d21d6c4840c747edcc99590681671d7d3c
2,353
package info.jdavid.ok.server.samples; import javax.annotation.Nullable; import info.jdavid.ok.server.RequestHandlerChain; import info.jdavid.ok.server.handler.RegexHandler; import info.jdavid.ok.server.handler.Request; import okhttp3.MediaType; import okhttp3.ResponseBody; import info.jdavid.ok.server.HttpServer; import info.jdavid.ok.server.Response; import info.jdavid.ok.server.StatusLines; import okio.Buffer; import okio.BufferedSource; @SuppressWarnings("WeakerAccess") public class EchoHttpServer { private final HttpServer mServer; public EchoHttpServer() { this(8080); } public EchoHttpServer(final int port) { mServer = new HttpServer(). requestHandler(new RequestHandlerChain().add(new EchoHandler())). port(port); } public void start() { mServer.start(); } @SuppressWarnings("unused") public void stop() { mServer.shutdown(); } public static void main(final String[] args) { new EchoHttpServer().start(); } private static Response.Builder echo(@Nullable final Buffer requestBody, @Nullable final MediaType mime) { if (requestBody == null) return new Response.Builder().statusLine(StatusLines.OK).noBody(); if (mime == null) return new Response.Builder().statusLine(StatusLines.BAD_REQUEST).noBody(); return new Response.Builder().statusLine(StatusLines.OK).body(new EchoBody(requestBody, mime)); } private static class EchoHandler extends RegexHandler { EchoHandler() { super("POST", "/echo"); } @Override public Response.Builder handle(final Request request, final String[] params) { final String contentType = request.headers.get("Content-Type"); final MediaType mime = contentType == null ? null : MediaType.parse(contentType); return echo(request.body, mime); } } private static class EchoBody extends ResponseBody { private final Buffer mBuffer; private final long mLength; private final MediaType mMediaType; public EchoBody(final Buffer buffer, final MediaType mediaType) { super(); mBuffer = buffer; mLength = buffer.size(); mMediaType = mediaType; } @Override public MediaType contentType() { return mMediaType; } @Override public long contentLength() { return mLength; } @Override public BufferedSource source() { return mBuffer; } } }
29.4125
108
0.718657
f915ab5ceb1aa90ed36d2d4482a61aa02c5818ba
676
package com.afei.auto; import com.afei.config.HelloProperties; import com.afei.service.HelloService; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * 自动配置 * @author shihengfei */ @Configuration @EnableConfigurationProperties(HelloProperties.class) public class HelloServiceAutoConfiguration { @ConditionalOnMissingBean(HelloService.class) @Bean public HelloService helloService(){ return new HelloService(); } }
28.166667
81
0.81213
9a19d480537cc2ca05b58604cadf0a67ae6b6f73
1,074
package cn.itcast.zt; import cn.itcast.zt.domain.User; import cn.itcast.zt.domain.UserRepository; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(classes = SpringbootEhcacheApplication.class) public class SpringbootEhcacheApplicationTests { @Autowired private UserRepository userRepository; //@Autowired //private CacheManager cacheManager; @Before public void setUp() { userRepository.save(new User("AAA", 10)) ; } @Test public void testEhcache() throws Exception { User u1 = userRepository.findByName("AAA"); System.out.println("第一次查询:" + u1.getAge()); User u2 = userRepository.findByName("AAA"); System.out.println("第二次查询:" + u2.getAge()); u1.setAge(20); userRepository.save(u1); User u3 = userRepository.findByName("AAA"); System.out.println("第三次查询:" + u3.getAge()); } }
26.85
62
0.761639
d494c9d8c9792b66c4a8c3574b6e72a4ec893495
194
package ca.corefacility.bioinformatics.irida.ria.web.ajax.dto; /** * Abstract class for the response for creating a new sample if a project. */ public abstract class CreateSampleResponse { }
24.25
74
0.773196
537e3651d0c940c8d58348a5fcdbb8a4c302ffeb
1,132
import com.fasterxml.jackson.annotation.*; public class AnyOfSchemaForTheLegalBasesOfTheDataDisclosed { private String description; private String reference; /** * An explanation about the legal basis used. */ @JsonProperty("description") public String getDescription() { return description; } @JsonProperty("description") public void setDescription(String value) { this.description = value; } /** * This field refers to the reference in legal regulations (laws, orders, declaration etc.). * The format is set to uppercase letters for the legal text followed by hyphened numbers * and lowercase letters for the exact location. */ @JsonProperty("reference") public String getReference() { return reference; } @JsonProperty("reference") public void setReference(String value) { this.reference = value; } @Override public String toString() { return "AnyOfSchemaForTheLegalBasesOfTheDataDisclosed{" + "description='" + description + '\'' + ", reference='" + reference + '\'' + '}'; } }
34.30303
96
0.660777
7b7316de4e9f4014a7cd4ae0e6ccb71aee233ca8
874
package voss.discovery.iolib.netconf; @SuppressWarnings("serial") public class NetConfException extends Exception { private final String operation; public NetConfException() { super(); this.operation = null; } public NetConfException(String msg) { super(msg); this.operation = null; } public NetConfException(Throwable cause) { super(cause); this.operation = null; } public NetConfException(String msg, String op) { super(msg); this.operation = op; } public NetConfException(Throwable cause, String op) { super(cause); this.operation = op; } public NetConfException(String msg, Throwable cause, String op) { super(msg, cause); this.operation = op; } public String getOperation() { return operation; } }
21.85
69
0.615561
a4ef66a3c999db41e70abefe28ede7074c7e01f0
1,530
package com.google.sitebricks.rendering.control; import com.google.inject.Injector; import com.google.sitebricks.MvelEvaluator; import com.google.sitebricks.Renderable; import com.google.sitebricks.compiler.EvaluatorCompiler; import com.google.sitebricks.compiler.ExpressionCompileException; import com.google.sitebricks.routing.PageBook; import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.createNiceMock; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** * @author Dhanji R. Prasanna ([email protected]) */ public class WidgetRegistryTest { private static final String WIDGETS_AND_KEYS = "widgetsAndKeys"; @DataProvider(name = WIDGETS_AND_KEYS) public Object[][] get() { return new Object[][] { { "twidg", TextFieldWidget.class }, { "teasdasxt", RepeatWidget.class }, { "sastext", ShowIfWidget.class }, }; } @Test(dataProvider = WIDGETS_AND_KEYS) public final void storeRetrieveWidgets(final String key, final Class<Renderable> expected) throws ExpressionCompileException { final WidgetRegistry registry = new DefaultWidgetRegistry(new MvelEvaluator(), createNiceMock(PageBook.class), createNiceMock(Injector.class)); registry.add(key, expected); Renderable widget = registry.newWidget(key, "some=expression", new ProceedingWidgetChain(), createMock(EvaluatorCompiler.class)); assert expected.isInstance(widget) : "Wrong widget returned"; } }
39.230769
151
0.745752
d0f2f5ccab1d1114c79b68fe7c7a712dab061a88
664
package com.xian.lessonnine.validator; import javax.validation.Constraint; import javax.validation.Payload; import java.lang.annotation.*; /** * @Description: * @Author: Xian * @CreateDate: 2019/9/11 14:20 * @Version: 0.0.1-SHAPSHOT */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.PARAMETER, ElementType.FIELD}) @Constraint(validatedBy = FlagValidatorObject.class) public @interface FlagValidator { // flag的有效值多个使用","隔开 String values(); // 提示内容 String message() default "flag不存在"; // groups 和 payload 这两个parameter 必须包含 Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
23.714286
52
0.707831
4f47cc3b287cb073a1a34f1980e71fd08c64ec80
803
package com.wall.myproject4test.java.zzw.inf4demo.xstream.model.irmsmodel; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamImplicit; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.List; /** * @description:记录内容-irms * @author: zhang.zw * @date: 2020/10/21 15:33 **/ @ApiModel @XStreamAlias("recordInfo") public class RecordInfoBeanFJIrms { @ApiModelProperty(value = "字段内容") @XStreamImplicit(itemFieldName = "fieldInfo") private List<FieldInfoBeanFjIrms> fieldInfo; public List<FieldInfoBeanFjIrms> getFieldInfo() { return fieldInfo; } public void setFieldInfo(List<FieldInfoBeanFjIrms> fieldInfo) { this.fieldInfo = fieldInfo; } }
25.903226
74
0.753425
fd887bead70248abf9ccca9bdbccc347dd72304b
873
package net.chuzarski.moviebucket.di; import android.arch.lifecycle.ViewModel; import android.arch.lifecycle.ViewModelProvider; import net.chuzarski.moviebucket.common.AppViewModelFactory; import net.chuzarski.moviebucket.ui.listing.ListingPreferencesViewModel; import net.chuzarski.moviebucket.ui.listing.ListingViewModel; import dagger.Binds; import dagger.Module; import dagger.multibindings.IntoMap; @Module public abstract class ViewModelModule { @Binds @IntoMap @ViewModelKey(ListingViewModel.class) abstract ViewModel bindListingViewModel(ListingViewModel viewModel); @Binds @IntoMap @ViewModelKey(ListingPreferencesViewModel.class) abstract ViewModel bindListingPreferencesViewModel(ListingPreferencesViewModel viewModel); @Binds abstract ViewModelProvider.Factory bindViewModelFactory(AppViewModelFactory factory); }
29.1
94
0.824742
623a7e4b386ff3b0d77754cdb3944841e0b285d3
458
package com.sula.dao.custom.impl; import com.sula.dao.CrudDAOImpl; import com.sula.dao.custom.OrderDAO; import com.sula.entity.Order; import org.springframework.stereotype.Repository; @Repository public class OrderDAOImpl extends CrudDAOImpl<Order,String> implements OrderDAO { @Override public String getLastOrderId() { return (String) session.createNativeQuery("select id from `order` order by id DESC LIMIT 1").uniqueResult(); } }
26.941176
116
0.764192
99384b75fb338f61bb3c98cf1be3bd2680a0c996
1,004
package com.ctrip.hermes.core.transport.command.v5; import io.netty.buffer.ByteBuf; import com.ctrip.hermes.core.bo.Offset; import com.ctrip.hermes.core.transport.command.AbstractCommand; import com.ctrip.hermes.core.transport.command.CommandType; import com.ctrip.hermes.core.utils.HermesPrimitiveCodec; public class QueryOffsetResultCommandV5 extends AbstractCommand { private static final long serialVersionUID = -3988734159665108642L; private Offset m_offset; public Offset getOffset() { return m_offset; } public QueryOffsetResultCommandV5() { this(null); } public QueryOffsetResultCommandV5(Offset offset) { super(CommandType.RESULT_QUERY_OFFSET_V5, 5); m_offset = offset; } @Override protected void parse0(ByteBuf buf) { HermesPrimitiveCodec codec = new HermesPrimitiveCodec(buf); m_offset = codec.readOffset(); } @Override protected void toBytes0(ByteBuf buf) { HermesPrimitiveCodec codec = new HermesPrimitiveCodec(buf); codec.writeOffset(m_offset); } }
23.904762
68
0.787849
df91063a393c53ef75c2acfbd814b2f529e9d138
6,322
package cn.com.szw.lib.myframework.app; import android.content.Context; import android.support.multidex.MultiDexApplication; import com.blankj.utilcode.util.SPUtils; import com.blankj.utilcode.util.Utils; import com.facebook.drawee.backends.pipeline.Fresco; import com.lzy.okgo.OkGo; import com.lzy.okgo.cache.CacheEntity; import com.lzy.okgo.cache.CacheMode; import com.lzy.okgo.cookie.store.PersistentCookieStore; import com.lzy.okgo.model.HttpHeaders; import com.lzy.okgo.model.HttpParams; import java.io.File; import java.io.IOException; import java.util.logging.Level; import cat.ereza.customactivityoncrash.CustomActivityOnCrash; import cn.com.szw.lib.myframework.entities.User; import io.realm.Realm; import okhttp3.Cache; import okhttp3.Interceptor; import okhttp3.Request; import okhttp3.Response; /** * Created by Swain * on 2016/6/28. */ public abstract class MyApplication extends MultiDexApplication implements AbsApplication{ /** * 加盐 */ public static String salt=""; /** * 本地存储 */ private SPUtils spUtils; @Override public void onCreate() { super.onCreate(); salt=getSalt(); Fresco.initialize(this); Utils.init(this); Realm.init(this); spUtils= SPUtils.getInstance("szw"); initOkHttp(); //Install 程序崩溃日志初始化 CustomActivityOnCrash.install(this); } public static SPUtils getSPUtils(Context context) { MyApplication application = (MyApplication) context.getApplicationContext(); return application.spUtils; } private void initOkHttp(){ try { //---------这里给出的是示例代码,告诉你可以这么传,实际使用的时候,根据需要传,不需要就不传-------------// HttpHeaders headers = new HttpHeaders(); headers.put("commonHeaderKey1", "commonHeaderValue1"); //header不支持中文 headers.put("commonHeaderKey2", "commonHeaderValue2"); HttpParams params = new HttpParams(); params.put("commonParamsKey1", "commonParamsValue1"); //param支持中文,直接传,不要自己编码 params.put("commonParamsKey2", "这里支持中文参数"); //-----------------------------------------------------------------------------------// //必须调用初始化 OkGo.init(this); //以下设置的所有参数是全局参数,同样的参数可以在请求的时候再设置一遍,那么对于该请求来讲,请求中的参数会覆盖全局参数 //好处是全局参数统一,特定请求可以特别定制参数 //以下都不是必须的,根据需要自行选择,一般来说只需要 debug,缓存相关,cookie相关的 就可以了 OkGo.getInstance() // 打开该调试开关,打印级别INFO,并不是异常,是为了显眼,不需要就不要加入该行 // 最后的true表示是否打印okgo的内部异常,一般打开方便调试错误 .debug("OkGo", Level.INFO, true) //如果使用默认的 60秒,以下三行也不需要传 .setConnectTimeout(OkGo.DEFAULT_MILLISECONDS) //全局的连接超时时间 .setReadTimeOut(OkGo.DEFAULT_MILLISECONDS) //全局的读取超时时间 .setWriteTimeOut(OkGo.DEFAULT_MILLISECONDS) //全局的写入超时时间 //可以全局统一设置缓存模式,默认是不使用缓存,可以不传,具体其他模式看 github 介绍 https://github.com/jeasonlzy/ .setCacheMode(CacheMode.NO_CACHE) //可以全局统一设置缓存时间,默认永不过期,具体使用方法看 github 介绍 .setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE) //可以全局统一设置超时重连次数,默认为三次,那么最差的情况会请求4次(一次原始请求,三次重连请求),不需要可以设置为0 .setRetryCount(3) //如果不想让框架管理cookie(或者叫session的保持),以下不需要 // .setCookieStore(new MemoryCookieStore()) //cookie使用内存缓存(app退出后,cookie消失) .setCookieStore(new PersistentCookieStore()) //cookie持久化存储,如果cookie不过期,则一直有效 //可以设置https的证书,以下几种方案根据需要自己设置 .setCertificates() ; //方法一:信任所有证书,不安全有风险 // .setCertificates(new SafeTrustManager()) //方法二:自定义信任规则,校验服务端证书 // .setCertificates(getAssets().open("srca.cer")) //方法三:使用预埋证书,校验服务端证书(自签名证书) // //方法四:使用bks证书和密码管理客户端证书(双向认证),使用预埋证书,校验服务端证书(自签名证书) // .setCertificates(getAssets().open("xxx.bks"), "123456", getAssets().open("yyy.cer"))// //配置https的域名匹配规则,详细看demo的初始化介绍,不需要就不要加入,使用不当会导致https握手失败 // .setHostnameVerifier(new SafeHostnameVerifier()) //可以添加全局拦截器,不需要就不要加入,错误写法直接导致任何回调不执行 // .addInterceptor(new Interceptor() { // @Override // public Response intercept(Chain chain) throws IOException { // return chain.proceed(chain.request()); // } // }) //这两行同上,不需要就不要加入 // .addCommonHeaders(headers) //设置全局公共头 // .addCommonParams(params); //设置全局公共参数 } catch (Exception e) { e.printStackTrace(); } } public Cache provideCache() { File httpCacheDirectory = new File(getCacheDir().getAbsolutePath(), "szw"); return new Cache(httpCacheDirectory, 10240*1024); } public class CacheInterceptor implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); Response response = chain.proceed(request); return response.newBuilder() .removeHeader("Pragma") .removeHeader("Cache-Control") //cache for 30 days .header("Cache-Control", "max-age=" + 300) .build(); } } //=================================================================================================================== private static User user; //判断 用户是否登录 public static boolean checkUserLogin() { return user != null && !"".equals(user.getUserId()); } //获取用户的登录userid public static String getLoginUserId() { if (user == null) { return ""; } else { return user.getUserId(); } } public static User getUser() { if (user == null) { return new User(); } else { return user; } } public static void setUser(User user) { MyApplication.user = user; } //=================================================================================================================== }
34.358696
121
0.561531
d5ec1f732ed4ee51a4fe3210f9669a427ef41a59
4,509
/** * netcell-gui - A Swing GUI for netcell ESB * Copyright (C) 2009 Adrian Cristian Ionescu - https://github.com/acionescu * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.segoia.netcell.toolkit.actions; import java.awt.Component; import java.awt.event.ActionEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.HashMap; import java.util.Map; import javax.swing.JDialog; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import net.segoia.java.forms.Form; import net.segoia.java.forms.impl.MapDataSource; import net.segoia.java.forms.model.ObjectFormModel; import net.segoia.netcell.constants.InputParameterType; import net.segoia.netcell.gui.NetcellGuiController; import net.segoia.netcell.vo.definitions.DataAccessComponentDefinition; import net.segoia.netcell.vo.definitions.DataSourceDefinition; import net.segoia.netcell.vo.definitions.EntityDefinition; import net.segoia.scriptdao.constants.DataSourceConfigParameters; import net.segoia.util.data.ConfigurationData; import net.segoia.util.data.UserInputParameter; import org.apache.log4j.Logger; public class UpdateDataAccessComponent extends NetcellAbstractAction { private static final long serialVersionUID = 4094427407180933187L; private static final Logger logger = Logger.getLogger(UpdateDataAccessComponent.class.getName()); public UpdateDataAccessComponent(NetcellGuiController controller) { super(controller); } @Override protected void actionPerformedDelegate(ActionEvent e) throws Exception { DataAccessComponentDefinition dacd = (DataAccessComponentDefinition) e.getSource(); /* * set the allowed values for each input param on this component from the used datasource */ Map<String, DataSourceDefinition> datasources = controller.getDatasources(); DataSourceDefinition ds = datasources.get(dacd.getDataSourceName()); Map dsConfigParams = (Map) ds.getConfigData().getParameterValue( DataSourceConfigParameters.DATA_ACCESS_COMPONENT_PARAMS); ConfigurationData configData = dacd.getConfigData(); if (configData != null) { Map<String, UserInputParameter> userInputParams = configData.getUserInputParams(); if (userInputParams != null) { for (UserInputParameter uip : userInputParams.values()) { if (uip != null && dsConfigParams != null) { UserInputParameter templateParam = (UserInputParameter) dsConfigParams.get(uip.getName()); if(templateParam == null) { logger.warn("No template found for "+uip.getName()); continue; } uip.setAllowedValues(templateParam.getAllowedValues()); } } } } dacd.setDataSourceType(ds.getDatasourceType()); Form form = controller.getFormForObject(dacd, "update"); Map<String, Object> auxiliaryData = new HashMap<String, Object>(); auxiliaryData.put("types", InputParameterType.valuesAsStringArray()); // form.setAuxiliaryData(auxiliaryData); form.setFormDataSource(new MapDataSource(auxiliaryData)); form.initialize(); JOptionPane pane = new JOptionPane(new JScrollPane((Component)form.getUi().getHolder())); JDialog dialog = pane.createDialog("Configure data access component"); form.getModel().addPropertyChangeListener(new PropertyChangeMonitor(dialog, pane)); dialog.validate(); dialog.setResizable(true); dialog.setVisible(true); } class PropertyChangeMonitor implements PropertyChangeListener { private JDialog dialog; private JOptionPane pane; public PropertyChangeMonitor(JDialog d, JOptionPane p) { dialog = d; pane = p; } public void propertyChange(PropertyChangeEvent evt) { String propName = evt.getPropertyName(); if (propName.contains("inputParameters")) { int index = propName.lastIndexOf("."); if (index > 0 && "inputParameters".equals(propName.substring(0, index))) { dialog.pack(); } } ObjectFormModel fm = (ObjectFormModel) evt.getSource(); controller.onEntityChanged((EntityDefinition) fm.getDataObject()); } } }
38.87069
101
0.767132
1349571109c191fac85425c43efcda819bef444a
581
package tests.utils; import com.oracle.oci.eclipse.account.PreferencesWrapper; public class SetupConfig { private static String profileName = "IDE-ADMIN"; private static String projectDir = System.getProperty("user.dir"); private static String configFileName = projectDir + "/resources/internal/config"; public static void init(){ PreferencesWrapper.setConfigFileName(configFileName); PreferencesWrapper.setProfile(profileName); } public static void setProxy() { System.setProperty("java.net.useSystemProxies", "true"); } }
29.05
85
0.726334
4d66dc2362631f85e371308976ecd963fd4f24dd
8,681
package qasino.simulation.qasino; import org.apache.jena.graph.Triple; import peersim.config.Configuration; import peersim.core.CommonState; import peersim.core.Node; import qasino.simulation.qasino.data.IBFStrata; import qasino.simulation.rps.ARandomPeerSamplingProtocol; import qasino.simulation.rps.IMessage; import qasino.simulation.rps.IRandomPeerSampling; import qasino.simulation.spray.Spray; import qasino.simulation.spray.SprayMessage; import qasino.simulation.spray.SprayPartialView; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class Qasino extends Spray { private static final String PAR_TRAFFIC = "traffic"; // minimization of the traffic public static boolean traffic; public static boolean start = false; private static int snobs = 0; public final int id = Qasino.snobs++; public int shuffle = 0; // Profile of the peer public Profile profile = new Profile(); public double messages = 0; public long tripleResponses = 0; public int observed = 0; // state based crdt counter Map(pattern, Map(id, counter)) public StateBasedCrdtCounter crdt = new StateBasedCrdtCounter(this.id); public Long oldest = null; public List<Node> previousSampleNode = new ArrayList<>(); public List<Node> previousPartialviewNode = new ArrayList<>(); /** * Constructor of the Spray instance * * @param prefix the peersim configuration */ public Qasino(String prefix) { super(prefix); Qasino.traffic = Configuration.getBoolean(prefix + "." + PAR_TRAFFIC); this.profile = new Profile(); this.partialView = new SprayPartialView(); } public Qasino() { this.partialView = new SprayPartialView(); } public static Qasino fromNodeToSnobSpray(Node node) { return (Qasino) node.getProtocol(ARandomPeerSamplingProtocol.pid); } @Override public void periodicCall() { super.periodicCall(); if (start) { shuffle++; // APPLY SNOB NOW List<Node> currentPartialview = this.getPeers(Integer.MAX_VALUE); List<Node> peers = computeRealNewPeers(this.node.getID(), this.oldest, previousPartialviewNode, previousSampleNode, currentPartialview); if (profile.has_query && !profile.query.terminated) { // 1 - send tpqs to neighbours and receive responses for (Node node_rps : peers) { observed++; this.exchangeTriplePatterns(fromNodeToSnobSpray(node_rps)); crdt.increment(); if (fromNodeToSnobSpray(node_rps).profile.has_query) { fromNodeToSnobSpray(node_rps).exchangeTriplePatterns(this); // warning only usable when the same query is executed in the network // see message in crdt class for a real prototype // update crdts on both side, synchronization crdt.update(fromNodeToSnobSpray(node_rps).crdt); fromNodeToSnobSpray(node_rps).crdt.update(this.crdt); } } profile.execute(); } } } @Override public void join(Node joiner, Node contact) { if (this.node == null) { // lazy loading of the node identity this.node = joiner; } if (contact != null) { // the very first join does not have any contact Qasino contactSpray = (Qasino) contact.getProtocol(Spray.pid); this.partialView.clear(); this.partialView.addNeighbor(contact); contactSpray.onSubscription(this.node); } this.isUp = true; } @Override public void onSubscription(Node origin) { List<Node> aliveNeighbors = this.getAliveNeighbors(); for (Node neighbor : aliveNeighbors) { Qasino neighborSpray = (Qasino) neighbor.getProtocol(Spray.pid); neighborSpray.addNeighbor(origin); } } @Override public IRandomPeerSampling clone() { try { Qasino sprayClone = new Qasino(); sprayClone.partialView = (SprayPartialView) this.partialView.clone(); return sprayClone; } catch (CloneNotSupportedException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } /** * Exchange Triple patterns with Invertible bloom filters associated with. * In return the other peers send us missing triples for each triple pattern. * See onTpqs(...) function * * @param remote */ protected void exchangeTriplePatterns(Qasino remote) { this.profile.query.patterns.forEach(pattern -> { if (remote.profile.has_query && remote.profile.query.patterns.contains(pattern)) { if (traffic) { exchangeTriplesFromPatternUsingIbf(remote, pattern); } else { exchangeTriplesFromPatternWithoutIblt(remote, pattern); } } else { if (!this.profile.query.alreadySeen.containsKey(pattern) || !this.profile.query.alreadySeen.get(pattern).contains(remote.id)) { exchangeTriplesFromPatternWithoutIblt(remote, pattern); } } this.profile.query.addAlreadySeen(pattern, remote.id, this.id); if (remote.profile.has_query && remote.profile.query.patterns.contains(pattern)) { this.profile.query.mergeAlreadySeen(pattern, remote.profile.query.alreadySeen.get(pattern)); } }); } /** * Exchange triples without using iblt. * * @param remote * @param pattern */ private void exchangeTriplesFromPatternWithoutIblt(Qasino remote, Triple pattern) { this.messages++; List<Triple> list; if (remote.profile.has_query && remote.profile.query.patterns.contains(pattern)) { list = remote.profile.query.data.get(pattern).parallelStream().collect(Collectors.toList()); } else { list = remote.profile.local_datastore.getTriplesMatchingTriplePatternAsList(pattern); } tripleResponses += list.size(); this.profile.insertTriplesWithList(pattern, list); } /** * Exchange triple pattern using Invertible bloom filter, and share data if necessary * * @param remote * @param pattern */ public void exchangeTriplesFromPatternUsingIbf(Qasino remote, Triple pattern) { // send the ibf to remote peer with the pattern if (!remote.profile.has_query || (remote.profile.has_query && !remote.profile.query.patterns.contains(pattern))) { // no synchronization as the other do not have any triple pattern in common. So send all triples // if remote does not have a query, get triple pattern, get ibf on this triple pattern, set reconciliation. List<Triple> computed = remote.profile.local_datastore.getTriplesMatchingTriplePatternAsList(pattern); this.messages++; if (computed.size() > 0) { this.profile.insertTriplesWithList(pattern, computed); this.tripleResponses += computed.size(); } } else { // the remote peer has the pattern IBFStrata.Result res = this.profile.query.strata.get(pattern).difference(remote.profile.query.strata.get(pattern)); if (res.messagessent == 0) { this.messages++; } else { this.messages += res.messagessent; } this.profile.insertTriplesWithList(pattern, res.missing); this.tripleResponses += res.missing.size(); } } private List<Node> computeRealNewPeers(long id, Long oldest, List<Node> previousPartialview, List<Node> previousSample, List<Node> currentPartialview) { // firstly, remove the oldest from the old partialview List<Node> oldpv = new ArrayList<>(previousPartialview); oldpv.remove(oldest); // secondly, remove the id from the old sample List<Node> oldsample = new ArrayList<>(previousSample); oldsample.remove(id); // thridly, substract oldpv wiith oldsample oldpv.removeAll(oldsample); // then remove all entry in newpv containing remaining oldpv entries List<Node> remainings = new ArrayList<>(currentPartialview); remainings.removeAll(oldpv); return remainings; } }
40.189815
156
0.631379
bd342b48832b36ed653ad10fe8566ed3973e63a7
535
package comp207p.target; public class ConstantVariableFolding { public int methodOne(){ int a = 62; int b = (a + 764) * 3; return b + 1234 - a; } public double methodTwo(){ double i = 0.67; int j = 1; return i + j; } public boolean methodThree(){ int x = 12345; int y = 54321; return x > y; } public boolean methodFour(){ long x = 4835783423L; long y = 400000; long z = x + y; return x > y; } }
17.833333
36
0.484112
dc29a997dbe111d028a6cdd14db795a3a18ebce1
6,090
/* * 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.openjpa.lib.meta; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.JarURLConnection; import java.net.URL; import java.security.AccessController; import java.security.PrivilegedActionException; import java.util.ArrayList; import java.util.Enumeration; import java.util.NoSuchElementException; import java.util.jar.JarEntry; import java.util.jar.JarFile; import org.apache.openjpa.lib.util.J2DoPrivHelper; /** * Iterator over all metadata resources in a given resource addressed by a jar:file URL. * */ public class JarFileURLMetaDataIterator implements MetaDataIterator, MetaDataFilter.Resource { private final MetaDataFilter _filter; private final JarFile _jarFile; private final JarEntry _jarTargetEntry; private int index = 0; private JarEntry _last = null; private final ArrayList<JarEntry> _entryList = new ArrayList<>(); public JarFileURLMetaDataIterator(URL url, MetaDataFilter filter) throws IOException { if (url == null) { _jarFile = null; _jarTargetEntry = null; } else { JarURLConnection jarURLConn = (JarURLConnection) url.openConnection(); jarURLConn.setDefaultUseCaches(false); try { _jarFile = AccessController.doPrivileged(J2DoPrivHelper.getJarFileAction(jarURLConn)); _jarTargetEntry = AccessController.doPrivileged(J2DoPrivHelper.getJarEntryAction(jarURLConn)); if (_jarTargetEntry.isDirectory()) { Enumeration<JarEntry> jarEntryEnum = _jarFile.entries(); while (jarEntryEnum.hasMoreElements()) { JarEntry jarEntry = jarEntryEnum.nextElement(); if (jarEntry.getName().startsWith(_jarTargetEntry.getName())) { _entryList.add(jarEntry); } } } else { _entryList.add(_jarTargetEntry); } } catch (PrivilegedActionException pae) { throw (IOException) pae.getException(); } } _filter = filter; } /** * Return whether there is another resource to iterate over. */ @Override public boolean hasNext() throws IOException { if (_entryList.size() <= index) { return false; } // Search for next metadata file while (index < _entryList.size()) { if (_filter != null && !_filter.matches(this)) { index++; continue; } break; } return (index < _entryList.size()); } /** * Return the next metadata resource. */ @Override public Object next() throws IOException { if (!hasNext()) { throw new NoSuchElementException(); } String ret = _entryList.get(index).getName(); _last = _entryList.get(index); index++; return ret; } /** * Return the last-iterated metadata resource content as a stream. */ @Override public InputStream getInputStream() throws IOException { if (_last == null) throw new IllegalStateException(); return _jarFile.getInputStream(_last); } /** * Return the last-iterated metadata resource content as a file, or null if not an extant file. */ @Override public File getFile() throws IOException { if (_last == null) throw new IllegalStateException(); return null; } /** * Close the resources used by this iterator. */ @Override public void close() { try { if (_jarFile != null) _jarFile.close(); } catch (IOException ioe) { } } // //////////////////////////////////////// // MetaDataFilter.Resource implementation // //////////////////////////////////////// /** * The name of the resource. */ @Override public String getName() { if (index < _entryList.size()) { return _entryList.get(index).getName(); } else { return null; } } /** * Resource content. */ @Override public byte[] getContent() throws IOException { if (_entryList.size() <= index) { return new byte[0]; } long size = _entryList.get(index).getSize(); if (size == 0) return new byte[0]; InputStream in = _jarFile.getInputStream(_entryList.get(index)); byte[] content; if (size < 0) { ByteArrayOutputStream bout = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; for (int r; (r = in.read(buf)) != -1; bout.write(buf, 0, r)) ; content = bout.toByteArray(); } else { content = new byte[(int) size]; int offset = 0; int read; while (offset < size && (read = in.read(content, offset, (int) size - offset)) != -1) { offset += read; } } in.close(); return content; } }
30.603015
110
0.585714
f526054f4323dbe91711b1b95b87f0b91219ee4f
2,151
package uk.org.fyodor.junit; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.ParameterContext; import org.junit.jupiter.api.extension.ParameterResolutionException; import org.junit.jupiter.api.extension.ParameterResolver; import uk.org.fyodor.generators.time.Temporality; import uk.org.fyodor.generators.time.Timekeeper; import uk.org.fyodor.testapi.Current; import java.lang.reflect.Parameter; import java.time.*; import java.util.HashMap; import java.util.Map; import java.util.function.Supplier; import static uk.org.fyodor.generators.time.Timekeeper.current; final class TemporalityParameterResolver implements ParameterResolver { private static final Map<Class<?>, Supplier<Object>> parameterSuppliersByType = new HashMap<Class<?>, Supplier<Object>>() {{ put(LocalDate.class, () -> current().date()); put(LocalTime.class, () -> current().time()); put(LocalDateTime.class, () -> current().dateTime()); put(ZonedDateTime.class, () -> current().zonedDateTime()); put(ZoneId.class, () -> current().zone()); put(Temporality.class, Timekeeper::current); }}; @Override public boolean supportsParameter(final ParameterContext parameterContext, final ExtensionContext extensionContext) throws ParameterResolutionException { final Parameter parameter = parameterContext.getParameter(); return parameter.getType().equals(Temporality.class) || isSupportedJavaTimeParameterWithCurrentAnnotation(parameter); } @Override public Object resolveParameter(final ParameterContext parameterContext, final ExtensionContext extensionContext) throws ParameterResolutionException { return parameterSuppliersByType.get(parameterContext.getParameter().getType()).get(); } private static boolean isSupportedJavaTimeParameterWithCurrentAnnotation(final Parameter parameter) { return parameterSuppliersByType.containsKey(parameter.getType()) && parameter.isAnnotationPresent(Current.class); } }
43.02
128
0.728498
39162e1249c1309b486c0c559cc10aa435ccbb14
562
package com.pj.squashrestapp.model; public enum SetWinningType { /** * Examples of scores if set is played up to 11 points * * <pre> * 11 : 6 * 12 : 10 * 14 : 12 * </pre> */ ADV_OF_2_ABSOLUTE, /** * Examples of scores if set is played up to 11 points * * <pre> * 11 : 6 * 11 : 9 * 11 : 10 * </pre> */ WINNING_POINTS_ABSOLUTE, /** * Examples of scores if set is played up to 11 points * * <pre> * 11 : 6 * 11 : 9 * 12 : 10 * 12 : 11 * </pre> */ ADV_OF_2_OR_1_AT_THE_END }
14.410256
56
0.523132
b0d33f452dc928bc317410bb35f7d1f74ef309ae
5,989
package com.yunlong.softpark.mapper; import com.yunlong.softpark.entity.ColumnEntity; import com.yunlong.softpark.entity.PlatesEntity; import com.yunlong.softpark.entity.SoftwareEntity; import com.yunlong.softpark.entity.SortEntity; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import org.springframework.stereotype.Repository; import java.util.Date; import java.util.List; @Repository public interface SoftwareMapper { /** * 通过userId获取历史发布的软件信息 * @param userId * @param min * @return */ @Select("select \"SOFT_ID\",\"SOFT_NAME\",\"PARENT_ID\",\"SOFT_LOGO\",\"EDITION\"," + "\"LANGUAGE\",\"PLATFORM\",\"SOFT_SIZE\",\"SOFT_ADDR\",\"USER_ID\"," + "\"CREATE_TIME\",\"UPDATE_TIME\",\"VERIFY\",\"DOWNLOADS\"\n" + "from \"softpark\".\"SOFTWARE\" " + "where \"USER_ID\" = #{userId} order by \"CREATE_TIME\" desc limit #{min},10") List<SoftwareEntity> selectByAuthor(String userId, Integer min); @Select("select \"PLATE_ID\",\"PLATE_NAME\",\"PLATE_LOGO\"\n" + "from \"softpark\".\"PLATES\" limit 0,#{num};") List<PlatesEntity> getPlates(Integer num); @Select("select \"SORT_ID\",\"SORT_NAME\",\"PARENT_ID\",\"SORT_LOGO\"\n" + "from \"softpark\".\"SORT\" where PARENT_ID = #{platesId}") List<SortEntity> getSortEntity(Integer platesId); @Select("select \"COLUMN_ID\",\"COLUMN_NAME\",\"PARENT_ID\",\"COLUMN_LOGO\",\"COLUMN_WEB\",\"WEB_INTRODUCE\",\"COLUMN_TYPE\",\"LICENSE\",\"INTRODUCE_ID\",\"DOWNLOADS\",\"SHOW_PIC\",\"RECOMMEND\",\"VERIFY\"\n" + "from \"softpark\".\"COLUMN\"" + "where PARENT_ID = #{sortId} limit #{page},25 ") List<ColumnEntity> getColumnEntity(Integer sortId,Integer page); @Select("select \"COLUMN_ID\",\"COLUMN_NAME\",\"PARENT_ID\",\"COLUMN_LOGO\",\"COLUMN_WEB\",\"WEB_INTRODUCE\"," + "\"COLUMN_TYPE\",\"LICENSE\",\"INTRODUCE_ID\",\"DOWNLOADS\",\"SHOW_PIC\",\"RECOMMEND\"\n" + "from \"softpark\".\"COLUMN\" where RECOMMEND = 1") List<ColumnEntity> getRecommend(); @Insert("insert into \"softpark\".\"SOFTWARE\"(\"SOFT_ID\", \"SOFT_NAME\", \"PARENT_ID\", " + "\"SOFT_LOGO\", \"EDITION\", \"LANGUAGE\", \"PLATFORM\", \"SOFT_SIZE\", \"SOFT_ADDR\", " + "\"USER_ID\", \"CREATE_TIME\", \"UPDATE_TIME\", \"VERIFY\", \"DOWNLOADS\", \"INSTALL_PROLEFT\", " + "\"SHOW_PIC\", \"INSTALL_PRORIGHT\", \"BRIEF_INTRO\") \n" + "VALUES( #{softId},#{softName},#{parentId},#{softLogo},#{edition},#{language},#{platform},#{softSize}," + "#{softAddr},#{userId},#{createTime},#{updateTime},#{verify},#{downloads},#{installProleft}," + "#{showPic},#{installProright},#{briefIntro} );") void insertSoft(String briefIntro, Date createTime, Integer downloads, String edition, String installProleft, String installProright, String language, String parentId, String platform, String showPic, String softAddr, String softId, String softLogo, String softName, String softSize, Date updateTime, String userId, Integer verify); @Select("select *\n" + "from \"softpark\".\"SOFTWARE\" \n" + "where \"SOFT_NAME\" like '%'||#{key}||'%' or \"EDITION\" like '%'||#{key}||'%' or \"LANGUAGE\" like '%'||#{key}||'%' " + "or \"PLATFORM\" like '%'||#{key}||'%' " + "or \"BRIEF_INTRO\" like '%'||#{key}||'%';") List<SoftwareEntity> selectByKey(String key); @Select("select * from \"softpark\".\"SORT\" where \"PARENT_ID\"=#{plateId}") List<SortEntity> selectSortByPlate(Integer plateId); /** * 通过sortId获取column */ @Select("select * from \"softpark\".\"COLUMN\" where \"PARENT_ID\"=#{sortId}") List<ColumnEntity> getColumnBySort(Integer sortId); /** * 根据id获取软件实体 * @param softId * @return */ @Select("select * from \"softpark\".\"SOFTWARE\" where \"SOFT_ID\"=#{softId}") SoftwareEntity selectBySoftId(String softId); /** * 根据id更新软件的下载次数 * @param softId * @param downloads */ @Update("update \"softpark\".\"SOFTWARE\" set \"DOWNLOADS\"= #{downloads} where \"SOFT_ID\" = #{softId}") void UpdateDownloads(String softId, int downloads); /** * 获取所有的分类 * @return */ @Select("select * from \"softpark\".\"SORT\" ") List<SortEntity> getSort(); /** * 获取所有的column * @return */ @Select("select * from \"softpark\".\"COLUMN\" where \"VERIFY\"=1") List<ColumnEntity> getColumn(); // /** // * 通过userId获取历史发布的软件信息 // * @param userId // * @param min // * @return // */ // @Select("select \"SOFT_ID\",\"SOFT_NAME\",\"PARENT_ID\",\"SOFT_LOGO\",\"LICENSE\",\"EDITION\",\"SOFT_TYPE\"," + // "\"SOFT_WEB\",\"LANGUAGE\",\"PLATFORM\",\"SOFT_SIZE\",\"SOFT_ADDR\",\"USER_ID\",\"INTRODUCE_ID\"," + // "\"CREATE_TIME\",\"UPDATE_TIME\",\"VERIFY\",\"DOWNLOADS\"\n" + // "from \"softpark\".\"SOFTWARE\" " + // "where \"USER_ID\" = #{userId} order by \"CREATE_TIME\" desc limit #{min},10") // List<SoftwareEntity> selectByAuthor(String userId, Integer min); /** * 通过columnId查询软件信息 * @param columnId * @return */ @Select("select * from \"softpark\".\"SOFTWARE\" where \"PARENT_ID\" = #{columnId};") List<SoftwareEntity> selectByColumnId(String columnId); // /** // * 根据softId查询软件信息 // * @param softId // * @return // */ // @Select("select * from \"softpark\".\"SOFTWARE\" where \"SOFT_ID\" = #{softId};\n") // SoftwareEntity selectBySoftId(String softId); /** * 根据userid查找用户发布过的软件信息 * @param userId * @return */ @Select("select * from \"softpark\".\"SOFTWARE\" where \"USER_ID\" = #{userId};") List<SoftwareEntity> selectByUerId(String userId); }
41.020548
214
0.591084
a8ac60690986bb38438a6cb9d5abcfdc874b32c6
1,309
/* * Copyright 2011-2012 Gregory P. Moyer * * 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.syphr.mythtv.db; public enum SchemaVersion { _1264(1264), _1293(1293); private final int value; private SchemaVersion(int value) { this.value = value; } public int getValue() { return value; } public String getPersistenceUnitName() { return "org.syphr.mythtv.db.schema.impl." + getValue(); } public static SchemaVersion valueOf(int value) { for (SchemaVersion version : values()) { if (value == version.getValue()) { return version; } } throw new IllegalArgumentException("Unable to locate schema version " + value); } }
25.173077
87
0.643239
c2bed399f3ae9a0cca09693ff1ddc1fb93549143
27,054
/* FlowView.java -- A composite View Copyright (C) 2005 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU Classpath is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package javax.swing.text; import java.awt.Component; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.Shape; import javax.swing.SizeRequirements; import javax.swing.event.DocumentEvent; /** * A <code>View</code> that can flows it's children into it's layout space. * * The <code>FlowView</code> manages a set of logical views (that are * the children of the {@link #layoutPool} field). These are translated * at layout time into a set of physical views. These are the views that * are managed as the real child views. Each of these child views represents * a row and are laid out within a box using the superclasses behaviour. * The concrete implementation of the rows must be provided by subclasses. * * @author Roman Kennke ([email protected]) */ public abstract class FlowView extends BoxView { /** * A strategy for translating the logical views of a <code>FlowView</code> * into the real views. */ public static class FlowStrategy { /** * Creates a new instance of <code>FlowStragegy</code>. */ public FlowStrategy() { // Nothing to do here. } /** * Receives notification from a <code>FlowView</code> that some content * has been inserted into the document at a location that the * <code>FlowView</code> is responsible for. * * The default implementation simply calls {@link #layout}. * * @param fv the flow view that sends the notification * @param e the document event describing the change * @param alloc the current allocation of the flow view */ public void insertUpdate(FlowView fv, DocumentEvent e, Rectangle alloc) { if (alloc == null) { fv.layoutChanged(X_AXIS); fv.layoutChanged(Y_AXIS); } else { Component host = fv.getContainer(); if (host != null) host.repaint(alloc.x, alloc.y, alloc.width, alloc.height); } } /** * Receives notification from a <code>FlowView</code> that some content * has been removed from the document at a location that the * <code>FlowView</code> is responsible for. * * The default implementation simply calls {@link #layout}. * * @param fv the flow view that sends the notification * @param e the document event describing the change * @param alloc the current allocation of the flow view */ public void removeUpdate(FlowView fv, DocumentEvent e, Rectangle alloc) { if (alloc == null) { fv.layoutChanged(X_AXIS); fv.layoutChanged(Y_AXIS); } else { Component host = fv.getContainer(); if (host != null) host.repaint(alloc.x, alloc.y, alloc.width, alloc.height); } } /** * Receives notification from a <code>FlowView</code> that some attributes * have changed in the document at a location that the * <code>FlowView</code> is responsible for. * * The default implementation simply calls {@link #layout}. * * @param fv the flow view that sends the notification * @param e the document event describing the change * @param alloc the current allocation of the flow view */ public void changedUpdate(FlowView fv, DocumentEvent e, Rectangle alloc) { if (alloc == null) { fv.layoutChanged(X_AXIS); fv.layoutChanged(Y_AXIS); } else { Component host = fv.getContainer(); if (host != null) host.repaint(alloc.x, alloc.y, alloc.width, alloc.height); } } /** * Returns the logical view of the managed <code>FlowView</code>. * * @param fv the flow view for which to return the logical view * * @return the logical view of the managed <code>FlowView</code> */ protected View getLogicalView(FlowView fv) { return fv.layoutPool; } /** * Performs the layout for the whole view. By default this rebuilds * all the physical views from the logical views of the managed FlowView. * * This is called by {@link FlowView#layout} to update the layout of * the view. * * @param fv the flow view for which we perform the layout */ public void layout(FlowView fv) { int start = fv.getStartOffset(); int end = fv.getEndOffset(); // Preserve the views from the logical view from beeing removed. View lv = getLogicalView(fv); int viewCount = lv.getViewCount(); for (int i = 0; i < viewCount; i++) { View v = lv.getView(i); v.setParent(lv); } // Then remove all views from the flow view. fv.removeAll(); for (int rowIndex = 0; start < end; rowIndex++) { View row = fv.createRow(); fv.append(row); int next = layoutRow(fv, rowIndex, start); if (row.getViewCount() == 0) { row.append(createView(fv, start, Integer.MAX_VALUE, rowIndex)); next = row.getEndOffset(); } if (start < next) start = next; else assert false: "May not happen"; } } /** * Lays out one row of the flow view. This is called by {@link #layout} to * fill one row with child views until the available span is exhausted. The * default implementation fills the row by calling * {@link #createView(FlowView, int, int, int)} until the available space is * exhausted, a forced break is encountered or there are no more views in * the logical view. If the available space is exhausted, * {@link #adjustRow(FlowView, int, int, int)} is called to fit the row into * the available span. * * @param fv the flow view for which we perform the layout * @param rowIndex the index of the row * @param pos the model position for the beginning of the row * @return the start position of the next row */ protected int layoutRow(FlowView fv, int rowIndex, int pos) { View row = fv.getView(rowIndex); int axis = fv.getFlowAxis(); int span = fv.getFlowSpan(rowIndex); int x = fv.getFlowStart(rowIndex); int end = fv.getEndOffset(); // Needed for adjusting indentation in adjustRow(). int preX = x; int availableSpan = span; TabExpander tabExp = fv instanceof TabExpander ? (TabExpander) fv : null; boolean forcedBreak = false; while (pos < end && span >= 0) { View view = createView(fv, pos, span, rowIndex); if (view == null || (span == 0 && view.getPreferredSpan(axis) > 0)) break; int viewSpan; if (axis == X_AXIS && view instanceof TabableView) viewSpan = (int) ((TabableView) view).getTabbedSpan(x, tabExp); else viewSpan = (int) view.getPreferredSpan(axis); // Break if the line if the view does not fit in this row or the // line just must be broken. int breakWeight = view.getBreakWeight(axis, pos, span); if (breakWeight >= ForcedBreakWeight) { int rowViewCount = row.getViewCount(); if (rowViewCount > 0) { view = view.breakView(axis, pos, x, span); if (view != null) { if (axis == X_AXIS && view instanceof TabableView) viewSpan = (int) ((TabableView) view).getTabbedSpan(x, tabExp); else viewSpan = (int) view.getPreferredSpan(axis); } else viewSpan = 0; } forcedBreak = true; } span -= viewSpan; x += viewSpan; if (view != null) { row.append(view); pos = view.getEndOffset(); } if (forcedBreak) break; } if (span < 0) adjustRow(fv, rowIndex, availableSpan, preX); else if (row.getViewCount() == 0) { View view = createView(fv, pos, Integer.MAX_VALUE, rowIndex); row.append(view); } return row.getEndOffset(); } /** * Creates physical views that form the rows of the flow view. This * can be an entire view from the logical view (if it fits within the * available span), a fragment of such a view (if it doesn't fit in the * available span and can be broken down) or <code>null</code> (if it does * not fit in the available span and also cannot be broken down). * * The default implementation fetches the logical view at the specified * <code>startOffset</code>. If that view has a different startOffset than * specified in the argument, a fragment is created using * {@link View#createFragment(int, int)} that has the correct startOffset * and the logical view's endOffset. * * @param fv the flow view * @param startOffset the start offset for the view to be created * @param spanLeft the available span * @param rowIndex the index of the row * * @return a view to fill the row with, or <code>null</code> if there * is no view or view fragment that fits in the available span */ protected View createView(FlowView fv, int startOffset, int spanLeft, int rowIndex) { View logicalView = getLogicalView(fv); int index = logicalView.getViewIndex(startOffset, Position.Bias.Forward); View retVal = logicalView.getView(index); if (retVal.getStartOffset() != startOffset) retVal = retVal.createFragment(startOffset, retVal.getEndOffset()); return retVal; } /** * Tries to adjust the specified row to fit within the desired span. The * default implementation iterates through the children of the specified * row to find the view that has the highest break weight and - if there * is more than one view with such a break weight - which is nearest to * the end of the row. If there is such a view that has a break weight > * {@link View#BadBreakWeight}, this view is broken using the * {@link View#breakView(int, int, float, float)} method and this view and * all views after the now broken view are replaced by the broken view. * * @param fv the flow view * @param rowIndex the index of the row to be adjusted * @param desiredSpan the layout span * @param x the X location at which the row starts */ protected void adjustRow(FlowView fv, int rowIndex, int desiredSpan, int x) { // Determine the last view that has the highest break weight. int axis = fv.getFlowAxis(); View row = fv.getView(rowIndex); int count = row.getViewCount(); int breakIndex = -1; int breakWeight = BadBreakWeight; int breakSpan = 0; int currentSpan = 0; for (int i = 0; i < count; ++i) { View view = row.getView(i); int spanLeft = desiredSpan - currentSpan; int weight = view.getBreakWeight(axis, x + currentSpan, spanLeft); if (weight >= breakWeight && weight > BadBreakWeight) { breakIndex = i; breakSpan = currentSpan; breakWeight = weight; if (weight >= ForcedBreakWeight) // Don't search further. break; } currentSpan += view.getPreferredSpan(axis); } // If there is a potential break location found, break the row at // this location. if (breakIndex >= 0) { int spanLeft = desiredSpan - breakSpan; View toBeBroken = row.getView(breakIndex); View brokenView = toBeBroken.breakView(axis, toBeBroken.getStartOffset(), x + breakSpan, spanLeft); View lv = getLogicalView(fv); for (int i = breakIndex; i < count; i++) { View tmp = row.getView(i); if (contains(lv, tmp)) tmp.setParent(lv); else if (tmp.getViewCount() > 0) reparent(tmp, lv); } row.replace(breakIndex, count - breakIndex, new View[]{ brokenView }); } } /** * Helper method to determine if one view contains another as child. */ private boolean contains(View view, View child) { boolean ret = false; int n = view.getViewCount(); for (int i = 0; i < n && ret == false; i++) { if (view.getView(i) == child) ret = true; } return ret; } /** * Helper method that reparents the <code>view</code> and all of its * decendents to the <code>parent</code> (the logical view). * * @param view the view to reparent * @param parent the new parent */ private void reparent(View view, View parent) { int n = view.getViewCount(); for (int i = 0; i < n; i++) { View tmp = view.getView(i); if (contains(parent, tmp)) tmp.setParent(parent); else reparent(tmp, parent); } } } /** * This special subclass of <code>View</code> is used to represent * the logical representation of this view. It does not support any * visual representation, this is handled by the physical view implemented * in the <code>FlowView</code>. */ class LogicalView extends CompositeView { /** * Creates a new LogicalView instance. */ LogicalView(Element el) { super(el); } /** * Overridden to return the attributes of the parent * (== the FlowView instance). */ public AttributeSet getAttributes() { View p = getParent(); return p != null ? p.getAttributes() : null; } protected void childAllocation(int index, Rectangle a) { // Nothing to do here (not visual). } protected View getViewAtPoint(int x, int y, Rectangle r) { // Nothing to do here (not visual). return null; } protected boolean isAfter(int x, int y, Rectangle r) { // Nothing to do here (not visual). return false; } protected boolean isBefore(int x, int y, Rectangle r) { // Nothing to do here (not visual). return false; } public float getPreferredSpan(int axis) { float max = 0; float pref = 0; int n = getViewCount(); for (int i = 0; i < n; i++) { View v = getView(i); pref += v.getPreferredSpan(axis); if (v.getBreakWeight(axis, 0, Integer.MAX_VALUE) >= ForcedBreakWeight) { max = Math.max(max, pref); pref = 0; } } max = Math.max(max, pref); return max; } public float getMinimumSpan(int axis) { float max = 0; float min = 0; boolean wrap = true; int n = getViewCount(); for (int i = 0; i < n; i++) { View v = getView(i); if (v.getBreakWeight(axis, 0, Integer.MAX_VALUE) == BadBreakWeight) { min += v.getPreferredSpan(axis); wrap = false; } else if (! wrap) { max = Math.max(min, max); wrap = true; min = 0; } } max = Math.max(max, min); return max; } public void paint(Graphics g, Shape s) { // Nothing to do here (not visual). } /** * Overridden to handle possible leaf elements. */ protected void loadChildren(ViewFactory f) { Element el = getElement(); if (el.isLeaf()) { View v = new LabelView(el); append(v); } else super.loadChildren(f); } /** * Overridden to reparent the children to this logical view, in case * they have been parented by a row. */ protected void forwardUpdateToView(View v, DocumentEvent e, Shape a, ViewFactory f) { v.setParent(this); super.forwardUpdateToView(v, e, a, f); } /** * Overridden to handle possible leaf element. */ protected int getViewIndexAtPosition(int pos) { int index = 0; if (! getElement().isLeaf()) index = super.getViewIndexAtPosition(pos); return index; } } /** * The shared instance of FlowStrategy. */ static final FlowStrategy sharedStrategy = new FlowStrategy(); /** * The span of the <code>FlowView</code> that should be flowed. */ protected int layoutSpan; /** * Represents the logical child elements of this view, encapsulated within * one parent view (an instance of a package private <code>LogicalView</code> * class). These will be translated to a set of real views that are then * displayed on screen. This translation is performed by the inner class * {@link FlowStrategy}. */ protected View layoutPool; /** * The <code>FlowStrategy</code> to use for translating between the * logical and physical view. */ protected FlowStrategy strategy; /** * Creates a new <code>FlowView</code> for the given * <code>Element</code> and <code>axis</code>. * * @param element the element that is rendered by this FlowView * @param axis the axis along which the view is tiled, either * <code>View.X_AXIS</code> or <code>View.Y_AXIS</code>, the flow * axis is orthogonal to this one */ public FlowView(Element element, int axis) { super(element, axis); strategy = sharedStrategy; layoutSpan = Short.MAX_VALUE; } /** * Returns the axis along which the view should be flowed. This is * orthogonal to the axis along which the boxes are tiled. * * @return the axis along which the view should be flowed */ public int getFlowAxis() { int axis = getAxis(); int flowAxis; if (axis == X_AXIS) flowAxis = Y_AXIS; else flowAxis = X_AXIS; return flowAxis; } /** * Returns the span of the flow for the specified child view. A flow * layout can be shaped by providing different span values for different * child indices. The default implementation returns the entire available * span inside the view. * * @param index the index of the child for which to return the span * * @return the span of the flow for the specified child view */ public int getFlowSpan(int index) { return layoutSpan; } /** * Returns the location along the flow axis where the flow span starts * given a child view index. The flow can be shaped by providing * different values here. * * @param index the index of the child for which to return the flow location * * @return the location along the flow axis where the flow span starts */ public int getFlowStart(int index) { return 0; } /** * Creates a new view that represents a row within a flow. * * @return a view for a new row */ protected abstract View createRow(); /** * Loads the children of this view. The <code>FlowView</code> does not * directly load its children. Instead it creates a logical view * ({@link #layoutPool}) which is filled by the logical child views. * The real children are created at layout time and each represent one * row. * * This method is called by {@link View#setParent} in order to initialize * the view. * * @param vf the view factory to use for creating the child views */ protected void loadChildren(ViewFactory vf) { if (layoutPool == null) { layoutPool = new LogicalView(getElement()); } layoutPool.setParent(this); // Initialize the flow strategy. strategy.insertUpdate(this, null, null); } /** * Performs the layout of this view. If the span along the flow axis changed, * this first calls {@link FlowStrategy#layout} in order to rebuild the * rows of this view. Then the superclass's behaviour is called to arrange * the rows within the box. * * @param width the width of the view * @param height the height of the view */ protected void layout(int width, int height) { int flowAxis = getFlowAxis(); int span; if (flowAxis == X_AXIS) span = (int) width; else span = (int) height; if (layoutSpan != span) { layoutChanged(flowAxis); layoutChanged(getAxis()); layoutSpan = span; } if (! isLayoutValid(flowAxis)) { int axis = getAxis(); int oldSpan = axis == X_AXIS ? getWidth() : getHeight(); strategy.layout(this); int newSpan = (int) getPreferredSpan(axis); if (oldSpan != newSpan) { View parent = getParent(); if (parent != null) parent.preferenceChanged(this, axis == X_AXIS, axis == Y_AXIS); } } super.layout(width, height); } /** * Receice notification that some content has been inserted in the region * that this view is responsible for. This calls * {@link FlowStrategy#insertUpdate}. * * @param changes the document event describing the changes * @param a the current allocation of the view * @param vf the view factory that is used for creating new child views */ public void insertUpdate(DocumentEvent changes, Shape a, ViewFactory vf) { // First we must send the insertUpdate to the logical view so it can // be updated accordingly. layoutPool.insertUpdate(changes, a, vf); strategy.insertUpdate(this, changes, getInsideAllocation(a)); } /** * Receice notification that some content has been removed from the region * that this view is responsible for. This calls * {@link FlowStrategy#removeUpdate}. * * @param changes the document event describing the changes * @param a the current allocation of the view * @param vf the view factory that is used for creating new child views */ public void removeUpdate(DocumentEvent changes, Shape a, ViewFactory vf) { layoutPool.removeUpdate(changes, a, vf); strategy.removeUpdate(this, changes, getInsideAllocation(a)); } /** * Receice notification that some attributes changed in the region * that this view is responsible for. This calls * {@link FlowStrategy#changedUpdate}. * * @param changes the document event describing the changes * @param a the current allocation of the view * @param vf the view factory that is used for creating new child views */ public void changedUpdate(DocumentEvent changes, Shape a, ViewFactory vf) { layoutPool.changedUpdate(changes, a, vf); strategy.changedUpdate(this, changes, getInsideAllocation(a)); } /** * Returns the index of the child <code>View</code> for the given model * position. * * This is implemented to iterate over the children of this * view (the rows) and return the index of the first view that contains * the given position. * * @param pos the model position for whicht the child <code>View</code> is * queried * * @return the index of the child <code>View</code> for the given model * position */ protected int getViewIndexAtPosition(int pos) { // First make sure we have a valid layout. if (!isAllocationValid()) layout(getWidth(), getHeight()); int count = getViewCount(); int result = -1; for (int i = 0; i < count; ++i) { View child = getView(i); int start = child.getStartOffset(); int end = child.getEndOffset(); if (start <= pos && end > pos) { result = i; break; } } return result; } /** * Calculates the size requirements of this <code>BoxView</code> along * its minor axis, that is the axis opposite to the axis specified in the * constructor. * * This is overridden and forwards the request to the logical view. * * @param axis the axis that is examined * @param r the <code>SizeRequirements</code> object to hold the result, * if <code>null</code>, a new one is created * * @return the size requirements for this <code>BoxView</code> along * the specified axis */ protected SizeRequirements calculateMinorAxisRequirements(int axis, SizeRequirements r) { SizeRequirements res = r; if (res == null) res = new SizeRequirements(); res.minimum = (int) layoutPool.getMinimumSpan(axis); res.preferred = Math.max(res.minimum, (int) layoutPool.getPreferredSpan(axis)); res.maximum = Integer.MAX_VALUE; res.alignment = 0.5F; return res; } }
32.130641
81
0.60808
596165caae91f1ee322f3c858bdc876fdb8881a7
597
package org.terraform.structure; import org.terraform.data.MegaChunk; import org.terraform.data.TerraformWorld; /** * This represents structures that can spawn multiple times within a mega chunk, * including things like small dungeons and shipwrecks. */ public abstract class MultiMegaChunkStructurePopulator extends StructurePopulator { public abstract boolean canSpawn(TerraformWorld tw, int chunkX, int chunkZ); public abstract int[][] getCoordsFromMegaChunk(TerraformWorld tw, MegaChunk mc); public abstract int[] getNearestFeature(TerraformWorld world, int rawX, int rawZ); }
33.166667
86
0.798995
5c787ccb357ef3527326f2fb2ba305c4ae911f72
8,384
package cn.elwy.eplus.framework.web; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.net.URLEncoder; import java.util.Date; import java.util.Enumeration; import java.util.List; import java.util.Map; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.pagehelper.Page; import cn.elwy.common.PropertyConstant; import cn.elwy.common.entity.Criteria; import cn.elwy.common.entity.OrderRule; import cn.elwy.common.entity.Parameter; import cn.elwy.common.exception.ExceptionSupport; import cn.elwy.common.util.AssertUtil; import cn.elwy.common.util.ConvertTypeUtil; import cn.elwy.common.util.DateUtil; import cn.elwy.common.util.JsonUtil; import cn.elwy.common.util.ReflectUtil; /** * @author huangsq * @version 1.0, 2018-02-19 */ public class WebUtil implements PropertyConstant { private static Logger logger = LoggerFactory.getLogger(WebUtil.class); public static final int RESPONSE_STATUS_ERROR = 500; public static final String UTF_8 = "UTF-8"; public static final String TEXT_JSON_CONTENT_TYPE = "text/json;charset=UTF-8"; private WebUtil() { } public static Page<?> getPage(ServletRequest request) { Integer pageNo = getInteger(request, PAGE_NO); Integer pageSize = getInteger(request, PAGE_SIZE); return new Page<Object>(pageNo, pageSize); } public static Parameter getParameter() { Parameter parameter = new Parameter(); return parameter; } public static Parameter getParameter(HttpServletRequest request) { Parameter parameter = null; String parameterText = request.getParameter(PARAMETER); if (AssertUtil.isNotEmpty(parameterText)) { parameter = JsonUtil.toObject(parameterText, Parameter.class); } else { parameter = new Parameter(); } parameter.put(CONTEXT_PATH, request.getContextPath()); Enumeration<?> enu = request.getParameterNames(); while (enu.hasMoreElements()) { String paraName = (String) enu.nextElement(); if (!PARAMETER.equals(paraName) && !OPERATE.equals(paraName) && !PAGE_NO.equals(paraName) && !PAGE_SIZE.equals(paraName) && !CRITERIAS.equals(paraName) && !ORDER_RULES.equals(paraName)) { parameter.put(paraName, request.getParameter(paraName)); } } String operate = WebUtil.getString(request, OPERATE); if (AssertUtil.isNotEmpty(operate)) { parameter.setOperate(operate); } String paramText = request.getParameter(PARAM); if (AssertUtil.isNotEmpty(paramText)) { @SuppressWarnings("unchecked") Map<String, Object> param = JsonUtil.toObject(paramText, Map.class); parameter.setParam(param); } Integer pageNo = WebUtil.getInteger(request, PAGE_NO); if (AssertUtil.isNotEmpty(pageNo)) { parameter.setPageNo(pageNo); } Integer pageSize = WebUtil.getInteger(request, PAGE_SIZE); if (AssertUtil.isNotEmpty(pageSize)) { parameter.setPageSize(pageSize); } String id = WebUtil.getString(request, ID); if (AssertUtil.isNotEmpty(id)) { parameter.setId(id); } String[] ids = WebUtil.getStringValues(request, IDS); if (AssertUtil.isNotEmpty(ids)) { parameter.setIds(ids); } String criteriaText = request.getParameter(CRITERIAS); if (AssertUtil.isNotEmpty(criteriaText)) { List<Criteria> criterias = JsonUtil.toList(criteriaText, Criteria.class); // for (Criteria criteria : groups) { // parameter.and(criteria); // } parameter.setCriterias(criterias); } String orderRuleText = request.getParameter(ORDER_RULES); if (AssertUtil.isNotEmpty(orderRuleText)) { List<OrderRule> orderRules = JsonUtil.toList(orderRuleText, OrderRule.class); parameter.setOrderRules(orderRules); } return parameter; } public static String getString(ServletRequest request, String key) { return getString(request, key, null); } public static String getString(ServletRequest request, String key, String defaultValue) { String string = request.getParameter(key); return string != null ? string : defaultValue; } public static String[] getStringValues(ServletRequest request, String key) { return request.getParameterValues(key); } public static Boolean getBoolean(ServletRequest request, String key, Boolean defaultValue) { String parameter = request.getParameter(key); return ConvertTypeUtil.toBoolean(parameter, defaultValue); } public static Boolean[] getBooleanValues(ServletRequest request, String key) { String[] parameterValues = request.getParameterValues(key); return ConvertTypeUtil.toBooleanArray(parameterValues, false); } public static Integer getInteger(ServletRequest request, String key) { return getInteger(request, key, null); } public static Integer getInteger(ServletRequest request, String key, Integer defaultValue) { String parameter = request.getParameter(key); return ConvertTypeUtil.toInteger(parameter, defaultValue); } public static Long getLong(ServletRequest request, String key) { return getLong(request, key, null); } public static Long getLong(ServletRequest request, String key, Long defaultValue) { String parameter = request.getParameter(key); return ConvertTypeUtil.toLong(parameter, defaultValue); } public static Long[] getLongValues(ServletRequest request, String key, Long defaultValue) { String[] parameters = request.getParameterValues(key); return ConvertTypeUtil.toLongArray(parameters, defaultValue); } public static Integer[] getIntegerValues(ServletRequest request, String key) { String[] parameterValues = request.getParameterValues(key); return ConvertTypeUtil.toIntegerArray(parameterValues, 0); } public static Date getDate(ServletRequest request, String key) { return getDate(request, key, null); } public static Date getDate(ServletRequest request, String key, Date defaultValue) { String parameterValues = request.getParameter(key); return DateUtil.toDateTime(parameterValues, defaultValue); } public static void outJson(HttpServletResponse response, String json) { PrintWriter writer = null; try { response.setContentType(TEXT_JSON_CONTENT_TYPE); response.setCharacterEncoding(UTF_8); writer = response.getWriter(); writer.write(json); writer.flush(); } catch (Exception e) { if (writer != null) { writer.println(e.getMessage()); } } finally { if (writer != null) { writer.close(); } } } public static void outJson(HttpServletResponse response, Object obj) { outJson(response, JsonUtil.toJson(obj)); } public static void failure(HttpServletResponse response, String msg) { response.setStatus(RESPONSE_STATUS_ERROR); outJson(response, msg); } /** * 访问失败,将异常信息返回到前台 * @param response 响应对象 * @param e 异常对象 */ public static void failure(HttpServletResponse response, Throwable e) { failure(response, ExceptionSupport.getDetailMessage(e)); } public static void outputStream(HttpServletResponse response, InputStream fis, String fileName) { try { // 以流的形式下载文件。 byte[] buffer = new byte[fis.available()]; fis.read(buffer); outputByte(response, fileName, buffer); } catch (IOException e) { logger.error(e.getMessage(), e); failure(response, e); } finally { ReflectUtil.close(fis); } } public static void outputByte(HttpServletResponse response, String fileName, byte[] data) { OutputStream out = null; try { // 以流的形式下载文件。 // 清空response response.reset(); response.setContentType("application/octet-stream;charset=UTF-8"); // response.setContentType("application/x-download"); fileName = URLEncoder.encode(fileName, "UTF-8"); response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // 设置response的Header response.addHeader("Content-Length", "" + data.length); out = new BufferedOutputStream(response.getOutputStream()); out.write(data); out.flush(); } catch (IOException e) { logger.error(e.getMessage(), e); failure(response, e); } finally { ReflectUtil.close(out); } } }
32.370656
103
0.723044
9cb5eb71ddba8b2bb1b5561191f1dded8362ab3a
4,059
/* * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.testgrid.dao.uow; import org.wso2.testgrid.common.infrastructure.AWSResourceLimit; import org.wso2.testgrid.common.infrastructure.AWSResourceRequirement; import org.wso2.testgrid.dao.EntityManagerHelper; import org.wso2.testgrid.dao.TestGridDAOException; import org.wso2.testgrid.dao.repository.AWSResourceLimitsRepository; import java.util.List; import java.util.Map; import javax.persistence.EntityManager; /** * This class defines the Unit of work related to a {@link AWSResourceLimit}. * * @since 1.0.0 */ public class AWSResourceLimitUOW { private final AWSResourceLimitsRepository awsResourceLimitsRepository; /** * Constructs an instance of {@link AWSResourceLimitUOW} to manager use cases related to test cases. */ public AWSResourceLimitUOW() { EntityManager entityManager = EntityManagerHelper.getEntityManager(); awsResourceLimitsRepository = new AWSResourceLimitsRepository(entityManager); } /** * Returns all the entries from the AWSResourceLimit table. * * @return List all the entries from the table matching the given entity type * @throws TestGridDAOException thrown when error on searching for entity */ public List<AWSResourceLimit> findAll() throws TestGridDAOException { return awsResourceLimitsRepository.findAll(); } /** * Returns a list of distinct {@link AWSResourceLimit} instances for the given product id and date. * * @param params parameter map of search fields * * @return matching distinct {@link AWSResourceLimit} instances * @throws TestGridDAOException thrown when error on retrieving results */ public List<AWSResourceLimit> findByFields(Map<String, Object> params) throws TestGridDAOException { return awsResourceLimitsRepository.findByFields(params); } /** * Return an available region on AWS for the given resource requirements * * @param resourceRequirements AWS resource requirement list * @return available AWS region * @throws TestGridDAOException thrown when error on retrieving region */ public String getAvailableRegion(List<AWSResourceRequirement> resourceRequirements) throws TestGridDAOException { return awsResourceLimitsRepository.getAvailableRegion(resourceRequirements); } /** * Persist initial resource limits for all AWS resources given in awsLimits.yaml. * * @param awsResourceLimitsList list of aws resources * @return persisted AWS resource limits list * @throws TestGridDAOException if persisting resources to database fails */ public List<AWSResourceLimit> persistInitialLimits( List<AWSResourceLimit> awsResourceLimitsList) throws TestGridDAOException { return awsResourceLimitsRepository.persistInitialLimits(awsResourceLimitsList); } /** * Release acquired resources. * * @param awsResourceRequirementList aws resource requirement list * @param region region to release resources from * @throws TestGridDAOException if persisting resourced fails */ public void releaseResources(List<AWSResourceRequirement> awsResourceRequirementList, String region) throws TestGridDAOException { awsResourceLimitsRepository.releaseResources(awsResourceRequirementList, region); } }
38.657143
117
0.741069
7c625cb07b2d91338719ad806195c818cb3af932
3,565
/* * Ext GWT - Ext for GWT * Copyright(c) 2007, 2008, Ext JS, LLC. * [email protected] * * http://extjs.com/license */ package org.net9.minipie.app.client.mvc; import org.net9.minipie.app.client.AppEvents; import com.extjs.gxt.themes.client.Slate; import com.extjs.gxt.ui.client.Registry; import com.extjs.gxt.ui.client.Style.LayoutRegion; import com.extjs.gxt.ui.client.mvc.AppEvent; import com.extjs.gxt.ui.client.mvc.Controller; import com.extjs.gxt.ui.client.mvc.View; import com.extjs.gxt.ui.client.util.Margins; import com.extjs.gxt.ui.client.util.ThemeManager; import com.extjs.gxt.ui.client.widget.ContentPanel; import com.extjs.gxt.ui.client.widget.HtmlContainer; import com.extjs.gxt.ui.client.widget.Viewport; import com.extjs.gxt.ui.client.widget.custom.ThemeSelector; import com.extjs.gxt.ui.client.widget.layout.BorderLayout; import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData; import com.extjs.gxt.ui.client.widget.layout.FitLayout; import com.extjs.gxt.ui.client.widget.toolbar.ToolBar; import com.google.gwt.user.client.ui.RootPanel; public class AppView extends View { public static final String CENTER_PANEL = "centerPanel"; public static final String WEST_PANEL = "westPanel"; public static final String NORTH_PANEL = "northPanel"; public static final String VIEWPORT = "viewPort"; private Viewport viewport; private ContentPanel centerPanel; private HtmlContainer northPanel; private ContentPanel westPanel; public AppView(Controller controller) { super(controller); } protected void handleEvent(AppEvent event) { if (event.getType() == AppEvents.Login) viewport.unmask(); } protected void initialize() { viewport = new Viewport(); viewport.setLayout(new BorderLayout()); Registry.register(VIEWPORT, viewport); createNorth(); createWest(); createCenter(); viewport.mask("Loading..."); RootPanel.get().add(viewport); } private void createCenter() { centerPanel = new ContentPanel(); centerPanel.setBorders(false); centerPanel.setHeaderVisible(false); centerPanel.setLayout(new FitLayout()); BorderLayoutData data = new BorderLayoutData(LayoutRegion.CENTER); data.setMargins(new Margins(5, 5, 5, 0)); viewport.add(centerPanel, data); Registry.register(CENTER_PANEL, centerPanel); } private void createWest() { BorderLayoutData data = new BorderLayoutData(LayoutRegion.WEST, 220, 150, 320); data.setMargins(new Margins(5, 5, 5, 5)); data.setCollapsible(true); westPanel = new ContentPanel(); ToolBar toolBar = new ToolBar(); westPanel.setTopComponent(toolBar); viewport.add(westPanel, data); Registry.register(WEST_PANEL, westPanel); } private void createNorth() { StringBuffer sb = new StringBuffer(); sb.append("<div id='demo-theme'></div><div id=demo-title>Mini-Pie Application Demo</div>"); northPanel = new HtmlContainer(sb.toString()); northPanel.setEnableState(false); northPanel.setId("demo-header"); northPanel.addStyleName("x-small-editor"); ThemeManager.register(Slate.SLATE); ThemeSelector selector = new ThemeSelector(); selector.setWidth(125); northPanel.add(selector, "#demo-theme"); BorderLayoutData data = new BorderLayoutData(LayoutRegion.NORTH, 33); data.setMargins(new Margins()); viewport.add(northPanel, data); Registry.register(NORTH_PANEL, northPanel); } }
32.409091
96
0.709116
40a1b1b8360e7ad46ebb344ed99f37755c11144b
1,280
package com.tuyu.service.impl; import com.tuyu.dao.TestMapper; import com.tuyu.service.BService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; /** * @author tuyu * @date 4/9/19 * Talk is cheap, show me the code. */ @Slf4j @Service public class BServiceImpl implements BService { @Autowired private TestMapper testMapper; @Override @Transactional( // propagation = Propagation.REQUIRED, // propagation = Propagation.SUPPORTS, // propagation = Propagation.MANDATORY, // propagation = Propagation.REQUIRES_NEW, // propagation = Propagation.NOT_SUPPORTED, propagation = Propagation.NEVER, // propagation = Propagation.NESTED, isolation = Isolation.DEFAULT, rollbackFor = Exception.class) public void b() { log.info("start b"); testMapper.b(); int i = 12 / 0; log.info("end b"); } }
29.767442
64
0.690625
5f7d6f21149be6c5279e52f81df0957b83484d05
301
package com.signature.api.resource; import java.util.Collection; public interface Resource<T, ID> { T insert(T entity); T updateWhereIdEquals(ID id, T entity); T selectAllWhereIdEquals(ID id); Collection<T> selectAll(); void delete(); void deleteWhereIdEquals(ID id); }
16.722222
43
0.694352
218b8447db066a2ca3bbc62eb5b6afe5f5108942
1,678
package com.breakersoft.plow.thrift.dao.pgsql; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import java.util.UUID; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.breakersoft.plow.Filter; import com.breakersoft.plow.dao.AbstractDao; import com.breakersoft.plow.thrift.MatcherField; import com.breakersoft.plow.thrift.MatcherT; import com.breakersoft.plow.thrift.MatcherType; import com.breakersoft.plow.thrift.dao.ThriftMatcherDao; @Repository @Transactional(readOnly=true) public class ThriftMatcherDaoImpl extends AbstractDao implements ThriftMatcherDao { private static final String GET = "SELECT " + "matcher.pk_matcher, "+ "matcher.int_field,"+ "matcher.int_type,"+ "matcher.int_order,"+ "matcher.str_value " + "FROM " + "plow.matcher "; public static final RowMapper<MatcherT> MAPPER = new RowMapper<MatcherT>() { @Override public MatcherT mapRow(ResultSet rs, int rowNum) throws SQLException { MatcherT matcher = new MatcherT(); matcher.id = rs.getString("pk_matcher"); matcher.field = MatcherField.findByValue(rs.getInt("int_field")); matcher.type = MatcherType.findByValue(rs.getInt("int_type")); matcher.value = rs.getString("str_value"); return matcher; } }; @Override public List<MatcherT> getAll(Filter filter) { return jdbc.query(GET + " WHERE pk_filter=? ORDER BY int_order ASC", MAPPER, filter.getFilterId()); } @Override public MatcherT get(UUID id) { return jdbc.queryForObject(GET + " WHERE pk_matcher=?", MAPPER, id); } }
29.438596
83
0.755662
2ef3deae87cebbb1df55716aa34333cd891188fb
1,732
/** * Copyright (c) 2006, 2007, 2008 Marwan Abi-Antoun, Jonathan Aldrich, Nels E. Beckman, * Kevin Bierhoff, David Dickey, Ciera Jaspan, Thomas LaToza, Gabriel Zenarosa, and others. * * This file is part of Crystal. * * Crystal 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 of the License, or * (at your option) any later version. * * Crystal is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Crystal. If not, see <http://www.gnu.org/licenses/>. */ package edu.cmu.cs.crystal; import java.util.List; import java.util.Set; import org.eclipse.jdt.core.ICompilationUnit; /** * A command to run certain crystal analyses on certain files. Should not require * any internal knowledge of Crystal so that it can be created by Eclipse buttons * and menus. Internally, Crystal will translate a command to run analyses into * actual jobs. * * @author Nels E. Beckman */ public interface IRunCrystalCommand { /** * A set of analyses to run. Could be run in any order. */ public Set<String> analyses(); /** * A list of compilation units that the analyses will be run on. Will * be run in order. */ public List<ICompilationUnit> compilationUnits(); /** * The reporter to be used. */ public IAnalysisReporter reporter(); }
32.074074
92
0.703811
14799a07e68d7262a6716c22c597bea865505b20
14,472
// RobotLadder.java package igx.bots.arena; import igx.bots.*; import java.util.*; import java.io.*; public class RobotLadder { public static final String BOT_FILE_NAME = "botWars.txt"; public static final String TABLE_NAME = "robotRankings.html"; public static final String TABLE_HEADER = "robotHeader.html"; public static final String TABLE_MIDDER = "robotMidder.html"; public static final String TABLE_FOOTER = "robotFooter.html"; public static final int NUMBER_OF_EACH_BOT = 1; static Robot[] robotList; static int maxPlayers = 2; static int segments = 800; static int numRobots; static int numberOfGames = 0; static long seed; public static void complain(String complaint) { System.out.println(complaint); System.out.println("Usage:"); System.out.println(" java igx.bots.arena.RobotLadder players segments"); System.out.println("(Where 'players' is the number of players in the largest game)"); System.out.println("(and 'segments' is the number of segments per game)"); System.exit(1); } public static void main(String[] args) { System.out.println("Welcome to the intergalactics robot ladder..."); if (args.length != 2) { complain("2 args required."); } try { maxPlayers = Integer.parseInt(args[0]); } catch (NumberFormatException e) { complain("Integer expected."); } try { segments = Integer.parseInt(args[1]); } catch (NumberFormatException e) { complain("Integer expected."); } robotList = generateBotList(); numRobots = robotList.length; if (numRobots < maxPlayers) { complain("You need enough bots to fill the biggest game!"); } while (true) { for (int i = 2; i <= maxPlayers; i++) { int[] spot = new int[i]; for (int j = 0; j < i; j++) { spot[j] = -1; } setSeed(); playGames(spot, 0, 0, 0); } System.out.println("Total games played: " + numberOfGames); for (int i = 0; i < numRobots; i++) { System.out.println(robotList[i].getName() + " - " + robotList[i].makeStats(numberOfGames)); } makeTable(); } //System.out.println(robotList[i].getName() + " - " + robotList[i].totalWins + " wins."); } static void setSeed() { System.out.println("New Game"); seed = System.currentTimeMillis(); } // Gets bot class and makes sure it's cool... protected static Class getBotClass(String className) { Class robotClass = null; try { robotClass = Class.forName(className); // Try to instantiate as a robot Bot robot = (Bot) robotClass.newInstance(); } catch (ClassNotFoundException e) { complain("'bot class name: " + className + " not found."); } catch (ClassCastException e) { complain("This... thing... is not a 'bot: " + className + "!"); } catch (Exception e) { complain("Problem with your 'bot, " + className + ". " + e + "."); } return robotClass; } protected static Robot[] generateBotList() { BufferedReader br; Vector bots = new Vector(); int numBots = 0; try { br = new BufferedReader(new FileReader(BOT_FILE_NAME)); String botType = br.readLine(); String bot = br.readLine(); while (bot != null) { Class botClass = getBotClass(bot); Bot botInstance = null; try { botInstance = (Bot) botClass.newInstance(); } catch (Exception f) { return new Robot[0]; } int n = botInstance.numberOfBots(); if (n >= NUMBER_OF_EACH_BOT) { n = NUMBER_OF_EACH_BOT; } for (int i = 0; i < n; i++) { String botName = botInstance.createName(i); Robot robot = new Robot(botName, botType, botClass, numBots++, i, maxPlayers); bots.addElement(robot); } botType = br.readLine(); bot = br.readLine(); } br.close(); } catch (IOException e) { System.out.println("Problem with 'bot file: " + e); return new Robot[0]; } int n = bots.size(); Robot[] robotList = new Robot[n]; for (int i = 0; i < n; i++) { Robot r = (Robot) (bots.elementAt(i)); r.setNumberOfRobots(n); robotList[i] = r; } return robotList; } static void playGames(int[] spot, int p, int skips, int players) { // System.out.println("Spot: " + spot + " P: " + p + " Skips: " + skips + " Players: " + players); int n = spot.length; if (players == n) { playGame(spot); return; } for (int i = 0; i < n; i++) { if (spot[i] == -1) { spot[i] = p; playGames(spot, p + 1, skips, players + 1); spot[i] = -1; } } if (skips < (numRobots - n)) { playGames(spot, p + 1, skips + 1, players); } } static void playGame(int[] spot) { numberOfGames++; int n = spot.length; for (int i = 0; i < n; i++) { System.out.print(" " + spot[i]); } RobotArena arena = new RobotArena(); for (int i = 0; i < n; i++) { arena.addRobot(robotList[spot[i]].getBotClass(), robotList[spot[i]].getSkill()); } arena.seed = seed; arena.numSegments = segments; arena.reportEvents = false; Statistics stats = arena.runGame(); int winner = spot[stats.winner]; System.out.println(" winner: " + winner); for (int i = 0; i < n; i++) { robotList[spot[i]].playedGame(n); if (spot[i] != winner) { robotList[winner].beat(spot[i]); } } robotList[winner].wonGame(n); // GC Runtime.getRuntime().gc(); } public static void setRankings() { for (int i = 0; i < numRobots; i++) { int rank = 1; for (int o = 0; o < numRobots; o++) { if (robotList[o].totalWins > robotList[i].totalWins) { rank += 1; } } robotList[i].rank = rank; } } public static final String DATA_START = "<TD ALIGN=\"center\"><FONT SIZE=-1 FACE=\"Verdana, Helvetica\">"; public static final String DATA_STOP = "</FONT></TD>"; public static final String BOLD_DATA_START = "<TD ALIGN=\"center\"><FONT SIZE=-1 COLOR=\"#FFCF51\" FACE=\"Verdana, Helvetica\">"; public static final String BOT_DATA_START = "<TD ALIGN=\"center\"><FONT SIZE=-1 COLOR=\"#FFFFFF\" FACE=\"Verdana, Helvetica\">"; public static String perCent(int wins, int max) { return new Integer(wins * 100 / max).toString(); } public static void makeTable() { BufferedWriter output; BufferedReader input; setRankings(); try { output = new BufferedWriter(new FileWriter(TABLE_NAME)); input = new BufferedReader(new FileReader(TABLE_HEADER)); String line = "<!-- Machine Generated Rankings File -->"; do { output.write(line); output.newLine(); line = input.readLine(); } while (line != null); input.close(); // Rowspan of game size % output.write("<TD ALIGN=\"center\" COLSPAN=" + (maxPlayers - 1) + "><FONT SIZE=-1 COLOR=\"#FFFFFF\" FACE=\"Verdana, Helvetica\">"); output.newLine(); output.write("Game Size %"); output.newLine(); output.write("</FONT></TD>"); output.newLine(); // Write out vertical bot columns for (int i = 0; i < numRobots; i++) { output.write(" <TD BGCOLOR=\"#202020\" ALIGN=\"center\" VALIGN=\"bottom\" ROWSPAN=2><FONT SIZE=-1 COLOR=\"#FFFFFF\" FACE=\"Verdana, Helvetica\">"); output.newLine(); String name = robotList[i].getName(); for (int j = 0; j < name.length(); j++) { output.write("" + name.charAt(j) + "<BR>"); } output.write("</FONT></TD>"); output.newLine(); } // Write out middle part input = new BufferedReader(new FileReader(TABLE_MIDDER)); line = "<!-- Middle -->"; do { output.write(line); output.newLine(); line = input.readLine(); } while (line != null); input.close(); // Write out column for each game size for (int i = 2; i <= maxPlayers; i++) { output.write(" <TD VALIGN=\"bottom\" ALIGN=\"center\"><FONT SIZE=-1 COLOR=\"#FFFFFF\" FACE=\"Verdana, Helvetica\">"); output.newLine(); output.write("" + i); output.newLine(); output.write("</FONT></TD>"); output.newLine(); } output.write("</TR>"); output.newLine(); // Write out rankings for each robot int i = 0; while (i < numRobots) { String type = robotList[i].getType(); // Find bots with same type int k = i; while ((k < numRobots) && (robotList[k].getType().equals(type))) { k++; } // Write Bot class data output.write("<TR BGCOLOR=\"#202020\">"); output.newLine(); output.write("<TD ALIGN=\"center\" ROWSPAN=" + (k - i) + "><FONT SIZE=-1 FACE=\"Verdana, Helvetica\">"); output.newLine(); output.write(type); output.newLine(); output.write("</FONT></TD>"); output.newLine(); for (int j = i; j < k; j++) { // If it isn't the first bot of this type, then start a new row. if (j > i) { output.write("</TR>"); output.newLine(); output.write("<TR BGCOLOR=\"#202020\">"); output.newLine(); } Robot r = robotList[j]; // Write name if (r.rank == 1) { output.write(BOLD_DATA_START); } else { output.write(BOT_DATA_START); } output.write(r.getName()); output.write(DATA_STOP); output.newLine(); // Write rank if (r.rank == 1) { output.write(BOLD_DATA_START); } else { output.write(DATA_START); } output.write(new Integer(r.rank).toString()); output.write(DATA_STOP); output.newLine(); // Write win per cent if (r.rank == 1) { output.write(BOLD_DATA_START); } else { output.write(DATA_START); } output.write(perCent(r.totalWins, r.numberOfGames)); output.write(DATA_STOP); output.newLine(); // Write out per cents for game sizes for (int l = 2; l <= maxPlayers; l++) { output.write(DATA_START); output.write(perCent(r.wins[l - 2], r.numGames[l - 2])); output.write(DATA_STOP); output.newLine(); } // Write out per cents against each robot for (int l = 0; l < numRobots; l++) { output.write(DATA_START); if (j == l) { output.write("X"); } else { output.write(new Integer(r.robotWins[l] * 100 / (r.robotWins[l] + robotList[l].robotWins[j])).toString()); } output.write(DATA_STOP); output.newLine(); } } output.write("</TR>"); output.newLine(); i = k; } // Write bottom of table output.write("<TR BGCOLOR=\"#464646\">"); output.newLine(); for (int l = 0; l < 4 + (maxPlayers - 1) + numRobots; l++) { output.write(DATA_START + "&nbsp;" + DATA_STOP); } // Write stats stuff... output.write("</TR>"); output.write("</TABLE>"); output.write("<!-- Stats section -->"); output.write("<TABLE WIDTH=550>"); output.write("<TR><TD>"); output.write("<FONT SIZE=-1 FACE=\"Verdana, Helvetica\">"); output.newLine(); output.write("<P>"); output.write("Last Updated: <B>" + new Date() + "</B> "); output.newLine(); output.write("<BR>Total Games Played: <B>" + numberOfGames + "</B> "); output.newLine(); output.write("<BR>Turns per Game: <B>" + segments / 20 + "</B>"); // Write footer info input = new BufferedReader(new FileReader(TABLE_FOOTER)); line = "<!-- Footer -->"; do { output.write(line); output.newLine(); line = input.readLine(); } while (line != null); input.close(); output.flush(); output.close(); } catch (IOException e) { } } }
39.219512
166
0.463032
10176ef99df408cdab927005bef56e6058fb250f
1,335
package com.electronclass.pda.mvp.entity; public class ClassInfo { String className; String classId;//班级信息 String yearId; //年级信息 String yearName; String facultyId;//学部信息 String facultyName; String schoolId; public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public String getClassId() { return classId; } public void setClassId(String classId) { this.classId = classId; } public String getYearId() { return yearId; } public void setYearId(String yearId) { this.yearId = yearId; } public String getYearName() { return yearName; } public void setYearName(String yearName) { this.yearName = yearName; } public String getFacultyId() { return facultyId; } public void setFacultyId(String facultyId) { this.facultyId = facultyId; } public String getFacultyName() { return facultyName; } public void setFacultyName(String facultyName) { this.facultyName = facultyName; } public String getSchoolId() { return schoolId; } public void setSchoolId(String schoolId) { this.schoolId = schoolId; } }
17.8
52
0.616479
a2ba8bf33cf9152a00501a7e9c067ca5f9ab3af8
1,678
package junit; import static org.junit.Assert.assertEquals; import java.lang.reflect.Method; import java.math.BigDecimal; import java.math.RoundingMode; import org.junit.Test; import xpeppers.interview.shoppingbasket.ShoppingBasketListBD; import xpeppers.interview.strategy.ExemptTaxStrategy; import xpeppers.interview.strategy.Item; public class ShoppingBasketListBDTest { @Test public void roundingTest() throws Exception, SecurityException { // This test uses Java Reflection. ShoppingBasket instance ShoppingBasketListBD s = new ShoppingBasketListBD(); // I want to test the rounding method. It is called "round" in the ShoppingBasketListBD class. Method method = s.getClass().getDeclaredMethod("round", double.class); method.setAccessible(true); //Let's try some values BigDecimal [] bdv = new BigDecimal [101]; double offset = 1.00; BigDecimal currentCent = new BigDecimal(0.05).setScale(2, RoundingMode.HALF_UP); bdv[0] = new BigDecimal(offset); for(int i = 1; i<bdv.length; i++){ bdv[i] = new BigDecimal(offset + (i / 100D)).setScale(2,RoundingMode.HALF_UP); BigDecimal rounded = (BigDecimal) method.invoke(s, bdv[i].doubleValue()); assertEquals(rounded.doubleValue(),currentCent.doubleValue(),offset); if(i % 5 == 0){ currentCent = currentCent.add(new BigDecimal(0.05).setScale(2, RoundingMode.HALF_UP)); } } } public void sizeTest(){ ShoppingBasketListBD s = new ShoppingBasketListBD(); Item a = new Item("test",1, new ExemptTaxStrategy()); Item b = new Item("test2",2, new ExemptTaxStrategy()); s.addOne(a); s.addOne(b); assertEquals(s.howManyDifferentItems(),2,0); } }
29.964286
96
0.727056
e51e6750ce92bb0079d789d643642a500ea748a8
421
package com.test.examine.entity; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import javax.validation.constraints.NotNull; import java.io.Serializable; @Data public class Lab implements Serializable { @JsonProperty(value = "labid") @NotNull private int labid; @JsonProperty(value = "capacity") private int capacity; private String id; private int total; }
17.541667
53
0.736342
32870dedd32f2969ec673ea5cc1a91b72403bd65
1,448
package org.gridgain.examples.compute.masterleave; import java.util.Arrays; import java.util.HashMap; import org.apache.ignite.Ignition; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.spi.checkpoint.cache.CacheCheckpointSpi; import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi; import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder; /** * Starts a server node with specific configuration. * * Refer to {@link ComputeMasterLeaveAwareExample} for details. */ public class ComputeLeaveAwareNodeStartup { /** * Executes example. * * @param args Command line arguments, none required. */ public static void main(String[] args) { IgniteConfiguration cfg = new IgniteConfiguration(); HashMap<String, Object> attrs = new HashMap<>(); attrs.put("checkpoint_key", "slave_node"); cfg.setUserAttributes(attrs); TcpDiscoveryVmIpFinder ipFinder = new TcpDiscoveryVmIpFinder(); ipFinder.setAddresses(Arrays.asList("127.0.0.1:47500..47509")); cfg.setDiscoverySpi(new TcpDiscoverySpi().setIpFinder(ipFinder)); // Configuring checkpoints spi. CacheCheckpointSpi checkpointSpi = new CacheCheckpointSpi(); checkpointSpi.setCacheName("checkpoints"); // Overriding default checkpoints SPI cfg.setCheckpointSpi(checkpointSpi); Ignition.start(cfg); } }
31.478261
78
0.722376
9b3233efec186b0a535ca51c03eccf42f1c7668c
3,451
package cn.com.ctrl.yjjy.project.control.plan.service; import java.util.List; import cn.com.ctrl.yjjy.common.utils.StringUtils; import cn.com.ctrl.yjjy.project.basis.host.domain.Shebei; import cn.com.ctrl.yjjy.project.basis.host.mapper.ShebeiMapper; import cn.com.ctrl.yjjy.project.tool.map.domain.Dijsktra; import cn.com.ctrl.yjjy.project.tool.map.mapper.DijsktraMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import lombok.Data; import lombok.extern.log4j.Log4j2; import cn.com.ctrl.yjjy.project.control.plan.mapper.PointMapper; import cn.com.ctrl.yjjy.project.control.plan.domain.Point; import cn.com.ctrl.yjjy.common.support.Convert; import org.springframework.transaction.annotation.Transactional; /** * 百度地图点 服务层实现 * * @author zzmh * @date 2019-01-05 */ @Data @Log4j2 @Service @Transactional public class PointServiceImpl implements IPointService { @Autowired private PointMapper pointMapper; @Autowired private ShebeiMapper shebeiMapper; @Autowired private DijsktraMapper dijsktraMapper; /** * 查询百度地图点信息 * * @param id 百度地图点ID * @return 百度地图点信息 */ @Override public Point selectPointById(String id) { return pointMapper.selectPointById(id); } /** * 查询百度地图点列表 * * @param point 百度地图点信息 * @return 百度地图点集合 */ @Override public List<Point> selectPointList(Point point) { return pointMapper.selectPointList(point); } /** * 新增百度地图点 * * @param point 百度地图点信息 * @return 结果 */ @Override public int insertPoint(Point point) { if("1".equals(point.getType())){ Shebei shebei = shebeiMapper.selectShebeiById(point.getId()); point.setPointX(shebei.getPointX()); point.setPointY(shebei.getPointY()); } else { point.setId(StringUtils.gainGUID()); } Dijsktra dijsktra = new Dijsktra(); //取weight_num最大值加1 String weightNum = dijsktraMapper.selectMaxWeightNum(); if(null == weightNum || "".equals(weightNum)){ dijsktra.setWeightNum("1"); }else{ dijsktra.setWeightNum(String.valueOf(Integer.valueOf(weightNum)+1)); } dijsktra.setId(StringUtils.gainGUID()); dijsktra.setPointId(point.getId()); dijsktra.setOpstatus("1"); dijsktra.setLarr(dijsktra.getWeightNum()); dijsktra.setAlarr(dijsktra.getWeightNum()); dijsktra.setPointName(dijsktra.getWeightNum()+"号标点"); dijsktraMapper.insertDijsktra(dijsktra); return pointMapper.insertPoint(point); } /** * 修改百度地图点 * * @param point 百度地图点信息 * @return 结果 */ @Override public int updatePoint(Point point) { return pointMapper.updatePoint(point); } /** * 删除百度地图点对象 * * @param ids 需要删除的数据ID * @return 结果 */ @Override public int deletePointByIds(String ids) { Point point = pointMapper.selectPointById(ids); Dijsktra d = new Dijsktra(); d.setPointId(point.getId()); Dijsktra dijsktra = dijsktraMapper.selectDijsktra(d); if(dijsktra.getLarr().split(",").length>1){ return 0; }else{ dijsktraMapper.deleteDijsktraById(dijsktra.getId()); return pointMapper.deletePointByIds(Convert.toStrArray(ids)); } } }
29.495726
80
0.652854
8c4fdeea566dc1bc8eb9408684430c15bd8afeaf
1,550
/* * ****************************************************************************** * * * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * See the NOTICE file distributed with this work for additional * * information regarding copyright ownership. * * 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. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package org.nd4j.linalg.dataset.api.iterator.enums; public enum InequalityHandling { /** * Parallel iterator will stop everything once one of producers runs out of data */ STOP_EVERYONE, /** * Parallel iterator will keep returning true on hasNext(), but next() will return null instead of DataSet */ PASS_NULL, /** * Parallel iterator will silently reset underlying producer */ RESET, /** * Parallel iterator will ignore this producer, and will use other producers. * * PLEASE NOTE: This option will invoke cross-device relocation in multi-device systems. */ RELOCATE, }
33.695652
110
0.616129
ede0a60c264d4cc15a40de046b153041e7585aeb
784
/* * Created on 18/04/2005 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package genesisRPGCreator.sysdeps; import java.io.IOException; import java.io.OutputStream; import genesisRPGCreator.Project; /** * @author wxp * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class ProjectBuilder { protected byte[] rawdata; /** * */ public ProjectBuilder() { super(); } public void translateProject(Project proj) throws Exception { rawdata = null; } public byte[] getBytes() { return rawdata; } public void savetoStream(OutputStream os) throws IOException { os.write(rawdata); } }
18.666667
68
0.704082
27ff4cfd54efef64712c084b7b689c0cf77ccbf6
708
package net.spizzer.aoc2019.helpers.maze.intcode; import net.spizzer.aoc2019.common.Printable; import net.spizzer.aoc2019.common.ValueBase; public enum IntcodeMazeTile implements ValueBase<Integer>, Printable { WALL(0, '█'), EMPTY(1, ' '), TARGET(2, 'X'); private final int value; private final char print; IntcodeMazeTile(int value, char print) { this.value = value; this.print = print; } @Override public Integer getValue() { return value; } @Override public char getPrintChar() { return print; } public static IntcodeMazeTile fromValue(int value) { return ValueBase.fromValue(values(), value); } }
21.454545
70
0.646893
c591e86f835ae01a466239ba34606ce2df03cfa7
843
package com.stm.regioncategory.base.interactor; import com.stm.common.dao.Market; import com.stm.common.dao.MarketCategory; import com.stm.common.dao.RegionCategory; import java.util.ArrayList; import java.util.List; /** * Created by ㅇㅇ on 2017-06-16. */ public interface RegionCategoryInteractor { void setMarketRepository(); void setMarketCategoryRepository(); void setRegionCategoryRepository(); RegionCategory getRegionCategory(); void setRegionCategory(RegionCategory regionCategory); List<Market> getMarkets(); void getMarketCategoryList(); void getRegionCategoryById(long regionCategoryId); void setMarkets(List<Market> markets); void getMarketListById(long regionCategoryId); void getMarketListByIdAndMarketCategoryId(long regionCategoryId, MarketCategory marketCategory); }
22.783784
100
0.775801
b7e3c73a85a807b59ce5914c52429fa20e49b955
217
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. /** * Package containing credentials used by Azure Storage services. */ package com.azure.storage.common.credentials;
27.125
65
0.764977
9bc04dabff9218801eec274ec6681724c9d7bf94
2,835
package net.minecraft.util.profiling.jfr; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import javax.annotation.Nullable; import net.minecraft.server.Bootstrap; import net.minecraft.util.profiling.jfr.parse.JfrStatsParser; import net.minecraft.util.profiling.jfr.parse.JfrStatsResult; import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.core.LifeCycle; import org.apache.logging.log4j.spi.LoggerContext; import org.apache.logging.log4j.util.Supplier; public class SummaryReporter { private static final Logger LOGGER = LogManager.getLogger(); private final Runnable onDeregistration; protected SummaryReporter(Runnable p_185398_) { this.onDeregistration = p_185398_; } public void recordingStopped(@Nullable Path p_185401_) { if (p_185401_ != null) { this.onDeregistration.run(); infoWithFallback(() -> { return "Dumped flight recorder profiling to " + p_185401_; }); JfrStatsResult jfrstatsresult; try { jfrstatsresult = JfrStatsParser.parse(p_185401_); } catch (Throwable throwable1) { warnWithFallback(() -> { return "Failed to parse JFR recording"; }, throwable1); return; } try { infoWithFallback(jfrstatsresult::asJson); Path path = p_185401_.resolveSibling("jfr-report-" + StringUtils.substringBefore(p_185401_.getFileName().toString(), ".jfr") + ".json"); Files.writeString(path, jfrstatsresult.asJson(), StandardOpenOption.CREATE); infoWithFallback(() -> { return "Dumped recording summary to " + path; }); } catch (Throwable throwable) { warnWithFallback(() -> { return "Failed to output JFR report"; }, throwable); } } } private static void infoWithFallback(Supplier<String> p_185403_) { if (log4jIsActive()) { LOGGER.info(p_185403_); } else { Bootstrap.realStdoutPrintln(p_185403_.get()); } } private static void warnWithFallback(Supplier<String> p_185405_, Throwable p_185406_) { if (log4jIsActive()) { LOGGER.warn(p_185405_, p_185406_); } else { Bootstrap.realStdoutPrintln(p_185405_.get()); p_185406_.printStackTrace(Bootstrap.STDOUT); } } private static boolean log4jIsActive() { LoggerContext loggercontext = LogManager.getContext(); if (loggercontext instanceof LifeCycle) { LifeCycle lifecycle = (LifeCycle)loggercontext; return !lifecycle.isStopped(); } else { return true; } } }
32.965116
148
0.65291
dd1b14cf294b21d44b30b6dd2b7ea79d0a966b02
892
package com.zxg.FingerOffer; /** * 二维数组查找 * 在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序, * 每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数, * 判断数组中是否含有该整数。 */ public class practice_1 { public static void main(String[] args) { int[][] arrs = new int[][]{{1, 2, 8}, {2, 4, 9}, {4, 7, 10}, {6, 8, 11}}; System.out.println("is find:" + Find(arrs, 10)); } public static boolean Find(int[][] arrs, int target) { int rowLen = arrs.length; int columnLen = arrs[0].length; int i = rowLen - 1; int j = 0; while (i >= 0 && j < columnLen) { if (arrs[i][j] > target) { i--; } else if (arrs[i][j] < target) { j++; } else { System.out.println("find target:" + arrs[i][j]); return true; } } return false; } }
26.235294
81
0.485426
a665207130951a186bbecfed0ef8ed960fcdb700
768
package org.folio.rest.validate; import java.io.IOException; import org.folio.rest.tools.utils.ObjectMapperTool; import com.fasterxml.jackson.core.JsonParseException; /** * Utility class for validating JSON. */ public class JsonValidator { private JsonValidator() { throw new UnsupportedOperationException("Cannot instantiate utility class."); } /** * @param entity String to parse as JSON * @return True if entity is a String representation of a JSON array, false otherwise. * @throws JsonParseException if entity cannot be parsed as JSON * @throws IOException on missing input */ public static boolean isValidJsonArray(String entity) throws IOException { return ObjectMapperTool.getMapper().readTree(entity).isArray(); } }
28.444444
88
0.75
bfb4e576c8d8b8c3355e8bf33462b2964ea585b5
1,413
package helpers.collections; import java.util.Collection; import java.util.Iterator; public class DummyCollection<E> implements Collection<E> { @Override public int size() { return 0; } @Override public boolean isEmpty() { return true; } @Override public boolean contains(Object object) { return false; } @Override public Iterator<E> iterator() { return DummyIterator.create(this); } @Override public Object[] toArray() { return new Object[0]; } @SuppressWarnings("unchecked") @Override public <T> T[] toArray(T[] array) { return (T[])new Object[0]; } @Override public boolean addAll(Collection<? extends E> collection) { throw new UnsupportedOperationException("This is a dummy collection which can not contain anything"); } @Override public boolean add(E element) { throw new UnsupportedOperationException("This is a dummy collection which can not contain anything"); } @Override public boolean remove(Object object) { return false; } @Override public boolean containsAll(Collection<?> collection) { return false; } @Override public boolean removeAll(Collection<?> collection) { return false; } @Override public boolean retainAll(Collection<?> c) { return false; } @Override public void clear() { } }
19.901408
106
0.648974
e39e1523cee1683be3ed22df11cf67c5792c80c6
2,400
/** * Copyright (C) Cloudera, Inc. 2019 */ package com.cloudera.training.kafka.solution; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; import org.apache.kafka.common.serialization.StringDeserializer; import java.util.Arrays; import java.util.Properties; public class SimpleConsumer { public static void main(String[] args) { String bootstrapServers = args[0]; String topic = args[1]; String consumerGroupId = args[2]; // Set up Java properties Properties props = new Properties(); // This should point to at least one broker. Some communication // will occur to find the controller. Adding more brokers will // help in case of host failure or broker failure. props.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers); // groupId is mandatory for consumers, starting with Kafka 0.9.0.x. // You can refer to this JIRA: https://issues.apache.org/jira/browse/KAFKA-2648 props.put(ConsumerConfig.GROUP_ID_CONFIG, consumerGroupId); // Required properties to process records props.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); props.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); // Required properties for Kerberos // props.setProperty("security.protocol", "SASL_PLAINTEXT"); // props.setProperty("sasl.kerberos.service.name", "kafka"); try (KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props)) { // List of topics to subscribe to consumer.subscribe(Arrays.asList(topic)); while (true) { ConsumerRecords<String, String> records = consumer.poll(100); for (ConsumerRecord<String, String> record : records) { System.out.printf("offset = %d, partition = %d, key = %s, value = %s%n", record.offset(), record.partition(), record.key(), record.value()); } } } catch (Exception e) { e.printStackTrace(); } } }
38.709677
95
0.655
584ce0e905869ec972e79316461cc3814a4f8585
229
package com.codetaylor.mc.artisanworktables.modules.tools.material; public class CustomMaterialValidationException extends Exception { public CustomMaterialValidationException(String message) { super(message); } }
20.818182
67
0.799127
9efd1723e60620dc079c3fc3fd4b96b8c32e49c3
519
package sk.moravcik.kristian.gl1.hw1; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner reader = new Scanner(System.in); System.out.println("This program prints out the sum of two numbers entered by user."); System.out.print("Enter first number: "); int i = reader.nextInt(); System.out.print("Enter second number: "); int j = reader.nextInt(); System.out.printf("Sum: %d", i+j); reader.close(); } }
30.529412
94
0.620424
75d21a918c21fcc776795ecf07c93c4b961b6b64
778
package com.insano10.puzzlers.puzzles.codility.countingElements; import org.assertj.core.api.Assertions; import org.junit.Test; public class FrogRiverOneTest { @Test public void shouldFindTheFirstIndexAtWhichAllRequiredValuesHaveBeenSeen() throws Exception { int[] input = new int[]{1, 3, 1, 4, 2, 3, 5, 4}; FrogRiverOne frogRiverOne = new FrogRiverOne(); Assertions.assertThat(frogRiverOne.solution(5, input)).isEqualTo(6); } @Test public void shouldReturnMinusOneWhenTheRequiredValuesCannotBeFound() throws Exception { int[] input = new int[]{1, 3, 1, 4, 2, 3, 5, 4}; FrogRiverOne frogRiverOne = new FrogRiverOne(); Assertions.assertThat(frogRiverOne.solution(6, input)).isEqualTo(-1); } }
28.814815
94
0.694087
34086107939ad966dffab6484eca024a5cc1cbc9
224
package com.inner.demo3; /** * @author 许大仙 * @version 1.0 * @since 2021-09-13 20:23 */ public class Test { public static void main(String[] args) { Outer outer = new Outer(); outer.method(); } }
16
44
0.575893
b6cf183f700ff7bf2bbbc3d69137b5d8a4e09fc2
11,782
package com.packt.masteringopencv4.opencvarucoar; import android.Manifest; import android.app.Activity; import android.content.Context; import android.content.pm.PackageManager; import android.graphics.ImageFormat; 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.ImageReader; import android.os.Handler; import android.os.HandlerThread; import android.support.annotation.Nullable; import android.util.Log; import android.util.Size; import android.view.Surface; import java.util.ArrayList; import java.util.Arrays; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; public class CameraHelper { private static final String LOGTAG = "CameraHepler"; public static final int REQUEST_PERMISSION_CODE = 99; private CameraDevice mCameraDevice; private CameraCaptureSession mCaptureSession; private CaptureRequest.Builder mPreviewRequestBuilder; private String mCameraID = null; private Size mPreviewSize = new Size(-1, -1); private HandlerThread mBackgroundThread; private Handler mBackgroundHandler; private Semaphore mCameraOpenCloseLock = new Semaphore(1); private ImageReader mImageReader; private CameraHandler mHandler; private Activity mContext; @Nullable private Surface mPreviewSurface; private boolean mCameraOpen = false; public CameraHelper(Activity activity) { mContext = activity; } public void startBackgroundThread() { Log.i(LOGTAG, "startBackgroundThread"); stopBackgroundThread(); mBackgroundThread = new HandlerThread("CameraBackground"); mBackgroundThread.start(); mBackgroundHandler = new Handler(mBackgroundThread.getLooper()); } public void stopBackgroundThread() { Log.i(LOGTAG, "stopBackgroundThread"); if(mBackgroundThread == null) return; mBackgroundThread.quitSafely(); try { mBackgroundThread.join(); mBackgroundThread = null; mBackgroundHandler = null; } catch (InterruptedException e) { Log.e(LOGTAG, "stopBackgroundThread"); } } private final CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() { @Override public void onOpened(CameraDevice cameraDevice) { Log.d(LOGTAG, "CameraDevice.StateCallback: onOpened"); mCameraDevice = cameraDevice; mCameraOpenCloseLock.release(); mCameraOpen = true; createCameraPreviewSession(mPreviewSurface); } @Override public void onDisconnected(CameraDevice cameraDevice) { cameraDevice.close(); mCameraDevice = null; mCameraOpenCloseLock.release(); } @Override public void onError(CameraDevice cameraDevice, int error) { cameraDevice.close(); mCameraDevice = null; mCameraOpenCloseLock.release(); } }; protected void closeCamera() { Log.i(LOGTAG, "closeCamera"); try { mCameraOpenCloseLock.acquire(); if (null != mCaptureSession) { mCaptureSession.close(); mCaptureSession = null; } if (null != mCameraDevice) { mCameraDevice.close(); mCameraDevice = null; } } catch (InterruptedException e) { throw new RuntimeException("Interrupted while trying to lock camera closing.", e); } finally { mCameraOpenCloseLock.release(); } stopBackgroundThread(); mCameraOpen = false; } protected void openCamera(@Nullable Surface previewSurface) { Log.i(LOGTAG, "openCamera"); startBackgroundThread(); mPreviewSurface = previewSurface; if (mContext.checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { mContext.requestPermissions(new String[] { Manifest.permission.CAMERA }, REQUEST_PERMISSION_CODE); return; } CameraManager manager = (CameraManager) mContext.getSystemService(Context.CAMERA_SERVICE); try { String camList[] = manager.getCameraIdList(); if(camList.length == 0) { Log.e(LOGTAG, "Error: camera isn't detected."); return; } mCameraID = camList[0]; for (String cameraID : camList) { CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraID); if(characteristics.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_BACK) { mCameraID = cameraID; break; } } if(mCameraID != null) { if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) { throw new RuntimeException( "Time out waiting to lock camera opening."); } Log.i(LOGTAG, "Opening camera: " + mCameraID); CameraCharacteristics characteristics = manager.getCameraCharacteristics(mCameraID); int sensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION); Log.i(LOGTAG, "camera sensorOrientation " + sensorOrientation); manager.openCamera(mCameraID, mStateCallback, mBackgroundHandler); } } catch (CameraAccessException e) { Log.e(LOGTAG, "OpenCamera - Camera Access Exception"); } catch (IllegalArgumentException e) { Log.e(LOGTAG, "OpenCamera - Illegal Argument Exception"); } catch (SecurityException e) { Log.e(LOGTAG, "OpenCamera - Security Exception", e); } catch (InterruptedException e) { Log.e(LOGTAG, "OpenCamera - Interrupted Exception"); } } private void createCameraPreviewSession(@Nullable Surface previewSurface) { cacPreviewSize(1280, 720); int w = mPreviewSize.getWidth(); int h = mPreviewSize.getHeight(); Log.i(LOGTAG, "createCameraPreviewSession("+w+"x"+h+")"); if (w < 0 || h < 0) { Log.e(LOGTAG, "Bad preview size"); return; } try { mCameraOpenCloseLock.acquire(); if (null == mCameraDevice) { mCameraOpenCloseLock.release(); Log.e(LOGTAG, "createCameraPreviewSession: camera isn't opened"); return; } if (null != mCaptureSession) { mCameraOpenCloseLock.release(); Log.e(LOGTAG, "createCameraPreviewSession: mCaptureSession is already started"); return; } mImageReader = ImageReader.newInstance(mPreviewSize.getWidth(), mPreviewSize.getHeight(), ImageFormat.YUV_420_888, 2); mImageReader.setOnImageAvailableListener(mHandler, mBackgroundHandler); mPreviewRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW); mPreviewRequestBuilder.addTarget(mImageReader.getSurface()); ArrayList<Surface> surfaceList = new ArrayList<>(Arrays.asList(mImageReader.getSurface())); if (previewSurface != null) { mPreviewRequestBuilder.addTarget(previewSurface); surfaceList.add(previewSurface); } mCameraDevice.createCaptureSession(surfaceList, new CameraCaptureSession.StateCallback() { @Override public void onConfigured( CameraCaptureSession cameraCaptureSession) { mCaptureSession = cameraCaptureSession; try { mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE); mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON); mCaptureSession.setRepeatingRequest(mPreviewRequestBuilder.build(), null, mBackgroundHandler); Log.i(LOGTAG, "CameraPreviewSession has been started"); } catch (CameraAccessException e) { Log.e(LOGTAG, "createCaptureSession failed"); } mCameraOpenCloseLock.release(); mHandler.onCameraSetup(mPreviewSize); } @Override public void onConfigureFailed( CameraCaptureSession cameraCaptureSession) { Log.e(LOGTAG, "createCameraPreviewSession failed"); mCameraOpenCloseLock.release(); } }, mBackgroundHandler); } catch (CameraAccessException e) { Log.e(LOGTAG, "createCameraPreviewSession"); } catch (InterruptedException e) { throw new RuntimeException( "Interrupted while createCameraPreviewSession", e); } finally { //mCameraOpenCloseLock.release(); } } boolean cacPreviewSize(final int width, final int height) { Log.i(LOGTAG, "cacPreviewSize: "+width+"x"+height); if(mCameraID == null) { Log.e(LOGTAG, "Camera isn't initialized!"); return false; } CameraManager manager = (CameraManager) mContext.getSystemService(Context.CAMERA_SERVICE); try { CameraCharacteristics characteristics = manager.getCameraCharacteristics(mCameraID); StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); int bestWidth = 0, bestHeight = 0; float aspect = (float)width / height; for (Size psize : map.getOutputSizes(ImageFormat.YUV_420_888)) { int w = psize.getWidth(), h = psize.getHeight(); Log.d(LOGTAG, "trying size: "+w+"x"+h); if ( width >= w && height >= h && bestWidth <= w && bestHeight <= h && Math.abs(aspect - (float)w/h) < 0.2 ) { bestWidth = w; bestHeight = h; } } Log.i(LOGTAG, "best size: "+bestWidth+"x"+bestHeight); if( bestWidth == 0 || bestHeight == 0 || mPreviewSize.getWidth() == bestWidth && mPreviewSize.getHeight() == bestHeight ) return false; else { mPreviewSize = new Size(bestWidth, bestHeight); return true; } } catch (CameraAccessException e) { Log.e(LOGTAG, "cacPreviewSize - Camera Access Exception"); } catch (IllegalArgumentException e) { Log.e(LOGTAG, "cacPreviewSize - Illegal Argument Exception"); } catch (SecurityException e) { Log.e(LOGTAG, "cacPreviewSize - Security Exception"); } return false; } public void setCameraListener(CameraHandler hander) { mHandler = hander; } public boolean isCameraOpen() { return mCameraOpen; } }
40.909722
142
0.606943
8f9c27f2bec0288afea1688409845b74108e41bd
16,391
package ec.research.gp.pareto; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.Set; import java.util.Vector; import org.apache.log4j.PropertyConfigurator; import org.junit.BeforeClass; import org.junit.Test; import ec.research.gp.pareto.ParetoGP; import ec.research.gp.pareto.ParetoOperators; import ec.research.gp.pareto.ParetoGP.OBJECTIVES; import ec.research.gp.simple.problem.ProblemRunner; import ec.research.gp.simple.representation.Individual; import ec.research.gp.simple.util.Config; import ec.research.gp.simple.util.Context; /** * Tests the {@link ParetoOperators} for functionality. * */ public class ParetoOperatorsTest { private static Context context; /* * Individuals for making a pareto front smaller than the target population * size. All individuals aren't actually non-dominated here. This is just an * easy way to make it work. The first for each tag is non-dominated. */ private static final Object[][] SMALL_FRONT = { { 1.0, "A" }, { 0.4, "A" }, { 0.3, "A" }, { 0.2, "A" }, { 0.1, "A" }, { 0.09, "B" }, { 0.08, "B" }, { 0.07, "B" }, { 0.06, "C" }, { 0.05, "C" }, { 0.04, "D" } }; // Pareto front whose size is equal to the target population size private static final Object[][] EQUAL_FRONT = { { 1.0, "A" }, { 1.0, "A" }, { 1.0, "A" }, { 1.0, "A" }, { 0.5, "B" }, { 0.5, "B" }, { 0.5, "B" }, { 0.2, "C" }, { 0.2, "C" }, { 0.1, "D" } }; // Large pareto front (larger than target pop size) private static final Object[][] LARGE_FRONT = { { 1.0, "A" }, { 1.0, "A" }, { 1.0, "A" }, { 1.0, "A" }, { 0.5, "B" }, { 0.5, "B" }, { 0.5, "B" }, { 0.2, "C" }, { 0.2, "C" }, { 0.1, "D" }, { 0.1, "E" }, { 0.1, "F" } }; // Pareto front on the age/fitness objectives. private static final Object[][] AF_FRONT = { { 1.0, 10, "A" }, { 0.9, 9, "A" }, { 0.8, 8, "A" }, { 0.7, 7, "B" }, { 0.6, 6, "B" }, { 0.5, 5, "B" }, { 0.4, 4, "C" }, { 0.3, 3, "D" }, { 0.2, 2, "D" }, { 0.1, 1, "E" } }; @BeforeClass public static void setup() throws FileNotFoundException, IOException { // Make log4j be quiet! PropertyConfigurator.configure("log4j.properties.unittest"); // Setup the output directory so the test won't fail if it was deleted. ProblemRunner.checkDirs("testOutput"); Config config = new Config( "src/test/resources/paretoGPRegression.properties"); // Make sure config points to the test output directory config.setOutputDir("testOutput"); context = new Context(config); } /** * Tests that the global pareto front is created correctly for the small * test front. */ @Test public void testGlobalFrontSmall() { Vector<Individual> population = new Vector<Individual>(); int size = 10; for (Object[] items : SMALL_FRONT) { Individual ind = new Individual(); ind.setId(0); ind.setFitness((Double) items[0]); ind.setTag((String) items[1]); ind.setNumNodes(size); size++; population.add(ind); } Set<Individual> paretoFront = ParetoOperators.getGlobalNonDominatedFront( context, population, ParetoGP.OBJECTIVES.AGE_DENSITY_FITNESS); assertEquals(4, paretoFront.size()); } /** * Tests that the global pareto front is correct using Age/Fitness as the * objectives. */ @Test public void testGlobalFrontAF() { Vector<Individual> population = new Vector<Individual>(); for (Object[] items : AF_FRONT) { Individual ind = new Individual(); ind.setId(0); ind.setFitness((Double) items[0]); ind.setAge((Integer) items[1]); ind.setTag((String) items[2]); population.add(ind); } // Now fill the population with dominated individuals. for (int i = 0; i < 20; i++) { Individual ind = new Individual(); ind.setFitness(0); ind.setAge(100); ind.setTag("A"); ind.setId(0); population.add(ind); } Set<Individual> paretoFront = ParetoOperators.getGlobalNonDominatedFront( context, population, ParetoGP.OBJECTIVES.AGE_FITNESS); assertEquals(10, paretoFront.size()); } /** * Tests that the global pareto front is created correctly for the large * test front. */ @Test public void testGlobalFrontLarge() { Vector<Individual> population = new Vector<Individual>(); int size = 10; for (Object[] items : LARGE_FRONT) { Individual ind = new Individual(); ind.setId(0); ind.setFitness((Double) items[0]); ind.setTag((String) items[1]); ind.setNumNodes(size); size++; population.add(ind); } Set<Individual> paretoFront = ParetoOperators.getGlobalNonDominatedFront( context, population, ParetoGP.OBJECTIVES.AGE_DENSITY_FITNESS); assertEquals(4, paretoFront.size()); } /** * Tests that the population shrinks to (less than or equal to -- as in * Lipson's approach)the target population size when the pareto front is * smaller than the population size. */ @Test public void testParetoFrontSmaller() { Vector<Individual> population = new Vector<Individual>(); // Manually set the target pop size to easily make the numbers work. int targetSize = 10; context.getConfig().setPopSize(targetSize); for (int i = 0; i < SMALL_FRONT.length; i++) { Individual ind = new Individual(); ind.setId(0); ind.setFitness((Double) SMALL_FRONT[i][0]); ind.setTag((String) SMALL_FRONT[i][1]); population.add(ind); } // Now fill the population up to 2x the target size with dominated // individuals. for (int i = 0; i < (targetSize * 2) - SMALL_FRONT.length; i++) { Individual ind = new Individual(); ind.setId(0); ind.setFitness(0); ind.setTag("ZZZ"); population.add(ind); } // Now run the ParetoTournamentSelection. ParetoOperators.delete(context, population, ParetoGP.OBJECTIVES.AGE_DENSITY_FITNESS); // Now make sure the population made it to the target population size. assertTrue(population.size() <= targetSize); } /** * Tests that the population goes to the size of the pareto front, which * happens to be equal to the target population size. */ @Test public void testParetoFrontEqual() { Vector<Individual> population = new Vector<Individual>(); // Manually set the target pop size to easily make the numbers work. int targetSize = 4; context.getConfig().setPopSize(targetSize); for (int i = 0; i < EQUAL_FRONT.length; i++) { Individual ind = new Individual(); ind.setId(0); ind.setFitness((Double) EQUAL_FRONT[i][0]); ind.setTag((String) EQUAL_FRONT[i][1]); population.add(ind); } // Now fill the population with dominated individuals. for (int i = 0; i < 20 - EQUAL_FRONT.length; i++) { Individual ind = new Individual(); ind.setFitness(0); ind.setTag("ZZZ"); ind.setId(0); population.add(ind); } // Now run the ParetoTournamentSelection. ParetoOperators.delete(context, population, ParetoGP.OBJECTIVES.AGE_DENSITY_FITNESS); // Now make sure the population made it to the target population size. assertEquals(targetSize, population.size()); } /** * Tests that the individual is actually non-dominated when it is better in * fitness and density. */ @Test public void testNotDominatedBothBetter() { HashMap<String, Double> densities = new HashMap<String, Double>(); // Make some test individuals. Individual ind1 = new Individual(); Individual ind2 = new Individual(); // Make individual 1 more fit than individual 2 ind1.setFitness(1.0); ind1.setTag("A"); ind2.setFitness(0.2); ind2.setTag("B"); // Make individual 1's marker density less than individual 2 densities.put("A", 0.2); densities.put("B", 0.8); assertEquals(false, ParetoOperators.individualIsDominated(ind1, ind2, densities, context, ParetoGP.OBJECTIVES.AGE_DENSITY_FITNESS)); } /** * Tests that the individual is actually non-dominated when it is equal in * all objectives, and has fewer nodes. * */ @Test public void testNotDominatedEqual() { HashMap<String, Double> densities = new HashMap<String, Double>(); // Make some test individuals. Individual ind1 = new Individual(); Individual ind2 = new Individual(); // Make them equal in fitness ind1.setFitness(1.0); ind1.setTag("A"); ind2.setFitness(1.0); ind2.setTag("A"); // Make ind1 smaller than ind2 ind1.setNumNodes(5); ind2.setNumNodes(6); // Make individual 1's marker density the same as individual 2 densities.put("A", 0.2); assertEquals(false, ParetoOperators.individualIsDominated(ind1, ind2, densities, context, ParetoGP.OBJECTIVES.AGE_DENSITY_FITNESS)); } /** * Tests that the individual is actually dominated when it is worse in both * fitness and density. */ @Test public void testIsDominatedBothWorse() { HashMap<String, Double> densities = new HashMap<String, Double>(); // Make some test individuals. Individual ind1 = new Individual(); Individual ind2 = new Individual(); // Make individual 1 less fit than individual 2 ind1.setFitness(0.2); ind1.setTag("A"); ind2.setFitness(1.0); ind2.setTag("B"); // Make individual 1's marker density worse than individual 2 densities.put("A", 0.8); densities.put("B", 0.2); assertEquals(true, ParetoOperators.individualIsDominated(ind1, ind2, densities, context, ParetoGP.OBJECTIVES.AGE_DENSITY_FITNESS)); } /** * Tests that the individual is not dominated when it is better in fitness * but worse in density. */ @Test public void testNotDominatedBetterFitness() { HashMap<String, Double> densities = new HashMap<String, Double>(); // Make some test individuals. Individual ind1 = new Individual(); Individual ind2 = new Individual(); // Make individual 1 more fit than individual 2 ind1.setFitness(1.0); ind1.setTag("A"); ind2.setFitness(0.2); ind2.setTag("B"); // Make individual 1's marker density worse than individual 2 densities.put("A", 0.8); densities.put("B", 0.2); assertEquals(false, ParetoOperators.individualIsDominated(ind1, ind2, densities, context, ParetoGP.OBJECTIVES.AGE_DENSITY_FITNESS)); } /** * Tests that the individual is not dominated when it is worse in fitness * but better in density. */ @Test public void testNotDominatedBetterDensity() { HashMap<String, Double> densities = new HashMap<String, Double>(); // Make some test individuals. Individual ind1 = new Individual(); Individual ind2 = new Individual(); // Make individual 1 less fit than individual 2 ind1.setFitness(0.2); ind1.setTag("A"); ind2.setFitness(1.0); ind2.setTag("B"); // Make individual 1's marker density less than individual 2 densities.put("A", 0.2); densities.put("B", 0.8); assertEquals(false, ParetoOperators.individualIsDominated(ind1, ind2, densities, context, ParetoGP.OBJECTIVES.AGE_DENSITY_FITNESS)); } /** * Tests the case where the first individual is better in all three * objectives. */ @Test public void testAllBetter() { HashMap<String, Double> densities = new HashMap<String, Double>(); // Make some test individuals. Individual ind1 = new Individual(); Individual ind2 = new Individual(); // Make individual 1 more fit than individual 2 ind1.setFitness(1.0); ind1.setTag("A"); ind2.setFitness(0.2); ind2.setTag("B"); // Make individual 1's marker density less than individual 2 densities.put("A", 0.2); densities.put("B", 0.8); // Make individual 1 the youngest ind1.setAge(1); ind2.setAge(3); assertEquals(false, ParetoOperators.individualIsDominated(ind1, ind2, densities, context, ParetoGP.OBJECTIVES.AGE_DENSITY_FITNESS)); } /** * Tests the case where the individual is worse on all objectives. */ @Test public void testAllWorse() { HashMap<String, Double> densities = new HashMap<String, Double>(); // Make some test individuals. Individual ind1 = new Individual(); Individual ind2 = new Individual(); // Make individual 1 less fit than individual 2 ind1.setFitness(0.2); ind1.setTag("A"); ind2.setFitness(1.0); ind2.setTag("B"); // Make individual 1's marker density greater than individual 2 densities.put("A", 0.8); densities.put("B", 0.2); // Make individual 1 the oldest ind1.setAge(3); ind2.setAge(1); assertEquals(true, ParetoOperators.individualIsDominated(ind1, ind2, densities, context, ParetoGP.OBJECTIVES.AGE_DENSITY_FITNESS)); } /** * Tests the case where the individual is better in age only. */ @Test public void testAgeBetter() { HashMap<String, Double> densities = new HashMap<String, Double>(); // Make some test individuals. Individual ind1 = new Individual(); Individual ind2 = new Individual(); // Make individual 1 less fit than individual 2 ind1.setFitness(0.2); ind1.setTag("A"); ind2.setFitness(1.0); ind2.setTag("B"); // Make individual 1's marker density greater than individual 2 densities.put("A", 0.8); densities.put("B", 0.2); // Make individual 1 the youngest ind1.setAge(1); ind2.setAge(3); assertEquals(false, ParetoOperators.individualIsDominated(ind1, ind2, densities, context, ParetoGP.OBJECTIVES.AGE_DENSITY_FITNESS)); } /** * Tests age/fitness objectives when age is equal and fitness is worse. */ @Test public void testAFAgeEqualFitnessWorse() { // Make some test individuals. Individual ind1 = new Individual(); Individual ind2 = new Individual(); HashMap<String, Double> densities = new HashMap<String, Double>(); // Fake the densities. ind1.setTag("A"); ind2.setTag("B"); densities.put("A", 0.3); densities.put("B", 0.3); // Make individual 1 less fit than individual 2 ind1.setFitness(0.2); ind2.setFitness(1.0); // Make individual 1 the youngest ind1.setAge(7); ind2.setAge(7); assertEquals(true, ParetoOperators.individualIsDominated(ind1, ind2, densities, context, OBJECTIVES.AGE_FITNESS)); } /** * Tests the Age/Fitness pareto objectives on a problematic case taken from * a real run. * * @throws IOException */ @Test public void testAFProblematic() throws IOException { BufferedReader reader = new BufferedReader(new FileReader( "src/test/resources/afPareto.txt")); Vector<Individual> population = new Vector<Individual>(); context.getConfig().setPopSize(256); String line = null; while ((line = reader.readLine()) != null) { String items[] = line.split("\t"); Individual ind = new Individual(); ind.setId(0); ind.setTag(items[0].trim()); ind.setAge(Integer.parseInt(items[1])); ind.setFitness(Double.parseDouble(items[2])); population.add(ind); } reader.close(); Set<Individual> paretoFront = ParetoOperators.delete(context, population, OBJECTIVES.AGE_FITNESS); assertTrue(paretoFront.size() < population.size()); } /** * Tests the age/fitness objectives when age is equal but fitness is better */ @Test public void testAFAgeEqualFitnessBetter() { // Make some test individuals. Individual ind1 = new Individual(); Individual ind2 = new Individual(); HashMap<String, Double> densities = new HashMap<String, Double>(); // Fake the densities. ind1.setTag("A"); ind2.setTag("B"); densities.put("A", 0.3); densities.put("B", 0.3); // Make individual 1 less fit than individual 2 ind1.setFitness(1.0); ind2.setFitness(0.2); // Make individual 1 the youngest ind1.setAge(7); ind2.setAge(7); assertEquals(false, ParetoOperators.individualIsDominated(ind1, ind2, densities, context, OBJECTIVES.AGE_FITNESS)); } /** * Tests the case where the individual is worse in age and better in fitness * and density. */ @Test public void testAgeWorse() { HashMap<String, Double> densities = new HashMap<String, Double>(); // Make some test individuals. Individual ind1 = new Individual(); Individual ind2 = new Individual(); // Make individual 1 less fit than individual 2 ind1.setFitness(1.0); ind1.setTag("A"); ind2.setFitness(0.2); ind2.setTag("B"); // Make individual 1's marker density less than individual 2 densities.put("A", 0.2); densities.put("B", 0.8); // Make individual 1 the oldest ind1.setAge(3); ind2.setAge(1); assertEquals(false, ParetoOperators.individualIsDominated(ind1, ind2, densities, context, ParetoGP.OBJECTIVES.AGE_DENSITY_FITNESS)); } }
27.640809
77
0.684583
f77e4a24d330d1f53687ea63cc59c62bf1c23024
1,946
package seedu.address.logic.parser; import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.address.logic.parser.CliSyntax.PREFIX_SORT_KEY; import static seedu.address.logic.parser.CliSyntax.PREFIX_SORT_ORDER; import java.util.stream.Stream; import seedu.address.logic.commands.sort.SortCommand; import seedu.address.logic.commands.sort.SortKey; import seedu.address.logic.commands.sort.SortOrder; import seedu.address.logic.parser.exceptions.ParseException; /** * Parses input arguments and creates a new SortCommand object */ public class SortCommandParser implements Parser<SortCommand> { /** * Parses the given {@code String} of arguments in the context of the SortCommand * and returns an SortCommand object for execution. * @throws ParseException if the user input does not conform the expected format */ public SortCommand parse(String args) throws ParseException { ArgumentMultimap argMultimap = ArgumentTokenizer.tokenize(args, PREFIX_SORT_KEY, PREFIX_SORT_ORDER); if (!arePrefixesPresent(argMultimap, PREFIX_SORT_KEY, PREFIX_SORT_ORDER) || !argMultimap.getPreamble().isEmpty()) { throw new ParseException(String.format(MESSAGE_INVALID_COMMAND_FORMAT, SortCommand.MESSAGE_USAGE)); } SortKey sortKey = ParserUtil.parseSortKey(argMultimap.getValue(PREFIX_SORT_KEY).get()); SortOrder sortOrder = ParserUtil.parseSortOrder(argMultimap.getValue(PREFIX_SORT_ORDER).get()); return new SortCommand(sortKey, sortOrder); } /** * Returns true if none of the prefixes contains empty {@code Optional} values in the given * {@code ArgumentMultimap}. */ private static boolean arePrefixesPresent(ArgumentMultimap argumentMultimap, Prefix... prefixes) { return Stream.of(prefixes).allMatch(prefix -> argumentMultimap.getValue(prefix).isPresent()); } }
41.404255
111
0.754882
f440b1afc023fc5f78a68d71e1b520da31b3f23e
5,078
package com.alibaba.dubbo.transactiontree.recovery; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; import com.alibaba.dubbo.transactiontree.api.Transaction; import com.alibaba.dubbo.transactiontree.api.TransactionCallback; import com.alibaba.dubbo.transactiontree.api.TransactionRepository; import com.alibaba.dubbo.transactiontree.log.TransactionLog; import com.alibaba.dubbo.transactiontree.stat.TransactionStat; /** * * @author fuhaining */ public class BadTransactionRecoveryTimer implements InitializingBean, DisposableBean, Runnable { private TransactionRepository transactionRepository = null; private ScheduledExecutorService recoveryScheduledExecutor = Executors.newScheduledThreadPool(1); private ScheduledFuture<?> recoveryScheduledFuture = null; private long recoveryInterval = 5 * 1000; // Millis private long badTransactionPeriod = 60 * 1000; // Millis private int maxRecoveryNum = 20; private ExecutorService recoveryExecutor = null; private TransactionStat transactionStat = TransactionStat.getInstance(); public void start() { if (recoveryScheduledFuture == null) { TransactionLog.RECOVERY.info("启动事务恢复线程"); recoveryScheduledFuture = recoveryScheduledExecutor.scheduleAtFixedRate(this, 0, recoveryInterval, TimeUnit.MILLISECONDS); } } public void stop() { recoveryScheduledFuture.cancel(false); recoveryScheduledFuture = null; TransactionLog.RECOVERY.info("停止事务恢复线程"); } @Override public void run() { transactionRepository.foreach(new TransactionCallback<Object>() { @Override public Object doInTransaction(final Transaction transaction) { long lastUpdateTime = transaction.getUpdateTime(); int recoveryNum = transaction.getRecoveryNum(); if (recoveryNum <= maxRecoveryNum && (lastUpdateTime + badTransactionPeriod + (recoveryNum * badTransactionPeriod)) <= System.currentTimeMillis()) { recoveryExecutor.execute(new Runnable() { @Override public void run() { String transactionId = transaction.getXid().getTransactionId(); try { transactionStat.incrRecoveryCount(); int currentyRecoveryNum = transaction.incrRecoveryNum(); transactionRepository.update(transaction); TransactionLog.RECOVERY.info("第{}次恢复事务, transactionId={}", currentyRecoveryNum, transactionId); transaction.recovery(); transactionRepository.delete(transactionId); TransactionLog.RECOVERY.info("恢复事务成功, transactionId={}", transactionId); transactionStat.incrRecoverySuccessCount(); } catch (Throwable e) { TransactionLog.RECOVERY.error("事务恢复错误,transactionId=" + transactionId, e); transactionStat.addRecoveryFailure(transactionId); } } }); } else { if (recoveryNum > maxRecoveryNum ) { TransactionLog.RECOVERY.debug("超过最大事务恢复次数,transactionId=" + transaction.getXid().getTransactionId()); } } return null; } }); } @Override public void afterPropertiesSet() throws Exception { start(); if (recoveryExecutor == null) { recoveryExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2); } } @Override public void destroy() throws Exception { recoveryScheduledExecutor.shutdown(); if (recoveryExecutor == null) { recoveryExecutor.shutdown(); } } public ScheduledExecutorService getRecoveryScheduledExecutor() { return recoveryScheduledExecutor; } public void setRecoveryScheduledExecutor(ScheduledExecutorService recoveryScheduledExecutor) { this.recoveryScheduledExecutor = recoveryScheduledExecutor; } public long getRecoveryInterval() { return recoveryInterval; } public void setRecoveryInterval(long recoveryInterval) { this.recoveryInterval = recoveryInterval; } public long getBadTransactionPeriod() { return badTransactionPeriod; } public void setBadTransactionPeriod(long badTransactionPeriod) { this.badTransactionPeriod = badTransactionPeriod; } public int getMaxRecoveryNum() { return maxRecoveryNum; } public void setMaxRecoveryNum(int maxRecoveryNum) { this.maxRecoveryNum = maxRecoveryNum; } public TransactionRepository getTransactionRepository() { return transactionRepository; } public void setTransactionRepository(TransactionRepository transactionRepository) { this.transactionRepository = transactionRepository; } public ExecutorService getRecoveryExecutor() { return recoveryExecutor; } public void setRecoveryExecutor(ExecutorService recoveryExecutor) { this.recoveryExecutor = recoveryExecutor; } }
31.937107
126
0.735723
03a144565afffe63999c0972fb45a45120902116
8,669
/** * */ package edu.berkeley.nlp.discPCFG; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.zip.GZIPInputStream; import edu.berkeley.nlp.PCFGLA.ArrayParser; import edu.berkeley.nlp.PCFGLA.Binarization; import edu.berkeley.nlp.PCFGLA.ConstrainedTwoChartsParser; import edu.berkeley.nlp.PCFGLA.Grammar; import edu.berkeley.nlp.PCFGLA.GrammarMerger; import edu.berkeley.nlp.PCFGLA.Lexicon; import edu.berkeley.nlp.PCFGLA.ParserData; import edu.berkeley.nlp.PCFGLA.StateSetTreeList; import edu.berkeley.nlp.discPCFG.ParsingObjectiveFunction.Counts; import edu.berkeley.nlp.syntax.StateSet; import edu.berkeley.nlp.syntax.Tree; import edu.berkeley.nlp.math.SloppyMath; import edu.berkeley.nlp.util.Numberer; import edu.berkeley.nlp.util.ScalingTools; /** * @author petrov * */ public class ConditionalMerger { int nProcesses; String consBaseName; Grammar grammar; Lexicon lexicon; double mergingPercentage; String outFileName; StateSetTreeList[] trainingTrees; ExecutorService pool; Merger[] tasks; double[][] mergeWeights; class Merger implements Callable{ ArrayParser gParser; ConstrainedTwoChartsParser eParser; StateSetTreeList myTrees; String consName; int myID; int nCounts; boolean[][][][][] myConstraints; int unparsableTrees, incorrectLLTrees; double[][] mergeWeights; Merger(StateSetTreeList myT, String consN, int i, Grammar gr, Lexicon lex, double[][] mergeWeights){ this.consName = consN; this.myTrees = myT; this.myID = i; this.mergeWeights = mergeWeights; gParser = new ArrayParser(gr, lex); eParser = new ConstrainedTwoChartsParser(gr, lex, null); } private void loadConstraints(){ myConstraints = new boolean[myTrees.size()][][][][]; boolean[][][][][] curBlock = null; int block = 0; int i = 0; if (consName==null) return; for (int tree=0; tree<myTrees.size(); tree++){ if (curBlock == null || i >= curBlock.length){ int blockNumber = ((block*nProcesses)+myID); curBlock = loadData(consName+"-"+blockNumber+".data"); block++; i = 0; System.out.print("."); } eParser.projectConstraints(curBlock[i]); myConstraints[tree] = curBlock[i]; i++; if (myConstraints[tree].length!=myTrees.get(tree).getYield().size()){ System.out.println("My ID: "+myID+", block: "+block+", sentence: "+i); System.out.println("Sentence length and constraints length do not match!"); myConstraints[tree] = null; } } } public double[][][] call() { if (myConstraints==null) loadConstraints(); double[][][] deltas = new double[grammar.numStates][mergeWeights[0].length][mergeWeights[0].length]; int i = -1; int block = 0; for (Tree<StateSet> stateSetTree : myTrees) { i++; boolean noSmoothing = true, debugOutput = false, hardCounts = false; gParser.doInsideOutsideScores(stateSetTree, noSmoothing, debugOutput); // parse the sentence List<StateSet> yield = stateSetTree.getYield(); List<String> sentence = new ArrayList<String>(yield.size()); for (StateSet el : yield){ sentence.add(el.getWord()); } boolean[][][][] cons = null; if (consName!=null){ cons = myConstraints[i]; if (cons.length != sentence.size()){ System.out.println("My ID: "+myID+", block: "+block+", sentence: "+i); System.out.println("Sentence length ("+sentence.size()+") and constraints length ("+cons.length+") do not match!"); System.exit(-1); } } eParser.doConstrainedInsideOutsideScores(yield,cons,noSmoothing,stateSetTree,null,false); eParser.tallyConditionalLoss(stateSetTree, deltas, mergeWeights); if (i%100==0) System.out.print("."); } System.out.print(" "+myID+" "); return deltas; } public boolean[][][][][] loadData(String fileName) { boolean[][][][][] data = null; try { FileInputStream fis = new FileInputStream(fileName); // Load from file GZIPInputStream gzis = new GZIPInputStream(fis); // Compressed ObjectInputStream in = new ObjectInputStream(gzis); // Load objects data = (boolean[][][][][])in.readObject(); // Read the mix of grammars in.close(); // And close the stream. } catch (IOException e) { System.out.println("IOException\n"+e); return null; } catch (ClassNotFoundException e) { System.out.println("Class not found!"); return null; } return data; } } /** * @param processes * @param consBaseName * @param trainingTrees */ public ConditionalMerger(int processes, String consBaseName, StateSetTreeList trainTrees, Grammar gr, Lexicon lex, double mergingPercentage, String outFileName) { this.nProcesses = processes; this.consBaseName = consBaseName; this.grammar = gr;//.copyGrammar(); this.lexicon = lex;//.copyLexicon(); this.mergingPercentage = mergingPercentage; this.outFileName = outFileName; int nTreesPerBlock = trainTrees.size()/processes; this.consBaseName = consBaseName; boolean[][][][][] tmp = edu.berkeley.nlp.PCFGLA.ParserConstrainer.loadData(consBaseName+"-0.data"); if (tmp!=null) nTreesPerBlock = tmp.length; // first compute the generative merging criterion mergeWeights = GrammarMerger.computeMergeWeights(grammar, lexicon,trainTrees); double[][][] deltas = GrammarMerger.computeDeltas(grammar, lexicon, mergeWeights, trainTrees); boolean[][][] mergeThesePairs = GrammarMerger.determineMergePairs(deltas,false,mergingPercentage,grammar); Grammar tmpGrammar = grammar.copyGrammar(true); Lexicon tmpLexicon = lexicon.copyLexicon(); tmpGrammar = GrammarMerger.doTheMerges(tmpGrammar, tmpLexicon, mergeThesePairs, mergeWeights); System.out.println("Generative merging criterion gives:"); GrammarMerger.printMergingStatistics(grammar, tmpGrammar); mergeWeights = GrammarMerger.computeMergeWeights(grammar, lexicon,trainTrees); // split the trees into chunks trainingTrees = new StateSetTreeList[nProcesses]; for (int i=0; i<nProcesses; i++){ trainingTrees[i] = new StateSetTreeList(); } int block = -1; int inBlock = 0; for (int i=0; i<trainTrees.size(); i++){ if (i%nTreesPerBlock==0) { block++; System.out.println(inBlock); inBlock = 0; } trainingTrees[block%nProcesses].add(trainTrees.get(i)); inBlock++; } trainTrees = null; pool = Executors.newFixedThreadPool(nProcesses);//CachedThreadPool(); tasks = new Merger[nProcesses]; for (int i=0; i<nProcesses; i++){ tasks[i] = new Merger(trainingTrees[i],consBaseName,i, grammar, lexicon, mergeWeights); } } public void mergeGrammarAndLexicon(){ System.out.print("Task: "); Future[] submits = new Future[nProcesses]; for (int i=0; i<nProcesses; i++){ Future submit = pool.submit(tasks[i]);//execute(tasks[i]); submits[i] = submit; } while (true) { boolean done = true; for (Future task : submits) { done &= task.isDone(); } if (done) break; } // accumulate double[][][] deltas = new double[grammar.numStates][mergeWeights[0].length][mergeWeights[0].length]; for (int i=0; i<nProcesses; i++){ double[][][] counts = null; try { counts = (double[][][]) submits[i].get(); } catch (ExecutionException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } for (int a=0; a<deltas.length; a++){ for (int b=0; b<deltas[0].length; b++){ for (int c=0; c<deltas[0][0].length; c++){ deltas[a][b][c] += counts[a][b][c]; } } } } System.out.print(" done. "); System.out.println("Conditional merging criterion gives:"); boolean[][][] mergeThesePairs = GrammarMerger.determineMergePairs(deltas,false,mergingPercentage,grammar); Grammar newGrammar = GrammarMerger.doTheMerges(grammar, lexicon, mergeThesePairs, mergeWeights); GrammarMerger.printMergingStatistics(grammar, newGrammar); ParserData pData = new ParserData(lexicon, newGrammar, null, Numberer.getNumberers(), newGrammar.numSubStates, 1, 0, Binarization.RIGHT); System.out.println("Saving grammar to "+outFileName+"."); if (pData.Save(outFileName+"-merged")) System.out.println("Saving successful."); else System.out.println("Saving failed!"); } }
33.600775
139
0.681278
74d185a687dd699e3f587e604ec38aae77b9973f
1,486
package omtteam.omlib.util.world; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.common.registry.ForgeRegistries; /** * Created by Keridos on 31/01/17. * This Class implements some Block related Utility functions */ public class BlockUtil { // --------------------------------------------------------------- // Utility functions for Camo Blockstates public static void writeBlockFromStateToNBT(NBTTagCompound nbtTagCompound, IBlockState state) { if (state != null && state.getBlock().getRegistryName() != null) { nbtTagCompound.setString("camoBlockRegName", state.getBlock().getRegistryName().toString()); nbtTagCompound.setInteger("camoBlockMeta", state.getBlock().getMetaFromState(state)); } } public static IBlockState getBlockStateFromNBT(NBTTagCompound nbtTagCompound) { if (nbtTagCompound.hasKey("camoBlockRegName") && nbtTagCompound.hasKey("camoBlockMeta")) { Block block = ForgeRegistries.BLOCKS.getValue( new ResourceLocation(nbtTagCompound.getString("camoBlockRegName"))); if (block != null) { return block.getStateFromMeta(nbtTagCompound.getInteger("camoBlockMeta")); } } return null; } // --------------------------------------------------------------- }
41.277778
104
0.638627
ffd013ea777200e9bed4ca3de493a72f3b477bec
7,135
package cc.duduhuo.simpler.adapter; import android.app.Activity; import android.content.Intent; import android.support.v4.content.ContextCompat; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.bumptech.glide.Glide; import com.sina.weibo.sdk.openapi.models.User; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import cc.duduhuo.simpler.R; import cc.duduhuo.simpler.activity.WBUserHomeActivity; import cc.duduhuo.simpler.listener.OnFriendshipListener; import cc.duduhuo.simpler.util.UserVerify; import de.hdodenhof.circleimageview.CircleImageView; /** * ======================================================= * 作者:liying - [email protected] * 日期:2017/3/29 18:46 * 版本:1.0 * 描述:粉丝列表、关注列表适配器 * 备注: * ======================================================= */ public class UserListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private static final int TYPE_ITEM = 0x0000; private static final int TYPE_FOOT = 0x0001; private Activity mActivity; private List<User> mFollowers = new ArrayList<>(); private String mFooterInfo = ""; private OnFriendshipListener mListener; private boolean mIsAuth; /** * 构造方法 * @param activity * @param isAuth 是否是当前授权用户的关注或粉丝 */ public UserListAdapter(Activity activity, boolean isAuth) { this.mActivity = activity; this.mIsAuth = isAuth; } /** * 设置footerView信息 * * @param footerInfo footerView信息 */ public void setFooterInfo(String footerInfo) { this.mFooterInfo = footerInfo; notifyItemChanged(mFollowers.size()); } public void setData(List<User> followers) { this.mFollowers.clear(); this.mFollowers.addAll(followers); notifyDataSetChanged(); } public void addData(List<User> followers) { int start = mFollowers.size(); mFollowers.addAll(followers); notifyItemRangeInserted(start, followers.size()); } /** * 成功关注某用户 * @param position */ public void createSuccess(int position) { this.mFollowers.get(position).following = true; notifyItemChanged(position); } /** * 成功取消关注某用户 * @param position */ public void destroySuccess(int position) { this.mFollowers.get(position).following = false; notifyItemChanged(position); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType == TYPE_ITEM) { View view = LayoutInflater.from(mActivity).inflate(R.layout.item_user, parent, false); return new ItemViewHolder(view); } else if (viewType == TYPE_FOOT) { View view = LayoutInflater.from(mActivity).inflate(R.layout.item_footer_view, parent, false); return new FooterViewHolder(view); } return null; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { if (getItemViewType(position) == TYPE_ITEM) { final User user = mFollowers.get(position); final ItemViewHolder itemHolder = (ItemViewHolder) holder; // 加载头像 Glide.with(mActivity).load(user.avatar_large).into(itemHolder.mCivHead); // 加载昵称 itemHolder.mTvName.setText(user.name); // 加载描述/认证信息 UserVerify.verify(user, itemHolder.mIvAvatarVip, itemHolder.mTvDescription); if (mIsAuth) { itemHolder.mTvRelation.setVisibility(View.VISIBLE); // 授权用户是否关注该用户 if (user.following) { itemHolder.mTvRelation.setBackgroundResource(R.drawable.selector_relation_btn); itemHolder.mTvRelation.setTextColor(ContextCompat.getColor(mActivity, R.color.unfollow_color)); itemHolder.mTvRelation.setText("已关注"); } else { itemHolder.mTvRelation.setBackgroundResource(R.drawable.selector_relation_blue_btn); itemHolder.mTvRelation.setTextColor(ContextCompat.getColor(mActivity, R.color.follow_color)); itemHolder.mTvRelation.setText("加关注"); } // 点击关注或取消关注 itemHolder.mTvRelation.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (user.following) { if (mListener != null) { mListener.onDestroy(itemHolder.getAdapterPosition(), user.id, user.screen_name); } } else { if (mListener != null) { mListener.onCreate(itemHolder.getAdapterPosition(), user.id, user.screen_name); } } } }); } else { itemHolder.mTvRelation.setVisibility(View.GONE); } // 点击条目打开用户HomeActivity itemHolder.mRlItem.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = WBUserHomeActivity.newIntent(mActivity, user.screen_name); mActivity.startActivity(intent); } }); } else if (getItemViewType(position) == TYPE_FOOT) { FooterViewHolder footHolder = (FooterViewHolder) holder; footHolder.mTvFooter.setText(mFooterInfo); } } @Override public int getItemCount() { return mFollowers.size() + 1; } @Override public int getItemViewType(int position) { if (position == getItemCount() - 1) { return TYPE_FOOT; } return TYPE_ITEM; } public void setOnFriendshipListener(OnFriendshipListener listener) { this.mListener = listener; } public class ItemViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.rlItem) RelativeLayout mRlItem; @BindView(R.id.civHead) CircleImageView mCivHead; @BindView(R.id.ivAvatarVip) ImageView mIvAvatarVip; @BindView(R.id.tvName) TextView mTvName; @BindView(R.id.tvDescription) TextView mTvDescription; @BindView(R.id.tvRelation) TextView mTvRelation; public ItemViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } } public class FooterViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.tvFooter) TextView mTvFooter; public FooterViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } } }
33.815166
115
0.607008
d7061722309f64602a3a5143ff473d6dd3d6412c
1,150
package org.dyndns.dalance.statuslogger; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; public class OutputFilenameTextChangedListener implements TextWatcher { private static final String TAG = OutputFilenameTextChangedListener.class.getSimpleName(); private Context context; OutputFilenameTextChangedListener (Context context_) { context = context_; } @Override public void afterTextChanged(Editable s) { Log.d(TAG, "afterTextChanged: " + s.toString()); SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor = pref.edit(); editor.putString("OutputFilename", s.toString()); editor.commit(); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub } }
29.487179
92
0.754783
b2291f3bbf479c600493d08481d116005b037d8a
2,710
package it.redhat.demo.rest; import it.redhat.demo.jaxb.JaxbContextFactory; import it.redhat.demo.model.Clue; import it.redhat.demo.model.Task; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.xml.bind.JAXB; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import java.io.StringWriter; /** * @author Fabio Massimo Ercoli * [email protected] * on 18/07/16 */ @Path("") public class RestService { Logger log = LoggerFactory.getLogger(RestService.class); @GET public String ciao() { log.info("ciao"); return "ciao"; } @GET @Path("task") @Produces({ "application/xml" }) public Task task() { Task task = getTask(); return task; } @GET @Path("jaxb/task") @Produces({ "application/xml" }) public String jaxbTask() { Task task = getTask(); StringWriter w = new StringWriter(); JAXB.marshal(task, w); return w.toString(); } @GET @Path("clue") @Produces({ "application/xml" }) public Clue clue() { Clue clue = getClue(); return clue; } @GET @Path("valid") @Produces({ "application/xml" }) public String validJaxbContext() throws JAXBException { Task task = getTask(); JaxbContextFactory contextFactory = new JaxbContextFactory(); JAXBContext jaxbContext = contextFactory.buildOk(); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, true); StringWriter w = new StringWriter(); marshaller.marshal(task, w); return w.toString(); } @GET @Path("invalid") @Produces({ "application/xml" }) public String invalidJaxbContext() throws JAXBException { Clue clue = getClue(); JaxbContextFactory contextFactory = new JaxbContextFactory(); JAXBContext jaxbContext = contextFactory.buildKo(); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, true); StringWriter w = new StringWriter(); marshaller.marshal(clue, w); return w.toString(); } private Task getTask() { Task task = new Task(); task.setId(1l); task.setTitle("My Task"); return task; } private Clue getClue() { Clue clue = new Clue(); clue.setUpper("Going ..."); clue.setDecision(7l); return clue; } }
22.396694
86
0.625461
e9538727eedf192bddb0016f5ef5ae9da66eb6db
1,494
package edu.heuet.shaohua.controller.viewobject; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; public class RegisterVO { @NotNull(message = "手机号不能为空") private String telephone; private String otpCode; @NotBlank(message = "用户名不能为空") private String name; @NotNull(message = "必须填写年龄") @Min(value = 0, message = "年龄必须大于0") @Max(value = 150, message = "年龄必须小于150") private String age; @NotNull(message = "必须填写性别") private String gender; private String password; public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public String getOtpCode() { return otpCode; } public void setOtpCode(String otpCode) { this.otpCode = otpCode; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
21.342857
48
0.633199
b23007a861b214bb9aff38178355ec48d33454cc
786
package com.smashdown.android.common.util; import android.util.Log; import com.google.firebase.crash.FirebaseCrash; import timber.log.Timber; public class CrashReportingTree extends Timber.Tree { private static final String CRASHLYTICS_KEY_PRIORITY = "priority"; private static final String CRASHLYTICS_KEY_TAG = "tag"; private static final String CRASHLYTICS_KEY_MESSAGE = "message"; @Override protected void log(int priority, String tag, String message, Throwable throwable) { if (priority < Log.ERROR) { return; } Throwable t = throwable != null ? throwable : new Exception(message); // Firebase Crash Reporting FirebaseCrash.logcat(priority, tag, message); FirebaseCrash.report(t); } }
30.230769
87
0.698473
de9019dce9297f6a0e07923c6169bbca68df51c1
908
package com.organization.Giscle.giscle_app.Variable; /** * Created by sushen.kumaron 9/17/2017. */ public class CONSTANT { public static final String GMAIL = "gmail"; public static final String FB = "fb"; public static final String HOUR = "hour"; public static final String POINTS = "points"; public static final String TOTAL_TIME = "total_time"; public static final String MINUTE = "minute"; public static final String SECOND = "second"; public static final String DISTANCE = "distance"; public static final String VIDEO_NAME ="videoname"; public static final String BUNDLE_VIDEO_CAMERA="bundleCamera"; public static final String COMPANY_NAME = "compName"; public static final String COUPON_NUMBER = "couponNumber"; public static final String INR_COUPON = "winningInr"; public static final String NOT_UPLOADED_VIDEO = "uploadVideoTriplog"; }
32.428571
73
0.727974
7c26f7a7b2eb12c34424f9c749e097768d4108b3
506
package cn.jansen.databind; import java.util.Arrays; public class AlbumNew { private String title; private Song[] songs; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Song[] getSongs() { return songs; } public void setSongs(Song[] songs) { this.songs = songs; } @Override public String toString() { return "AlbumNew [title=" + title + ", songs=" + Arrays.toString(songs) + "]"; } }
17.448276
81
0.624506
ec5b6807fdd117587db5237f958d029980c47679
3,132
package com.yifan.sounddemo; import android.media.AudioManager; import android.media.MediaPlayer; import android.provider.MediaStore; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.SeekBar; import java.util.Timer; import java.util.TimerTask; public class MainActivity extends AppCompatActivity { MediaPlayer mediaPlayer; AudioManager audioManager; public void play(View view) { mediaPlayer.start(); } public void pause(View view) { mediaPlayer.pause(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mediaPlayer = MediaPlayer.create(this, R.raw.demo); audioManager = (AudioManager) getSystemService(AUDIO_SERVICE); int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC); // different devices have different maximum volume, so this variable is necessary int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC); SeekBar volumeControl = (SeekBar) findViewById(R.id.volumeSeekBar); volumeControl.setMax(maxVolume); volumeControl.setProgress(currentVolume); // the seekBar will start at the current Volume when the app is started volumeControl.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int i, boolean b) { // Log.i("SeekBar changed", Integer.toString(i)); // i is the value of the seekBar audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, i, 0); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); final SeekBar scrubSeekBar = (SeekBar) findViewById(R.id.scrubSeekBar); scrubSeekBar.setMax(mediaPlayer.getDuration()); // set the max of the seekBar to be the length of the audio scrubSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser) { // 一定要加上fromUser,否则由于进度条随播放而变化,seekTo总是被执行,音乐会变得断断续续U mediaPlayer.seekTo(progress); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); new Timer().scheduleAtFixedRate(new TimerTask() { // use the timer to update the scrubSeekBar @Override public void run() { scrubSeekBar.setProgress(mediaPlayer.getCurrentPosition()); } }, 0, 300); // 0 for start the timer when the app is started, and 1000 means run the task every 300ms } }
36
165
0.664112
25e0e4fa265ebf82a4886961bfe28c1f5386961b
8,215
package com.exelate.training.java8refresher; import com.google.common.collect.ImmutableMap; import org.apache.commons.lang3.NotImplementedException; import org.junit.Test; import java.util.*; public class LambdaWorkshop { /* ======================= Streams with Collections ====================== */ @Test public void collectToSet() { List<Integer> input = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); } @Test public void collectToSortedList() { List<Integer> input = Arrays.asList(5, 2, 3, 1, 4); } @Test public void countNamesOfLength5() { List<String> names = Arrays.asList("gilad", "amir", "maya", "ronen", "efrat", "alon"); } @Test public void collectToSortedListByLength() { List<String> names = Arrays.asList("gilad", "amir", "maya", "ronen", "efrat", "alon"); // 1. Hint: with a Comparator... // 2. Hint: Comparator.comparingInt() } @Test public void collectToCommaSeparatedStringSortedByLength() { List<String> names = Arrays.asList("gilad", "amir", "maya", "ronen", "efrat", "alon"); } @Test public void collectEvenInRangeGroupByGreaterThan5() { List<Integer> input = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // Hint: Collect group by ... something. } @Test public void sortByAge() { List<Person> people = Arrays.asList( new Person("ran", 25), new Person("omer", 40), new Person("rina", 33), new Person("ran", 11), new Person("elad", 7), new Person("elad", 35)); } @Test public void collectAges() { List<Person> people = Arrays.asList( new Person("ran", 25), new Person("omer", 40), new Person("rina", 33), new Person("ran", 11), new Person("elad", 7), new Person("elad", 35)); // TODO: Map of name -> ages. } @Test public void hashCodeViaReduce() { List<Integer> input = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // TODO: Calculate a hash code ((A + 2) * (B + 2) * ... * (Z + 2)) using reduce(). } static class Context { Set<Integer> younger = new HashSet<>(); Set<Integer> older = new HashSet<>(); } @Test public void buildContext() { List<Person> people = Arrays.asList( new Person("ran", 25), new Person("omer", 40), new Person("rina", 33), new Person("ran", 11), new Person("elad", 7), new Person("elad", 35)); // Create a pair of Contexts with partitioning of ages greater/smaller than 30. // TODO: Without reduce() or forEach(). // ... 2 streams ... } @Test public void groupSizes() { Map<String, List<Person>> groups = ImmutableMap.of( "children", Arrays.asList( new Person("ran", 11), new Person("elad", 7)), "parents", Arrays.asList( new Person("ran", 25), new Person("elad", 35), new Person("rina", 33)), "drivers", Arrays.asList( new Person("ran", 25), new Person("omer", 40), new Person("rina", 33), new Person("elad", 35))); // TODO: Map of group_name -> list of names. } @Test public void listOfDistinctNamesSortedByLength() { Map<String, List<Person>> groups = ImmutableMap.of( "children", Arrays.asList( new Person("ran", 11), new Person("elad", 7)), "parents", Arrays.asList( new Person("ran", 25), new Person("elad", 35), new Person("rina", 33)), "drivers", Arrays.asList( new Person("ran", 25), new Person("omer", 40), new Person("rina", 33), new Person("elad", 35))); // Hint: FlatMap. } /* ======================= Extra Lambdas 1 ====================== */ /** * A container of a list of CLEAN names. * This means: No extra spaces, proper capitalization, no repetition. */ class ContainerOfNames { private final List<String> names; public ContainerOfNames(Collection<String> names) { throw new NotImplementedException("constructor"); } /** * For-each. E.g. container.forEach(name -> println(name)) */ public void forEachName(Object doSomething) { throw new NotImplementedException("for each"); } /** * Return a list of names, filtered by <code>filter</code>. */ public void toFilteredList(Object filter) { throw new NotImplementedException("to list"); } /** * Return a {@link Set} containing all the names, but with * same iteration order as the original list. */ public void toSortedSet() { throw new NotImplementedException("to sorted set"); } } /* ======================= Extra Lambdas 2 ====================== */ // For each of the exercises below, please build *convincing* unit tests. // (Extra points for making this more generic). class Node<T> { final T value; final Node<T> left; final Node<T> right; public Node(T value, Node<T> left, Node<T> right) { this.value = value; this.left = left; this.right = right; } } /** * Walk the tree, using recursion, execute the function on each node. */ void walk1(Node<String> tree, Object function) { throw new NotImplementedException("walk recursively"); } /** * Walk the tree, using recursion, execute the function on each node. * If we exceed the max depth, die horribly. */ void walk1Limited(Node<String> tree, Object function) { throw new NotImplementedException("walk recursively with a limit"); } /** * Walk the tree, without recursion, execute the function on each node. */ void walk2(Node<String> tree, Object function) { throw new NotImplementedException("walk recursively"); } /** * Count the nodes in the tree. */ void size(Node<?> tree) { throw new NotImplementedException("walk recursively"); } /** * Return a sorted list of the tree's values. */ void sortedValues(Node<String> tree) { throw new NotImplementedException("sorted list of values"); } /** * Extra points: return a sorted, balanced tree. */ Node<String> sorted(Node<String> tree) { throw new NotImplementedException("sorted tree"); } /* ======================= Extra Lambdas 3 ====================== */ /* * Task: Define a class that will implement 3 flow control constructs. * Please design a reasonably friendly API :) * Use standard (i.e. java.util.*) interfaces! * * 1. An IF/IF-ELSE statement. * Example of use: Logic.if(<condition>, <run-if-true>) * Example of use: Logic.ifElse(<condition>, <run-if-true>, <run-if-false>) * * 2. A WHILE loop. * Example of use (simple): Logic.while(<condition>, <body>) * More useful (?): Logic.while(<context>, <condition-on-context>, <body-using-context>) * * 3. A CASE construct. * Example: Logic.case(<value>, Case(<condition>, <run-if-condition>), Case(..), ...) * Maybe better: Logic.case(<value>, Case(<condition>, <run-if-condition-with-value>), ...) * * Please provide sample usage tests for all of the above, nice ones! */ public static class Logic { // ... } }
25.5919
104
0.514181
6fc060e64c8132050d82d8b47067517b4ee74dc1
1,594
/* * Copyright 2015-2016 Lexteam * * 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 xyz.lexteam.ygd.core; import com.google.common.base.Preconditions; import org.slf4j.Logger; import xyz.lexteam.ygd.core.service.ServiceManager; import java.io.File; /** * Static access to {@link Game}. * * @author Jamie Mansfield */ public class LexGame { private static final Game GAME = null; public static Game getGame() { Preconditions.checkNotNull(GAME, "Game not yet initialised!"); return GAME; } /** * @see Game#getServiceManager() */ public static ServiceManager getServiceManager() { return GAME.getServiceManager(); } /** * @see Game#getSettings() */ public static GameSettings getSettings() { return GAME.getSettings(); } /** * @see Game#getLogger() */ public static Logger getLogger() { return GAME.getLogger(); } /** * @see Game#getDirectory() */ public static File getDirectory() { return GAME.getDirectory(); } }
24.151515
75
0.66123
bb5406bac87d1064e5a6a540f73c57a03236766e
1,689
package br.com.technologies.venom.medalertapp.services; import br.com.technologies.venom.medalertapp.models.ConsultasResp; import br.com.technologies.venom.medalertapp.models.Gerenciamento; import br.com.technologies.venom.medalertapp.models.GerenciamentoResp; import br.com.technologies.venom.medalertapp.models.MedicamentoDetalheResp; import br.com.technologies.venom.medalertapp.models.Usuario; import br.com.technologies.venom.medalertapp.models.UsuarioResp; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.Headers; import retrofit2.http.POST; import retrofit2.http.Path; public interface RESTService { //Fazer login na API passando login e senha no corpo @Headers({"Content-Type:application/json; charset=utf-8"}) @POST("autenticacao/login") Call<UsuarioResp> fazerLogin(@Body Usuario usuario); //Obter as consultas do paciente @Headers({"Content-Type:application/json; charset=utf-8"}) @GET("consultas") Call<ConsultasResp> obterConsultas(@Header("Authorization") String token); //Consultar um medicamento específico @Headers({"Content-Type:application/json; charset=utf-8"}) @GET("remedios/{codigo}") Call<MedicamentoDetalheResp> consultarMedicamento( @Header("Authorization") String token, @Path("codigo") String gtin ); //Cadastrar um gerenciamento de medicação @Headers({"Content-Type:application/json; charset=utf-8"}) @POST("gerenciamentos") Call<GerenciamentoResp> cadastrarGerenciamento( @Header("Authorization") String token, @Body Gerenciamento gerenciamento ); }
36.717391
78
0.751332
00253bf0e99e463d2eab722f9ef65d911eed800c
3,343
/* First created by JCasGen Tue Sep 03 12:34:17 CEST 2019 */ package de.julielab.jcore.types.pubmed; import de.julielab.jcore.types.Annotation_Type; import org.apache.uima.cas.Feature; import org.apache.uima.cas.Type; import org.apache.uima.cas.impl.FeatureImpl; import org.apache.uima.cas.impl.TypeImpl; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.JCasRegistry; /** PubMed/Medline abstracts sometimes have other IDs besided their PMID from different sources. This type discloses the respective ID and source. For details see https://www.nlm.nih.gov/bsd/mms/medlineelements.html#oid * Updated by JCasGen Tue Sep 03 12:34:17 CEST 2019 * @generated */ public class OtherID_Type extends Annotation_Type { /** @generated */ @SuppressWarnings ("hiding") public final static int typeIndexID = OtherID.typeIndexID; /** @generated @modifiable */ @SuppressWarnings ("hiding") public final static boolean featOkTst = JCasRegistry.getFeatOkTst("de.julielab.jcore.types.pubmed.OtherID"); /** @generated */ final Feature casFeat_id; /** @generated */ final int casFeatCode_id; /** @generated * @param addr low level Feature Structure reference * @return the feature value */ public String getId(int addr) { if (featOkTst && casFeat_id == null) jcas.throwFeatMissing("id", "de.julielab.jcore.types.pubmed.OtherID"); return ll_cas.ll_getStringValue(addr, casFeatCode_id); } /** @generated * @param addr low level Feature Structure reference * @param v value to set */ public void setId(int addr, String v) { if (featOkTst && casFeat_id == null) jcas.throwFeatMissing("id", "de.julielab.jcore.types.pubmed.OtherID"); ll_cas.ll_setStringValue(addr, casFeatCode_id, v);} /** @generated */ final Feature casFeat_source; /** @generated */ final int casFeatCode_source; /** @generated * @param addr low level Feature Structure reference * @return the feature value */ public String getSource(int addr) { if (featOkTst && casFeat_source == null) jcas.throwFeatMissing("source", "de.julielab.jcore.types.pubmed.OtherID"); return ll_cas.ll_getStringValue(addr, casFeatCode_source); } /** @generated * @param addr low level Feature Structure reference * @param v value to set */ public void setSource(int addr, String v) { if (featOkTst && casFeat_source == null) jcas.throwFeatMissing("source", "de.julielab.jcore.types.pubmed.OtherID"); ll_cas.ll_setStringValue(addr, casFeatCode_source, v);} /** initialize variables to correspond with Cas Type and Features * @generated * @param jcas JCas * @param casType Type */ public OtherID_Type(JCas jcas, Type casType) { super(jcas, casType); casImpl.getFSClassRegistry().addGeneratorForType((TypeImpl)this.casType, getFSGenerator()); casFeat_id = jcas.getRequiredFeatureDE(casType, "id", "uima.cas.String", featOkTst); casFeatCode_id = (null == casFeat_id) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_id).getCode(); casFeat_source = jcas.getRequiredFeatureDE(casType, "source", "uima.cas.String", featOkTst); casFeatCode_source = (null == casFeat_source) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_source).getCode(); } }
34.463918
219
0.70685
472ecec7d11234ba7d09d20bf9045720a82fc7ba
956
package com.scaleunlimited.flinkcrawler.fetcher; import java.util.HashSet; import crawlercommons.fetcher.http.UserAgent; public class FetchUtils { /** * @param maxSimultaneousRequests * for the fetcher that the builder will construct * @param userAgent * for the fetcher that the builder will construct * @return builder for a fetcher configured to avoid fetching any content from the URL but instead to throw an * exception with the redirect target */ public static SimpleHttpFetcherBuilder makeRedirectFetcherBuilder(int maxSimultaneousRequests, UserAgent userAgent) { SimpleHttpFetcherBuilder builder = new SimpleHttpFetcherBuilder(maxSimultaneousRequests, userAgent); builder.setDefaultMaxContentSize(0); builder.setValidMimeTypes(new HashSet<String>()); builder.setMaxRedirects(0); return builder; } }
35.407407
114
0.699791
4afbb54b2e4db8402de7fe395989fcadf2fbaf8b
2,432
/******************************************************************************* * Copyright 2012 Danny Kunz * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package org.omnaest.utils.beans.replicator; import java.io.Serializable; import java.util.Arrays; import org.omnaest.utils.structure.element.converter.ElementConverter; /** * @author Omnaest * @param <FROM> * @param <TO> */ class Pipe<FROM, TO> implements Serializable { private static final long serialVersionUID = -5157086773922721837L; private final Class<FROM> typeFrom; private final Class<TO> typeTo; private final ElementConverter<Object, Object>[] elementConverters; Pipe( Class<FROM> typeFrom, Class<TO> typeTo, ElementConverter<Object, Object>[] elementConverters ) { super(); this.typeFrom = typeFrom; this.typeTo = typeTo; this.elementConverters = elementConverters; } @SuppressWarnings("unchecked") public TO convert( FROM instance ) { Object retval = instance; for ( ElementConverter<Object, Object> elementConverter : this.elementConverters ) { retval = elementConverter.convert( retval ); } return (TO) retval; } public TypeAndType getTypeAndType() { return new TypeAndType( this.typeFrom, this.typeTo ); } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append( "Pipe [typeFrom=" ); builder.append( this.typeFrom ); builder.append( ", typeTo=" ); builder.append( this.typeTo ); builder.append( ", elementConverters=" ); builder.append( Arrays.toString( this.elementConverters ) ); builder.append( "]" ); return builder.toString(); } }
32.426667
103
0.618421
f3a633fb1c9cc7afb8b8ca010ac4a3649274beb6
265
/** * Alipay.com Inc. Copyright (c) 2004-2017 All Rights Reserved. */ package edu.ecnu.yt.pretty.publisher.rpc; /** * * @author yt * @version $Id: Callback.java, v 0.1 2017年12月16日 下午4:54 yt Exp $ */ public interface Callback<T> { void accept(T result); }
20.384615
65
0.660377
0a3316808ca1be51f76c9b91a277aeb00fc0c0b8
1,671
/** * TLS-Attacker - A Modular Penetration Testing Framework for TLS * * Copyright 2014-2020 Ruhr University Bochum, Paderborn University, * and Hackmanit GmbH * * Licensed under Apache License 2.0 * http://www.apache.org/licenses/LICENSE-2.0 */ package de.rub.nds.tlsattacker.attacks.cca; import de.rub.nds.tlsattacker.core.crypto.keys.CustomPrivateKey; import de.rub.nds.tlsattacker.core.crypto.keys.CustomPublicKey; import java.util.LinkedList; import java.util.List; public class CcaCertificateChain { private List<byte[]> encodedCertificates; private CustomPrivateKey leafCertificatePrivateKey; private CustomPublicKey leafCertificatePublicKey; CcaCertificateChain() { this.encodedCertificates = new LinkedList<>(); } public void appendEncodedCertificate(byte[] encodedCertificate) { encodedCertificates.add(encodedCertificate); } public void setLeafCertificatePrivateKey(CustomPrivateKey leafCertificatePrivateKey) { this.leafCertificatePrivateKey = leafCertificatePrivateKey; } public CustomPrivateKey getLeafCertificatePrivateKey() { return leafCertificatePrivateKey; } public void setLeafCertificatePublicKey(CustomPublicKey leafCertificatePublicKey) { this.leafCertificatePublicKey = leafCertificatePublicKey; } public CustomPublicKey getLeafCertificatePublicKey() { return leafCertificatePublicKey; } public List<byte[]> getEncodedCertificates() { return encodedCertificates; } public void setEncodedCertificates(List<byte[]> encodedCertificates) { this.encodedCertificates = encodedCertificates; } }
30.381818
90
0.755835
763ccad4c580cadef71167154b9f53bc104cdb9b
18,133
package net.osmand.plus.activities; import java.io.File; import java.text.MessageFormat; import java.util.Random; import net.osmand.access.AccessibleAlertBuilder; import net.osmand.data.LatLon; import net.osmand.plus.OsmandApplication; import net.osmand.plus.R; import net.osmand.plus.Version; import net.osmand.plus.activities.search.SearchActivity; import net.osmand.plus.render.MapRenderRepositories; import android.app.Activity; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.text.SpannableString; import android.text.method.LinkMovementMethod; import android.text.style.ClickableSpan; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.view.animation.AccelerateInterpolator; import android.view.animation.Animation; import android.view.animation.Transformation; import android.view.animation.TranslateAnimation; import android.widget.TextView; public class MainMenuActivity extends Activity { private static final String FIRST_TIME_APP_RUN = "FIRST_TIME_APP_RUN"; //$NON-NLS-1$ private static final String VECTOR_INDEXES_CHECK = "VECTOR_INDEXES_CHECK"; //$NON-NLS-1$ private static final String TIPS_SHOW = "TIPS_SHOW"; //$NON-NLS-1$ private static final String VERSION_INSTALLED = "VERSION_INSTALLED"; //$NON-NLS-1$ private static final String EXCEPTION_FILE_SIZE = "EXCEPTION_FS"; //$NON-NLS-1$ private static final String CONTRIBUTION_VERSION_FLAG = "CONTRIBUTION_VERSION_FLAG"; public static final int APP_EXIT_CODE = 4; public static final String APP_EXIT_KEY = "APP_EXIT_KEY"; private ProgressDialog startProgressDialog; public void checkPreviousRunsForExceptions(boolean firstTime) { long size = getPreferences(MODE_WORLD_READABLE).getLong(EXCEPTION_FILE_SIZE, 0); final OsmandApplication app = ((OsmandApplication) getApplication()); final File file = app.getAppPath(OsmandApplication.EXCEPTION_PATH); if (file.exists() && file.length() > 0) { if (size != file.length() && !firstTime) { String msg = MessageFormat.format(getString(R.string.previous_run_crashed), OsmandApplication.EXCEPTION_PATH); Builder builder = new AccessibleAlertBuilder(MainMenuActivity.this); builder.setMessage(msg).setNeutralButton(getString(R.string.close), null); builder.setPositiveButton(R.string.send_report, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_EMAIL, new String[] { "[email protected]" }); //$NON-NLS-1$ intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file)); intent.setType("vnd.android.cursor.dir/email"); //$NON-NLS-1$ intent.putExtra(Intent.EXTRA_SUBJECT, "OsmAnd bug"); //$NON-NLS-1$ StringBuilder text = new StringBuilder(); text.append("\nDevice : ").append(Build.DEVICE); //$NON-NLS-1$ text.append("\nBrand : ").append(Build.BRAND); //$NON-NLS-1$ text.append("\nModel : ").append(Build.MODEL); //$NON-NLS-1$ text.append("\nProduct : ").append(Build.PRODUCT); //$NON-NLS-1$ text.append("\nBuild : ").append(Build.DISPLAY); //$NON-NLS-1$ text.append("\nVersion : ").append(Build.VERSION.RELEASE); //$NON-NLS-1$ text.append("\nApp Version : ").append(Version.getAppName(app)); //$NON-NLS-1$ try { PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0); if (info != null) { text.append("\nApk Version : ").append(info.versionName).append(" ").append(info.versionCode); //$NON-NLS-1$ //$NON-NLS-2$ } } catch (NameNotFoundException e) { } intent.putExtra(Intent.EXTRA_TEXT, text.toString()); startActivity(Intent.createChooser(intent, getString(R.string.send_report))); } }); builder.show(); } getPreferences(MODE_WORLD_WRITEABLE).edit().putLong(EXCEPTION_FILE_SIZE, file.length()).commit(); } else { if (size > 0) { getPreferences(MODE_WORLD_WRITEABLE).edit().putLong(EXCEPTION_FILE_SIZE, 0).commit(); } } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(resultCode == APP_EXIT_CODE){ getMyApplication().closeApplication(this); } } public static Animation getAnimation(int left, int top){ Animation anim = new TranslateAnimation(TranslateAnimation.RELATIVE_TO_SELF, left, TranslateAnimation.RELATIVE_TO_SELF, 0, TranslateAnimation.RELATIVE_TO_SELF, top, TranslateAnimation.RELATIVE_TO_SELF, 0); anim.setDuration(700); anim.setInterpolator(new AccelerateInterpolator()); return anim; } public static void onCreateMainMenu(Window window, final Activity activity){ View head = (View) window.findViewById(R.id.Headliner); head.startAnimation(getAnimation(0, -1)); View leftview = (View) window.findViewById(R.id.MapButton); leftview.startAnimation(getAnimation(-1, 0)); leftview = (View) window.findViewById(R.id.FavoritesButton); leftview.startAnimation(getAnimation(-1, 0)); View rightview = (View) window.findViewById(R.id.SettingsButton); rightview.startAnimation(getAnimation(1, 0)); rightview = (View) window.findViewById(R.id.SearchButton); rightview.startAnimation(getAnimation(1, 0)); String textVersion = Version.getAppVersion(((OsmandApplication) activity.getApplication())); final TextView textVersionView = (TextView) window.findViewById(R.id.TextVersion); textVersionView.setText(textVersion); SharedPreferences prefs = activity.getApplicationContext().getSharedPreferences("net.osmand.settings", MODE_WORLD_READABLE); // only one commit should be with contribution version flag // prefs.edit().putBoolean(CONTRIBUTION_VERSION_FLAG, true).commit(); if (prefs.contains(CONTRIBUTION_VERSION_FLAG)) { SpannableString content = new SpannableString(textVersion); content.setSpan(new ClickableSpan() { @Override public void onClick(View widget) { final Intent mapIntent = new Intent(activity, ContributionVersionActivity.class); activity.startActivityForResult(mapIntent, 0); // test geo activity // String uri = "geo:0,0?q=Amsterdamseweg"; // Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(uri)); // activity.startActivity(intent); } }, 0, content.length(), 0); textVersionView.setText(content); textVersionView.setMovementMethod(LinkMovementMethod.getInstance()); } View helpButton = window.findViewById(R.id.HelpButton); helpButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { TipsAndTricksActivity tactivity = new TipsAndTricksActivity(activity); Dialog dlg = tactivity.getDialogToShowTips(false, true); dlg.show(); } }); } @Override protected void onCreate(Bundle savedInstanceState) { ((OsmandApplication) getApplication()).applyTheme(this); super.onCreate(savedInstanceState); boolean exit = false; if(getIntent() != null){ Intent intent = getIntent(); if(intent.getExtras() != null && intent.getExtras().containsKey(APP_EXIT_KEY)){ exit = true; } } requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.menu); onCreateMainMenu(getWindow(), this); Window window = getWindow(); final Activity activity = this; View showMap = window.findViewById(R.id.MapButton); showMap.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { final Intent mapIndent = new Intent(activity, OsmandIntents.getMapActivity()); activity.startActivityForResult(mapIndent, 0); } }); View settingsButton = window.findViewById(R.id.SettingsButton); settingsButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { final Intent settings = new Intent(activity, OsmandIntents.getSettingsActivity()); activity.startActivity(settings); } }); View favouritesButton = window.findViewById(R.id.FavoritesButton); favouritesButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { final Intent favorites = new Intent(activity, OsmandIntents.getFavoritesActivity()); favorites.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); activity.startActivity(favorites); } }); final View closeButton = window.findViewById(R.id.CloseButton); closeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { getMyApplication().closeApplication(activity); } }); View searchButton = window.findViewById(R.id.SearchButton); searchButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { final Intent search = new Intent(activity, OsmandIntents.getSearchActivity()); search.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); activity.startActivity(search); } }); if(exit){ getMyApplication().closeApplication(activity); return; } OsmandApplication app = getMyApplication(); // restore follow route mode if(app.getSettings().FOLLOW_THE_ROUTE.get() && !app.getRoutingHelper().isRouteCalculated()){ final Intent mapIndent = new Intent(this, OsmandIntents.getMapActivity()); startActivityForResult(mapIndent, 0); return; } startProgressDialog = new ProgressDialog(this); getMyApplication().checkApplicationIsBeingInitialized(this, startProgressDialog); SharedPreferences pref = getPreferences(MODE_WORLD_WRITEABLE); boolean firstTime = false; if(!pref.contains(FIRST_TIME_APP_RUN)){ firstTime = true; pref.edit().putBoolean(FIRST_TIME_APP_RUN, true).commit(); pref.edit().putString(VERSION_INSTALLED, Version.getFullVersion(app)).commit(); applicationInstalledFirstTime(); } else { int i = pref.getInt(TIPS_SHOW, 0); if (i < 7){ pref.edit().putInt(TIPS_SHOW, ++i).commit(); } boolean appVersionChanged = false; if(!Version.getFullVersion(app).equals(pref.getString(VERSION_INSTALLED, ""))){ pref.edit().putString(VERSION_INSTALLED, Version.getFullVersion(app)).commit(); appVersionChanged = true; } if (i == 1 || i == 5 || appVersionChanged) { TipsAndTricksActivity tipsActivity = new TipsAndTricksActivity(this); Dialog dlg = tipsActivity.getDialogToShowTips(!appVersionChanged, false); dlg.show(); } else { if (startProgressDialog.isShowing()) { startProgressDialog.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { checkVectorIndexesDownloaded(); } }); } else { checkVectorIndexesDownloaded(); } } } checkPreviousRunsForExceptions(firstTime); } private void applicationInstalledFirstTime() { boolean netOsmandWasInstalled = false; try { ApplicationInfo applicationInfo = getPackageManager().getApplicationInfo("net.osmand", PackageManager.GET_META_DATA); netOsmandWasInstalled = applicationInfo != null && !Version.isFreeVersion(getMyApplication()); } catch (NameNotFoundException e) { netOsmandWasInstalled = false; } if(netOsmandWasInstalled){ Builder builder = new AccessibleAlertBuilder(this); builder.setMessage(R.string.osmand_net_previously_installed); builder.setPositiveButton(R.string.default_buttons_ok, null); builder.show(); } else { Builder builder = new AccessibleAlertBuilder(this); builder.setMessage(R.string.first_time_msg); builder.setPositiveButton(R.string.first_time_download, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { startActivity(new Intent(MainMenuActivity.this, OsmandIntents.getDownloadIndexActivity())); } }); builder.setNegativeButton(R.string.first_time_continue, null); builder.show(); } } protected void checkVectorIndexesDownloaded() { MapRenderRepositories maps = getMyApplication().getResourceManager().getRenderer(); SharedPreferences pref = getPreferences(MODE_WORLD_WRITEABLE); boolean check = pref.getBoolean(VECTOR_INDEXES_CHECK, true); // do not show each time if (check && new Random().nextInt() % 5 == 1) { Builder builder = new AccessibleAlertBuilder(this); if(maps.isEmpty()){ builder.setMessage(R.string.vector_data_missing); } else if(!maps.basemapExists()){ builder.setMessage(R.string.basemap_missing); } else { return; } builder.setPositiveButton(R.string.download_files, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { startActivity(new Intent(MainMenuActivity.this, DownloadIndexActivity.class)); } }); builder.setNeutralButton(R.string.vector_map_not_needed, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { getPreferences(MODE_WORLD_WRITEABLE).edit().putBoolean(VECTOR_INDEXES_CHECK, false).commit(); } }); builder.setNegativeButton(R.string.first_time_continue, null); builder.show(); } } private OsmandApplication getMyApplication() { return (OsmandApplication) getApplication(); } @Override protected Dialog onCreateDialog(int id) { if(id == OsmandApplication.PROGRESS_DIALOG){ return startProgressDialog; } return super.onCreateDialog(id); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_SEARCH && event.getRepeatCount() == 0) { final Intent search = new Intent(MainMenuActivity.this, SearchActivity.class); search.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); startActivity(search); return true; } return super.onKeyDown(keyCode, event); } public static void backToMainMenuDialog(final Activity a, final LatLon searchLocation) { final Dialog dlg = new Dialog(a, R.style.Dialog_Fullscreen); final View menuView = (View) a.getLayoutInflater().inflate(R.layout.menu, null); menuView.setBackgroundColor(Color.argb(200, 150, 150, 150)); dlg.setContentView(menuView); MainMenuActivity.onCreateMainMenu(dlg.getWindow(), a); Animation anim = new Animation() { @Override protected void applyTransformation(float interpolatedTime, Transformation t) { ColorDrawable colorDraw = ((ColorDrawable) menuView.getBackground()); colorDraw.setAlpha((int) (interpolatedTime * 200)); } }; anim.setDuration(700); anim.setInterpolator(new AccelerateInterpolator()); menuView.setAnimation(anim); View showMap = dlg.findViewById(R.id.MapButton); showMap.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dlg.dismiss(); } }); View settingsButton = dlg.findViewById(R.id.SettingsButton); settingsButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { final Intent settings = new Intent(a, OsmandIntents.getSettingsActivity()); a.startActivity(settings); dlg.dismiss(); } }); View favouritesButton = dlg.findViewById(R.id.FavoritesButton); favouritesButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { final Intent favorites = new Intent(a, OsmandIntents.getFavoritesActivity()); favorites.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); a.startActivity(favorites); dlg.dismiss(); } }); View closeButton = dlg.findViewById(R.id.CloseButton); closeButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dlg.dismiss(); // 1. Work for almost all cases when user open apps from main menu Intent newIntent = new Intent(a, OsmandIntents.getMainMenuActivity()); newIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); newIntent.putExtra(MainMenuActivity.APP_EXIT_KEY, MainMenuActivity.APP_EXIT_CODE); a.startActivity(newIntent); // 2. good analogue but user will come back to the current activity onResume() // so application is not reloaded !!! // moveTaskToBack(true); // 3. bad results if user comes from favorites // a.setResult(MainMenuActivity.APP_EXIT_CODE); // a.finish(); } }); View searchButton = dlg.findViewById(R.id.SearchButton); searchButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { final Intent search = new Intent(a, OsmandIntents.getSearchActivity()); LatLon loc = searchLocation; search.putExtra(SearchActivity.SEARCH_LAT, loc.getLatitude()); search.putExtra(SearchActivity.SEARCH_LON, loc.getLongitude()); // causes wrong position caching: search.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); search.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); a.startActivity(search); dlg.dismiss(); } }); menuView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dlg.dismiss(); } }); dlg.show(); // Intent newIntent = new Intent(a, MainMenuActivity.class); // newIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // startActivity(newIntent); } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(0, 0, 0, R.string.exit_Button); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == 0) { getMyApplication().closeApplication(this); return true; } return false; } }
37.3107
130
0.737219
eff2b660296f12b877eff42462fc57fd59a6b464
522
package eu.midnightdust.motschen.dishes; import net.fabricmc.api.ClientModInitializer; import net.fabricmc.fabric.api.blockrenderlayer.v1.BlockRenderLayerMap; import net.minecraft.client.render.RenderLayer; public class DishesClient implements ClientModInitializer { @Override public void onInitializeClient() { BlockRenderLayerMap.INSTANCE.putBlocks(RenderLayer.getCutout(),DishesMain.TomatoBush); BlockRenderLayerMap.INSTANCE.putBlocks(RenderLayer.getCutout(),DishesMain.LettuceBush); } }
34.8
95
0.806513
e5755502588152120831644ad5d07eb9a55e7782
426
package one.yate.spring.cloud.provider.metadata.dao.mapper; import one.yate.spring.cloud.provider.metadata.dao.IBaseMapperDao; import one.yate.spring.cloud.provider.metadata.entity.OrderInfo; import org.springframework.stereotype.Repository; /** * 本段代码由sql2java自动生成. * https://github.com/yangting/sql2java * * @author Yate */ @Repository public interface OrderInfoMapper extends IBaseMapperDao<OrderInfo, Integer> { }
25.058824
77
0.798122
1c05945184e614d907fe24851061b2ecc0d2d717
2,308
/* * Copyright 2014 Achim Nierbeck. * * 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.ops4j.pax.web.utils; import javax.servlet.DispatcherType; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebFilter; import javax.servlet.annotation.WebInitParam; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class FilterAnnotationScanner { private final Logger log = LoggerFactory.getLogger(this.getClass()); public Boolean scanned = false; public String[] urlPatterns; public String filterName; public Integer loadOnStartup; public Boolean asyncSupported; public WebInitParam[] webInitParams; public MultipartConfig multiPartConfigAnnotation; public WebFilter filterAnnotation; public String[] servletNames; public DispatcherType[] dispatcherTypes; public FilterAnnotationScanner(Class<?> clazz) { filterAnnotation = (WebFilter) clazz.getAnnotation(WebFilter.class); if (filterAnnotation == null) { return; } scanned = true; multiPartConfigAnnotation = (MultipartConfig) clazz.getAnnotation(MultipartConfig.class); if (filterAnnotation.urlPatterns().length > 0 && filterAnnotation.value().length > 0) { log.warn(clazz.getName() + " defines both @WebFilter.value and @WebFilter.urlPatterns"); return; } urlPatterns = filterAnnotation.value(); if (urlPatterns.length == 0) { urlPatterns = filterAnnotation.urlPatterns(); } filterName = (filterAnnotation.filterName().equals("") ? clazz .getName() : filterAnnotation.filterName()); webInitParams = filterAnnotation.initParams(); servletNames = filterAnnotation.servletNames(); dispatcherTypes = filterAnnotation.dispatcherTypes(); asyncSupported = filterAnnotation.asyncSupported(); } }
27.807229
91
0.751733
ff60d348ac670ac4578c8ac7ce506a03ff98f0d9
3,145
package de.einholz.ehmooshroom.container; /*XXX: Do we need this? maybe in the future package de.alberteinholz.ehmooshroom.container; import java.util.Map; import java.util.NoSuchElementException; import de.alberteinholz.ehmooshroom.MooshroomLib; import de.alberteinholz.ehmooshroom.container.component.data.NameDataComponent; import io.netty.buffer.Unpooled; import nerdhub.cardinal.components.api.component.Component; import net.fabricmc.fabric.api.util.NbtType; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerInventory; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.PacketByteBuf; import net.minecraft.screen.ScreenHandler; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.text.Text; import net.minecraft.text.TranslatableText; import net.minecraft.util.Identifier; public interface AdvancedContainer { /* public AdvancedContainerBlockEntity(RegistryEntry registryEntry) { comps.put(MooshroomLib.HELPER.makeId("name"), new NameDataComponent("name")); comps.put(MooshroomLib.HELPER.makeId("config"), new ConfigDataComponent()); comps.forEach((id, comp) -> { if (comp instanceof AdvancedInventoryComponent) ((AdvancedInventoryComponent) comp).setConfig((ConfigDataComponent) comps.get(MooshroomLib.HELPER.makeId("config"))); }); } */ /* public Map<Identifier, Component> getComponents(); public void addComponent(Component comp) { } public NameDataComponent getNameComponent(); //you have to add all needed components first default public void fromTag(CompoundTag tag) { for (String key : tag.getKeys()) { Identifier id = new Identifier(key); if (!tag.contains(key, NbtType.COMPOUND) || tag.getCompound(key).isEmpty()) continue; if (!getComponents().containsKey(id)) { MooshroomLib.LOGGER.smallBug(new NoSuchElementException("There is no component with the id " + key + " in the AdvancedContainer" + getDisplayName().getString())); continue; } CompoundTag compTag = tag.getCompound(key); getComponents().get(id).fromTag(compTag); } } default public CompoundTag toTag(CompoundTag tag) { getComponents().forEach((id, comp) -> { CompoundTag compTag = new CompoundTag(); comp.toTag(compTag); if (!compTag.isEmpty()) tag.put(id.toString(), compTag); }); return tag; } default public Text getDisplayName() { return new TranslatableText(getNameComponent().containerName.getLabel().asString()); } default public ScreenHandler createMenu(int syncId, PlayerInventory playerInv, PlayerEntity player) { PacketByteBuf buf = new PacketByteBuf(Unpooled.buffer()); writeScreenOpeningData((ServerPlayerEntity) player, buf); return registryEntry.clientHandlerFactory.create(syncId, playerInv, buf); } public void writeScreenOpeningData(ServerPlayerEntity player, PacketByteBuf buf) { buf.writeBlockPos(pos); } } */
39.3125
178
0.710016
635753151eba90b8e1c274257eb7dc857506803a
3,182
package com.chibusoft.bakingtime; /** * Created by EBELE PC on 6/4/2018. */ import timber.log.Timber; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.support.v7.widget.RecyclerView; import android.widget.ImageView; import android.widget.TextView; import butterknife.BindView; import butterknife.ButterKnife; import java.util.List; public class BakingAdapter extends RecyclerView.Adapter<BakingAdapter.BakeViewHolder> { @BindView(R.id.bake_img) ImageView bake_image; @BindView(R.id.bake_text) TextView bake_text; // private static final String TAG = BakingAdapter.class.getSimpleName(); private List<Baking> bakingItems; private final ListItemClickListener mOnCLickListener; public interface ListItemClickListener{ //interface of item we want to capture click for //here we are interested in only one item interger clicked void onListItemClick(int clickedItemIndex); } public BakingAdapter(List<Baking> bakeItems, ListItemClickListener listener) { bakingItems = bakeItems; mOnCLickListener = listener; } @Override public BakeViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { Context context = viewGroup.getContext(); int layoutIdForListItem = R.layout.bake_list_item; LayoutInflater inflater = LayoutInflater.from(context); boolean shouldAttachToParentImmediately = false; View view = inflater.inflate(layoutIdForListItem, viewGroup, shouldAttachToParentImmediately); BakeViewHolder viewHolder = new BakeViewHolder(view); ButterKnife.bind(this, view); return viewHolder; } @Override public void onBindViewHolder(BakeViewHolder holder, int position) { // Log.d(TAG, "#" + position); Timber.d("#" + position); holder.bind(position); } @Override public int getItemCount() { if (bakingItems == null) return 0; return bakingItems.size(); } class BakeViewHolder extends RecyclerView.ViewHolder implements OnClickListener { public BakeViewHolder(View itemView) { super(itemView); itemView.setOnClickListener(this); } void bind(int index) { bake_text.setText(bakingItems.get(index).getName()); if(index == 0) bake_image.setImageResource(R.drawable.nutella); else if(index == 1) bake_image.setImageResource(R.drawable.brownies); else if(index == 2) bake_image.setImageResource(R.drawable.yellowcake); else if(index == 3) bake_image.setImageResource(R.drawable.cheesecake); else bake_image.setImageResource(R.drawable.cheesecake); } @Override public void onClick(View view) { int clickedPosition = getAdapterPosition(); mOnCLickListener.onListItemClick(clickedPosition); } } public void setData(List<Baking> baking) { bakingItems = baking; notifyDataSetChanged(); } }
28.159292
102
0.688561
f66e7fbc852ae6cb8974b3fa956fde37cc57b196
11,800
package li.cil.scannable.common.item; import li.cil.scannable.api.API; import li.cil.scannable.api.scanning.ScannerModule; import li.cil.scannable.client.ScanManager; import li.cil.scannable.client.audio.SoundManager; import li.cil.scannable.common.capabilities.CapabilityProviderScanner; import li.cil.scannable.common.capabilities.CapabilityScannerModule; import li.cil.scannable.common.config.Constants; import li.cil.scannable.common.config.Settings; import li.cil.scannable.common.container.ScannerContainerProvider; import li.cil.scannable.common.inventory.ItemHandlerScanner; import net.minecraft.client.Minecraft; import net.minecraft.client.util.ITooltipFlag; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.ServerPlayerEntity; import net.minecraft.inventory.container.INamedContainerProvider; import net.minecraft.item.Item; import net.minecraft.item.ItemGroup; import net.minecraft.item.ItemStack; import net.minecraft.nbt.CompoundNBT; import net.minecraft.util.ActionResult; import net.minecraft.util.Hand; import net.minecraft.util.NonNullList; import net.minecraft.util.SoundEvents; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TranslationTextComponent; import net.minecraft.world.World; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.capabilities.ICapabilityProvider; import net.minecraftforge.common.util.LazyOptional; import net.minecraftforge.energy.CapabilityEnergy; import net.minecraftforge.energy.IEnergyStorage; import net.minecraftforge.event.entity.PlaySoundAtEntityEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.network.NetworkHooks; import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.IItemHandler; import net.minecraftforge.registries.ObjectHolder; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; @ObjectHolder(API.MOD_ID) public final class ItemScanner extends AbstractItem { @ObjectHolder(Constants.NAME_SCANNER) public static final Item INSTANCE = null; public static boolean isScanner(final ItemStack stack) { return stack.getItem() == INSTANCE; } // --------------------------------------------------------------------- // public ItemScanner() { super(new Properties().maxStackSize(1)); } // --------------------------------------------------------------------- // // Item @Override public ICapabilityProvider initCapabilities(final ItemStack stack, @Nullable final CompoundNBT nbt) { return new CapabilityProviderScanner(stack); } @Override public void fillItemGroup(final ItemGroup group, final NonNullList<ItemStack> items) { super.fillItemGroup(group, items); if (!isInGroup(group)) { return; } if (group == ItemGroup.SEARCH) { return; // Called before capabilities have been initialized... } final ItemStack stack = new ItemStack(this); final LazyOptional<IEnergyStorage> energyStorage = stack.getCapability(CapabilityEnergy.ENERGY); if (!energyStorage.isPresent()) { return; } energyStorage.ifPresent(storage -> storage.receiveEnergy(storage.getMaxEnergyStored(), false)); items.add(stack); } @Override public void addInformation(final ItemStack stack, @Nullable final World world, final List<ITextComponent> tooltip, final ITooltipFlag flag) { super.addInformation(stack, world, tooltip, flag); tooltip.add(new TranslationTextComponent(Constants.TOOLTIP_SCANNER)); if (world == null) { return; // Presumably from initial search tree population where capabilities have not yet been initialized. } if (!Settings.useEnergy) { return; } final LazyOptional<IEnergyStorage> energyStorage = stack.getCapability(CapabilityEnergy.ENERGY); if (!energyStorage.isPresent()) { return; } energyStorage.ifPresent(storage -> { tooltip.add(new TranslationTextComponent(Constants.TOOLTIP_SCANNER_ENERGY, storage.getEnergyStored(), storage.getMaxEnergyStored())); }); } @Override public boolean showDurabilityBar(final ItemStack stack) { return Settings.useEnergy; } @Override public double getDurabilityForDisplay(final ItemStack stack) { if (!Settings.useEnergy) { return 0; } final LazyOptional<IEnergyStorage> energyStorage = stack.getCapability(CapabilityEnergy.ENERGY); return energyStorage .map(storage -> 1 - storage.getEnergyStored() / (float) storage.getMaxEnergyStored()) .orElse(1.0f); } @Override public ActionResult<ItemStack> onItemRightClick(final World world, final PlayerEntity player, final Hand hand) { final ItemStack stack = player.getHeldItem(hand); if (player.isSneaking()) { if (!world.isRemote) { final INamedContainerProvider containerProvider = new ScannerContainerProvider(player, hand); NetworkHooks.openGui((ServerPlayerEntity) player, containerProvider, buffer -> buffer.writeEnumValue(hand)); } } else { final List<ItemStack> modules = new ArrayList<>(); if (!collectModules(stack, modules)) { if (world.isRemote) { Minecraft.getInstance().ingameGUI.getChatGUI().printChatMessageWithOptionalDeletion(new TranslationTextComponent(Constants.MESSAGE_NO_SCAN_MODULES), Constants.CHAT_LINE_ID); } player.getCooldownTracker().setCooldown(this, 10); return ActionResult.resultFail(stack); } if (!tryConsumeEnergy(player, stack, modules, true)) { if (world.isRemote) { Minecraft.getInstance().ingameGUI.getChatGUI().printChatMessageWithOptionalDeletion(new TranslationTextComponent(Constants.MESSAGE_NOT_ENOUGH_ENERGY), Constants.CHAT_LINE_ID); } player.getCooldownTracker().setCooldown(this, 10); return ActionResult.resultFail(stack); } player.setActiveHand(hand); if (world.isRemote) { ScanManager.INSTANCE.beginScan(player, modules); SoundManager.INSTANCE.playChargingSound(); } } return ActionResult.resultSuccess(stack); } @Override public boolean shouldCauseReequipAnimation(final ItemStack oldStack, final ItemStack newStack, final boolean slotChanged) { return oldStack.getItem() != newStack.getItem() || slotChanged; } @Override public int getUseDuration(final ItemStack stack) { return Constants.SCAN_COMPUTE_DURATION; } @Override public void onUsingTick(final ItemStack stack, final LivingEntity entity, final int count) { if (entity.getEntityWorld().isRemote) { ScanManager.INSTANCE.updateScan(entity, false); } } @Override public void onPlayerStoppedUsing(final ItemStack stack, final World world, final LivingEntity entity, final int timeLeft) { if (world.isRemote) { ScanManager.INSTANCE.cancelScan(); SoundManager.INSTANCE.stopChargingSound(); } super.onPlayerStoppedUsing(stack, world, entity, timeLeft); } @Override public ItemStack onItemUseFinish(final ItemStack stack, final World world, final LivingEntity entity) { if (!(entity instanceof PlayerEntity)) { return stack; } if (world.isRemote) { SoundCanceler.cancelEquipSound(); } final List<ItemStack> modules = new ArrayList<>(); if (!collectModules(stack, modules)) { return stack; } final boolean hasEnergy = tryConsumeEnergy((PlayerEntity) entity, stack, modules, false); if (world.isRemote) { SoundManager.INSTANCE.stopChargingSound(); if (hasEnergy) { ScanManager.INSTANCE.updateScan(entity, true); SoundManager.INSTANCE.playActivateSound(); } else { ScanManager.INSTANCE.cancelScan(); } } final PlayerEntity player = (PlayerEntity) entity; player.getCooldownTracker().setCooldown(this, 40); return stack; } // --------------------------------------------------------------------- // static int getModuleEnergyCost(final PlayerEntity player, final ItemStack stack) { final LazyOptional<ScannerModule> module = stack.getCapability(CapabilityScannerModule.SCANNER_MODULE_CAPABILITY); return module.map(p -> p.getEnergyCost(player, stack)).orElse(0); } private static boolean tryConsumeEnergy(final PlayerEntity player, final ItemStack scanner, final List<ItemStack> modules, final boolean simulate) { if (!Settings.useEnergy) { return true; } if (player.isCreative()) { return true; } final LazyOptional<IEnergyStorage> energyStorage = scanner.getCapability(CapabilityEnergy.ENERGY); if (!energyStorage.isPresent()) { return false; } int totalCostAccumulator = 0; for (final ItemStack module : modules) { totalCostAccumulator += getModuleEnergyCost(player, module); } final int totalCost = totalCostAccumulator; final int extracted = energyStorage.map(storage -> storage.extractEnergy(totalCost, simulate)).orElse(0); if (extracted < totalCost) { return false; } return true; } private static boolean collectModules(final ItemStack scanner, final List<ItemStack> modules) { final LazyOptional<IItemHandler> itemHandler = scanner.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY); return itemHandler .filter(handler -> handler instanceof ItemHandlerScanner) .map(handler -> { final IItemHandler activeModules = ((ItemHandlerScanner) handler).getActiveModules(); boolean hasScannerModules = false; for (int slot = 0; slot < activeModules.getSlots(); slot++) { final ItemStack module = activeModules.getStackInSlot(slot); if (module.isEmpty()) { continue; } modules.add(module); final LazyOptional<ScannerModule> capability = module.getCapability(CapabilityScannerModule.SCANNER_MODULE_CAPABILITY); hasScannerModules |= capability.map(ScannerModule::hasResultProvider).orElse(false); } return hasScannerModules; }) .orElse(false); } // --------------------------------------------------------------------- // // Used to suppress the re-equip sound after finishing a scan (due to potential scanner item stack data change). private enum SoundCanceler { INSTANCE; public static void cancelEquipSound() { MinecraftForge.EVENT_BUS.register(SoundCanceler.INSTANCE); } @SubscribeEvent public void onPlaySoundAtEntityEvent(final PlaySoundAtEntityEvent event) { if (event.getSound() == SoundEvents.ITEM_ARMOR_EQUIP_GENERIC) { event.setCanceled(true); } MinecraftForge.EVENT_BUS.unregister(this); } } }
38.815789
195
0.653475
70ccf1974bd94f6d7141e8b3bb42fbf711cb5f4f
333
package ua.leonidius.trdinterface.controllers; import ua.leonidius.trdinterface.views.ScreenManager; public abstract class AmountSelectorController extends ItemDetailsViewController { public AmountSelectorController(ScreenManager manager) { super(manager); } public abstract void selectAmount(int amount); }
23.785714
82
0.792793
f08975faf3e012a6e55bc37d7bf654c26a3ee608
19,311
package com.github.ricorodriges.metricui.extractor.hibernate; import com.github.ricorodriges.metricui.extractor.ExtractorUtils; import com.github.ricorodriges.metricui.extractor.hibernate.HibernateMetricExtractor.HibernateMetricResult.*; import com.github.ricorodriges.metricui.model.MeterData; import lombok.experimental.UtilityClass; import java.time.Duration; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; import static com.github.ricorodriges.metricui.extractor.ExtractorUtils.findMetersByName; /** * @see org.hibernate.stat.HibernateMetrics */ @UtilityClass public final class HibernateMetricExtractor { public static List<HibernateMetricResult> extractResults(Collection<MeterData> meters) { List<MeterData> hibernateMeters = meters.stream() .filter(m -> m.getName().startsWith("hibernate.")) .collect(Collectors.toList()); return hibernateMeters.stream() .map(HibernateMetricExtractor::getEntityManagerFactory) .distinct() .map(manager -> new HibernateMetricResult(manager, extractSessions(hibernateMeters, manager), extractTransactions(hibernateMeters, manager), extractFlushCount(hibernateMeters, manager), extractConnections(hibernateMeters, manager), extractStatements(hibernateMeters, manager), extractSecondLevelCaches(hibernateMeters, manager), extractEntities(hibernateMeters, manager), extractCollections(hibernateMeters, manager), extractNaturalIdQueries(hibernateMeters, manager), extractQueries(hibernateMeters, manager), extractQueryPlans(hibernateMeters, manager), extractTimestampCache(hibernateMeters, manager))) .collect(Collectors.toList()); } private static SessionMetricResult extractSessions(Collection<MeterData> meters, String manager) { long openSessions = findMetersByName(meters, "hibernate.sessions.open") .filter(m -> manager.equals(getEntityManagerFactory(m))) .findAny() .flatMap(ExtractorUtils::getFirstValueAsLong) .orElse(0L); long closedSessions = findMetersByName(meters, "hibernate.sessions.closed") .filter(m -> manager.equals(getEntityManagerFactory(m))) .findAny() .flatMap(ExtractorUtils::getFirstValueAsLong) .orElse(0L); return new SessionMetricResult(openSessions, closedSessions); } private static TransactionMetricResult extractTransactions(Collection<MeterData> meters, String manager) { long success = findMetersByName(meters, "hibernate.transactions") .filter(m -> manager.equals(getEntityManagerFactory(m))) .filter(HibernateMetricExtractor::isTransactionSuccess) .findAny() .flatMap(ExtractorUtils::getFirstValueAsLong) .orElse(0L); long failure = findMetersByName(meters, "hibernate.transactions") .filter(m -> manager.equals(getEntityManagerFactory(m))) .filter(m -> !isTransactionSuccess(m)) .findAny() .flatMap(ExtractorUtils::getFirstValueAsLong) .orElse(0L); long optimisticFailures = findMetersByName(meters, "hibernate.optimistic.failures") .filter(m -> manager.equals(getEntityManagerFactory(m))) .findAny() .flatMap(ExtractorUtils::getFirstValueAsLong) .orElse(0L); return new TransactionMetricResult(success, failure, optimisticFailures); } private static long extractFlushCount(Collection<MeterData> meters, String manager) { return findMetersByName(meters, "hibernate.flushes") .filter(m -> manager.equals(getEntityManagerFactory(m))) .findAny() .flatMap(ExtractorUtils::getFirstValueAsLong) .orElse(0L); } private static long extractConnections(Collection<MeterData> meters, String manager) { return findMetersByName(meters, "hibernate.connections.obtained") .filter(m -> manager.equals(getEntityManagerFactory(m))) .findAny() .flatMap(ExtractorUtils::getFirstValueAsLong) .orElse(0L); } private static StatementMetricResult extractStatements(Collection<MeterData> meters, String manager) { long preparedStatements = findMetersByName(meters, "hibernate.statements") .filter(m -> manager.equals(getEntityManagerFactory(m))) .filter(m -> "prepared".equals(m.getTags().get("status"))) .findAny() .flatMap(ExtractorUtils::getFirstValueAsLong) .orElse(0L); long closedStatements = findMetersByName(meters, "hibernate.statements") .filter(m -> manager.equals(getEntityManagerFactory(m))) .filter(m -> "closed".equals(m.getTags().get("status"))) .findAny() .flatMap(ExtractorUtils::getFirstValueAsLong) .orElse(0L); return new StatementMetricResult(preparedStatements, closedStatements); } private static EntityMetricResult extractEntities(Collection<MeterData> meters, String manager) { long deletes = findMetersByName(meters, "hibernate.entities.deletes") .filter(m -> manager.equals(getEntityManagerFactory(m))) .findAny() .flatMap(ExtractorUtils::getFirstValueAsLong) .orElse(0L); long fetches = findMetersByName(meters, "hibernate.entities.fetches") .filter(m -> manager.equals(getEntityManagerFactory(m))) .findAny() .flatMap(ExtractorUtils::getFirstValueAsLong) .orElse(0L); long inserts = findMetersByName(meters, "hibernate.entities.inserts") .filter(m -> manager.equals(getEntityManagerFactory(m))) .findAny() .flatMap(ExtractorUtils::getFirstValueAsLong) .orElse(0L); long loads = findMetersByName(meters, "hibernate.entities.loads") .filter(m -> manager.equals(getEntityManagerFactory(m))) .findAny() .flatMap(ExtractorUtils::getFirstValueAsLong) .orElse(0L); long updates = findMetersByName(meters, "hibernate.entities.updates") .filter(m -> manager.equals(getEntityManagerFactory(m))) .findAny() .flatMap(ExtractorUtils::getFirstValueAsLong) .orElse(0L); return new EntityMetricResult(deletes, fetches, inserts, loads, updates); } private static CollectionMetricResult extractCollections(Collection<MeterData> meters, String manager) { long deletes = findMetersByName(meters, "hibernate.collections.deletes") .filter(m -> manager.equals(getEntityManagerFactory(m))) .findAny() .flatMap(ExtractorUtils::getFirstValueAsLong) .orElse(0L); long fetches = findMetersByName(meters, "hibernate.collections.fetches") .filter(m -> manager.equals(getEntityManagerFactory(m))) .findAny() .flatMap(ExtractorUtils::getFirstValueAsLong) .orElse(0L); long loads = findMetersByName(meters, "hibernate.collections.loads") .filter(m -> manager.equals(getEntityManagerFactory(m))) .findAny() .flatMap(ExtractorUtils::getFirstValueAsLong) .orElse(0L); long recreates = findMetersByName(meters, "hibernate.collections.recreates") .filter(m -> manager.equals(getEntityManagerFactory(m))) .findAny() .flatMap(ExtractorUtils::getFirstValueAsLong) .orElse(0L); long updates = findMetersByName(meters, "hibernate.collections.updates") .filter(m -> manager.equals(getEntityManagerFactory(m))) .findAny() .flatMap(ExtractorUtils::getFirstValueAsLong) .orElse(0L); return new CollectionMetricResult(deletes, fetches, loads, recreates, updates); } private static QueryMetricResult extractNaturalIdQueries(Collection<MeterData> meters, String manager) { Duration max = findMetersByName(meters, "hibernate.query.natural.id.executions.max") .filter(m -> manager.equals(getEntityManagerFactory(m))) .findAny() .flatMap(ExtractorUtils::getFirstValueAsDuration) .orElse(Duration.ZERO); long executions = findMetersByName(meters, "hibernate.query.natural.id.executions") .filter(m -> manager.equals(getEntityManagerFactory(m))) .findAny() .flatMap(ExtractorUtils::getFirstValueAsLong) .orElse(0L); long hits = findMetersByName(meters, "hibernate.cache.natural.id.requests") .filter(m -> manager.equals(getEntityManagerFactory(m))) .filter(HibernateMetricExtractor::isHit) .findAny() .flatMap(ExtractorUtils::getFirstValueAsLong) .orElse(0L); long misses = findMetersByName(meters, "hibernate.cache.natural.id.requests") .filter(m -> manager.equals(getEntityManagerFactory(m))) .filter(HibernateMetricExtractor::isMiss) .findAny() .flatMap(ExtractorUtils::getFirstValueAsLong) .orElse(0L); long puts = findMetersByName(meters, "hibernate.cache.natural.id.puts") .filter(m -> manager.equals(getEntityManagerFactory(m))) .findAny() .flatMap(ExtractorUtils::getFirstValueAsLong) .orElse(0L); return new QueryMetricResult(hits, misses, puts, executions, max); } private static QueryMetricResult extractQueries(Collection<MeterData> meters, String manager) { Duration max = findMetersByName(meters, "hibernate.query.executions.max") .filter(m -> manager.equals(getEntityManagerFactory(m))) .findAny() .flatMap(ExtractorUtils::getFirstValueAsDuration) .orElse(Duration.ZERO); long executions = findMetersByName(meters, "hibernate.query.executions") .filter(m -> manager.equals(getEntityManagerFactory(m))) .findAny() .flatMap(ExtractorUtils::getFirstValueAsLong) .orElse(0L); long hits = findMetersByName(meters, "hibernate.cache.query.requests") .filter(m -> manager.equals(getEntityManagerFactory(m))) .filter(HibernateMetricExtractor::isHit) .findAny() .flatMap(ExtractorUtils::getFirstValueAsLong) .orElse(0L); long misses = findMetersByName(meters, "hibernate.cache.query.requests") .filter(m -> manager.equals(getEntityManagerFactory(m))) .filter(HibernateMetricExtractor::isMiss) .findAny() .flatMap(ExtractorUtils::getFirstValueAsLong) .orElse(0L); long puts = findMetersByName(meters, "hibernate.cache.query.puts") .filter(m -> manager.equals(getEntityManagerFactory(m))) .findAny() .flatMap(ExtractorUtils::getFirstValueAsLong) .orElse(0L); return new QueryMetricResult(hits, misses, puts, executions, max); } private static QueryPlanMetricResult extractQueryPlans(Collection<MeterData> meters, String manager) { long hits = findMetersByName(meters, "hibernate.cache.query.plan") .filter(m -> manager.equals(getEntityManagerFactory(m))) .filter(HibernateMetricExtractor::isHit) .findAny() .flatMap(ExtractorUtils::getFirstValueAsLong) .orElse(0L); long misses = findMetersByName(meters, "hibernate.cache.query.plan") .filter(m -> manager.equals(getEntityManagerFactory(m))) .filter(HibernateMetricExtractor::isMiss) .findAny() .flatMap(ExtractorUtils::getFirstValueAsLong) .orElse(0L); return new QueryPlanMetricResult(hits, misses); } private static List<SecondLevelCacheMetricResult> extractSecondLevelCaches(Collection<MeterData> meters, String manager) { return findMetersByName(meters, "hibernate.second.level.cache.requests") .filter(m -> manager.equals(getEntityManagerFactory(m))) .map(HibernateMetricExtractor::getRegion) .distinct() .map(region -> { long hits = findMetersByName(meters, "hibernate.second.level.cache.requests") .filter(m -> manager.equals(getEntityManagerFactory(m))) .filter(m -> region.equals(getRegion(m))) .filter(HibernateMetricExtractor::isHit) .findAny() .flatMap(ExtractorUtils::getFirstValueAsLong) .orElse(0L); long misses = findMetersByName(meters, "hibernate.second.level.cache.requests") .filter(m -> manager.equals(getEntityManagerFactory(m))) .filter(m -> region.equals(getRegion(m))) .filter(HibernateMetricExtractor::isMiss) .findAny() .flatMap(ExtractorUtils::getFirstValueAsLong) .orElse(0L); long puts = findMetersByName(meters, "hibernate.second.level.cache.puts") .filter(m -> manager.equals(getEntityManagerFactory(m))) .filter(m -> region.equals(getRegion(m))) .findAny() .flatMap(ExtractorUtils::getFirstValueAsLong) .orElse(0L); return new SecondLevelCacheMetricResult(region, hits, misses, puts); }) .collect(Collectors.toList()); } private static TimestampCacheMetricResult extractTimestampCache(Collection<MeterData> meters, String manager) { long hits = findMetersByName(meters, "hibernate.cache.update.timestamps.requests") .filter(m -> manager.equals(getEntityManagerFactory(m))) .filter(HibernateMetricExtractor::isHit) .findAny() .flatMap(ExtractorUtils::getFirstValueAsLong) .orElse(0L); long misses = findMetersByName(meters, "hibernate.cache.update.timestamps.requests") .filter(m -> manager.equals(getEntityManagerFactory(m))) .filter(HibernateMetricExtractor::isMiss) .findAny() .flatMap(ExtractorUtils::getFirstValueAsLong) .orElse(0L); long puts = findMetersByName(meters, "hibernate.cache.update.timestamps.puts") .filter(m -> manager.equals(getEntityManagerFactory(m))) .findAny() .flatMap(ExtractorUtils::getFirstValueAsLong) .orElse(0L); return new TimestampCacheMetricResult(hits, misses, puts); } private static String getEntityManagerFactory(MeterData m) { return m.getTags().get("entityManagerFactory"); } private static String getRegion(MeterData m) { return m.getTags().get("region"); } private static boolean isTransactionSuccess(MeterData m) { return "success".equals(m.getTags().get("result")); } private static boolean isHit(MeterData m) { return "hit".equals(m.getTags().get("result")); } private static boolean isMiss(MeterData m) { return "miss".equals(m.getTags().get("result")); } @lombok.Data @lombok.AllArgsConstructor public static class HibernateMetricResult { private String entityManager; private SessionMetricResult sessions; private TransactionMetricResult transactions; private Long flushes; private Long obtainedConnections; private StatementMetricResult statements; private Collection<SecondLevelCacheMetricResult> secondLevelCaches; private EntityMetricResult entities; private CollectionMetricResult collections; private QueryMetricResult naturalIdQueries; private QueryMetricResult queries; private QueryPlanMetricResult queryPlans; private TimestampCacheMetricResult timestampCache; @lombok.Data @lombok.AllArgsConstructor public static class SessionMetricResult { private Long open; private Long closed; } @lombok.Data @lombok.AllArgsConstructor public static class TransactionMetricResult { private Long success; private Long failure; private Long optimisticFailures; } @lombok.Data @lombok.AllArgsConstructor public static class StatementMetricResult { private Long prepared; private Long closed; } @lombok.Data @lombok.AllArgsConstructor public static class SecondLevelCacheMetricResult { private String region; private Long hits; private Long misses; private Long puts; } @lombok.Data @lombok.AllArgsConstructor public static class EntityMetricResult { private Long deletes; private Long fetches; private Long inserts; private Long loads; private Long updates; } @lombok.Data @lombok.AllArgsConstructor public static class CollectionMetricResult { private Long deletes; private Long fetches; private Long loads; private Long recreates; private Long updates; } @lombok.Data @lombok.AllArgsConstructor public static class QueryMetricResult { private Long hits; private Long misses; private Long puts; private Long executions; private Duration maxExecutionTime; } @lombok.Data @lombok.AllArgsConstructor public static class QueryPlanMetricResult { private Long hits; private Long misses; } @lombok.Data @lombok.AllArgsConstructor public static class TimestampCacheMetricResult { private Long hits; private Long misses; private Long puts; } } }
45.978571
126
0.61017
10388a08ccfd5cc6b3b0cd5c3acdd98e341931a4
516
package vZ80.instruction.access; import vZ80.VirtualMachine; public interface I8bitAccessor { //---------------------------------------------------------- // STATIC VARIABLES //---------------------------------------------------------- //---------------------------------------------------------- // INSTANCE METHODS //---------------------------------------------------------- public int get8( VirtualMachine vm ); public void set8( VirtualMachine vm, int data ); }
30.352941
61
0.341085
046e9dec44a04c1f671b02d756a97732209533d2
694
package com.neo.sword2offer.q25; import com.neo.struct.ListNode; public class Solution { public ListNode merge(ListNode list1, ListNode list2) { if (list1 == null) { return list2; } if(list2 == null) { return list1; } ListNode head = null; if (list1 == null || list2.intValue < list1.intValue) { //链表2头结点比链表1大 head = list2; head.next = merge(list1, list2.next); } else if (list2 == null || list1.intValue < list2.intValue) { //链表1头结点比链表2大 head = list1; head.next = merge(list1.next, list2); } return head; } }
21.6875
70
0.517291
91ce1e36e278f412fdc68165ca45e47c2eda73af
534
package com.jozufozu.flywheel.core.source; import com.jozufozu.flywheel.core.source.span.Span; public interface FileIndex { /** * Returns an arbitrary file ID for use this compilation context, or generates one if missing. * * @param sourceFile The file to retrieve the ID for. * @return A file ID unique to the given sourceFile. */ int getFileID(SourceFile sourceFile); SourceFile getFile(int fileID); default Span getLineSpan(int fileId, int lineNo) { return getFile(fileId).getLineSpanNoWhitespace(lineNo); } }
26.7
95
0.754682
8d98a6eb1350ad1db0760e2f5682409c80eab64a
936
package com.matas.liteconstruct.db.models.companyrelations.repos; import java.util.List; import java.util.UUID; import com.matas.liteconstruct.db.models.companyrelations.abstractmodel.CompanyRelationsAbstract; public interface CompanyRelationsRepository { void addCompanyRelations(CompanyRelationsAbstract companyRelation); void removeCompanyRelationsBySlaveCompanyId(UUID slaveCompanyId); void removeCompanyRelationsByMasterCompanyRoleId(UUID slaveCompanyId, UUID masterCompanyRoleId); CompanyRelationsAbstract getCompanyRelationsByMasterSlaveRole(UUID masterCompanyId, UUID slaveCompanyId, UUID masterCompanyRoleId); List<CompanyRelationsAbstract> getCompanyRelationsByMaster(UUID masterCompanyId); List<CompanyRelationsAbstract> getCompanyRelationsBySlave(UUID slaveCompanyId); List<CompanyRelationsAbstract> getCompanyRelationsByMasterAndRole(UUID masterCompanyId, UUID masterCompanyRoleId); }
36
98
0.856838
04df33a2cd6f0beb5df962e7174230154bf32b9e
2,432
package top.ss007.springlearn.model; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.env.Environment; import org.springframework.stereotype.Repository; import top.ss007.springlearn.config.*; import top.ss007.springlearn.config.configuration_annotaion.Father; import top.ss007.springlearn.config.configuration_annotaion.MyConfiguration; /** * Created by Ben.Wang * <p> * author : Ben.Wang * date : 2021/5/12 14:13 * description: */ @Repository public class UserModel { @Value("${demo.user.name}") private String userName; private Environment environment; private final DatabaseConfig databaseConfig; private final InfoConfig infoConfig; private final ComplexConfig complexConfig; private final ConversionConfig conversionConfig; private final ImmutablePresident immutablePresident; @Autowired public MyConfiguration myConfiguration; @Autowired public UserModel(DatabaseConfig databaseConfig, InfoConfig infoConfig, ComplexConfig complexConfig, ConversionConfig conversionConfig, ImmutablePresident immutablePresident) { this.databaseConfig = databaseConfig; this.infoConfig = infoConfig; this.complexConfig = complexConfig; this.conversionConfig = conversionConfig; this.immutablePresident = immutablePresident; } @Autowired public void setEnvironment(Environment environment) { this.environment = environment; } public String getUserName(){ return userName + ":"+ infoConfig.getTest(); } public String getUserNameByEnv(){ return environment.getProperty("demo.user.name"); } public String getDatabaseInfo(){ return databaseConfig.toString(); } public String getComplexConfig(){ return complexConfig.toString(); } public String getConversionConfig(){ return conversionConfig.toString(); } public String getImmutablePresident(){ return immutablePresident.toString(); } public String isSameObj() { Father father1 = myConfiguration.father(); Father father2 = myConfiguration.father(); return String.format("father1:%s | father2:%s 是否为同一对象:%s",father1.getClass().getClassLoader(), father2.getClass().getClassLoader(),father1 == father2); } }
29.301205
179
0.720806
2b1517c85fff08e59677128eccd0c9758f75cea4
1,076
package prankmailrobot.config; import prankmailrobot.model.mail.Person; import java.util.ArrayList; /** * Interface à implémenter pour être un parser de la configuration de PrankMailRobot. * @author Forestier Quentin et Herzig Melvyn * @date 16/04/2021 */ public interface IConfigurationManager { /** * Getter de l'adresse du serveur smtp. * @return Retourne l'adresse du serveur smtp. */ String getSmtpServerAddress(); /** * Getter du port du serveur smtp. * @return Retourne le port du serveur smtp. */ int getSmtpServerPort(); /** * Getter du nombre de groupe de victimes. * @return Retourne le nombre de groupes. */ int getNumberOfGroups(); /** * Getter des personnes en CC. * @return Retourne les personnes en copie. */ ArrayList<Person> getWitnessesToCC(); /** * Getter des victimes. * @return Retourne les victimes. */ ArrayList<Person> getVictims(); /** * Getter des contenus. * @return Retourne les contenus. */ ArrayList<String> getContents(); }
21.52
85
0.660781
c39c76d3b374e49f0e1e6471153d6557dfe08707
945
/* Copyright (C) 2005-2011 Fabio Riccardi */ package com.lightcrafts.app; import com.lightcrafts.ui.toolkit.CoolButton; import javax.swing.*; /** * A button that does something at the ComboFrame level, interacting with * top-level components and displayed in a LayoutHeader. */ abstract class FrameButton extends CoolButton { private ComboFrame frame; @SuppressWarnings({"OverridableMethodCallInConstructor"}) protected FrameButton(ComboFrame frame, String text) { setText(text); this.frame = frame; updateButton(); } @SuppressWarnings({"OverridableMethodCallInConstructor"}) protected FrameButton(ComboFrame frame, Icon icon) { setIcon(icon); this.frame = frame; updateButton(); } public ComboFrame getComboFrame() { return frame; } // Called when things in the frame change (folder, document, etc.) abstract void updateButton(); }
24.868421
73
0.689947
cb314d6c931d8029bc04f563cf335ce8f8c56af6
208
package com.quarkdata.yunpan.api.service; /** * Created by [email protected] on 2018/6/4. */ public interface ExternalUserService { /** * 定时删除过期系统账号相关数据 */ Long timingDelete(); }
17.333333
52
0.668269
91753baf2bb7b51051486474db0d882b17dfbd72
3,439
package mitsk.gui; import javax.swing.*; import javax.swing.border.EmptyBorder; import java.awt.*; public class GUI extends JFrame { private Integer clients = 0; private JTextField clientsTextField = new JTextField(clients.toString()); private Integer impatient = 0; private JTextField impatientTextField = new JTextField(impatient.toString()); private Integer inQueue = 0; private JTextField inQueueTextField = new JTextField(inQueue.toString()); GUI() { setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setLocationRelativeTo(null); setTitle("Restaurant Federation"); { clientsTextField.setEditable(false); clientsTextField.setHorizontalAlignment(JTextField.CENTER); JLabel clientsLabel = new JLabel("Clients"); clientsLabel.setLabelFor(clientsTextField); clientsLabel.setVerticalTextPosition(JLabel.CENTER); clientsLabel.setHorizontalTextPosition(JLabel.CENTER); JPanel clientsPanel = new JPanel(new GridLayout(2, 1)); clientsPanel.add(clientsLabel); clientsPanel.add(clientsTextField); clientsPanel.setBorder(new EmptyBorder(16, 16, 16, 16)); add(clientsPanel); } { impatientTextField.setEditable(false); impatientTextField.setHorizontalAlignment(JTextField.CENTER); JLabel impatientLabel = new JLabel("Impatient Clients"); impatientLabel.setLabelFor(impatientTextField); impatientLabel.setVerticalTextPosition(JLabel.CENTER); impatientLabel.setHorizontalTextPosition(JLabel.CENTER); JPanel impatientPanel = new JPanel(new GridLayout(2, 1)); impatientPanel.add(impatientLabel); impatientPanel.add(impatientTextField); impatientPanel.setBorder(new EmptyBorder(16, 16, 16, 16)); add(impatientPanel); } { inQueueTextField.setEditable(false); inQueueTextField.setHorizontalAlignment(JTextField.CENTER); JLabel inQueueLabel = new JLabel("Queue"); inQueueLabel.setLabelFor(inQueueTextField); inQueueLabel.setVerticalTextPosition(JLabel.CENTER); inQueueLabel.setHorizontalTextPosition(JLabel.CENTER); JPanel inQueuePanel = new JPanel(new GridLayout(2, 1)); inQueuePanel.add(inQueueLabel); inQueuePanel.add(inQueueTextField); inQueuePanel.setBorder(new EmptyBorder(16, 16, 16, 16)); add(inQueuePanel); } setLayout(new GridLayout(1, 3)); } void addClient() { ++clients; updateAll(); } void addImpatientClient() { removeClient(); removeFromQueue(); ++impatient; updateAll(); } void addToQueue() { ++inQueue; updateAll(); } void removeClient() { --clients; updateAll(); } void removeFromQueue() { --inQueue; updateAll(); } public void run() { pack(); setVisible(true); } private void updateAll() { clientsTextField.setText(clients.toString()); impatientTextField.setText(impatient.toString()); inQueueTextField.setText(inQueue.toString()); validate(); repaint(); pack(); } }
26.05303
81
0.624019
d632fa96cc580e76265eda8bf8f4a81ff8134db7
1,869
package io.atomix.core.iterator.impl; import java.util.Queue; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentLinkedQueue; import io.atomix.core.iterator.AsyncIterator; import io.atomix.utils.concurrent.Futures; import io.atomix.utils.stream.StreamHandler; /** * Stream handler iterator. */ public class StreamHandlerIterator<T> implements StreamHandler<T>, AsyncIterator<T> { private final Queue<CompletableFuture<T>> queue = new ConcurrentLinkedQueue<>(); private volatile CompletableFuture<T> nextFuture; @Override public synchronized CompletableFuture<Boolean> hasNext() { CompletableFuture<T> future = queue.peek(); if (future == null) { if (nextFuture == null) { nextFuture = new CompletableFuture<>(); queue.add(nextFuture); } future = nextFuture; } return future.thenApply(value -> value != null); } @Override public synchronized CompletableFuture<T> next() { CompletableFuture<T> future = queue.poll(); if (future != null) { return future; } else if (nextFuture != null) { return nextFuture; } else { nextFuture = new CompletableFuture<>(); return nextFuture; } } @Override public synchronized void next(T value) { if (nextFuture != null) { nextFuture.complete(value); nextFuture = null; } else { queue.add(CompletableFuture.completedFuture(value)); } } @Override public synchronized void complete() { if (nextFuture != null) { nextFuture.complete(null); } else { queue.add(CompletableFuture.completedFuture(null)); } } @Override public synchronized void error(Throwable error) { if (nextFuture != null) { nextFuture.completeExceptionally(error); } else { queue.add(Futures.exceptionalFuture(error)); } } }
25.958333
85
0.676297
657da9511254dcfa5f68629ce60dbe5083da1096
207
package com.xxdb.data; /* * Interface for dictionary object */ public interface Dictionary extends Entity{ DATA_TYPE getKeyDataType(); Entity get(Scalar key); boolean put(Scalar key, Entity value); }
17.25
43
0.748792
b056f94dd4ae90019940f343e9b860ee4d6318d1
1,121
package com.Project3.Server.Service; import static org.junit.Assert.assertEquals; import javax.inject.Inject; import org.json.JSONException; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import com.Project3.Server.Domain.User; @RunWith(SpringRunner.class) @SpringBootTest public class UserJSONParserTest { @Inject UserJSONParser userJSONParser; User user; String testString; @Before public void initializeVariables() { JSONObject jsonObject = new JSONObject(); testString = "test"; try { jsonObject.put("username", testString); jsonObject.put("password", testString); jsonObject.put("email", testString); } catch (JSONException e) { e.printStackTrace(); } user = userJSONParser.parse(jsonObject); } @Test public void parseTest() { assertEquals(user.getUsername(), testString); assertEquals(user.getPassword(), testString); assertEquals(user.getEmail(), testString); } }
20.759259
60
0.752899
f01c14fed3b80802471e0835cced262ac081f506
3,148
//Licensed under the MIT License. //Include the license text thingy if you're gonna use this. //Copyright (c) 2016 Chansol Yang package com.cosmicsubspace.nerdyaudio.visuals; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.view.SurfaceHolder; import com.cosmicsubspace.nerdyaudio.helper.Log2; import com.cosmicsubspace.nerdyaudio.ui.VisualizationManager; public class VisualsRenderThread extends Thread { public static final String LOG_TAG = "CS_AFN"; Paint pt; int w, h; long lastDrawn = 0, currentDrawn = 1; float fps = 0; //float maxFPS=60.0f; //BaseRenderer renderer; VisualizationManager vm; SurfaceHolder sf; boolean active = true; Canvas c; public VisualsRenderThread() { pt = new Paint(Paint.ANTI_ALIAS_FLAG); vm = VisualizationManager.getInstance(); } public void setSurfaceHolder(SurfaceHolder sf) { //is this valid? this.sf = sf; } public void stopRender() { active = false; } /* public void setRenderer(BaseRenderer r){ if (this.renderer!=null) this.renderer.release(); this.renderer=r; }*/ public void setSize(int w, int h) { this.w = w; this.h = h; } /* public void setMaxFPS(float maxFPS){ this.maxFPS=maxFPS; this.minDelay=(int)(1000.0f/maxFPS); }*/ /* public BaseRenderer getRenderer(){ return renderer; } */ long lastTime = 0, currentTime; int framesDrawn = 0; @Override public void run() { while (active) { framesDrawn++; currentTime = System.currentTimeMillis(); if (lastTime + 1000 < currentTime) { //1 sec has elapsed. Update FPS. fps = framesDrawn; lastTime = currentTime; framesDrawn = 0; } c = sf.lockCanvas(); if (c == null) { Log2.log(2, this, "VisualsRenderThread: lockCanvas() returned null. breaking loop."); break; } c.drawColor(Color.WHITE); if (vm.getActiveRenderer() != null) vm.getActiveRenderer().draw(c, w, h); /* //Log2.log(1,this,"DB: "+lastDrawn+" | "+minDelay+" | "+System.currentTimeMillis()); while (lastDrawn+minDelay>System.currentTimeMillis()){ try { //Log2.log(1,this,"Sleeping(FPS too high)"); Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); Log2.log(e); } } */ pt.setTextSize(36.0f); pt.setStyle(Paint.Style.STROKE); pt.setStrokeWidth(8); pt.setColor(Color.BLACK); c.drawText("FPS: " + (int) fps, 10, 40, pt); pt.setStyle(Paint.Style.FILL); pt.setColor(Color.WHITE); c.drawText("FPS: " + (int) fps, 10, 40, pt); sf.unlockCanvasAndPost(c); } } }
25.593496
101
0.553367
dce7428e067ee01bf77a00140331631a14948932
538
package com.velocitypowered.api.util; /** * Represents where a chat message is going to be sent. */ public enum MessagePosition { /** * The chat message will appear in the client's HUD. These messages can be filtered out by the * client. */ CHAT, /** * The chat message will appear in the client's HUD and can't be dismissed. */ SYSTEM, /** * The chat message will appear above the player's main HUD. This text format doesn't support many * component features, such as hover events. */ ACTION_BAR }
24.454545
100
0.680297
1ecb3683a5870b0d0789993a6a99b2e4ef0a80fd
759
package ru.job4j.calculator.array; /** * удаление Удаление дубликатов в массиве. *@author afanasev sergei([email protected]) * */ public class ArrayDuplicate { public String[] remove(String[] array) { int n = array.length; for ( int i = 0, m = 0; i != n; i++, n = m ) { for ( int j = m = i + 1; j != n; j++ ) { if ( array[j] != array[i] ) { if ( m != j ) array[m] = array[j]; m++; } } } if ( n != array.length ) { String[] b = new String[n]; for ( int i = 0; i < n; i++ ) b[i] = array[i]; array = b; } return array; } }
21.685714
58
0.383399
5b09dd4ebc9ecbdd59fb6798eb6f6a0542f246c0
10,087
package com.github.hollykunge.security.admin.biz; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.github.hollykunge.security.admin.annotation.FilterByDeletedAndOrderHandler; import com.github.hollykunge.security.admin.api.dto.AdminUser; import com.github.hollykunge.security.admin.api.dto.OrgUser; import com.github.hollykunge.security.admin.constant.AdminCommonConstant; import com.github.hollykunge.security.admin.entity.Org; import com.github.hollykunge.security.admin.entity.OrgUserMap; import com.github.hollykunge.security.admin.entity.User; import com.github.hollykunge.security.admin.mapper.OrgMapper; import com.github.hollykunge.security.admin.mapper.OrgUserMapMapper; import com.github.hollykunge.security.admin.mapper.UserMapper; import com.github.hollykunge.security.admin.redis.service.IRedisDataBaseService; import com.github.hollykunge.security.admin.rpc.service.UserRestService; import com.github.hollykunge.security.admin.util.EasyExcelUtil; import com.github.hollykunge.security.admin.util.ExcelListener; import com.github.hollykunge.security.common.biz.BaseBiz; import com.github.hollykunge.security.common.constant.CommonConstants; import com.github.hollykunge.security.common.msg.ObjectRestResponse; import com.github.hollykunge.security.common.util.EntityUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; import org.springframework.web.multipart.MultipartFile; import tk.mybatis.mapper.entity.Example; import javax.annotation.Resource; import java.io.IOException; import java.util.*; import java.util.function.Predicate; import java.util.stream.Collectors; /** * @author 云雀小组 */ @Service @Transactional(rollbackFor = Exception.class) public class OrgBiz extends BaseBiz<OrgMapper, Org> { @Resource private OrgUserMapMapper orgUserMapMapper; @Resource private UserMapper userMapper; @Resource private UserBiz userBiz; @Resource IRedisDataBaseService iRedisDataBaseService; @Autowired private UserRestService userRestService; @Autowired private OrgMapper orgMapper; //用户缓存namespace private final String USER_ONLINE_KEY = "users_on_line:"; private final String USER_ONLINE = "700"; private final String USER_OFFLINE = "701"; @FilterByDeletedAndOrderHandler public List<AdminUser> getOrgUsers(String orgCode, String secretLevels, String PId, String grouptype, String localUserOrg) { //如果orgCode为航天二院,则直接返回空数据 if (AdminCommonConstant.NO_DATA_ORG_CODE.equals(orgCode)) { return new ArrayList<AdminUser>(); } User userParams = new User(); userParams.setOrgCode(orgCode); Example userExample = new Example(User.class); Example.Criteria criteria = userExample.createCriteria(); criteria.andLike("orgCode", orgCode + "%"); if (!StringUtils.isEmpty(secretLevels)) { String[] secretLevelArray = secretLevels.split(","); List<String> secretList = Arrays.asList(secretLevelArray); for (String secretLevel : secretLevelArray) { criteria.andIn("secretLevel", secretList); } } if (!StringUtils.isEmpty(PId)) { criteria.andNotEqualTo("PId", PId); } List<User> users = userMapper.selectByExample(userExample); List<AdminUser> userList; userList = JSON.parseArray(JSON.toJSONString(users), AdminUser.class); //科室内部 if ("0".equals(grouptype)) { userList = userList.stream().filter(new Predicate<AdminUser>() { @Override public boolean test(AdminUser adminUser) { if (StringUtils.isEmpty(adminUser.getOrgCode())) { return false; } return adminUser.getOrgCode().equals(localUserOrg); } }).collect(Collectors.toList()); } //跨科室 if ("1".equals(grouptype)) { String parentOrgCode; //过滤外网错误数据,内网正常人员不会出现5为以下的orgCode if (localUserOrg.length() > 6) { //为院机关 if (!AdminCommonConstant.ORG_CODE_INSTITUTE_ORGAN.equals(parentOrgCode = localUserOrg.substring(0, 6))) { parentOrgCode = localUserOrg.substring(0, 4); } } else { parentOrgCode = localUserOrg; } final String finalParentOrgCode = parentOrgCode; userList = userList.stream().filter(new Predicate<AdminUser>() { @Override public boolean test(AdminUser adminUser) { if (StringUtils.isEmpty(adminUser.getOrgCode())) { return false; } //内网中不可能出现人员orgcode长度小于6的值,此处过滤外网错误数据 if (adminUser.getOrgCode().length() < 6) { return false; } return adminUser.getOrgCode().substring(0, 6).contains(finalParentOrgCode); } }).collect(Collectors.toList()); } //跨场所显示全部数据 return userList; } // @CacheClear(pre = "permission") public void modifyOrgUsers(String orgId, String users) { OrgUserMap orgUserMap = new OrgUserMap(); orgUserMap.setOrgId(orgId); orgUserMapMapper.delete(orgUserMap); if (!StringUtils.isEmpty(users)) { String[] mem = users.split(","); for (String m : mem) { orgUserMap.setUserId(m); EntityUtils.setCreatAndUpdatInfo(orgUserMap); orgUserMapMapper.insertSelective(orgUserMap); } } } @Override protected String getPageName() { return null; } @Override public void insertSelective(Org entity) { EntityUtils.setCreatAndUpdatInfo(entity); entity.setId(entity.getOrgCode()); mapper.insertSelective(entity); } @FilterByDeletedAndOrderHandler public List<OrgUser> getChildOrgUser(String parentCode) throws Exception{ List<OrgUser> result = new ArrayList<>(); Example example = new Example(Org.class); Example.Criteria criteria = example.createCriteria(); criteria.andEqualTo("parentId",parentCode); List<Org> orgs = mapper.selectByExample(example); if(orgs.size() > 0){ return setOrgUserList(result,orgs,null); } User userTemp = new User(); userTemp.setOrgCode(parentCode); List<User> users = userBiz.selectList(userTemp); if(users.size() > 0){ return setOrgUserList(result,null,users); } return result; } private List<com.github.hollykunge.security.admin.api.dto.OrgUser> setOrgUserList(List<com.github.hollykunge.security.admin.api.dto.OrgUser> orgUserList, List<Org> orgs, List<User> users){ if(orgs != null){ orgUserList = JSONArray.parseArray(JSONObject.toJSONString(orgs),com.github.hollykunge.security.admin.api.dto.OrgUser.class); setUserOrOrgFlag(orgUserList,AdminCommonConstant.CONTACT_FLAG_ORGNODE); } if(users != null){ orgUserList = JSONArray.parseArray(JSONObject.toJSONString(users),com.github.hollykunge.security.admin.api.dto.OrgUser.class); setUserOrOrgFlag(orgUserList,AdminCommonConstant.CONTACT_FLAG_USERNODE); //先以在线状态降序,再以orderId升序 // orgUserList.sort(Comparator.comparing(com.github.hollykunge.security.admin.api.dto.OrgUser::getOnline) // .reversed().thenComparing(com.github.hollykunge.security.admin.api.dto.OrgUser::getOrderId)); } return orgUserList; } private void setUserOrOrgFlag(List<com.github.hollykunge.security.admin.api.dto.OrgUser> orgUserList, String flag){ orgUserList.stream().forEach(orgUser ->{ orgUser.setScopedSlotsTitle(flag); if(Objects.equals(AdminCommonConstant.CONTACT_FLAG_USERNODE,flag)){ orgUser.setOnline(true); //读取缓存判断用户是否在线 String online = iRedisDataBaseService.get(USER_ONLINE_KEY+orgUser.getId()); if(online==null || USER_OFFLINE.equals(online)){ orgUser.setOnline(false); } String userInfo = userRestService.getUserInfo(null, orgUser.getId()); List<AdminUser> adminUsers = JSONArray.parseArray(userInfo, AdminUser.class); if(adminUsers.size() > 0){ orgUser.setPathName(adminUsers.get(0).getPathName()); } } }); } public List<Org> getPathName(String orgCode) { Example example = new Example(Org.class); Example.Criteria criteria = example.createCriteria(); criteria.andEqualTo("orgCode",orgCode); List<Org> orgs = this.selectByExample(example); return orgs; } /** * fansq * 20-2-23 * 添加组织数据导入 * @param file * @return * @throws IOException */ public ObjectRestResponse importExcel(MultipartFile file) throws Exception { ExcelListener excelListener = EasyExcelUtil.importOrgExcel(file.getInputStream(),orgMapper); ObjectRestResponse objectRestResponse = new ObjectRestResponse(); objectRestResponse.setStatus(CommonConstants.HTTP_SUCCESS); objectRestResponse.setMessage("导入成功!"); return objectRestResponse; } /** * * @param orgCode * @param orgLevel * @return */ public List<Org> findOrgByLevelAndParentId(String orgCode, Integer orgLevel) { return orgMapper.findOrgByLevelAndParentId(orgCode,orgLevel); } }
41.171429
157
0.651333
cf94498ff69ed5daa77e015a0725c805bb4e1d74
81
package com.tarkiflettes.main; public enum MirrorType { MIRROR, FIX, WALL; }
9
30
0.728395
6fba45414f9575650318434df09094b51228e51d
334
package techloxa.gamificacion.juego3d; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Juego3dApplication { public static void main(String[] args) { SpringApplication.run(Juego3dApplication.class, args); } } // jijiji
22.266667
68
0.820359