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
|
---|---|---|---|---|---|
ad8edb6f3ff5e3c7eaf3900b03412e503ade4693 | 731 | package com.tz.film.film.service;
/**
*
* 项目名称:filmSystem
* 类名称:FilmService
* 类描述: 影片列表Service
* 创建人:edwarder
* 创建时间:2017年10月15日 下午1:50:51
*
*/
import java.util.List;
import com.tz.film.film.entity.Film;
import com.tz.film.film.entity.PageBean;
import com.tz.film.film.vo.FilmVo;
public interface FilmService{
//保存影片信息
public String saveFilm(Film film);
//根据条件查询列表
public List<Film> queryFilmListByCondition(FilmVo filmVo);
//根据id查询影片信息
public Film queryFilmByPrimaryKey(Integer id);
//更新影片信息
public String updateFilm(Film film);
//批量删除
public String deleteFilms(String ids);
//分页查询列表
public PageBean<Film> queryFilmByCondition(Integer currentPage,Integer size,FilmVo filmVo);
}
| 19.756757 | 92 | 0.730506 |
96dc0a21dc8ebc79ee5e294324135f73122c6061 | 418 | package gov.loc.repository.bagit.hash;
import gov.loc.repository.bagit.exceptions.UnsupportedAlgorithmException;
/**
* Implement this interface if you need to be able to use other algorithms than the {@link StandardSupportedAlgorithms}
*/
public interface BagitAlgorithmNameToSupportedAlgorithmMapping {
SupportedAlgorithm getSupportedAlgorithm(String bagitAlgorithmName) throws UnsupportedAlgorithmException;
}
| 38 | 119 | 0.844498 |
2282674c6cfe998e449c0215aa9c9af2d0286d3d | 1,283 | package com.andyadc.ssm.persistence.entity;
import com.andyadc.ssm.persistence.common.BaseEntity;
import java.time.LocalDateTime;
public class Demo extends BaseEntity {
private static final long serialVersionUID = 1L;
private Long id;
private String name;
private int type;
private int status;
private Integer version;
private LocalDateTime createTime;
private LocalDateTime updateTime;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
public LocalDateTime getCreateTime() {
return createTime;
}
public void setCreateTime(LocalDateTime createTime) {
this.createTime = createTime;
}
public LocalDateTime getUpdateTime() {
return updateTime;
}
public void setUpdateTime(LocalDateTime updateTime) {
this.updateTime = updateTime;
}
}
| 15.839506 | 54 | 0.71629 |
00b4ee7bebc6cb554917c284d87cbeb000b64b96 | 1,239 | package com.github.privilege.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.privilege.bean.SysRole;
import com.github.privilege.bean.SysUser;
import com.github.privilege.bean.vo.RoleVO;
import com.github.privilege.bean.vo.SysUserVO;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface ISysRoleDao extends BaseMapper<SysRole> {
/**
* 查询角色分页
*/
List<SysRole> getRolePage(Page page,@Param("ew") RoleVO roleVO);
/**
* 查询角色信息
*/
List<SysRole> getRoleListAll();
/**
* 根据用户id查询角色
*/
List<SysRole> getRolesByUserId(Long userId);
/**
* 通过角色id查询角色
*/
SysRole getRoleById(Long roleId);
/**
* 批量删除
*/
int deleteRoleBatch(Long roleIds);
/**
* 根据角色id该角色有哪些用户
*/
List<SysUser> getUserRoleById(Page page,@Param("ew") SysUserVO userVO);
/**
* 通过角色id查询该角色未拥有的用户
*/
List<SysUser> getUserUNRoleById(Page page ,@Param("ew") SysUserVO userVO);
/**
* 取消授权
*/
int cancelAuthorization(Long roleId);
/**
* 批量取消授权
*/
int cancelAuthorizationAll(Long roleIds);
}
| 20.65 | 78 | 0.65456 |
05533ea7cc87a4212c46b07f2f47fc549c8511a0 | 7,376 | package org.nextime.ion.framework.business.impl;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import org.exolab.castor.jdo.Database;
import org.exolab.castor.jdo.OQLQuery;
import org.exolab.castor.jdo.Persistent;
import org.exolab.castor.jdo.QueryResults;
import org.exolab.castor.mapping.AccessMode;
import org.nextime.ion.framework.business.Group;
import org.nextime.ion.framework.business.PublicationVersion;
import org.nextime.ion.framework.business.User;
import org.nextime.ion.framework.event.WcmEvent;
import org.nextime.ion.framework.event.WcmListener;
import org.nextime.ion.framework.logger.Logger;
import org.nextime.ion.framework.mapping.Mapping;
import org.nextime.ion.framework.mapping.MappingException;
/**
* Une implementation de User
*
* @author gbort
* @version 1.0
*/
public class UserImpl extends User implements Persistent, Comparable {
private static Vector _listeners = new Vector();
public static void addListener(WcmListener listener) {
_listeners.add(listener);
}
public static void removeListener(WcmListener listener) {
_listeners.remove(listener);
}
private Vector _groups;
private String _login;
private Hashtable _metaData;
private String _password;
// pour que la classe soit constructible par castor
public UserImpl() {
_password = "";
_metaData = new Hashtable();
_groups = new Vector();
}
public void addGroup(Group group) {
if (!_groups.contains(group)) {
_groups.add(group);
group.addUser(this);
}
}
// comparer : par ordre alphabetique du login
public int compareTo(Object o) {
try {
UserImpl u = (UserImpl) o;
return u.getLogin().compareTo(getLogin());
} catch (Exception e) {
return -1;
}
}
public boolean equals(Object o) {
try {
return ((UserImpl) o).getLogin().equals(getLogin());
} catch (Exception e) {
return false;
}
}
public Vector getGroups() {
return _groups;
}
public String[] getGroupsIds() {
String[] groups = new String[_groups.size()];
for (int i = 0; i < _groups.size(); i++) {
groups[i] = ((Group) _groups.get(i)).getId();
}
return groups;
}
public String getLogin() {
return _login;
}
public Object getMetaData(String key) {
return _metaData.get(key);
}
public Hashtable getMetaData() {
return _metaData;
}
public byte[] getMetaDataBytes() throws Exception {
ByteArrayOutputStream os = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(_metaData);
byte[] result = os.toByteArray();
os.close();
return result;
}
public Vector getMetaDataFields() {
Enumeration keys = _metaData.keys();
Vector v = new Vector();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
v.add(new DataField(key + "", _metaData.get(key) + ""));
}
return v;
}
public String getPassword() {
return _password;
}
public boolean isInGroup(Group group) {
for (int i = 0; i < _groups.size(); i++) {
if (_groups.get(i).equals(group)) {
return true;
}
}
return false;
}
public void jdoAfterCreate() {
WcmEvent event = new WcmEvent(this, getLogin());
for (int i = 0; i < _listeners.size(); i++) {
((WcmListener) _listeners.get(i)).objectCreated(event);
}
}
public void jdoAfterRemove() {
WcmEvent event = new WcmEvent(this, getLogin());
for (int i = 0; i < _listeners.size(); i++) {
((WcmListener) _listeners.get(i)).objectDeleted(event);
}
}
public void jdoBeforeCreate(Database db) {
}
public void jdoBeforeRemove() {
}
@Override
public Class jdoLoad(AccessMode am) throws Exception {
return null;
}
public Class jdoLoad(short accessMode) {
return null;
}
public void jdoPersistent(Database db) {
}
public void jdoStore(boolean modified) {
if (modified) {
WcmEvent event = new WcmEvent(this, getLogin());
for (int i = 0; i < _listeners.size(); i++) {
((WcmListener) _listeners.get(i)).objectModified(event);
}
}
}
public void jdoTransient() {
}
public void jdoUpdate() {
}
public Vector listGroups() {
return (Vector) _groups.clone();
}
public Vector listPublications() {
Vector v = new Vector();
try {
OQLQuery oql
= Mapping.getInstance().getDb().getOQLQuery(
"SELECT p FROM org.nextime.ion.framework.business.impl.PublicationVersionImpl p WHERE author = $1");
oql.bind(this);
QueryResults results = oql.execute();
while (results.hasMore()) {
PublicationVersion s = (PublicationVersion) results.next();
v.add(s);
}
} catch (Exception e) {
Logger.getInstance().error(
"erreur lors du list des publication de l'auteur",
this,
e);
return v;
}
return v;
}
public void removeGroup(Group group) {
_groups.remove(group);
}
public void removeMetaData(String key) {
_metaData.remove(key);
}
public void resetGroups() {
for (int i = 0; i < _groups.size(); i++) {
Group g = (Group) _groups.get(i);
g.removeUser(this);
}
_groups = new Vector();
}
public void setGroups(Vector v) {
_groups = v;
}
public void setLogin(String value) {
_login = value;
}
public void setMetaData(String key, Object value) throws MappingException {
if (!(value instanceof java.io.Serializable)) {
throw new MappingException(
value.getClass()
+ " n'implemente pas l'interface java.io.Serializable");
}
_metaData.put(key, value);
}
public void setMetaData(Hashtable ht) {
_metaData = ht;
}
public void setMetaDataBytes(byte[] value) throws Exception {
try {
ByteArrayInputStream is = new ByteArrayInputStream(value);
ObjectInputStream ois = new ObjectInputStream(is);
Object o = ois.readObject();
is.close();
_metaData = (Hashtable) o;
} catch (NullPointerException e) {
_metaData = new Hashtable();
}
}
public void setPassword(String value) {
_password = value;
}
public String toString() {
return "type[USER] properties["
+ _login
+ ";"
+ _password
+ "] metaData"
+ _metaData
+ " groups"
+ _groups;
}
}
| 27.018315 | 128 | 0.576735 |
f81feaa83eeab59eb1ca3ed21a1d2581721c1b8b | 31,465 | /*
* GridGain Community Edition Licensing
* Copyright 2019 GridGain Systems, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License") modified with Commons Clause
* Restriction; 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.
*
* Commons Clause Restriction
*
* The Software is provided to you by the Licensor under the License, as defined below, subject to
* the following condition.
*
* Without limiting other conditions in the License, the grant of rights under the License will not
* include, and the License does not grant to you, the right to Sell the Software.
* For purposes of the foregoing, “Sell” means practicing any or all of the rights granted to you
* under the License to provide to third parties, for a fee or other consideration (including without
* limitation fees for hosting or consulting/ support services related to the Software), a product or
* service whose value derives, entirely or substantially, from the functionality of the Software.
* Any license notice or attribution required by the License must also include this Commons Clause
* License Condition notice.
*
* For purposes of the clause above, the “Licensor” is Copyright 2019 GridGain Systems, Inc.,
* the “License” is the Apache License, Version 2.0, and the Software is the GridGain Community
* Edition software provided with this notice.
*/
package org.apache.ignite.internal.managers.encryption;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.IgniteException;
import org.apache.ignite.cluster.ClusterNode;
import org.apache.ignite.spi.encryption.EncryptionSpi;
import org.apache.ignite.internal.GridKernalContext;
import org.apache.ignite.internal.IgniteInternalFuture;
import org.apache.ignite.internal.managers.GridManagerAdapter;
import org.apache.ignite.internal.managers.communication.GridMessageListener;
import org.apache.ignite.internal.managers.eventstorage.DiscoveryEventListener;
import org.apache.ignite.internal.processors.cache.CacheGroupDescriptor;
import org.apache.ignite.internal.processors.cache.GridCacheProcessor;
import org.apache.ignite.internal.processors.cache.persistence.metastorage.MetastorageLifecycleListener;
import org.apache.ignite.internal.processors.cache.persistence.metastorage.ReadOnlyMetastorage;
import org.apache.ignite.internal.processors.cache.persistence.metastorage.ReadWriteMetastorage;
import org.apache.ignite.internal.processors.cluster.IgniteChangeGlobalStateSupport;
import org.apache.ignite.internal.util.future.GridFinishedFuture;
import org.apache.ignite.internal.util.future.GridFutureAdapter;
import org.apache.ignite.internal.util.lang.GridPlainClosure;
import org.apache.ignite.internal.util.typedef.F;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.lang.IgniteFuture;
import org.apache.ignite.lang.IgniteFutureCancelledException;
import org.apache.ignite.lang.IgnitePredicate;
import org.apache.ignite.lang.IgniteProductVersion;
import org.apache.ignite.lang.IgniteUuid;
import org.apache.ignite.spi.IgniteNodeValidationResult;
import org.apache.ignite.spi.discovery.DiscoveryDataBag;
import org.apache.ignite.spi.discovery.DiscoveryDataBag.GridDiscoveryData;
import org.apache.ignite.spi.discovery.DiscoveryDataBag.JoiningNodeDiscoveryData;
import org.apache.ignite.spi.discovery.DiscoverySpi;
import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi;
import org.jetbrains.annotations.Nullable;
import static org.apache.ignite.events.EventType.EVT_NODE_FAILED;
import static org.apache.ignite.events.EventType.EVT_NODE_LEFT;
import static org.apache.ignite.internal.GridComponent.DiscoveryDataExchangeType.ENCRYPTION_MGR;
import static org.apache.ignite.internal.GridTopic.TOPIC_GEN_ENC_KEY;
import static org.apache.ignite.internal.IgniteNodeAttributes.ATTR_ENCRYPTION_MASTER_KEY_DIGEST;
import static org.apache.ignite.internal.managers.communication.GridIoPolicy.SYSTEM_POOL;
/**
* Manages cache keys and {@code EncryptionSpi} instances.
*
* NOTE: Following protocol applied to statically configured caches.
* For dynamically created caches key generated in request creation.
*
* Group keys generation protocol:
*
* <ul>
* <li>Joining node:
* <ul>
* <li>1. Collects and send all stored group keys to coordinator.</li>
* <li>2. Generate(but doesn't store locally!) and send keys for all statically configured groups in case the not presented in metastore.</li>
* <li>3. Store all keys received from coordinator to local store.</li>
* </ul>
* </li>
* <li>Coordinator:
* <ul>
* <li>1. Checks master key digest are equal to local. If not join is rejected.</li>
* <li>2. Checks all stored keys from joining node are equal to stored keys. If not join is rejected.</li>
* <li>3. Collects all stored keys and sends it to joining node.</li>
* </ul>
* </li>
* <li>All nodes:
* <ul>
* <li>1. If new key for group doesn't exists locally it added to local store.</li>
* <li>2. If new key for group exists locally, then received key skipped.</li>
* </ul>
* </li>
* </ul>
*
* @see GridCacheProcessor#generateEncryptionKeysAndStartCacheAfter(int, GridPlainClosure)
*/
public class GridEncryptionManager extends GridManagerAdapter<EncryptionSpi> implements MetastorageLifecycleListener,
IgniteChangeGlobalStateSupport {
/**
* Cache encryption introduced in this Ignite version.
*/
private static final IgniteProductVersion CACHE_ENCRYPTION_SINCE = IgniteProductVersion.fromString("2.7.0");
/** Synchronization mutex. */
private final Object metaStorageMux = new Object();
/** Synchronization mutex for an generate encryption keys operations. */
private final Object genEcnKeyMux = new Object();
/** Disconnected flag. */
private volatile boolean disconnected;
/** Stopped flag. */
private volatile boolean stopped;
/** Flag to enable/disable write to metastore on cluster state change. */
private volatile boolean writeToMetaStoreEnabled;
/** Prefix for a encryption group key in meta store. */
public static final String ENCRYPTION_KEY_PREFIX = "grp-encryption-key-";
/** Encryption key predicate for meta store. */
private static final IgnitePredicate<String> ENCRYPTION_KEY_PREFIX_PRED =
(IgnitePredicate<String>)key -> key.startsWith(ENCRYPTION_KEY_PREFIX);
/** Group encryption keys. */
private final ConcurrentHashMap<Integer, Serializable> grpEncKeys = new ConcurrentHashMap<>();
/** Pending generate encryption key futures. */
private ConcurrentMap<IgniteUuid, GenerateEncryptionKeyFuture> genEncKeyFuts = new ConcurrentHashMap<>();
/** Metastorage. */
private volatile ReadWriteMetastorage metaStorage;
/** I/O message listener. */
private GridMessageListener ioLsnr;
/** System discovery message listener. */
private DiscoveryEventListener discoLsnr;
/**
* @param ctx Kernel context.
*/
public GridEncryptionManager(GridKernalContext ctx) {
super(ctx, ctx.config().getEncryptionSpi());
ctx.internalSubscriptionProcessor().registerMetastorageListener(this);
}
/** {@inheritDoc} */
@Override public void start() throws IgniteCheckedException {
startSpi();
if (getSpi().masterKeyDigest() != null)
ctx.addNodeAttribute(ATTR_ENCRYPTION_MASTER_KEY_DIGEST, getSpi().masterKeyDigest());
ctx.event().addDiscoveryEventListener(discoLsnr = (evt, discoCache) -> {
UUID leftNodeId = evt.eventNode().id();
synchronized (genEcnKeyMux) {
Iterator<Map.Entry<IgniteUuid, GenerateEncryptionKeyFuture>> futsIter =
genEncKeyFuts.entrySet().iterator();
while (futsIter.hasNext()) {
GenerateEncryptionKeyFuture fut = futsIter.next().getValue();
if (!F.eq(leftNodeId, fut.nodeId()))
return;
try {
futsIter.remove();
sendGenerateEncryptionKeyRequest(fut);
genEncKeyFuts.put(fut.id(), fut);
}
catch (IgniteCheckedException e) {
fut.onDone(null, e);
}
}
}
}, EVT_NODE_LEFT, EVT_NODE_FAILED);
ctx.io().addMessageListener(TOPIC_GEN_ENC_KEY, ioLsnr = (nodeId, msg, plc) -> {
synchronized (genEcnKeyMux) {
if (msg instanceof GenerateEncryptionKeyRequest) {
GenerateEncryptionKeyRequest req = (GenerateEncryptionKeyRequest)msg;
assert req.keyCount() != 0;
List<byte[]> encKeys = new ArrayList<>(req.keyCount());
for (int i = 0; i < req.keyCount(); i++)
encKeys.add(getSpi().encryptKey(getSpi().create()));
try {
ctx.io().sendToGridTopic(nodeId, TOPIC_GEN_ENC_KEY,
new GenerateEncryptionKeyResponse(req.id(), encKeys), SYSTEM_POOL);
}
catch (IgniteCheckedException e) {
U.error(log, "Unable to send generate key response[nodeId=" + nodeId + "]");
}
}
else {
GenerateEncryptionKeyResponse resp = (GenerateEncryptionKeyResponse)msg;
GenerateEncryptionKeyFuture fut = genEncKeyFuts.get(resp.requestId());
if (fut != null)
fut.onDone(resp.encryptionKeys(), null);
else
U.warn(log, "Response received for a unknown request.[reqId=" + resp.requestId() + "]");
}
}
});
}
/** {@inheritDoc} */
@Override public void stop(boolean cancel) throws IgniteCheckedException {
stopSpi();
}
/** {@inheritDoc} */
@Override protected void onKernalStart0() throws IgniteCheckedException {
// No-op.
}
/** {@inheritDoc} */
@Override protected void onKernalStop0(boolean cancel) {
synchronized (genEcnKeyMux) {
stopped = true;
if (ioLsnr != null)
ctx.io().removeMessageListener(TOPIC_GEN_ENC_KEY, ioLsnr);
if (discoLsnr != null)
ctx.event().removeDiscoveryEventListener(discoLsnr, EVT_NODE_LEFT, EVT_NODE_FAILED);
cancelFutures("Kernal stopped.");
}
}
/** {@inheritDoc} */
@Override public void onDisconnected(IgniteFuture<?> reconnectFut) {
synchronized (genEcnKeyMux) {
assert !disconnected;
disconnected = true;
cancelFutures("Client node was disconnected from topology (operation result is unknown).");
}
}
/** {@inheritDoc} */
@Override public IgniteInternalFuture<?> onReconnected(boolean clusterRestarted) {
synchronized (genEcnKeyMux) {
assert disconnected;
disconnected = false;
return null;
}
}
/**
* Callback for local join.
*/
public void onLocalJoin() {
if (notCoordinator())
return;
//We can't store keys before node join to cluster(on statically configured cache registration).
//Because, keys should be received from cluster.
//Otherwise, we would generate different keys on each started node.
//So, after starting, coordinator saves locally newly generated encryption keys.
//And sends that keys to every joining node.
synchronized (metaStorageMux) {
//Keys read from meta storage.
HashMap<Integer, byte[]> knownEncKeys = knownEncryptionKeys();
//Generated(not saved!) keys for a new caches.
//Configured statically in config, but doesn't stored on the disk.
HashMap<Integer, byte[]> newEncKeys =
newEncryptionKeys(knownEncKeys == null ? Collections.EMPTY_SET : knownEncKeys.keySet());
if (newEncKeys == null)
return;
//We can store keys to the disk, because we are on a coordinator.
for (Map.Entry<Integer, byte[]> entry : newEncKeys.entrySet()) {
groupKey(entry.getKey(), entry.getValue());
U.quietAndInfo(log, "Added encryption key on local join [grpId=" + entry.getKey() + "]");
}
}
}
/** {@inheritDoc} */
@Nullable @Override public IgniteNodeValidationResult validateNode(ClusterNode node,
JoiningNodeDiscoveryData discoData) {
IgniteNodeValidationResult res = super.validateNode(node, discoData);
if (res != null)
return res;
if (node.isClient())
return null;
res = validateNode(node);
if (res != null)
return res;
if (!discoData.hasJoiningNodeData()) {
U.quietAndInfo(log, "Joining node doesn't have encryption data [node=" + node.id() + "]");
return null;
}
NodeEncryptionKeys nodeEncKeys = (NodeEncryptionKeys)discoData.joiningNodeData();
if (nodeEncKeys == null || F.isEmpty(nodeEncKeys.knownKeys)) {
U.quietAndInfo(log, "Joining node doesn't have stored group keys [node=" + node.id() + "]");
return null;
}
for (Map.Entry<Integer, byte[]> entry : nodeEncKeys.knownKeys.entrySet()) {
Serializable locEncKey = grpEncKeys.get(entry.getKey());
if (locEncKey == null)
continue;
Serializable rmtKey = getSpi().decryptKey(entry.getValue());
if (F.eq(locEncKey, rmtKey))
continue;
return new IgniteNodeValidationResult(ctx.localNodeId(),
"Cache key differs! Node join is rejected. [node=" + node.id() + ", grp=" + entry.getKey() + "]",
"Cache key differs! Node join is rejected.");
}
return null;
}
/** {@inheritDoc} */
@Nullable @Override public IgniteNodeValidationResult validateNode(ClusterNode node) {
IgniteNodeValidationResult res = super.validateNode(node);
if (res != null)
return res;
if (node.isClient())
return null;
byte[] lclMkDig = getSpi().masterKeyDigest();
byte[] rmtMkDig = node.attribute(ATTR_ENCRYPTION_MASTER_KEY_DIGEST);
if (Arrays.equals(lclMkDig, rmtMkDig))
return null;
return new IgniteNodeValidationResult(ctx.localNodeId(),
"Master key digest differs! Node join is rejected. [node=" + node.id() + "]",
"Master key digest differs! Node join is rejected.");
}
/** {@inheritDoc} */
@Override public void collectJoiningNodeData(DiscoveryDataBag dataBag) {
HashMap<Integer, byte[]> knownEncKeys = knownEncryptionKeys();
HashMap<Integer, byte[]> newKeys =
newEncryptionKeys(knownEncKeys == null ? Collections.EMPTY_SET : knownEncKeys.keySet());
if ((knownEncKeys == null && newKeys == null) || dataBag.isJoiningNodeClient())
return;
if (log.isInfoEnabled()) {
String knownGrps = F.isEmpty(knownEncKeys) ? null : F.concat(knownEncKeys.keySet(), ",");
if (knownGrps != null)
U.quietAndInfo(log, "Sending stored group keys to coordinator [grps=" + knownGrps + "]");
String newGrps = F.isEmpty(newKeys) ? null : F.concat(newKeys.keySet(), ",");
if (newGrps != null)
U.quietAndInfo(log, "Sending new group keys to coordinator [grps=" + newGrps + "]");
}
dataBag.addJoiningNodeData(ENCRYPTION_MGR.ordinal(), new NodeEncryptionKeys(knownEncKeys, newKeys));
}
/** {@inheritDoc} */
@Override public void onJoiningNodeDataReceived(JoiningNodeDiscoveryData data) {
NodeEncryptionKeys nodeEncryptionKeys = (NodeEncryptionKeys)data.joiningNodeData();
if (nodeEncryptionKeys == null || nodeEncryptionKeys.newKeys == null || ctx.clientNode())
return;
for (Map.Entry<Integer, byte[]> entry : nodeEncryptionKeys.newKeys.entrySet()) {
if (groupKey(entry.getKey()) == null) {
U.quietAndInfo(log, "Store group key received from joining node [node=" +
data.joiningNodeId() + ", grp=" + entry.getKey() + "]");
groupKey(entry.getKey(), entry.getValue());
}
else {
U.quietAndInfo(log, "Skip group key received from joining node. Already exists. [node=" +
data.joiningNodeId() + ", grp=" + entry.getKey() + "]");
}
}
}
/** {@inheritDoc} */
@Override public void collectGridNodeData(DiscoveryDataBag dataBag) {
if (dataBag.isJoiningNodeClient() || dataBag.commonDataCollectedFor(ENCRYPTION_MGR.ordinal()))
return;
HashMap<Integer, byte[]> knownEncKeys = knownEncryptionKeys();
HashMap<Integer, byte[]> newKeys =
newEncryptionKeys(knownEncKeys == null ? Collections.EMPTY_SET : knownEncKeys.keySet());
if (knownEncKeys == null)
knownEncKeys = newKeys;
else if (newKeys != null) {
for (Map.Entry<Integer, byte[]> entry : newKeys.entrySet()) {
byte[] old = knownEncKeys.putIfAbsent(entry.getKey(), entry.getValue());
assert old == null;
}
}
dataBag.addGridCommonData(ENCRYPTION_MGR.ordinal(), knownEncKeys);
}
/** {@inheritDoc} */
@Override public void onGridDataReceived(GridDiscoveryData data) {
Map<Integer, byte[]> encKeysFromCluster = (Map<Integer, byte[]>)data.commonData();
if (F.isEmpty(encKeysFromCluster))
return;
for (Map.Entry<Integer, byte[]> entry : encKeysFromCluster.entrySet()) {
if (groupKey(entry.getKey()) == null) {
U.quietAndInfo(log, "Store group key received from coordinator [grp=" + entry.getKey() + "]");
groupKey(entry.getKey(), entry.getValue());
}
else {
U.quietAndInfo(log, "Skip group key received from coordinator. Already exists. [grp=" +
entry.getKey() + "]");
}
}
}
/**
* Returns group encryption key.
*
* @param grpId Group id.
* @return Group encryption key.
*/
@Nullable public Serializable groupKey(int grpId) {
if (grpEncKeys.isEmpty())
return null;
return grpEncKeys.get(grpId);
}
/**
* Store group encryption key.
*
* @param grpId Group id.
* @param encGrpKey Encrypted group key.
*/
public void groupKey(int grpId, byte[] encGrpKey) {
assert !grpEncKeys.containsKey(grpId);
Serializable encKey = getSpi().decryptKey(encGrpKey);
synchronized (metaStorageMux) {
if (log.isDebugEnabled())
log.debug("Key added. [grp=" + grpId + "]");
grpEncKeys.put(grpId, encKey);
writeToMetaStore(grpId, encGrpKey);
}
}
/**
* Removes encryption key.
*
* @param grpId Group id.
*/
private void removeGroupKey(int grpId) {
synchronized (metaStorageMux) {
ctx.cache().context().database().checkpointReadLock();
try {
grpEncKeys.remove(grpId);
metaStorage.remove(ENCRYPTION_KEY_PREFIX + grpId);
if (log.isDebugEnabled())
log.debug("Key removed. [grp=" + grpId + "]");
}
catch (IgniteCheckedException e) {
U.error(log, "Failed to clear meta storage", e);
}
finally {
ctx.cache().context().database().checkpointReadUnlock();
}
}
}
/**
* Callback for cache group start event.
* @param grpId Group id.
* @param encKey Encryption key
*/
public void beforeCacheGroupStart(int grpId, @Nullable byte[] encKey) {
if (encKey == null || ctx.clientNode())
return;
groupKey(grpId, encKey);
}
/**
* Callback for cache group destroy event.
* @param grpId Group id.
*/
public void onCacheGroupDestroyed(int grpId) {
if (groupKey(grpId) == null)
return;
removeGroupKey(grpId);
}
/** {@inheritDoc} */
@Override public void onReadyForRead(ReadOnlyMetastorage metastorage) {
try {
Map<String, ? extends Serializable> encKeys = metastorage.readForPredicate(ENCRYPTION_KEY_PREFIX_PRED);
if (encKeys.isEmpty())
return;
for (String key : encKeys.keySet()) {
Integer grpId = Integer.valueOf(key.replace(ENCRYPTION_KEY_PREFIX, ""));
byte[] encGrpKey = (byte[])encKeys.get(key);
grpEncKeys.putIfAbsent(grpId, getSpi().decryptKey(encGrpKey));
}
if (!grpEncKeys.isEmpty()) {
U.quietAndInfo(log, "Encryption keys loaded from metastore. [grps=" +
F.concat(grpEncKeys.keySet(), ",") + "]");
}
}
catch (IgniteCheckedException e) {
throw new IgniteException("Failed to read encryption keys state.", e);
}
}
/** {@inheritDoc} */
@Override public void onReadyForReadWrite(ReadWriteMetastorage metaStorage) throws IgniteCheckedException {
synchronized (metaStorageMux) {
this.metaStorage = metaStorage;
writeToMetaStoreEnabled = true;
writeAllToMetaStore();
}
}
/** {@inheritDoc} */
@Override public void onActivate(GridKernalContext kctx) throws IgniteCheckedException {
synchronized (metaStorageMux) {
writeToMetaStoreEnabled = metaStorage != null;
if (writeToMetaStoreEnabled)
writeAllToMetaStore();
}
}
/** {@inheritDoc} */
@Override public void onDeActivate(GridKernalContext kctx) {
synchronized (metaStorageMux) {
writeToMetaStoreEnabled = false;
}
}
/**
* @param keyCnt Count of keys to generate.
* @return Future that will contain results of generation.
*/
public IgniteInternalFuture<Collection<byte[]>> generateKeys(int keyCnt) {
if (keyCnt == 0 || !ctx.clientNode())
return new GridFinishedFuture<>(createKeys(keyCnt));
synchronized (genEcnKeyMux) {
if (disconnected || stopped) {
return new GridFinishedFuture<>(
new IgniteFutureCancelledException("Node " + (stopped ? "stopped" : "disconnected")));
}
try {
GenerateEncryptionKeyFuture genEncKeyFut = new GenerateEncryptionKeyFuture(keyCnt);
sendGenerateEncryptionKeyRequest(genEncKeyFut);
genEncKeyFuts.put(genEncKeyFut.id(), genEncKeyFut);
return genEncKeyFut;
}
catch (IgniteCheckedException e) {
return new GridFinishedFuture<>(e);
}
}
}
/** */
private void sendGenerateEncryptionKeyRequest(GenerateEncryptionKeyFuture fut) throws IgniteCheckedException {
ClusterNode rndNode = U.randomServerNode(ctx);
if (rndNode == null)
throw new IgniteCheckedException("There is no node to send GenerateEncryptionKeyRequest to");
GenerateEncryptionKeyRequest req = new GenerateEncryptionKeyRequest(fut.keyCount());
fut.id(req.id());
fut.nodeId(rndNode.id());
ctx.io().sendToGridTopic(rndNode.id(), TOPIC_GEN_ENC_KEY, req, SYSTEM_POOL);
}
/**
* Writes all unsaved grpEncKeys to metaStorage.
* @throws IgniteCheckedException If failed.
*/
private void writeAllToMetaStore() throws IgniteCheckedException {
for (Map.Entry<Integer, Serializable> entry : grpEncKeys.entrySet()) {
if (metaStorage.read(ENCRYPTION_KEY_PREFIX + entry.getKey()) != null)
continue;
writeToMetaStore(entry.getKey(), getSpi().encryptKey(entry.getValue()));
}
}
/**
* Checks cache encryption supported by all nodes in cluster.
*
* @throws IgniteCheckedException If check fails.
*/
public void checkEncryptedCacheSupported() throws IgniteCheckedException {
Collection<ClusterNode> nodes = ctx.grid().cluster().nodes();
for (ClusterNode node : nodes) {
if (CACHE_ENCRYPTION_SINCE.compareTo(node.version()) > 0) {
throw new IgniteCheckedException("All nodes in cluster should be 2.7.0 or greater " +
"to create encrypted cache! [nodeId=" + node.id() + "]");
}
}
}
/** {@inheritDoc} */
@Override public DiscoveryDataExchangeType discoveryDataType() {
return ENCRYPTION_MGR;
}
/**
* Writes encryption key to metastore.
*
* @param grpId Group id.
* @param encGrpKey Group encryption key.
*/
private void writeToMetaStore(int grpId, byte[] encGrpKey) {
if (metaStorage == null || !writeToMetaStoreEnabled)
return;
ctx.cache().context().database().checkpointReadLock();
try {
metaStorage.write(ENCRYPTION_KEY_PREFIX + grpId, encGrpKey);
}
catch (IgniteCheckedException e) {
throw new IgniteException("Failed to write cache group encryption key [grpId=" + grpId + ']', e);
}
finally {
ctx.cache().context().database().checkpointReadUnlock();
}
}
/**
* @param knownKeys Saved keys set.
* @return New keys for local cache groups.
*/
@Nullable private HashMap<Integer, byte[]> newEncryptionKeys(Set<Integer> knownKeys) {
Map<Integer, CacheGroupDescriptor> grpDescs = ctx.cache().cacheGroupDescriptors();
HashMap<Integer, byte[]> newKeys = null;
for (CacheGroupDescriptor grpDesc : grpDescs.values()) {
if (knownKeys.contains(grpDesc.groupId()) || !grpDesc.config().isEncryptionEnabled())
continue;
if (newKeys == null)
newKeys = new HashMap<>();
newKeys.put(grpDesc.groupId(), getSpi().encryptKey(getSpi().create()));
}
return newKeys;
}
/**
* @return Local encryption keys.
*/
@Nullable private HashMap<Integer, byte[]> knownEncryptionKeys() {
if (F.isEmpty(grpEncKeys))
return null;
HashMap<Integer, byte[]> knownKeys = new HashMap<>();
for (Map.Entry<Integer, Serializable> entry : grpEncKeys.entrySet())
knownKeys.put(entry.getKey(), getSpi().encryptKey(entry.getValue()));
return knownKeys;
}
/**
* Generates required count of encryption keys.
*
* @param keyCnt Keys count.
* @return Collection with newly generated encryption keys.
*/
private Collection<byte[]> createKeys(int keyCnt) {
if (keyCnt == 0)
return Collections.emptyList();
List<byte[]> encKeys = new ArrayList<>(keyCnt);
for(int i=0; i<keyCnt; i++)
encKeys.add(getSpi().encryptKey(getSpi().create()));
return encKeys;
}
/**
* @param msg Error message.
*/
private void cancelFutures(String msg) {
for (GenerateEncryptionKeyFuture fut : genEncKeyFuts.values())
fut.onDone(new IgniteFutureCancelledException(msg));
}
/**
* Checks whether local node is coordinator. Nodes that are leaving or failed
* (but are still in topology) are removed from search.
*
* @return {@code true} if local node is coordinator.
*/
private boolean notCoordinator() {
DiscoverySpi spi = ctx.discovery().getInjectedDiscoverySpi();
if (spi instanceof TcpDiscoverySpi)
return !((TcpDiscoverySpi)spi).isLocalNodeCoordinator();
else {
ClusterNode crd = null;
for (ClusterNode node : ctx.discovery().aliveServerNodes()) {
if (crd == null || crd.order() > node.order())
crd = node;
}
return crd == null || !F.eq(ctx.localNodeId(), crd.id());
}
}
/** */
public static class NodeEncryptionKeys implements Serializable {
/** */
private static final long serialVersionUID = 0L;
/** */
NodeEncryptionKeys(Map<Integer, byte[]> knownKeys, Map<Integer, byte[]> newKeys) {
this.knownKeys = knownKeys;
this.newKeys = newKeys;
}
/** Known i.e. stored in {@code ReadWriteMetastorage} keys from node. */
Map<Integer, byte[]> knownKeys;
/** New keys i.e. keys for a local statically configured caches. */
Map<Integer, byte[]> newKeys;
}
/** */
@SuppressWarnings("ExternalizableWithoutPublicNoArgConstructor")
private class GenerateEncryptionKeyFuture extends GridFutureAdapter<Collection<byte[]>> {
/** */
private IgniteUuid id;
/** */
private int keyCnt;
/** */
private UUID nodeId;
/**
* @param keyCnt Count of keys to generate.
*/
private GenerateEncryptionKeyFuture(int keyCnt) {
this.keyCnt = keyCnt;
}
/** {@inheritDoc} */
@Override public boolean onDone(@Nullable Collection<byte[]> res, @Nullable Throwable err) {
// Make sure to remove future before completion.
genEncKeyFuts.remove(id, this);
return super.onDone(res, err);
}
/** */
public IgniteUuid id() {
return id;
}
/** */
public void id(IgniteUuid id) {
this.id = id;
}
/** */
public UUID nodeId() {
return nodeId;
}
/** */
public void nodeId(UUID nodeId) {
this.nodeId = nodeId;
}
/** */
public int keyCount() {
return keyCnt;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(GenerateEncryptionKeyFuture.class, this);
}
}
}
| 35.553672 | 150 | 0.621294 |
0cd5d07cd5d3f3c7a9285b8e9364d73b8166f97d | 3,703 | package mkl.testarea.pdfbox2.extract;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.Collections;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPageTree;
import org.apache.pdfbox.text.PDFTextStripper;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* @author mkl
*/
public class CompareText {
final static File RESULT_FOLDER = new File("target/test-outputs", "extract");
@BeforeClass
public static void setUpBeforeClass() throws Exception {
RESULT_FOLDER.mkdirs();
}
/**
* <a href="https://stackoverflow.com/questions/49256943/comparing-two-pdf-files-text-using-pdfbox-is-failing-eventhough-both-files-are-h">
* Comparing two PDF files text using PDFBox is failing eventhough both files are having same text
* </a>
* <br/>
* <a href="https://drive.google.com/file/d/1SeqdWhZdp-wuc0sfR3tvaSIRlRBSYOxL/view?usp=sharing">
* Table_Basic.pdf
* </a>
* <br/>
* <a href="https://drive.google.com/file/d/1mFD2cPSSzY3OHTP07d2ZUosaI0ZyCpf2/view?usp=sharing">
* Table_Basicf0313153905592.pdf
* </a>
* <p>
* Indeed, there is a difference in output. It is due to different
* <b>ToUnicode</b> mappings of certain characters in a certain font.
* As the Unicode code points in question are in a private use area,
* this wasn't that apparent.
* </p>
*/
@Test
public void testCompareSjethvaniFiles() throws IOException {
String pdfFile1 = "Table_Basic.pdf";
String pdfFile2 = "Table_Basicf0313153905592.pdf";
try ( InputStream resource1 = getClass().getResourceAsStream(pdfFile1);
InputStream resource2 = getClass().getResourceAsStream(pdfFile2)) {
PDDocument pdf1 = Loader.loadPDF(resource1);
PDDocument pdf2 = Loader.loadPDF(resource2);
PDPageTree pdf1pages = pdf1.getDocumentCatalog().getPages();
PDPageTree pdf2pages = pdf2.getDocumentCatalog().getPages();
try
{
if (pdf1pages.getCount() != pdf2pages.getCount())
{
String message = "Number of pages in the files ("+pdfFile1+","+pdfFile2+") do not match. pdfFile1 has "+pdf1pages.getCount()+" no pages, while pdf2pages has "+pdf2pages.getCount()+" no of pages";
fail(message);
}
PDFTextStripper pdfStripper = new PDFTextStripper();
for (int i = 0; i < pdf1pages.getCount(); i++)
{
pdfStripper.setStartPage(i + 1);
pdfStripper.setEndPage(i + 1);
String pdf1PageText = pdfStripper.getText(pdf1);
String pdf2PageText = pdfStripper.getText(pdf2);
if (!pdf1PageText.equals(pdf2PageText))
{
String message = "Contents of the files ("+pdfFile1+","+pdfFile2+") do not match on Page no: " + (i + 1)+" pdf1PageText is : "+pdf1PageText+" , while pdf2PageText is : "+pdf2PageText;
Files.write(new File(RESULT_FOLDER, pdfFile1 + '-' + i + ".txt").toPath(), Collections.singleton(pdf1PageText));
Files.write(new File(RESULT_FOLDER, pdfFile2 + '-' + i + ".txt").toPath(), Collections.singleton(pdf2PageText));
fail(message);
}
}
} finally {
pdf1.close();
pdf2.close();
}
}
}
}
| 42.079545 | 215 | 0.605185 |
e395cc6a7e898bf3d1e0d9d72efbc6e7c5e51595 | 1,736 | /*
* 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 PracticaTienda;
import java.io.Serializable;
/**
*
* @author dany
*/
public class Item implements Serializable{
private int id;
private String pic;
private String name;
private int stock;
private int price;
/**
*
* @param id unique id tag for each product
* @param pic name of the pic file
* @param name name of the item
* @param stock number of units avilable
* @param price price of the product
*/
public Item(int id,String pic, String name, int stock, int price) {
this.id=id;
this.pic = pic;
this.name = name;
this.stock = stock;
this.price = price;
}
public Item(Item i){//Solo usar para agregar algo al carrito
this.id=i.getId();
this.pic = i.getPic();
this.name = i.getName();
this.stock = 1;
this.price = i.getPrice();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getStock() {
return stock;
}
public void setStock(int stock) {
this.stock = stock;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
| 19.727273 | 79 | 0.565092 |
9ad446162087ccd01e2fdff8b05f2f42025aab36 | 1,352 | public class ReverseLinkedList {
protected static class LinkedNode<T> {
public LinkedNode<T> next;
T t;
public LinkedNode(LinkedNode<T> next, T t) {
this.next = next;
this.t = t;
}
public boolean hasNext() {
return next != null;
}
public LinkedNode<T> reverseList() {
LinkedNode<T> prevNode = null;
LinkedNode<T> currNode = this;
while(currNode.hasNext()) {
LinkedNode<T> tmp = currNode.next;
currNode.next = prevNode;
prevNode = currNode;
currNode = tmp;
}
currNode.next = prevNode;
return currNode;
}
}
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
// Core Function here
LinkedNode<Integer> h = new LinkedNode<Integer>(null, 4);
h = new LinkedNode<Integer>(h, 3);
h = new LinkedNode<Integer>(h, 2);
h = new LinkedNode<Integer>(h, 1);
printList(h);
h = h.reverseList();
printList(h);
h = h.reverseList();
printList(h);
double duration = System.currentTimeMillis() - startTime;
System.out.println();
System.out.print("Processing time: ");
System.out.format("%.3f", duration / 1000);
System.out.println(" seconds.");
}
public static void printList(LinkedNode n) {
while(n.hasNext()) {
System.out.print(n.t);
System.out.print(" -> ");
n = n.next;
}
System.out.println(n.t);
}
}
| 22.533333 | 59 | 0.638314 |
09a52d2907e899fc62831b6e2df4fd7e500dfd65 | 799 | package com.airbnb.aerosolve.core.features;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
public class FeatureMappingTest {
@Test
public void add() throws Exception {
FeatureMapping m = new FeatureMapping(100);
String[] doubleNames = {"a", "b"};
m.add(Double.class, doubleNames);
String[] booleanNames = {"c", "d"};
m.add(Boolean.class, booleanNames);
String[] strNames = {"e", "f"};
m.add(String.class, strNames);
m.finish();
assertEquals(m.getNames().length, 6);
assertArrayEquals(m.getNames(),
new String[]{"a", "b", "c", "d", "e", "f"});
assertEquals(m.getMapping().get(String.class).start, 4);
assertEquals(m.getMapping().get(String.class).length, 2);
}
} | 29.592593 | 61 | 0.659574 |
290f779ac03dc5ae2a7ce7f4648ff3c9a918ac7c | 2,099 | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.activiti.idm.api;
import java.util.List;
/**
* Allows to programmatically query for {@link Group}s.
*
* @author Joram Barrez
*/
public interface GroupQuery extends Query<GroupQuery, Group> {
/** Only select {@link Group}s with the given id. */
GroupQuery groupId(String groupId);
/** Only select {@link Group}s with the given ids. */
GroupQuery groupIds(List<String> groupIds);
/** Only select {@link Group}s with the given name. */
GroupQuery groupName(String groupName);
/**
* Only select {@link Group}s where the name matches the given parameter. The syntax to use is that of SQL, eg. %activiti%.
*/
GroupQuery groupNameLike(String groupNameLike);
/** Only select {@link Group}s which have the given type. */
GroupQuery groupType(String groupType);
/** Only selects {@link Group}s where the given user is a member of. */
GroupQuery groupMember(String groupMemberUserId);
/** Only selects {@link Group}s where the given users are a member of. */
GroupQuery groupMembers(List<String> groupMemberUserIds);
// sorting ////////////////////////////////////////////////////////
/**
* Order by group id (needs to be followed by {@link #asc()} or {@link #desc()}).
*/
GroupQuery orderByGroupId();
/**
* Order by group name (needs to be followed by {@link #asc()} or {@link #desc()}).
*/
GroupQuery orderByGroupName();
/**
* Order by group type (needs to be followed by {@link #asc()} or {@link #desc()}).
*/
GroupQuery orderByGroupType();
}
| 31.80303 | 125 | 0.673178 |
9eaa5f5b3b7e4a1a0e98ecd99e93c4e6e4fab8ff | 4,489 | import java.util.*;
import java.io.*;
// -------------------------------------------------------------------------
/**
* @author Daniel Nugent
* @version HT 2020
*/
class SortComparison {
static double[] insertionSort(double a[]) {
if (a != null) {
int len = a.length;
for (int i = 1; i < len; ++i) {
double key = a[i];
int j = i - 1;
/*
* Move elements of arr[0..i-1], that are greater than key, to one position
* ahead of their current position
*/
while (j >= 0 && a[j] > key) {
a[j + 1] = a[j];
j = j - 1;
}
a[j + 1] = key;
}
return a;
} else
return a;
}// end insertionsort
static double[] selectionSort(double[] a) {
if (a != null) {
for (int i = 0; i < a.length - 1; i++) {
int min = i;
for (int j = i + 1; j < a.length; j++) {
if (a[j] < a[min]) {
min = j;
}
}
swap(min, i, a);
}
return a;
} else {
return null;
}
}// end selectionsort
static void swap(int i, int j, double a[]) {
double temp = a[i];
a[i] = a[j];
a[j] = temp;
}
static double[] quickSort(double a[]) {
if(a == null) return a;
int lo = 0;
int hi = a.length - 1;
if (lo < hi) {
int partition = partition(a, lo, hi);
quickSort(a, lo, partition - 1);
quickSort(a, partition + 1, hi);
}
return a;
}
static void quickSort(double a[], int lo, int hi) {
if (lo < hi) {
int partition = partition(a, lo, hi);
quickSort(a, lo, partition - 1);
quickSort(a, partition + 1, hi);
}
}
static int partition(double a[], int lo, int hi) {
double pivot = a[hi];
int i = lo - 1;
for (int j = lo; j <= hi - 1; j++) {
if (a[j] < pivot) {
i++;
swap(i, j, a);
}
}
swap(i + 1, hi, a);
return i + 1;
}
static double[] mergeSortIterative(double[] a) {
if (a != null) {
int low = 0;
int high = a.length - 1;
double[] temp = Arrays.copyOf(a, a.length);
for (int m = 1; m <= high - low; m = 2 * m) {
for (int bottom = low; bottom < high; bottom += 2 * m) {
int mid = bottom + m - 1;
int top = bottom + 2 * m - 1;
merge(a, temp, bottom, mid, (top < high) ? top : high);
}
}
return a;
} else {
return null;
}
}
private static void merge(double[] a, double[] temp, int bottom, int mid, int top) {
int k = bottom, i = bottom, j = mid + 1;
while (i <= mid && j <= top) {
if (a[i] < a[j]) {
temp[k++] = a[i++];
} else {
temp[k++] = a[j++];
}
}
while (i <= mid && i < a.length) {
temp[k++] = a[i++];
}
for (i = bottom; i <= top; i++) {
a[i] = temp[i];
}
}
static double[] mergeSortRecursive(double[] a) {
mergeSort(a);
return a;
}//end mergeSortRecursive
private static void mergeSort(double[] a) {
if (a != null) {
if (a.length > 1) {
int mid = a.length / 2;
double[] leftArray = new double[mid];
System.arraycopy(a, 0, leftArray, 0, mid);
double[] rightArray = new double[a.length - mid];
if (a.length - mid >= 0) System.arraycopy(a, mid, rightArray, 0, a.length - mid);
mergeSort(leftArray);
mergeSort(rightArray);
int i = 0;
int j = 0;
int k = 0;
while (i < leftArray.length && j < rightArray.length) {
if (leftArray[i] < rightArray[j]) {
a[k] = leftArray[i];
i++;
} else {
a[k] = rightArray[j];
j++;
}
k++;
}
while (i < leftArray.length) {
a[k] = leftArray[i];
i++;
k++;
}
while (j < rightArray.length) {
a[k] = rightArray[j];
j++;
k++;
}
}
}
}
}
// end class
| 24.938889 | 98 | 0.390956 |
6c63d7b038a35a6278436c1ad6c838975633dfed | 2,993 | /*
* Copyright 2018 ConsenSys AG.
*
* 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.hyperledger.besu.ethereum.api.jsonrpc.internal.results;
import org.hyperledger.besu.ethereum.core.Transaction;
import org.hyperledger.besu.util.bytes.BytesValue;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonPropertyOrder({
"blockHash",
"blockNumber",
"from",
"gas",
"gasPrice",
"hash",
"input",
"nonce",
"to",
"transactionIndex",
"value",
"v",
"r",
"s"
})
public class TransactionPendingResult implements TransactionResult {
private final String from;
private final String gas;
private final String gasPrice;
private final String hash;
private final String input;
private final String nonce;
private final String to;
private final String value;
private final String v;
private final String r;
private final String s;
public TransactionPendingResult(final Transaction transaction) {
this.from = transaction.getSender().toString();
this.gas = Quantity.create(transaction.getGasLimit());
this.gasPrice = Quantity.create(transaction.getGasPrice());
this.hash = transaction.hash().toString();
this.input = transaction.getPayload().toString();
this.nonce = Quantity.create(transaction.getNonce());
this.to = transaction.getTo().map(BytesValue::toString).orElse(null);
this.value = Quantity.create(transaction.getValue());
this.v = Quantity.create(transaction.getV());
this.r = Quantity.create(transaction.getR());
this.s = Quantity.create(transaction.getS());
}
@JsonGetter(value = "from")
public String getFrom() {
return from;
}
@JsonGetter(value = "gas")
public String getGas() {
return gas;
}
@JsonGetter(value = "gasPrice")
public String getGasPrice() {
return gasPrice;
}
@JsonGetter(value = "hash")
public String getHash() {
return hash;
}
@JsonGetter(value = "input")
public String getInput() {
return input;
}
@JsonGetter(value = "nonce")
public String getNonce() {
return nonce;
}
@JsonGetter(value = "to")
public String getTo() {
return to;
}
@JsonGetter(value = "value")
public String getValue() {
return value;
}
@JsonGetter(value = "v")
public String getV() {
return v;
}
@JsonGetter(value = "r")
public String getR() {
return r;
}
@JsonGetter(value = "s")
public String getS() {
return s;
}
}
| 24.941667 | 118 | 0.695289 |
e929754cf7670d56251dbde91c6eb7df6fed9e88 | 2,319 | package cn.ffcs.ms.crm_mobile_v20.entities;
import android.support.annotation.NonNull;
import android.util.Log;
import java.util.List;
import java.util.concurrent.TimeUnit;
import cn.ffcs.ms.crm_mobile_v20.greendao.gen.SceneDao;
import rx.Observable;
import rx.Scheduler;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
/**
* Created by Vic on 16/12/26.
*/
public class SceneModel implements ISceneModel {
private SceneDao mDao;
public SceneModel(@NonNull SceneDao dao) {
mDao = dao;
}
public void addScene(@NonNull Scene scene) {
if (mDao.load(scene.getId()) == null) {
mDao.insert(scene);
} else {
mDao.update(scene);
}
}
public void addScenes(@NonNull List<Scene> scenes) {
for (Scene scene : scenes) {
addScene(scene);
}
}
@Override
public void loadAllScenes(@NonNull final GetScenesCallback callback) {
mDao.rxPlain()
.loadAll()
.delay(2, TimeUnit.SECONDS) // 延时2s
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<List<Scene>>() {
@Override
public void call(List<Scene> scenes) {
Log.d("LoadScene", "--------");
if (scenes != null && scenes.size() > 0) {
callback.onSuccessed(scenes);
} else {
callback.onFailed("无Scene数据!");
}
}
});
/*
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(2000);
List<Scene> scenes = mDao.loadAll();
if (scenes != null && scenes.size() > 0) {
callback.onSuccessed(scenes);
} else {
callback.onFailed("无Scene数据!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
*/
}
}
| 28.62963 | 74 | 0.496335 |
a80bc6096d08d42bf25b04c70f511db4e12b3be3 | 1,011 | import java.util.*;
public class LC484FindPermutation {
public static int[] findPermutation(String s) {
if(s==null)
return new int[]{};
int n= s.length()+1;
int[] res = new int[n];
for(int i=1; i<=n; i++){
res[i-1]=i;
}
int lasti=0;
for(int i=0; i<s.length(); i++){
if(s.charAt(i)=='I'){
reverse(res, lasti, i);
lasti=i+1;
}
}
reverse(res, lasti, s.length());
return res;
}
private static void reverse(int[] res, int s, int e) {
while(s<e){
swap(res, s, e);
s++;
e--;
}
}
private static void swap(int[] nums, int a, int b){
int temp=nums[a];
nums[a] =nums[b];
nums[b] =temp;
}
public static void main(String args[]){
String s= "DII";
int[] res = findPermutation(s);
System.out.print(Arrays.toString(res));
}
}
| 19.823529 | 58 | 0.445104 |
59c2e76691524d73810ffcb216d6289cb8e6a1e0 | 805 | package learn.katas.corejava.generics.simple;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class ArrayAlgTest {
@SuppressWarnings("rawtypes")
@Test
void testMinMax() {
String[] data = {"B", "C", "A", "E", "F", "D"};
Pair result = ArrayAlg.minMax(data);
assertNotNull(result);
assertEquals("A", result.getFirst());
assertEquals("F", result.getSecond());
}
@SuppressWarnings("rawtypes")
@Test
void testMinMaxCount() {
String[] data = {"Bb", "A", "F", "Dd"};
Three result = ArrayAlg.minMaxCount(data);
assertNotNull(result);
assertEquals("A", result.getFirst());
assertEquals("F", result.getSecond());
assertEquals(6L, result.getThird());
}
}
| 26.833333 | 55 | 0.6 |
60d5124925aea1fe34fbb421c05b4f00f10e8ced | 28,155 | /**
* 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.
*
* Copyright 2012-2015 the original author or authors.
*/
package org.assertj.swing.core;
import static java.awt.event.InputEvent.BUTTON1_MASK;
import static java.awt.event.InputEvent.BUTTON2_MASK;
import static java.awt.event.InputEvent.BUTTON3_MASK;
import static java.awt.event.KeyEvent.CHAR_UNDEFINED;
import static java.awt.event.KeyEvent.KEY_TYPED;
import static java.awt.event.KeyEvent.VK_UNDEFINED;
import static java.awt.event.WindowEvent.WINDOW_CLOSING;
import static java.lang.System.currentTimeMillis;
import static javax.swing.SwingUtilities.getWindowAncestor;
import static javax.swing.SwingUtilities.isEventDispatchThread;
import static org.assertj.core.util.Lists.newArrayList;
import static org.assertj.core.util.Preconditions.checkNotNull;
import static org.assertj.core.util.Strings.concat;
import static org.assertj.swing.awt.AWT.centerOf;
import static org.assertj.swing.awt.AWT.visibleCenterOf;
import static org.assertj.swing.core.ActivateWindowTask.activateWindow;
import static org.assertj.swing.core.ComponentIsFocusableQuery.isFocusable;
import static org.assertj.swing.core.ComponentRequestFocusTask.giveFocusTo;
import static org.assertj.swing.core.FocusOwnerFinder.focusOwner;
import static org.assertj.swing.core.FocusOwnerFinder.inEdtFocusOwner;
import static org.assertj.swing.core.InputModifiers.unify;
import static org.assertj.swing.core.MouseButton.LEFT_BUTTON;
import static org.assertj.swing.core.MouseButton.RIGHT_BUTTON;
import static org.assertj.swing.core.Scrolling.scrollToVisible;
import static org.assertj.swing.core.WindowAncestorFinder.windowAncestorOf;
import static org.assertj.swing.edt.GuiActionRunner.execute;
import static org.assertj.swing.exception.ActionFailedException.actionFailure;
import static org.assertj.swing.format.Formatting.format;
import static org.assertj.swing.format.Formatting.inEdtFormat;
import static org.assertj.swing.hierarchy.NewHierarchy.ignoreExistingComponents;
import static org.assertj.swing.keystroke.KeyStrokeMap.keyStrokeFor;
import static org.assertj.swing.query.ComponentShowingQuery.isShowing;
import static org.assertj.swing.timing.Pause.pause;
import static org.assertj.swing.util.Modifiers.keysFor;
import static org.assertj.swing.util.Modifiers.updateModifierWithKeyCode;
import static org.assertj.swing.util.TimeoutWatch.startWatchWithTimeoutOf;
import java.applet.Applet;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.InvocationEvent;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;
import java.util.Collection;
import java.util.List;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
import javax.swing.JComponent;
import javax.swing.JMenu;
import javax.swing.JPopupMenu;
import javax.swing.KeyStroke;
import org.assertj.core.util.VisibleForTesting;
import org.assertj.swing.annotation.RunsInCurrentThread;
import org.assertj.swing.annotation.RunsInEDT;
import org.assertj.swing.edt.GuiQuery;
import org.assertj.swing.edt.GuiTask;
import org.assertj.swing.exception.ActionFailedException;
import org.assertj.swing.exception.ComponentLookupException;
import org.assertj.swing.exception.WaitTimedOutError;
import org.assertj.swing.hierarchy.ComponentHierarchy;
import org.assertj.swing.hierarchy.ExistingHierarchy;
import org.assertj.swing.input.InputState;
import org.assertj.swing.lock.ScreenLock;
import org.assertj.swing.monitor.WindowMonitor;
import org.assertj.swing.util.Pair;
import org.assertj.swing.util.TimeoutWatch;
import org.assertj.swing.util.ToolkitProvider;
/**
* Default implementation of {@link Robot}.
*
* @author Alex Ruiz
* @author Yvonne Wang
*
* @see Robot
*/
public class BasicRobot implements Robot {
private static final int POPUP_DELAY = 10000;
private static final int POPUP_TIMEOUT = 5000;
private static final int WINDOW_DELAY = 20000;
private static final ComponentMatcher POPUP_MATCHER = new TypeMatcher(JPopupMenu.class, true);
@GuardedBy("this")
private volatile boolean active;
private static final Runnable EMPTY_RUNNABLE = new Runnable() {
@Override
public void run() {
}
};
private static final int BUTTON_MASK = BUTTON1_MASK | BUTTON2_MASK | BUTTON3_MASK;
private static Toolkit toolkit = ToolkitProvider.instance().defaultToolkit();
private static WindowMonitor windowMonitor = WindowMonitor.instance();
private static InputState inputState = new InputState(toolkit);
private final ComponentHierarchy hierarchy;
private final Object screenLockOwner;
private final ComponentFinder finder;
private final Settings settings;
private final AWTEventPoster eventPoster;
private final InputEventGenerator eventGenerator;
private final UnexpectedJOptionPaneFinder unexpectedJOptionPaneFinder;
/**
* Creates a new {@link Robot} with a new AWT hierarchy. The created {@code Robot} will not be able to access any AWT
* and Swing {@code Component}s that were created before it.
*
* @return the created {@code Robot}.
*/
public static @Nonnull Robot robotWithNewAwtHierarchy() {
Object screenLockOwner = acquireScreenLock();
return new BasicRobot(screenLockOwner, ignoreExistingComponents());
}
public static @Nonnull Robot robotWithNewAwtHierarchyWithoutScreenLock() {
return new BasicRobot(null, ignoreExistingComponents());
}
/**
* Creates a new {@link Robot} that has access to all the AWT and Swing {@code Component}s in the AWT hierarchy.
*
* @return the created {@code Robot}.
*/
public static @Nonnull Robot robotWithCurrentAwtHierarchy() {
Object screenLockOwner = acquireScreenLock();
return new BasicRobot(screenLockOwner, new ExistingHierarchy());
}
// TODO document
public static @Nonnull Robot robotWithCurrentAwtHierarchyWithoutScreenLock() {
return new BasicRobot(null, new ExistingHierarchy());
}
private static @Nonnull Object acquireScreenLock() {
Object screenLockOwner = new Object();
ScreenLock.instance().acquire(screenLockOwner);
return screenLockOwner;
}
@VisibleForTesting
BasicRobot(@Nullable Object screenLockOwner, @Nonnull ComponentHierarchy hierarchy) {
this.screenLockOwner = screenLockOwner;
this.hierarchy = hierarchy;
settings = new Settings();
eventGenerator = new RobotEventGenerator(settings);
eventPoster = new AWTEventPoster(toolkit, inputState, windowMonitor, settings);
finder = new BasicComponentFinder(hierarchy, settings);
unexpectedJOptionPaneFinder = new UnexpectedJOptionPaneFinder(finder);
active = true;
}
@Override
public @Nonnull ComponentPrinter printer() {
return finder().printer();
}
@Override
public @Nonnull ComponentFinder finder() {
return finder;
}
@RunsInEDT
@Override
public void showWindow(@Nonnull Window w) {
showWindow(w, null, true);
}
@RunsInEDT
@Override
public void showWindow(@Nonnull Window w, @Nonnull Dimension size) {
showWindow(w, size, true);
}
@RunsInEDT
@Override
public void showWindow(@Nonnull final Window w, @Nullable final Dimension size, final boolean pack) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
if (pack) {
packAndEnsureSafePosition(w);
}
if (size != null) {
w.setSize(size);
}
w.setVisible(true);
}
});
waitForWindow(w);
}
@RunsInCurrentThread
private void packAndEnsureSafePosition(@Nonnull Window w) {
w.pack();
w.setLocation(100, 100);
}
@RunsInEDT
private void waitForWindow(@Nonnull Window w) {
long start = currentTimeMillis();
while (!windowMonitor.isWindowReady(w) || !isShowing(w)) {
long elapsed = currentTimeMillis() - start;
if (elapsed > WINDOW_DELAY) {
throw new WaitTimedOutError(concat("Timed out waiting for Window to open (", String.valueOf(elapsed), "ms)"));
}
pause();
}
}
@RunsInEDT
@Override
public void close(@Nonnull Window w) {
WindowEvent event = new WindowEvent(w, WINDOW_CLOSING);
// If the window contains an applet, send the event on the applet's queue instead to ensure a shutdown from the
// applet's context (assists AppletViewer cleanup).
Component applet = findAppletDescendent(w);
EventQueue eventQueue = windowMonitor.eventQueueFor(applet != null ? applet : w);
checkNotNull(eventQueue).postEvent(event);
waitForIdle();
}
/**
* Returns the {@code Applet} descendant of the given AWT {@code Container}, if any.
*
* @param c the given {@code Container}.
* @return the {@code Applet} descendant of the given AWT {@code Container}, or {@code null} if none is found.
*/
@RunsInEDT
private @Nullable Applet findAppletDescendent(@Nonnull Container c) {
List<Component> found = newArrayList(finder.findAll(c, new TypeMatcher(Applet.class)));
if (found.size() == 1) {
return (Applet) found.get(0);
}
return null;
}
@RunsInEDT
@Override
public void focusAndWaitForFocusGain(@Nonnull Component c) {
focus(c, true);
}
@RunsInEDT
@Override
public void focus(@Nonnull Component c) {
focus(c, false);
}
@RunsInEDT
private void focus(@Nonnull Component target, boolean wait) {
Component currentOwner = inEdtFocusOwner();
if (currentOwner == target) {
return;
}
FocusMonitor focusMonitor = FocusMonitor.attachTo(target);
// for pointer focus
moveMouse(target);
// Make sure the correct window is in front
activateWindowOfFocusTarget(target, currentOwner);
giveFocusTo(target);
try {
if (wait) {
TimeoutWatch watch = startWatchWithTimeoutOf(settings().timeoutToBeVisible());
while (!focusMonitor.hasFocus()) {
if (watch.isTimeOut()) {
throw actionFailure(concat("Focus change to ", format(target), " failed", " focus owner: ",
format(FocusOwnerFinder.focusOwner())));
}
pause();
}
}
} finally {
target.removeFocusListener(focusMonitor);
}
}
@RunsInEDT
private void activateWindowOfFocusTarget(@Nullable Component target, @Nullable Component currentOwner) {
Pair<Window, Window> windowAncestors = windowAncestorsOf(currentOwner, target);
Window currentOwnerAncestor = windowAncestors.first;
Window targetAncestor = windowAncestors.second;
if (currentOwnerAncestor == targetAncestor) {
return;
}
activate(checkNotNull(targetAncestor));
waitForIdle();
}
@RunsInEDT
private static Pair<Window, Window> windowAncestorsOf(final @Nullable Component one, final @Nullable Component two) {
return execute(new GuiQuery<Pair<Window, Window>>() {
@Override
protected Pair<Window, Window> executeInEDT() throws Throwable {
return Pair.of(windowAncestor(one), windowAncestor(two));
}
private @Nullable Window windowAncestor(Component c) {
return (c != null) ? windowAncestorOf(c) : null;
}
});
}
/**
* Activates the given AWT {@code Window}. "Activate" means that the given window gets the keyboard focus.
*
* @param w the window to activate.
*/
@RunsInEDT
private void activate(@Nonnull Window w) {
activateWindow(w);
moveMouse(w); // For pointer-focus systems
}
@RunsInEDT
@Override
public synchronized void cleanUp() {
cleanUp(true);
}
@RunsInEDT
@Override
public synchronized void cleanUpWithoutDisposingWindows() {
cleanUp(false);
}
@RunsInEDT
private void cleanUp(boolean disposeWindows) {
try {
if (disposeWindows) {
disposeWindows(hierarchy);
}
releaseMouseButtons();
} finally {
active = false;
releaseScreenLock();
}
}
private void releaseScreenLock() {
ScreenLock screenLock = ScreenLock.instance();
if (screenLock.acquiredBy(screenLockOwner)) {
screenLock.release(screenLockOwner);
}
}
@RunsInEDT
private static void disposeWindows(final @Nonnull ComponentHierarchy hierarchy) {
execute(new GuiTask() {
@Override
protected void executeInEDT() {
for (Container c : hierarchy.roots()) {
if (c instanceof Window) {
dispose(hierarchy, (Window) c);
}
}
}
});
}
@RunsInCurrentThread
private static void dispose(final @Nonnull ComponentHierarchy hierarchy, @Nonnull Window w) {
hierarchy.dispose(w);
w.setVisible(false);
w.dispose();
}
@RunsInEDT
@Override
public void click(@Nonnull Component c) {
click(c, LEFT_BUTTON);
}
@RunsInEDT
@Override
public void rightClick(@Nonnull Component c) {
click(c, RIGHT_BUTTON);
}
@RunsInEDT
@Override
public void click(@Nonnull Component c, @Nonnull MouseButton button) {
click(c, button, 1);
}
@RunsInEDT
@Override
public void doubleClick(@Nonnull Component c) {
click(c, LEFT_BUTTON, 2);
}
@RunsInEDT
@Override
public void click(@Nonnull Component c, @Nonnull MouseButton button, int times) {
Point where = visibleCenterOf(c);
if (c instanceof JComponent) {
where = scrollIfNecessary((JComponent) c);
}
click(c, where, button, times);
}
private @Nonnull Point scrollIfNecessary(@Nonnull JComponent c) {
scrollToVisible(this, c);
return visibleCenterOf(c);
}
@RunsInEDT
@Override
public void click(@Nonnull Component c, @Nonnull Point where) {
click(c, where, LEFT_BUTTON, 1);
}
@RunsInEDT
@Override
public void click(@Nonnull Point where, @Nonnull MouseButton button, int times) {
doClick(null, where, button, times);
}
@RunsInEDT
@Override
public void click(@Nonnull Component c, @Nonnull Point where, @Nonnull MouseButton button, int times) {
doClick(c, where, button, times);
}
private void doClick(@Nullable Component c, @Nonnull Point where, @Nonnull MouseButton button, int times) {
int mask = button.mask;
int modifierMask = mask & ~BUTTON_MASK;
mask &= BUTTON_MASK;
pressModifiers(modifierMask);
// From Abbot: Adjust the auto-delay to ensure we actually get a multiple click
// In general clicks have to be less than 200ms apart, although the actual setting is not readable by Java.
int delayBetweenEvents = settings.delayBetweenEvents();
if (shouldSetDelayBetweenEventsToZeroWhenClicking(times)) {
settings.delayBetweenEvents(0);
}
if (c == null) {
eventGenerator.pressMouse(where, mask);
for (int i = times; i > 1; i--) {
eventGenerator.releaseMouse(mask);
eventGenerator.pressMouse(mask);
}
} else {
eventGenerator.pressMouse(c, where, mask);
for (int i = times; i > 1; i--) {
eventGenerator.releaseMouse(mask);
eventGenerator.pressMouse(mask);
}
}
settings.delayBetweenEvents(delayBetweenEvents);
eventGenerator.releaseMouse(mask);
releaseModifiers(modifierMask);
waitForIdle();
}
private boolean shouldSetDelayBetweenEventsToZeroWhenClicking(int times) {
return times > 1 /* FEST-137: && settings.delayBetweenEvents() * 2 > 200 */;
}
@Override
public void pressModifiers(int modifierMask) {
for (int modifierKey : keysFor(modifierMask)) {
pressKey(modifierKey);
}
}
@Override
public void releaseModifiers(int modifierMask) {
// For consistency, release in the reverse order of press.
int[] modifierKeys = keysFor(modifierMask);
for (int i = modifierKeys.length - 1; i >= 0; i--) {
releaseKey(modifierKeys[i]);
}
}
@RunsInEDT
@Override
public void moveMouse(@Nonnull Component c) {
moveMouse(c, visibleCenterOf(c));
}
@RunsInEDT
@Override
public void moveMouse(@Nonnull Component c, @Nonnull Point p) {
moveMouse(c, p.x, p.y);
}
@RunsInEDT
@Override
public void moveMouse(@Nonnull Component c, int x, int y) {
if (!waitForComponentToBeReady(c, settings.timeoutToBeVisible())) {
throw actionFailure(concat("Could not obtain position of component ", format(c)));
}
eventGenerator.moveMouse(c, x, y);
waitForIdle();
}
@Override
public void moveMouse(@Nonnull Point p) {
moveMouse(p.x, p.y);
}
@Override
public void moveMouse(int x, int y) {
eventGenerator.moveMouse(x, y);
}
@Override
public void pressMouse(@Nonnull MouseButton button) {
eventGenerator.pressMouse(button.mask);
}
@Override
public void pressMouse(@Nonnull Component c, @Nonnull Point where) {
pressMouse(c, where, LEFT_BUTTON);
}
@Override
public void pressMouse(@Nonnull Component c, @Nonnull Point where, @Nonnull MouseButton button) {
jitter(c, where);
moveMouse(c, where.x, where.y);
eventGenerator.pressMouse(c, where, button.mask);
}
@Override
public void pressMouse(@Nonnull Point where, @Nonnull MouseButton button) {
eventGenerator.pressMouse(where, button.mask);
}
@RunsInEDT
@Override
public void releaseMouse(@Nonnull MouseButton button) {
mouseRelease(button.mask);
}
@RunsInEDT
@Override
public void releaseMouseButtons() {
int buttons = inputState.buttons();
if (buttons == 0) {
return;
}
mouseRelease(buttons);
}
@Override
public void rotateMouseWheel(@Nonnull Component c, int amount) {
moveMouse(c);
rotateMouseWheel(amount);
}
@Override
public void rotateMouseWheel(int amount) {
eventGenerator.rotateMouseWheel(amount);
waitForIdle();
}
@RunsInEDT
@Override
public void jitter(@Nonnull Component c) {
jitter(c, visibleCenterOf(c));
}
@RunsInEDT
@Override
public void jitter(@Nonnull Component c, @Nonnull Point where) {
int x = where.x;
int y = where.y;
moveMouse(c, (x > 0 ? x - 1 : x + 1), y);
}
// Wait the given number of milliseconds for the component to be showing and ready.
@RunsInEDT
private boolean waitForComponentToBeReady(@Nonnull Component c, long timeout) {
if (isReadyForInput(c)) {
return true;
}
TimeoutWatch watch = startWatchWithTimeoutOf(timeout);
while (!isReadyForInput(c)) {
if (c instanceof JPopupMenu) {
// wiggle the mouse over the parent menu item to ensure the sub-menu shows
Pair<Component, Point> invokerAndCenterOfInvoker = invokerAndCenterOfInvoker((JPopupMenu) c);
Component invoker = invokerAndCenterOfInvoker.first;
if (invoker instanceof JMenu) {
jitter(invoker, invokerAndCenterOfInvoker.second);
}
}
if (watch.isTimeOut()) {
return false;
}
pause();
}
return true;
}
@RunsInEDT
private static @Nonnull Pair<Component, Point> invokerAndCenterOfInvoker(final @Nonnull JPopupMenu popupMenu) {
Pair<Component, Point> result = execute(new GuiQuery<Pair<Component, Point>>() {
@Override
protected Pair<Component, Point> executeInEDT() {
Component invoker = checkNotNull(popupMenu.getInvoker());
return Pair.of(invoker, centerOf(invoker));
}
});
return checkNotNull(result);
}
@RunsInEDT
@Override
public void enterText(@Nonnull String text) {
checkNotNull(text);
if (text.isEmpty()) {
return;
}
for (char character : text.toCharArray()) {
type(character);
}
}
@RunsInEDT
@Override
public void type(char character) {
KeyStroke keyStroke = keyStrokeFor(character);
if (keyStroke == null) {
Component focus = focusOwner();
if (focus == null) {
return;
}
KeyEvent keyEvent = keyEventFor(focus, character);
// Allow any pending robot events to complete; otherwise we might stuff the typed event before previous
// robot-generated events are posted.
waitForIdle();
eventPoster.postEvent(focus, keyEvent);
return;
}
keyPressAndRelease(keyStroke.getKeyCode(), keyStroke.getModifiers());
}
private KeyEvent keyEventFor(Component c, char character) {
return new KeyEvent(c, KEY_TYPED, currentTimeMillis(), 0, VK_UNDEFINED, character);
}
@RunsInEDT
@Override
public void pressAndReleaseKey(int keyCode, @Nonnull int... modifiers) {
keyPressAndRelease(keyCode, unify(modifiers));
waitForIdle();
}
@RunsInEDT
@Override
public void pressAndReleaseKeys(@Nonnull int... keyCodes) {
for (int keyCode : keyCodes) {
keyPressAndRelease(keyCode, 0);
waitForIdle();
pause(50); // it seems that even when waiting for idle the events are not completely propagated
}
}
@RunsInEDT
private void keyPressAndRelease(int keyCode, int modifiers) {
int updatedModifiers = updateModifierWithKeyCode(keyCode, modifiers);
pressModifiers(updatedModifiers);
if (updatedModifiers == modifiers) {
doPressKey(keyCode);
eventGenerator.releaseKey(keyCode);
}
releaseModifiers(updatedModifiers);
}
@RunsInEDT
@Override
public void pressKey(int keyCode) {
doPressKey(keyCode);
waitForIdle();
}
@RunsInEDT
private void doPressKey(int keyCode) {
eventGenerator.pressKey(keyCode, CHAR_UNDEFINED);
}
@RunsInEDT
@Override
public void releaseKey(int keyCode) {
eventGenerator.releaseKey(keyCode);
waitForIdle();
}
@RunsInEDT
private void mouseRelease(int buttons) {
eventGenerator.releaseMouse(buttons);
}
@RunsInEDT
@Override
public void waitForIdle() {
waitIfNecessary();
Collection<EventQueue> queues = windowMonitor.allEventQueues();
if (queues.size() == 1) {
waitForIdle(checkNotNull(toolkit.getSystemEventQueue()));
return;
}
// FIXME this resurrects dead event queues
for (EventQueue queue : queues) {
waitForIdle(checkNotNull(queue));
}
}
private void waitIfNecessary() {
int delayBetweenEvents = settings.delayBetweenEvents();
int eventPostingDelay = settings.eventPostingDelay();
if (eventPostingDelay > delayBetweenEvents) {
pause(eventPostingDelay - delayBetweenEvents);
}
}
private void waitForIdle(@Nonnull EventQueue eventQueue) {
if (EventQueue.isDispatchThread()) {
throw new IllegalThreadStateException("Cannot call method from the event dispatcher thread");
}
// Abbot: as of Java 1.3.1, robot.waitForIdle only waits for the last event on the queue at the time of this
// invocation to be processed. We need better than that. Make sure the given event queue is empty when this method
// returns.
// We always post at least one idle event to allow any current event dispatch processing to finish.
long start = currentTimeMillis();
int count = 0;
do {
// Timed out waiting for idle
int idleTimeout = settings.idleTimeout();
if (postInvocationEvent(eventQueue, idleTimeout)) {
break;
}
// Timed out waiting for idle event queue
if (currentTimeMillis() - start > idleTimeout) {
break;
}
++count;
// Force a yield
pause();
// Abbot: this does not detect invocation events (i.e. what gets posted with EventQueue.invokeLater), so if
// someone is repeatedly posting one, we might get stuck. Not too worried, since if a Runnable keeps calling
// invokeLater on itself, *nothing* else gets much chance to run, so it seems to be a bad programming practice.
} while (eventQueue.peekEvent() != null);
}
// Indicates whether we timed out waiting for the invocation to run
@RunsInEDT
private boolean postInvocationEvent(@Nonnull EventQueue eventQueue, long timeout) {
Object lock = new RobotIdleLock();
synchronized (lock) {
eventQueue.postEvent(new InvocationEvent(toolkit, EMPTY_RUNNABLE, lock, true));
long start = currentTimeMillis();
try {
// NOTE: on fast linux systems when showing a dialog, if we don't provide a timeout, we're never notified, and
// the test will wait forever (up through 1.5.0_05).
lock.wait(timeout);
return (currentTimeMillis() - start) >= settings.idleTimeout();
} catch (InterruptedException e) {
}
return false;
}
}
private static class RobotIdleLock {
RobotIdleLock() {
}
}
@Override
public boolean isDragging() {
return inputState.dragInProgress();
}
@RunsInEDT
@Override
public @Nonnull JPopupMenu showPopupMenu(@Nonnull Component invoker) {
return showPopupMenu(invoker, visibleCenterOf(invoker));
}
@RunsInEDT
@Override
public @Nonnull JPopupMenu showPopupMenu(@Nonnull Component invoker, @Nonnull Point location) {
if (isFocusable(invoker)) {
focusAndWaitForFocusGain(invoker);
}
click(invoker, location, RIGHT_BUTTON, 1);
JPopupMenu popup = findActivePopupMenu();
if (popup == null) {
throw new ComponentLookupException(concat("Unable to show popup at ", location, " on ", inEdtFormat(invoker)));
}
long start = currentTimeMillis();
while (!isWindowAncestorReadyForInput(popup) && currentTimeMillis() - start > POPUP_DELAY) {
pause();
}
return popup;
}
@RunsInEDT
private boolean isWindowAncestorReadyForInput(final JPopupMenu popup) {
Boolean result = execute(new GuiQuery<Boolean>() {
@Override
protected Boolean executeInEDT() {
Window ancestor = checkNotNull(getWindowAncestor(popup));
return isReadyForInput(ancestor);
}
});
return checkNotNull(result);
}
/**
* <p>
* Indicates whether the given AWT or Swing {@code Component} is ready for input.
* </p>
*
* <p>
* <b>Note:</b> This method is accessed in the current executing thread. Such thread may or may not be the event
* dispatch thread (EDT.) Client code must call this method from the EDT.
* </p>
*
* @param c the given {@code Component}.
* @return {@code true} if the given {@code Component} is ready for input, {@code false} otherwise.
* @throws ActionFailedException if the given {@code Component} does not have a {@code Window} ancestor.
*/
@Override
@RunsInCurrentThread
public boolean isReadyForInput(@Nonnull Component c) {
Window w = windowAncestorOf(c);
if (w == null) {
throw actionFailure(concat("Component ", format(c), " does not have a Window ancestor"));
}
return c.isShowing() && windowMonitor.isWindowReady(w);
}
@RunsInEDT
@Override
public @Nullable JPopupMenu findActivePopupMenu() {
JPopupMenu popup = activePopupMenu();
if (popup != null || isEventDispatchThread()) {
return popup;
}
TimeoutWatch watch = startWatchWithTimeoutOf(POPUP_TIMEOUT);
while ((popup = activePopupMenu()) == null) {
if (watch.isTimeOut()) {
break;
}
pause(100);
}
return popup;
}
@RunsInEDT
private @Nullable JPopupMenu activePopupMenu() {
List<Component> found = newArrayList(finder().findAll(POPUP_MATCHER));
if (found.size() == 1) {
return (JPopupMenu) found.get(0);
}
return null;
}
@RunsInEDT
@Override
public void requireNoJOptionPaneIsShowing() {
unexpectedJOptionPaneFinder.requireNoJOptionPaneIsShowing();
}
@Override
public @Nonnull Settings settings() {
return settings;
}
@Override
public @Nonnull ComponentHierarchy hierarchy() {
return hierarchy;
}
@Override
public synchronized boolean isActive() {
return active;
}
@VisibleForTesting
final @Nullable Object screenLockOwner() {
return screenLockOwner;
}
}
| 30.93956 | 119 | 0.703498 |
e999a8d882e4d2d873ee9c1fd5169169b5d689d8 | 544 | package raznorazno;
public class razno {
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
int p = prastevilo(n);
System.out.println(p);
}
private static int prastevilo(int n) {
int[] pra = new int[n];
pra[0] = 2;
int p = 3;
for (int i = 1; i < n; i+=1) {
int j = 0;
while (pra[i]==0){
if (p%pra[j]!=0 && j==i-1){
pra[i]=p;
}
else if (j==i-1 || p%pra[j]==0){
j=-1;
p+=2;
}
j+=1;
}
p+=2;
}
return pra[n-1];
}
}
| 16 | 42 | 0.457721 |
82469abe87aea60e9c6d4ec87c413d5a6a80e04d | 1,260 | package dsi;
import dsi.FileSystemTreeModel;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.io.IOException;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class FileSystemTreeModelTest {
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
@Before
public void createTestData() throws IOException {
String tempPath = tempFolder.getRoot().toString();
//System.out.format("created temp folder: %s", tempPath);
tempFolder.newFile("empty.txt");
File f1 = tempFolder.newFolder("f1");
new File(f1, "a.txt");
File f2 = tempFolder.newFolder("f2");
new File(f2, "b.txt");
new File(f2, "c.txt");
File f3 = new File(f2, "f3");
f3.mkdir();
}
@Test
public void testGetRoot() throws Exception {
FileSystemTreeModel fileSystemTreeModel = new FileSystemTreeModel(tempFolder.getRoot().getPath());
assertThat(fileSystemTreeModel.getRoot().toString(),is(tempFolder.getRoot().getName()));
assertThat(fileSystemTreeModel.getChildCount(fileSystemTreeModel.getRoot()),is(3));
}
}
| 27.391304 | 106 | 0.683333 |
27eef298500468bfab0bb86235e7b742b7828c4a | 5,425 | /*
* Copyright (C) 2010-2015 FBReader.ORG Limited <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
package org.geometerplus.android.fbreader.dict;
import com.github.johnpersano.supertoasts.SuperActivityToast;
import com.github.johnpersano.supertoasts.SuperToast;
import com.github.johnpersano.supertoasts.util.OnClickWrapper;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Parcelable;
import android.view.View;
import org.geometerplus.zlibrary.core.resources.ZLResource;
import org.geometerplus.android.fbreader.FBReaderMainActivity;
final class Dictan extends DictionaryUtil.PackageInfo {
private static final int MAX_LENGTH_FOR_TOAST = 180;
Dictan(String id, String title) {
super(id, title);
}
@Override
void open(String text, Runnable outliner, FBReaderMainActivity fbreader, DictionaryUtil.PopupFrameMetric frameMetrics) {
final Intent intent = getActionIntent(text);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
intent.putExtra("article.mode", 20);
intent.putExtra("article.text.size.max", MAX_LENGTH_FOR_TOAST);
try {
fbreader.startActivityForResult(intent, FBReaderMainActivity.REQUEST_DICTIONARY);
fbreader.overridePendingTransition(0, 0);
if (outliner != null) {
outliner.run();
}
} catch (ActivityNotFoundException e) {
InternalUtil.installDictionaryIfNotInstalled(fbreader, this);
}
}
void onActivityResult(final FBReaderMainActivity fbreader, int resultCode, final Intent data) {
if (data == null) {
fbreader.hideDictionarySelection();
return;
}
final int errorCode = data.getIntExtra("error.code", -1);
if (resultCode != FBReaderMainActivity.RESULT_OK || errorCode != -1) {
showError(fbreader, errorCode, data);
return;
}
String text = data.getStringExtra("article.text");
if (text == null) {
showError(fbreader, -1, data);
return;
}
// a hack for obsolete (before 5.0 beta) dictan versions
final int index = text.indexOf("\000");
if (index >= 0) {
text = text.substring(0, index);
}
final boolean hasExtraData;
if (text.length() == MAX_LENGTH_FOR_TOAST) {
text = trimArticle(text);
hasExtraData = true;
} else {
hasExtraData = data.getBooleanExtra("article.resources.contains", false);
}
final SuperActivityToast toast;
if (hasExtraData) {
toast = new SuperActivityToast(fbreader, SuperToast.Type.BUTTON);
toast.setButtonIcon(
android.R.drawable.ic_menu_more,
ZLResource.resource("toast").getResource("more").getValue()
);
toast.setOnClickWrapper(new OnClickWrapper("dict", new SuperToast.OnClickListener() {
@Override
public void onClick(View view, Parcelable token) {
final String word = data.getStringExtra("article.word");
final Intent intent = getActionIntent(word);
try {
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
fbreader.startActivity(intent);
fbreader.overridePendingTransition(0, 0);
} catch (ActivityNotFoundException e) {
// ignore
}
}
}));
} else {
toast = new SuperActivityToast(fbreader, SuperToast.Type.STANDARD);
}
toast.setText(text);
toast.setDuration(DictionaryUtil.TranslationToastDurationOption.getValue().Value);
InternalUtil.showToast(toast, fbreader);
}
private static String trimArticle(String text) {
final int len = text.length();
final int eolIndex = text.lastIndexOf("\n");
final int spaceIndex = text.lastIndexOf(" ");
if (spaceIndex < eolIndex || eolIndex >= len * 2 / 3) {
return text.substring(0, eolIndex);
} else {
return text.substring(0, spaceIndex);
}
}
private static void showError(final FBReaderMainActivity fbreader, int code, Intent data) {
final ZLResource resource = ZLResource.resource("dictanErrors");
String message;
switch (code) {
default:
message = data.getStringExtra("error.message");
if (message == null) {
message = resource.getResource("unknown").getValue();
}
break;
case 100:
{
final String word = data.getStringExtra("article.word");
message = resource.getResource("noArticle").getValue().replaceAll("%s", word);
break;
}
case 130:
message = resource.getResource("cannotOpenDictionary").getValue();
break;
case 131:
message = resource.getResource("noDictionarySelected").getValue();
break;
}
final SuperActivityToast toast = new SuperActivityToast(fbreader, SuperToast.Type.STANDARD);
toast.setText("Dictan: " + message);
toast.setDuration(DictionaryUtil.ErrorToastDurationOption.getValue().Value);
InternalUtil.showToast(toast, fbreader);
}
}
| 33.695652 | 121 | 0.731244 |
52870ce7f1d637db06f3032ecb24742701aeed64 | 6,361 | package com.hotbitmapgg.ohmybilibili.module.common;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.hotbitmapgg.ohmybilibili.R;
import com.hotbitmapgg.ohmybilibili.base.RxAppCompatBaseActivity;
import com.hotbitmapgg.ohmybilibili.widget.CircleProgressView;
import butterknife.Bind;
/**
* Created by hcc on 16/8/7 14:12
* [email protected]
* <p/>
* 浏览器界面
*/
public class WebActivity extends RxAppCompatBaseActivity implements DownloadListener
{
@Bind(R.id.toolbar)
Toolbar mToolbar;
@Bind(R.id.circle_progress)
CircleProgressView progressBar;
@Bind(R.id.webView)
WebView mWebView;
private final Handler mHandler = new Handler();
private String url, mTitle;
private WebViewClientBase webViewClient = new WebViewClientBase();
private static final String EXTRA_URL = "url";
private static final String EXTRA_TITLE = "title";
@Override
public int getLayoutId()
{
return R.layout.activity_web;
}
@Override
public void initViews(Bundle savedInstanceState)
{
Intent intent = getIntent();
if (intent != null)
{
url = intent.getStringExtra(EXTRA_URL);
mTitle = intent.getStringExtra(EXTRA_TITLE);
}
setupWebView();
}
@Override
public void initToolBar()
{
mToolbar.setNavigationIcon(R.drawable.action_button_back_pressed_light);
mToolbar.setTitle(mTitle == null ? "详情" : mTitle);
mToolbar.setNavigationOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
onBackPressed();
}
});
}
public static void launch(Activity activity, String url, String title)
{
Intent intent = new Intent(activity, WebActivity.class);
intent.putExtra(EXTRA_URL, url);
intent.putExtra(EXTRA_TITLE, title);
activity.startActivity(intent);
}
@SuppressLint("SetJavaScriptEnabled")
private void setupWebView()
{
progressBar.spin();
final WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
webSettings.setDomStorageEnabled(true);
webSettings.setGeolocationEnabled(true);
webSettings.setUseWideViewPort(true);
webSettings.setLoadWithOverviewMode(true);
mWebView.getSettings().setRenderPriority(RenderPriority.HIGH);
mWebView.getSettings().setBlockNetworkImage(true);
mWebView.setWebViewClient(webViewClient);
mWebView.requestFocus(View.FOCUS_DOWN);
mWebView.setDownloadListener(this);
mWebView.getSettings().setDefaultTextEncodingName("UTF-8");
mWebView.setWebChromeClient(new WebChromeClient()
{
@Override
public boolean onJsAlert(WebView view, String url, String message, final JsResult result)
{
AlertDialog.Builder b2 = new AlertDialog
.Builder(WebActivity.this)
.setTitle(R.string.app_name)
.setMessage(message)
.setPositiveButton("确定", new AlertDialog.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
result.confirm();
}
});
b2.setCancelable(false);
b2.create();
b2.show();
return true;
}
});
mWebView.loadUrl(url);
}
public class WebViewClientBase extends WebViewClient
{
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
super.onPageStarted(view, url, favicon);
}
@Override
public void onPageFinished(WebView view, String url)
{
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
progressBar.stopSpinning();
mWebView.getSettings().setBlockNetworkImage(false);
}
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
{
super.onReceivedError(view, errorCode, description, failingUrl);
String errorHtml = "<html><body><h2>找不到网页</h2></body></html>";
view.loadDataWithBaseURL(null, errorHtml, "text/html", "UTF-8", null);
}
}
@Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype, long contentLength)
{
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
try
{
startActivity(intent);
return;
} catch (ActivityNotFoundException e)
{
e.printStackTrace();
}
}
public void initialize()
{
mHandler.post(new Runnable()
{
@Override
public void run()
{
mWebView.loadUrl("javascript:initialize()");
}
});
}
@Override
protected void onPause()
{
mWebView.reload();
super.onPause();
}
@Override
protected void onDestroy()
{
mWebView.destroy();
mHandler.removeCallbacksAndMessages(null);
super.onDestroy();
}
}
| 26.615063 | 103 | 0.617985 |
dc89844f6c0bca1085c7ae092f9261e5264f08a9 | 3,666 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.videoanalyzer.fluent.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.management.ProxyResource;
import com.azure.core.management.SystemData;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.videoanalyzer.models.AccessPolicyRole;
import com.azure.resourcemanager.videoanalyzer.models.AuthenticationBase;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
/** Access policies help define the authentication rules, and control access to specific video resources. */
@Fluent
public final class AccessPolicyEntityInner extends ProxyResource {
@JsonIgnore private final ClientLogger logger = new ClientLogger(AccessPolicyEntityInner.class);
/*
* The resource properties.
*/
@JsonProperty(value = "properties")
private AccessPolicyProperties innerProperties;
/*
* Azure Resource Manager metadata containing createdBy and modifiedBy
* information.
*/
@JsonProperty(value = "systemData", access = JsonProperty.Access.WRITE_ONLY)
private SystemData systemData;
/**
* Get the innerProperties property: The resource properties.
*
* @return the innerProperties value.
*/
private AccessPolicyProperties innerProperties() {
return this.innerProperties;
}
/**
* Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information.
*
* @return the systemData value.
*/
public SystemData systemData() {
return this.systemData;
}
/**
* Get the role property: Defines the access level granted by this policy.
*
* @return the role value.
*/
public AccessPolicyRole role() {
return this.innerProperties() == null ? null : this.innerProperties().role();
}
/**
* Set the role property: Defines the access level granted by this policy.
*
* @param role the role value to set.
* @return the AccessPolicyEntityInner object itself.
*/
public AccessPolicyEntityInner withRole(AccessPolicyRole role) {
if (this.innerProperties() == null) {
this.innerProperties = new AccessPolicyProperties();
}
this.innerProperties().withRole(role);
return this;
}
/**
* Get the authentication property: Authentication method to be used when validating client API access.
*
* @return the authentication value.
*/
public AuthenticationBase authentication() {
return this.innerProperties() == null ? null : this.innerProperties().authentication();
}
/**
* Set the authentication property: Authentication method to be used when validating client API access.
*
* @param authentication the authentication value to set.
* @return the AccessPolicyEntityInner object itself.
*/
public AccessPolicyEntityInner withAuthentication(AuthenticationBase authentication) {
if (this.innerProperties() == null) {
this.innerProperties = new AccessPolicyProperties();
}
this.innerProperties().withAuthentication(authentication);
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
if (innerProperties() != null) {
innerProperties().validate();
}
}
}
| 33.633028 | 116 | 0.693672 |
5a6a5b844c76d6cc34de2d25fe25deb06bdb419e | 2,324 | /*
* 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.taverna.workbench.file.impl;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import org.apache.taverna.workbench.file.AbstractDataflowPersistenceHandler;
import org.apache.taverna.workbench.file.DataflowInfo;
import org.apache.taverna.workbench.file.DataflowPersistenceHandler;
import org.apache.taverna.workbench.file.FileType;
import org.apache.taverna.workbench.file.exceptions.OpenException;
import org.apache.taverna.scufl2.api.container.WorkflowBundle;
import org.apache.taverna.scufl2.api.core.Workflow;
/**
* @author alanrw
*/
public class DataflowFromDataflowPersistenceHandler extends
AbstractDataflowPersistenceHandler implements
DataflowPersistenceHandler {
private static final WorkflowBundleFileType WORKFLOW_BUNDLE_FILE_TYPE = new WorkflowBundleFileType();
@Override
public DataflowInfo openDataflow(FileType fileType, Object source)
throws OpenException {
if (!getOpenFileTypes().contains(fileType))
throw new IllegalArgumentException("Unsupported file type "
+ fileType);
WorkflowBundle workflowBundle = (WorkflowBundle) source;
Date lastModified = null;
Object canonicalSource = null;
return new DataflowInfo(WORKFLOW_BUNDLE_FILE_TYPE, canonicalSource,
workflowBundle, lastModified);
}
@Override
public List<FileType> getOpenFileTypes() {
return Arrays.<FileType> asList(WORKFLOW_BUNDLE_FILE_TYPE);
}
@Override
public List<Class<?>> getOpenSourceTypes() {
return Arrays.<Class<?>> asList(Workflow.class);
}
}
| 36.888889 | 102 | 0.789157 |
a4d77d753558f63293b63594b7728dfad232ed9c | 1,541 | package com.sysu.cloudgaminghub.hub.portalnetwork;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AuthServlet extends HttpServlet{
/**
*
*/
private final static String USERNAME1="test";
private final static String PASSWORD1="test";
private final static String USERNAME2="test1";
private final static String PASSWORD2="test1";
private static final long serialVersionUID = -5753953317338913902L;
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
execute(req,resp);
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
execute(req,resp);
}
private void execute(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
PrintWriter writer= resp.getWriter();
String username=req.getParameter("username");
String password=req.getParameter("password");
if(username==null||password==null)
{
writer.print("{\"errorCode\":0,\"successful\":false}");
return;
}
if((username.equals(USERNAME1)&&password.equals(PASSWORD1))||(username.equals(USERNAME2)&&password.equals(PASSWORD2)))
{
writer.print("{\"errorCode\":0,\"successful\":true}");
}
else
{
writer.print("{\"errorCode\":0,\"successful\":false}");
}
}
}
| 30.215686 | 120 | 0.740428 |
43da5d42b57e89bab58dee4785657dc44e937fe2 | 614 | package io.renren.modules.hotel.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
*
*
* @author taoz
* @email [email protected]
* @date 2019-09-18 20:38:22
*/
@Data
@TableName("t_hotel_protocol")
public class HotelProtocolEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
*
*/
@TableId
private Long id;
/**
* 名称
*/
private String name;
/**
* 协议内容
*/
private String content;
private String code;
}
| 15.74359 | 58 | 0.710098 |
488b0844e4cf8a0619994fd41541c53c80b6b0dc | 1,549 | package com.cognizant.cognizantits.qcconnection.qcupdation;
import com4j.Com4jObject;
import com4j.DISPID;
import com4j.DefaultValue;
import com4j.IID;
import com4j.NativeType;
import com4j.Optional;
import com4j.ReturnValue;
import com4j.VTID;
@IID("{35692E1B-C235-426A-A77B-CD0D159C4F2E}")
public abstract interface IReq2
extends IReq
{
@DISPID(37)
@VTID(54)
@ReturnValue(type=NativeType.Dispatch)
public abstract Com4jObject reqTraceFactory(int paramInt);
@DISPID(38)
@VTID(55)
public abstract boolean hasReqTraceability(int paramInt);
@DISPID(39)
@VTID(56)
@ReturnValue(type=NativeType.Dispatch)
public abstract Com4jObject requirementType();
@DISPID(40)
@VTID(57)
public abstract String typeId();
@DISPID(40)
@VTID(58)
public abstract void typeId(String paramString);
@DISPID(41)
@VTID(59)
public abstract IStream get_Icon();
@DISPID(42)
@VTID(60)
public abstract int parentId();
@DISPID(42)
@VTID(61)
public abstract void parentId(int paramInt);
@DISPID(43)
@VTID(62)
public abstract void populateTargetCycleToChildren();
@DISPID(44)
@VTID(63)
public abstract void populateTargetReleaseToChildren();
@DISPID(45)
@VTID(64)
public abstract boolean hasRichContent();
@DISPID(46)
@VTID(65)
public abstract IList getCoverageTestsByReqFilter(String paramString, @Optional @DefaultValue("0") boolean paramBoolean);
}
/* Location: D:\Prabu\jars\QC.jar
* Qualified Name: qcupdation.IReq2
* JD-Core Version: 0.7.0.1
*/ | 21.816901 | 123 | 0.719819 |
3f1fccc8bfc101b7a2f2ae89221feb51c645beed | 1,217 | package co.hrsquare.bindad.mapper;
import co.hrsquare.bindad.model.company.Department;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface IDepartmentMapper {
@Insert("insert into tbl_department (client_id, company_id, public_id, full_name, short_name, is_deleted, updated_by, updated_time) " +
"select " +
"#{client.id}, " +
"#{company.id}, " +
"#{publicId}, " +
"#{fullName}, " +
"#{shortName}, " +
"#{deleted}, " +
"#{updatedBy}, " +
"#{updatedTime}")
void insert(Department department);
@Select("select id from tbl_department where full_name=#{fullName}")
Long findId(Department department);
@Delete("delete from tbl_department " +
"where client_id = #{clientId}")
void deleteByClientId(long clientId);
@Delete("delete from tbl_department " +
"where client_id = #{clientId} " +
"and company_id = #{companyId}")
void deleteByClientAndCompanyId(long clientId, long companyId);
}
| 32.891892 | 139 | 0.63599 |
fc7ff7b64bdc5fedcc56600ae7442c10855b3bdf | 1,356 | package garden.druid.pool.endpoints.admin;
import java.util.ArrayList;
import java.util.Collection;
import javax.servlet.annotation.WebServlet;
import garden.druid.base.http.auth.api.UserLevel;
import garden.druid.base.http.rest.RestEndpoint;
import garden.druid.base.http.rest.annotation.Consumes;
import garden.druid.base.http.rest.annotation.POST;
import garden.druid.base.http.rest.annotation.RequireAuthenticator;
import garden.druid.base.http.rest.annotation.RequireUserLevel;
import garden.druid.base.http.rest.annotation.RestPattern;
import garden.druid.base.http.rest.annotation.ReturnType;
import garden.druid.base.http.rest.enums.ConsumerTypes;
import garden.druid.base.http.rest.enums.ReturnTypes;
import garden.druid.pool.Pool;
import garden.druid.pool.types.FarmerPayoutRecord;
@WebServlet(value = { "/api/admin/v1/farmerpayouts" })
@RestPattern( uri = "/api/admin/v1/farmerpayouts")
@RequireAuthenticator()
@RequireUserLevel( level = UserLevel.ADMIN)
public class FarmerPayoutProcessorEndpoint extends RestEndpoint {
private static final long serialVersionUID = 1L;
@POST
@ReturnType(type=ReturnTypes.JSON)
@Consumes(consumer=ConsumerTypes.NONE)
public Collection<ArrayList<FarmerPayoutRecord>> runUpdateBalance() {
Pool.getInstance().runFarmerPayoutProcessor();
return Pool.getInstance().getPending_farmer_payments();
}
}
| 36.648649 | 70 | 0.816372 |
0223bdc60814140f0236f3e19d3ba1f50cb2cac7 | 3,253 | /*
* Copyright (C) 2013-2016 Rinde van Lon, iMinds-DistriNet, KU Leuven
*
* 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.github.rinde.logistics.pdptw.mas.comm;
import static com.google.common.base.Verify.verifyNotNull;
import static com.google.common.collect.Lists.newArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.rinde.rinsim.core.model.Model.AbstractModel;
import com.github.rinde.rinsim.core.model.ModelProvider;
import com.github.rinde.rinsim.core.model.ModelReceiver;
import com.github.rinde.rinsim.core.model.pdp.PDPModel;
import com.github.rinde.rinsim.core.model.pdp.PDPModel.PDPModelEventType;
import com.github.rinde.rinsim.core.model.pdp.PDPModelEvent;
import com.github.rinde.rinsim.core.model.pdp.Parcel;
import com.github.rinde.rinsim.event.Event;
import com.github.rinde.rinsim.event.Listener;
import com.google.common.base.Optional;
/**
* This class provides a common base for classes that implement a communication
* strategy between a set of {@link Communicator}s. There are currently two
* implementations, blackboard communication ({@link BlackboardCommModel}) and
* auctioning ({@link AuctionCommModel}).
* @author Rinde van Lon
* @param <T> The type of {@link Communicator} this model expects.
*/
public abstract class AbstractCommModel<T extends Communicator> extends
AbstractModel<T> implements ModelReceiver {
/**
* The logger.
*/
protected static final Logger LOGGER = LoggerFactory
.getLogger(AbstractCommModel.class);
/**
* The list of registered communicators.
*/
protected List<T> communicators;
/**
* New instance.
*/
protected AbstractCommModel() {
communicators = newArrayList();
}
@Override
public void registerModelProvider(ModelProvider mp) {
final PDPModel pm = Optional.fromNullable(mp.getModel(PDPModel.class))
.get();
pm.getEventAPI().addListener(new Listener() {
@Override
public void handleEvent(Event e) {
final PDPModelEvent event = (PDPModelEvent) e;
final Parcel dp = event.parcel;
receiveParcel(verifyNotNull(dp), event.time);
}
}, PDPModelEventType.NEW_PARCEL);
}
/**
* Subclasses can define their own parcel handling strategy in this method.
* @param p The new {@link Parcel} that becomes available.
* @param time The current time.
*/
protected abstract void receiveParcel(Parcel p, long time);
@Override
public boolean register(final T communicator) {
LOGGER.trace("register {}", communicator);
communicators.add(communicator);
return true;
}
@Override
public boolean unregister(T element) {
throw new UnsupportedOperationException();
}
}
| 33.536082 | 79 | 0.738088 |
145183be8f2a77d9df9d8fa220c877a71a6cfe6d | 273 | package com.caidong.common.http.entity.request;
public class BaseRequest {
protected String requestCode;
public String getRequestCode() {
return requestCode;
}
public void setRequestCode(String requestCode) {
this.requestCode = requestCode;
}
}
| 18.2 | 50 | 0.725275 |
5d79e35ec9df80670eb2186796ce64121542562c | 4,205 | package integration;
import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import org.apache.commons.io.FileUtils;
import org.w3c.dom.Document;
import main.Files2Facts;
import util.ConfigManager;
/**
* Integrates Two AutomationML(ML) files based on PSL Rules.
*
* @author omar
*/
public class Integration {
private XMLParser xml;
public static int count = 0;
ArrayList<File> file;
public Integration() {
xml = new XMLParser();
}
/**
* This method integrates two AML files.
*
* @throws Throwable
*/
public void integrate() throws Throwable {
Files2Facts filesAMLInRDF = new Files2Facts();
// gets heterogeneity files in array.
file = filesAMLInRDF.readFiles(ConfigManager.getFilePath(), ".aml", ".opcua", ".xml");
String contents = FileUtils.readFileToString(new File(file.get(1).getPath()), "UTF-8");
new File(ConfigManager.getFilePath() + "integration/").mkdir();
// One of the AML file will have its contents copied as it is.
PrintWriter outputWriter;
if (file.get(1).getName().endsWith(".aml")) {
outputWriter = new PrintWriter(
new File(ConfigManager.getFilePath() + "integration/integration.aml"));
} else {
outputWriter = new PrintWriter(
new File(ConfigManager.getFilePath() + "integration/integration.opcua"));
}
outputWriter.println(contents);
outputWriter.close();
// initializing documents.
Document seed = xml.initInput(file.get(0).getPath());
Document integration;
if (file.get(0).getName().endsWith(".aml") && file.get(1).getName().endsWith(".aml")) {
integration = xml
.initInput(ConfigManager.getFilePath() + "integration/integration.aml");
} else {
integration = xml
.initInput(ConfigManager.getFilePath() + "integration/integration.opcua");
}
processNodesArributes(seed, integration);
processNodesValues(seed, integration);
}
/**
* This function integrates data for nodes with Attributes. It compares
* elements with similar.txt and skips those which are already there.
* Conflicted Elements are added in to the final integration file.
*
* @param seed
* @param integration
* @throws Throwable
*/
public void processNodesArributes(Document seed, Document integration) throws Throwable {
xml.getAllNodes(seed, integration);
// looping through the seedNode which will be compared to matching
// elements in similar.txt
for (int i = 0; i < xml.getSeedNodes().size(); i++) {
// not in the conflicting Element of similar.txt
if (xml.compareConflicts(i, seed, integration) == 0) {
// we run our noConflicting comparision algorithm
if (xml.compareNonConflicts(i, seed, integration) != 1) {
// if its identified its not in integration.aml
// We need to add non match elements to the integration
// file.
xml.addNonConflicts(i, seed, integration);
}
}
}
// update the integration.aml file
xml.finalizeIntegration(integration, file.get(0).getName());
}
/**
* This function integrates data for nodes with values. It compares elements
* with similar.txt and skips those which are already there. Conflicted
* Elements are added in to the final integration file.
*
* compareConflicts(skips compared one),compareNonConflictsNodes with
* value,addNonConflicts
*
* @param seed
* @param integration
* @throws Throwable
*/
void processNodesValues(Document seed, Document integration) throws Throwable {
// update for node values, array's updated.
xml.setNodeValues(seed, integration);
// looping through the seedNode which will be compared to matching
// elements in similar.txt
for (int i = 0; i < xml.getSeedNodes().size(); i++) {
// not in the conflicting Element of similar.txt
if (xml.compareConflicts(i, seed, integration) == 0) {
// we run our noConflicting comparision algorithm
if (xml.compareNonConflictsValues(i, seed, integration) != 1) {
// if its identified its not in integration.aml
// We need to add only non matched elements to the
// integration file.
xml.addNonConflictsValues(i, seed, integration);
}
}
}
xml.finalizeIntegration(integration, file.get(0).getName());
}
} | 26.955128 | 90 | 0.702735 |
b6e1b3fa3559350010eeec7c68d7caa7d30aeb1b | 3,429 | /*-------------------------------------------------------------------------+
| |
| Copyright 2005-2011 The ConQAT 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 org.conqat.engine.java.junit;
import org.conqat.engine.commons.ConQATPipelineProcessorBase;
import org.conqat.engine.commons.node.NodeConstants;
import org.conqat.engine.commons.node.NodeUtils;
import org.conqat.engine.core.core.AConQATKey;
import org.conqat.engine.core.core.AConQATProcessor;
import org.conqat.lib.commons.assessment.Assessment;
import org.conqat.lib.commons.assessment.ETrafficLightColor;
/**
* This processor assess JUnit results. Suites with errors or failures are rated
* red, others green. Assessments are aggregated and set as summary.
*
* @author Florian Deissenboeck
* @author $Author: kinnen $
* @version $Rev: 41751 $
* @ConQAT.Rating GREEN Hash: 8B6389C92C26F3F0FDFAC2D63372F28F
*/
@AConQATProcessor(description = "This processor assess JUnit results. "
+ " Suites with errors or failures are rated red, others green. "
+ " Assessments are aggregated and set as summary.")
public class JUnitAssessor extends ConQATPipelineProcessorBase<JUnitResultNode> {
/** The key to use for saving the <code>Assessment</code>. */
@AConQATKey(description = "Key for assessment", type = "org.conqat.lib.commons.assessment.Assessment")
public static final String ASSESSMENT_KEY = "JUnit-Assessment";
/** {@inheritDoc} */
@Override
protected void processInput(JUnitResultNode input) {
NodeUtils.addToDisplayList(input, ASSESSMENT_KEY);
Assessment rootAssessment = new Assessment();
input.setValue(ASSESSMENT_KEY, rootAssessment);
input.setValue(NodeConstants.SUMMARY, rootAssessment);
for (JUnitTestSuiteNode testSuite : input.getChildren()) {
Assessment suiteAssessment = assess(testSuite);
rootAssessment.add(suiteAssessment);
testSuite.setValue(ASSESSMENT_KEY, suiteAssessment);
}
}
/**
* Determine assessment for a single test suite. Failure and error are added
* as red assessments.
*/
private Assessment assess(JUnitTestSuiteNode testSuite) {
Assessment result = new Assessment();
int reds = testSuite.getErrorCount() + testSuite.getFailureCount();
int greens = testSuite.getTestCount() - reds;
result.add(ETrafficLightColor.RED, reds);
result.add(ETrafficLightColor.GREEN, greens);
return result;
}
} | 46.337838 | 103 | 0.625838 |
ef79e556539df929bbc3bf278452230a28b1df0a | 307 | package fr.mrcubee.plugin.util.spigot.annotations;
import fr.mrcubee.annotation.spigot.config.ConfigAnnotation;
import org.bukkit.plugin.Plugin;
public class PluginAnnotations {
public static void load(Plugin plugin, Object... objects) {
ConfigAnnotation.loadClass(plugin.getConfig(), objects);
}
}
| 23.615385 | 60 | 0.791531 |
9a74a84a8d5181a2b7c38eae2d96d4aab3874b26 | 761 | package cz.tvrzna.pointy.exceptions;
/**
* The Class BadRequestException.
*
* @author michalt
*/
public class BadRequestException extends RuntimeException
{
private static final long serialVersionUID = 200146466614564185L;
/**
* Instantiates a new bad request exception.
*/
public BadRequestException()
{
super();
}
/**
* Instantiates a new bad request exception.
*
* @param message
* the message
*/
public BadRequestException(String message)
{
super(message);
}
/**
* Instantiates a new bad request exception.
*
* @param message
* the message
* @param throwable
* the throwable
*/
public BadRequestException(String message, Throwable throwable)
{
super(message, throwable);
}
}
| 17.295455 | 66 | 0.674113 |
520afbdf520c3a4a34fa2a0b10343395ed6d5cb3 | 2,758 | /*
* 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.submarine.runtimes.yarnservice.pytorch;
import java.io.IOException;
import org.apache.submarine.client.cli.param.runjob.PyTorchRunJobParameters;
import org.apache.submarine.client.cli.runjob.Framework;
import org.apache.submarine.common.ClientContext;
import org.apache.submarine.runtimes.yarnservice.AbstractServiceSpec;
import org.apache.submarine.runtimes.yarnservice.FileSystemOperations;
import org.apache.submarine.runtimes.yarnservice.ServiceWrapper;
import org.apache.submarine.runtimes.yarnservice.command.PyTorchLaunchCommandFactory;
import org.apache.submarine.utils.Localizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class contains all the logic to create an instance
* of a {Service} object for PyTorch.
* Please note that currently, only single-node (non-distributed)
* support is implemented for PyTorch.
*/
public class PyTorchServiceSpec extends AbstractServiceSpec {
private static final Logger LOG =
LoggerFactory.getLogger(PyTorchServiceSpec.class);
//this field is needed in the future!
private final PyTorchRunJobParameters pyTorchParameters;
public PyTorchServiceSpec(PyTorchRunJobParameters parameters,
ClientContext clientContext, FileSystemOperations fsOperations,
PyTorchLaunchCommandFactory launchCommandFactory, Localizer localizer) {
super(parameters, clientContext, fsOperations, launchCommandFactory,
localizer);
this.pyTorchParameters = parameters;
}
@Override
public ServiceWrapper create() throws IOException {
LOG.info("Creating PyTorch service spec");
ServiceWrapper serviceWrapper = createServiceSpecWrapper();
if (parameters.getNumWorkers() > 0) {
addWorkerComponents(serviceWrapper, Framework.PYTORCH);
}
// After all components added, handle quicklinks
handleQuicklinks(serviceWrapper.getService());
return serviceWrapper;
}
}
| 40.558824 | 100 | 0.773387 |
3fef41681cb22a8e0335d57b1439846c4983da05 | 1,249 | package au.com.codeka.warworlds.client.game.empire;
import android.os.Bundle;
import au.com.codeka.warworlds.client.activity.TabbedBaseFragment;
import au.com.codeka.warworlds.client.game.fleets.FleetsFragment;
import au.com.codeka.warworlds.common.Log;
/**
* This fragment shows the status of the empire. You can see all your colonies, all your fleets, etc.
*/
public class EmpireFragment extends TabbedBaseFragment {
private static final Log log = new Log("EmpireFragment");
public static Bundle createArguments() {
Bundle bundle = new Bundle();
return bundle;
}
@Override
protected void createTabs() {
Bundle args = getArguments();
getTabManager().addTab(getContext(),
new TabInfo(this, "Overview", OverviewFragment.class, new Bundle()));
getTabManager().addTab(getContext(),
new TabInfo(this, "Colonies", ColoniesFragment.class, new Bundle()));
getTabManager().addTab(getContext(),
new TabInfo(this, "Build", BuildQueueFragment.class, new Bundle()));
getTabManager().addTab(getContext(),
new TabInfo(this, "Fleets", FleetsFragment.class, new Bundle()));
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
} | 33.756757 | 101 | 0.722978 |
9d2deed24ec0473ff5e53751b35b7ba84c54e891 | 10,723 | package us.ihmc.behaviors.tools;
import com.google.common.base.CaseFormat;
import controller_msgs.msg.dds.*;
import org.apache.commons.lang.WordUtils;
import us.ihmc.avatar.drcRobot.DRCRobotModel;
import us.ihmc.behaviors.BehaviorRegistry;
import us.ihmc.behaviors.tools.interfaces.MessagerPublishSubscribeAPI;
import us.ihmc.behaviors.tools.interfaces.StatusLogger;
import us.ihmc.behaviors.tools.walkingController.ControllerStatusTracker;
import us.ihmc.behaviors.tools.yo.YoBooleanClientHelper;
import us.ihmc.behaviors.tools.yo.YoDoubleClientHelper;
import us.ihmc.behaviors.tools.yo.YoVariableClientPublishSubscribeAPI;
import us.ihmc.behaviors.tools.yo.YoVariableClientHelper;
import us.ihmc.commons.thread.Notification;
import us.ihmc.commons.thread.TypedNotification;
import us.ihmc.communication.ROS2Tools;
import us.ihmc.communication.packets.ToolboxState;
import us.ihmc.humanoidRobotics.communication.packets.behaviors.BehaviorControlModeEnum;
import us.ihmc.humanoidRobotics.communication.packets.behaviors.CurrentBehaviorStatus;
import us.ihmc.humanoidRobotics.communication.packets.behaviors.HumanoidBehaviorType;
import us.ihmc.messager.Messager;
import us.ihmc.messager.MessagerAPIFactory.Topic;
import us.ihmc.messager.TopicListener;
import us.ihmc.ros2.ROS2NodeInterface;
import us.ihmc.ros2.ROS2Topic;
import us.ihmc.tools.thread.ActivationReference;
import us.ihmc.tools.thread.PausablePeriodicThread;
import us.ihmc.utilities.ros.ROS1Helper;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.DoubleSupplier;
import java.util.function.Function;
/**
* Class for entry methods for developing robot behaviors. The idea is to have this be the one-stop
* shopping location for everything one might want to do when creating a robot behavior. It should
* hide all of the network traffic. The methods should be a useful reminder to a behavior developer
* all of the things that one can do with the robots. This class will likely get too large
* eventually and need to be refactored into several classes. But until that time comes it should
* contain everything for interacting with: the robot actions (taking steps and achieving poses),
* robot sensing (reference frames, etc.), REA (getting planar regions), footstep planning, etc. At
* first we'll make this so that all of the things are created, even if you don't need them. But
* later, we'll make it so that they are created as needed. The main goal is to simplify and make
* clean the Behaviors themselves. The public interface of this class should be a joy to work with.
* The internals and all the things it relies on might be a nightmare, but the public API should not
* be.
*
* Open question: Trust vs. power vs. safety for/from behavior authors
*
* Robot:
* - Command-only
* - Status-only
* - Interactive (footstep completion, hand trajectory completion, etc.)
*
* UI Communication.
*
* Toolbox comms:
* - REA Input/Output
* - Footstep planner
*
* Helper tools (threading, etc.)
*
* TODO: Extract comms helper that does not have the behavior messager as part of it.
*/
public class BehaviorHelper extends CommunicationHelper implements MessagerPublishSubscribeAPI, YoVariableClientPublishSubscribeAPI
{
private final ROS1Helper ros1Helper;
private final MessagerHelper messagerHelper = new MessagerHelper(BehaviorRegistry.getActiveRegistry().getMessagerAPI());
private final YoVariableClientHelper yoVariableClientHelper;
private StatusLogger statusLogger;
private ControllerStatusTracker controllerStatusTracker;
// TODO: Considerations for ROS 1, Messager, and YoVariableClient with reconnecting
public BehaviorHelper(String titleCasedBehaviorName, DRCRobotModel robotModel, ROS2NodeInterface ros2Node)
{
this(titleCasedBehaviorName, robotModel, ros2Node, true);
}
public BehaviorHelper(String titleCasedBehaviorName,
DRCRobotModel robotModel,
ROS2NodeInterface ros2Node,
boolean commsEnabledToStart)
{
super(robotModel, ros2Node, commsEnabledToStart);
String ros1NodeName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, titleCasedBehaviorName.replace(" ", ""));
String yoVariableRegistryName = WordUtils.capitalize(titleCasedBehaviorName).replace(" ", "");
this.ros1Helper = new ROS1Helper(ros1NodeName);
yoVariableClientHelper = new YoVariableClientHelper(yoVariableRegistryName);
messagerHelper.setCommunicationCallbacksEnabled(commsEnabledToStart);
}
public StatusLogger getOrCreateStatusLogger()
{
if (statusLogger == null)
statusLogger = new StatusLogger(this::publish);
return statusLogger;
}
public ControllerStatusTracker getOrCreateControllerStatusTracker()
{
if (controllerStatusTracker == null)
controllerStatusTracker = new ControllerStatusTracker(getOrCreateStatusLogger(), getROS2Node(), getRobotModel().getSimpleRobotName());
return controllerStatusTracker;
}
// UI Communication Methods:
@Override
public DoubleSupplier subscribeToYoVariableDoubleValue(String variableName)
{
return yoVariableClientHelper.subscribeToYoVariableDoubleValue(variableName);
}
@Override
public void publishDoubleValueToYoVariable(String variableName, double value)
{
yoVariableClientHelper.publishDoubleValueToYoVariable(variableName, value);
}
@Override
public YoBooleanClientHelper subscribeToYoBoolean(String variableName)
{
return yoVariableClientHelper.subscribeToYoBoolean(variableName);
}
@Override
public YoDoubleClientHelper subscribeToYoDouble(String variableName)
{
return yoVariableClientHelper.subscribeToYoDouble(variableName);
}
@Override
public <T> void publish(Topic<T> topic, T message)
{
messagerHelper.publish(topic, message);
}
@Override
public void publish(Topic<Object> topic)
{
messagerHelper.publish(topic);
}
@Override
public ActivationReference<Boolean> subscribeViaActivationReference(Topic<Boolean> topic)
{
return messagerHelper.subscribeViaActivationReference(topic);
}
@Override
public <T> void subscribeViaCallback(Topic<T> topic, TopicListener<T> listener)
{
messagerHelper.subscribeViaCallback(topic, listener);
}
@Override
public <T> AtomicReference<T> subscribeViaReference(Topic<T> topic, T initialValue)
{
return messagerHelper.subscribeViaReference(topic, initialValue);
}
public <T> AtomicReference<T> subscribeViaReference(Function<String, ROS2Topic<T>> topicFunction, T initialValue)
{
AtomicReference<T> reference = new AtomicReference<>(initialValue);
ros2Helper.subscribeViaCallback(topicFunction, reference::set);
return reference;
}
@Override
public Notification subscribeTypelessViaNotification(Topic<Object> topic)
{
return messagerHelper.subscribeTypelessViaNotification(topic);
}
@Override
public void subscribeViaCallback(Topic<Object> topic, Runnable callback)
{
messagerHelper.subscribeViaCallback(topic, callback);
}
@Override
public <T extends K, K> TypedNotification<K> subscribeViaNotification(Topic<T> topic)
{
TypedNotification<K> typedNotification = new TypedNotification<>();
subscribeViaCallback(topic, typedNotification::set);
return typedNotification;
}
public void publishBehaviorControlMode(BehaviorControlModeEnum controlMode)
{
BehaviorControlModePacket behaviorControlModePacket = new BehaviorControlModePacket();
behaviorControlModePacket.setBehaviorControlModeEnumRequest(controlMode.toByte());
publish(ROS2Tools.getBehaviorControlModeTopic(getRobotModel().getSimpleRobotName()), behaviorControlModePacket);
}
public void publishBehaviorType(HumanoidBehaviorType type)
{
HumanoidBehaviorTypePacket humanoidBehaviorTypePacket = new HumanoidBehaviorTypePacket();
humanoidBehaviorTypePacket.setHumanoidBehaviorType(type.toByte());
publish(ROS2Tools.getBehaviorTypeTopic(getRobotModel().getSimpleRobotName()), humanoidBehaviorTypePacket);
}
public void publishToolboxState(Function<String, ROS2Topic<?>> robotNameConsumer, ToolboxState state)
{
ToolboxStateMessage toolboxStateMessage = new ToolboxStateMessage();
toolboxStateMessage.setRequestedToolboxState(state.toByte());
publish(robotNameConsumer.apply(getRobotModel().getSimpleRobotName()).withTypeName(ToolboxStateMessage.class), toolboxStateMessage);
}
public void subscribeToBehaviorStatusViaCallback(Consumer<CurrentBehaviorStatus> callback)
{
subscribeViaCallback(ROS2Tools.getBehaviorStatusTopic(getRobotModel().getSimpleRobotName()), behaviorStatusPacket ->
{
callback.accept(CurrentBehaviorStatus.fromByte(behaviorStatusPacket.getCurrentBehaviorStatus()));
});
}
public void subscribeToDoorLocationViaCallback(Consumer<DoorLocationPacket> callback)
{
subscribeViaCallback(ROS2Tools.getDoorLocationTopic(getRobotModel().getSimpleRobotName()), callback);
}
public void setCommunicationCallbacksEnabled(boolean enabled)
{
super.setCommunicationCallbacksEnabled(enabled);
messagerHelper.setCommunicationCallbacksEnabled(enabled);
}
public MessagerHelper getMessagerHelper()
{
return messagerHelper;
}
public Messager getMessager()
{
return messagerHelper.getMessager();
}
public ROS1Helper getROS1Helper()
{
return ros1Helper;
}
public YoVariableClientHelper getYoVariableClientHelper()
{
return yoVariableClientHelper;
}
// Behavior Helper Stuff:
// Thread and Schedule Methods:
// TODO: Track and auto start/stop threads?
public PausablePeriodicThread createPausablePeriodicThread(Class<?> clazz, double period, Runnable runnable)
{
return createPausablePeriodicThread(clazz.getSimpleName(), period, 0, runnable);
}
public PausablePeriodicThread createPausablePeriodicThread(Class<?> clazz, double period, int crashesBeforeGivingUp, Runnable runnable)
{
return createPausablePeriodicThread(clazz.getSimpleName(), period, crashesBeforeGivingUp, runnable);
}
public PausablePeriodicThread createPausablePeriodicThread(String name, double period, int crashesBeforeGivingUp, Runnable runnable)
{
return new PausablePeriodicThread(name, period, crashesBeforeGivingUp, runnable);
}
public void destroy()
{
super.destroy();
ros1Helper.destroy();
messagerHelper.disconnect();
yoVariableClientHelper.disconnect();
}
}
| 38.433692 | 143 | 0.770773 |
936fbecfbbc9998c4ef408ce37314eaed97b4615 | 90 | public class Hello{public static void main(String[] args){System.out.println("こんにちは世界");}} | 90 | 90 | 0.766667 |
36a1a03112209689538322dd3e8f05dd0ed372ae | 2,660 | /*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.cli.bundler.command;
import alluxio.Constants;
import alluxio.client.file.FileSystemContext;
import alluxio.conf.PropertyKey;
import alluxio.exception.AlluxioException;
import alluxio.util.CommonUtils;
import com.google.common.collect.ImmutableSet;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Set;
/**
* Command to collect Alluxio config files.
* */
public class CollectConfigCommand extends AbstractCollectInfoCommand {
public static final String COMMAND_NAME = "collectConfig";
private static final Logger LOG = LoggerFactory.getLogger(CollectConfigCommand.class);
private static final Set<String> EXCLUDED_FILE_PREFIXES = ImmutableSet.of(
Constants.SITE_PROPERTIES);
/**
* Creates a new instance of {@link CollectConfigCommand}.
*
* @param fsContext the {@link FileSystemContext} to execute in
* */
public CollectConfigCommand(FileSystemContext fsContext) {
super(fsContext);
}
@Override
public String getCommandName() {
return COMMAND_NAME;
}
@Override
public int run(CommandLine cl) throws AlluxioException, IOException {
mWorkingDirPath = getWorkingDirectory(cl);
String confDirPath = mFsContext.getClusterConf().get(PropertyKey.CONF_DIR);
File confDir = new File(confDirPath);
List<File> allFiles = CommonUtils.recursiveListLocalDir(confDir);
for (File f : allFiles) {
String filename = f.getName();
String relativePath = confDir.toURI().relativize(f.toURI()).getPath();
// Ignore file prefixes to exclude
if (EXCLUDED_FILE_PREFIXES.stream().anyMatch(filename::startsWith)) {
continue;
}
File targetFile = new File(mWorkingDirPath, relativePath);
FileUtils.copyFile(f, targetFile, true);
}
return 0;
}
@Override
public String getUsage() {
return "collectConfig <outputPath>";
}
@Override
public String getDescription() {
return "Collect Alluxio configurations files";
}
}
| 30.930233 | 98 | 0.741353 |
de6c7c7363fc002b2cdc13ac1038071a9a0365e6 | 320 | package com.morethanheroic.swords.tavern.domain.chat;
import com.morethanheroic.swords.user.domain.UserEntity;
import lombok.Builder;
import lombok.Getter;
import java.util.Date;
@Builder
@Getter
public class ChatEntry {
private UserEntity userEntity;
private String message;
private Date writingTime;
}
| 18.823529 | 56 | 0.7875 |
8d2cb4c5a8e4f66cf0622fa94c6dbe62508dbe63 | 4,581 | /*******************************************************************************
* Copyright 2016-2019 Francesco Benincasa ([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 sqlite.feature.javadoc.select.bean;
import java.util.List;
import com.abubusoft.kripton.android.annotation.BindContentProviderEntry;
import com.abubusoft.kripton.android.annotation.BindContentProviderEntry.MultiplicityResultType;
import com.abubusoft.kripton.android.sqlite.OnReadBeanListener;
import com.abubusoft.kripton.android.annotation.BindContentProviderPath;
import com.abubusoft.kripton.android.annotation.BindDao;
import com.abubusoft.kripton.android.annotation.BindSqlDynamicOrderBy;
import com.abubusoft.kripton.android.annotation.BindSqlDynamicWhere;
import com.abubusoft.kripton.android.annotation.BindSqlDynamicWhereParams;
import com.abubusoft.kripton.android.annotation.BindSqlParam;
import com.abubusoft.kripton.android.annotation.BindSqlSelect;
import sqlite.feature.javadoc.Person;
// TODO: Auto-generated Javadoc
/**
* The Interface SelectBeanPersonDao.
*/
@BindContentProviderPath(path = "persons")
@BindDao(Person.class)
public interface SelectBeanPersonDao {
/**
* select BEAN with no parameters.
*
* @return the list
*/
@BindContentProviderEntry
@BindSqlSelect
List<Person> selectAllBeans();
/**
* select BEAN with no parameters.
*
* @param bean the bean
* @return the int
*/
@BindContentProviderEntry(path = "a/${love.id}")
@BindSqlSelect(fields = "count(*)", where = " id=${love.id}")
int selectAllBeansCount(@BindSqlParam("love") Person bean);
/**
* select BEAN with one parameter.
*
* @param benza the benza
* @return the person
*/
@BindContentProviderEntry(path = "${bean.id}", multiplicityResult = MultiplicityResultType.ONE)
@BindSqlSelect(where = "id=${bean.id}")
Person selectOneBean(@BindSqlParam("bean") Person benza);
/**
* select BEAN with one parameter and dynamic where.
*
* @param bean the bean
* @param where the where
* @return the person
*/
@BindContentProviderEntry(path = "dynamic/${bean.id}")
@BindSqlSelect(fields = "personname", where = "id=${bean.id}")
Person selectOneBeanWithDynamic(Person bean, @BindSqlDynamicWhere String where);
/**
* select BEAN with one parameter and dynamic where and args.
*
* @param bean the bean
* @param where the where
* @param args the args
* @return the person
*/
@BindContentProviderEntry(path = "dynamicandArgs/${bean.id}")
@BindSqlSelect(where = "id=${bean.id}")
Person selectOneBeanWithDynamicAndArgs(Person bean, @BindSqlDynamicWhere String where, @BindSqlDynamicWhereParams String[] args);
/**
* select BEAN with one parameter and dynamic order.
*
* @param bean the bean
* @param order the order
* @return the person
*/
@BindContentProviderEntry(path = "dynamicOrder/${bean.id}")
@BindSqlSelect(where = "id=${bean.id}")
Person selectOneBeanWithDynamicOrder(Person bean, @BindSqlDynamicOrderBy String order);
/**
* select BEAN with one parameter and dynamic order.
*
* @param bean the bean
* @param order the order
* @param listener the listener
*/
@BindContentProviderEntry(path = "dynamicOrderAndLis/${bean.id}")
@BindSqlSelect(where = "id=${bean.id}")
void selectOneBeanWithDynamicOrderAndListener(Person bean, @BindSqlDynamicOrderBy String order, OnReadBeanListener<Person> listener);
/**
* select BEAN with one parameter and dynamic order.
*
* @param bean the bean
* @return the person
*/
@BindContentProviderEntry(path = "jql/${bean.id}")
@BindSqlSelect(jql = "select * from Person where id=${bean.id}")
Person selectWithJQL(Person bean);
/**
* select BEAN with JQL and inner SELECT.
*
* @param bean the bean
* @return the person
*/
@BindContentProviderEntry(path = "jqlAndInnserSQL/${bean.id}")
@BindSqlSelect(jql = "select * from Person where id=${bean.id} and id in (select id from Person)")
Person selectWithJQLAndInnerSQL(Person bean);
}
| 33.683824 | 134 | 0.716219 |
46523bee5db6255be520440d50787036dfbb2634 | 6,740 | /*
* LinShare is an open source filesharing software, part of the LinPKI software
* suite, developed by Linagora.
*
* Copyright (C) 2015 LINAGORA
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any
* later version, provided you comply with the Additional Terms applicable for
* LinShare software by Linagora pursuant to Section 7 of the GNU Affero General
* Public License, subsections (b), (c), and (e), pursuant to which you must
* notably (i) retain the display of the “LinShare™” trademark/logo at the top
* of the interface window, the display of the “You are using the Open Source
* and free version of LinShare™, powered by Linagora © 2009–2015. Contribute to
* Linshare R&D by subscribing to an Enterprise offer!” infobox and in the
* e-mails sent with the Program, (ii) retain all hypertext links between
* LinShare and t3c.io, between linagora.com and Linagora, and (iii)
* refrain from infringing Linagora intellectual property rights over its
* trademarks and commercial brands. Other Additional Terms apply, see
* <http://www.linagora.com/licenses/> for more details.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License and
* its applicable Additional Terms for LinShare along with this program. If not,
* see <http://www.gnu.org/licenses/> for the GNU Affero General Public License
* version 3 and <http://www.linagora.com/licenses/> for the Additional Terms
* applicable to LinShare software.
*/
package com.t3c.anchel.core.domain.entities;
import java.util.Date;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.t3c.anchel.core.domain.constants.Language;
import com.t3c.anchel.core.domain.constants.MailContentType;
import com.t3c.anchel.core.exception.TechnicalException;
public class MailConfig implements Cloneable {
private long id;
private MailLayout mailLayoutHtml;
private AbstractDomain domain;
private String name;
private boolean visible;
private boolean readonly;
private Date creationDate;
private Date modificationDate;
private String uuid;
private Map<Integer, MailFooterLang> mailFooters = Maps.newHashMap();
private Set<MailContentLang> mailContentLangs = Sets.newHashSet();
public MailConfig() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public MailLayout getMailLayoutHtml() {
return mailLayoutHtml;
}
public void setMailLayoutHtml(MailLayout mailLayoutHtml) {
this.mailLayoutHtml = mailLayoutHtml;
}
public AbstractDomain getDomain() {
return domain;
}
public void setDomain(AbstractDomain domain) {
this.domain = domain;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isVisible() {
return visible;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
public Date getCreationDate() {
return creationDate;
}
public boolean isReadonly() {
return readonly;
}
public void setReadonly(boolean readonly) {
this.readonly = readonly;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Date getModificationDate() {
return modificationDate;
}
public void setModificationDate(Date modificationDate) {
this.modificationDate = modificationDate;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public Map<Integer, MailFooterLang> getMailFooters() {
return mailFooters;
}
public void setMailFooters(Map<Integer, MailFooterLang> mailFooters) {
this.mailFooters = mailFooters;
}
public Set<MailContentLang> getMailContentLangs() {
return mailContentLangs;
}
public void setMailContentLangs(Set<MailContentLang> mailContents) {
this.mailContentLangs = mailContents;
}
@Override
public MailConfig clone() throws CloneNotSupportedException {
// Every properties are clones, except domain.
MailConfig mc = null;
try {
mc = (MailConfig) super.clone();
mc.id = 0;
mc.mailLayoutHtml = mailLayoutHtml.clone();
mc.mailFooters = Maps.newHashMap();
Set<Entry<Integer,MailFooterLang>> entrySet = mailFooters.entrySet();
for (Entry<Integer, MailFooterLang> entry : entrySet) {
mc.mailFooters.put(entry.getKey(), entry.getValue().clone());
}
mc.mailContentLangs = Sets.newHashSet();
for (MailContentLang mailContentLang : mailContentLangs) {
mc.mailContentLangs.add(mailContentLang.clone());
}
} catch (CloneNotSupportedException cnse) {
cnse.printStackTrace(System.err);
}
return mc;
}
/*
* Helpers
*/
/**
* Find a Footer by its Language
* @param lang
* @return
*/
public MailFooter findFooter(final Language lang) {
MailFooterLang f = mailFooters.get(lang.toInt());
if (f == null)
throw new TechnicalException(
"No MailFooter matching the language: " + lang);
return f.getMailFooter();
}
/**
* Find a MailContent by its Language and MailContentType
*
* @param lang
* @param type
* @return
*/
public MailContent findContent(final Language lang,
final MailContentType type) {
MailContentLang needle = new MailContentLang(lang, type);
for (MailContentLang mcl : mailContentLangs) {
if (mcl.businessEquals(needle))
return mcl.getMailContent();
}
throw new TechnicalException(
"No MailContent matching the [Language,MailContentType] pair: ["
+ lang + "," + type + "]");
}
public void replaceMailContent(final Language lang,
final MailContentType type, MailContent replace) {
MailContentLang needle = new MailContentLang(lang, type);
needle.setMailContent(replace);
boolean found = false;
for (MailContentLang mcl : mailContentLangs) {
if (mcl.businessEquals(needle)) {
mailContentLangs.remove(mcl);
mailContentLangs.add(needle);
found = true;
break;
}
}
if (!found) {
throw new TechnicalException(
"No MailContent matching the [Language,MailContentType] pair: ["
+ lang + "," + type + "]");
}
}
@Override
public String toString() {
return "MailConfig [domain=" + domain + ", name=" + name + ", visible=" + visible + ", readonly=" + readonly
+ ", uuid=" + uuid + "]";
}
}
| 26.96 | 110 | 0.726113 |
1c22a80b29aacff7253de683eeeaa84e1571fd1b | 3,675 | // ***************************************************************************************************************************
// * 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.juneau.rest.guards;
import java.text.*;
import java.util.*;
import java.util.stream.*;
import org.apache.juneau.rest.*;
/**
* {@link RestGuard} that uses role expressions to determine whether an authenticated user has access to a class or method.
*
* <p>
* The role expression supports the following constructs:
* <ul>
* <li><js>"foo"</js> - Single arguments.
* <li><js>"foo,bar,baz"</js> - Multiple OR'ed arguments.
* <li><js>"foo | bar | bqz"</js> - Multiple OR'ed arguments, pipe syntax.
* <li><js>"foo || bar || bqz"</js> - Multiple OR'ed arguments, Java-OR syntax.
* <li><js>"fo*"</js> - Patterns including <js>'*'</js> and <js>'?'</js>.
* <li><js>"fo* & *oo"</js> - Multiple AND'ed arguments, ampersand syntax.
* <li><js>"fo* && *oo"</js> - Multiple AND'ed arguments, Java-AND syntax.
* <li><js>"fo* || (*oo || bar)"</js> - Parenthesis.
* </ul>
*
* <ul class='notes'>
* <li>AND operations take precedence over OR operations (as expected).
* <li>Whitespace is ignored.
* <li><jk>null</jk> or empty expressions always match as <jk>false</jk>.
* </ul>
*/
public class RoleBasedRestGuard extends RestGuard {
private final Set<String> roles;
private final RoleMatcher roleMatcher;
/**
* Constructor.
*
* @param declaredRoles
* List of possible declared roles.
* <br>If <jk>null</jk>, we find the roles in the expression itself.
* <br>This is only needed if you're using pattern matching in the expression.
* @param roleExpression
* The role expression.
* <br>If <jk>null</jk> or empty/blanks, the this guard will never pass.
* @throws ParseException Invalid role expression syntax.
*/
public RoleBasedRestGuard(Set<String> declaredRoles, String roleExpression) throws ParseException {
roleMatcher = new RoleMatcher(roleExpression);
roles = new TreeSet<>(declaredRoles == null ? roleMatcher.getRolesInExpression() : declaredRoles);
}
@Override
public boolean isRequestAllowed(RestRequest req) {
Set<String> userRoles = roles.stream().filter(x -> req.isUserInRole(x)).collect(Collectors.toSet());
return roleMatcher.matches(userRoles);
}
}
| 51.760563 | 126 | 0.56517 |
2e29d50dbdb8a2dd3ef90451ee57fd29f66c8266 | 3,874 | /*
* Copyright (c) 2017, MegaEase
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.megaease.easeagent.core.utils;
import lombok.SneakyThrows;
import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.util.*;
public class ServletUtils {
public static final String BEST_MATCHING_PATTERN_ATTRIBUTE =
"org.springframework.web.servlet.HandlerMapping.bestMatchingPattern";
private static final String UNKNOWN = "unknown";
private ServletUtils() {}
public static String getHttpRouteAttributeFromRequest(HttpServletRequest request) {
Object httpRoute = request.getAttribute(BEST_MATCHING_PATTERN_ATTRIBUTE);
return httpRoute != null ? httpRoute.toString() : "";
}
public static String getRemoteHost(HttpServletRequest request) {
if (request == null) {
return UNKNOWN;
}
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
}
public static Map<String, String> getHeaders(HttpServletRequest httpServletRequest) {
Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
Map<String, String> map = new HashMap<>();
while (headerNames.hasMoreElements()) {
String name = headerNames.nextElement();
String value = httpServletRequest.getHeader(name);
map.put(name, value);
}
return map;
}
@SneakyThrows
public static Map<String, List<String>> getQueries(HttpServletRequest httpServletRequest) {
Map<String, List<String>> map = new HashMap<>();
String queryString = httpServletRequest.getQueryString();
if (queryString == null || queryString.isEmpty()) {
return map;
}
String[] pairs = queryString.split("&");
for (String pair : pairs) {
int idx = pair.indexOf("=");
String key = idx > 0 ? URLDecoder.decode(pair.substring(0, idx), "UTF-8") : pair;
if (!map.containsKey(key)) {
map.put(key, new LinkedList<>());
}
String value =
idx > 0 && pair.length() > idx + 1
? URLDecoder.decode(pair.substring(idx + 1), "UTF-8")
: null;
map.get(key).add(value);
}
return map;
}
public static Map<String, String> getQueries4SingleValue(
HttpServletRequest httpServletRequest) {
Map<String, List<String>> map = getQueries(httpServletRequest);
Map<String, String> singleValueMap = new HashMap<>();
map.forEach(
(key, values) -> {
if (values != null && !values.isEmpty()) {
singleValueMap.put(key, values.get(0));
}
});
return singleValueMap;
}
}
| 37.61165 | 95 | 0.60635 |
29ef28b58f2379e3106b80d76f121f29eae27378 | 2,358 | package com.github.phenomics.ontolib.io.obo;
import de.charite.compbio.ontolib.io.obo.parser.Antlr4OboParser;
import org.antlr.v4.runtime.BaseErrorListener;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CodePointCharStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.DiagnosticErrorListener;
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.Recognizer;
import org.junit.Test;
import com.github.phenomics.ontolib.io.obo.OboLexer;
/**
* Smoke tests for the ANTLR 4 OBO lexer.
*
* @author <a href="mailto:[email protected]">Manuel Holtgrewe</a>
*/
public class Antlr4OboParserSmokeTest extends SmokeTestBase {
@Test
public void testParsingMinimalFile() throws Exception {
final CodePointCharStream inputStream = CharStreams.fromString(MINIMAL_FILE);
final OboLexer l = new OboLexer(inputStream);
final Antlr4OboParser p = new Antlr4OboParser(new CommonTokenStream(l));
p.addErrorListener(new BaseErrorListener() {
@Override
public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line,
int charPositionInLine, String msg, RecognitionException e) {
throw new IllegalStateException("failed to parse at line " + line + " due to " + msg, e);
}
});
p.addErrorListener(new DiagnosticErrorListener());
try {
p.oboFile();
} catch (IllegalStateException e) {
throw new Exception("Problem parsing \"" + MINIMAL_FILE + "\"", e);
}
}
@Test
public void testParsingHeadOfHPO() throws Exception {
final CodePointCharStream inputStream = CharStreams.fromString(HEAD_HPO);
final OboLexer l = new OboLexer(inputStream);
final Antlr4OboParser p = new Antlr4OboParser(new CommonTokenStream(l));
p.addErrorListener(new BaseErrorListener() {
@Override
public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line,
int charPositionInLine, String msg, RecognitionException e) {
throw new IllegalStateException("failed to parse at line " + line + " due to " + msg, e);
}
});
p.addErrorListener(new DiagnosticErrorListener());
try {
p.oboFile();
} catch (IllegalStateException e) {
throw new Exception("Problem parsing \"" + HEAD_HPO + "\"", e);
}
}
}
| 37.428571 | 97 | 0.719678 |
903c0fd78a5b1f1533daf8a60af39e244ed5f4e4 | 1,032 | // This file is auto-generated, don't edit it. Thanks.
package com.antgroup.antchain.openapi.iam.models;
import com.aliyun.tea.*;
public class Action extends TeaModel {
// 操作点描述
@NameInMap("description")
public String description;
// 操作点ID
@NameInMap("id")
public String id;
// 操作点名称
@NameInMap("name")
public String name;
public static Action build(java.util.Map<String, ?> map) throws Exception {
Action self = new Action();
return TeaModel.build(map, self);
}
public Action setDescription(String description) {
this.description = description;
return this;
}
public String getDescription() {
return this.description;
}
public Action setId(String id) {
this.id = id;
return this;
}
public String getId() {
return this.id;
}
public Action setName(String name) {
this.name = name;
return this;
}
public String getName() {
return this.name;
}
}
| 21.061224 | 79 | 0.608527 |
4dd6ab8f1d085d93a9484eb5ef7f0192034a6ccd | 7,266 | /**
* Author: Archie, Disono ([email protected])
* Website: http://www.webmons.com
*
* Created at: 12/08/2018
*/
package disono.com.webmons.ruler;
import android.app.Activity;
import android.app.DialogFragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import org.opencv.android.OpenCVLoader;
import java.io.File;
import disono.com.webmons.ruler.Actions.CameraActions;
import disono.com.webmons.ruler.Actions.StorageActions;
import disono.com.webmons.ruler.OpenCVLib.DetectCircle;
import disono.com.webmons.ruler.Ruler.DrawView;
import disono.com.webmons.ruler.Ruler.ImageSurface;
import disono.com.webmons.ruler.Ruler.InputDialog;
import disono.com.webmons.ruler.Ruler.Utils;
import stud.dress.booth.R;
public class CameraActivity extends AppCompatActivity implements InputDialog.InputDialogListener {
private Activity activity;
private static String TAG = "CameraActivity";
private DrawView drawView;
private FrameLayout preview;
private File photoFile;
private Button btn_ok;
private Button btn_cancel;
private Button btn_takePicture;
DetectCircle detectCircle;
static {
if (!OpenCVLoader.initDebug()) {
Log.wtf(TAG, "OpenCV failed to load!");
}
}
BroadcastReceiver br = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent != null) {
String length = intent.getStringExtra("length");
String unit = intent.getStringExtra("unit");
if (length != null && unit != null) {
finish();
}
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_ruler_activity);
activity = this;
System.loadLibrary("opencv_java3");
_UIInit();
_UIAttached();
_UIListener();
_broadcastRCV();
}
@Override
protected void onResume() {
super.onResume();
}
@Override
public void onDestroy() {
super.onDestroy();
activity.unregisterReceiver(br);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// 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();
switch (id) {
case R.id.action_cleanStorage:
StorageActions.cleanPhotoStorage(activity);
break;
case R.id.action_choosePhoto:
CameraActions.dispatchChoosePhotoIntent(activity);
break;
case R.id.action_takePicture:
photoFile = CameraActions.dispatchTakePictureIntent(activity);
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onDialogPositiveClick(DialogFragment dialog) {
int inputUnit = ((Spinner) dialog.getDialog().findViewById(R.id.input_unit_chooser)).getSelectedItemPosition();
int outputUnit = ((Spinner) dialog.getDialog().findViewById(R.id.output_unit_chooser)).getSelectedItemPosition();
try {
double reference = Double.parseDouble(((EditText) dialog.getDialog().findViewById(R.id.reference_input)).getText().toString());
double result = drawView.calculate(reference, inputUnit, outputUnit);
StorageActions.showResult(activity, result, outputUnit);
} catch (NumberFormatException ex) {
Toast.makeText(this, getResources().getString(R.string.error_numberFormat), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onDialogNegativeClick(DialogFragment dialog) {
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case CameraActions.REQUEST_IMAGE_CAPTURE:
if (resultCode == RESULT_OK) {
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse(photoFile.getAbsolutePath())));
pictureTaken();
}
break;
case CameraActions.REQUEST_SELECT_PHOTO:
if (resultCode == RESULT_OK) {
Uri uri = data.getData();
String filePath = Utils.getPath(this, uri);
assert filePath != null;
photoFile = new File(filePath);
pictureTaken();
}
break;
default:
super.onActivityResult(requestCode, resultCode, data);
break;
}
}
private void _broadcastRCV() {
IntentFilter filter = new IntentFilter("CordovaCameraRuler.Filter");
activity.registerReceiver(br, filter);
}
private void pictureTaken() {
preview.removeAllViews();
btn_cancel.setVisibility(View.VISIBLE);
btn_ok.setVisibility(View.VISIBLE);
btn_takePicture.setVisibility(View.GONE);
ImageSurface image = new ImageSurface(activity.getApplicationContext(), photoFile);
preview.addView(image);
((TextView) findViewById(R.id.info_lbl)).setText(getResources().getString(R.string.setReferencePoints));
// get the x and y
detectCircle = new DetectCircle();
detectCircle.detect(photoFile.getAbsolutePath());
drawView = new DrawView(this, detectCircle);
preview.addView(drawView);
}
private void _UIInit() {
preview = (FrameLayout) findViewById(R.id.camera_preview);
btn_ok = (Button) findViewById(R.id.button_calculate);
btn_cancel = (Button) findViewById(R.id.button_cancel);
btn_takePicture = (Button) findViewById(R.id.button_takePicture);
}
private void _UIAttached() {
preview.removeAllViews();
btn_cancel.setVisibility(View.GONE);
btn_ok.setVisibility(View.GONE);
btn_takePicture.setVisibility(View.VISIBLE);
}
private void _UIListener() {
btn_takePicture.setOnClickListener(v -> photoFile = CameraActions.dispatchTakePictureIntent(activity));
btn_ok.setOnClickListener(v -> new InputDialog().show(getFragmentManager(), "input_dialog"));
btn_cancel.setOnClickListener(v -> drawView.clearCanvas());
}
}
| 32.293333 | 139 | 0.655106 |
926844897151e3afd805fe3f8c30558f52267b85 | 613 | package link.mc.lang;
import java.util.ListIterator;
import link.mc.util.MarkupUtil;
import link.mc.util.Placeholder;
public class Translator {
public static String translate(String lang, String s) {
ListIterator<Translation> li = Translation.translations.listIterator(Translation.translations.size());
while (li.hasPrevious()) {
Translation t = li.previous();
if (t.getId().equalsIgnoreCase(lang) && t.getConfig().getString(s) != null)
return MarkupUtil.markupToChat(Placeholder.replace(t.getConfig().getString(s)));
else
return s;
}
return s;
}
}
| 24.52 | 105 | 0.69168 |
1c8ca18f35da47bac5a0033e73297337a6e0883f | 1,370 | package com.ebstrada.formreturn.manager.log4j;
import javax.swing.JScrollPane;
import org.apache.log4j.spi.LoggingEvent;
public class AbstractAppenderScrollPane extends JScrollPane {
private static final long serialVersionUID = 1L;
protected LoggingEventModel logModel;
protected int maxEntries;
private ComponentAppender appender;
public AbstractAppenderScrollPane(int maxEntries) {
super();
this.maxEntries = maxEntries;
appender = null;
logModel = new LoggingEventModel();
}
public void setMaxEntries(int value) {
int toomuch = logModel.getSize() - value;
for (int i = 0; i < toomuch; i++) {
logModel.removeElementAt(0);
}
maxEntries = value;
}
public ComponentAppender getAppender() {
return appender;
}
public void setAppender(ComponentAppender appender) {
this.appender = appender;
}
public void removeElementAt(int index) {
logModel.removeElementAt(index);
}
public void removeAllElements() {
logModel.removeAllElements();
}
public void addElement(LoggingEvent event) {
if (logModel.getSize() == maxEntries) {
logModel.removeElementAt(0);
}
logModel.addElement(event);
}
}
| 23.62069 | 62 | 0.623358 |
4f89b80fbf842b172157dbcbf34c1db7d785591c | 1,254 | package com.t0ugh.server.handler.impl.list;
import com.t0ugh.sdk.proto.Proto;
import com.t0ugh.server.BaseTest;
import com.t0ugh.server.handler.Handler;
import com.t0ugh.server.utils.TestUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class LLenHandlerTest extends BaseListHandlerTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void test1() throws Exception {
test("Hi", 3);
}
@Test
public void test2() throws Exception {
test("Ha", 0);
}
public void test(String key, int count) throws Exception {
Proto.Request request = Proto.Request.newBuilder()
.setMessageType(Proto.MessageType.LLen)
.setLLenRequest(Proto.LLenRequest.newBuilder()
.setKey(key)
.build())
.build();
Proto.Response response = testContext.getHandlerFactory().getHandler(Proto.MessageType.LLen).get().handle(request);
TestUtils.assertOK(Proto.MessageType.LLen, response);
assertEquals(count, response.getLLenResponse().getCount());
}
} | 28.5 | 123 | 0.652313 |
e02e515b31389e45efb786768e0289d4daa8459f | 3,517 | /**
* Copyright (C) 2017 Red Hat, 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.atlasmap.itests.core;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.net.URL;
import java.util.HashMap;
import org.junit.Test;
import org.xmlunit.assertj.XmlAssert;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.atlasmap.api.AtlasContext;
import io.atlasmap.api.AtlasSession;
import io.atlasmap.core.DefaultAtlasContextFactory;
public class JsonXmlEnumTest {
@Test
public void test() throws Exception {
URL url = Thread.currentThread().getContextClassLoader().getResource("mappings/atlasmapping-json-xml-enum.json");
AtlasContext context = DefaultAtlasContextFactory.getInstance().createContext(url.toURI());
assertForValues(context, "NA", "Available", "NA", "Available");
assertForValues(context, "EMEA", "Pending", "EMEA", "Pending");
assertForValues(context, "LATAM", "Sold", "LATAM", "Sold");
assertForValues(context, "APAC", "Available", "NA", "Available");
}
private void assertForValues(AtlasContext context, String sourceJsonValue, String sourceXmlValue,
String targetJsonValue, String targetXmlValue) throws Exception {
AtlasSession session = context.createSession();
String sourceJson = String.format("{\"region\": \"%s\"}", sourceJsonValue);
session.setSourceDocument("address-enum-schema-19eabdd2-fec0-439a-824f-47f514a06177", sourceJson);
String sourceXml = String.format(
"<tns:request xmlns:tns=\"http://syndesis.io/v1/swagger-connector-template/request\">"
+ "<tns:body><Pet><status>%s</status></Pet></tns:body></tns:request>", sourceXmlValue);
session.setSourceDocument("XMLSchemaSource-2c88ee00-7ddc-4137-b906-52d56e9b7f9e", sourceXml);
context.process(session);
assertFalse(TestHelper.printAudit(session), session.hasErrors());
String targetJson = (String) session.getTargetDocument("address-enum-schema-afdf5b0b-416a-4b7a-a4ba-f6219af64f43");
JsonNode root = new ObjectMapper().readTree(targetJson);
JsonNode field = root.get("region");
assertFalse(field.isNull());
assertTrue(field.isTextual());
assertEquals(targetJsonValue, field.asText());
String targetXml = (String) session.getTargetDocument("XMLSchemaSource-c1b7b86e-959a-4cd8-b1fd-0bf52ddf0f43");
assertNotNull("target XML is null", targetXml);
HashMap<String, String> namespaces = new HashMap<>();
namespaces.put("tns", "http://syndesis.io/v1/swagger-connector-template/request");
XmlAssert.assertThat(targetXml).withNamespaceContext(namespaces)
.valueByXPath("//tns:request/tns:body/Pet/status").isEqualTo(targetXmlValue);
}
}
| 46.276316 | 123 | 0.715667 |
0718cb3df4278f716b38bbaa4790bb2718a38329 | 2,022 | package com.androiddeft.recyclerviewdemo;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import com.androiddeft.recyclerviewdemo.font.FontHelper;
import com.leo.font.lib.annotations.IgnoreScale;
import com.leo.font.lib.binder.FontBinding;
import com.vn.fa.font.FontManager;
public class TestScaleAllAppActivity extends AppCompatActivity {
public TextView tvGreeting1;
@IgnoreScale
public TextView tvGreeting2;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
tvGreeting1 = (TextView) findViewById(R.id.tv_greeting1);
tvGreeting2 = (TextView) findViewById(R.id.tv_greeting2);
FontHelper.init(this, FontManager.FontScaleType.SCALE_ALL);
FontBinding.bind(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.font_small:
FontHelper.scaleFont(TestScaleAllAppActivity.this, 0);
break;
case R.id.font_big:
FontHelper.scaleFont(TestScaleAllAppActivity.this, 1);
break;
case R.id.font_huge:
FontHelper.scaleFont(TestScaleAllAppActivity.this, 2);
break;
}
FontManager.adjustFontScaleAll(this, FontManager.getDefault().getScale());
startActivity(new Intent(this, TestScaleAllAppActivity.class));
finish();
//startActivity(IntentCompat.makeRestartActivityTask(getComponentName()));
return super.onOptionsItemSelected(item);
}
}
| 35.473684 | 82 | 0.702275 |
1e510ee25286cd80deafae2c8e57834ad1c33c71 | 5,011 | package org.adrianl.stream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class NoMioDeInternet {
/*
ORDENAR
Se crea una lista y se la añaden elementos.
Collections.sort(lista, (l1,l2) -> l1.compareTo(l2));
for(String elemento : lista){
System.out.println(elemento);
}
public static void main(String[] args) {
Person p1 = new Person(1, "Mito", LocalDate.of(1991, 1, 21));
Person p2 = new Person(2, "Code", LocalDate.of(1990, 2, 21));
Person p3 = new Person(3, "Jaime", LocalDate.of(1980, 6, 23));
Person p4 = new Person(4, "Duke", LocalDate.of(2019, 5, 15));
Person p5 = new Person(5, "James", LocalDate.of(2010, 1, 4));
Product pr1 = new Product(1, "Ceviche", 15.0);
Product pr2 = new Product(2, "Chilaquiles", 25.50);
Product pr3 = new Product(3, "Bandeja Paisa", 35.50);
Product pr4 = new Product(4, "Ceviche", 15.0);
List<Person> persons = Arrays.asList(p1, p2, p3, p4, p5);
List<Product> products = Arrays.asList(pr1, pr2, pr3, pr4);
// Lambda //method reference
// list.forEach(System.out::println);
for(int i = 0; i<persons.size(); i++){
System.out.println(persons.get(i));
}
/*for(Person p : persons){
System.out.println(p);
}
//persons.forEach(x -> System.out.println(x));
//persons.forEach(System.out::println);
// 1-Filter (param: Predicate)
List<Person> filteredList1 = persons.stream()
.filter(p -> App.getAge(p.getBirthDate()) >= 18)
.collect(Collectors.toList());
//App.printList(filteredList1);
// 2-Map (param: Function)
Function<String, String> coderFunction = name -> "Coder " + name;
List<String> filteredList2 = persons.stream()
//.filter(p -> App.getAge(p.getBirthDate()) >= 18)
//.map(p -> App.getAge(p.getBirthDate()))
//.map(p -> "Coder " + p.getName())
//.map(p-> p.getName())
.map(Person::getName)
.map(coderFunction)
.collect(Collectors.toList());
//App.printList(filteredList2);
// 3-Sorted (param: Comparator)
Comparator<Person> byNameAsc = (Person o1, Person o2) -> o1.getName().compareTo(o2.getName());
Comparator<Person> byNameDesc = (Person o1, Person o2) -> o2.getName().compareTo(o1.getName());
Comparator<Person> byBirthDate = (Person o1, Person o2) -> o1.getBirthDate().compareTo(o2.getBirthDate());
List<Person> filteredList3 = persons.stream()
.sorted(byBirthDate)
.collect(Collectors.toList());
//App.printList(filteredList3);
// 4-Match (param: Predicate)
Predicate<Person> startsWithPredicate = person -> person.getName().startsWith("J");
// anyMatch : No evalua todo el stream, termina en la coincidencia
boolean rpta1 = persons.stream()
.anyMatch(startsWithPredicate);
// allMatch : Evalua todo el stream bajo la condicion
boolean rpta2 = persons.stream()
.allMatch(startsWithPredicate);
// noneMatch : Evalua todo el stream bajo la condicion
boolean rpta3 = persons.stream()
.noneMatch(startsWithPredicate);
// 5-Limit/Skip
int pageNumber = 1;
int pageSize = 2;
List<Person> filteredList4 = persons.stream()
.skip(pageNumber * pageSize)
.limit(pageSize)
.collect(Collectors.toList());
//App.printList(filteredList4);
// 6-Collectors
// GroupBy
Map<String, List<Product>> collect1 = products.stream()
.filter(p -> p.getPrice() > 20)
.collect(Collectors.groupingBy(Product::getName));
//System.out.println(collect1);
// Counting
Map<String, Long> collect2 = products.stream()
.collect(Collectors.groupingBy(
Product::getName, Collectors.counting()
)
);
//System.out.println(collect2);
//Agrupando por nombre producto y sumando
Map<String, Double> collect3 = products.stream()
.collect(Collectors.groupingBy(
Product::getName,
Collectors.summingDouble(Product::getPrice)
)
);
//System.out.println(collect3);
//Obteniendo suma y resumen
DoubleSummaryStatistics statistics = products.stream()
.collect(Collectors.summarizingDouble(Product::getPrice));
//System.out.println(statistics);
//7-reduce
Optional<Double> sum = products.stream()
.map(Product::getPrice)
.reduce(Double::sum);
//.reduce((a,b) -> a+b)
System.out.println(sum.get());
}
public static int getAge(LocalDate birthDate) {
return Period.between(birthDate, LocalDate.now()).getYears();
}
public static void printList(List<?> list){
list.forEach(System.out::println);
}
*/
}
| 34.798611 | 110 | 0.597086 |
5fe7545177d174593f53d3dfa70173cea8a86acf | 761 | package ru.rd.rest;
import org.testng.SkipException;
import org.testng.annotations.BeforeSuite;
import java.io.IOException;
import java.math.BigInteger;
public class TestBase {
protected static final ApplicationManager app = new ApplicationManager();
@BeforeSuite(alwaysRun = true)
public void setUp() throws Exception {
app.init();
}
private boolean isIssueOpen(BigInteger issueId) throws IOException {
Issue issue = app.rest().getIssueById(issueId);
return !issue.getStateName().equals("Resolved");
}
public void skipIfNotFixed(BigInteger issueId) throws IOException {
if (isIssueOpen(issueId)) {
throw new SkipException("Ignored because of issue " + issueId);
}
}
}
| 25.366667 | 77 | 0.693824 |
80309ef44aa256141969b4aa47efce1dd2640aae | 1,570 | /**
* Appia: Group communication and protocol composition framework library
* Copyright 2006 University of Lisbon
*
* 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.
*
* Initial developer(s): Alexandre Pinto and Hugo Miranda.
* Contributor(s): See Appia web page for a list of contributors.
*/
package net.sf.appia.protocols.nakfifo.multicast;
import net.sf.appia.core.AppiaEventException;
import net.sf.appia.core.Channel;
import net.sf.appia.core.Direction;
import net.sf.appia.core.Session;
import net.sf.appia.core.events.SendableEvent;
/** Event used to signal the last received message and therfore allow the
* sender to clean the unconfirmed messages list.
*
* @author Alexandre Pinto
*/
public class ConfirmEvent extends SendableEvent {
/** Creates a new instance of ConfirmEvent */
public ConfirmEvent() {
super();
setPriority(130);
}
/** Creates a new instance of ConfirmEvent */
public ConfirmEvent(Channel channel, Session source)
throws AppiaEventException {
super(channel, Direction.DOWN, source);
setPriority(130);
}
}
| 32.040816 | 75 | 0.753503 |
08e4fb38c080470a682b26ad41d8d366e80eeed8 | 8,844 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.refactoring.typeMigration.rules.guava;
import com.intellij.codeInspection.AnonymousCanBeLambdaInspection;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.psi.*;
import com.intellij.psi.util.InheritanceUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiTypesUtil;
import com.intellij.refactoring.typeMigration.TypeEvaluator;
import com.intellij.refactoring.typeMigration.inspections.GuavaConversionSettings;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collections;
import java.util.Set;
/**
* @author Dmitry Batkovich
*/
public final class GuavaConversionUtil {
private final static Logger LOG = Logger.getInstance(GuavaConversionUtil.class);
@Nullable
public static PsiType getFunctionReturnType(PsiExpression functionExpression) {
if (functionExpression instanceof PsiFunctionalExpression) {
return LambdaUtil.getFunctionalInterfaceReturnType((PsiFunctionalExpression)functionExpression);
}
PsiType currentType = functionExpression.getType();
if (currentType == null) return null;
while (true) {
if (LambdaUtil.isFunctionalType(currentType)) {
return LambdaUtil.getFunctionalInterfaceReturnType(currentType);
}
final PsiType[] superTypes = currentType.getSuperTypes();
currentType = null;
for (PsiType type : superTypes) {
final PsiClass aClass = PsiTypesUtil.getPsiClass(type);
if (aClass != null && InheritanceUtil.isInheritor(aClass, GuavaLambda.FUNCTION.getClassQName())) {
currentType = type;
break;
}
}
if (currentType == null) {
return null;
}
}
}
@NotNull
public static PsiType addTypeParameters(@NotNull String baseClassQualifiedName, @Nullable PsiType type, @NotNull PsiElement context) {
String parameterText = "";
if (type != null) {
final String canonicalText = type.getCanonicalText(false);
if (canonicalText.contains("<")) {
parameterText = canonicalText.substring(canonicalText.indexOf('<'));
}
}
return JavaPsiFacade.getElementFactory(context.getProject()).createTypeFromText(baseClassQualifiedName + parameterText, context);
}
public static boolean isJavaLambda(PsiElement element, TypeEvaluator evaluator) {
if (element instanceof PsiLocalVariable) {
return GuavaLambda.findJavaAnalogueFor(evaluator.getType(element)) != null;
}
else if (element instanceof PsiReturnStatement) {
final PsiElement methodOrLambda = PsiTreeUtil.getParentOfType(element, PsiMethod.class, PsiLambdaExpression.class);
PsiType methodReturnType = null;
if (methodOrLambda instanceof PsiMethod) {
methodReturnType = evaluator.getType(methodOrLambda);
}
return GuavaLambda.findJavaAnalogueFor(methodReturnType) != null;
}
else if (element instanceof PsiExpressionList) {
final PsiElement parent = element.getParent();
if (parent instanceof PsiMethodCallExpression) {
return evaluator.getType(parent) != null;
}
}
return false;
}
public static PsiExpression adjustLambdaContainingExpression(PsiExpression expression,
boolean insertTypeCase,
PsiType targetType,
@NotNull TypeEvaluator evaluator) {
if (expression instanceof PsiNewExpression) {
final PsiAnonymousClass anonymousClass = ((PsiNewExpression)expression).getAnonymousClass();
if (anonymousClass != null) {
return convertAnonymousClass((PsiNewExpression)expression, anonymousClass, evaluator);
}
else {
final GuavaLambda lambda = GuavaLambda.findFor(evaluator.evaluateType(expression));
if (lambda == null) {
return expression;
}
else {
final PsiExpression expressionWithMethodReference = addMethodReference(expression, lambda);
if (insertTypeCase) {
return adjustLambdaContainingExpression(expressionWithMethodReference, true, targetType, evaluator);
} else {
return expressionWithMethodReference;
}
}
}
}
if (expression instanceof PsiMethodReferenceExpression) {
final PsiExpression qualifier = ((PsiMethodReferenceExpression)expression).getQualifierExpression();
final PsiType evaluatedType = evaluator.evaluateType(qualifier);
final GuavaLambda lambda = GuavaLambda.findJavaAnalogueFor(evaluatedType);
if (lambda != null) {
PsiExpression replaced = (PsiExpression)expression.replace(qualifier);
if (targetType == null &&
lambda.getSamName().equals(((PsiMethodReferenceExpression)expression).getReferenceName())) {
return replaced;
}
return adjustLambdaContainingExpression(replaced, insertTypeCase, targetType, evaluator);
}
}
if (expression instanceof PsiFunctionalExpression) {
if (insertTypeCase) {
return JavaPsiFacade.getElementFactory(expression.getProject()).createExpressionFromText("((" + targetType.getCanonicalText() + ")" + expression.getText() + ")", expression);
}
}
else if (expression instanceof PsiMethodCallExpression || expression instanceof PsiReferenceExpression) {
final GuavaLambda lambda = GuavaLambda.findFor(evaluator.evaluateType(expression));
if (lambda != null) {
expression = addMethodReference(expression, lambda);
return adjustLambdaContainingExpression(expression, insertTypeCase, targetType, evaluator);
}
}
return expression;
}
public static PsiExpression convertAnonymousClass(@NotNull PsiNewExpression expression,
@NotNull PsiAnonymousClass anonymousClass,
@NotNull TypeEvaluator typeEvaluator) {
final GuavaConversionSettings settings = typeEvaluator.getSettings(GuavaConversionSettings.class);
final Set<String> ignoredAnnotations = settings != null ? settings.getIgnoredAnnotations() : Collections.emptySet();
if (AnonymousCanBeLambdaInspection.canBeConvertedToLambda(anonymousClass, true, ignoredAnnotations)) {
return AnonymousCanBeLambdaInspection.replacePsiElementWithLambda(expression, true, true);
} else {
return tryConvertClassAndSamNameToJava(expression);
}
}
public static PsiExpression tryConvertClassAndSamNameToJava(PsiNewExpression expression) {
final GuavaLambda lambda = GuavaLambda.findFor(expression.getType());
if (lambda == null) return expression;
final PsiAnonymousClass aClass = expression.getAnonymousClass();
LOG.assertTrue(aClass != null);
final PsiElementFactory factory = JavaPsiFacade.getElementFactory(expression.getProject());
if (!lambda.getSamName().equals(lambda.getJavaAnalogueSamName())) {
boolean isFound = false;
for (PsiMethod method : aClass.findMethodsByName(lambda.getSamName(), false)) {
if (method.getParameterList().getParametersCount() == lambda.getParametersCount()) {
for (PsiMethod psiMethod : method.findSuperMethods()) {
final PsiClass superMethodContainingClass = psiMethod.getContainingClass();
if (superMethodContainingClass != null && lambda.getClassQName().equals(superMethodContainingClass.getQualifiedName())) {
final PsiIdentifier methodNameIdentifier = method.getNameIdentifier();
LOG.assertTrue(methodNameIdentifier != null);
methodNameIdentifier.replace(factory.createIdentifier(lambda.getJavaAnalogueSamName()));
isFound = true;
break;
}
}
}
if (isFound) break;
}
}
final PsiElement currentClassName = aClass.getBaseClassReference().getReferenceNameElement();
if (currentClassName != null) {
final PsiElement newNameElement = factory.createReferenceFromText(lambda.getJavaAnalogueClassQName(), null);
currentClassName.replace(newNameElement);
}
return (PsiExpression)expression.replace(factory.createExpressionFromText(expression.getText(), null));
}
private static PsiExpression addMethodReference(@NotNull PsiExpression expression, @NotNull GuavaLambda lambda) {
return (PsiExpression)expression.replace(JavaPsiFacade.getElementFactory(expression.getProject())
.createExpressionFromText(expression.getText() + "::" + lambda.getSamName(), expression));
}
}
| 47.042553 | 182 | 0.70251 |
2d196224fdd7c57e64a1afb3187b68e8f6dfd748 | 1,248 | package com.ciphercloud.parsers;
import com.ciphercloud.parsers.htmlcontentextractor.ContentNode;
import com.ciphercloud.parsers.htmlcontentextractor.Node;
import com.ciphercloud.parsers.htmlcontentextractor.TagNode;
import com.ciphercloud.parsers.htmlstreamreader.SimpleHtmlStreamReader;
public class SimpleHtmlStreamReaderHandler extends HtmlContentExtractorHandler {
public SimpleHtmlStreamReaderHandler() {
}
public SimpleHtmlStreamReaderHandler(boolean doPrint) {
super(doPrint);
}
@Override
public String rewrite(String originalHtml) {
String rewrittenHtml = originalHtml;
if (originalHtml != null && originalHtml.length() > 0) {
SimpleHtmlStreamReader parser = new SimpleHtmlStreamReader(
originalHtml);
// StringBuilder resultBuilder = new StringBuilder();
// int lastSegmentEnd = 0;
while(parser.hasNext()) {
Node node = parser.next();
String nodeData = node.getText();
String nodeType;
if (node instanceof TagNode) {
String s1 = nodeData;// System.out.println("TAG:\n" + seg);
nodeType = "Tag: ";
} else {
String s3 = nodeData;
nodeType = "Content: ";
}
if(doPrint) {
System.out.println(nodeType + node);
}
}
}
return rewrittenHtml;
}
}
| 27.733333 | 80 | 0.723558 |
b6a676541d1b6d9ecb3196e893a54e2b1d3163fa | 183 | package com.wuyi.repairer.builder.tasks;
import org.gradle.api.Describable;
import org.gradle.api.Task;
public interface Action extends org.gradle.api.Action<Task>, Describable {
}
| 22.875 | 74 | 0.797814 |
82448f41ed9293f9e05538456ee9be27768f5d27 | 701 | package think.rpgitems.power;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import javax.annotation.CheckReturnValue;
/**
* Triggers when player clicks an item in offhand
*/
public interface PowerOffhandClick extends Pimpl {
/**
* Calls when {@code player} using {@code stack} in offhand clicks
*
* @param player Player
* @param stack Item that triggered this power
* @param event Event that triggered this power
* @return PowerResult with proposed damage
*/
@CheckReturnValue
PowerResult<Void> offhandClick(Player player, ItemStack stack, PlayerInteractEvent event);
} | 30.478261 | 94 | 0.736091 |
da72a0685675ca640b4ca5805ed0c454f323fb3f | 284 | package ru.job4j.pseudo;
/**
* Интерфейс фигуры.
*
* @author Alexandr Kholodov ([email protected]) on 26.04.18.
* @version 1.0.
* @since 0.1.
*/
public interface Shape {
/**
* Метод рисования фигуры.
*
* @return Результат.
*/
String draw();
}
| 15.777778 | 67 | 0.584507 |
a4c250c2e3bac2436647e3bf0a4f031c89a1f268 | 9,565 | /*
* ============LICENSE_START==========================================
* org.onap.music
* ===================================================================
* Copyright (c) 2017 AT&T Intellectual Property
* ===================================================================
* 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.
*
* ============LICENSE_END=============================================
* ====================================================================
*/
package org.onap.music.unittests;
/**
* @author srupane
*
*/
import java.io.IOException;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.exceptions.NoHostAvailableException;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.thrift.transport.TTransportException;
import org.cassandraunit.utils.EmbeddedCassandraServerHelper;
import org.onap.music.datastore.MusicDataStore;
import org.onap.music.datastore.PreparedQueryObject;
public class CassandraCQL {
public static final String createKeySpace =
"CREATE KEYSPACE IF NOT EXISTS testCassa WITH replication = "
+"{'class':'SimpleStrategy','replication_factor':1} AND durable_writes = true;";
public static final String dropKeyspace = "DROP KEYSPACE IF EXISTS testCassa";
public static final String createTableEmployees =
"CREATE TABLE IF NOT EXISTS testCassa.employees "
+ "(vector_ts text,empId uuid,empName text,empSalary varint,address Map<text,text>,PRIMARY KEY (empName)) "
+ "WITH comment='Financial Info of employees' "
+ "AND compression={'sstable_compression':'DeflateCompressor','chunk_length_kb':64} "
+ "AND compaction={'class':'SizeTieredCompactionStrategy','min_threshold':6};";
public static final String insertIntoTablePrepared1 =
"INSERT INTO testCassa.employees (vector_ts,empId,empName,empSalary) VALUES (?,?,?,?); ";
public static final String insertIntoTablePrepared2 =
"INSERT INTO testCassa.employees (vector_ts,empId,empName,empSalary,address) VALUES (?,?,?,?,?);";
public static final String selectALL = "SELECT * FROM testCassa.employees;";
public static final String selectSpecific =
"SELECT * FROM testCassa.employees WHERE empName= ?;";
public static final String updatePreparedQuery =
"UPDATE testCassa.employees SET vector_ts=?,address= ? WHERE empName= ?;";
public static final String deleteFromTable = " ";
public static final String deleteFromTablePrepared = " ";
// Set Values for Prepared Query
public static List<Object> setPreparedInsertValues1() {
List<Object> preppreparedInsertValues1 = new ArrayList<>();
String vectorTs =
String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis());
UUID empId = UUID.fromString("abc66ccc-d857-4e90-b1e5-df98a3d40cd6");
BigInteger empSalary = BigInteger.valueOf(23443);
String empName = "Mr Test one";
preppreparedInsertValues1.add(vectorTs);
preppreparedInsertValues1.add(empId);
preppreparedInsertValues1.add(empName);
preppreparedInsertValues1.add(empSalary);
return preppreparedInsertValues1;
}
public static List<Object> setPreparedInsertValues2() {
List<Object> preparedInsertValues2 = new ArrayList<>();
String vectorTs =
String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis());
UUID empId = UUID.fromString("abc434cc-d657-4e90-b4e5-df4223d40cd6");
BigInteger empSalary = BigInteger.valueOf(45655);
String empName = "Mr Test two";
Map<String, String> address = new HashMap<>();
preparedInsertValues2.add(vectorTs);
preparedInsertValues2.add(empId);
preparedInsertValues2.add(empName);
preparedInsertValues2.add(empSalary);
address.put("Street", "1 some way");
address.put("City", "Some town");
preparedInsertValues2.add(address);
return preparedInsertValues2;
}
public static List<Object> setPreparedUpdateValues() {
List<Object> preparedUpdateValues = new ArrayList<>();
String vectorTs =
String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis());
Map<String, String> address = new HashMap<>();
preparedUpdateValues.add(vectorTs);
String empName = "Mr Test one";
address.put("Street", "101 Some Way");
address.put("City", "New York");
preparedUpdateValues.add(address);
preparedUpdateValues.add(empName);
return preparedUpdateValues;
}
// Generate Different Prepared Query Objects
/**
* Query Object for Get.
*
* @return
*/
public static PreparedQueryObject setPreparedGetQuery() {
PreparedQueryObject queryObject = new PreparedQueryObject();
String empName1 = "Mr Test one";
queryObject.appendQueryString(selectSpecific);
queryObject.addValue(empName1);
return queryObject;
}
/**
* Query Object 1 for Insert.
*
* @return {@link PreparedQueryObject}
*/
public static PreparedQueryObject setPreparedInsertQueryObject1() {
PreparedQueryObject queryobject = new PreparedQueryObject();
queryobject.appendQueryString(insertIntoTablePrepared1);
List<Object> values = setPreparedInsertValues1();
if (!values.isEmpty() || values != null) {
for (Object o : values) {
queryobject.addValue(o);
}
}
return queryobject;
}
/**
* Query Object 2 for Insert.
*
* @return {@link PreparedQueryObject}
*/
public static PreparedQueryObject setPreparedInsertQueryObject2() {
PreparedQueryObject queryobject = new PreparedQueryObject();
queryobject.appendQueryString(insertIntoTablePrepared2);
List<Object> values = setPreparedInsertValues2();
if (!values.isEmpty() || values != null) {
for (Object o : values) {
queryobject.addValue(o);
}
}
return queryobject;
}
/**
* Query Object for Update.
*
* @return {@link PreparedQueryObject}
*/
public static PreparedQueryObject setPreparedUpdateQueryObject() {
PreparedQueryObject queryobject = new PreparedQueryObject();
queryobject.appendQueryString(updatePreparedQuery);
List<Object> values = setPreparedUpdateValues();
if (!values.isEmpty() || values != null) {
for (Object o : values) {
queryobject.addValue(o);
}
}
return queryobject;
}
private static ArrayList<String> getAllPossibleLocalIps() {
ArrayList<String> allPossibleIps = new ArrayList<String>();
try {
Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
while (en.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) en.nextElement();
Enumeration<InetAddress> ee = ni.getInetAddresses();
while (ee.hasMoreElements()) {
InetAddress ia = (InetAddress) ee.nextElement();
allPossibleIps.add(ia.getHostAddress());
}
}
} catch (SocketException e) {
System.out.println(e.getMessage());
}
return allPossibleIps;
}
public static MusicDataStore connectToEmbeddedCassandra() {
Iterator<String> it = getAllPossibleLocalIps().iterator();
String address = "localhost";
Cluster cluster = null;
Session session = null;
while (it.hasNext()) {
try {
try {
EmbeddedCassandraServerHelper.startEmbeddedCassandra(80000);
} catch (ConfigurationException | TTransportException | IOException e) {
System.out.println(e.getMessage());
}
cluster = new Cluster.Builder().addContactPoint(address).withPort(9142).build();
cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(20000);
session = cluster.connect();
break;
} catch (NoHostAvailableException e) {
address = it.next();
System.out.println(e.getMessage());
}
}
return new MusicDataStore(cluster, session);
}
}
| 37.217899 | 127 | 0.62321 |
93ee1238f8fface778175d69be6306dd10fe2546 | 835 | // Problem Description: https://leetcode.com/problems/merge-two-sorted-lists/
class MergeTwoLists{
public ListNode mergeTwoLists(ListNode l1,ListNode l2){
ListNode s1=l1,s2=l2;
// Dummy node to point at head of new merged list
ListNode dummy=new ListNode(0);
ListNode curr=dummy; // traversing pointer
// TC : O(m+n)
// SC : O(1) -> No new list created. We only reallocate pointers to create one list
while(s1!=null&&s2!=null){
if(s1.val<=s2.val){
curr.next=s1;
s1=s1.next;
}else{
curr.next=s2;
s2=s2.next;
}
curr=curr.next;
}
// Link remaining elements of the larger list
curr.next=s1==null?s2:s1;
return dummy.next;
}
} | 27.833333 | 91 | 0.541317 |
29ee951c501a09d156aea52a612f2f86bf5f095e | 1,280 | /*
* Copyright 2018 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.guvnor.rest.client;
import org.jboss.errai.common.client.api.annotations.Portable;
@Portable
public class PublicURI {
private String protocol;
private String uri;
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
@Override
public String toString() {
return "PublicURI{" +
"protocol='" + protocol + '\'' +
", uri='" + uri + '\'' +
'}';
}
}
| 25.6 | 75 | 0.639844 |
a1918445bb993215ea85727d44487924c5f32ae9 | 657 | package bg.softuni.programming_basics.nested_loops.lab;
import java.util.Scanner;
public class E03Combinations {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = Integer.parseInt(scanner.nextLine());
int i, j, m;
int sum;
int count = 0;
for (i = 0; i <= n; i++) {
for (j = 0; j <= n; j++) {
for (m = 0; m <= n; m++) {
sum = i + j + m;
if (sum == n) {
count++;
}
}
}
}
System.out.println(count);
}
}
| 24.333333 | 55 | 0.418569 |
3053a7d99387d5b29c68dd09af5136ade35de1f5 | 4,073 | package it.finsiel.siged.mvc.presentation.action.documentale;
import it.finsiel.siged.constant.Constants;
import it.finsiel.siged.exception.DataException;
import it.finsiel.siged.model.organizzazione.Organizzazione;
import it.finsiel.siged.model.organizzazione.Utente;
import it.finsiel.siged.mvc.business.DocumentaleDelegate;
import it.finsiel.siged.mvc.presentation.actionform.documentale.CartelleForm;
import it.finsiel.siged.mvc.presentation.actionform.documentale.DocumentiCondivisiForm;
import it.finsiel.siged.mvc.vo.documentale.CartellaVO;
import it.finsiel.siged.util.NumberUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
/**
* Implementation of <strong>Action </strong> to create a new E-Photo Utente.
*
* @author Almaviva sud.
*
*/
public final class DocumentiCondivisiAction extends Action {
static Logger logger = Logger.getLogger(DocumentiCondivisiAction.class
.getName());
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionMessages errors = new ActionMessages();
HttpSession session = request.getSession(true);
Utente utente = (Utente) session.getAttribute(Constants.UTENTE_KEY);
int utenteId = utente.getValueObject().getId().intValue();
DocumentaleDelegate delegate = DocumentaleDelegate.getInstance();
DocumentiCondivisiForm cForm = (DocumentiCondivisiForm) form;
if (request.getParameter("documentoSelezionatoId") != null) {
int docId = NumberUtil.getInt(request
.getParameter("documentoSelezionatoId"));
try {
if (delegate.getTipoPermessoSuDocumento(docId, utenteId,
Organizzazione.getInstance().getUfficio(
utente.getUfficioInUso())
.getListaUfficiDiscendentiId()) >= 0) {
request.setAttribute("documentoId", new Integer(docId));
return mapping.findForward("visualizzaDocumento");
} else {
errors.add("permissi", new ActionMessage(
"error.documento.no_permission"));
saveErrors(request, errors);
return mapping.findForward("input");
}
} catch (DataException e1) {
errors.add("generale",
new ActionMessage("database.cannot.load"));
}
}
try {
cForm.setFileCondivisi(DocumentaleDelegate.getInstance()
.getFileCondivisiC(
Organizzazione.getInstance().getUfficio(
utente.getUfficioInUso())
.getListaUfficiDiscendentiId(),
utente.getValueObject().getId().intValue())
.values());
} catch (DataException e) {
errors.add("generale", new ActionMessage("database.cannot.load"));
}
if (!errors.isEmpty())
saveErrors(request, errors);
return mapping.findForward("input");
}
public CartellaVO preparaCartellaVO(CartelleForm cForm, Utente utente) {
CartellaVO vo = new CartellaVO();
vo.setAooId(utente.getValueObject().getAooId());
vo.setNome(cForm.getNomeCartella());
vo.setParentId(cForm.getCartellaCorrenteId());
vo.setRoot(false);
vo.setUfficioId(utente.getUfficioInUso());
vo.setUtenteId(utente.getValueObject().getId().intValue());
return vo;
}
} | 42.427083 | 87 | 0.647189 |
eecb00d3f25e58d51b05cf4fae99294d77d8150c | 1,473 | /**
* Copyright 2020 yametech.
*
* 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.yametech.yangjian.agent.api.convert.statistic.impl;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.LongAdder;
import com.yametech.yangjian.agent.api.bean.TimeEvent;
import com.yametech.yangjian.agent.api.convert.statistic.StatisticType;
public class QPSStatistic extends BaseStatistic {
private LongAdder num = new LongAdder();// 当前秒数的总调用次数
@Override
protected void clear() {
num.reset();
}
@Override
public void combine(TimeEvent timeEvent) {
this.num.add(timeEvent.getNumber());
}
@Override
public Map<String, Object> statisticKV() {
Map<String, Object> kvs = new HashMap<>();
kvs.put("num", num.sum());
return kvs;
}
@Override
public StatisticType statisticType() {
return StatisticType.QPS;
}
@Override
public String toString() {
return super.toString() + " : " + num.sum();
}
}
| 25.842105 | 75 | 0.727766 |
a4a33c3d5f0f7c917fddd65cba32d570b3317377 | 885 | package com.fy.common.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ApiResult<T> {
public static final int SUCCESS = 0;
/**
* 默认错误码
*/
public static final int DEFAULT_ERROR = 1;
public static final int ERROR_CAPTCHA = 1001;
private int code;
private String msg;
private T data;
public static <T> ApiResult<T> success(T data){
return new ApiResult<>(SUCCESS, null, data);
}
public static <T> ApiResult<T> success(){
return new ApiResult<>(SUCCESS, null, null);
}
public static <T> ApiResult<T> error(String msg){
return new ApiResult<>(DEFAULT_ERROR, msg, null);
}
public static <T> ApiResult<T> error(String msg, int code){
return new ApiResult<>(code, msg, null);
}
}
| 22.692308 | 63 | 0.658757 |
ea7ff0550ce2e3446fe01846dfdcf2e3a2419afc | 1,755 | package doiframework.statistics.calculations;
import doiframework.exceptions.DatasetNotMatchingException;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import java.util.List;
public final class Covariance extends AdvancedStatistics{
/**
* @param data1 double[]
* @param data2 double[]
**/
@Contract(pure = true)
public Covariance(@NotNull double[] data1, @NotNull double[] data2){
super(data1, data2);
}
@Contract(pure = true)
public Covariance(@NotNull Double[] data1, @NotNull Double[] data2){
super(data1, data2);
}
@Contract(pure = true)
public Covariance(@NotNull Number[] data1, @NotNull Number[] data2){
super(data1, data2);
}
@Contract(pure = true)
public Covariance(@NotNull List<Number> data1, @NotNull List<Number> data2){
super(data1, data2);
}
private double covariance() throws DatasetNotMatchingException {
double sum = 0;
Average avg = new Average(data);
Average avg2 = new Average(data2);
double avgMean = avg.calcMean();
double avg2Mean = avg2.calcMean();
if (data.length != data2.length) {
throw new DatasetNotMatchingException();
}
for (int i = 0; i < n; i++) {
sum += ((data[i] - avgMean) * (data2[i] - avg2Mean));
}
return sum;
}
public double calcCovarianceFromPopulation() throws DatasetNotMatchingException {
return covariance() / n;
}
public double calcCovarianceFromSample()throws DatasetNotMatchingException {
return covariance() / (n-1);
}
@Override
public String toString() {
return "Covariance Calculation";
}
}
| 28.770492 | 85 | 0.635328 |
7c75737b4b28dc6d204e9421c254c16bfe01a5ec | 1,668 | package com.jonathanedgecombe.srt;
import java.util.ArrayList;
import java.util.List;
public class Subtitle {
private Timestamp startTime, endTime;
private final List<String> lines;
/* Create a new Subtitle with the given start and end times. */
public Subtitle(Timestamp startTime, Timestamp endTime) {
this.startTime = startTime;
this.endTime = endTime;
lines = new ArrayList<>();
}
public Timestamp getStartTime() {
return startTime;
}
public void setStartTime(Timestamp startTime) {
this.startTime = startTime;
}
public Timestamp getEndTime() {
return endTime;
}
public void setEndTime(Timestamp endTime) {
this.endTime = endTime;
}
public void clearLines() {
lines.clear();
}
public void addLine(String line) {
lines.add(line);
}
public void removeLine(String line) {
lines.remove(line);
}
public void removeLine(int index) {
lines.remove(index);
}
public String getLine(int index) {
return lines.get(index);
}
public List<String> getLines() {
return lines;
}
/* Compiles subtitle into a string with the given subtitle index. */
public String compile(int index) {
String subtitle = "";
subtitle += Integer.toString(index) + "\n";
subtitle += startTime.compile() + " --> " + endTime.compile() + "\n";
for (String line : lines) {
subtitle += line + "\n";
}
subtitle += "\n";
return subtitle;
}
public static String formatLine(String line) {
/* Replace CRLF with LF for neatness. */
line = line.replace("\r\n", "\n");
/* Empty line marks the end of a subtitle, replace it with a space. */
line = line.replace("\n\n", "\n \n");
return line;
}
}
| 20.341463 | 73 | 0.667266 |
a3e279644013ee3aa601fa7a4f38435b40d7316c | 20,734 | package com.mercari.solution.module.transform;
import com.google.cloud.spanner.Struct;
import com.google.datastore.v1.Entity;
import com.google.datastore.v1.Value;
import com.google.gson.*;
import com.google.protobuf.NullValue;
import com.mercari.solution.config.TransformConfig;
import com.mercari.solution.module.DataType;
import com.mercari.solution.module.FCollection;
import com.mercari.solution.util.schema.AvroSchemaUtil;
import org.apache.avro.SchemaBuilder;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.generic.GenericRecordBuilder;
import org.apache.beam.sdk.coders.AvroCoder;
import org.apache.beam.sdk.schemas.Schema;
import org.apache.beam.sdk.testing.PAssert;
import org.apache.beam.sdk.testing.TestPipeline;
import org.apache.beam.sdk.transforms.Create;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.sdk.values.Row;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import java.util.Arrays;
import java.util.Map;
public class PartitionTransformTest {
@Rule
public final transient TestPipeline pipeline = TestPipeline.create();
@Test
public void testRow() {
final TransformConfig config = new TransformConfig();
config.setName("partition");
config.setModule("partition");
config.setInputs(Arrays.asList("rowInput"));
config.setParameters(createPartitionParameters());
final Schema rowSchema = Schema.builder()
.addField("stringField", Schema.FieldType.STRING.withNullable(true))
.addInt64Field("intField")
.addDoubleField("floatField")
.build();
Row testRow1 = Row.withSchema(rowSchema)
.withFieldValue("stringField", "a")
.withFieldValue("intField", 1L)
.withFieldValue("floatField", 0.15D)
.build();
Row testRow2 = Row.withSchema(rowSchema)
.withFieldValue("stringField", "b")
.withFieldValue("intField", 2L)
.withFieldValue("floatField", -0.15D)
.build();
Row testRow3 = Row.withSchema(rowSchema)
.withFieldValue("stringField", null)
.withFieldValue("intField", 3L)
.withFieldValue("floatField", 0.0D)
.build();
final PCollection<Row> inputStructs = pipeline
.apply("CreateDummy", Create.of(testRow1, testRow2, testRow3));
final FCollection<Row> fCollection = FCollection.of("rowInput", inputStructs, DataType.ROW, rowSchema);
final Map<String, FCollection<?>> outputs = PartitionTransform.transform(Arrays.asList(fCollection), config);
final PCollection<Row> outputRows1 = (PCollection<Row>) outputs.get("partition.output1").getCollection();
final PCollection<Row> outputRows2 = (PCollection<Row>) outputs.get("partition.output2").getCollection();
final PCollection<Row> outputRows3 = (PCollection<Row>) outputs.get("partition.output3").getCollection();
final PCollection<Row> outputRows4 = (PCollection<Row>) outputs.get("partition.output4").getCollection();
final PCollection<Row> outputRows5 = (PCollection<Row>) outputs.get("partition.output5").getCollection();
PAssert.that(outputRows1).satisfies(rows -> {
int count = 0;
for(final Row row : rows) {
Assert.assertEquals("a", row.getString("stringField"));
count++;
}
Assert.assertEquals(1, count);
return null;
});
PAssert.that(outputRows2).satisfies(rows -> {
int count = 0;
for(final Row row : rows) {
Assert.assertTrue(row.getInt64("intField") <= 2);
count++;
}
Assert.assertEquals(2, count);
return null;
});
PAssert.that(outputRows3).satisfies(rows -> {
int count = 0;
for(final Row row : rows) {
Assert.assertTrue(row.getDouble("floatField") > 0);
count++;
}
Assert.assertEquals(1, count);
return null;
});
PAssert.that(outputRows4).satisfies(rows -> {
int count = 0;
for(final Row row : rows) {
Assert.assertTrue(row.getString("stringField").equals("a"));
count++;
}
Assert.assertEquals(1, count);
return null;
});
PAssert.that(outputRows5).satisfies(rows -> {
int count = 0;
for(final Row row : rows) {
Assert.assertNull(row.getValue("stringField"));
count++;
}
Assert.assertEquals(1, count);
return null;
});
pipeline.run();
}
@Test
public void testAvro() {
final TransformConfig config = new TransformConfig();
config.setName("partition");
config.setModule("partition");
config.setInputs(Arrays.asList("rowInput"));
config.setParameters(createPartitionParameters());
final org.apache.avro.Schema avroSchema = SchemaBuilder.builder()
.record("record").fields()
.name("stringField").type(AvroSchemaUtil.NULLABLE_STRING).noDefault()
.name("intField").type(AvroSchemaUtil.NULLABLE_LONG).noDefault()
.name("floatField").type(AvroSchemaUtil.NULLABLE_DOUBLE).noDefault()
.endRecord();
final GenericRecord testRecord1 = new GenericRecordBuilder(avroSchema)
.set("stringField", "a")
.set("intField", 1L)
.set("floatField", 0.15D)
.build();
final GenericRecord testRecord2 = new GenericRecordBuilder(avroSchema)
.set("stringField", "b")
.set("intField", 2L)
.set("floatField", -0.15D)
.build();
final GenericRecord testRecord3 = new GenericRecordBuilder(avroSchema)
.set("stringField", null)
.set("intField", 3L)
.set("floatField", 0.0D)
.build();
final PCollection<GenericRecord> inputStructs = pipeline
.apply("CreateDummy", Create.of(testRecord1, testRecord2, testRecord3).withCoder(AvroCoder.of(avroSchema)));
//.setCoder(AvroCoder.of(avroSchema));
final FCollection<GenericRecord> fCollection = FCollection.of("avroInput", inputStructs, DataType.AVRO, avroSchema);
final Map<String, FCollection<?>> outputs = PartitionTransform.transform(Arrays.asList(fCollection), config);
final PCollection<GenericRecord> outputRecords1 = (PCollection<GenericRecord>) outputs.get("partition.output1").getCollection();
final PCollection<GenericRecord> outputRecords2 = (PCollection<GenericRecord>) outputs.get("partition.output2").getCollection();
final PCollection<GenericRecord> outputRecords3 = (PCollection<GenericRecord>) outputs.get("partition.output3").getCollection();
final PCollection<GenericRecord> outputRecords4 = (PCollection<GenericRecord>) outputs.get("partition.output4").getCollection();
final PCollection<GenericRecord> outputRecords5 = (PCollection<GenericRecord>) outputs.get("partition.output5").getCollection();
PAssert.that(outputRecords1).satisfies(records -> {
int count = 0;
for(final GenericRecord record : records) {
Assert.assertEquals("a", record.get("stringField").toString());
count++;
}
Assert.assertEquals(1, count);
return null;
});
PAssert.that(outputRecords2).satisfies(records -> {
int count = 0;
for(final GenericRecord record : records) {
Assert.assertTrue((Long)record.get("intField") <= 2);
count++;
}
Assert.assertEquals(2, count);
return null;
});
PAssert.that(outputRecords3).satisfies(records -> {
int count = 0;
for(final GenericRecord record : records) {
Assert.assertTrue((Double)record.get("floatField") > 0);
count++;
}
Assert.assertEquals(1, count);
return null;
});
PAssert.that(outputRecords4).satisfies(records -> {
int count = 0;
for(final GenericRecord record : records) {
Assert.assertTrue(record.get("stringField").toString().equals("a"));
count++;
}
Assert.assertEquals(1, count);
return null;
});
PAssert.that(outputRecords5).satisfies(records -> {
int count = 0;
for(final GenericRecord record : records) {
Assert.assertNull(record.get("stringField"));
count++;
}
Assert.assertEquals(1, count);
return null;
});
pipeline.run();
}
@Test
public void testStruct() {
final TransformConfig config = new TransformConfig();
config.setName("partition");
config.setModule("partition");
config.setInputs(Arrays.asList("structInput"));
config.setParameters(createPartitionParameters());
Struct testStruct1 = Struct.newBuilder()
.set("stringField").to("a")
.set("intField").to(1)
.set("floatField").to(0.15D)
.build();
Struct testStruct2 = Struct.newBuilder()
.set("stringField").to("b")
.set("intField").to(2)
.set("floatField").to(-0.15D)
.build();
Struct testStruct3 = Struct.newBuilder()
.set("stringField").to((String)null)
.set("intField").to(3)
.set("floatField").to(0.0D)
.build();
final PCollection<Struct> inputStructs = pipeline
.apply("CreateDummy", Create.of(testStruct1, testStruct2, testStruct3));
final FCollection<Struct> fCollection = FCollection.of("structInput", inputStructs, DataType.STRUCT, testStruct1.getType());
final Map<String, FCollection<?>> outputs = PartitionTransform.transform(Arrays.asList(fCollection), config);
final PCollection<Struct> outputStructs1 = (PCollection<Struct>) outputs.get("partition.output1").getCollection();
final PCollection<Struct> outputStructs2 = (PCollection<Struct>) outputs.get("partition.output2").getCollection();
final PCollection<Struct> outputStructs3 = (PCollection<Struct>) outputs.get("partition.output3").getCollection();
final PCollection<Struct> outputStructs4 = (PCollection<Struct>) outputs.get("partition.output4").getCollection();
final PCollection<Struct> outputStructs5 = (PCollection<Struct>) outputs.get("partition.output5").getCollection();
PAssert.that(outputStructs1).satisfies(structs -> {
int count = 0;
for(final Struct struct : structs) {
Assert.assertEquals("a", struct.getString("stringField"));
count++;
}
Assert.assertEquals(1, count);
return null;
});
PAssert.that(outputStructs2).satisfies(structs -> {
int count = 0;
for(final Struct struct : structs) {
Assert.assertTrue(struct.getLong("intField") <= 2);
count++;
}
Assert.assertEquals(2, count);
return null;
});
PAssert.that(outputStructs3).satisfies(structs -> {
int count = 0;
for(final Struct struct : structs) {
Assert.assertTrue(struct.getDouble("floatField") > 0);
count++;
}
Assert.assertEquals(1, count);
return null;
});
PAssert.that(outputStructs4).satisfies(structs -> {
int count = 0;
for(final Struct struct : structs) {
Assert.assertTrue(struct.getString("stringField").equals("a"));
count++;
}
Assert.assertEquals(1, count);
return null;
});
PAssert.that(outputStructs5).satisfies(structs -> {
int count = 0;
for(final Struct struct : structs) {
Assert.assertTrue(struct.isNull("stringField"));
count++;
}
Assert.assertEquals(1, count);
return null;
});
pipeline.run();
}
@Test
public void testEntity() {
final TransformConfig config = new TransformConfig();
config.setName("partition");
config.setModule("partition");
config.setInputs(Arrays.asList("entityInput"));
config.setParameters(createPartitionParameters());
final Schema rowSchema = Schema.builder()
.addStringField("stringField")
.addInt64Field("intField")
.addDoubleField("floatField")
.build();
final Entity testEntity1 = Entity.newBuilder()
.putProperties("stringField", Value.newBuilder().setStringValue("a").build())
.putProperties("intField", Value.newBuilder().setIntegerValue(1).build())
.putProperties("floatField", Value.newBuilder().setDoubleValue(0.15D).build())
.build();
final Entity testEntity2 = Entity.newBuilder()
.putProperties("stringField", Value.newBuilder().setStringValue("b").build())
.putProperties("intField", Value.newBuilder().setIntegerValue(2).build())
.putProperties("floatField", Value.newBuilder().setDoubleValue(-0.15D).build())
.build();
final Entity testEntity3 = Entity.newBuilder()
.putProperties("stringField", Value.newBuilder().setNullValue(NullValue.NULL_VALUE).build())
.putProperties("intField", Value.newBuilder().setIntegerValue(3).build())
.putProperties("floatField", Value.newBuilder().setDoubleValue(0D).build())
.build();
final PCollection<Entity> inputEntities = pipeline
.apply("CreateDummy", Create.of(testEntity1, testEntity2, testEntity3));
final FCollection<Entity> fCollection = FCollection.of("entityInput", inputEntities, DataType.ENTITY, rowSchema);
final Map<String, FCollection<?>> outputs = PartitionTransform.transform(Arrays.asList(fCollection), config);
final PCollection<Entity> outputEntities1 = (PCollection<Entity>) outputs.get("partition.output1").getCollection();
final PCollection<Entity> outputEntities2 = (PCollection<Entity>) outputs.get("partition.output2").getCollection();
final PCollection<Entity> outputEntities3 = (PCollection<Entity>) outputs.get("partition.output3").getCollection();
final PCollection<Entity> outputEntities4 = (PCollection<Entity>) outputs.get("partition.output4").getCollection();
final PCollection<Entity> outputEntities5 = (PCollection<Entity>) outputs.get("partition.output5").getCollection();
PAssert.that(outputEntities1).satisfies(entities -> {
int count = 0;
for(final Entity entity : entities) {
Assert.assertEquals("a", entity.getPropertiesMap().get("stringField").getStringValue());
count++;
}
Assert.assertEquals(1, count);
return null;
});
PAssert.that(outputEntities2).satisfies(entities -> {
int count = 0;
for(final Entity entity : entities) {
Assert.assertTrue(entity.getPropertiesMap().get("intField").getIntegerValue() <= 2);
count++;
}
Assert.assertEquals(2, count);
return null;
});
PAssert.that(outputEntities3).satisfies(entities -> {
int count = 0;
for(final Entity entity : entities) {
Assert.assertTrue(entity.getPropertiesMap().get("floatField").getDoubleValue() > 0);
count++;
}
Assert.assertEquals(1, count);
return null;
});
PAssert.that(outputEntities4).satisfies(entities -> {
int count = 0;
for(final Entity entity : entities) {
Assert.assertTrue(entity.getPropertiesOrThrow("stringField").getStringValue().equals("a"));
count++;
}
Assert.assertEquals(1, count);
return null;
});
PAssert.that(outputEntities5).satisfies(entities -> {
int count = 0;
for(final Entity entity : entities) {
Assert.assertTrue(entity.getPropertiesOrThrow("stringField").getNullValue().equals(NullValue.NULL_VALUE));
count++;
}
Assert.assertEquals(1, count);
return null;
});
pipeline.run();
}
private JsonObject createPartitionParameters() {
final JsonArray partitions = new JsonArray();
{
final JsonObject partition1 = new JsonObject();
partition1.addProperty("output", "output1");
final JsonArray filters = new JsonArray();
final JsonObject filter = new JsonObject();
filter.addProperty("key", "stringField");
filter.addProperty("op", "=");
filter.addProperty("value", "a");
filters.add(filter);
partition1.add("filters", filters);
partitions.add(partition1);
}
{
final JsonObject partition2 = new JsonObject();
partition2.addProperty("output", "output2");
final JsonArray filters = new JsonArray();
final JsonObject filter = new JsonObject();
filter.addProperty("key", "intField");
filter.addProperty("op", "<=");
filter.addProperty("value", 2);
filters.add(filter);
partition2.add("filters", filters);
partitions.add(partition2);
}
{
final JsonObject partition3 = new JsonObject();
partition3.addProperty("output", "output3");
final JsonArray filters = new JsonArray();
final JsonObject filter = new JsonObject();
filter.addProperty("key", "floatField");
filter.addProperty("op", ">");
filter.addProperty("value", 0);
filters.add(filter);
partition3.add("filters", filters);
partitions.add(partition3);
}
{
final JsonObject partition4 = new JsonObject();
partition4.addProperty("output", "output4");
final JsonArray filters = new JsonArray();
{
final JsonObject filter = new JsonObject();
filter.addProperty("key", "stringField");
filter.addProperty("op", "!=");
filter.addProperty("value", "null");
filters.add(filter);
}
{
final JsonObject filter = new JsonObject();
filter.addProperty("key", "intField");
filter.addProperty("op", "<");
filter.addProperty("value", 2);
filters.add(filter);
}
{
final JsonObject filter = new JsonObject();
filter.addProperty("key", "floatField");
filter.addProperty("op", ">");
filter.addProperty("value", 0);
filters.add(filter);
}
partition4.add("filters", filters);
partitions.add(partition4);
}
{
final JsonObject partition5 = new JsonObject();
partition5.addProperty("output", "output5");
final JsonArray filters = new JsonArray();
{
final JsonObject filter = new JsonObject();
filter.addProperty("key", "stringField");
filter.addProperty("op", "=");
filter.add("value", JsonNull.INSTANCE);
filters.add(filter);
}
partition5.add("filters", filters);
partitions.add(partition5);
}
final JsonObject parameters = new JsonObject();
parameters.addProperty("exclusive", false);
parameters.add("partitions", partitions);
return parameters;
}
}
| 40.734774 | 136 | 0.580496 |
0f2ca34f02f6f979eb85e0c77063f8980bfbbcb9 | 1,376 | package org.extreme.script.core.parser;
import java.io.Serializable;
import org.extreme.base.ColumnRow;
public class LocationDim implements Cloneable, Serializable {
public static final byte ABSOLUTE = 0;
public static final byte PLUS = 1;
public static final byte MINUS = 2;
private ColumnRow columnrow;
private int index;
private byte op;
public LocationDim(ColumnRow columnrow, byte op, int index) {
this.columnrow = columnrow;
this.op = op;
this.index = index;
}
public ColumnRow getColumnrow() {
return columnrow;
}
public void setIndex(int idx) {
this.index = idx;
}
public int getIndex() {
return index;
}
public byte getOp() {
return op;
}
public String toString() {
return this.columnrow + ":" + (op == PLUS ? "+" : (op == MINUS ? "-" : "!")) + this.index;
}
public void changeColumnRow(int rowIndex, int rowChanged, int columnIndex, int colChanged){
int newColumnIndex = columnrow.getColumn();
if (columnIndex != -1 && columnrow.getColumn() >= columnIndex) {
newColumnIndex += colChanged;
}
int newRowIndex = columnrow.getRow();
if (rowIndex != -1 && columnrow.getRow() >= rowIndex) {
newRowIndex += rowChanged;
}
columnrow = ColumnRow.valueOf(newColumnIndex, newRowIndex);
}
}
| 24.571429 | 93 | 0.632267 |
e4c58f020fd3e2e89408d7955da3b508ebcb4919 | 5,607 | package com.winsun.fruitmix.video;
import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.support.v4.util.ArrayMap;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.widget.VideoView;
import com.winsun.fruitmix.R;
import com.winsun.fruitmix.databinding.PlayVideoFragmentBinding;
import com.winsun.fruitmix.file.data.model.RemoteFile;
import com.winsun.fruitmix.http.HttpRequest;
import com.winsun.fruitmix.http.InjectHttp;
import com.winsun.fruitmix.http.request.factory.HttpRequestFactory;
import com.winsun.fruitmix.mediaModule.model.Video;
import com.winsun.fruitmix.util.Util;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import static com.winsun.fruitmix.file.data.station.StationFileDataSourceImpl.DOWNLOAD_FILE_PARAMETER;
/**
* Created by Administrator on 2017/11/2.
*/
public class PlayVideoFragment {
public static final String TAG = PlayVideoFragment.class.getSimpleName();
private VideoView videoView;
private HttpRequestFactory httpRequestFactory;
private View view;
private ImageView playVideoView;
private ProgressBar progressBar;
private boolean mIsPlaying = false;
public PlayVideoFragment(Context context) {
initVideoView(context);
}
private void initVideoView(Context context) {
PlayVideoFragmentBinding binding = PlayVideoFragmentBinding.inflate(LayoutInflater.from(context), null, false);
view = binding.getRoot();
playVideoView = binding.playVideo;
videoView = binding.videoView;
progressBar = binding.progressBar;
httpRequestFactory = InjectHttp.provideHttpRequestFactory(context);
MediaController mediaController = new MediaController(context);
mediaController.setAnchorView(videoView);
videoView.setMediaController(mediaController);
videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
onPlayCompleted();
}
});
videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Log.d(TAG, "onError: what: " + what + " extra: " + extra);
progressBar.setVisibility(View.INVISIBLE);
onPlayCompleted();
Context viewContext = view.getContext();
Toast.makeText(viewContext, viewContext.getString(R.string.fail, viewContext.getString(R.string.play_video)), Toast.LENGTH_SHORT).show();
return true;
}
});
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
progressBar.setVisibility(View.INVISIBLE);
mIsPlaying = true;
}
});
}
private void onPlayCompleted() {
playVideoView.setVisibility(View.VISIBLE);
mIsPlaying = false;
}
public View getView() {
return view;
}
public void startPlayVideo(Video video, Context context) {
startPlayVideo(getHttpRequest(video, context));
}
public void startPlayVideo(String driveRootUUID, RemoteFile remoteFile) {
startPlayVideo(getHttpRequest(driveRootUUID, remoteFile));
}
private void startPlayVideo(HttpRequest httpRequest) {
if (mIsPlaying) {
return;
}
if (playVideoView.getVisibility() == View.VISIBLE)
playVideoView.setVisibility(View.INVISIBLE);
progressBar.setVisibility(View.VISIBLE);
String url = httpRequest.getUrl();
Uri uri = Uri.parse(url);
Map<String, String> map = new HashMap<>();
map.put(httpRequest.getHeaderKey(), httpRequest.getHeaderValue());
if (Util.checkRunningOnLollipopOrHigher()) {
videoView.setVideoURI(uri, map);
} else {
videoView.setVideoURI(uri);
try {
Field field = VideoView.class.getDeclaredField("mHeaders");
field.setAccessible(true);
field.set(videoView, map);
} catch (Exception e) {
e.printStackTrace();
}
}
videoView.start();
}
private HttpRequest getHttpRequest(String driveRootUUID, RemoteFile remoteFile) {
String encodedFileName = null;
try {
encodedFileName = URLEncoder.encode(remoteFile.getName(), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return httpRequestFactory.createHttpGetFileRequest(DOWNLOAD_FILE_PARAMETER + "/"
+ driveRootUUID + "/dirs/" + remoteFile.getParentFolderUUID()
+ "/entries/" + remoteFile.getUuid() + "?name=" + encodedFileName);
}
private HttpRequest getHttpRequest(Video video, Context context) {
return video.getImageOriginalUrl(context);
}
public void stopPlayVideo() {
videoView.stopPlayback();
videoView.suspend();
onPlayCompleted();
}
public void onDestroy() {
}
}
| 25.60274 | 153 | 0.66417 |
31aad16b024453f57e4e2f529ecff305830426e1 | 20,133 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2.source;
import static com.google.android.exoplayer2.util.Util.castNonNull;
import android.content.Context;
import android.util.Pair;
import android.util.SparseArray;
import androidx.annotation.Nullable;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.drm.DrmSessionManager;
import com.google.android.exoplayer2.drm.DrmSessionManagerProvider;
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory;
import com.google.android.exoplayer2.extractor.ExtractorsFactory;
import com.google.android.exoplayer2.offline.StreamKey;
import com.google.android.exoplayer2.source.ads.AdsLoader;
import com.google.android.exoplayer2.source.ads.AdsLoader.AdViewProvider;
import com.google.android.exoplayer2.source.ads.AdsMediaSource;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DataSpec;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.upstream.HttpDataSource;
import com.google.android.exoplayer2.upstream.LoadErrorHandlingPolicy;
import com.google.android.exoplayer2.util.Assertions;
import com.google.android.exoplayer2.util.Log;
import com.google.android.exoplayer2.util.MimeTypes;
import com.google.android.exoplayer2.util.Util;
import java.util.Arrays;
import java.util.List;
/**
* The default {@link MediaSourceFactory} implementation.
*
* <p>This implementation delegates calls to {@link #createMediaSource(MediaItem)} to the following
* factories:
*
* <ul>
* <li>{@code DashMediaSource.Factory} if the item's {@link MediaItem.PlaybackProperties#uri uri}
* ends in '.mpd' or if its {@link MediaItem.PlaybackProperties#mimeType mimeType field} is
* explicitly set to {@link MimeTypes#APPLICATION_MPD} (Requires the <a
* href="https://exoplayer.dev/hello-world.html#add-exoplayer-modules">exoplayer-dash module
* to be added</a> to the app).
* <li>{@code HlsMediaSource.Factory} if the item's {@link MediaItem.PlaybackProperties#uri uri}
* ends in '.m3u8' or if its {@link MediaItem.PlaybackProperties#mimeType mimeType field} is
* explicitly set to {@link MimeTypes#APPLICATION_M3U8} (Requires the <a
* href="https://exoplayer.dev/hello-world.html#add-exoplayer-modules">exoplayer-hls module to
* be added</a> to the app).
* <li>{@code SsMediaSource.Factory} if the item's {@link MediaItem.PlaybackProperties#uri uri}
* ends in '.ism', '.ism/Manifest' or if its {@link MediaItem.PlaybackProperties#mimeType
* mimeType field} is explicitly set to {@link MimeTypes#APPLICATION_SS} (Requires the <a
* href="https://exoplayer.dev/hello-world.html#add-exoplayer-modules">
* exoplayer-smoothstreaming module to be added</a> to the app).
* <li>{@link ProgressiveMediaSource.Factory} serves as a fallback if the item's {@link
* MediaItem.PlaybackProperties#uri uri} doesn't match one of the above. It tries to infer the
* required extractor by using the {@link
* com.google.android.exoplayer2.extractor.DefaultExtractorsFactory} or the {@link
* ExtractorsFactory} provided in the constructor. An {@link UnrecognizedInputFormatException}
* is thrown if none of the available extractors can read the stream.
* </ul>
*
* <h3>Ad support for media items with ad tag URIs</h3>
*
* <p>To support media items with {@link MediaItem.PlaybackProperties#adsConfiguration ads
* configuration}, {@link #setAdsLoaderProvider} and {@link #setAdViewProvider} need to be called to
* configure the factory with the required providers.
*/
public final class DefaultMediaSourceFactory implements MediaSourceFactory {
/**
* Provides {@link AdsLoader} instances for media items that have {@link
* MediaItem.PlaybackProperties#adsConfiguration ad tag URIs}.
*/
public interface AdsLoaderProvider {
/**
* Returns an {@link AdsLoader} for the given {@link
* MediaItem.PlaybackProperties#adsConfiguration ads configuration}, or {@code null} if no ads
* loader is available for the given ads configuration.
*
* <p>This method is called each time a {@link MediaSource} is created from a {@link MediaItem}
* that defines an {@link MediaItem.PlaybackProperties#adsConfiguration ads configuration}.
*/
@Nullable
AdsLoader getAdsLoader(MediaItem.AdsConfiguration adsConfiguration);
}
private static final String TAG = "DefaultMediaSourceFactory";
private final DataSource.Factory dataSourceFactory;
private final SparseArray<MediaSourceFactory> mediaSourceFactories;
@C.ContentType private final int[] supportedTypes;
@Nullable private AdsLoaderProvider adsLoaderProvider;
@Nullable private AdViewProvider adViewProvider;
@Nullable private LoadErrorHandlingPolicy loadErrorHandlingPolicy;
private long liveTargetOffsetMs;
private long liveMinOffsetMs;
private long liveMaxOffsetMs;
private float liveMinSpeed;
private float liveMaxSpeed;
/**
* Creates a new instance.
*
* @param context Any context.
*/
public DefaultMediaSourceFactory(Context context) {
this(new DefaultDataSourceFactory(context));
}
/**
* Creates a new instance.
*
* @param context Any context.
* @param extractorsFactory An {@link ExtractorsFactory} used to extract progressive media from
* its container.
*/
public DefaultMediaSourceFactory(Context context, ExtractorsFactory extractorsFactory) {
this(new DefaultDataSourceFactory(context), extractorsFactory);
}
/**
* Creates a new instance.
*
* @param dataSourceFactory A {@link DataSource.Factory} to create {@link DataSource} instances
* for requesting media data.
*/
public DefaultMediaSourceFactory(DataSource.Factory dataSourceFactory) {
this(dataSourceFactory, new DefaultExtractorsFactory());
}
/**
* Creates a new instance.
*
* @param dataSourceFactory A {@link DataSource.Factory} to create {@link DataSource} instances
* for requesting media data.
* @param extractorsFactory An {@link ExtractorsFactory} used to extract progressive media from
* its container.
*/
public DefaultMediaSourceFactory(
DataSource.Factory dataSourceFactory, ExtractorsFactory extractorsFactory) {
this.dataSourceFactory = dataSourceFactory;
mediaSourceFactories = loadDelegates(dataSourceFactory, extractorsFactory);
supportedTypes = new int[mediaSourceFactories.size()];
for (int i = 0; i < mediaSourceFactories.size(); i++) {
supportedTypes[i] = mediaSourceFactories.keyAt(i);
}
liveTargetOffsetMs = C.TIME_UNSET;
liveMinOffsetMs = C.TIME_UNSET;
liveMaxOffsetMs = C.TIME_UNSET;
liveMinSpeed = C.RATE_UNSET;
liveMaxSpeed = C.RATE_UNSET;
}
/**
* Sets the {@link AdsLoaderProvider} that provides {@link AdsLoader} instances for media items
* that have {@link MediaItem.PlaybackProperties#adsConfiguration ads configurations}.
*
* @param adsLoaderProvider A provider for {@link AdsLoader} instances.
* @return This factory, for convenience.
*/
public DefaultMediaSourceFactory setAdsLoaderProvider(
@Nullable AdsLoaderProvider adsLoaderProvider) {
this.adsLoaderProvider = adsLoaderProvider;
return this;
}
/**
* Sets the {@link AdViewProvider} that provides information about views for the ad playback UI.
*
* @param adViewProvider A provider for {@link AdsLoader} instances.
* @return This factory, for convenience.
*/
public DefaultMediaSourceFactory setAdViewProvider(@Nullable AdViewProvider adViewProvider) {
this.adViewProvider = adViewProvider;
return this;
}
/**
* Sets the target live offset for live streams, in milliseconds.
*
* @param liveTargetOffsetMs The target live offset, in milliseconds, or {@link C#TIME_UNSET} to
* use the media-defined default.
* @return This factory, for convenience.
*/
public DefaultMediaSourceFactory setLiveTargetOffsetMs(long liveTargetOffsetMs) {
this.liveTargetOffsetMs = liveTargetOffsetMs;
return this;
}
/**
* Sets the minimum offset from the live edge for live streams, in milliseconds.
*
* @param liveMinOffsetMs The minimum allowed live offset, in milliseconds, or {@link
* C#TIME_UNSET} to use the media-defined default.
* @return This factory, for convenience.
*/
public DefaultMediaSourceFactory setLiveMinOffsetMs(long liveMinOffsetMs) {
this.liveMinOffsetMs = liveMinOffsetMs;
return this;
}
/**
* Sets the maximum offset from the live edge for live streams, in milliseconds.
*
* @param liveMaxOffsetMs The maximum allowed live offset, in milliseconds, or {@link
* C#TIME_UNSET} to use the media-defined default.
* @return This factory, for convenience.
*/
public DefaultMediaSourceFactory setLiveMaxOffsetMs(long liveMaxOffsetMs) {
this.liveMaxOffsetMs = liveMaxOffsetMs;
return this;
}
/**
* Sets the minimum playback speed for live streams.
*
* @param minSpeed The minimum factor by which playback can be sped up for live streams, or {@link
* C#RATE_UNSET} to use the media-defined default.
* @return This factory, for convenience.
*/
public DefaultMediaSourceFactory setLiveMinSpeed(float minSpeed) {
this.liveMinSpeed = minSpeed;
return this;
}
/**
* Sets the maximum playback speed for live streams.
*
* @param maxSpeed The maximum factor by which playback can be sped up for live streams, or {@link
* C#RATE_UNSET} to use the media-defined default.
* @return This factory, for convenience.
*/
public DefaultMediaSourceFactory setLiveMaxSpeed(float maxSpeed) {
this.liveMaxSpeed = maxSpeed;
return this;
}
@SuppressWarnings("deprecation") // Calling through to the same deprecated method.
@Override
public DefaultMediaSourceFactory setDrmHttpDataSourceFactory(
@Nullable HttpDataSource.Factory drmHttpDataSourceFactory) {
for (int i = 0; i < mediaSourceFactories.size(); i++) {
mediaSourceFactories.valueAt(i).setDrmHttpDataSourceFactory(drmHttpDataSourceFactory);
}
return this;
}
@SuppressWarnings("deprecation") // Calling through to the same deprecated method.
@Override
public DefaultMediaSourceFactory setDrmUserAgent(@Nullable String userAgent) {
for (int i = 0; i < mediaSourceFactories.size(); i++) {
mediaSourceFactories.valueAt(i).setDrmUserAgent(userAgent);
}
return this;
}
@SuppressWarnings("deprecation") // Calling through to the same deprecated method.
@Override
public DefaultMediaSourceFactory setDrmSessionManager(
@Nullable DrmSessionManager drmSessionManager) {
for (int i = 0; i < mediaSourceFactories.size(); i++) {
mediaSourceFactories.valueAt(i).setDrmSessionManager(drmSessionManager);
}
return this;
}
@Override
public DefaultMediaSourceFactory setDrmSessionManagerProvider(
@Nullable DrmSessionManagerProvider drmSessionManagerProvider) {
for (int i = 0; i < mediaSourceFactories.size(); i++) {
mediaSourceFactories.valueAt(i).setDrmSessionManagerProvider(drmSessionManagerProvider);
}
return this;
}
@Override
public DefaultMediaSourceFactory setLoadErrorHandlingPolicy(
@Nullable LoadErrorHandlingPolicy loadErrorHandlingPolicy) {
this.loadErrorHandlingPolicy = loadErrorHandlingPolicy;
for (int i = 0; i < mediaSourceFactories.size(); i++) {
mediaSourceFactories.valueAt(i).setLoadErrorHandlingPolicy(loadErrorHandlingPolicy);
}
return this;
}
/**
* @deprecated Use {@link MediaItem.Builder#setStreamKeys(List)} and {@link
* #createMediaSource(MediaItem)} instead.
*/
@SuppressWarnings("deprecation") // Calling through to the same deprecated method.
@Deprecated
@Override
public DefaultMediaSourceFactory setStreamKeys(@Nullable List<StreamKey> streamKeys) {
for (int i = 0; i < mediaSourceFactories.size(); i++) {
mediaSourceFactories.valueAt(i).setStreamKeys(streamKeys);
}
return this;
}
@Override
public int[] getSupportedTypes() {
return Arrays.copyOf(supportedTypes, supportedTypes.length);
}
@Override
public MediaSource createMediaSource(MediaItem mediaItem) {
Assertions.checkNotNull(mediaItem.playbackProperties);
@C.ContentType
int type =
Util.inferContentTypeForUriAndMimeType(
mediaItem.playbackProperties.uri, mediaItem.playbackProperties.mimeType);
@Nullable MediaSourceFactory mediaSourceFactory = mediaSourceFactories.get(type);
Assertions.checkNotNull(
mediaSourceFactory, "No suitable media source factory found for content type: " + type);
// Make sure to retain the very same media item instance, if no value needs to be overridden.
if ((mediaItem.liveConfiguration.targetOffsetMs == C.TIME_UNSET
&& liveTargetOffsetMs != C.TIME_UNSET)
|| (mediaItem.liveConfiguration.minPlaybackSpeed == C.RATE_UNSET
&& liveMinSpeed != C.RATE_UNSET)
|| (mediaItem.liveConfiguration.maxPlaybackSpeed == C.RATE_UNSET
&& liveMaxSpeed != C.RATE_UNSET)
|| (mediaItem.liveConfiguration.minOffsetMs == C.TIME_UNSET
&& liveMinOffsetMs != C.TIME_UNSET)
|| (mediaItem.liveConfiguration.maxOffsetMs == C.TIME_UNSET
&& liveMaxOffsetMs != C.TIME_UNSET)) {
mediaItem =
mediaItem
.buildUpon()
.setLiveTargetOffsetMs(
mediaItem.liveConfiguration.targetOffsetMs == C.TIME_UNSET
? liveTargetOffsetMs
: mediaItem.liveConfiguration.targetOffsetMs)
.setLiveMinPlaybackSpeed(
mediaItem.liveConfiguration.minPlaybackSpeed == C.RATE_UNSET
? liveMinSpeed
: mediaItem.liveConfiguration.minPlaybackSpeed)
.setLiveMaxPlaybackSpeed(
mediaItem.liveConfiguration.maxPlaybackSpeed == C.RATE_UNSET
? liveMaxSpeed
: mediaItem.liveConfiguration.maxPlaybackSpeed)
.setLiveMinOffsetMs(
mediaItem.liveConfiguration.minOffsetMs == C.TIME_UNSET
? liveMinOffsetMs
: mediaItem.liveConfiguration.minOffsetMs)
.setLiveMaxOffsetMs(
mediaItem.liveConfiguration.maxOffsetMs == C.TIME_UNSET
? liveMaxOffsetMs
: mediaItem.liveConfiguration.maxOffsetMs)
.build();
}
MediaSource mediaSource = mediaSourceFactory.createMediaSource(mediaItem);
List<MediaItem.Subtitle> subtitles = castNonNull(mediaItem.playbackProperties).subtitles;
if (!subtitles.isEmpty()) {
MediaSource[] mediaSources = new MediaSource[subtitles.size() + 1];
mediaSources[0] = mediaSource;
SingleSampleMediaSource.Factory singleSampleSourceFactory =
new SingleSampleMediaSource.Factory(dataSourceFactory)
.setLoadErrorHandlingPolicy(loadErrorHandlingPolicy);
for (int i = 0; i < subtitles.size(); i++) {
mediaSources[i + 1] =
singleSampleSourceFactory.createMediaSource(
subtitles.get(i), /* durationUs= */ C.TIME_UNSET);
}
mediaSource = new MergingMediaSource(mediaSources);
}
return maybeWrapWithAdsMediaSource(mediaItem, maybeClipMediaSource(mediaItem, mediaSource));
}
// internal methods
private static MediaSource maybeClipMediaSource(MediaItem mediaItem, MediaSource mediaSource) {
if (mediaItem.clippingProperties.startPositionMs == 0
&& mediaItem.clippingProperties.endPositionMs == C.TIME_END_OF_SOURCE
&& !mediaItem.clippingProperties.relativeToDefaultPosition) {
return mediaSource;
}
return new ClippingMediaSource(
mediaSource,
C.msToUs(mediaItem.clippingProperties.startPositionMs),
C.msToUs(mediaItem.clippingProperties.endPositionMs),
/* enableInitialDiscontinuity= */ !mediaItem.clippingProperties.startsAtKeyFrame,
/* allowDynamicClippingUpdates= */ mediaItem.clippingProperties.relativeToLiveWindow,
mediaItem.clippingProperties.relativeToDefaultPosition);
}
private MediaSource maybeWrapWithAdsMediaSource(MediaItem mediaItem, MediaSource mediaSource) {
Assertions.checkNotNull(mediaItem.playbackProperties);
@Nullable
MediaItem.AdsConfiguration adsConfiguration = mediaItem.playbackProperties.adsConfiguration;
if (adsConfiguration == null) {
return mediaSource;
}
AdsLoaderProvider adsLoaderProvider = this.adsLoaderProvider;
AdViewProvider adViewProvider = this.adViewProvider;
if (adsLoaderProvider == null || adViewProvider == null) {
Log.w(
TAG,
"Playing media without ads. Configure ad support by calling setAdsLoaderProvider and"
+ " setAdViewProvider.");
return mediaSource;
}
@Nullable AdsLoader adsLoader = adsLoaderProvider.getAdsLoader(adsConfiguration);
if (adsLoader == null) {
Log.w(TAG, "Playing media without ads, as no AdsLoader was provided.");
return mediaSource;
}
return new AdsMediaSource(
mediaSource,
new DataSpec(adsConfiguration.adTagUri),
/* adsId= */ adsConfiguration.adsId != null
? adsConfiguration.adsId
: Pair.create(mediaItem.mediaId, adsConfiguration.adTagUri),
/* adMediaSourceFactory= */ this,
adsLoader,
adViewProvider);
}
private static SparseArray<MediaSourceFactory> loadDelegates(
DataSource.Factory dataSourceFactory, ExtractorsFactory extractorsFactory) {
SparseArray<MediaSourceFactory> factories = new SparseArray<>();
// LINT.IfChange
try {
Class<? extends MediaSourceFactory> factoryClazz =
Class.forName("com.google.android.exoplayer2.source.dash.DashMediaSource$Factory")
.asSubclass(MediaSourceFactory.class);
factories.put(
C.TYPE_DASH,
factoryClazz.getConstructor(DataSource.Factory.class).newInstance(dataSourceFactory));
} catch (Exception e) {
// Expected if the app was built without the dash module.
}
try {
Class<? extends MediaSourceFactory> factoryClazz =
Class.forName(
"com.google.android.exoplayer2.source.smoothstreaming.SsMediaSource$Factory")
.asSubclass(MediaSourceFactory.class);
factories.put(
C.TYPE_SS,
factoryClazz.getConstructor(DataSource.Factory.class).newInstance(dataSourceFactory));
} catch (Exception e) {
// Expected if the app was built without the smoothstreaming module.
}
try {
Class<? extends MediaSourceFactory> factoryClazz =
Class.forName("com.google.android.exoplayer2.source.hls.HlsMediaSource$Factory")
.asSubclass(MediaSourceFactory.class);
factories.put(
C.TYPE_HLS,
factoryClazz.getConstructor(DataSource.Factory.class).newInstance(dataSourceFactory));
} catch (Exception e) {
// Expected if the app was built without the hls module.
}
// LINT.ThenChange(../../../../../../../../proguard-rules.txt)
factories.put(
C.TYPE_OTHER, new ProgressiveMediaSource.Factory(dataSourceFactory, extractorsFactory));
return factories;
}
}
| 42.207547 | 100 | 0.718273 |
b0bdd83e8c897a2c9e7bf801aae1a352a7279fdd | 347 | package org.study.datamining.clustering.kmeans;
/**
* K-means(K均值)算法调用类
* @author lyq
*
*/
public class Client {
public static void main(String[] args){
String filePath = "C:\\Users\\lyq\\Desktop\\icon\\input.txt";
//聚类中心数量设定
int classNum = 3;
KMeansTool tool = new KMeansTool(filePath, classNum);
tool.kMeansClustering();
}
}
| 19.277778 | 63 | 0.680115 |
192e6e83baef007699354247c6c4fc916f6d2d47 | 814 | import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class MainClass {
public static void main(String[] args) throws IOException, InterruptedException {
BufferedWriter writer = new BufferedWriter(new FileWriter("primeNumbers"));
var maxPrime = Integer.parseInt(args[0]);
var startTime = System.currentTimeMillis();
var primes = new OptimizedPrimeCalculator().getPrimes(maxPrime);
long endTime = System.currentTimeMillis();
writer.write("Total execution time taken to identify all the prime numbers less than or equal to " + maxPrime + ": " +
(endTime - startTime) + " ms \n");
for (Integer prime : primes) {
writer.write(prime + "\n");
}
writer.close();
}
}
| 30.148148 | 126 | 0.648649 |
33e49f47bec0b5e0ecc446997ad66a8dabb4bc07 | 1,571 | package com.strategyobject.substrateclient.pallet.storage;
import com.google.common.annotations.Beta;
import com.strategyobject.substrateclient.rpc.api.BlockHash;
import com.strategyobject.substrateclient.rpc.api.section.State;
import com.strategyobject.substrateclient.scale.ScaleReader;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import java.util.concurrent.CompletableFuture;
@Beta
@RequiredArgsConstructor(staticName = "with")
public class StorageDoubleMapImpl<F, S, V> implements StorageDoubleMap<F, S, V> {
private final StorageNMap<V> underlying;
private StorageDoubleMapImpl(@NonNull State state,
@NonNull ScaleReader<V> scaleReader,
@NonNull StorageKeyProvider storageKeyProvider) {
underlying = StorageNMapImpl.with(state, scaleReader, storageKeyProvider);
}
public static <F, S, V> StorageDoubleMap<F, S, V> with(@NonNull State state,
@NonNull ScaleReader<V> scaleReader,
@NonNull StorageKeyProvider storageKeyProvider) {
return new StorageDoubleMapImpl<>(state, scaleReader, storageKeyProvider);
}
@Override
public CompletableFuture<V> get(@NonNull F first, @NonNull S second) {
return underlying.get(first, second);
}
@Override
public CompletableFuture<V> at(@NonNull BlockHash block, @NonNull F first, @NonNull S second) {
return underlying.at(block, first, second);
}
}
| 40.282051 | 108 | 0.676639 |
4dedfcaffaf76827534d0b48031cbd444e040443 | 864 | /*
* Copyright (c) 2018-2021. Ivan Vakhrushev. All rights reserved.
* https://github.com/mfvanek
*/
package com.mfvanek.money.transfer.utils;
import com.google.gson.Gson;
import lombok.Getter;
import lombok.ToString;
public final class JsonUtils {
private JsonUtils() {}
public static Gson make() {
return new Gson().newBuilder().setPrettyPrinting().create();
}
public static String toJson(Exception err, int errCode) {
final ErrorInfo info = new ErrorInfo(err, errCode);
return make().toJson(info);
}
@Getter
@ToString
private static class ErrorInfo {
private final int errorCode;
private final String errorMessage;
ErrorInfo(Exception err, int errCode) {
this.errorCode = errCode;
this.errorMessage = err.getLocalizedMessage();
}
}
}
| 22.736842 | 68 | 0.65162 |
8acdba19771ed5cdd936c5c2cd57708cc47764e7 | 1,904 | package chair.crud.demo.domain.dto;
import chair.crud.demo.domain.Manufacturer;
import chair.crud.demo.domain.extension.DestinationT;
import java.util.List;
public class ChairDto {
private long id;
private String model;
private DestinationT destination;
private Manufacturer manufacturer;
private SpecificationDto specification;
private List<DistributorDto> distributors;
// Get and Set
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public DestinationT getDestination() {
return destination;
}
public void setDestination(DestinationT destination) {
this.destination = destination;
}
public Manufacturer getManufacturer() {
return manufacturer;
}
public void setManufacturer(Manufacturer manufacturer) {
this.manufacturer = manufacturer;
}
public SpecificationDto getSpecification() {
return specification;
}
public void setSpecification(SpecificationDto specification) {
this.specification = specification;
}
public List<DistributorDto> getDistributors() {
return distributors;
}
public void setDistributors(List<DistributorDto> distributors) {
this.distributors = distributors;
}
// Constructors
public ChairDto() {
}
public ChairDto(long id, String model, DestinationT destination, Manufacturer manufacturer, SpecificationDto specification, List<DistributorDto> distributors) {
this.id = id;
this.model = model;
this.destination = destination;
this.manufacturer = manufacturer;
this.specification = specification;
this.distributors = distributors;
}
}
| 21.885057 | 164 | 0.671218 |
13cf6a11ecce37a70e28b9a3d7f6e3408818411e | 3,190 | // Copyright (C) 2014 Guibing Guo
//
// This file is part of LibRec.
//
// LibRec is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// LibRec 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 LibRec. If not, see <http://www.gnu.org/licenses/>.
//
package librec.data;
import java.util.HashSet;
import java.util.Set;
/**
* User-related Contextual Entry Information
*
* @author Keqiang Wang
*/
public class UserContextEntry {
/**
* user's social relations
*/
private Set<Integer> socialSet;
/**
* user name
*/
private String userName;
/**
* user age
*/
private int age;
/**
* user gender 1 for man, 0 for female
*/
private int gender;
/**
* user description
*/
private String userDescription;
/**
* add social relations
*
* @param userIdx user id socially related with
*/
public void addSocial(int userIdx) {
if (socialSet == null)
socialSet = new HashSet<>();
socialSet.add(userIdx);
}
/**
* Returns {@code true} if friends set of user contains the friend userIdx
*
* @param userIdx of user social friends to search for
*/
public boolean socialContains(int userIdx) {
return socialSet.contains(userIdx);
}
/**
* @return the social friends set of user.
*/
public Set<Integer> getSocialSet() {
return socialSet;
}
/**
* @return user name
*/
public String getUserName() {
return userName;
}
/**
* set userName as the name of this user context entry
*
* @param userName user name of this user context entry
*/
public void setUserName(String userName) {
this.userName = userName;
}
/**
* @return the age of this user
*/
public int getAge() {
return age;
}
/**
* set the age of this user
*
* @param age the age of this user
*/
public void setAge(int age) {
this.age = age;
}
/**
* @return the gender of this user
*/
public int getGender() {
return gender;
}
/**
* set the gender of this user
*
* @param gender the gender of this user
*/
public void setGender(int gender) {
this.gender = gender;
}
/**
* @return the text description of this user
*/
public String getUserDescription() {
return userDescription;
}
/**
* set the text description of this user
*
* @param userDescription the text description of this user
*/
public void setUserDescription(String userDescription) {
this.userDescription = userDescription;
}
}
| 21.70068 | 78 | 0.602194 |
c51c0805f005723becd1a1a9a8f1979a2dea5aaa | 304 | package com.goitho.customerapp.screen.blog;
import com.goitho.customerapp.app.di.ActivityScope;
import dagger.Subcomponent;
/**
* Created by MSI on 26/11/2017.
*/
@ActivityScope
@Subcomponent(modules = {BlogModule.class})
public interface BlogComponent {
void inject(BlogActivity activity);
}
| 17.882353 | 51 | 0.763158 |
3f74a9af6a64586871ef4407e81c3415ea50eeb9 | 38,384 | /**
* Copyright (c) 2013, impossibl.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of impossibl.com nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.impossibl.postgres.jdbc;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.Array;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Date;
import java.sql.NClob;
import java.sql.Ref;
import java.sql.RowId;
import java.sql.SQLException;
import java.sql.SQLType;
import java.sql.SQLXML;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Map;
/**
* CallableStatement delegator
* @author <a href="mailto:[email protected]">Jesper Pedersen</a>
*/
public class PGCallableStatementDelegator extends PGPreparedStatementDelegator implements CallableStatement {
private PGPooledConnectionDelegator owner;
private CallableStatement delegator;
/**
* Constructor
* @param owner The owner
* @param delegator The delegator
*/
public PGCallableStatementDelegator(PGPooledConnectionDelegator owner, CallableStatement delegator) {
super(owner, delegator);
this.owner = owner;
this.delegator = delegator;
}
/**
* {@inheritDoc}
*/
@Override
public Array getArray(int parameterIndex) throws SQLException {
try {
return delegator.getArray(parameterIndex);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public Array getArray(String parameterName) throws SQLException {
try {
return delegator.getArray(parameterName);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public BigDecimal getBigDecimal(int parameterIndex) throws SQLException {
try {
return delegator.getBigDecimal(parameterIndex);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
@Deprecated
public BigDecimal getBigDecimal(int parameterIndex, int scale) throws SQLException {
try {
return delegator.getBigDecimal(parameterIndex, scale);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public BigDecimal getBigDecimal(String parameterName) throws SQLException {
try {
return delegator.getBigDecimal(parameterName);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public Blob getBlob(int parameterIndex) throws SQLException {
try {
return delegator.getBlob(parameterIndex);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public Blob getBlob(String parameterName) throws SQLException {
try {
return delegator.getBlob(parameterName);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean getBoolean(int parameterIndex) throws SQLException {
try {
return delegator.getBoolean(parameterIndex);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean getBoolean(String parameterName) throws SQLException {
try {
return delegator.getBoolean(parameterName);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public byte getByte(int parameterIndex) throws SQLException {
try {
return delegator.getByte(parameterIndex);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public byte getByte(String parameterName) throws SQLException {
try {
return delegator.getByte(parameterName);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public byte[] getBytes(int parameterIndex) throws SQLException {
try {
return delegator.getBytes(parameterIndex);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public byte[] getBytes(String parameterName) throws SQLException {
try {
return delegator.getBytes(parameterName);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public Reader getCharacterStream(int parameterIndex) throws SQLException {
try {
return delegator.getCharacterStream(parameterIndex);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public Reader getCharacterStream(String parameterName) throws SQLException {
try {
return delegator.getCharacterStream(parameterName);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public Clob getClob(int parameterIndex) throws SQLException {
try {
return delegator.getClob(parameterIndex);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public Clob getClob(String parameterName) throws SQLException {
try {
return delegator.getClob(parameterName);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public Date getDate(int parameterIndex) throws SQLException {
try {
return delegator.getDate(parameterIndex);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public Date getDate(int parameterIndex, Calendar cal) throws SQLException {
try {
return delegator.getDate(parameterIndex, cal);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public Date getDate(String parameterName) throws SQLException {
try {
return delegator.getDate(parameterName);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public Date getDate(String parameterName, Calendar cal) throws SQLException {
try {
return delegator.getDate(parameterName, cal);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public double getDouble(int parameterIndex) throws SQLException {
try {
return delegator.getDouble(parameterIndex);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public double getDouble(String parameterName) throws SQLException {
try {
return delegator.getDouble(parameterName);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public float getFloat(int parameterIndex) throws SQLException {
try {
return delegator.getFloat(parameterIndex);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public float getFloat(String parameterName) throws SQLException {
try {
return delegator.getFloat(parameterName);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public int getInt(int parameterIndex) throws SQLException {
try {
return delegator.getInt(parameterIndex);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public int getInt(String parameterName) throws SQLException {
try {
return delegator.getInt(parameterName);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public long getLong(int parameterIndex) throws SQLException {
try {
return delegator.getLong(parameterIndex);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public long getLong(String parameterName) throws SQLException {
try {
return delegator.getLong(parameterName);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public Reader getNCharacterStream(int parameterIndex) throws SQLException {
try {
return delegator.getNCharacterStream(parameterIndex);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public Reader getNCharacterStream(String parameterName) throws SQLException {
try {
return delegator.getNCharacterStream(parameterName);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public NClob getNClob(int parameterIndex) throws SQLException {
try {
return delegator.getNClob(parameterIndex);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public NClob getNClob(String parameterName) throws SQLException {
try {
return delegator.getNClob(parameterName);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public String getNString(int parameterIndex) throws SQLException {
try {
return delegator.getNString(parameterIndex);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public String getNString(String parameterName) throws SQLException {
try {
return delegator.getNString(parameterName);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public Object getObject(int parameterIndex) throws SQLException {
try {
return delegator.getObject(parameterIndex);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public <T> T getObject(int parameterIndex, Class<T> type) throws SQLException {
try {
return delegator.getObject(parameterIndex, type);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public Object getObject(int parameterIndex, Map<String, Class<?>> map) throws SQLException {
try {
return delegator.getObject(parameterIndex, map);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public Object getObject(String parameterName) throws SQLException {
try {
return delegator.getObject(parameterName);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public <T> T getObject(String parameterName, Class<T> type) throws SQLException {
try {
return delegator.getObject(parameterName, type);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public Object getObject(String parameterName, Map<String, Class<?>> map) throws SQLException {
try {
return delegator.getObject(parameterName, map);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public Ref getRef(int parameterIndex) throws SQLException {
try {
return delegator.getRef(parameterIndex);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public Ref getRef(String parameterName) throws SQLException {
try {
return delegator.getRef(parameterName);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public RowId getRowId(int parameterIndex) throws SQLException {
try {
return delegator.getRowId(parameterIndex);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public RowId getRowId(String parameterName) throws SQLException {
try {
return delegator.getRowId(parameterName);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public short getShort(int parameterIndex) throws SQLException {
try {
return delegator.getShort(parameterIndex);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public short getShort(String parameterName) throws SQLException {
try {
return delegator.getShort(parameterName);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public SQLXML getSQLXML(int parameterIndex) throws SQLException {
try {
return delegator.getSQLXML(parameterIndex);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public SQLXML getSQLXML(String parameterName) throws SQLException {
try {
return delegator.getSQLXML(parameterName);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public String getString(int parameterIndex) throws SQLException {
try {
return delegator.getString(parameterIndex);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public String getString(String parameterName) throws SQLException {
try {
return delegator.getString(parameterName);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public Time getTime(int parameterIndex) throws SQLException {
try {
return delegator.getTime(parameterIndex);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public Time getTime(int parameterIndex, Calendar cal) throws SQLException {
try {
return delegator.getTime(parameterIndex, cal);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public Time getTime(String parameterName) throws SQLException {
try {
return delegator.getTime(parameterName);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public Time getTime(String parameterName, Calendar cal) throws SQLException {
try {
return delegator.getTime(parameterName, cal);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public Timestamp getTimestamp(int parameterIndex) throws SQLException {
try {
return delegator.getTimestamp(parameterIndex);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public Timestamp getTimestamp(int parameterIndex, Calendar cal) throws SQLException {
try {
return delegator.getTimestamp(parameterIndex, cal);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public Timestamp getTimestamp(String parameterName) throws SQLException {
try {
return delegator.getTimestamp(parameterName);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public Timestamp getTimestamp(String parameterName, Calendar cal) throws SQLException {
try {
return delegator.getTimestamp(parameterName, cal);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public URL getURL(int parameterIndex) throws SQLException {
try {
return delegator.getURL(parameterIndex);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public URL getURL(String parameterName) throws SQLException {
try {
return delegator.getURL(parameterName);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void registerOutParameter(int parameterIndex, int sqlType) throws SQLException {
try {
delegator.registerOutParameter(parameterIndex, sqlType);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void registerOutParameter(int parameterIndex, int sqlType, int scale) throws SQLException {
try {
delegator.registerOutParameter(parameterIndex, sqlType, scale);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void registerOutParameter(int parameterIndex, int sqlType, String typeName) throws SQLException {
try {
delegator.registerOutParameter(parameterIndex, sqlType, typeName);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void registerOutParameter(String parameterName, int sqlType) throws SQLException {
try {
delegator.registerOutParameter(parameterName, sqlType);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void registerOutParameter(String parameterName, int sqlType, int scale) throws SQLException {
try {
delegator.registerOutParameter(parameterName, sqlType, scale);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void registerOutParameter(String parameterName, int sqlType, String typeName) throws SQLException {
try {
delegator.registerOutParameter(parameterName, sqlType, typeName);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setAsciiStream(String parameterName, InputStream x) throws SQLException {
try {
delegator.setAsciiStream(parameterName, x);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setAsciiStream(String parameterName, InputStream x, int length) throws SQLException {
try {
delegator.setAsciiStream(parameterName, x, length);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setAsciiStream(String parameterName, InputStream x, long length) throws SQLException {
try {
delegator.setAsciiStream(parameterName, x, length);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setBigDecimal(String parameterName, BigDecimal x) throws SQLException {
try {
delegator.setBigDecimal(parameterName, x);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setBinaryStream(String parameterName, InputStream x) throws SQLException {
try {
delegator.setBinaryStream(parameterName, x);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setBinaryStream(String parameterName, InputStream x, int length) throws SQLException {
try {
delegator.setBinaryStream(parameterName, x, length);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setBinaryStream(String parameterName, InputStream x, long length) throws SQLException {
try {
delegator.setBinaryStream(parameterName, x, length);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setBlob(String parameterName, Blob x) throws SQLException {
try {
delegator.setBlob(parameterName, x);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setBlob(String parameterName, InputStream inputStream) throws SQLException {
try {
delegator.setBlob(parameterName, inputStream);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setBlob(String parameterName, InputStream inputStream, long length) throws SQLException {
try {
delegator.setBlob(parameterName, inputStream, length);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setBoolean(String parameterName, boolean x) throws SQLException {
try {
delegator.setBoolean(parameterName, x);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setByte(String parameterName, byte x) throws SQLException {
try {
delegator.setByte(parameterName, x);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setBytes(String parameterName, byte[] x) throws SQLException {
try {
delegator.setBytes(parameterName, x);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setCharacterStream(String parameterName, Reader reader) throws SQLException {
try {
delegator.setCharacterStream(parameterName, reader);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setCharacterStream(String parameterName, Reader reader, int length) throws SQLException {
try {
delegator.setCharacterStream(parameterName, reader, length);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setCharacterStream(String parameterName, Reader reader, long length) throws SQLException {
try {
delegator.setCharacterStream(parameterName, reader, length);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setClob(String parameterName, Clob x) throws SQLException {
try {
delegator.setClob(parameterName, x);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setClob(String parameterName, Reader reader) throws SQLException {
try {
delegator.setClob(parameterName, reader);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setClob(String parameterName, Reader reader, long length) throws SQLException {
try {
delegator.setClob(parameterName, reader, length);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setDate(String parameterName, Date x) throws SQLException {
try {
delegator.setDate(parameterName, x);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setDate(String parameterName, Date x, Calendar cal) throws SQLException {
try {
delegator.setDate(parameterName, x, cal);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setDouble(String parameterName, double x) throws SQLException {
try {
delegator.setDouble(parameterName, x);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setFloat(String parameterName, float x) throws SQLException {
try {
delegator.setFloat(parameterName, x);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setInt(String parameterName, int x) throws SQLException {
try {
delegator.setInt(parameterName, x);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setLong(String parameterName, long x) throws SQLException {
try {
delegator.setLong(parameterName, x);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setNCharacterStream(String parameterName, Reader value) throws SQLException {
try {
delegator.setNCharacterStream(parameterName, value);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setNCharacterStream(String parameterName, Reader value, long length) throws SQLException {
try {
delegator.setNCharacterStream(parameterName, value, length);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setNClob(String parameterName, NClob value) throws SQLException {
try {
delegator.setNClob(parameterName, value);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setNClob(String parameterName, Reader reader) throws SQLException {
try {
delegator.setNClob(parameterName, reader);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setNClob(String parameterName, Reader reader, long length) throws SQLException {
try {
delegator.setNClob(parameterName, reader, length);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setNString(String parameterName, String value) throws SQLException {
try {
delegator.setNString(parameterName, value);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setNull(String parameterName, int sqlType) throws SQLException {
try {
delegator.setNull(parameterName, sqlType);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setNull(String parameterName, int sqlType, String typeName) throws SQLException {
try {
delegator.setNull(parameterName, sqlType, typeName);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setObject(String parameterName, Object x) throws SQLException {
try {
delegator.setObject(parameterName, x);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setObject(String parameterName, Object x, int targetSqlType) throws SQLException {
try {
delegator.setObject(parameterName, x, targetSqlType);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setObject(String parameterName, Object x, int targetSqlType, int scale) throws SQLException {
try {
delegator.setObject(parameterName, x, targetSqlType, scale);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setRowId(String parameterName, RowId x) throws SQLException {
try {
delegator.setRowId(parameterName, x);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setShort(String parameterName, short x) throws SQLException {
try {
delegator.setShort(parameterName, x);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setSQLXML(String parameterName, SQLXML xmlObject) throws SQLException {
try {
delegator.setSQLXML(parameterName, xmlObject);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setString(String parameterName, String x) throws SQLException {
try {
delegator.setString(parameterName, x);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setTime(String parameterName, Time x) throws SQLException {
try {
delegator.setTime(parameterName, x);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setTime(String parameterName, Time x, Calendar cal) throws SQLException {
try {
delegator.setTime(parameterName, x, cal);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setTimestamp(String parameterName, Timestamp x) throws SQLException {
try {
delegator.setTimestamp(parameterName, x);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setTimestamp(String parameterName, Timestamp x, Calendar cal) throws SQLException {
try {
delegator.setTimestamp(parameterName, x, cal);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setURL(String parameterName, URL val) throws SQLException {
try {
delegator.setURL(parameterName, val);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean wasNull() throws SQLException {
try {
return delegator.wasNull();
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setObject(String parameterName, Object x, SQLType targetSqlType, int scaleOrLength) throws SQLException {
try {
delegator.setObject(parameterName, x, targetSqlType, scaleOrLength);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void setObject(String parameterName, Object x, SQLType targetSqlType) throws SQLException {
try {
delegator.setObject(parameterName, x, targetSqlType);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void registerOutParameter(int parameterIndex, SQLType sqlType) throws SQLException {
try {
delegator.registerOutParameter(parameterIndex, sqlType);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void registerOutParameter(int parameterIndex, SQLType sqlType, int scale) throws SQLException {
try {
delegator.registerOutParameter(parameterIndex, sqlType, scale);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void registerOutParameter(int parameterIndex, SQLType sqlType, String typeName) throws SQLException {
try {
delegator.registerOutParameter(parameterIndex, sqlType, typeName);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void registerOutParameter(String parameterName, SQLType sqlType) throws SQLException {
try {
delegator.registerOutParameter(parameterName, sqlType);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void registerOutParameter(String parameterName, SQLType sqlType, int scale) throws SQLException {
try {
delegator.registerOutParameter(parameterName, sqlType, scale);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public void registerOutParameter(String parameterName, SQLType sqlType, String typeName) throws SQLException {
try {
delegator.registerOutParameter(parameterName, sqlType, typeName);
}
catch (SQLException se) {
owner.fireStatementError(this, se);
throw se;
}
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return super.hashCode();
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || !(o instanceof PGCallableStatementDelegator))
return false;
PGCallableStatementDelegator other = (PGCallableStatementDelegator)o;
return delegator.equals(other.delegator);
}
}
| 21.479575 | 119 | 0.633519 |
56c1df09c9c28fc35695b6415663879df9f5a6c5 | 4,983 | /*
* Copyright (c) 2015 Evident Solutions Oy
*
* 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 org.dalesbred.internal.instantiation;
import org.dalesbred.annotation.DalesbredIgnore;
import org.dalesbred.annotation.Reflective;
import org.jetbrains.annotations.Nullable;
import org.junit.Test;
import java.util.Optional;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
public class PropertyAccessorTest {
@Test
public void findingSetters() {
assertThat(PropertyAccessor.findAccessor(DepartmentWithSetters.class, "department_name"), is(not(Optional.empty())));
}
@Test
public void findingFields() {
assertThat(PropertyAccessor.findAccessor(DepartmentWithFields.class, "department_name"), is(not(Optional.empty())));
}
@Test
public void ignoredSetters() {
assertThat(PropertyAccessor.findAccessor(IgnoredValues.class, "ignoredMethod"), is(Optional.empty()));
}
@Test
public void ignoredFields() {
assertThat(PropertyAccessor.findAccessor(IgnoredValues.class, "ignoredField"), is(Optional.empty()));
}
@Test
public void nestedPathsWithIntermediateFields() {
PropertyAccessor accessor = PropertyAccessor.findAccessor(NestedPaths.class, "namedField.name").orElse(null);
assertNotNull(accessor);
NestedPaths paths = new NestedPaths();
accessor.set(paths, "foo");
assertThat(paths.namedField.name, is("foo"));
}
@Test
public void nestedPathsWithIntermediateGetters() {
PropertyAccessor accessor = PropertyAccessor.findAccessor(NestedPaths.class, "namedGetter.name").orElse(null);
assertNotNull(accessor);
NestedPaths paths = new NestedPaths();
accessor.set(paths, "foo");
assertThat(paths.getNamedGetter().name, is("foo"));
}
@Test(expected = InstantiationFailureException.class)
public void nestedPathsWithNullFields() {
PropertyAccessor accessor = PropertyAccessor.findAccessor(NestedPaths.class, "nullField.name").orElse(null);
assertNotNull(accessor);
accessor.set(new NestedPaths(), "foo");
}
@Test(expected = InstantiationFailureException.class)
public void nestedPathsWithNullGetters() {
PropertyAccessor accessor = PropertyAccessor.findAccessor(NestedPaths.class, "nullGetter.name").orElse(null);
assertNotNull(accessor);
accessor.set(new NestedPaths(), "foo");
}
@Test
public void invalidPathElements() {
assertThat(PropertyAccessor.findAccessor(Named.class, "foo.name"), is(Optional.empty()));
}
private static class DepartmentWithFields {
@Reflective
public String departmentName;
}
public static class DepartmentWithSetters {
private String departmentName;
@Reflective
public String getDepartmentName() {
return departmentName;
}
@Reflective
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
}
public static class NestedPaths {
public final Named namedField = new Named();
@Reflective
public final Named nullField = null;
@Reflective
public Named getNamedGetter() {
return namedField;
}
@Nullable
@Reflective
public Named getNullGetter() {
return null;
}
}
public static class Named {
@Reflective
public String name;
}
@SuppressWarnings("unused")
public static class IgnoredValues {
@DalesbredIgnore
public String ignoredField;
@SuppressWarnings({"UnusedParameters", "EmptyMethod"})
@DalesbredIgnore
public void setIgnoredMethod(String s) {
}
}
}
| 31.14375 | 125 | 0.695766 |
45611ae5ecd167f008e6185940a95784439504c7 | 3,077 | package com.concurrentthought.hive.udfs;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import java.util.ArrayList;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class PerRecordNGramsAsArraysTest {
private PerRecordNGramsAsArrays func = new PerRecordNGramsAsArrays();
private ArrayList<String> toArray(String s) {
ArrayList<String> a = new ArrayList<String>();
for (String s2: s.split(" ")) {
a.add(s2);
}
return a;
}
private ArrayList<ArrayList<String>> empty = new ArrayList<ArrayList<String>>();
@Test
public void emptyListReturnedForNullText() throws HiveException {
assertEquals(empty, func.evaluate(3, null));
}
@Test
public void emptyListReturnedForEmptyText() throws HiveException {
assertEquals(empty, func.evaluate(3, ""));
}
@Test(expected = HiveException.class)
public void throwsIfNIsNegative() throws HiveException {
func.evaluate(-1, null);
}
@Test(expected = HiveException.class)
public void throwsIfNEqualsZero() throws HiveException {
func.evaluate(0, null);
}
@Test
public void emptyListReturnedForTextWithFewerThanNWords() throws HiveException {
assertEquals(empty, func.evaluate(3, "Now is"));
}
@Test
public void oneElementListReturnedForTextWithNWords() throws HiveException {
ArrayList<ArrayList<String>> expected = new ArrayList<ArrayList<String>>();
expected.add(toArray("Now is the"));
assertEquals(expected, func.evaluate(3, "Now is the"));
}
@Test
public void manyElementListReturnedForTextWithMoreThanNWords() throws HiveException {
ArrayList<ArrayList<String>> expected = new ArrayList<ArrayList<String>>();
expected.add(toArray("Now is the"));
expected.add(toArray("is the time"));
assertEquals(expected, func.evaluate(3, "Now is the time"));
expected = new ArrayList<ArrayList<String>>();
expected.add(toArray("Now is the"));
expected.add(toArray("is the time"));
expected.add(toArray("the time for"));
expected.add(toArray("time for all"));
expected.add(toArray("for all good"));
expected.add(toArray("all good men"));
assertEquals(expected, func.evaluate(3, "Now is the time for all good men"));
}
@Test
public void leadingAndTrailingWhitespaceIsIgnored() throws HiveException {
ArrayList<ArrayList<String>> expected = new ArrayList<ArrayList<String>>();
expected.add(toArray("Now is the"));
expected.add(toArray("is the time"));
assertEquals(expected, func.evaluate(3, " \tNow is the time \t"));
}
@Test
public void punctuationIsTreatedAsWhitespace() throws HiveException {
ArrayList<ArrayList<String>> expected = new ArrayList<ArrayList<String>>();
expected.add(toArray("Now is the"));
expected.add(toArray("is the time"));
assertEquals(expected, func.evaluate(3, "?Now-is.the ! time ;"));
}
}
| 35.367816 | 89 | 0.668183 |
9e12ca4a5d0653cade1895181c113ab00d4beb74 | 4,169 | package com.apollo.stockTrading.maxProfit04;
/**
* 188. 买卖股票的最佳时机 IV
* dp[i][k][0] = max(dp[i-1][k][0], dp[i-1][k][1] + prices[i])
* dp[i][k][1] = max(dp[i-1][k][1], dp[i-1][k-1][0] - prices[i])
*
* i == 0
* dp[0][k][0] = max(dp[-1][k][0], dp[-1][k][1] + prices[i])
* dp[0][k][1] = max(dp[-1][k][1], dp[-1][k-1][0] - prices[i])
*/
public class MaxProfit04 {
// 1.动态规划
public int maxProfit(int k, int[] prices) {
// 0.预处理
if (prices == null || prices.length == 0) {
return 0;
}
// 1.分类讨论
int n = prices.length;
// 2.k >= n/2
if (k >= n / 2) {
// a.初始化状态
int dp_i_0 = 0, dp_i_1 = Integer.MIN_VALUE;
// b.动态规划
for (int i = 0; i < n; i++) {
int temp = dp_i_0;
dp_i_0 = Math.max(dp_i_0, dp_i_1 + prices[i]);
dp_i_1 = Math.max(dp_i_1, temp - prices[i]);
}
return dp_i_0;
} else {
// 3.k < n/2
// a.初始化状态
int[][][] dp = new int[n][k + 1][2];
for (int i = 0; i < n; i++) {
// 从k->1,因为i用到i-1的数据
for (int j = k; j >= 1; j--) {
if (i == 0) {
dp[i][j][0] = 0;
dp[i][j][1] = -prices[i];
} else {
dp[i][j][0] = Math.max(dp[i-1][j][0], dp[i-1][j][1] + prices[i]);
dp[i][j][1] = Math.max(dp[i-1][j][1], dp[i-1][j-1][0] - prices[i]);
}
}
}
return dp[n-1][k][0];
}
}
public int maxProfit02(int k, int[] prices) {
// 0.预处理
if (prices == null || prices.length == 0) {
return 0;
}
// 1.分类讨论
int n = prices.length;
// 2.k >= n/2
if (k >= n / 2) {
// a.初始化状态
int dp_i_0 = 0, dp_i_1 = Integer.MIN_VALUE;
// b.动态规划
for (int i = 0; i < n; i++) {
int temp = dp_i_0;
dp_i_0 = Math.max(dp_i_0, dp_i_1 + prices[i]);
dp_i_1 = Math.max(dp_i_1, temp - prices[i]);
}
return dp_i_0;
} else {
// 3.k < n/2
// a.初始化状态
int[][] dp = new int[k + 1][2];
for (int i = 0; i < n; i++) {
// 从k->1,因为i用到i-1的数据
for (int j = k; j >= 1; j--) {
if (i == 0) {
dp[j][0] = 0;
dp[j][1] = -prices[i];
} else {
dp[j][0] = Math.max(dp[j][0], dp[j][1] + prices[i]);
dp[j][1] = Math.max(dp[j][1], dp[j - 1][0] - prices[i]);
}
}
}
return dp[k][0];
}
}
public int maxProfit03(int k, int[] prices) {
// 0.预处理
if (prices == null || prices.length == 0) {
return 0;
}
// 1.分类讨论
int n = prices.length;
// 2.k >= n/2
if (k >= n / 2) {
// a.初始化状态
int dp_i_0 = 0, dp_i_1 = Integer.MIN_VALUE;
// b.动态规划
for (int i = 0; i < n; i++) {
int temp = dp_i_0;
dp_i_0 = Math.max(dp_i_0, dp_i_1 + prices[i]);
dp_i_1 = Math.max(dp_i_1, temp - prices[i]);
}
return dp_i_0;
} else {
// 3.k < n/2
// a.初始化状态
int[][][] dp = new int[n][k + 1][2];
for (int i = 0; i < n; i++) {
// 从k->1,因为i用到i-1的数据
for (int j = 1; j <= k; j++) {
if (i == 0) {
dp[i][j][0] = 0;
dp[i][j][1] = -prices[i];
} else {
dp[i][j][0] = Math.max(dp[i-1][j][0], dp[i-1][j][1] + prices[i]);
dp[i][j][1] = Math.max(dp[i-1][j][1], dp[i-1][j-1][0] - prices[i]);
}
}
}
return dp[n-1][k][0];
}
}
}
| 30.881481 | 91 | 0.332454 |
10c777324a0455543d7634532e590f05de0872e8 | 268 | package react4j.examples.factory_example;
import com.google.gwt.core.client.EntryPoint;
import static react4j.dom.DOM.*;
public class FactoryExample
implements EntryPoint
{
public void onModuleLoad()
{
section( h1( "My Title" ), p( "My text..." ) );
}
}
| 19.142857 | 51 | 0.708955 |
aaec904d3e223502c8cf7cf44bc3abe57ef424de | 4,053 | package com.hxr.lockdeeping;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* synchronized 和 Lock的区别:
* 一、原始构成:
* 1.synchronized是java的关键字属于JVM层面
* monitorenter(底层是monitor对象来完成,
* 其实waite/notify等方法都依赖monitor对象只有在同步块或方法中才能调用wait/notify等方法
* monitorexit(有2个是为了程序不管异常都退出-释放锁)
* 2.Lock是一个具体的类(java.util.concurrent.locks.Lock)
* 二、使用方法:
* synchronized不需要手动去释放锁,当synchronized代码块执行完成后系统会自动让线程释放对锁的占用
* ReentrantLock需要用户手动去释放锁,若没有手动释放锁就回导致出现死锁的现象
* 需要lock和unlock方法成对配合try/finally语句块完成。
* 三、等待是否可中断
* synchronized 不可中断,除非程序抛出异常或者正常运行结束
* ReentrantLock 可以中断:
* 1.设置超时方法 tryLock(Long timeout,TimeUnit unit)
* 2.lockInterrupt()放代码块中,调用interrupt()方法可以中断
* 四、加锁是否公平
* synchronized 默认是非公平锁
* ReentrantLock 默认也是非公平锁,但是可以构造方法中传boolean可以设置true公平,false非公平
* 五、锁是否可以绑定多个Condition条件
* synchronized 不能绑定多个条件
* ReentrantLock 用来实现分组唤醒的线程们,可以精确唤醒,而不是像 synchronized 要么随机唤醒一个线程要么全部唤醒所有线程
*
* @author houxiurong
* @date 2019-11-05
* <p>
* 题目:
* 多线程之间要求按照顺序调用,实现 A->B->C三个线程按照顺序启动,要求如下:
* AA打印5次,BB打印10次,CC打印15次
* 接着再
* AA打印5次,BB打印10次,CC打印15次
* ---每个线程来10轮
*/
public class SyncAndReentrantLockDemo {
public static void main(String[] args) {
ShareResource shareResource = new ShareResource();
new Thread(() -> {
for (int i = 1; i <= 10; i++) {
shareResource.print5();
}
}, "AA").start();
new Thread(() -> {
for (int i = 1; i <= 10; i++) {
shareResource.print10();
}
}, "BB").start();
new Thread(() -> {
for (int i = 1; i <= 10; i++) {
shareResource.print15();
}
}, "CC").start();
System.out.println("================================");
for (int i = 1; i <= 10; i++) {
new Thread(() -> {
shareResource.print5();
}, "AA").start();
new Thread(() -> {
shareResource.print10();
}, "BB").start();
new Thread(() -> {
shareResource.print15();
}, "CC").start();
}
}
}
/**
* 共享资源
*/
class ShareResource {
private int number = 1;//A:1 B:2 C:3
private Lock lock = new ReentrantLock();
private Condition c1 = lock.newCondition();
private Condition c2 = lock.newCondition();
private Condition c3 = lock.newCondition();
//判断 干活 通知三步走
public void print5() {
lock.lock();
try {
//判断
while (number != 1) {
c1.await();
}
//A干活5次
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + "\t" + i);
}
//通知
number = 2;//修改标记位
c2.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
//判断 干活 通知三步走
public void print10() {
lock.lock();
try {
//判断
while (number != 2) {
c2.await();
}
//B干活10次
for (int i = 1; i <= 10; i++) {
System.out.println(Thread.currentThread().getName() + "\t" + i);
}
//通知
number = 3;
c3.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
//判断 干活 通知三步走
public void print15() {
lock.lock();
try {
//判断
while (number != 3) {
c3.await();
}
//C干活15次
for (int i = 1; i <= 15; i++) {
System.out.println(Thread.currentThread().getName() + "\t" + i);
}
//通知
number = 1;
c1.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
| 25.490566 | 80 | 0.501604 |
19fee29df2f89c6b4a4d42bbad607ba20ae2e0dd | 964 | package com.performance.liferecord.activity;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import com.performance.liferecord.databinding.ActivityGirlBinding;
import com.performance.liferecord.model.GankData;
import com.squareup.picasso.Picasso;
public class GirlActivity extends AppCompatActivity {
String imageUrl;
private ActivityGirlBinding mActivityGirlBinding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mActivityGirlBinding = ActivityGirlBinding.inflate(getLayoutInflater());
setContentView(mActivityGirlBinding.getRoot());
getData();
}
private void getData() {
Intent intent = getIntent();
imageUrl = intent.getStringExtra(GankData.IMAGE_URL);
Picasso.with(this).load(imageUrl).into(mActivityGirlBinding.girlImage);
}
}
| 31.096774 | 81 | 0.735477 |
7379265935d8903cf243e5d389b49b86d4c00ac8 | 17,027 | /*
* @(#)TextSearch.java
*
* $Date: 2015-12-27 03:42:44 +0100 (So, 27 Dez 2015) $
*
* Copyright (c) 2011 by Jeremy Wood.
* All rights reserved.
*
* The copyright of this software is owned by Jeremy Wood.
* You may not use, copy or modify this software, except in
* accordance with the license agreement you entered into with
* Jeremy Wood. For details see accompanying license terms.
*
* This software is probably, but not necessarily, discussed here:
* https://javagraphics.java.net/
*
* That site should also contain the most recent official version
* of this software. (See the SVN repository for more details.)
*/
package com.bric.swing;
import java.awt.Toolkit;
import java.lang.reflect.Constructor;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
import javax.swing.text.Segment;
import com.bric.plaf.AbstractSearchHighlight;
/** Some static methods relating to searching a <code>JTextComponent</code> or <code>JTable</code>.
*
*/
public class SwingSearch {
/** This performs a basic search, starting from the current selection.
* Also this consults <code>UIManager.get("beepWhenSearchFails")</code>
* to determine whether to beep or not if a match is not found.
*
* @param textComponent the component to search.
* @param searchPhrase the phrase to search for.
* @param forward whether to move forward or backward (aka "next" or "previous").
* @param matchCase whether to match the case or not.
* @return true if a match is found, false otherwise.
*/
public static boolean find(JTextComponent textComponent, String searchPhrase,
boolean forward,boolean matchCase) {
boolean returnValue = find2(textComponent,searchPhrase,forward,matchCase);
if(!returnValue) {
notifyFailedSearch();
}
return returnValue;
}
/** This performs a basic search, starting from the current selection.
* Also this consults <code>UIManager.get("beepWhenSearchFails")</code>
* to determine whether to beep or not if a match is not found.
*
* @param table the component to search.
* @param searchPhrase the phrase to search for.
* @param forward whether to move forward or backward (aka "next" or "previous").
* @param matchCase whether to match the case or not.
* @return true if a match is found, false otherwise.
*/
public static boolean find(JTable table, String searchPhrase,
boolean forward,boolean matchCase) {
boolean returnValue = find2(table,searchPhrase,forward,matchCase);
if(!returnValue) {
notifyFailedSearch();
}
return returnValue;
}
private static void notifyFailedSearch() {
Boolean beep = (Boolean)UIManager.get("beepWhenSearchFails");
if(beep==null) beep = Boolean.TRUE;
if(beep.booleanValue())
Toolkit.getDefaultToolkit().beep();
}
private static boolean find2(JTextComponent textComponent, String searchPhrase,
boolean forward,boolean matchCase) {
if (textComponent == null)
throw new NullPointerException(
"No text component was provided to search.");
if (searchPhrase == null)
throw new NullPointerException(
"No search phrase was provided to search for.");
if(searchPhrase.length()==0)
return false;
if(matchCase==false)
searchPhrase = searchPhrase.toUpperCase();
int[] selection = new int[2];
int startingIndex;
if(forward) {
startingIndex = Math.max(textComponent.getSelectionStart(), textComponent.getSelectionEnd());
} else {
startingIndex = Math.min(textComponent.getSelectionStart(), textComponent.getSelectionEnd());
}
int endIndex = forward ? textComponent.getDocument().getLength() : 0;
if(find(textComponent, searchPhrase, forward, matchCase, true, startingIndex, endIndex, selection)) {
int prevStart = Math.min(textComponent.getSelectionStart(), textComponent.getSelectionEnd());
int prevEnd = Math.max(textComponent.getSelectionStart(), textComponent.getSelectionEnd());
//if the selection doesn't change, do nothing.
if(prevStart==selection[0] && prevEnd==selection[1])
return false;
textComponent.setSelectionStart(selection[0]);
textComponent.setSelectionEnd(selection[1]);
highlight(textComponent, selection[0], selection[1]);
return true;
}
return false;
}
private static boolean find2(JTable table, String searchPhrase,
boolean forward,boolean matchCase) {
if (table == null)
throw new NullPointerException(
"No table component was provided to search.");
if (searchPhrase == null)
throw new NullPointerException(
"No search phrase was provided to search for.");
if(searchPhrase.length()==0)
return false;
if(matchCase==false)
searchPhrase = searchPhrase.toUpperCase();
int selectedColumn = table.getSelectedColumn();
int selectedRow = table.getSelectedRow();
int[] selection = new int[] { selectedRow, selectedColumn };
if(find(table, searchPhrase, forward, matchCase, true, selection)) {
//if the selection doesn't change, do nothing.
if(selectedRow==selection[0] && selectedColumn==selection[1])
return false;
table.changeSelection(selection[0], selection[1], false, false);
highlight(table, selection[0], selection[1]);
return true;
}
return false;
}
/** Returns the number of occurances of a phrase in a text component.
*
* @param textComponent the text component to search.
* @param searchPhrase the phrase we're looking for.
* @param matchCase whether we have to be case sensitive or not.
* @return the number of occurrences of the phrase in the text component.
*/
public static int countOccurrence(JTextComponent textComponent,String searchPhrase,boolean matchCase) {
if (textComponent == null)
throw new NullPointerException(
"No text component was provided to search.");
if (searchPhrase == null)
throw new NullPointerException(
"No search phrase was provided to search for.");
if(searchPhrase.length()==0)
return 0;
if(matchCase==false)
searchPhrase = searchPhrase.toUpperCase();
int sum = 0;
int index = 0;
int docLength = textComponent.getDocument().getLength();
int[] selection = new int[2];
while(index<docLength) {
if(find(textComponent, searchPhrase, true, matchCase, false, index, docLength, selection)) {
//alternatively, this could be: index = selection[1]?
index = selection[0]+1;
sum++;
} else {
return sum;
}
}
return sum;
}
/** This performs a basic search, starting from a specific index.
* If a match is found, the indices are stored in the <code>selection</code> array,
* and <code>true</code> is returned.
*
* @param textComponent the component to search.
* @param searchPhrase the phrase to search for.
* @param forward whether to move forward or backward
* @param matchCase whether to match the case or not.
* @param startingIndex the index in the document to begin searching.
* @param selection the array to store the indices in if a match is found.
* @return true if the array provided now contains two indices enclosing
* the search phrase.
*/
public static boolean find(JTextComponent textComponent, String searchPhrase,
boolean forward,boolean matchCase,int startingIndex,int[] selection) {
if(matchCase==false)
searchPhrase = searchPhrase.toUpperCase();
if(forward) {
int length = textComponent.getDocument().getLength();
return find(textComponent, searchPhrase, forward, matchCase, false, startingIndex, length, selection);
} else {
return find(textComponent, searchPhrase, forward, matchCase, false, startingIndex, 0, selection);
}
}
/**
*
* @param textComponent
* @param searchPhrase if matchCase is false, this must be uppercase
* @param forward
* @param matchCase
* @param wrapAround
* @param startingIndex the index at which we start reading
* @param endIndex the index at which we stop reading
* @param selection the selection start and end will be stored in this 2-int array
* @return true if the "selection" argument is now populated with the location of
* this search phrase
*/
private static boolean find(JTextComponent textComponent, String searchPhrase,
boolean forward,boolean matchCase,boolean wrapAround,int startingIndex, int endIndex,int[] selection) {
/** I don't have a lot of experience with large text documents in Java.
*
* It would be easiest to just convert the textComponent's document into
* a String, and then use indexOf and lastIndexOf to perform these searches:
* but it seems like that might be really wasteful in terms of large
* documents. (Especially consider the countOccurrence method, which may
* call this method thousands of times with every keystroke.)
*
* So -- while I admit I don't know what I'm doing -- it seems like using
* the Segment class might be the better way to do this?
*/
int spl = searchPhrase.length();
Document doc = textComponent.getDocument();
char[] array = new char[spl];
Segment segment = new Segment(array, 0, 0);
try {
if(forward) { //searching forward
int index = startingIndex;
int matching = 0;
segment.setPartialReturn(true);
while(index<endIndex) {
int remainingCharsInDoc = endIndex-index;
int remainingCharsInSearchPhrase = spl-matching;
int searchLength = remainingCharsInDoc>remainingCharsInSearchPhrase ?
remainingCharsInSearchPhrase : remainingCharsInDoc;
doc.getText(index, searchLength, segment);
char[] workingArray;
int arrayOffset;
if(matchCase==false) {
for(int a = 0; a<segment.count; a++) {
array[a] = Character.toUpperCase( segment.array[a+segment.offset] );
}
workingArray = array;
arrayOffset = 0;
} else {
workingArray = segment.array;
arrayOffset = segment.offset;
}
scan : {
for(int a = 0; a<segment.count; a++) {
if(searchPhrase.charAt(matching)==workingArray[arrayOffset+a]) {
matching++;
if(matching==spl) {
selection[1] = index+matching-(spl-segment.count);
selection[0] = selection[1]-spl;
return true;
}
} else {
if(matching>0) {
matching = 0;
index = index-matching+1;
break scan;
}
matching = 0;
}
}
index+=segment.count;
}
}
if(wrapAround && startingIndex!=0) {
startingIndex = Math.min( textComponent.getDocument().getLength(), startingIndex+spl);
return find(textComponent, searchPhrase, forward, matchCase, false, 0, startingIndex, selection);
}
return false;
} else { //searching backward
int index = Math.max(startingIndex-spl,0);
int matching = 0;
segment.setPartialReturn(false);
while(index>endIndex) {
int remainingCharsInDoc = index-endIndex;
int remainingCharsInSearchPhrase = spl-matching;
int searchLength = remainingCharsInDoc>remainingCharsInSearchPhrase ?
remainingCharsInSearchPhrase : remainingCharsInDoc;
doc.getText(index+matching, searchLength, segment);
char[] workingArray;
int arrayOffset;
if(matchCase==false) {
for(int a = 0; a<segment.count; a++) {
array[a] = Character.toUpperCase( segment.array[a+segment.offset] );
}
workingArray = array;
arrayOffset = 0;
} else {
workingArray = segment.array;
arrayOffset = segment.offset;
}
scan : {
for(int a = segment.count-1; a>=0; a--) {
if(searchPhrase.charAt(spl-1-matching)==workingArray[arrayOffset+a]) {
matching++;
if(matching==spl) {
selection[0] = index+matching-(segment.count-1-a)-1;
selection[1] = selection[0]+spl;
return true;
}
} else {
if(matching>0) {
matching = 0;
index = index+matching-1;
break scan;
}
matching = 0;
}
}
index-=segment.count;
}
}
int docLength = textComponent.getDocument().getLength();
if(wrapAround && startingIndex!=docLength) {
startingIndex = Math.max(0, startingIndex-spl);
return find(textComponent, searchPhrase, forward, matchCase, false, docLength, startingIndex, selection);
}
return false;
}
} catch(BadLocationException e) {
//this shouldn't happen, right?
RuntimeException e2 = new RuntimeException();
e2.initCause(e);
throw e2;
}
}
/**
*
* @param textComponent
* @param searchPhrase if matchCase is false, this must be uppercase
* @param forward
* @param matchCase
* @param wrapAround
* @param selection this 2-int array represents the [row, column] of the current selection,
* and will be modified to a new cell coordinate if this method returns true.
* @return true if the "selection" argument is now populated with the location of
* this search phrase
*/
private static boolean find(JTable table, String searchPhrase,
boolean forward,boolean matchCase,boolean wrapAround,int[] selection) {
if(!matchCase)
searchPhrase = searchPhrase.toUpperCase();
int rowCount = table.getRowCount();
int columnCount = table.getColumnCount();
int currentRow = selection[0];
int currentColumn = selection[1];
if(currentRow==-1) currentRow = 0;
if(currentColumn==-1) currentColumn = 0;
int initialRow = currentRow;
int initialColumn = currentColumn;
while(true) {
if(forward) {
currentColumn++;
if(currentColumn==columnCount) {
currentColumn = 0;
currentRow++;
}
if(currentRow==rowCount) {
if(wrapAround) {
currentRow = 0;
} else {
return false;
}
}
} else {
currentColumn--;
if(currentColumn==-1) {
currentColumn = columnCount - 1;
currentRow--;
}
if(currentRow==-1) {
if(wrapAround) {
currentRow = rowCount-1;
} else {
return false;
}
}
}
if(currentRow == initialRow && currentColumn == initialColumn) {
return false;
}
Object value = table.getModel().getValueAt(currentRow, currentColumn);
String text = value==null ? "" : value.toString();
if(!matchCase) {
text = text.toUpperCase();
}
if(text.contains(searchPhrase)) {
selection[0] = currentRow;
selection[1] = currentColumn;
return true;
}
}
}
/** This can create a highlight effect for a selection of text.
* Originally this was designed to work with the {@link com.bric.plaf.AbstractSearchHighlight} class,
* but it can work with any object that has a constructor accepting the
* same arguments this method uses.
* <P>By default this will use the <code>AquaSearchHighlight</code>,
* but you can call <Code>UIManager.put("textSearchHighlightEffect", myClassName)</code>
* to change this default class.
*
* @param tc the text component.
* @param selectionStart the beginning of the selection to highlight.
* @param selectionEnd the end of the selection to highlight.
*/
public static void highlight(JTextComponent tc, int selectionStart,
int selectionEnd) {
String className = UIManager.getString("textSearchHighlightEffect");
if(className==null) {
className = "com.bric.plaf.AquaSearchHighlight";
}
try {
Class<?> c = Class.forName(className);
Constructor<?> constructor = c.getConstructor(new Class[] {JTextComponent.class, Integer.TYPE, Integer.TYPE });
constructor.newInstance(new Object[] {tc, new Integer(selectionStart), new Integer(selectionEnd)});
} catch(Throwable t) {
if(t instanceof RuntimeException)
throw (RuntimeException)t;
}
}
/** This can create a highlight effect for a selection of text.
* Originally this was designed to work with the {@link com.bric.plaf.AbstractSearchHighlight} class,
* but it can work with any object that has a constructor accepting the
* same arguments this method uses.
* <P>By default this will use the <code>AquaSearchHighlight</code>,
* but you can call <Code>UIManager.put("textSearchHighlightEffect", myClassName)</code>
* to change this default class.
*
* @param table the table to highlight.
* @param selectedRow the row that is selected.
* @param selectedColumn the column that is selected.
*/
public static void highlight(JTable table,int selectedRow,int selectedColumn) {
String className = UIManager.getString("textSearchHighlightEffect");
if(className==null) {
className = "com.bric.plaf.AquaSearchHighlight";
}
try {
Class<?> c = Class.forName(className);
Constructor<?> constructor = c.getConstructor(new Class[] {JTable.class, Integer.TYPE, Integer.TYPE });
constructor.newInstance(new Object[] {table, new Integer(selectedRow), new Integer(selectedColumn)});
} catch(Throwable t) {
if(t instanceof RuntimeException)
throw (RuntimeException)t;
}
}
public static void clearHighlights(JTextComponent jtc) {
AbstractSearchHighlight.clearHighlights();
}
}
| 34.054 | 114 | 0.692841 |
b9f1f37b64e34ff1ddbe9e5e94659a866fc6d32e | 236 | package statistics;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor
public enum LiveReqMethod {
INGEST("ingest"),//回源
PLAY("play"),
PUBLISH("publish");
private String reqMethod;
}
| 14.75 | 33 | 0.720339 |
1f8146cba5dac3ec4e490235bec397286bee3d93 | 2,998 | /*
* Copyright 2011 CodeGist.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ===================================================================
*
* More information at http://www.codegist.org.
*/
package org.codegist.crest.util;
import org.codegist.crest.CRestConfig;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import static java.lang.reflect.Modifier.isPublic;
/**
* CRest Component factory
* @see org.codegist.crest.annotate.CRestComponent
* @author [email protected]
*/
public final class ComponentFactory {
private ComponentFactory(){
throw new IllegalStateException();
}
/**
* Instanciate the given component class passing the CRestConfig to the constructor if available, otherwise uses the default empty constructor.
* @param clazz the component class to instanciate
* @param crestConfig the CRestConfig to pass if the component is CRestConfig aware
* @param <T> Type of the component
* @return the component instance
* @throws InvocationTargetException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws NoSuchMethodException
*/
public static <T> T instantiate(Class<T> clazz, CRestConfig crestConfig) throws InvocationTargetException, IllegalAccessException, InstantiationException, NoSuchMethodException {
try {
return accessible(clazz.getDeclaredConstructor(CRestConfig.class)).newInstance(crestConfig);
} catch (NoSuchMethodException e) {
return accessible(clazz.getDeclaredConstructor()).newInstance();
}
}
private static <T> Constructor<? extends T> accessible(final Constructor<? extends T> constructor){
if(!isPublic(constructor.getModifiers()) || !isPublic(constructor.getDeclaringClass().getModifiers())) {
AccessController.doPrivileged(new MakeAccessible(constructor));
}
return constructor;
}
private static final class MakeAccessible implements PrivilegedAction<Constructor> {
private final Constructor constructor;
private MakeAccessible(Constructor constructor) {
this.constructor = constructor;
}
public Constructor run() {
constructor.setAccessible(true);
return constructor;
}
}
}
| 36.560976 | 182 | 0.695464 |
081cb1a10f86a826411b55f8b603b742d24c308b | 1,789 | import java.util.Scanner;
public class p10_Diamond {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = Integer.parseInt(scanner.nextLine());
int sideDashCount = (n - 1) / 2;
int centerDashCount = 0;
for (int i = 0; i < n / 2 + n % 2; i++) {
String sideDashes = repeatStr("-", sideDashCount);
centerDashCount = n - 2 - 2 * sideDashCount;
String centerDashes = "";
if (centerDashCount > 0) {
centerDashes = repeatStr("-", centerDashCount);
}
if ((i == 0 || i == n - 1) && n % 2 != 0) {
System.out.println(sideDashes + "*" + sideDashes);
} else {
System.out.println(sideDashes + "*" + centerDashes + "*" + sideDashes);
}
sideDashCount-- ;
}
sideDashCount +=2;
for (int i = 0; i < n / 2 + n % 2 - 1; i++) {
String sideDashes = repeatStr("-", sideDashCount);
String centerDashes = "";
centerDashCount = n - 2 - 2 * sideDashCount;
if (centerDashCount > 0) {
centerDashes = repeatStr("-", centerDashCount);
}
if ((i == n / 2 + n % 2 - 2) && n % 2 != 0) {
System.out.println(sideDashes + "*" + sideDashes);
} else {
System.out.println(sideDashes + "*" + centerDashes + "*" + sideDashes);
}
sideDashCount++;
}
}
static String repeatStr (String str,int count){
StringBuilder sb = new StringBuilder();
for (int i = 0; i < count; i++) {
sb.append(str);
}
return sb.toString();
}
} | 33.754717 | 87 | 0.4673 |
bd2a751afeaa42c776e99ccf5840f8139a1bdb89 | 5,241 | /*
* JBoss, Home of Professional Open Source
* Copyright 2015, Red Hat, Inc., and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* 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 javax.enterprise.inject.spi.configurator;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.Set;
import javax.enterprise.util.TypeLiteral;
/**
* This API is an helper to configure a new {@link BeanAttributes} instance.
* CDI container must provides an implementation of this interface.
*
* This configurator is not thread safe and shall not be used concurrently.
*
* @see ProcessBeanAttributes#configureBeanAttributes()
* @param <T> the class of the bean instance
* @author Antoine Sabot-Durand
* @since 2.0
*/
public interface BeanAttributesConfigurator<T> {
/**
*
* Add a type to the bean types
*
* @param type the type to add
* @return self
*/
BeanAttributesConfigurator<T> addType(Type type);
/**
*
* Add a type to the bean types
*
* @param typeLiteral the type to add
* @return self
*/
BeanAttributesConfigurator<T> addType(TypeLiteral<?> typeLiteral);
/**
*
* Add types to the bean types
*
* @param types types to add
* @return self
*/
BeanAttributesConfigurator<T> addTypes(Type... types);
/**
*
* Add types to the bean types
*
* @param types types to add
* @return self
*/
BeanAttributesConfigurator<T> addTypes(Set<Type> types);
/**
* Adds an unrestricted set of bean types for the given type as if it represented a bean class of a managed bean.
* Illegal bean types are omitted.
*
* @param type to build the closure from
* @return self
*/
BeanAttributesConfigurator<T> addTransitiveTypeClosure(Type type);
/**
*
* Replace bean types
*
* @param types the types of the configured bean
* @return self
*/
BeanAttributesConfigurator<T> types(Type... types);
/**
*
* Replace bean types
*
* @param types the types of the configured bean
* @return self
*/
BeanAttributesConfigurator<T> types(Set<Type> types);
/**
*
* Replace Bean scope
*
* @param scope new scope for the configured bean
* @return self
*/
BeanAttributesConfigurator<T> scope(Class<? extends Annotation> scope);
/**
*
* Add a qualifier to the configured bean
*
* @param qualifier qualifier to add
* @return self
*/
BeanAttributesConfigurator<T> addQualifier(Annotation qualifier);
/**
*
* Add qualifiers to the bean.
*
* @param qualifiers qualifiers to add
* @return self
*/
BeanAttributesConfigurator<T> addQualifiers(Annotation... qualifiers);
/**
*
* Add qualifiers to the bean.
*
* @param qualifiers qualifiers to add
* @return self
*/
BeanAttributesConfigurator<T> addQualifiers(Set<Annotation> qualifiers);
/**
* Replace all qualifiers.
*
* @param qualifiers qualifiers for the build bean
* @return self
*/
BeanAttributesConfigurator<T> qualifiers(Annotation... qualifiers);
/**
* Replace all qualifiers.
*
* @param qualifiers for the configured bean
* @return self
*/
BeanAttributesConfigurator<T> qualifiers(Set<Annotation> qualifiers);
/**
*
* Add a stereotype to the configured bean
*
* @param stereotype stereotype to add
* @return self
*/
BeanAttributesConfigurator<T> addStereotype(Class<? extends Annotation> stereotype);
/**
*
* Add stereotypes to the configured bean
*
* @param stereotypes stereotypes to add
* @return self
*/
BeanAttributesConfigurator<T> addStereotypes(Set<Class<? extends Annotation>> stereotypes);
/**
*
* Replace stereotypes on the configured bean
*
* @param stereotypes for the configured bean
* @return self
*/
BeanAttributesConfigurator<T> stereotypes(Set<Class<? extends Annotation>> stereotypes);
/**
*
* Set the name of the configured bean
*
* @param name name for the configured bean
* @return self
*/
BeanAttributesConfigurator<T> name(String name);
/**
*
* Change the alternative status of the configured bean.
* By default the configured bean is not an alternative.
*
* @param value value for alternative property
* @return self
*/
BeanAttributesConfigurator<T> alternative(boolean value);
}
| 26.205 | 117 | 0.648159 |
89f28fc69d187b277ec90fd291d00d3f024159dd | 2,661 | package test;
import java.util.Date;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springrain.SpringrainApplication;
import org.springrain.cms.entity.CmsChannel;
import org.springrain.cms.entity.CmsContent;
import org.springrain.cms.entity.CmsSite;
import org.springrain.cms.service.ICmsChannelService;
import org.springrain.cms.service.ICmsContentService;
import org.springrain.cms.service.ICmsSiteService;
@RunWith(SpringRunner.class)
@SpringBootTest(classes=SpringrainApplication.class)
public class SiteTest {
@Resource
private ICmsSiteService cmsSiteService;
@Resource
private ICmsChannelService cmsChannelService;
@Resource
private ICmsContentService cmsContentService;
//@Test
public void addSite() throws Exception{
CmsSite cmsSite=new CmsSite();
cmsSite.setName("测试网站");
cmsSite.setLogo("");
cmsSite.setLookcount(1);
cmsSite.setPhone("138");
cmsSite.setQq("33333");
cmsSite.setUserId("admin");
cmsSite.setSiteType(0);
cmsSite.setActive(1);
cmsSite.setFooter("footer");
cmsSite.setContacts("contacts");
cmsSite.setDescription("description");
cmsSite.setDomainurl("http://www.baidu.com");
cmsSite.setTitle("title");
cmsSiteService.saveCmsSite(cmsSite);
}
/**
* 添加栏目
* @param siteId
* @throws Exception
*/
//@Test
public void addChannel() throws Exception{
String siteId="s_11";
CmsChannel cmsChannel=new CmsChannel();
cmsChannel.setSiteId(siteId);
cmsChannel.setName("测试栏目");
cmsChannel.setKeywords("keywords");
//cmsChannel.setComcode(value);
cmsChannel.setPid(null);
cmsChannel.setLookcount(0);
cmsChannel.setPositionLevel(0);
cmsChannel.setSortno(1);
cmsChannel.setActive(1);
cmsChannelService.saveChannel(cmsChannel);
}
/**
* 添加内容
* @throws Exception
*/
@Test
public void addContent() throws Exception{
String siteId="s_11";
String channelId="h_101";
CmsContent cmsContent=new CmsContent();
cmsContent.setSiteId(siteId);
cmsContent.setChannelId(channelId);
cmsContent.setContent("测试内容的内容Content");
cmsContent.setKeywords("keywords");
//cmsChannel.setComcode(value);
cmsContent.setLookcount(0);
cmsContent.setSortno(1);
cmsContent.setActive(1);
cmsContent.setTitle("title");
cmsContent.setCreateDate(new Date());
cmsContent.setCreatePerson("admin");
cmsContentService.saveContent(cmsContent);
}
}
| 24.190909 | 61 | 0.722661 |
7a4fbd6bb732ebc99cdb7ede48afade077ae171c | 280 | package Model.topology;
/**
* Created by lajtman on 24-04-2017.
*/
public class LatLng {
public LatLng() { }
public LatLng(double lat, double lng) {
this.lat = lat;
this.lng = lng;
}
public double lat;
public double lng;
}
| 16.470588 | 44 | 0.553571 |
d4f9a9dba92c2d5603cee7b89e5dfd700b6deaa3 | 2,122 | /********************************************************************************
* Copyright (c) 2018 Cirrus Link Solutions and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Cirrus Link Solutions - initial implementation
********************************************************************************/
package org.eclipse.tahu.pibrella;
import org.eclipse.tahu.pi.dio.PinDirection;
import org.eclipse.tahu.pi.dio.Pins;
/**
* Enumerates Pibrella I/O pins
*/
public enum PibrellaPins {
INA(Pins.P21, PinDirection.INPUT, "Input A", "Inputs/a"),
INB(Pins.P26, PinDirection.INPUT, "Input B", "Inputs/b"),
INC(Pins.P24, PinDirection.INPUT, "Input C", "Inputs/c"),
IND(Pins.P19, PinDirection.INPUT, "Input D", "Inputs/d"),
BUTTON(Pins.P23, PinDirection.INPUT, "Button", "button"),
OUTE(Pins.P15, PinDirection.OUTPUT, "Output E", "Outputs/e"),
OUTF(Pins.P16, PinDirection.OUTPUT, "Output F", "Outputs/f"),
OUTG(Pins.P18, PinDirection.OUTPUT, "Output G", "Outputs/g"),
OUTH(Pins.P22, PinDirection.OUTPUT, "Output H", "Outputs/h"),
LEDG(Pins.P7, PinDirection.OUTPUT, "Green LED", "Outputs/LEDs/green"),
LEDY(Pins.P11, PinDirection.OUTPUT, "Yellow LED", "Outputs/LEDs/yellow"),
LEDR(Pins.P13, PinDirection.OUTPUT, "Red LED", "Outputs/LEDs/red"),
BUZZER(Pins.P12, PinDirection.OUTPUT, "Buzzer", "buzzer");
private Pins pin;
private PinDirection direction;
private String name;
private String description;
private PibrellaPins(Pins pin, PinDirection direction, String name, String description) {
this.pin = pin;
this.direction = direction;
this.name = name;
this.description = description;
}
public Pins getPin() {
return this.pin;
}
public int getGPIO() {
return this.pin.getGPIO();
}
public PinDirection getDirection() {
return this.direction;
}
public String getName() {
return this.name;
}
public String getDescription() {
return this.description;
}
}
| 31.205882 | 90 | 0.658812 |
b5078c43eadbde57265dadbcf2c5756adf5b2620 | 543 | package net.minecraft.world.gen.placement;
import com.mojang.datafixers.Dynamic;
import java.util.Random;
import java.util.function.Function;
import java.util.stream.Stream;
import net.minecraft.util.math.BlockPos;
public class Passthrough extends SimplePlacement<NoPlacementConfig> {
public Passthrough(Function<Dynamic<?>, ? extends NoPlacementConfig> p_i51363_1_) {
super(p_i51363_1_);
}
public Stream<BlockPos> getPositions(Random random, NoPlacementConfig p_212852_2_, BlockPos pos) {
return Stream.of(pos);
}
} | 31.941176 | 101 | 0.777164 |
83fbc8d0bea44573f84089c09b4eda1026a65a0e | 2,370 | package ch.sourcepond.maven.release.scm.git;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.maven.plugin.logging.Log;
import org.junit.Before;
import org.junit.Test;
import ch.sourcepond.maven.release.commons.Version;
import ch.sourcepond.maven.release.scm.ProposedTag;
import ch.sourcepond.maven.release.scm.SCMException;
public class GitProposedTagsTest {
private static final String ANY_TAG = "anyTag";
private static final String ANY_VERSION = "1.0.0";
private final Log log = mock(Log.class);
private final ProposedTag tag = mock(ProposedTag.class);
private final Map<String, ProposedTag> proposedTags = new HashMap<>();
private final GitProposedTags tags = new GitProposedTags(log, proposedTags);
@Before
public void setup() {
proposedTags.put(ANY_TAG + "/" + ANY_VERSION, tag);
}
@Test
public void tagAndPushRepo() throws Exception {
tags.tag();
verify(tag).tagAndPush();
}
@Test
public void getTag() throws Exception {
final Version version = mock(Version.class);
when(version.getReleaseVersion()).thenReturn(ANY_VERSION);
assertSame(tag, tags.getTag(ANY_TAG, version));
}
@Test
public void getTag_NotFound() throws Exception {
final Version version = mock(Version.class);
when(version.getReleaseVersion()).thenReturn(ANY_VERSION);
try {
tags.getTag("notAvailable", version);
fail("Exception expected!");
} catch (final SCMException expected) {
assertEquals("No proposed tag registered for notAvailable/1.0.0", expected.getMessage());
}
}
@Test
public void iterator() {
final Iterator<ProposedTag> it = tags.iterator();
assertSame(tag, it.next());
assertFalse(it.hasNext());
}
@Test
public void revertTagsAndPush() throws Exception {
tags.undoTag();
verify(tag).delete();
}
@Test
public void revertTagsAndPush_LogWarnIfFailed() throws Exception {
final SCMException expected = new SCMException("expected");
doThrow(expected).when(tag).delete();
tags.undoTag();
verify(log).warn(expected);
}
}
| 28.214286 | 92 | 0.753586 |
7a8e463cabad72661aa375a2f2e748992b992754 | 2,348 | package net.viperfish.crawlerApp.core;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.FileVisitOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;
import java.util.function.Consumer;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import net.viperfish.crawlerApp.exceptions.ModuleLoadingException;
public class ModuleDirJarLoader implements CrawlerModuleLoader {
private Path path2Dir;
public ModuleDirJarLoader(Path path2Dir) {
this.path2Dir = path2Dir;
}
@Override
public List<CrawlerModule> loadModules() throws ModuleLoadingException {
try {
List<CrawlerModule> modules = new LinkedList<>();
Files.walk(path2Dir, FileVisitOption.FOLLOW_LINKS).forEach(new Consumer<Path>() {
@Override
public void accept(Path path) {
try {
if (Files.isRegularFile(path) && path.getFileName().toString()
.endsWith(".jar")) {
JarFile jarFile = new JarFile(path.toFile());
modules.add(load(path, jarFile));
}
} catch (IOException | ClassNotFoundException | InstantiationException | IllegalAccessException e) {
return;
}
}
});
return modules;
} catch (IOException e) {
throw new ModuleLoadingException(e);
}
}
private CrawlerModule load(Path path2Jar, JarFile jarFile)
throws ClassNotFoundException, MalformedURLException, InstantiationException, IllegalAccessException {
Enumeration<JarEntry> e = jarFile.entries();
URL[] urls = {new URL("jar:file:" + path2Jar.toString() + "!/")};
URLClassLoader cl = URLClassLoader.newInstance(urls);
String moduleClassname = "";
while (e.hasMoreElements()) {
JarEntry je = e.nextElement();
if (je.isDirectory() || !je.getName().endsWith(".class")) {
continue;
}
// -6 because of .class
String className = je.getName().substring(0, je.getName().length() - 6);
className = className.replace('/', '.');
Class c = cl.loadClass(className);
if (c.getSimpleName().equals("MainModule")) {
moduleClassname = className;
}
}
Object result = Class.forName(moduleClassname).newInstance();
if (result instanceof CrawlerModule) {
return (CrawlerModule) result;
}
return null;
}
}
| 30.493506 | 105 | 0.715503 |
5597d0570eb06c1f384d4a3c054ca4a796b746eb | 1,127 | package com.uikoo9.manage.ucenter.model;
import java.util.List;
import com.jfinal.plugin.activerecord.Model;
import com.uikoo9.util.core.annotation.QTable;
import com.uikoo9.util.core.data.QStringUtil;
/**
* UcenterRoleRMenuModel<br>
* id id<br>
* ucenter_role_id 角色id<br>
* ucenter_menu_id 菜单id<br>
* ucenter_menu_url 菜单url<br>
* cdate 创建时间<br>
* cuser_id 创建人id<br>
* cuser_name 创建人姓名<br>
* @author qiaowenbin
*/
@QTable("t_ucenter_role_r_menu")
@SuppressWarnings("serial")
public class UcenterRoleRMenuModel extends Model<UcenterRoleRMenuModel>{
public static final UcenterRoleRMenuModel dao = new UcenterRoleRMenuModel();
/**
* find all
* @return
*/
public List<UcenterRoleRMenuModel> findAll(){
return findAll(null);
}
/**
* find all by order
* @param order
* @return
*/
public List<UcenterRoleRMenuModel> findAll(String order){
StringBuilder sb = new StringBuilder("select * from t_ucenter_role_r_menu ");
if(QStringUtil.isEmpty(order)){
return dao.find(sb.append("order by id desc").toString());
}else{
return dao.find(sb.append(order).toString());
}
}
}
| 23 | 79 | 0.721384 |
a35438ec5c29a37337b0062c5a1cd9e8813c3089 | 1,761 | // ### TopLink Mapping Workbench 9.0.3 generated source code ###
package com.profitera.descriptor.db.config;
public class Holiday
implements java.io.Serializable
{
// Generated constants
public static final String HOLIDAY_DATE = "holidayDate";
public static final String HOLIDAY_DESC = "holidayDesc";
public static final String HOLIDAY_ID = "holidayId";
public static final String HOLIDAY_STATE_REL = "holidayStateRel";
public static final String NO_OF_DAYS = "noOfDays";
// End of generated constants
private java.sql.Timestamp holidayDate;
private java.lang.String holidayDesc;
private java.lang.Double holidayId;
private oracle.toplink.indirection.ValueHolderInterface holidayStateRel= new oracle.toplink.indirection.ValueHolder(new java.util.Vector());
private java.lang.Integer noOfDays;
public Holiday()
{
// Fill in method body here.
}
public java.sql.Timestamp getHolidayDate()
{
return holidayDate;
}
public java.lang.String getHolidayDesc()
{
return holidayDesc;
}
public java.lang.Double getHolidayId()
{
return holidayId;
}
public java.util.Vector getHolidayStateRel()
{
return (java.util.Vector) holidayStateRel.getValue();
}
public java.lang.Integer getNoOfDays()
{
return noOfDays;
}
public void setHolidayDate(java.sql.Timestamp holidayDate)
{
this.holidayDate = holidayDate;
}
public void setHolidayDesc(java.lang.String holidayDesc)
{
this.holidayDesc = holidayDesc;
}
public void setHolidayId(java.lang.Double holidayId)
{
this.holidayId = holidayId;
}
public void setHolidayStateRel(java.util.Vector holidayStateRel)
{
this.holidayStateRel.setValue(holidayStateRel);
}
public void setNoOfDays(java.lang.Integer noOfDays)
{
this.noOfDays = noOfDays;
}
}
| 21.740741 | 141 | 0.760363 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.