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
|
---|---|---|---|---|---|
dc63bb7a44a52617cef92b6df947bf0d36db1cfc | 1,659 | /*
* Copyright © 2021 Cask Data, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package io.cdap.plugin.gcp.bigquery.sqlengine.transform;
import io.cdap.cdap.api.data.format.StructuredRecord;
import io.cdap.cdap.api.data.schema.Schema;
import io.cdap.cdap.api.dataset.lib.KeyValue;
import io.cdap.cdap.etl.api.Emitter;
import io.cdap.cdap.etl.api.SerializableTransform;
import org.apache.avro.generic.GenericData;
import org.apache.hadoop.io.LongWritable;
/**
* Transform used when pulling records from BigQuery.
*/
public class PullTransform extends SerializableTransform<KeyValue<LongWritable, GenericData.Record>, StructuredRecord> {
private final SQLEngineAvroToStructuredTransformer transformer;
private final Schema schema;
public PullTransform(Schema schema) {
this.transformer = new SQLEngineAvroToStructuredTransformer();
this.schema = schema;
}
@Override
public void transform(KeyValue<LongWritable, GenericData.Record> input, Emitter<StructuredRecord> emitter)
throws Exception {
StructuredRecord transformed = transformer.transform(input.getValue(), schema);
emitter.emit(transformed);
}
}
| 36.065217 | 120 | 0.773357 |
e2cc17160e88eba8608500657c7331af771785c5 | 4,211 | /*
* Copyright 2020 Mind Computing Inc, Sagebits LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 sh.isaac.misc.exporters.rf2.files;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.Optional;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.logging.log4j.LogManager;
/**
*
* @author <a href="mailto:[email protected]">Dan Armbrust</a>
*/
public abstract class RF2File
{
private final File location;
private final int colCount;
private final BufferedWriter writer;
private final Semaphore rowLock = new Semaphore(1);
private final AtomicInteger writtenData = new AtomicInteger(0);
/**
*
* @param rootFolder
* @param relativePath
* @param fileType
* @param contentType
* @param contentSubType
* @param languageCode
* @param releaseType
* @param namespace
* @param versionDate YYYYMMDD
* @param colNames
* @throws IOException
*/
public RF2File(File rootFolder, String relativePath, String fileType, String contentType, Optional<String> contentSubType, Optional<String> languageCode,
RF2ReleaseType releaseType, String namespace, String versionDate, String ... colNames) throws IOException
{
Path temp = rootFolder.toPath().resolve(releaseType.name() + "/" + relativePath);
location = temp.resolve(fileType + "_" + contentType + "_" + contentSubType.orElse("") + releaseType.name()
+ (languageCode.isEmpty() ? "" : "-" + languageCode.get()) + "_" + namespace + "_" + versionDate + ".txt").toFile();
location.getParentFile().mkdirs();
colCount = colNames.length;
writer = new BufferedWriter(new FileWriter(location, StandardCharsets.UTF_8));
writeRow(colNames);
//don't count the header
writtenData.decrementAndGet();
}
/**
* For ad-hoc files like my error log file
* @param rootFolder
* @param releaseType - may be null, to place a file in the root folder
* @param fileName
* @throws IOException
*/
protected RF2File(File rootFolder, RF2ReleaseType releaseType, String fileName) throws IOException
{
Path temp = rootFolder.toPath();
if (releaseType != null)
{
temp = temp.resolve(releaseType.name());
}
location = temp.resolve(fileName + ".log").toFile();
location.getParentFile().mkdirs();
colCount = 0;
writer = new BufferedWriter(new FileWriter(location, StandardCharsets.UTF_8));
}
/**
* This is thread safe
* @param columns - must match spec for file in length
* @throws IOException
*/
public void writeRow(String ... columns) throws IOException
{
if (columns.length != colCount)
{
throw new IllegalArgumentException("Wrong number of columns - should be " + colCount + " in " + location.toString());
}
rowLock.acquireUninterruptibly();
for (int i = 0; i < columns.length; i++)
{
writer.append(columns[i]);
if (i < (columns.length - 1))
{
writer.append("\t");
}
}
writer.append("\r\n");
rowLock.release();
writtenData.incrementAndGet();
}
/**
* Bypass all column checking, and just write the string as a full line.
* @throws IOException
*/
public void writeLine(String line) throws IOException
{
rowLock.acquireUninterruptibly();
writer.append(line);
writer.append("\r\n");
rowLock.release();
writtenData.incrementAndGet();
}
public void close() throws IOException
{
LogManager.getLogger().debug("Wrote {} rows of data to file {}", getWrittenRowCount(), location.getName());
writer.close();
}
public int getWrittenRowCount()
{
return writtenData.get();
}
}
| 29.243056 | 155 | 0.710283 |
4b5403cbf7263b8d155fdddfdabe0855dac0a1af | 582 | package core.meta;
import java.util.HashMap;
import java.util.Map;
public enum ActionsOnItem {
Harvested, Planted, Sold;
protected static final Map<String, ActionsOnItem> sv;
static {
sv = new HashMap<>();
for (ActionsOnItem v : values()) {
sv.put(v.toString().toLowerCase(), v);
}
}
public static ActionsOnItem fromString(String act) {
if (null == act || act.trim().isEmpty())
throw new IllegalArgumentException("Action can not be null nor empty");
return sv.get(act.toLowerCase());
}
}
| 23.28 | 83 | 0.613402 |
5c5c94df428ca5f5d6cfba0170461bb4c9fb9227 | 8,107 | package com.yoga.admin.shiro;
import com.yoga.core.redis.RedisOperator;
import com.yoga.core.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.Authenticator;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.mgt.SubjectFactory;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.session.mgt.SessionKey;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.subject.SubjectContext;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.mgt.DefaultWebSubjectFactory;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.type.filter.AssignableTypeFilter;
import org.springframework.web.filter.DelegatingFilterProxy;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Slf4j
@Configuration
public class ShiroConfiguration implements EnvironmentAware {
private Environment environment;
public void setEnvironment(Environment environment) {
this.environment = environment;
}
@Bean(name = "securityManager")
public DefaultWebSecurityManager getDefaultWebSecurityManager(ApplicationContext applicationContext, SessionManager sessionManager, SubjectFactory subjectFactory, Authenticator authenticator) {
DefaultWebSecurityManager dwsm = new DefaultWebSecurityManager();
dwsm.setAuthenticator(authenticator);
dwsm.setRealms(allRealms(applicationContext));
dwsm.setCacheManager(getEhCacheManager());
dwsm.setSessionManager(sessionManager);
dwsm.setSubjectFactory(subjectFactory);
return dwsm;
}
private List<Realm> allRealms(ApplicationContext applicationContext) {
List<Realm> realms = new ArrayList<>();
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
provider.addIncludeFilter(new AssignableTypeFilter(Realm.class));
log.debug("查找Shiro授权服务");
if (true) {
Set<BeanDefinition> definitions = provider.findCandidateComponents("com.**");
createRealmBean(applicationContext, realms, definitions);
}
String realmPackage = environment.getProperty("app.shiro.realm.package");
if (StringUtil.isNotBlank(realmPackage)) {
Set<BeanDefinition> definitions = provider.findCandidateComponents(realmPackage);
createRealmBean(applicationContext, realms, definitions);
}
log.debug("查找Shiro授权服务结束");
return realms;
}
private void createRealmBean(ApplicationContext applicationContext, List<Realm> realms, Set<BeanDefinition> definitions) {
for (BeanDefinition definition : definitions) {
try {
String beanName = definition.getBeanClassName();
Class c = Class.forName(beanName);
Realm realm = (Realm) applicationContext.getBean(c);
realms.add(realm);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
@Bean(name = "subjectFactory")
public DefaultWebSubjectFactory getDefaultWebSubjectFactory() {
return new DefaultWebSubjectFactory() {
@Override
public Subject createSubject(SubjectContext context) {
return super.createSubject(context);
}
};
}
@Bean
public RedisSessionDAO getRedisSessionDAO(RedisOperator redisOperator) {
RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
redisSessionDAO.setRedisOperator(redisOperator);
return redisSessionDAO;
}
@Autowired
@Bean(name = "sessionManager")
public DefaultWebSessionManager getDefaultWebSessionManager(RedisOperator redisOperator) {
DefaultWebSessionManager dwsm = new DefaultWebSessionManager() {
@Override
public Serializable getSessionId(SessionKey key) {
Serializable id = null;
if (WebUtils.isWeb(key)) {
ServletRequest request = WebUtils.getRequest(key);
if (request instanceof HttpServletRequest) {
id = ((HttpServletRequest) request).getHeader("token");
if (id == null) id = ((HttpServletRequest) request).getParameter("token");
}
}
if (id == null)id = super.getSessionId(key);
return id;
}
};
RedisSessionDAO sessionDAO = this.getRedisSessionDAO(redisOperator);
dwsm.setSessionDAO(sessionDAO);
return dwsm;
}
@Bean
public EhCacheManager getEhCacheManager() {
EhCacheManager em = new EhCacheManager();
em.setCacheManagerConfigFile("classpath:ehcache-shiro.xml");
return em;
}
@Bean(name = "authenticator")
public ModularRealmAuthenticator getAuthenticator() {
return new MultiRealmAuthenticator();
}
@Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean filterRegistration = new FilterRegistrationBean();
filterRegistration.setFilter(new DelegatingFilterProxy("shiroFilter"));
filterRegistration.addInitParameter("targetFilterLifecycle", "true");
filterRegistration.setEnabled(true);
filterRegistration.addUrlPatterns("/*");
filterRegistration.setOrder(Integer.MIN_VALUE);
return filterRegistration;
}
@Bean(name = "lifecycleBeanPostProcessor")
public LifecycleBeanPostProcessor getLifecycleBeanPostProcessor() {
return new LifecycleBeanPostProcessor();
}
@Bean
public DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator daap = new DefaultAdvisorAutoProxyCreator();
daap.setProxyTargetClass(true);
return daap;
}
@Bean
public AuthorizationAttributeSourceAdvisor getAuthorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor aasa = new AuthorizationAttributeSourceAdvisor();
aasa.setSecurityManager(securityManager);
return aasa;
}
@Bean(name = "shiroFilter")
public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new FilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager);
shiroFilterFactoryBean.setLoginUrl("/admin/toLogin");
shiroFilterFactoryBean.setSuccessUrl("/admin");
shiroFilterFactoryBean.setUnauthorizedUrl("/403");
Map<String, String> filterChainDefinitionMap = new ShiroXMLReader().filterChainDefinitionMap("/shiro-conf.xml");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
}
}
| 42.668421 | 197 | 0.729246 |
898fac8a4b8f69088dfca933d8d365f06707c7b4 | 1,592 | package com.db117.example.leetcode.solution2;
import java.util.HashMap;
import java.util.Map;
/**
* 205. 同构字符串
* 给定两个字符串 s 和 t,判断它们是否是同构的。
* <p>
* 如果 s 中的字符可以被替换得到 t ,那么这两个字符串是同构的。
* <p>
* 所有出现的字符都必须用另一个字符替换,同时保留字符的顺序。两个字符不能映射到同一个字符上,但字符可以映射自己本身。
* <p>
* 示例 1:
* <p>
* 输入: s = "egg", t = "add"
* 输出: true
* 示例 2:
* <p>
* 输入: s = "foo", t = "bar"
* 输出: false
* 示例 3:
* <p>
* 输入: s = "paper", t = "title"
* 输出: true
* 说明:
* 你可以假设 s 和 t 具有相同的长度。
* <p>
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/isomorphic-strings
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*
* @author db117
* @date 2019/8/11/011
**/
public class Solution205 {
public static void main(String[] args) {
System.out.println(new Solution205().isIsomorphic("foo", "bar"));
}
public boolean isIsomorphic(String s, String t) {
if (s.equals(t)) {
return true;
}
if (s.length() != t.length()) {
return false;
}
// 第一个字符串->第二个字符串
Map<Character, Character> map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
if (map.containsKey(s.charAt(i))) {
if (map.get(s.charAt(i)) != t.charAt(i)) {
// 如果s有,但不等于t
return false;
}
} else {
if (map.containsValue(t.charAt(i))) {
// s没有,t有
return false;
}
// 放入缓存
map.put(s.charAt(i), t.charAt(i));
}
}
return true;
}
}
| 22.422535 | 73 | 0.491834 |
62d3c24d7e15b5442ef2be5ff789ea68eda96a2a | 820 | package org.spoofax.jsglr2.util;
import org.spoofax.interpreter.terms.IStrategoTerm;
import org.spoofax.jsglr.client.InvalidParseTableException;
import org.spoofax.jsglr.client.ParseTable;
import org.spoofax.jsglr.client.SGLR;
import org.spoofax.jsglr.client.imploder.TermTreeFactory;
import org.spoofax.jsglr.client.imploder.TreeBuilder;
import org.spoofax.terms.TermFactory;
public interface WithJSGLR1 {
IStrategoTerm getParseTableTerm();
default SGLR getJSGLR1() throws InvalidParseTableException {
TermFactory termFactory = new TermFactory();
TreeBuilder jsglr1TreeBuilder = new TreeBuilder(new TermTreeFactory(termFactory));
ParseTable jsglr1ParseTable = new ParseTable(getParseTableTerm(), termFactory);
return new SGLR(jsglr1TreeBuilder, jsglr1ParseTable);
}
}
| 32.8 | 90 | 0.790244 |
4c9ad47aa8ca77fd5e2e9bd9f83b52910ab2e9e2 | 1,215 | package ru.pet.stockservices.service.impl;
import lombok.RequiredArgsConstructor;
import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Service;
import ru.pet.stockservices.dto.PermissionDto;
import ru.pet.stockservices.repository.PermissionRepository;
import ru.pet.stockservices.service.PermissionService;
import java.util.List;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
public class PermissionServiceImpl implements PermissionService {
private final PermissionRepository repository;
private final ModelMapper modelMapper;
@Override
public List<PermissionDto> findAll() {
return repository.findAll()
.stream()
.map(permission -> modelMapper.map(permission, PermissionDto.class))
.collect(Collectors.toList());
}
@Override
public PermissionDto findPermissionById(Long id) {
return modelMapper.map(repository.findById(id).orElseThrow(), PermissionDto.class);
}
@Override
public PermissionDto findByPermission(String permission) {
return modelMapper.map(repository.findByPermissionIgnoreCase(permission).orElseThrow(), PermissionDto.class);
}
}
| 31.973684 | 117 | 0.754733 |
aaa224db7ce4c7a6f99a088057a1292b58116d7b | 2,920 | package org.jw.basex.renjin;
import static org.basex.query.QueryError.castError;
import java.util.concurrent.Callable;
import org.basex.query.QueryContext;
import org.basex.query.QueryException;
import org.basex.query.expr.Expr;
import org.basex.query.expr.XQFunction;
import org.basex.query.util.list.AnnList;
import org.basex.query.value.Value;
import org.basex.query.value.item.FItem;
import org.basex.query.value.item.Item;
import org.basex.query.value.item.QNm;
import org.basex.query.value.node.FElem;
import org.basex.query.value.type.FuncType;
import org.basex.query.value.type.SeqType;
import org.basex.query.var.VarScope;
import org.basex.util.InputInfo;
import org.renjin.eval.Context;
import org.renjin.script.RenjinScriptEngine;
import org.renjin.sexp.Closure;
import org.renjin.sexp.Function;
import org.renjin.sexp.FunctionCall;
import org.renjin.sexp.PairList;
import org.renjin.sexp.SEXP;
public class XqRenjinFunction extends FItem implements XQFunction {
Function func;
XqRenjin renjin;
protected XqRenjinFunction(FuncType type, AnnList anns) {
super(type, anns);
}
public XqRenjinFunction(XqRenjin renjinIn, Function in) {
super(SeqType.ANY_FUN, new AnnList());
renjin = renjinIn;
func = in;
}
@Override
public QNm argName(int arg0) {
return QNm.get("arguments");
}
@Override
public int arity() {
return !(func instanceof Closure) ? 0 :
((Closure)func).getFormals().length();
}
@Override
public QNm funcName() {
return QNm.get("renjin_function");
}
@Override
public FuncType funcType() {
return FuncType.get(SeqType.ITEM_ZM, SeqType.ITEM_ZM);
}
@Override
public Expr inlineExpr(Expr[] arg0, QueryContext arg1, VarScope arg2, InputInfo arg3) throws QueryException {
return null;
}
@Override
public Item invItem(QueryContext qc, InputInfo ii, Value... args) throws QueryException {
return (Item) invValue(qc, ii, args);
}
@Override
public Value invValue(QueryContext qc, InputInfo ii, Value... args) throws QueryException {
RenjinScriptEngine engine = (RenjinScriptEngine) renjin.getEngine();
Context ctx = engine.getTopLevelContext();
PairList.Builder arguments = new PairList.Builder();
for(Value v : args) {
if(v.size() > 0) {
arguments.add(XqRenjinModule.xQueryValueToRValue(renjin, v));
}
}
FunctionCall call = new FunctionCall(func, arguments.build());
SEXP result = ctx.evaluate(call);
return XqRenjinModule.rValueToXQueryValue(renjin, result);
}
@Override
public int stackFrameSize() {
return 0;
}
@Override
public FItem coerceTo(FuncType ft, QueryContext arg1, InputInfo ii, boolean arg3) throws QueryException {
if(instanceOf(ft)) return this;
throw castError(ii, this, ft);
}
@Override
public void plan(FElem arg0) { }
@Override
public Object toJava() throws QueryException {
return this;
}
@Override
public String toString() {
return func.toString();
}
}
| 24.957265 | 110 | 0.745548 |
21983056b44125b0b261c1cabcb38d72f8dc1a71 | 2,401 | package com.example.focuss;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Vibrator;
import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
public class alertReciever extends BroadcastReceiver {
private static final String CHANNEL_ID="Sample_Channnel";
public void onReceive(Context context, Intent intent) {
int notificationId=intent.getIntExtra("notificationId",0);
String message= intent.getStringExtra("message");
Vibrator vibrator=(Vibrator)context.getSystemService(context.VIBRATOR_SERVICE);
vibrator.vibrate(2000);
Intent mainIntent= new Intent(context,MainActivity2.class);
PendingIntent contentIntent= PendingIntent.getActivity(context,0,mainIntent,0);
NotificationManager myNotification= (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
CharSequence channel_name="My Notification";
int importance= NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel= new NotificationChannel(CHANNEL_ID,channel_name,importance);
myNotification.createNotificationChannel(channel);
}
NotificationCompat.Builder builder=new NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_baseline_notifications_active_24)
.setContentTitle("Close now")
.setContentText(message)
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setContentIntent(contentIntent)
.setPriority(Notification.PRIORITY_MAX)
.setDefaults(Notification.DEFAULT_ALL);
myNotification.notify(notificationId,builder.build());
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r=RingtoneManager.getRingtone(context,notification);
r.play();
}
}
| 36.378788 | 121 | 0.740525 |
c45a921196827c61ba53af9faf7c2425d0a02ab7 | 1,008 | /*
* @(#)JFileURIChooser.java
*
* Copyright (c) 2009-2010 by the original authors of JHotDraw and all its
* contributors. All rights reserved.
*
* You may not use, copy or modify this file, except in compliance with the
* license agreement you entered into with the copyright holders. For details
* see accompanying license terms.
*/
package org.jhotdraw.gui;
import java.io.File;
import java.net.URI;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
/**
* JFileURIChooser.
*
* @author Werner Randelshofer
* @version $Id: JFileURIChooser.java 717 2010-11-21 12:30:57Z rawcoder $
*/
public class JFileURIChooser extends JFileChooser implements URIChooser {
@Override
public void setSelectedURI(URI uri) {
setSelectedFile(new File(uri));
}
@Override
public URI getSelectedURI() {
return getSelectedFile() == null ? null : getSelectedFile().toURI();
}
@Override
public JComponent getComponent() {
return this;
}
}
| 24.585366 | 77 | 0.700397 |
93390e3c0dda304b6de2fd7cfc25202f3f1f2e15 | 530 | package com.neu.his.backend.dao;
import com.neu.his.backend.pojo.UserEntity;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
public interface UserDAO extends JpaRepository<UserEntity, Integer> {
UserEntity findByUsername(String username);
UserEntity getByUsernameAndPassword(String username, String password);
List<UserEntity> findByDeptidAndRegistrationlevelidAndUsertype(int deptid, int registrationlevelid,int usertype);
}
| 29.444444 | 115 | 0.830189 |
e0553cf57c318a70c5b2715b0e74b1edae5c37fe | 7,118 | package com.rodvar.mfandroidtest;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.rodvar.mfandroidtest.adapter.CoffeeShopAdapter;
import com.rodvar.mfandroidtest.backend.CallMeBack;
import com.rodvar.mfandroidtest.backend.task.SearchTask;
import com.rodvar.mfandroidtest.model.IBaseModel;
import com.rodvar.mfandroidtest.model.Venue;
import java.text.DateFormat;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
public class CoffeeListActivity extends ActionBarActivity implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private static final String LAT_KEY = "##LAT##";
private static final String LON_KEY = "##LON##";
private static final String LIMIT = "8";
private static final String BASE_URL = "https://api.foursquare.com/v2/venues/search?client_id=ACAO2JPKM1MXHQJCK45IIFKRFR2ZVL0QASMCBCG5NPJQWF2G&client_secret=YZCKUYJ1WHUV2QICBXUBEILZI1DMPUIDP5SHV043O04FKBHL&v=20130815&ll=" + LAT_KEY + "," + LON_KEY + "&query=coffee&limit=" + LIMIT;
private static final long LOCATION_INTERVAL = 10000l;
private static final long LOCATION_FASTEST_INTERVAL = 5000l;
private CoffeeShopAdapter coffeeShopAdapter;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private boolean isRequestingLocationUpdates;
private Location currentLocation;
private String lastUpdateTime;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.buildGoogleApiClient();
this.createLocationRequest();
setContentView(R.layout.activity_coffee_list);
ListView listView = (ListView) this.findViewById(R.id.shopList);
this.coffeeShopAdapter = new CoffeeShopAdapter(this);
listView.setAdapter(this.coffeeShopAdapter);
}
private List<Venue> fakeList() {
List<Venue> list = new LinkedList<Venue>();
list.add(new Venue("Pepe", "91 Goulburn St", Long.valueOf(23l)));
list.add(new Venue("Pregfa", "231 Tuvieja en tanga", Long.valueOf(233l)));
list.add(new Venue("Largartoide", "91 Marriot St", Long.valueOf(354l)));
list.add(new Venue("Coffeee puto", "343 Marquick St", Long.valueOf(53l)));
return list;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_coffee_list, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onConnected(Bundle connectionHint) {
Log.d("LOCATION", "Connected!");
this.currentLocation = LocationServices.FusedLocationApi.getLastLocation(
googleApiClient);
this.startLocationUpdates();
}
@Override
public void onLocationChanged(Location location) {
currentLocation = location;
lastUpdateTime = DateFormat.getTimeInstance().format(new Date());
new SearchTask(new CallMeBack() {
@Override
public void done(IBaseModel object) {
List<Venue> venues = (List<Venue>) object;
Collections.sort(venues);
coffeeShopAdapter.reset(venues);
}
@Override
public void onError() {
Toast.makeText(CoffeeListActivity.this, "ERROR on call!", Toast.LENGTH_SHORT).show();
}
}, this.buildURL()).execute((String[]) null);
}
private String buildURL() {
return BASE_URL.replace(LAT_KEY, String.valueOf(this.currentLocation.getLatitude())).replace(LON_KEY, String.valueOf(this.currentLocation.getLongitude()));
}
@Override
protected void onResume() {
super.onResume();
this.checkGPS();
if (googleApiClient.isConnected() && !isRequestingLocationUpdates)
this.startLocationUpdates();
else
googleApiClient.connect();
}
private void checkGPS() {
if (!((LocationManager) this.getSystemService(Context.LOCATION_SERVICE))
.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
}
@Override
protected void onPause() {
super.onPause();
this.stopLocationUpdates();
}
protected void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(
googleApiClient, locationRequest, this);
this.isRequestingLocationUpdates = true;
}
protected void stopLocationUpdates() {
try {
LocationServices.FusedLocationApi.removeLocationUpdates(
googleApiClient, this);
this.isRequestingLocationUpdates = false;
} catch (Exception e) {
Log.e("LOCATION", "Failed", e);
}
}
protected void createLocationRequest() {
this.locationRequest = new LocationRequest();
this.locationRequest.setInterval(LOCATION_INTERVAL);
this.locationRequest.setFastestInterval(LOCATION_FASTEST_INTERVAL);
this.locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); //BALANCED_POWER_ACCURACY
}
protected synchronized void buildGoogleApiClient() {
this.googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
// TODO
Log.w("LOCATION", "CONNECTION FAILED");
}
@Override
public void onConnectionSuspended(int i) {
// TODO
Log.w("LOCATION", "CONNECTION SUSPENDED");
}
}
| 36.502564 | 285 | 0.689801 |
f7b8999e2237504a91ac4b888edeeb52629ec56c | 6,043 | package org.everit.json.schema.loader;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyMap;
import static org.everit.json.schema.JSONMatcher.sameJsonAs;
import static org.everit.json.schema.TestSupport.asStream;
import static org.everit.json.schema.loader.JsonValueTest.withLs;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import org.everit.json.schema.ResourceLoader;
import org.everit.json.schema.SchemaException;
import org.everit.json.schema.SchemaLocation;
import org.json.JSONObject;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class JsonPointerEvaluatorTest {
private static final JsonObject rootSchemaJson = withLs(JsonValue.of(ResourceLoader.DEFAULT.readObj("testschemas.json")
.getJSONObject("refPointerDerivatedFromPointer").toMap())).requireObject();
private static final ResourceLoader LOADER = ResourceLoader.DEFAULT;
@Test
void sameDocumentSuccess() {
JsonPointerEvaluator pointer = JsonPointerEvaluator.forDocument(rootSchemaJson, "#/definitions/Bar");
JsonObject actual = pointer.query().getQueryResult().requireObject();
assertEquals("dummy schema at #/definitions/Bar", actual.require("description").requireString());
assertEquals("http://localhost:1234/folder/", actual.ls.id.toString());
assertEquals(new SchemaLocation(asList("definitions", "Bar")), actual.ls.pointerToCurrentObj);
}
@Test
void sameDocumentNotFound() {
Assertions.assertThrows(SchemaException.class, () -> {
JsonPointerEvaluator pointer = JsonPointerEvaluator.forDocument(rootSchemaJson, "#/definitions/NotFound");
JsonObject actual = pointer.query().getQueryResult().requireObject();
assertEquals("dummy schema at #/definitions/Bar", actual.require("description").requireString());
assertEquals("http://localhost:1234/folder/", actual.ls.id.toString());
assertEquals(new SchemaLocation(asList("definitions", "Bar")), actual.ls.pointerToCurrentObj);
});
}
@Test
void arrayIndexSuccess() {
JsonPointerEvaluator pointer = JsonPointerEvaluator.forDocument(rootSchemaJson, "#/definitions/Array/0");
JsonObject actual = pointer.query().getQueryResult().requireObject();
assertEquals("dummy schema in array", actual.require("description").requireString());
}
@Test
void rootRefSuccess() {
JsonPointerEvaluator pointer = JsonPointerEvaluator.forDocument(rootSchemaJson, "#");
JsonObject actual = pointer.query().getQueryResult().requireObject();
assertSame(rootSchemaJson, actual);
}
@Test
void escaping() {
JsonPointerEvaluator pointer = JsonPointerEvaluator.forDocument(rootSchemaJson, "#/definitions/Escaping/sla~1sh/ti~0lde");
JsonObject actual = pointer.query().getQueryResult().requireObject();
assertEquals("tiled", actual.require("description").requireString());
}
private LoadingState createLoadingState(SchemaClient schemaClient, String ref) {
LoaderConfig config = new LoaderConfig(schemaClient, emptyMap(), SpecificationVersion.DRAFT_4, false);
URI parentScopeId = null;
Object rootSchemaJson = this.rootSchemaJson;
HashMap<String, Object> schemaJson = new HashMap<>();
schemaJson.put("$ref", ref);
return new LoadingState(config, new HashMap<>(), rootSchemaJson, schemaJson, parentScopeId, SchemaLocation.empty());
}
@Test
void remoteDocumentSuccess() throws URISyntaxException {
SchemaClient schemaClient = mock(SchemaClient.class);
when(schemaClient.get("http://localhost:1234/hello")).thenReturn(rootSchemaJsonAsStream());
JsonPointerEvaluator pointer = JsonPointerEvaluator
.forURL(schemaClient, "http://localhost:1234/hello#/definitions/Bar",
createLoadingState(schemaClient, "#/definitions/Foo"));
JsonObject actual = pointer.query().getQueryResult().requireObject();
assertEquals("dummy schema at #/definitions/Bar", actual.require("description").requireString());
assertEquals("http://localhost:1234/folder/", actual.ls.id.toString());
assertEquals(new SchemaLocation(new URI("http://localhost:1234/hello"), asList("definitions", "Bar")),
actual.ls.pointerToCurrentObj);
}
@Test
void remoteDocument_jsonParsingFailure() {
SchemaClient schemaClient = mock(SchemaClient.class);
when(schemaClient.get("http://localhost:1234/hello")).thenReturn(asStream("unparseable"));
SchemaException actual = assertThrows(SchemaException.class,
() -> JsonPointerEvaluator.forURL(schemaClient, "http://localhost:1234/hello#/foo", createLoadingState(schemaClient, "")).query()
);
assertEquals("http://localhost:1234/hello", actual.getSchemaLocation());
}
@Test
void schemaExceptionForInvalidURI() {
try {
SchemaClient schemaClient = mock(SchemaClient.class);
JsonPointerEvaluator subject = JsonPointerEvaluator.forURL(schemaClient, "||||",
createLoadingState(schemaClient, "#/definitions/Foo"));
subject.query();
fail("did not throw exception");
} catch (SchemaException e) {
assertThat(e.toJSON(), sameJsonAs(LOADER.readObj("pointer-eval-non-uri-failure.json")));
}
}
protected InputStream rootSchemaJsonAsStream() {
return asStream(new JSONObject(rootSchemaJson.toMap()).toString());
}
}
| 47.582677 | 141 | 0.712395 |
518209617b5f5b29b3dde4d1420f6a71686ac4db | 6,730 | package org.ak80.standin.verification;
import org.ak80.standin.ReceivedMessage;
import org.ak80.standin.verification.exception.*;
import java.util.List;
/**
* Define optionally how often a message is wanted to be received
*/
public final class Times implements VerificationMode {
public static final String MATCHED = " [*matched*]";
public static final String MATCHED_TOO_OFTEN = " [*matched too often*]";
private final long numberOfWantedMessages;
private long numberOfMatchedMessages;
/**
* Define how many times a message is wanted to be received
*
* @param numberOfWantedMessages number of wanted messages
*/
Times(long numberOfWantedMessages) {
if (numberOfWantedMessages < 0) {
throw new IllegalArgumentException("the wanted number of messages "
+ "must not be negative, the given value was "
+ numberOfWantedMessages);
}
this.numberOfWantedMessages = numberOfWantedMessages;
}
public static Times never() {
return new Times(0L);
}
public static Times once() {
return new Times(1L);
}
public static Times times(int wantedNumberOfMessages) {
return new Times(wantedNumberOfMessages);
}
@Override
public boolean verifyMode(List<ReceivedMessage> matchedMessages, List<ReceivedMessage> receivedMessages, String explanation) {
checkIfAnyReceived(receivedMessages.size(), explanation);
checkIfMatchWanted(matchedMessages, receivedMessages, explanation);
return true;
}
private void checkIfAnyReceived(long numberOfReceivedMessages, String explanation) {
if (numberOfReceivedMessages == 0) {
if (getNumberOfWantedMessages() > 0) {
throw new NoMessagesReceivedError("no messages received while looking for " + explanation);
}
}
}
private void checkIfMatchWanted(List<ReceivedMessage> matchedMessages, List<ReceivedMessage> receivedMessages, String explanation) {
if (matchedButNotWanted(matchedMessages.size())) {
throw new NeverWantedButReceivedError(
String.format("never wanted messages but received %s while looking for %s",
matchedMessages.size(), explanation) + printMatchedMessages(matchedMessages));
}
if (receivedOneButNotTheOneWanted(receivedMessages.size(), matchedMessages.size())) {
throw new MessageNotReceivedError("expected message not received, expected "
+ explanation + printReceivedMessages(receivedMessages, matchedMessages));
}
if (matchedTooManyMessages(matchedMessages.size())) {
throw new TooManyMessagesError(
String.format("more than %s messages received, received %s while looking for %s",
getNumberOfWantedMessages(), matchedMessages.size(), explanation)
+ printMatchedMessages(matchedMessages));
}
if (matchedTooFewMessages(matchedMessages.size()) && getNumberOfWantedMessages() == 1) {
throw new MessageNotReceivedError(
String.format("expected message not received, expected %s",
explanation) + printReceivedMessages(receivedMessages, matchedMessages));
}
if (matchedTooFewMessages(matchedMessages.size())) {
throw new NotEnoughMessagesError(
String.format("fewer than %s messages received, received %s while looking for %s",
getNumberOfWantedMessages(), matchedMessages.size(), explanation) +
printReceivedMessages(receivedMessages, matchedMessages));
}
}
private boolean matchedButNotWanted(long numberOfMatchedMessages) {
boolean matchedMessages = numberOfMatchedMessages > 0;
boolean notWantedMessages = getNumberOfWantedMessages() == 0;
return matchedMessages && notWantedMessages;
}
private boolean receivedOneButNotTheOneWanted(long numberOfReceivedMessage, long numberOfMatchedMessages) {
boolean receivedOne = numberOfReceivedMessage == 1;
boolean matchedNone = numberOfMatchedMessages == 0;
boolean wantedMessages = getNumberOfWantedMessages() == 1;
return receivedOne && matchedNone && wantedMessages;
}
private boolean matchedTooManyMessages(long numberOfMatchedMessages) {
return numberOfMatchedMessages > getNumberOfWantedMessages();
}
private boolean matchedTooFewMessages(long numberOfMatchedMessages) {
return numberOfMatchedMessages < getNumberOfWantedMessages();
}
String printReceivedMessages(List<ReceivedMessage> receivedMessages, List<ReceivedMessage> matchedMessages) {
if (receivedMessages.isEmpty()) {
return "";
}
StringBuilder prettyPrinted = new StringBuilder("\nReceived messages:\n");
numberOfMatchedMessages = 0;
receivedMessages.forEach(receivedMessage -> prettyPrinted.append(printReceivedMessage(receivedMessage, matchedMessages)));
return prettyPrinted.toString();
}
private String printReceivedMessage(ReceivedMessage receivedMessage, List<ReceivedMessage> matchedMessages) {
return " " + receivedMessage + printMatched(receivedMessage, matchedMessages) + "\n";
}
private String printMatched(ReceivedMessage receivedMessage, List<ReceivedMessage> matchedMessages) {
if (matchedMessages.contains(receivedMessage)) {
numberOfMatchedMessages = numberOfMatchedMessages + 1;
if (numberOfMatchedMessages <= getNumberOfWantedMessages()) {
return MATCHED;
} else {
return MATCHED_TOO_OFTEN;
}
} else {
return "";
}
}
String printMatchedMessages(List<ReceivedMessage> matchedMessages) {
if (matchedMessages.isEmpty()) {
return "";
}
long expectedMessages = getNumberOfWantedMessages();
StringBuilder prettyPrinted = new StringBuilder("\nMatched messages:\n");
for (int i = 0; i < matchedMessages.size(); i++) {
prettyPrinted.append(" " + matchedMessages.get(i));
if (i < expectedMessages) {
prettyPrinted.append(MATCHED);
}
prettyPrinted.append("\n");
}
return prettyPrinted.toString();
}
public long getNumberOfWantedMessages() {
return numberOfWantedMessages;
}
public boolean is(Times times) {
return numberOfWantedMessages == times.getNumberOfWantedMessages();
}
}
| 41.54321 | 136 | 0.66315 |
8133c8773055331af133ea9853a24e605922b4e3 | 505 | package fox.spiteful.avaritia.compat.botania;
import net.minecraft.client.model.ModelBase;
import net.minecraft.client.model.ModelRenderer;
public class ModelInfinitato extends ModelBase {
ModelRenderer potato;
public ModelInfinitato() {
textureWidth = 64;
textureHeight = 32;
potato = new ModelRenderer(this, 0, 0);
potato.addBox(0F, 0F, 0F, 8, 12, 8);
potato.setRotationPoint(-4F, 12F, -4F);
potato.setTextureSize(64, 32);
}
public void render() {
potato.render(1F / 16F);
}
}
| 20.2 | 48 | 0.724752 |
7db019df609880066c80e14f37dac910825dbe6a | 4,140 | /*
ScoreBoard
Copyright © 2020 Adam Poole
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject
to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.floatingpanda.scoreboard.views.fragments;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.floatingpanda.scoreboard.R;
import com.floatingpanda.scoreboard.adapters.recyclerview_adapters.GameRecordDetailsSkillRatingListAdapter;
import com.floatingpanda.scoreboard.data.entities.GameRecord;
import com.floatingpanda.scoreboard.data.relations.PlayerTeamWithPlayersAndRatingChanges;
import com.floatingpanda.scoreboard.data.relations.PlayerWithRatingChanges;
import com.floatingpanda.scoreboard.viewmodels.GameRecordViewModel;
import java.util.List;
/**
* A view fragment which shows a list of category skill ratings and their changes resulting from a
* specific game record. The skill ratings are provided along with member details, showing whose
* ratings each are. The ratings are grouped for each member and the members are sorted according to
* their finishing positions in the game record. The skill ratings themselves are sorted in the
* grouping alphabetically based on category name.
*/
public class GameRecordSkillRatingsListFragment extends Fragment {
private GameRecord gameRecord;
//Holds the shared game record that is used by the fragment. This record is set in the calling
// activity - GameRecordActivity.
private GameRecordViewModel gameRecordViewModel;
public GameRecordSkillRatingsListFragment() { }
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.recyclerview_layout, container, false);
RecyclerView recyclerView = rootView.findViewById(R.id.recyclerview);
final GameRecordDetailsSkillRatingListAdapter adapter = new GameRecordDetailsSkillRatingListAdapter(getActivity());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
gameRecordViewModel = new ViewModelProvider(requireActivity()).get(GameRecordViewModel.class);
gameRecord = gameRecordViewModel.getSharedGameRecord();
gameRecordViewModel.getPlayerTeamsWithPlayersAndRatingChangesByRecordId(gameRecord.getId()).observe(getViewLifecycleOwner(), new Observer<List<PlayerTeamWithPlayersAndRatingChanges>>() {
@Override
public void onChanged(List<PlayerTeamWithPlayersAndRatingChanges> playerTeamsWithPlayersAndRatingChanges) {
List<PlayerWithRatingChanges> playersWithRatingChanges =
gameRecordViewModel.extractPlayersWithRatingChanges(playerTeamsWithPlayersAndRatingChanges);
adapter.setPlayersWithRatingChanges(playersWithRatingChanges);
}
});
return rootView;
}
}
| 47.586207 | 194 | 0.790097 |
ed216665520cec1661356ef43e2fabc5383d7236 | 2,835 | import net.runelite.mapping.Export;
import net.runelite.mapping.Implements;
import net.runelite.mapping.ObfuscatedGetter;
import net.runelite.mapping.ObfuscatedName;
import net.runelite.mapping.ObfuscatedSignature;
@ObfuscatedName("if")
@Implements("ArchiveDiskActionHandler")
public class ArchiveDiskActionHandler implements Runnable {
@ObfuscatedName("n")
@ObfuscatedSignature(
descriptor = "Lji;"
)
@Export("ArchiveDiskActionHandler_requestQueue")
public static NodeDeque ArchiveDiskActionHandler_requestQueue;
@ObfuscatedName("v")
@ObfuscatedSignature(
descriptor = "Lji;"
)
@Export("ArchiveDiskActionHandler_responseQueue")
public static NodeDeque ArchiveDiskActionHandler_responseQueue;
@ObfuscatedName("d")
@ObfuscatedGetter(
intValue = -1788680015
)
public static int field3187;
@ObfuscatedName("c")
@Export("ArchiveDiskActionHandler_lock")
public static Object ArchiveDiskActionHandler_lock;
@ObfuscatedName("y")
@Export("ArchiveDiskActionHandler_thread")
static Thread ArchiveDiskActionHandler_thread;
static {
ArchiveDiskActionHandler_requestQueue = new NodeDeque(); // L: 9
ArchiveDiskActionHandler_responseQueue = new NodeDeque(); // L: 10
field3187 = 0; // L: 11
ArchiveDiskActionHandler_lock = new Object();
} // L: 12
ArchiveDiskActionHandler() {
} // L: 15
public void run() {
try {
while (true) {
ArchiveDiskAction var1;
synchronized(ArchiveDiskActionHandler_requestQueue) { // L: 43
var1 = (ArchiveDiskAction)ArchiveDiskActionHandler_requestQueue.last(); // L: 44
} // L: 45
if (var1 != null) { // L: 46
if (var1.type == 0) { // L: 47
var1.archiveDisk.write((int)var1.key, var1.data, var1.data.length); // L: 48
synchronized(ArchiveDiskActionHandler_requestQueue) { // L: 49
var1.remove(); // L: 50
} // L: 51
} else if (var1.type == 1) { // L: 53
var1.data = var1.archiveDisk.read((int)var1.key); // L: 54
synchronized(ArchiveDiskActionHandler_requestQueue) { // L: 55
ArchiveDiskActionHandler_responseQueue.addFirst(var1); // L: 56
} // L: 57
}
synchronized(ArchiveDiskActionHandler_lock) { // L: 59
if (field3187 <= 1) { // L: 60
field3187 = 0; // L: 61
ArchiveDiskActionHandler_lock.notifyAll(); // L: 62
return; // L: 63
}
field3187 = 600; // L: 65
}
} else {
ApproximateRouteStrategy.sleepExact(100L); // L: 69
synchronized(ArchiveDiskActionHandler_lock) { // L: 70
if (field3187 <= 1) { // L: 71
field3187 = 0; // L: 72
ArchiveDiskActionHandler_lock.notifyAll(); // L: 73
return; // L: 74
}
--field3187; // L: 76
}
}
}
} catch (Exception var13) { // L: 81
SequenceDefinition.RunException_sendStackTrace((String)null, var13); // L: 82
}
} // L: 84
}
| 30.815217 | 85 | 0.680071 |
6379303a06d7037a279327167cf25201077564fa | 540 | package com.mailjet.client.errors;
/**
* Indicates that the error happened during communication with the server
* And the error nature is bound to the underlying HTTP provider / java.net stack
* Please, verify your network configuration
* */
public class MailjetClientCommunicationException extends MailjetException {
public MailjetClientCommunicationException(String message) {
super(message);
}
public MailjetClientCommunicationException(String message, Exception cause) {
super(message, cause);
}
}
| 31.764706 | 81 | 0.757407 |
88235a20d9eec6634cb02b66fa70097a0cebcd8f | 6,583 | /*
* Copyright (c) 2016. TedaLIEz <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hustunique.jianguo.dribile.ui.activity;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ViewAnimator;
import com.hustunique.jianguo.dribile.R;
import com.hustunique.jianguo.dribile.app.PresenterManager;
import com.hustunique.jianguo.dribile.models.Comments;
import com.hustunique.jianguo.dribile.models.Shots;
import com.hustunique.jianguo.dribile.presenters.CommentListPresenter;
import com.hustunique.jianguo.dribile.ui.adapters.CommentsAdapter;
import com.hustunique.jianguo.dribile.ui.viewholders.CommentsViewHolder;
import com.hustunique.jianguo.dribile.ui.widget.DividerItemDecoration;
import com.hustunique.jianguo.dribile.utils.Utils;
import com.hustunique.jianguo.dribile.utils.Logger;
import com.hustunique.jianguo.dribile.views.CommentListView;
import com.squareup.picasso.Picasso;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;
import jp.wasabeef.recyclerview.adapters.SlideInBottomAnimationAdapter;
public class ShotCommentActivity extends BaseActivity implements CommentListView {
private static final int POS_LOADING = 0;
private static final int POS_SHOW_DATA = 1;
private static final int POS_EMPTY = 2;
private static final String TAG = "ShotCommentActivity";
@BindView(R.id.comments_count)
TextView mCommentsTitle;
@BindView(R.id.comments_detail)
TextView mCommentsSubtitle;
@BindView(R.id.comments_list)
RecyclerView mComments;
@BindView(R.id.avatar_comments)
CircleImageView mAvatar;
@BindView(R.id.btn_send_comments)
FloatingActionButton mSend;
@BindView(R.id.et_add_comment)
EditText mEditText;
@BindView(R.id.animator)
ViewAnimator mAnimator;
private CommentsAdapter mAdapter;
private CommentListPresenter mCommentListPresenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shot_comment);
ButterKnife.bind(this);
Shots mShot = (Shots) getIntent().getSerializableExtra(Utils.EXTRA_SHOT);
if (mShot == null || TextUtils.isEmpty(mShot.getComments_url())) {
throw new NullPointerException("shot in ShotCommentActivity mustn't be null");
}
if (savedInstanceState == null) {
mCommentListPresenter = new CommentListPresenter(mShot);
} else {
PresenterManager.getInstance().restorePresenter(savedInstanceState);
}
initView();
}
private void initView() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mCommentListPresenter.sendComments(mEditText.getText().toString());
Utils.hideSoftInputFromWindow(ShotCommentActivity.this);
}
});
initCommentsRecyclerView();
}
//TODO: incorrect position of recyclerView
private void initCommentsRecyclerView() {
mAdapter = new CommentsAdapter(this, R.layout.item_comments);
mAdapter.setOnItemClickListener(new CommentsViewHolder.OnCommentClickListener() {
@Override
public void onCommentClick(Comments model) {
Utils.startActivityWithUser(ShotCommentActivity.this, ProfileActivity.class, model.getUser());
}
});
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
mComments.setAdapter(new SlideInBottomAnimationAdapter(mAdapter));
mComments.setLayoutManager(linearLayoutManager);
mComments.addItemDecoration(new DividerItemDecoration(this, R.drawable.divider));
}
@Override
public void onAddCommentSuccess(Comments comment) {
mEditText.setText("");
mAdapter.addItem(comment);
mComments.scrollToPosition(mAdapter.getItemCount() - 1);
}
@Override
public void onAddCommentError(Throwable e) {
Logger.wtf(TAG, e);
mEditText.setText("");
}
@Override
public void setTitle(String title) {
mCommentsTitle.setText(title);
}
@Override
public void setSubTitle(String subTitle) {
mCommentsSubtitle.setText(subTitle);
}
@Override
public void setAvatar(Uri avatar_url) {
Picasso.with(this).load(avatar_url)
.into(mAvatar);
}
@Override
public void showEmpty() {
mAnimator.setDisplayedChild(POS_EMPTY);
}
@Override
public void showLoading() {
mAnimator.setDisplayedChild(POS_LOADING);
}
@Override
public void onError(Throwable e) {
Logger.wtf(TAG, e);
}
@Override
public void showData(List<Comments> commentsList) {
mAnimator.setDisplayedChild(POS_SHOW_DATA);
mAdapter.clearAndAddAll(commentsList);
}
@Override
public void showLoadingMore() {
}
@Override
protected void onResume() {
super.onResume();
mCommentListPresenter.bindView(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
mCommentListPresenter.unbindView();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
PresenterManager.getInstance().savePresenter(mCommentListPresenter, outState);
}
}
| 32.915 | 110 | 0.716087 |
5dd9f7cf694acf225ebee9fcdead59239eab1e40 | 955 | package org.limmen.flexproxy.domain;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import static jakarta.xml.bind.annotation.XmlAccessType.FIELD;
import jakarta.xml.bind.annotation.XmlAccessorType;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlRootElement;
import java.io.IOException;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
@Data
@EqualsAndHashCode
@XmlAccessorType(FIELD)
@XmlRootElement(name = "status")
@Slf4j
public class Status implements Result {
@XmlElement(name = "status_code")
private int statusCode;
private String message;
@Override
public void handleResult(HttpServletRequest request, HttpServletResponse response) throws IOException {
log.debug("Response[statusCode={},message={}]", getStatusCode(), getMessage());
response.sendError(getStatusCode(), getMessage());
}
}
| 29.84375 | 105 | 0.793717 |
cda0580a2c8a69baec4f93d0f7af127ac74b17a3 | 1,623 | package com.pit.ext.system;
import com.pit.core.data.DataSizeUtil;
import com.pit.core.log.ILogService;
/**
* @author gy
* @version 1.0
* @date 2020/9/17.
* @description:
*/
public class RuntimeInfo {
/**
* 获得JVM最大内存
*
* @return 最大内存
*/
public final static long getMaxMemory() {
return Runtime.getRuntime().maxMemory();
}
/**
* 获得JVM已分配内存
*
* @return 已分配内存
*/
public final static long getTotalMemory() {
return Runtime.getRuntime().totalMemory();
}
/**
* 获得JVM已分配内存中的剩余空间
*
* @return 已分配内存中的剩余空间
*/
public final static long getFreeMemory() {
return Runtime.getRuntime().freeMemory();
}
/**
* 获得JVM最大可用内存
*
* @return 最大可用内存
*/
public final static long getUsableMemory() {
return Runtime.getRuntime().maxMemory() - Runtime.getRuntime().totalMemory() + Runtime.getRuntime().freeMemory();
}
public final static String printRuntimeInfo() {
StringBuilder builder = new StringBuilder(128);
ILogService.append(builder, "Max Memory: ", DataSizeUtil.prettyLook(getMaxMemory()), "\n");
ILogService.append(builder, "Total Memory: ", DataSizeUtil.prettyLook(getTotalMemory()), "\n");
ILogService.append(builder, "Free Memory: ", DataSizeUtil.prettyLook(getFreeMemory()), "\n");
ILogService.append(builder, "Usable Memory: ", DataSizeUtil.prettyLook(getUsableMemory()), "\n");
return builder.toString();
}
public static void main(String[] args) {
System.out.println(printRuntimeInfo());
}
}
| 25.359375 | 121 | 0.622304 |
344f67fcb4f7f4158837b57f7b5761208142a36f | 3,549 | /*-
* #%L
* anchor-plugin-image-task
* %%
* Copyright (C) 2010 - 2022 Owen Feehan, ETH Zurich, University of Zurich, Hoffmann-La Roche
* %%
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* #L%
*/
package org.anchoranalysis.plugin.image.task.bean.combine;
import java.util.Arrays;
import java.util.List;
import org.anchoranalysis.core.exception.OperationFailedException;
import org.anchoranalysis.image.io.ImageIOException;
import org.anchoranalysis.image.io.stack.input.StackSequenceInput;
import org.anchoranalysis.test.experiment.task.ExecuteTaskHelper;
import org.anchoranalysis.test.image.io.BeanInstanceMapFixture;
import org.junit.jupiter.api.Test;
/**
* Tests {@link Montage}.
*
* <p>Each test combines six inputs of different sizes and colors.
*
* @author Owen Feehan
*/
class MontageTest extends StackIOTestBase {
/** We don't test the labelled output as fonts vary on windows and linux. */
private static List<String> FILENAMES_TO_COMPARE =
Arrays.asList(Montage.OUTPUT_UNLABELLED + ".png");
static {
BeanInstanceMapFixture.ensureStackDisplayer();
}
/** Varying the image location and image size. */
@Test
void testVaryBoth() throws OperationFailedException, ImageIOException {
Montage task = new Montage();
task.setVaryImageLocation(true);
doTest(task, "varyBoth");
}
/** Varying the image size <b>only</b>. */
@Test
void testVaryImageSize() throws OperationFailedException, ImageIOException {
Montage task = new Montage();
task.setVaryImageLocation(false);
task.setVaryImageSize(true);
doTest(task, "varyImageSize");
}
/** Varying <b>neither</b> the image size nor location. */
@Test
void testVaryNeither() throws OperationFailedException, ImageIOException {
Montage task = new Montage();
task.setVaryImageLocation(false);
task.setVaryImageSize(false);
doTest(task, "varyNeither");
}
@SuppressWarnings("unchecked")
private void doTest(Montage task, String expectedOutputSubdirectory)
throws ImageIOException, OperationFailedException {
BeanInstanceMapFixture.check(task);
ExecuteTaskHelper.runTaskAndCompareOutputs(
(List<StackSequenceInput>) ColoredStacksInputFixture.createInputs(STACK_READER),
task,
directory,
"montage/expectedOutput/" + expectedOutputSubdirectory,
FILENAMES_TO_COMPARE);
}
}
| 37.755319 | 96 | 0.715131 |
412ba7de5606837987142fb3e8cf9d6fb885a0bb | 262 | package com.cybernetica.bj.client.interfaces;
import com.cybernetica.bj.client.events.UserDataEvent;
import com.cybernetica.bj.client.exceptions.ClientException;
public interface IDataListener {
void onUserData(UserDataEvent event) throws ClientException;
}
| 29.111111 | 62 | 0.839695 |
1b32187cc764f70210f8324959884b08d747f6e9 | 1,702 | package uk.org.ponder.streamutil;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import uk.org.ponder.util.Logger;
/** This class abstracts the idea of an array of bytes, and handles the task of
* converting it (the array, not the idea) to and from input and output streams.
*/
public class BytePen {
private InputStream stashed;
private byte[] bytes;
/** Returns an output stream to which the byte array contents can be written.
* @return An output stream to which the byte array contents can be written.
*/
public OutputStream getOutputStream() {
final ByteArrayOutputStream togo = new ByteArrayOutputStream();
OutputStream toreallygo = new TrackerOutputStream
(togo, new StreamClosedCallback() {
public void streamClosed(Object o) {
Logger.println("BytePen OutputStream closed", Logger.DEBUG_INFORMATIONAL);
bytes = togo.toByteArray();
}
});
return toreallygo;
}
/** Sets the input stream from which the byte array can be read.
* @param is The input stream from which the byte array can be read.
*/
public void setInputStream(InputStream is) {
stashed = is;
}
/** Returns an input stream from which the byte array can be read. If the
* array was specified via <code>setInputStream</code>, the original input
* stream will be returned.
* @return An input stream from which the byte array can be read.
*/
public InputStream getInputStream() {
if (stashed != null) {
InputStream togo = stashed;
stashed = null;
return togo;
}
else return new ByteArrayInputStream(bytes);
}
}
| 30.945455 | 81 | 0.706816 |
85bbb218877862c60e8d5f006ed5c9bda1a57773 | 821 | import java.util.Arrays;
/**
* @author Politeness Chen
* @create 2019--08--09 21:14
*/
public class _28_MoreThanHalfNum_Solution {
public int MoreThanHalfNum_Solution(int [] array) {
int count = 1;
int num = array[0];
for (int i = 0; i < array.length; i++) {
if (count == 0) {
count = 1;
num = array[i];
} else {
if (num == array[i]) {
count ++;
} else {
count --;
}
}
}
count = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == num) {
count ++;
}
}
if (count*2 <= array.length) {
return 0;
}
return num;
}
}
| 22.805556 | 55 | 0.377588 |
2685552ce734318e545bd329bca403eff06b4ab3 | 1,986 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.java.codeInspection;
import com.intellij.JavaTestUtil;
import com.intellij.analysis.AnalysisScope;
import com.intellij.codeInspection.unusedLibraries.UnusedLibrariesInspection;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.testFramework.InspectionTestCase;
import com.intellij.testFramework.PsiTestUtil;
import org.jetbrains.annotations.NotNull;
public class UnusedLibraryInspectionTest extends InspectionTestCase {
@Override
protected String getTestDataPath() {
return JavaTestUtil.getJavaTestDataPath() + "/inspection/unusedLibrary";
}
@Override
protected void setupRootModel(@NotNull String testDir, @NotNull VirtualFile[] sourceDir, String sdkName) {
super.setupRootModel(testDir, sourceDir, sdkName);
PsiTestUtil.addLibrary(getModule(), "JUnit", getTestDataPath(), "/junit.jar");
}
private void doTest() throws Exception {
doTest("/" + getTestName(true), new UnusedLibrariesInspection());
}
@NotNull
@Override
protected AnalysisScope createAnalysisScope(VirtualFile sourceDir) {
return new AnalysisScope(getProject());
}
public void testSimple() throws Exception { doTest(); }
public void testUsedJunit() throws Exception { doTest(); }
public void testUsedJunitFromField() throws Exception { doTest(); }
public void testUsedInParameterAnnotation() throws Exception { doTest(); }
}
| 36.777778 | 108 | 0.767875 |
3ca51883f6bf80674344719d789090f8c5456590 | 2,250 | //package com.sun.overweight.config;
//
//import org.apache.ibatis.session.SqlSessionFactory;
//import org.mybatis.spring.SqlSessionFactoryBean;
//import org.mybatis.spring.SqlSessionTemplate;
//import org.mybatis.spring.annotation.MapperScan;
//import org.springframework.beans.factory.annotation.Qualifier;
//import org.springframework.boot.context.properties.ConfigurationProperties;
//import org.springframework.boot.jdbc.DataSourceBuilder;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.context.annotation.Primary;
//import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
//import org.springframework.core.io.support.ResourcePatternResolver;
//
//import javax.sql.DataSource;
//
///**
// * @author wen
// */
//@Configuration
//@MapperScan(basePackages = {"com.sun.overweight.mapper","com.sun.overweight.ramp.common.model"}, sqlSessionTemplateRef = "pgSqlSessionTemplate")
//public class PgMybatisConfig {
//
// @Bean(name = "pgDataSource")
// /** 必须加此注解,不然报错,下一个类则不需要添加 */
// @Primary
// /** prefix值必须是application.properteis中对应属性的前缀 */
// @ConfigurationProperties(prefix = "spring.datasource")
// public DataSource pgDataSource() {
// return DataSourceBuilder.create().build();
// }
//
// @Bean
// public SqlSessionFactory pgSqlSessionFactory(@Qualifier("pgDataSource") DataSource dataSource) throws Exception {
// SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
// bean.setDataSource(dataSource);
// //添加XML目录
// ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
// try {
// bean.setMapperLocations(resolver.getResources("classpath:mybatis/mapper/*.xml"));
// return bean.getObject();
// } catch (Exception e) {
// e.printStackTrace();
// throw new RuntimeException(e);
// }
// }
//
// @Bean
// public SqlSessionTemplate pgSqlSessionTemplate(@Qualifier("pgSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
// // 使用上面配置的Factory
// SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory);
// return template;
// }
//}
| 40.178571 | 146 | 0.732 |
dc789c96c74f0069ec8106da6cac3c0b0b0aed82 | 2,450 | package com.mycompany.core.framework.reports;
import com.google.common.io.Files;
//import TestExecutionListener;
import java.io.File;
import java.io.IOException;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.testng.ITestResult;
import org.testng.Reporter;
public class CustomReporter
{
//static int value = 0;
public static void log(String paramString)
{
TestExecutionListener.lineNumber = java.lang.Thread.currentThread().getStackTrace()[2].getLineNumber();
Reporter.log(paramString);
}
public static void log(String paramString, boolean paramBoolean)
{
TestExecutionListener.lineNumber = java.lang.Thread.currentThread().getStackTrace()[2].getLineNumber();
Reporter.log(paramString, paramBoolean);
}
public static void logWithScreenShot(String paramString)
{
TestExecutionListener.lineNumber = java.lang.Thread.currentThread().getStackTrace()[2].getLineNumber();
Reporter.log(paramString);
String str1 = "[" + Reporter.getCurrentTestResult().getTestClass().getName() + "]" + Reporter.getCurrentTestResult().getName();
String str2 = takeScreenShot(TestExecutionListener.reportsDirectory + System.getProperty("file.separator") + "executions" + System.getProperty("file.separator") + "Execution_" + TestExecutionListener.executionCount + System.getProperty("file.separator") + "teststeps" + System.getProperty("file.separator") + "screenshots" + System.getProperty("file.separator") + str1, Reporter.getCurrentTestResult());
TestExecutionListener.screenShotNames.add(str2);
}
private static String takeScreenShot(String paramString, ITestResult paramITestResult)
{
File localFile = null;
String str = "";
int i = Integer.parseInt(paramITestResult.getAttribute("invokeCountAtttrib").toString());
localFile = new File(paramString + "_Iteration" +i + "_Step_" + Reporter.getOutput(Reporter.getCurrentTestResult()).size() + ".jpg");
// value++;
try
{
if ((TestEnvironmentProperties.driver instanceof TakesScreenshot))
{
byte[] arrayOfByte = ((TakesScreenshot)TestEnvironmentProperties.driver).getScreenshotAs(OutputType.BYTES);
try
{
Files.write(arrayOfByte, localFile);
str = localFile.getName();
}
catch (IOException localIOException)
{
}
}
}
catch (Exception localException)
{
}
return str;
}
} | 38.888889 | 407 | 0.722449 |
0310018ad3bd2dc9863d99fd0fee2548ebb38c9c | 1,098 | package com.ctrip.xpipe.utils;
import java.util.concurrent.locks.AbstractQueuedLongSynchronizer;
/**
* @author marsqing
*
* May 20, 2016 2:06:20 PM
*/
public class OffsetNotifier {
private static final class Sync extends AbstractQueuedLongSynchronizer {
private static final long serialVersionUID = 4982264981922014374L;
Sync(long offset) {
setState(offset);
}
@Override
protected long tryAcquireShared(long startOffset) {
return (getState() >= startOffset) ? 1 : -1;
}
@Override
protected boolean tryReleaseShared(long newOffset) {
setState(newOffset);
return true;
}
}
private final Sync sync;
public OffsetNotifier(long offset) {
this.sync = new Sync(offset);
}
public void await(long startOffset) throws InterruptedException {
sync.acquireSharedInterruptibly(startOffset);
}
public boolean await(long startOffset, long miliSeconds) throws InterruptedException{
return sync.tryAcquireSharedNanos(startOffset, miliSeconds * (1000*1000));
}
public void offsetIncreased(long newOffset) {
sync.releaseShared(newOffset);
}
}
| 22.408163 | 86 | 0.742259 |
5e97f78e443f69facf8688526760f5a9685f27cc | 407 | package generators.utils;
import java.util.LinkedList;
import java.util.List;
public class Lake {
public List<Point> lakePoints = new LinkedList<>();
public List<LakePass> neighbours = new LinkedList<>();
public Lake next = null;
public LakePass pass = null;
private int id;
public boolean isOnEdge = false;
public Lake(int id){
this.id = id;
}
}
| 22.611111 | 59 | 0.636364 |
bacb92526f5e146c761c82416821d0e01df67f17 | 595 | package com.dev.crm.core.dto;
import java.io.Serializable;
public class EstadosCuentaResultViewModel implements Serializable {
/**
*
*/
private static final long serialVersionUID = 6364087068352335959L;
private Integer codigoEstado;
private String estado;
public EstadosCuentaResultViewModel() {
}
public Integer getCodigoEstado() {
return codigoEstado;
}
public void setCodigoEstado(Integer codigoEstado) {
this.codigoEstado = codigoEstado;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
}
| 16.527778 | 67 | 0.744538 |
6c393aaf0e61b2f74453ea49b729d3f93ee53b90 | 7,268 | package cs2030.simulator;
import java.util.LinkedList;
import java.util.List;
import java.util.ArrayList;
import java.util.Optional;
import java.util.NoSuchElementException;
/**
* Server class will serve the customer and also rest.
* @author Brendan Cheong
* @version CS2030 AY 2021-2022 Sem 1
*/
public class Server {
private final int id;
private final LinkedList<Customer> queue;
private final List<Optional<Customer>> currentCustomer;
private final int queueAmount;
private final List<Double> canServeAt;
private final List<Boolean> restingState;
private final double restingProb;
private final RandomGenerator rng;
private final boolean useRandomMachine;
private static LinkedList<Double> RESTING_ARRAY;
/**
* Creates a Normal Server that rests when neccessary.
* @param id server id
* @param queueAmount size of server's queue
* @param restTimeArray server's chronological rest times
* @param restingProb probability to rest
* @param rng random number generator
* @param useRandomMachine whether to use rng or not
*/
public Server(int id, int queueAmount, LinkedList<Double> restTimeArray,
double restingProb, RandomGenerator rng, boolean useRandomMachine) {
this.id = id;
this.queue = new LinkedList<>();
this.currentCustomer = new ArrayList<>();
this.queueAmount = queueAmount;
this.canServeAt = new ArrayList<>();
this.restingState = new ArrayList<>();
this.restingProb = restingProb;
this.rng = rng;
this.useRandomMachine = useRandomMachine;
RESTING_ARRAY = restTimeArray;
currentCustomer.add(Optional.empty());
canServeAt.add((double) 0);
restingState.add(false);
}
public int getId() {
return this.id;
}
public LinkedList<Customer> getQueue() {
return this.queue;
}
public Optional<Customer> getCurrentCustomer() {
return this.currentCustomer.get(0);
}
public List<Optional<Customer>> getCurrentCustomerList() {
return this.currentCustomer;
}
public int getQueueAmount() {
return this.queueAmount;
}
public double getCanServeAt() {
return this.canServeAt.get(0);
}
public int getQueueLength() {
return this.queue.size();
}
/**
* Set the next time to serve customers for this server.
* @param servedTime next time to serve
*/
public void setServeTime(double servedTime) {
this.canServeAt.add(0, servedTime);
}
/**
* Based on resting probability and rng, decide whether to rest or not.
* @return to rest or not to rest
*/
public boolean decideToRest() {
return useRandomMachine
? this.restingProb > rng.genRandomRest()
: false;
}
/**
* Checks whether the server is idle at the moment.
* <p> an idle server is a server that has no waiting customer in queue </p>
* <p> a server that is not resting </p>
* <p> and a server that is not serving anyone </p>
* <p> so this server can take a customer </p>
* @return returns whether the server is idle or not
*/
public boolean isIdle() {
Optional<Customer> currentCustomer = this.getCurrentCustomer();
try {
Customer customer = currentCustomer
.map((x) -> x)
.orElseThrow();
return false; // if there is a customer(no empty value error) then server is not Idle
} catch (NoSuchElementException e) {
return true && this.getQueue().isEmpty() && !this.isResting();
}
}
public boolean isFull() {
return getQueueLength() == this.queueAmount;
}
public boolean isResting() {
return this.restingState.get(0);
}
/**
* Serves the given customer and updates when the customer finishes being served.
* @param customer the given customer to serve
* @return a served customer with the new time where it will finish being served
*/
public Customer serve(Customer customer) {
Optional<Customer> newCustomer = Optional.<Customer>of(customer);
this.currentCustomer.add(0, newCustomer);
double serveTime = useRandomMachine
? rng.genServiceTime()
: customer.getServeTime();
double nextServeTime = customer.getTime() + serveTime;
this.canServeAt.add(0, nextServeTime);
return customer.setTime(nextServeTime);
}
public void addToQueue(Customer customer) {
this.queue.add(customer);
}
/**
* Completes serving the customer, decide to rest or move on to the next customer.
* </p> when done serving the customer, the currentCustomer served is now Optional.empty </p>
* </p> however, if the queue has a waiting customer,
* then output that customer in an optional </p>
* </p> and change the customer details like when the customer will finish being served </p>
* </p> if not, return an Optional.empty </p>
* @return returns the next customer to serve or no customer
*/
public Optional<Customer> done() {
this.currentCustomer.add(0, Optional.empty());
double restTime = useRandomMachine
? 0.000
: RESTING_ARRAY.pop();
if (restTime != 0 && !useRandomMachine) {
this.rest(restTime);
return Optional.empty();
} else if (useRandomMachine && decideToRest()) {
this.rest(rng.genRestPeriod());
return Optional.empty();
}
if (!this.getQueue().isEmpty()) {
return Optional.<Customer>of(
this.getQueue()
.pop()
.setTime(getCanServeAt()));
}
return Optional.empty();
}
/**
* The server officiallys rests given the rest time.
* @param restTime server rest given the stipulated rest time
*/
public void rest(double restTime) {
this.restingState.add(0, true);
double currentServeAt = this.getCanServeAt();
this.canServeAt.add(0, currentServeAt + restTime);
}
/**
* The server returns from their rest.
* <p> server can either move on to the next customer to serve </p>
* <p> or the server can state that they have no customers to serve </p>
* <p> and thus must wait for the next customer in the simulation </p>
* @return the next customer to serve or no customer
*/
public Optional<Customer> comeBackFromRest() {
this.restingState.add(0, false);
if (!this.getQueue().isEmpty()) {
return Optional.<Customer>of(
this.getQueue()
.pop()
.setTime(getCanServeAt()));
}
return Optional.empty();
}
@Override
public String toString() {
return String.format("server %d", getId());
}
}
| 32.017621 | 99 | 0.599064 |
c6d88ea20716941d96d06dc67497311b9e3d9cd5 | 387 | package com.itstyle.seckill.service;
import com.itstyle.seckill.common.entity.Role;
import com.itstyle.seckill.common.entity.User;
import java.util.Map;
/**
* @author 周瑞忠
* @description java类作用描述
* @date 2019/3/4 20:07
*/
public interface ILoginService {
User addUser(Map<String, Object> map);
Role addRole(Map<String, Object> map);
User findByName(String name);
}
| 18.428571 | 46 | 0.72093 |
73955e21269d02f53932dc871cba599fcdd2f2c2 | 1,984 | package com.pjzhong.leetcode.contest87;
import org.junit.Test;
/**
* Let's call any (contiguous) subarray B (of A) a mountain if the following properties hold:
* <p>
* B.length >= 3
* There exists some 0 < i < B.length - 1 such that B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1]
* (Note that B could be any subarray of A, including the entire array A.)
* <p>
* Given an array A of integers, return the length of the longest mountain.
* <p>
* Return 0 if there is no mountain.
* <p>
* <p>
* <p>
* Example 1:
* <p>
* Input: [2,1,4,7,3,2,5]
* Output: 5
* Explanation: The largest mountain is [1,4,7,3,2] which has length 5.
* Example 2:
* <p>
* Input: [2,2,2]
* Output: 0
* Explanation: There is no mountain.
* <p>
* <p>
* Note:
* <p>
* 0 <= A.length <= 10000
* 0 <= A[i] <= 10000
* <p>
* https://leetcode.com/problems/longest-mountain-in-array/description/
*/
public class LongestMountainInArray {
@Test
public void test() {
int[][] testCases = {
{2, 1, 4, 7, 3, 2, 5},
{2, 2, 2},
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
{9, 8, 7, 6, 5, 4, 3, 2, 1, 0},
};
for (int[] t : testCases) {
System.out.println(longestMountain(t));
}
}
public int longestMountain(int[] A) {
int longest = 0;
int leftCount = 0, rightCount = 0;
for (int i = 1, size = A.length - 1; i < size; i++) {
leftCount = rightCount = 0;
for (int left = i - 1; 0 <= left && A[left] < A[left + 1]; left--) {
leftCount++;
}
for (int right = i + 1; right < A.length && A[right] < A[right - 1]; right++) {
rightCount++;
}
if (0 < leftCount && 0 < rightCount && 3 <= (leftCount + rightCount + 1)) {
longest = Math.max(longest, 1 + leftCount + rightCount);
}
}
return longest;
}
}
| 27.178082 | 116 | 0.49748 |
94c7ff3847237dc81a4c77cd3d278ea0b8df0ee6 | 938 | package example.services;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
@Service
public class CountService {
private final StringRedisTemplate stringRedisTemplate;
@Autowired
public CountService(StringRedisTemplate stringRedisTemplate) {
this.stringRedisTemplate = stringRedisTemplate;
}
@HystrixCommand(fallbackMethod = "fallbackCount", commandProperties = {
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "50")
})
public long count() {
return stringRedisTemplate.boundValueOps("counter").increment(1);
}
private long fallbackCount() {
return -1;
}
}
| 31.266667 | 97 | 0.763326 |
f9ef4b2937f542c737694f969221d9648458e1c7 | 340 | package io.wisoft.java_seminar.chap06.sec15.exam_annotation;
import java.lang.annotation.*;
@Target({ElementType.METHOD}) // 메소드에만 적용
@Retention(RetentionPolicy.RUNTIME) // 런타임 시까지 어노테이션 정보를 유지
public @interface PrintAnnotation {
String value() default "-"; // 기본 엘리먼트 value는 구분선에 사용될 문자
int number() default 15; // 반복 출력 횟수
}
| 30.909091 | 62 | 0.726471 |
b0c1dddb3715322f302b557b72a30c28851ed247 | 1,891 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.usages.impl;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.ToggleAction;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.usages.UsageView;
import com.intellij.usages.rules.UsageFilteringRuleProvider;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
/**
* @author Eugene Zhuravlev
* Date: Jan 19, 2005
*/
abstract class RuleAction extends ToggleAction implements DumbAware {
private final UsageViewImpl myView;
private boolean myState;
RuleAction(@NotNull UsageView view, @NotNull String text, @NotNull Icon icon) {
super(text, null, icon);
myView = (UsageViewImpl)view;
myState = getOptionValue();
}
protected abstract boolean getOptionValue();
protected abstract void setOptionValue(boolean value);
@Override
public boolean isSelected(AnActionEvent e) {
return myState;
}
@Override
public void setSelected(AnActionEvent e, boolean state) {
setOptionValue(state);
myState = state;
Project project = e.getProject();
if (project != null) {
project.getMessageBus().syncPublisher(UsageFilteringRuleProvider.RULES_CHANGED).run();
}
myView.select();
}
}
| 29.546875 | 92 | 0.745637 |
722821a7c6da0162ef9804afe066997d9eafef5a | 5,917 | /*
* Copyright (c) 2016 eBay Software Foundation. Licensed under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable
* law or agreed to in writing, software distributed under the License is distributed on an "AS IS"
* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License
* for the specific language governing permissions and limitations under the License.
*/
package com.ebay.oss.griffin.repo;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;
import com.ebay.oss.griffin.domain.DataAsset;
import com.ebay.oss.griffin.domain.DqModel;
import com.ebay.oss.griffin.domain.ModelType;
import com.ebay.oss.griffin.domain.ValidityType;
import com.google.gson.Gson;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.util.JSON;
@Repository
public class DqModelRepoImpl extends BaseIdRepo<DqModel> implements DqModelRepo {
public DqModelRepoImpl() {
super("dq_model", "DQ_MODEL_NO", DqModel.class);
}
@Override
public List<DqModel> getByStatus(int status) {
List<DqModel> result = new ArrayList<DqModel>();
DBCursor cursor = dbCollection.find(new BasicDBObject("status", status));
for (DBObject dbo : cursor) {
result.add(toEntity(dbo));
}
return result;
}
// FIXME what's the difference with save(T)
@Override
public DqModel update(DqModel entity) {
DBObject temp = dbCollection.findOne(new BasicDBObject("modelId", entity.getModelName()));
if (temp != null) {
dbCollection.remove(temp);
}
Gson gson = new Gson();
DBObject t1 = (DBObject) JSON.parse(gson.toJson(entity));
dbCollection.save(t1);
return toEntity(t1);
}
// FIXME concerned could be removed
// get models concerned with data asset
// allConcerned: false- only the models directly concerned with the data asset
// true - the models directly concerned and non-directly concerned(eg. as the source asset of
// accuracy model)
//
// } else if (allConcerned) { // check the non-directly concerned models
// if (me.getModelType() == ModelType.ACCURACY) { // accuracy
// // find model
// DqModel entity = findByName(me.getModelName());
// ModelInput mi = new ModelInput();
// mi.parseFromString(entity.getModelContent());
//
// // get mapping list to get the asset name
// String otherAsset = "";
// List<MappingItemInput> mappingList = mi.getMappings();
// Iterator<MappingItemInput> mpitr = mappingList.iterator();
// while (mpitr.hasNext()) {
// MappingItemInput mapping = mpitr.next();
// // since the target data asset is directly concerned, we should get source
// // as the other one
// String col = mapping.getSrc();
// otherAsset = col.replaceFirst("\\..+", ""); // delete from the first .xxxx
// if (!otherAsset.isEmpty())
// break;
// }
//
// // check the other asset name equals to this asst or not
// if (otherAsset.equals(da.getAssetName())) { // concerned non-directly
// result.add(me);
// }
// }
@Override
public List<DqModel> getByDataAsset(DataAsset da) {
List<DqModel> result = new ArrayList<DqModel>();
List<DqModel> allModels = getAll();
Iterator<DqModel> itr = allModels.iterator();
while (itr.hasNext()) {
DqModel me = itr.next();
if (me.getAssetId() == da.get_id()) { // concerned directly
result.add(me);
}
}
return result;
}
@Override
public DqModel findByColumn(String colName, String value) {
DBObject temp = dbCollection.findOne(new BasicDBObject(colName, value));
if (temp == null) {
return null;
} else {
Gson gson = new Gson();
return gson.fromJson(temp.toString(), DqModel.class);
}
}
@Override
public DqModel findByName(String name) {
DBObject temp = dbCollection.findOne(new BasicDBObject("modelName", name));
if (temp == null) {
return null;
} else {
return new Gson().fromJson(temp.toString(), DqModel.class);
}
}
@Override
public DqModel findCountModelByAssetID(long assetID) {
DBCursor cursor = dbCollection.find(new BasicDBObject("assetId", assetID));
for (DBObject tempDBObject : cursor) {
if (tempDBObject.get("modelType").equals(ModelType.VALIDITY)) {
String content = tempDBObject.get("modelContent").toString();
String[] contents = content.split("\\|");
if (contents[2].equals(ValidityType.TOTAL_COUNT + "")) {
return toEntity(tempDBObject);
}
}
}
return null;
}
@SuppressWarnings("deprecation")
@Override
public void addReference(DqModel dqModel, String reference) {
if (!StringUtils.isBlank(dqModel.getReferenceModel())) {
reference = dqModel.getReferenceModel() + "," + reference;
}
dqModel.setReferenceModel(reference);
save(dqModel);
}
}
| 36.300613 | 100 | 0.597093 |
c0ec0511eccec77f385c5b369dab5faa1edfaaa6 | 3,609 | /*
* Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8214031
* @summary Verify various corner cases with nested switch expressions.
* @compile ExpressionSwitchBugsInGen.java
* @run main ExpressionSwitchBugsInGen
*/
public class ExpressionSwitchBugsInGen {
public static void main(String... args) {
new ExpressionSwitchBugsInGen().test(0, 0, 0, false);
new ExpressionSwitchBugsInGen().test(0, 0, 1, true);
new ExpressionSwitchBugsInGen().test(0, 1, 1, false);
new ExpressionSwitchBugsInGen().test(1, 1, -1, true);
new ExpressionSwitchBugsInGen().test(1, 12, -1, false);
new ExpressionSwitchBugsInGen().testCommonSuperType(0, "a", new StringBuilder(), "a");
new ExpressionSwitchBugsInGen().testCommonSuperType(1, "", new StringBuilder("a"), "a");
new ExpressionSwitchBugsInGen().testSwitchExpressionInConditional(0, null, -1);
new ExpressionSwitchBugsInGen().testSwitchExpressionInConditional(1, "", 0);
new ExpressionSwitchBugsInGen().testSwitchExpressionInConditional(1, 1, 1);
new ExpressionSwitchBugsInGen().testIntBoxing(0, 10, 10);
new ExpressionSwitchBugsInGen().testIntBoxing(1, 10, -1);
}
private void test(int a, int b, int c, boolean expected) {
if ( !(switch (a) {
case 0 -> b == (switch (c) { case 0 -> 0; default -> 1; });
default -> b == 12;
})) {
if (!expected) {
throw new IllegalStateException();
}
} else {
if (expected) {
throw new IllegalStateException();
}
}
}
private void testCommonSuperType(int a, String s1, StringBuilder s2, String expected) {
String r = (switch (a) {
case 0 -> s1;
default -> s2;
}).toString();
if (!expected.equals(r)) {
throw new IllegalStateException();
}
}
private void testSwitchExpressionInConditional(int a, Object o, int expected) {
int v = a == 0 ? -1
: switch (o instanceof String ? 0 : 1) {
case 0 -> 0;
default -> 1;
};
if (v != expected) {
throw new IllegalStateException();
}
}
private void testIntBoxing(int a, Integer res, int expected) {
int r = switch (a) {
case 0 -> res;
default -> -1;
};
if (r != expected) {
throw new IllegalStateException();
}
}
}
| 37.989474 | 96 | 0.61125 |
1c1bbd918e443cf0348a952006f040bbc5966b53 | 2,007 | /**
* Based on material from Digital Audio with Java, Craig Lindley
* ftp://ftp.prenhall.com/pub/ptr/professional_computer_science.w-022/digital_audio/
*/
package org.hyperdata.beeps.filters;
// Base class for all IIR filters.
public abstract class IIRFilterBase {
protected static final int HISTORYSIZE = 3;
// IIRFilterBase class constructor
// alpha, beta and gamma are precalculated filter coefficients
// that are passed into this filter element.
public IIRFilterBase(double alpha, double beta, double gamma) {
// Save incoming
this.alpha = alpha;
this.beta = beta;
this.gamma = gamma;
amplitudeAdj = 1.0;
// Allocate history buffers
inArray = new double[HISTORYSIZE];
outArray = new double[HISTORYSIZE];
}
// Filter coefficients can also be extracted by passing in
// design object.
public IIRFilterBase(IIRFilterDesignBase fdb) {
this(fdb.getAlpha(), fdb.getBeta(), fdb.getGamma());
}
public void updateFilterCoefficients(IIRFilterDesignBase fdb) {
this.alpha = fdb.getAlpha();
this.beta = fdb.getBeta();
this.gamma = fdb.getGamma();
}
public void setAlpha(double alpha) {
this.alpha = alpha;
}
public void setBeta(double beta) {
this.beta = beta;
}
public void setGamma(double gamma) {
this.gamma = gamma;
}
// Abstract method that runs the filter algorithm
public abstract void doFilter(short [] inBuffer, double [] outBuffer,
int length);
// Set the amplitude adjustment to be applied to filtered data
// Values typically range from -.25 to +4.0 or -12 to +12 db.
public void setAmplitudeAdj(double amplitudeAdj) {
this.amplitudeAdj = amplitudeAdj;
}
// Private class data
protected double alpha;
protected double beta;
protected double gamma;
protected double amplitudeAdj;
protected double [] inArray;
protected double [] outArray;
protected int iIndex;
protected int jIndex;
protected int kIndex;
}
| 24.47561 | 85 | 0.693074 |
65b0f9c37acf2d04fbf82378e3420824a11ee5db | 1,416 | package org.spacehq.packetlib.test;
import org.spacehq.packetlib.event.session.ConnectedEvent;
import org.spacehq.packetlib.event.session.DisconnectedEvent;
import org.spacehq.packetlib.event.session.DisconnectingEvent;
import org.spacehq.packetlib.event.session.PacketReceivedEvent;
import org.spacehq.packetlib.event.session.PacketSentEvent;
import org.spacehq.packetlib.event.session.SessionAdapter;
public class ServerSessionListener extends SessionAdapter {
@Override
public void packetReceived(PacketReceivedEvent event) {
if(event.getPacket() instanceof PingPacket) {
System.out.println("SERVER Received: " + event.<PingPacket>getPacket().getPingId());
event.getSession().send(event.getPacket());
}
}
@Override
public void packetSent(PacketSentEvent event) {
if(event.getPacket() instanceof PingPacket) {
System.out.println("SERVER Sent: " + event.<PingPacket>getPacket().getPingId());
}
}
@Override
public void connected(ConnectedEvent event) {
System.out.println("SERVER Connected");
}
@Override
public void disconnecting(DisconnectingEvent event) {
System.out.println("SERVER Disconnecting: " + event.getReason());
}
@Override
public void disconnected(DisconnectedEvent event) {
System.out.println("SERVER Disconnected: " + event.getReason());
}
}
| 34.536585 | 96 | 0.715395 |
2fa3df247a9ef7f24dc2828cd2a9c5139ca84170 | 960 | package net.maromo.prjapolice;
public class Apolice {
//Atributos
private String nomeSegurado;
private int idade;
private float valorPremio;
//Métodos gets - sets
//<ALT> + <INSERT>
public String getNomeSegurado() {
return nomeSegurado;
}
public void setNomeSegurado(String nomeSegurado) {
this.nomeSegurado = nomeSegurado;
}
public int getIdade() {
return idade;
}
public void setIdade(int idade) {
this.idade = idade;
}
public float getValorPremio() {
return valorPremio;
}
public void setValorPremio(float valorPremio) {
this.valorPremio = valorPremio;
}
//Método da classe
public void imprimir(){
System.out.println("Dados do Segurado");
System.out.println("Nome: " + nomeSegurado);
System.out.println("Idade: " + idade);
System.out.println("Valor do Prêmio: " + valorPremio);
}
}
| 20.869565 | 62 | 0.617708 |
94fd8bdd1cefcfe8488f3cf2e15d5df9fd18750c | 366 | package com.explodingpixels.macwidgets;
/**
* An interface for listening to {@link SourceListItem} selections.
*/
public interface SourceListSelectionListener {
/**
* Called when a {@link SourceListItem} is selected in a {@link SourceList}.
* @param item the item that was selected.
*/
void sourceListItemSelected(SourceListItem item);
}
| 24.4 | 80 | 0.713115 |
4ef24dc913abe5dba524e28a78ec0b1f1d95f012 | 4,354 | package home.operatorsanddecisionp1;
import javax.swing.*;
public class logicLibrary {
public immutableLibrary referDataLibrary = new immutableLibrary();
public String userSSCodeInput;
public String userCRSCodeInput;
public double userRegFeeInput;
double discountAmount;
double finalUserPercentDiscount;
public double finalTotalBalance;
String finalUserSession;
public String userCurrentName;
public String currentSS;
public String currentSSCode;
public String currentCRSCode;
public double currentRegFee;
public void studentInputNewVersion(){
String scanUserCurrentFName = JOptionPane.showInputDialog("First Name: ");
String scanCurrentSS = String.valueOf(JOptionPane.showInputDialog(
null,
"Preferred session: ",
"Input", JOptionPane.QUESTION_MESSAGE,
null, referDataLibrary.ssDataList, referDataLibrary.ssDataList[0]));
JOptionPane.showMessageDialog(
null,
"Student Name: " + userCurrentName + '\n' + "Session: " + currentSS +
'\n' + "Course Description: " + referDataLibrary.courseName + '\n' + "Total Balance: Php " + finalTotalBalance);
// String scanUserCurrentFName = JOptionPane.showInputDialog("First Name: ");
// String scanUserCurrentMName = JOptionPane.showInputDialog("Middle Name: ");
// String scanUserCurrentLName = JOptionPane.showInputDialog("Last Name: ");
// String scanCurrentSS = String.valueOf(JOptionPane.showInputDialog(
// null,
// "Preferred session: ",
// "Input", JOptionPane.QUESTION_MESSAGE,
// null, referDataLibrary.ssDataList, referDataLibrary.ssDataList[0]));
// String scanCurrentCRSCode = (String) JOptionPane.showInputDialog(
// null,
// "Programming Course: ",
// "Input", JOptionPane.QUESTION_MESSAGE,
// null, referDataLibrary.crsDescriptionDataList, referDataLibrary.crsDescriptionDataList[0]);
// double scanCurrentRegFee = Integer.parseInt(JOptionPane.showInputDialog("Registration Fee: "));
//
// char converToMiddleInitial = scanUserCurrentMName.charAt(0);
// userCurrentName = scanUserCurrentFName + " " + converToMiddleInitial + "." + " " + scanUserCurrentLName;
// currentSS = scanCurrentSS;
// currentCRSCode = scanCurrentCRSCode;
// currentRegFee = scanCurrentRegFee;
}
public void cjcLogic() {
switch (userSSCodeInput) {
case "Morning":
finalUserSession = referDataLibrary.ssDataList[0];
break;
case "Afternoon":
finalUserSession = referDataLibrary.ssDataList[1];
break;
}
switch (userCRSCodeInput) {
case "C++":
referDataLibrary.cPlusPlus();
break;
case "Java":
referDataLibrary.java();
break;
case "Visual Basic":
referDataLibrary.visualBasic();
break;
}
if (currentRegFee <= 4499) {
finalUserPercentDiscount = 0;
}
else if ((currentRegFee >= 4500) || (currentRegFee <= 5499)) {
finalUserPercentDiscount = 2;
}
else if ((currentRegFee >= 5500) || (currentRegFee <= 6499)) {
finalUserPercentDiscount = 4;
}
else if (currentRegFee >= 6500) {
finalUserPercentDiscount = 6;
}
}
public void cjcComputation() {
if (currentRegFee > referDataLibrary.courseFee) {
currentRegFee = referDataLibrary.courseFee;
finalUserPercentDiscount = 0;
}
discountAmount = referDataLibrary.courseFee * (finalUserPercentDiscount/100);
finalTotalBalance = referDataLibrary.courseFee - (currentRegFee + discountAmount);
}
public void cjcOutput() {
JOptionPane.showMessageDialog(null, "Student Name: " + userCurrentName + '\n' + "Session: " + currentSS + '\n' + "Course Description: " + referDataLibrary.courseName + '\n' + "Total Balance: Php " + finalTotalBalance);
}
}
| 43.979798 | 227 | 0.604042 |
4381bce78988f78fd9309aae748e899ce7560124 | 3,006 | package net.foulest.togepi.check.impl.wtap;
import net.foulest.togepi.Togepi;
import net.foulest.togepi.check.checks.PacketCheck;
import net.foulest.togepi.data.PlayerData;
import net.minecraft.server.v1_8_R3.Packet;
import net.minecraft.server.v1_8_R3.PacketPlayInBlockDig;
import net.minecraft.server.v1_8_R3.PacketPlayInEntityAction;
import net.minecraft.server.v1_8_R3.PacketPlayInFlying;
import java.util.Deque;
import java.util.LinkedList;
/**
* @author Foulest
* @project Togepi
*/
public class WTapA extends PacketCheck {
private final Deque<Integer> flyingCounts = new LinkedList<>();
private boolean sent;
private int flyingCount;
private double buffer;
public WTapA(Togepi plugin, PlayerData playerData) {
super(plugin, playerData, "WTap (A)", "No description.", 5, 30000L);
}
@Override
public void handleCheck(Packet packet) {
if (packet instanceof PacketPlayInEntityAction) {
PacketPlayInEntityAction wrapper = (PacketPlayInEntityAction) packet;
PacketPlayInEntityAction.EnumPlayerAction action = wrapper.b();
if (action == PacketPlayInEntityAction.EnumPlayerAction.START_SPRINTING) {
if (playerData.getLastAttackPacket() < 1000L && flyingCount < 10 && !sent) {
flyingCounts.add(flyingCount);
if (flyingCounts.size() == 20) {
double average = 0.0;
for (double flyCount : flyingCounts) {
average += flyCount;
}
average /= flyingCounts.size();
double stdDev = 0.0;
for (long l : flyingCounts) {
stdDev += Math.pow(l - average, 2.0);
}
stdDev /= flyingCounts.size();
stdDev = Math.sqrt(stdDev);
if (stdDev == 0.0) {
buffer += 1.2;
if (buffer >= 2.4) {
alert(true, String.format("\n&7DEV: &f%.2f", stdDev));
}
} else {
buffer = Math.max(0, buffer - 2.0);
}
flyingCounts.clear();
}
}
} else if (action == PacketPlayInEntityAction.EnumPlayerAction.STOP_SPRINTING) {
flyingCount = 0;
}
} else if (packet instanceof PacketPlayInFlying) {
++flyingCount;
sent = false;
} else if (packet instanceof PacketPlayInBlockDig) {
PacketPlayInBlockDig wrapper = (PacketPlayInBlockDig) packet;
PacketPlayInBlockDig.EnumPlayerDigType digType = wrapper.c();
if (digType == PacketPlayInBlockDig.EnumPlayerDigType.RELEASE_USE_ITEM) {
sent = true;
}
}
}
}
| 35.785714 | 92 | 0.544578 |
888aab4eb296c9177b4af60b45e982440f05d140 | 5,518 | package com.rainbow.smartpos.service;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import com.rainbow.smartpos.Restaurant;
import com.sanyipos.sdk.core.AgentRequests;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class SendLogService extends Service {
public static class SendLogServiceBinder extends Binder {
private SendLogService service;
public SendLogServiceBinder(SendLogService service) {
this.service = service;
}
public SendLogService getService() {
return service;
}
}
private static final int BUFFER_SIZE = 1024;
private Timer timer = null;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return new SendLogServiceBinder(this);
}
public void startSend() {
if (timer == null) {
final String url = AgentRequests.port_9090_url + Restaurant.uploadLogUrl;
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
String inputFile = Restaurant.operationLogTxtName;
String outFile = inputFile.substring(0, inputFile.length() - 4) + ".zip";
try {
if (new File(inputFile).exists()) {
synchronized (Restaurant.operationLogTxtName) {
zip(new String[] { inputFile }, outFile);
// new File(inputFile).delete();
new File(inputFile).renameTo(new File(inputFile + "." + System.currentTimeMillis()));
}
upload(outFile, url);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
}
// }, 1000 * 60, 1000 * 60 * 5);
}, 0, 1000 * 60);
}
}
public static void zip(String[] files, String zipFile) throws IOException {
BufferedInputStream origin = null;
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));
try {
byte data[] = new byte[BUFFER_SIZE];
for (int i = 0; i < files.length; i++) {
FileInputStream fi = new FileInputStream(files[i]);
origin = new BufferedInputStream(fi, BUFFER_SIZE);
try {
ZipEntry entry = new ZipEntry(files[i].substring(files[i].lastIndexOf("/") + 1));
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER_SIZE)) != -1) {
out.write(data, 0, count);
}
} finally {
origin.close();
}
}
} finally {
out.close();
}
}
protected void upload(String path, String url) {
try {
String BOUNDARY = "" + System.currentTimeMillis(); // 定义数据分隔线
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
conn.setRequestProperty("sanyi-shop-id", Long.toString(Restaurant.shopId));
OutputStream out = new DataOutputStream(conn.getOutputStream());
byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// 定义最后数据分隔线
File file = new File(path);
StringBuilder sb = new StringBuilder();
sb.append("--");
sb.append(BOUNDARY);
sb.append("\r\n");
sb.append("Content-Disposition: form-data;name=\"file0\";filename=\"" + file.getName() + "\"\r\n");
sb.append("Content-Type:application/octet-stream\r\n\r\n");
byte[] data = sb.toString().getBytes();
out.write(data);
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
// out.write("\r\n".getBytes()); //多个文件时,二个文件之间加入这个
in.close();
out.write(end_data);
out.flush();
out.close();
// 定义BufferedReader输入流来读取URL的响应
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String s = reader.readLine();
String line = null;
// while ((line = reader.readLine()) != null) {
// System.out.println(line);
// }
file.delete();
} catch (Exception e) {
// System.out.println("发送POST请求出现异常!" + e);
e.printStackTrace();
}
}
private void copy(File src, OutputStream output) throws IOException {
InputStream in = new FileInputStream(src);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
output.write(buf, 0, len);
}
in.close();
}
public void deleteFile(File file) {
if (file.exists()) {
if (file.isFile()) {
file.delete();
} else if (file.isDirectory()) {
File files[] = file.listFiles();
for (int i = 0; i < files.length; i++) {
deleteFile(files[i]);
}
}
file.delete();
} else {
}
}
}
| 29.042105 | 102 | 0.672708 |
9b1cfeff38a8479a65651f0c65715b669ccdbcb0 | 426 | package com.hubspot.slack.client.models.response.usergroups.users;
import org.immutables.value.Value.Immutable;
import com.hubspot.immutables.style.HubSpotStyle;
import com.hubspot.slack.client.models.response.SlackResponse;
import com.hubspot.slack.client.models.usergroups.SlackUsergroup;
@Immutable
@HubSpotStyle
public interface UsergroupUsersUpdateResponseIF extends SlackResponse {
SlackUsergroup getUsergroup();
}
| 30.428571 | 71 | 0.847418 |
095bcb18437bd42c68d5574f2a0dd490546c8c08 | 1,134 | /*
* $Id: BusinessException.java,v 1.2 2009/03/02 20:39:39 haraujo Exp $
*
* Copyright (c) Critical Software S.A., All Rights Reserved.
* (www.criticalsoftware.com)
*
* This software is the proprietary information of Critical Software S.A.
* Use is subject to license terms.
*
* Last changed on : $Date: 2009/03/02 20:39:39 $
* Last changed by : $Author: haraujo $
*/
package com.criticalsoftware.certitools.business.exception;
import javax.ejb.ApplicationException;
/**
* Bussiness Exception
*
* @author : lt-rico
* @version : $version $
*/
@ApplicationException(rollback = true)
public class BusinessException extends Exception {
/**
* Business Exception with corresponding message and throwable.
*
* @param message the exception message
* @param cause the exception throwable
*/
public BusinessException(String message, Throwable cause) {
super(message, cause);
}
/**
* Business Exception with corresponding message.
*
* @param message the exception message
*/
public BusinessException(String message) {
super(message);
}
}
| 25.2 | 73 | 0.677249 |
ceca033e432a10a4cd3ea491428abcc1ea5a910c | 2,332 | /*
* SoapUI, Copyright (C) 2004-2016 SmartBear Software
*
* Licensed under the EUPL, Version 1.1 or - as soon as they will be approved by the European Commission - subsequent
* versions of the EUPL (the "Licence");
* You may not use this work except in compliance with the Licence.
* You may obtain a copy of the Licence at:
*
* http://ec.europa.eu/idabc/eupl
*
* Unless required by applicable law or agreed to in writing, software distributed under the Licence is
* distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the Licence for the specific language governing permissions and limitations
* under the Licence.
*/
package com.eviware.soapui.ui.desktop;
import com.eviware.soapui.model.ModelItem;
import com.eviware.soapui.support.PropertyChangeNotifier;
import javax.swing.Icon;
import javax.swing.JComponent;
/**
* Behaviour for a SoapUI desktop panel
*
* @author Ole.Matzura
*/
public interface DesktopPanel extends PropertyChangeNotifier {
public final static String TITLE_PROPERTY = DesktopPanel.class.getName() + "@title";
public final static String ICON_PROPERTY = DesktopPanel.class.getName() + "@icon";
/**
* Gets the title for this desktop panel
*/
public String getTitle();
/**
* Gets the description for this desktop panel.. may be used as tooltip,
* etc..
*
* @return
*/
public String getDescription();
/**
* Gets the model item associated with this desktop panel
*/
public ModelItem getModelItem();
/**
* Called when a desktop panel is about to be closed, may be overriden
* (depending on situation) by returning false if canCancel is set to true.
*/
public boolean onClose(boolean canCancel);
/**
* Gets the component used to display this desktop panel
*/
public JComponent getComponent();
/**
* Checks if this desktop panel depends on the existence of the specified
* model item, used for closing relevant panels.
*
* @param modelItem
*/
public boolean dependsOn(ModelItem modelItem);
/**
* Returns the icon for this panel
*/
public Icon getIcon();
}
| 27.761905 | 119 | 0.661235 |
59663a466d5e72ed90562afdd83376a451b755a9 | 53,315 | /*
* 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.felix.mosgi.jmx.agent.mx4j.server;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.AttributeNotFoundException;
import javax.management.BadAttributeValueExpException;
import javax.management.BadBinaryOpValueExpException;
import javax.management.BadStringOperationException;
import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
import javax.management.IntrospectionException;
import javax.management.InvalidApplicationException;
import javax.management.InvalidAttributeValueException;
import javax.management.JMRuntimeException;
import javax.management.ListenerNotFoundException;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanPermission;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MBeanServerDelegate;
import javax.management.MBeanServerNotification;
import javax.management.MBeanServerPermission;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.NotificationBroadcaster;
import javax.management.NotificationEmitter;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import javax.management.OperationsException;
import javax.management.QueryExp;
import javax.management.ReflectionException;
import javax.management.RuntimeErrorException;
import javax.management.RuntimeOperationsException;
import javax.management.StandardMBean;
import javax.management.loading.ClassLoaderRepository;
import javax.management.loading.PrivateClassLoader;
import org.apache.felix.mosgi.jmx.agent.mx4j.ImplementationException;
import org.apache.felix.mosgi.jmx.agent.mx4j.MX4JSystemKeys;
import org.apache.felix.mosgi.jmx.agent.mx4j.loading.ClassLoaderObjectInputStream;
import org.apache.felix.mosgi.jmx.agent.mx4j.log.Log;
import org.apache.felix.mosgi.jmx.agent.mx4j.log.Logger;
import org.apache.felix.mosgi.jmx.agent.mx4j.server.interceptor.InvokerMBeanServerInterceptor;
import org.apache.felix.mosgi.jmx.agent.mx4j.server.interceptor.MBeanServerInterceptor;
import org.apache.felix.mosgi.jmx.agent.mx4j.server.interceptor.MBeanServerInterceptorConfigurator;
import org.apache.felix.mosgi.jmx.agent.mx4j.util.Utils;
/**
* The MX4J MBeanServer implementation. <br>
* The MBeanServer accomplishes these roles:
* <ul>
* <li> Returns information about the Agent
* <li> Acts as a repository for MBeans
* <li> Acts as an invoker, on behalf of the user, on MBeans
* </ul>
* <br>
* The repository function is delegated to instances of {@link MBeanRepository} classes.
* This class acts as a factory for MBeanRepository instances, that can be controlled via the system property
* {@link mx4j.MX4JSystemKeys#MX4J_MBEANSERVER_REPOSITORY} to the qualified name of the implementation class. <br>
*
* This class also acts as an invoker on MBeans. The architecture is interceptor-based, that is whenever you call
* from a client an MBeanServer method that will end up to call the MBean instance, the call is dispatched to
* the interceptor chain and eventually to the MBean. <br>
* The interceptors are configurable via the MBean {@link MBeanServerInterceptorConfigurator}.
* When the call is about to arrive to the MBean instance, the last interceptor dispatches the call depending on
* the MBean type: if the MBean is a dynamic MBean, the call is dispatched directly; if the MBean is a standard
* MBean an {@link MBeanInvoker} is delegated to invoke on the MBean instance.
*
* @author <a href="mailto:[email protected]">Simone Bordet</a>
* @version $Revision: 1.3 $
*/
public class MX4JMBeanServer implements MBeanServer, java.io.Serializable
{
private String defaultDomain;
private MBeanRepository mbeanRepository;
private MBeanServerDelegate delegate;
private ObjectName delegateName;
private MBeanIntrospector introspector;
private MBeanServerInterceptorConfigurator invoker;
private static long notifications;
private ModifiableClassLoaderRepository classLoaderRepository;
private Map domains = new HashMap();
private static final String[] EMPTY_PARAMS = new String[0];
private static final Object[] EMPTY_ARGS = new Object[0];
/**
* Create a new MBeanServer implementation with the specified default domain.
* If the default domain is null, then the empty string is assumed.
*
* @param defaultDomain The default domain to be used
* @throws SecurityException if access is not granted to create an MBeanServer instance
*/
public MX4JMBeanServer(String defaultDomain, MBeanServer outer, MBeanServerDelegate delegate)
{
Logger logger = getLogger();
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Creating MBeanServer instance...");
SecurityManager sm = System.getSecurityManager();
if (sm != null)
{
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Checking permission to create MBeanServer...");
sm.checkPermission(new MBeanServerPermission("newMBeanServer"));
}
if (defaultDomain == null) defaultDomain = "";
this.defaultDomain = defaultDomain;
if (delegate==null) throw new JMRuntimeException("Delegate can't be null");
this.delegate = delegate;
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("MBeanServer default domain is: '" + this.defaultDomain + "'");
mbeanRepository = createMBeanRepository();
classLoaderRepository = createClassLoaderRepository();
// JMX 1.2 requires the CLR to have as first entry the classloader of this class
classLoaderRepository.addClassLoader(getClass().getClassLoader());
introspector = new MBeanIntrospector();
// This is the official name of the delegate, it is used as a source for MBeanServerNotifications
try
{
delegateName = new ObjectName("JMImplementation", "type", "MBeanServerDelegate");
}
catch (MalformedObjectNameException ignored)
{
}
try
{
ObjectName invokerName = new ObjectName(MBeanServerInterceptorConfigurator.OBJECT_NAME);
invoker = new MBeanServerInterceptorConfigurator(this);
// ContextClassLoaderMBeanServerInterceptor ccl = new ContextClassLoaderMBeanServerInterceptor();
// NotificationListenerMBeanServerInterceptor notif = new NotificationListenerMBeanServerInterceptor();
// SecurityMBeanServerInterceptor sec = new SecurityMBeanServerInterceptor();
InvokerMBeanServerInterceptor inv = new InvokerMBeanServerInterceptor(outer==null ? this : outer);
// invoker.addPreInterceptor(ccl);
// invoker.addPreInterceptor(notif);
// invoker.addPostInterceptor(sec);
invoker.addPostInterceptor(inv);
invoker.start();
// The interceptor stack is in place, register the configurator and all interceptors
privilegedRegisterMBean(invoker, invokerName);
// ObjectName cclName = new ObjectName("JMImplementation", "interceptor", "contextclassloader");
// ObjectName notifName = new ObjectName("JMImplementation", "interceptor", "notificationwrapper");
// ObjectName secName = new ObjectName("JMImplementation", "interceptor", "security");
ObjectName invName = new ObjectName("JMImplementation", "interceptor", "invoker");
// privilegedRegisterMBean(ccl, cclName);
// privilegedRegisterMBean(notif, notifName);
// privilegedRegisterMBean(sec, secName);
privilegedRegisterMBean(inv, invName);
}
catch (Exception x)
{
logger.error("MBeanServerInterceptorConfigurator cannot be registered", x);
throw new ImplementationException();
}
// Now register the delegate
try
{
privilegedRegisterMBean(delegate, delegateName);
}
catch (Exception x)
{
logger.error("MBeanServerDelegate cannot be registered", x);
throw new ImplementationException(x.toString());
}
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("MBeanServer instance created successfully");
}
/**
* Returns the ClassLoaderRepository for this MBeanServer.
* When first the ClassLoaderRepository is created in the constructor, the system property
* {@link mx4j.MX4JSystemKeys#MX4J_MBEANSERVER_CLASSLOADER_REPOSITORY} is tested;
* if it is non-null and defines a subclass of
* {@link ModifiableClassLoaderRepository}, then that class is used instead of the default one.
*/
public ClassLoaderRepository getClassLoaderRepository()
{
SecurityManager sm = System.getSecurityManager();
if (sm != null)
{
sm.checkPermission(new MBeanPermission("-#-[-]", "getClassLoaderRepository"));
}
return getModifiableClassLoaderRepository();
}
private ModifiableClassLoaderRepository getModifiableClassLoaderRepository()
{
return classLoaderRepository;
}
public ClassLoader getClassLoader(ObjectName name) throws InstanceNotFoundException
{
SecurityManager sm = System.getSecurityManager();
if (sm != null)
{
name = secureObjectName(name);
if (name == null)
{
sm.checkPermission(new MBeanPermission("-#-[-]", "getClassLoader"));
}
else
{
MBeanMetaData metadata = findMBeanMetaData(name);
sm.checkPermission(new MBeanPermission(metadata.info.getClassName(), "-", name, "getClassLoader"));
}
}
return getClassLoaderImpl(name);
}
public ClassLoader getClassLoaderFor(ObjectName name) throws InstanceNotFoundException
{
SecurityManager sm = System.getSecurityManager();
if (sm != null)
{
name = secureObjectName(name);
}
// If name is null, I get InstanceNotFoundException
MBeanMetaData metadata = findMBeanMetaData(name);
if (sm != null)
{
sm.checkPermission(new MBeanPermission(metadata.info.getClassName(), "-", name, "getClassLoaderFor"));
}
return metadata.mbean.getClass().getClassLoader();
}
/**
* Returns the MBean classloader corrispondent to the given ObjectName.
* If <code>name</code> is null, the classloader of this class is returned.
*/
private ClassLoader getClassLoaderImpl(ObjectName name) throws InstanceNotFoundException
{
if (name == null)
{
return getClass().getClassLoader();
}
else
{
MBeanMetaData metadata = findMBeanMetaData(name);
if (metadata.mbean instanceof ClassLoader)
{
return (ClassLoader)metadata.mbean;
}
else
{
throw new InstanceNotFoundException(name.getCanonicalName());
}
}
}
public ObjectInputStream deserialize(String className, ObjectName loaderName, byte[] bytes)
throws InstanceNotFoundException, OperationsException, ReflectionException
{
if (className == null || className.trim().length() == 0)
{
throw new RuntimeOperationsException(new IllegalArgumentException("Invalid class name '" + className + "'"));
}
ClassLoader cl = getClassLoader(loaderName);
try
{
Class cls = cl.loadClass(className);
return deserializeImpl(cls.getClassLoader(), bytes);
}
catch (ClassNotFoundException x)
{
throw new ReflectionException(x);
}
}
public ObjectInputStream deserialize(String className, byte[] bytes)
throws OperationsException, ReflectionException
{
if (className == null || className.trim().length() == 0)
{
throw new RuntimeOperationsException(new IllegalArgumentException("Invalid class name '" + className + "'"));
}
// Find the classloader that can load the given className using the ClassLoaderRepository
try
{
Class cls = getClassLoaderRepository().loadClass(className);
return deserializeImpl(cls.getClassLoader(), bytes);
}
catch (ClassNotFoundException x)
{
throw new ReflectionException(x);
}
}
public ObjectInputStream deserialize(ObjectName objectName, byte[] bytes)
throws InstanceNotFoundException, OperationsException
{
ClassLoader cl = getClassLoaderFor(objectName);
return deserializeImpl(cl, bytes);
}
/**
* Deserializes the given bytes using the specified classloader.
*/
private ObjectInputStream deserializeImpl(ClassLoader classloader, byte[] bytes) throws OperationsException
{
if (bytes == null || bytes.length == 0)
{
throw new RuntimeOperationsException(new IllegalArgumentException("Invalid byte array " + bytes));
}
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
try
{
return new ClassLoaderObjectInputStream(bais, classloader);
}
catch (IOException x)
{
throw new OperationsException(x.toString());
}
}
private MBeanServerInterceptor getHeadInterceptor()
{
MBeanServerInterceptor head = invoker.getHeadInterceptor();
if (head == null) throw new IllegalStateException("No MBeanServer interceptor, probably the configurator has been stopped");
return head;
}
private Logger getLogger()
{
return Log.getLogger(getClass().getName());
}
/**
* Creates a new repository for MBeans.
* The system property {@link mx4j.MX4JSystemKeys#MX4J_MBEANSERVER_REPOSITORY} is tested
* for a full qualified name of a class implementing the {@link MBeanRepository} interface.
* In case the system property is not defined or the class is not loadable or instantiable, a default
* implementation is returned.
*/
private MBeanRepository createMBeanRepository()
{
Logger logger = getLogger();
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Checking for system property " + MX4JSystemKeys.MX4J_MBEANSERVER_REPOSITORY);
String value = (String)AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
return System.getProperty(MX4JSystemKeys.MX4J_MBEANSERVER_REPOSITORY);
}
});
if (value != null)
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Property found for custom MBeanServer registry; class is: " + value);
try
{
MBeanRepository registry = (MBeanRepository)Thread.currentThread().getContextClassLoader().loadClass(value).newInstance();
if (logger.isEnabledFor(Logger.TRACE))
{
logger.trace("Custom MBeanServer registry created successfully");
}
return registry;
}
catch (Exception x)
{
if (logger.isEnabledFor(Logger.TRACE))
{
logger.trace("Custom MBeanServer registry could not be created", x);
}
}
}
return new DefaultMBeanRepository();
}
/**
* Creates a new ClassLoaderRepository for ClassLoader MBeans.
* The system property {@link mx4j.MX4JSystemKeys#MX4J_MBEANSERVER_CLASSLOADER_REPOSITORY}
* is tested for a full qualified name of a class
* extending the {@link ModifiableClassLoaderRepository} class.
* In case the system property is not defined or the class is not loadable or instantiable, a default
* implementation is returned.
*/
private ModifiableClassLoaderRepository createClassLoaderRepository()
{
Logger logger = getLogger();
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Checking for system property " + MX4JSystemKeys.MX4J_MBEANSERVER_CLASSLOADER_REPOSITORY);
String value = (String)AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
return System.getProperty(MX4JSystemKeys.MX4J_MBEANSERVER_CLASSLOADER_REPOSITORY);
}
});
if (value != null)
{
if (logger.isEnabledFor(Logger.DEBUG)) logger.debug("Property found for custom ClassLoaderRepository; class is: " + value);
try
{
ModifiableClassLoaderRepository repository = (ModifiableClassLoaderRepository)Thread.currentThread().getContextClassLoader().loadClass(value).newInstance();
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Custom ClassLoaderRepository created successfully " + repository);
return repository;
}
catch (Exception x)
{
if (logger.isEnabledFor(Logger.TRACE)) logger.trace("Custom ClassLoaderRepository could not be created", x);
}
}
return new DefaultClassLoaderRepository();
}
/**
* Returns the repository of MBeans for this MBeanServer
*/
private MBeanRepository getMBeanRepository()
{
return mbeanRepository;
}
/**
* Looks up the metadata associated with the given ObjectName.
* @throws InstanceNotFoundException if the given ObjectName is not a registered MBean
*/
private MBeanMetaData findMBeanMetaData(ObjectName objectName) throws InstanceNotFoundException
{
MBeanMetaData metadata = null;
if (objectName != null)
{
objectName = normalizeObjectName(objectName);
MBeanRepository repository = getMBeanRepository();
synchronized (repository)
{
metadata = repository.get(objectName);
}
}
if (metadata == null)
{
throw new InstanceNotFoundException("MBeanServer cannot find MBean with ObjectName " + objectName);
}
return metadata;
}
public void addNotificationListener(ObjectName observed, ObjectName listener, NotificationFilter filter, Object handback)
throws InstanceNotFoundException
{
listener = secureObjectName(listener);
Object mbean = findMBeanMetaData(listener).mbean;
if (!(mbean instanceof NotificationListener))
{
throw new RuntimeOperationsException(new IllegalArgumentException("MBean " + listener + " is not a NotificationListener"));
}
addNotificationListener(observed, (NotificationListener)mbean, filter, handback);
}
public void addNotificationListener(ObjectName observed, NotificationListener listener, NotificationFilter filter, Object handback)
throws InstanceNotFoundException
{
if (listener == null)
{
throw new RuntimeOperationsException(new IllegalArgumentException("NotificationListener cannot be null"));
}
observed = secureObjectName(observed);
MBeanMetaData metadata = findMBeanMetaData(observed);
Object mbean = metadata.mbean;
if (!(mbean instanceof NotificationBroadcaster))
{
throw new RuntimeOperationsException(new IllegalArgumentException("MBean " + observed + " is not a NotificationBroadcaster"));
}
addNotificationListenerImpl(metadata, listener, filter, handback);
}
private void addNotificationListenerImpl(MBeanMetaData metadata, NotificationListener listener, NotificationFilter filter, Object handback)
{
getHeadInterceptor().addNotificationListener(metadata, listener, filter, handback);
}
public void removeNotificationListener(ObjectName observed, ObjectName listener)
throws InstanceNotFoundException, ListenerNotFoundException
{
listener = secureObjectName(listener);
Object mbean = findMBeanMetaData(listener).mbean;
if (!(mbean instanceof NotificationListener))
{
throw new RuntimeOperationsException(new IllegalArgumentException("MBean " + listener + " is not a NotificationListener"));
}
removeNotificationListener(observed, (NotificationListener)mbean);
}
public void removeNotificationListener(ObjectName observed, NotificationListener listener)
throws InstanceNotFoundException, ListenerNotFoundException
{
if (listener == null)
{
throw new ListenerNotFoundException("NotificationListener cannot be null");
}
observed = secureObjectName(observed);
MBeanMetaData metadata = findMBeanMetaData(observed);
Object mbean = metadata.mbean;
if (!(mbean instanceof NotificationBroadcaster))
{
throw new RuntimeOperationsException(new IllegalArgumentException("MBean " + observed + " is not a NotificationBroadcaster"));
}
removeNotificationListenerImpl(metadata, listener);
}
public void removeNotificationListener(ObjectName observed, ObjectName listener, NotificationFilter filter, Object handback)
throws InstanceNotFoundException, ListenerNotFoundException
{
listener = secureObjectName(listener);
Object mbean = findMBeanMetaData(listener).mbean;
if (!(mbean instanceof NotificationListener))
{
throw new RuntimeOperationsException(new IllegalArgumentException("MBean " + listener + " is not a NotificationListener"));
}
removeNotificationListener(observed, (NotificationListener)mbean, filter, handback);
}
public void removeNotificationListener(ObjectName observed, NotificationListener listener, NotificationFilter filter, Object handback)
throws InstanceNotFoundException, ListenerNotFoundException
{
if (listener == null)
{
throw new ListenerNotFoundException("NotificationListener cannot be null");
}
observed = secureObjectName(observed);
MBeanMetaData metadata = findMBeanMetaData(observed);
Object mbean = metadata.mbean;
if (!(mbean instanceof NotificationEmitter))
{
throw new RuntimeOperationsException(new IllegalArgumentException("MBean " + observed + " is not a NotificationEmitter"));
}
removeNotificationListenerImpl(metadata, listener, filter, handback);
}
private void removeNotificationListenerImpl(MBeanMetaData metadata, NotificationListener listener)
throws ListenerNotFoundException
{
getHeadInterceptor().removeNotificationListener(metadata, listener);
}
private void removeNotificationListenerImpl(MBeanMetaData metadata, NotificationListener listener, NotificationFilter filter, Object handback)
throws ListenerNotFoundException
{
getHeadInterceptor().removeNotificationListener(metadata, listener, filter, handback);
}
public Object instantiate(String className)
throws ReflectionException, MBeanException
{
return instantiate(className, null, null);
}
public Object instantiate(String className, Object[] args, String[] parameters)
throws ReflectionException, MBeanException
{
if (className == null || className.trim().length() == 0)
{
throw new RuntimeOperationsException(new IllegalArgumentException("Class name cannot be null or empty"));
}
try
{
Class cls = getModifiableClassLoaderRepository().loadClass(className);
return instantiateImpl(className, cls.getClassLoader(), null, parameters, args).mbean;
}
catch (ClassNotFoundException x)
{
throw new ReflectionException(x);
}
}
public Object instantiate(String className, ObjectName loaderName)
throws ReflectionException, MBeanException, InstanceNotFoundException
{
return instantiate(className, loaderName, null, null);
}
public Object instantiate(String className, ObjectName loaderName, Object[] args, String[] parameters)
throws ReflectionException, MBeanException, InstanceNotFoundException
{
if (className == null || className.trim().length() == 0)
{
throw new RuntimeOperationsException(new IllegalArgumentException("Class name cannot be null or empty"));
}
// loaderName can be null: means using this class' ClassLoader
loaderName = secureObjectName(loaderName);
if (loaderName != null && loaderName.isPattern())
{
throw new RuntimeOperationsException(new IllegalArgumentException("ObjectName for the ClassLoader cannot be a pattern ObjectName: " + loaderName));
}
ClassLoader cl = getClassLoaderImpl(loaderName);
return instantiateImpl(className, cl, null, parameters, args).mbean;
}
private MBeanMetaData instantiateImpl(String className, ClassLoader classloader, ObjectName name, String[] params, Object[] args)
throws ReflectionException, MBeanException
{
if (params == null) params = EMPTY_PARAMS;
if (args == null) args = EMPTY_ARGS;
MBeanMetaData metadata = createMBeanMetaData();
metadata.classloader = classloader;
metadata.name = secureObjectName(name);
getHeadInterceptor().instantiate(metadata, className, params, args);
return metadata;
}
public ObjectInstance createMBean(String className, ObjectName objectName)
throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException
{
return createMBean(className, objectName, null, null);
}
public ObjectInstance createMBean(String className, ObjectName objectName, Object[] args, String[] parameters)
throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException
{
try
{
Class cls = getModifiableClassLoaderRepository().loadClass(className);
MBeanMetaData metadata = instantiateImpl(className, cls.getClassLoader(), objectName, parameters, args);
registerImpl(metadata, false);
return metadata.instance;
}
catch (ClassNotFoundException x)
{
throw new ReflectionException(x);
}
}
public ObjectInstance createMBean(String className, ObjectName objectName, ObjectName loaderName)
throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, InstanceNotFoundException
{
return createMBean(className, objectName, loaderName, null, null);
}
public ObjectInstance createMBean(String className, ObjectName objectName, ObjectName loaderName, Object[] args, String[] parameters)
throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, InstanceNotFoundException
{
loaderName = secureObjectName(loaderName);
ClassLoader cl = getClassLoaderImpl(loaderName);
MBeanMetaData metadata = instantiateImpl(className, cl, objectName, parameters, args);
registerImpl(metadata, false);
return metadata.instance;
}
public ObjectInstance registerMBean(Object mbean, ObjectName objectName)
throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException
{
return registerMBeanImpl(mbean, objectName, false);
}
private ObjectInstance registerMBeanImpl(Object mbean, ObjectName objectName, boolean privileged)
throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException
{
if (mbean == null)
{
throw new RuntimeOperationsException(new IllegalArgumentException("MBean instance cannot be null"));
}
MBeanMetaData metadata = createMBeanMetaData();
metadata.mbean = mbean;
metadata.classloader = mbean.getClass().getClassLoader();
metadata.name = secureObjectName(objectName);
registerImpl(metadata, privileged);
return metadata.instance;
}
/**
* Returns a new instance of the metadata class used to store MBean information.
*/
private MBeanMetaData createMBeanMetaData()
{
return new MBeanMetaData();
}
/**
* This method is called only to register implementation MBeans from the constructor.
* Since to create an instance of this class already requires a permission, here we hide the registration
* of implementation MBeans to the client that thus need no further permissions.
*/
private ObjectInstance privilegedRegisterMBean(final Object mbean, final ObjectName name)
throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException
{
try
{
return (ObjectInstance)AccessController.doPrivileged(new PrivilegedExceptionAction()
{
public Object run() throws Exception
{
return registerMBeanImpl(mbean, name, true);
}
});
}
catch (PrivilegedActionException x)
{
Exception xx = x.getException();
if (xx instanceof InstanceAlreadyExistsException)
throw (InstanceAlreadyExistsException)xx;
else if (xx instanceof MBeanRegistrationException)
throw (MBeanRegistrationException)xx;
else if (xx instanceof NotCompliantMBeanException)
throw (NotCompliantMBeanException)xx;
else
throw new MBeanRegistrationException(xx);
}
}
private void registerImpl(MBeanMetaData metadata, boolean privileged) throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException
{
introspector.introspect(metadata);
if (!introspector.isMBeanCompliant(metadata)) throw new NotCompliantMBeanException("MBean is not compliant");
MBeanServerInterceptor head = getHeadInterceptor();
try
{
// With this call, the MBean implementor can replace the ObjectName with a subclass that is not secure, secure it again
head.registration(metadata, MBeanServerInterceptor.PRE_REGISTER);
metadata.name = secureObjectName(metadata.name);
metadata.instance = new ObjectInstance(metadata.name, metadata.info.getClassName());
register(metadata, privileged);
head.registration(metadata, MBeanServerInterceptor.POST_REGISTER_TRUE);
}
catch (Throwable x)
{
try
{
head.registration(metadata, MBeanServerInterceptor.POST_REGISTER_FALSE);
}
catch (MBeanRegistrationException ignored)
{/* Ignore this one to rethrow the other one */
}
if (x instanceof SecurityException)
{
throw (SecurityException)x;
}
else if (x instanceof InstanceAlreadyExistsException)
{
throw (InstanceAlreadyExistsException)x;
}
else if (x instanceof MBeanRegistrationException)
{
throw (MBeanRegistrationException)x;
}
else if (x instanceof RuntimeOperationsException)
{
throw (RuntimeOperationsException)x;
}
else if (x instanceof JMRuntimeException)
{
throw (JMRuntimeException)x;
}
else if (x instanceof Exception)
{
throw new MBeanRegistrationException((Exception)x);
}
else if (x instanceof Error)
{
throw new MBeanRegistrationException(new RuntimeErrorException((Error)x));
}
else
{
throw new ImplementationException();
}
}
if (metadata.mbean instanceof ClassLoader && !(metadata.mbean instanceof PrivateClassLoader))
{
ClassLoader cl = (ClassLoader)metadata.mbean;
getModifiableClassLoaderRepository().addClassLoader(cl);
}
}
private void register(MBeanMetaData metadata, boolean privileged) throws InstanceAlreadyExistsException
{
metadata.name = normalizeObjectName(metadata.name);
ObjectName objectName = metadata.name;
if (objectName == null || objectName.isPattern())
{
throw new RuntimeOperationsException(new IllegalArgumentException("ObjectName cannot be null or a pattern ObjectName"));
}
if (objectName.getDomain().equals("JMImplementation") && !privileged)
{
throw new JMRuntimeException("Domain 'JMImplementation' is reserved for the JMX Agent");
}
MBeanRepository repository = getMBeanRepository();
synchronized (repository)
{
if (repository.get(objectName) != null) throw new InstanceAlreadyExistsException(objectName.toString());
repository.put(objectName, metadata);
}
addDomain(objectName.getDomain());
notify(objectName, MBeanServerNotification.REGISTRATION_NOTIFICATION);
}
private void notify(ObjectName objectName, String notificationType)
{
long sequenceNumber = 0;
synchronized (MX4JMBeanServer.class)
{
sequenceNumber = notifications;
++notifications;
}
delegate.sendNotification(new MBeanServerNotification(notificationType, delegateName, sequenceNumber, objectName));
}
private void addDomain(String domain)
{
synchronized (domains)
{
Integer count = (Integer)domains.get(domain);
if (count == null)
domains.put(domain, new Integer(1));
else
domains.put(domain, new Integer(count.intValue() + 1));
}
}
private void removeDomain(String domain)
{
synchronized (domains)
{
Integer count = (Integer)domains.get(domain);
if (count == null) throw new ImplementationException();
if (count.intValue() < 2)
domains.remove(domain);
else
domains.put(domain, new Integer(count.intValue() - 1));
}
}
public void unregisterMBean(ObjectName objectName)
throws InstanceNotFoundException, MBeanRegistrationException
{
objectName = secureObjectName(objectName);
if (objectName == null || objectName.isPattern())
{
throw new RuntimeOperationsException(new IllegalArgumentException("ObjectName cannot be null or a pattern ObjectName"));
}
if (objectName.getDomain().equals("JMImplementation"))
{
throw new RuntimeOperationsException(new IllegalArgumentException("Domain 'JMImplementation' is reserved for the JMX Agent"));
}
MBeanMetaData metadata = findMBeanMetaData(objectName);
try
{
MBeanServerInterceptor head = getHeadInterceptor();
head.registration(metadata, MBeanServerInterceptor.PRE_DEREGISTER);
unregister(metadata);
getHeadInterceptor().registration(metadata, MBeanServerInterceptor.POST_DEREGISTER);
if (metadata.mbean instanceof ClassLoader && !(metadata.mbean instanceof PrivateClassLoader))
{
getModifiableClassLoaderRepository().removeClassLoader((ClassLoader)metadata.mbean);
}
}
catch (MBeanRegistrationException x)
{
throw x;
}
catch (SecurityException x)
{
throw x;
}
catch (Exception x)
{
throw new MBeanRegistrationException(x);
}
catch (Error x)
{
throw new MBeanRegistrationException(new RuntimeErrorException(x));
}
}
private void unregister(MBeanMetaData metadata)
{
ObjectName objectName = metadata.name;
MBeanRepository repository = getMBeanRepository();
synchronized (repository)
{
repository.remove(objectName);
}
removeDomain(objectName.getDomain());
notify(objectName, MBeanServerNotification.UNREGISTRATION_NOTIFICATION);
}
public Object getAttribute(ObjectName objectName, String attribute)
throws InstanceNotFoundException, MBeanException, AttributeNotFoundException, ReflectionException
{
if (attribute == null || attribute.trim().length() == 0)
{
throw new RuntimeOperationsException(new IllegalArgumentException("Invalid attribute"));
}
objectName = secureObjectName(objectName);
MBeanMetaData metadata = findMBeanMetaData(objectName);
return getHeadInterceptor().getAttribute(metadata, attribute);
}
public void setAttribute(ObjectName objectName, Attribute attribute)
throws InstanceNotFoundException, AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException
{
if (attribute == null || attribute.getName().trim().length() == 0)
{
throw new RuntimeOperationsException(new IllegalArgumentException("Invalid attribute"));
}
objectName = secureObjectName(objectName);
MBeanMetaData metadata = findMBeanMetaData(objectName);
getHeadInterceptor().setAttribute(metadata, attribute);
}
public AttributeList getAttributes(ObjectName objectName, String[] attributes)
throws InstanceNotFoundException, ReflectionException
{
if (attributes == null || attributes.length == 0)
{
throw new RuntimeOperationsException(new IllegalArgumentException("Invalid attribute list"));
}
objectName = secureObjectName(objectName);
MBeanMetaData metadata = findMBeanMetaData(objectName);
SecurityManager sm = System.getSecurityManager();
if (sm != null)
{
// Must check if the user has the right to call this method, regardless of the attributes
sm.checkPermission(new MBeanPermission(metadata.info.getClassName(), "-", objectName, "getAttribute"));
}
return getHeadInterceptor().getAttributes(metadata, attributes);
}
public AttributeList setAttributes(ObjectName objectName, AttributeList attributes)
throws InstanceNotFoundException, ReflectionException
{
if (attributes == null)
{
throw new RuntimeOperationsException(new IllegalArgumentException("Invalid attribute list"));
}
objectName = secureObjectName(objectName);
MBeanMetaData metadata = findMBeanMetaData(objectName);
SecurityManager sm = System.getSecurityManager();
if (sm != null)
{
// Must check if the user has the right to call this method, regardless of the attributes
sm.checkPermission(new MBeanPermission(metadata.info.getClassName(), "-", objectName, "setAttribute"));
}
return getHeadInterceptor().setAttributes(metadata, attributes);
}
public Object invoke(ObjectName objectName, String methodName, Object[] args, String[] parameters)
throws InstanceNotFoundException, MBeanException, ReflectionException
{
if (methodName == null || methodName.trim().length() == 0)
{
throw new RuntimeOperationsException(new IllegalArgumentException("Invalid operation name '" + methodName + "'"));
}
if (args == null) args = EMPTY_ARGS;
if (parameters == null) parameters = EMPTY_PARAMS;
objectName = secureObjectName(objectName);
MBeanMetaData metadata = findMBeanMetaData(objectName);
return getHeadInterceptor().invoke(metadata, methodName, parameters, args);
}
public String getDefaultDomain()
{
return defaultDomain;
}
public String[] getDomains()
{
synchronized (domains)
{
Set keys = domains.keySet();
return (String[])keys.toArray(new String[keys.size()]);
}
}
public Integer getMBeanCount()
{
MBeanRepository repository = getMBeanRepository();
synchronized (repository)
{
return new Integer(repository.size());
}
}
public boolean isRegistered(ObjectName objectName)
{
try
{
return findMBeanMetaData(objectName) != null;
}
catch (InstanceNotFoundException x)
{
return false;
}
}
public MBeanInfo getMBeanInfo(ObjectName objectName)
throws InstanceNotFoundException, IntrospectionException, ReflectionException
{
objectName = secureObjectName(objectName);
MBeanMetaData metadata = findMBeanMetaData(objectName);
MBeanInfo info = getHeadInterceptor().getMBeanInfo(metadata);
if (info == null) throw new JMRuntimeException("MBeanInfo returned for MBean " + objectName + " is null");
return info;
}
public ObjectInstance getObjectInstance(ObjectName objectName)
throws InstanceNotFoundException
{
SecurityManager sm = System.getSecurityManager();
if (sm != null)
{
objectName = secureObjectName(objectName);
}
MBeanMetaData metadata = findMBeanMetaData(objectName);
if (sm != null)
{
sm.checkPermission(new MBeanPermission(metadata.info.getClassName(), "-", objectName, "getObjectInstance"));
}
return metadata.instance;
}
public boolean isInstanceOf(ObjectName objectName, String className)
throws InstanceNotFoundException
{
if (className == null || className.trim().length() == 0)
{
throw new RuntimeOperationsException(new IllegalArgumentException("Invalid class name"));
}
objectName = secureObjectName(objectName);
MBeanMetaData metadata = findMBeanMetaData(objectName);
SecurityManager sm = System.getSecurityManager();
if (sm != null)
{
sm.checkPermission(new MBeanPermission(metadata.info.getClassName(), "-", objectName, "isInstanceOf"));
}
try
{
ClassLoader loader = metadata.classloader;
Class cls = null;
if (loader != null)
cls = loader.loadClass(className);
else
cls = Class.forName(className, false, null);
if (metadata.mbean instanceof StandardMBean)
{
Object impl = ((StandardMBean) metadata.mbean).getImplementation();
return cls.isInstance(impl);
}
else
{
return cls.isInstance(metadata.mbean);
}
}
catch (ClassNotFoundException x)
{
return false;
}
}
public Set queryMBeans(ObjectName patternName, QueryExp filter)
{
SecurityManager sm = System.getSecurityManager();
if (sm != null)
{
patternName = secureObjectName(patternName);
// Must check if the user has the right to call this method,
// no matter which ObjectName has been passed.
sm.checkPermission(new MBeanPermission("-#-[-]", "queryMBeans"));
}
Set match = queryObjectNames(patternName, filter, true);
Set set = new HashSet();
for (Iterator i = match.iterator(); i.hasNext();)
{
ObjectName name = (ObjectName)i.next();
try
{
MBeanMetaData metadata = findMBeanMetaData(name);
set.add(metadata.instance);
}
catch (InstanceNotFoundException ignored)
{
// A concurrent thread removed the MBean after queryNames, ignore
}
}
return set;
}
public Set queryNames(ObjectName patternName, QueryExp filter)
{
SecurityManager sm = System.getSecurityManager();
if (sm != null)
{
patternName = secureObjectName(patternName);
// Must check if the user has the right to call this method,
// no matter which ObjectName has been passed.
sm.checkPermission(new MBeanPermission("-#-[-]", "queryNames"));
}
return queryObjectNames(patternName, filter, false);
}
/**
* Utility method for queryNames and queryMBeans that returns a set of ObjectNames.
* It does 3 things:
* 1) filter the MBeans following the given ObjectName pattern
* 2) filter the MBeans following the permissions that client code has
* 3) filter the MBeans following the given QueryExp
* It is important that these 3 operations are done in this order
*/
private Set queryObjectNames(ObjectName patternName, QueryExp filter, boolean instances)
{
// First, retrieve the scope of the query: all mbeans matching the patternName
Set scope = findMBeansByPattern(patternName);
// Second, filter the scope by checking the caller's permissions
Set secureScope = filterMBeansBySecurity(scope, instances);
// Third, filter the scope using the given QueryExp
Set match = filterMBeansByQuery(secureScope, filter);
return match;
}
/**
* Returns a set of ObjectNames of the registered MBeans that match the given ObjectName pattern
*/
private Set findMBeansByPattern(ObjectName pattern)
{
if (pattern == null)
{
try
{
pattern = new ObjectName("*:*");
}
catch (MalformedObjectNameException ignored)
{
}
}
pattern = normalizeObjectName(pattern);
String patternDomain = pattern.getDomain();
Hashtable patternProps = pattern.getKeyPropertyList();
Set set = new HashSet();
// Clone the repository, we are faster than holding the lock while iterating
MBeanRepository repository = (MBeanRepository)getMBeanRepository().clone();
for (Iterator i = repository.iterator(); i.hasNext();)
{
MBeanMetaData metadata = (MBeanMetaData)i.next();
ObjectName name = metadata.name;
Hashtable props = name.getKeyPropertyList();
String domain = name.getDomain();
if (Utils.wildcardMatch(patternDomain, domain))
{
// Domain matches, now check properties
if (pattern.isPropertyPattern())
{
// A property pattern with no entries, can only be '*'
if (patternProps.size() == 0)
{
// User wants all properties
set.add(name);
}
else
{
// Loop on the properties of the pattern.
// If one is not found then the current ObjectName does not match
boolean found = true;
for (Iterator j = patternProps.entrySet().iterator(); j.hasNext();)
{
Map.Entry entry = (Map.Entry)j.next();
Object patternKey = entry.getKey();
Object patternValue = entry.getValue();
if (patternKey.equals("*"))
{
continue;
}
// Try to see if the current ObjectName contains this entry
if (!props.containsKey(patternKey))
{
// Not even the key is present
found = false;
break;
}
else
{
// The key is present, let's check if the values are equal
Object value = props.get(patternKey);
if (value == null && patternValue == null)
{
// Values are equal, go on with next pattern entry
continue;
}
if (value != null && value.equals(patternValue))
{
// Values are equal, go on with next pattern entry
continue;
}
// Here values are different
found = false;
break;
}
}
if (found) set.add(name);
}
}
else
{
if (props.entrySet().equals(patternProps.entrySet())) set.add(name);
}
}
}
return set;
}
/**
* Filters the given set of ObjectNames following the permission that client code has granted.
* Returns a set containing the allowed ObjectNames.
*/
private Set filterMBeansBySecurity(Set mbeans, boolean instances)
{
SecurityManager sm = System.getSecurityManager();
if (sm == null) return mbeans;
HashSet set = new HashSet();
for (Iterator i = mbeans.iterator(); i.hasNext();)
{
ObjectName name = (ObjectName)i.next();
try
{
MBeanMetaData metadata = findMBeanMetaData(name);
String className = metadata.info.getClassName();
sm.checkPermission(new MBeanPermission(className, "-", name, instances ? "queryMBeans" : "queryNames"));
set.add(name);
}
catch (InstanceNotFoundException ignored)
{
// A concurrent thread removed this MBean, continue
continue;
}
catch (SecurityException ignored)
{
// Don't add the name to the list, and go on.
}
}
return set;
}
/**
* Filters the given set of ObjectNames following the given QueryExp.
* Returns a set of ObjectNames that match the given QueryExp.
*/
private Set filterMBeansByQuery(Set scope, QueryExp filter)
{
if (filter == null) return scope;
Set set = new HashSet();
for (Iterator i = scope.iterator(); i.hasNext();)
{
ObjectName name = (ObjectName)i.next();
filter.setMBeanServer(this);
try
{
if (filter.apply(name)) set.add(name);
}
catch (BadStringOperationException ignored)
{
}
catch (BadBinaryOpValueExpException ignored)
{
}
catch (BadAttributeValueExpException x)
{
}
catch (InvalidApplicationException x)
{
}
catch (SecurityException x)
{
}
catch (Exception x)
{
// The 1.2 spec says Exceptions must not be propagated
}
}
return set;
}
/**
* Returns a normalized ObjectName from the given one.
* If an ObjectName is specified with the abbreviated notation for the default domain, that is ':key=value'
* this method returns an ObjectName whose domain is the default domain of this MBeanServer and with the same
* properties.
*/
private ObjectName normalizeObjectName(ObjectName name)
{
if (name == null) return null;
String defaultDomain = getDefaultDomain();
String domain = name.getDomain();
if (domain.length() == 0 && defaultDomain.length() > 0)
{
// The given object name specifies the abbreviated form to indicate the default domain,
// ie ':key=value', the empty string as domain. I must convert this abbreviated form
// to the full one, if the default domain of this mbeanserver is not the empty string as well
StringBuffer buffer = new StringBuffer(defaultDomain).append(":").append(name.getKeyPropertyListString());
if (name.isPropertyPattern())
{
if (name.getKeyPropertyList().size() > 0)
buffer.append(",*");
else
buffer.append("*");
}
try
{
name = new ObjectName(buffer.toString());
}
catch (MalformedObjectNameException ignored)
{
}
}
return name;
}
/**
* Returns an ObjectName instance even if the provided ObjectName is a subclass.
* This is done to avoid security holes: a nasty ObjectName subclass can bypass security checks.
*/
private ObjectName secureObjectName(ObjectName name)
{
// I cannot trust ObjectName, since a malicious user can send a subclass that overrides equals and hashcode
// to match another ObjectName for which it does not have permission, or returns different results from
// ObjectName.getCanonicalName() for different calls, so that passes the security checks but in fact will
// later refer to a different ObjectName for which it does not have permission.
if (name == null) return null;
return ObjectName.getInstance(name);
}
}
| 35.902357 | 168 | 0.673544 |
0bf76eb809f00e170b29ede64bfb73e70b3b5bb4 | 14,371 | /* CSSParser.java --
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.html;
import java.io.*;
/**
* Parses a CSS document. This works by way of a delegate that implements the
* CSSParserCallback interface. The delegate is notified of the following
* events:
* - Import statement: handleImport
* - Selectors handleSelector. This is invoked for each string. For example if
* the Reader contained p, bar , a {}, the delegate would be notified 4 times,
* for 'p,' 'bar' ',' and 'a'.
* - When a rule starts, startRule
* - Properties in the rule via the handleProperty. This
* is invoked one per property/value key, eg font size: foo;, would cause the
* delegate to be notified once with a value of 'font size'.
* - Values in the rule via the handleValue, this is notified for the total value.
* - When a rule ends, endRule
*
* @author Lillian Angel ([email protected])
*/
class CSSParser
{
/**
* Receives all information about the CSS document structure while parsing it.
* The methods are invoked by parser.
*/
static interface CSSParserCallback
{
/**
* Handles the import statment in the document.
*
* @param imp - the import string
*/
public abstract void handleImport(String imp);
/**
* Called when the start of a rule is encountered.
*/
public abstract void startRule();
/**
* Called when the end of a rule is encountered.
*/
public abstract void endRule();
/**
* Handles the selector of a rule.
*
* @param selector - the selector in the rule
*/
public abstract void handleSelector(String selector);
/**
* Handles the properties in the document.
*
* @param property - the property in the document.
*/
public abstract void handleProperty(String property);
/**
* Handles the values in the document.
*
* @param value - the value to handle.
*/
public abstract void handleValue(String value);
}
/**
* The identifier of the rule.
*/
private static final int IDENTIFIER = 1;
/**
* The open bracket.
*/
private static final int BRACKET_OPEN = 2;
/**
* The close bracket.
*/
private static final int BRACKET_CLOSE = 3;
/**
* The open brace.
*/
private static final int BRACE_OPEN = 4;
/**
* The close brace.
*/
private static final int BRACE_CLOSE = 5;
/**
* The open parentheses.
*/
private static final int PAREN_OPEN = 6;
/**
* The close parentheses.
*/
private static final int PAREN_CLOSE = 7;
/**
* The end of the document.
*/
private static final int END = -1;
/**
* The character mapping in the document.
*/
// FIXME: What is this used for?
private static final char[] charMapping = null;
/**
* Set to true if one character has been read ahead.
*/
private boolean didPushChar;
/**
* The read ahead character.
*/
private int pushedChar;
/**
* Temporary place to hold identifiers.
*/
private StringBuffer unitBuffer;
/**
* Used to indicate blocks.
*/
private int[] unitStack;
/**
* Number of valid blocks.
*/
private int stackCount;
/**
* Holds the incoming CSS rules.
*/
private Reader reader;
/**
* Set to true when the first non @ rule is encountered.
*/
private boolean encounteredRuleSet;
/**
* The call back used to parse.
*/
private CSSParser.CSSParserCallback callback;
/**
* nextToken() inserts the string here.
*/
private char[] tokenBuffer;
/**
* Current number of chars in tokenBufferLength.
*/
private int tokenBufferLength;
/**
* Set to true if any whitespace is read.
*/
private boolean readWS;
/**
* Constructor
*/
CSSParser()
{
unitBuffer = new StringBuffer();
tokenBuffer = new char[10];
}
/**
* Appends a character to the token buffer.
*
* @param c - the character to append
*/
private void append(char c)
{
if (tokenBuffer.length >= tokenBufferLength)
{
char[] temp = new char[tokenBufferLength * 2];
if (tokenBuffer != null)
System.arraycopy(tokenBuffer, 0, temp, 0, tokenBufferLength);
temp[tokenBufferLength] = c;
tokenBuffer = temp;
}
else
tokenBuffer[tokenBufferLength] = c;
tokenBufferLength++;
}
/**
* Fetches the next token.
*
* @param c - the character to fetch.
* @return the location
* @throws IOException - any i/o error encountered while reading
*/
private int nextToken(char c) throws IOException
{
readWS = false;
int next = readWS();
switch (next)
{
case '\"':
if (tokenBufferLength > 0)
tokenBufferLength--;
return IDENTIFIER;
case '\'':
if (tokenBufferLength > 0)
tokenBufferLength--;
return IDENTIFIER;
case '(':
return PAREN_OPEN;
case ')':
return PAREN_CLOSE;
case '{':
return BRACE_OPEN;
case '}':
return BRACE_CLOSE;
case '[':
return BRACKET_OPEN;
case ']':
return BRACKET_CLOSE;
case -1:
return END;
default:
pushChar(next);
getIdentifier(c);
return IDENTIFIER;
}
}
/**
* Reads a character from the stream.
*
* @return the number of characters read or -1 if end of stream is reached.
* @throws IOException - any i/o encountered while reading
*/
private int readChar() throws IOException
{
if (didPushChar)
{
didPushChar = false;
return pushedChar;
}
return reader.read();
}
/**
* Parses the the contents of the reader using the
* callback.
*
* @param reader - the reader to read from
* @param callback - the callback instance
* @param parsingDeclaration - true if parsing a declaration
* @throws IOException - any i/o error from the reader
*/
void parse(Reader reader, CSSParser.CSSParserCallback callback,
boolean parsingDeclaration)
throws IOException
{
this.reader = reader;
this.callback = callback;
try
{
if (!parsingDeclaration)
while(getNextStatement());
else
parseDeclarationBlock();
}
catch (IOException ioe)
{
// Nothing to do here.
}
}
/**
* Skips any white space, returning the character after the white space.
*
* @return the character after the whitespace
* @throws IOException - any i/o error from the reader
*/
private int readWS() throws IOException
{
int next = readChar();
while (Character.isWhitespace((char) next))
{
readWS = true;
int tempNext = readChar();
if (tempNext == END)
return next;
next = tempNext;
}
// Its all whitespace
return END;
}
/**
* Gets the next statement, returning false if the end is reached.
* A statement is either an At-rule, or a ruleset.
*
* @return false if the end is reached
* @throws IOException - any i/o error from the reader
*/
private boolean getNextStatement() throws IOException
{
int c = nextToken((char) 0);
switch (c)
{
case PAREN_OPEN:
case BRACE_OPEN:
case BRACKET_OPEN:
parseTillClosed(c);
break;
case BRACKET_CLOSE:
case BRACE_CLOSE:
case PAREN_CLOSE:
throw new IOException("Not a proper statement.");
case IDENTIFIER:
if (tokenBuffer[0] == ('@'))
parseAtRule();
else
parseRuleSet();
break;
case END:
return false;
}
return true;
}
/**
* Parses an @ rule, stopping at a matching brace pair, or ;.
*
* @throws IOException - any i/o error from the reader
*/
private void parseAtRule() throws IOException
{
// An At-Rule begins with the "@" character followed immediately by a keyword.
// Following the keyword separated by a space is an At-rule statement appropriate
// to the At-keyword used. If the At-Rule is a simple declarative statement
// (charset, import, fontdef), it is terminated by a semi-colon (";".)
// If the At-Rule is a conditional or informative statement (media, page, font-face),
// it is followed by optional arguments and then a style declaration block inside matching
// curly braces ("{", "}".) At-Rules are sometimes nestable, depending on the context.
// If any part of an At-Rule is not understood, it should be ignored.
// FIXME: Not Implemented
// call handleimport
}
/**
* Parses the next rule set, which is a selector followed by a declaration
* block.
*
* @throws IOException - any i/o error from the reader
*/
private void parseRuleSet() throws IOException
{
// call parseDeclarationBlock
// call parse selectors
// call parse identifiers
// call startrule/endrule
// FIXME: Not Implemented
}
/**
* Parses a set of selectors, returning false if the end of the stream is
* reached.
*
* @return false if the end of stream is reached
* @throws IOException - any i/o error from the reader
*/
private boolean parseSelectors() throws IOException
{
// FIXME: Not Implemented
// call handleselector
return false;
}
/**
* Parses a declaration block. Which a number of declarations followed by a
* })].
*
* @throws IOException - any i/o error from the reader
*/
private void parseDeclarationBlock() throws IOException
{
// call parseDeclaration
// FIXME: Not Implemented
}
/**
* Parses a single declaration, which is an identifier a : and another identifier.
* This returns the last token seen.
*
* @returns the last token
* @throws IOException - any i/o error from the reader
*/
private int parseDeclaration() throws IOException
{
// call handleValue
// FIXME: Not Implemented
return 0;
}
/**
* Parses identifiers until c is encountered, returning the ending token,
* which will be IDENTIFIER if c is found.
*
* @param c - the stop character
* @param wantsBlocks - true if blocks are wanted
* @return the ending token
* @throws IOException - any i/o error from the reader
*/
private int parseIdentifiers(char c, boolean wantsBlocks) throws IOException
{
// FIXME: Not implemented
// call handleproperty?
return 0;
}
/**
* Parses till a matching block close is encountered. This is only appropriate
* to be called at the top level (no nesting).
*
* @param i - FIXME
* @throws IOException - any i/o error from the reader
*/
private void parseTillClosed(int i) throws IOException
{
// FIXME: Not Implemented
}
/**
* Gets an identifier, returning true if the length of the string is greater
* than 0, stopping when c, whitespace, or one of {}()[] is hit.
*
* @param c - the stop character
* @return returns true if the length of the string > 0
* @throws IOException - any i/o error from the reader
*/
private boolean getIdentifier(char c) throws IOException
{
// FIXME: Not Implemented
return false;
}
/**
* Reads till c is encountered, escaping characters as necessary.
*
* @param c - the stop character
* @throws IOException - any i/o error from the reader
*/
private void readTill(char c) throws IOException
{
// FIXME: Not Implemented
}
/**
* Parses a comment block.
*
* @throws IOException - any i/o error from the reader
*/
private void readComment() throws IOException
{
// Should ignore comments. Read until end of comment.
// FIXME: Not implemented
}
/**
* Called when a block start is encountered ({[.
*
* @param start of block
*/
private void startBlock(int start)
{
// FIXME: Not Implemented
}
/**
* Called when an end block is encountered )]}
*
* @param end of block
*/
private void endBlock(int end)
{
// FIXME: Not Implemented
}
/**
* Checks if currently in a block.
*
* @return true if currently in a block.
*/
private boolean inBlock()
{
// FIXME: Not Implemented
return false;
}
/**
* Supports one character look ahead, this will throw if called twice in a row.
*
* @param c - the character to push.
* @throws IOException - if called twice in a row
*/
private void pushChar(int c) throws IOException
{
if (didPushChar)
throw new IOException("pushChar called twice.");
didPushChar = true;
pushedChar = c;
}
}
| 25.301056 | 95 | 0.641639 |
369784cdb8372219e0e52e09b7d6f5f1b36caa2f | 319 | package cn.enilu.flash.bean.vo;
import lombok.Data;
import java.util.Date;
/**
* @author :enilu
* @date :Created in 11/6/2019 11:29 AM
*/
@Data
public class UserInfo {
private String mobile;
private String avatar;
private String nickName;
private Date lastLoginTime;
private String gender;
}
| 15.95 | 39 | 0.69279 |
6e23cd7deb52617af628374effd23301172cc089 | 10,887 | package com.java110.community.listener.community;
import com.alibaba.fastjson.JSONObject;
import com.java110.utils.constant.ResponseConstant;
import com.java110.utils.constant.StatusConstant;
import com.java110.utils.exception.ListenerExecuteException;
import com.java110.entity.center.Business;
import com.java110.core.event.service.AbstractBusinessServiceDataFlowListener;
import com.java110.community.dao.ICommunityServiceDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 小区 服务侦听 父类
* Created by wuxw on 2018/7/4.
*/
public abstract class AbstractCommunityBusinessServiceDataFlowListener extends AbstractBusinessServiceDataFlowListener {
private final static Logger logger = LoggerFactory.getLogger(AbstractCommunityBusinessServiceDataFlowListener.class);
/**
* 获取 DAO工具类
*
* @return
*/
public abstract ICommunityServiceDao getCommunityServiceDaoImpl();
/**
* 刷新 businessCommunityInfo 数据
* 主要将 数据库 中字段和 接口传递字段建立关系
*
* @param businessCommunityInfo
*/
protected void flushBusinessCommunityInfo(Map businessCommunityInfo, String statusCd) {
businessCommunityInfo.put("newBId", businessCommunityInfo.get("b_id"));
businessCommunityInfo.put("communityId", businessCommunityInfo.get("community_id"));
businessCommunityInfo.put("cityCode", businessCommunityInfo.get("city_code"));
businessCommunityInfo.put("nearbyLandmarks", businessCommunityInfo.get("nearby_landmarks"));
businessCommunityInfo.put("mapX", businessCommunityInfo.get("map_x"));
businessCommunityInfo.put("mapY", businessCommunityInfo.get("map_y"));
businessCommunityInfo.put("state", businessCommunityInfo.get("state"));
businessCommunityInfo.put("communityArea", businessCommunityInfo.get("community_area"));
businessCommunityInfo.put("statusCd", statusCd);
}
/**
* 刷新 businessCommunityAttr 数据
* 主要将 数据库 中字段和 接口传递字段建立关系
*
* @param businessCommunityAttr
* @param statusCd
*/
protected void flushBusinessCommunityAttr(Map businessCommunityAttr, String statusCd) {
businessCommunityAttr.put("attrId", businessCommunityAttr.get("attr_id"));
businessCommunityAttr.put("specCd", businessCommunityAttr.get("spec_cd"));
businessCommunityAttr.put("communityId", businessCommunityAttr.get("community_id"));
businessCommunityAttr.put("newBId", businessCommunityAttr.get("b_id"));
businessCommunityAttr.put("statusCd", statusCd);
}
/**
* 刷新 businessCommunityPhoto 数据
*
* @param businessCommunityPhoto
* @param statusCd
*/
protected void flushBusinessCommunityPhoto(Map businessCommunityPhoto, String statusCd) {
businessCommunityPhoto.put("communityId", businessCommunityPhoto.get("community_id"));
businessCommunityPhoto.put("communityPhotoId", businessCommunityPhoto.get("community_photo_id"));
businessCommunityPhoto.put("communityPhotoTypeCd", businessCommunityPhoto.get("community_photo_type_cd"));
businessCommunityPhoto.put("newBId", businessCommunityPhoto.get("b_id"));
businessCommunityPhoto.put("statusCd", statusCd);
}
/**
* 刷新 businessCommunityMember 数据
* 主要将 数据库 中字段和 接口传递字段建立关系
*
* @param businessCommunityMember
*/
protected void flushBusinessCommunityMember(Map businessCommunityMember, String statusCd) {
businessCommunityMember.put("newBId", businessCommunityMember.get("b_id"));
businessCommunityMember.put("communityId", businessCommunityMember.get("community_id"));
businessCommunityMember.put("communityMemberId", businessCommunityMember.get("community_member_id"));
businessCommunityMember.put("memberId", businessCommunityMember.get("member_id"));
businessCommunityMember.put("memberTypeCd", businessCommunityMember.get("member_type_cd"));
businessCommunityMember.put("auditStatusCd", businessCommunityMember.get("audit_status_cd"));
businessCommunityMember.put("statusCd", statusCd);
}
/**
* 当修改数据时,查询instance表中的数据 自动保存删除数据到business中
*
* @param businessCommunity 小区信息
*/
protected void autoSaveDelBusinessCommunity(Business business, JSONObject businessCommunity) {
//自动插入DEL
Map info = new HashMap();
info.put("communityId", businessCommunity.getString("communityId"));
info.put("statusCd", StatusConstant.STATUS_CD_VALID);
Map currentCommunityInfo = getCommunityServiceDaoImpl().getCommunityInfo(info);
if (currentCommunityInfo == null || currentCommunityInfo.isEmpty()) {
throw new ListenerExecuteException(ResponseConstant.RESULT_PARAM_ERROR, "未找到需要修改数据信息,入参错误或数据有问题,请检查" + info);
}
currentCommunityInfo.put("bId", business.getbId());
currentCommunityInfo.put("communityId", currentCommunityInfo.get("community_id"));
currentCommunityInfo.put("cityCode", currentCommunityInfo.get("city_code"));
currentCommunityInfo.put("nearbyLandmarks", currentCommunityInfo.get("nearby_landmarks"));
currentCommunityInfo.put("mapX", currentCommunityInfo.get("map_x"));
currentCommunityInfo.put("mapY", currentCommunityInfo.get("map_y"));
currentCommunityInfo.put("state", currentCommunityInfo.get("state"));
currentCommunityInfo.put("communityArea", currentCommunityInfo.get("community_area"));
currentCommunityInfo.put("operate", StatusConstant.OPERATE_DEL);
getCommunityServiceDaoImpl().saveBusinessCommunityInfo(currentCommunityInfo);
for(Object key : currentCommunityInfo.keySet()) {
if(businessCommunity.get(key) == null) {
businessCommunity.put(key.toString(), currentCommunityInfo.get(key));
}
}
}
/**
* 当修改数据时,查询instance表中的数据 自动保存删除数据到business中
*
* @param business 当前业务
* @param communityAttr 小区属性
*/
protected void autoSaveDelBusinessCommunityAttr(Business business, JSONObject communityAttr) {
Map info = new HashMap();
info.put("attrId", communityAttr.getString("attrId"));
info.put("communityId", communityAttr.getString("communityId"));
info.put("statusCd", StatusConstant.STATUS_CD_VALID);
List<Map> currentCommunityAttrs = getCommunityServiceDaoImpl().getCommunityAttrs(info);
if (currentCommunityAttrs == null || currentCommunityAttrs.size() != 1) {
throw new ListenerExecuteException(ResponseConstant.RESULT_PARAM_ERROR, "未找到需要修改数据信息,入参错误或数据有问题,请检查" + info);
}
Map currentCommunityAttr = currentCommunityAttrs.get(0);
currentCommunityAttr.put("bId", business.getbId());
currentCommunityAttr.put("attrId", currentCommunityAttr.get("attr_id"));
currentCommunityAttr.put("communityId", currentCommunityAttr.get("community_id"));
currentCommunityAttr.put("specCd", currentCommunityAttr.get("spec_cd"));
currentCommunityAttr.put("operate", StatusConstant.OPERATE_DEL);
getCommunityServiceDaoImpl().saveBusinessCommunityAttr(currentCommunityAttr);
for(Object key : currentCommunityAttr.keySet()) {
if(communityAttr.get(key) == null) {
communityAttr.put(key.toString(), currentCommunityAttr.get(key));
}
}
}
/**
* 当修改数据时,查询instance表中的数据 自动保存删除数据到business中
*
* @param business
* @param businessCommunityPhoto 小区照片
*/
protected void autoSaveDelBusinessCommunityPhoto(Business business, JSONObject businessCommunityPhoto) {
Map info = new HashMap();
info.put("communityPhotoId", businessCommunityPhoto.getString("communityPhotoId"));
info.put("communityId", businessCommunityPhoto.getString("communityId"));
info.put("statusCd", StatusConstant.STATUS_CD_VALID);
List<Map> currentCommunityPhotos = getCommunityServiceDaoImpl().getCommunityPhoto(info);
if (currentCommunityPhotos == null || currentCommunityPhotos.size() != 1) {
throw new ListenerExecuteException(ResponseConstant.RESULT_PARAM_ERROR, "未找到需要修改数据信息,入参错误或数据有问题,请检查" + info);
}
Map currentCommunityPhoto = currentCommunityPhotos.get(0);
currentCommunityPhoto.put("bId", business.getbId());
currentCommunityPhoto.put("communityPhotoId", currentCommunityPhoto.get("community_photo_id"));
currentCommunityPhoto.put("communityId", currentCommunityPhoto.get("community_id"));
currentCommunityPhoto.put("communityPhotoTypeCd", currentCommunityPhoto.get("community_photo_type_cd"));
currentCommunityPhoto.put("operate", StatusConstant.OPERATE_DEL);
getCommunityServiceDaoImpl().saveBusinessCommunityPhoto(currentCommunityPhoto);
for(Object key : currentCommunityPhoto.keySet()) {
if(businessCommunityPhoto.get(key) == null) {
businessCommunityPhoto.put(key.toString(), currentCommunityPhoto.get(key));
}
}
}
/**
* 当修改数据时,查询instance表中的数据 自动保存删除数据到business中
*
* @param businessCommunityMember 小区信息
*/
protected void autoSaveDelBusinessCommunityMember(Business business, JSONObject businessCommunityMember) {
//自动插入DEL
Map info = new HashMap();
info.put("communityMemberId", businessCommunityMember.getString("communityMemberId"));
info.put("statusCd", StatusConstant.STATUS_CD_VALID);
List<Map> currentCommunityMembers = getCommunityServiceDaoImpl().getCommunityMember(info);
if (currentCommunityMembers == null || currentCommunityMembers.size() != 1) {
throw new ListenerExecuteException(ResponseConstant.RESULT_PARAM_ERROR, "未找到需要修改数据信息,入参错误或数据有问题,请检查" + info);
}
Map currentCommunityMember = currentCommunityMembers.get(0);
currentCommunityMember.put("bId", business.getbId());
currentCommunityMember.put("communityId", currentCommunityMember.get("community_id"));
currentCommunityMember.put("communityMemberId", currentCommunityMember.get("community_member_id"));
currentCommunityMember.put("memberId", currentCommunityMember.get("member_id"));
currentCommunityMember.put("memberTypeCd", currentCommunityMember.get("member_type_cd"));
currentCommunityMember.put("auditStatusCd", currentCommunityMember.get("audit_status_cd"));
currentCommunityMember.put("operate", StatusConstant.OPERATE_DEL);
getCommunityServiceDaoImpl().saveBusinessCommunityMember(currentCommunityMember);
for(Object key : currentCommunityMember.keySet()) {
if(businessCommunityMember.get(key) == null) {
businessCommunityMember.put(key.toString(), currentCommunityMember.get(key));
}
}
}
}
| 48.386667 | 121 | 0.721962 |
008885bde9f66865e99bee44e7d77ae45b9a3434 | 274 | package com.yky.ykyblog.aspect.annotation;
import java.lang.annotation.*;
/**
* @Author: yky
* @CreateTime: 2020-08-06
* Describe:
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface PermissionCheck {
String value();
}
| 17.125 | 42 | 0.729927 |
281587f1c77946c440743a6f738344034121ba9f | 4,028 | package quina.net.nio.tcp;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
/**
* メモリでのデータ受信処理.
*
* メモリ上でデータを管理するので「大きなサイズ」の場合は
* OutputFileBodyを使ってください.
*/
public class NioRecvMemBody implements NioRecvBody {
/** Nio受信バッファ. **/
protected NioBuffer buffer;
/** 最大データ長. **/
private long length = -1L;
/** InputStream. **/
private InputStream input = null;
/** exitWriteFlag. **/
private boolean exitWriteFlag = false;
/**
* コンストラクタ.
*/
public NioRecvMemBody() {
this.buffer = new NioBuffer();
this.length = -1L;
this.exitWriteFlag = false;
}
/**
* コンストラクタ.
* @param buf Nio受信バッファを設定します.
*/
public NioRecvMemBody(NioBuffer buf) {
try {
this.buffer = buf;
this.length = -1L;
this.exitWriteFlag = false;
} catch(NioException ne) {
throw ne;
} catch(Exception e) {
throw new NioException(e);
}
}
/**
* オブジェクトのクローズ.
* @exception IOException
*/
@Override
public void close() throws IOException {
exitWrite();
if(input != null) {
try {
input.close();
} catch(Exception e) {}
input = null;
}
buffer = null;
length = -1L;
exitWriteFlag = false;
}
// クローズ済みかチェック.
protected void checkClose() {
if(buffer == null) {
throw new NioException("It is already closed.");
}
}
// 書き込みクローズ済みかチェック.
protected void checkWriteEnd() {
if(exitWriteFlag) {
throw new NioException("It is already write closed.");
}
}
/**
* binaryで書き込み.
* @param bin
* @return
* @throws IOException
*/
@Override
public int write(byte[] bin)
throws IOException {
return write(bin, 0, bin.length);
}
/**
* binaryで書き込み.
* @param bin
* @param len
* @return
* @throws IOException
*/
@Override
public int write(byte[] bin, int len)
throws IOException {
return write(bin, 0, len);
}
/**
* binaryで書き込み.
* @param bin
* @param off
* @param len
* @return
* @throws IOException
*/
@Override
public int write(byte[] bin, int off, int len)
throws IOException {
checkClose();
checkWriteEnd();
// 書き込み元のByteBufferデータが存在しない場合.
if(len <= 0) {
return 0; // データ書き込み出来ない.
}
buffer.write(bin, off, len);
return len;
}
/**
* ByteBufferで書き込み.
* ByteBufferにはremainingが無い場合は書き込みしません.
* @param buf
* @return
* @throws IOException
*/
@Override
public int write(ByteBuffer buf)
throws IOException {
checkClose();
checkWriteEnd();
// 書き込み元のByteBufferデータが存在しない場合.
if(!buf.hasRemaining()) {
return 0; // データ書き込み出来ない.
}
int ret = buf.remaining();
buffer.write(buf);
return ret;
}
/**
* 現在の受信データ長を取得.
* @return
*/
@Override
public long remaining() {
checkClose();
return (long)buffer.size();
}
/**
* 受信データが存在するかチェック.
* @return boolan true の場合受信情報は存在します.
*/
public boolean hasRemaining() {
checkClose();
return remaining() != 0L;
}
/**
* 書き込み処理を終了.
*/
@Override
public void exitWrite() {
checkClose();
// 全体の長さを更新.
length = buffer.size();
exitWriteFlag = true;
}
/**
* 書き込み終了処理が行われたかチェック.
* @return boolean [true]の場合、書き込みは終了しています.
*/
@Override
public boolean isExitWrite() {
checkClose();
return exitWriteFlag;
}
/**
* 受信される予定のBody取得データ長を取得.
* @return long -1Lの場合は[exitWrite()]を呼び出されず長さが確定していません.
*/
@Override
public long getLength() {
checkClose();
return length;
}
/**
* 読み込みInputStreamを作成.
* また、このInputStreamはクローズすると自動的に削除されます.
* @return InputStream InputStreamが返却されます.
* @exception IOException I/O例外.
*/
@Override
public InputStream getInputStream() throws IOException {
// 書き込みチャネルが閉じていない場合は閉じる.
if(!exitWriteFlag) {
exitWrite();
}
// 既にInputStream作成済み.
else if(input != null) {
// 作成した内容を返却.
return input;
}
// InputStreamを作成して返却.
input = buffer.getInputStream();
return input;
}
/**
* バイナリを取得.
* @return byte[] バイナリが返却されます.
*/
public byte[] toByteArray() {
// 書き込みチャネルが閉じていない場合は閉じる.
if(!exitWriteFlag) {
exitWrite();
}
NioBuffer b = buffer;
buffer = null;
return b.toByteArray();
}
}
| 16.995781 | 57 | 0.641758 |
1a6b631ccb35fbb83ac29fa6fddd7aced710a4cd | 854 | import java.util.Scanner; //Need to import this to use the Scanner object
class AddNumbers
{
public static void main(String args[]){
int x; //Decalre integer variable x
int y; //Declare integer variable y
int sum; //Declare integer variable sum
//Use System.out.println to print to console
System.out.println("Enter two integers to calculate their sum ");
//Scanner System.in allows for user input
Scanner in = new Scanner(System.in);
x = in.nextInt(); //First input goes into variable x
y = in.nextInt(); //Second input goes into variable y
sum = x + y; //x and y get added together and their value is stored into sum
//Print out the answer || use '+' when you want to print more on the same line
System.out.println("Sum of entered integers is as follows = " + sum);
}
}
| 35.583333 | 83 | 0.665105 |
3851d96029a7f1a829f1ae5405f8d0fdc8712054 | 3,219 | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*/
package com.microsoft.jenkins.acs;
import hudson.AbortException;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.AbstractProject;
import hudson.model.Result;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.BuildStepMonitor;
import hudson.tasks.Builder;
import jenkins.tasks.SimpleBuildStep;
import org.kohsuke.stapler.DataBoundConstructor;
import javax.annotation.Nonnull;
import java.io.IOException;
public class ACSDeploymentBuilder extends Builder implements SimpleBuildStep {
private ACSDeploymentContext context;
@DataBoundConstructor
public ACSDeploymentBuilder(ACSDeploymentContext context) {
this.context = context;
}
public ACSDeploymentContext getContext() {
return this.context;
}
@Override
public BuildStepMonitor getRequiredMonitorService() {
return BuildStepMonitor.NONE;
}
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl) super.getDescriptor();
}
@Override
public void perform(
@Nonnull Run<?, ?> run,
@Nonnull FilePath workspace,
@Nonnull Launcher launcher,
@Nonnull TaskListener listener) throws IOException, InterruptedException {
listener.getLogger().println(Messages.ACSDeploymentBuilder_starting());
this.context.configure(run, workspace, launcher, listener);
this.context.executeCommands();
if (context.getLastCommandState().isError()) {
run.setResult(Result.FAILURE);
// NB: The perform(AbstractBuild<?,?>, Launcher, BuildListener) method inherited from
// BuildStepCompatibilityLayer will delegate the call to SimpleBuildStep#perform when possible,
// and always return true (continue the followed build steps) regardless of the Run#getResult.
// We need to terminate the execution explicitly with an exception.
//
// see BuildStep#perform
// Using the return value to indicate success/failure should
// be considered deprecated, and implementations are encouraged
// to throw {@link AbortException} to indicate a failure.
throw new AbortException(Messages.ACSDeploymentBuilder_endWithErrorState(context.getCommandState()));
} else {
listener.getLogger().println(Messages.ACSDeploymentBuilder_finished());
}
}
@Extension
public static final class DescriptorImpl extends BuildStepDescriptor<Builder> {
public boolean isApplicable(Class<? extends AbstractProject> aClass) {
// Indicates that this builder can be used with all kinds of project types
return true;
}
/**
* This human readable name is used in the configuration screen.
*/
public String getDisplayName() {
return Messages.plugin_displayName();
}
}
}
| 34.98913 | 113 | 0.690898 |
dbdead979b8c1340c4748847ccea3d58001c27a4 | 706 | // Java Program to find
// transpose of a matrix
class Program10
{
static final int N = 4;
// Finds transpose of A[][] in-place
static void transpose(int A[][])
{
for (int i = 0; i < N; i++)
for (int j = i+1; j < N; j++)
{
int temp = A[i][j];
A[i][j] = A[j][i];
A[j][i] = temp;
}
}
// Driver code
public static void main (String[] args)
{
int A[][] = { {1, 1, 1, 1},
{2, 2, 2, 2},
{3, 3, 3, 3},
{4, 4, 4, 4}};
transpose(A);
System.out.print("Modified matrix is \n");
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
System.out.print(A[i][j] + " ");
System.out.print("\n");
}
}
}
| 17.65 | 45 | 0.443343 |
54a558d632646655ed9e09e7cebf9a25d43fcb8b | 1,869 | import net.runelite.mapping.Export;
import net.runelite.mapping.ObfuscatedGetter;
import net.runelite.mapping.ObfuscatedName;
import net.runelite.mapping.ObfuscatedSignature;
@ObfuscatedName("am")
public final class class43 {
@ObfuscatedName("qp")
@ObfuscatedSignature(
signature = "Ldw;"
)
@Export("pcmPlayer1")
static PcmPlayer pcmPlayer1;
@ObfuscatedName("v")
@ObfuscatedGetter(
intValue = -2015849949
)
static int field381;
@ObfuscatedName("i")
@ObfuscatedSignature(
signature = "(II)Lbn;",
garbageValue = "-983073165"
)
@Export("Messages_getMessage")
static Message Messages_getMessage(int var0) {
return (Message)Messages.Messages_hashTable.get((long)var0);
}
@ObfuscatedName("g")
@ObfuscatedSignature(
signature = "(II)I",
garbageValue = "-1093470855"
)
public static int method816(int var0) {
return class14.method169(ViewportMouse.ViewportMouse_entityTags[var0]);
}
@ObfuscatedName("d")
@ObfuscatedSignature(
signature = "(Lks;B)V",
garbageValue = "-25"
)
static final void method813(PacketBuffer var0) {
for (int var1 = 0; var1 < Players.Players_pendingUpdateCount; ++var1) {
int var2 = Players.Players_pendingUpdateIndices[var1];
Player var3 = Client.players[var2];
int var4 = var0.readUnsignedByte();
if ((var4 & 4) != 0) {
var4 += var0.readUnsignedByte() << 8;
}
AbstractWorldMapIcon.method613(var0, var2, var3, var4);
}
}
@ObfuscatedName("y")
@ObfuscatedSignature(
signature = "(Ljava/lang/String;I)V",
garbageValue = "-67193374"
)
static final void method817(String var0) {
PacketBufferNode var1 = TilePaint.getPacketBufferNode(ClientPacket.field2240, Client.packetWriter.isaacCipher);
var1.packetBuffer.writeByte(Buddy.stringCp1252NullTerminatedByteSize(var0));
var1.packetBuffer.writeStringCp1252NullTerminated(var0);
Client.packetWriter.addNode(var1);
}
}
| 26.7 | 113 | 0.738898 |
56462bcbd65fe819a4a0c303b9c1615917771d5b | 293 | package com.pratamawijaya.blog.presentation.di;
import com.pratamawijaya.blog.presentation.utils.PratamaImageLoader;
/**
* Created by Pratama Nur Wijaya
* Date : Oct - 10/15/16
* Project Name : MoviesInfoKotlin
*/
public interface UIDependencies {
PratamaImageLoader imageLoader();
}
| 20.928571 | 68 | 0.767918 |
ba6c2f8d3da49b1370e3115700c16f1f8fb3a4c1 | 4,093 | package com.vaani.leetcode.divide_and_conquer;
import java.util.Iterator;
import java.util.TreeSet;
/**
* 02/11/2019 Implement a MyCalendarTwo class to store your
* events. A new event can be added if adding the event will not cause a triple booking.
*
* <p>Your class will have one method, book(int start, int end). Formally, this represents a booking
* on the half open interval [start, end), the range of real numbers x such that start <= x < end.
*
* <p>A triple booking happens when three events have some non-empty intersection (ie., there is
* some time that is common to all 3 events.)
*
* <p>For each call to the method MyCalendar.book, return true if the event can be added to the
* calendar successfully without causing a triple booking. Otherwise, return false and do not add
* the event to the calendar.
*
* <p>Your class will be called like this: MyCalendar cal = new MyCalendar(); MyCalendar.book(start,
* end) Example 1:
*
* <p>MyCalendar(); MyCalendar.book(10, 20); // returns true MyCalendar.book(50, 60); // returns
* true MyCalendar.book(10, 40); // returns true MyCalendar.book(5, 15); // returns false
* MyCalendar.book(5, 10); // returns true MyCalendar.book(25, 55); // returns true Explanation: The
* first two events can be booked. The third event can be double booked. The fourth event (5, 15)
* can't be booked, because it would result in a triple booking. The fifth event (5, 10) can be
* booked, as it does not use time 10 which is already double booked. The sixth event (25, 55) can
* be booked, as the time in [25, 40) will be double booked with the third event; the time [40, 50)
* will be single booked, and the time [50, 55) will be double booked with the second event.
*
* <p>Note:
*
* <p>The number of calls to MyCalendar.book per test case will be at most 1000. In calls to
* MyCalendar.book(start, end), start and end are integers in the range [0, 10^9].
*/
public class MyCalendarII {
public static void main(String[] args) {
MyCalendarII t = new MyCalendarII();
System.out.println(t.book(20, 27));
System.out.println(t.book(27, 36));
System.out.println(t.book(27, 36));
System.out.println(t.book(24, 33));
}
private class Pair {
int a, b, index;
Pair(int a, int b, int index) {
this.a = a;
this.b = b;
this.index = index;
}
}
TreeSet<Pair> treeSet;
int count;
public MyCalendarII() {
count = 0;
treeSet =
new TreeSet<>(
(o1, o2) -> {
int r = Integer.compare(o1.a, o2.a);
if (r == 0) {
int r2 = Integer.compare(o1.b, o2.b);
if (r2 == 0) {
return Integer.compare(o1.index, o2.index);
} else return r2;
}
return r;
});
}
public boolean book(int start, int end) {
Pair range = new Pair(start, end, count++);
Iterator<Pair> ascending = treeSet.iterator();
Pair prev = null;
while (ascending.hasNext()) {
Pair cur = ascending.next();
if (prev != null) {
if ((range.a >= prev.a && range.a < prev.b) && (range.a >= cur.a && range.a < cur.b)) {
return false;
} else if ((prev.a >= range.a && prev.a < range.b)
&& (cur.a >= prev.a && cur.a < Math.min(prev.b, range.b))) {
return false;
} else if ((range.a >= prev.a && range.a < range.b)
&& (cur.a >= range.a && cur.a < Math.min(prev.b, range.b))) {
return false;
}
}
if ((range.a >= cur.a && range.a < cur.b) || (cur.a >= range.a && cur.a < range.b)) {
prev = cur;
}
}
treeSet.add(range);
return true;
}
}
| 40.93 | 103 | 0.549719 |
3670ed6bda5e30aff401a904d5fac50a1751aa31 | 1,871 | package leetcode;
/**
* @No 494
* @problem Target Sum
* @level Medium
* @desc 目标和
* @author liyazhou1
* @date 2019/10/07
*
* <pre>
* You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symbols + and -. For each integer, you should choose one from + and - as its new symbol.
*
* Find out how many ways to assign symbols to make sum of integers equal to target S.
*
* Example 1:
* Input: nums is [1, 1, 1, 1, 1], S is 3.
* Output: 5
* Explanation:
*
* -1+1+1+1+1 = 3
* +1-1+1+1+1 = 3
* +1+1-1+1+1 = 3
* +1+1+1-1+1 = 3
* +1+1+1+1-1 = 3
*
* There are 5 ways to assign symbols to make the sum of nums be target 3.
*
* Note:
* The length of the given array is positive and will not exceed 20.
* The sum of elements in the given array will not exceed 1000.
* Your output answer is guaranteed to be fitted in a 32-bit integer.
* </pre>
*/
public class _0494_TargetSum {
/**
* Note
*
* Thought
* 递归
*
* Challenge
*
* Algorithm
* 1.
* 2.
*
* Complexity
* Time,
* Space,
*/
private static class Solution {
public int findTargetSumWays(int[] nums, int S) {
return dfs(nums, S, 0);
}
private int dfs(int[] nums, int sum, int start) {
if (start == nums.length) {
return sum == 0 ? 1 : 0;
}
return dfs(nums, sum+nums[start], start+1)
+ dfs(nums, sum-nums[start], start+1);
}
public static void main(String[] args) {
int[] input = {1, 1, 1, 1, 1};
int target = 3;
int result = new Solution().findTargetSumWays(input, target);
System.out.println("result = " + result);
}
}
}
| 23.987179 | 187 | 0.520043 |
343521ff8733f5412312e29c601c51116d973afc | 3,384 | /**
* Apache Licence Version 2.0
* Please read the LICENCE file
*/
package org.hypothesis.event.interfaces;
import org.hypothesis.data.model.Group;
import org.hypothesis.data.model.User;
/**
* @author Kamil Morong, Tilioteo Ltd
*
* Hypothesis
*
*/
@SuppressWarnings("serial")
public interface MainUIEvent extends HypothesisEvent {
public static final class UserLoginRequestedEvent implements MainUIEvent {
private final String userName;
private final String password;
public UserLoginRequestedEvent(final String userName, final String password) {
this.userName = userName;
this.password = password;
}
public String getUserName() {
return userName;
}
public String getPassword() {
return password;
}
}
class GuestAccessRequestedEvent implements MainUIEvent {
}
class InvalidLoginEvent implements MainUIEvent {
}
class InvalidUserPermissionEvent implements MainUIEvent {
}
class UserLoggedOutEvent implements MainUIEvent {
}
final class PostViewChangeEvent implements MainUIEvent {
private final String viewName;
public PostViewChangeEvent(final String viewName) {
this.viewName = viewName;
}
public String getViewName() {
return viewName;
}
}
/*
* public static class MaskEvent implements MainUIEvent { }
*
* public static class LegacyWindowClosedEvent implements MainUIEvent { }
*/
final class CloseOpenWindowsEvent implements MainUIEvent {
}
final class ProfileUpdatedEvent implements MainUIEvent {
}
final class UserAddedEvent implements MainUIEvent {
private final User user;
public UserAddedEvent(final User user) {
this.user = user;
}
public User getUser() {
return user;
}
}
final class UserSelectionChangedEvent implements MainUIEvent {
}
final class GroupUsersChangedEvent implements MainUIEvent {
private final Group group;
public GroupUsersChangedEvent(final Group group) {
this.group = group;
}
public Group getGroup() {
return group;
}
}
final class GroupAddedEvent implements MainUIEvent {
private final Group group;
public GroupAddedEvent(final Group group) {
this.group = group;
}
public Group getGroup() {
return group;
}
}
final class GroupSelectionChangedEvent implements MainUIEvent {
}
final class UserGroupsChangedEvent implements MainUIEvent {
private final User user;
public UserGroupsChangedEvent(final User user) {
this.user = user;
}
public User getUser() {
return user;
}
}
final class UserPacksChangedEvent implements MainUIEvent {
private final User user;
public UserPacksChangedEvent(final User user) {
this.user = user;
}
public User getUser() {
return user;
}
}
final class PackSelectionChangedEvent implements MainUIEvent {
}
final class ExportFinishedEvent implements MainUIEvent {
private final boolean canceled;
public ExportFinishedEvent(final boolean canceled) {
this.canceled = canceled;
}
public boolean isCanceled() {
return canceled;
}
}
final class ExportErrorEvent implements MainUIEvent {
}
final class ExportProgressEvent implements MainUIEvent {
private final float progress;
public ExportProgressEvent(final float progress) {
this.progress = progress;
}
public float getProgress() {
return progress;
}
}
final class UserPacksRequestRefresh implements MainUIEvent {
}
}
| 19.560694 | 80 | 0.739953 |
7bfe29f2a9bce7b07eb90c92ec982ca046f19321 | 2,082 | /*
* Copyright 2021 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.kogito.incubation.processes.services.contexts;
import org.kie.kogito.incubation.common.DefaultCastable;
import org.kie.kogito.incubation.common.LocalId;
import org.kie.kogito.incubation.common.MetaDataContext;
import org.kie.kogito.incubation.processes.ProcessIdParser;
public class ProcessMetaDataContext implements DefaultCastable, MetaDataContext {
private String id;
private String businessKey;
private String startFrom;
protected ProcessMetaDataContext() {
}
public static ProcessMetaDataContext of(LocalId localId) {
ProcessMetaDataContext mdc = new ProcessMetaDataContext();
mdc.setId(localId);
return mdc;
}
public <T extends LocalId> T id(Class<T> expected) {
return ProcessIdParser.parse(id, expected);
}
String id() {
return id;
}
public String businessKey() {
return businessKey;
}
public String startFrom() {
return startFrom;
}
void setId(String id) {
this.id = id;
}
void setId(LocalId localId) {
this.id = localId.asLocalUri().path();
}
void setBusinessKey(String businessKey) {
this.businessKey = businessKey;
}
void setStartFrom(String startFrom) {
this.startFrom = startFrom;
}
@Override
public String toString() {
return "ProcessMetaDataContext{" +
"id='" + id + '\'' +
'}';
}
} | 27.394737 | 81 | 0.674832 |
4b9464e7a29bcea4decc11f8d68182da362511d6 | 5,254 | package com.example.android.notificationchannels;
import android.app.Activity;
import android.app.Notification;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends Activity {
private static final String TAG = MainActivity.class.getSimpleName();
private static final int NOTI_PRIMARY1 = 1100;
private static final int NOTI_PRIMARY2 = 1101;
private static final int NOTI_SECONDARY1 = 1200;
private static final int NOTI_SECONDARY2 = 1201;
/*
* 用来与UI进行交互的视图model
* A view model for interacting with the UI elements.
*/
private MainUi ui;
private NotificationHelper noti;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
noti = new NotificationHelper(this);
ui = new MainUi(findViewById(R.id.activity_main));
}
/**
* 发送通知
* @param id 要创建的通知id
* @param title 通知的标题
*/
public void sendNotification(int id, String title) {
Notification.Builder nb = null;
switch (id) {
case NOTI_PRIMARY1:
nb = noti.getNotification1(title, getString(R.string.primary1_body));
break;
case NOTI_PRIMARY2:
nb = noti.getNotification1(title, getString(R.string.primary2_body));
break;
case NOTI_SECONDARY1:
nb = noti.getNotification2(title, getString(R.string.secondary1_body));
break;
case NOTI_SECONDARY2:
nb = noti.getNotification2(title, getString(R.string.secondary2_body));
break;
}
if (nb != null) {
noti.notify(id, nb);
}
}
/**
* 为当前app发送Intent去加载系统通知设置
*/
public void goToNotificationSettings() {
Intent i = new Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
i.putExtra(Settings.EXTRA_APP_PACKAGE, getPackageName());
startActivity(i);
}
/**
* 为特定的通道发送Intent去加载系统通知设置UI
* @param channel Name of channel to configure
*/
public void goToNotificationSettings(String channel) {
Intent i = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS);
i.putExtra(Settings.EXTRA_APP_PACKAGE, getPackageName());
i.putExtra(Settings.EXTRA_CHANNEL_ID, channel);
startActivity(i);
}
/**
* 视图模型用来与ActivityUI元素交互
* 保持核心逻辑简单独立
*/
class MainUi implements View.OnClickListener {
final TextView titlePrimary;
final TextView titleSecondary;
private MainUi(View root) {
titlePrimary = root.findViewById(R.id.main_primary_title);
(root.findViewById(R.id.main_primary_send1)).setOnClickListener(this);
(root.findViewById(R.id.main_primary_send2)).setOnClickListener(this);
(root.findViewById(R.id.main_primary_config)).setOnClickListener(this);
titleSecondary = root.findViewById(R.id.main_secondary_title);
(root.findViewById(R.id.main_secondary_send1)).setOnClickListener(this);
(root.findViewById(R.id.main_secondary_send2)).setOnClickListener(this);
(root.findViewById(R.id.main_secondary_config)).setOnClickListener(this);
(root.findViewById(R.id.btnA)).setOnClickListener(this);
}
private String getTitlePrimaryText() {
if (titlePrimary != null) {
return titlePrimary.getText().toString();
}
return "";
}
private String getTitleSecondaryText() {
if (titlePrimary != null) {
return titleSecondary.getText().toString();
}
return "";
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.main_primary_send1:
sendNotification(NOTI_PRIMARY1, getTitlePrimaryText());
break;
case R.id.main_primary_send2:
sendNotification(NOTI_PRIMARY2, getTitlePrimaryText());
break;
case R.id.main_primary_config:
goToNotificationSettings(NotificationHelper.PRIMARY_CHANNEL);
break;
case R.id.main_secondary_send1:
sendNotification(NOTI_SECONDARY1, getTitleSecondaryText());
break;
case R.id.main_secondary_send2:
sendNotification(NOTI_SECONDARY2, getTitleSecondaryText());
break;
case R.id.main_secondary_config:
goToNotificationSettings(NotificationHelper.SECONDARY_CHANNEL);
break;
case R.id.btnA:
goToNotificationSettings();
break;
default:
Log.e(TAG, "Unknown click event.");
break;
}
}
}
}
| 33.896774 | 87 | 0.607727 |
b99fe28bdbd37df49b4d755081f0c2dc10ca11ef | 1,328 | package com.zzzmode.appopsx.common;
import android.os.Parcelable;
/**
* Created by zl on 2018/1/9.
*/
public abstract class CallerMethod implements Parcelable{
protected Class[] cParamsType;
protected String[] sParamsType;
protected Object[] params;
protected void initParams(Class[] paramsType,Object[] params){
setParamsType(paramsType);
this.params=params;
}
public void setParamsType(Class[] paramsType) {
if(paramsType != null){
sParamsType=new String[paramsType.length];
for (int i = 0; i < paramsType.length; i++) {
sParamsType[i]=paramsType[i].getName();
}
}
}
public void setParamsType(String[] paramsType) {
this.sParamsType=paramsType;
}
public Class[] getParamsType() {
if(sParamsType != null) {
if(cParamsType == null) {
cParamsType = ClassUtils.string2Class(sParamsType);
}
return cParamsType;
}
return null;
}
public Object[] getParams() {
return params;
}
public CallerMethod wrapParams(){
return ParamsFixer.wrap(this);
}
public CallerMethod unwrapParams(){
return ParamsFixer.unwrap(this);
}
public abstract int getType();
}
| 20.75 | 67 | 0.596386 |
9e62edbc0d15004aba21f1da27461b025ba75e4a | 486 | package com.github.houbb.valid.jsr.constraint;
import com.github.houbb.valid.core.api.constraint.AbstractLessThanConstraint;
import java.util.Calendar;
/**
* 日历是否在过去
* @author binbin.hou
* @since 0.0.3
*/
class CalendarPastConstraint extends AbstractLessThanConstraint<Calendar> {
public CalendarPastConstraint(boolean inclusive, Calendar expect) {
super(inclusive, expect);
}
public CalendarPastConstraint(Calendar expect) {
super(expect);
}
}
| 22.090909 | 77 | 0.736626 |
23ab1690028365af6b1f56a04011f46b7966fa9b | 1,489 | package com.xem.mzbemployeeapp.entity;
import java.io.Serializable;
/**
* Created by xuebing on 15/8/28.
*/
public class EmployeData implements Serializable {
// employe:{ accid:1, empid:1, roles:[“101”,”102”,”103”],rights:[“PH001”,”PH002”,”PH003”] }
public int accid;
public Integer empid;
public String[] roles;
public String[] rights;
public String name;
public String bname;
public String portrait;
public String positon;
public String ppid;
public String sex;
public String firstbranid;
// public String
public void setAccid(int accid) {
this.accid = accid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPortrait() {
return portrait;
}
public void setPortrait(String portrait) {
this.portrait = portrait;
}
public Integer getAccid() {
return accid;
}
public void setAccid(Integer accid) {
this.accid = accid;
}
public Integer getEmpid() {
return empid;
}
public void setEmpid(Integer empid) {
this.empid = empid;
}
public String[] getRoles() {
return roles;
}
public void setRoles(String[] roles) {
this.roles = roles;
}
public String[] getRights() {
return rights;
}
public void setRights(String[] rights) {
this.rights = rights;
}
}
| 19.592105 | 98 | 0.597045 |
dd1b0600d0abe05326ce3da3eaef17910bb5452e | 21 | package com.yemao.im; | 21 | 21 | 0.809524 |
b64239aa1f7769db11c3b05af39192fe65864d49 | 3,551 | package com.github.stephanenicolas.injectresource;
import android.app.Activity;
import android.app.Fragment;
import android.content.res.ColorStateList;
import android.graphics.Movie;
import android.os.Bundle;
import android.view.animation.Animation;
import com.test.injectresource.R;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
/**
* @author SNI
*/
@RunWith(InjectResourceTestRunner.class)
public class InjectResourceProcessorInFragmentTest {
public static final int RESOURCE_ID_STRING = R.string.string1;
public static final int RESOURCE_ID_INTEGER = R.integer.integer1;
public static final int RESOURCE_ID_BOOLEAN = R.bool.bool1;
public static final int RESOURCE_ID_STRING_ARRAY = R.array.array1;
public static final int RESOURCE_ID_INTEGER_ARRAY = R.array.intarray1;
public static final int RESOURCE_ID_MOVIE = R.raw.small;
public static final int RESOURCE_ID_ANIMATION = android.R.anim.fade_in;
public static final int RESOURCE_COLOR_STATE_LIST = R.color.colorlist;
public static final String TAG = "TAG";
@Test
public void shouldInjectResource_simple() {
TestActivity activity = Robolectric.buildActivity(TestActivity.class).create().get();
assertThat(activity.fragment.string, is(Robolectric.application.getText(RESOURCE_ID_STRING)));
assertThat(activity.fragment.intA,
is(Robolectric.application.getResources().getInteger(RESOURCE_ID_INTEGER)));
assertThat(activity.fragment.intB,
is(Robolectric.application.getResources().getInteger(RESOURCE_ID_INTEGER)));
assertThat(activity.fragment.boolA,
is(Robolectric.application.getResources().getBoolean(RESOURCE_ID_BOOLEAN)));
assertThat(activity.fragment.boolB,
is(Robolectric.application.getResources().getBoolean(RESOURCE_ID_BOOLEAN)));
assertThat(activity.fragment.arrayA,
is(Robolectric.application.getResources().getStringArray(RESOURCE_ID_STRING_ARRAY)));
assertThat(activity.fragment.arrayB,
is(Robolectric.application.getResources().getIntArray(RESOURCE_ID_INTEGER_ARRAY)));
assertNotNull(activity.fragment.anim);
//doesn't work on Robolectric..
//assertNotNull(activity.movie);
assertNotNull(activity.fragment.colorStateList);
}
public static class TestActivity extends Activity {
private TestFragment fragment;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fragment = new TestFragment();
getFragmentManager().beginTransaction().add(fragment, TAG).commit();
}
public static class TestFragment extends Fragment {
@InjectResource(RESOURCE_ID_STRING)
protected String string;
@InjectResource(RESOURCE_ID_INTEGER)
protected int intA;
@InjectResource(RESOURCE_ID_INTEGER)
protected Integer intB;
@InjectResource(RESOURCE_ID_BOOLEAN)
protected boolean boolA;
@InjectResource(RESOURCE_ID_BOOLEAN)
protected Boolean boolB;
@InjectResource(RESOURCE_ID_STRING_ARRAY)
protected String[] arrayA;
@InjectResource(RESOURCE_ID_INTEGER_ARRAY)
protected int[] arrayB;
@InjectResource(RESOURCE_ID_MOVIE)
protected Movie movie;
@InjectResource(RESOURCE_ID_ANIMATION)
protected Animation anim;
@InjectResource(RESOURCE_COLOR_STATE_LIST)
protected ColorStateList colorStateList;
}
}
}
| 39.898876 | 98 | 0.770206 |
4488377303e9157a2922add3ae6963f87a98f196 | 3,239 | package tfar.upgradableshields.world;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.nbt.INBT;
import net.minecraft.nbt.ListNBT;
import net.minecraft.world.World;
import net.minecraft.world.server.ServerWorld;
import net.minecraft.world.storage.WorldSavedData;
import net.minecraftforge.common.util.Constants;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.UUID;
public class PersistentData extends WorldSavedData {
private final HashSet<UUID> hasBook = new HashSet<>();
private final Map<UUID,UpgradeData> upgradeDataMap = new HashMap<>();
public static PersistentData getDefaultInstance(ServerWorld level) {
return getInstance(level.getServer().getWorld(World.OVERWORLD));
}
public UpgradeData getOrCreate(UUID uuid) {
if (upgradeDataMap.containsKey(uuid)) {
return upgradeDataMap.get(uuid);
}
UpgradeData upgradeData = UpgradeData.makeDefault();
upgradeDataMap.put(uuid,upgradeData);
markDirty();
return upgradeDataMap.get(uuid);
}
private static PersistentData getInstance(ServerWorld level) {
return level.getSavedData()
.getOrCreate(() -> new PersistentData(level.getDimensionKey().getLocation().toString())
,level.getDimensionKey().getLocation().toString());
}
public PersistentData(String name) {
super(name);
}
public boolean alreadyJoined(UUID uuid) {
return hasBook.contains(uuid);
}
public void markJoined(UUID uuid) {
hasBook.add(uuid);
markDirty();
}
@Override
public void read(CompoundNBT nbt) {
hasBook.clear();
upgradeDataMap.clear();
ListNBT listNBT = nbt.getList("hasBook", Constants.NBT.TAG_COMPOUND);
for (INBT inbt : listNBT) {
CompoundNBT nbt1 = (CompoundNBT)inbt;
UUID uuid = nbt1.getUniqueId("uuid");
hasBook.add(uuid);
}
ListNBT listNBT1 = nbt.getList("upgrade_datas",Constants.NBT.TAG_COMPOUND);
for (INBT inbt : listNBT1) {
CompoundNBT nbt1 = (CompoundNBT)inbt;
ListNBT listNBT2 = nbt1.getList("upgrade_data",Constants.NBT.TAG_COMPOUND);
UpgradeData upgradeData = UpgradeData.read(listNBT2);
UUID uuid = nbt1.getUniqueId("uuid");
upgradeDataMap.put(uuid,upgradeData);
}
}
@Override
public CompoundNBT write(CompoundNBT compound) {
ListNBT listNBT = new ListNBT();
for (UUID uuid : hasBook) {
CompoundNBT nbt1 = new CompoundNBT();
nbt1.putUniqueId("uuid",uuid);
listNBT.add(nbt1);
}
ListNBT listNBT1 = new ListNBT();
for (Map.Entry<UUID,UpgradeData> entry: upgradeDataMap.entrySet()) {
CompoundNBT nbt1 = new CompoundNBT();
nbt1.putUniqueId("uuid",entry.getKey());
nbt1.put("upgrade_data",entry.getValue().save());
listNBT1.add(nbt1);
}
if (!listNBT.isEmpty())
compound.put("hasBook",listNBT);
if (!listNBT1.isEmpty())
compound.put("upgrade_datas",listNBT1);
return compound;
}
}
| 32.39 | 103 | 0.641247 |
a7209773451f41fe1ab9f318388d94b254090475 | 1,338 | package com.boboyuwu.xnews.mvp.presenter;
import com.boboyuwu.xnews.beans.NewsDetailBean;
import com.boboyuwu.xnews.common.utils.RxSubscriber;
import com.boboyuwu.xnews.common.utils.RxSubscriberState;
import com.boboyuwu.xnews.common.utils.RxUtil;
import com.boboyuwu.xnews.mvp.model.NewsDetailModel;
import com.boboyuwu.xnews.mvp.view.NewsDetailView;
import java.util.Map;
import javax.inject.Inject;
/**
* Created by wubo on 2017/9/25.
* 获取详情页Presenter
*/
public class NewsDetailPresenter extends BasePresenter<NewsDetailView> {
NewsDetailModel mNewsDetailModel;
@Inject
public NewsDetailPresenter() {
mNewsDetailModel = new NewsDetailModel();
}
/**
* 获取新闻详情界面
*/
public void getNewsDetail(final String postId) {
addDispose(mNewsDetailModel.getNewsDetail(postId)
.compose(RxUtil.<Map<String, NewsDetailBean>>schedulerFlowableOnIoThread())
.subscribeWith(new RxSubscriber<Map<String, NewsDetailBean>>(mBaseView, RxSubscriberState.builder()
.setLoadMode(RxSubscriberState.LOAD).build()) {
@Override
public void onNext(Map<String, NewsDetailBean> detail) {
mBaseView.onLoadNewsDetail(detail.get(postId));
}
}));
}
}
| 29.733333 | 115 | 0.675635 |
9545c0794a3e722ad8fbd578001dea6e43dffe6f | 641 | package ch.unisg.roster.roster.application.handler;
import ch.unisg.roster.roster.application.port.in.ExecutorAddedEvent;
import ch.unisg.roster.roster.application.port.in.ExecutorAddedEventHandler;
import ch.unisg.roster.roster.domain.ExecutorRegistry;
import org.springframework.stereotype.Component;
@Component
public class ExecutorAddedHandler implements ExecutorAddedEventHandler {
@Override
public boolean handleNewExecutorEvent(ExecutorAddedEvent executorAddedEvent) {
return ExecutorRegistry.getInstance().addExecutor(executorAddedEvent.getExecutorType(),
executorAddedEvent.getExecutorURI());
}
}
| 37.705882 | 95 | 0.817473 |
160ae0722c68c7cd3e8a09f2dd135ece73f70402 | 4,633 | /*
* 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.syncope.core.persistence.jpa.entity;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import org.apache.syncope.core.persistence.api.entity.Any;
import org.apache.syncope.core.persistence.api.entity.GroupablePlainAttr;
import org.apache.syncope.core.persistence.api.entity.Membership;
import org.apache.syncope.core.persistence.api.entity.GroupableRelatable;
import org.apache.syncope.core.persistence.api.entity.Relationship;
import org.apache.syncope.core.persistence.api.entity.RelationshipType;
public abstract class AbstractGroupableRelatable<
L extends Any<P>,
M extends Membership<L>,
P extends GroupablePlainAttr<L, M>,
R extends Any<?>,
REL extends Relationship<L, R>>
extends AbstractAny<P> implements GroupableRelatable<L, M, P, R, REL> {
private static final long serialVersionUID = -2269285197388729673L;
protected abstract List<? extends P> internalGetPlainAttrs();
@Override
public boolean remove(final P attr) {
return internalGetPlainAttrs().remove(attr);
}
@Override
public Optional<? extends P> getPlainAttr(final String plainSchema) {
return internalGetPlainAttrs().stream().filter(plainAttr
-> plainAttr != null && plainAttr.getSchema() != null && plainAttr.getMembership() == null
&& plainSchema.equals(plainAttr.getSchema().getKey())).findFirst();
}
@Override
public Optional<? extends P> getPlainAttr(final String plainSchema, final Membership<?> membership) {
return internalGetPlainAttrs().stream().filter(plainAttr
-> plainAttr != null && plainAttr.getSchema() != null
&& plainAttr.getMembership() != null && plainAttr.getMembership().equals(membership)
&& plainSchema.equals(plainAttr.getSchema().getKey())).findFirst();
}
@Override
public List<? extends P> getPlainAttrs() {
return internalGetPlainAttrs().stream().filter(plainAttr
-> plainAttr != null && plainAttr.getSchema() != null && plainAttr.getMembership() == null).
collect(Collectors.toList());
}
@Override
public Collection<? extends P> getPlainAttrs(final String plainSchema) {
return internalGetPlainAttrs().stream().filter(plainAttr
-> plainAttr != null && plainAttr.getSchema() != null
&& plainSchema.equals(plainAttr.getSchema().getKey())).
collect(Collectors.toList());
}
@Override
public Collection<? extends P> getPlainAttrs(final Membership<?> membership) {
return internalGetPlainAttrs().stream().filter(plainAttr
-> plainAttr != null && plainAttr.getSchema() != null
&& membership.equals(plainAttr.getMembership())).
collect(Collectors.toList());
}
@Override
public Optional<? extends M> getMembership(final String groupKey) {
return getMemberships().stream().filter(membership
-> groupKey != null && groupKey.equals(membership.getRightEnd().getKey())).findFirst();
}
@Override
public Collection<? extends REL> getRelationships(final RelationshipType relationshipType) {
return getRelationships().stream().filter(relationship
-> relationshipType != null && relationshipType.equals(relationship.getType())).
collect(Collectors.toList());
}
@Override
public Collection<? extends REL> getRelationships(final String otherEndKey) {
return getRelationships().stream().filter(relationship
-> otherEndKey != null && otherEndKey.equals(relationship.getRightEnd().getKey())).
collect(Collectors.toList());
}
}
| 43.299065 | 108 | 0.684006 |
4f1ba2021603bf99e9da758ebddfe9cc0b30b5ae | 786 | package cl.mineduc.sismologia.models.entity;
import java.io.Serializable;
import java.math.BigDecimal;
import javax.validation.constraints.NotEmpty;
import org.hibernate.validator.constraints.Range;
import lombok.Getter;
import lombok.Setter;
/**
*
* Rango de Magnitudes
*
* @author Alejandro Sandoval S.
*
*/
@Setter
@Getter
public class Rango implements Serializable{
/**
*
*/
private static final long serialVersionUID = -7179732598731034411L;
@Range(min = (long) 0.0, max = (long) 10.0, message="La magnitud mínima 0 hasta 10")
public double minmagnitude;
@Range(min = (long) 0.0, max = (long) 10.0, message="La magnitud mínima 0 hasta 10")
public double maxmagnitude;
public Rango() {
super();
// TODO Auto-generated constructor stub
}
}
| 17.466667 | 85 | 0.712468 |
872eb73621d8e5bb3146600b1430385b560f981f | 3,249 | package rxfamily.entity;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.Map;
/**
* Created by Ray_L_Pain on 2018/1/13 0013.
*/
public class HealthMyFamilyBean extends BaseEntity {
@SerializedName("data")
public DataBean data;
public class DataBean {
@SerializedName("homeplans")
public ArrayList<Map<String, ArrayList<HomeBean.FamilyBean>>> homeplans;
public class HomeBean {
public class FamilyBean {
@SerializedName("APPLY_DATE")//申请时间
public String APPLY_DATE;
@SerializedName("JOIN_AMOUNT")//加入金额
public String JOIN_AMOUNT;
@SerializedName("PERIOD_TPYE")//期限类型(1.年,2.月,3天)
public String PERIOD_TPYE;
@SerializedName("PLAN_PERIOD")//互助期限
public String PLAN_PERIOD;
@SerializedName("STATUS")//状态(1.已提交;2.审核通过;3.审核驳回;4.保障中;5.已结算;6.已结束)
public String STATUS;
@SerializedName("TAG")//目前有四种类型:本人;配偶;子女;父母
public String TAG;
@SerializedName("TAG_ID")//1:本人;2:配偶;3:父母;4:子女;
public String TAG_ID;
@SerializedName("WAIT_PERIOD") //等待生效天数
public String waitTime;
@SerializedName("joinUserId")//加入人员ID
public String joinUserId;
@SerializedName("msg")//描述内容
public String msg;
@SerializedName("projectId")//参与项目ID
public String projectId;
@SerializedName("project_name") //参与项目名称
public String project_name;
@SerializedName("user_name") //加入人员姓名
public String user_name;
@SerializedName("birthday")
public String birthday;
@SerializedName("id_num")
public String id_num;
@SerializedName("statusName")
public String statusName;
@Override
public String toString() {
return "FamilyBean{" +
"APPLY_DATE='" + APPLY_DATE + '\'' +
", JOIN_AMOUNT='" + JOIN_AMOUNT + '\'' +
", PERIOD_TPYE='" + PERIOD_TPYE + '\'' +
", PLAN_PERIOD='" + PLAN_PERIOD + '\'' +
", STATUS='" + STATUS + '\'' +
", TAG='" + TAG + '\'' +
", TAG_ID='" + TAG_ID + '\'' +
", waitTime='" + waitTime + '\'' +
", joinUserId='" + joinUserId + '\'' +
", msg='" + msg + '\'' +
", projectId='" + projectId + '\'' +
", project_name='" + project_name + '\'' +
", user_name='" + user_name + '\'' +
", birthday='" + birthday + '\'' +
", id_num='" + id_num + '\'' +
", statusName='" + statusName + '\'' +
'}';
}
}
}
}
}
| 39.621951 | 84 | 0.451524 |
4107b296f91d562766e60ab3989c79306f4d916b | 3,746 | package com.seadev.aksi.model.dataapi;
import com.google.gson.annotations.SerializedName;
public class DataHarian {
@SerializedName("attributes")
private Attributes attributes;
public DataHarian() {
}
public DataHarian(Attributes attributes) {
this.attributes = attributes;
}
public Attributes getAttributes() {
return attributes;
}
public class Attributes {
@SerializedName("Hari_ke")
private int hari;
@SerializedName("Tanggal")
private long tgl;
@SerializedName("Jumlah_Kasus_Kumulatif")
private int KasusTotal;
@SerializedName("Jumlah_pasien_dalam_perawatan")
private int dalamPerawatan;
@SerializedName("Jumlah_Pasien_Sembuh")
private int sembuh;
@SerializedName("Jumlah_Pasien_Meninggal")
private int meninggal;
@SerializedName("Jumlah_Kasus_Baru_per_Hari")
private int kasusBaru;
@SerializedName("Jumlah_Kasus_Sembuh_per_Hari")
private int sembuhBaru;
@SerializedName("Jumlah_Kasus_Dirawat_per_Hari")
private int dirawatBaru;
@SerializedName("Jumlah_Kasus_Meninggal_per_Hari")
private int meninggalBaru;
@SerializedName("Persentase_Pasien_dalam_Perawatan")
private double persenPerawatan;
@SerializedName("Persentase_Pasien_Sembuh")
private double persenSembuh;
@SerializedName("Persentase_Pasien_Meninggal")
private double persenMeninggal;
public Attributes() {
}
public Attributes(int hari, int tgl, int kasusTotal, int dalamPerawatan, int sembuh, int meninggal) {
this.hari = hari;
this.tgl = tgl;
KasusTotal = kasusTotal;
this.dalamPerawatan = dalamPerawatan;
this.sembuh = sembuh;
this.meninggal = meninggal;
}
public Attributes(int hari, int tgl, int kasusTotal, int dalamPerawatan, int sembuh, int meninggal, int kasusBaru, int sembuhBaru, int dirawatBaru, int meninggalBaru, double persenPerawatan, double persenSembuh, double persenMeninggal) {
this.hari = hari;
this.tgl = tgl;
KasusTotal = kasusTotal;
this.dalamPerawatan = dalamPerawatan;
this.sembuh = sembuh;
this.meninggal = meninggal;
this.kasusBaru = kasusBaru;
this.sembuhBaru = sembuhBaru;
this.dirawatBaru = dirawatBaru;
this.meninggalBaru = meninggalBaru;
this.persenPerawatan = persenPerawatan;
this.persenSembuh = persenSembuh;
this.persenMeninggal = persenMeninggal;
}
public int getHari() {
return hari;
}
public long getTgl() {
return tgl;
}
public int getKasusTotal() {
return KasusTotal;
}
public int getDalamPerawatan() {
return dalamPerawatan;
}
public int getSembuh() {
return sembuh;
}
public int getMeninggal() {
return meninggal;
}
public int getKasusBaru() {
return kasusBaru;
}
public int getSembuhBaru() {
return sembuhBaru;
}
public int getDirawatBaru() {
return dirawatBaru;
}
public int getMeninggalBaru() {
return meninggalBaru;
}
public double getPersenPerawatan() {
return persenPerawatan;
}
public double getPersenSembuh() {
return persenSembuh;
}
public double getPersenMeninggal() {
return persenMeninggal;
}
}
}
| 28.165414 | 245 | 0.605446 |
5349e278c33ac4e0414e523df71a846efc24f29b | 4,638 | package com.example.wenda01;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import com.example.wenda01.utils.Ks;
import com.example.wenda01.utils.TTSUtility;
import com.example.wenda01.utils.ToastUtils;
import com.example.wenda01.views.Wheel.WheelView;
import org.litepal.LitePal;
public class MyApplication extends Application { //启动的应用
private static Context context; //全局上下文
private static boolean isSoundOpen; //是否开启播报辅助功能
private static boolean isDialogOpen; //是否开启对话框辅助功能
private static int sayLock=0; //声音播报锁
private static String reportString; //播报内容
private static WheelView wheelView=null;
public static int HSIZE=6; //历史记录存储大小
public static boolean bzRDel=true; //病症记录删除提示
public static int qaMsgDel= Ks.QA_MSG_UNDEL; //知识问答消息删除标记
public static int qaSesDel= Ks.QA_MSG_UNDEL; //知识问答会话删除标记
public static int getQaMsgDel() {
return qaMsgDel;
}
public static void setQaMsgDel(int qaMsgDel) {
MyApplication.qaMsgDel = qaMsgDel;
}
public static int getQaSesDel() {
return qaSesDel;
}
public static void setQaSesDel(int qaSesDel) {
MyApplication.qaSesDel = qaSesDel;
}
@Override
public void onCreate() {
super.onCreate();
context=getApplicationContext();
LitePal.initialize(context);
initSound();
initDialog();
}
@Override
public void onTrimMemory(int level) {
super.onTrimMemory(level);
saveSound();
saveDialog();
}
private void initSound(){
SharedPreferences sharedPreferences=getSharedPreferences("init",MODE_PRIVATE);
isSoundOpen=sharedPreferences.getBoolean("isSoundOpen",true);
}
private void saveSound(){
SharedPreferences sharedPreferences=getSharedPreferences("init",MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putBoolean("isSoundOpen",isSoundOpen);
editor.commit();
}
public static boolean isIsSoundOpen() {
return isSoundOpen;
}
public static void setIsSoundOpen(boolean isSoundOpen) {
MyApplication.isSoundOpen = isSoundOpen;
}
public static void changeSoundOpen(){
if(isIsSoundOpen()){
setIsSoundOpen(false);
ToastUtils.showS("辅助语音功能关闭");
TTSUtility.getInstance(getContext()).stopSpeaking();
}else{
setIsSoundOpen(true);
ToastUtils.showS("辅助语音功能开启");
}
}
private void initDialog(){
SharedPreferences sharedPreferences=getSharedPreferences("init",MODE_PRIVATE);
isDialogOpen=sharedPreferences.getBoolean("isDialogOpen",true);
}
private void saveDialog(){
SharedPreferences sharedPreferences=getSharedPreferences("init",MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putBoolean("isDialogOpen",isDialogOpen);
editor.commit();
}
public static boolean isIsDialogOpen() {
return isDialogOpen;
}
public static void setIsDialogOpen(boolean isDialogOpen) {
MyApplication.isDialogOpen = isDialogOpen;
}
public static void changeDialogOpen(){
if(isIsDialogOpen()){
setIsDialogOpen(false);
ToastUtils.showS("对话介绍功能关闭");
TTSUtility.getInstance(getContext()).stopSpeaking();
}else{
setIsDialogOpen(true);
ToastUtils.showS("对话介绍功能开启");
}
}
public static Context getContext(){
return context;
}
public static int getSayLock() {
return sayLock;
}
public static void setSayLock(int sayLock) {
MyApplication.sayLock = sayLock;
}
public static boolean isSayLocked(){
return sayLock==0;
}
public static void addSayLock(){
sayLock++;
}
public static void subSayLock(){
sayLock--;
}
public static String getReportString() {
return reportString;
}
public static void setReportString(String reportString) {
MyApplication.reportString = reportString;
}
public static WheelView getWheelView() {
return wheelView;
}
public static void setWheelView(WheelView wheelView) {
MyApplication.wheelView = wheelView;
}
public static boolean hasWheelView(){
return wheelView==null;
}
public static boolean isBzRDel() {
return bzRDel;
}
public static void setBzRDel(boolean bzRDel) {
MyApplication.bzRDel = bzRDel;
}
}
| 26.809249 | 86 | 0.663217 |
c0daeb305f0b202f9446c8ee0ef29754758b4403 | 48,171 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v@@BUILD_VERSION@@
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2011.03.27 um 12:23:14 MESZ
//
package biz.wolschon.fileformats.gnucash.jwsdpimpl.generated;
/**
* Java content class for anonymous complex type.
* <p>The following schema fragment specifies the expected content contained within this java content object. (defined at file:/C:/Users/fox/Documents/My%20Dropbox/Sourcecode/jGnucashLib-GPL/plugins/biz.wolschon.finance.jgnucash.viewer.main/source/gnucash.xsd line 161)
* <p>
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <all>
* <element name="sx_id">
* <complexType>
* <simpleContent>
* <extension base="<http://www.w3.org/2001/XMLSchema>string">
* <attribute name="type" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* </extension>
* </simpleContent>
* </complexType>
* </element>
* <element name="sx_name" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="sx_enabled" minOccurs="0">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="n"/>
* <enumeration value="y"/>
* </restriction>
* </element>
* <element name="sx_autoCreate">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="n"/>
* <enumeration value="y"/>
* </restriction>
* </element>
* <element name="sx_autoCreateNotify">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="n"/>
* <enumeration value="y"/>
* </restriction>
* </element>
* <element name="sx_advanceCreateDays" type="{http://www.w3.org/2001/XMLSchema}byte"/>
* <element name="sx_advanceRemindDays" type="{http://www.w3.org/2001/XMLSchema}int"/>
* <element name="sx_instanceCount" type="{http://www.w3.org/2001/XMLSchema}byte"/>
* <element name="sx_start">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{}gdate"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="sx_end" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{}gdate"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="sx_last" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{}gdate"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="sx_num-occur" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* <element name="sx_rem-occur" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* <element name="sx_templ-acct">
* <complexType>
* <simpleContent>
* <extension base="<http://www.w3.org/2001/XMLSchema>string">
* <attribute name="type">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}NMTOKEN">
* <enumeration value="guid"/>
* </restriction>
* </simpleType>
* </attribute>
* </extension>
* </simpleContent>
* </complexType>
* </element>
* <element name="sx_freqspec" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="gnc_freqspec">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="fs_id">
* <complexType>
* <simpleContent>
* <extension base="<http://www.w3.org/2001/XMLSchema>string">
* <attribute name="type" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* </extension>
* </simpleContent>
* </complexType>
* </element>
* <element name="fs_ui_type" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="fs_monthly">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="fs_interval" type="{http://www.w3.org/2001/XMLSchema}int"/>
* <element name="fs_offset" type="{http://www.w3.org/2001/XMLSchema}int"/>
* <element name="fs_day" type="{http://www.w3.org/2001/XMLSchema}int"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </sequence>
* <attribute name="version" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="sx_schedule" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="gnc_recurrence" maxOccurs="unbounded" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="recurrence_mult" type="{http://www.w3.org/2001/XMLSchema}int"/>
* <element name="recurrence_period_type" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="recurrence_start">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="gdate" type="{http://www.w3.org/2001/XMLSchema}string"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="recurrence_weekend_adj" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* <attribute name="version" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </all>
* <attribute name="version" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*/
public interface GncSchedxactionType {
/**
* Gets the value of the sxStart property.
*
* @return
* possible object is
* {@link biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxStartType}
*/
biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxStartType getSxStart();
/**
* Sets the value of the sxStart property.
*
* @param value
* allowed object is
* {@link biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxStartType}
*/
void setSxStart(biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxStartType value);
/**
* Gets the value of the sxTemplAcct property.
*
* @return
* possible object is
* {@link biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxTemplAcctType}
*/
biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxTemplAcctType getSxTemplAcct();
/**
* Sets the value of the sxTemplAcct property.
*
* @param value
* allowed object is
* {@link biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxTemplAcctType}
*/
void setSxTemplAcct(biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxTemplAcctType value);
/**
* Gets the value of the sxAutoCreateNotify property.
*
* @return
* possible object is
* {@link java.lang.String}
*/
java.lang.String getSxAutoCreateNotify();
/**
* Sets the value of the sxAutoCreateNotify property.
*
* @param value
* allowed object is
* {@link java.lang.String}
*/
void setSxAutoCreateNotify(java.lang.String value);
/**
* Gets the value of the sxEnd property.
*
* @return
* possible object is
* {@link biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxEndType}
*/
biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxEndType getSxEnd();
/**
* Sets the value of the sxEnd property.
*
* @param value
* allowed object is
* {@link biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxEndType}
*/
void setSxEnd(biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxEndType value);
/**
* Gets the value of the sxLast property.
*
* @return
* possible object is
* {@link biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxLastType}
*/
biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxLastType getSxLast();
/**
* Sets the value of the sxLast property.
*
* @param value
* allowed object is
* {@link biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxLastType}
*/
void setSxLast(biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxLastType value);
/**
* Gets the value of the sxRemOccur property.
*
*/
int getSxRemOccur();
/**
* Sets the value of the sxRemOccur property.
*
*/
void setSxRemOccur(int value);
/**
* Gets the value of the sxAutoCreate property.
*
* @return
* possible object is
* {@link java.lang.String}
*/
java.lang.String getSxAutoCreate();
/**
* Sets the value of the sxAutoCreate property.
*
* @param value
* allowed object is
* {@link java.lang.String}
*/
void setSxAutoCreate(java.lang.String value);
/**
* Gets the value of the sxInstanceCount property.
*
*/
byte getSxInstanceCount();
/**
* Sets the value of the sxInstanceCount property.
*
*/
void setSxInstanceCount(byte value);
/**
* Gets the value of the sxName property.
*
* @return
* possible object is
* {@link java.lang.String}
*/
java.lang.String getSxName();
/**
* Sets the value of the sxName property.
*
* @param value
* allowed object is
* {@link java.lang.String}
*/
void setSxName(java.lang.String value);
/**
* Gets the value of the sxSchedule property.
*
* @return
* possible object is
* {@link biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxScheduleType}
*/
biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxScheduleType getSxSchedule();
/**
* Sets the value of the sxSchedule property.
*
* @param value
* allowed object is
* {@link biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxScheduleType}
*/
void setSxSchedule(biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxScheduleType value);
/**
* Gets the value of the sxFreqspec property.
*
* @return
* possible object is
* {@link biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxFreqspecType}
*/
biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxFreqspecType getSxFreqspec();
/**
* Sets the value of the sxFreqspec property.
*
* @param value
* allowed object is
* {@link biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxFreqspecType}
*/
void setSxFreqspec(biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxFreqspecType value);
/**
* Gets the value of the sxAdvanceCreateDays property.
*
*/
byte getSxAdvanceCreateDays();
/**
* Sets the value of the sxAdvanceCreateDays property.
*
*/
void setSxAdvanceCreateDays(byte value);
/**
* Gets the value of the sxAdvanceRemindDays property.
*
*/
int getSxAdvanceRemindDays();
/**
* Sets the value of the sxAdvanceRemindDays property.
*
*/
void setSxAdvanceRemindDays(int value);
/**
* Gets the value of the sxEnabled property.
*
* @return
* possible object is
* {@link java.lang.String}
*/
java.lang.String getSxEnabled();
/**
* Sets the value of the sxEnabled property.
*
* @param value
* allowed object is
* {@link java.lang.String}
*/
void setSxEnabled(java.lang.String value);
/**
* Gets the value of the version property.
*
* @return
* possible object is
* {@link java.lang.String}
*/
java.lang.String getVersion();
/**
* Sets the value of the version property.
*
* @param value
* allowed object is
* {@link java.lang.String}
*/
void setVersion(java.lang.String value);
/**
* Gets the value of the sxId property.
*
* @return
* possible object is
* {@link biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxIdType}
*/
biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxIdType getSxId();
/**
* Sets the value of the sxId property.
*
* @param value
* allowed object is
* {@link biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxIdType}
*/
void setSxId(biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxIdType value);
/**
* Gets the value of the sxNumOccur property.
*
*/
int getSxNumOccur();
/**
* Sets the value of the sxNumOccur property.
*
*/
void setSxNumOccur(int value);
/**
* Java content class for anonymous complex type.
* <p>The following schema fragment specifies the expected content contained within this java content object. (defined at file:/C:/Users/fox/Documents/My%20Dropbox/Sourcecode/jGnucashLib-GPL/plugins/biz.wolschon.finance.jgnucash.viewer.main/source/gnucash.xsd line 208)
* <p>
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{}gdate"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*/
public interface SxEndType {
/**
* Gets the value of the gdate property.
*
* @return
* possible object is
* {@link java.util.Calendar}
*/
java.util.Calendar getGdate();
/**
* Sets the value of the gdate property.
*
* @param value
* allowed object is
* {@link java.util.Calendar}
*/
void setGdate(java.util.Calendar value);
}
/**
* Java content class for anonymous complex type.
* <p>The following schema fragment specifies the expected content contained within this java content object. (defined at file:/C:/Users/fox/Documents/My%20Dropbox/Sourcecode/jGnucashLib-GPL/plugins/biz.wolschon.finance.jgnucash.viewer.main/source/gnucash.xsd line 239)
* <p>
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="gnc_freqspec">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="fs_id">
* <complexType>
* <simpleContent>
* <extension base="<http://www.w3.org/2001/XMLSchema>string">
* <attribute name="type" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* </extension>
* </simpleContent>
* </complexType>
* </element>
* <element name="fs_ui_type" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="fs_monthly">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="fs_interval" type="{http://www.w3.org/2001/XMLSchema}int"/>
* <element name="fs_offset" type="{http://www.w3.org/2001/XMLSchema}int"/>
* <element name="fs_day" type="{http://www.w3.org/2001/XMLSchema}int"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </sequence>
* <attribute name="version" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*/
public interface SxFreqspecType {
/**
* Gets the value of the gncFreqspec property.
*
* @return
* possible object is
* {@link biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxFreqspecType.GncFreqspecType}
*/
biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxFreqspecType.GncFreqspecType getGncFreqspec();
/**
* Sets the value of the gncFreqspec property.
*
* @param value
* allowed object is
* {@link biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxFreqspecType.GncFreqspecType}
*/
void setGncFreqspec(biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxFreqspecType.GncFreqspecType value);
/**
* Java content class for anonymous complex type.
* <p>The following schema fragment specifies the expected content contained within this java content object. (defined at file:/C:/Users/fox/Documents/My%20Dropbox/Sourcecode/jGnucashLib-GPL/plugins/biz.wolschon.finance.jgnucash.viewer.main/source/gnucash.xsd line 242)
* <p>
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="fs_id">
* <complexType>
* <simpleContent>
* <extension base="<http://www.w3.org/2001/XMLSchema>string">
* <attribute name="type" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* </extension>
* </simpleContent>
* </complexType>
* </element>
* <element name="fs_ui_type" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="fs_monthly">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="fs_interval" type="{http://www.w3.org/2001/XMLSchema}int"/>
* <element name="fs_offset" type="{http://www.w3.org/2001/XMLSchema}int"/>
* <element name="fs_day" type="{http://www.w3.org/2001/XMLSchema}int"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </sequence>
* <attribute name="version" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*/
public interface GncFreqspecType {
/**
* Gets the value of the fsUiType property.
*
* @return
* possible object is
* {@link java.lang.String}
*/
java.lang.String getFsUiType();
/**
* Sets the value of the fsUiType property.
*
* @param value
* allowed object is
* {@link java.lang.String}
*/
void setFsUiType(java.lang.String value);
/**
* Gets the value of the fsMonthly property.
*
* @return
* possible object is
* {@link biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxFreqspecType.GncFreqspecType.FsMonthlyType}
*/
biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxFreqspecType.GncFreqspecType.FsMonthlyType getFsMonthly();
/**
* Sets the value of the fsMonthly property.
*
* @param value
* allowed object is
* {@link biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxFreqspecType.GncFreqspecType.FsMonthlyType}
*/
void setFsMonthly(biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxFreqspecType.GncFreqspecType.FsMonthlyType value);
/**
* Gets the value of the fsId property.
*
* @return
* possible object is
* {@link biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxFreqspecType.GncFreqspecType.FsIdType}
*/
biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxFreqspecType.GncFreqspecType.FsIdType getFsId();
/**
* Sets the value of the fsId property.
*
* @param value
* allowed object is
* {@link biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxFreqspecType.GncFreqspecType.FsIdType}
*/
void setFsId(biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxFreqspecType.GncFreqspecType.FsIdType value);
/**
* Gets the value of the version property.
*
* @return
* possible object is
* {@link java.lang.String}
*/
java.lang.String getVersion();
/**
* Sets the value of the version property.
*
* @param value
* allowed object is
* {@link java.lang.String}
*/
void setVersion(java.lang.String value);
/**
* Java content class for anonymous complex type.
* <p>The following schema fragment specifies the expected content contained within this java content object. (defined at file:/C:/Users/fox/Documents/My%20Dropbox/Sourcecode/jGnucashLib-GPL/plugins/biz.wolschon.finance.jgnucash.viewer.main/source/gnucash.xsd line 245)
* <p>
* <pre>
* <complexType>
* <simpleContent>
* <extension base="<http://www.w3.org/2001/XMLSchema>string">
* <attribute name="type" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* </extension>
* </simpleContent>
* </complexType>
* </pre>
*
*/
public interface FsIdType {
/**
* Gets the value of the value property.
*
* @return
* possible object is
* {@link java.lang.String}
*/
java.lang.String getValue();
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link java.lang.String}
*/
void setValue(java.lang.String value);
/**
* Gets the value of the type property.
*
* @return
* possible object is
* {@link java.lang.String}
*/
java.lang.String getType();
/**
* Sets the value of the type property.
*
* @param value
* allowed object is
* {@link java.lang.String}
*/
void setType(java.lang.String value);
}
/**
* Java content class for anonymous complex type.
* <p>The following schema fragment specifies the expected content contained within this java content object. (defined at file:/C:/Users/fox/Documents/My%20Dropbox/Sourcecode/jGnucashLib-GPL/plugins/biz.wolschon.finance.jgnucash.viewer.main/source/gnucash.xsd line 255)
* <p>
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="fs_interval" type="{http://www.w3.org/2001/XMLSchema}int"/>
* <element name="fs_offset" type="{http://www.w3.org/2001/XMLSchema}int"/>
* <element name="fs_day" type="{http://www.w3.org/2001/XMLSchema}int"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*/
public interface FsMonthlyType {
/**
* Gets the value of the fsDay property.
*
*/
int getFsDay();
/**
* Sets the value of the fsDay property.
*
*/
void setFsDay(int value);
/**
* Gets the value of the fsInterval property.
*
*/
int getFsInterval();
/**
* Sets the value of the fsInterval property.
*
*/
void setFsInterval(int value);
/**
* Gets the value of the fsOffset property.
*
*/
int getFsOffset();
/**
* Sets the value of the fsOffset property.
*
*/
void setFsOffset(int value);
}
}
}
/**
* Java content class for anonymous complex type.
* <p>The following schema fragment specifies the expected content contained within this java content object. (defined at file:/C:/Users/fox/Documents/My%20Dropbox/Sourcecode/jGnucashLib-GPL/plugins/biz.wolschon.finance.jgnucash.viewer.main/source/gnucash.xsd line 164)
* <p>
* <pre>
* <complexType>
* <simpleContent>
* <extension base="<http://www.w3.org/2001/XMLSchema>string">
* <attribute name="type" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* </extension>
* </simpleContent>
* </complexType>
* </pre>
*
*/
public interface SxIdType {
/**
* Gets the value of the value property.
*
* @return
* possible object is
* {@link java.lang.String}
*/
java.lang.String getValue();
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link java.lang.String}
*/
void setValue(java.lang.String value);
/**
* Gets the value of the type property.
*
* @return
* possible object is
* {@link java.lang.String}
*/
java.lang.String getType();
/**
* Sets the value of the type property.
*
* @param value
* allowed object is
* {@link java.lang.String}
*/
void setType(java.lang.String value);
}
/**
* Java content class for anonymous complex type.
* <p>The following schema fragment specifies the expected content contained within this java content object. (defined at file:/C:/Users/fox/Documents/My%20Dropbox/Sourcecode/jGnucashLib-GPL/plugins/biz.wolschon.finance.jgnucash.viewer.main/source/gnucash.xsd line 215)
* <p>
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{}gdate"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*/
public interface SxLastType {
/**
* Gets the value of the gdate property.
*
* @return
* possible object is
* {@link java.util.Calendar}
*/
java.util.Calendar getGdate();
/**
* Sets the value of the gdate property.
*
* @param value
* allowed object is
* {@link java.util.Calendar}
*/
void setGdate(java.util.Calendar value);
}
/**
* Java content class for anonymous complex type.
* <p>The following schema fragment specifies the expected content contained within this java content object. (defined at file:/C:/Users/fox/Documents/My%20Dropbox/Sourcecode/jGnucashLib-GPL/plugins/biz.wolschon.finance.jgnucash.viewer.main/source/gnucash.xsd line 271)
* <p>
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="gnc_recurrence" maxOccurs="unbounded" minOccurs="0">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="recurrence_mult" type="{http://www.w3.org/2001/XMLSchema}int"/>
* <element name="recurrence_period_type" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="recurrence_start">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="gdate" type="{http://www.w3.org/2001/XMLSchema}string"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="recurrence_weekend_adj" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* <attribute name="version" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*/
public interface SxScheduleType {
/**
* Gets the value of the GncRecurrence property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the GncRecurrence property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getGncRecurrence().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxScheduleType.GncRecurrenceType}
*
*/
java.util.List getGncRecurrence();
/**
* Java content class for anonymous complex type.
* <p>The following schema fragment specifies the expected content contained within this java content object. (defined at file:/C:/Users/fox/Documents/My%20Dropbox/Sourcecode/jGnucashLib-GPL/plugins/biz.wolschon.finance.jgnucash.viewer.main/source/gnucash.xsd line 274)
* <p>
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="recurrence_mult" type="{http://www.w3.org/2001/XMLSchema}int"/>
* <element name="recurrence_period_type" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="recurrence_start">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="gdate" type="{http://www.w3.org/2001/XMLSchema}string"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* <element name="recurrence_weekend_adj" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* <attribute name="version" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*/
public interface GncRecurrenceType {
/**
* Gets the value of the recurrenceMult property.
*
*/
int getRecurrenceMult();
/**
* Sets the value of the recurrenceMult property.
*
*/
void setRecurrenceMult(int value);
/**
* Gets the value of the recurrencePeriodType property.
*
* @return
* possible object is
* {@link java.lang.String}
*/
java.lang.String getRecurrencePeriodType();
/**
* Sets the value of the recurrencePeriodType property.
*
* @param value
* allowed object is
* {@link java.lang.String}
*/
void setRecurrencePeriodType(java.lang.String value);
/**
* Gets the value of the recurrenceStart property.
*
* @return
* possible object is
* {@link biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxScheduleType.GncRecurrenceType.RecurrenceStartType}
*/
biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxScheduleType.GncRecurrenceType.RecurrenceStartType getRecurrenceStart();
/**
* Sets the value of the recurrenceStart property.
*
* @param value
* allowed object is
* {@link biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxScheduleType.GncRecurrenceType.RecurrenceStartType}
*/
void setRecurrenceStart(biz.wolschon.fileformats.gnucash.jwsdpimpl.generated.GncSchedxactionType.SxScheduleType.GncRecurrenceType.RecurrenceStartType value);
/**
* Gets the value of the recurrenceWeekendAdj property.
*
* @return
* possible object is
* {@link java.lang.String}
*/
java.lang.String getRecurrenceWeekendAdj();
/**
* Sets the value of the recurrenceWeekendAdj property.
*
* @param value
* allowed object is
* {@link java.lang.String}
*/
void setRecurrenceWeekendAdj(java.lang.String value);
/**
* Gets the value of the version property.
*
* @return
* possible object is
* {@link java.lang.String}
*/
java.lang.String getVersion();
/**
* Sets the value of the version property.
*
* @param value
* allowed object is
* {@link java.lang.String}
*/
void setVersion(java.lang.String value);
/**
* Java content class for anonymous complex type.
* <p>The following schema fragment specifies the expected content contained within this java content object. (defined at file:/C:/Users/fox/Documents/My%20Dropbox/Sourcecode/jGnucashLib-GPL/plugins/biz.wolschon.finance.jgnucash.viewer.main/source/gnucash.xsd line 279)
* <p>
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="gdate" type="{http://www.w3.org/2001/XMLSchema}string"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*/
public interface RecurrenceStartType {
/**
* Gets the value of the gdate property.
*
* @return
* possible object is
* {@link java.lang.String}
*/
java.lang.String getGdate();
/**
* Sets the value of the gdate property.
*
* @param value
* allowed object is
* {@link java.lang.String}
*/
void setGdate(java.lang.String value);
}
}
}
/**
* Java content class for anonymous complex type.
* <p>The following schema fragment specifies the expected content contained within this java content object. (defined at file:/C:/Users/fox/Documents/My%20Dropbox/Sourcecode/jGnucashLib-GPL/plugins/biz.wolschon.finance.jgnucash.viewer.main/source/gnucash.xsd line 201)
* <p>
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element ref="{}gdate"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*/
public interface SxStartType {
/**
* Gets the value of the gdate property.
*
* @return
* possible object is
* {@link java.util.Calendar}
*/
java.util.Calendar getGdate();
/**
* Sets the value of the gdate property.
*
* @param value
* allowed object is
* {@link java.util.Calendar}
*/
void setGdate(java.util.Calendar value);
}
/**
* Java content class for anonymous complex type.
* <p>The following schema fragment specifies the expected content contained within this java content object. (defined at file:/C:/Users/fox/Documents/My%20Dropbox/Sourcecode/jGnucashLib-GPL/plugins/biz.wolschon.finance.jgnucash.viewer.main/source/gnucash.xsd line 224)
* <p>
* <pre>
* <complexType>
* <simpleContent>
* <extension base="<http://www.w3.org/2001/XMLSchema>string">
* <attribute name="type">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}NMTOKEN">
* <enumeration value="guid"/>
* </restriction>
* </simpleType>
* </attribute>
* </extension>
* </simpleContent>
* </complexType>
* </pre>
*
*/
public interface SxTemplAcctType {
/**
* Gets the value of the value property.
*
* @return
* possible object is
* {@link java.lang.String}
*/
java.lang.String getValue();
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link java.lang.String}
*/
void setValue(java.lang.String value);
/**
* Gets the value of the type property.
*
* @return
* possible object is
* {@link java.lang.String}
*/
java.lang.String getType();
/**
* Sets the value of the type property.
*
* @param value
* allowed object is
* {@link java.lang.String}
*/
void setType(java.lang.String value);
}
}
| 38.413876 | 285 | 0.504619 |
a072438721882b9307b101a6b95c33edc4fe6f7d | 1,469 | package me.Munchii.Shex.Errors;
import me.Munchii.Shex.Lexing.Lexer;
import me.Munchii.Shex.Shex;
import me.Munchii.Shex.Tokens.Location;
import me.Munchii.Shex.Utils.Color;
import me.Munchii.Shex.Utils.ErrorHelper;
import java.util.stream.IntStream;
public class UnexpectedCharacterError extends Error
{
private final String Error = "UnexpectedCharacterError";
private final String Description = "Unexpected character";
private final Location Position;
private final char Value;
public UnexpectedCharacterError (Location Position, char Value)
{
super ("UnexpectedCharacterError", "Unexpected character", Position, Value);
this.Position = Position;
this.Value = Value;
}
@Override
public String toString ()
{
String Lines = ErrorHelper.MakeLines (Position);
StringBuilder LinesAmount = new StringBuilder ();
LinesAmount.append (Position.GetStartLine ());
if (!(Position.GetStartLine () == Position.GetEndLine ())) LinesAmount.append ("-" + Position.GetEndLine ());
return Color.BoldRed.GetANSICode () + Color.Underline.GetANSICode () + Error + Color.Reset.GetANSICode () + '\n' + '\n' +
'\t' + Color.Reset.GetANSICode () + Description + ": '" + Value + "'" + '\n' +
'\t' + Color.Reset.GetANSICode () + Color.Make256Color (60) + Shex.GetPath () + ":" + LinesAmount.toString () + '\n' + '\n' +
Lines;
}
}
| 34.162791 | 141 | 0.656229 |
57ddb4a5c979ea150dc5bd3b4d2b1ce5574019bd | 3,952 | package com.packt.modern.api.controller;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.packt.modern.api.AppConfig;
import com.packt.modern.api.entity.ShipmentEntity;
import com.packt.modern.api.exception.RestApiErrorHandler;
import com.packt.modern.api.hateoas.ShipmentRepresentationModelAssembler;
import com.packt.modern.api.model.Shipment;
import com.packt.modern.api.service.ShipmentService;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.List;
import java.util.UUID;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.BeanUtils;
import org.springframework.boot.test.json.JacksonTester;
import org.springframework.context.MessageSource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
/**
* @author : github.com/sharmasourabh
* @project : Chapter09 - Modern API Development with Spring and Spring Boot
**/
@ExtendWith(MockitoExtension.class)
public class ShipmentControllerTest {
private static final String id = "a1b9b31d-e73c-4112-af7c-b68530f38222";
private MockMvc mockMvc;
@Mock
private ShipmentService service;
@Mock
private ShipmentRepresentationModelAssembler assembler;
@Mock
private MessageSource msgSource;
@InjectMocks
private ShipmentController controller;
private ShipmentEntity entity;
private Shipment model = new Shipment();
private JacksonTester<List<Shipment>> shipmentTester;
@BeforeEach
public void setup() {
ObjectMapper mapper = new AppConfig().objectMapper();
JacksonTester.initFields(this, mapper);
MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new
MappingJackson2HttpMessageConverter();
mappingJackson2HttpMessageConverter.setObjectMapper(mapper);
mockMvc = MockMvcBuilders.standaloneSetup(controller)
.setControllerAdvice(new RestApiErrorHandler(msgSource))
.setMessageConverters(mappingJackson2HttpMessageConverter)
//.alwaysDo(print())
.build();
final Instant now = Instant.now();
entity = new ShipmentEntity()
.setId(UUID.fromString(id))
.setCarrier("Carrier").setEstDeliveryDate(new Timestamp(now.getEpochSecond() * 1000));
BeanUtils.copyProperties(entity, model);
model.setId(entity.getId().toString());
model.setEstDeliveryDate(entity.getEstDeliveryDate().toLocalDateTime().toLocalDate());
}
@Test
@DisplayName("returns shipments by given order ID")
public void testGetShipmentByOrderId() throws Exception {
// given
given(service.getShipmentByOrderId(id))
.willReturn(List.of(entity));
given(assembler.toListModel(List.of(entity)))
.willReturn(List.of(model));
// when
MockHttpServletResponse response = mockMvc.perform(
get("/api/v1/shipping/" + id)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andDo(print())
.andReturn().getResponse();
// then
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
assertThat(response.getContentAsString())
.isEqualTo(shipmentTester.write(List.of(model)).getJson());
}
}
| 38.368932 | 94 | 0.775304 |
d8c5136f4ec9c1e60ab3bcf79cbd8675480e0643 | 1,042 | /*
* @(#)ObservableArraySet.java
* Copyright © 2021 The authors and contributors of JHotDraw. MIT License.
*/
package org.jhotdraw8.collection;
import javafx.beans.InvalidationListener;
import javafx.collections.ObservableSet;
import javafx.collections.SetChangeListener;
import java.util.ArrayList;
public class ObservableArraySet<E> extends ArrayList<E> implements ObservableSet<E> {
private static final long serialVersionUID = 1L;
public ObservableArraySet() {
}
@Override
public void addListener(SetChangeListener<? super E> listener) {
throw new UnsupportedOperationException();
}
@Override
public void addListener(InvalidationListener listener) {
throw new UnsupportedOperationException();
}
@Override
public void removeListener(InvalidationListener listener) {
throw new UnsupportedOperationException();
}
@Override
public void removeListener(SetChangeListener<? super E> listener) {
throw new UnsupportedOperationException();
}
}
| 26.717949 | 85 | 0.737044 |
60e4cc2c66582d616f407d58d20aa1500f47abca | 1,184 | package cyou.mrd.persist;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import net.sf.ehcache.config.CacheConfiguration;
import net.sf.ehcache.store.MemoryStoreEvictionPolicy;
public class EhCacheCache implements Cache {
protected CacheManager manager;
public EhCacheCache() {
manager = CacheManager.create();
}
public void createGroup(String group) {
CacheConfiguration conf = new CacheConfiguration(group, 1000)
.eternal(true).overflowToDisk(false).diskPersistent(false)
.memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LRU);
net.sf.ehcache.Cache cache = new net.sf.ehcache.Cache(conf);
manager.addCache(cache);
}
public void put(String group, Object key, Object entity) {
getCache(group).put(new Element(key,entity));
}
public Object get(String group, Object key) {
Element element = getCache(group).get(key);
if(element == null)
return null;
return element.getObjectValue();
}
public boolean remove(String group, Object key) {
return getCache(group).remove(key);
}
protected net.sf.ehcache.Cache getCache(String group) {
return manager.getCache(group);
}
}
| 27.534884 | 64 | 0.728885 |
890cb0d451969db7c3b665e9f0fc9b457029df51 | 28,213 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package bookstore.GUI;
import bookstore.BLL.GianHangBLL;
import bookstore.Entity.GianHang;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
/**
*
* @author HieuNguyen
*/
public class frmGianHang extends javax.swing.JFrame {
GianHangBLL obj = new GianHangBLL();
ArrayList<GianHang> lst = new ArrayList<>();
/**
* Creates new form frmGianHang
*/
public frmGianHang() {
initComponents();
setIconImage(new ImageIcon(getClass().getResource("imgs/library.png")).getImage());
setDefaultCloseOperation(HIDE_ON_CLOSE);
binData("", "", "");
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPopupMenu1 = new javax.swing.JPopupMenu();
jPanel1 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
txtMaGianHang = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jScrollPane2 = new javax.swing.JScrollPane();
txtMoTa = new javax.swing.JTextArea();
txtTenGianHang = new javax.swing.JTextField();
jPanel3 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
tbGianHang = new javax.swing.JTable();
txtTimKiem = new javax.swing.JTextField();
btnTimKiem = new javax.swing.JButton();
jLabel4 = new javax.swing.JLabel();
jPanel4 = new javax.swing.JPanel();
btnThem = new javax.swing.JButton();
btnSua = new javax.swing.JButton();
btnLamTuoi = new javax.swing.JButton();
btnXoa = new javax.swing.JButton();
btnXuat = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Quản Lý Gian Hàng | Phần Mềm Quản Lý Cửa Hàng Kinh Doanh Sách");
setLocation(new java.awt.Point(250, 50));
setResizable(false);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
jLabel1.setText("Mã Gian Hàng");
jLabel2.setText("Tên Gian Hàng");
jLabel3.setText("Mô tả");
txtMoTa.setColumns(20);
txtMoTa.setRows(5);
jScrollPane2.setViewportView(txtMoTa);
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(38, 38, 38)
.addComponent(jLabel1)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addContainerGap(38, Short.MAX_VALUE)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(txtTenGianHang, javax.swing.GroupLayout.PREFERRED_SIZE, 169, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addGap(29, 29, 29)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jLabel3)
.addComponent(jLabel2))
.addComponent(txtMaGianHang, javax.swing.GroupLayout.PREFERRED_SIZE, 169, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(49, 49, 49))
);
jPanel2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jScrollPane2, txtMaGianHang, txtTenGianHang});
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(42, 42, 42)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(txtMaGianHang, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel2)
.addGap(18, 18, 18)
.addComponent(txtTenGianHang, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(28, 28, 28)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(34, 34, 34))
);
jPanel3.setBackground(new java.awt.Color(255, 255, 255));
tbGianHang.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
tbGianHang.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tbGianHangMouseClicked(evt);
}
});
jScrollPane1.setViewportView(tbGianHang);
btnTimKiem.setText("Tìm Kiếm");
btnTimKiem.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
btnTimKiemMouseClicked(evt);
}
});
btnTimKiem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnTimKiemActionPerformed(evt);
}
});
jLabel4.setText("Tìm Kiếm Theo Tên Gian Hàng");
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 420, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(59, 59, 59)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(txtTimKiem, javax.swing.GroupLayout.PREFERRED_SIZE, 240, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btnTimKiem)))))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel4)
.addGap(5, 5, 5)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtTimKiem, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnTimKiem, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(21, 21, 21)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE))
);
btnThem.setText("Thêm");
btnThem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnThemActionPerformed(evt);
}
});
btnSua.setText("Sửa");
btnSua.setEnabled(false);
btnSua.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
btnSuaMouseClicked(evt);
}
});
btnLamTuoi.setText("Làm Tươi");
btnLamTuoi.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
btnLamTuoiMouseClicked(evt);
}
});
btnLamTuoi.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLamTuoiActionPerformed(evt);
}
});
btnXoa.setText("Xóa");
btnXoa.setEnabled(false);
btnXoa.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
btnXoaMouseClicked(evt);
}
});
btnXuat.setText("Xuất DS");
btnXuat.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
btnXuatMouseClicked(evt);
}
});
btnXuat.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnXuatActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGap(36, 36, 36)
.addComponent(btnLamTuoi)
.addGap(78, 78, 78)
.addComponent(btnThem)
.addGap(74, 74, 74)
.addComponent(btnSua)
.addGap(69, 69, 69)
.addComponent(btnXoa)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnXuat)
.addGap(20, 20, 20))
);
jPanel4Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnLamTuoi, btnSua, btnThem, btnXoa, btnXuat});
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnThem)
.addComponent(btnSua, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnXoa, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnLamTuoi, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnXuat, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 12, Short.MAX_VALUE))
);
jPanel4Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btnLamTuoi, btnSua, btnThem, btnXoa});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 439, javax.swing.GroupLayout.PREFERRED_SIZE))))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(14, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
public void binData(String t, String w, String o) {
lst = obj.getAll(t, w, o);
Vector col = new Vector();
col.add("Mã Gian Hàng");
col.add("Tên Gian Hàng");
col.add("Mô Tả");
Vector data = new Vector();
for (GianHang i : lst) {
Vector row = new Vector();
row.add(i.getMaGianHang());
row.add(i.getTenGianHang());
row.add(i.getMoTa());
data.add(row);
}
DefaultTableModel dtm = new DefaultTableModel(data, col);
tbGianHang.setModel(dtm);
}
void clearText() {
txtMaGianHang.setText("");
txtTenGianHang.setText("");
txtMoTa.setText("");
txtTimKiem.setText("");
}
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
// TODO add your handling code here:
new frmHeThong().setVisible(true);
}//GEN-LAST:event_formWindowClosing
private void tbGianHangMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbGianHangMouseClicked
// TODO add your handling code here:
if(tbGianHang.getSelectedRow() == -1) return;
btnThem.setEnabled(false);
btnSua.setEnabled(true);
btnXoa.setEnabled(true);
int row = tbGianHang.getSelectedRow();
txtMaGianHang.setText(tbGianHang.getValueAt(row, 0).toString());
txtTenGianHang.setText(tbGianHang.getValueAt(row, 1).toString());
txtMoTa.setText(tbGianHang.getValueAt(row, 2).toString());
}//GEN-LAST:event_tbGianHangMouseClicked
private void btnLamTuoiMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnLamTuoiMouseClicked
// TODO add your handling code here:
binData("", "", "");
clearText();
btnThem.setEnabled(true);
btnSua.setEnabled(false);
btnXoa.setEnabled(false);
}//GEN-LAST:event_btnLamTuoiMouseClicked
private void btnThemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnThemActionPerformed
// TODO add your handling code here:
GianHang data = new GianHang();
if (txtMaGianHang.getText().equals("")) {
JOptionPane.showMessageDialog(this, "Mã gian hàng trống!");
return;
}
data.setMaGianHang(txtMaGianHang.getText());
if (txtTenGianHang.getText().equals("")) {
JOptionPane.showMessageDialog(this, "Tên gian hàng gian hàng trống!");
return;
}
data.setTenGianHang(txtTenGianHang.getText());
data.setMoTa(txtMoTa.getText());
if (obj.insertData(data)) {
binData("", "", "");
JOptionPane.showMessageDialog(this, "Thêm mới thành công !");
} else {
JOptionPane.showMessageDialog(this, "Thêm mới thất bại !");
}
clearText();
}//GEN-LAST:event_btnThemActionPerformed
private void btnSuaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnSuaMouseClicked
// TODO add your handling code here:
int row = tbGianHang.getSelectedRow();
if (row >= 0) {
String id = tbGianHang.getValueAt(row, 0).toString();
GianHang data = new GianHang();
if (txtTenGianHang.getText().equals("")) {
JOptionPane.showMessageDialog(this, "Tên gian hàng gian hàng trống!");
return;
}
data.setTenGianHang(txtTenGianHang.getText());
data.setMoTa(txtMoTa.getText());
data.setMaGianHang(id);
if (obj.updateData(data)) {
binData("", "", "");
JOptionPane.showMessageDialog(this, "Sửa thành công!");
} else {
JOptionPane.showMessageDialog(this, "Sửa không thành công!");
}
clearText();
} else {
JOptionPane.showMessageDialog(this, "Chọn bạn ghi cần sửa trước");
}
}//GEN-LAST:event_btnSuaMouseClicked
private void btnXoaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnXoaMouseClicked
// TODO add your handling code here:
int row = tbGianHang.getSelectedRow();
if (row >= 0) {
String id = tbGianHang.getValueAt(row, 0).toString();
int dialogResult = JOptionPane.showConfirmDialog(this, "Bạn muốn xóa bản ghi?", "Cảnh báo", JOptionPane.YES_NO_OPTION);
if (dialogResult == JOptionPane.YES_OPTION) {
if (obj.deleteData(id)) {
binData("", "", "");
JOptionPane.showMessageDialog(this, "Xóa thành công!");
} else {
JOptionPane.showMessageDialog(this, "Xóa không thành công!");
}
}
clearText();
} else {
JOptionPane.showMessageDialog(this, "Chọn bạn ghi cần xóa trước");
}
}//GEN-LAST:event_btnXoaMouseClicked
private void btnTimKiemMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnTimKiemMouseClicked
// TODO add your handling code here:
String w = "tenGianHang like N'" + "%" + txtTimKiem.getText() + "%" + "'";
// ArrayList<GianHang> lst = new ArrayList<>();
// lst = obj.getAll("", w, "");
binData("", w, "");
// if(!lst.isEmpty()){
// tbGianHang.rowAtPoint(0);
// }
}//GEN-LAST:event_btnTimKiemMouseClicked
private void btnLamTuoiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLamTuoiActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_btnLamTuoiActionPerformed
private void btnTimKiemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTimKiemActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_btnTimKiemActionPerformed
private void btnXuatMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnXuatMouseClicked
// TODO add your handling code here:
}//GEN-LAST:event_btnXuatMouseClicked
private void btnXuatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnXuatActionPerformed
// TODO add your handling code here:
JFileChooser fc = new JFileChooser();
int option = fc.showSaveDialog(this);
if (option == JFileChooser.APPROVE_OPTION) {
String filename = fc.getSelectedFile().getName();
String path = fc.getSelectedFile().getParentFile().getPath();
int len = filename.length();
String ext = "";
String file = "";
if (len > 4) {
ext = filename.substring(len - 4, len);
}
if (ext.equals(".xls")) {
file = path + "\\" + filename;
} else {
file = path + "\\" + filename + ".xls";
}
try {
toExcel(tbGianHang, new File(file));
JOptionPane.showMessageDialog(this, "Xuất file thành công!");
} catch (IOException ex) {
Logger.getLogger(frmSach.class
.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(this, "Xuất file không thành công!");
}
}
}//GEN-LAST:event_btnXuatActionPerformed
public static void toExcel(JTable table, File file) throws IOException {
String sheetName = "Sheet1";//name of sheet
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet(sheetName);
TableModel model = table.getModel();
//Get colum name
HSSFRow row = sheet.createRow(0);
for (int i = 0; i < model.getColumnCount(); i++) {
HSSFCell cell = row.createCell(i);
cell.setCellValue(model.getColumnName(i).toString());
}
//iterating r number of rows
for (int r = 1; r <= model.getRowCount(); r++) {
row = sheet.createRow(r);
//iterating c number of columns
for (int c = 0; c < model.getColumnCount(); c++) {
HSSFCell cell = row.createCell(c);
cell.setCellValue(model.getValueAt(r - 1, c).toString());
}
}
FileOutputStream fileOut = new FileOutputStream(file);
//write this workbook to an Outputstream.
wb.write(fileOut);
fileOut.flush();
fileOut.close();
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(frmGianHang.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(frmGianHang.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(frmGianHang.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(frmGianHang.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new frmGianHang().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnLamTuoi;
private javax.swing.JButton btnSua;
private javax.swing.JButton btnThem;
private javax.swing.JButton btnTimKiem;
private javax.swing.JButton btnXoa;
private javax.swing.JButton btnXuat;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPopupMenu jPopupMenu1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTable tbGianHang;
private javax.swing.JTextField txtMaGianHang;
private javax.swing.JTextArea txtMoTa;
private javax.swing.JTextField txtTenGianHang;
private javax.swing.JTextField txtTimKiem;
// End of variables declaration//GEN-END:variables
}
| 46.556106 | 174 | 0.634778 |
33da96d814fd0a80b36b3f83bd7c4fc3cb522fb4 | 611 | // Time complexity - O(N^(0.5))
import java.util.*;
import java.math.*;
public class PrimeFactorization {
public static void primeFactorization(int n) {
for (int i = 2; i <= (int) Math.sqrt(n); i++) {
int count = 0;
while (n % i == 0) {
count++;
n = n / i;
}
System.out.print(i + "^" + count + "X");
}
if (n != 1) {
System.out.print(n + "^" + "1");
}
}
public static void main(String args[]) {
primeFactorization(66);
// Output - 2^1X3^1X11^1
}
}
| 19.709677 | 55 | 0.435352 |
86ecd79c0573d674078c9d18fc7c157edbcefb9f | 8,128 | package com.jquestrade;
/** Represents information about a symbol/ticker */
public class SymbolInfo {
private SymbolInfo() {}
private String symbol;
private int symbolId;
private double prevDayClosePrice;
private double highPrice52;
private double lowPrice52;
private long averageVol3Months;
private long averageVol20Days;
private long outstandingShares;
private double eps;
private double pe;
private double dividend;
private double yield;
private String exDate;
private long marketCap;
private int tradeUnit;
private String optionType;
private String optionDurationType;
private String optionRoot;
private Object optionContractDeliverables;
private String optionExerciseType;
private String listingExchange;
private String description;
private String securityType;
private String optionExpiryDate;
private String dividendDate;
private String optionStrikePrice;
private boolean isTradable;
private boolean isQuotable;
private boolean hasOptions;
private String currency;
private MinTick[] minTicks;
/** Represents a min tick. */
public class MinTick {
private MinTick() {}
private double pivot;
private double minTick;
/** Returns the beginning of the interval for a given minimum price increment.
* @return The pivot.
*/
public double getPivot() {
return pivot;
}
/** Returns the minimum price increment.
* @return The min Tick.
*/
public double getMinTick() {
return minTick;
}
}
private String industrySector;
private String industryGroup;
private String industrySubgroup;
/** Returns the stock symbol/ticker.
* @return The stock symbol/ticker.
*/
public String getSymbol() {
return symbol;
}
/** Returns the internal unique symbol identifier.
* @return The internal unique symbol identifier.
*/
public int getSymbolId() {
return symbolId;
}
/** Returns the symbol description (e.g., "Microsoft Corp.").
* @return The symbol description.
*/
public String getDescription() {
return description;
}
/** Returns the symbol security type (Eg: "Stock")
* @return The symbol security type
* @see <a href="https://www.questrade.com/api/documentation/rest-operations/enumerations/enumerations#security-type">
* The Security Type section</a>
* for all possible values.
*/
public String getSecurityType() {
return securityType;
}
/** Returns the primary listing exchange of the symbol.
* @return The primary listing exchange.
* @see <a href="https://www.questrade.com/api/documentation/rest-operations/enumerations/enumerations#listing-exchange">
* The Listing Exchange section</a>
* for all possible values.
*/
public String getListingExchange() {
return listingExchange;
}
/** Returns whether a symbol is tradable on the platform.
* @return Whether a symbol is tradable on the platform.
*/
public boolean isTradable() {
return isTradable;
}
/** Returns whether a symbol has live market data.
* @return Whether a symbol has live market data.
*/
public boolean isQuotable() {
return isQuotable;
}
/** Returns the symbol currency (ISO format).
* @return The symbol currency.
*/
public String getCurrency() {
return currency;
}
/** Returns the closing trade price from the previous trading day.
* @return The closing trade price from the previous trading day.
*/
public double getPrevDayClosePrice() {
return prevDayClosePrice;
}
/** Returns the 52-week high price.
* @return The 52-week high price.
*/
public double getHighPrice52() {
return highPrice52;
}
/** Returns the 52-week low price.
* @return The 52-week low price.
*/
public double getLowPrice52() {
return lowPrice52;
}
/** Returns the average trading volume over trailing 3 months.
* @return The average trading volume over trailing 3 months.
*/
public long getAverageVol3Months() {
return averageVol3Months;
}
/** Returns the average trading volume over trailing 20 days.
* @return The average trading volume over trailing 20 days.
*/
public long getAverageVol20Days() {
return averageVol20Days;
}
/** Returns the total number of shares outstanding.
* @return The total number of shares outstanding.
*/
public long getOutstandingShares() {
return outstandingShares;
}
/** Returns the trailing 12-month earnings per share.
* @return The trailing 12-month earnings per share.
*/
public double getEps() {
return eps;
}
/** Returns the trailing 12-month price to earnings ratio.
* @return The trailing 12-month price to earnings ratio.
*/
public double getPe() {
return pe;
}
/** Returns the dividend amount per share.
* @return The dividend amount per share.
*/
public double getDividend() {
return dividend;
}
/** Returns the dividend yield (dividend / prevDayClosePrice).
* @return The dividend yield (dividend / prevDayClosePrice).
*/
public double getYield() {
return yield;
}
/** Returns the dividend ex-date.
* @return The dividend ex-date.
*/
public String getExDate() {
return exDate;
}
/** Returns the market capitalization (outstandingShares * prevDayClosePrice).
* @return The market capitalization.
*/
public long getMarketCap() {
return marketCap;
}
/** Returns the number of shares of a particular security that is used as the acceptable quantity for trading
* @return The trade unit.
*/
public int getTradeUnit() {
return tradeUnit;
}
/** Returns the option duration type (e.g., "Weekly").
* @return The option duration type.
* @see <a href="https://www.questrade.com/api/documentation/rest-operations/enumerations/enumerations#option-type">
* The Option Type section</a>
* for all possible values.
*/
public String getOptionType() {
return optionType;
}
/** Returns the option type (e.g., "Call").
* @return The option type
* @see <a href="https://www.questrade.com/api/documentation/rest-operations/enumerations/enumerations#option-duration-type">
* The Option Duration Type section</a>
* for all possible values.
*/
public String getOptionDurationType() {
return optionDurationType;
}
/** Returns the option root symbol (e.g., "MSFT").
* @return The option root symbol
*/
public String getOptionRoot() {
return optionRoot;
}
/** Returns the option contract deliverables. Unimplemented.
* @return the optionContractDeliverables
*/
@Deprecated
public Object getOptionContractDeliverables() {
return optionContractDeliverables;
}
/** Returns the option exercise style (e.g., "American").
* @return The option exercise style.
* @see <a href="https://www.questrade.com/api/documentation/rest-operations/enumerations/enumerations#option-exercise-type">
* The Option Exercise Type section</a>
* for all possible values.
*/
public String getOptionExerciseType() {
return optionExerciseType;
}
/** Returns the date on which the option expires.
* @return The date on which the option expires.
*/
public String getOptionExpiryDate() {
return optionExpiryDate;
}
/** Returns the dividend declaration date.
* @return The dividend declaration date.
*/
public String getDividendDate() {
return dividendDate;
}
/** Returns the option strike price
* @return the optionStrikePrice
*/
public String getOptionStrikePrice() {
return optionStrikePrice;
}
/** Returns whether the symbol is an underlying option.
* @return Whether the symbol is an underlying option.
*/
public boolean hasOptions() {
return hasOptions;
}
/** Returns the min ticks.
* @return The min ticks.
*/
public MinTick[] getMinTicks() {
return minTicks;
}
/** Returns the industry sector classification.
* @return The industry sector classification.
*/
public String getIndustrySector() {
return industrySector;
}
/** Returns the industry group classification.
* @return The industry group classification.
*/
public String getIndustryGroup() {
return industryGroup;
}
/** Returns the industry subgroup classification.
* @return The industry subgroup classification.
*/
public String getIndustrySubgroup() {
return industrySubgroup;
}
} | 25.4 | 126 | 0.721949 |
bd275bf1807f1d24c501bc2e3a5c77c6505a9a25 | 3,584 | /* @author yujie
*
*/
package ace.rest.customer;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import databeans.Customer;
import databeans.CustomerFund;
import databeans.CustomerFundView;
import databeans.ViewPortfolioWrapper;
import model.CustomerDAO;
import model.Model;
import model.viewDAO.CustomerFundDAO;
import util.Common;
@Path("/viewPortfolio")
public class ViewPortfolio {
@GET
public Response viewPortfolioAction(@Context HttpServletRequest request) throws ServletException {
Model model = new Model();
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
CustomerDAO customerDAO = model.getCustomerDAO();
CustomerFundDAO customerFundDAO = model.getCustomerFundDAO();
String err;
ViewPortfolioWrapper wrapper = new ViewPortfolioWrapper();
HttpSession session = request.getSession(false);
// if (session == null) {
// wrapper.setMessage("You must log in prior to making this request");
// return Response.status(200).entity(gson.toJson(wrapper).replaceAll("\"", "")).build();
// }
if (request.getSession().getAttribute("employee") == null
&& request.getSession().getAttribute("customer") == null) {
wrapper.setMessage("You must log in prior to making this request");
return Response.status(200).entity(gson.toJson(wrapper)).build();
}
if (session.getAttribute("customer") == null) {
wrapper.setMessage("I'm sorry you are not authorized to preform that action");
return Response.status(200).entity(gson.toJson(wrapper)).build();
}
try {
Customer customer = (Customer) session.getAttribute("customer");
customer = customerDAO.read(customer.getCustomerId());
CustomerFund[] allFunds = customerFundDAO.getCustomerFund(customer.getCustomerId());
if (allFunds == null || allFunds.length == 0) {
wrapper.setMessage("You don't have any funds at this time");
} else {
wrapper.Funds = new CustomerFundView[allFunds.length];
for (int i = 0; i < allFunds.length; i++) {
CustomerFundView view = new CustomerFundView();
view.setFundSymbol(allFunds[i].getFundTicker());
view.setFundPrice(Common.convertLongPriceToString(allFunds[i].getFundPrice()));
view.setShares(Common.convertLongShareToString(allFunds[i].getShares()));
wrapper.Funds[i] = view;
}
}
// long depositPendingAmount = transactionDAO.getPendingDepositAmountByCustomerId(customer.getCustomerId());
// Set amount with no decimal
String cash = Double.toString((double) customer.getCash() / 100);
wrapper.setCash(cash);
// return Response.status(200).entity(gson.toJson(wrapper)).build();
// Alternative output without quotes
return Response.status(200).entity(gson.toJson(wrapper).replaceAll("\"", "")).build();
} catch (Exception e) {
err = e.getMessage();
}
return Response.status(200).entity(gson.toJson(err)).build();
}
}
| 38.12766 | 120 | 0.640346 |
4a7c54f9ef1789123d25935cf992dddeb86dd6e3 | 1,580 | package packt.selenium.chap3_8_advancedwebdriver;
import org.junit.rules.MethodRule;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.Statement;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import java.io.FileOutputStream;
/**
* Created by Ripon on 11/15/2015.
*/
public class ScreenShotRule implements MethodRule {
private WebDriver driver;
public ScreenShotRule(WebDriver driver){
this.driver = driver;
}
public Statement apply(final Statement statement, final FrameworkMethod frameworkMethod, final Object object) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
try {
statement.evaluate();
} catch (Throwable throwable) {
captureScreenshot(frameworkMethod.getName());
throw throwable; // rethrow to allow the failure to be reported to JUnit
}
}
public void captureScreenshot(String fileName) {
try {
FileOutputStream out = new FileOutputStream("D:/test/" + fileName + ".png");
out.write(((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES));
out.close();
} catch (Exception e) {
//If the screenshot fails no need to interrupt the tests
}
}
};
}
} | 37.619048 | 116 | 0.59557 |
815f61315845cf5f8a6c953df2da5f530277a930 | 969 | /*
* Copyright 2014-2022 The Ideal Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file or at
* https://theideal.org/license/
*/
package ideal.development.actions;
import ideal.library.elements.*;
import ideal.library.reflections.*;
import ideal.runtime.elements.*;
import ideal.development.elements.*;
import ideal.development.values.*;
import ideal.development.declarations.*;
import javax.annotation.Nullable;
/**
* Implements access to static variables.
*/
public class static_variable extends variable_action {
public static_variable(variable_declaration the_declaration, type_flavor reference_flavor) {
super(the_declaration, reference_flavor, the_declaration);
}
@Override
protected variable_context get_context(entity_wrapper from_entity,
execution_context the_context) {
return action_utilities.get_context(the_context).static_context();
}
}
| 27.685714 | 94 | 0.779154 |
14db1ac652251809291c21262a816d26d646861d | 247 | package com.lara.annotations;
class T14
{
{
private int i=10;
}public static void main(String args[])
{
// private int Object=12;
// System.out.println(Object);
// System.out.println(i);
// System.out.println(Exception);
}
} | 11.761905 | 40 | 0.639676 |
44d58c14550f31848e0902bf769e24696485a935 | 3,015 | public class Hangman {
private final String[] asciiHangman = {"",
"___",
" | " + System.lineSeparator() + "_|_",
" __" + System.lineSeparator() + " | " + System.lineSeparator() + "_|_",
" __" + System.lineSeparator() + " |/ " + System.lineSeparator() + "_|_",
" __" + System.lineSeparator() + " |/ |" + System.lineSeparator() + "_|_",
" __" + System.lineSeparator() + " |/ |" + System.lineSeparator() + "_|_ O",
" __" + System.lineSeparator() + " |/ |" + System.lineSeparator() + "_|_ O"
+ System.lineSeparator() + " |",
" __" + System.lineSeparator() + " |/ |" + System.lineSeparator() + "_|_ O"
+ System.lineSeparator() + " /|\\",
" __" + System.lineSeparator() + " |/ |" + System.lineSeparator() + "_|_ O"
+ System.lineSeparator() + " /|\\" + System.lineSeparator() + " / \\"
};
private String word;
private int CurrentTurn = 0;
private boolean endOfGame = false;
private int nbPenalizations = 0;
private String[] blankLetters;
private int lettersFound = 0;
public void setWord(String word) {
this.word = word;
blankLetters = new String[word.length()];
for (int i = 0; i < blankLetters.length; i++) {
blankLetters[i] = "_";
}
}
public String wordToLine() {
StringBuilder lineFromWord = new StringBuilder();
for (int i = 0; i < blankLetters.length; i++) {
lineFromWord.append(blankLetters[i]);
if (i + 1 < blankLetters.length) {
lineFromWord.append(" ");
}
}
return lineFromWord.toString();
}
public boolean isEndOfGame() {
return endOfGame;
}
public LETTER_VALIDITY giveLetter(final String letter) {
CurrentTurn++;
boolean exists = word.contains(letter);
LETTER_VALIDITY validity = LETTER_VALIDITY.VALID_LETTER;
if (!exists || letter.length() > 1) {
nbPenalizations++;
validity = letter.length() > 1 ? LETTER_VALIDITY.NOT_A_LETTER : LETTER_VALIDITY.INVALID_LETTER;
} else {
char chr_letter = letter.charAt(0);
lettersFound += word.chars().filter(c -> c == chr_letter).count();
for (int i = 0; i < blankLetters.length; i++) {
if (word.charAt(i) == chr_letter) {
blankLetters[i] = letter;
}
}
}
if (nbPenalizations == 9 || lettersFound == word.length()) {
endOfGame = true;
}
return validity;
}
public int getTurn() {
return CurrentTurn;
}
public boolean isGameOver() {
boolean gameOver = false;
if (nbPenalizations == 9) {
gameOver = true;
}
return gameOver;
}
public String getAscii() {
return asciiHangman[nbPenalizations];
}
}
| 35.892857 | 107 | 0.51874 |
c96c5bc44d70794f8b621a904b43796e29ab5740 | 414 | package com.test;
import org.apache.spark.sql.SparkSession;
/**
* -Dspark.master=local
*/
public abstract class CommonSpark {
public static final SparkSession spark ;
static {
spark = SparkSession
.builder()
.appName("Java Spark SQL data sources example")
.config("spark.some.config.option", "some-value")
.getOrCreate();
}
}
| 23 | 65 | 0.589372 |
b63e8c30c6eadb464d376112858efb7c20fd30be | 1,482 | package zhushen.com.shejimoshi.leetcode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by Zhushen on 2018/11/21.
*/
public class minAreaRect {
public static void main(String[] args){
}
public int minAreaRect(int[][] points) {
int min = Integer.MAX_VALUE;
Map<Integer, List<Integer>> x2y = new HashMap<>(); //将x相同的点,其y放在一个列表中
//下面是x2y的初始化过程
for(int[] point : points) {
if(!x2y.containsKey(point[0])) {
List<Integer> list = new ArrayList<Integer>();
list.add(point[1]);
x2y.put(point[0], list);
}else {
x2y.get(point[0]).add(point[1]);
}
}
int len = points.length;
for(int i = 1; i < len; i++) {
for(int j = i - 1; j >=0; j--) {
if(points[i][0] == points[j][0] || points[i][1] == points[j][1]) {
continue;
}
int x1 = points[i][0];
int y1 = points[i][1];
int x2 = points[j][0];
int y2 = points[j][1];
if(x2y.get(x1).contains(y2) && x2y.get(x2).contains(y1)) { //如果能找到这样的长方形,计算其面积
min = Math.min(min, Math.abs(x1 - x2) * Math.abs(y1- y2));
}
}
}
if(min == Integer.MAX_VALUE) {
return 0;
}
return min;
}
}
| 29.64 | 94 | 0.468286 |
023536fcee114d6c8c49ac9d82904adf38fe0b40 | 6,734 | package com.tramchester.graph;
import com.netflix.governator.guice.lazy.LazySingleton;
import com.tramchester.config.GraphDBConfig;
import com.tramchester.config.TramchesterConfig;
import com.tramchester.domain.DataSourceInfo;
import com.tramchester.graph.databaseManagement.GraphDatabaseLifecycleManager;
import com.tramchester.graph.graphbuild.GraphLabel;
import com.tramchester.metrics.TimedTransaction;
import com.tramchester.repository.DataSourceRepository;
import org.neo4j.graphalgo.BasicEvaluationContext;
import org.neo4j.graphalgo.EvaluationContext;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.ResourceIterator;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.event.DatabaseEventContext;
import org.neo4j.graphdb.event.DatabaseEventListener;
import org.neo4j.graphdb.schema.Schema;
import org.neo4j.graphdb.traversal.TraversalDescription;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@LazySingleton
public class GraphDatabase implements DatabaseEventListener {
private static final Logger logger = LoggerFactory.getLogger(GraphDatabase.class);
private final DataSourceRepository transportData;
private final GraphDBConfig graphDBConfig;
private final GraphDatabaseLifecycleManager lifecycleManager;
private GraphDatabaseService databaseService;
@Inject
public GraphDatabase(TramchesterConfig configuration, DataSourceRepository transportData, GraphDatabaseLifecycleManager lifecycleManager) {
this.transportData = transportData;
this.graphDBConfig = configuration.getGraphDBConfig();
this.lifecycleManager = lifecycleManager;
}
@PostConstruct
public void start() {
logger.info("start");
Set<DataSourceInfo> dataSourceInfo = transportData.getDataSourceInfo();
final Path dbPath = graphDBConfig.getDbPath();
boolean fileExists = Files.exists(dbPath);
databaseService = lifecycleManager.startDatabase(dataSourceInfo, dbPath, fileExists);
logger.info("graph db started ");
}
@PreDestroy
public void stop() {
logger.info("stopping");
lifecycleManager.stopDatabase();
logger.info("stopped");
}
public boolean isCleanDB() {
return lifecycleManager.isCleanDB();
}
public Transaction beginTx() {
return databaseService.beginTx();
}
public Transaction beginTx(int timeout, TimeUnit timeUnit) {
return databaseService.beginTx(timeout, timeUnit);
}
public void createIndexs() {
try (TimedTransaction timed = new TimedTransaction(this, logger, "Create DB Constraints & indexes"))
{
Transaction tx = timed.transaction();
Schema schema = tx.schema();
schema.indexFor(GraphLabel.STATION).on(GraphPropertyKey.ROUTE_ID.getText()).create();
createUniqueIdConstraintFor(schema, GraphLabel.STATION, GraphPropertyKey.STATION_ID);
createUniqueIdConstraintFor(schema, GraphLabel.ROUTE_STATION, GraphPropertyKey.ROUTE_STATION_ID);
schema.indexFor(GraphLabel.ROUTE_STATION).on(GraphPropertyKey.STATION_ID.getText()).create();
schema.indexFor(GraphLabel.ROUTE_STATION).on(GraphPropertyKey.ROUTE_ID.getText()).create();
schema.indexFor(GraphLabel.PLATFORM).on(GraphPropertyKey.PLATFORM_ID.getText()).create();
timed.commit();
}
}
private void createUniqueIdConstraintFor(Schema schema, GraphLabel label, GraphPropertyKey property) {
schema.indexFor(label).on(property.getText()).create();
}
public void waitForIndexesReady(Schema schema) {
logger.info("Wait for indexs online");
schema.awaitIndexesOnline(5, TimeUnit.SECONDS);
schema.getIndexes().forEach(indexDefinition -> {
Schema.IndexState state = schema.getIndexState(indexDefinition);
if (indexDefinition.isNodeIndex()) {
logger.info(String.format("Node Index %s labels %s keys %s state %s",
indexDefinition.getName(),
indexDefinition.getLabels(), indexDefinition.getPropertyKeys(), state));
} else {
logger.info(String.format("Non-Node Index %s keys %s state %s",
indexDefinition.getName(), indexDefinition.getPropertyKeys(), state));
}
});
schema.getConstraints().forEach(definition -> logger.info(String.format("Constraint label %s keys %s type %s",
definition.getLabel(), definition.getPropertyKeys(), definition.getConstraintType()
)));
}
public Node createNode(Transaction tx, GraphLabel label) {
return tx.createNode(label);
}
public Node createNode(Transaction tx, Set<GraphLabel> labels) {
GraphLabel[] toApply = new GraphLabel[labels.size()];
labels.toArray(toApply);
return tx.createNode(toApply);
}
public Node findNode(Transaction tx, GraphLabel labels, String idField, String idValue) {
return tx.findNode(labels, idField, idValue);
}
public boolean isAvailable(long timeoutMillis) {
if (databaseService == null) {
return false;
}
return databaseService.isAvailable(timeoutMillis);
}
public ResourceIterator<Node> findNodes(Transaction tx, GraphLabel label) {
return tx.findNodes(label);
}
public TraversalDescription traversalDescription(Transaction tx) {
return tx.traversalDescription();
}
public EvaluationContext createContext(Transaction txn) {
return new BasicEvaluationContext(txn, databaseService);
}
@Override
public void databaseStart(DatabaseEventContext eventContext) {
logger.info("database event: start " + eventContext.getDatabaseName());
}
@Override
public void databaseShutdown(DatabaseEventContext eventContext) {
logger.warn("database event: shutdown " + eventContext.getDatabaseName());
}
@Override
public void databasePanic(DatabaseEventContext eventContext) {
logger.error("database event: panic " + eventContext.getDatabaseName());
}
public String getDbPath() {
return graphDBConfig.getDbPath().toAbsolutePath().toString();
}
}
| 38.48 | 144 | 0.693199 |
04b947a77c29535c84e206578c6866e4de36e4c6 | 7,108 | /*
* Copyright (c) 2007-2014 Concurrent, Inc. All Rights Reserved.
*
* Project and contact information: http://www.cascading.org/
*
* This file is part of the Cascading project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cascading.flow.hadoop.planner;
import java.io.IOException;
import cascading.flow.FlowException;
import cascading.flow.hadoop.HadoopFlowStep;
import cascading.flow.planner.BaseFlowStep;
import cascading.flow.planner.FlowStepJob;
import cascading.management.state.ClientState;
import cascading.stats.FlowNodeStats;
import cascading.stats.FlowStepStats;
import cascading.stats.hadoop.HadoopStepStats;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.JobStatus;
import org.apache.hadoop.mapred.RunningJob;
import org.apache.hadoop.mapred.TaskCompletionEvent;
import static cascading.flow.FlowProps.JOB_POLLING_INTERVAL;
import static cascading.stats.CascadingStats.STATS_STORE_INTERVAL;
/**
*
*/
public class HadoopFlowStepJob extends FlowStepJob<JobConf>
{
/** static field to capture errors in hadoop local mode */
private static Throwable localError;
/** Field currentConf */
private final JobConf currentConf;
/** Field jobClient */
private JobClient jobClient;
/** Field runningJob */
private RunningJob runningJob;
private static long getStoreInterval( JobConf jobConf )
{
return jobConf.getLong( STATS_STORE_INTERVAL, 60 * 1000 );
}
public static long getJobPollingInterval( JobConf jobConf )
{
return jobConf.getLong( JOB_POLLING_INTERVAL, 5000 );
}
public HadoopFlowStepJob( ClientState clientState, BaseFlowStep flowStep, JobConf currentConf )
{
super( clientState, flowStep, getJobPollingInterval( currentConf ), getStoreInterval( currentConf ) );
this.currentConf = currentConf;
if( flowStep.isDebugEnabled() )
flowStep.logDebug( "using polling interval: " + pollingInterval );
}
@Override
public JobConf getConfig()
{
return currentConf;
}
@Override
protected FlowStepStats createStepStats( ClientState clientState )
{
return new HadoopStepStats( flowStep, clientState )
{
@Override
public JobClient getJobClient()
{
return jobClient;
}
@Override
public RunningJob getJobStatusClient()
{
return runningJob;
}
};
}
protected void internalBlockOnStop() throws IOException
{
if( runningJob != null && !runningJob.isComplete() )
runningJob.killJob();
}
protected void internalNonBlockingStart() throws IOException
{
jobClient = new JobClient( currentConf );
runningJob = jobClient.submitJob( currentConf );
flowStep.logInfo( "submitted hadoop job: " + runningJob.getID() );
if( runningJob.getTrackingURL() != null )
flowStep.logInfo( "tracking url: " + runningJob.getTrackingURL() );
}
@Override
protected void markNodeRunningStatus( FlowNodeStats flowNodeStats )
{
try
{
if( runningJob == null )
return;
float progress;
boolean isMapper = flowNodeStats.getOrdinal() == 0;
if( isMapper )
progress = runningJob.mapProgress();
else
progress = runningJob.reduceProgress();
if( progress == 0.0F ) // not yet running, is only started
return;
if( progress != 1.0F )
{
flowNodeStats.markRunning();
return;
}
if( !flowNodeStats.isRunning() )
flowNodeStats.markRunning();
if( isMapper && runningJob.reduceProgress() > 0.0F )
{
flowNodeStats.markSuccessful();
return;
}
int jobState = runningJob.getJobState();
if( JobStatus.SUCCEEDED == jobState )
flowNodeStats.markSuccessful();
else if( JobStatus.FAILED == jobState )
flowNodeStats.markFailed( null ); // todo: find failure
}
catch( IOException exception )
{
flowStep.logError( "failed setting node status", throwable );
}
}
@Override
public boolean isSuccessful()
{
try
{
return super.isSuccessful();
}
catch( NullPointerException exception )
{
throw new FlowException( "Hadoop is not keeping a large enough job history, please increase the \'mapred.jobtracker.completeuserjobs.maximum\' property", exception );
}
}
protected boolean internalNonBlockingIsSuccessful() throws IOException
{
return runningJob != null && runningJob.isSuccessful();
}
@Override
protected boolean isRemoteExecution()
{
return !( (HadoopFlowStep) flowStep ).isHadoopLocalMode( getConfig() );
}
@Override
protected Throwable getThrowable()
{
return localError;
}
protected String internalJobId()
{
return runningJob.getJobID();
}
protected boolean internalNonBlockingIsComplete() throws IOException
{
return runningJob.isComplete();
}
protected void dumpDebugInfo()
{
try
{
if( runningJob == null )
return;
int jobState = runningJob.getJobState(); // may throw an NPE internally
flowStep.logWarn( "hadoop job " + runningJob.getID() + " state at " + JobStatus.getJobRunState( jobState ) );
flowStep.logWarn( "failure info: " + runningJob.getFailureInfo() );
TaskCompletionEvent[] events = runningJob.getTaskCompletionEvents( 0 );
flowStep.logWarn( "task completion events identify failed tasks" );
flowStep.logWarn( "task completion events count: " + events.length );
for( TaskCompletionEvent event : events )
flowStep.logWarn( "event = " + event );
}
catch( Throwable throwable )
{
flowStep.logError( "failed reading task completion events", throwable );
}
}
protected boolean internalIsStartedRunning()
{
if( runningJob == null )
return false;
try
{
return runningJob.mapProgress() > 0;
}
catch( IOException exception )
{
flowStep.logWarn( "unable to test for map progress", exception );
return false;
}
}
/**
* Internal method to report errors that happen on hadoop local mode. Hadoops local
* JobRunner does not give access to TaskReports, but we want to be able to capture
* the exception and not just print it to stderr. FlowMapper and FlowReducer use this method.
*
* @param throwable the throwable to be reported.
*/
public static void reportLocalError( Throwable throwable )
{
localError = throwable;
}
}
| 27.550388 | 172 | 0.681204 |
71bea24794ad9c043aee03e83a5550ec43161188 | 592 | package forms.translation;
public class ProgramTranslationForm {
private String displayName;
private String displayDescription;
public ProgramTranslationForm() {
this.displayName = "";
this.displayDescription = "";
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getDisplayDescription() {
return displayDescription;
}
public void setDisplayDescription(String displayDescription) {
this.displayDescription = displayDescription;
}
}
| 20.413793 | 64 | 0.739865 |
5b7482f1c9faaee7550c873799a3a12d7b39143a | 5,569 | /*******************************************************************************
* Copyright (c) 2005 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.model.simpleapi;
import org.eclipse.birt.report.model.activity.ActivityStack;
import org.eclipse.birt.report.model.api.GroupHandle;
import org.eclipse.birt.report.model.api.activity.SemanticException;
import org.eclipse.birt.report.model.api.simpleapi.IGroup;
import org.eclipse.birt.report.model.api.util.StringUtil;
import org.eclipse.birt.report.model.elements.interfaces.IGroupElementModel;
import org.eclipse.birt.report.model.elements.interfaces.IStyleModel;
public class Group extends DesignElement implements IGroup
{
public Group( GroupHandle handle )
{
super( handle );
}
public String getKeyExpr( )
{
return ( (GroupHandle) handle ).getKeyExpr( );
}
public void setKeyExpr( String expr ) throws SemanticException
{
setProperty( IGroupElementModel.KEY_EXPR_PROP, expr );
}
public String getName( )
{
return ( (GroupHandle) handle ).getName( );
}
public void setName( String name ) throws SemanticException
{
setProperty( IGroupElementModel.GROUP_NAME_PROP, StringUtil
.trimString( name ) );
}
public String getIntervalBase( )
{
return ( (GroupHandle) handle ).getIntervalBase( );
}
public void setIntervalBase( String intervalBase ) throws SemanticException
{
setProperty( IGroupElementModel.INTERVAL_BASE_PROP, intervalBase );
}
public String getInterval( )
{
return ( (GroupHandle) handle ).getInterval( );
}
public void setInterval( String interval ) throws SemanticException
{
setProperty( IGroupElementModel.INTERVAL_PROP, interval );
}
public double getIntervalRange( )
{
return ( (GroupHandle) handle ).getIntervalRange( );
}
public void setIntervalRange( double intervalRange )
throws SemanticException
{
setProperty( IGroupElementModel.INTERVAL_RANGE_PROP, Double
.valueOf( intervalRange ) );
}
public String getSortDirection( )
{
return ( (GroupHandle) handle ).getSortDirection( );
}
public void setSortDirection( String direction ) throws SemanticException
{
setProperty( IGroupElementModel.SORT_DIRECTION_PROP, direction );
}
public boolean hasHeader( )
{
return ( (GroupHandle) handle ).hasHeader( );
}
public boolean hasFooter( )
{
return ( (GroupHandle) handle ).hasFooter( );
}
public String getTocExpression( )
{
return ( (GroupHandle) handle ).getTocExpression( );
}
public void setTocExpression( String expression ) throws SemanticException
{
ActivityStack cmdStack = handle.getModule( ).getActivityStack( );
cmdStack.startNonUndoableTrans( null );
try
{
( (GroupHandle) handle ).setTocExpression( expression );
}
catch ( SemanticException e )
{
cmdStack.rollback( );
throw e;
}
cmdStack.commit( );
}
public String getSortType( )
{
return ( (GroupHandle) handle ).getSortType( );
}
public void setSortType( String sortType ) throws SemanticException
{
setProperty( IGroupElementModel.SORT_TYPE_PROP, sortType );
}
/**
* Returns hide detail.
*
* @return hide detail.
*/
public boolean getHideDetail( )
{
Boolean value = (Boolean) ( (GroupHandle) handle )
.getProperty( GroupHandle.HIDE_DETAIL_PROP );
if ( value == null )
return false;
return value.booleanValue( );
}
/**
* Sets hide detail
*
* @param hideDetail
* hide detail
* @throws SemanticException
* if the property is locked.
*/
public void setHideDetail( boolean hideDetail ) throws SemanticException
{
setProperty( IGroupElementModel.HIDE_DETAIL_PROP, Boolean
.valueOf( hideDetail ) );
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.report.model.api.simpleapi.IGroup#getPageBreakBefore()
*/
public String getPageBreakBefore( )
{
return ( (GroupHandle) handle ).getPageBreakBefore( );
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.report.model.api.simpleapi.IGroup#setPageBreakBefore
* (java.lang.String)
*/
public void setPageBreakBefore( String value ) throws SemanticException
{
setProperty( IStyleModel.PAGE_BREAK_BEFORE_PROP, value );
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.report.model.api.simpleapi.IGroup#getPageBreakAfter()
*/
public String getPageBreakAfter( )
{
return ( (GroupHandle) handle ).getPageBreakAfter( );
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.report.model.api.simpleapi.IGroup#setPageBreakAfter(
* java.lang.String)
*/
public void setPageBreakAfter( String value ) throws SemanticException
{
setProperty( IStyleModel.PAGE_BREAK_AFTER_PROP, value );
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.report.model.api.simpleapi.IGroup#getPageBreakInside()
*/
public String getPageBreakInside( )
{
return ( (GroupHandle) handle ).getPageBreakInside( );
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.report.model.api.simpleapi.IGroup#setPageBreakInside
* (java.lang.String)
*/
public void setPageBreakInside( String value ) throws SemanticException
{
setProperty( IStyleModel.PAGE_BREAK_INSIDE_PROP, value );
}
}
| 22.455645 | 81 | 0.696894 |
baf38744d13487126c1a3010e04020c9bd9c8542 | 1,948 | package colorsdatabase.about;
import colorsdatabase.colorpicker.ColorPickerController;
import colorsdatabase.utilities.Logger;
import java.awt.Desktop;
import java.net.URI;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.input.MouseEvent;
/**
* FXML Controller class
*
* @author Abdelrahman Bayoumi
*/
public class AboutController implements Initializable {
// ===== Helper Objects =====
private static final String CLASS_NAME = ColorPickerController.class.getName();
/**
* Initializes the controller class.
*
* @param url
* @param rb
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
}
@FXML
private void okAction(ActionEvent event) {
colorsdatabase.homepage.HomepageController.aboutDialog.close();
}
@FXML
private void mailAction(MouseEvent event) {
try {
Desktop desktop;
if (Desktop.isDesktopSupported()
&& (desktop = Desktop.getDesktop()).isSupported(Desktop.Action.MAIL)) {
URI mailto = new URI("mailto:[email protected]?");
desktop.mail(mailto);
} else {
// TODO fallback to some Runtime.exec(..) voodoo?
throw new RuntimeException("Desktop doesn't support mailto; mail is dead anyway;)");
}
} catch (Exception ex) {
Logger.log(Logger.Level.ERROR, "Exception[" + ex + "] in " + CLASS_NAME + ".mailAction()");
}
}
@FXML
private void githubAction(MouseEvent event) {
try {
Desktop.getDesktop().browse(new URI("https://github.com/AbdelrahmanBayoumi"));
} catch (Exception ex) {
Logger.log(Logger.Level.ERROR, "Exception[" + ex + "] in " + CLASS_NAME + ".githubAction()");
}
}
}
| 29.969231 | 105 | 0.62885 |
476f149ce90253504b67a9f1a88448926361c187 | 1,518 | package com.unidev.zulustorage;
import java.util.HashMap;
/**
* Storage metadata entry
*/
public class Metadata extends HashMap<String, Object> {
public static Metadata newMetadata() {return new Metadata(); }
public static Metadata newMetadata(String id) {return new Metadata()._id(id);}
/**
* Fetch metadata by key, if value is missing, null is returned
* @param key Metadata key
* @return value by key or null
*/
public <T> T opt(String key) {
if (!super.containsKey(key)) {
return null;
}
return (T) get(key);
}
/**
* Return default by key, if value is missing, defaultValue is returned
* @param key
* @param defaultValue
* @param <T>
* @return
*/
public <T> T opt(String key, T defaultValue) {
if (!super.containsKey(key)) {
return defaultValue;
}
return (T) get(key);
}
public String link() {
return opt("link");
}
public String _id() {
return opt("_id");
}
public Metadata _id(String id) {
put("_id", id);
return this;
}
public Metadata link(String link) {
put("link", link);
return this;
}
public String get_id() {
return opt("_id");
}
public void set_id(String _id) {
put("_id", _id);
}
public String getLink() {
return opt("link");
}
public void setLink(String link) {
put("link", link);
}
}
| 19.714286 | 82 | 0.550066 |
43f5ab80623d7f71d390024cacdf339c53c93204 | 2,281 | package au.com.ds.ef;
import java.util.*;
/**
* User: andrey
* Date: 6/12/2013
* Time: 2:21 PM
*/
public final class Transition {
private static ThreadLocal<List<Transition>> transitions = new ThreadLocal<List<Transition>>();
private EventEnum event;
private StateEnum stateFrom;
private StateEnum stateTo;
private boolean isFinal;
protected Transition(EventEnum event, StateEnum stateTo, boolean isFinal) {
this.event = event;
this.stateTo = stateTo;
this.isFinal = isFinal;
register(this);
}
private static void register(Transition transition) {
List<Transition> list = transitions.get();
if (list == null) {
list = new ArrayList<Transition>();
transitions.set(list);
}
list.add(transition);
}
protected EventEnum getEvent() {
return event;
}
protected void setStateFrom(StateEnum stateFrom) {
this.stateFrom = stateFrom;
}
protected StateEnum getStateFrom() {
return stateFrom;
}
protected StateEnum getStateTo() {
return stateTo;
}
protected boolean isFinal() {
return isFinal;
}
public Transition transit(Transition... transitions) {
for (Transition transition : transitions) {
transition.setStateFrom(stateTo);
}
return this;
}
@Override
public String toString() {
return "Transition{" +
"event=" + event +
", stateFrom=" + stateFrom +
", stateTo=" + stateTo +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Transition that = (Transition) o;
if (!event.equals(that.event)) return false;
if (!stateFrom.equals(that.stateFrom)) return false;
return true;
}
@Override
public int hashCode() {
int result = event.hashCode();
result = 31 * result + stateFrom.hashCode();
return result;
}
protected static List<Transition> consumeTransitions() {
List<Transition> ts = transitions.get();
transitions.remove();
return ts;
}
}
| 23.515464 | 99 | 0.587462 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.