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 |
|---|---|---|---|---|---|
1a79fde48d67009f065a806bcb113b9c44039cfe | 6,089 | /*
* Copyright 2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.rsocket.broker.spring.cluster;
import java.net.URI;
import java.time.Duration;
import java.util.function.Consumer;
import io.rsocket.exceptions.ApplicationErrorException;
import io.rsocket.exceptions.RejectedSetupException;
import io.rsocket.broker.RoutingTable;
import io.rsocket.broker.spring.BrokerProperties;
import io.rsocket.broker.spring.BrokerProperties.Broker;
import io.rsocket.broker.common.WellKnownKey;
import io.rsocket.broker.frames.BrokerInfo;
import io.rsocket.broker.frames.RouteJoin;
import io.rsocket.broker.frames.BrokerFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Mono;
import reactor.core.publisher.Sinks;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.rsocket.RSocketRequester;
import org.springframework.messaging.rsocket.annotation.ConnectMapping;
import org.springframework.stereotype.Controller;
/**
* Handles inter-broker communication.
*/
@Controller
public class ClusterController {
private final Logger logger = LoggerFactory.getLogger(getClass());
private final BrokerProperties properties;
private final BrokerConnections brokerConnections;
private final RoutingTable routingTable;
private final Consumer<Broker> connectionEventPublisher;
private final Sinks.Many<BrokerInfo> connectEvents = Sinks.many().multicast().directBestEffort();
public ClusterController(BrokerProperties properties, BrokerConnections brokerConnections, RoutingTable routingTable,
Consumer<Broker> connectionEventPublisher) {
this.properties = properties;
this.brokerConnections = brokerConnections;
this.routingTable = routingTable;
this.connectionEventPublisher = connectionEventPublisher;
// subscribe to connect events so that a return BrokerInfo call is delayed
// This allows broker to maintain a single connection, but allows other broker
// to call brokerInfo() to get this broker's id and add it to BrokerConnections.
// TODO: configurable delay
connectEvents.asFlux().delayElements(Duration.ofSeconds(1))
.flatMap(brokerInfo -> {
RSocketRequester requester = brokerConnections.get(brokerInfo);
return sendBrokerInfo(requester, brokerInfo);
}).subscribe();
}
@ConnectMapping
public Mono<Void> onConnect(BrokerFrame BrokerFrame, RSocketRequester rSocketRequester) {
// FIXME: hack
if (!(BrokerFrame instanceof BrokerInfo)) {
return Mono.empty();
}
BrokerInfo brokerInfo = (BrokerInfo) BrokerFrame;
if (brokerInfo.getBrokerId().equals(properties.getBrokerId())) {
//TODO: weird case I wonder if I can avoid
return Mono.empty();
}
logger.info("received connection from {}", brokerInfo);
if (brokerConnections.contains(brokerInfo)) {
// reject duplicate connections
return Mono.error(new RejectedSetupException("Duplicate connection from " + brokerInfo));
}
// store broker info
brokerConnections.put(brokerInfo, rSocketRequester);
// send a connectEvent
connectEvents.tryEmitNext(brokerInfo);
return Mono.empty();
}
@MessageMapping("cluster.remote-broker-info")
public void brokerInfoUpdate(BrokerInfo brokerInfo) {
logger.info("received remote BrokerInfo {}", brokerInfo);
// make new cluster and proxy connections if they don't exist.
Broker broker = new Broker();
broker.setCluster(URI.create(brokerInfo.getTags().get(WellKnownKey.BROKER_CLUSTER_URI)));
broker.setProxy(URI.create(brokerInfo.getTags().get(WellKnownKey.BROKER_PROXY_URI)));
connectionEventPublisher.accept(broker);
}
@MessageMapping("cluster.broker-info")
public Mono<BrokerInfo> brokerInfo(BrokerInfo brokerInfo, RSocketRequester rSocketRequester) {
logger.info("received brokerInfo from {}", brokerInfo);
// if brokerConnections has connections
if (brokerConnections.contains(brokerInfo)) {
logger.debug("connection for broker already exists {}", brokerInfo);
// we can now accept RouteJoin from this broker
// TODO: add flag to RoutingTable for this broker
return Mono.just(getLocalBrokerInfo());
}
// else store broker info
brokerConnections.put(brokerInfo, rSocketRequester);
// send BrokerInfo back
return sendBrokerInfo(rSocketRequester, brokerInfo);
}
//TODO: @MessageMapping("cluster.broker-info")
private Mono<BrokerInfo> sendBrokerInfo(RSocketRequester rSocketRequester, BrokerInfo brokerInfo) {
BrokerInfo localBrokerInfo = getLocalBrokerInfo();
return rSocketRequester.route("cluster.broker-info")
.data(localBrokerInfo)
.retrieveMono(BrokerInfo.class)
.map(bi -> localBrokerInfo);
}
private BrokerInfo getLocalBrokerInfo() {
return BrokerInfo.from(properties.getBrokerId())
.with(WellKnownKey.BROKER_PROXY_URI, properties.getUri().toString())
.with(WellKnownKey.BROKER_CLUSTER_URI, properties.getCluster().getUri().toString())
.build();
}
@MessageMapping("cluster.route-join")
private Mono<RouteJoin> routeJoin(RouteJoin routeJoin) {
logger.info("received RouteJoin {}", routeJoin);
BrokerInfo brokerInfo = BrokerInfo.from(routeJoin.getBrokerId()).build();
if (!brokerConnections.contains(brokerInfo)) {
// attempting to add a route for a broker with no connection.
return Mono.error(new ApplicationErrorException("No connection for broker " + brokerInfo));
}
routingTable.add(routeJoin);
return Mono.just(routeJoin);
}
@MessageMapping("hello")
public Mono<String> hello(String name) {
return Mono.just("Hello " + name);
}
}
| 36.461078 | 118 | 0.773854 |
5f92abc9872594b3141ff4fef480a5283d25a473 | 5,741 | package com.redshift.rs_vapourtraining;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.Menu;
import android.widget.TextView;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.navigation.NavigationView;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import com.redshift.rs_vapourtraining.databinding.ActivityNavigationComponentBinding;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.Map;
public class NavigationComponent extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
private ActivityNavigationComponentBinding binding;
private DBHandler dbHandler;
int userCreds = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityNavigationComponentBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
setSupportActionBar(binding.appBarNavigationComponent.toolbar);
binding.appBarNavigationComponent.fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Hello", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = binding.drawerLayout;
NavigationView navigationView = binding.navView;
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_buy_creds, R.id.nav_add_cards)
.setOpenableLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_navigation_component);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
dbHandler = new DBHandler(NavigationComponent.this);
String IPaddress = getLocalIpAddress();
getServer(IPaddress);
String username = getIntent().getStringExtra("username");
if (username == null){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("userRS","1"); //vuln
editor.commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.navigation_component, menu);
String username = getIntent().getStringExtra("username");
if (username == null){
username = "admin";
}
TextView actionName = (TextView)findViewById(R.id.Actionname);
actionName.setText(username);
String userID = dbHandler.getUserID(username);
userCreds = dbHandler.getCreds(userID);
return true;
}
@Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_navigation_component);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
public static String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException ex) {
ex.printStackTrace();
}
return null;
}
public void getServer(String ipAddress){
RequestQueue ExampleRequestQueue = Volley.newRequestQueue(this);
String url = "http://192.168.1.193:5000/";
StringRequest ExampleStringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//This code is executed if the server responds, whether or not the response contains data.
}
}, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
@Override
public void onErrorResponse(VolleyError error) {
//This code is executed if there is an error.
}
});
ExampleRequestQueue.add(ExampleStringRequest);
}
} | 38.530201 | 126 | 0.691343 |
046d2323291441502a886a42f836912fe968f71b | 594 | package com.coutemeier.utils;
import java.util.Collection;
public enum CollectionsUtils {
INSTANCE;
public static final String asString(Collection<? extends String> collection) {
if (isEmpty(collection)) {
return "";
}
final StringBuilder asList = new StringBuilder(64);
for(String item: collection) {
asList.append(", ").append(item);
}
return asList.substring(2);
}
public static final boolean isEmpty(Collection<?> collection) {
return (collection == null || collection.size() == 0);
}
} | 27 | 82 | 0.617845 |
36daa1de920368cab3f98a913607649f9a46d210 | 12,759 | package pl.polidea.treeview;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import android.database.DataSetObserver;
import android.util.Log;
/**
* In-memory manager of tree state.
*
* @param <T>
* type of identifier
*/
public class InMemoryTreeStateManager<T> implements TreeStateManager<T> {
private static final String TAG = InMemoryTreeStateManager.class
.getSimpleName();
private static final long serialVersionUID = 1L;
private final Map<T, InMemoryTreeNode<T>> allNodes = new HashMap<T, InMemoryTreeNode<T>>();
private final InMemoryTreeNode<T> topSentinel = new InMemoryTreeNode<T>(
null, null, -1, true);
private transient List<T> visibleListCache = null; // lasy initialised
private transient List<T> unmodifiableVisibleList = null;
private boolean visibleByDefault = true;
private final transient Set<DataSetObserver> observers = new HashSet<DataSetObserver>();
private synchronized void internalDataSetChanged() {
visibleListCache = null;
unmodifiableVisibleList = null;
for (final DataSetObserver observer : observers) {
observer.onChanged();
}
}
/**
* If true new nodes are visible by default.
*
* @param visibleByDefault
* if true, then newly added nodes are expanded by default
*/
public void setVisibleByDefault(final boolean visibleByDefault) {
this.visibleByDefault = visibleByDefault;
}
private InMemoryTreeNode<T> getNodeFromTreeOrThrow(final T id) {
if (id == null) {
throw new NodeNotInTreeException("(null)");
}
final InMemoryTreeNode<T> node = allNodes.get(id);
if (node == null) {
throw new NodeNotInTreeException(id.toString());
}
return node;
}
private InMemoryTreeNode<T> getNodeFromTreeOrThrowAllowRoot(final T id) {
if (id == null) {
return topSentinel;
}
return getNodeFromTreeOrThrow(id);
}
private void expectNodeNotInTreeYet(final T id) {
final InMemoryTreeNode<T> node = allNodes.get(id);
if (node != null) {
throw new NodeAlreadyInTreeException(id.toString(), node.toString());
}
}
@Override
public synchronized TreeNodeInfo<T> getNodeInfo(final T id) {
final InMemoryTreeNode<T> node = getNodeFromTreeOrThrow(id);
final List<InMemoryTreeNode<T>> children = node.getChildren();
boolean expanded = false;
if (!children.isEmpty() && children.get(0).isVisible()) {
expanded = true;
}
return new TreeNodeInfo<T>(id, node.getLevel(), !children.isEmpty(),
node.isVisible(), expanded);
}
@Override
public synchronized List<T> getChildren(final T id) {
final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id);
return node.getChildIdList();
}
@Override
public synchronized T getParent(final T id) {
final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id);
return node.getParent();
}
private boolean getChildrenVisibility(final InMemoryTreeNode<T> node) {
boolean visibility;
final List<InMemoryTreeNode<T>> children = node.getChildren();
if (children.isEmpty()) {
visibility = visibleByDefault;
} else {
visibility = children.get(0).isVisible();
}
return visibility;
}
@Override
public synchronized void addBeforeChild(final T parent, final T newChild,
final T beforeChild) {
expectNodeNotInTreeYet(newChild);
final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(parent);
final boolean visibility = getChildrenVisibility(node);
// top nodes are always expanded.
if (beforeChild == null) {
final InMemoryTreeNode<T> added = node.add(0, newChild, visibility);
allNodes.put(newChild, added);
} else {
final int index = node.indexOf(beforeChild);
final InMemoryTreeNode<T> added = node.add(index == -1 ? 0 : index,
newChild, visibility);
allNodes.put(newChild, added);
}
if (visibility) {
internalDataSetChanged();
}
}
@Override
public synchronized void addAfterChild(final T parent, final T newChild,
final T afterChild) {
expectNodeNotInTreeYet(newChild);
final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(parent);
final boolean visibility = getChildrenVisibility(node);
if (afterChild == null) {
final InMemoryTreeNode<T> added = node.add(
node.getChildrenListSize(), newChild, visibility);
allNodes.put(newChild, added);
} else {
final int index = node.indexOf(afterChild);
final InMemoryTreeNode<T> added = node.add(
index == -1 ? node.getChildrenListSize() : index + 1, newChild,
visibility);
allNodes.put(newChild, added);
}
if (visibility) {
internalDataSetChanged();
}
}
@Override
public synchronized void removeNodeRecursively(final T id) {
final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id);
final boolean visibleNodeChanged = removeNodeRecursively(node);
final T parent = node.getParent();
final InMemoryTreeNode<T> parentNode = getNodeFromTreeOrThrowAllowRoot(parent);
parentNode.removeChild(id);
if (visibleNodeChanged) {
internalDataSetChanged();
}
}
private boolean removeNodeRecursively(final InMemoryTreeNode<T> node) {
boolean visibleNodeChanged = false;
for (final InMemoryTreeNode<T> child : node.getChildren()) {
if (removeNodeRecursively(child)) {
visibleNodeChanged = true;
}
}
node.clearChildren();
if (node.getId() != null) {
allNodes.remove(node.getId());
if (node.isVisible()) {
visibleNodeChanged = true;
}
}
return visibleNodeChanged;
}
private void setChildrenVisibility(final InMemoryTreeNode<T> node,
final boolean visible, final boolean recursive) {
for (final InMemoryTreeNode<T> child : node.getChildren()) {
child.setVisible(visible);
if (recursive) {
setChildrenVisibility(child, visible, true);
}
}
}
@Override
public synchronized void expandDirectChildren(final T id) {
Log.d(TAG, "Expanding direct children of " + id);
final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id);
setChildrenVisibility(node, true, false);
internalDataSetChanged();
}
@Override
public synchronized void expandEverythingBelow(final T id) {
Log.d(TAG, "Expanding all children below " + id);
final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id);
setChildrenVisibility(node, true, true);
internalDataSetChanged();
}
@Override
public synchronized void collapseChildren(final T id) {
final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id);
if (node == topSentinel) {
for (final InMemoryTreeNode<T> n : topSentinel.getChildren()) {
setChildrenVisibility(n, false, true);
}
} else {
setChildrenVisibility(node, false, true);
}
internalDataSetChanged();
}
@Override
public synchronized T getNextSibling(final T id) {
final T parent = getParent(id);
final InMemoryTreeNode<T> parentNode = getNodeFromTreeOrThrowAllowRoot(parent);
boolean returnNext = false;
for (final InMemoryTreeNode<T> child : parentNode.getChildren()) {
if (returnNext) {
return child.getId();
}
if (child.getId().equals(id)) {
returnNext = true;
}
}
return null;
}
@Override
public synchronized T getPreviousSibling(final T id) {
final T parent = getParent(id);
final InMemoryTreeNode<T> parentNode = getNodeFromTreeOrThrowAllowRoot(parent);
T previousSibling = null;
for (final InMemoryTreeNode<T> child : parentNode.getChildren()) {
if (child.getId().equals(id)) {
return previousSibling;
}
previousSibling = child.getId();
}
return null;
}
@Override
public synchronized boolean isInTree(final T id) {
return allNodes.containsKey(id);
}
@Override
public synchronized int getVisibleCount() {
return getVisibleList().size();
}
@Override
public synchronized List<T> getVisibleList() {
T currentId = null;
if (visibleListCache == null) {
visibleListCache = new ArrayList<T>(allNodes.size());
do {
currentId = getNextVisible(currentId);
if (currentId == null) {
break;
} else {
visibleListCache.add(currentId);
}
} while (true);
}
if (unmodifiableVisibleList == null) {
unmodifiableVisibleList = Collections
.unmodifiableList(visibleListCache);
}
return unmodifiableVisibleList;
}
public synchronized T getNextVisible(final T id) {
final InMemoryTreeNode<T> node = getNodeFromTreeOrThrowAllowRoot(id);
if (!node.isVisible()) {
return null;
}
final List<InMemoryTreeNode<T>> children = node.getChildren();
if (!children.isEmpty()) {
final InMemoryTreeNode<T> firstChild = children.get(0);
if (firstChild.isVisible()) {
return firstChild.getId();
}
}
final T sibl = getNextSibling(id);
if (sibl != null) {
return sibl;
}
T parent = node.getParent();
do {
if (parent == null) {
return null;
}
final T parentSibling = getNextSibling(parent);
if (parentSibling != null) {
return parentSibling;
}
parent = getNodeFromTreeOrThrow(parent).getParent();
} while (true);
}
@Override
public synchronized void registerDataSetObserver(
final DataSetObserver observer) {
observers.add(observer);
}
@Override
public synchronized void unregisterDataSetObserver(
final DataSetObserver observer) {
observers.remove(observer);
}
@Override
public int getLevel(final T id) {
return getNodeFromTreeOrThrow(id).getLevel();
}
@Override
public Integer[] getHierarchyDescription(final T id) {
final int level = getLevel(id);
final Integer[] hierarchy = new Integer[level + 1];
int currentLevel = level;
T currentId = id;
T parent = getParent(currentId);
while (currentLevel >= 0) {
hierarchy[currentLevel--] = getChildren(parent).indexOf(currentId);
currentId = parent;
parent = getParent(parent);
}
return hierarchy;
}
private void appendToSb(final StringBuilder sb, final T id) {
if (id != null) {
final TreeNodeInfo<T> node = getNodeInfo(id);
final int indent = node.getLevel() * 4;
final char[] indentString = new char[indent];
Arrays.fill(indentString, ' ');
sb.append(indentString);
sb.append(node.toString());
sb.append(Arrays.asList(getHierarchyDescription(id)).toString());
sb.append("\n");
}
final List<T> children = getChildren(id);
for (final T child : children) {
appendToSb(sb, child);
}
}
@Override
public synchronized String toString() {
final StringBuilder sb = new StringBuilder();
appendToSb(sb, null);
return sb.toString();
}
@Override
public synchronized void clear() {
allNodes.clear();
topSentinel.clearChildren();
internalDataSetChanged();
}
@Override
public void refresh() {
internalDataSetChanged();
}
}
| 33.488189 | 95 | 0.601536 |
ac0f032e3391b261c17f2113f607a2713fc3a6ff | 1,164 | package com.feizhang.activityresult.sample;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import com.feizhang.activityresult.ActivityResult;
import com.feizhang.activityresult.InterceptWith;
import com.feizhang.activityresult.OnInterceptResult;
import com.feizhang.activityresult.sample.interceptor.LoginInterceptor;
@InterceptWith(LoginInterceptor.class)
public class OrderDetailActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_detail);
ActivityResult result = new ActivityResult(this);
result.intercept(new OnInterceptResult() {
/**
* init data or load data from http and so on.
*/
@SuppressLint("SetTextI18n")
@Override
public void invoke() {
TextView imageView = findViewById(R.id.contentView);
imageView.setText("This Is the Order Detail Page");
}
});
}
}
| 32.333333 | 71 | 0.70189 |
644ab076d11ca0f72da0c3579acfa4d8f393dbf7 | 4,610 | package app.domains.models;
import app.validation.Age;
import app.validation.Email;
import app.validation.Password;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
@Entity
@Table(name = "users")
public class User implements Serializable {
private Integer id;
private String username;
private String password;
private String email;
private Picture profilePicture;
private String firstName;
private String lastName;
private Town bornTown;
private Town currentTown;
private Date registeredOn;
private Date lastTimeLoggedIn;
private Integer age;
private Boolean isDeleted;
private Set<User> friends;
private Set<AlbumRole> albumRoles;
public User() {
this.setFriends(new HashSet<>());
this.setAlbumRoles(new HashSet<>());
}
@Id
@Column(name = "user_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(name = "username")
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Column(name = "password")
@Password(minLength = 6, maxLength = 50, containsLowercase = true)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Column(name = "email")
@Email
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Column(name = "profile_picture")
public Picture getProfilePicture() {
return profilePicture;
}
public void setProfilePicture(Picture profilePicture) {
this.profilePicture = profilePicture;
}
@Column(name = "first_name")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@Column(name = "last_name")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Transient
public String getFullName(){
return this.firstName + " " + this.lastName;
}
@ManyToOne(cascade = CascadeType.ALL)
public Town getBornTown() {
return bornTown;
}
public void setBornTown(Town bornTown) {
this.bornTown = bornTown;
}
@ManyToOne(cascade = CascadeType.ALL)
public Town getCurrentTown() {
return currentTown;
}
public void setCurrentTown(Town currentTown) {
this.currentTown = currentTown;
}
@Column(name = "registered_on")
public Date getRegisteredOn() {
return registeredOn;
}
public void setRegisteredOn(Date registeredOn) {
this.registeredOn = registeredOn;
}
@Column(name = "last_login_time")
public Date getLastTimeLoggedIn() {
return lastTimeLoggedIn;
}
public void setLastTimeLoggedIn(Date lastTimeLoggedIn) {
this.lastTimeLoggedIn = lastTimeLoggedIn;
}
@Column(name = "age")
@Age
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Column(name = "is_deleted")
public Boolean getDeleted() {
return isDeleted;
}
public void setDeleted(Boolean deleted) {
isDeleted = deleted;
}
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(
name = "users_friends",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "friend_id")
)
public Set<User> getFriends() {
return friends;
}
public void setFriends(Set<User> friends) {
this.friends = friends;
}
@OneToMany(cascade = CascadeType.ALL, mappedBy = "user")
public Set<AlbumRole> getAlbumRoles() {
return albumRoles;
}
public void setAlbumRoles(Set<AlbumRole> albumRoles) {
this.albumRoles = albumRoles;
}
@Override
public String toString() {
return String.format("%s %s %d %s",this.getUsername(), this.getEmail(), this.getAge(),this.getFullName());
}
}
| 23.762887 | 115 | 0.60564 |
cceb739c48bec615c6c93e08c04cfc185bd032c6 | 356 | package org.planet_sl.apimigration.benchmark.anno;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Wrapping {
}
| 27.384615 | 73 | 0.831461 |
02f27060b0d82ec1f7357cb289cf137e82291878 | 1,037 | package gui.controllers;
import java.util.Observer;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.spi.LoggingEvent;
/**
* The Class ObservableAppender.
*/
public class ObservableAppender extends AppenderSkeleton {
/** The observable delegate. */
private final ObservableDelegate observableDelegate = new ObservableDelegate();
/**
* Adds the observer.
*
* @param o the observer
*/
public void addObserver(Observer o) {
observableDelegate.addObserver(o);
}
/* (non-Javadoc)
* @see org.apache.log4j.AppenderSkeleton#append(org.apache.log4j.spi.LoggingEvent)
*/
@Override
protected void append(LoggingEvent event) {
observableDelegate.doSetChanged();
observableDelegate.notifyObservers(event.getLevel() + ": " + event.getMessage());
}
/* (non-Javadoc)
* @see org.apache.log4j.Appender#close()
*/
@Override
public void close() { }
/* (non-Javadoc)
* @see org.apache.log4j.Appender#requiresLayout()
*/
@Override
public boolean requiresLayout() {
return false;
}
}
| 21.163265 | 84 | 0.718419 |
466498f4811cd6242d0eb7f51526aa95a6bad840 | 3,547 | package sonar.calculator.mod.client.renderers;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.block.model.ItemCameraTransforms.TransformType;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
import sonar.calculator.mod.client.models.ModelFabricationArm;
import sonar.calculator.mod.common.tileentity.machines.TileEntityFabricationChamber;
import sonar.core.common.block.properties.SonarProperties;
public class RenderFabricationChamber extends TileEntitySpecialRenderer<TileEntityFabricationChamber> {
private static final ResourceLocation texture = new ResourceLocation("Calculator:textures/model/fabrication_arm_techne.png");
private ModelFabricationArm model;
public RenderFabricationChamber() {
this.model = new ModelFabricationArm();
}
@Override
public void render(TileEntityFabricationChamber tileentity, double x, double y, double z, float partialTicks, int destroyStage, float f) {
//public void renderTileEntityAt(TileEntityFabricationChamber tileentity, double x, double y, double z, float partialTicks, int destroyStage) {
int i;
if (tileentity.getWorld() == null) {
i = 0;
} else {
i = tileentity.getWorld().getBlockState(tileentity.getPos()).getValue(SonarProperties.FACING).getIndex();
}
GlStateManager.pushMatrix();
GlStateManager.translate((float) x + 0.5F, (float) y + 1.5F, (float) z + 0.5F);
GlStateManager.pushMatrix();
GlStateManager.rotate(180.0F, 0.0F, 0.0F, 1.0F);
GlStateManager.rotate(90F, 0.0F, 1.0F, 0.0F);
// GlStateManager.rotate(tileentity.angle * 10, 0.0F, 1.0F, 0.0F);
switch (i) {
case 1:
GlStateManager.rotate(0.0F, 0.0F, 1.0F, 0.0F);
break;
case 2:
GlStateManager.rotate(-90.0F, 0.0F, 1.0F, 0.0F);
break;
case 3:
GlStateManager.rotate(90.0F, 0.0F, 1.0F, 0.0F);
break;
case 4:
GlStateManager.rotate(180.0F, 0.0F, 1.0F, 0.0F);
}
int progress=tileentity.currentMoveTime.getObject();
float rotateR = (float) progress * 25 / 50;
float rotateL=360-rotateR;
GlStateManager.pushMatrix();
GlStateManager.scale(0.5, 0.5, 0.5);
GlStateManager.translate(0.5, 0.375, 0.75);
Minecraft.getMinecraft().renderEngine.bindTexture(texture);
GlStateManager.rotate(rotateR, 0, 1, 0);
this.model.renderTile(null, 0.0F, 0.0F, -0.1F, 0.0F, 0.0F, 0.0625F, false, false, progress);
GlStateManager.rotate(rotateR, 0, -1, 0);
GlStateManager.translate(-1, 0.0, 0.0);
GlStateManager.rotate(rotateL, 0, 1, 0);
this.model.renderTile(null, 0.0F, 0.0F, -0.1F, 0.0F, 0.0F, 0.0625F, false, false, progress);
GlStateManager.rotate(rotateL, 0, -1, 0);
GlStateManager.popMatrix();
GlStateManager.translate(0.5, 1.506, 0.5);
if (tileentity.selected != null) {
if (!Minecraft.getMinecraft().getRenderItem().shouldRenderItemIn3D(tileentity.selected )) {
GL11.glRotated(90, 1, 0, 0);
GL11.glTranslated(0, -0.0, 0);
GL11.glScaled(0.7, 0.7, 0.7);
GL11.glTranslated(-0.72, -0.84, 0.74);
Minecraft.getMinecraft().getRenderItem().renderItem(tileentity.selected , TransformType.GROUND);
} else {
GL11.glRotated(180, 1, 0, 0);
GL11.glRotated(180, 0, 1, 0);
GL11.glScaled(0.6, 0.6, 0.6);
GL11.glTranslated(0.84, 1.08, -0.84);
Minecraft.getMinecraft().getRenderItem().renderItem(tileentity.selected , TransformType.GROUND);
}
}
GlStateManager.popMatrix();
GlStateManager.popMatrix();
}
} | 41.729412 | 151 | 0.724274 |
f964a1d99625993f5abaca6db194d46a023d895d | 247 | package com.bitcola.exchange.ctc.mapper;
import com.bitcola.ctc.ColaCtcFee;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.common.Mapper;
@Repository
public interface ColaCtcFeeMapper extends Mapper<ColaCtcFee> {
}
| 20.583333 | 62 | 0.825911 |
11fd242a33d3005608fede929f0f279907ae851e | 8,028 | package pinacolada.resources.pcl;
import basemod.BaseMod;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.megacrit.cardcrawl.cards.AbstractCard;
import com.megacrit.cardcrawl.core.CardCrawlGame;
import com.megacrit.cardcrawl.helpers.GameDictionary;
import com.megacrit.cardcrawl.helpers.TipHelper;
import com.megacrit.cardcrawl.localization.*;
import eatyourbeets.console.CommandsManager;
import eatyourbeets.resources.common.CommonResources;
import eatyourbeets.utilities.EYBFontHelper;
import pinacolada.cards.base.*;
import pinacolada.cards.base.baseeffects.BaseEffect;
import pinacolada.effects.AttackEffects;
import pinacolada.effects.SFX;
import pinacolada.events.base.PCLEvent;
import pinacolada.misc.CardPoolPanelItem;
import pinacolada.powers.affinity.AbstractPCLAffinityPower;
import pinacolada.powers.replacement.GenericFadingPower;
import pinacolada.resources.CardTooltips;
import pinacolada.resources.PCLAbstractResources;
import pinacolada.resources.PGR;
import pinacolada.rewards.pcl.ConcertsFinalHourReward;
import pinacolada.rewards.pcl.MissingPieceReward;
import pinacolada.rewards.pcl.SpecialGoldReward;
import pinacolada.utilities.PCLJUtils;
import java.lang.reflect.Field;
import static pinacolada.resources.PGR.Enums.Characters.THE_FOOL;
public class PCLResources extends PCLAbstractResources {
public static final String ID = PGR.BASE_PREFIX;
public final PCLDungeonData Dungeon = PCLDungeonData.Register(CreateID("Data"));
public final PCLStrings Strings = new PCLStrings();
public final PCLImages Images = new PCLImages();
public final PCLConfig Config = new PCLConfig();
protected String defaultLanguagePath;
public PCLResources()
{
super(ID, AbstractCard.CardColor.COLORLESS, THE_FOOL);
}
protected void InitializeEvents()
{
PCLEvent.RegisterEvents();
}
protected void InitializeAudio()
{
SFX.Initialize();
}
protected void InitializeStrings()
{
PCLJUtils.LogInfo(this, "InitializeStrings();");
LoadCustomStrings(OrbStrings.class);
LoadCustomCardStrings();
LoadCustomStrings(RelicStrings.class);
LoadCustomStrings(PowerStrings.class);
LoadCustomStrings(UIStrings.class);
LoadCustomStrings(EventStrings.class);
LoadCustomStrings(PotionStrings.class);
LoadCustomStrings(MonsterStrings.class);
LoadCustomStrings(BlightStrings.class);
LoadCustomStrings(RunModStrings.class);
LoadCustomStrings(StanceStrings.class);
EYBFontHelper.Initialize();
}
protected void InitializeCards()
{
PCLJUtils.LogInfo(this, "InitializeCards();");
PGR.Tooltips = new CardTooltips();
Strings.Initialize();
CardSeries.InitializeStrings();
LoadCustomCards();
PCLCardData.PostInitialize();
}
protected void InitializeRelics()
{
PCLJUtils.LogInfo(this, "InitializeRelics();");
LoadCustomRelics();
}
protected void InitializeKeywords()
{
PCLJUtils.LogInfo(this, "InitializeKeywords();");
LoadKeywords();
for (PCLAffinity affinity : PCLAffinity.Extended()) {
AddAffinityTooltip(affinity);
}
// AddEnergyTooltip("[R]", AbstractCard.orb_red);
// AddEnergyTooltip("[G]", AbstractCard.orb_green);
// AddEnergyTooltip("[L]", AbstractCard.orb_blue);
// AddEnergyTooltip("[P]", AbstractCard.orb_purple);
AddEnergyTooltip("[E]", null); // TODO: generalize this
for (Field field : GameDictionary.class.getDeclaredFields())
{
if (field.getType() == Keyword.class)
{
try
{
final Keyword k = (Keyword) field.get(null);
final PCLCardTooltip tooltip = new PCLCardTooltip(PCLJUtils.Capitalize(k.NAMES[0]), k.DESCRIPTION);
CardTooltips.RegisterID(PCLJUtils.Capitalize(field.getName()), tooltip);
for (String name : k.NAMES)
{
CardTooltips.RegisterName(name, tooltip);
}
}
catch (IllegalAccessException ex)
{
ex.printStackTrace();
}
}
}
}
protected void InitializePowers()
{
BaseMod.addPower(GenericFadingPower.class, GenericFadingPower.POWER_ID);
// LoadCustomPowers();
}
protected void InitializePotions()
{
PCLJUtils.LogInfo(this, "InitializePotions();");
LoadCustomPotions();
}
protected void InitializeRewards()
{
MissingPieceReward.Serializer synergySerializer = new MissingPieceReward.Serializer();
BaseMod.registerCustomReward(Enums.Rewards.SERIES_CARDS, synergySerializer, synergySerializer);
SpecialGoldReward.Serializer goldSerializer = new SpecialGoldReward.Serializer();
BaseMod.registerCustomReward(Enums.Rewards.SPECIAL_GOLD, goldSerializer, goldSerializer);
ConcertsFinalHourReward.Serializer concertSerializer = new ConcertsFinalHourReward.Serializer();
BaseMod.registerCustomReward(Enums.Rewards.BOSS_SERIES_CARDS, concertSerializer, concertSerializer);
}
protected void PostInitialize()
{
AttackEffects.Initialize();
CommandsManager.RegisterCommands();
PGR.Tooltips.InitializeIcons();
PGR.UI.Initialize();
Config.Load(CardCrawlGame.saveSlot);
Config.InitializeOptions();
BaseEffect.Initialize();
PCLCustomCardSlot.Initialize();
BaseMod.addTopPanelItem(new CardPoolPanelItem());
}
private static void AddEnergyTooltip(String symbol, TextureAtlas.AtlasRegion region)
{
if (region == null)
{
Texture texture = PGR.GetTexture(PGR.PCL.Images.ORB_C_PNG);
region = new TextureAtlas.AtlasRegion(texture, 0, 0, texture.getWidth(), texture.getHeight());
//region = new TextureAtlas.AtlasRegion(texture, 2, 2, texture.getWidth()-4, texture.getHeight()-4);
}
PCLCardTooltip tooltip = new PCLCardTooltip(TipHelper.TEXT[0], GameDictionary.TEXT[0]);
tooltip.icon = region;
CardTooltips.RegisterName(symbol, tooltip);
}
private static void AddAffinityTooltip(PCLAffinity affinity)
{
String symbol = affinity.GetFormattedPowerSymbol();
String id = affinity.PowerName;
AbstractPCLAffinityPower power = affinity.GetPower();
if (power == null || power.img == null)
{
PCLJUtils.LogError(CommonResources.class, "Could not find image: Symbol: {0}, ID: {1}",
symbol, id);
return;
}
int size = power.img.getWidth(); // width should always be equal to height
PCLCardTooltip tooltip = CardTooltips.FindByID(id);
if (tooltip == null)
{
PCLJUtils.LogError(CommonResources.class, "Could not find tooltip: Symbol: {0}, ID: {1}, Power: {2} ",
symbol, id, power.name);
return;
}
tooltip.icon = new TextureAtlas.AtlasRegion(power.img, 3, 5, size-6, size-6);
//tooltip.icon = new TextureAtlas.AtlasRegion(power.img, 2, 4, size-4, size-4);
PCLCardTooltip stance = CardTooltips.FindByID(affinity.GetStanceTooltipID());
if (stance != null)
{
stance.icon = tooltip.icon;
}
PCLCardTooltip scaling = CardTooltips.FindByID(affinity.GetScalingTooltipID());
if (scaling != null)
{
scaling.icon = tooltip.icon;
}
CardTooltips.RegisterName(symbol, tooltip);
}
public String CreateID(String suffix)
{
return CreateID(ID, suffix);
}
public void InitializeInternal() { }
protected void InitializeMonsters() { }
protected void InitializeTextures() { }
} | 34.016949 | 119 | 0.665919 |
6cd4e86898f76d9162c6a8b70e215670860f7ce1 | 221 | package com.service.demo.dao;
import dao.entity.Dept;
import java.util.List;
/**
* @author Crysmart
* @date 2020/8/17 17:06
*/
public interface DeptMapper {
List<Dept> getList();
Dept findOne(Integer id);
}
| 14.733333 | 29 | 0.678733 |
816702287d06896da6c9cb29af59399db05bd2d8 | 2,434 | /*
* Copyright (C) 2014, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The Java Pathfinder core (jpf-core) platform is 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 gov.nasa.jpf.vm.choice;
import gov.nasa.jpf.vm.ChoiceGeneratorBase;
import gov.nasa.jpf.vm.LongChoiceGenerator;
/**
*
*/
public class RandomOrderLongCG extends ChoiceGeneratorBase<Long> implements LongChoiceGenerator {
protected long[] choices;
protected int nextIdx;
public RandomOrderLongCG (LongChoiceGenerator sub) {
super(sub.getId());
setPreviousChoiceGenerator(sub.getPreviousChoiceGenerator());
choices = new long[sub.getTotalNumberOfChoices()];
for (int i = 0; i < choices.length; i++) {
sub.advance();
choices[i] = sub.getNextChoice();
}
for (int i = choices.length - 1; i > 0; i--) { // all but first
int j = random.nextInt(i + 1);
long tmp = choices[i];
choices[i] = choices[j];
choices[j] = tmp;
}
nextIdx = -1;
}
@Override
public Long getChoice (int idx){
if (idx >= 0 && idx < choices.length){
return choices[idx];
} else {
throw new IllegalArgumentException("choice index out of range: " + idx);
}
}
@Override
public Long getNextChoice() {
return choices[nextIdx];
}
@Override
public void advance() {
if (nextIdx + 1 < choices.length) nextIdx++;
}
@Override
public int getProcessedNumberOfChoices() {
return nextIdx+1;
}
@Override
public int getTotalNumberOfChoices() {
return choices.length;
}
@Override
public boolean hasMoreChoices() {
return !isDone && (nextIdx + 1 < choices.length);
}
@Override
public void reset() {
nextIdx = -1;
isDone = false;
}
@Override
public Class<Long> getChoiceType() {
return Long.class;
}
}
| 25.354167 | 97 | 0.672966 |
6697b653704e7c950b7d1e6d89bc7e2e36aa38cb | 391 | package com.housingcentre.repository;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Component;
import com.housingcentre.entities.Form5;
@Component
public interface FormsRepository5
extends CrudRepository<Form5, Integer>{
List<Form5> findByJawatan6(String jawatan6);
Form5 findById(int id);
}
| 20.578947 | 58 | 0.790281 |
084431dbe814809fb194355499e8a3ec68b42217 | 184 | package com.zsw.mybatis.config;
/**
* @author ZhangShaowei on 2019/4/24 10:48
**/
//@Configuration
//@MapperScan("com.zsw.persistemce.mapper")
public class MyBatisConfiguration {
}
| 18.4 | 43 | 0.728261 |
91c5680c47e21d89953c658556001173bca703af | 1,842 | package com.polidea.rxandroidble.internal.connection;
import android.bluetooth.BluetoothDevice;
import com.polidea.rxandroidble.exceptions.BleDisconnectedException;
import com.polidea.rxandroidble.internal.operations.DisconnectOperation;
import com.polidea.rxandroidble.internal.serialization.ClientOperationQueue;
import com.polidea.rxandroidble.internal.serialization.ConnectionOperationQueue;
import javax.inject.Inject;
import rx.Subscription;
import rx.functions.Action0;
import rx.functions.Actions;
@ConnectionScope
public class DisconnectAction implements Action0 {
private final ConnectionOperationQueue connectionOperationQueue;
private final ClientOperationQueue clientOperationQueue;
private final DisconnectOperation operationDisconnect;
private final BluetoothDevice bluetoothDevice;
@Inject
public DisconnectAction(ConnectionOperationQueue connectionOperationQueue, ClientOperationQueue clientOperationQueue,
DisconnectOperation operationDisconnect, BluetoothDevice bluetoothDevice) {
this.connectionOperationQueue = connectionOperationQueue;
this.clientOperationQueue = clientOperationQueue;
this.operationDisconnect = operationDisconnect;
this.bluetoothDevice = bluetoothDevice;
}
@Override
public void call() {
connectionOperationQueue.terminate(new BleDisconnectedException(bluetoothDevice.getAddress()));
enqueueDisconnectOperation(operationDisconnect);
}
private Subscription enqueueDisconnectOperation(DisconnectOperation operationDisconnect) {
return clientOperationQueue
.queue(operationDisconnect)
.subscribe(
Actions.empty(),
Actions.<Throwable>toAction1(Actions.empty())
);
}
}
| 38.375 | 121 | 0.763301 |
d4062d235870729c42318787123b4350697d607e | 89,575 | /*
* Copyright 2015 OpenMarket Ltd
* Copyright 2017 Vector Creations Ltd
* Copyright 2018 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package im.vector.activity;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.DownloadManager;
import android.app.PendingIntent;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Parcelable;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import org.matrix.androidsdk.MXDataHandler;
import org.matrix.androidsdk.MXSession;
import org.matrix.androidsdk.crypto.data.MXDeviceInfo;
import org.matrix.androidsdk.crypto.data.MXUsersDevicesMap;
import org.matrix.androidsdk.data.Room;
import org.matrix.androidsdk.data.RoomPreviewData;
import org.matrix.androidsdk.data.RoomSummary;
import org.matrix.androidsdk.db.MXMediasCache;
import org.matrix.androidsdk.rest.callback.ApiCallback;
import org.matrix.androidsdk.rest.callback.SimpleApiCallback;
import org.matrix.androidsdk.rest.model.MatrixError;
import org.matrix.androidsdk.rest.model.RoomMember;
import org.matrix.androidsdk.util.Log;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import im.vector.Matrix;
import im.vector.MyPresenceManager;
import im.vector.R;
import im.vector.VectorApp;
import im.vector.adapters.VectorRoomsSelectionAdapter;
import im.vector.contacts.ContactsManager;
import im.vector.contacts.PIDsRetriever;
import im.vector.fragments.VectorUnknownDevicesFragment;
import im.vector.gcm.GcmRegistrationManager;
import im.vector.services.EventStreamService;
import im.vector.util.MatrixSdkExtensionsKt;
import im.vector.util.PreferencesManager;
import im.vector.util.VectorUtils;
import me.leolin.shortcutbadger.ShortcutBadger;
/**
* Contains useful functions which are called in multiple activities.
*/
public class CommonActivityUtils {
private static final String LOG_TAG = CommonActivityUtils.class.getSimpleName();
// global helper constants:
public static final boolean UTILS_DISPLAY_PROGRESS_BAR = true;
public static final boolean UTILS_HIDE_PROGRESS_BAR = false;
// room details members:
public static final String KEY_GROUPS_EXPANDED_STATE = "KEY_GROUPS_EXPANDED_STATE";
public static final String KEY_SEARCH_PATTERN = "KEY_SEARCH_PATTERN";
public static final boolean GROUP_IS_EXPANDED = true;
public static final boolean GROUP_IS_COLLAPSED = false;
// power levels
public static final float UTILS_POWER_LEVEL_ADMIN = 100;
public static final float UTILS_POWER_LEVEL_MODERATOR = 50;
private static final int ROOM_SIZE_ONE_TO_ONE = 2;
// Android M permission request code management
private static final boolean PERMISSIONS_GRANTED = true;
private static final boolean PERMISSIONS_DENIED = !PERMISSIONS_GRANTED;
private static final int PERMISSION_BYPASSED = 0x0;
public static final int PERMISSION_CAMERA = 0x1;
private static final int PERMISSION_WRITE_EXTERNAL_STORAGE = 0x1 << 1;
private static final int PERMISSION_RECORD_AUDIO = 0x1 << 2;
private static final int PERMISSION_READ_CONTACTS = 0x1 << 3;
public static final int REQUEST_CODE_PERMISSION_AUDIO_IP_CALL = PERMISSION_RECORD_AUDIO;
public static final int REQUEST_CODE_PERMISSION_VIDEO_IP_CALL = PERMISSION_CAMERA | PERMISSION_RECORD_AUDIO;
public static final int REQUEST_CODE_PERMISSION_TAKE_PHOTO = PERMISSION_CAMERA | PERMISSION_WRITE_EXTERNAL_STORAGE;
public static final int REQUEST_CODE_PERMISSION_MEMBERS_SEARCH = PERMISSION_READ_CONTACTS;
public static final int REQUEST_CODE_PERMISSION_MEMBER_DETAILS = PERMISSION_READ_CONTACTS;
public static final int REQUEST_CODE_PERMISSION_ROOM_DETAILS = PERMISSION_CAMERA;
public static final int REQUEST_CODE_PERMISSION_VIDEO_RECORDING = PERMISSION_CAMERA | PERMISSION_RECORD_AUDIO;
public static final int REQUEST_CODE_PERMISSION_HOME_ACTIVITY = PERMISSION_WRITE_EXTERNAL_STORAGE;
private static final int REQUEST_CODE_PERMISSION_BY_PASS = PERMISSION_BYPASSED;
/**
* Logout a sessions list
*
* @param context the context
* @param sessions the sessions list
* @param clearCredentials true to clear the credentials
* @param callback the asynchronous callback
*/
public static void logout(Context context, List<MXSession> sessions, boolean clearCredentials, final SimpleApiCallback<Void> callback) {
logout(context, sessions.iterator(), clearCredentials, callback);
}
/**
* Internal method to logout a sessions list
*
* @param context the context
* @param sessions the sessions iterator
* @param clearCredentials true to clear the credentials
* @param callback the asynchronous callback
*/
private static void logout(final Context context,
final Iterator<MXSession> sessions,
final boolean clearCredentials,
final SimpleApiCallback<Void> callback) {
if (!sessions.hasNext()) {
if (null != callback) {
callback.onSuccess(null);
}
return;
}
MXSession session = sessions.next();
if (session.isAlive()) {
// stop the service
EventStreamService eventStreamService = EventStreamService.getInstance();
// reported by a rageshake
if (null != eventStreamService) {
List<String> matrixIds = new ArrayList<>();
matrixIds.add(session.getMyUserId());
eventStreamService.stopAccounts(matrixIds);
}
// Publish to the server that we're now offline
MyPresenceManager.getInstance(context, session).advertiseOffline();
MyPresenceManager.remove(session);
// clear notification
EventStreamService.removeNotification();
// unregister from the GCM.
Matrix.getInstance(context).getSharedGCMRegistrationManager().unregister(session, null);
// clear credentials
Matrix.getInstance(context).clearSession(context, session, clearCredentials, new SimpleApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
logout(context, sessions, clearCredentials, callback);
}
});
}
}
public static boolean shouldRestartApp(Context context) {
EventStreamService eventStreamService = EventStreamService.getInstance();
if (!Matrix.hasValidSessions()) {
Log.e(LOG_TAG, "shouldRestartApp : the client has no valid session");
}
if (null == eventStreamService) {
Log.e(LOG_TAG, "eventStreamService is null : restart the event stream");
CommonActivityUtils.startEventStreamService(context);
}
return !Matrix.hasValidSessions();
}
/**
* With android M, the permissions kills the backgrounded application
* and try to restart the last opened activity.
* But, the sessions are not initialised (i.e the stores are not ready and so on).
* Thus, the activity could have an invalid behaviour.
* It seems safer to go to splash screen and to wait for the end of the initialisation.
*
* @param activity the caller activity
* @return true if go to splash screen
*/
public static boolean isGoingToSplash(Activity activity) {
return isGoingToSplash(activity, null, null);
}
/**
* With android M, the permissions kills the backgrounded application
* and try to restart the last opened activity.
* But, the sessions are not initialised (i.e the stores are not ready and so on).
* Thus, the activity could have an invalid behaviour.
* It seems safer to go to splash screen and to wait for the end of the initialisation.
*
* @param activity the caller activity
* @param sessionId the session id
* @param roomId the room id
* @return true if go to splash screen
*/
public static boolean isGoingToSplash(Activity activity, String sessionId, String roomId) {
if (Matrix.hasValidSessions()) {
List<MXSession> sessions = Matrix.getInstance(activity).getSessions();
for (MXSession session : sessions) {
if (session.isAlive() && !session.getDataHandler().getStore().isReady()) {
Intent intent = new Intent(activity, SplashActivity.class);
if ((null != sessionId) && (null != roomId)) {
intent.putExtra(SplashActivity.EXTRA_MATRIX_ID, sessionId);
intent.putExtra(SplashActivity.EXTRA_ROOM_ID, roomId);
}
activity.startActivity(intent);
activity.finish();
return true;
}
}
}
return false;
}
private static final String RESTART_IN_PROGRESS_KEY = "RESTART_IN_PROGRESS_KEY";
/**
* The application has been started
*/
public static void onApplicationStarted(Activity activity) {
PreferenceManager.getDefaultSharedPreferences(activity)
.edit()
.putBoolean(RESTART_IN_PROGRESS_KEY, false)
.apply();
}
/**
* Restart the application after 100ms
*
* @param activity activity
*/
public static void restartApp(Activity activity) {
// clear the preferences
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity);
// use the preference to avoid infinite relaunch on some devices
// the culprit activity is restarted when System.exit is called.
// so called it once to fix it
if (!preferences.getBoolean(RESTART_IN_PROGRESS_KEY, false)) {
Toast.makeText(activity, "Restart the application (low memory)", Toast.LENGTH_SHORT).show();
Log.e(LOG_TAG, "Kill the application");
preferences
.edit()
.putBoolean(RESTART_IN_PROGRESS_KEY, true)
.apply();
PendingIntent mPendingIntent =
PendingIntent.getActivity(activity, 314159, new Intent(activity, LoginActivity.class), PendingIntent.FLAG_CANCEL_CURRENT);
// so restart the application after 100ms
AlarmManager mgr = (AlarmManager) activity.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 50, mPendingIntent);
System.exit(0);
} else {
Log.e(LOG_TAG, "The application is restarting, please wait !!");
activity.finish();
}
}
/**
* Logout the current user.
* Jump to the login page when the logout is done.
*
* @param activity the caller activity
*/
public static void logout(Activity activity) {
logout(activity, true);
}
/**
* Logout the current user.
*
* @param activity the caller activity
* @param goToLoginPage true to jump to the login page
*/
public static void logout(final Activity activity, final boolean goToLoginPage) {
Log.d(LOG_TAG, "## logout() : from " + activity + " goToLoginPage " + goToLoginPage);
// if no activity is provided, use the application context instead.
final Context context = (null == activity) ? VectorApp.getInstance().getApplicationContext() : activity;
EventStreamService.removeNotification();
stopEventStream(context);
try {
ShortcutBadger.setBadge(context, 0);
} catch (Exception e) {
Log.d(LOG_TAG, "## logout(): Exception Msg=" + e.getMessage());
}
// warn that the user logs out
Collection<MXSession> sessions = Matrix.getMXSessions(context);
for (MXSession session : sessions) {
// Publish to the server that we're now offline
MyPresenceManager.getInstance(context, session).advertiseOffline();
MyPresenceManager.remove(session);
}
// clear the preferences
PreferencesManager.clearPreferences(context);
// reset the GCM
Matrix.getInstance(context).getSharedGCMRegistrationManager().resetGCMRegistration();
// clear the preferences when the application goes to the login screen.
if (goToLoginPage) {
// display a dummy activity until the logout is done
Matrix.getInstance(context).getSharedGCMRegistrationManager().clearPreferences();
if (null != activity) {
// go to login page
activity.startActivity(new Intent(activity, LoggingOutActivity.class));
activity.finish();
} else {
Intent intent = new Intent(context, LoggingOutActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
context.startActivity(intent);
}
}
// clear credentials
Matrix.getInstance(context).clearSessions(context, true, new SimpleApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
// ensure that corrupted values are cleared
Matrix.getInstance(context).getLoginStorage().clear();
// clear the tmp store list
Matrix.getInstance(context).clearTmpStoresList();
// reset the contacts
PIDsRetriever.getInstance().reset();
ContactsManager.getInstance().reset();
MXMediasCache.clearThumbnailsCache(context);
if (goToLoginPage) {
Activity activeActivity = VectorApp.getCurrentActivity();
if (null != activeActivity) {
// go to login page
activeActivity.startActivity(new Intent(activeActivity, LoginActivity.class));
activeActivity.finish();
} else {
Intent intent = new Intent(context, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
context.startActivity(intent);
}
}
}
});
}
/**
* Clear all local data after a user account deactivation
*
* @param context the application context
* @param mxSession the session to deactivate
* @param userPassword the user password
* @param eraseUserData true to also erase all the user data
* @param callback the callback success and failure callback
*/
public static void deactivateAccount(final Context context,
final MXSession mxSession,
final String userPassword,
final boolean eraseUserData,
final @NonNull ApiCallback<Void> callback) {
Matrix.getInstance(context).deactivateSession(context, mxSession, userPassword, eraseUserData, new SimpleApiCallback<Void>(callback) {
@Override
public void onSuccess(Void info) {
EventStreamService.removeNotification();
stopEventStream(context);
try {
ShortcutBadger.setBadge(context, 0);
} catch (Exception e) {
Log.d(LOG_TAG, "## logout(): Exception Msg=" + e.getMessage());
}
// Publish to the server that we're now offline
MyPresenceManager.getInstance(context, mxSession).advertiseOffline();
MyPresenceManager.remove(mxSession);
// clear the preferences
PreferencesManager.clearPreferences(context);
// reset the GCM
Matrix.getInstance(context).getSharedGCMRegistrationManager().resetGCMRegistration();
// clear the preferences
Matrix.getInstance(context).getSharedGCMRegistrationManager().clearPreferences();
// Clear the credentials
Matrix.getInstance(context).getLoginStorage().clear();
// clear the tmp store list
Matrix.getInstance(context).clearTmpStoresList();
// reset the contacts
PIDsRetriever.getInstance().reset();
ContactsManager.getInstance().reset();
MXMediasCache.clearThumbnailsCache(context);
callback.onSuccess(info);
}
});
}
/**
* Start LoginActivity in a new task, and clear any other existing task
*
* @param activity the current Activity
*/
public static void startLoginActivityNewTask(Activity activity) {
Intent intent = new Intent(activity, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
activity.startActivity(intent);
}
//==============================================================================================================
// Events stream service
//==============================================================================================================
/**
* Indicate if a user is logged out or not. If no default session is enabled,
* no user is logged.
*
* @param aContext App context
* @return true if no user is logged in, false otherwise
*/
private static boolean isUserLogout(Context aContext) {
boolean retCode = false;
if (null == aContext) {
retCode = true;
} else {
if (null == Matrix.getInstance(aContext.getApplicationContext()).getDefaultSession()) {
retCode = true;
}
}
return retCode;
}
/**
* Send an action to the events service.
*
* @param context the context.
* @param action the action to send.
*/
private static void sendEventStreamAction(Context context, EventStreamService.StreamAction action) {
Context appContext = context.getApplicationContext();
if (!isUserLogout(appContext)) {
Intent eventStreamService = new Intent(appContext, EventStreamService.class);
if ((action == EventStreamService.StreamAction.CATCHUP) && (EventStreamService.isStopped())) {
Log.d(LOG_TAG, "sendEventStreamAction : auto restart");
eventStreamService.putExtra(EventStreamService.EXTRA_AUTO_RESTART_ACTION, EventStreamService.EXTRA_AUTO_RESTART_ACTION);
} else {
Log.d(LOG_TAG, "sendEventStreamAction " + action);
eventStreamService.putExtra(EventStreamService.EXTRA_STREAM_ACTION, action.ordinal());
}
appContext.startService(eventStreamService);
} else {
Log.d(LOG_TAG, "## sendEventStreamAction(): \"" + action + "\" action not sent - user logged out");
}
}
/**
* Stop the event stream.
*
* @param context the context.
*/
private static void stopEventStream(Context context) {
Log.d(LOG_TAG, "stopEventStream");
sendEventStreamAction(context, EventStreamService.StreamAction.STOP);
}
/**
* Pause the event stream.
*
* @param context the context.
*/
public static void pauseEventStream(Context context) {
Log.d(LOG_TAG, "pauseEventStream");
sendEventStreamAction(context, EventStreamService.StreamAction.PAUSE);
}
/**
* Resume the events stream
*
* @param context the context.
*/
public static void resumeEventStream(Context context) {
Log.d(LOG_TAG, "resumeEventStream");
sendEventStreamAction(context, EventStreamService.StreamAction.RESUME);
}
/**
* Trigger a event stream catchup i.e. there is only sync/ call.
*
* @param context the context.
*/
public static void catchupEventStream(Context context) {
if (VectorApp.isAppInBackground()) {
Log.d(LOG_TAG, "catchupEventStream");
sendEventStreamAction(context, EventStreamService.StreamAction.CATCHUP);
}
}
/**
* Warn the events stream that there was a GCM status update.
*
* @param context the context.
*/
public static void onGcmUpdate(Context context) {
Log.d(LOG_TAG, "onGcmUpdate");
sendEventStreamAction(context, EventStreamService.StreamAction.GCM_STATUS_UPDATE);
}
/**
* Start the events stream service.
*
* @param context the context.
*/
public static void startEventStreamService(Context context) {
// the events stream service is launched
// either the application has never be launched
// or the service has been killed on low memory
if (EventStreamService.isStopped()) {
List<String> matrixIds = new ArrayList<>();
Collection<MXSession> sessions = Matrix.getInstance(context.getApplicationContext()).getSessions();
if ((null != sessions) && (sessions.size() > 0)) {
GcmRegistrationManager gcmRegistrationManager = Matrix.getInstance(context).getSharedGCMRegistrationManager();
Log.e(LOG_TAG, "## startEventStreamService() : restart EventStreamService");
for (MXSession session : sessions) {
// reported by GA
if ((null != session.getDataHandler()) && (null != session.getDataHandler().getStore())) {
boolean isSessionReady = session.getDataHandler().getStore().isReady();
if (!isSessionReady) {
Log.e(LOG_TAG, "## startEventStreamService() : the session " + session.getMyUserId() + " is not opened");
session.getDataHandler().getStore().open();
} else {
// it seems that the crypto is not always restarted properly after a crash
Log.e(LOG_TAG, "## startEventStreamService() : check if the crypto of the session " + session.getMyUserId());
session.checkCrypto();
}
session.setSyncDelay(gcmRegistrationManager.isBackgroundSyncAllowed() ? gcmRegistrationManager.getBackgroundSyncDelay() : 0);
session.setSyncTimeout(gcmRegistrationManager.getBackgroundSyncTimeOut());
// session to activate
matrixIds.add(session.getCredentials().userId);
}
}
// check size
if (matrixIds.size() > 0) {
Intent intent = new Intent(context, EventStreamService.class);
intent.putExtra(EventStreamService.EXTRA_MATRIX_IDS, matrixIds.toArray(new String[matrixIds.size()]));
intent.putExtra(EventStreamService.EXTRA_STREAM_ACTION, EventStreamService.StreamAction.START.ordinal());
context.startService(intent);
}
}
if (null != EventStreamService.getInstance()) {
EventStreamService.getInstance().refreshForegroundNotification();
}
}
}
/**
* Check if the permissions provided in the list are granted.
* This is an asynchronous method if permissions are requested, the final response
* is provided in onRequestPermissionsResult(). In this case checkPermissions()
* returns false.
* <br>If checkPermissions() returns true, the permissions were already granted.
* The permissions to be granted are given as bit map in aPermissionsToBeGrantedBitMap (ex: {@link #REQUEST_CODE_PERMISSION_TAKE_PHOTO}).
* <br>aPermissionsToBeGrantedBitMap is passed as the request code in onRequestPermissionsResult().
* <p>
* If a permission was already denied by the user, a popup is displayed to
* explain why vector needs the corresponding permission.
*
* @param aPermissionsToBeGrantedBitMap the permissions bit map to be granted
* @param aCallingActivity the calling Activity that is requesting the permissions (or fragment parent)
* @param fragment the calling fragment that is requesting the permissions
* @return true if the permissions are granted (synchronous flow), false otherwise (asynchronous flow)
*/
private static boolean checkPermissions(final int aPermissionsToBeGrantedBitMap, final Activity aCallingActivity, final Fragment fragment) {
boolean isPermissionGranted = false;
// sanity check
if (null == aCallingActivity) {
Log.w(LOG_TAG, "## checkPermissions(): invalid input data");
isPermissionGranted = false;
} else if (REQUEST_CODE_PERMISSION_BY_PASS == aPermissionsToBeGrantedBitMap) {
isPermissionGranted = true;
} else if ((REQUEST_CODE_PERMISSION_TAKE_PHOTO != aPermissionsToBeGrantedBitMap)
&& (REQUEST_CODE_PERMISSION_AUDIO_IP_CALL != aPermissionsToBeGrantedBitMap)
&& (REQUEST_CODE_PERMISSION_VIDEO_IP_CALL != aPermissionsToBeGrantedBitMap)
&& (REQUEST_CODE_PERMISSION_MEMBERS_SEARCH != aPermissionsToBeGrantedBitMap)
&& (REQUEST_CODE_PERMISSION_HOME_ACTIVITY != aPermissionsToBeGrantedBitMap)
&& (REQUEST_CODE_PERMISSION_MEMBER_DETAILS != aPermissionsToBeGrantedBitMap)
&& (REQUEST_CODE_PERMISSION_ROOM_DETAILS != aPermissionsToBeGrantedBitMap)
) {
Log.w(LOG_TAG, "## checkPermissions(): permissions to be granted are not supported");
isPermissionGranted = false;
} else {
List<String> permissionListAlreadyDenied = new ArrayList<>();
List<String> permissionsListToBeGranted = new ArrayList<>();
final List<String> finalPermissionsListToBeGranted;
boolean isRequestPermissionRequired = false;
String explanationMessage = "";
String permissionType;
// retrieve the permissions to be granted according to the request code bit map
if (PERMISSION_CAMERA == (aPermissionsToBeGrantedBitMap & PERMISSION_CAMERA)) {
permissionType = Manifest.permission.CAMERA;
isRequestPermissionRequired
|= updatePermissionsToBeGranted(aCallingActivity, permissionListAlreadyDenied, permissionsListToBeGranted, permissionType);
}
if (PERMISSION_RECORD_AUDIO == (aPermissionsToBeGrantedBitMap & PERMISSION_RECORD_AUDIO)) {
permissionType = Manifest.permission.RECORD_AUDIO;
isRequestPermissionRequired
|= updatePermissionsToBeGranted(aCallingActivity, permissionListAlreadyDenied, permissionsListToBeGranted, permissionType);
}
if (PERMISSION_WRITE_EXTERNAL_STORAGE == (aPermissionsToBeGrantedBitMap & PERMISSION_WRITE_EXTERNAL_STORAGE)) {
permissionType = Manifest.permission.WRITE_EXTERNAL_STORAGE;
isRequestPermissionRequired
|= updatePermissionsToBeGranted(aCallingActivity, permissionListAlreadyDenied, permissionsListToBeGranted, permissionType);
}
// the contact book access is requested for any android platforms
// for android M, we use the system preferences
// for android < M, we use a dedicated settings
if (PERMISSION_READ_CONTACTS == (aPermissionsToBeGrantedBitMap & PERMISSION_READ_CONTACTS)) {
permissionType = Manifest.permission.READ_CONTACTS;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
isRequestPermissionRequired
|= updatePermissionsToBeGranted(aCallingActivity, permissionListAlreadyDenied, permissionsListToBeGranted, permissionType);
} else {
if (!ContactsManager.getInstance().isContactBookAccessRequested()) {
isRequestPermissionRequired = true;
permissionsListToBeGranted.add(permissionType);
}
}
}
finalPermissionsListToBeGranted = permissionsListToBeGranted;
// if some permissions were already denied: display a dialog to the user before asking again..
if (!permissionListAlreadyDenied.isEmpty()) {
if (aPermissionsToBeGrantedBitMap == REQUEST_CODE_PERMISSION_VIDEO_IP_CALL
|| aPermissionsToBeGrantedBitMap == REQUEST_CODE_PERMISSION_AUDIO_IP_CALL) {
// Permission request for VOIP call
if (permissionListAlreadyDenied.contains(Manifest.permission.CAMERA)
&& permissionListAlreadyDenied.contains(Manifest.permission.RECORD_AUDIO)) {
// Both missing
explanationMessage += aCallingActivity.getString(R.string.permissions_rationale_msg_camera_and_audio);
} else if (permissionListAlreadyDenied.contains(Manifest.permission.RECORD_AUDIO)) {
// Audio missing
explanationMessage += aCallingActivity.getString(R.string.permissions_rationale_msg_record_audio);
explanationMessage += aCallingActivity.getString(R.string.permissions_rationale_msg_record_audio_explanation);
} else if (permissionListAlreadyDenied.contains(Manifest.permission.CAMERA)) {
// Camera missing
explanationMessage += aCallingActivity.getString(R.string.permissions_rationale_msg_camera);
explanationMessage += aCallingActivity.getString(R.string.permissions_rationale_msg_camera_explanation);
}
} else {
for (String permissionAlreadyDenied : permissionListAlreadyDenied) {
if (Manifest.permission.CAMERA.equals(permissionAlreadyDenied)) {
if (!TextUtils.isEmpty(explanationMessage)) {
explanationMessage += "\n\n";
}
explanationMessage += aCallingActivity.getString(R.string.permissions_rationale_msg_camera);
} else if (Manifest.permission.RECORD_AUDIO.equals(permissionAlreadyDenied)) {
if (!TextUtils.isEmpty(explanationMessage)) {
explanationMessage += "\n\n";
}
explanationMessage += aCallingActivity.getString(R.string.permissions_rationale_msg_record_audio);
} else if (Manifest.permission.WRITE_EXTERNAL_STORAGE.equals(permissionAlreadyDenied)) {
if (!TextUtils.isEmpty(explanationMessage)) {
explanationMessage += "\n\n";
}
explanationMessage += aCallingActivity.getString(R.string.permissions_rationale_msg_storage);
} else if (Manifest.permission.READ_CONTACTS.equals(permissionAlreadyDenied)) {
if (!TextUtils.isEmpty(explanationMessage)) {
explanationMessage += "\n\n";
}
explanationMessage += aCallingActivity.getString(R.string.permissions_rationale_msg_contacts);
} else {
Log.d(LOG_TAG, "## checkPermissions(): already denied permission not supported");
}
}
}
// display the dialog with the info text
new AlertDialog.Builder(aCallingActivity)
.setTitle(R.string.permissions_rationale_popup_title)
.setMessage(explanationMessage)
.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
Toast.makeText(aCallingActivity, R.string.missing_permissions_warning, Toast.LENGTH_SHORT).show();
}
})
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (!finalPermissionsListToBeGranted.isEmpty()) {
if (fragment != null) {
fragment.requestPermissions(finalPermissionsListToBeGranted.toArray(new String[finalPermissionsListToBeGranted.size()]),
aPermissionsToBeGrantedBitMap);
} else {
ActivityCompat.requestPermissions(aCallingActivity,
finalPermissionsListToBeGranted.toArray(new String[finalPermissionsListToBeGranted.size()]),
aPermissionsToBeGrantedBitMap);
}
}
}
})
.show();
} else {
// some permissions are not granted, ask permissions
if (isRequestPermissionRequired) {
final String[] fPermissionsArrayToBeGranted = finalPermissionsListToBeGranted.toArray(new String[finalPermissionsListToBeGranted.size()]);
// for android < M, we use a custom dialog to request the contacts book access.
if (permissionsListToBeGranted.contains(Manifest.permission.READ_CONTACTS) && (Build.VERSION.SDK_INT < 23)) {
new AlertDialog.Builder(aCallingActivity)
.setIcon(android.R.drawable.ic_dialog_info)
.setTitle(R.string.permissions_rationale_popup_title)
.setMessage(R.string.permissions_msg_contacts_warning_other_androids)
// gives the contacts book access
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ContactsManager.getInstance().setIsContactBookAccessAllowed(true);
if (fragment != null) {
fragment.requestPermissions(fPermissionsArrayToBeGranted, aPermissionsToBeGrantedBitMap);
} else {
ActivityCompat.requestPermissions(aCallingActivity, fPermissionsArrayToBeGranted, aPermissionsToBeGrantedBitMap);
}
}
})
// or reject it
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ContactsManager.getInstance().setIsContactBookAccessAllowed(false);
if (fragment != null) {
fragment.requestPermissions(fPermissionsArrayToBeGranted, aPermissionsToBeGrantedBitMap);
} else {
ActivityCompat.requestPermissions(aCallingActivity, fPermissionsArrayToBeGranted, aPermissionsToBeGrantedBitMap);
}
}
})
.show();
} else {
if (fragment != null) {
fragment.requestPermissions(fPermissionsArrayToBeGranted, aPermissionsToBeGrantedBitMap);
} else {
ActivityCompat.requestPermissions(aCallingActivity, fPermissionsArrayToBeGranted, aPermissionsToBeGrantedBitMap);
}
}
} else {
// permissions were granted, start now..
isPermissionGranted = true;
}
}
}
return isPermissionGranted;
}
/**
* See {@link #checkPermissions(int, Activity, Fragment)}
*
* @param aPermissionsToBeGrantedBitMap
* @param aCallingActivity
* @return true if the permissions are granted (synchronous flow), false otherwise (asynchronous flow)
*/
public static boolean checkPermissions(final int aPermissionsToBeGrantedBitMap, final Activity aCallingActivity) {
return checkPermissions(aPermissionsToBeGrantedBitMap, aCallingActivity, null);
}
/**
* See {@link #checkPermissions(int, Activity, Fragment)}
*
* @param aPermissionsToBeGrantedBitMap
* @param fragment
*/
public static void checkPermissions(final int aPermissionsToBeGrantedBitMap, final Fragment fragment) {
checkPermissions(aPermissionsToBeGrantedBitMap, fragment.getActivity(), fragment);
}
/**
* Helper method used in {@link #checkPermissions(int, Activity)} to populate the list of the
* permissions to be granted (aPermissionsListToBeGranted_out) and the list of the permissions already denied (aPermissionAlreadyDeniedList_out).
*
* @param aCallingActivity calling activity
* @param aPermissionAlreadyDeniedList_out list to be updated with the permissions already denied by the user
* @param aPermissionsListToBeGranted_out list to be updated with the permissions to be granted
* @param permissionType the permission to be checked
* @return true if the permission requires to be granted, false otherwise
*/
private static boolean updatePermissionsToBeGranted(final Activity aCallingActivity,
List<String> aPermissionAlreadyDeniedList_out,
List<String> aPermissionsListToBeGranted_out,
final String permissionType) {
boolean isRequestPermissionRequested = false;
// add permission to be granted
aPermissionsListToBeGranted_out.add(permissionType);
if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(aCallingActivity.getApplicationContext(), permissionType)) {
isRequestPermissionRequested = true;
// add permission to the ones that were already asked to the user
if (ActivityCompat.shouldShowRequestPermissionRationale(aCallingActivity, permissionType)) {
aPermissionAlreadyDeniedList_out.add(permissionType);
}
}
return isRequestPermissionRequested;
}
/**
* Helper method to process {@link CommonActivityUtils#REQUEST_CODE_PERMISSION_AUDIO_IP_CALL}
* on onRequestPermissionsResult() methods.
*
* @param aContext App context
* @param aPermissions permissions list
* @param aGrantResults permissions granted results
* @return true if audio IP call is permitted, false otherwise
*/
public static boolean onPermissionResultAudioIpCall(Context aContext, String[] aPermissions, int[] aGrantResults) {
boolean isPermissionGranted = false;
try {
if (Manifest.permission.RECORD_AUDIO.equals(aPermissions[0])) {
if (PackageManager.PERMISSION_GRANTED == aGrantResults[0]) {
Log.d(LOG_TAG, "## onPermissionResultAudioIpCall(): RECORD_AUDIO permission granted");
isPermissionGranted = true;
} else {
Log.d(LOG_TAG, "## onPermissionResultAudioIpCall(): RECORD_AUDIO permission not granted");
if (null != aContext)
Toast.makeText(aContext, R.string.permissions_action_not_performed_missing_permissions, Toast.LENGTH_SHORT).show();
}
}
} catch (Exception ex) {
Log.d(LOG_TAG, "## onPermissionResultAudioIpCall(): Exception MSg=" + ex.getMessage());
}
return isPermissionGranted;
}
/**
* Helper method to process {@link CommonActivityUtils#REQUEST_CODE_PERMISSION_VIDEO_IP_CALL}
* on onRequestPermissionsResult() methods.
* For video IP calls, record audio and camera permissions are both mandatory.
*
* @param aContext App context
* @param aPermissions permissions list
* @param aGrantResults permissions granted results
* @return true if video IP call is permitted, false otherwise
*/
public static boolean onPermissionResultVideoIpCall(Context aContext, String[] aPermissions, int[] aGrantResults) {
boolean isPermissionGranted = false;
int result = 0;
try {
for (int i = 0; i < aPermissions.length; i++) {
Log.d(LOG_TAG, "## onPermissionResultVideoIpCall(): " + aPermissions[i] + "=" + aGrantResults[i]);
if (Manifest.permission.CAMERA.equals(aPermissions[i])) {
if (PackageManager.PERMISSION_GRANTED == aGrantResults[i]) {
Log.d(LOG_TAG, "## onPermissionResultVideoIpCall(): CAMERA permission granted");
result++;
} else {
Log.w(LOG_TAG, "## onPermissionResultVideoIpCall(): CAMERA permission not granted");
}
}
if (Manifest.permission.RECORD_AUDIO.equals(aPermissions[i])) {
if (PackageManager.PERMISSION_GRANTED == aGrantResults[i]) {
Log.d(LOG_TAG, "## onPermissionResultVideoIpCall(): WRITE_EXTERNAL_STORAGE permission granted");
result++;
} else {
Log.w(LOG_TAG, "## onPermissionResultVideoIpCall(): RECORD_AUDIO permission not granted");
}
}
}
// Video over IP requires, both Audio & Video !
if (2 == result) {
isPermissionGranted = true;
} else {
Log.w(LOG_TAG, "## onPermissionResultVideoIpCall(): No permissions granted to IP call (video or audio)");
if (null != aContext)
Toast.makeText(aContext, R.string.permissions_action_not_performed_missing_permissions, Toast.LENGTH_SHORT).show();
}
} catch (Exception ex) {
Log.d(LOG_TAG, "## onPermissionResultVideoIpCall(): Exception MSg=" + ex.getMessage());
}
return isPermissionGranted;
}
//==============================================================================================================
// Room preview methods.
//==============================================================================================================
/**
* Start a room activity in preview mode.
*
* @param fromActivity the caller activity.
* @param roomPreviewData the room preview information
*/
public static void previewRoom(final Activity fromActivity, RoomPreviewData roomPreviewData) {
if ((null != fromActivity) && (null != roomPreviewData)) {
VectorRoomActivity.sRoomPreviewData = roomPreviewData;
Intent intent = new Intent(fromActivity, VectorRoomActivity.class);
intent.putExtra(VectorRoomActivity.EXTRA_ROOM_ID, roomPreviewData.getRoomId());
intent.putExtra(VectorRoomActivity.EXTRA_ROOM_PREVIEW_ID, roomPreviewData.getRoomId());
intent.putExtra(VectorRoomActivity.EXTRA_EXPAND_ROOM_HEADER, true);
fromActivity.startActivity(intent);
}
}
/**
* Helper method used to build an intent to trigger a room preview.
*
* @param aMatrixId matrix ID of the user
* @param aRoomId room ID
* @param aContext application context
* @param aTargetActivity the activity set in the returned intent
* @return a valid intent if operation succeed, null otherwise
*/
public static Intent buildIntentPreviewRoom(String aMatrixId, String aRoomId, Context aContext, Class<?> aTargetActivity) {
Intent intentRetCode;
// sanity check
if ((null == aContext) || (null == aRoomId) || (null == aMatrixId)) {
intentRetCode = null;
} else {
MXSession session;
// get the session
if (null == (session = Matrix.getInstance(aContext).getSession(aMatrixId))) {
session = Matrix.getInstance(aContext).getDefaultSession();
}
// check session validity
if ((null == session) || !session.isAlive()) {
intentRetCode = null;
} else {
String roomAlias = null;
Room room = session.getDataHandler().getRoom(aRoomId);
// get the room alias (if any) for the preview data
if ((null != room) && (null != room.getLiveState())) {
roomAlias = room.getLiveState().getAlias();
}
intentRetCode = new Intent(aContext, aTargetActivity);
// extra required by VectorRoomActivity
intentRetCode.putExtra(VectorRoomActivity.EXTRA_ROOM_ID, aRoomId);
intentRetCode.putExtra(VectorRoomActivity.EXTRA_ROOM_PREVIEW_ID, aRoomId);
intentRetCode.putExtra(VectorRoomActivity.EXTRA_MATRIX_ID, aMatrixId);
intentRetCode.putExtra(VectorRoomActivity.EXTRA_EXPAND_ROOM_HEADER, true);
// extra only required by VectorFakeRoomPreviewActivity
intentRetCode.putExtra(VectorRoomActivity.EXTRA_ROOM_PREVIEW_ROOM_ALIAS, roomAlias);
}
}
return intentRetCode;
}
/**
* Start a room activity in preview mode.
* If the room is already joined, open it in edition mode.
*
* @param fromActivity the caller activity.
* @param session the session
* @param roomId the roomId
* @param roomAlias the room alias
* @param callback the operation callback
*/
public static void previewRoom(final Activity fromActivity,
final MXSession session,
final String roomId,
final String roomAlias,
final ApiCallback<Void> callback) {
previewRoom(fromActivity, session, roomId, new RoomPreviewData(session, roomId, null, roomAlias, null), callback);
}
/**
* Start a room activity in preview mode.
* If the room is already joined, open it in edition mode.
*
* @param fromActivity the caller activity.
* @param session the session
* @param roomId the roomId
* @param roomPreviewData the room preview data
* @param callback the operation callback
*/
public static void previewRoom(final Activity fromActivity,
final MXSession session,
final String roomId,
final RoomPreviewData roomPreviewData,
final ApiCallback<Void> callback) {
Room room = session.getDataHandler().getRoom(roomId, false);
// if the room exists
if (null != room) {
// either the user is invited
if (room.isInvited()) {
Log.d(LOG_TAG, "previewRoom : the user is invited -> display the preview " + VectorApp.getCurrentActivity());
previewRoom(fromActivity, roomPreviewData);
} else {
Log.d(LOG_TAG, "previewRoom : open the room");
Map<String, Object> params = new HashMap<>();
params.put(VectorRoomActivity.EXTRA_MATRIX_ID, session.getMyUserId());
params.put(VectorRoomActivity.EXTRA_ROOM_ID, roomId);
CommonActivityUtils.goToRoomPage(fromActivity, session, params);
}
if (null != callback) {
callback.onSuccess(null);
}
} else {
roomPreviewData.fetchPreviewData(new ApiCallback<Void>() {
private void onDone() {
if (null != callback) {
callback.onSuccess(null);
}
previewRoom(fromActivity, roomPreviewData);
}
@Override
public void onSuccess(Void info) {
onDone();
}
@Override
public void onNetworkError(Exception e) {
onDone();
}
@Override
public void onMatrixError(MatrixError e) {
onDone();
}
@Override
public void onUnexpectedError(Exception e) {
onDone();
}
});
}
}
//==============================================================================================================
// Room jump methods.
//==============================================================================================================
/**
* Start a room activity with the dedicated parameters.
* Pop the activity to the homeActivity before pushing the new activity.
*
* @param fromActivity the caller activity.
* @param params the room activity parameters
*/
public static void goToRoomPage(final Activity fromActivity, final Map<String, Object> params) {
goToRoomPage(fromActivity, null, params);
}
/**
* Start a room activity with the dedicated parameters.
* Pop the activity to the homeActivity before pushing the new activity.
*
* @param fromActivity the caller activity.
* @param session the session.
* @param params the room activity parameters.
*/
public static void goToRoomPage(final Activity fromActivity, final MXSession session, final Map<String, Object> params) {
final MXSession finalSession = (session == null) ? Matrix.getMXSession(fromActivity, (String) params.get(VectorRoomActivity.EXTRA_MATRIX_ID)) : session;
// sanity check
if ((null == finalSession) || !finalSession.isAlive()) {
return;
}
String roomId = (String) params.get(VectorRoomActivity.EXTRA_ROOM_ID);
Room room = finalSession.getDataHandler().getRoom(roomId);
// do not open a leaving room.
// it does not make.
if ((null != room) && (room.isLeaving())) {
return;
}
fromActivity.runOnUiThread(
new Runnable() {
@Override
public void run() {
// if the activity is not the home activity
if (!(fromActivity instanceof VectorHomeActivity)) {
// pop to the home activity
Log.d(LOG_TAG, "## goToRoomPage(): start VectorHomeActivity..");
Intent intent = new Intent(fromActivity, VectorHomeActivity.class);
intent.setFlags(android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP | android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra(VectorHomeActivity.EXTRA_JUMP_TO_ROOM_PARAMS, (Serializable) params);
fromActivity.startActivity(intent);
} else {
// already to the home activity
// so just need to open the room activity
Log.d(LOG_TAG, "## goToRoomPage(): already in VectorHomeActivity..");
Intent intent = new Intent(fromActivity, VectorRoomActivity.class);
for (String key : params.keySet()) {
Object value = params.get(key);
if (value instanceof String) {
intent.putExtra(key, (String) value);
} else if (value instanceof Boolean) {
intent.putExtra(key, (Boolean) value);
} else if (value instanceof Parcelable) {
intent.putExtra(key, (Parcelable) value);
}
}
// try to find a displayed room name
if (null == params.get(VectorRoomActivity.EXTRA_DEFAULT_NAME)) {
Room room = finalSession.getDataHandler().getRoom((String) params.get(VectorRoomActivity.EXTRA_ROOM_ID));
if ((null != room) && room.isInvited()) {
String displayName = VectorUtils.getRoomDisplayName(fromActivity, finalSession, room);
if (null != displayName) {
intent.putExtra(VectorRoomActivity.EXTRA_DEFAULT_NAME, displayName);
}
}
}
fromActivity.startActivity(intent);
}
}
}
);
}
//==============================================================================================================
// 1:1 Room methods.
//==============================================================================================================
/**
* Return all the 1:1 rooms joined by the searched user and by the current logged in user.
* This method go through all the rooms, and for each room, tests if the searched user
* and the logged in user are present.
*
* @param aSession session
* @param aSearchedUserId the searched user ID
* @return an array containing the found rooms
*/
private static List<Room> findOneToOneRoomList(final MXSession aSession, final String aSearchedUserId) {
List<Room> listRetValue = new ArrayList<>();
List<RoomMember> roomMembersList;
String userId0, userId1;
if ((null != aSession) && (null != aSearchedUserId)) {
Collection<Room> roomsList = aSession.getDataHandler().getStore().getRooms();
for (Room room : roomsList) {
roomMembersList = (List<RoomMember>) room.getJoinedMembers();
if ((null != roomMembersList) && (ROOM_SIZE_ONE_TO_ONE == roomMembersList.size())) {
userId0 = roomMembersList.get(0).getUserId();
userId1 = roomMembersList.get(1).getUserId();
// add the room where the second member is the searched one
if (userId0.equals(aSearchedUserId) || userId1.equals(aSearchedUserId)) {
listRetValue.add(room);
}
}
}
}
return listRetValue;
}
/**
* Set a room as a direct chat room.<br>
* In case of success the corresponding room is displayed.
*
* @param aSession session
* @param aRoomId room ID
* @param aParticipantUserId the direct chat invitee user ID
* @param fromActivity calling activity
* @param callback async response handler
*/
public static void setToggleDirectMessageRoom(final MXSession aSession,
final String aRoomId,
String aParticipantUserId,
final Activity fromActivity,
final ApiCallback<Void> callback) {
if ((null == aSession) || (null == fromActivity) || TextUtils.isEmpty(aRoomId)) {
Log.d(LOG_TAG, "## setToggleDirectMessageRoom(): failure - invalid input parameters");
} else {
aSession.toggleDirectChatRoom(aRoomId, aParticipantUserId, new ApiCallback<Void>() {
@Override
public void onSuccess(Void info) {
callback.onSuccess(null);
}
@Override
public void onNetworkError(Exception e) {
Log.d(LOG_TAG, "## setToggleDirectMessageRoom(): invite() onNetworkError Msg=" + e.getLocalizedMessage());
if (null != callback) {
callback.onNetworkError(e);
}
}
@Override
public void onMatrixError(MatrixError e) {
Log.d(LOG_TAG, "## setToggleDirectMessageRoom(): invite() onMatrixError Msg=" + e.getLocalizedMessage());
if (null != callback) {
callback.onMatrixError(e);
}
}
@Override
public void onUnexpectedError(Exception e) {
Log.d(LOG_TAG, "## setToggleDirectMessageRoom(): invite() onUnexpectedError Msg=" + e.getLocalizedMessage());
if (null != callback) {
callback.onUnexpectedError(e);
}
}
});
}
}
/**
* Offer to send some dedicated intent data to an existing room
*
* @param fromActivity the caller activity
* @param intent the intent param
*/
public static void sendFilesTo(final Activity fromActivity, final Intent intent) {
if (Matrix.getMXSessions(fromActivity).size() == 1) {
sendFilesTo(fromActivity, intent, Matrix.getMXSession(fromActivity, null));
} else if (fromActivity instanceof FragmentActivity) {
// TBD
}
}
/**
* Offer to send some dedicated intent data to an existing room
*
* @param fromActivity the caller activity
* @param intent the intent param
* @param session the session/
*/
private static void sendFilesTo(final Activity fromActivity, final Intent intent, final MXSession session) {
// sanity check
if ((null == session) || !session.isAlive() || fromActivity.isFinishing()) {
return;
}
List<RoomSummary> mergedSummaries = new ArrayList<>(session.getDataHandler().getStore().getSummaries());
// keep only the joined room
for (int index = 0; index < mergedSummaries.size(); index++) {
RoomSummary summary = mergedSummaries.get(index);
Room room = session.getDataHandler().getRoom(summary.getRoomId());
if ((null == room) || room.isInvited() || room.isConferenceUserRoom()) {
mergedSummaries.remove(index);
index--;
}
}
Collections.sort(mergedSummaries, new Comparator<RoomSummary>() {
@Override
public int compare(RoomSummary lhs, RoomSummary rhs) {
if (lhs == null || lhs.getLatestReceivedEvent() == null) {
return 1;
} else if (rhs == null || rhs.getLatestReceivedEvent() == null) {
return -1;
}
if (lhs.getLatestReceivedEvent().getOriginServerTs() > rhs.getLatestReceivedEvent().getOriginServerTs()) {
return -1;
} else if (lhs.getLatestReceivedEvent().getOriginServerTs() < rhs.getLatestReceivedEvent().getOriginServerTs()) {
return 1;
}
return 0;
}
});
VectorRoomsSelectionAdapter adapter = new VectorRoomsSelectionAdapter(fromActivity, R.layout.adapter_item_vector_recent_room, session);
adapter.addAll(mergedSummaries);
final List<RoomSummary> fMergedSummaries = mergedSummaries;
new AlertDialog.Builder(fromActivity)
.setTitle(R.string.send_files_in)
.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.setAdapter(adapter,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, final int which) {
dialog.dismiss();
fromActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
RoomSummary summary = fMergedSummaries.get(which);
Map<String, Object> params = new HashMap<>();
params.put(VectorRoomActivity.EXTRA_MATRIX_ID, session.getMyUserId());
params.put(VectorRoomActivity.EXTRA_ROOM_ID, summary.getRoomId());
params.put(VectorRoomActivity.EXTRA_ROOM_INTENT, intent);
CommonActivityUtils.goToRoomPage(fromActivity, session, params);
}
});
}
})
.show();
}
//==============================================================================================================
// Parameters checkers.
//==============================================================================================================
//==============================================================================================================
// Media utils
//==============================================================================================================
/**
* Save a media in the downloads directory and offer to open it with a third party application.
*
* @param activity the activity
* @param savedMediaPath the media path
* @param mimeType the media mime type.
*/
public static void openMedia(final Activity activity, final String savedMediaPath, final String mimeType) {
if ((null != activity) && (null != savedMediaPath)) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
try {
File file = new File(savedMediaPath);
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), mimeType);
activity.startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(activity, e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
} catch (Exception e) {
Log.d(LOG_TAG, "## openMedia(): Exception Msg=" + e.getMessage());
}
}
});
}
}
/**
* Copy a file into a dstPath directory.
* The output filename can be provided.
* The output file is not overridden if it is already exist.
*
* @param sourceFile the file source path
* @param dstDirPath the dst path
* @param outputFilename optional the output filename
* @param callback the asynchronous callback
*/
private static void saveFileInto(final File sourceFile, final String dstDirPath, final String outputFilename, final ApiCallback<String> callback) {
// sanity check
if ((null == sourceFile) || (null == dstDirPath)) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
if (null != callback) {
callback.onNetworkError(new Exception("Null parameters"));
}
}
});
return;
}
AsyncTask<Void, Void, Pair<String, Exception>> task = new AsyncTask<Void, Void, Pair<String, Exception>>() {
@Override
protected Pair<String, Exception> doInBackground(Void... params) {
Pair<String, Exception> result;
// defines another name for the external media
String dstFileName;
// build a filename is not provided
if (null == outputFilename) {
// extract the file extension from the uri
int dotPos = sourceFile.getName().lastIndexOf(".");
String fileExt = "";
if (dotPos > 0) {
fileExt = sourceFile.getName().substring(dotPos);
}
dstFileName = "vector_" + System.currentTimeMillis() + fileExt;
} else {
dstFileName = outputFilename;
}
File dstDir = Environment.getExternalStoragePublicDirectory(dstDirPath);
if (dstDir != null) {
dstDir.mkdirs();
}
File dstFile = new File(dstDir, dstFileName);
// if the file already exists, append a marker
if (dstFile.exists()) {
String baseFileName = dstFileName;
String fileExt = "";
int lastDotPos = dstFileName.lastIndexOf(".");
if (lastDotPos > 0) {
baseFileName = dstFileName.substring(0, lastDotPos);
fileExt = dstFileName.substring(lastDotPos);
}
int counter = 1;
while (dstFile.exists()) {
dstFile = new File(dstDir, baseFileName + "(" + counter + ")" + fileExt);
counter++;
}
}
// Copy source file to destination
FileInputStream inputStream = null;
FileOutputStream outputStream = null;
try {
dstFile.createNewFile();
inputStream = new FileInputStream(sourceFile);
outputStream = new FileOutputStream(dstFile);
byte[] buffer = new byte[1024 * 10];
int len;
while ((len = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, len);
}
result = new Pair<>(dstFile.getAbsolutePath(), null);
} catch (Exception e) {
result = new Pair<>(null, e);
} finally {
// Close resources
try {
if (inputStream != null) inputStream.close();
if (outputStream != null) outputStream.close();
} catch (Exception e) {
Log.e(LOG_TAG, "## saveFileInto(): Exception Msg=" + e.getMessage());
result = new Pair<>(null, e);
}
}
return result;
}
@Override
protected void onPostExecute(Pair<String, Exception> result) {
if (null != callback) {
if (null == result) {
callback.onNetworkError(new Exception("Null parameters"));
} else if (null != result.first) {
callback.onSuccess(result.first);
} else {
callback.onNetworkError(result.second);
}
}
}
};
try {
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} catch (final Exception e) {
Log.e(LOG_TAG, "## saveFileInto() failed " + e.getMessage());
task.cancel(true);
(new android.os.Handler(Looper.getMainLooper())).post(new Runnable() {
@Override
public void run() {
if (null != callback) {
callback.onUnexpectedError(e);
}
}
});
}
}
/**
* Save a media URI into the download directory
*
* @param context the context
* @param srcFile the source file.
* @param filename the filename (optional)
* @param callback the asynchronous callback
*/
@SuppressLint("NewApi")
public static void saveMediaIntoDownloads(final Context context,
final File srcFile,
final String filename,
final String mimeType,
final SimpleApiCallback<String> callback) {
saveFileInto(srcFile, Environment.DIRECTORY_DOWNLOADS, filename, new ApiCallback<String>() {
@Override
public void onSuccess(String fullFilePath) {
if (null != fullFilePath) {
DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
try {
File file = new File(fullFilePath);
downloadManager.addCompletedDownload(file.getName(), file.getName(), true, mimeType, file.getAbsolutePath(), file.length(), true);
} catch (Exception e) {
Log.e(LOG_TAG, "## saveMediaIntoDownloads(): Exception Msg=" + e.getMessage());
}
}
if (null != callback) {
callback.onSuccess(fullFilePath);
}
}
@Override
public void onNetworkError(Exception e) {
Toast.makeText(context, e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
if (null != callback) {
callback.onNetworkError(e);
}
}
@Override
public void onMatrixError(MatrixError e) {
Toast.makeText(context, e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
if (null != callback) {
callback.onMatrixError(e);
}
}
@Override
public void onUnexpectedError(Exception e) {
Toast.makeText(context, e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
if (null != callback) {
callback.onUnexpectedError(e);
}
}
});
}
//==============================================================================================================
// Application badge (displayed in the launcher)
//==============================================================================================================
private static int mBadgeValue = 0;
/**
* Update the application badge value.
*
* @param context the context
* @param badgeValue the new badge value
*/
public static void updateBadgeCount(Context context, int badgeValue) {
try {
mBadgeValue = badgeValue;
ShortcutBadger.setBadge(context, badgeValue);
} catch (Exception e) {
Log.e(LOG_TAG, "## updateBadgeCount(): Exception Msg=" + e.getMessage());
}
}
/**
* Refresh the badge count for specific configurations.<br>
* The refresh is only effective if the device is:
* <ul><li>offline</li><li>does not support GCM</li>
* <li>GCM registration failed</li>
* <br>Notifications rooms are parsed to track the notification count value.
*
* @param aSession session value
* @param aContext App context
*/
public static void specificUpdateBadgeUnreadCount(MXSession aSession, Context aContext) {
MXDataHandler dataHandler;
// sanity check
if ((null == aContext) || (null == aSession)) {
Log.w(LOG_TAG, "## specificUpdateBadgeUnreadCount(): invalid input null values");
} else if ((null == (dataHandler = aSession.getDataHandler()))) {
Log.w(LOG_TAG, "## specificUpdateBadgeUnreadCount(): invalid DataHandler instance");
} else {
if (aSession.isAlive()) {
boolean isRefreshRequired;
GcmRegistrationManager gcmMgr = Matrix.getInstance(aContext).getSharedGCMRegistrationManager();
// update the badge count if the device is offline, GCM is not supported or GCM registration failed
isRefreshRequired = !Matrix.getInstance(aContext).isConnected();
isRefreshRequired |= (null != gcmMgr) && (!gcmMgr.useGCM() || !gcmMgr.hasRegistrationToken());
if (isRefreshRequired) {
updateBadgeCount(aContext, dataHandler);
}
}
}
}
/**
* Update the badge count value according to the rooms content.
*
* @param aContext App context
* @param aDataHandler data handler instance
*/
private static void updateBadgeCount(Context aContext, MXDataHandler aDataHandler) {
//sanity check
if ((null == aContext) || (null == aDataHandler)) {
Log.w(LOG_TAG, "## updateBadgeCount(): invalid input null values");
} else if (null == aDataHandler.getStore()) {
Log.w(LOG_TAG, "## updateBadgeCount(): invalid store instance");
} else {
List<Room> roomCompleteList = new ArrayList<>(aDataHandler.getStore().getRooms());
int unreadRoomsCount = 0;
for (Room room : roomCompleteList) {
if (room.getNotificationCount() > 0) {
unreadRoomsCount++;
}
}
// update the badge counter
Log.d(LOG_TAG, "## updateBadgeCount(): badge update count=" + unreadRoomsCount);
CommonActivityUtils.updateBadgeCount(aContext, unreadRoomsCount);
}
}
//==============================================================================================================
// Low memory management
//==============================================================================================================
private static final String LOW_MEMORY_LOG_TAG = "Memory usage";
/**
* Log the memory statuses.
*
* @param activity the calling activity
* @return if the device is running on low memory.
*/
public static boolean displayMemoryInformation(Activity activity, String title) {
long freeSize = 0L;
long totalSize = 0L;
long usedSize = -1L;
try {
Runtime info = Runtime.getRuntime();
freeSize = info.freeMemory();
totalSize = info.totalMemory();
usedSize = totalSize - freeSize;
} catch (Exception e) {
e.printStackTrace();
}
Log.e(LOW_MEMORY_LOG_TAG, "---------------------------------------------------");
Log.e(LOW_MEMORY_LOG_TAG, "----------- " + title + " -----------------");
Log.e(LOW_MEMORY_LOG_TAG, "---------------------------------------------------");
Log.e(LOW_MEMORY_LOG_TAG, "usedSize " + (usedSize / 1048576L) + " MB");
Log.e(LOW_MEMORY_LOG_TAG, "freeSize " + (freeSize / 1048576L) + " MB");
Log.e(LOW_MEMORY_LOG_TAG, "totalSize " + (totalSize / 1048576L) + " MB");
Log.e(LOW_MEMORY_LOG_TAG, "---------------------------------------------------");
if (null != activity) {
ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
ActivityManager activityManager = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);
activityManager.getMemoryInfo(mi);
Log.e(LOW_MEMORY_LOG_TAG, "availMem " + (mi.availMem / 1048576L) + " MB");
Log.e(LOW_MEMORY_LOG_TAG, "totalMem " + (mi.totalMem / 1048576L) + " MB");
Log.e(LOW_MEMORY_LOG_TAG, "threshold " + (mi.threshold / 1048576L) + " MB");
Log.e(LOW_MEMORY_LOG_TAG, "lowMemory " + (mi.lowMemory));
Log.e(LOW_MEMORY_LOG_TAG, "---------------------------------------------------");
return mi.lowMemory;
} else {
return false;
}
}
/**
* Manage the low memory case
*
* @param activity activity instance
*/
public static void onLowMemory(Activity activity) {
if (!VectorApp.isAppInBackground()) {
String activityName = (null != activity) ? activity.getClass().getSimpleName() : "NotAvailable";
Log.e(LOW_MEMORY_LOG_TAG, "Active application : onLowMemory from " + activityName);
// it seems that onLowMemory is called whereas the device is seen on low memory condition
// so, test if the both conditions
if (displayMemoryInformation(activity, "onLowMemory test")) {
if (CommonActivityUtils.shouldRestartApp(activity)) {
Log.e(LOW_MEMORY_LOG_TAG, "restart");
CommonActivityUtils.restartApp(activity);
} else {
Log.e(LOW_MEMORY_LOG_TAG, "clear the application cache");
Matrix.getInstance(activity).reloadSessions(activity);
}
} else {
Log.e(LOW_MEMORY_LOG_TAG, "Wait to be concerned");
}
} else {
Log.e(LOW_MEMORY_LOG_TAG, "background application : onLowMemory ");
}
displayMemoryInformation(activity, "onLowMemory global");
}
/**
* Manage the trim memory.
*
* @param activity the activity.
* @param level the memory level
*/
public static void onTrimMemory(Activity activity, int level) {
String activityName = (null != activity) ? activity.getClass().getSimpleName() : "NotAvailable";
Log.e(LOW_MEMORY_LOG_TAG, "Active application : onTrimMemory from " + activityName + " level=" + level);
// TODO implement things to reduce memory usage
displayMemoryInformation(activity, "onTrimMemory");
}
//==============================================================================================================
// e2e devices management
//==============================================================================================================
/**
* Display the device verification warning
*
* @param deviceInfo the device info
*/
static public <T> void displayDeviceVerificationDialog(final MXDeviceInfo deviceInfo,
final String sender,
final MXSession session,
Activity activiy,
final ApiCallback<Void> callback) {
// sanity check
if ((null == deviceInfo) || (null == sender) || (null == session)) {
Log.e(LOG_TAG, "## displayDeviceVerificationDialog(): invalid imput parameters");
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(activiy);
LayoutInflater inflater = activiy.getLayoutInflater();
View layout = inflater.inflate(R.layout.encrypted_verify_device, null);
TextView textView;
textView = layout.findViewById(R.id.encrypted_device_info_device_name);
textView.setText(deviceInfo.displayName());
textView = layout.findViewById(R.id.encrypted_device_info_device_id);
textView.setText(deviceInfo.deviceId);
textView = layout.findViewById(R.id.encrypted_device_info_device_key);
textView.setText(MatrixSdkExtensionsKt.getFingerprintHumanReadable(deviceInfo));
builder
.setView(layout)
.setTitle(R.string.encryption_information_verify_device)
.setPositiveButton(R.string.encryption_information_verify_key_match, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
session.getCrypto().setDeviceVerification(MXDeviceInfo.DEVICE_VERIFICATION_VERIFIED, deviceInfo.deviceId, sender, callback);
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (null != callback) {
callback.onSuccess(null);
}
}
})
.show();
}
/**
* Export the e2e keys for a dedicated session.
*
* @param session the session
* @param password the password
* @param callback the asynchronous callback.
*/
public static void exportKeys(final MXSession session, final String password, final ApiCallback<String> callback) {
final Context appContext = VectorApp.getInstance();
if (null == session.getCrypto()) {
if (null != callback) {
callback.onMatrixError(new MatrixError("EMPTY", "No crypto"));
}
return;
}
session.getCrypto().exportRoomKeys(password, new ApiCallback<byte[]>() {
@Override
public void onSuccess(byte[] bytesArray) {
try {
ByteArrayInputStream stream = new ByteArrayInputStream(bytesArray);
String url = session.getMediasCache().saveMedia(stream, "riot-" + System.currentTimeMillis() + ".txt", "text/plain");
stream.close();
CommonActivityUtils.saveMediaIntoDownloads(appContext,
new File(Uri.parse(url).getPath()), "riot-keys.txt", "text/plain", new SimpleApiCallback<String>() {
@Override
public void onSuccess(String path) {
if (null != callback) {
callback.onSuccess(path);
}
}
@Override
public void onNetworkError(Exception e) {
if (null != callback) {
callback.onNetworkError(e);
}
}
@Override
public void onMatrixError(MatrixError e) {
if (null != callback) {
callback.onMatrixError(e);
}
}
@Override
public void onUnexpectedError(Exception e) {
if (null != callback) {
callback.onUnexpectedError(e);
}
}
});
} catch (Exception e) {
if (null != callback) {
callback.onMatrixError(new MatrixError(null, e.getLocalizedMessage()));
}
}
}
@Override
public void onNetworkError(Exception e) {
if (null != callback) {
callback.onNetworkError(e);
}
}
@Override
public void onMatrixError(MatrixError e) {
if (null != callback) {
callback.onMatrixError(e);
}
}
@Override
public void onUnexpectedError(Exception e) {
if (null != callback) {
callback.onUnexpectedError(e);
}
}
});
}
private static final String TAG_FRAGMENT_UNKNOWN_DEVICES_DIALOG_DIALOG = "ActionBarActivity.TAG_FRAGMENT_UNKNOWN_DEVICES_DIALOG_DIALOG";
/**
* Display the unknown e2e devices
*
* @param session the session
* @param activity the calling activity
* @param unknownDevices the unknown devices list
* @param listener optional listener to add an optional "Send anyway" button
*/
public static void displayUnknownDevicesDialog(MXSession session,
FragmentActivity activity,
MXUsersDevicesMap<MXDeviceInfo> unknownDevices,
VectorUnknownDevicesFragment.IUnknownDevicesSendAnywayListener listener) {
// sanity checks
if (activity.isFinishing() || (null == unknownDevices) || (0 == unknownDevices.getMap().size())) {
return;
}
FragmentManager fm = activity.getSupportFragmentManager();
VectorUnknownDevicesFragment fragment = (VectorUnknownDevicesFragment) fm.findFragmentByTag(TAG_FRAGMENT_UNKNOWN_DEVICES_DIALOG_DIALOG);
if (fragment != null) {
fragment.dismissAllowingStateLoss();
}
fragment = VectorUnknownDevicesFragment.newInstance(session.getMyUserId(), unknownDevices, listener);
try {
fragment.show(fm, TAG_FRAGMENT_UNKNOWN_DEVICES_DIALOG_DIALOG);
} catch (Exception e) {
Log.e(LOG_TAG, "## displayUnknownDevicesDialog() failed : " + e.getMessage());
}
}
}
| 44.989955 | 160 | 0.560648 |
db77a74b6159c6e45e113a92ec70b3b1044ba5ce | 1,084 | package org.maptalks.geojson;
import java.util.Map;
public class Feature extends GeoJSON {
private Object id;
private Geometry geometry;
private Map<String, Object> properties;
public Feature(
Geometry geometry,
Map<String,Object> properties) {
this(null, geometry, properties);
}
public Feature() {
}
public Feature(
Object id,
Geometry geometry,
Map<String,Object> properties) {
super();
this.setId(id);
this.setGeometry(geometry);
this.setProperties(properties);
}
public Object getId() {
return id;
}
public void setId(Object id) {
this.id = id;
}
public Geometry getGeometry() {
return geometry;
}
public void setGeometry(Geometry geometry) {
this.geometry = geometry;
}
public Map<String, Object> getProperties() {
return properties;
}
public void setProperties(Map<String, Object> properties) {
this.properties = properties;
}
}
| 20.074074 | 63 | 0.589483 |
f9b14e43457591e9605e81726b79b3d11e318b54 | 636 | package com.dzyoba.expr;
import junit.framework.TestCase;
public class NumberTest extends TestCase {
public void testSimple() {
Number o = new Number("123");
// Number internal representation is double
assertEquals("123.0", o.toString());
}
public void testDouble() {
Number o = new Number("123.45");
assertEquals("123.45", o.toString());
}
public void testFormatException() {
boolean thrown = false;
try {
new Number("123a");
} catch (NumberFormatException e) {
thrown = true;
}
assertTrue(thrown);
}
} | 23.555556 | 51 | 0.577044 |
961e252632f55ab58740d8daa7383565af1880ce | 306 | package com.cip.crane.restlet.resource.impl;
import com.cip.crane.restlet.resource.IHealthCheckResource;
import org.restlet.resource.ServerResource;
public class HealthCheckResource extends ServerResource implements IHealthCheckResource {
@Override
public String healthCheck() {
return "ok";
}
}
| 21.857143 | 89 | 0.80719 |
e8da928d39976b13e769b569a853a8ad95405f37 | 2,427 | /*
* Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.strata.basics.currency;
/**
* A provider of FX rates.
* <p>
* This provides the ability to obtain an FX rate. The interface does not mandate when the
* rate applies, however it typically represents the current rate.
* <p>
* One possible implementation is {@link FxMatrix}.
* <p>
* Implementations do not have to be immutable, but calls to the methods must be thread-safe.
*/
public interface FxRateProvider {
/**
* Converts an amount in a currency to an amount in a different currency using this rate.
* <p>
* The currencies must both be included in the currency pair of this rate.
*
* @param amount an amount in {@code fromCurrency}
* @param fromCurrency the currency of the amount
* @param toCurrency the currency into which the amount should be converted
* @return the amount converted into {@code toCurrency}
* @throws IllegalArgumentException if either of the currencies aren't included in the currency pair of this rate
*/
public default double convert(double amount, Currency fromCurrency, Currency toCurrency) {
return amount * fxRate(fromCurrency, toCurrency);
}
/**
* Gets the FX rate for the specified currency pair.
* <p>
* The rate returned is the rate from the base currency to the counter currency
* as defined by this formula: {@code (1 * baseCurrency = fxRate * counterCurrency)}.
*
* @param baseCurrency the base currency, to convert from
* @param counterCurrency the counter currency, to convert to
* @return the FX rate for the currency pair
* @throws RuntimeException if no FX rate could be found
*/
public abstract double fxRate(Currency baseCurrency, Currency counterCurrency);
/**
* Gets the FX rate for the specified currency pair.
* <p>
* The rate returned is the rate from the base currency to the counter currency
* as defined by this formula: {@code (1 * baseCurrency = fxRate * counterCurrency)}.
*
* @param currencyPair the ordered currency pair defining the rate required
* @return the FX rate for the currency pair
* @throws RuntimeException if no FX rate could be found
*/
public default double fxRate(CurrencyPair currencyPair) {
return fxRate(currencyPair.getBase(), currencyPair.getCounter());
}
}
| 38.52381 | 115 | 0.720231 |
14ba568ef86e041a2ceabfc4153e3bcbc644a24f | 3,457 | /*
* 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 Transaction;
import java.io.*;
import java.util.*;
import Main.*;
import java.util.logging.*;
/**
*
* @author fatma
*/
public class Balance implements IHashmap{
private double Amount;
private static final String filepath = "Balance.bin";
public double getAmount() {
return Amount;
}
public void setAmount(double Amount) {
this.Amount = Amount;
}
public boolean changeBalance(Entity entity,double newAmount){
HashMap hm= new HashMap();
boolean found = false;
hm= Read(filepath);
Set set = hm.entrySet();
Iterator i = set.iterator();
while (i.hasNext()){
Map.Entry me = (Map.Entry)i.next();
if((int) me.getKey()== entity.getID()){
found = true;
Amount = newAmount;
hm.put(entity.getID(), newAmount);
wirte(filepath,hm);
}
}
return found;
}
public static Balance getBalance(Entity entity)
{
Balance balance=new Balance();
HashMap hm = new HashMap();
hm= new Balance().Read(filepath);
Set set = hm.entrySet();
Iterator i = set.iterator();
while(i.hasNext()){
Map.Entry me= (Map.Entry) i.next();
if((int) me.getKey() == entity.getID()){
balance.setAmount((Double) me.getValue());
}
}
return balance;
}
public boolean addnewbalance(Balance balance,Entity entity)
{
HashMap hm = new HashMap();
hm=Read(filepath);
hm.put(entity.getID(), balance.getAmount());
wirte(filepath,hm);
return true;
}
public boolean RemoveBalance (Entity entity){
boolean done=false;
HashMap hm = new HashMap();
hm=Read(filepath);
Set set = hm.entrySet();
Iterator it = set.iterator();
for(int i=0;i<hm.size();i++)
{
Map.Entry me= (Map.Entry) it.next();
if((int) me.getKey() == entity.getID()){
hm.remove(me.getKey());
}
}
wirte(filepath,hm);
return done;
}
@Override
public boolean wirte(String path, HashMap hm) {
ObjectOutputStream in;
try {
in = new ObjectOutputStream(new FileOutputStream(path));
in.writeObject(hm);
in.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Balance.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Balance.class.getName()).log(Level.SEVERE, null, ex);
}
return true;
}
public HashMap Read(String path) {
ObjectInputStream out;
HashMap hm = new HashMap();
try {
out = new ObjectInputStream(new FileInputStream(path));
hm = (HashMap) out.readObject();
} catch (IOException ex) {
Logger.getLogger(Balance.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(Balance.class.getName()).log(Level.SEVERE, null, ex);
}
return hm;
}
} | 29.801724 | 82 | 0.547585 |
60e3e3db71458b73f174a9f67ce919d3b90c9f63 | 4,442 | package com.bumptech.glide.load.resource.bitmap;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import android.graphics.Bitmap;
import com.bumptech.glide.load.EncodeStrategy;
import com.bumptech.glide.load.Options;
import com.bumptech.glide.load.engine.Resource;
import com.bumptech.glide.util.ByteBufferUtil;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.Shadows;
import org.robolectric.annotation.Config;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import org.robolectric.shadows.ShadowBitmap;
import java.io.File;
import java.io.IOException;
@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE, sdk = 18, shadows = {
BitmapEncoderTest.AlphaShadowBitmap.class })
public class BitmapEncoderTest {
private EncoderHarness harness;
@Before
public void setUp() {
harness = new EncoderHarness();
}
@After
public void tearDown() {
harness.tearDown();
}
@Test
public void testBitmapIsEncoded() throws IOException {
String fakeBytes = harness.encode();
assertContains(fakeBytes, Shadows.shadowOf(harness.bitmap).getDescription());
}
@Test
public void testBitmapIsEncodedWithGivenQuality() throws IOException {
int quality = 7;
harness.setQuality(quality);
String fakeBytes = harness.encode();
assertContains(fakeBytes, String.valueOf(quality));
}
@Test
public void testEncoderObeysNonNullCompressFormat() throws IOException {
Bitmap.CompressFormat format = Bitmap.CompressFormat.WEBP;
harness.setFormat(format);
String fakeBytes = harness.encode();
assertContains(fakeBytes, format.toString());
}
@Test
public void testEncoderEncodesJpegWithNullFormatAndBitmapWithoutAlpha() throws IOException {
harness.setFormat(null);
harness.bitmap.setHasAlpha(false);
String fakeBytes = harness.encode();
assertContains(fakeBytes, Bitmap.CompressFormat.JPEG.toString());
}
@Test
public void testEncoderEncodesPngWithNullFormatAndBitmapWithAlpha() throws IOException {
harness.setFormat(null);
harness.bitmap.setHasAlpha(true);
String fakeBytes = harness.encode();
assertContains(fakeBytes, Bitmap.CompressFormat.PNG.toString());
}
@Test
public void testReturnsTrueFromWrite() {
BitmapEncoder encoder = new BitmapEncoder();
assertTrue(encoder.encode(harness.resource, harness.file, harness.options));
}
@Test
public void testEncodeStrategy_alwaysReturnsTransformed() {
BitmapEncoder encoder = new BitmapEncoder();
assertEquals(EncodeStrategy.TRANSFORMED, encoder.getEncodeStrategy(harness.options));
}
private static void assertContains(String string, String expected) {
assertThat(string).contains(expected);
}
@SuppressWarnings("unchecked")
private static class EncoderHarness {
Resource<Bitmap> resource = mock(Resource.class);
Bitmap bitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
Options options = new Options();
File file = new File(RuntimeEnvironment.application.getCacheDir(), "test");
public EncoderHarness() {
when(resource.get()).thenReturn(bitmap);
}
public void setQuality(int quality) {
options.set(BitmapEncoder.COMPRESSION_QUALITY, quality);
}
public void setFormat(Bitmap.CompressFormat format) {
options.set(BitmapEncoder.COMPRESSION_FORMAT, format);
}
public String encode() throws IOException {
BitmapEncoder encoder = new BitmapEncoder();
encoder.encode(resource, file, options);
byte[] data = ByteBufferUtil.toBytes(ByteBufferUtil.fromFile(file));
return new String(data);
}
public void tearDown() {
file.delete();
}
}
@Implements(Bitmap.class)
public static class AlphaShadowBitmap extends ShadowBitmap {
private boolean hasAlpha;
@SuppressWarnings("unused")
@Implementation
public void setHasAlpha(boolean hasAlpha) {
this.hasAlpha = hasAlpha;
}
@SuppressWarnings("unused")
@Implementation
public boolean hasAlpha() {
return hasAlpha;
}
}
}
| 28.113924 | 94 | 0.745835 |
55cffae0c91950296acc2f10efa8abe80ec39ff8 | 1,606 | package com.peruncs.gwt.tabulator;
import jsinterop.annotations.JsFunction;
import jsinterop.annotations.JsOverlay;
import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsType;
import jsinterop.base.Js;
/**
* The movableRowsSender option should be set on the sending table, and sets the action that should be taken
* after the row has been successfuly dropped into the receiving table.
*/
@JsType(isNative = true, name = "?", namespace = JsPackage.GLOBAL)
public interface MovableRowsSender {
/**
* do nothing(default).
*
* @return MovableRowsSender
*/
@JsOverlay
static MovableRowsSender doNothing() {
return Js.cast(false);
}
/**
* Deletes the row from the table.
*
* @return MovableRowsSender
*/
@JsOverlay
static MovableRowsSender delete() {
return Js.cast("delete");
}
/**
* Custom.
*
* @return MovableRowsSender
*/
@JsOverlay
static MovableRowsSender custom(Custom customCallback) {
return Js.cast(customCallback);
}
/**
* You can also pass a callback to the movableRowsSender option for custom sender functionality.
*/
@JsFunction
@FunctionalInterface
interface Custom {
/**
* @param fromRow the row component from the sending table
* @param toRow the row component from the receiving table (if available)
* @param fromTable the Tabulator object for the receiving table
*/
void onSend(RowComponent fromRow, RowComponent toRow, Tabulator fromTable);
}
}
| 26.327869 | 108 | 0.663761 |
2b5ec2a6c0fc750d6ffd3c4dafedb4cb19f903c8 | 13,000 | package com.mapbox.services.android.navigation.v5.navigation;
import android.location.Location;
import com.mapbox.services.android.navigation.BuildConfig;
import com.mapbox.services.android.navigation.v5.navigation.metrics.RerouteEvent;
import com.mapbox.services.android.navigation.v5.navigation.metrics.SessionState;
import com.mapbox.services.android.navigation.v5.routeprogress.MetricsRouteProgress;
import com.mapbox.services.android.navigation.v5.routeprogress.RouteProgress;
import com.mapbox.services.android.navigation.v5.utils.DistanceUtils;
import com.mapbox.services.android.telemetry.MapboxTelemetry;
import com.mapbox.services.android.telemetry.navigation.MapboxNavigationEvent;
import com.mapbox.services.android.telemetry.utils.TelemetryUtils;
import java.util.Hashtable;
import java.util.List;
final class NavigationMetricsWrapper {
static String sdkIdentifier;
private static String upcomingInstruction;
private static String previousInstruction;
private static String upcomingModifier;
private static String previousModifier;
private static String upcomingType;
private static String upcomingName;
private static String previousType;
private static String previousName;
private NavigationMetricsWrapper() {
// Empty private constructor for preventing initialization of this class.
}
static void arriveEvent(SessionState sessionState, RouteProgress routeProgress, Location location) {
Hashtable<String, Object> arriveEvent = MapboxNavigationEvent.buildArriveEvent(
sdkIdentifier, BuildConfig.MAPBOX_NAVIGATION_VERSION_NAME,
sessionState.sessionIdentifier(), location.getLatitude(), location.getLongitude(),
sessionState.currentGeometry(), routeProgress.directionsRoute().routeOptions().profile(),
routeProgress.directionsRoute().distance().intValue(),
routeProgress.directionsRoute().duration().intValue(),
sessionState.rerouteCount(), sessionState.startTimestamp(),
(int) (sessionState.eventRouteDistanceCompleted() + routeProgress.distanceTraveled()),
(int) routeProgress.distanceRemaining(), (int) routeProgress.durationRemaining(),
sessionState.mockLocation(), sessionState.originalRequestIdentifier(),
sessionState.requestIdentifier(),
sessionState.originalGeometry(), sessionState.originalDistance(),
sessionState.originalDuration(), null, sessionState.currentStepCount(),
sessionState.originalStepCount()
);
MetricsRouteProgress metricsRouteProgress = new MetricsRouteProgress(routeProgress);
int absoluteDistance = DistanceUtils.calculateAbsoluteDistance(location, metricsRouteProgress);
MapboxTelemetry.getInstance().addPercentTimeInForeground(sessionState.percentInForeground(), arriveEvent);
MapboxTelemetry.getInstance().addPercentTimeInPortrait(sessionState.percentInPortrait(), arriveEvent);
MapboxTelemetry.getInstance().addAbsoluteDistanceToDestination(absoluteDistance, arriveEvent);
MapboxTelemetry.getInstance().addLocationEngineName(sessionState.locationEngineName(), arriveEvent);
MapboxTelemetry.getInstance().pushEvent(arriveEvent);
MapboxTelemetry.getInstance().flushEventsQueueImmediately(false);
}
static void cancelEvent(SessionState sessionState, MetricsRouteProgress metricProgress, Location location) {
Hashtable<String, Object> cancelEvent = MapboxNavigationEvent.buildCancelEvent(
sdkIdentifier, BuildConfig.MAPBOX_NAVIGATION_VERSION_NAME,
sessionState.sessionIdentifier(),
location.getLatitude(), location.getLongitude(),
sessionState.currentGeometry(), metricProgress.getDirectionsRouteProfile(),
metricProgress.getDirectionsRouteDistance(),
metricProgress.getDirectionsRouteDuration(),
sessionState.rerouteCount(), sessionState.startTimestamp(),
(int) (sessionState.eventRouteDistanceCompleted() + metricProgress.getDistanceTraveled()),
metricProgress.getDistanceRemaining(), metricProgress.getDurationRemaining(),
sessionState.mockLocation(),
sessionState.originalRequestIdentifier(),
sessionState.requestIdentifier(),
sessionState.originalGeometry(),
sessionState.originalDistance(), sessionState.originalDuration(), null,
sessionState.arrivalTimestamp(), sessionState.currentStepCount(), sessionState.originalStepCount()
);
int absoluteDistance = DistanceUtils.calculateAbsoluteDistance(location, metricProgress);
MapboxTelemetry.getInstance().addPercentTimeInForeground(sessionState.percentInForeground(), cancelEvent);
MapboxTelemetry.getInstance().addPercentTimeInPortrait(sessionState.percentInPortrait(), cancelEvent);
MapboxTelemetry.getInstance().addAbsoluteDistanceToDestination(absoluteDistance, cancelEvent);
MapboxTelemetry.getInstance().addLocationEngineName(sessionState.locationEngineName(), cancelEvent);
MapboxTelemetry.getInstance().pushEvent(cancelEvent);
MapboxTelemetry.getInstance().flushEventsQueueImmediately(false);
}
static void departEvent(SessionState sessionState, MetricsRouteProgress metricProgress, Location location) {
Hashtable<String, Object> departEvent = MapboxNavigationEvent.buildDepartEvent(
sdkIdentifier, BuildConfig.MAPBOX_NAVIGATION_VERSION_NAME,
sessionState.sessionIdentifier(), location.getLatitude(), location.getLongitude(),
sessionState.currentGeometry(), metricProgress.getDirectionsRouteProfile(),
metricProgress.getDirectionsRouteDistance(),
metricProgress.getDirectionsRouteDuration(),
sessionState.rerouteCount(), sessionState.mockLocation(),
sessionState.originalRequestIdentifier(), sessionState.requestIdentifier(),
sessionState.originalGeometry(), sessionState.originalDistance(), sessionState.originalDuration(),
null, sessionState.currentStepCount(), sessionState.originalStepCount(),
metricProgress.getDistanceTraveled(), metricProgress.getDistanceRemaining(),
metricProgress.getDurationRemaining(), sessionState.startTimestamp()
);
int absoluteDistance = DistanceUtils.calculateAbsoluteDistance(location, metricProgress);
MapboxTelemetry.getInstance().addPercentTimeInForeground(sessionState.percentInForeground(), departEvent);
MapboxTelemetry.getInstance().addPercentTimeInPortrait(sessionState.percentInPortrait(), departEvent);
MapboxTelemetry.getInstance().addAbsoluteDistanceToDestination(absoluteDistance, departEvent);
MapboxTelemetry.getInstance().addLocationEngineName(sessionState.locationEngineName(), departEvent);
MapboxTelemetry.getInstance().pushEvent(departEvent);
MapboxTelemetry.getInstance().flushEventsQueueImmediately(false);
}
static void rerouteEvent(RerouteEvent rerouteEvent, MetricsRouteProgress metricProgress,
Location location) {
SessionState sessionState = rerouteEvent.getSessionState();
updateRouteProgressSessionData(metricProgress);
Hashtable<String, Object> navRerouteEvent = MapboxNavigationEvent.buildRerouteEvent(
sdkIdentifier, BuildConfig.MAPBOX_NAVIGATION_VERSION_NAME, sessionState.sessionIdentifier(),
location.getLatitude(), location.getLongitude(),
sessionState.currentGeometry(), metricProgress.getDirectionsRouteProfile(),
metricProgress.getDirectionsRouteDistance(),
metricProgress.getDirectionsRouteDuration(),
sessionState.rerouteCount(), sessionState.startTimestamp(),
convertToArray(sessionState.beforeEventLocations()),
convertToArray(sessionState.afterEventLocations()),
(int) sessionState.eventRouteDistanceCompleted(), // distanceCompleted
sessionState.eventRouteProgress().getDistanceRemaining(), // distanceRemaining
sessionState.eventRouteProgress().getDurationRemaining(), // durationRemaining
rerouteEvent.getNewDistanceRemaining(), // new distanceRemaining
rerouteEvent.getNewDurationRemaining(), // new durationRemaining
sessionState.secondsSinceLastReroute(), TelemetryUtils.buildUUID(),
rerouteEvent.getNewRouteGeometry(), sessionState.mockLocation(),
sessionState.originalRequestIdentifier(), sessionState.requestIdentifier(), sessionState.originalGeometry(),
sessionState.originalDistance(), sessionState.originalDuration(), null,
upcomingInstruction, upcomingType, upcomingModifier, upcomingName,
previousInstruction, previousType, previousModifier, previousName,
metricProgress.getCurrentStepDistance(),
metricProgress.getCurrentStepDuration(),
metricProgress.getCurrentStepDistanceRemaining(),
metricProgress.getCurrentStepDurationRemaining(),
sessionState.currentStepCount(), sessionState.originalStepCount());
navRerouteEvent.put(MapboxNavigationEvent.KEY_CREATED, TelemetryUtils.generateCreateDate(location));
int absoluteDistance = DistanceUtils.calculateAbsoluteDistance(location, metricProgress);
MapboxTelemetry.getInstance().addPercentTimeInForeground(sessionState.percentInForeground(), navRerouteEvent);
MapboxTelemetry.getInstance().addPercentTimeInPortrait(sessionState.percentInPortrait(), navRerouteEvent);
MapboxTelemetry.getInstance().addAbsoluteDistanceToDestination(absoluteDistance, navRerouteEvent);
MapboxTelemetry.getInstance().addLocationEngineName(sessionState.locationEngineName(), navRerouteEvent);
MapboxTelemetry.getInstance().pushEvent(navRerouteEvent);
MapboxTelemetry.getInstance().flushEventsQueueImmediately(false);
}
static void feedbackEvent(SessionState sessionState, MetricsRouteProgress metricProgress, Location location,
String description, String feedbackType, String screenshot, String feedbackId,
String vendorId) {
updateRouteProgressSessionData(metricProgress);
Hashtable<String, Object> feedbackEvent = MapboxNavigationEvent.buildFeedbackEvent(sdkIdentifier,
BuildConfig.MAPBOX_NAVIGATION_VERSION_NAME, sessionState.sessionIdentifier(), location.getLatitude(),
location.getLongitude(), sessionState.currentGeometry(), metricProgress.getDirectionsRouteProfile(),
metricProgress.getDirectionsRouteDistance(), metricProgress.getDirectionsRouteDuration(),
sessionState.rerouteCount(), sessionState.startTimestamp(), feedbackType,
convertToArray(sessionState.beforeEventLocations()),
convertToArray(sessionState.afterEventLocations()),
(int) sessionState.eventRouteDistanceCompleted(),
sessionState.eventRouteProgress().getDistanceRemaining(),
sessionState.eventRouteProgress().getDurationRemaining(),
description, vendorId, feedbackId, screenshot,
sessionState.mockLocation(), sessionState.originalRequestIdentifier(),
sessionState.requestIdentifier(), sessionState.originalGeometry(),
sessionState.originalDistance(), sessionState.originalDuration(), null,
upcomingInstruction, upcomingType, upcomingModifier, upcomingName,
previousInstruction, previousType, previousModifier, previousName,
metricProgress.getCurrentStepDistance(),
metricProgress.getCurrentStepDuration(),
metricProgress.getCurrentStepDistanceRemaining(),
metricProgress.getCurrentStepDurationRemaining(),
sessionState.currentStepCount(), sessionState.originalStepCount()
);
int absoluteDistance = DistanceUtils.calculateAbsoluteDistance(location, metricProgress);
MapboxTelemetry.getInstance().addPercentTimeInForeground(sessionState.percentInForeground(), feedbackEvent);
MapboxTelemetry.getInstance().addPercentTimeInPortrait(sessionState.percentInPortrait(), feedbackEvent);
MapboxTelemetry.getInstance().addAbsoluteDistanceToDestination(absoluteDistance, feedbackEvent);
feedbackEvent.put(MapboxNavigationEvent.KEY_CREATED, TelemetryUtils.generateCreateDate(location));
MapboxTelemetry.getInstance().addLocationEngineName(sessionState.locationEngineName(), feedbackEvent);
MapboxTelemetry.getInstance().pushEvent(feedbackEvent);
MapboxTelemetry.getInstance().flushEventsQueueImmediately(false);
}
static void turnstileEvent() {
MapboxTelemetry.getInstance().setCustomTurnstileEvent(
MapboxNavigationEvent.buildTurnstileEvent(sdkIdentifier, BuildConfig.MAPBOX_NAVIGATION_VERSION_NAME)
);
}
private static void updateRouteProgressSessionData(MetricsRouteProgress routeProgress) {
upcomingName = routeProgress.getUpcomingStepName();
upcomingInstruction = routeProgress.getUpcomingStepInstruction();
upcomingType = routeProgress.getUpcomingStepType();
upcomingModifier = routeProgress.getUpcomingStepModifier();
previousInstruction = routeProgress.getPreviousStepInstruction();
previousType = routeProgress.getPreviousStepType();
previousModifier = routeProgress.getPreviousStepModifier();
previousName = routeProgress.getPreviousStepName();
}
private static Location[] convertToArray(List<Location> locationList) {
return locationList.toArray(new Location[locationList.size()]);
}
}
| 59.090909 | 114 | 0.802077 |
d934be714805cf07e26f2f9ce7038cf6f18fa9d2 | 5,338 | package javamodularinput;
import com.splunk.modularinput.Argument;
import com.splunk.modularinput.Event;
import com.splunk.modularinput.EventWriter;
import com.splunk.modularinput.InputDefinition;
import com.splunk.modularinput.MalformedDataException;
import com.splunk.modularinput.Scheme;
import com.splunk.modularinput.Script;
import com.splunk.modularinput.SingleValueParameter;
import com.splunk.modularinput.ValidationDefinition;
import java.io.IOException;
import java.util.Random;
import javax.xml.stream.XMLStreamException;
/**
*
* @author kospol
*/
public class JavaModularInput extends Script {
/**
* Starts the Script
*/
public static void main(String[] args) {
new JavaModularInput().run(args);
}
/**
* Creates the Scheme for the Modular Input
* @return the Scheme
*/
@Override
public Scheme getScheme() {
Scheme scheme = new Scheme("Java RandomNumbers ModInput");
scheme.setDescription("Generates events containing a random number.");
scheme.setUseExternalValidation(true);
scheme.setUseSingleInstance(true);
Argument minArgument = new Argument("min");
minArgument.setDataType(Argument.DataType.NUMBER);
minArgument.setDescription("Minimum value to be produced by this input.");
minArgument.setRequiredOnCreate(true);
scheme.addArgument(minArgument);
Argument maxArgument = new Argument("max");
maxArgument.setDataType(Argument.DataType.NUMBER);
maxArgument.setDescription("Maximum value to be produced by this input.");
maxArgument.setRequiredOnCreate(true);
scheme.addArgument(maxArgument);
Argument timeArgument = new Argument("waitfor");
timeArgument.setDataType(Argument.DataType.NUMBER);
timeArgument.setDescription("How often the input will produce the random numbers (in seconds)");
timeArgument.setRequiredOnCreate(true);
scheme.addArgument(timeArgument);
return scheme;
}
@Override
public void validateInput(ValidationDefinition definition) throws Exception {
// Get the values of the parameters
int min = ((SingleValueParameter) definition.getParameters().get("min")).getInt();
int max = ((SingleValueParameter) definition.getParameters().get("max")).getInt();
int waitfor = ((SingleValueParameter) definition.getParameters().get("waitfor")).getInt();
//Validate the parameters
if (min >= max) {
throw new Exception("min must be less than max; found min=" + Double.toString(min)
+ ", max=" + Double.toString(max));
}
//Validate the parameters
if (waitfor <= 0) {
throw new Exception("waitfor must be at least 1 second");
}
}
@Override
public void streamEvents(InputDefinition inputs, EventWriter ew) throws MalformedDataException,
XMLStreamException, IOException {
for (String inputName : inputs.getInputs().keySet()) {
// We get the parameters for each input and start a new thread for each one.
// All the real work happens in the class for event generation.
int min = ((SingleValueParameter) inputs.getInputs().get(inputName).get("min")).getInt();
int max = ((SingleValueParameter) inputs.getInputs().get(inputName).get("max")).getInt();
int waitfor = ((SingleValueParameter) inputs.getInputs().get(inputName).get("waitfor")).getInt();
Thread t = new Thread(new Generator(ew, inputName, min, max, waitfor));
t.run();
}
}
final Random randomGenerator = new Random(System.currentTimeMillis());
/**
* A class that generates random numbers and sends the events to Splunk
*/
class Generator implements Runnable {
private final int min, max, waitfor;
private final EventWriter ew;
private final String inputName;
public Generator(EventWriter ew, String inputName, int min, int max, int waitfor) {
super();
this.min = min;
this.max = max;
this.ew = ew;
this.waitfor = waitfor;
this.inputName = inputName;
}
@Override
public void run() {
ew.synchronizedLog(EventWriter.INFO, "Random number generator " + inputName
+ " started, generating numbers between "
+ Integer.toString(min) + " and " + Integer.toString(max)
+ " with time set to: " + Integer.toString(waitfor));
while (true) {
Event event = new Event();
event.setStanza(inputName);
event.setData("number=" + (randomGenerator.nextInt((max - min) + 1) + min));
try {
ew.writeEvent(event);
} catch (MalformedDataException e) {
ew.synchronizedLog(EventWriter.ERROR, "MalformedDataException in writing event to input"
+ inputName + ": " + e.toString());
}
try {
Thread.sleep(waitfor * 1000);
} catch (InterruptedException e) {
return;
}
}
}
}
} | 37.858156 | 109 | 0.62233 |
7172fbbd535f03ce7be8b497e385fcf175f28381 | 259 | package org.fullnodej.data;
import lombok.Data;
/**P2SH address and hex-encoded redeem script*/
@Data
public class RedeemScript {
/**P2SH address for this multisig redeem script*/
String address;
/**hex multisig redeem script*/
String redeemScript;
}
| 17.266667 | 50 | 0.749035 |
4658f6f9939cdaaede8ec997769263d6592bb025 | 5,011 | /*******************************************************************************
* Copyright 2009 OpenSHA.org in partnership with
* the Southern California Earthquake Center (SCEC, http://www.scec.org)
* at the University of Southern California and the UnitedStates Geological
* Survey (USGS; http://www.usgs.gov)
*
* 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.opensha.nshmp.sha.data.calc;
import org.opensha.nshmp.util.GlobalConstants;
import org.opensha.nshmp.util.Interpolation;
/**
* <p>Title: FaFvCalc</p>
*
* <p>Description: This class calculates the Fa and Fv values based on
* Ss (SA at 0.1sec) and S1 (SA at 1.0sec) respectively, and selected site coefficient.</p>
* @author Ned Field, Nitin Gupta and E.V.Leyendecker
* @version 1.0
*/
public class FaFvCalc {
/**
* Calculates Fa based on site class and SA at 0.1sec value (Ss Value)
* @param siteClassVal String
* @param sValue double
* @return double
*/
public double getFa(String siteClassVal, double sValue) {
return getFaFv(siteClassVal, GlobalConstants.faData,
GlobalConstants.faColumnNames, sValue);
}
/**
* Calculates Fv based on site class and SA at 1.0sec value (S1 Value)
* @param siteClassVal String
* @param s1Value double
* @return double
*/
public double getFv(String siteClassVal, double s1Value) {
return getFaFv(siteClassVal, GlobalConstants.fvData,
GlobalConstants.fvColumnNames, s1Value);
}
/*
* Calculate the Fa and Fv based on what user has requested
* @param siteClassVal String
* @param data Object[][] : Fa or Fv array
* @param columnNames String[]
* @param sValue double
* @return double
*/
private double getFaFv(String siteClassVal, Object[][] data,
String[] columnNames, double sValue) {
char siteClass = siteClassVal.charAt(siteClassVal.length() - 1);
int rowNumber;
int length = data.length;
// get the row number
rowNumber = -1;
//iterating over all the rows to get the row number which is based on the site class
for (int i = 0; i < length; ++i) {
char val = ( (String) data[i][0]).charAt(0);
if (val == siteClass) {
rowNumber = i;
break;
}
}
//get the column number
int columnNumber = -1;
length = columnNames.length;
/**
* This finds the column number based on Sa value.It checks between which 2 columns
* does the SA value lies. If column number is 1 then no interpolation is
* required else interpolate between the column number one got to previous column.
* starting the index from 1 as first element in the columns names array is
* constant "Site Class".
*/
for (int j = 1; j < columnNames.length; ++j) {
String columnName = columnNames[j];
double colVal = getValueFromString(columnName);
if (Double.isNaN(colVal)) {
continue;
}
// found the columnNumber
if (sValue <= colVal) {
columnNumber = j;
break;
}
}
if (columnNumber == -1) {
return Double.parseDouble( (String) data[rowNumber][columnNames.length -
1]);
}
else if (columnNumber == 1) {
return Double.parseDouble( (String) data[rowNumber][columnNumber]);
}
else {
String y2String = (String) data[rowNumber][columnNumber];
String y1String = (String) data[rowNumber][columnNumber - 1];
double y2 = Double.parseDouble(y2String);
double x2 = getValueFromString(columnNames[columnNumber]);
double y1 = Double.parseDouble(y1String);
double x1 = getValueFromString(columnNames[columnNumber - 1]);
return Interpolation.getInterpolatedY(x1, x2, y1, y2, sValue);
}
}
/*
* Getting the S value from the column name.
* @param columnName String
* @return double
*/
private double getValueFromString(String columnName) {
int index = -1;
int indexForEqual = columnName.indexOf("=");
for (int k = indexForEqual; k < columnName.length(); ++k) {
if ( (columnName.charAt(k) >= '0' && columnName.charAt(k) <= '9') ||
columnName.charAt(k) == '.') {
index = k;
break;
}
}
if (index >= columnName.length() || index < 0) {
return Double.NaN;
}
else {
return Double.parseDouble(columnName.substring(index));
}
}
}
| 32.967105 | 91 | 0.628218 |
d74ea3de20f812e74b7f643672eb26c1faa91bd7 | 558 | package com.baoyongan.java.eg.base.error_ch;
public class ReturnValue {
public static void main(String[] args) {
System.out.println(decision());
}
private static boolean decision() {
try {
return true;
}finally {
return false;
}
/* boolean flag=false;
try {
flag=true;
System.out.println("before return");
return flag;
}finally {
System.out.println("execute finally");
flag=false;
}*/
}
}
| 19.241379 | 50 | 0.507168 |
b770755bfaa1598a4e5ac43d58242f545169bd08 | 197 | package com.epita.domain;
import org.jsoup.nodes.Document;
public class RawDocument {
public final Document doc;
public RawDocument(final Document doc) {
this.doc = doc;
}
}
| 16.416667 | 44 | 0.685279 |
a1bbafea1cf38433892f8b55f260fe6fa61fff1b | 3,596 | import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertArrayEquals;
/**
* Tests to test your Heap and Priority Queue classes
*
* @author CS 1332 TAs
* @version 1.1
*/
public class StudentTests {
private Heap<Integer> heap;
private PriorityQueue<Integer> pQueue;
@Before
public void setUp() {
heap = new Heap<Integer>();
pQueue = new PriorityQueue<Integer>();
}
@Test(timeout = 200)
public void testBasicAddInOrder1() {
basicAdd(1, 2, 3);
checkBackingArray(1, 2, 3);
}
@Test(timeout = 200)
public void testPeek1() {
basicAdd(4, 6, 1, 3, 2, 5);
assertEquals(new Integer(1), heap.peek());
assertEquals(6, heap.size());
}
@Test(timeout = 200)
public void testIsEmpty() {
assertTrue(heap.isEmpty());
basicAdd(1, 2, 3, 4, 5, 6);
assertFalse(heap.isEmpty());
}
/**
* Adds all of the numbers from an array to the heap.
*
* @param arr The array of numbers to add.
*/
private void basicAdd(Integer... arr) {
int i = 0;
while (i < arr.length && arr[i] != null) {
heap.add(arr[i]);
i++;
}
}
@Test(timeout = 200)
public void testBasicResize() {
@SuppressWarnings("rawtypes")
Comparable[] array = heap.toArray();
// 10 should be the default size of the heap backing array
assertEquals(10, array.length);
int num = 11;
addMany(num);
array = heap.toArray();
assertEquals(20, array.length);
}
@Test(timeout = 200)
public void testBasicInsert() {
pQueueBasicAdd();
assertArrayEquals(new Comparable[] {null, 21, 34, 38, 82, 73, 56, null,
null, null}, pQueue.toArray());
}
@Test(timeout = 200)
public void testBasicRemove() {
basicAdd(5, 2, 8, 12, 31, 4, 6, 11, 15);
assertEquals((Integer) 2, heap.remove());
checkBackingArray(4, 5, 6, 11, 31, 8, 15, 12);
}
@Test(timeout = 200)
public void testPQueueRemove() {
pQueueBasicAdd();
assertEquals((Integer) 21, pQueue.findMin());
assertEquals((Integer) 21, pQueue.deleteMin());
assertArrayEquals(new Comparable[] {null, 34, 56, 38, 82, 73, null,
null, null, null}, pQueue.toArray());
}
/**
* Adds num elements to the heap.
*
* @param num The number of elements to add to the heap.
*/
private void addMany(int num) {
for (int i = 1; i <= num; i++) {
heap.add(i);
}
}
/**
* Checks that the backing array maintains the right properties.
*
* @param numbers The numbers to compare to.
*/
private void checkBackingArray(Integer... numbers) {
@SuppressWarnings("rawtypes")
Comparable[] backingArray = heap.toArray();
assertNull(backingArray[0]);
for (int i = 1; i < backingArray.length; i++) {
if (i > numbers.length) {
assertNull(backingArray[i]);
} else {
assertEquals(numbers[i - 1], backingArray[i]);
}
}
}
private void pQueueBasicAdd() {
pQueue.insert(34);
pQueue.insert(82);
pQueue.insert(38);
pQueue.insert(21);
pQueue.insert(73);
pQueue.insert(56);
}
}
| 24.972222 | 79 | 0.56535 |
cdcc8579b5333c851baf3a98de7e4a28cd4f6abe | 2,289 | package org.texastorque.torquelib.component;
import edu.wpi.first.wpilibj.CounterBase;
import edu.wpi.first.wpilibj.Encoder;
import edu.wpi.first.wpilibj.Timer;
/**
* Class for a FRC encoder.
*
* @author Matthew
*/
public class TorqueEncoder extends Encoder {
private double averageRate;
private double acceleration;
private double previousTime;
private double previousPosition;
private double previousRate;
/**
* Create a new encoder.
*
* @param aChannel Channel a port.
* @param bChannel Channel b port.
* @param indexChannel The index channel digital input channel.
* @param reverseDirection Whether or not the encoder is reversed.
*/
public TorqueEncoder(int aChannel, int bChannel, int indexChannel, boolean reverseDirection) {
super(aChannel, bChannel, indexChannel, reverseDirection);
}
/**
* Create a new encoder.
*
* @param aChannel Channel a port.
* @param bChannel Channel b port.
* @param reverseDireciton Whether or not the encoder is revered.
* @param encodingType What type of encoding the encoder is using.
*/
public TorqueEncoder(int aChannel, int bChannel, boolean reverseDireciton, CounterBase.EncodingType encodingType) {
super(aChannel, bChannel, reverseDireciton, encodingType);
}
/**
* Calculate the values for the encoder.
*/
public void calc() {
double currentTime = Timer.getFPGATimestamp();
double currentPosition = super.get();
averageRate = (currentPosition - previousPosition) / (currentTime - previousTime);
acceleration = (averageRate - previousRate) / (currentTime - previousTime);
previousTime = currentTime;
previousPosition = currentPosition;
previousRate = averageRate;
}
/**
* Get the average rate at which encoder position changes over time. This
* rate is calculated in the dx/dt method rather than 1 / period method.
*
* @return The rate.
*/
public double getAverageRate() {
return averageRate;
}
/**
* Get the average rate at which rate changes over time.
*
* @return The rate.
*/
public double getAcceleration() {
return acceleration;
}
}
| 29.346154 | 119 | 0.668851 |
f51bd9ec22cd27bb6c480a56c6f716afb8f2f579 | 1,003 | package com.sequenceiq.cloudbreak.cloud.azure;
public class AzureImage {
private String id;
private String name;
private boolean alreadyExists;
public AzureImage(String id, String name, boolean alreadyExists) {
this.id = id;
this.name = name;
this.alreadyExists = alreadyExists;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean getAlreadyExists() {
return alreadyExists;
}
public void setAlreadyExists(boolean alreadyExists) {
this.alreadyExists = alreadyExists;
}
@Override
public String toString() {
return "AzureImage{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", alreadyExists=" + alreadyExists +
'}';
}
}
| 20.06 | 70 | 0.552343 |
0e0dcd4cd0d006dd78fbf67c718e1a7d8d7e52be | 79 | package org.ungs.gorgory.enums;
public enum Language {
JAVA,
PYTHON
}
| 11.285714 | 31 | 0.683544 |
66e9fb3abf13572190f96ab26eb1d18fc54ca8b5 | 1,431 | package com.sp.admin.controller;
import com.alibaba.fastjson.JSONObject;
import com.sp.admin.commonutil.redis.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.validation.FieldError;
import java.util.List;
public class BaseController {
@Autowired
protected RedisUtil redisUtil;
@Autowired
protected ApplicationContext applicationContext;
public boolean isDev(){
Environment env = applicationContext.getEnvironment();
String[] activeProfiles = env.getActiveProfiles();
for (String profile : activeProfiles) {
if ("dev".equals(profile)) {
return true;
}
}
return false;
}
public JSONObject getViolationErrMsg(List<FieldError> detailErr) {
JSONObject error = new JSONObject();
detailErr.forEach(fieldError -> {
error.put(fieldError.getField(), fieldError.getDefaultMessage());
});
return error;
}
public JSONObject buildTableResult(int code, String msg, long count, List<Object> pageData) {
JSONObject result = new JSONObject();
result.put("data", pageData);
result.put("count", count);
result.put("code", code);
result.put("msg", msg);
return result;
}
}
| 28.058824 | 97 | 0.67086 |
9c040d1d6a3e9f7d2087acc67f91d705a16f5710 | 6,574 | /*
* Copyright 2013 APPNEXUS INC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.appnexus.opensdk;
import android.content.Context;
import com.appnexus.opensdk.shadows.ShadowAsyncTaskNoExecutor;
import com.appnexus.opensdk.util.Lock;
import com.squareup.okhttp.mockwebserver.MockResponse;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotSame;
@Config(sdk = 21,
shadows = {ShadowAsyncTaskNoExecutor.class})
@RunWith(RobolectricTestRunner.class)
public class AdFetcherTest extends BaseRoboTest {
private AdFetcher adFetcher;
@Override
public void setup() {
super.setup();
// Since ad type is not a key factor that affects ad fetcher
// Using BannerAdView as the owner ad of AdFetcher here
MockAdOwner owner = new MockAdOwner(activity);
owner.setPlacementID("0");
owner.setAdSize(320, 50);
adFetcher = new AdFetcher(owner);
}
@Override
public void tearDown() {
super.tearDown();
if (adFetcher != null) {
adFetcher.stop();
adFetcher.clearDurations();
}
adFetcher = null;
}
/**
* When instantiating an AdView instance, AAID retrieval async tasks are scheduled
* This method clears all the background and UI thread tasks before running actual tests
*/
private void clearAAIDAsyncTasks() {
Robolectric.flushBackgroundThreadScheduler();
Robolectric.flushForegroundThreadScheduler();
}
private void assertExpectedBGTasksAfterOneAdRequest(int expectedBgTaskCount) {
// pause until a scheduler has a task in queue
waitForTasks();
// AdFetcher posts to a Handler which executes (queues) an AdRequest -- run the handler message
Robolectric.getForegroundThreadScheduler().advanceToLastPostedRunnable();
// Check that the AdRequest was queued
int bgTaskCount = Robolectric.getBackgroundThreadScheduler().size();
assertEquals("Expected: " + expectedBgTaskCount + ", actual: " + bgTaskCount, expectedBgTaskCount, bgTaskCount);
}
@Test
public void testDefaultState() {
assertEquals(-1, adFetcher.getPeriod());
assertEquals(AdFetcher.STATE.STOPPED, adFetcher.getState());
}
@Test
public void testStartWithRefreshOff() {
// Default state is auto refresh off, just start the ad fetcher
assertEquals("Default state should be stopped", AdFetcher.STATE.STOPPED, adFetcher.getState());
adFetcher.start();
Lock.pause(1000); // added this so jenkins can have enough time to process
assertEquals("Single request should be used.", AdFetcher.STATE.SINGLE_REQUEST, adFetcher.getState());
assertExpectedBGTasksAfterOneAdRequest(2);
assertEquals("State should not be changed after request.", AdFetcher.STATE.SINGLE_REQUEST, adFetcher.getState());
}
@Test
public void testStartWithRefreshOn() {
// default state was stopped
adFetcher.setPeriod(30000);
adFetcher.start();
Lock.pause(1000); // added this so jenkins can have enough time to process
// assert 3 here because a AAID async task
assertExpectedBGTasksAfterOneAdRequest(2);
assertEquals(AdFetcher.STATE.AUTO_REFRESH, adFetcher.getState());
// reset background scheduler, clear tasks for the refresh
Lock.pause(30000 + 1000); // We wait for till autorefresh is triggered
// in the following method, wait until next ad request is enqueued
assertExpectedBGTasksAfterOneAdRequest(3);
assertEquals(AdFetcher.STATE.AUTO_REFRESH, adFetcher.getState());
}
@Test
public void testStop() {
if (adFetcher != null) {
// not needed, but in case AdRequest is run
server.enqueue(new MockResponse().setResponseCode(200).setBody(TestResponsesUT.blank()));
clearAAIDAsyncTasks();
// start an AdFetcher normally, until an AdRequest is queued
adFetcher.start();
Lock.pause(1000); // added this so jenkins can have enough time to process
assertExpectedBGTasksAfterOneAdRequest(1);
assertNotSame(AdFetcher.STATE.STOPPED, adFetcher.getState());
adFetcher.stop();
// pause until a scheduler has a task in queue
waitForTasks();
// Run the cancel command on AdRequest
Robolectric.flushForegroundThreadScheduler();
// Run the pending AdRequest from start() -- should have been canceled
while (Robolectric.getBackgroundThreadScheduler().areAnyRunnable()) {
Robolectric.getBackgroundThreadScheduler().runOneTask();
}
// A normally executed AdRequest will queue onPostExecute call to the UI thread,
// but it should be canceled, and queue nothing
int uiTaskCount = Robolectric.getForegroundThreadScheduler().size();
assertEquals(0, uiTaskCount);
assertEquals(AdFetcher.STATE.STOPPED, adFetcher.getState());
}
}
@Test
public void testSetPeriod() {
int period = 30000;
adFetcher.setPeriod(period);
assertEquals(period, adFetcher.getPeriod());
}
@Test
public void testResetRefreshOff() {
adFetcher.setPeriod(5000);
adFetcher.start();
assertEquals(AdFetcher.STATE.AUTO_REFRESH, adFetcher.getState());
adFetcher.setPeriod(-1);
assertEquals(AdFetcher.STATE.SINGLE_REQUEST, adFetcher.getState());
}
class MockAdOwner extends BannerAdView {
public MockAdOwner(Context context) {
super(context);
}
@Override
public boolean isReadyToStart() {
return true;
}
}
}
| 36.726257 | 121 | 0.673867 |
8d544ca809a9fdfef4360a1098b46f42797c436f | 7,759 | package io.eluv.format.base58;
import java.io.*;
import java.util.UUID;
import io.eluv.os.OSInfo;
import jnr.ffi.LibraryLoader;
import jnr.ffi.provider.FFIProvider;
/**
* The library files are automatically extracted from this project's package (JAR).
*/
public class NativeB58Loader<T> {
private final String mTempDir;
private final String mSearchPattern;
/** The simple library name */
private final String mNativeLibraryName;
/** The library path (can be the same as library name) */
private final String mNativeLibraryPath;
private final boolean mDisableSelfExtract;
NativeB58Loader(
String nativeLibraryName,
String nativeLibraryPath,
String tmpDir,
String searchPattern,
boolean disableSelfExtract) {
mNativeLibraryName = nativeLibraryName;
mNativeLibraryPath = nativeLibraryPath;
mTempDir = tmpDir;
mSearchPattern = searchPattern;
mDisableSelfExtract = disableSelfExtract;
}
/**
* Loads the native library.
*
* @return True if the native library is successfully loaded, false otherwise.
* @throws Exception if loading fails
*/
T load(Class<T> pClass) throws Throwable {
cleanup();
LibraryLoader<T> loader = FFIProvider.getSystemProvider().createLibraryLoader(pClass);
loader.failImmediately();
Throwable loadError;
try {
return loader.load(mNativeLibraryPath);
} catch (Throwable t) {
loadError = t;
if (mDisableSelfExtract) {
throw t;
}
}
String sysLibraryName = System.mapLibraryName(mNativeLibraryName);
// Load the os-dependent library from the jar file
String packagePath = pClass.getPackage().getName().replaceAll("\\.", "/");
String resourceLibraryPath = String.format(
"/%s/native/%s",
packagePath,
sysLibraryName);
boolean hasNativeLib = hasResource(resourceLibraryPath);
if (!hasNativeLib) {
throw new IOException(
String.format(
"No native library found for os.name=%s and os.arch=%s. path=%s",
OSInfo.getOSName(),
OSInfo.getArchName(),
resourceLibraryPath),
loadError);
}
File lib;
try {
// Try extracting the library from jar
lib = extractLibraryFile(
sysLibraryName,
resourceLibraryPath,
getTempDir().getAbsolutePath());
} catch (Exception e) {
e.initCause(loadError);
throw e;
}
loader = FFIProvider.getSystemProvider().createLibraryLoader(pClass);
loader.failImmediately();
return loader.load(lib.getAbsolutePath());
}
private File getTempDir() {
return new File(mTempDir);
}
/**
* Delete old native libraries that were not removed on VM-Exit
*/
void cleanup() {
String tempFolder = getTempDir().getAbsolutePath();
File dir = new File(tempFolder);
File[] nativeLibFiles = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith(mSearchPattern) && !name.endsWith(".lck");
}
});
if (nativeLibFiles != null) {
for (File nativeLibFile : nativeLibFiles) {
File lckFile = new File(nativeLibFile.getAbsolutePath() + ".lck");
if (!lckFile.exists()) {
try {
nativeLibFile.delete();
} catch (SecurityException e) {
System.err.println("Failed to delete old native lib" + e.getMessage());
}
}
}
}
}
private boolean contentsEquals(InputStream in1, InputStream in2) throws IOException {
if (!(in1 instanceof BufferedInputStream)) {
in1 = new BufferedInputStream(in1);
}
if (!(in2 instanceof BufferedInputStream)) {
in2 = new BufferedInputStream(in2);
}
int ch = in1.read();
while (ch != -1) {
int ch2 = in2.read();
if (ch != ch2) {
return false;
}
ch = in1.read();
}
int ch2 = in2.read();
return ch2 == -1;
}
/**
* Extracts the specified library file to the target folder
*
* @param resourceFilePath Library resource path.
* @param targetFolder Target folder.
* @return
*/
private File extractLibraryFile(
String systemLibraryName,
String resourceFilePath,
String targetFolder) throws Exception {
// Include architecture name in temporary filename in order to avoid conflicts
// when multiple JVMs with different architectures running at the same time
String uuid = UUID.randomUUID().toString();
String extractedLibFileName = String.format(mSearchPattern + "%s-%s", uuid, systemLibraryName);
String extractedLckFileName = extractedLibFileName + ".lck";
File extractedLibFile = new File(targetFolder, extractedLibFileName);
File extractedLckFile = new File(targetFolder, extractedLckFileName);
// Extract a native library file into the target directory
InputStream reader = NativeB58Loader.class.getResourceAsStream(resourceFilePath);
if (!extractedLckFile.exists()) {
FileOutputStream los = new FileOutputStream(extractedLckFile);
try {los.close(); } catch (Exception io) {}
}
FileOutputStream writer = new FileOutputStream(extractedLibFile);
try {
byte[] buffer = new byte[8192];
int bytesRead = 0;
while ((bytesRead = reader.read(buffer)) != -1) {
writer.write(buffer, 0, bytesRead);
}
} finally {
// Delete the extracted lib file on JVM exit.
extractedLibFile.deleteOnExit();
extractedLckFile.deleteOnExit();
if (writer != null) {
try { writer.close(); } catch (Exception io) {}
}
if (reader != null) {
try { reader.close(); } catch (Exception io) {}
}
}
// Set executable (x) flag to enable Java to load the native library
extractedLibFile.setReadable(true);
extractedLibFile.setWritable(true, true);
extractedLibFile.setExecutable(true);
// Check whether the contents are properly copied from the resource folder
{
InputStream nativeIn = NativeB58Loader.class.getResourceAsStream(resourceFilePath);
InputStream extractedLibIn = new FileInputStream(extractedLibFile);
try {
if (!contentsEquals(nativeIn, extractedLibIn)) {
throw new IOException(String.format(
"Failed to write a native library file at %s",
extractedLibFile));
}
} finally {
if (nativeIn != null) {
nativeIn.close();
}
if (extractedLibIn != null) {
extractedLibIn.close();
}
}
}
return extractedLibFile;
}
private boolean hasResource(String path) {
return NativeB58Loader.class.getResource(path) != null;
}
}
| 34.484444 | 103 | 0.564892 |
dd0b1e09b50d75fb213bd3097dc71d8425392602 | 1,943 | /**
* Copyright 2010-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ly.demo;
import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.sql.DataSource;
@Configuration
@MapperScan("com.ly.demo.mapper")
public class Config {
@Bean
public SqlSessionFactoryBean sqlSessionFactory(DataSource druidDataSource) throws Exception {
PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(druidDataSource);
factoryBean.setMapperLocations(resourcePatternResolver.getResources("mybatis/mapper/*.xml"));
return factoryBean;
}
@Bean
public DataSource druidDataSource() {
DruidDataSource datasource = new DruidDataSource();
datasource.setUrl("jdbc:mysql://127.0.0.1:3306/tmp_ly?serverTimezone=UTC");
datasource.setUsername("root");
datasource.setPassword("123456ly");
datasource.setDriverClassName("com.mysql.jdbc.Driver");
return datasource;
}
}
| 36.660377 | 108 | 0.783839 |
952578295c8a89f22bd971c4c242be237c303706 | 384 | package patternTemplate.optimized;
public class Tea extends CaffeineBeverage {
@Override
void prepareRecipe() {
boilWater();
steepTeaBag();
pourInCup();
addLemon();
}
private void addLemon() {
System.out.println("Adding Lemon");
}
private void steepTeaBag() {
System.out.println("Steeping the tea");
}
}
| 18.285714 | 47 | 0.59375 |
3a28fcb9a070fafbda04c60baee3305d9a1af177 | 583 | package com.example.android.interpolatorplayground.custom;
import android.view.animation.Interpolator;
/**
* EaseIn as in:
* https://github.com/PrimaryFeather/Sparrow-Framework/blob/9de0e1f03c9d3fc532c4f7d6f60114387adb786e/sparrow/src/Classes/SPTransitions.m#L38
*
* @author Piotr Zawadzki
*/
public class EaseInInterpolator implements Interpolator {
@Override
public float getInterpolation(float input) {
return calculateInterpolation(input);
}
public static float calculateInterpolation(float input) {
return input * input * input;
}
}
| 26.5 | 140 | 0.754717 |
db9959fb31b639ae939620b188193e8ee2717754 | 1,541 | package com.w00tmast3r.skquery.elements.effects;
import ch.njol.skript.lang.Effect;
import ch.njol.skript.lang.Expression;
import ch.njol.skript.lang.SkriptParser;
import ch.njol.util.Kleenean;
import com.w00tmast3r.skquery.api.Description;
import com.w00tmast3r.skquery.api.Examples;
import com.w00tmast3r.skquery.api.Name;
import com.w00tmast3r.skquery.api.Patterns;
import com.w00tmast3r.skquery.util.minecraft.FireworkFactory;
import org.bukkit.FireworkEffect;
import org.bukkit.Location;
import org.bukkit.event.Event;
@Name("Pop Firework")
@Description("Instantly detonate a firework at a given location. Having multiple effects will cause them to stack.")
@Examples("on death:;->pop ball large firework colored red at victim")
@Patterns("(detonate|pop) %fireworkeffects% at %locations%")
public class EffPop extends Effect {
private Expression<FireworkEffect> effects;
private Expression<Location> loc;
@Override
protected void execute(Event event) {
for(Location l : loc.getAll(event)){
new FireworkFactory().location(l).effects(effects.getAll(event)).play();
}
}
@Override
public String toString(Event event, boolean b) {
return "pop firework";
}
@SuppressWarnings("unchecked")
@Override
public boolean init(Expression<?>[] expressions, int i, Kleenean kleenean, SkriptParser.ParseResult parseResult) {
effects = (Expression<FireworkEffect>) expressions[0];
loc = (Expression<Location>) expressions[1];
return true;
}
}
| 33.5 | 118 | 0.736535 |
bf5fc7a570e50d12d84348ed09f157c1ceb6ab74 | 365 | /*
* Copyright (c) 2009 University of Tartu
*/
package org.qsardb.model;
import javax.xml.bind.annotation.*;
@XmlType (
name = "ParameterRegistry"
)
abstract
public class ParameterRegistry <R extends ParameterRegistry<R, C>, C extends Parameter<R, C>> extends ContainerRegistry<R, C> {
ParameterRegistry(){
}
ParameterRegistry(Qdb qdb){
super(qdb);
}
} | 18.25 | 127 | 0.723288 |
1915b3bd18b4ab58569cfb55ef3abac1190c537a | 6,147 | /**
* Copyright © 2018 Mayo Clinic (RSTKNOWLEDGEMGMT@mayo.edu)
*
* 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 edu.mayo.kmdp.util;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.regex.Matcher;
public class FileUtil {
public static Optional<String> read(String file) {
try {
return read(new FileInputStream(file));
} catch (IOException e) {
return Optional.empty();
}
}
public static Optional<String> read(File file) {
try {
return read(new FileInputStream(file));
} catch (IOException e) {
return Optional.empty();
}
}
public static Optional<String> read(InputStream is) {
try {
int available = is.available();
byte[] data = new byte[available];
int actual = is.read(data);
if (available != actual) {
throw new IOException("Unable to read all data");
}
return Optional.of(new String(data));
} catch (IOException e) {
e.printStackTrace();
return Optional.empty();
}
}
public static Optional<String> read(URL url) {
try {
File f = new File(url.toURI());
if (!f.exists()) {
throw new FileNotFoundException("Unable to find file for url " + url);
}
return read(f);
} catch (URISyntaxException | IOException e) {
e.printStackTrace();
return Optional.empty();
}
}
public static Optional<byte[]> readBytes(InputStream is) {
try {
DataInputStream dis = new DataInputStream(is);
int available = is.available();
byte[] data = new byte[available];
dis.readFully(data);
return Optional.of(data);
} catch (IOException e) {
e.printStackTrace();
return Optional.empty();
}
}
public static Optional<byte[]> readBytes(URL url) {
try {
return readBytes(url.openStream());
} catch (IOException e) {
e.printStackTrace();
return Optional.empty();
}
}
public static List<URL> findFiles(URL rootURL, String regxpFilter) {
try {
File root = new File(rootURL.toURI());
if (root.isDirectory()) {
List<URL> files = new LinkedList<>();
findFiles(root, regxpFilter, files);
return files;
} else if (root.getPath().matches(regxpFilter)) {
return Collections.singletonList(root.toURI().toURL());
} else {
return Collections.emptyList();
}
} catch (URISyntaxException | MalformedURLException e) {
e.printStackTrace();
return Collections.emptyList();
}
}
private static void findFiles(File root, String regxpFilter, List<URL> fileURLs)
throws MalformedURLException {
if (root == null) {
return;
}
for (File child : Objects.requireNonNull(root.listFiles())) {
if (child.isDirectory()) {
findFiles(child, regxpFilter, fileURLs);
} else {
if (child.getPath().matches(regxpFilter)) {
fileURLs.add(child.toURI().toURL());
}
}
}
}
public static boolean copyTo(URL source, File targetFile) {
try {
return copyTo(source.openStream(), targetFile);
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public static boolean copyTo(InputStream sourceStream, File targetFile) {
try {
if (targetFile.isDirectory()) {
return false;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(sourceStream));
StringBuilder out = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
}
reader.close();
if (!targetFile.getParentFile().exists() && !targetFile.getParentFile().mkdirs()) {
return false;
}
FileOutputStream fos = new FileOutputStream(targetFile);
fos.write(out.toString().getBytes());
fos.close();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public static void delete(File root) {
Path pathToBeDeleted = root.toPath();
try {
Files.walk(pathToBeDeleted)
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
} catch (IOException e) {
e.printStackTrace();
}
}
public static File relativePathToFile(String rootPath, String relativePath) {
return new File(rootPath + asPlatformSpecific(relativePath));
}
public static String asPlatformSpecific(String path) {
return path.contains("/")
? path.replaceAll("/", Matcher.quoteReplacement(File.separator))
: path;
}
public static void write(byte[] content, File file) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(content);
fos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void write(String content, File file) {
PrintWriter wr = null;
try {
wr = new PrintWriter(file);
wr.write(content);
wr.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (wr != null) {
wr.close();
}
}
}
}
| 26.157447 | 89 | 0.623882 |
f45699109eebb2e4055289abd82dbf3067846aab | 546 | package com.huazie.frame.core.base.cfgdata.dao.impl;
import com.huazie.frame.core.base.cfgdata.dao.interfaces.IFleaJerseyResServiceLogDAO;
import com.huazie.frame.core.base.cfgdata.entity.FleaJerseyResServiceLog;
import org.springframework.stereotype.Repository;
/**
* <p> Flea Jersey资源服务调用日志DAO层实现类 </p>
*
* @author huazie
* @version 1.0.0
* @since 1.0.0
*/
@Repository("fleaJerseyResServiceLogDAO")
public class FleaJerseyResServiceLogDAOImpl extends FleaConfigDAOImpl<FleaJerseyResServiceLog> implements IFleaJerseyResServiceLogDAO {
} | 34.125 | 135 | 0.813187 |
04246efc378cdbadb8daeb3bb195ad802e8fbf55 | 1,715 |
class encrypt {
public encrypt(String receivedString, Integer encryptKey) {
this.receivedString = receivedString;
this.encryptKey = encryptKey;
}
private String receivedString;
public String getReceivedString() {
return receivedString;
}
public void setReceivedString(String receivedString) {
this.receivedString = receivedString;
}
private Integer encryptKey;
public Integer getEncryptKey() {
return encryptKey;
}
public void setEncryptKey(Integer encryptKey) {
this.encryptKey = encryptKey;
}
public boolean validReceivedString(){
char[] validateReceivedChars = receivedString.toCharArray();
boolean numberFlag = false;
for(char ch:validateReceivedChars){
if( Character.isLetter(ch) && ch!=' '){
numberFlag=true;
}
}
return numberFlag;
};
public boolean validKey(){
boolean validKey = false;
if(encryptKey>0 && encryptKey<=25){
validKey= true;
}
return validKey;
}
public String encryption() {
char[] receivedChars = receivedString.toUpperCase().toCharArray();
String alphabetList = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String encryptedText = "";
for (int i = 0; i<receivedChars.length; i++) {
if(receivedChars[i]==' '){
encryptedText+=' ';
}
else{
int charIndex = alphabetList.indexOf(receivedChars[i]);
int encryptedIndex = (charIndex + encryptKey) % 26;
char encryptedLetter = alphabetList.charAt(encryptedIndex);
encryptedText=encryptedText+encryptedLetter;
}
}
return encryptedText;
}
}; | 26.384615 | 73 | 0.627405 |
833a20b2b5317005c997fe2296dbcf016f68ade7 | 2,343 | /*
* Copyright (C) 2016 Peter Gregus for GravityBox Project (C3C076@xda)
* 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.wrbug.gravitybox.nougat.shortcuts;
import com.wrbug.gravitybox.nougat.ModHwKeys;
import com.wrbug.gravitybox.nougat.R;
import android.content.Context;
import android.content.Intent;
import android.content.Intent.ShortcutIconResource;
import android.graphics.drawable.Drawable;
public class GoHomeShortcut extends AShortcut {
protected static final String ACTION = ModHwKeys.ACTION_GO_HOME;
public static final String ACTION_DEFAULT_URI = "#Intent;action=gravitybox.intent.action.LAUNCH_ACTION;launchFlags=0x10008000;component=com.wrbug.gravitybox.nougat/.shortcuts.LaunchActivity;S.action=gravitybox.intent.action.GO_HOME;S.prefLabel=GravityBox%20Actions%3A%20Go%20home;i.mode=1;S.label=Go%20home;S.iconResName=com.wrbug.gravitybox.nougat%3Adrawable%2Fshortcut_home;S.actionType=broadcast;end";
public GoHomeShortcut(Context context) {
super(context);
}
@Override
public String getText() {
return mContext.getString(R.string.hwkey_action_home);
}
@Override
public Drawable getIconLeft() {
return mResources.getDrawable(R.drawable.shortcut_home, null);
}
@Override
protected String getAction() {
return ACTION;
}
@Override
protected String getShortcutName() {
return getText();
}
@Override
protected ShortcutIconResource getIconResource() {
return ShortcutIconResource.fromContext(mContext, R.drawable.shortcut_home);
}
public static void launchAction(final Context context, Intent intent) {
Intent launchIntent = new Intent(ACTION);
context.sendBroadcast(launchIntent);
}
}
| 36.609375 | 409 | 0.726419 |
007b48ba4ac249367ecb20d6c9fd3d54a0e6aa30 | 2,074 | package leetcode;
import java.math.BigInteger;
/**
* https://leetcode.com/problems/additive-number/
*/
public class Problem306 {
public boolean isAdditiveNumber(String num) {
for (int i = 0; i < num.length(); i++) {
boolean result = isAdditiveNumber(num, i + 1);
if (result) {
return true;
}
}
return false;
}
private boolean isAdditiveNumber(String num, int idx) {
BigInteger a = new BigInteger(num.substring(0, idx));
int beg = idx;
for (int i = 1; i < num.length(); i++) {
int endIdx = idx + i;
if (endIdx <= num.length()) {
String str = num.substring(beg, endIdx);
if (str.length() > 1 && str.startsWith("0")) {
return false;
}
BigInteger b = new BigInteger(str);
boolean result = isAdditiveNumber(num, a, b, endIdx);
if (result) {
return true;
}
}
}
return false;
}
private boolean isAdditiveNumber(String num, BigInteger a, BigInteger b, int idx) {
BigInteger x = a;
BigInteger y = b;
BigInteger sum = x.add(y);
String sumStr = sum.toString();
int begIdx = idx;
int endIdx = begIdx + sumStr.length();
if (endIdx > num.length()) {
return false;
}
String nextStr = num.substring(begIdx, endIdx);
if (!sumStr.equals(nextStr)) {
return false;
}
while (endIdx < num.length()) {
x = y;
y = sum;
sum = x.add(y);
sumStr = sum.toString();
begIdx = endIdx;
endIdx = begIdx + sumStr.length();
if (endIdx > num.length()) {
return false;
}
nextStr = num.substring(begIdx, endIdx);
if (!sumStr.equals(nextStr)) {
return false;
}
}
return true;
}
}
| 29.211268 | 87 | 0.472517 |
d7d2ac7ee706c780f7b128f82bd11a672a0fa845 | 8,753 | /*******************************************************************************
* Copyright (c) 2021 Gregory Mazo
*
* 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.
*******************************************************************************/
/**
* Author: Greg Mazo
* Date Modified: Jan 7, 2021
* Version: 2021.1
*/
package plotParts.DataShowingParts;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.geom.Path2D;
import java.awt.geom.Rectangle2D;
import java.util.HashMap;
import dataSeries.Basic1DDataSeries;
import dataSeries.DataSeries;
import dialogs.BoxPlotDialog;
import export.pptx.OfficeObjectMaker;
import export.svg.SVGExporter;
import graphicalObjects.CordinateConverter;
import graphicalObjects_LayerTypes.GraphicGroup;
import graphicalObjects_LayerTypes.GraphicLayerPane;
import graphicalObjects_Shapes.BasicShapeGraphic;
import plotParts.Core.PlotCordinateHandler;
/**The shape of a boxplot*/
public class Boxplot extends DataShowingShape {
/**
*
*/
private static final long serialVersionUID = 1L;
public static final int TYPE_IQR=1, TYPE_NORMAL_BOX_PLOT=0;
private int type=TYPE_NORMAL_BOX_PLOT;
Path2D allFillRect=new Path2D.Double();
private Rectangle2D fillRect;
/**the ratio of the cap to the width of the box*/
private double capSize=0.5;
public Boxplot(DataSeries data) {
super(data);
}
/**sets the traits that must be consistent between series on the same plot*/
public void copyTraitsFrom(Boxplot m) {
this.setWhiskerType(m.getWhiskerType());
this.setBarWidth(m.getBarWidth());
super.copyStrokeFrom(m);
}
public void copyEverythingFrom(Boxplot m) {
this.copyTraitsFrom(m);
this.copyStrokeFrom(m);
this.copyColorsFrom(m);
this.copyAttributesFrom(m);
}
public Boxplot copy() {
Boxplot output = new Boxplot(getTheData());
output.copyEverythingFrom(this);
return output;
}
@Override
public void draw(Graphics2D g, CordinateConverter cords) {
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, isAntialize()?RenderingHints.VALUE_ANTIALIAS_ON: RenderingHints.VALUE_ANTIALIAS_OFF);
/**Draws the boxes fill*/
if (this.isFilled()&&this.allFillRect!=null) {
Shape fr = cords.getAffineTransform().createTransformedShape(allFillRect);
g.setColor(getFillColor());
g.fill(fr);
//RectangularGraphic r = new RectangularGraphic(fillRect.getBounds());
// r.setFillColor(getFillColor());r.setStrokeColor(new Color(255,255,255, 0));
//r.draw(g, cords);
}
super.draw(g, cords);
}
/**updates the shape to account for changes to the style and data*/
@Override
protected void updateShape() {
super.partialShapes=new HashMap<Shape, DataSeries> ();
allFillRect=new Path2D.Double();
Path2D output = new Path2D.Double();
if (area==null) return;
/**if (this.getTheData().getAllPositions().length==1) {
Basic1DDataSeries series0 = this.getTheData().getIncludedValues();
output.append(addPathPartsForDataSeries(series0), false);
allFillRect.append(fillRect, false);
partialShapes.put(output, series0)
;
}
else*/ {
DataSeries[] all = PlotUtil.getAllSeriesFor(getTheData());
for(DataSeries a: all) {
if (isDataSeriesInvalid(a)) continue;
if (a.length()>2)
{
Shape pShape=addPathPartsForDataSeries(a.getIncludedValues());
output.append(pShape, false);
allFillRect.append(fillRect, false);
partialShapes.put(pShape, a);}
}
}
super.currentDrawShape=output;
}
protected Shape addPathPartsForDataSeries(Basic1DDataSeries series0) {
return addPathsForPVBox(new Path2D.Double(), series0);
}
protected Shape addPathsForPVBox(Path2D output, Basic1DDataSeries data) {
double vmin=data.getMin();
double vq1=data.getQ1();//location of bottom of bar
double v2=data.getMedian();
double vq3=data.getQ3();//location of bottom of bar
double vmax=data.getMax();
//double x1=0;
//double x2=0;
//double xcenter=0;
double position=data.getPosition(0);
double pOffset=data.getPositionOffset();
if (type==TYPE_IQR) {
vmin=data.getMinExcludingOutliers();
vmax=data.getMaxExcludingOutliers();
}
double barWidth2=this.getBarWidth()*this.capSize;
double boxWidth=this.getBarWidth();
PlotCordinateHandler c = this.getCordinateHandler();
java.awt.geom.Point2D.Double topCross1 = c.translate(position, vmax, pOffset-barWidth2, 0);
java.awt.geom.Point2D.Double topCross2 = c.translate(position, vmax, pOffset+barWidth2, 0);
java.awt.geom.Point2D.Double botCross1 = c.translate(position, vmin, pOffset-barWidth2, 0);
java.awt.geom.Point2D.Double botCross2 = c.translate(position, vmin, pOffset+barWidth2, 0);
if (barWidth2>0) {
super.lineBetween(output, topCross1, topCross2);
super.lineBetween(output, botCross1, botCross2);
}
java.awt.geom.Point2D.Double topOfUpperLine = c.translate(position, vmax, pOffset, 0);
java.awt.geom.Point2D.Double botOfUpperLine = c.translate(position, vq3, pOffset, 0);
super.lineBetween(output, botOfUpperLine, topOfUpperLine);
if (barWidth2>0&&super.getStrokeCap()==BasicStroke.CAP_ROUND) super.lineTo(output, topCross2);
java.awt.geom.Point2D.Double topOfLowerLine = c.translate(position, vmin, pOffset, 0);
java.awt.geom.Point2D.Double botOfLowerLine = c.translate(position, vq1, pOffset, 0);
super.lineBetween(output, botOfLowerLine, topOfLowerLine);
if (barWidth2>0&&super.getStrokeCap()==BasicStroke.CAP_ROUND) super.lineTo(output, botCross2);
java.awt.geom.Point2D.Double medLine1 = c.translate(position, v2, pOffset-boxWidth, 0);
java.awt.geom.Point2D.Double medLine2 = c.translate(position, v2, pOffset+boxWidth, 0);
super.lineBetween(output, medLine1, medLine2);
/**The top and bottom caps*/
java.awt.geom.Point2D.Double b1 = c.translate(position, vq3, pOffset-boxWidth, 0);
java.awt.geom.Point2D.Double b2 = c.translate(position, vq3, pOffset+boxWidth, 0);
java.awt.geom.Point2D.Double b3 = c.translate(position, vq1, pOffset+boxWidth, 0);
java.awt.geom.Point2D.Double b4 = c.translate(position, vq1, pOffset-boxWidth, 0);
java.awt.geom.Path2D.Double rectpath = new Path2D.Double();
super.lineBetween(rectpath, b1, b2);
super.lineBetween(rectpath, b3, b4);
fillRect=rectpath.getBounds2D();
output.append(fillRect, false);
return output;
}
public void updatePlotArea() {
}
public int getWhiskerType() {
return type;
}
public void setWhiskerType(int t) {
type=t;
}
public void showOptionsDialog() {
new BoxPlotDialog(this, false).showDialog();
}
public GraphicLayerPane getBreakdownGroup() {
GraphicLayerPane output = new GraphicLayerPane(this.getName());
BasicShapeGraphic r = new BasicShapeGraphic(allFillRect);
r.setFillColor(getFillColor());r.setStrokeColor(new Color(255,255,255, 0));
output.add(r);
BasicShapeGraphic shape2 = new BasicShapeGraphic(currentDrawShape);
shape2.copyAttributesFrom(this);shape2.copyColorsFrom(this);shape2.copyStrokeFrom(this);
output.add(shape2);
return output;
}
@Override
public SVGExporter getSVGEXporter() {
return getBreakdownGroup().getSVGEXporter();
}
@Override
public OfficeObjectMaker getObjectMaker() {
return new GraphicGroup(getBreakdownGroup()).getObjectMaker();
}
@Override
public double getMaxNeededValue() {
Basic1DDataSeries data = this.getTheData().getIncludedValues();
return data.getMax();
}
/**returns the area that this item takes up for
receiving user clicks*/
@Override
public Shape getOutline() {
return createOutlineForShape(getShape());
}
/**sets the ratio of the cap to the width of the box*/
public void setCapSize(double number) {
this.capSize=number;
}
/**returns the ratio of the cap to the width of the box*/
public double getCapSize() {
return capSize;
}
}
| 31.149466 | 140 | 0.694962 |
318d381154f37a66f2375b93b7f0247ef70c8d7a | 1,008 | // 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.internal.statistic.uploader.events;
import org.jetbrains.annotations.Nullable;
import java.util.Objects;
public class ExternalUploadFinishedEvent extends ExternalSystemEvent {
private final String myError;
public ExternalUploadFinishedEvent(long timestamp, @Nullable String error) {
super(ExternalSystemEventType.FINISHED, timestamp);
myError = error;
}
@Nullable
public String getError() {
return myError;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
ExternalUploadFinishedEvent event = (ExternalUploadFinishedEvent)o;
return Objects.equals(myError, event.myError);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), myError);
}
}
| 28.8 | 140 | 0.732143 |
3bbca43b7ea09a646bac0c8091859935679d054d | 160 | package org.immunophenotype.web.common;
public enum ZygosityType {
Het,
Hom,
Hemi,
Mutant;
public String getName(){
return this.toString();
}
}
| 10 | 39 | 0.68125 |
8c87538dd2eab8f3f9320c8623aa3b233dc905a1 | 1,341 | package com.tr.example.tests;
import com.tr.example.model.GroupData;
import org.testng.Assert;
import org.testng.annotations.Test;
public class GroupModificationTest extends TestBase {
@Test
public void testGroupModification(){
//methods openSite & login are located in parent class TestBase
app.getNavigationHelper().goToGroupPage();
if (!app.getGroupHelper().isThereAGroup()) {
app.getGroupHelper().createGroup();
}
int before = app.getGroupHelper().getGroupCount();
app.getGroupHelper().selectFirstGroup();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
app.getGroupHelper().initGroupModification();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// app.getGroupHelper().fillGroupForm(new GroupData("new_name", "new_header", ""));
app.getGroupHelper().confirmGroupModification();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
app.getGroupHelper().returnToGroupPage();
int after = app.getGroupHelper().getGroupCount();
Assert.assertEquals(after,before);
}
}
| 30.477273 | 90 | 0.616704 |
06509f9c0ad6e300c586fc95a691825eafe36a86 | 3,256 | package org.apache.mesos.elasticsearch.executor;
import com.beust.jcommander.JCommander;
import org.apache.log4j.Logger;
import org.apache.mesos.elasticsearch.common.cli.ElasticsearchCLIParameter;
import org.apache.mesos.elasticsearch.common.cli.ZookeeperCLIParameter;
import org.apache.mesos.elasticsearch.common.zookeeper.formatter.IpPortsListZKFormatter;
import org.apache.mesos.elasticsearch.common.zookeeper.formatter.ZKFormatter;
import org.apache.mesos.elasticsearch.common.zookeeper.parser.ZKAddressParser;
import org.elasticsearch.common.lang3.StringUtils;
import java.net.URISyntaxException;
/**
* Executor configuration
*/
public class Configuration {
private static final Logger LOGGER = Logger.getLogger(Configuration.class);
public static final String ELASTICSEARCH_YML = "elasticsearch.yml";
private final ElasticsearchCLIParameter elasticsearchCLI = new ElasticsearchCLIParameter();
// **** ZOOKEEPER
private final ZookeeperCLIParameter zookeeperCLI = new ZookeeperCLIParameter();
public Configuration(String[] args) {
final JCommander jCommander = new JCommander();
jCommander.addObject(zookeeperCLI);
jCommander.addObject(elasticsearchCLI);
jCommander.addObject(this);
try {
jCommander.parse(args); // Parse command line args into configuration class.
} catch (com.beust.jcommander.ParameterException ex) {
System.out.println(ex);
jCommander.setProgramName("(Options preceded by an asterisk are required)");
jCommander.usage();
throw ex;
}
}
// ******* ELASTICSEARCH
public String getElasticsearchSettingsLocation() {
String result = elasticsearchCLI.getElasticsearchSettingsLocation();
if (result.isEmpty()) {
result = getElasticsearchSettingsPath();
}
return result;
}
public int getElasticsearchNodes() {
return elasticsearchCLI.getElasticsearchNodes();
}
private String getElasticsearchSettingsPath() {
String path = "";
try {
path = getClass().getClassLoader().getResource(ELASTICSEARCH_YML).toURI().toString();
} catch (NullPointerException | URISyntaxException ex) {
LOGGER.error("Unable to read default settings file from resources", ex);
}
return path;
}
public String getElasticsearchZKURL() {
ZKFormatter mesosZKFormatter = new IpPortsListZKFormatter(new ZKAddressParser());
if (StringUtils.isBlank(zookeeperCLI.getZookeeperFrameworkUrl())) {
LOGGER.info("Zookeeper framework option is blank, using Zookeeper for Mesos: " + zookeeperCLI.getZookeeperMesosUrl());
return mesosZKFormatter.format(zookeeperCLI.getZookeeperMesosUrl());
} else {
LOGGER.info("Zookeeper framework option : " + zookeeperCLI.getZookeeperFrameworkUrl());
return mesosZKFormatter.format(zookeeperCLI.getZookeeperFrameworkUrl());
}
}
public long getElasticsearchZKTimeout() {
return zookeeperCLI.getZookeeperFrameworkTimeout();
}
public String getElasticsearchClusterName() {
return elasticsearchCLI.getElasticsearchClusterName();
}
}
| 39.707317 | 130 | 0.711302 |
79e1e53f54d10585ed7346aa280a4623c48f2cf9 | 1,646 | /*******************************************************************************
* Master-COLLiDER CONFIDENTIAL
* @author Probal D. Saikia.
* Github.com/Master-COLLiDER
* Copyright (c) 2020 - 2020.
* NOTICE: This file is subject to the terms and conditions defined
* in file 'LICENSE.txt' which is part of this source code package.
*
******************************************************************************/
package com.mastercollider.stegofierfx.GUI;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.input.MouseButton;
import javafx.stage.Stage;
import java.io.IOException;
public class RSAKeyGeneratorFX extends Application {
private double xOffset,yOffset;
@Override
public void start(Stage primaryStage) {
}
public void display(Stage stage) {
try {
Parent root = FXMLLoader.load(getClass().getResource("layouts/RSAKeysGeneratorLayout.fxml"));
stage.setScene(new Scene(root));
//we gonna drag the frame
root.setOnMousePressed(event -> {
xOffset = event.getSceneX();
yOffset = event.getSceneY();
});
root.setOnMouseDragged(event -> {
if (event.getButton().equals(MouseButton.PRIMARY))
{
stage.setX(event.getScreenX() - xOffset);
stage.setY(event.getScreenY() - yOffset);
}
});
stage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 28.37931 | 105 | 0.553463 |
a3455bb9652e25c7e3545404db26db55edfcdfdd | 1,707 | /*
* 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.facebook.presto.spi.plan;
import com.facebook.presto.spi.ColumnHandle;
import com.facebook.presto.spi.ConnectorSession;
import com.facebook.presto.spi.relation.RowExpression;
import com.facebook.presto.spi.statistics.TableStatistics;
import com.facebook.presto.spi.type.Type;
import java.util.Map;
/**
* Estimates the size of the data after applying a predicate using calculations compatible with Cost-Based Optimizer.
*/
public interface FilterStatsCalculatorService
{
/**
* @param tableStatistics Table-level and column-level statistics. Columns are identified using ColumnHandles.
* @param predicate Filter expression referring to columns by name
* @param columnNames Mapping from ColumnHandles used in tableStatistics to column names used in the predicate
* @param columnTypes Mapping from column names used in the predicate to column types
*/
TableStatistics filterStats(
TableStatistics tableStatistics,
RowExpression predicate,
ConnectorSession session,
Map<ColumnHandle, String> columnNames,
Map<String, Type> columnTypes);
}
| 39.697674 | 117 | 0.749854 |
703aaf80ad83d5ead42402d944b6bfbdb019e4a4 | 893 | package com.beatshadow.concurrent.chapter4;
import lombok.extern.slf4j.Slf4j;
import static java.lang.Thread.sleep;
/**
* @author : <a href="mailto:gnehcgnaw@gmail.com">gnehcgnaw</a>
* @since : 2020/4/28 21:22
*/
@Slf4j
public class TestThread8Monitor_6 {
public static void main(String[] args) {
Number6 number6 = new Number6() ;
new Thread(() -> {
try {
number6.a();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
new Thread(() -> {
number6.b();
}).start();
// 2 1S 1
// 1S 1 2
}
}
@Slf4j(topic = "c.Number")
class Number6{
public static synchronized void a() throws InterruptedException {
sleep(1);
log.debug("1");
}
public static synchronized void b() {
log.debug("2");
}
} | 21.780488 | 69 | 0.538634 |
0d54c8c657b4e9ead954b6f91b7c1edcb925ee8e | 386 | package com.bradforj287.raytracer.geometry;
public class Plane3d {
private Vector3d normal;
private Vector3d point;
public Plane3d(Vector3d normal, Vector3d point) {
this.normal = normal.toUnitVector();
this.point = point;
}
public Vector3d getNormal() {
return normal;
}
public Vector3d getPoint() {
return point;
}
}
| 19.3 | 53 | 0.639896 |
ddb2d5405150516903d483472fd3d0d4315143e8 | 1,947 | /*
* Copyright 2015 Skymind,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 org.deeplearning4j.clustering.kmeans;
import org.deeplearning4j.clustering.algorithm.BaseClusteringAlgorithm;
import org.deeplearning4j.clustering.algorithm.strategy.ClusteringStrategy;
import org.deeplearning4j.clustering.algorithm.strategy.FixedClusterCountStrategy;
/**
*
* @author Julien Roch
*
*/
public class KMeansClustering extends BaseClusteringAlgorithm {
private static final long serialVersionUID = 8476951388145944776L;
protected KMeansClustering(ClusteringStrategy clusteringStrategy) {
super(clusteringStrategy);
}
public static KMeansClustering setup(int clusterCount, int maxIterationCount,String distanceFunction) {
ClusteringStrategy clusteringStrategy = FixedClusterCountStrategy.setup(clusterCount, distanceFunction);
clusteringStrategy.endWhenIterationCountEquals(maxIterationCount);
return new KMeansClustering(clusteringStrategy);
}
public static KMeansClustering setup(int clusterCount, double minDistributionVariationRate,
String distanceFunction, boolean allowEmptyClusters) {
ClusteringStrategy clusteringStrategy = FixedClusterCountStrategy.setup(clusterCount, distanceFunction);
clusteringStrategy.endWhenDistributionVariationRateLessThan(minDistributionVariationRate);
return new KMeansClustering(clusteringStrategy);
}
}
| 34.767857 | 106 | 0.792501 |
5715865b4ec0ad0cf64dbce3db11569d75abc862 | 17,204 | package com.portofrotterdam.versiondebt;
import com.portofrotterdam.versiondebt.Versiondebts.VersiondebtItem;
import com.portofrotterdam.versiondebt.Versiondebts.VersiondebtItem.Version;
import org.apache.http.client.utils.DateUtils;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.repository.metadata.ArtifactRepositoryMetadata;
import org.apache.maven.artifact.repository.metadata.Metadata;
import org.apache.maven.artifact.repository.metadata.RepositoryMetadata;
import org.apache.maven.artifact.repository.metadata.RepositoryMetadataManager;
import org.apache.maven.artifact.repository.metadata.RepositoryMetadataResolutionException;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
*
* This is the Maven plugin.
*
* It creates a versiondebt.xml file for each submodule which contains all the version information.
*
* Part of this plugin is heavily based on:
* https://github.com/mojohaus/cobertura-maven-plugin/blob/master/src/main/java/org/codehaus/mojo/cobertura/CoberturaReportMojo.java
* This is used to create an aggregate file containing all the version information (which is used by the Sonar plugin).
*
* Possible improvements:
* - Add caching? Checking the latest version is a bit slow and it might be possible to cache this for a day for example?
*
*/
@Mojo(name = "generate", defaultPhase = LifecyclePhase.COMPILE, requiresProject = true, threadSafe = true)
public class VersiondebtMojo extends AbstractMojo {
/**
* <p>
* The Datafile Location.
* </p>
*/
@Parameter(defaultValue= "${project.build.directory}/versiondebt.xml")
private File dataFile;
/**
* The Maven project.
*/
@Parameter(defaultValue = "${project}")
private MavenProject currentProject;
/**
* List of maven project of the current build
*
* @parameter expression="${reactorProjects}"
* @required
* @readonly
*/
@Parameter(defaultValue = "${reactorProjects}")
private List<MavenProject> reactorProjects;
private Map<MavenProject, List<MavenProject>> projectChildren;
private String relDataFileName;
/**
* Misc Maven components:
*/
@Component
protected RepositoryMetadataManager repositoryMetadataManager;
@Parameter(defaultValue = "${localRepository}")
protected ArtifactRepository localRepository;
@Override
public void execute() throws MojoExecutionException {
// attempt to determine where data files and output dir are
relDataFileName = relativize( currentProject.getBasedir(), dataFile);
if ( relDataFileName == null )
{
getLog().warn( "Could not determine relative data file name, defaulting to 'versiondebt.xml'" );
relDataFileName = "versiondebt.xml";
}
try {
executeDependencyReport();
if (canGenerateAggregateReports()) {
// If we are executing the final project, write the aggregate:
executeAggregateReport();
}
} catch (IOException ioe) {
throw new MojoExecutionException("Error creating report ", ioe);
}
}
private void writeVersiondebtReport(Versiondebts versiondebts, MavenProject project) throws IOException {
final File outputFile = new File(project.getBasedir(), relDataFileName);
verifyDirectory(outputFile);
FileWriter fileWriter = null;
try {
fileWriter = new FileWriter(outputFile);
VersiondebtsFactory.newInstance().toXML(versiondebts, fileWriter);
} finally {
if (fileWriter != null) {
try {
fileWriter.close();
} catch (final IOException e) {
// ignore
}
}
}
}
private void executeDependencyReport() throws IOException {
final Versiondebts versiondebts = new Versiondebts();
final List<String> repositoryUrls = getRepositoryUrls();
final Log log = getLog();
log.info("");
log.info("------------------------------------------------------------------------");
log.info("Analyzing dependency version debt:");
log.info("------------------------------------------------------------------------");
log.info("");
long totalDebtTime = 0;
long amountOfOutdatedDependencies = 0;
@SuppressWarnings("unchecked")
final Set<Artifact> artifacts = currentProject.getDependencyArtifacts();
for (final Artifact artifact : artifacts) {
final String currentVersion = artifact.getVersion();
final Date currentVersionDate = extractLastModified(artifact, currentVersion, repositoryUrls);
final String latestVersion = retrieveLatestReleasedVersion(artifact);
final Date latestVersionDate = extractLastModified(artifact, latestVersion, repositoryUrls);
log.info("--- Dependency:" + artifact.getGroupId() + " : " + artifact.getArtifactId()+" ---");
log.info("");
log.info("\tCurrent version: " + currentVersion+ "\t" + currentVersionDate);
log.info("\tLatest version: " + latestVersion+ "\t" + latestVersionDate);
log.info("");
if (latestVersionDate != null && currentVersionDate != null) {
final long artifactDebtTime = latestVersionDate.getTime() - currentVersionDate.getTime();
if (artifactDebtTime > 0) {
amountOfOutdatedDependencies++;
totalDebtTime += artifactDebtTime;
log.info("\tArtifact debt: " + PrettyFormatter.formatMillisToYearsDaysHours(artifactDebtTime));
log.info("");
} else {
log.info("\tArtifact debt: Congratulations! You are up to date!");
log.info("");
}
}
versiondebts.addVersiondebtItem(generateVersiondebtItem(artifact, currentVersion, currentVersionDate, latestVersion, latestVersionDate));
}
long averageDebtTime = amountOfOutdatedDependencies > 0 ? totalDebtTime / amountOfOutdatedDependencies : 0;
log.info("------------------------------------------------------------------------");
log.info("AVERAGE DEBT PER DEP: " + PrettyFormatter.formatMillisToYearsDaysHours(averageDebtTime));
log.info("TOTAL DEBT: " + PrettyFormatter.formatMillisToYearsDaysHours(totalDebtTime));
log.info("------------------------------------------------------------------------");
log.info("");
writeVersiondebtReport(versiondebts, currentProject);
}
private VersiondebtItem generateVersiondebtItem(final Artifact artifact, final String currentVersionName, final Date currentVersionDate,
final String latestVersionName, final Date latestVersionDate) {
final VersiondebtItem versiondebt = new VersiondebtItem(artifact.getGroupId(), artifact.getArtifactId());
versiondebt.setUsedVersion(new Version(currentVersionName, currentVersionDate));
versiondebt.setLatestVersion(new Version(latestVersionName, latestVersionDate));
return versiondebt;
}
/**
* Method for combining all know URLs to get the best match/latest version
*/
private List<String> getRepositoryUrls() {
final List<String> repositoryUrls = new ArrayList<>();
// Combine all possible repository urls:
@SuppressWarnings("unchecked")
final List<ArtifactRepository> artifactRepositories = currentProject.getRemoteArtifactRepositories();
for (final ArtifactRepository repository : artifactRepositories) {
repositoryUrls.add(repository.getUrl());
}
return repositoryUrls;
}
private Date extractLastModified(final Artifact artifact, final String version, final List<String> repositoryUrls) throws IOException {
for (final String repositoryUrl : repositoryUrls) {
final URL url = new URL(generateUrl(artifact, version, repositoryUrl));
final URLConnection connection = url.openConnection();
String lastModified = connection.getHeaderField("Last-Modified");
if (lastModified != null) {
// Once found, return.
return DateUtils.parseDate(lastModified);
}
}
return null;
}
private String generateUrl(final Artifact artifact, final String version, final String repositoryUrl) {
// Build the repository URL to check the Last-Modified header:
String groupIdPart = artifact.getGroupId().replace(".", "/");
String artifactIdPart = artifact.getArtifactId().replace(".", "/");
return repositoryUrl + "/" + groupIdPart + "/" + artifactIdPart + "/" + version
+ "/" + artifact.getArtifactId() + "-" + version + ".pom";
}
private String retrieveLatestReleasedVersion(final Artifact artifact) {
final RepositoryMetadata metadata = new ArtifactRepositoryMetadata(artifact);
try {
repositoryMetadataManager.resolve(metadata, currentProject.getRemoteArtifactRepositories(), localRepository);
} catch (final RepositoryMetadataResolutionException e1) {
e1.printStackTrace();
}
final Metadata repoMetadata = metadata.getMetadata();
if (repoMetadata.getVersioning() != null) {
final String releasedVersion = repoMetadata.getVersioning().getRelease();
if (releasedVersion != null) {
return releasedVersion;
}
final String latestVersion = repoMetadata.getVersioning().getLatest();
if (latestVersion != null) {
return latestVersion;
}
}
return repoMetadata.getVersion();
}
/**
* -------------------------------------------------------------------------------------------
* Stuff below is heavily based on:
* https://github.com/mojohaus/cobertura-maven-plugin/blob/master/src/main/java/org/codehaus/mojo/cobertura/CoberturaReportMojo.java
*
* Needed to generate an aggregate report.
* -------------------------------------------------------------------------------------------
*/
/**
* Generates an aggregate report for the given project.
*/
private void executeAggregateReport(MavenProject topProject) throws IOException {
Versiondebts aggregateVersiondebts = new Versiondebts();
List<MavenProject> children = getAllChildren( topProject );
if ( children.isEmpty() )
{
return;
}
List<File> partialReportFiles = getOutputFiles(children);
if(partialReportFiles.isEmpty()) {
getLog().info("No reports found");
return;
}
getLog().info( "Executing aggregate reports for " + topProject.getName());
for ( File partialReportFile : partialReportFiles ) {
try {
// Merge all the versiondebts:
getLog().info("Collecting report: "+partialReportFile.toString());
Versiondebts partialDebts = VersiondebtsFactory.newInstance().fromXML(Files.newInputStream(partialReportFile.toPath()));
aggregateVersiondebts.addAll(partialDebts.getVersiondebtItems());
} catch (IOException ioe) {
getLog().error(ioe);
}
}
writeVersiondebtReport(aggregateVersiondebts, topProject);
}
/**
* Returns a list containing all the recursive, non-pom children of the given project, never <code>null</code>.
*/
private List<MavenProject> getAllChildren( MavenProject parentProject )
{
List<MavenProject> children = projectChildren.get( parentProject );
if(children == null) {
return Collections.emptyList();
}
List<MavenProject> result = new ArrayList<>();
for(MavenProject child : children) {
if(isMultiModule(child)) {
result.addAll( getAllChildren( child ) );
} else {
result.add( child );
}
}
return result;
}
/**
* Generates aggregate reports for all multi-module projects.
*/
private void executeAggregateReport() throws IOException {
// Find the top project and create a report for that project:
for ( MavenProject proj : reactorProjects) {
if(!isMultiModule(proj)) {
continue;
}
executeAggregateReport(proj);
}
}
/**
* Returns whether or not we can generate any aggregate reports at this time.
*/
private boolean canGenerateAggregateReports()
{
// we only generate aggregate reports after the last project runs
if(isLastProject(currentProject, reactorProjects)) {
buildAggregateInfo();
if (!getOutputFiles(reactorProjects).isEmpty()) {
return true;
}
}
return false;
}
/**
* Check whether the element is the last element of the list
*
* @param project element to check
* @param mavenProjectList list of maven project
* @return true if project is the last element of mavenProjectList list
*/
private boolean isLastProject( MavenProject project, List<MavenProject> mavenProjectList )
{
return project.equals( mavenProjectList.get( mavenProjectList.size() - 1 ) );
}
/**
* Generates various information needed for building aggregate reports.
*/
private void buildAggregateInfo()
{
if(projectChildren != null) {
return; // already did this work
}
// build parent-child map
projectChildren = new HashMap<>();
for(MavenProject proj : reactorProjects) {
List<MavenProject> depList = projectChildren.get(proj.getParent());
if(depList == null) {
depList = new ArrayList<>();
projectChildren.put( proj.getParent(), depList);
}
depList.add(proj);
}
}
/**
* Returns any existing partial reports from the given list of projects.
*/
private List<File> getOutputFiles( List<MavenProject> projects )
{
List<File> files = new ArrayList<>();
for ( MavenProject proj : projects )
{
if ( isMultiModule( proj ) )
{
continue;
}
File outputFile = new File(proj.getBasedir(), relDataFileName);
if ( outputFile.exists() )
{
files.add( outputFile );
}
}
return files;
}
/**
* Test if the project has pom packaging
*
* @param mavenProject Project to test
* @return True if it has a pom packaging
*/
private boolean isMultiModule( MavenProject mavenProject )
{
return "pom".equals( mavenProject.getPackaging() );
}
/**
* Attempts to make the given childFile relative to the given parentFile.
*/
private String relativize( File parentFile, File childFile )
{
try {
URI parentURI = parentFile.getCanonicalFile().toURI().normalize();
URI childURI = childFile.getCanonicalFile().toURI().normalize();
URI relativeURI = parentURI.relativize( childURI );
if ( relativeURI.isAbsolute() ) {
// child is not relative to parent
return null;
}
String relativePath = relativeURI.getPath();
if ( File.separatorChar != '/' ) {
relativePath = relativePath.replace( '/', File.separatorChar );
}
return relativePath;
}
catch ( Exception e ) {
getLog().warn( "Failed relativizing " + childFile + " to " + parentFile, e );
}
return null;
}
private void verifyDirectory(final File directory) {
File currentTarget = directory;
// Move to top directory, not file:
currentTarget = currentTarget.getParentFile();
if(!currentTarget.exists()) {
currentTarget.mkdirs();
}
}
}
| 37.318872 | 149 | 0.61724 |
72c53250fca77e828b6d5bc315817d8596a31525 | 2,069 | package com.evolent.backend.domain;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import org.hibernate.validator.constraints.NotEmpty;
/**
* This is Model class for maintaining contact
*
* @author dharmjeet.kumar
*
*/
@Entity
@Table(name = "CONTACT")
@NamedQuery(name = "contact.findAll", query = "from Contact c")
public class Contact implements Serializable {
/**
*
*/
private static final long serialVersionUID = 4811474799266486075L;
@Id
@Column(name = "CONTACT_ID")
private int contactId;
@Column(name = "EMAIL_ID")
private String emailId;
@Column(name = "FIRST_NAME")
private String firstName;
@Column(name = "LAST_NAME")
private String lastName;
@Column(name = "PHONE_NUMBER")
private String phoneNumber;
@Column(name = "STATUS")
private String status;
public int getContactId() {
return contactId;
}
public void setContactId(int contactId) {
this.contactId = contactId;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
@Override
public String toString() {
return "Contact [contactId=" + contactId + ", emailId=" + emailId + ", firstName=" + firstName + ", lastName="
+ lastName + ", phoneNumber=" + phoneNumber + ", status=" + status + "]";
}
}
| 20.087379 | 113 | 0.677622 |
eb17d2dc9bef6ba97a71053122bea5f8102fb0ee | 3,318 | /*
* 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.webbeans.newtests.subclassing;
import org.junit.Test;
import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.CtNewMethod;
import javassist.Modifier;
import javassist.NotFoundException;
import junit.framework.Assert;
public class TestSubclassCreation
{
@Test
public void testSubclassCreation() throws Exception
{
Class<ClassToGetIntercepted> ctgiClass = createSubClass(ClassToGetIntercepted.class);
ClassToGetIntercepted ctgi = ctgiClass.newInstance();
Assert.assertNotNull(ctgi);
String x = ctgi.getResult();
Assert.assertEquals("X", x);
}
private <T> Class<T> createSubClass(Class<T> cls)
throws NotFoundException, CannotCompileException
{
ClassPool pool = ClassPool.getDefault();
// first we need to load the class via javassist
CtClass origClass = pool.get(cls.getName());
// we create a new subclass with a certain postfix
CtClass subClass = pool.makeClass(cls.getName() + "_intcpted", origClass);
overrideInterceptedMethods(subClass);
// now let's get the real class from it
@SuppressWarnings("unchecked")
Class<T> interceptedClass = subClass.toClass();
return interceptedClass;
}
private void overrideInterceptedMethods(CtClass subClass)
throws CannotCompileException
{
CtMethod[] allMethods = subClass.getMethods();
for (CtMethod method : allMethods)
{
overrideInterceptedMethod(subClass, method);
}
}
private void overrideInterceptedMethod(CtClass subClass, CtMethod method)
throws CannotCompileException {
if (!method.visibleFrom(subClass) ||
((method.getModifiers() & (Modifier.FINAL | Modifier.STATIC)) > 0))
{
// we cannot delegate non visible, final or static methods
return;
}
String methodName = method.getLongName();
if (methodName.startsWith("java.lang.Object."))
{
// we also have to skip methods we derive from 'java.lang.Object'
return;
}
CtMethod overridenMethod = CtNewMethod.delegator(method, subClass);
subClass.addMethod(overridenMethod);
overridenMethod.insertBefore("{System.out.println(\"juuubel!:\");};");
}
}
| 31.903846 | 93 | 0.672694 |
352f9d400084a07e9ffa3f53c77f02e6c5aa45d3 | 25,930 | package org.apidb.apicomplexa.wsfplugin.spanlogic;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
import org.gusdb.fgputil.db.SqlUtils;
import org.gusdb.fgputil.db.platform.DBPlatform;
import org.gusdb.fgputil.runtime.InstanceManager;
import org.gusdb.fgputil.validation.ValidationLevel;
import org.gusdb.wdk.model.Utilities;
import org.gusdb.wdk.model.WdkModel;
import org.gusdb.wdk.model.WdkModelException;
import org.gusdb.wdk.model.WdkUserException;
import org.gusdb.wdk.model.answer.AnswerValue;
import org.gusdb.wdk.model.answer.factory.AnswerValueFactory;
import org.gusdb.wdk.model.user.Step;
import org.gusdb.wdk.model.user.User;
import org.gusdb.wsf.plugin.AbstractPlugin;
import org.gusdb.wsf.plugin.PluginModelException;
import org.gusdb.wsf.plugin.PluginRequest;
import org.gusdb.wsf.plugin.PluginResponse;
import org.gusdb.wsf.plugin.PluginUserException;
/**
Approach: there are two input answervalues. One is considered the "output" and the other the "reference."
The output av is the one whose records we output --those that match the spans of the reference.
For both avs, we make a temp table that has columns for the genomic locations. We then join the tables,
using the user's choice of operation, to produce a set of match rows. These are sorted by the output source_id.
To produce output, we scan the joined result, and accumulate into Feature datastructure all the matches belonging
to each output record. We print that record when the cursor moves to the next record.
There are a few hacks to accomodate alt splice. We force the temp tables to have a gene_source_id, regardless of
record type. For transcript records, this value is correctly set. For all others, it is set to "dontcare". Also, the
temp table for transcripts is expanded to include all transcripts of the genes found. Each has an identical span
location, that of the gene.
If the reference av is transcripts, then we only accumulate one match per gene, and print the gene_source_id as the match's ID,
rather than the usual source_id.
*/
public class SpanCompositionPlugin extends AbstractPlugin {
private static final Logger logger = Logger.getLogger(SpanCompositionPlugin.class);
protected static class Feature {
private static NumberFormat format = NumberFormat.getIntegerInstance();
public String sourceId;
public String geneSourceId; // for transcript subclass. ok, a hack, but so what
public String projectId;
public int begin;
public int end;
public int weight;
public boolean reversed;
public List<Feature> matched = new ArrayList<Feature>();
public String getBegin() {
return format.format(begin);
}
public String getEnd() {
return format.format(end);
}
public String getReversed() {
return reversed ? "-" : "+";
}
/**
* format the region of the feature
*
* @return
*/
public String getRegion() {
StringBuilder buffer = new StringBuilder();
buffer.append(begin).append(" - ").append(end);
buffer.append(" (").append(getReversed()).append(")");
return buffer.toString();
}
}
private static class Flag {
private boolean hasSnp = false;
}
public static final String COLUMN_SOURCE_ID = "source_id";
public static final String COLUMN_PROJECT_ID = "project_id";
public static final String COLUMN_WDK_WEIGHT = "wdk_weight";
public static final String COLUMN_FEATURE_REGION = "feature_region";
public static final String COLUMN_MATCHED_COUNT = "matched_count";
public static final String COLUMN_MATCHED_REGIONS = "matched_regions";
public static final String COLUMN_MATCHED_RESULT = "matched_result";
public static final String PARAM_OPERATION = "span_operation";
public static final String PARAM_STRAND = "span_strand";
public static final String PARAM_OUTPUT = "span_output";
public static final String PARAM_SPAN_PREFIX = "span_";
public static final String PARAM_BEGIN_PREFIX = "span_begin_";
public static final String PARAM_BEGIN_DIRECTION_PREFIX = "span_begin_direction_";
public static final String PARAM_BEGIN_OFFSET_PREFIX = "span_begin_offset_";
public static final String PARAM_END_PREFIX = "span_end_";
public static final String PARAM_END_DIRECTION_PREFIX = "span_end_direction_";
public static final String PARAM_END_OFFSET_PREFIX = "span_end_offset_";
// values for span_operation
public static final String PARAM_VALUE_OVERLAP = "overlap";
public static final String PARAM_VALUE_A_CONTAIN_B = "a_contain_b";
public static final String PARAM_VALUE_B_CONTAIN_A = "b_contain_a";
// values for begin/end
public static final String PARAM_VALUE_START = "start";
public static final String PARAM_VALUE_STOP = "stop";
// values for span_output
public static final String PARAM_VALUE_OUTPUT_A = "a";
public static final String PARAM_VALUE_OUTPUT_B = "b";
// values for begin/end_direction
public static final String PARAM_VALUE_UPSTREAM = "-";
public static final String PARAM_VALUE_DOWNSTREAM = "+";
// values for span_strand
public static final String PARAM_VALUE_BOTH_STRANDS = "both_strands";
public static final String PARAM_VALUE_SAME_STRAND = "same_strand";
public static final String PARAM_VALUE_OPPOSITE_STRANDS = "opposite_strands";
private static final String TEMP_TABLE_PREFIX = "spanlogic";
private final Random random = new Random();
@Override
public String[] getColumns(PluginRequest request) {
return new String[] { COLUMN_PROJECT_ID, COLUMN_SOURCE_ID, COLUMN_WDK_WEIGHT, COLUMN_FEATURE_REGION,
COLUMN_MATCHED_COUNT, COLUMN_MATCHED_REGIONS, COLUMN_MATCHED_RESULT };
}
@Override
public String[] getRequiredParameterNames() {
return new String[] { PARAM_OPERATION, PARAM_SPAN_PREFIX + "a", PARAM_SPAN_PREFIX + "b" };
}
@Override
public void validateParameters(PluginRequest request) throws PluginUserException {
Map<String, String> params = request.getParams();
Set<String> operators = new HashSet<String>(Arrays.asList(PARAM_VALUE_OVERLAP, PARAM_VALUE_A_CONTAIN_B,
PARAM_VALUE_B_CONTAIN_A));
Set<String> outputs = new HashSet<String>(Arrays.asList(PARAM_VALUE_OUTPUT_A, PARAM_VALUE_OUTPUT_B));
Set<String> strands = new HashSet<String>(Arrays.asList(PARAM_VALUE_BOTH_STRANDS,
PARAM_VALUE_SAME_STRAND, PARAM_VALUE_OPPOSITE_STRANDS));
Set<String> anchors = new HashSet<String>(Arrays.asList(PARAM_VALUE_START, PARAM_VALUE_STOP));
Set<String> directions = new HashSet<String>(Arrays.asList(PARAM_VALUE_DOWNSTREAM, PARAM_VALUE_UPSTREAM));
// validate operator
if (params.containsKey(PARAM_OPERATION)) {
String op = params.get(PARAM_OPERATION);
if (!operators.contains(op))
throw new PluginUserException("Invalid " + PARAM_OPERATION + ": " + op);
}
// validate output choice
if (params.containsKey(PARAM_OUTPUT)) {
String out = params.get(PARAM_OUTPUT);
if (!outputs.contains(out))
throw new PluginUserException("Invalid " + PARAM_OUTPUT + ": " + out);
}
// validate strand
if (params.containsKey(PARAM_STRAND)) {
String strand = params.get(PARAM_STRAND);
if (!strands.contains(strand))
throw new PluginUserException("Invalid " + PARAM_STRAND + ": " + strand);
}
// validate begin a
validateAnchorParams(params, anchors, PARAM_BEGIN_PREFIX + "a");
validateDirectionParams(params, directions, PARAM_BEGIN_DIRECTION_PREFIX + "a");
validateOffsetParams(params, PARAM_BEGIN_OFFSET_PREFIX + "a");
// validate end a
validateAnchorParams(params, anchors, PARAM_END_PREFIX + "a");
validateDirectionParams(params, directions, PARAM_END_DIRECTION_PREFIX + "a");
validateOffsetParams(params, PARAM_END_OFFSET_PREFIX + "a");
// validate begin b
validateAnchorParams(params, anchors, PARAM_BEGIN_PREFIX + "b");
validateDirectionParams(params, directions, PARAM_BEGIN_DIRECTION_PREFIX + "b");
validateOffsetParams(params, PARAM_BEGIN_OFFSET_PREFIX + "b");
// validate end b
validateAnchorParams(params, anchors, PARAM_END_PREFIX + "b");
validateDirectionParams(params, directions, PARAM_END_DIRECTION_PREFIX + "a");
validateOffsetParams(params, PARAM_END_OFFSET_PREFIX + "b");
}
private void validateAnchorParams(Map<String, String> params, Set<String> anchors, String param)
throws PluginUserException {
if (params.containsKey(param)) {
String anchor = params.get(param).intern();
if (!anchors.contains(anchor))
throw new PluginUserException("Invalid " + param + ": " + anchor);
}
}
private void validateDirectionParams(Map<String, String> params, Set<String> directions, String param)
throws PluginUserException {
if (params.containsKey(param)) {
String direction = params.get(param).intern();
if (!directions.contains(direction))
throw new PluginUserException("Invalid " + param + ": " + direction);
}
}
private void validateOffsetParams(Map<String, String> params, String param) throws PluginUserException {
if (params.containsKey(param)) {
String offset = params.get(param);
try {
Integer.parseInt(offset);
}
catch (NumberFormatException ex) {
throw new PluginUserException("Invalid " + param + " (expected number): " + offset);
}
}
}
@Override
public int execute(PluginRequest request, PluginResponse response) throws PluginModelException {
Map<String, String> params = request.getParams();
String operation = params.get(PARAM_OPERATION);
String output = params.get(PARAM_OUTPUT);
if (output == null || !output.equalsIgnoreCase(PARAM_VALUE_OUTPUT_B))
output = PARAM_VALUE_OUTPUT_A;
String strand = params.get(PARAM_STRAND);
if (strand == null)
strand = PARAM_VALUE_BOTH_STRANDS;
// get the proper begin & end of the derived regions.
String[] startStopA = getStartStop(params, "a");
String[] startStopB = getStartStop(params, "b");
String tempA = null, tempB = null;
try {
WdkModel wdkModel = InstanceManager.getInstance(WdkModel.class, request.getProjectId());
// get the answerValue from the step id
String userId = request.getContext().get(Utilities.QUERY_CTX_USER);
User user = wdkModel.getUserFactory().getUserById(Long.valueOf(userId))
.orElseThrow(() -> new PluginModelException("Cannot find user with passed context ID " + userId));
// create temp tables from caches
Flag flag = new Flag();
tempA = getSpanSql(wdkModel, user, params, startStopA, "a", flag);
tempB = getSpanSql(wdkModel, user, params, startStopB, "b", flag);
// compose the final sql by comparing two regions with span
// operation.
String sql = composeSql(operation, tempA, tempB, strand, output, flag);
logger.debug("SPAN LOGIC SQL:\n" + sql);
// execute the final sql, and fetch the result for the output.
prepareResult(wdkModel, response, sql, request.getOrderedColumns(), output);
// drop the cache tables
DBPlatform platform = wdkModel.getAppDb().getPlatform();
DataSource dataSource = wdkModel.getAppDb().getDataSource();
String schema = wdkModel.getAppDb().getDefaultSchema();
platform.dropTable(dataSource, schema, tempA, true);
platform.dropTable(dataSource, schema, tempB, true);
return 0;
}
catch (Exception ex) {
throw new PluginModelException(ex);
}
finally {
// dropTempTables(wdkModel, tempA, tempB);
}
}
private String[] getStartStop(Map<String, String> params, String suffix) {
// get the user's choice of begin & end, and the offsets from params.
String begin = params.get(PARAM_BEGIN_PREFIX + suffix);
if (begin == null)
begin = PARAM_VALUE_START;
String end = params.get(PARAM_END_PREFIX + suffix);
if (end == null)
end = PARAM_VALUE_STOP;
String beginDir = params.get(PARAM_BEGIN_DIRECTION_PREFIX + suffix);
if (beginDir == null)
beginDir = PARAM_VALUE_UPSTREAM;
String endDir = params.get(PARAM_END_DIRECTION_PREFIX + suffix);
if (endDir == null)
endDir = PARAM_VALUE_UPSTREAM;
int beginOff = 0;
if (params.containsKey(PARAM_BEGIN_OFFSET_PREFIX + suffix))
beginOff = Integer.valueOf(params.get(PARAM_BEGIN_OFFSET_PREFIX + suffix));
int endOff = 0;
if (params.containsKey(PARAM_END_OFFSET_PREFIX + suffix))
endOff = Integer.valueOf(params.get(PARAM_END_OFFSET_PREFIX + suffix));
if (beginDir.equals(PARAM_VALUE_UPSTREAM))
beginOff *= -1;
if (endDir.equals(PARAM_VALUE_UPSTREAM))
endOff *= -1;
String table = "fl.";
// depending on whether the feature is on forward or reversed strand,
// and user's choice of begin and end, we get the proper begin of the
// region.
StringBuilder sql = new StringBuilder("(CASE ");
sql.append(" WHEN NVL(" + table + "is_reversed, 0) = 0 THEN (");
sql.append(begin.equals(PARAM_VALUE_START) ? "start_min" : "end_max");
sql.append(" + 1*(" + beginOff + ")) ");
sql.append(" WHEN NVL(" + table + "is_reversed, 0) = 1 THEN (");
sql.append(end.equals(PARAM_VALUE_START) ? "end_max" : "start_min");
sql.append(" - 1*(" + endOff + ")) ");
sql.append("END)");
String start = sql.toString();
// we get the proper end of the region.
sql = new StringBuilder("(CASE ");
sql.append(" WHEN NVL(" + table + "is_reversed, 0) = 0 THEN (");
sql.append(end.equals(PARAM_VALUE_START) ? "start_min" : "end_max");
sql.append(" + 1*(" + endOff + ")) ");
sql.append(" WHEN NVL(" + table + "is_reversed, 0) = 1 THEN (");
sql.append(begin.equals(PARAM_VALUE_START) ? "end_max" : "start_min");
sql.append(" - 1*(" + beginOff + ")) ");
sql.append("END)");
String stop = sql.toString();
return new String[] { start, stop };
}
private String composeSql(String operation, String tempTableA, String tempTableB,
String strand, String output, Flag flag) {
StringBuilder builder = new StringBuilder();
// determine the output type
builder.append("SELECT fa.source_id AS source_id_a, ");
builder.append(" fa.gene_source_id AS gene_source_id_a, ");
builder.append(" fa.project_id AS project_id_a, ");
builder.append(" fa.wdk_weight AS wdk_weight_a, ");
builder.append(" fa.begin AS begin_a, fa.end AS end_a, ");
builder.append(" fa.is_reversed AS is_reversed_a, ");
builder.append(" fb.source_id AS source_id_b, ");
builder.append(" fb.gene_source_id AS gene_source_id_b, ");
builder.append(" fb.project_id AS project_id_b, ");
builder.append(" fb.wdk_weight AS wdk_weight_b, ");
builder.append(" fb.begin AS begin_b, fb.end AS end_b, ");
builder.append(" fb.is_reversed AS is_reversed_b ");
builder.append("FROM (" + tempTableA + ") fa, (" + tempTableB + ") fb ");
// make sure the regions come from sequence source.
builder.append("WHERE fa.sequence_source_id = fb.sequence_source_id ");
// restrict the regions to have start_min <= end_max
builder.append(" AND fa.begin <= fa.end ");
builder.append(" AND fb.begin <= fb.end ");
// check the strand choice
if (!flag.hasSnp) {
if (strand.equalsIgnoreCase(PARAM_VALUE_SAME_STRAND)) {
builder.append(" AND fa.is_reversed = fb.is_reversed ");
}
else if (strand.equalsIgnoreCase(PARAM_VALUE_OPPOSITE_STRANDS)) {
builder.append(" AND fa.is_reversed != fb.is_reversed ");
}
}
// apply span operation.
if (operation.equals(PARAM_VALUE_OVERLAP)) {
builder.append(" AND fa.begin <= fb.end ");
builder.append(" AND fa.end >= fb.begin ");
}
else if (operation.equals(PARAM_VALUE_A_CONTAIN_B)) {
builder.append(" AND fa.begin <= fb.begin ");
builder.append(" AND fa.end >= fb.end ");
}
else { // b_contain_a
builder.append(" AND fa.begin >= fb.begin ");
builder.append(" AND fa.end <= fb.end ");
}
// sort the result by output records
builder.append("ORDER BY f" + output + ".project_id ASC, ");
builder.append(" f" + output + ".source_id ASC ");
return builder.toString();
}
private String getSpanSql(WdkModel wdkModel, User user, Map<String, String> params, String[] region,
String suffix, Flag flag) throws WdkModelException, WdkUserException {
int stepId = Integer.parseInt(params.get(PARAM_SPAN_PREFIX + suffix));
WdkUserException e = new WdkUserException("No step with ID " + stepId + " exists for user " + user.getUserId());
Step step = wdkModel.getStepFactory().getStepByIdAndUserId(stepId, user.getUserId(),
ValidationLevel.RUNNABLE).orElseThrow(() -> e);
AnswerValue answerValue = AnswerValueFactory.makeAnswer(step.getRunnable()
.getOrThrow(validatedStep -> new WdkModelException(
"Step " + stepId + " is not runnable. Validation: " + validatedStep.getValidationBundle().toString())));
// get the sql to the cache table
String cacheSql = "(" + answerValue.getIdSql() + ")";
// get the table or sql that returns the location information
String rcName = answerValue.getAnswerSpec().getQuestion().getRecordClass().getFullName();
String locTable;
if (rcName.equals("DynSpanRecordClasses.DynSpanRecordClass")) {
locTable = "(SELECT source_id AS feature_source_id, project_id, " +
" regexp_substr(source_id, '[^:]+', 1, 1) as sequence_source_id, " +
" regexp_substr(regexp_substr(source_id, '[^:]+', 1, 2), '[^\\-]+', 1,1) as start_min, " +
" regexp_substr(regexp_substr(source_id, '[^:]+', 1, 2), '[^\\-]+', 1,2) as end_max, " +
" DECODE(regexp_substr(source_id, '[^:]+', 1, 3), 'r', 1, 0) AS is_reversed, " +
" 1 AS is_top_level, 'DynamicSpanFeature' AS feature_type " + " FROM " + cacheSql + ")";
}
else if (rcName.equals("SnpRecordClasses.SnpRecordClass")) {
flag.hasSnp = true;
String projectId = wdkModel.getProjectId();
locTable = "(SELECT sn.source_id AS feature_source_id, '" + projectId + "' AS project_id, " +
" sa.source_id AS sequence_source_id, sn.location AS start_min, sn.location AS end_max, " +
" 0 AS is_reversed, 1 AS is_top_level, 'SnpFeature' AS feature_type " +
" FROM Apidb.Snp sn, ApidbTuning.GenomicSeqAttributes sa " +
" WHERE sn.na_sequence_id = sa.na_sequence_id)";
}
else {
locTable = "apidb.FeatureLocation";
}
// get a temp table name
DBPlatform platform = wdkModel.getAppDb().getPlatform();
DataSource dataSource = wdkModel.getAppDb().getDataSource();
String schema = wdkModel.getAppDb().getDefaultSchema();
try {
String tableName = null;
while (true) {
tableName = TEMP_TABLE_PREFIX + random.nextInt(Integer.MAX_VALUE);
if (!platform.checkTableExists(dataSource, schema, tableName))
break;
}
String sql = rcName.equals("TranscriptRecordClasses.TranscriptRecordClass")
? getTranscriptSpanSql(tableName, region, cacheSql)
: getStandardSpanSql(tableName, region, locTable, cacheSql);
logger.debug("SPAN SQL: " + sql);
// cache the sql
SqlUtils.executeUpdate(dataSource, sql, "span-logic-child");
return tableName;
}
catch (SQLException ex) {
throw new WdkModelException(ex);
}
}
private String getStandardSpanSql(String tableName, String[] region, String locTable, String cacheSql ) {
StringBuilder builder = new StringBuilder();
builder.append("CREATE TABLE " + tableName + " AS ");
builder.append("SELECT DISTINCT fl.feature_source_id AS source_id, 'dontcare' as gene_source_id, ");
builder.append(" fl.sequence_source_id, fl.feature_type, ");
builder.append(" ca.wdk_weight, ca.project_id, ");
builder.append(" NVL(fl.is_reversed, 0) AS is_reversed, ");
builder.append(" " + region[0] + " AS begin, " + region[1] + " AS end ");
builder.append("FROM " + locTable + " fl, " + cacheSql + " ca ");
builder.append("WHERE fl.feature_source_id = ca.source_id");
builder.append(" AND fl.is_top_level = 1");
builder.append(" AND fl.feature_type = (");
builder.append(" SELECT fl.feature_type ");
builder.append(" FROM " + locTable + " fl, " + cacheSql + " ca");
builder.append(" WHERE fl.feature_source_id = ca.source_id");
builder.append(" AND rownum = 1) ");
return builder.toString();
}
private String getTranscriptSpanSql(String tableName, String[] region, String cacheSql ) {
StringBuilder builder = new StringBuilder();
builder.append("CREATE TABLE " + tableName + " AS ");
builder.append("SELECT DISTINCT ca.source_id, ca.gene_source_id, ");
builder.append(" fl.sequence_source_id, fl.feature_type, ");
builder.append(" ca.wdk_weight, ca.project_id, ");
builder.append(" NVL(fl.is_reversed, 0) AS is_reversed, ");
builder.append(" " + region[0] + " AS begin, " + region[1] + " AS end ");
builder.append("FROM apidb.FeatureLocation fl, " + cacheSql + " ca ");
builder.append("WHERE fl.feature_source_id = ca.gene_source_id");
builder.append(" AND fl.is_top_level = 1");
builder.append(" AND fl.feature_type = 'GeneFeature'");
return builder.toString();
}
private void prepareResult(WdkModel wdkModel, PluginResponse response, String sql, String[] orderedColumns,
String output) throws SQLException, PluginModelException, PluginUserException {
// prepare column order
Map<String, Integer> columnOrders = new LinkedHashMap<>(orderedColumns.length);
for (int i = 0; i < orderedColumns.length; i++) {
columnOrders.put(orderedColumns[i], i);
}
// read results
DataSource dataSource = wdkModel.getAppDb().getDataSource();
ResultSet resultSet = null;
Feature prevFeature = null;
Feature prevReference = null;
try {
resultSet = SqlUtils.executeQuery(dataSource, sql, "span-logic-cached");
Feature feature = null;
String ref = output.equals("a") ? "b" : "a";
while (resultSet.next()) {
String sourceId = resultSet.getString("source_id_" + output);
// the result is sorted by the ids of the output result
if (feature == null) {
// reading the first line
feature = new Feature();
readFeature(resultSet, feature, output);
}
else if (!feature.sourceId.equals(sourceId)) {
// start on a new record, output the previous feature
writeFeature(response, columnOrders, feature);
feature = new Feature();
readFeature(resultSet, feature, output);
}
// read the reference
Feature reference = new Feature();
readFeature(resultSet, reference, ref);
// if refs are genes, only add one match per gene. (non-gene refs have dontcare as gene_source_id)
if (feature != prevFeature || reference.geneSourceId.equals("dontcare") || prevReference == null || !reference.geneSourceId.equals(prevReference.geneSourceId))
feature.matched.add(reference);
prevFeature = feature;
prevReference = reference;
}
if (feature != null) { // write the last feature
writeFeature(response, columnOrders, feature);
}
}
finally {
SqlUtils.closeResultSetAndStatement(resultSet, null);
}
}
private void writeFeature(PluginResponse response, Map<String, Integer> columnOrders, Feature feature)
throws PluginModelException, PluginUserException {
// format the matched regions
StringBuilder builder = new StringBuilder();
for (Feature fr : feature.matched) {
if (builder.length() > 0) builder.append("; ");
String srcId = fr.geneSourceId.equals("dontcare")? fr.sourceId : fr.geneSourceId;
builder.append(srcId + ": " + fr.getBegin() + " - " + fr.getEnd() + " (" + fr.getReversed() + ")");
}
String matched = builder.toString();
if (matched.length() > 4000)
matched = matched.substring(0, 3997) + "...";
// construct row by column orders
String[] row = makeRow(columnOrders, feature, matched);
// save the row
response.addRow(row);
}
protected String[] makeRow(Map<String, Integer> columnOrders, Feature feature, String matched) {
String[] row = new String[columnOrders.size()];
row[columnOrders.get(COLUMN_SOURCE_ID)] = feature.sourceId;
row[columnOrders.get(COLUMN_PROJECT_ID)] = feature.projectId;
row[columnOrders.get(COLUMN_FEATURE_REGION)] = feature.getRegion();
row[columnOrders.get(COLUMN_MATCHED_COUNT)] = Integer.toString(feature.matched.size());
row[columnOrders.get(COLUMN_WDK_WEIGHT)] = Integer.toString(feature.weight);
row[columnOrders.get(COLUMN_MATCHED_REGIONS)] = matched;
row[columnOrders.get(COLUMN_MATCHED_RESULT)] = "Y";
return row;
}
protected void readFeature(ResultSet resultSet, Feature feature, String suffix) throws SQLException {
feature.sourceId = resultSet.getString("source_id_" + suffix);
feature.geneSourceId = resultSet.getString("gene_source_id_" + suffix);
feature.projectId = resultSet.getString("project_id_" + suffix);
feature.begin = resultSet.getInt("begin_" + suffix);
feature.end = resultSet.getInt("end_" + suffix);
feature.weight = resultSet.getInt("wdk_weight_" + suffix);
feature.reversed = resultSet.getBoolean("is_reversed_" + suffix);
}
}
| 42.930464 | 160 | 0.689279 |
48e7efb6ef630d4f315e79e48585227feb31df2f | 1,016 | package com.springboot.ex.SpringRestJPAExample.Exception;
import java.util.Date;
/**
* Custom Exception Response Model Class
*
* @author Udhay
*
*/
public class ExceptionResponse {
private Date dateObj;
private String errMsg;
private String errDesc;
private String webRequest;
public Date getDateObj() {
return dateObj;
}
public void setDateObj(Date dateObj) {
this.dateObj = dateObj;
}
public String getErrMsg() {
return errMsg;
}
public void setErrMsg(String errMsg) {
this.errMsg = errMsg;
}
public String getErrDesc() {
return errDesc;
}
public void setErrDesc(String errDesc) {
this.errDesc = errDesc;
}
public ExceptionResponse(Date dateObj, String errMsg, String errDesc,
String webRequest) {
super();
this.dateObj = dateObj;
this.errMsg = errMsg;
this.errDesc = errDesc;
this.webRequest = webRequest;
}
public String getWebRequest() {
return webRequest;
}
public void setWebRequest(String webRequest) {
this.webRequest = webRequest;
}
}
| 16.933333 | 70 | 0.71752 |
f873509ec9b8325fee63a4e3309aaf9020335608 | 876 | /**
* Copyright (c) 2017 Dell Inc., or its subsidiaries. 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
*/
package io.pravega.client.state;
import io.pravega.client.stream.EventWriterConfig;
import java.io.Serializable;
import lombok.Builder;
import lombok.Data;
/**
* The configuration for a Consistent replicated state synchronizer.
*/
@Data
@Builder
public class SynchronizerConfig implements Serializable {
private static final long serialVersionUID = 1L;
EventWriterConfig eventWriterConfig;
public static class SynchronizerConfigBuilder {
private EventWriterConfig eventWriterConfig = EventWriterConfig.builder().build();
}
}
| 28.258065 | 90 | 0.746575 |
d7aaecfdc0045b5c5215e52387a5cedacf705eb9 | 106 | package com.alibaba.otter.canal.store;
public interface BufferMaxSequence {
long getMaxSequence();
}
| 17.666667 | 38 | 0.773585 |
7a63115fc4c25b15bd1fb39c31bde8971174e31e | 3,007 | package com.wilsonburhan.todayintech.base;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
/**
* Created by Wilson on 9/19/2014.
*/
public abstract class BaseProvider extends ContentProvider {
private DbHelper helper;
private BaseLookup lookup;
@Override
public boolean onCreate() {
lookup = new BaseLookup();
addTables(lookup);
helper = new DbHelper(getContext(), getDatabaseName(), null, getDatabaseVersion());
return true;
}
protected abstract String getDatabaseName();
protected abstract int getDatabaseVersion();
protected abstract void addTables(BaseLookup lookup);
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
// use *writable* instead of readable db because helper might need to create or upgrade
SQLiteDatabase db = helper.getWritableDatabase();
BaseTable table = lookup.locate(uri);
if (table != null) {
return table.query(db, uri, projection, selection, selectionArgs, sortOrder);
} else {
return null;
}
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
SQLiteDatabase db = helper.getWritableDatabase();
BaseTable table = lookup.locate(uri);
return table.update(db, uri, values, selection, selectionArgs);
}
@Override
public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase db = helper.getWritableDatabase();
BaseTable table = lookup.locate(uri);
long id = table.insert(db, uri, values);
return Uri.withAppendedPath(uri, String.valueOf(id));
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
SQLiteDatabase db = helper.getWritableDatabase();
BaseTable table = lookup.locate(uri);
return table.delete(db, uri, selection, selectionArgs);
}
@Override
public String getType(Uri uri) {
BaseTable table = lookup.locate(uri);
return table.getType(uri);
}
private class DbHelper extends SQLiteOpenHelper {
public DbHelper(Context context, String name, CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
for(BaseTable table : lookup)
table.onCreate(db);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
for(BaseTable table : lookup)
table.onUpgrade(db, oldVersion, newVersion);
}
}
}
| 31.989362 | 115 | 0.671101 |
cfe8fdb782bdef5fa1701725bd01ba17e910341f | 368 | package com.bisa.health.rest.service;
import com.bisa.health.model.AccessToken;
import com.bisa.health.model.WxUserInfo;
import java.util.Map;
/**
* Created by Administrator on 2017/8/2.
*/
public interface IWxRestService {
public AccessToken getAccesstokenByCode(Map<String,String> param);
public WxUserInfo getWxUserinfo(Map<String,String> param);
}
| 21.647059 | 70 | 0.766304 |
d963b069eb9febf776149aa448b54822c47e7aa0 | 9,069 | package com.dslplatform.json;
import com.dslplatform.json.runtime.Settings;
import org.junit.Assert;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class BuilderTest {
public static class Composite1 {
@JsonAttribute(index = 1)
public final int i;
@JsonAttribute(index = 2, name = "ss")
public final String s;
private Composite1(int i, String s) {
this.i = i;
this.s = s;
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private int i;
private String s;
private Builder() {}
public Builder i(int i) {
this.i = i;
return this;
}
public Builder s(String s) {
this.s = s;
return this;
}
@CompiledJson(formats = {CompiledJson.Format.ARRAY, CompiledJson.Format.OBJECT})
public Composite1 build() {
return new Composite1(i, s);
}
}
}
@CompiledJson(formats = {CompiledJson.Format.ARRAY, CompiledJson.Format.OBJECT})
public static class Composite2 {
@JsonAttribute(index = 1)
public final int i;
@JsonAttribute(index = 2)
public final String s;
private Composite2(int i, String s) {
this.i = i;
this.s = s;
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private int i;
private String s;
private Builder() {}
public Builder i(int i) {
this.i = i;
return this;
}
public Builder s(String s) {
this.s = s;
return this;
}
public Composite2 build() {
return new Composite2(i, s);
}
}
}
public static class Composite3 {
@JsonAttribute(index = 1)
public final int i;
@JsonAttribute(index = 2)
public final String s;
private Composite3(int i, String s) {
this.i = i;
this.s = s;
}
public static class Builder {
private int i;
private String s;
public Builder() {}
public Builder i(int i) {
this.i = i;
return this;
}
public Builder s(String s) {
this.s = s;
return this;
}
@CompiledJson(formats = {CompiledJson.Format.ARRAY, CompiledJson.Format.OBJECT})
public Composite3 build() {
return new Composite3(i, s);
}
}
}
public static abstract class CompositeAbstract {
@JsonAttribute(index = 1, name = "_i")
public abstract int getI();
@JsonAttribute(index = 2)
public abstract String getS();
public static Builder builder() {
return new BuilderImpl();
}
public abstract static class Builder {
public abstract Builder i(int i);
public abstract Builder s(String s);
@CompiledJson(formats = {CompiledJson.Format.ARRAY, CompiledJson.Format.OBJECT})
public abstract CompositeAbstract build();
}
private static class BuilderImpl extends Builder {
private int i;
private String s;
private BuilderImpl() {}
public Builder i(int i) {
this.i = i;
return this;
}
public Builder s(String s) {
this.s = s;
return this;
}
public CompositeAbstract build() {
return new CompositeAbstractImpl(i, s);
}
}
private static class CompositeAbstractImpl extends CompositeAbstract {
private int i;
private String s;
private CompositeAbstractImpl(int i, String s) {
this.i = i;
this.s = s;
}
public int getI() {
return i;
}
public String getS() {
return s;
}
}
}
@CompiledJson(formats = {CompiledJson.Format.ARRAY, CompiledJson.Format.OBJECT})
public static abstract class FreeBuilder {
@JsonAttribute(index = 1, name = "name")
public abstract String name();
@JsonAttribute(index = 2, name = "id", alternativeNames = {"ID"})
public abstract int id();
public static Builder builder() {
return new Builder();
}
public static class Builder extends Employee_Builder {
}
static abstract class Employee_Builder {
private String name;
private int id;
public Builder name(String name) {
this.name = name;
return (Builder) this;
}
public String name() {
return name;
}
public Builder id(int id) {
this.id = id;
return (Builder) this;
}
public int id() {
return id;
}
public FreeBuilder build() {
return new Employee_Builder.Value(this);
}
private static final class Value extends FreeBuilder {
private final String name;
private final int id;
private Value(Employee_Builder builder) {
this.name = builder.name;
this.id = builder.id;
}
@Override
public String name() {
return name;
}
@Override
public int id() {
return id;
}
}
}
}
private final DslJson<Object> dslJsonArray = new DslJson<>(Settings.withRuntime().allowArrayFormat(true).includeServiceLoader());
private final DslJson<Object> dslJsonObject = new DslJson<>(Settings.withRuntime().allowArrayFormat(false).includeServiceLoader());
@Test
public void roundtripBuild() throws IOException {
Composite1 c = Composite1.builder().i(5).s("abc").build();
ByteArrayOutputStream os = new ByteArrayOutputStream();
dslJsonArray.serialize(c, os);
Assert.assertEquals("[5,\"abc\"]", os.toString());
Composite1 res = dslJsonArray.deserialize(Composite1.class, os.toByteArray(), os.size());
Assert.assertEquals(c.i, res.i);
Assert.assertEquals(c.s, res.s);
os.reset();
dslJsonObject.serialize(c, os);
Assert.assertEquals("{\"i\":5,\"ss\":\"abc\"}", os.toString());
res = dslJsonObject.deserialize(Composite1.class, os.toByteArray(), os.size());
Assert.assertEquals(c.i, res.i);
Assert.assertEquals(c.s, res.s);
os.reset();
}
@Test
public void roundtripCtor() throws IOException {
Composite2 c = Composite2.builder().i(5).s("abc").build();
ByteArrayOutputStream os = new ByteArrayOutputStream();
dslJsonArray.serialize(c, os);
Assert.assertEquals("[5,\"abc\"]", os.toString());
Composite2 res = dslJsonArray.deserialize(Composite2.class, os.toByteArray(), os.size());
Assert.assertEquals(c.i, res.i);
Assert.assertEquals(c.s, res.s);
os.reset();
dslJsonObject.serialize(c, os);
Assert.assertEquals("{\"i\":5,\"s\":\"abc\"}", os.toString());
res = dslJsonObject.deserialize(Composite2.class, os.toByteArray(), os.size());
Assert.assertEquals(c.i, res.i);
Assert.assertEquals(c.s, res.s);
os.reset();
}
@Test
public void roundtripNoFactory() throws IOException {
Composite3 c = new Composite3.Builder().i(5).s("abc").build();
ByteArrayOutputStream os = new ByteArrayOutputStream();
dslJsonArray.serialize(c, os);
Assert.assertEquals("[5,\"abc\"]", os.toString());
Composite3 res = dslJsonArray.deserialize(Composite3.class, os.toByteArray(), os.size());
Assert.assertEquals(c.i, res.i);
Assert.assertEquals(c.s, res.s);
os.reset();
dslJsonObject.serialize(c, os);
Assert.assertEquals("{\"i\":5,\"s\":\"abc\"}", os.toString());
res = dslJsonObject.deserialize(Composite3.class, os.toByteArray(), os.size());
Assert.assertEquals(c.i, res.i);
Assert.assertEquals(c.s, res.s);
os.reset();
}
@Test
public void roundtripAbstracts() throws IOException {
CompositeAbstract c = CompositeAbstract.builder().i(5).s("abc").build();
ByteArrayOutputStream os = new ByteArrayOutputStream();
dslJsonArray.serialize(c, os);
Assert.assertEquals("[5,\"abc\"]", os.toString());
CompositeAbstract res = dslJsonArray.deserialize(CompositeAbstract.class, os.toByteArray(), os.size());
Assert.assertEquals(c.getI(), res.getI());
Assert.assertEquals(c.getS(), res.getS());
os.reset();
dslJsonObject.serialize(c, os);
Assert.assertEquals("{\"_i\":5,\"s\":\"abc\"}", os.toString());
res = dslJsonObject.deserialize(CompositeAbstract.class, os.toByteArray(), os.size());
Assert.assertEquals(c.getI(), res.getI());
Assert.assertEquals(c.getS(), res.getS());
os.reset();
}
@Test
public void roundtripNested() throws IOException {
FreeBuilder c = FreeBuilder.builder().id(5).name("abc").build();
ByteArrayOutputStream os = new ByteArrayOutputStream();
dslJsonArray.serialize(c, os);
Assert.assertEquals("[\"abc\",5]", os.toString());
FreeBuilder res = dslJsonArray.deserialize(FreeBuilder.class, os.toByteArray(), os.size());
Assert.assertEquals(c.id(), res.id());
Assert.assertEquals(c.name(), res.name());
os.reset();
dslJsonObject.serialize(c, os);
Assert.assertEquals("{\"name\":\"abc\",\"id\":5}", os.toString());
res = dslJsonObject.deserialize(FreeBuilder.class, os.toByteArray(), os.size());
Assert.assertEquals(c.id(), res.id());
Assert.assertEquals(c.name(), res.name());
byte[] bytes = "{\"name\":\"abc\",\"ID\":5}".getBytes(StandardCharsets.UTF_8);
res = dslJsonObject.deserialize(FreeBuilder.class, bytes, os.size());
Assert.assertEquals(c.id(), res.id());
Assert.assertEquals(c.name(), res.name());
os.reset();
}
}
| 29.734426 | 133 | 0.650899 |
cdd426b6ed97ec399f881cbcc5aeeae830bdc23d | 51 | /**
*
*/
package pl.projewski.bitcoin.commander; | 12.75 | 39 | 0.666667 |
da9cb2e268aeb0da3a054b43d2cbdd12ddac304e | 1,153 | /*L
* Copyright SAIC, Ellumen and RSNA (CTP)
*
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/national-biomedical-image-archive/LICENSE.txt for details.
*/
package gov.nih.nci.nbia.dao;
import java.util.*;
import gov.nih.nci.nbia.searchresult.*;
import gov.nih.nci.nbia.util.TreeNode;
import gov.nih.nci.nbia.dto.ValuesAndCountsDTO;
import gov.nih.nci.nbia.dto.CriteriaValuesForPatientDTO;
import gov.nih.nci.nbia.dto.SpeciesDTO;
import gov.nih.nci.ncia.criteria.*;
import org.springframework.dao.DataAccessException;
public interface ValueAndCountDAO {
public List<ValuesAndCountsDTO> getValuesAndCounts(ValuesAndCountsCriteria criteria) throws DataAccessException;
public List<CriteriaValuesForPatientDTO> patientQuery(ValuesAndCountsCriteria criteria) throws DataAccessException;
public Map<String, ExtendedPatientSearchResult> extendedQuery(ExtendedSearchResultCriteria criteria) throws DataAccessException;
public TreeNode manufacturerTreeQuery(ValuesAndCountsCriteria criteria);
public List<SpeciesDTO> speciesTax(ValuesAndCountsCriteria criteria);
}
| 37.193548 | 130 | 0.799653 |
04f42b5831fa0f6c02f15591244e3b9e8ffe1fe0 | 1,506 | package org.mockserver.model;
import java.nio.charset.Charset;
import static org.mockserver.mappers.ContentTypeMapper.DEFAULT_HTTP_CHARACTER_SET;
/**
* @author jamesdbloom
*/
public class XmlBody extends BodyWithContentType<String> {
public static final MediaType DEFAULT_CONTENT_TYPE = MediaType.create("application", "xml");
private final String xml;
private final byte[] rawBinaryData;
public XmlBody(String xml) {
this(xml, DEFAULT_CONTENT_TYPE);
}
public XmlBody(String xml, Charset charset) {
this(xml, (charset != null ? MediaType.create("application", "xml").withCharset(charset) : null));
}
public XmlBody(String xml, MediaType contentType) {
super(Type.XML, contentType);
this.xml = xml;
if (xml != null) {
this.rawBinaryData = xml.getBytes(determineCharacterSet(contentType, DEFAULT_HTTP_CHARACTER_SET));
} else {
this.rawBinaryData = new byte[0];
}
}
public static XmlBody xml(String xml) {
return new XmlBody(xml);
}
public static XmlBody xml(String xml, Charset charset) {
return new XmlBody(xml, charset);
}
public static XmlBody xml(String xml, MediaType contentType) {
return new XmlBody(xml, contentType);
}
public String getValue() {
return xml;
}
public byte[] getRawBytes() {
return rawBinaryData;
}
@Override
public String toString() {
return xml;
}
}
| 25.1 | 110 | 0.65073 |
16f8cb1c3080837314d71cb0b43d2a6758b9b95c | 1,522 | package uk.me.jasonmarston.domain.validator.impl;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.springframework.beans.BeanWrapperImpl;
import uk.me.jasonmarston.domain.validator.FieldsValueMatch;
public class FieldsValueMatchValidator implements ConstraintValidator<FieldsValueMatch, Object> {
private String field;
private String fieldMatch;
public void initialize(FieldsValueMatch constraintAnnotation) {
this.field = constraintAnnotation.field();
this.fieldMatch = constraintAnnotation.fieldMatch();
}
@SuppressWarnings("deprecation")
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
final Object fieldValue = new BeanWrapperImpl(value)
.getPropertyValue(field);
final Object fieldMatchValue = new BeanWrapperImpl(value)
.getPropertyValue(fieldMatch);
if (fieldValue != null) {
if(fieldValue.equals(fieldMatchValue)) {
return true;
}
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(
context.getDefaultConstraintMessageTemplate())
.addNode(fieldMatch)
.addConstraintViolation();
return false;
} else {
if(fieldMatchValue == null) {
return true;
}
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(
context.getDefaultConstraintMessageTemplate())
.addNode(fieldMatch)
.addConstraintViolation();
return false;
}
}
} | 28.185185 | 97 | 0.769382 |
cba2d2cd899d7183dc31a328819a130b75e784bd | 758 | package com.bluejay.framework.property;
public enum PropertiesEnum {
SERVER_PORT("bluejay.server.port", 8331),
SERVER_HOSTNAME("bluejay.server.hostname", "localhost"),
SERVER_WORKERS("bluejay.server.workers", 0),
SERVER_BUFFER_SIZE("bluejay.server.buffersize", 0),
SERVER_OPTION("bluejay.server.option", "undertow"),
SERVER_DEBUG("bluejay.server.debug", false);
private String propertyName;
private Object defaultValue;
PropertiesEnum(String propertyName, Object defaultValue) {
this.propertyName = propertyName;
this.defaultValue = defaultValue;
}
public String getPropertyName() {
return propertyName;
}
public Object getDefaultValue() {
return defaultValue;
}
}
| 28.074074 | 62 | 0.703166 |
4fd3664bbf798a35dc5da22c791583b685386ebc | 205 | package org.gramat.capturing.edits;
import org.gramat.capturing.models.ObjectModel;
import java.util.Stack;
public interface Edit {
void compile(Stack<ObjectModel> wrappers, Stack<Object> values);
} | 18.636364 | 66 | 0.785366 |
9640c7ffd20edc45fdbcf6018dfe2c3f6b3f765c | 1,738 | package java_impl.concreteTimeFormats;
import java_impl.TimeFormat;
public class SingleSuffixTimeFormat extends TimeFormat {
private static SingleSuffixTimeFormat instance;
/**
* @return object instance of the class
*/
public static SingleSuffixTimeFormat getInstance()
{
if(instance == null)
{
instance = new SingleSuffixTimeFormat();
}
return instance;
}
/**
* Primary method made private in order to enable the Singleton design pattern.
*/
private SingleSuffixTimeFormat(){}
@Override
public String formatSeconds(long seconds) {
if(seconds < 10) // basically turn 3s to 03s
return "0" + seconds + "s";
return seconds + "s";
}
@Override
public String formatMinutes(long minutes) {
if(minutes < 10)
return "0" + minutes + "m";
return minutes + "m";
}
@Override
public String formatHours(long hours) {
if(hours < 10)
return "0" + hours + "h";
return hours + "h";
}
@Override
public String formatDays(long days) {
if(days < 10)
return "0" + days + "d";
return days + "d";
}
@Override
public String formatMonths(long months) {
if(months < 10)
return "0" + months + "M";
return months + "M";
}
@Override
public String formatYears(long years) {
return years + "y";
}
@Override
public String getJoiningCharacter() {
return ":";
}
@Override
public String getLastJoiningCharacter() {
return this.getJoiningCharacter(); // there's no special last joining character here
}
}
| 20.939759 | 92 | 0.575374 |
6fafb3408c6fa9b2323b635ffaa7b13df87b1d69 | 3,209 | package org.firstinspires.ftc.robotcontroller.internal.testcode;
import com.qualcomm.hardware.modernrobotics.ModernRoboticsI2cGyro;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.DcMotorSimple;
import com.qualcomm.robotcore.hardware.GyroSensor;
/**
* Created by juanjose1 on 11/15/16.
*/
public class gyro_method extends LinearOpMode {
DcMotor frontleft;
DcMotor frontright;
DcMotor backleft;
DcMotor backright;
GyroSensor sensorgyro;
ModernRoboticsI2cGyro mrgyro;
@Override
public void runOpMode() throws InterruptedException {
frontleft = hardwareMap.dcMotor.get("frontleft");
frontright = hardwareMap.dcMotor.get("frontright");
backleft = hardwareMap.dcMotor.get("backleft");
backright = hardwareMap.dcMotor.get("backright");
frontright.setDirection(DcMotorSimple.Direction.REVERSE);
frontleft.setDirection(DcMotorSimple.Direction.REVERSE);
sensorgyro = hardwareMap.gyroSensor.get("gyro");
mrgyro = (ModernRoboticsI2cGyro) sensorgyro;
/*frontleft.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
frontright.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
backleft.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
backright.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
idle();
*/
frontleft.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
frontright.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
backleft.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
backright.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
telemetry.addData(">", "Gyro Calibrating. Do Not move!");
telemetry.update();
mrgyro.calibrate();
while (mrgyro.isCalibrating()) {
Thread.sleep(50);
idle();
}
telemetry.addData(">", "Gyro Calibrated. Press Start.");
telemetry.update();
waitForStart();
while (opModeIsActive()) {
turnabsolute(90);
sleep(1000);
turnabsolute(0);
sleep(1000);
}
}
public void turnabsolute(int target) throws InterruptedException{
int zAccumulated = mrgyro.getHeading();
while (Math.abs(zAccumulated - target) > 3) {
if (zAccumulated > target) {
frontleft.setPower(0.15);
frontright.setPower(-0.15);
backleft.setPower(0.15);
backright.setPower(-0.15);
}
if (zAccumulated < target) {
frontleft.setPower(-0.15);
frontright.setPower(0.15);
backleft.setPower(-0.15);
backright.setPower(0.15);
}
zAccumulated = mrgyro.getHeading();
telemetry.addData("1 accu", String.format("03d", zAccumulated));
}
frontleft.setPower(0);
frontright.setPower(0);
backleft.setPower(0);
backright.setPower(0);
telemetry.addData("1 accu", String.format("03d", zAccumulated));
}
}
| 26.303279 | 76 | 0.630103 |
5278488abc2b67a29a7887e2f806f70c9e33e282 | 607 | package L08DataTypeAndVarExercises;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
public class Ex04VarInHex {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
// System.out.println(new BigInteger(reader.readLine().toUpperCase().replace("X",""), 16)); // working also
String hexagon = reader.readLine();
int dec = Integer.parseUnsignedInt(hexagon.substring(2), 16);
System.out.print(dec);
}
}
| 33.722222 | 114 | 0.719934 |
baaf3b767c85a29b6c4eb2bb7ddff1bef6893c03 | 302 | package com.example.lidar_demo.nativeinterface.lidar;
public class LidarSpring {
native public static void print(float[] dist, float[] angle);
native public static void lidar_start();
native public static void lidar_stop();
static {
System.loadLibrary("lidarspring");
}
}
| 25.166667 | 65 | 0.708609 |
e97737d773837ff00719c978a2625aab34b14cfe | 1,507 | /*
* Copyright (C) 2005 - 2013 Jaspersoft Corporation. All rights reserved.
* http://www.jaspersoft.com.
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* 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.
*
* 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jaspersoft.jasperserver.war.util;
/**
* <p></p>
*
* @author yaroslav.kovalchyk
* @version $Id: IsoCalendarFormatProvider.java 48468 2014-08-21 07:47:20Z yuriy.plakosh $
*/
public class IsoCalendarFormatProvider extends DefaultCalendarFormatProvider {
@Override
protected String getDatetimeFormatPattern() {
return "yyyy-MM-dd'T'HH:mm:ss";
}
@Override
protected String getTimeFormatPattern() {
return "HH:mm:ss";
}
@Override
protected String getDateFormatPattern() {
return "yyyy-MM-dd";
}
}
| 33.488889 | 91 | 0.704711 |
eb7db337b7dea22a1cab32b1a17a572cdf3e5b25 | 2,126 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/gkehub/v1/configmanagement/configmanagement.proto
package com.google.cloud.gkehub.configmanagement.v1;
public interface HierarchyControllerStateOrBuilder extends
// @@protoc_insertion_point(interface_extends:google.cloud.gkehub.configmanagement.v1.HierarchyControllerState)
com.google.protobuf.MessageOrBuilder {
/**
* <pre>
* The version for Hierarchy Controller
* </pre>
*
* <code>.google.cloud.gkehub.configmanagement.v1.HierarchyControllerVersion version = 1;</code>
* @return Whether the version field is set.
*/
boolean hasVersion();
/**
* <pre>
* The version for Hierarchy Controller
* </pre>
*
* <code>.google.cloud.gkehub.configmanagement.v1.HierarchyControllerVersion version = 1;</code>
* @return The version.
*/
com.google.cloud.gkehub.configmanagement.v1.HierarchyControllerVersion getVersion();
/**
* <pre>
* The version for Hierarchy Controller
* </pre>
*
* <code>.google.cloud.gkehub.configmanagement.v1.HierarchyControllerVersion version = 1;</code>
*/
com.google.cloud.gkehub.configmanagement.v1.HierarchyControllerVersionOrBuilder getVersionOrBuilder();
/**
* <pre>
* The deployment state for Hierarchy Controller
* </pre>
*
* <code>.google.cloud.gkehub.configmanagement.v1.HierarchyControllerDeploymentState state = 2;</code>
* @return Whether the state field is set.
*/
boolean hasState();
/**
* <pre>
* The deployment state for Hierarchy Controller
* </pre>
*
* <code>.google.cloud.gkehub.configmanagement.v1.HierarchyControllerDeploymentState state = 2;</code>
* @return The state.
*/
com.google.cloud.gkehub.configmanagement.v1.HierarchyControllerDeploymentState getState();
/**
* <pre>
* The deployment state for Hierarchy Controller
* </pre>
*
* <code>.google.cloud.gkehub.configmanagement.v1.HierarchyControllerDeploymentState state = 2;</code>
*/
com.google.cloud.gkehub.configmanagement.v1.HierarchyControllerDeploymentStateOrBuilder getStateOrBuilder();
}
| 33.21875 | 115 | 0.724365 |
b2cb7ee4ed1d70124c3d26e9fc0db8fe78409eb9 | 1,662 | package cech12.brickhopper.init;
import cech12.brickhopper.BrickHopperMod;
import cech12.brickhopper.api.block.BrickHopperBlocks;
import cech12.brickhopper.block.BrickHopperBlock;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.material.Material;
import net.minecraft.world.level.material.MaterialColor;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.CreativeModeTab;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraft.world.level.block.state.BlockBehaviour;
@Mod.EventBusSubscriber(modid= BrickHopperMod.MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD)
public final class ModBlocks {
@SubscribeEvent
public static void registerBlocks(RegistryEvent.Register<Block> event) {
BrickHopperBlocks.BRICK_HOPPER = registerBlock("brick_hopper", CreativeModeTab.TAB_REDSTONE, new BrickHopperBlock(BlockBehaviour.Properties.of(Material.STONE, MaterialColor.COLOR_RED).requiresCorrectToolForDrops().strength(2.0F, 6.0F).noOcclusion()));
}
public static Block registerBlock(String name, CreativeModeTab itemGroup, Block block) {
Item.Properties itemProperties = new Item.Properties().tab(itemGroup);
BlockItem itemBlock = new BlockItem(block, itemProperties);
block.setRegistryName(name);
itemBlock.setRegistryName(name);
ForgeRegistries.BLOCKS.register(block);
ForgeRegistries.ITEMS.register(itemBlock);
return block;
}
} | 44.918919 | 259 | 0.796631 |
6383a26b60c2c283cc272d33e587fb6c70349904 | 765 | package net.dongliu.proxy.netty.codec.frame;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.http2.Http2FrameTypes;
/**
* Whole http2 headers
*/
public class Http2GoAwayEvent extends Http2Event {
private final int lastStreamId;
private final long errorCode;
private final ByteBuf debugData;
public Http2GoAwayEvent(int lastStreamId, long errorCode, ByteBuf debugData) {
super(Http2FrameTypes.GO_AWAY);
this.lastStreamId = lastStreamId;
this.errorCode = errorCode;
this.debugData = debugData;
}
public int lastStreamId() {
return lastStreamId;
}
public long errorCode() {
return errorCode;
}
public ByteBuf debugData() {
return debugData;
}
}
| 22.5 | 82 | 0.684967 |
47c50f825d18b27de05984f684f14d3beb5fc279 | 1,284 | package simulator.netty.serverCommands;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Vector;
import simulator.netty.ServerCommand;
public class SpaceMapStationsCommand
implements ServerCommand {
public static int ID = 15562;
public double var_2893 = 0;
public Vector<SpaceMapStationModule> stations;
public SpaceMapStationsCommand(double param1, Vector<SpaceMapStationModule> pStations) {
this.var_2893 = param1;
this.stations = pStations;
}
public int getID() {
return ID;
}
public int method_1005() {
return 12;
}
public void write(DataOutputStream out) {
try {
out.writeShort(ID);
this.writeInternal(out);
} catch (IOException e) {
e.printStackTrace();
}
}
protected void writeInternal(DataOutputStream out) {
try {
out.writeShort(-14172);
out.writeInt(this.stations.size());
for (SpaceMapStationModule c : this.stations) {
c.write(out);
}
out.writeShort(-6389);
out.writeDouble(this.var_2893);
} catch (IOException e) {
e.printStackTrace();
}
}
} | 25.176471 | 92 | 0.596573 |
fcae84b224b58d657d28a2f8a0cba25f1a9265da | 433 | package com.orientechnologies.orient.object.db.entity;
/**
* Created by tglman on 09/05/16.
*/
public class LoopEntity {
private LoopEntityLink link;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public LoopEntityLink getLink() {
return link;
}
public void setLink(LoopEntityLink link) {
this.link = link;
}
}
| 16.037037 | 54 | 0.658199 |
97ce76bd26c8e71f2a4791ad59f2d1111e81b506 | 1,001 | /*
* Copyright (c) 2012-2017 ZoxWeb.com LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.zoxweb.shared.data;
import org.zoxweb.shared.util.CRUD;
import org.zoxweb.shared.util.CRUDEvent;
/**
*
*/
@SuppressWarnings("serial")
public abstract class CRUDEventDAO
implements CRUDEvent
{
protected CRUD crud;
protected CRUDEventDAO(CRUD crud)
{
this.crud = crud;
}
@Override
public CRUD getCRUD()
{
return crud;
}
} | 23.833333 | 81 | 0.699301 |
1548d2a444e8ecc0094733ca3b390ee4316c12f1 | 724 | package com.kuroha.algorithm.find;
/**
* 二分查找
* @author kuroha
*/
public class BinarySearch {
public static int find(int[] data,int num) {
int low = 0;
int high = data.length;
int mid;
while (true) {
if (low > high) {
return -1;
}
mid = low + ((high-low)>>1);
if (data[mid] > num) {
high = mid - 1;
} else if (data[mid] < num) {
low = mid + 1;
} else {
return mid;
}
}
}
public static void main(String[] args) {
int[] data = new int[] {1,4,5,7,24,35,66,475};
System.out.println(find(data,8));
}
}
| 21.294118 | 54 | 0.422652 |
c65b27f59a2c55e3a40015465be65d2441a60021 | 2,852 | /*
* All GTAS code is Copyright 2016, The Department of Homeland Security (DHS), U.S. Customs and Border Protection (CBP).
*
* Please see LICENSE.txt for details.
*/
package gov.gtas.services.search;
import java.util.Date;
public class IndexedPassengerVo {
private String title;
private String firstName;
private String middleName;
private String lastName;
private String suffix;
private String gender;
private String citizenshipCountry;
private String residencyCountry;
private String passengerType;
private Integer age;
private Date dob;
private String embarkation;
private String debarkation;
private String raw;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getSuffix() {
return suffix;
}
public void setSuffix(String suffix) {
this.suffix = suffix;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getCitizenshipCountry() {
return citizenshipCountry;
}
public void setCitizenshipCountry(String citizenshipCountry) {
this.citizenshipCountry = citizenshipCountry;
}
public String getResidencyCountry() {
return residencyCountry;
}
public void setResidencyCountry(String residencyCountry) {
this.residencyCountry = residencyCountry;
}
public String getPassengerType() {
return passengerType;
}
public void setPassengerType(String passengerType) {
this.passengerType = passengerType;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public String getEmbarkation() {
return embarkation;
}
public void setEmbarkation(String embarkation) {
this.embarkation = embarkation;
}
public String getDebarkation() {
return debarkation;
}
public void setDebarkation(String debarkation) {
this.debarkation = debarkation;
}
public String getRaw() {
return raw;
}
public void setRaw(String raw) {
this.raw = raw;
}
}
| 25.693694 | 120 | 0.646564 |
f8e5dca71beabef3ace2cf9f4e44ac9a3555a034 | 182 | package org.testory.proxy.testing;
public class ConcreteClassWithPrivateConstructorWithArguments {
private ConcreteClassWithPrivateConstructorWithArguments(Object arguments) {}
}
| 30.333333 | 79 | 0.868132 |
a8e3d6e0036556d988a05da6e13a8ba66fdf4b4f | 3,662 | /*******************************************************************************
* BSD 3-Clause License
*
* Copyright (c) 2017 Beshr Al Nahas and Olaf Landsiedel.
* 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 the copyright holder 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 HOLDER 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.
*******************************************************************************/
log.log("Script started.\n");
//sim.stopSimulation();
//sim.startSimulation();
//5min*60sec*1000ms*1000us
timeout=5*60*1000*1000;
var timeSlice = 1*60*1000*1000; //1 min in us
var step = 0;
var t0 = 0;
globalClusterSize=4;
globalDistance=1000;
function clusterNodes(clusterSize, distance){
count=sim.getMotesCount();
for(i=0; i<count/clusterSize; i++){
moveCluster(i, clusterSize, distance);
}
}
function moveCluster(i, clusterSize, distance){
for(j=i*clusterSize; j<i*clusterSize+clusterSize; j++){
var mm = sim.getMoteWithID(j+1);
var x = mm.getInterfaces().getPosition().getXCoordinate();
var y = mm.getInterfaces().getPosition().getYCoordinate();
var z = 0.0;
x=i * distance;
y=j-i*clusterSize;
mm.getInterfaces().getPosition().setCoordinates(x, y, z);
}
}
/* create a log file */
date = new java.util.Date();
path = sim.getCooja().currentConfigFile.getParentFile();
logFileName = "\/log-" + sim.getTitle() + '-' + date.toString()
logFileName=logFileName.replaceAll(':', '.').replaceAll(' ', '_') +".txt";
logFilePath = path + logFileName;
outputFile = new java.io.FileWriter(logFilePath);
log.log(logFilePath+"\n");
outputFile.write(logFilePath);
/* set a new random seed */
sim.setRandomSeed(java.lang.System.currentTimeMillis());
seedStr = "New random seed: " + sim.getRandomSeedString() + "\n";
outputFile.write(seedStr);
log.log(seedStr);
clusterNodes(globalClusterSize, globalDistance);
var startTime = time;
while (time-startTime < timeout) {
// logMsg = time + "\tID:" + id + "\t" + msg + "\n";
// //log to file
// outputFile.write(logMsg);
if((time-t0 > step * timeSlice)) {
moveCluster(step, globalClusterSize, globalDistance);
t0 = time;
step++;
}
//log.log(logMsg);
YIELD();
}
//Close the log file
outputFile.close();
//Rethrow exception again, to end the script.
throw('test script finished ' + time); | 36.257426 | 81 | 0.690879 |
9a8e30a85ecb1487a706fd62f8ed054424bde308 | 1,431 | package me.javaee.ffa.information.commands.argments;
import me.javaee.ffa.FFA;
import me.javaee.ffa.information.Information;
import me.javaee.ffa.utils.command.CommandArgument;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class StopKothArgument extends CommandArgument {
public StopKothArgument() {
super("stopkoth", null, "stop");
}
@Override public String getUsage(String label) {
return ChatColor.RED + "/" + label + " " + getName();
}
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (sender instanceof Player) {
Player player = (Player) sender;
if (args.length != 1) {
player.sendMessage(getUsage(label));
return true;
}
Information information = FFA.getPlugin().getInformationManager().getInformation();
if (!information.isKothStarted()) {
player.sendMessage(ChatColor.RED + "The koth isn't enabled.");
return true;
}
information.setKothStarted(false);
Bukkit.broadcastMessage(ChatColor.translateAlternateColorCodes('&', "&6[KingOfTheHill] &eThe &9Koth &ehas been shut down. &7(10:00)"));
}
return true;
}
}
| 33.27907 | 147 | 0.646401 |
bbce55ce320dff955204242e0cc41ec33aad693b | 380 | package com.example.zhang.test;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import com.example.zhang.test.R;
public class AboutUs extends Activity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.about);
}
}
| 23.75 | 66 | 0.752632 |
e48f40dccd46c789c6f15510cae95f9f0371258d | 575 | package com.headless.ecommerce.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import com.headless.ecommerce.domain.Category;
@Service
public class CategoryService {
@Autowired
private MongoTemplate mongoTemplate;
public Category getCategory(String id) {
return mongoTemplate.findById(id, Category.class);
}
public Category saveCategory(Category category) {
return mongoTemplate.save(category);
}
}
| 26.136364 | 62 | 0.773913 |
dc9c0abb934a9878714bcaddbea86834724ed07b | 13,922 | /*
* Copyright 2002.2.rc1710017 Barcelona Supercomputing Center (www.bsc.es)
*
* 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 es.bsc.compss.ui;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.zkoss.bind.annotation.BindingParam;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.GlobalCommand;
import org.zkoss.bind.annotation.Init;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.zk.ui.Session;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zul.Messagebox;
import es.bsc.compss.commons.Loggers;
import es.bsc.compss.ui.auth.UserCredential;
import monitoringParsers.*;
public class ViewModel {
private ResourcesViewModel resourcesViewModel;
private CoresViewModel coresViewModel;
private CurrentGraphViewModel currentGraphViewModel;
private CompleteGraphViewModel completeGraphViewModel;
private LoadChartViewModel loadChartViewModel;
private RuntimeLogViewModel runtimeLogViewModel;
private ExecutionInformationViewModel executionInformationViewModel;
private StatisticsViewModel statisticsViewModel;
private String selectedTab;
private static int runtimeLogConfirmation = -1; // -1: do not apply, 0: accepted, 1:denied
private static final Logger logger = LogManager.getLogger(Loggers.UI_VMS);
@Init
public void init() {
logger.debug("Initializing Resources ViewModel Structure...");
resourcesViewModel = new ResourcesViewModel();
resourcesViewModel.init();
logger.debug("Initializing Tasks ViewModel Structure...");
coresViewModel = new CoresViewModel();
coresViewModel.init();
logger.debug("Initializing Current Graph ViewModel Structure...");
currentGraphViewModel = new CurrentGraphViewModel();
currentGraphViewModel.init();
logger.debug("Initializing Complete Graph ViewModel Structure...");
completeGraphViewModel = new CompleteGraphViewModel();
completeGraphViewModel.init();
logger.debug("Initializing Resources Load Chart ViewModel Structure...");
loadChartViewModel = new LoadChartViewModel();
loadChartViewModel.init();
logger.debug("Initializing it.log Structure...");
runtimeLogViewModel = new RuntimeLogViewModel();
runtimeLogViewModel.init();
logger.debug("Initializing Execution Information Structure...");
executionInformationViewModel = new ExecutionInformationViewModel();
executionInformationViewModel.init();
logger.debug("Initializing Statistics Structure...");
statisticsViewModel = new StatisticsViewModel();
statisticsViewModel.init();
logger.debug("Initalizing private structures...");
selectedTab = new String(Constants.resourcesInformationTabName);
logger.info("Initialization DONE");
// Update information
update();
}
public ResourcesViewModel getResourcesViewModel() {
return this.resourcesViewModel;
}
public CoresViewModel getCoresViewModel() {
return this.coresViewModel;
}
public CurrentGraphViewModel getCurrentGraphViewModel() {
return this.currentGraphViewModel;
}
public CompleteGraphViewModel getCompleteGraphViewModel() {
return this.completeGraphViewModel;
}
public LoadChartViewModel getLoadChartViewModel() {
return this.loadChartViewModel;
}
public RuntimeLogViewModel getRuntimeLogViewModel() {
return this.runtimeLogViewModel;
}
public ExecutionInformationViewModel getExecutionInformationViewModel() {
return this.executionInformationViewModel;
}
public StatisticsViewModel getStatisticsViewModel() {
return this.statisticsViewModel;
}
public int getRefreshTime() {
return Properties.getRefreshTime();
}
@Command
@NotifyChange({ "resourcesViewModel", "coresViewModel", "currentGraphViewModel", "completeGraphViewModel", "loadChartViewModel",
"runtimeLogViewModel", "executionInformationViewModel", "statisticsViewModel" })
public void select(@BindingParam("selectedTab") String selectedTab) {
if (!this.selectedTab.equals(selectedTab)) {
this.selectedTab = selectedTab;
// Runtime log message box protection
if (selectedTab.equals(Constants.runtimeLogTabName)) {
logger.debug("Trying to load runtime.log, displaying messagebox");
runtimeLogConfirmation = -1;
Messagebox.show(
"The runtime.log can be huge and you may experience slowness loading this tab. Do you really want to load it?",
"Warning", Messagebox.OK | Messagebox.CANCEL, Messagebox.QUESTION, new EventListener<Event>() {
public void onEvent(Event e) {
if (Messagebox.ON_OK.equals(e.getName())) {
runtimeLogConfirmation = 0;
} else {
runtimeLogConfirmation = 1;
}
}
});
} else {
// Normal tab selection
this.update();
this.updateRuntimeLog();
this.updateExecutionInformation();
}
}
}
@Command
@NotifyChange({ "resourcesViewModel", "coresViewModel", "currentGraphViewModel", "completeGraphViewModel", "loadChartViewModel",
"statisticsViewModel", "runtimeLogViewModel" })
public void update() {
logger.debug("Loading Monitored Application...");
Application monitoredApp = new Application();
Session session = Sessions.getCurrent();
if (session != null) {
UserCredential userCred = ((UserCredential) session.getAttribute("userCredential"));
if (userCred != null) {
monitoredApp = userCred.getMonitoredApp();
}
}
logger.info("Loaded Monitored Application: " + monitoredApp.getName());
if (monitoredApp.getName() != "") {
if (selectedTab.equals(Constants.resourcesInformationTabName)) {
logger.debug("Updating Resources Information...");
// Monitor XML parse
logger.debug("Parsing Monitor XML File...");
MonitorXmlParser.parseResources();
logger.debug("Monitor XML File parsed");
// Update
resourcesViewModel.update(MonitorXmlParser.getWorkersDataArray());
logger.info("Structures updated");
} else if (selectedTab.equals(Constants.tasksInformationTabName)) {
logger.debug("Updating Jobs Information...");
// Monitoring parse
logger.debug("Parsing Monitor XML File...");
MonitorXmlParser.parseCores();
logger.debug("Monitor XML File parsed");
// Update
coresViewModel.update(MonitorXmlParser.getCoresDataArray());
logger.info("Structures updated");
} else if (selectedTab.equals(Constants.currentTasksGraphTabName)) {
logger.debug("Updating Current Tasks Graph...");
// Monitor XML parse
logger.debug("Parsing Monitor XML File...");
MonitorXmlParser.parseCores();
logger.debug("Monitor XML File parsed");
// Update
coresViewModel.update(MonitorXmlParser.getCoresDataArray());
currentGraphViewModel.update(monitoredApp);
logger.info("Structures updated");
} else if (selectedTab.equals(Constants.completeTasksGraphTabName)) {
logger.debug("Updating Complete Tasks Graph...");
// Monitor XML parse
logger.debug("Parsing Monitor XML File...");
MonitorXmlParser.parseCores();
logger.debug("Monitor XML File parsed");
// Update
coresViewModel.update(MonitorXmlParser.getCoresDataArray());
completeGraphViewModel.update(monitoredApp);
logger.info("Structures updated");
} else if (selectedTab.equals(Constants.loadChartTabName)) {
logger.debug("Updating Resouces Load Chart...");
// Update
loadChartViewModel.update();
logger.info("Structures updated");
} else if (selectedTab.equals(Constants.statisticsTabName)) {
logger.debug("Updating statistics...");
// Monitor XML parse
logger.debug("Parsing Monitor XML File...");
MonitorXmlParser.parseStatistics();
logger.debug("Monitor XML File parsed");
// Update
statisticsViewModel.update(MonitorXmlParser.getStatisticsParameters());
logger.info("Structures updated");
} else if (selectedTab.equals(Constants.runtimeLogTabName)) {
// Wait for messagebox handler. If already answered do nothing because this tab has no automatic update
// Check messagebox result
if (runtimeLogConfirmation == 0) {
logger.debug("Messagebox confirmation received. Loading runtime.log");
this.updateRuntimeLog();
// Reset messagebox handler to avoid automatic refresh
runtimeLogConfirmation = -1;
} else if (runtimeLogConfirmation == 1) {
logger.debug("Messagebox denied");
// Reset messagebox handler to avoid automatic refresh
runtimeLogConfirmation = -1;
}
} else if (selectedTab.equals(Constants.executionInformationTabName)) {
// Nothing to do. This tab doesn't have automatic update
} else {
logger.info("No Information Tab selected");
}
} else {
resourcesViewModel.clear();
coresViewModel.clear();
currentGraphViewModel.clear();
completeGraphViewModel.clear();
loadChartViewModel.clear();
statisticsViewModel.clear();
runtimeLogViewModel.clear();
logger.info("No Application Selected");
}
}
@Command
@NotifyChange("runtimeLogViewModel")
public void updateRuntimeLog() {
logger.debug("Loading Monitored Application...");
Application monitoredApp = new Application();
Session session = Sessions.getCurrent();
if (session != null) {
UserCredential userCred = ((UserCredential) session.getAttribute("userCredential"));
if (userCred != null) {
monitoredApp = userCred.getMonitoredApp();
}
}
logger.debug("Loaded Monitored Application: " + monitoredApp.getName());
logger.debug("Updating RuntimeLog...");
if (monitoredApp.getName() != "") {
if (selectedTab.equals(Constants.runtimeLogTabName)) {
runtimeLogViewModel.update();
} else {
runtimeLogViewModel.clear();
}
} else {
runtimeLogViewModel.clear();
}
logger.info("Runtime.log updated");
}
@Command
@NotifyChange("executionInformationViewModel")
public void updateExecutionInformation() {
logger.debug("Loading Monitored Application...");
Application monitoredApp = new Application();
Session session = Sessions.getCurrent();
if (session != null) {
UserCredential userCred = ((UserCredential) session.getAttribute("userCredential"));
if (userCred != null) {
monitoredApp = userCred.getMonitoredApp();
}
}
logger.debug("Loaded Monitored Application: " + monitoredApp.getName());
logger.debug("Updating Execution Information...");
if (monitoredApp.getName() != "") {
if (selectedTab.equals(Constants.executionInformationTabName)) {
executionInformationViewModel.update();
}
} else {
executionInformationViewModel.clear();
}
logger.info("Execution Information updated");
}
@Command
@NotifyChange("loadChartViewModel")
public void setDivUUID(@BindingParam("divuuid") String divuuid) {
loadChartViewModel.setDivUUID(divuuid);
}
@Command
public void downloadCompleteGraph() {
completeGraphViewModel.download();
}
@Command
public void downloadCurrentGraph() {
currentGraphViewModel.download();
}
@GlobalCommand
@NotifyChange({ "resourcesViewModel", "coresViewModel", "currentGraphViewModel", "completeGraphViewModel", "loadChartViewModel",
"runtimeLogViewModel", "executionInformationViewModel", "statisticsViewModel" })
public void refresh() {
this.update();
this.updateRuntimeLog();
this.updateExecutionInformation();
}
}
| 40.121037 | 135 | 0.626059 |
5231663f369cba74d3651c6af01bb7ee44bf6f0c | 1,371 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.monitor.models;
import com.azure.core.util.ExpandableStringEnum;
import com.fasterxml.jackson.annotation.JsonCreator;
import java.util.Collection;
/** Defines values for OnboardingStatus. */
public final class OnboardingStatus extends ExpandableStringEnum<OnboardingStatus> {
/** Static value onboarded for OnboardingStatus. */
public static final OnboardingStatus ONBOARDED = fromString("onboarded");
/** Static value notOnboarded for OnboardingStatus. */
public static final OnboardingStatus NOT_ONBOARDED = fromString("notOnboarded");
/** Static value unknown for OnboardingStatus. */
public static final OnboardingStatus UNKNOWN = fromString("unknown");
/**
* Creates or finds a OnboardingStatus from its string representation.
*
* @param name a name to look for.
* @return the corresponding OnboardingStatus.
*/
@JsonCreator
public static OnboardingStatus fromString(String name) {
return fromString(name, OnboardingStatus.class);
}
/** @return known OnboardingStatus values. */
public static Collection<OnboardingStatus> values() {
return values(OnboardingStatus.class);
}
}
| 36.078947 | 84 | 0.739606 |
ae6d18049fbdecdf3639b783582ccc529128f69e | 1,434 | package com.futuristic.breweryclient.web.client;
import com.futuristic.breweryclient.web.model.BeerDto;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.net.URI;
import java.util.UUID;
/**
* aditya created on 26/01/20
*/
@Component
@ConfigurationProperties(value = "micserv.brewery", ignoreUnknownFields = false)
public class BreweryClient {
public final String BEER_PATH = "/api/v1/beer/";
private String apihost;
private final RestTemplate restTemplate;
public void setApihost(String apihost) {
this.apihost = apihost;
}
public BreweryClient(RestTemplateBuilder restTemplateBuilder) {
this.restTemplate = restTemplateBuilder.build();
}
public BeerDto getBeerById(UUID uuid) {
return restTemplate.getForObject(apihost + BEER_PATH + UUID.randomUUID().toString(), BeerDto.class);
}
public URI saveBeer(BeerDto beerDto) {
return restTemplate.postForLocation(apihost+BEER_PATH , beerDto);
}
public void updateBeer(UUID uuid, BeerDto beerDto) {
restTemplate.put(apihost + BEER_PATH + UUID.randomUUID().toString(), beerDto);
}
public void deleteBeer(UUID uuid) {
restTemplate.delete(apihost + BEER_PATH + uuid);
}
}
| 31.173913 | 108 | 0.739888 |
83bf3fa14964959fd884e991693ad6c7e9864b63 | 314 | package fr.flavi1.flap.android;
public interface ActionResolver {
public boolean getSignedInGPGS();
public void loginGPGS();
public void submitScoreGPGS(int score);
public void unlockAchievementGPGS(String achievementId);
public void getLeaderboardGPGS();
public void getAchievementsGPGS();
} | 31.4 | 59 | 0.770701 |
5c4b5b770a7d2553d63b94338c9913078387f438 | 333 | package test;
import methods.FloatingMenuMethod;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
public class FloatingMenuTest extends FloatingMenuMethod {
@Test
public void floatingMenuTest() {
startFloatingMenuTest();
assertTrue(isMenuDisplayed(), "menu is not displayed");
}
}
| 23.785714 | 63 | 0.735736 |
0ec306c124b5233059ad6d347f76c9871e622688 | 1,530 | package com.willlee.algorithms.recursion;
public class BinarySearch {
public static void main(String[] args) {
int maxSize = 100;
BinarySearch arr;
arr = new BinarySearch(maxSize);
arr.insert(72);
arr.insert(90);
arr.insert(126);
arr.insert(354);
arr.insert(399);
arr.insert(144);
arr.insert(135);
arr.insert(9);
arr.insert(117);
arr.display();
int searchKey = 9;
if (arr.find(searchKey) != arr.size()) {
System.out.println("Found " + searchKey);
} else {
System.out.println("Can't find " + searchKey);
}
}
private long[] a;
private int nElems;
public BinarySearch(int max) {
a = new long[max];
nElems = 0;
}
public int size() {
return nElems;
}
public void insert(long value) {
int j;
for (j = 0; j < nElems; j++) {
if (a[j] > value)
break;
}
for (int k = nElems; k > j; k--) {
a[k] = a[k - 1];
}
a[j] = value;
nElems++;
}
public void display() {
for (int j = 0; j < nElems; j++) {
System.out.print(a[j] + " ");
}
System.out.println();
}
public int find(long searchKey) {
return recFind(searchKey, 0, nElems - 1);
}
private int recFind(long searchKey, int lowerBound, int upperBound) {
int curIn;
curIn = (lowerBound + upperBound) / 2;
if (a[curIn] == searchKey) {
return curIn;
} else if (lowerBound > upperBound) {
return nElems;
} else {
if (a[curIn] < searchKey) {
return recFind(searchKey, curIn + 1, upperBound);
} else {
return recFind(searchKey, lowerBound, curIn - 1);
}
}
}
}
| 18.888889 | 70 | 0.603922 |
151d08dccab78c8221234d30147ab40377a74903 | 923 | package org.aksw.rdfunit.io.writer;
import org.aksw.jena_sparql_api.core.QueryExecutionFactory;
import java.util.Collection;
/**
* <p>RDFMultipleWriter class.</p>
*
* @author Dimitris Kontokostas
* Description
* @since 11/14/13 1:13 PM
* @version $Id: $Id
*/
public class RdfMultipleWriter implements RdfWriter {
private final Collection<RdfWriter> writers;
/**
* <p>Constructor for RDFMultipleWriter.</p>
*
* @param writers a {@link java.util.Collection} object.
*/
public RdfMultipleWriter(Collection<RdfWriter> writers) {
super();
this.writers = writers;
}
/** {@inheritDoc} */
@Override
public void write(QueryExecutionFactory model) throws RdfWriterException {
//TODO check for early exceptions
for (RdfWriter w : writers) {
if (w != null) {
w.write(model);
}
}
}
}
| 23.666667 | 78 | 0.619718 |
04fd0cb0d2b8f70070e01ffee761bf90edbc11b3 | 2,735 | /*
* See LICENSE file in distribution for copyright and licensing
* information.
*/
package ioke.lang.coverage;
import java.util.HashMap;
import java.util.Map;
import ioke.lang.Interpreter;
import ioke.lang.IokeObject;
import ioke.lang.IokeRegistry;
import ioke.lang.Message;
import ioke.lang.exceptions.ControlFlow;
/**
* @author <a href="mailto:ola.bini@gmail.com">Ola Bini</a>
*/
public class CoverageInterpreter extends Interpreter {
public static class CoveragePoint {
String filename;
String name;
int line;
int pos;
IokeObject message;
public int count = 0;
@Override
public String toString() {
return "CoveragePoint<" + filename + ":" + line + ":" + pos
+ " - " + name + "(" + count + ")>";
}
}
public final Map<String, Map<String, CoveragePoint>> covered = new HashMap<>();
private boolean covering = true;
public void stopCovering() {
covering = false;
}
private void cover(IokeObject message) throws ControlFlow {
if (covering) {
CoveragePoint cp = new CoveragePoint();
cp.filename = Message.file(message);
cp.name = Message.name(message);
cp.line = Message.line(message);
cp.pos = Message.position(message);
cp.message = message;
Map<String, CoveragePoint> perLinePos = covered
.get(cp.filename);
if (perLinePos == null) {
perLinePos = new HashMap<>();
covered.put(cp.filename, perLinePos);
}
CoveragePoint cp2 = perLinePos
.get("" + cp.line + ":" + cp.pos);
if (cp2 == null) {
cp2 = cp;
perLinePos.put("" + cp.line + ":" + cp.pos, cp2);
}
cp2.count++;
}
}
@Override
public Object evaluate(IokeObject self, IokeObject ctx, Object ground,
Object receiver) throws ControlFlow {
ioke.lang.Runtime runtime = self.runtime;
Object current = receiver;
Object tmp = null;
String name = null;
Object lastReal = runtime.getNil();
IokeObject m = self;
Message msg;
while (m != null) {
msg = (Message) m.data;
tmp = msg.cached;
cover(m);
if (tmp != null) {
lastReal = current = tmp;
} else if ((name = msg.name.intern()) == ".") {
current = ctx;
} else if (name.length() > 0 && msg.arguments.size() == 0
&& name.charAt(0) == ':') {
lastReal = msg.cached = current = runtime
.getSymbol(name.substring(1));
} else {
if ((current instanceof IokeObject)
|| IokeRegistry.isWrapped(current, ctx)) {
IokeObject recv = IokeObject.as(current, ctx);
tmp = perform(recv, recv, ctx, m, name);
} else {
tmp = perform(current,
IokeRegistry.wrap(current.getClass(), ctx),
ctx, m, name);
}
lastReal = current = tmp;
}
m = Message.next(m);
}
return lastReal;
}
}// CoverageInterpreter
| 24.863636 | 81 | 0.634735 |
3693cd69675fa8aa92f5d5f6ffeda6e1cede0489 | 1,545 | package gui;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.io.File;
import javax.swing.UIManager;
import util.EnFrString;
import util.Log;//TODO remove
public class FileChooser extends JFileChooser
{
private static EnFrString title = new EnFrString("Choose a file", "Choisir un fichier");
private static EnFrString filterName = new EnFrString("XML file", "fichier XML");
public FileChooser(boolean dirChoiceEnabled)
{
this(title.toString(), dirChoiceEnabled);
//TODO REMOVE THIS PART
// try {
// UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
// } catch (Exception e) {
// Log.err("Couldn't set file chooser's window theme.");
// }
// super.updateUI();
// try {
// UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
// } catch (Exception e) {
// Log.err("Couldn't get system's window theme.");
// }
//TODO UNTIL HERE
}
public FileChooser(String windowTitle, boolean dirChoiceEnabled)
{
super();
setCurrentDirectory(new File("."));
setDialogTitle(windowTitle);
if (dirChoiceEnabled)
setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
else
setFileSelectionMode(JFileChooser.FILES_ONLY);
setFileFilter(new FileNameExtensionFilter(filterName.toString(), "xml"));
}
public String getFileSelected()
{
if (showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
return getSelectedFile().toString();
}
else
return null;
}
}
| 27.589286 | 89 | 0.71521 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.