repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
klaskoski/become-a-full-stack-developer-with-spring-aws-and-stripe | src/main/java/com/training/fullstack/backend/repositories/UserRepository.java | 967 | package com.training.fullstack.backend.repositories;
import com.training.fullstack.backend.domain.backend.User;
import org.hibernate.validator.constraints.ParameterScriptAssert;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
@Repository
@Transactional(readOnly = true)
public interface UserRepository extends CrudRepository<User, Long> {
User findByUsername(String username);
User findByEmail(String email);
@Modifying
@Query("update User u set u.password = :password where u.id = :userId")
void updateUserPassword(@Param("userId") long userId, @Param("password") String password);
}
| mit |
openwebnet/openwebnet-android | app/src/main/java/com/github/openwebnet/view/ChangeLogDialogFragment.java | 1694 | package com.github.openwebnet.view;
import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import com.github.openwebnet.R;
import it.gmariotti.changelibs.library.view.ChangeLogRecyclerView;
public class ChangeLogDialogFragment extends DialogFragment {
private static final String TAG_FRAGMENT = "changelog_dialog";
public ChangeLogDialogFragment() {}
public static void show(AppCompatActivity activity) {
DialogFragment dialogFragment = new ChangeLogDialogFragment();
FragmentManager fm = activity.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Fragment prev = fm.findFragmentByTag(TAG_FRAGMENT);
if (prev != null) {
ft.remove(prev);
}
dialogFragment.show(ft, TAG_FRAGMENT);
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
ChangeLogRecyclerView chgList = (ChangeLogRecyclerView) LayoutInflater
.from(getContext()).inflate(R.layout.changelog_fragment_dialog, null);
return new AlertDialog.Builder(getActivity(), R.style.AppCompatAlertDialogStyle)
.setTitle(R.string.changelog_title)
.setView(chgList)
.setPositiveButton(R.string.button_close, (dialog, which) -> dialog.dismiss())
.create();
}
}
| mit |
andreichernov/srntygeorest | src/main/java/ru/andreichernov/configuration/GoogleMapApiStatus.java | 1106 | package ru.andreichernov.configuration;
public enum GoogleMapApiStatus {
OK, // ошибок нет, адрес обработан и получен хотя бы один геокод.
ZERO_RESULTS, // геокодирование успешно выполнено, однако результаты не найдены.
// Это может произойти, если геокодировщику был передан несуществующий адрес (address).
OVER_QUERY_LIMIT, // указывает на превышение квоты.
REQUEST_DENIED, // указывает на отклонение запроса.
INVALID_REQUEST, // как правило, указывает на отсутствие в запросе полей address, components или latlng.
UNKNOWN_ERROR // указывает, что запрос не удалось обработать из-за ошибки сервера. Если повторить попытку, запрос может оказаться успешным.
}
| mit |
fahadadeel/Aspose.Cells-for-Java | Examples/src/main/java/com/aspose/cells/examples/SmartMarkers/UsingNestedObjects.java | 1064 | package com.aspose.cells.examples.SmartMarkers;
import java.util.ArrayList;
import com.aspose.cells.Workbook;
import com.aspose.cells.WorkbookDesigner;
import com.aspose.cells.examples.Utils;
public class UsingNestedObjects {
public static void main(String[] args) throws Exception {
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(UsingNestedObjects.class) + "SmartMarkers/";
Workbook workbook = new Workbook(dataDir + "TestSmartMarkers.xlsx");
WorkbookDesigner designer = new WorkbookDesigner();
designer.setWorkbook(workbook);
ArrayList<Individual> list = new ArrayList<Individual>();
list.add(new Individual("John", 23, new Wife("Jill", 20)));
list.add(new Individual("Jack", 25, new Wife("Hilly", 21)));
list.add(new Individual("James", 26, new Wife("Hally", 22)));
list.add(new Individual("Baptist", 27, new Wife("Newly", 23)));
designer.setDataSource("Individual", list);
designer.process(false);
workbook.save(dataDir + "UsingNestedObjects-out.xlsx");
}
}
| mit |
Larhard/bridge | src/main/java/com/elgassia/bridge/adapter/main/LobbyAdapter.java | 1275 | package com.elgassia.bridge.adapter.main;
import com.elgassia.bridge.Model.Strategy;
import com.elgassia.bridge.Model.UserLobbyModel;
import com.elgassia.bridge.exception.BridgeLogicException;
public class LobbyAdapter implements com.elgassia.bridge.adapter.LobbyAdapter {
private final UserTeamAdapter userTeamAdapter;
private final UserLobbyModel userLobbyModel;
public LobbyAdapter(UserTeamAdapter userTeamAdapter, UserLobbyModel userLobbyModel) {
this.userTeamAdapter = userTeamAdapter;
this.userLobbyModel = userLobbyModel;
}
@Override
public boolean setName(String name) throws BridgeLogicException {
return userLobbyModel.setName(name);
}
@Override
public void startGame() throws BridgeLogicException {
userLobbyModel.ready();
}
@Override
public void setRandomTeam() throws BridgeLogicException {
userLobbyModel.randomTeam();
}
@Override
public void setTeam(int team) throws BridgeLogicException {
userLobbyModel.setTeam(team);
}
@Override
public String getName() {
return userLobbyModel.getName();
}
@Override
public void setDeckStrategy(Strategy strategy) {
userLobbyModel.setDeckStrategy(strategy);
}
}
| mit |
amritbhat786/DocIT | 101repo/contributions/emfGenerative/src/company/impl/DepartmentImpl.java | 8857 | /**
* <copyright>
* </copyright>
*
* $Id$
*/
package company.impl;
import company.CompanyPackage;
import company.Department;
import company.Employee;
import java.util.Collection;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.EObjectImpl;
import org.eclipse.emf.ecore.util.EObjectContainmentEList;
import org.eclipse.emf.ecore.util.InternalEList;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Department</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link company.impl.DepartmentImpl#getName <em>Name</em>}</li>
* <li>{@link company.impl.DepartmentImpl#getManager <em>Manager</em>}</li>
* <li>{@link company.impl.DepartmentImpl#getSubdepts <em>Subdepts</em>}</li>
* <li>{@link company.impl.DepartmentImpl#getEmployees <em>Employees</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class DepartmentImpl extends EObjectImpl implements Department {
/**
* The default value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected static final String NAME_EDEFAULT = null;
/**
* The cached value of the '{@link #getName() <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getName()
* @generated
* @ordered
*/
protected String name = NAME_EDEFAULT;
/**
* The cached value of the '{@link #getManager() <em>Manager</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getManager()
* @generated
* @ordered
*/
protected Employee manager;
/**
* The cached value of the '{@link #getSubdepts() <em>Subdepts</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getSubdepts()
* @generated
* @ordered
*/
protected EList<Department> subdepts;
/**
* The cached value of the '{@link #getEmployees() <em>Employees</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getEmployees()
* @generated
* @ordered
*/
protected EList<Employee> employees;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected DepartmentImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return CompanyPackage.Literals.DEPARTMENT;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getName() {
return name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setName(String newName) {
String oldName = name;
name = newName;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, CompanyPackage.DEPARTMENT__NAME, oldName, name));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Employee getManager() {
return manager;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetManager(Employee newManager, NotificationChain msgs) {
Employee oldManager = manager;
manager = newManager;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, CompanyPackage.DEPARTMENT__MANAGER, oldManager, newManager);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setManager(Employee newManager) {
if (newManager != manager) {
NotificationChain msgs = null;
if (manager != null)
msgs = ((InternalEObject)manager).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - CompanyPackage.DEPARTMENT__MANAGER, null, msgs);
if (newManager != null)
msgs = ((InternalEObject)newManager).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - CompanyPackage.DEPARTMENT__MANAGER, null, msgs);
msgs = basicSetManager(newManager, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, CompanyPackage.DEPARTMENT__MANAGER, newManager, newManager));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Department> getSubdepts() {
if (subdepts == null) {
subdepts = new EObjectContainmentEList<Department>(Department.class, this, CompanyPackage.DEPARTMENT__SUBDEPTS);
}
return subdepts;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Employee> getEmployees() {
if (employees == null) {
employees = new EObjectContainmentEList<Employee>(Employee.class, this, CompanyPackage.DEPARTMENT__EMPLOYEES);
}
return employees;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case CompanyPackage.DEPARTMENT__MANAGER:
return basicSetManager(null, msgs);
case CompanyPackage.DEPARTMENT__SUBDEPTS:
return ((InternalEList<?>)getSubdepts()).basicRemove(otherEnd, msgs);
case CompanyPackage.DEPARTMENT__EMPLOYEES:
return ((InternalEList<?>)getEmployees()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case CompanyPackage.DEPARTMENT__NAME:
return getName();
case CompanyPackage.DEPARTMENT__MANAGER:
return getManager();
case CompanyPackage.DEPARTMENT__SUBDEPTS:
return getSubdepts();
case CompanyPackage.DEPARTMENT__EMPLOYEES:
return getEmployees();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case CompanyPackage.DEPARTMENT__NAME:
setName((String)newValue);
return;
case CompanyPackage.DEPARTMENT__MANAGER:
setManager((Employee)newValue);
return;
case CompanyPackage.DEPARTMENT__SUBDEPTS:
getSubdepts().clear();
getSubdepts().addAll((Collection<? extends Department>)newValue);
return;
case CompanyPackage.DEPARTMENT__EMPLOYEES:
getEmployees().clear();
getEmployees().addAll((Collection<? extends Employee>)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case CompanyPackage.DEPARTMENT__NAME:
setName(NAME_EDEFAULT);
return;
case CompanyPackage.DEPARTMENT__MANAGER:
setManager((Employee)null);
return;
case CompanyPackage.DEPARTMENT__SUBDEPTS:
getSubdepts().clear();
return;
case CompanyPackage.DEPARTMENT__EMPLOYEES:
getEmployees().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case CompanyPackage.DEPARTMENT__NAME:
return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name);
case CompanyPackage.DEPARTMENT__MANAGER:
return manager != null;
case CompanyPackage.DEPARTMENT__SUBDEPTS:
return subdepts != null && !subdepts.isEmpty();
case CompanyPackage.DEPARTMENT__EMPLOYEES:
return employees != null && !employees.isEmpty();
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (name: ");
result.append(name);
result.append(')');
return result.toString();
}
public double total() {
double total = getManager().total();
for (Department subdept : getSubdepts())
total += subdept.total();
for (Employee employee : getEmployees())
total += employee.total();
return total;
}
public void cut() {
getManager().cut();
for (Department subdept : getSubdepts())
subdept.cut();
for (Employee employee : getEmployees())
employee.cut();
}
} //DepartmentImpl
| mit |
JonathanZwiebel/LFT-asteroid-analysis | src/core/preprocess/Preprocessor.java | 724 | package core.preprocess;
import nom.tam.fits.Fits;
import nom.tam.fits.FitsException;
import java.io.IOException;
/**
* @author Jonathan Zwiebel
* @version November 25th, 2015
*
* This abstract class takes in a file of astronomical static field data and coverts it to a data cube where the first
* index correspond, the other two correspond to location (RA and D) and the floating point value at each cell is the
* brightness as detected by a CCD array.
* TODO[Major]: Make this work with non-rectangular data sets
*/
public abstract class Preprocessor {
final Fits file_;
Preprocessor(Fits file) {
file_ = file;
}
public abstract float[][][] read() throws FitsException, IOException;
}
| mit |
jenkinsci/ec2-plugin | src/main/java/hudson/plugins/ec2/win/winrm/WinRMClient.java | 15490 | package hudson.plugins.ec2.win.winrm;
import hudson.plugins.ec2.win.winrm.request.RequestFactory;
import hudson.plugins.ec2.win.winrm.soap.Namespaces;
import hudson.remoting.FastPipedOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.auth.AuthSchemeProvider;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.HttpClient;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Lookup;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.auth.BasicSchemeFactory;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.XPath;
import org.jaxen.SimpleNamespaceContext;
public class WinRMClient {
private static final Logger LOGGER = Logger.getLogger(WinRMClient.class.getName());
private final URL url;
private final String username;
private final String password;
private String shellId;
private String commandId;
private int exitCode;
private final RequestFactory factory;
private final ThreadLocal<BasicAuthCache> authCache = new ThreadLocal<>();
private boolean useHTTPS;
private BasicCredentialsProvider credsProvider;
private final boolean allowSelfSignedCertificate;
@Deprecated
public WinRMClient(URL url, String username, String password) {
this(url, username, password, false);
}
public WinRMClient(URL url, String username, String password, boolean allowSelfSignedCertificate) {
this.url = url;
this.username = username;
this.password = password;
this.factory = new RequestFactory(url);
this.allowSelfSignedCertificate = allowSelfSignedCertificate;
setupHTTPClient();
}
public void openShell() {
LOGGER.log(Level.FINE, () -> "opening winrm shell to: " + url);
Document request = factory.newOpenShellRequest().build();
shellId = first(sendRequest(request), "//*[@Name='ShellId']");
LOGGER.log(Level.FINER, () -> "shellid: " + shellId);
}
public void executeCommand(String command) {
LOGGER.log(Level.FINE, () -> "winrm execute on " + shellId + " command: " + command);
Document request = factory.newExecuteCommandRequest(shellId, command).build();
commandId = first(sendRequest(request), "//" + Namespaces.NS_WIN_SHELL.getPrefix() + ":CommandId");
LOGGER.log(Level.FINER, ()-> "winrm started execution on " + shellId + " commandId: " + commandId);
}
public void deleteShell() {
if (shellId == null) {
throw new IllegalStateException("no shell has been created");
}
LOGGER.log(Level.FINE, () -> "closing winrm shell " + shellId);
Document request = factory.newDeleteShellRequest(shellId).build();
sendRequest(request);
}
public void signal() {
if (commandId == null) {
throw new IllegalStateException("no command is running");
}
LOGGER.log(Level.FINE, () -> "signalling winrm shell " + shellId + " command: " + commandId);
Document request = factory.newSignalRequest(shellId, commandId).build();
sendRequest(request);
}
public void sendInput(byte[] input) {
LOGGER.log(Level.FINE, () -> "--> sending " + input.length);
Document request = factory.newSendInputRequest(input, shellId, commandId).build();
sendRequest(request);
}
public boolean slurpOutput(FastPipedOutputStream stdout, FastPipedOutputStream stderr) throws IOException {
LOGGER.log(Level.FINE, () -> "--> SlurpOutput");
Map<String, FastPipedOutputStream> streams = new HashMap<>(); streams.put("stdout", stdout); streams.put("stderr", stderr);
Document request = factory.newGetOutputRequest(shellId, commandId).build();
Document response = sendRequest(request);
XPath xpath = DocumentHelper.createXPath("//" + Namespaces.NS_WIN_SHELL.getPrefix() + ":Stream");
SimpleNamespaceContext namespaceContext = new SimpleNamespaceContext();
namespaceContext.addNamespace(Namespaces.NS_WIN_SHELL.getPrefix(), Namespaces.NS_WIN_SHELL.getURI());
xpath.setNamespaceContext(namespaceContext);
for (Node node : xpath.selectNodes(response)) {
if (node instanceof Element) {
Element e = (Element) node;
FastPipedOutputStream stream = streams.get(e.attribute("Name").getText().toLowerCase());
final byte[] decode = Base64.getDecoder().decode(e.getText());
LOGGER.log(Level.FINE, () -> "piping " + decode.length + " bytes from "
+ e.attribute("Name").getText().toLowerCase());
stream.write(decode);
}
}
XPath done = DocumentHelper.createXPath("//*[@State='http://schemas.microsoft.com/wbem/wsman/1/windows/shell/CommandState/Done']");
done.setNamespaceContext(namespaceContext);
final List<Node> nodes = done.selectNodes(response);
if (nodes != null && nodes.isEmpty()) {
LOGGER.log(Level.FINE, "keep going baby!");
return true;
} else {
exitCode = Integer.parseInt(first(response, "//" + Namespaces.NS_WIN_SHELL.getPrefix() + ":ExitCode"));
LOGGER.log(Level.FINE, () -> "no more output - command is now done - exit code: " + exitCode);
}
return false;
}
public int exitCode() {
return exitCode;
}
private static String first(Document doc, String selector) {
XPath xpath = DocumentHelper.createXPath(selector);
List<Node> nodes = xpath.selectNodes(doc);
if (!nodes.isEmpty() && nodes.get(0) instanceof Element) {
return nodes.get(0).getText();
}
throw new RuntimeException("Malformed response for " + selector + " in " + doc.asXML());
}
private void setupHTTPClient() {
credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(username, password));
}
private HttpClient buildHTTPClient() {
HttpClientBuilder builder = HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider);
if(! (username.contains("\\")|| username.contains("/"))) {
//user is not a domain user
Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
.register(AuthSchemes.BASIC, new BasicSchemeFactory())
.register(AuthSchemes.SPNEGO,new NegotiateNTLMSchemaFactory())
.build();
builder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
}
if (useHTTPS) {
WinRMConnectionManagerFactory.WinRMHttpConnectionManager connectionManager =
allowSelfSignedCertificate ? WinRMConnectionManagerFactory.SSL_ALLOW_SELF_SIGNED
: WinRMConnectionManagerFactory.SSL;
builder.setSSLSocketFactory(connectionManager.getSocketFactory());
builder.setConnectionManager(connectionManager.getConnectionManager());
} else {
builder.setConnectionManager(WinRMConnectionManagerFactory.DEFAULT.getConnectionManager());
}
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000)
.setSocketTimeout(0)
.build();
builder.setDefaultRequestConfig(requestConfig);
SocketConfig socketConfig = SocketConfig.custom()
.setTcpNoDelay(true)
.build();
builder.setDefaultSocketConfig(socketConfig);
// Add sleep between re-tries, by-default the call gets retried immediately.
builder.setRetryHandler(new DefaultHttpRequestRetryHandler() {
@Override
public boolean retryRequest(
final IOException exception,
final int executionCount,
final HttpContext context) {
boolean retryRequest = super.retryRequest(exception, executionCount, context);
if ( retryRequest ) {
// sleep before retrying, increase the sleep time on each re-try
int sleepTime = executionCount * 5;
try {
TimeUnit.SECONDS.sleep(sleepTime);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException("Exception while executing command", e);
}
}
return retryRequest;
}
});
return builder.build();
}
private Document sendRequest(Document request) {
return sendRequest(request, 0);
}
private Document sendRequest(Document request, int retry) {
if (retry > 3) {
throw new RuntimeException("Too many retry for request");
}
HttpClient httpclient = buildHTTPClient();
HttpContext context = new BasicHttpContext();
if (authCache.get() == null) {
authCache.set(new BasicAuthCache());
}
context.setAttribute(HttpClientContext.AUTH_CACHE, authCache.get());
try {
HttpPost post = new HttpPost(url.toURI());
HttpEntity entity = new StringEntity(request.asXML(), ContentType.APPLICATION_SOAP_XML);
post.setEntity(entity);
LOGGER.log(Level.FINEST, () -> "Request:\nPOST " + url + "\n" + request.asXML());
HttpResponse response = httpclient.execute(post, context);
HttpEntity responseEntity = response.getEntity();
if (response.getStatusLine().getStatusCode() != 200) {
// check for possible timeout
if (response.getStatusLine().getStatusCode() == 500
&& (responseEntity.getContentType() != null && entity.getContentType().getValue().startsWith(ContentType.APPLICATION_SOAP_XML.getMimeType()))) {
String respStr = EntityUtils.toString(responseEntity);
if (respStr.contains("TimedOut")) {
return DocumentHelper.parseText(respStr);
}
} else {
// this shouldn't happen, as httpclient knows how to auth
// the request
// but I've seen it. I blame keep-alive, so we're just going
// to scrap the connections, and try again
if (response.getStatusLine().getStatusCode() == 401) {
// we need to force using new connections here
// throw away our auth cache
LOGGER.log(Level.WARNING, "winrm returned 401 - shouldn't happen though - retrying in 2 minutes");
try {
Thread.sleep(TimeUnit.MINUTES.toMillis(2));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
authCache.set(new BasicAuthCache());
LOGGER.log(Level.WARNING, "winrm returned 401 - retrying now");
return sendRequest(request, ++retry);
}
LOGGER.log(Level.WARNING, "winrm service " + shellId + " unexpected HTTP Response ("
+ response.getStatusLine().getReasonPhrase() + "): "
+ EntityUtils.toString(response.getEntity()));
throw new RuntimeException("Unexpected HTTP response " + response.getStatusLine().getStatusCode()
+ " on " + url + ": " + response.getStatusLine().getReasonPhrase());
}
}
if (responseEntity.getContentType() == null
|| !entity.getContentType().getValue().startsWith(ContentType.APPLICATION_SOAP_XML.getMimeType())) {
throw new RuntimeException("Unexpected WinRM content type: " + entity.getContentType());
}
Document responseDocument = DocumentHelper.parseText(EntityUtils.toString(responseEntity));
LOGGER.log(Level.FINEST, () -> "Response:\n" + responseDocument.asXML());
return responseDocument;
} catch (URISyntaxException e) {
throw new RuntimeException("Invalid WinRM URI " + url);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Invalid WinRM body " + request.asXML());
} catch (ClientProtocolException e) {
throw new RuntimeException("HTTP Error " + e.getMessage(), e);
} catch (HttpHostConnectException e) {
LOGGER.log(Level.SEVERE, "Can't connect to host", e);
throw new WinRMConnectException("Can't connect to host: " + e.getMessage(), e);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "I/O Exception in HTTP POST", e);
throw new RuntimeIOException("I/O Exception " + e.getMessage(), e);
} catch (ParseException e) {
LOGGER.log(Level.SEVERE, "XML Parse exception in HTTP POST", e);
throw new RuntimeException("Unparseable XML in winRM response " + e.getMessage(), e);
} catch (DocumentException e) {
LOGGER.log(Level.SEVERE, "XML Document exception in HTTP POST", e);
throw new RuntimeException("Invalid XML document in winRM response " + e.getMessage(), e);
}
}
public String getTimeout() {
return factory.getTimeout();
}
public void setTimeout(String timeout) {
factory.setTimeout(timeout);
}
public void setUseHTTPS(boolean useHTTPS) {
this.useHTTPS = useHTTPS;
}
}
| mit |
julianmendez/desktop-search | search-core/src/main/java/com/semantic/SearchProcess.java | 2701 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.semantic;
import igmas.process.JVMProcess;
import igmas.process.util.Util;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.bind.JAXBException;
/**
*
* @author Christian Plonka (cplonka81@gmail.com)
*/
public class SearchProcess extends JVMProcess {
/* */
private final List<File> _classPath = new ArrayList<File>();
private final Map<String, String> _properties = new HashMap<String, String>();
private File _splashScreen;
public SearchProcess() {
super();
initProcess();
}
private void initProcess() {
_classPath.add(new File("./search-core.jar"));
_classPath.add(new File("./lib/*"));
_classPath.add(new File("./plugin/*"));
_classPath.add(new File("./plugin/lib/*"));
}
@Override
public String command() {
/* look if we have an bundled jvm and prefer that */
File bundled = Util.findBundledJRE();
if (bundled != null && bundled.exists()) {
return bundled.getAbsolutePath();
}
return super.command();
}
@Override
public List<File> getClassPath() {
return _classPath;
}
@Override
public File getSplash() {
return _splashScreen;
}
@Override
public Map<String, String> getProperties() {
return _properties;
}
@Override
public String getMainClass() {
return "com.semantic.ApplicationContext";
}
@Override
public int getXms() {
return 32;
}
@Override
public int getXmx() {
return 1024;
}
public static void main(String[] arg) throws IOException {
/* default startup parameter */
JVMProcess process = new SearchProcess();
/* search for jvm configuration */
File jvm = new File(new File(ApplicationContext.ISEARCH_HOME), "jvm.conf");
/* load settings */
if (jvm.exists()) {
try {
process = Util.read(jvm);
} catch (JAXBException ex) {
ex.printStackTrace();
}
}
/* build the jvm with the configuration */
ProcessBuilder builder = new ProcessBuilder(process.buildCommandLine());
builder.directory(process.workingDirectory());
/* start process and exit current jvm */
builder.start();
/* exit us!? */
System.exit(0);
}
} | mit |
ayushmaanbhav/stockmart | src/com/ayushmaanbhav/jstockmart/client/RankingWindow.java | 953 | package com.ayushmaanbhav.jstockmart.client;
import javax.swing.*;
import java.awt.*;
import javax.swing.text.*;
@SuppressWarnings("serial")
class RankingWindow extends JPanel {
JTextPane jta;
JScrollPane jsp;
public RankingWindow(Client cc) {
setLayout(new BorderLayout());
JLabel jlab = new JLabel("<<RANKINGS>>");
jta = new JTextPane();
StyledDocument doc = jta.getStyledDocument();
SimpleAttributeSet center = new SimpleAttributeSet();
StyleConstants.setAlignment(center, StyleConstants.ALIGN_LEFT);
doc.setParagraphAttributes(0, doc.getLength(), center, false);
jta.setFont(new Font("Calibri", Font.PLAIN, 13));
jta.setEditable(false);
jta.setForeground(Color.red.darker());
jsp = new JScrollPane(jta, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
add(jlab, BorderLayout.NORTH);
add(jsp, BorderLayout.CENTER);
RankingClient cser = new RankingClient(jta, jsp);
cc.rc = cser;
}
} | mit |
zsgithub3895/common.code | src/com/zs/algorithm/binary/tree/BinaryTreeRecursion.java | 1632 | package com.zs.algorithm.binary.tree;
/**
* recursion 递归,递推
* */
public class BinaryTreeRecursion {
public static void main(String[] args) {
int[] array = {12,76,35,22,16,48,90,46,9,40};
BinaryTree root = new BinaryTree(array[0]);//创建二叉树
for(int i=1;i<array.length;i++){
root.insert(root, array[i]);//向二叉树中插入数据
}
System.out.println("先序遍历:");
preOrderRec(root);
System.out.println();
System.out.println("中序遍历:");
inOrderRec(root);
System.out.println();
System.out.println("后序遍历:");
postOrderRec(root);
}
/**
* @param root 树根节点 (根节点->左孩子->右孩子)
* 递归先序遍历
*/
public static void preOrderRec(BinaryTree root){
if(root!=null){
System.out.print(root.value+",");
preOrderRec(root.left);
preOrderRec(root.right);
}
}
/**
* @param root 树根节点 (左孩子->根节点->右孩子)
* 递归中序遍历
*/
public static void inOrderRec(BinaryTree root){
if(root!=null){
inOrderRec(root.left);
System.out.print(root.value+",");
inOrderRec(root.right);
}
}
/**
* @param root 树根节点 (左孩子->右孩子->根节点)
* 递归后序遍历
*/
public static void postOrderRec(BinaryTree root){
if(root!=null){
postOrderRec(root.left);
postOrderRec(root.right);
System.out.print(root.value+",");
}
}
}
| mit |
EaW1805/www | src/main/java/com/eaw1805/www/scenario/stores/BrigadeUtils.java | 3207 | package com.eaw1805.www.scenario.stores;
import com.eaw1805.data.dto.web.army.BattalionDTO;
import com.eaw1805.data.dto.web.army.BrigadeDTO;
import com.eaw1805.www.scenario.views.ArmyBrushView;
import com.eaw1805.www.scenario.views.EditorPanel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class BrigadeUtils {
private static int brigadeId = -1;
public static void createBrigade(final int x, final int y) {
final ArmyBrushView brush = EditorPanel.getInstance().getArmyBrush();
final BrigadeDTO brigade = new BrigadeDTO();
brigade.setBrigadeId(getBrigadeId());
brigade.setX(x);
brigade.setY(y);
brigade.setRegionId(RegionSettings.region.getRegionId());
brigade.setName("brigade " + Math.abs(brigade.getBrigadeId()));
brigade.setNationId(brush.getNation().getNationId());
List<BattalionDTO> batts = new ArrayList<BattalionDTO>();
if (brush.getBatt1() != null) {
batts.add(cloneBattalion(brush.getBatt1()));
}
if (brush.getBatt2() != null) {
batts.add(cloneBattalion(brush.getBatt2()));
}
if (brush.getBatt3() != null) {
batts.add(cloneBattalion(brush.getBatt3()));
}
if (brush.getBatt4() != null) {
batts.add(cloneBattalion(brush.getBatt4()));
}
if (brush.getBatt5() != null) {
batts.add(cloneBattalion(brush.getBatt5()));
}
if (brush.getBatt6() != null) {
batts.add(cloneBattalion(brush.getBatt6()));
}
brigade.setBattalions(batts);
final Map<Integer, Map<Integer, Map<Integer, BrigadeDTO>>> brigMap = EditorStore.getInstance().getBrigades().get(RegionSettings.region.getRegionId());
if (!brigMap.containsKey(x)) {
brigMap.put(x, new HashMap<Integer, Map<Integer, BrigadeDTO>>());
}
if (!brigMap.get(x).containsKey(y)) {
brigMap.get(x).put(y, new HashMap<Integer, BrigadeDTO>());
}
brigMap.get(x).get(y).put(brigade.getBrigadeId(), brigade);
EditorMapUtils.getInstance().drawBrigade(brigade);
}
public static void deleteBrigade(final BrigadeDTO brigade) {
//first if the brigade belongs to a corps.. update the corps.
if (brigade.getCorpId() != 0) {
EditorStore.getInstance().getCorps().get(brigade.getRegionId()).get(brigade.getX()).get(brigade.getY()).get(brigade.getCorpId()).getBrigades().remove(brigade.getBrigadeId());
}
//second remove the brigade from the store.
EditorStore.getInstance().getBrigades().get(brigade.getRegionId()).get(brigade.getX()).get(brigade.getY()).remove(brigade.getBrigadeId());
}
private static BattalionDTO cloneBattalion(final BattalionDTO in) {
BattalionDTO out = new BattalionDTO();
out.setOrder(in.getOrder());
out.setExperience(in.getExperience());
out.setHeadcount(in.getHeadcount());
out.setEmpireArmyType(in.getEmpireArmyType());
return out;
}
private static int getBrigadeId() {
brigadeId--;
return brigadeId;
}
}
| mit |
resd/massive-octo-batman | src/main/java/algorithm/bab/parallel/branch/ChoseBranchParallel.java | 7098 | package algorithm.bab.parallel.branch;
import algorithm.bab.classic.branch.ChoseBranchClassic;
import algorithm.bab.util.*;
import java.util.ArrayList;
import java.util.Map;
/**
* @author Admin
* @since 11.11.2015
*/
public class ChoseBranchParallel extends ChoseBranchClassic {
public Struct chooseBoth(Path path, Var var, Var varRef, ArrayClass arrayClass) {
Struct sa;
GeneralStruct generalStruct;
// ���� ����� ������� > 2
if (var.getArrayLength() > 2) {
Map <int[], Double> map;// = new HashMap<Object, Double>();
// ������� max ����� ���� ������� ��-��� �� ������ ���
map = defineMapEdge(var.getArray());
// ������� ��-� �����-��� max ����� �� ����� map
ArrayList edges = difineEdges(map);
// ��������� ������ Struct � �������� � ��� ������� �� HWith � HWithout
//try {
if (map.size() == 0) {
return new Struct(true);
}
sa = chooseHone((int[]) edges.get(0), map.get(edges.get(0)), path, var, varRef);
/*} catch (Exception e) {
e.printStackTrace();
}*/
} else {
double HWith;
double HWithout;
double Sum = 0;
var.setArray(null);
var.setM1(null);
path.getP()[arrayClass.getOriginalSize() - 2][0] = path.getMi()[0];
path.getP()[arrayClass.getOriginalSize() - 2][1] = path.getMj()[1];
path.getP()[arrayClass.getOriginalSize() - 1][0] = path.getMi()[1];
path.getP()[arrayClass.getOriginalSize() - 1][1] = path.getMj()[0];
for (int k = 0; k < arrayClass.getOriginalSize(); k++) {
Sum += arrayClass.getA()[path.getP()[k][0]][path.getP()[k][1]];
}
HWithout = Sum - var.getH();
if (HWithout < 0) System.out.println("Error with (Sum - H) = " + HWithout);
var.setH(var.getH() + HWithout);
var.setMin(var.getH());
HWith = Double.POSITIVE_INFINITY;
generalStruct = new GeneralStruct(var.getH(), HWithout, HWith, true, Other.cloneMatrix(path.getP()));
var.setMinLowerBound(var.getH());
/*structHW = new StructHW(var.getH(), HWith, null, Other.cloneMatrix(path.getP()), path.getPathCount(),
path.getMi().clone(), path.getMj().clone());*/
sa = new Struct(generalStruct);
// sa.setActivatehw(true);
}
// if (sa.getM1() == null) {
// sa.setAdditional(Other.cloneMatrix(path.getP()), Other.cloneMatrix(var.getM1()), path.getMi().clone(), path.getMj().clone(), path.getPathCount());
// }
return sa;
}
// ��������� ������ Struct � �������� � ��� ������� �� HWith � HWithout
@SuppressWarnings("UnusedParameters") // TODO Safe delete parameter
private Struct chooseHone(int[] edge, double HWith, Path path, Var var, Var varRef) {
double[][] arrayC;
Struct sa;
GeneralStruct generalStruct;
StructHW structHW = null;
StructHWout structHWout = null;
double HWithout;
arrayC = Other.cloneMatrix(var.getArray());
var.getArray()[edge[1]][edge[0]] = Double.POSITIVE_INFINITY;
var.setM1(getHWithout(edge, var.getArray()));
HWithout = getSumOfDelta();
arrayC[edge[0]][edge[1]] = Double.POSITIVE_INFINITY;
Normalize.INSTANCE.normalize(arrayC);
// sa.setArray(Other.cloneMatrix(arrayC));// ���� ������� ������ �� 2 �������, �� ���-��� �������� �� ����� �������.
// sa.newStruct(edge.clone(), HWith, HWithout, var.getH(), Other.cloneMatrix(path.getP()), path.getPathCount());
// sa.addMiMj(path.getMi().clone(), path.getMj().clone());
//todo System.out.println((H + HWithout) + ", " + (H + HWith) + " (" + (mi[edge[0]] + 1) + ", " + (mj[edge[1]] + 1) + ")");
//System.out.println("");display(array);System.out.println("");
if (HWithout <= HWith) {
if (HWithout < var.getMinParallel()) {
generalStruct = new GeneralStruct(edge, var.getH(), HWithout, HWith);
if (HWith < var.getMinLeftBound()) {
structHW = new StructHW(var.getH(), HWith, Other.cloneMatrix(arrayC), Other.cloneMatrix(path.getP()),
path.getPathCount(), path.getMi().clone(), path.getMj().clone());
}
path.getPath(edge);
structHWout = new StructHWout(var.getH(), HWithout, Other.cloneMatrix(var.getM1()),
Other.cloneMatrix(path.getP()), path.getPathCount(), path.getMi().clone(), path.getMj().clone());
sa = new Struct(generalStruct, structHWout, structHW);
var.setH(var.getH() + HWithout);
var.setArray(Other.cloneMatrix(var.getM1()));
var.setMin(var.getH());
var.setMinParallel(HWithout);
} else return null;
} else {
if (HWith < var.getMinParallel()) {
generalStruct = new GeneralStruct(edge, var.getH(), HWithout, HWith);
structHW = new StructHW(var.getH(), HWith, Other.cloneMatrix(arrayC), Other.cloneMatrix(path.getP()),
path.getPathCount(), path.getMi().clone(), path.getMj().clone());
int x = edge[0];
int y = edge[1];
int[][] pC = Other.cloneMatrix(path.getP());
int[] miC = path.getMi().clone();
int[] mjC = path.getMj().clone();
pC[path.getPathCount()][0] = miC[x];
pC[path.getPathCount()][1] = mjC[y];
miC[x] = miC[y];
miC = path.remove(miC, y);
mjC = path.remove(mjC, y);
if (HWithout < var.getMinLeftBound()) {
structHWout = new StructHWout(var.getH(), HWithout, Other.cloneMatrix(var.getM1()), Other.cloneMatrix(pC),
path.getPathCount() + 1, miC.clone(), mjC.clone());
}
var.setH(var.getH() + HWith);
var.setMin(var.getH());
var.setArray(arrayC);
// sa.setAdditional(Other.cloneMatrix(pC), Other.cloneMatrix(var.getM1()), miC.clone(), mjC.clone(), path.getPathCount() + 1);
sa = new Struct(generalStruct, structHWout, structHW);
var.setMinParallel(HWithout);
} else return null;
}
//da.add(sa);
//System.out.println("");display(array);System.out.println("");
return sa;
}
}
| mit |
anon6789/KSSMonolith | src/main/java/de/mstock/monolith/config/SecurityConfig.java | 678 | package de.mstock.monolith.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/account/**")
.authenticated()
.and()
.formLogin();
}
}
| mit |
conveyal/otp-deployer | app/data/OsmSource.java | 3939 | package data;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.apache.commons.io.FileUtils;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import util.HashUtils;
import util.JsonModel;
@JsonIgnoreProperties(ignoreUnknown = true)
public class OsmSource extends JsonModel implements Comparable<OsmSource> {
public static String TYPE = "osm";
public String currentVersion;
public List<String> osmVersions = new ArrayList<String>();
public static File getRootDirectory() {
return JsonModel.getDirectory(null, TYPE);
}
public static File getDataPath(String id) {
return new File(getDirectory(id), "data.json");
}
public static File getDirectory(String id) {
return buildPath(getRootDirectory(), id);
}
public File getDirectory() {
return getDirectory(id);
}
public File getDataPath() {
return getDataPath(id);
}
public void save() {
ObjectMapper mapper = new ObjectMapper();
modified = new Date();
try {
File path = getDataPath();
mapper.writeValue(path, this);
} catch (JsonGenerationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static OsmSource load(String id) {
ObjectMapper mapper = new ObjectMapper();
try {
File path = getDataPath(id);
return mapper.readValue(path, OsmSource.class);
} catch (JsonGenerationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
@Override
public int compareTo(OsmSource other) {
return name.compareTo(other.name);
}
public void addFile(final File osmFile) {
String osmHash = HashUtils.hashFile(osmFile);
try {
if(osmVersions.contains(osmHash)) {
// switch current to stored/existing version
setVersion(osmHash);
}
else {
osmVersions.add(osmHash);
// create a new version
final File osmVersionFile = OsmVersion.getOsmPath(id, osmHash);
FileUtils.copyFile(osmFile, osmVersionFile);
OsmVersion summary = new OsmVersion();
summary.osmId = this.id;
summary.versionId = osmHash;
summary.name = osmFile.getName();
summary.created = new Date(osmFile.lastModified());
summary.modified = new Date();
summary.save();
setVersion(osmHash);
}
save();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public List<OsmVersion> getVersions() {
List<OsmVersion> versionList = new ArrayList<OsmVersion>();
for(File versionDir : OsmVersion.getRootDirectory(id).listFiles()) {
String versionId = versionDir.getName();
OsmVersion version = OsmVersion.load(id, versionId);
versionList.add(version);
}
Collections.sort(versionList);
return versionList;
}
public OsmVersion getVersion(String versionId) {
return OsmVersion.load(id, versionId);
}
public void setVersion(String osmVersionId) {
this.currentVersion = osmVersionId;
try {
FileUtils.copyFile(OsmVersion.getOsmPath(id, osmVersionId), new File(getDirectory(), "current_osm.pbf"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.save();
}
} | mit |
r0adkll/deadSkunk | deadSkunk/deadSkunk/src/main/java/com/r0adkll/deadskunk/preferences/StringPreference.java | 1995 | /*
* MIT License (MIT)
*
* Copyright (c) 2014 Drew Heavner
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.r0adkll.deadskunk.preferences;
import android.content.SharedPreferences;
public class StringPreference {
private final SharedPreferences preferences;
private final String key;
private final String defaultValue;
public StringPreference(SharedPreferences preferences, String key) {
this(preferences, key, null);
}
public StringPreference(SharedPreferences preferences, String key, String defaultValue) {
this.preferences = preferences;
this.key = key;
this.defaultValue = defaultValue;
}
public String get() {
return preferences.getString(key, defaultValue);
}
public boolean isSet() {
return preferences.contains(key);
}
public void set(String value) {
preferences.edit().putString(key, value).apply();
}
public void delete() {
preferences.edit().remove(key).apply();
}
}
| mit |
Samuel-Oliveira/Java_NFe | src/main/java/br/com/swconsultoria/nfe/schema/epec/TEnvEvento.java | 3234 |
package br.com.swconsultoria.nfe.schema.epec;
import javax.xml.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
/**
* Tipo Lote de Envio
*
* <p>Classe Java de TEnvEvento complex type.
*
* <p>O seguinte fragmento do esquema especifica o contedo esperado contido dentro desta classe.
*
* <pre>
* <complexType name="TEnvEvento">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="idLote">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <whiteSpace value="preserve"/>
* <pattern value="[0-9]{1,15}"/>
* </restriction>
* </simpleType>
* </element>
* <element name="evento" type="{http://www.portalfiscal.inf.br/nfe}TEvento" maxOccurs="20"/>
* </sequence>
* <attribute name="versao" use="required" type="{http://www.portalfiscal.inf.br/nfe}TVerEnvEvento" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "TEnvEvento", namespace = "http://www.portalfiscal.inf.br/nfe", propOrder = {
"idLote",
"evento"
})
public class TEnvEvento {
@XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true)
protected String idLote;
@XmlElement(namespace = "http://www.portalfiscal.inf.br/nfe", required = true)
protected List<TEvento> evento;
@XmlAttribute(name = "versao", required = true)
protected String versao;
/**
* Obtm o valor da propriedade idLote.
*
* @return possible object is
* {@link String }
*/
public String getIdLote() {
return idLote;
}
/**
* Define o valor da propriedade idLote.
*
* @param value allowed object is
* {@link String }
*/
public void setIdLote(String value) {
this.idLote = value;
}
/**
* Gets the value of the evento property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the evento property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getEvento().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link TEvento }
*/
public List<TEvento> getEvento() {
if (evento == null) {
evento = new ArrayList<TEvento>();
}
return this.evento;
}
/**
* Obtm o valor da propriedade versao.
*
* @return possible object is
* {@link String }
*/
public String getVersao() {
return versao;
}
/**
* Define o valor da propriedade versao.
*
* @param value allowed object is
* {@link String }
*/
public void setVersao(String value) {
this.versao = value;
}
}
| mit |
gregbiv/news-today | app/src/main/java/com/github/gregbiv/news/ui/widget/BetterViewAnimator.java | 1088 |
/**
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Gregory Kornienko <gregbiv@gmail.com>
* @license MIT
*/
package com.github.gregbiv.news.ui.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ViewAnimator;
public final class BetterViewAnimator extends ViewAnimator {
public BetterViewAnimator(Context context, AttributeSet attrs) {
super(context, attrs);
}
public int getDisplayedChildId() {
return getChildAt(getDisplayedChild()).getId();
}
public void setDisplayedChildId(int id) {
if (getDisplayedChildId() == id) {
return;
}
for (int i = 0, count = getChildCount(); i < count; i++) {
if (getChildAt(i).getId() == id) {
setDisplayedChild(i);
return;
}
}
String name = getResources().getResourceEntryName(id);
throw new IllegalArgumentException("No view with ID " + name);
}
}
| mit |
mrzli/tria | core/src/com/symbolplay/tria/data/DataTemplate.java | 749 | package com.symbolplay.tria.data;
import com.badlogic.gdx.utils.ObjectMap;
import com.badlogic.gdx.utils.ObjectMap.Keys;
public final class DataTemplate {
public final String name;
private final ObjectMap<String, String> properties;
public DataTemplate(String name, ObjectMap<String, String> properties) {
this.name = name;
this.properties = properties;
}
public String getName() {
return name;
}
public String getProperty(String name) {
return properties.get(name);
}
public boolean hasProperty(String name) {
return properties.containsKey(name);
}
public Keys<String> getPropertyNames() {
return properties.keys();
}
}
| mit |
liulixiang1988/hibernate_demo | contactmgr-hibernate/src/main/java/io/github/liulixiang1988/contactmgr/Application.java | 3190 | package io.github.liulixiang1988.contactmgr;
import io.github.liulixiang1988.contactmgr.model.Contact;
import io.github.liulixiang1988.contactmgr.model.Contact.ContactBuilder;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;
import java.util.List;
public class Application {
//保存一个SessionFactory(我们也只需要一个)
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
//创建StandardServiceRegistry
final ServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build();
return new MetadataSources(registry).buildMetadata().buildSessionFactory();
}
public static void main(String[] args) {
Contact contact = new ContactBuilder("Liu","Lixiang")
.withEmail("550488300@qq.com")
.withPhone(7735556666L)
.build();
int id = save(contact);
//显示列表数据
// for(Contact c : fetchAllContact()) {
// System.out.println(c);
// }
fetchAllContact().stream().forEach(System.out::println);
Contact c = findContactById(id);
c.setEmail("xjtuliulixiang@qq.com");
update(c);
fetchAllContact().stream().forEach(System.out::println);
}
private static Contact findContactById(int id) {
//打开会话
Session session = sessionFactory.openSession();
//获取对象或者null
Contact contact = session.get(Contact.class, id);
//关闭会话
session.close();
//返回对象
return contact;
}
private static void update(Contact contact) {
Session session = sessionFactory.openSession();
session.beginTransaction();
session.update(contact);
session.getTransaction().commit();
session.close();
}
private static void delete(Contact contact) {
Session session = sessionFactory.openSession();
session.beginTransaction();
session.delete(contact);
session.getTransaction().commit();
session.close();
}
@SuppressWarnings("unchecked")
private static List<Contact> fetchAllContact() {
Session session = sessionFactory.openSession();
//创建Criteria
Criteria criteria = session.createCriteria(Contact.class);
//从Criteria中获取数据
List<Contact> contacts = criteria.list();
//关闭会话
session.close();
return contacts;
}
private static int save(Contact contact) {
//打开session
Session session = sessionFactory.openSession();
//begin transaction
session.beginTransaction();
//使用session来保存对象
int id = (int)session.save(contact);
//提交session
session.getTransaction().commit();
//关闭session
session.close();
return id;
}
}
| mit |
nirima/SnowGlobe | snowglobe/server/snowglobe-webapp/src/test/java/com/nirima/snowglobe/repository/FilesystemRepositoryTest.java | 473 | package com.nirima.snowglobe.repository;
import org.testng.annotations.Test;
import java.io.File;
import static org.testng.Assert.*;
public class FilesystemRepositoryTest {
@Test
public void testCloneRepo() throws Exception {
FilesystemRepository repo = new FilesystemRepository(null, new File("/tmp/fry"));
// repo.cloneRepo("https://github.com/nirima/snowglobe-test-lib1");
//repo.cloneRepo("https://github.com/AllocateSoftware/support", new C);
}
} | mit |
ericminio/sandbox | spring-boot-test/src/main/java/ericminio/demo/profiles/ShouldBeUsed.java | 299 | package ericminio.demo.profiles;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
@Component
@Profile("visible")
public class ShouldBeUsed implements Stuff {
@Override
public String getName() {
return "visible name";
}
}
| mit |
andrjooshka/ForSchoolWithContracts | src/main/java/tap/execounting/entities/TeacherAddition.java | 1748 | package tap.execounting.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
@Entity
@Table(name = "teacher_addition")
@NamedQueries({
@NamedQuery(name = TeacherAddition.BY_TEACHER_ID, query = "from TeacherAddition where teacherId=:id")
})
public class TeacherAddition {
public static final String BY_TEACHER_ID="TeacherAddition.byTeacherId";
@Id
@Column(name = "addition_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column(name = "teacher_id", unique = true, nullable = false)
private int teacherId;
private String field_1;
private String field_2;
private String field_3;
private String field_4;
private String field_5;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getTeacherId() {
return teacherId;
}
public void setTeacherId(int teacherId) {
this.teacherId = teacherId;
}
public String getField_1() {
return field_1;
}
public void setField_1(String field_1) {
this.field_1 = field_1;
}
public String getField_2() {
return field_2;
}
public void setField_2(String field_2) {
this.field_2 = field_2;
}
public String getField_3() {
return field_3;
}
public void setField_3(String field_3) {
this.field_3 = field_3;
}
public String getField_4() {
return field_4;
}
public void setField_4(String field_4) {
this.field_4 = field_4;
}
public String getField_5() {
return field_5;
}
public void setField_5(String field_5) {
this.field_5 = field_5;
}
}
| mit |
hawkup/learn-web-programming | 09-java-rabbitmq-helloworld/src/main/java/com/hawkup/rabbitmq/Send.java | 928 | package com.hawkup.rabbitmq;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import java.util.concurrent.TimeoutException;
/**
* Created by hawkup on 5/19/16.
*/
public class Send {
private final static String QUEUE_NAME = "hello";
public static void main(String[] argv)
throws java.io.IOException, TimeoutException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
String message = "Hello World!";
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
System.out.println(" [x] Sent '" + message + "'");
channel.close();
connection.close();
}
}
| mit |
palfrey/robolectric | src/test/java/com/xtremelabs/robolectric/util/SchedulerTest.java | 3670 | package com.xtremelabs.robolectric.util;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
public class SchedulerTest {
private Transcript transcript;
private Scheduler scheduler;
@Before
public void setUp() throws Exception {
scheduler = new Scheduler();
scheduler.pause();
transcript = new Transcript();
}
@Test
public void testTick_ReturnsTrueIffSomeJobWasRun() throws Exception {
scheduler.postDelayed(new AddToTranscript("one"), 0);
scheduler.postDelayed(new AddToTranscript("two"), 0);
scheduler.postDelayed(new AddToTranscript("three"), 1000);
assertThat(scheduler.advanceBy(0), equalTo(true));
transcript.assertEventsSoFar("one", "two");
assertThat(scheduler.advanceBy(0), equalTo(false));
transcript.assertNoEventsSoFar();
assertThat(scheduler.advanceBy(1000), equalTo(true));
transcript.assertEventsSoFar("three");
}
@Test
public void testShadowPostDelayed() throws Exception {
scheduler.postDelayed(new AddToTranscript("one"), 1000);
scheduler.postDelayed(new AddToTranscript("two"), 2000);
scheduler.postDelayed(new AddToTranscript("three"), 3000);
scheduler.advanceBy(1000);
transcript.assertEventsSoFar("one");
scheduler.advanceBy(500);
transcript.assertNoEventsSoFar();
scheduler.advanceBy(501);
transcript.assertEventsSoFar("two");
scheduler.advanceBy(999);
transcript.assertEventsSoFar("three");
}
@Test
public void testShadowPostDelayed_WhenMoreItemsAreAdded() throws Exception {
scheduler.postDelayed(new Runnable() {
@Override
public void run() {
transcript.add("one");
scheduler.postDelayed(new Runnable() {
@Override
public void run() {
transcript.add("two");
scheduler.postDelayed(new AddToTranscript("three"), 1000);
}
}, 1000);
}
}, 1000);
scheduler.advanceBy(1000);
transcript.assertEventsSoFar("one");
scheduler.advanceBy(500);
transcript.assertNoEventsSoFar();
scheduler.advanceBy(501);
transcript.assertEventsSoFar("two");
scheduler.advanceBy(999);
transcript.assertEventsSoFar("three");
}
@Test
public void resetShouldUnPause() throws Exception {
scheduler.pause();
TestRunnable runnable = new TestRunnable();
scheduler.post(runnable);
assertThat(runnable.wasRun, equalTo(false));
scheduler.reset();
scheduler.post(runnable);
assertThat(runnable.wasRun, equalTo(true));
}
@Test
public void resetShouldClearPendingRunnables() throws Exception {
scheduler.pause();
TestRunnable runnable1 = new TestRunnable();
scheduler.post(runnable1);
assertThat(runnable1.wasRun, equalTo(false));
scheduler.reset();
TestRunnable runnable2 = new TestRunnable();
scheduler.post(runnable2);
assertThat(runnable1.wasRun, equalTo(false));
assertThat(runnable2.wasRun, equalTo(true));
}
private class AddToTranscript implements Runnable {
private String event;
public AddToTranscript(String event) {
this.event = event;
}
@Override
public void run() {
transcript.add(event);
}
}
}
| mit |
larsgrefer/GithubAndroidSdk | src/main/java/com/alorma/github/sdk/bean/dto/request/CreateRepoRequestDTO.java | 495 | package com.alorma.github.sdk.bean.dto.request;
import com.google.gson.annotations.SerializedName;
/**
* Created by Bernat on 13/10/2014.
*/
public class CreateRepoRequestDTO {
public String name;
public String description;
private String homepage;
@SerializedName("private")
public boolean isPrivate;
public boolean has_issues;
public boolean has_wiki;
public boolean has_downloads;
public boolean auto_init;
public String gitignore_template;
public String license_template;
}
| mit |
chuangxian/lib-edge | lib-edge-core/src/main/java/libedge/services/impl/SessionCacheService.java | 1893 | package libedge.services.impl;
import com.google.common.base.Charsets;
import com.google.common.hash.Hasher;
import com.google.common.hash.Hashing;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import javax.websocket.Session;
import java.util.Date;
import java.util.Map;
/**
* @author yrw
* @since 2018/3/6
*/
public class SessionCacheService {
private RedisTemplate<String, String> redisTemplate;
@Value("${session.expire.seconds}")
private Integer expireSeconds;
public SessionCacheService(RedisTemplate<String, String> redisTemplate){
this.redisTemplate = redisTemplate;
}
private String hashState(Map<String, String> state) {
Hasher hasher = Hashing.md5().newHasher();
state.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(entry -> {
hasher.putString(entry.getKey(), Charsets.UTF_8);
hasher.putString(entry.getValue() == null ? "" : entry.getValue(), Charsets.UTF_8);
});
return Hex.encodeHexString(hasher.hash().asBytes());
}
public String createCache(Map<String, String> state2cache) {
if (state2cache == null) {
return null;
}
String key = hashState(state2cache);
redisTemplate.delete(key);
redisTemplate.opsForHash().putAll(key, state2cache);
redisTemplate.expireAt(key, DateUtils.addMinutes(new Date(), expireSeconds));
return key;
}
public Map<String, String> getState(String key) {
HashOperations<String, String, String> hash = redisTemplate.opsForHash();
return hash.entries(key);
}
public void deleteState(String key) {
redisTemplate.delete(key);
}
}
| mit |
kuiwang/my-framework | src/main/java/com/fengjing/framework/struts2/model/Employee.java | 564 | package com.fengjing.framework.struts2.model;
public class Employee {
private long empid;
private String empname;
private Department department;
public long getEmpid() {
return empid;
}
public void setEmpid(long empid) {
this.empid = empid;
}
public String getEmpname() {
return empname;
}
public void setEmpname(String empname) {
this.empname = empname;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
}
| mit |
bhewett/mozu-java | mozu-java-core/src/main/java/com/mozu/api/resources/commerce/returns/ShipmentResource.java | 4443 | /**
* This code was auto-generated by a Codezu.
*
* Changes to this file may cause incorrect behavior and will be lost if
* the code is regenerated.
*/
package com.mozu.api.resources.commerce.returns;
import com.mozu.api.ApiContext;
import org.joda.time.DateTime;
import java.util.List;
import java.util.ArrayList;
import com.mozu.api.MozuClient;
import com.mozu.api.MozuClientFactory;
import com.mozu.api.MozuUrl;
import com.mozu.api.Headers;
import com.mozu.api.security.AuthTicket;
import org.apache.commons.lang.StringUtils;
/** <summary>
* Use the Return Shipments subresource to manage shipments for a return replacement.
* </summary>
*/
public class ShipmentResource {
///
/// <see cref="Mozu.Api.ApiContext"/>
///
private ApiContext _apiContext;
public ShipmentResource(ApiContext apiContext)
{
_apiContext = apiContext;
}
/**
* Retrieves the details of the specified return replacement shipment.
* <p><pre><code>
* Shipment shipment = new Shipment();
* Shipment shipment = shipment.getShipment( returnId, shipmentId);
* </code></pre></p>
* @param returnId Unique identifier of the return whose items you want to get.
* @param shipmentId Unique identifier of the shipment to retrieve.
* @return com.mozu.api.contracts.commerceruntime.fulfillment.Shipment
* @see com.mozu.api.contracts.commerceruntime.fulfillment.Shipment
*/
public com.mozu.api.contracts.commerceruntime.fulfillment.Shipment getShipment(String returnId, String shipmentId) throws Exception
{
return getShipment( returnId, shipmentId, null);
}
/**
* Retrieves the details of the specified return replacement shipment.
* <p><pre><code>
* Shipment shipment = new Shipment();
* Shipment shipment = shipment.getShipment( returnId, shipmentId, responseFields);
* </code></pre></p>
* @param responseFields Use this field to include those fields which are not included by default.
* @param returnId Unique identifier of the return whose items you want to get.
* @param shipmentId Unique identifier of the shipment to retrieve.
* @return com.mozu.api.contracts.commerceruntime.fulfillment.Shipment
* @see com.mozu.api.contracts.commerceruntime.fulfillment.Shipment
*/
public com.mozu.api.contracts.commerceruntime.fulfillment.Shipment getShipment(String returnId, String shipmentId, String responseFields) throws Exception
{
MozuClient<com.mozu.api.contracts.commerceruntime.fulfillment.Shipment> client = com.mozu.api.clients.commerce.returns.ShipmentClient.getShipmentClient( returnId, shipmentId, responseFields);
client.setContext(_apiContext);
client.executeRequest();
return client.getResult();
}
/**
* Creates a shipment from one or more packages associated with a return replacement.
* <p><pre><code>
* Shipment shipment = new Shipment();
* Package package = shipment.createPackageShipments( packageIds, returnId);
* </code></pre></p>
* @param returnId Unique identifier of the return whose items you want to get.
* @param packageIds List of unique identifiers for each package associated with this shipment. Not all packages must belong to the same shipment.
* @return List<com.mozu.api.contracts.commerceruntime.fulfillment.Package>
* @see com.mozu.api.contracts.commerceruntime.fulfillment.Package
* @see string
*/
public List<com.mozu.api.contracts.commerceruntime.fulfillment.Package> createPackageShipments(List<String> packageIds, String returnId) throws Exception
{
MozuClient<List<com.mozu.api.contracts.commerceruntime.fulfillment.Package>> client = com.mozu.api.clients.commerce.returns.ShipmentClient.createPackageShipmentsClient( packageIds, returnId);
client.setContext(_apiContext);
client.executeRequest();
return client.getResult();
}
/**
* Deletes a shipment for a return replacement.
* <p><pre><code>
* Shipment shipment = new Shipment();
* shipment.deleteShipment( returnId, shipmentId);
* </code></pre></p>
* @param returnId Unique identifier of the return whose items you want to get.
* @param shipmentId Unique identifier of the shipment to retrieve.
* @return
*/
public void deleteShipment(String returnId, String shipmentId) throws Exception
{
MozuClient client = com.mozu.api.clients.commerce.returns.ShipmentClient.deleteShipmentClient( returnId, shipmentId);
client.setContext(_apiContext);
client.executeRequest();
client.cleanupHttpConnection();
}
}
| mit |
lucionei/chamadotecnico | chamadosTecnicosFinal-ejb/src/main/java/com/lucionei/chamadostecnicosfinal/model/Cliente.java | 4083 | package com.lucionei.chamadostecnicosfinal.model;
import java.io.Serializable;
import java.util.Objects;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import org.hibernate.validator.constraints.NotEmpty;
/**
*
* @author Lucionei
*/
@Entity
@XmlRootElement
@Table(name = "CLIENTE")
public class Cliente implements Serializable, BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID_CLIENTE")
private Long id;
@NotNull(message = "Campo nome é obrigatório")
@NotEmpty
@Size(min = 1, max = 200, message = "Favor informar no mínimo 1 e no máximo 200 caracteres.")
@Column(name = "NOME", length = 200, nullable = false)
private String nome;
@NotNull
@NotEmpty
@Column(name = "TELEFONE", length = 20, nullable = false)
private String telefone;
@NotNull(message = "Campo telefone é obrigatório")
@NotEmpty
@Size(min = 1, max = 20, message = "Favor informar no mínimo 1 e no máximo 20 caracteres.")
@Column(name = "DOCUMENTO", length = 20, nullable = false)
private String documento;
@Column(name = "EMAIL", length = 120)
private String email;
@Embedded
Endereco endereco;
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
public String getDocumento() {
return documento;
}
public void setDocumento(String documento) {
this.documento = documento;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Endereco getEndereco() {
return endereco;
}
public void setEndereco(Endereco endereco) {
this.endereco = endereco;
}
@Override
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Override
public int hashCode() {
int hash = 3;
hash = 29 * hash + Objects.hashCode(this.getId());
hash = 29 * hash + Objects.hashCode(this.nome);
hash = 29 * hash + Objects.hashCode(this.telefone);
hash = 29 * hash + Objects.hashCode(this.documento);
hash = 29 * hash + Objects.hashCode(this.email);
hash = 29 * hash + Objects.hashCode(this.endereco);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Cliente other = (Cliente) obj;
if (!Objects.equals(this.nome, other.nome)) {
return false;
}
if (!Objects.equals(this.telefone, other.telefone)) {
return false;
}
if (!Objects.equals(this.documento, other.documento)) {
return false;
}
if (!Objects.equals(this.email, other.email)) {
return false;
}
if (!Objects.equals(this.getId(), other.getId())) {
return false;
}
return Objects.equals(this.endereco, other.endereco);
}
@Override
public String toString() {
return "Cliente{" + "ID=" + this.getId() + ", nome=" + nome + ", telefone=" + telefone + ", documento=" + documento + ", email=" + email + ", endereco=" + endereco + '}';
}
}
| mit |
Eptwalabha/shmup | MysteryBazookaDisaster/src/main/java/src/components/LockPosition.java | 403 | package src.components;
import com.artemis.Component;
/**
* User: Eptwalabha
* Date: 07/02/14
* Time: 10:25
*/
public class LockPosition extends Component {
public Position lockedPosition;
public LockPosition(Position position) {
lockedPosition = position;
}
public void setLockedPosition(Position lockedPosition) {
this.lockedPosition = lockedPosition;
}
}
| mit |
marcio-da-silva-arantes/ProOF | ProOFJava/src/ProOF/apl/sample2/problem/HTSP/HTSPEdge.java | 540 | /*
* 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 ProOF.apl.sample2.problem.HTSP;
/**
*
* @author marcio
*/
public class HTSPEdge {
public final int i; //source
public final int j; //destine
public HTSPEdge(int i, int j) {
this.i = i;
this.j = j;
}
@Override
public String toString() {
return String.format("[%2d -> %2d]", i, j);
}
}
| mit |
team1389/Simulation-Ohm | Simulation-Ohm/src/simulation/motor/element/CylinderElement.java | 351 | package simulation.motor.element;
public class CylinderElement extends Element {
public CylinderElement(double mass, double radius) {
super(mass, mass * radius * radius / 2, 0);
}
public CylinderElement(Material material, double radius, double length) {
this(material.getMass(radius * radius * Math.PI * length), radius);
}
}
| mit |
RunsCode/AppFacadeMVC | puremvc_appfacade/src/main/java/com/example/puremvc_appfacade/Runs/protocol/IView.java | 484 | package com.example.puremvc_appfacade.Runs.protocol;
/**
* Created by dev_wang on 2017/1/23.
*/
public interface IView {
void registerMediator(String key, Class cls);
void removeMediator(String key);
IMediator getMediator(String key);
boolean hasMediator(String key);
void notifyObservers(INotification notification);
void registerObserver(IObserver observer, String notificationName);
void removeObserver(Object context, String notificationName);
}
| mit |
pzagawa/DiamondJack | DiamondJack-Desktop/src/pl/pzagawa/game/engine/objects/set/DoorElementGameObject.java | 1098 | package pl.pzagawa.game.engine.objects.set;
import pl.pzagawa.game.engine.GameInstance;
import pl.pzagawa.game.engine.gfx.Screen;
import pl.pzagawa.game.engine.map.tiles.TileItem;
import pl.pzagawa.game.engine.objects.BoundingBox;
import pl.pzagawa.game.engine.objects.ViewObject;
//static object, that does nothing but renders
public class DoorElementGameObject
extends StaticGameObject
{
private boolean openDoors = false;
public DoorElementGameObject(GameInstance game, TileItem tile, int tileWidth, int tileHeight)
{
super(game, tile, tileWidth, tileHeight);
}
@Override
public void update()
{
if (!enabled)
return;
//slide door element tile down to parentObject (base)
if (openDoors)
{
if (y < parentObject.top())
{
y += 4;
} else {
//hide it at the base
enabled = false;
}
}
}
public void checkCollision(BoundingBox box)
{
}
@Override
public void setCollision()
{
openDoors = true;
}
@Override
public void render(Screen screen, ViewObject viewObject)
{
}
}
| mit |
konstructs/server-api | src/main/java/konstructs/utils/LSystem.java | 7606 | package konstructs.utils;
import java.util.Arrays;
import java.util.Collections;
/**
* LSystem is a class that represents a <a href="https://en.wikipedia.org/wiki/L-system">Lindenmayer system</a>
* named after the Hungarian biologist Aristid Lindenmayer. In short, one can say that an LSystem is a way to
* generate something that evolves over generations (called iterations in the LSystem). In an LSystem what is
* generated is String. It is generated from an initial string and a set of rules that changes the string each
* iteration. Wikipedia
* <a href="https://en.wikipedia.org/wiki/L-system#Example_1:_Algae">has a good example of a simple L-System</a>.
* In Konstructs it is mainly used to generate text strings that are programs for the
* {@link BlockMachine BlockMachine} class. One very good example of this is the
* <a href="https://github.com/konstructs/server-plugin-forest">forest plugin</a> that
* uses LSystem together with the BlockMachine class to generate trees that evolve over several generations.
* <p>
* This class implements an L-System in the following manner. It has a list of {@link ProductionRule rules}
* that are math against the input string. The longest matching rule is used. To know which is the longest
* matching rule we need to understand what a rule is. A rule has two values, The <code>predecessor</code>
* and the <code>successor</code>. The predecessor is the part of the rule that is matched against the
* input and the successor is the part of the rule that will be written to the output. The output of the LSystem
* is the next generation. Let's have a look at a simple example:
* </p>
* <pre>
* {@code
* Input string:
* AB
* Rules:
* A -> B
* B -> BB
* BB -> C
* }
* </pre>
* <p>
* Running this system for one iteration would take the input string <code>AB</code> and transform it to
* <code>BBB</code>. Why? The LSystem tries to find a rule that matches the beginning of the input. There is only one
* rule that matches {@code A -> B}. It will then write the successor of this rule to the output, i.e. "B".
* It now moves forward in the input as many characters as the matched rules predecessor, in this case it was "A" so
* it moves forward only one character. It then tries to match the input again, starting at the new position. This time
* it only matches the {@code B -> BB} rule so it writes to the output the successor of this rules,
* <code>BB</code>. Thus the output now contains <code>BBB</code> which is the second generation. If we now run the
* same system again over the output (that means that the input in the example above is changed to <code>BBB</code>),
* we get the next iteration. Using the same methodology we see that first the rule {@code BB -> C} matches, since
* it is the longest of the two matching rules {@code B -> BB} and {@code BB -> C}. Then the we move two
* characters forward in the input and now only the {@code B -> BB} rules matches. This means that the output
* of this iteration (the third generation) is <code>CBB</code>. If iterating once more we reached a final generation
* since only the {@code BB -> C} matches and the output is then <code>CC</code> which can never match any of the
* rules again. It is also possible (and common) that the rules of an LSystem can continue indefinitely. So that for
* each successor there will be a predecessor that can match.
* </p>
* <p>
* How are rules represented when used with this class? There is a base class {@link ProductionRule ProductionRule}
* and two concrete rule types. {@link DeterministicProductionRule DeterministicProductionRule} work just like in
* the example and {@link ProbabilisticProductionRule ProbabilisticProductionRule} have a set of weighted
* successors from which it will randomly choose one (probability is based on the weight). A simple example:
* </p>
* <pre>
* {@code
* ProbabilisticProduction randomProductions[] = {
* new ProbabilisticProduction(50, "c"),
* new ProbabilisticProduction(50, "ca")
* };
* ProductionRule rules[] = {
* new DeterministicProductionRule("a", "b"),
* new ProbabilisticProductionRule("b", randomProductions)
* };
* LSystem system = new LSystem(rules);
* String firstGeneration = system.iterate("a"); // Returns "b"
* system.iterate(firstGeneration); // Returns "c" or "ca"
* }
* </pre>
* */
public class LSystem {
private static boolean startsWith(StringBuilder builder, String str) {
final int length = str.length();
if(builder.length() < length)
return false;
for(int i = 0; i < length; i++) {
if(builder.charAt(i) != str.charAt(i))
return false;
}
return true;
}
private final ProductionRule[] rules;
/**
* Constructs a new immutable LSystem
* @param rules The rules that dicates the behaviour of this LSystem
*/
public LSystem(ProductionRule[] rules) {
Arrays.sort(rules);
Collections.reverse(Arrays.asList(rules));
this.rules = rules;
}
/**
* Find the first rule that matches the given production. This means that the production
* starts with the predecessor of the rule. Since the rules are sorted by the longest predecessor
* first this is guaranteed to be the longest matching rule.
* @param production The production to be searched for a matching rule
* @return The matching rule or null if none was found
*/
private ProductionRule longestMatch(StringBuilder production) {
for(ProductionRule rule: rules) {
if(startsWith(production, rule.getPredecessor())) {
return rule;
}
}
return null;
}
/**
* Run the LSysytem on a string and produce the next generation of this string.
* @param generation The current generation of the string
* @return The next generation of the string as determined by the LSystem rules
*/
public String iterate(String generation) {
StringBuilder current = new StringBuilder();
StringBuilder production = new StringBuilder(generation);
/* Iterate throught the whole production */
while(production.length() != 0) {
ProductionRule match = longestMatch(production);
if(match != null) {
/* If there is a matching rule, use its successor, and remove its
* predecessor from the production
*/
current.append(match.getSuccessor());
production.delete(0, match.getPredecessor().length());
} else {
/* if there is no matching rule, copy the initial character to the result
* and remove it from the production
*/
current.append(production.charAt(0));
production = production.deleteCharAt(0);
}
}
return current.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
LSystem lSystem = (LSystem) o;
return Arrays.equals(rules, lSystem.rules);
}
@Override
public int hashCode() {
return Arrays.hashCode(rules);
}
@Override
public String toString() {
return "LSystem(" +
"rules=" + Arrays.toString(rules) +
')';
}
}
| mit |
koen93/HybridAssignment | plugins/cordova-plugin-x-socialsharing/src/android/nl/xservices/plugins/SocialSharing.java | 26396 | package nl.xservices.plugins;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.*;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.text.Html;
import android.util.Base64;
import android.view.Gravity;
import android.widget.Toast;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SocialSharing extends CordovaPlugin {
private static final String ACTION_AVAILABLE_EVENT = "available";
private static final String ACTION_SHARE_EVENT = "share";
private static final String ACTION_CAN_SHARE_VIA = "canShareVia";
private static final String ACTION_CAN_SHARE_VIA_EMAIL = "canShareViaEmail";
private static final String ACTION_SHARE_VIA = "shareVia";
private static final String ACTION_SHARE_VIA_TWITTER_EVENT = "shareViaTwitter";
private static final String ACTION_SHARE_VIA_FACEBOOK_EVENT = "shareViaFacebook";
private static final String ACTION_SHARE_VIA_FACEBOOK_WITH_PASTEMESSAGEHINT = "shareViaFacebookWithPasteMessageHint";
private static final String ACTION_SHARE_VIA_WHATSAPP_EVENT = "shareViaWhatsApp";
private static final String ACTION_SHARE_VIA_INSTAGRAM_EVENT = "shareViaInstagram";
private static final String ACTION_SHARE_VIA_SMS_EVENT = "shareViaSMS";
private static final String ACTION_SHARE_VIA_EMAIL_EVENT = "shareViaEmail";
private static final int ACTIVITY_CODE_SEND = 1;
private static final int ACTIVITY_CODE_SENDVIAEMAIL = 2;
private static final int ACTIVITY_CODE_SENDVIAWHATSAPP = 3;
private CallbackContext _callbackContext;
private String pasteMessage;
private abstract class SocialSharingRunnable implements Runnable {
public CallbackContext callbackContext;
SocialSharingRunnable(CallbackContext cb) {
this.callbackContext = cb;
}
}
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
this._callbackContext = callbackContext; // only used for onActivityResult
this.pasteMessage = null;
if (ACTION_AVAILABLE_EVENT.equals(action)) {
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK));
return true;
} else if (ACTION_SHARE_EVENT.equals(action)) {
return doSendIntent(callbackContext, args.getString(0), args.getString(1), args.getJSONArray(2), args.getString(3), null, false);
} else if (ACTION_SHARE_VIA_TWITTER_EVENT.equals(action)) {
return doSendIntent(callbackContext, args.getString(0), args.getString(1), args.getJSONArray(2), args.getString(3), "twitter", false);
} else if (ACTION_SHARE_VIA_FACEBOOK_EVENT.equals(action)) {
return doSendIntent(callbackContext, args.getString(0), args.getString(1), args.getJSONArray(2), args.getString(3), "com.facebook.katana", false);
} else if (ACTION_SHARE_VIA_FACEBOOK_WITH_PASTEMESSAGEHINT.equals(action)) {
this.pasteMessage = args.getString(4);
return doSendIntent(callbackContext, args.getString(0), args.getString(1), args.getJSONArray(2), args.getString(3), "com.facebook.katana", false);
} else if (ACTION_SHARE_VIA_WHATSAPP_EVENT.equals(action)) {
if (notEmpty(args.getString(4))) {
return shareViaWhatsAppDirectly(callbackContext, args.getString(0), args.getString(1), args.getJSONArray(2), args.getString(3), args.getString(4));
} else {
return doSendIntent(callbackContext, args.getString(0), args.getString(1), args.getJSONArray(2), args.getString(3), "whatsapp", false);
}
} else if (ACTION_SHARE_VIA_INSTAGRAM_EVENT.equals(action)) {
if (notEmpty(args.getString(0))) {
copyHintToClipboard(args.getString(0), "Instagram paste message");
}
return doSendIntent(callbackContext, args.getString(0), args.getString(1), args.getJSONArray(2), args.getString(3), "instagram", false);
} else if (ACTION_CAN_SHARE_VIA.equals(action)) {
return doSendIntent(callbackContext, args.getString(0), args.getString(1), args.getJSONArray(2), args.getString(3), args.getString(4), true);
} else if (ACTION_CAN_SHARE_VIA_EMAIL.equals(action)) {
if (isEmailAvailable()) {
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK));
return true;
} else {
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "not available"));
return false;
}
} else if (ACTION_SHARE_VIA.equals(action)) {
return doSendIntent(callbackContext, args.getString(0), args.getString(1), args.getJSONArray(2), args.getString(3), args.getString(4), false);
} else if (ACTION_SHARE_VIA_SMS_EVENT.equals(action)) {
return invokeSMSIntent(callbackContext, args.getJSONObject(0), args.getString(1));
} else if (ACTION_SHARE_VIA_EMAIL_EVENT.equals(action)) {
return invokeEmailIntent(callbackContext, args.getString(0), args.getString(1), args.getJSONArray(2), args.isNull(3) ? null : args.getJSONArray(3), args.isNull(4) ? null : args.getJSONArray(4), args.isNull(5) ? null : args.getJSONArray(5));
} else {
callbackContext.error("socialSharing." + action + " is not a supported function. Did you mean '" + ACTION_SHARE_EVENT + "'?");
return false;
}
}
private boolean isEmailAvailable() {
final Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", "someone@domain.com", null));
return cordova.getActivity().getPackageManager().queryIntentActivities(intent, 0).size() > 0;
}
private boolean invokeEmailIntent(final CallbackContext callbackContext, final String message, final String subject, final JSONArray to, final JSONArray cc, final JSONArray bcc, final JSONArray files) throws JSONException {
final SocialSharing plugin = this;
cordova.getThreadPool().execute(new SocialSharingRunnable(callbackContext) {
public void run() {
final Intent draft = new Intent(Intent.ACTION_SEND_MULTIPLE);
if (notEmpty(message)) {
Pattern htmlPattern = Pattern.compile(".*\\<[^>]+>.*", Pattern.DOTALL);
if (htmlPattern.matcher(message).matches()) {
draft.putExtra(android.content.Intent.EXTRA_TEXT, Html.fromHtml(message));
draft.setType("text/html");
} else {
draft.putExtra(android.content.Intent.EXTRA_TEXT, message);
draft.setType("text/plain");
}
}
if (notEmpty(subject)) {
draft.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
}
try {
if (to != null && to.length() > 0) {
draft.putExtra(android.content.Intent.EXTRA_EMAIL, toStringArray(to));
}
if (cc != null && cc.length() > 0) {
draft.putExtra(android.content.Intent.EXTRA_CC, toStringArray(cc));
}
if (bcc != null && bcc.length() > 0) {
draft.putExtra(android.content.Intent.EXTRA_BCC, toStringArray(bcc));
}
if (files.length() > 0) {
final String dir = getDownloadDir();
if (dir != null) {
ArrayList<Uri> fileUris = new ArrayList<Uri>();
for (int i = 0; i < files.length(); i++) {
final Uri fileUri = getFileUriAndSetType(draft, dir, files.getString(i), subject, i);
if (fileUri != null) {
fileUris.add(fileUri);
}
}
if (!fileUris.isEmpty()) {
draft.putExtra(Intent.EXTRA_STREAM, fileUris);
}
}
}
} catch (Exception e) {
callbackContext.error(e.getMessage());
}
// this was added to start the intent in a new window as suggested in #300 to prevent crashes upon return
draft.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
draft.setType("application/octet-stream");
cordova.startActivityForResult(plugin, Intent.createChooser(draft, "Choose Email App"), ACTIVITY_CODE_SENDVIAEMAIL);
}
});
return true;
}
private String getDownloadDir() throws IOException {
// better check, otherwise it may crash the app
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
// we need to use external storage since we need to share to another app
final String dir = webView.getContext().getExternalFilesDir(null) + "/socialsharing-downloads";
createOrCleanDir(dir);
return dir;
} else {
return null;
}
}
private boolean doSendIntent(final CallbackContext callbackContext, final String msg, final String subject, final JSONArray files, final String url, final String appPackageName, final boolean peek) {
final CordovaInterface mycordova = cordova;
final CordovaPlugin plugin = this;
cordova.getThreadPool().execute(new SocialSharingRunnable(callbackContext) {
public void run() {
String message = msg;
final boolean hasMultipleAttachments = files.length() > 1;
final Intent sendIntent = new Intent(hasMultipleAttachments ? Intent.ACTION_SEND_MULTIPLE : Intent.ACTION_SEND);
sendIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
try {
if (files.length() > 0 && !"".equals(files.getString(0))) {
final String dir = getDownloadDir();
if (dir != null) {
ArrayList<Uri> fileUris = new ArrayList<Uri>();
Uri fileUri = null;
for (int i = 0; i < files.length(); i++) {
fileUri = getFileUriAndSetType(sendIntent, dir, files.getString(i), subject, i);
if (fileUri != null) {
fileUris.add(fileUri);
}
}
if (!fileUris.isEmpty()) {
if (hasMultipleAttachments) {
sendIntent.putExtra(Intent.EXTRA_STREAM, fileUris);
} else {
sendIntent.putExtra(Intent.EXTRA_STREAM, fileUri);
}
}
} else {
sendIntent.setType("text/plain");
}
} else {
sendIntent.setType("text/plain");
}
} catch (Exception e) {
callbackContext.error(e.getMessage());
}
if (notEmpty(subject)) {
sendIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
}
// add the URL to the message, as there seems to be no separate field
if (notEmpty(url)) {
if (notEmpty(message)) {
message += " " + url;
} else {
message = url;
}
}
if (notEmpty(message)) {
sendIntent.putExtra(android.content.Intent.EXTRA_TEXT, message);
// sometimes required when the user picks share via sms
if (Build.VERSION.SDK_INT < 21) { // LOLLIPOP
sendIntent.putExtra("sms_body", message);
}
}
// this was added to start the intent in a new window as suggested in #300 to prevent crashes upon return
sendIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (appPackageName != null) {
String packageName = appPackageName;
String passedActivityName = null;
if (packageName.contains("/")) {
String[] items = appPackageName.split("/");
packageName = items[0];
passedActivityName = items[1];
}
final ActivityInfo activity = getActivity(callbackContext, sendIntent, packageName);
if (activity != null) {
if (peek) {
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK));
} else {
sendIntent.addCategory(Intent.CATEGORY_LAUNCHER);
sendIntent.setComponent(new ComponentName(activity.applicationInfo.packageName,
passedActivityName != null ? passedActivityName : activity.name));
mycordova.startActivityForResult(plugin, sendIntent, 0);
if (pasteMessage != null) {
// add a little delay because target app (facebook only atm) needs to be started first
new Timer().schedule(new TimerTask() {
public void run() {
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
copyHintToClipboard(msg, pasteMessage);
showPasteMessage(pasteMessage);
}
});
}
}, 2000);
}
}
}
} else {
if (peek) {
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK));
} else {
mycordova.startActivityForResult(plugin, Intent.createChooser(sendIntent, null), ACTIVITY_CODE_SEND);
}
}
}
});
return true;
}
@SuppressLint("NewApi")
private void copyHintToClipboard(String msg, String label) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
return;
}
final ClipboardManager clipboard = (android.content.ClipboardManager) cordova.getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
final ClipData clip = android.content.ClipData.newPlainText(label, msg);
clipboard.setPrimaryClip(clip);
}
@SuppressLint("NewApi")
private void showPasteMessage(String label) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
return;
}
final Toast toast = Toast.makeText(webView.getContext(), label, Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
private Uri getFileUriAndSetType(Intent sendIntent, String dir, String image, String subject, int nthFile) throws IOException {
// we're assuming an image, but this can be any filetype you like
String localImage = image;
sendIntent.setType("image/*");
if (image.startsWith("http") || image.startsWith("www/")) {
String filename = getFileName(image);
localImage = "file://" + dir + "/" + filename;
if (image.startsWith("http")) {
// filename optimisation taken from https://github.com/EddyVerbruggen/SocialSharing-PhoneGap-Plugin/pull/56
URLConnection connection = new URL(image).openConnection();
String disposition = connection.getHeaderField("Content-Disposition");
if (disposition != null) {
final Pattern dispositionPattern = Pattern.compile("filename=([^;]+)");
Matcher matcher = dispositionPattern.matcher(disposition);
if (matcher.find()) {
filename = matcher.group(1).replaceAll("[^a-zA-Z0-9._-]", "");
if (filename.length() == 0) {
// in this case we can't determine a filetype so some targets (gmail) may not render it correctly
filename = "file";
}
localImage = "file://" + dir + "/" + filename;
}
}
saveFile(getBytes(connection.getInputStream()), dir, filename);
} else {
saveFile(getBytes(webView.getContext().getAssets().open(image)), dir, filename);
}
} else if (image.startsWith("data:")) {
// safeguard for https://code.google.com/p/android/issues/detail?id=7901#c43
if (!image.contains(";base64,")) {
sendIntent.setType("text/plain");
return null;
}
// image looks like this: data:image/png;base64,R0lGODlhDAA...
final String encodedImg = image.substring(image.indexOf(";base64,") + 8);
// correct the intent type if anything else was passed, like a pdf: data:application/pdf;base64,..
if (!image.contains("data:image/")) {
sendIntent.setType(image.substring(image.indexOf("data:") + 5, image.indexOf(";base64")));
}
// the filename needs a valid extension, so it renders correctly in target apps
final String imgExtension = image.substring(image.indexOf("/") + 1, image.indexOf(";base64"));
String fileName;
// if a subject was passed, use it as the filename
// filenames must be unique when passing in multiple files [#158]
if (notEmpty(subject)) {
fileName = sanitizeFilename(subject) + (nthFile == 0 ? "" : "_" + nthFile) + "." + imgExtension;
} else {
fileName = "file" + (nthFile == 0 ? "" : "_" + nthFile) + "." + imgExtension;
}
saveFile(Base64.decode(encodedImg, Base64.DEFAULT), dir, fileName);
localImage = "file://" + dir + "/" + fileName;
} else if (image.startsWith("df:")) {
// safeguard for https://code.google.com/p/android/issues/detail?id=7901#c43
if (!image.contains(";base64,")) {
sendIntent.setType("text/plain");
return null;
}
// format looks like this : df:filename.txt;data:image/png;base64,R0lGODlhDAA...
final String fileName = image.substring(image.indexOf("df:") + 3, image.indexOf(";data:"));
final String fileType = image.substring(image.indexOf(";data:") + 6, image.indexOf(";base64,"));
final String encodedImg = image.substring(image.indexOf(";base64,") + 8);
sendIntent.setType(fileType);
saveFile(Base64.decode(encodedImg, Base64.DEFAULT), dir, sanitizeFilename(fileName));
localImage = "file://" + dir + "/" + fileName;
} else if (!image.startsWith("file://")) {
throw new IllegalArgumentException("URL_NOT_SUPPORTED");
}
return Uri.parse(localImage);
}
private boolean shareViaWhatsAppDirectly(final CallbackContext callbackContext, String message, final String subject, final JSONArray files, final String url, final String number) {
// add the URL to the message, as there seems to be no separate field
if (notEmpty(url)) {
if (notEmpty(message)) {
message += " " + url;
} else {
message = url;
}
}
final String shareMessage = message;
final SocialSharing plugin = this;
cordova.getThreadPool().execute(new SocialSharingRunnable(callbackContext) {
public void run() {
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("smsto:" + number));
intent.putExtra("sms_body", shareMessage);
intent.putExtra("sms_subject", subject);
intent.setPackage("com.whatsapp");
try {
if (files.length() > 0 && !"".equals(files.getString(0))) {
final boolean hasMultipleAttachments = files.length() > 1;
final String dir = getDownloadDir();
if (dir != null) {
ArrayList<Uri> fileUris = new ArrayList<Uri>();
Uri fileUri = null;
for (int i = 0; i < files.length(); i++) {
fileUri = getFileUriAndSetType(intent, dir, files.getString(i), subject, i);
if (fileUri != null) {
fileUris.add(fileUri);
}
}
if (!fileUris.isEmpty()) {
if (hasMultipleAttachments) {
intent.putExtra(Intent.EXTRA_STREAM, fileUris);
} else {
intent.putExtra(Intent.EXTRA_STREAM, fileUri);
}
}
}
}
} catch (Exception e) {
callbackContext.error(e.getMessage());
}
try {
// this was added to start the intent in a new window as suggested in #300 to prevent crashes upon return
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
cordova.startActivityForResult(plugin, intent, ACTIVITY_CODE_SENDVIAWHATSAPP);
} catch (Exception e) {
callbackContext.error(e.getMessage());
}
}
});
return true;
}
private boolean invokeSMSIntent(final CallbackContext callbackContext, JSONObject options, String p_phonenumbers) {
final String message = options.optString("message");
// TODO test this on a real SMS enabled device before releasing it
// final String subject = options.optString("subject");
// final String image = options.optString("image");
final String subject = null; //options.optString("subject");
final String image = null; // options.optString("image");
final String phonenumbers = getPhoneNumbersWithManufacturerSpecificSeparators(p_phonenumbers);
final SocialSharing plugin = this;
cordova.getThreadPool().execute(new SocialSharingRunnable(callbackContext) {
public void run() {
Intent intent;
if (Build.VERSION.SDK_INT >= 19) { // Build.VERSION_CODES.KITKAT) {
// passing in no phonenumbers for kitkat may result in an error,
// but it may also work for some devices, so documentation will need to cover this case
intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("smsto:" + (notEmpty(phonenumbers) ? phonenumbers : "")));
} else {
intent = new Intent(Intent.ACTION_VIEW);
intent.setType("vnd.android-dir/mms-sms");
if (phonenumbers != null) {
intent.putExtra("address", phonenumbers);
}
}
intent.putExtra("sms_body", message);
intent.putExtra("sms_subject", subject);
try {
if (image != null && !"".equals(image)) {
final Uri fileUri = getFileUriAndSetType(intent, getDownloadDir(), image, subject, 0);
if (fileUri != null) {
intent.putExtra(Intent.EXTRA_STREAM, fileUri);
}
}
// this was added to start the intent in a new window as suggested in #300 to prevent crashes upon return
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
cordova.startActivityForResult(plugin, intent, 0);
} catch (Exception e) {
callbackContext.error(e.getMessage());
}
}
});
return true;
}
private static String getPhoneNumbersWithManufacturerSpecificSeparators(String phonenumbers) {
if (notEmpty(phonenumbers)) {
char separator;
if (android.os.Build.MANUFACTURER.equalsIgnoreCase("samsung")) {
separator = ',';
} else {
separator = ';';
}
return phonenumbers.replace(';', separator).replace(',', separator);
}
return null;
}
private ActivityInfo getActivity(final CallbackContext callbackContext, final Intent shareIntent, final String appPackageName) {
final PackageManager pm = webView.getContext().getPackageManager();
List<ResolveInfo> activityList = pm.queryIntentActivities(shareIntent, 0);
for (final ResolveInfo app : activityList) {
if ((app.activityInfo.packageName).contains(appPackageName)) {
return app.activityInfo;
}
}
// no matching app found
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, getShareActivities(activityList)));
return null;
}
private JSONArray getShareActivities(List<ResolveInfo> activityList) {
List<String> packages = new ArrayList<String>();
for (final ResolveInfo app : activityList) {
packages.add(app.activityInfo.packageName);
}
return new JSONArray(packages);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (_callbackContext != null) {
if (ACTIVITY_CODE_SENDVIAEMAIL == requestCode) {
_callbackContext.success();
} else {
_callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, resultCode == Activity.RESULT_OK));
}
}
}
private void createOrCleanDir(final String downloadDir) throws IOException {
final File dir = new File(downloadDir);
if (!dir.exists()) {
if (!dir.mkdirs()) {
throw new IOException("CREATE_DIRS_FAILED");
}
} else {
cleanupOldFiles(dir);
}
}
private static String getFileName(String url) {
if (url.endsWith("/")) {
url = url.substring(0, url.length()-1);
}
final String pattern = ".*/([^?#]+)?";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(url);
if (m.find()) {
return m.group(1);
} else {
return "file";
}
}
private byte[] getBytes(InputStream is) throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[16384];
while ((nRead = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
return buffer.toByteArray();
}
private void saveFile(byte[] bytes, String dirName, String fileName) throws IOException {
final File dir = new File(dirName);
final FileOutputStream fos = new FileOutputStream(new File(dir, fileName));
fos.write(bytes);
fos.flush();
fos.close();
}
/**
* As file.deleteOnExit does not work on Android, we need to delete files manually.
* Deleting them in onActivityResult is not a good idea, because for example a base64 encoded file
* will not be available for upload to Facebook (it's deleted before it's uploaded).
* So the best approach is deleting old files when saving (sharing) a new one.
*/
private void cleanupOldFiles(File dir) {
for (File f : dir.listFiles()) {
//noinspection ResultOfMethodCallIgnored
f.delete();
}
}
private static boolean notEmpty(String what) {
return what != null &&
!"".equals(what) &&
!"null".equalsIgnoreCase(what);
}
private static String[] toStringArray(JSONArray jsonArray) throws JSONException {
String[] result = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
result[i] = jsonArray.getString(i);
}
return result;
}
public static String sanitizeFilename(String name) {
return name.replaceAll("[:\\\\/*?|<> ]", "_");
}
}
| mit |
angeliferreira/environment | src/main/java/br/com/lemao/environment/exception/EnvironmentHierarchyException.java | 343 | package br.com.lemao.environment.exception;
public class EnvironmentHierarchyException extends EnvironmentException {
private static final long serialVersionUID = -8816563652053350425L;
public EnvironmentHierarchyException(Class<?> environmentClass) {
super("Missing 'extends Environment' or @Environment !?", environmentClass);
}
}
| mit |
asciiCerebrum/neocortexEngine | src/test/java/org/asciicerebrum/neocortexengine/integrationtests/pool/inventoryItems/armors/StandardStuddedLeather.java | 482 | package org.asciicerebrum.neocortexengine.integrationtests.pool.inventoryItems.armors;
import org.asciicerebrum.neocortexengine.domain.setup.ArmorSetup;
/**
*
* @author species8472
*/
public class StandardStuddedLeather {
public static ArmorSetup getSetup() {
final ArmorSetup armor = new ArmorSetup();
armor.setId("standardStuddedLeather");
armor.setName("studdedLeather");
armor.setSizeCategory("medium");
return armor;
}
}
| mit |
selvasingh/azure-sdk-for-java | sdk/synapse/mgmt-v2019_06_01_preview/src/main/java/com/microsoft/azure/management/synapse/v2019_06_01_preview/WorkspacePatchInfo.java | 2860 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.synapse.v2019_06_01_preview;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.microsoft.rest.serializer.JsonFlatten;
/**
* Workspace patch details.
*/
@JsonFlatten
public class WorkspacePatchInfo {
/**
* Resource tags.
*/
@JsonProperty(value = "tags")
private Map<String, String> tags;
/**
* The identity of the workspace.
*/
@JsonProperty(value = "identity")
private ManagedIdentity identity;
/**
* SQL administrator login password.
*/
@JsonProperty(value = "properties.sqlAdministratorLoginPassword")
private String sqlAdministratorLoginPassword;
/**
* Resource provisioning state.
*/
@JsonProperty(value = "properties.provisioningState", access = JsonProperty.Access.WRITE_ONLY)
private String provisioningState;
/**
* Get resource tags.
*
* @return the tags value
*/
public Map<String, String> tags() {
return this.tags;
}
/**
* Set resource tags.
*
* @param tags the tags value to set
* @return the WorkspacePatchInfo object itself.
*/
public WorkspacePatchInfo withTags(Map<String, String> tags) {
this.tags = tags;
return this;
}
/**
* Get the identity of the workspace.
*
* @return the identity value
*/
public ManagedIdentity identity() {
return this.identity;
}
/**
* Set the identity of the workspace.
*
* @param identity the identity value to set
* @return the WorkspacePatchInfo object itself.
*/
public WorkspacePatchInfo withIdentity(ManagedIdentity identity) {
this.identity = identity;
return this;
}
/**
* Get sQL administrator login password.
*
* @return the sqlAdministratorLoginPassword value
*/
public String sqlAdministratorLoginPassword() {
return this.sqlAdministratorLoginPassword;
}
/**
* Set sQL administrator login password.
*
* @param sqlAdministratorLoginPassword the sqlAdministratorLoginPassword value to set
* @return the WorkspacePatchInfo object itself.
*/
public WorkspacePatchInfo withSqlAdministratorLoginPassword(String sqlAdministratorLoginPassword) {
this.sqlAdministratorLoginPassword = sqlAdministratorLoginPassword;
return this;
}
/**
* Get resource provisioning state.
*
* @return the provisioningState value
*/
public String provisioningState() {
return this.provisioningState;
}
}
| mit |
IanField90/Coursework | Part 2/CS2TS6/S1DrawTalk/src/cs2ts6/packets/Packet.java | 213 | package cs2ts6.packets;
import java.io.Serializable;
/**
*
* @author stephen
*
*/
public abstract class Packet implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
}
| mit |
Hbas/androidrules | src/test/java/com/github/hbas/rules/RuleEngineTest.java | 1408 | package com.github.hbas.rules;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import com.github.hbas.rules.test_utils.BuzzRule;
import com.github.hbas.rules.test_utils.FizzBuzzRule;
import com.github.hbas.rules.test_utils.FizzRule;
public class RuleEngineTest {
private RuleEngine<FactsWithObjects> engine;
@Before
public void setupEngine() {
this.engine = new RuleEngine<FactsWithObjects>();
engine.register(new FizzRule());
engine.register(new BuzzRule());
engine.register(new FizzBuzzRule());
}
@Test
public void when1_nothing() {
FactsWithObjects facts = new FactsWithObjects();
facts.put("number", 1);
engine.fire(facts);
assertFalse(facts.is("fizz"));
assertFalse(facts.is("buzz"));
}
@Test
public void when6_fizz() {
FactsWithObjects facts = new FactsWithObjects();
facts.put("number", 6);
engine.fire(facts);
assertTrue(facts.is("fizz"));
assertFalse(facts.is("buzz"));
}
@Test
public void when5_buzz() {
FactsWithObjects facts = new FactsWithObjects();
facts.put("number", 5);
engine.fire(facts);
assertFalse(facts.is("fizz"));
assertTrue(facts.is("buzz"));
}
@Test
public void when15_fizzbuzz() {
FactsWithObjects facts = new FactsWithObjects();
facts.put("number", 15);
engine.fire(facts);
assertTrue(facts.is("fizzbuzz"));
}
}
| mit |
detienne11/imie | app-inject/app-inject-run/src/main/java/fr/imie/training/cdi13/dav/tpinject/cdi/service/EnvoiMessageService.java | 163 | package fr.imie.training.cdi13.dav.tpinject.cdi.service;
public interface EnvoiMessageService {
public void envoiMessage(String msg, String sendTo);
}
| mit |
techa03/goodsKill | goodskill-mongo-provider/goodskill-mongo-service/src/main/java/com/goodskill/mongo/service/impl/MongoReactiveServiceImpl.java | 1383 | package com.goodskill.mongo.service.impl;
import com.goodskill.mongo.entity.SuccessKilled;
import com.goodskill.mongo.entity.SuccessKilledDto;
import com.goodskill.mongo.repository.SuceessKillRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;
import java.math.BigInteger;
import java.util.UUID;
/**
* @author heng
*/
@Slf4j
@Service
public class MongoReactiveServiceImpl {
@Autowired
private SuceessKillRepository suceessKillRepository;
public Mono<Boolean> deleteRecord(long seckillId) {
return suceessKillRepository.deleteBySeckillId(BigInteger.valueOf(seckillId)).thenReturn(true);
}
public Mono<Boolean> saveRecord(SuccessKilledDto successKilledDto) {
return suceessKillRepository.insert(SuccessKilled.builder()
.id(UUID.randomUUID().toString())
.seckillId(successKilledDto.getSeckillId())
.userPhone(successKilledDto.getUserPhone())
.build())
.doOnSuccess(n -> log.info("mongo秒杀记录插入成功:{}", n)).thenReturn(true);
}
public Mono<Long> count(long seckillId) {
return suceessKillRepository.findBySeckillId(BigInteger.valueOf(seckillId)).count();
}
} | mit |
jfmyers9/LagerLogger | src/main/java/com/jfmyers9/LagerLoggerApplication.java | 117 | package com.jfmyers9;
import android.app.Application;
public class LagerLoggerApplication extends Application {
}
| mit |
jawher/min-bug-tra | src/main/java/min/bug/tra/domain/TaskRepository.java | 2630 | package min.bug.tra.domain;
import static min.bug.tra.domain.JdbcCanBeNice.cachingConnectionProvider;
import static min.bug.tra.domain.JdbcCanBeNice.doWithConnection;
import static min.bug.tra.domain.JdbcCanBeNice.dontThrowSqlException;
import static min.bug.tra.domain.JdbcCanBeNice.sqlQuery;
import static min.bug.tra.domain.JdbcCanBeNice.sqlTx;
import static min.bug.tra.domain.JdbcCanBeNice.sqlUpdate;
import static min.bug.tra.domain.JdbcCanBeNice.sqlUpdateAndReturnKey;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.NoSuchElementException;
import min.bug.tra.domain.JdbcCanBeNice.ConnectionProvider;
import min.bug.tra.domain.JdbcCanBeNice.RowMapper;
public class TaskRepository {
private static ConnectionProvider connectionProvider = cachingConnectionProvider(JdbcCanBeNice.driverManagerConnectionProvider("org.hsqldb.jdbc.JDBCDriver", "jdbc:hsqldb:file:db/db", "", ""));
private static final RowMapper<Task> TASK_MAPPER = new RowMapper<Task>() {
public Task mapRow(ResultSet resultSet, int row) throws SQLException {
return new Task(resultSet.getLong("id"), resultSet
.getString("title"), resultSet.getString("description"),
Task.TaskType.valueOf(resultSet.getString("task_type")),
Task.TaskStatus.valueOf(resultSet.getString("task_status")));
}
};
public List<Task> selectAll() {
return doWithConnection(sqlQuery("select * from task", TASK_MAPPER),
connectionProvider);
}
public Task selectById(Long id) {
List<Task> list = doWithConnection(sqlQuery(
"select * from task where id=?", TASK_MAPPER, id),
connectionProvider);
if (list.size() == 1) {
return list.get(0);
} else {
throw new NoSuchElementException();
}
}
public Task insert(Task task) {
Long key = doWithConnection(
sqlTx(sqlUpdateAndReturnKey(
"insert into task(title, description, task_type, task_status) values(?, ?, ?, ?)",
task.getTitle(), task.getDescription(), task.getType()
.toString(), task.getStatus().toString())),
connectionProvider).longValue();
task.setId(key);
return task;
}
public boolean update(Task task) {
return doWithConnection(
sqlTx(sqlUpdate(
"update task set title=?, description=?, task_type=?, task_status=? where id=?",
task.getTitle(), task.getDescription(), task.getType()
.toString(), task.getStatus().toString(), task
.getId())), connectionProvider) > 0;
}
public boolean deleteById(Long id) {
return doWithConnection(sqlTx(sqlUpdate("delete from task where id=?",
id)), connectionProvider) > 0;
}
}
| mit |
glipecki/watson | watson-business/src/main/java/net/lipecki/watson/productprice/GetProductPriceQuery.java | 5593 | package net.lipecki.watson.productprice;
import lombok.extern.slf4j.Slf4j;
import net.lipecki.watson.WatsonException;
import net.lipecki.watson.category.Category;
import net.lipecki.watson.category.GetCategoryQuery;
import net.lipecki.watson.producer.Producer;
import net.lipecki.watson.product.GetProductQuery;
import net.lipecki.watson.product.Product;
import net.lipecki.watson.reatialchain.RetailChain;
import net.lipecki.watson.shop.GetShopQuery;
import net.lipecki.watson.shop.Shop;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@Slf4j
@Service
public class GetProductPriceQuery {
private final ProductPriceRepository repository;
private final GetCategoryQuery categoryQuery;
private final GetShopQuery shopQuery;
private final GetProductQuery productQuery;
public GetProductPriceQuery(
final ProductPriceRepository repository,
final GetCategoryQuery categoryQuery,
final GetShopQuery shopQuery,
final GetProductQuery productQuery) {
this.repository = repository;
this.categoryQuery = categoryQuery;
this.shopQuery = shopQuery;
this.productQuery = productQuery;
}
public ProductPriceReport getProductPriceReport(final String categoryUuid, final boolean includeSubcategories) {
final Category category = categoryQuery
.getCategory(categoryUuid)
.orElseThrow(WatsonException.supplier("Unknown category uuid: " + categoryUuid));
final ProductPriceReport.ProductPriceReportBuilder report = ProductPriceReport
.builder()
.categoryUuid(categoryUuid)
.includeSubcategories(includeSubcategories);
final List<ProductPriceReportItem> items = new ArrayList<>();
if (includeSubcategories) {
category.accept(subcategory -> items.addAll(getProductPriceReportItems(subcategory)));
} else {
items.addAll(getProductPriceReportItems(category));
}
report.items(items);
final ProductPriceReport result = report.build();
final Comparator<ProductPriceReportItem> byName = Comparator.comparing(item1 -> item1.getProduct().getName());
final Comparator<ProductPriceReportItem> byDateDesc = Comparator.comparing(ProductPriceReportItem::getDate).reversed();
result.getItems().sort(byName.thenComparing(byDateDesc));
return result;
}
private List<ProductPriceReportItem> getProductPriceReportItems(final Category category) {
return repository
.findAllByCategoryUuid(category.getUuid())
.map(price -> asReportItem(price, category))
.collect(Collectors.toList());
}
private ProductPriceReportItem asReportItem(final ProductPriceEntity price, final Category category) {
final Shop shop = shopQuery
.getShop(price.getShopUuid())
.orElseThrow(WatsonException.supplier("Missing shop for uuid: " + price.getShopUuid()));
final Product product = productQuery
.getProduct(price.getProductUuid())
.orElseThrow(WatsonException.supplier("Missing product for uuid: " + price.getProductUuid()));
return ProductPriceReportItem
.builder()
.id(price.getId())
.categoryPath(asCategoryPath(category))
.product(asProductDto(product))
.shop(asShopDto(shop))
.receipt(asReceiptDto())
.date(price.getDate())
.pricePerUnit(price.getPricePerUnit())
.unit(price.getUnit())
.build();
}
private List<ProductPriceReportItem.CategoryDto> asCategoryPath(final Category category) {
final List<ProductPriceReportItem.CategoryDto> path = new ArrayList<>();
Optional<Category> pathPart = Optional.of(category);
while (pathPart.isPresent()) {
path.add(
0,
pathPart.map(this::asCategory)
.orElseThrow(WatsonException.supplier("Path part should not be null"))
);
pathPart = pathPart.flatMap(Category::getParent);
}
return path;
}
private ProductPriceReportItem.CategoryDto asCategory(final Category part) {
return ProductPriceReportItem
.CategoryDto
.builder()
.name(part.getName())
.uuid(part.getUuid())
.build();
}
private ProductPriceReportItem.ProductDto asProductDto(final Product product) {
return ProductPriceReportItem
.ProductDto
.builder()
.name(product.getName())
.uuid(product.getUuid())
.producerName(product.getProducerOptional().map(Producer::getName).orElse(null))
.build();
}
private ProductPriceReportItem.ShopDto asShopDto(final Shop shop) {
return ProductPriceReportItem.ShopDto
.builder()
.name(shop.getName())
.uuid(shop.getUuid())
.retailChainName(shop.getRetailChainOptional().map(RetailChain::getName).orElse(null))
.build();
}
private ProductPriceReportItem.ReceiptInfoDto asReceiptDto() {
return ProductPriceReportItem.ReceiptInfoDto.builder().build();
}
}
| mit |
Lanceolata/code-problems | java/src/main/java/com/lanceolata/leetcode_easy/Question_124_Poor_Pigs.java | 341 | package com.lanceolata.leetcode_easy;
/**
* Created by lance on 2017/11/8.
*/
public class Question_124_Poor_Pigs {
public int poorPigs(int buckets, int minutesToDie, int minutesToTest) {
int pigs = 0;
while (Math.pow(minutesToTest / minutesToDie + 1, pigs) < buckets)
pigs++;
return pigs;
}
}
| mit |
jnovinger/DemoReader | app/src/androidTest/java/org/novinger/jason/demoreader/ApplicationTest.java | 360 | package org.novinger.jason.demoreader;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | mit |
plumer/codana | tomcat_files/8.0.22/RewriteValve.java | 31004 | /*
* 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.catalina.valves.rewrite;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.StringTokenizer;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import org.apache.catalina.Container;
import org.apache.catalina.Context;
import org.apache.catalina.Engine;
import org.apache.catalina.Host;
import org.apache.catalina.Lifecycle;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.Pipeline;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.util.URLEncoder;
import org.apache.catalina.valves.ValveBase;
import org.apache.tomcat.util.buf.CharChunk;
import org.apache.tomcat.util.buf.MessageBytes;
import org.apache.tomcat.util.http.RequestUtil;
import org.apache.tomcat.util.net.URL;
public class RewriteValve extends ValveBase {
/**
* The rewrite rules that the valve will use.
*/
protected RewriteRule[] rules = null;
/**
* If rewriting occurs, the whole request will be processed again.
*/
protected ThreadLocal<Boolean> invoked = new ThreadLocal<>();
/**
* Relative path to the configuration file.
* Note: If the valve's container is a context, this will be relative to
* /WEB-INF/.
*/
protected String resourcePath = "rewrite.config";
/**
* Will be set to true if the valve is associated with a context.
*/
protected boolean context = false;
/**
* enabled this component
*/
protected boolean enabled = true;
/**
* Maps to be used by the rules.
*/
protected Map<String, RewriteMap> maps = new Hashtable<>();
public boolean getEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
@Override
protected synchronized void startInternal() throws LifecycleException {
super.startInternal();
InputStream is = null;
// Process configuration file for this valve
if (getContainer() instanceof Context) {
context = true;
is = ((Context) getContainer()).getServletContext()
.getResourceAsStream("/WEB-INF/" + resourcePath);
if (container.getLogger().isDebugEnabled()) {
if (is == null) {
container.getLogger().debug("No configuration resource found: /WEB-INF/" + resourcePath);
} else {
container.getLogger().debug("Read configuration from: /WEB-INF/" + resourcePath);
}
}
} else if (getContainer() instanceof Host) {
String resourceName = getHostConfigPath(resourcePath);
File file = new File(getConfigBase(), resourceName);
try {
if (!file.exists()) {
if (resourceName != null) {
// Use getResource and getResourceAsStream
is = getClass().getClassLoader()
.getResourceAsStream(resourceName);
if (is != null && container.getLogger().isDebugEnabled()) {
container.getLogger().debug("Read configuration from CL at " + resourceName);
}
}
} else {
if (container.getLogger().isDebugEnabled()) {
container.getLogger().debug("Read configuration from " + file.getAbsolutePath());
}
is = new FileInputStream(file);
}
if ((is == null) && (container.getLogger().isDebugEnabled())) {
container.getLogger().debug("No configuration resource found: " + resourceName +
" in " + getConfigBase() + " or in the classloader");
}
} catch (Exception e) {
container.getLogger().error("Error opening configuration", e);
}
}
if (is == null) {
// Will use management operations to configure the valve dynamically
return;
}
try (InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
BufferedReader reader = new BufferedReader(isr)) {
parse(reader);
} catch (IOException ioe) {
container.getLogger().error("Error closing configuration", ioe);
} finally {
try {
is.close();
} catch (IOException e) {
container.getLogger().error("Error closing configuration", e);
}
}
}
public void setConfiguration(String configuration)
throws Exception {
maps.clear();
parse(new BufferedReader(new StringReader(configuration)));
}
public String getConfiguration() {
StringBuffer buffer = new StringBuffer();
// FIXME: Output maps if possible
for (int i = 0; i < rules.length; i++) {
for (int j = 0; j < rules[i].getConditions().length; j++) {
buffer.append(rules[i].getConditions()[j].toString()).append("\r\n");
}
buffer.append(rules[i].toString()).append("\r\n").append("\r\n");
}
return buffer.toString();
}
protected void parse(BufferedReader reader) throws LifecycleException {
ArrayList<RewriteRule> rules = new ArrayList<>();
ArrayList<RewriteCond> conditions = new ArrayList<>();
while (true) {
try {
String line = reader.readLine();
if (line == null) {
break;
}
Object result = parse(line);
if (result instanceof RewriteRule) {
RewriteRule rule = (RewriteRule) result;
if (container.getLogger().isDebugEnabled()) {
container.getLogger().debug("Add rule with pattern " + rule.getPatternString()
+ " and substitution " + rule.getSubstitutionString());
}
for (int i = (conditions.size() - 1); i > 0; i--) {
if (conditions.get(i - 1).isOrnext()) {
conditions.get(i).setOrnext(true);
}
}
for (int i = 0; i < conditions.size(); i++) {
if (container.getLogger().isDebugEnabled()) {
RewriteCond cond = conditions.get(i);
container.getLogger().debug("Add condition " + cond.getCondPattern()
+ " test " + cond.getTestString() + " to rule with pattern "
+ rule.getPatternString() + " and substitution "
+ rule.getSubstitutionString() + (cond.isOrnext() ? " [OR]" : "")
+ (cond.isNocase() ? " [NC]" : ""));
}
rule.addCondition(conditions.get(i));
}
conditions.clear();
rules.add(rule);
} else if (result instanceof RewriteCond) {
conditions.add((RewriteCond) result);
} else if (result instanceof Object[]) {
String mapName = (String) ((Object[]) result)[0];
RewriteMap map = (RewriteMap) ((Object[]) result)[1];
maps.put(mapName, map);
if (map instanceof Lifecycle) {
((Lifecycle) map).start();
}
}
} catch (IOException e) {
container.getLogger().error("Error reading configuration", e);
}
}
this.rules = rules.toArray(new RewriteRule[0]);
// Finish parsing the rules
for (int i = 0; i < this.rules.length; i++) {
this.rules[i].parse(maps);
}
}
@Override
protected synchronized void stopInternal() throws LifecycleException {
super.stopInternal();
Iterator<RewriteMap> values = maps.values().iterator();
while (values.hasNext()) {
RewriteMap map = values.next();
if (map instanceof Lifecycle) {
((Lifecycle) map).stop();
}
}
maps.clear();
rules = null;
}
@Override
public void invoke(Request request, Response response)
throws IOException, ServletException {
if (!getEnabled() || rules == null || rules.length == 0) {
getNext().invoke(request, response);
return;
}
if (invoked.get() == Boolean.TRUE) {
try {
getNext().invoke(request, response);
} finally {
invoked.set(null);
}
return;
}
try {
Resolver resolver = new ResolverImpl(request);
invoked.set(Boolean.TRUE);
// As long as MB isn't a char sequence or affiliated, this has to be
// converted to a string
MessageBytes urlMB = context ? request.getRequestPathMB() : request.getDecodedRequestURIMB();
urlMB.toChars();
CharSequence url = urlMB.getCharChunk();
CharSequence host = request.getServerName();
boolean rewritten = false;
boolean done = false;
for (int i = 0; i < rules.length; i++) {
RewriteRule rule = rules[i];
CharSequence test = (rule.isHost()) ? host : url;
CharSequence newtest = rule.evaluate(test, resolver);
if (newtest != null && !test.equals(newtest.toString())) {
if (container.getLogger().isDebugEnabled()) {
container.getLogger().debug("Rewrote " + test + " as " + newtest
+ " with rule pattern " + rule.getPatternString());
}
if (rule.isHost()) {
host = newtest;
} else {
url = newtest;
}
rewritten = true;
}
// Final reply
// - forbidden
if (rule.isForbidden() && newtest != null) {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
done = true;
break;
}
// - gone
if (rule.isGone() && newtest != null) {
response.sendError(HttpServletResponse.SC_GONE);
done = true;
break;
}
// - redirect (code)
if (rule.isRedirect() && newtest != null) {
// append the query string to the url if there is one and it hasn't been rewritten
String queryString = request.getQueryString();
StringBuffer urlString = new StringBuffer(url);
if (queryString != null && queryString.length() > 0) {
int index = urlString.indexOf("?");
if (index != -1) {
// if qsa is specified append the query
if (rule.isQsappend()) {
urlString.append('&');
urlString.append(queryString);
}
// if the ? is the last character delete it, its only purpose was to
// prevent the rewrite module from appending the query string
else if (index == urlString.length() - 1) {
urlString.deleteCharAt(index);
}
} else {
urlString.append('?');
urlString.append(queryString);
}
}
// Insert the context if
// 1. this valve is associated with a context
// 2. the url starts with a leading slash
// 3. the url isn't absolute
if (context && urlString.charAt(0) == '/' && !hasScheme(urlString)) {
urlString.insert(0, request.getContext().getEncodedPath());
}
response.sendRedirect(urlString.toString());
response.setStatus(rule.getRedirectCode());
done = true;
break;
}
// Reply modification
// - cookie
if (rule.isCookie() && newtest != null) {
Cookie cookie = new Cookie(rule.getCookieName(),
rule.getCookieResult());
cookie.setDomain(rule.getCookieDomain());
cookie.setMaxAge(rule.getCookieLifetime());
cookie.setPath(rule.getCookiePath());
cookie.setSecure(rule.isCookieSecure());
cookie.setHttpOnly(rule.isCookieHttpOnly());
response.addCookie(cookie);
}
// - env (note: this sets a request attribute)
if (rule.isEnv() && newtest != null) {
for (int j = 0; j < rule.getEnvSize(); j++) {
request.setAttribute(rule.getEnvName(j), rule.getEnvResult(j));
}
}
// - content type (note: this will not force the content type, use a filter
// to do that)
if (rule.isType() && newtest != null) {
request.setContentType(rule.getTypeValue());
}
// - qsappend
if (rule.isQsappend() && newtest != null) {
String queryString = request.getQueryString();
String urlString = url.toString();
if (urlString.indexOf('?') != -1 && queryString != null) {
url = urlString + "&" + queryString;
}
}
// Control flow processing
// - chain (skip remaining chained rules if this one does not match)
if (rule.isChain() && newtest == null) {
for (int j = i; j < rules.length; j++) {
if (!rules[j].isChain()) {
i = j;
break;
}
}
continue;
}
// - last (stop rewriting here)
if (rule.isLast() && newtest != null) {
break;
}
// - next (redo again)
if (rule.isNext() && newtest != null) {
i = 0;
continue;
}
// - skip (n rules)
if (newtest != null) {
i += rule.getSkip();
}
}
if (rewritten) {
if (!done) {
// See if we need to replace the query string
String urlString = url.toString();
String queryString = null;
int queryIndex = urlString.indexOf('?');
if (queryIndex != -1) {
queryString = urlString.substring(queryIndex+1);
urlString = urlString.substring(0, queryIndex);
}
// Set the new 'original' URI
String contextPath = null;
if (context) {
contextPath = request.getContextPath();
}
request.getCoyoteRequest().requestURI().setString(null);
CharChunk chunk = request.getCoyoteRequest().requestURI().getCharChunk();
chunk.recycle();
if (context) {
chunk.append(contextPath);
}
chunk.append(URLEncoder.DEFAULT.encode(urlString));
request.getCoyoteRequest().requestURI().toChars();
// Decoded and normalized URI
request.getCoyoteRequest().decodedURI().setString(null);
chunk = request.getCoyoteRequest().decodedURI().getCharChunk();
chunk.recycle();
if (context) {
chunk.append(contextPath);
}
chunk.append(RequestUtil.normalize(urlString));
request.getCoyoteRequest().decodedURI().toChars();
// Set the new Query if there is one
if (queryString != null) {
request.getCoyoteRequest().queryString().setString(null);
chunk = request.getCoyoteRequest().queryString().getCharChunk();
chunk.recycle();
chunk.append(queryString);
request.getCoyoteRequest().queryString().toChars();
}
// Set the new host if it changed
if (!host.equals(request.getServerName())) {
request.getCoyoteRequest().serverName().setString(null);
chunk = request.getCoyoteRequest().serverName().getCharChunk();
chunk.recycle();
chunk.append(host.toString());
request.getCoyoteRequest().serverName().toChars();
}
request.getMappingData().recycle();
// Reinvoke the whole request recursively
try {
Connector connector = request.getConnector();
if (!connector.getProtocolHandler().getAdapter().prepare(
request.getCoyoteRequest(), response.getCoyoteResponse())) {
return;
}
Pipeline pipeline = connector.getService().getContainer().getPipeline();
request.setAsyncSupported(pipeline.isAsyncSupported());
pipeline.getFirst().invoke(request, response);
} catch (Exception e) {
// This doesn't actually happen in the Catalina adapter implementation
}
}
} else {
getNext().invoke(request, response);
}
} finally {
invoked.set(null);
}
}
/**
* Get config base.
*/
protected File getConfigBase() {
File configBase =
new File(System.getProperty("catalina.base"), "conf");
if (!configBase.exists()) {
return null;
} else {
return configBase;
}
}
/**
* Find the configuration path where the rewrite configuration file
* will be stored.
*
* @param resourceName
*/
protected String getHostConfigPath(String resourceName) {
StringBuffer result = new StringBuffer();
Container container = getContainer();
Container host = null;
Container engine = null;
while (container != null) {
if (container instanceof Host)
host = container;
if (container instanceof Engine)
engine = container;
container = container.getParent();
}
if (engine != null) {
result.append(engine.getName()).append('/');
}
if (host != null) {
result.append(host.getName()).append('/');
}
result.append(resourceName);
return result.toString();
}
/**
* This factory method will parse a line formed like:
*
* Example:
* RewriteCond %{REMOTE_HOST} ^host1.* [OR]
*
* @param line A line from the rewrite configuration
*
* @return The condition, rule or map resulting from parsing the line
*/
public static Object parse(String line) {
StringTokenizer tokenizer = new StringTokenizer(line);
if (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
if (token.equals("RewriteCond")) {
// RewriteCond TestString CondPattern [Flags]
RewriteCond condition = new RewriteCond();
if (tokenizer.countTokens() < 2) {
throw new IllegalArgumentException("Invalid line: " + line);
}
condition.setTestString(tokenizer.nextToken());
condition.setCondPattern(tokenizer.nextToken());
if (tokenizer.hasMoreTokens()) {
String flags = tokenizer.nextToken();
if (flags.startsWith("[") && flags.endsWith("]")) {
flags = flags.substring(1, flags.length() - 1);
}
StringTokenizer flagsTokenizer = new StringTokenizer(flags, ",");
while (flagsTokenizer.hasMoreElements()) {
parseCondFlag(line, condition, flagsTokenizer.nextToken());
}
}
return condition;
} else if (token.equals("RewriteRule")) {
// RewriteRule Pattern Substitution [Flags]
RewriteRule rule = new RewriteRule();
if (tokenizer.countTokens() < 2) {
throw new IllegalArgumentException("Invalid line: " + line);
}
rule.setPatternString(tokenizer.nextToken());
rule.setSubstitutionString(tokenizer.nextToken());
if (tokenizer.hasMoreTokens()) {
String flags = tokenizer.nextToken();
if (flags.startsWith("[") && flags.endsWith("]")) {
flags = flags.substring(1, flags.length() - 1);
}
StringTokenizer flagsTokenizer = new StringTokenizer(flags, ",");
while (flagsTokenizer.hasMoreElements()) {
parseRuleFlag(line, rule, flagsTokenizer.nextToken());
}
}
return rule;
} else if (token.equals("RewriteMap")) {
// RewriteMap name rewriteMapClassName whateverOptionalParameterInWhateverFormat
if (tokenizer.countTokens() < 2) {
throw new IllegalArgumentException("Invalid line: " + line);
}
String name = tokenizer.nextToken();
String rewriteMapClassName = tokenizer.nextToken();
RewriteMap map = null;
try {
map = (RewriteMap) (Class.forName(rewriteMapClassName).newInstance());
} catch (Exception e) {
throw new IllegalArgumentException("Invalid map className: " + line);
}
if (tokenizer.hasMoreTokens()) {
map.setParameters(tokenizer.nextToken());
}
Object[] result = new Object[2];
result[0] = name;
result[1] = map;
return result;
} else if (token.startsWith("#")) {
// it's a comment, ignore it
} else {
throw new IllegalArgumentException("Invalid line: " + line);
}
}
return null;
}
/**
* Parser for RewriteCond flags.
*
* @param condition
* @param flag
*/
protected static void parseCondFlag(String line, RewriteCond condition, String flag) {
if (flag.equals("NC") || flag.equals("nocase")) {
condition.setNocase(true);
} else if (flag.equals("OR") || flag.equals("ornext")) {
condition.setOrnext(true);
} else {
throw new IllegalArgumentException("Invalid flag in: " + line + " flags: " + flag);
}
}
/**
* Parser for ReweriteRule flags.
*
* @param rule
* @param flag
*/
protected static void parseRuleFlag(String line, RewriteRule rule, String flag) {
if (flag.equals("chain") || flag.equals("C")) {
rule.setChain(true);
} else if (flag.startsWith("cookie=") || flag.startsWith("CO=")) {
rule.setCookie(true);
if (flag.startsWith("cookie")) {
flag = flag.substring("cookie=".length());
} else if (flag.startsWith("CO=")) {
flag = flag.substring("CO=".length());
}
StringTokenizer tokenizer = new StringTokenizer(flag, ":");
if (tokenizer.countTokens() < 2) {
throw new IllegalArgumentException("Invalid flag in: " + line);
}
rule.setCookieName(tokenizer.nextToken());
rule.setCookieValue(tokenizer.nextToken());
if (tokenizer.hasMoreTokens()) {
rule.setCookieDomain(tokenizer.nextToken());
}
if (tokenizer.hasMoreTokens()) {
try {
rule.setCookieLifetime(Integer.parseInt(tokenizer.nextToken()));
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid flag in: " + line, e);
}
}
if (tokenizer.hasMoreTokens()) {
rule.setCookiePath(tokenizer.nextToken());
}
if (tokenizer.hasMoreTokens()) {
rule.setCookieSecure(Boolean.parseBoolean(tokenizer.nextToken()));
}
if (tokenizer.hasMoreTokens()) {
rule.setCookieHttpOnly(Boolean.parseBoolean(tokenizer.nextToken()));
}
} else if (flag.startsWith("env=") || flag.startsWith("E=")) {
rule.setEnv(true);
if (flag.startsWith("env=")) {
flag = flag.substring("env=".length());
} else if (flag.startsWith("E=")) {
flag = flag.substring("E=".length());
}
int pos = flag.indexOf(':');
if (pos == -1 || (pos + 1) == flag.length()) {
throw new IllegalArgumentException("Invalid flag in: " + line);
}
rule.addEnvName(flag.substring(0, pos));
rule.addEnvValue(flag.substring(pos + 1));
} else if (flag.startsWith("forbidden") || flag.startsWith("F")) {
rule.setForbidden(true);
} else if (flag.startsWith("gone") || flag.startsWith("G")) {
rule.setGone(true);
} else if (flag.startsWith("host") || flag.startsWith("H")) {
rule.setHost(true);
} else if (flag.startsWith("last") || flag.startsWith("L")) {
rule.setLast(true);
} else if (flag.startsWith("next") || flag.startsWith("N")) {
rule.setNext(true);
} else if (flag.startsWith("nocase") || flag.startsWith("NC")) {
rule.setNocase(true);
} else if (flag.startsWith("noescape") || flag.startsWith("NE")) {
rule.setNoescape(true);
// FIXME: Proxy not supported, would require proxy capabilities in Tomcat
/* } else if (flag.startsWith("proxy") || flag.startsWith("P")) {
rule.setProxy(true);*/
} else if (flag.startsWith("qsappend") || flag.startsWith("QSA")) {
rule.setQsappend(true);
} else if (flag.startsWith("redirect") || flag.startsWith("R")) {
if (flag.startsWith("redirect=")) {
flag = flag.substring("redirect=".length());
rule.setRedirect(true);
rule.setRedirectCode(Integer.parseInt(flag));
} else if (flag.startsWith("R=")) {
flag = flag.substring("R=".length());
rule.setRedirect(true);
rule.setRedirectCode(Integer.parseInt(flag));
} else {
rule.setRedirect(true);
rule.setRedirectCode(HttpServletResponse.SC_FOUND);
}
} else if (flag.startsWith("skip") || flag.startsWith("S")) {
if (flag.startsWith("skip=")) {
flag = flag.substring("skip=".length());
} else if (flag.startsWith("S=")) {
flag = flag.substring("S=".length());
}
rule.setSkip(Integer.parseInt(flag));
} else if (flag.startsWith("type") || flag.startsWith("T")) {
if (flag.startsWith("type=")) {
flag = flag.substring("type=".length());
} else if (flag.startsWith("T=")) {
flag = flag.substring("T=".length());
}
rule.setType(true);
rule.setTypeValue(flag);
} else {
throw new IllegalArgumentException("Invalid flag in: " + line + " flag: " + flag);
}
}
/**
* Determine if a URI string has a <code>scheme</code> component.
*/
protected static boolean hasScheme(StringBuffer uri) {
int len = uri.length();
for(int i=0; i < len ; i++) {
char c = uri.charAt(i);
if(c == ':') {
return i > 0;
} else if(!URL.isSchemeChar(c)) {
return false;
}
}
return false;
}
}
| mit |
bladestery/Sapphire | example_apps/AndroidStudioMinnie/sapphire/src/main/java/boofcv/abst/tracker/Comaniciu2003_to_TrackerObjectQuad.java | 5078 | /*
* Copyright (c) 2011-2015, Peter Abeles. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package boofcv.abst.tracker;
import boofcv.alg.InputSanityCheck;
import boofcv.alg.filter.binary.GThresholdImageOps;
import boofcv.alg.filter.binary.ThresholdImageOps;
import boofcv.alg.filter.blur.BlurImageOps;
import boofcv.alg.filter.blur.GBlurImageOps;
import boofcv.alg.filter.blur.impl.ImplMedianHistogramInner;
import boofcv.alg.filter.blur.impl.ImplMedianSortEdgeNaive;
import boofcv.alg.filter.blur.impl.ImplMedianSortNaive;
import boofcv.alg.filter.convolve.ConvolveImageMean;
import boofcv.alg.filter.convolve.ConvolveImageNoBorder;
import boofcv.alg.filter.convolve.ConvolveNormalized;
import boofcv.alg.filter.convolve.border.ConvolveJustBorder_General;
import boofcv.alg.filter.convolve.noborder.ImplConvolveMean;
import boofcv.alg.filter.convolve.normalized.ConvolveNormalizedNaive;
import boofcv.alg.filter.convolve.normalized.ConvolveNormalized_JustBorder;
import boofcv.alg.filter.derivative.DerivativeHelperFunctions;
import boofcv.alg.filter.derivative.impl.GradientSobel_Outer;
import boofcv.alg.filter.derivative.impl.GradientSobel_UnrolledOuter;
import boofcv.alg.misc.GImageMiscOps;
import boofcv.alg.misc.GImageStatistics;
import boofcv.alg.misc.ImageMiscOps;
import boofcv.alg.misc.ImageStatistics;
import boofcv.alg.tracker.meanshift.TrackerMeanShiftComaniciu2003;
import boofcv.alg.transform.fft.DiscreteFourierTransformOps;
import boofcv.alg.transform.wavelet.UtilWavelet;
import boofcv.core.image.ConvertImage;
import boofcv.core.image.GeneralizedImageOps;
import boofcv.factory.distort.FactoryDistort;
import boofcv.factory.filter.blur.FactoryBlurFilter;
import boofcv.factory.filter.kernel.FactoryKernelGaussian;
import boofcv.factory.transform.pyramid.FactoryPyramid;
import boofcv.struct.RectangleRotate_F32;
import boofcv.struct.image.ImageBase;
import boofcv.struct.image.ImageType;
import georegression.struct.shapes.Quadrilateral_F64;
/**
* Wrapper around {@link TrackerMeanShiftComaniciu2003} for {@link TrackerObjectQuad}
*
* @author Peter Abeles
*/
public class Comaniciu2003_to_TrackerObjectQuad<T extends ImageBase>
implements TrackerObjectQuad<T>
{
TrackerMeanShiftComaniciu2003<T> alg;
RectangleRotate_F32 rectangle = new RectangleRotate_F32();
ImageType<T> type;
public Comaniciu2003_to_TrackerObjectQuad(TrackerMeanShiftComaniciu2003<T> alg, ImageType<T> type) {
this.alg = alg;
this.type = type;
}
@Override
public boolean initialize(T image, Quadrilateral_F64 location, GBlurImageOps GBIO, InputSanityCheck ISC, GeneralizedImageOps GIO, BlurImageOps BIO, ConvolveImageMean CIM,
FactoryKernelGaussian FKG, ConvolveNormalized CN, ConvolveNormalizedNaive CNN, ConvolveImageNoBorder CINB, ConvolveNormalized_JustBorder CNJB, ImplMedianHistogramInner IMHI,
ImplMedianSortEdgeNaive IMSEN, ImplMedianSortNaive IMSN, ImplConvolveMean ICM, GThresholdImageOps GTIO, GImageStatistics GIS, ImageStatistics IS, ThresholdImageOps TIO,
GImageMiscOps GIMO, ImageMiscOps IMO, FactoryBlurFilter FBF, ConvolveJustBorder_General CJBG, ConvertImage CI, UtilWavelet UW, DerivativeHelperFunctions DHF, GradientSobel_Outer GSO,
GradientSobel_UnrolledOuter GSUO, FactoryPyramid FP, DiscreteFourierTransformOps DFTO, ImageType IT, FactoryDistort FDs) {
Sfot_to_TrackObjectQuad.quadToRectRot(location,rectangle);
alg.initialize(image,rectangle);
return true;
}
@Override
public boolean process(T image, Quadrilateral_F64 location, GBlurImageOps GBIO, InputSanityCheck ISC, GeneralizedImageOps GIO, BlurImageOps BIO, ConvolveImageMean CIM,
FactoryKernelGaussian FKG, ConvolveNormalized CN, ConvolveNormalizedNaive CNN, ConvolveImageNoBorder CINB, ConvolveNormalized_JustBorder CNJB, ImplMedianHistogramInner IMHI,
ImplMedianSortEdgeNaive IMSEN, ImplMedianSortNaive IMSN, ImplConvolveMean ICM, GThresholdImageOps GTIO, GImageStatistics GIS, ImageStatistics IS, ThresholdImageOps TIO,
GImageMiscOps GIMO, ImageMiscOps IMO, FactoryBlurFilter FBF, ConvolveJustBorder_General CJBG, ConvertImage CI, UtilWavelet UW, DerivativeHelperFunctions DHF, GradientSobel_Outer GSO,
GradientSobel_UnrolledOuter GSUO, FactoryPyramid FP, DiscreteFourierTransformOps DFTO, ImageType IT, FactoryDistort FDs) {
alg.track(image);
Sfot_to_TrackObjectQuad.rectRotToQuad(alg.getRegion(),location);
return true;
}
@Override
public ImageType<T> getImageType() {
return type;
}
}
| mit |
andyadc/scaffold | scaffold-util/src/main/java/com/andyadc/scaffold/util/number/MathUtils.java | 4369 | package com.andyadc.scaffold.util.number;
import com.google.common.math.IntMath;
import com.google.common.math.LongMath;
import java.math.RoundingMode;
/**
* 数学相关工具类.包括
* <p>
* 1. 2的倍数的计算
* 2. 其他函数如最大公约数, 乘方,开方,安全的取模,可控制取整方向的相除等。
*
* @author andaicheng
* @version 2017/4/23
*/
public final class MathUtils {
private MathUtils() {
}
/////// 2 的倍数的计算////
/**
* 往上找出最接近的2的倍数,比如15返回16, 17返回32.
*
* @param value 必须为正数,否则抛出异常.
*/
public static int nextPowerOfTwo(final int value) {
return IntMath.ceilingPowerOfTwo(value);
}
/**
* 往上找出最接近的2的倍数,比如15返回16, 17返回32.
*
* @param value 必须为正数,否则抛出异常.
*/
public static long nextPowerOfTwo(final long value) {
return LongMath.ceilingPowerOfTwo(value);
}
/**
* 往下找出最接近2的倍数,比如15返回8, 17返回16.
*
* @param value 必须为正数,否则抛出异常.
*/
public static int previousPowerOfTwo(final int value) {
return IntMath.floorPowerOfTwo(value);
}
/**
* 往下找出最接近2的倍数,比如15返回8, 17返回16.
*
* @param value 必须为正数,否则抛出异常.
*/
public static long previousPowerOfTwo(final long value) {
return LongMath.floorPowerOfTwo(value);
}
/**
* 是否2的倍数
*
* @param value 不是正数时总是返回false
*/
public static boolean isPowerOfTwo(int value) {
return IntMath.isPowerOfTwo(value);
}
/**
* 是否2的倍数
*
* @param value <=0 时总是返回false
*/
public static boolean isPowerOfTwo(final long value) {
return LongMath.isPowerOfTwo(value);
}
/**
* 当模为2的倍数时,用比取模块更快的方式计算.
*
* @param value 可以为负数,比如 -1 mod 16 = 15
*/
public static int modByPowerOfTwo(final int value, final int mod) {
return value & mod - 1;
}
////////////// 其他函数//////////
/**
* 两个数的最大公约数,必须均为非负数.
* <p>
* 是公约数,别想太多
*/
public static int gcd(final int a, final int b) {
return IntMath.gcd(a, b);
}
/**
* 两个数的最大公约数,必须均为非负数
*/
public static long gcd(final long a, final long b) {
return LongMath.gcd(a, b);
}
/**
* 保证结果为正数的取模.
* <p>
* 如果(v = x/m) <0,v+=m.
*/
public static int mod(final int x, final int m) {
return IntMath.mod(x, m);
}
/**
* 保证结果为正数的取模.
* <p>
* 如果(v = x/m) <0,v+=m.
*/
public static long mod(final long x, final long m) {
return LongMath.mod(x, m);
}
/**
* 保证结果为正数的取模
*/
public static long mod(final long x, final int m) {
return LongMath.mod(x, m);
}
/**
* 能控制rounding方向的相除.
* <p>
* jdk的'/'运算符,直接向下取整
*/
public static int divide(final int p, final int q, RoundingMode mode) {
return IntMath.divide(p, q, mode);
}
/**
* 能控制rounding方向的相除
* <p>
* jdk的'/'运算符,直接向下取整
*/
public static long divide(final long p, final long q, RoundingMode mode) {
return LongMath.divide(p, q, mode);
}
/**
* 平方
*
* @param k 平方次数,不能为负数, k=0时返回1.
*/
public static int pow(final int b, final int k) {
return IntMath.pow(b, k);
}
/**
* 平方
*
* @param k 平方次数,不能为负数, k=0时返回1.
*/
public static long pow(final long b, final int k) {
return LongMath.pow(b, k);
}
/**
* 开方
*/
public static int sqrt(final int x, RoundingMode mode) {
return IntMath.sqrt(x, mode);
}
/**
* 开方
*/
public static long sqrt(final long x, RoundingMode mode) {
return LongMath.sqrt(x, mode);
}
}
| mit |
listenzz/RxCommand | sample/src/androidTest/java/com/shundaojia/rxcommand/ExampleInstrumentedTest.java | 749 | package com.shundaojia.rxcommand;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("me.listenzz.rxcommand", appContext.getPackageName());
}
}
| mit |
zongsizhang/GeoSpark | core/src/main/java/org/datasyslab/geospark/geometryObjects/SpatialIndexSerde.java | 11497 | /*
* FILE: SpatialIndexSerde
* Copyright (c) 2015 - 2018 GeoSpark Development Team
*
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package org.datasyslab.geospark.geometryObjects;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.index.quadtree.Node;
import com.vividsolutions.jts.index.quadtree.Quadtree;
import com.vividsolutions.jts.index.strtree.AbstractNode;
import com.vividsolutions.jts.index.strtree.ItemBoundable;
import com.vividsolutions.jts.index.strtree.STRtree;
import org.apache.log4j.Logger;
import java.util.ArrayList;
import java.util.List;
/**
* Provides methods to efficiently serialize and deserialize spatialIndex types.
* <p>
* Support Quadtree, STRtree types
* <p>
* trees are serialized recursively.
*/
public class SpatialIndexSerde
extends Serializer
{
private static final Logger log = Logger.getLogger(SpatialIndexSerde.class);
private GeometrySerde geometrySerde;
public SpatialIndexSerde()
{
super();
geometrySerde = new GeometrySerde();
}
public SpatialIndexSerde(GeometrySerde geometrySerde)
{
super();
this.geometrySerde = geometrySerde;
}
private enum Type
{
QUADTREE(0),
RTREE(1);
private final int id;
Type(int id)
{
this.id = id;
}
public static Type fromId(int id)
{
for (Type type : values()) {
if (type.id == id) {
return type;
}
}
return null;
}
}
@Override
public void write(Kryo kryo, Output output, Object o)
{
if (o instanceof Quadtree) {
// serialize quadtree index
writeType(output, Type.QUADTREE);
Quadtree tree = (Quadtree) o;
if (tree.isEmpty()) {
output.writeByte(0);
}
else {
output.writeByte(1);
// write root
List items = tree.getRoot().getItems();
output.writeInt(items.size());
for (Object item : items) {
geometrySerde.write(kryo, output, item);
}
Node[] subNodes = tree.getRoot().getSubnode();
for (int i = 0; i < 4; ++i) {
writeQuadTreeNode(kryo, output, subNodes[i]);
}
}
}
else if (o instanceof STRtree) {
//serialize rtree index
writeType(output, Type.RTREE);
STRtree tree = (STRtree) o;
output.writeInt(tree.getNodeCapacity());
if (tree.isEmpty()) {
output.writeByte(0);
}
else {
output.writeByte(1);
// write head
output.writeByte(tree.isBuilt() ? 1 : 0);
if (!tree.isBuilt()) {
// if not built, itemBoundables will not be null, record it
ArrayList itemBoundables = tree.getItemBoundables();
output.writeInt(itemBoundables.size());
for (Object obj : itemBoundables) {
if (!(obj instanceof ItemBoundable)) { throw new UnsupportedOperationException(" itemBoundables should only contain ItemBoundable objects "); }
ItemBoundable itemBoundable = (ItemBoundable) obj;
// write envelope
writeItemBoundable(kryo, output, itemBoundable);
}
}
else {
// if built, write from root
writeSTRTreeNode(kryo, output, tree.getRoot());
}
}
}
else {
throw new UnsupportedOperationException(" index type not supported ");
}
}
@Override
public Object read(Kryo kryo, Input input, Class aClass)
{
byte typeID = input.readByte();
Type indexType = Type.fromId(typeID);
switch (indexType) {
case QUADTREE: {
Quadtree index = new Quadtree();
boolean notEmpty = (input.readByte() & 0x01) == 1;
if (!notEmpty) { return index; }
int itemSize = input.readInt();
List items = new ArrayList();
for (int i = 0; i < itemSize; ++i) {
items.add(geometrySerde.read(kryo, input, Geometry.class));
}
index.getRoot().setItems(items);
for (int i = 0; i < 4; ++i) {
index.getRoot().getSubnode()[i] = readQuadTreeNode(kryo, input);
}
return index;
}
case RTREE: {
int nodeCapacity = input.readInt();
boolean notEmpty = (input.readByte() & 0x01) == 1;
if (notEmpty) {
STRtree index = new STRtree(nodeCapacity);
boolean built = (input.readByte() & 0x01) == 1;
if (built) {
// if built, root is not null, set itemBoundables to null
index.setBuilt(true);
index.setItemBoundables(null);
index.setRoot(readSTRtreeNode(kryo, input));
}
else {
// if not built, just read itemBoundables
ArrayList itemBoundables = new ArrayList();
int itemSize = input.readInt();
for (int i = 0; i < itemSize; ++i) {
itemBoundables.add(readItemBoundable(kryo, input));
}
index.setItemBoundables(itemBoundables);
}
return index;
}
else { return new STRtree(nodeCapacity); }
}
default: {
throw new UnsupportedOperationException("can't deserialize spatial index of type" + indexType);
}
}
}
private void writeQuadTreeNode(Kryo kryo, Output output, Node node)
{
// write head first
if (node == null || node.isEmpty()) {
output.writeByte(0);
}
else { // not empty
output.writeByte(1);
// write node information, envelope and level
geometrySerde.write(kryo, output, node.getEnvelope());
output.writeInt(node.getLevel());
List items = node.getItems();
output.writeInt(items.size());
for (Object obj : items) {
geometrySerde.write(kryo, output, obj);
}
Node[] subNodes = node.getSubnode();
for (int i = 0; i < 4; ++i) {
writeQuadTreeNode(kryo, output, subNodes[i]);
}
}
}
private Node readQuadTreeNode(Kryo kryo, Input input)
{
boolean notEmpty = (input.readByte() & 0x01) == 1;
if (!notEmpty) { return null; }
Envelope envelope = (Envelope) geometrySerde.read(kryo, input, Envelope.class);
int level = input.readInt();
Node node = new Node(envelope, level);
int itemSize = input.readInt();
List items = new ArrayList();
for (int i = 0; i < itemSize; ++i) {
items.add(geometrySerde.read(kryo, input, Geometry.class));
}
node.setItems(items);
// read children
for (int i = 0; i < 4; ++i) {
node.getSubnode()[i] = readQuadTreeNode(kryo, input);
}
return node;
}
private void writeSTRTreeNode(Kryo kryo, Output output, AbstractNode node)
{
// write head
output.writeInt(node.getLevel());
// write children
List children = node.getChildBoundables();
int childrenSize = children.size();
output.writeInt(childrenSize);
// if children not empty, write children
if (childrenSize > 0) {
if (children.get(0) instanceof AbstractNode) {
// write type as 0, non-leaf node
output.writeByte(0);
for (Object obj : children) {
AbstractNode child = (AbstractNode) obj;
writeSTRTreeNode(kryo, output, child);
}
}
else if (children.get(0) instanceof ItemBoundable) {
// write type as 1, leaf node
output.writeByte(1);
// for leaf node, write items
for (Object obj : children) {
writeItemBoundable(kryo, output, (ItemBoundable) obj);
}
}
else {
throw new UnsupportedOperationException("wrong node type of STRtree");
}
}
}
private STRtree.STRtreeNode readSTRtreeNode(Kryo kryo, Input input)
{
int level = input.readInt();
STRtree.STRtreeNode node = new STRtree.STRtreeNode(level);
int childrenSize = input.readInt();
boolean isLeaf = (input.readByte() & 0x01) == 1;
ArrayList children = new ArrayList();
if (isLeaf) {
for (int i = 0; i < childrenSize; ++i) {
children.add(readItemBoundable(kryo, input));
}
}
else {
for (int i = 0; i < childrenSize; ++i) {
children.add(readSTRtreeNode(kryo, input));
}
}
node.setChildBoundables(children);
return node;
}
private void writeItemBoundable(Kryo kryo, Output output, ItemBoundable itemBoundable)
{
geometrySerde.write(kryo, output, itemBoundable.getBounds());
geometrySerde.write(kryo, output, itemBoundable.getItem());
}
private ItemBoundable readItemBoundable(Kryo kryo, Input input)
{
return new ItemBoundable(
geometrySerde.read(kryo, input, Envelope.class),
geometrySerde.read(kryo, input, Geometry.class)
);
}
private void writeType(Output output, Type type)
{
output.writeByte((byte) type.id);
}
}
| mit |
sel-project/sel-utils | public/java/util/src/main/java/soupply/util/DecodeException.java | 1294 | /*
* Copyright (c) 2016-2018 sel-project
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
package soupply.util;
import java.io.IOException;
public class DecodeException extends IOException {
public DecodeException(String reason) {
super(reason);
}
}
| mit |
1684Chimeras/2014Robot | 2014CompetitionRobot/src/org/chimeras1684/year2014/iterative/aaroot/Compressor.java | 1148 | /*
* API for the $clazz$ class
*
* Usage :
* Toggling the compressor:
* 1) call compressor.compress()
*
* TODO :
* Delete this class and use the "Compressor" object
*/
package org.chimeras1684.year2014.iterative.aaroot;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.Relay;
/**
* Custom interface for compressors
* because we're too cool to use WPI classes
*
* @author Arhowk
*/
public class Compressor
{
Relay compressor;
DigitalInput pressureSwitch;
/**
* Constructs a new singleton compressor because we can.
*/
public Compressor()
{
compressor = new Relay(RobotMap.compressor);
pressureSwitch = new DigitalInput(RobotMap.pressureSwitch);
}
/**
* Compresses the compressor if the relay is relaying
*/
public void compress()
{
if(pressureSwitch.get())
{
compressor.set(Relay.Value.kOff);
}else{
compressor.set(Relay.Value.kForward);
}
}
public void disable(){
compressor.set(Relay.Value.kOff);
}
}
| mit |
Hu3bl/statsbot | statsbot-parent/statsbot-module.messages.model/src/main/java/MessagesModel/impl/ConnectedMessageImpl.java | 8260 | /**
*/
package MessagesModel.impl;
import MessagesModel.ConnectedMessage;
import MessagesModel.ModelPackage;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Connected Message</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link MessagesModel.impl.ConnectedMessageImpl#getUserID <em>User ID</em>}</li>
* <li>{@link MessagesModel.impl.ConnectedMessageImpl#getUserName <em>User Name</em>}</li>
* <li>{@link MessagesModel.impl.ConnectedMessageImpl#getUserSteamID <em>User Steam ID</em>}</li>
* <li>{@link MessagesModel.impl.ConnectedMessageImpl#getAddress <em>Address</em>}</li>
* </ul>
*
* @generated
*/
public class ConnectedMessageImpl extends MessageImpl implements ConnectedMessage {
/**
* The default value of the '{@link #getUserID() <em>User ID</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getUserID()
* @generated
* @ordered
*/
protected static final String USER_ID_EDEFAULT = null;
/**
* The cached value of the '{@link #getUserID() <em>User ID</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getUserID()
* @generated
* @ordered
*/
protected String userID = USER_ID_EDEFAULT;
/**
* The default value of the '{@link #getUserName() <em>User Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getUserName()
* @generated
* @ordered
*/
protected static final String USER_NAME_EDEFAULT = null;
/**
* The cached value of the '{@link #getUserName() <em>User Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getUserName()
* @generated
* @ordered
*/
protected String userName = USER_NAME_EDEFAULT;
/**
* The default value of the '{@link #getUserSteamID() <em>User Steam ID</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getUserSteamID()
* @generated
* @ordered
*/
protected static final String USER_STEAM_ID_EDEFAULT = null;
/**
* The cached value of the '{@link #getUserSteamID() <em>User Steam ID</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getUserSteamID()
* @generated
* @ordered
*/
protected String userSteamID = USER_STEAM_ID_EDEFAULT;
/**
* The default value of the '{@link #getAddress() <em>Address</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getAddress()
* @generated
* @ordered
*/
protected static final String ADDRESS_EDEFAULT = null;
/**
* The cached value of the '{@link #getAddress() <em>Address</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getAddress()
* @generated
* @ordered
*/
protected String address = ADDRESS_EDEFAULT;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ConnectedMessageImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return ModelPackage.Literals.CONNECTED_MESSAGE;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getUserID() {
return userID;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setUserID(String newUserID) {
String oldUserID = userID;
userID = newUserID;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.CONNECTED_MESSAGE__USER_ID, oldUserID, userID));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getUserName() {
return userName;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setUserName(String newUserName) {
String oldUserName = userName;
userName = newUserName;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.CONNECTED_MESSAGE__USER_NAME, oldUserName, userName));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getUserSteamID() {
return userSteamID;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setUserSteamID(String newUserSteamID) {
String oldUserSteamID = userSteamID;
userSteamID = newUserSteamID;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.CONNECTED_MESSAGE__USER_STEAM_ID, oldUserSteamID, userSteamID));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getAddress() {
return address;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setAddress(String newAddress) {
String oldAddress = address;
address = newAddress;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, ModelPackage.CONNECTED_MESSAGE__ADDRESS, oldAddress, address));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case ModelPackage.CONNECTED_MESSAGE__USER_ID:
return getUserID();
case ModelPackage.CONNECTED_MESSAGE__USER_NAME:
return getUserName();
case ModelPackage.CONNECTED_MESSAGE__USER_STEAM_ID:
return getUserSteamID();
case ModelPackage.CONNECTED_MESSAGE__ADDRESS:
return getAddress();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case ModelPackage.CONNECTED_MESSAGE__USER_ID:
setUserID((String)newValue);
return;
case ModelPackage.CONNECTED_MESSAGE__USER_NAME:
setUserName((String)newValue);
return;
case ModelPackage.CONNECTED_MESSAGE__USER_STEAM_ID:
setUserSteamID((String)newValue);
return;
case ModelPackage.CONNECTED_MESSAGE__ADDRESS:
setAddress((String)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case ModelPackage.CONNECTED_MESSAGE__USER_ID:
setUserID(USER_ID_EDEFAULT);
return;
case ModelPackage.CONNECTED_MESSAGE__USER_NAME:
setUserName(USER_NAME_EDEFAULT);
return;
case ModelPackage.CONNECTED_MESSAGE__USER_STEAM_ID:
setUserSteamID(USER_STEAM_ID_EDEFAULT);
return;
case ModelPackage.CONNECTED_MESSAGE__ADDRESS:
setAddress(ADDRESS_EDEFAULT);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case ModelPackage.CONNECTED_MESSAGE__USER_ID:
return USER_ID_EDEFAULT == null ? userID != null : !USER_ID_EDEFAULT.equals(userID);
case ModelPackage.CONNECTED_MESSAGE__USER_NAME:
return USER_NAME_EDEFAULT == null ? userName != null : !USER_NAME_EDEFAULT.equals(userName);
case ModelPackage.CONNECTED_MESSAGE__USER_STEAM_ID:
return USER_STEAM_ID_EDEFAULT == null ? userSteamID != null : !USER_STEAM_ID_EDEFAULT.equals(userSteamID);
case ModelPackage.CONNECTED_MESSAGE__ADDRESS:
return ADDRESS_EDEFAULT == null ? address != null : !ADDRESS_EDEFAULT.equals(address);
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (userID: ");
result.append(userID);
result.append(", userName: ");
result.append(userName);
result.append(", userSteamID: ");
result.append(userSteamID);
result.append(", address: ");
result.append(address);
result.append(')');
return result.toString();
}
} //ConnectedMessageImpl
| mit |
quanhua92/AudioVideoRecorder | recorduvccamera/src/androidTest/java/com/quan404/recorduvccamera/ApplicationTest.java | 358 | package com.quan404.recorduvccamera;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | mit |
TSavo/XChange | xchange-core/src/main/java/org/knowm/xchange/dto/trade/UserTrade.java | 6036 | package org.knowm.xchange.dto.trade;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Objects;
import org.knowm.xchange.currency.Currency;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dto.Order.OrderType;
import org.knowm.xchange.dto.marketdata.Trade;
import org.knowm.xchange.service.trade.TradeService;
import org.knowm.xchange.service.trade.params.TradeHistoryParams;
/** Data object representing a user trade */
@JsonDeserialize(builder = UserTrade.Builder.class)
public class UserTrade extends Trade {
private static final long serialVersionUID = -3021617981214969292L;
/** The id of the order responsible for execution of this trade */
private final String orderId;
/** The fee that was charged by the exchange for this trade. */
private final BigDecimal feeAmount;
/** The currency in which the fee was charged. */
private final Currency feeCurrency;
/** The order reference id which has been added by the user on the order creation */
private final String orderUserReference;
/**
* This constructor is called to construct user's trade objects (in {@link
* TradeService#getTradeHistory(TradeHistoryParams)} implementations).
*
* @param type The trade type (BID side or ASK side)
* @param originalAmount The depth of this trade
* @param currencyPair The exchange identifier (e.g. "BTC/USD")
* @param price The price (either the bid or the ask)
* @param timestamp The timestamp of the trade
* @param id The id of the trade
* @param orderId The id of the order responsible for execution of this trade
* @param feeAmount The fee that was charged by the exchange for this trade
* @param feeCurrency The symbol of the currency in which the fee was charged
* @param orderUserReference The id that the user has insert to the trade
*/
public UserTrade(
OrderType type,
BigDecimal originalAmount,
CurrencyPair currencyPair,
BigDecimal price,
Date timestamp,
String id,
String orderId,
BigDecimal feeAmount,
Currency feeCurrency,
String orderUserReference) {
super(type, originalAmount, currencyPair, price, timestamp, id, null, null);
this.orderId = orderId;
this.feeAmount = feeAmount;
this.feeCurrency = feeCurrency;
this.orderUserReference = orderUserReference;
}
public String getOrderId() {
return orderId;
}
public BigDecimal getFeeAmount() {
return feeAmount;
}
public Currency getFeeCurrency() {
return feeCurrency;
}
public String getOrderUserReference() {
return orderUserReference;
}
@Override
public String toString() {
return "UserTrade[type="
+ type
+ ", originalAmount="
+ originalAmount
+ ", currencyPair="
+ currencyPair
+ ", price="
+ price
+ ", timestamp="
+ timestamp
+ ", id="
+ id
+ ", orderId='"
+ orderId
+ '\''
+ ", feeAmount="
+ feeAmount
+ ", feeCurrency='"
+ feeCurrency
+ '\''
+ ", orderUserReference='"
+ orderUserReference
+ '\''
+ "]";
}
@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;
UserTrade userTrade = (UserTrade) o;
return Objects.equals(orderId, userTrade.orderId)
&& Objects.equals(feeAmount, userTrade.feeAmount)
&& Objects.equals(feeCurrency, userTrade.feeCurrency);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), orderId, feeAmount, feeCurrency);
}
@JsonPOJOBuilder(withPrefix = "")
public static class Builder extends Trade.Builder {
protected String orderId;
protected BigDecimal feeAmount;
protected Currency feeCurrency;
protected String orderUserReference;
public static Builder from(UserTrade trade) {
return new Builder()
.type(trade.getType())
.originalAmount(trade.getOriginalAmount())
.currencyPair(trade.getCurrencyPair())
.price(trade.getPrice())
.timestamp(trade.getTimestamp())
.id(trade.getId())
.orderId(trade.getOrderId())
.feeAmount(trade.getFeeAmount())
.feeCurrency(trade.getFeeCurrency());
}
@Override
public Builder type(OrderType type) {
return (Builder) super.type(type);
}
@Override
public Builder originalAmount(BigDecimal originalAmount) {
return (Builder) super.originalAmount(originalAmount);
}
@Override
public Builder currencyPair(CurrencyPair currencyPair) {
return (Builder) super.currencyPair(currencyPair);
}
@Override
public Builder price(BigDecimal price) {
return (Builder) super.price(price);
}
@Override
public Builder timestamp(Date timestamp) {
return (Builder) super.timestamp(timestamp);
}
@Override
public Builder id(String id) {
return (Builder) super.id(id);
}
public Builder orderId(String orderId) {
this.orderId = orderId;
return this;
}
public Builder feeAmount(BigDecimal feeAmount) {
this.feeAmount = feeAmount;
return this;
}
public Builder feeCurrency(Currency feeCurrency) {
this.feeCurrency = feeCurrency;
return this;
}
public Builder orderUserReference(String orderUserReference) {
this.orderUserReference = orderUserReference;
return this;
}
@Override
public UserTrade build() {
return new UserTrade(
type,
originalAmount,
currencyPair,
price,
timestamp,
id,
orderId,
feeAmount,
feeCurrency,
orderUserReference);
}
}
}
| mit |
Iurii-Dziuban/algorithms | src/main/java/iurii/job/interview/yandex/bencode/Bencode.java | 2442 | package iurii.job.interview.yandex.bencode;
import iurii.job.interview.yandex.bencode.decoders.CompositeDecoder;
import iurii.job.interview.yandex.bencode.encoders.CompositeEncoder;
import iurii.job.interview.yandex.bencode.utils.ByteString;
import iurii.job.interview.yandex.bencode.utils.CharacterInputStreamIterator;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/**
*
* Implement encode, decode methods for basic data structures:
*
* byte strings,
* integers,
* lists, and
* dictionaries (associative arrays).
*
* More details at: https://en.wikipedia.org/wiki/Bencode
*/
public class Bencode {
/**
* Only for testing
*/
public static void main(String[] args) throws IOException {
FileOutputStream fileOutputStream = new FileOutputStream("src/main/resources/decodeBencode.txt");
Writer writer = new OutputStreamWriter(fileOutputStream, Charset.forName("US-ASCII"));
writer.append("d4:name11:Arthur Dent6:numberi42e7:picture0:7:planetsl5:Earth14:Somewhere else9:Old Earthee");
writer.close();
File decodedFile = new File("src/main/resources/decodeBencode.txt");
File encodedFile = new File("src/main/resources/encodeBencode.txt");
InputStream is = new FileInputStream(decodedFile);
OutputStream os = new FileOutputStream(encodedFile);
System.out.println(new CompositeDecoder().decode(new CharacterInputStreamIterator(is), ""));
Map<ByteString, Object> dictionary = new TreeMap<ByteString, Object>();
List<Object> list = new ArrayList<Object>();
list.add(ByteString.valueOf("Earth"));
list.add(ByteString.valueOf("Somewhere else"));
list.add(ByteString.valueOf("Old Earth"));
dictionary.put(ByteString.valueOf("name"), ByteString.valueOf("Arthur Dent"));
dictionary.put(ByteString.valueOf("number"), 42);
dictionary.put(ByteString.valueOf("picture"), ByteString.valueOf(""));
dictionary.put(ByteString.valueOf("planets"), list);
System.out.println(new CompositeEncoder().encode(dictionary));
is.close();
os.close();
}
}
| mit |
abhn/marvel | openCVLibrary2410/src/main/java/org/opencv/android/FpsMeter.java | 2044 | package org.opencv.android;
import java.text.DecimalFormat;
import org.opencv.core.Core;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.Log;
public class FpsMeter {
private static final String TAG = "FpsMeter";
private static final int STEP = 20;
private static final DecimalFormat FPS_FORMAT = new DecimalFormat("0.00");
private int mFramesCouner;
private double mFrequency;
private long mprevFrameTime;
private String mStrfps;
Paint mPaint;
boolean mIsInitialized = false;
int mWidth = 0;
int mHeight = 0;
public void init() {
mFramesCouner = 0;
mFrequency = Core.getTickFrequency();
mprevFrameTime = Core.getTickCount();
mStrfps = "";
mPaint = new Paint();
mPaint.setColor(Color.BLUE);
mPaint.setTextSize(40);
}
public void measure() {
if (!mIsInitialized) {
init();
mIsInitialized = true;
} else {
mFramesCouner++;
if (mFramesCouner % STEP == 0) {
long time = Core.getTickCount();
double fps = STEP * mFrequency / (time - mprevFrameTime);
mprevFrameTime = time;
if (mWidth != 0 && mHeight != 0)
mStrfps = FPS_FORMAT.format(fps) + " FPS@" + Integer.valueOf(mWidth) + "x" + Integer.valueOf(mHeight);
else
mStrfps = FPS_FORMAT.format(fps) + " FPS";
Log.i(TAG, mStrfps);
}
}
}
public void setResolution(int width, int height) {
mWidth = width;
mHeight = height;
}
public void draw(Canvas canvas, float offsetx, float offsety) {
Log.d(TAG, mStrfps);
canvas.drawText(mStrfps, offsetx, offsety, mPaint);
}
}
| mit |
mxmo0rhuhn/map-reduce | mapreduce-master/src/test/java/ch/zhaw/mapreduce/TestUtil.java | 257 | package ch.zhaw.mapreduce;
import com.google.inject.Provider;
public final class TestUtil {
public static <T> Provider<T> toProvider(final T instance) {
return new Provider<T>() {
@Override
public T get() {
return instance;
}
};
}
}
| mit |
blnz/palomar | src/main/java/com/blnz/xml/xml/parse/ParserBase.java | 606 | package com.blnz.xml.parse;
import java.util.Locale;
/**
*
* @version $Revision: 1.1 $ $Date: 1998/06/25 10:52:26 $
*/
public class ParserBase {
protected EntityManager entityManager = new EntityManagerImpl();
protected Locale locale = Locale.getDefault();
public void setEntityManager(EntityManager entityManager) {
if (entityManager == null)
throw new NullPointerException();
this.entityManager = entityManager;
}
public void setLocale(Locale locale) {
if (locale == null)
throw new NullPointerException();
this.locale = locale;
}
}
| mit |
cabralRodrigo/jarm | src/main/java/br/com/cabralrodrigo/minecraft/jarm/client/gui/GuiAmuletStamper.java | 2230 | package br.com.cabralrodrigo.minecraft.jarm.client.gui;
import br.com.cabralrodrigo.minecraft.jarm.client.lib.LibGuiTextures;
import br.com.cabralrodrigo.minecraft.jarm.common.inventory.container.misc.ContainerAmuletStamper;
import br.com.cabralrodrigo.minecraft.jarm.common.tileentity.TileEntityAmuletStamper;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.entity.player.EntityPlayer;
import org.lwjgl.opengl.GL11;
public class GuiAmuletStamper extends GuiContainer {
private TileEntityAmuletStamper stamper;
public GuiAmuletStamper(EntityPlayer player, TileEntityAmuletStamper stamper) {
super(new ContainerAmuletStamper(player, stamper));
this.stamper = stamper;
this.xSize = 176;
this.ySize = 213;
}
@Override
public void initGui() {
super.initGui();
this.buttonList.add(new GuiButton(0, ((this.width - this.xSize) / 2) + 106, ((this.height - this.ySize) / 2) + 99, 64, 20, "Craft"));
this.buttonList.get(0).enabled = true;
}
@Override
protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY) {
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
this.mc.getTextureManager().bindTexture(LibGuiTextures.GUI_AMULET_STAMPER);
int guiX = (this.width - this.xSize) / 2;
int guiY = (this.height - this.ySize) / 2;
drawTexturedModalRect(guiX, guiY, 0, 0, this.xSize, this.ySize);
}
@Override
protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) {
/*
*/
ContainerAmuletStamper container = (ContainerAmuletStamper) this.inventorySlots;
this.fontRendererObj.drawString(container.getPlayer().inventory.getDisplayName().getUnformattedText(), 8, this.ySize - 96 + 2, 4210752);
this.fontRendererObj.drawString(this.stamper.getDisplayName().getUnformattedText(), 8, 6, 4210752);
this.fontRendererObj.drawString("12 Levels", 30, this.ySize - 105, 4210752);
//this.fontRendererObj.drawString("Amulet Stamper", 8, 6, 4210752);
//this.fontRendererObj.drawString("Inventory", 8, this.ySize - 96 + 2, 4210752);
}
}
| mit |
momo3210/gold | momo-run/src/main/java/com/momohelp/model/Buy.java | 2748 | package com.momohelp.model;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
/**
*
* @author Administrator
*
*/
@Table(name = "p_buy")
public class Buy implements Serializable {
private static final long serialVersionUID = -8880872222905009779L;
@Id
@Column(name = "id")
private String id;
/**
* 关联批次
*/
private String w_farm_chick_id;
/**
* 购买数量
*/
private Integer num_buy;
/**
* 购买时间
*/
private Date create_time;
/**
* 计算时间
*/
private Date calc_time;
private String user_id;
/**
* 真实的成交时间(后台计算后,更新此字段)
*/
private Date time_deal;
/**
* 是否是订金(预付款)
*
* 1是
*
* 0不是
*/
private Integer is_deposit;
private Integer num_deal;
/**
* 计算标志
*
* 0未计算
*
* 1已计算
*/
private Integer flag_calc_bonus=0;
@Transient
private List<BuySell> buySells;
@Transient
private Farm farm;
public Integer getFlag_calc_bonus() {
return flag_calc_bonus;
}
public void setFlag_calc_bonus(Integer flag_calc_bonus) {
this.flag_calc_bonus = flag_calc_bonus;
}
public Integer getNum_deal() {
return num_deal;
}
public void setNum_deal(Integer num_deal) {
this.num_deal = num_deal;
}
public Farm getFarm() {
return farm;
}
public void setFarm(Farm farm) {
this.farm = farm;
}
public Integer getIs_deposit() {
return is_deposit;
}
public void setIs_deposit(Integer is_deposit) {
this.is_deposit = is_deposit;
}
public List<BuySell> getBuySells() {
return buySells;
}
public void setBuySells(List<BuySell> buySells) {
this.buySells = buySells;
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public Date getTime_deal() {
return time_deal;
}
public void setTime_deal(Date time_deal) {
this.time_deal = time_deal;
}
public Date getCalc_time() {
return calc_time;
}
public void setCalc_time(Date calc_time) {
this.calc_time = calc_time;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getW_farm_chick_id() {
return w_farm_chick_id;
}
public void setW_farm_chick_id(String w_farm_chick_id) {
this.w_farm_chick_id = w_farm_chick_id;
}
public Integer getNum_buy() {
return num_buy;
}
public void setNum_buy(Integer num_buy) {
this.num_buy = num_buy;
}
public Date getCreate_time() {
return create_time;
}
public void setCreate_time(Date create_time) {
this.create_time = create_time;
}
}
| mit |
Noneatme/mta-metaxmlgenerator | com/beust/jcommander/internal/Lists.java | 1563 | /**
* Copyright (C) 2010 the original author or authors.
* See the notice.md file distributed with this work for additional
* information regarding copyright ownership.
*
* 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.beust.jcommander.internal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
public class Lists {
public static <K> List<K> newArrayList() {
return new ArrayList<K>();
}
public static <K> List<K> newArrayList(Collection<K> c) {
return new ArrayList<K>(c);
}
@SafeVarargs
public static <K> List<K> newArrayList(K... c) {
return new ArrayList<K>(Arrays.asList(c));
}
public static <K> List<K> newArrayList(int size) {
return new ArrayList<K>(size);
}
public static <K> LinkedList<K> newLinkedList() {
return new LinkedList<K>();
}
public static <K> LinkedList<K> newLinkedList(Collection<K> c) {
return new LinkedList<K>(c);
}
}
| mit |
CodesCubesAndCrashes/AgriCraft | src/main/java/com/infinityraider/agricraft/api/v1/adapter/IAgriAdapterizer.java | 3157 | /*
*/
package com.infinityraider.agricraft.api.v1.adapter;
import java.util.Optional;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* Interface representing a registry that contains adapters for determining the
* true value of arbitrary objects.
*
* @param <T> The type that this registry adapts to.
*/
public interface IAgriAdapterizer<T> {
/**
* Determines if the registry has the given adapter instance.
*
* @param adapter The adapter instance to check if present.
* @return If the registry contains the adapter instance.
*/
boolean hasAdapter(@Nullable IAgriAdapter<T> adapter);
/**
* Determines if the registry has an adapter capable of converting the given
* object to the target type.
*
* @param object The object to find a converter for.
* @return {@literal true} if the registry has an adapter capable of
* converting the given object, {@literal false} otherwise.
*/
boolean hasAdapter(@Nullable Object object);
/**
* Fetches the highest priority converter capable of converting the given
* object, or else the empty optional.
*
* @param obj The object to find a converter for.
* @return The highest priority converter capable of converting the given
* object, or else the empty optional.
*/
@Nonnull
Optional<IAgriAdapter<T>> getAdapter(@Nullable Object obj);
/**
* Registers the given adapter instance to the registry.
* <p>
* Notice, that per the current implementation, the adapters are assigned
* priority according to their registration order, whereas the first adapter
* registered gets assigned the lowest priority, and the last adapter
* registered will be assigned the highest priority.
*
* @param adapter The adapter instance to be registered.
* @return {@literal true} if the adapter was not already registered and its
* registration was a success. Otherwise returns {@literal false}.
*/
boolean registerAdapter(@Nonnull IAgriAdapter<T> adapter);
/**
* Removes the given adapter instance from the registry.
* <p>
* Notice, that if the registry does not already contain the given adapter
* instance, the registry will remain unchanged and the method will return
* false.
*
* @param adapter The adapter instance to be unregistered.
* @return {@literal true} if the adapter was already registered and its
* removal was a success. Otherwise returns {@literal false}.
*/
boolean unregisterAdapter(@Nonnull IAgriAdapter<T> adapter);
/**
* Determines the value of the given object, using the highest priority
* adapter that accepts the given object, or else returns the empty
* optional.
*
* @param obj The object to be converted to the target type.
* @return The value of the converted object, or the empty optional in the
* case that the conversion failed in some manner.
*/
@Nonnull
default Optional<T> valueOf(@Nullable Object obj) {
return getAdapter(obj).flatMap(a -> a.valueOf(obj));
}
}
| mit |
wStockhausen/DisMELS | DisMELS_Framework/src/wts/models/DisMELS/framework/LHS_Classes.java | 5203 | /*
* LHS_Classes.java
*
* Created on March 20, 2012.
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package wts.models.DisMELS.framework;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Instances of this class provide information for the various classes (e.g.,
* parameters, attributes) associated with each LHS class found in the Lookup.
*
* @author William Stockhausen
*/
public class LHS_Classes {
/** HashMap linking LHS types (the keys) to associated classes as LHS_ClassInfo objects (the values) */
private final HashMap<String,LHS_ClassInfo> map = new HashMap<>();
/** Creates a new instance of LHS_Classes */
public LHS_Classes(Set<Class<? extends LifeStageInterface>> clazzes) {
updateInfo(clazzes);
}
public final void updateInfo(Set<Class<? extends LifeStageInterface>> clazzes){
LHS_ClassInfo lhs;
try {
for (Iterator<Class<? extends LifeStageInterface>> it = clazzes.iterator(); it.hasNext();) {
Class<? extends LifeStageInterface> clazz = it.next();
lhs = new LHS_ClassInfo(clazz);
map.put(lhs.lhsClass, lhs);
}
} catch (Exception ex) {
Logger.getLogger(LHS_Classes.class.getName()).log(Level.WARNING, null, ex);
}
}
public HashMap<String,LHS_ClassInfo> getMap() {
return map;
}
public Set<String> getKeys() {
return map.keySet();
}
public LHS_ClassInfo getClassInfo(String className) {
return map.get(className);
}
protected class LHS_ClassInfo {
/** name of LHS class */
public String lhsClass;
/** name of associated LHS attributes class */
public String attributesClass;
/** name of associated LHS parameters class */
public String parametersClass;
/** name of associated LHS point feature type class */
public String pointFTClass;
/** name of associated LHS classes that can represent 'next' stages */
public String[] nextLHSClasses;
/** name of associated LHS classes that can be 'spawned' */
public String[] spawnedLHSClasses;
protected LHS_ClassInfo() {
}
protected LHS_ClassInfo(Class<? extends LifeStageInterface> lhsClass) {
try {
Field f;
this.lhsClass = lhsClass.getName();
/* get the attributes class name */
f = lhsClass.getField("attributesClass");
this.attributesClass = (String) f.get(null);
/* get the parameters class name */
f = lhsClass.getField("parametersClass");
this.parametersClass = (String) f.get(null);
/* get the point feature type class name and the associated class */
f = lhsClass.getField("pointFTClass");
this.pointFTClass = (String) f.get(null);
/* get the potential 'next' LHS classes names and associated classes */
f = lhsClass.getField("nextLHSClasses");
this.nextLHSClasses = (String[]) f.get(null);
/* get the spawned LHS class names and associated classes */
f = lhsClass.getField("spawnedLHSClasses");
this.spawnedLHSClasses = (String[]) f.get(null);
} catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException ex) {
Logger.getLogger(LHS_Classes.class.getName()).log(Level.SEVERE, null, ex);
}
}
protected LHS_ClassInfo(String lhsClass,
String attributesClass,
String parametersClass,
String pointFTClass,
String nextLHSClass,
String spawnedLHSClass) {
this.lhsClass = lhsClass;
this.attributesClass = attributesClass;
this.parametersClass = parametersClass;
this.pointFTClass = pointFTClass;
this.nextLHSClasses = new String[]{nextLHSClass};
this.spawnedLHSClasses = new String[]{spawnedLHSClass};
}
protected LHS_ClassInfo(String lhsClass,
String attributesClass,
String parametersClass,
String pointFTClass,
String[] nextLHSClasses,
String[] spawnedLHSClasses) {
this.lhsClass = lhsClass;
this.attributesClass = attributesClass;
this.parametersClass = parametersClass;
this.pointFTClass = pointFTClass;
this.nextLHSClasses = nextLHSClasses;
this.spawnedLHSClasses = spawnedLHSClasses;
}
}
}
| mit |
BrassGoggledCoders/SteamAgeRevolution | src/main/java/xyz/brassgoggledcoders/steamagerevolution/multiblocks/tank/ControllerTank.java | 3497 | package xyz.brassgoggledcoders.steamagerevolution.multiblocks.tank;
import org.apache.commons.lang3.tuple.Pair;
import com.teamacronymcoders.base.multiblocksystem.IMultiblockPart;
import net.minecraft.client.gui.Gui;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidTank;
import xyz.brassgoggledcoders.steamagerevolution.machinesystem.MachineType;
import xyz.brassgoggledcoders.steamagerevolution.machinesystem.multiblock.MultiblockMachineType;
import xyz.brassgoggledcoders.steamagerevolution.machinesystem.multiblock.SARMultiblockBase;
import xyz.brassgoggledcoders.steamagerevolution.utils.inventory.ContainerSingleTank;
import xyz.brassgoggledcoders.steamagerevolution.utils.inventory.GuiSingleTank;
//TODO Convert to inventory system
public class ControllerTank extends SARMultiblockBase {
public static final String uid = "tank";
public BlockPos minimumInteriorPos;
public BlockPos maximumInteriorPos;
public FluidTank tank;
public ControllerTank(World world) {
super(world);
// TODO
tank = new FluidTank(0);
}
@Override
public void onAttachedPartWithMultiblockData(IMultiblockPart part, NBTTagCompound data) {
tank.readFromNBT(data);
}
// TODO Caching
@Override
protected void onMachineAssembled() {
Pair<BlockPos, BlockPos> interiorPositions = com.teamacronymcoders.base.util.PositionUtils
.shrinkPositionCubeBy(getMinimumCoord(), getMaximumCoord(), 1);
minimumInteriorPos = interiorPositions.getLeft();
maximumInteriorPos = interiorPositions.getRight();
int blocksInside = 0;
// TODO Expensive for loop just to increment an integer
for(BlockPos pos : BlockPos.getAllInBox(minimumInteriorPos, maximumInteriorPos)) {
blocksInside++;
}
// Size internal tank accordingly
tank = new FluidTank(tank.getFluid(), blocksInside * Fluid.BUCKET_VOLUME * 16);
super.onMachineAssembled();
}
@Override
protected int getMinimumNumberOfBlocksForAssembledMachine() {
return 26;
}
@Override
public int getMaximumXSize() {
// TODO Auto-generated method stub
return 10;
}
@Override
public int getMaximumZSize() {
// TODO Auto-generated method stub
return 10;
}
@Override
public int getMaximumYSize() {
// TODO Auto-generated method stub
return 10;
}
@Override
protected boolean updateServer() {
return false;
}
@Override
public void writeToDisk(NBTTagCompound data) {
tank.writeToNBT(data);
}
@Override
public MultiblockMachineType getMachineType() {
if(!MachineType.machinesList.containsKey(uid)) {
MachineType.machinesList.put(uid, new MultiblockMachineType(uid));
}
return (MultiblockMachineType) MachineType.machinesList.get(uid);
}
@Override
public Gui getGui(EntityPlayer entityPlayer, World world, BlockPos blockPos) {
return new GuiSingleTank(entityPlayer, tank);
}
@Override
public Container getContainer(EntityPlayer entityPlayer, World world, BlockPos blockPos) {
return new ContainerSingleTank(entityPlayer, null);
}
}
| mit |
facebook/redex | test/instr/InlineFinalInstanceFieldTest.java | 7634 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package redex;
import static org.fest.assertions.api.Assertions.assertThat;
import org.junit.Test;
class MixedTypeInstance {
public final int m_final_accessed;
public int m_non_final_accessed;
public final int m_final_inlineable;
public int m_non_final_inlineable;
public int m_changed_0;
public int m_changed_2;
public int m_changed_4;
public int m_changed_5;
public int m_not_deletable;
public int m_deletable;
public MixedTypeInstance() {
m_deletable = 0;
change0();
m_final_accessed = 2;
change2();
m_non_final_accessed = 4;
change4();
m_non_final_accessed = 5;
change5();
m_final_inlineable = 0;
m_non_final_inlineable = 5;
m_non_final_accessed = 6;
m_not_deletable = 2;
m_not_deletable = 0;
}
public void change0() {
m_changed_0 = m_final_accessed;
}
public void change2() {
m_changed_2 = m_final_accessed;
}
public void change4() {
m_changed_4 = m_non_final_accessed;
}
public void change5() {
m_changed_5 = m_non_final_accessed;
}
public int return_final_inlineable() {
// Should return 0
return m_final_inlineable;
}
public int return_non_final_inlineable() {
// Should return 5
return m_non_final_inlineable;
}
}
class MultipleLayerAccessed {
public final int m_final_accessed;
public int m_non_final_accessed;
public int m_a;
public int m_b;
public MultipleLayerAccessed() {
m_non_final_accessed = 3;
wrapper();
m_final_accessed = 2;
m_non_final_accessed = 4;
}
public void wrapper() { change0(); }
public void change0() {
m_a = m_final_accessed;
m_b = m_non_final_accessed;
}
}
class EncodableFinal {
public final boolean m_bool = true;
public final byte m_byte = 'b';
public final char m_char = 'c';
public final short m_short = 128;
public final int m_int = 12345;
public final String m_string = "string";
public final long m_long = 0x1000200030004000L;
public final double m_double = 1.0000000000000002;
}
class NotFinal {
public boolean m_bool = true;
public byte m_byte = 'b';
public char m_char = 'c';
public short m_short = 128;
public int m_int = 12345;
public String m_string = "string";
public long m_long = 0x1000200030004000L;
public double m_double = 1.0000000000000002;
public void changeMInt() {
m_int = 12346;
}
}
class UnEncodableFinal {
public final int m_int = Math.random() > .5 ? 1 : 0;
}
class HasCharSequenceFinal {
// CharSequence must not be processed because DalvikVM can't handle it.
public final CharSequence m_charseq = "SEQ";
}
class OneInitCanReplaceFinal {
public final int m_int;
public OneInitCanReplaceFinal() {
m_int = 1;
}
}
class OneInitCantReplaceFinal {
public final int m_int;
public OneInitCantReplaceFinal(int a) {
m_int = a;
}
}
class TwoInitCantReplaceFinal {
public final int m_int;
public TwoInitCantReplaceFinal() {
m_int = 5;
}
public TwoInitCantReplaceFinal(int a) {
m_int = 6;
}
}
class ReadInCtors1 {
public final int m_int;
public final int m_int_2;
public ReadInCtors1() {
m_int = 5;
m_int_2 = m_int;
}
}
class ReadInCtors2 {
public final int m_int_3;
public ReadInCtors2() {
ReadInCtors1 a = new ReadInCtors1();
m_int_3 = a.m_int;
}
}
class ReadEscape {
public int add_two(EscapeObject a) { return a.m_a + 2; }
}
class EscapeObject {
public int m_a;
public EscapeObject() {
ReadEscape b = new ReadEscape();
m_a = b.add_two(this);
}
}
class AccessedString {
int x;
String s;
public String toString() { return Integer.toString(x); }
public AccessedString() {
// s is "0".
s = new StringBuilder().append(this).toString();
x = 42;
}
}
class NotAccessedString {
int x;
String s;
public NotAccessedString() {
s = new StringBuilder().append("Blah").toString();
x = 42;
}
}
public class InlineFinalInstanceFieldTest {
@Test
public void testEncodableFinal() {
EncodableFinal a = new EncodableFinal();
assertThat(a.m_bool).isEqualTo(true);
assertThat(a.m_byte).isEqualTo((byte) 'b');
assertThat(a.m_char).isEqualTo('c');
assertThat(a.m_short).isEqualTo((short) 128);
assertThat(a.m_int).isEqualTo(12345);
assertThat(a.m_string).isEqualTo("string");
assertThat(a.m_long).isEqualTo(0x1000200030004000L);
assertThat(a.m_double).isEqualTo(1.0000000000000002);
}
@Test
public void testNotFinal() {
NotFinal a = new NotFinal();
assertThat(a.m_bool).isEqualTo(true);
assertThat(a.m_byte).isEqualTo((byte) 'b');
assertThat(a.m_char).isEqualTo('c');
assertThat(a.m_short).isEqualTo((short) 128);
assertThat(a.m_int).isEqualTo(12345);
assertThat(a.m_string).isEqualTo("string");
assertThat(a.m_long).isEqualTo(0x1000200030004000L);
assertThat(a.m_double).isEqualTo(1.0000000000000002);
a.m_string = "still a string";
a.changeMInt();
assertThat(a.m_string).isEqualTo("still a string");
assertThat(a.m_int).isEqualTo(12346);
}
@Test
public void testUnEncodableFinal() {
UnEncodableFinal a = new UnEncodableFinal();
assertThat(a.m_int == 0 || a.m_int == 1).isTrue();
}
@Test
public void testHasCharSequenceFinal() {
HasCharSequenceFinal a = new HasCharSequenceFinal();
assertThat(a.m_charseq).isEqualTo("SEQ");
}
@Test
public void testOneInitCanReplaceFinal() {
OneInitCanReplaceFinal a = new OneInitCanReplaceFinal();
assertThat(a.m_int).isEqualTo(1);
}
@Test
public void testOneInitCantReplaceFinal() {
OneInitCantReplaceFinal a = new OneInitCantReplaceFinal(2);
assertThat(a.m_int).isEqualTo(2);
}
@Test
public void testTwoInitCantReplaceFinal() {
TwoInitCantReplaceFinal a = new TwoInitCantReplaceFinal();
assertThat(a.m_int).isEqualTo(5);
}
@Test
public void testMixedTypeInstance() {
MixedTypeInstance a = new MixedTypeInstance();
assertThat(a.return_final_inlineable()).isEqualTo(0);
assertThat(a.m_final_inlineable).isEqualTo(0);
assertThat(a.return_non_final_inlineable()).isEqualTo(5);
assertThat(a.m_non_final_inlineable).isEqualTo(5);
assertThat(a.m_final_accessed).isEqualTo(2);
assertThat(a.m_non_final_accessed).isEqualTo(6);
assertThat(a.m_changed_0).isEqualTo(0);
assertThat(a.m_changed_2).isEqualTo(2);
assertThat(a.m_changed_4).isEqualTo(4);
assertThat(a.m_changed_5).isEqualTo(5);
assertThat(a.m_not_deletable).isEqualTo(0);
}
@Test
public void testReadInCtors() {
ReadInCtors1 a = new ReadInCtors1();
ReadInCtors2 b = new ReadInCtors2();
assertThat(a.m_int).isEqualTo(5);
assertThat(a.m_int_2).isEqualTo(5);
assertThat(b.m_int_3).isEqualTo(5);
}
@Test
public void testMultipleLayerAccesseds() {
MultipleLayerAccessed a = new MultipleLayerAccessed();
assertThat(a.m_a).isEqualTo(0);
assertThat(a.m_b).isEqualTo(3);
assertThat(a.m_non_final_accessed).isEqualTo(4);
assertThat(a.m_final_accessed).isEqualTo(2);
}
@Test
public void testEscapeInInit() {
EscapeObject a = new EscapeObject();
assertThat(a.m_a).isEqualTo(2);
}
@Test
public void testString() {
AccessedString a = new AccessedString();
assertThat(a.s.length()).isEqualTo(1);
assertThat(a.x).isEqualTo(42);
NotAccessedString b = new NotAccessedString();
assertThat(b.s.length()).isEqualTo(4);
assertThat(b.x).isEqualTo(42);
}
}
| mit |
BoiseState/CS121-resources | examples/chap04/StringEquals.java | 748 | /**
* Demonstrate equals versus == for objects.
*
* @author amit
*/
public class StringEquals
{
public static void main(String[] args)
{
String s1 = "hello";
String s2 = new String("hello");
if (s1 == s2)
System.out.println("Using == hello is hello");
else
System.out.println("Using == hello is not hello!");
if (s1.equals(s2))
System.out.println("Using equals hello is hello");
else
System.out.println("Using equals hello is not hello!");
if(s1.compareTo(s2) == 0)
{
System.out.println(s1 + " equals " + s2);
}
else if(s1.compareTo(s2) < 0)
{
System.out.println(s1 + " less than " + s2);
}
else if(s1.compareTo(s2) > 0)
{
System.out.println(s1 + " greater than " + s2);
}
}
}
| mit |
CarsonF/silex-idea-plugin | src/sk/sorien/silexplugin/pimple/Parameter.java | 604 | package sk.sorien.silexplugin.pimple;
import sk.sorien.silexplugin.utils.ContainerMapItem;
/**
* @author Stanislav Turza
*/
public class Parameter extends ContainerMapItem {
private final ParameterType type;
private final String value;
public Parameter(String name, ParameterType type, String value) {
super(name);
this.type = type;
this.value = value;
}
public ParameterType getType() {
return type;
}
public String getFqn() {
return "\\" + type.toString();
}
public String getValue() {
return value;
}
}
| mit |
comapi/comapi-sdk-android | COMAPI/foundation/src/test/java/com/comapi/helpers/DataTestHelper.java | 4757 | /*
* The MIT License (MIT)
*
* Copyright (c) 2017 Comapi (trading name of Dynmark International Limited)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
* LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.comapi.helpers;
import android.content.Context;
import android.content.SharedPreferences;
import org.robolectric.RuntimeEnvironment;
/**
* @author Marcin Swierczek
* @since 1.0.0
*/
public class DataTestHelper {
/*
Session
*/
public static final String KEY_PROFILE_ID = "pId";
public static final String KEY_SESSION_ID = "sId";
public static final String KEY_ACCESS_TOKEN = "sT";
public static final String KEY_EXPIRES_ON = "exp";
public static final String PROFILE_ID = "profileId";
public static final String SESSION_ID = "sessionId";
public static final String ACCESS_TOKEN = "accessToken";
public static final long EXPIRES_ON = Long.MAX_VALUE;
/*
Device
*/
public static final String KEY_INSTANCE_ID = "iId";
public static final String KEY_APP_VER = "aV";
public static final String KEY_DEVICE_ID = "dId";
public static final String KEY_API_SPACE_ID = "aS";
public static final String KEY_PUSH_TOKEN = "pushToken";
public static final String INSTANCE_ID = "instanceId";
public static final int APP_VER = 1;
public static final String DEVICE_ID = "deviceId";
public static final String API_SPACE_ID = "apiSpaceId";
public static final String PUSH_TOKEN = "pushToken";
/*
Files
*/
public static final String fileNameSession = "profile."+API_SPACE_ID;
public static final String fileNameDevice = "device."+API_SPACE_ID;
public static void saveSessionData() {
SharedPreferences sharedPreferences = RuntimeEnvironment.application.getSharedPreferences(fileNameSession, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(KEY_PROFILE_ID, PROFILE_ID);
editor.putString(KEY_SESSION_ID, SESSION_ID);
editor.putLong(KEY_EXPIRES_ON, EXPIRES_ON);
editor.putString(KEY_ACCESS_TOKEN, ACCESS_TOKEN);
editor.clear().apply();
}
public static void saveExpiredSessionData() {
SharedPreferences sharedPreferences = RuntimeEnvironment.application.getSharedPreferences(fileNameSession, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(KEY_PROFILE_ID, PROFILE_ID);
editor.putString(KEY_SESSION_ID, SESSION_ID);
editor.putLong(KEY_EXPIRES_ON, 0);
editor.putString(KEY_ACCESS_TOKEN, ACCESS_TOKEN);
editor.clear().apply();
}
public static void clearSessionData() {
SharedPreferences sharedPreferences = RuntimeEnvironment.application.getSharedPreferences(fileNameSession, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear().apply();
}
public static void saveDeviceData() {
SharedPreferences sharedPreferences = RuntimeEnvironment.application.getSharedPreferences(fileNameDevice, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(KEY_DEVICE_ID, DEVICE_ID);
editor.putString(KEY_INSTANCE_ID, INSTANCE_ID);
editor.putInt(KEY_APP_VER, APP_VER);
editor.putString(KEY_API_SPACE_ID, API_SPACE_ID);
editor.clear().apply();
}
public static void clearDeviceData() {
SharedPreferences sharedPreferences = RuntimeEnvironment.application.getSharedPreferences(fileNameDevice, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear().apply();
}
}
| mit |
hubcarl/android-html-engine | src/com/x5/template/providers/NetTemplates.java | 1117 | package com.x5.template.providers;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class NetTemplates extends TemplateProvider
{
private String baseURL = null;
public NetTemplates(String baseURL)
{
this.baseURL = baseURL;
}
public String loadContainerDoc(String docName)
throws IOException
{
return getUrlContents(baseURL + docName);
}
public String getProtocol()
{
return "net";
}
private static String getUrlContents(String theUrl)
throws IOException
{
URL url = new URL(theUrl);
URLConnection urlConnection = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder content = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
content.append(line + "\n");
}
bufferedReader.close();
return content.toString();
}
}
| mit |
spacerovka/jShop | src/main/java/shop/main/controller/admin/AdminCategoriesController.java | 4995 | package shop.main.controller.admin;
import static shop.main.controller.admin.AdminController.ADMIN_PREFIX;
import static shop.main.controller.admin.AdminController.MANAGER_PREFIX;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import shop.main.data.entity.Category;
import shop.main.data.service.CategoryService;
import shop.main.utils.URLUtils;
@Controller
@RequestMapping(value = { ADMIN_PREFIX, MANAGER_PREFIX })
public class AdminCategoriesController extends AdminController {
@Autowired
private CategoryService categoryService;
@Autowired
ServletContext context;
@RequestMapping(value = "/categories")
public String categoriesList(Model model) {
loadTableData("", null, 1, PAGE_SIZE, model);
return "../admin/categories/categories";
}
@RequestMapping(value = "/findCategories", method = RequestMethod.POST)
public String findCategories(@RequestParam String name, @RequestParam String url,
@RequestParam(value = "current", required = false) Integer current,
@RequestParam(value = "pageSize", required = false) Integer pageSize, Model model) {
loadTableData(name, url, current, pageSize, model);
return "../admin/categories/_table";
}
private void loadTableData(String name, String url, Integer current, Integer pageSize, Model model) {
Pageable pageable = new PageRequest(current - 1, pageSize);
model.addAttribute("categoryList", categoryService.findByNameAndURL(name, url, pageable));
model.addAttribute("current", current);
model.addAttribute("pageSize", pageSize);
addPaginator(model, current, pageSize, categoryService.countByNameAndURL(name, url));
}
@RequestMapping(value = "/category", method = RequestMethod.POST)
public String saveCategory(@ModelAttribute("category") @Valid Category category, BindingResult result, Model model,
final RedirectAttributes redirectAttributes, HttpServletRequest request) {
if (result.hasErrors()) {
redirectAttributes.addFlashAttribute("errorMessage", "URL is not unique!");
model.addAttribute("errorSummary", result.getFieldErrors().stream()
.map(e -> e.getField() + " error - " + e.getDefaultMessage() + " ").collect(Collectors.toList()));
return "../admin/categories/edit_category";
} else if (category.isNew() && !categoryService.checkUniqueURL(category)) {
model.addAttribute("errorSummary", new ArrayList<String>(Arrays.asList("URL is not unique!")));
model.addAttribute("urlError", "has-error");
return "../admin/categories/edit_category";
} else {
if (category.isNew()) {
redirectAttributes.addFlashAttribute("flashMessage", "Category added successfully!");
} else {
redirectAttributes.addFlashAttribute("flashMessage", "Category updated successfully!");
}
if (category.getParentCategory().getId() == -1) {
category.setParentCategory(null);
}
categoryService.saveCategory(category);
return "redirect:" + getUrlPrefix(request) + "categories";
}
}
@RequestMapping(value = "/category/add", method = RequestMethod.GET)
public String addCategory(Model model) {
model.addAttribute("category", new Category());
model.addAttribute("urlError", "");
model.addAttribute("parentCategoryList", categoryService.listAll());
return "../admin/categories/edit_category";
}
@RequestMapping(value = "/category/{id}/update", method = RequestMethod.GET)
public String editCategory(@PathVariable("id") long id, Model model) {
model.addAttribute("category", categoryService.findCategoryById(id));
model.addAttribute("urlError", "");
model.addAttribute("parentCategoryList", categoryService.listAll());
model.addAttribute("images", URLUtils.getCategoryImages(context, id));
return "../admin/categories/edit_category";
}
@RequestMapping(value = "/category/{id}/delete", method = RequestMethod.GET)
public String deleteCategory(@PathVariable("id") long id, Model model, final RedirectAttributes redirectAttributes,
HttpServletRequest request) {
categoryService.deleteCategoryById(id);
redirectAttributes.addFlashAttribute("flashMessage", "Category deleted successfully!");
// TODO delete images
return "redirect:" + getUrlPrefix(request) + "categories";
}
}
| mit |
seqcode/seqcode-core | src/org/seqcode/viz/metaprofile/MotifProfiler.java | 3060 | package org.seqcode.viz.metaprofile;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedList;
import org.seqcode.data.motifdb.WeightMatrix;
import org.seqcode.genome.Genome;
import org.seqcode.genome.location.Point;
import org.seqcode.genome.location.Region;
import org.seqcode.genome.location.StrandedPoint;
import org.seqcode.genome.sequence.SequenceGenerator;
import org.seqcode.gsebricks.verbs.motifs.WeightMatrixScoreProfile;
import org.seqcode.gsebricks.verbs.motifs.WeightMatrixScorer;
public class MotifProfiler implements PointProfiler<Point, Profile>{
private WeightMatrix motif;
private WeightMatrixScorer scorer;
private SequenceGenerator seqgen;
private Genome gen;
private BinningParameters params=null;
private double minThreshold=0;
public MotifProfiler(BinningParameters bp, Genome g, WeightMatrix wm, double minThres, boolean useCache, String seqPath){
minThreshold=minThres;
gen=g;
params=bp;
motif=wm;
scorer = new WeightMatrixScorer(motif);
seqgen = new SequenceGenerator();
seqgen.useCache(useCache);
if(useCache){
seqgen.setGenomePath(seqPath);
}
}
public BinningParameters getBinningParameters() {
return params;
}
public Profile execute(Point a) {
double[] array = new double[params.getNumBins()];
for(int i = 0; i < array.length; i++) { array[i] = 0; }
int window = params.getWindowSize();
int left = window/2;
int right = window-left-1;
int start = Math.max(1, a.getLocation()-left);
int end = Math.min(a.getLocation()+right, a.getGenome().getChromLength(a.getChrom()));
Region query = new Region(gen, a.getChrom(), start, end);
boolean strand = (a instanceof StrandedPoint) ?
((StrandedPoint)a).getStrand() == '+' : true;
String seq = seqgen.execute(query);
WeightMatrixScoreProfile profiler = scorer.execute(seq);
for(int i=query.getStart(); i<query.getEnd(); i+=params.getBinSize()){
double maxScore=Double.MIN_VALUE;
int maxPos=0;
for(int j=i; j<i+params.getBinSize() && j<query.getEnd(); j++){
int offset = j-query.getStart();
if(profiler.getMaxScore(offset)>maxScore){
maxScore= profiler.getMaxScore(offset);
maxPos=offset;
}
}
if(maxScore>=minThreshold){
int startbin, stopbin;
startbin = params.findBin(maxPos);
stopbin = params.findBin(maxPos+motif.length()-1);
if(!strand) {
int tmp = (params.getNumBins()-stopbin)-1;
stopbin = (params.getNumBins()-startbin)-1;
startbin = tmp;
}
//addToArray(startbin, stopbin, array, maxScore);
maxToArray(startbin, stopbin, array, maxScore);
}
}
return new PointProfile(a, params, array, (a instanceof StrandedPoint));
}
private void addToArray(int i, int j, double[] array, double value) {
for(int k = i; k <= j; k++) {
array[k] += value;
}
}
private void maxToArray(int i, int j, double[] array, double value) {
for(int k = i; k <= j; k++) {
array[k] = Math.max(array[k],value);
}
}
public void cleanup() {}
}
| mit |
Kuruchy/and_mymovies | app/src/main/java/com/kuruchy/android/and_mymovies/EndlessRecyclerViewScrollListener.java | 4317 | package com.kuruchy.android.and_mymovies;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
public abstract class EndlessRecyclerViewScrollListener extends RecyclerView.OnScrollListener {
// The minimum amount of items to have below your current scroll position
// before loading more.
private int visibleThreshold = 5;
// The current offset index of data you have loaded
private int currentPage = 0;
// The total number of items in the dataset after the last load
private int previousTotalItemCount = 0;
// True if we are still waiting for the last set of data to load.
private boolean loading = true;
// Sets the starting page index
private int startingPageIndex = 0;
RecyclerView.LayoutManager mLayoutManager;
public EndlessRecyclerViewScrollListener(LinearLayoutManager layoutManager) {
this.mLayoutManager = layoutManager;
}
public EndlessRecyclerViewScrollListener(GridLayoutManager layoutManager) {
this.mLayoutManager = layoutManager;
visibleThreshold = visibleThreshold * layoutManager.getSpanCount();
}
public EndlessRecyclerViewScrollListener(StaggeredGridLayoutManager layoutManager) {
this.mLayoutManager = layoutManager;
visibleThreshold = visibleThreshold * layoutManager.getSpanCount();
}
public int getLastVisibleItem(int[] lastVisibleItemPositions) {
int maxSize = 0;
for (int i = 0; i < lastVisibleItemPositions.length; i++) {
if (i == 0) {
maxSize = lastVisibleItemPositions[i];
}
else if (lastVisibleItemPositions[i] > maxSize) {
maxSize = lastVisibleItemPositions[i];
}
}
return maxSize;
}
// This happens many times a second during a scroll, so be wary of the code you place here.
// We are given a few useful parameters to help us work out if we need to load some more data,
// but first we check if we are waiting for the previous load to finish.
@Override
public void onScrolled(RecyclerView view, int dx, int dy) {
int lastVisibleItemPosition = 0;
int totalItemCount = mLayoutManager.getItemCount();
if (mLayoutManager instanceof StaggeredGridLayoutManager) {
int[] lastVisibleItemPositions = ((StaggeredGridLayoutManager) mLayoutManager).findLastVisibleItemPositions(null);
// get maximum element within the list
lastVisibleItemPosition = getLastVisibleItem(lastVisibleItemPositions);
} else if (mLayoutManager instanceof GridLayoutManager) {
lastVisibleItemPosition = ((GridLayoutManager) mLayoutManager).findLastVisibleItemPosition();
} else if (mLayoutManager instanceof LinearLayoutManager) {
lastVisibleItemPosition = ((LinearLayoutManager) mLayoutManager).findLastVisibleItemPosition();
}
// If it’s still loading, we check to see if the dataset count has
// changed, if so we conclude it has finished loading and update the current page
// number and total item count.
if (loading && (totalItemCount > previousTotalItemCount)) {
loading = false;
previousTotalItemCount = totalItemCount;
}
// If it isn’t currently loading, we check to see if we have breached
// the visibleThreshold and need to reload more data.
// If we do need to reload some more data, we execute onLoadMore to fetch the data.
// threshold should reflect how many total columns there are too
if (!loading && (lastVisibleItemPosition + visibleThreshold) > totalItemCount) {
currentPage++;
onLoadMore(currentPage, totalItemCount, view);
loading = true;
}
}
// Call whenever performing new searches
public void resetState() {
this.currentPage = this.startingPageIndex;
this.previousTotalItemCount = 0;
this.loading = true;
}
// Defines the process for actually loading more data based on page
public abstract void onLoadMore(int page, int totalItemsCount, RecyclerView view);
} | mit |
ZejunPeng/leetcode | src/array/q_485.java | 516 | /*
485.最大连续1的个数
给定一个二进制数组, 计算其中最大连续1的个数。
示例 1:
输入: [1,1,0,1,1,1]
输出: 3
解释: 开头的两位和最后的三位都是连续1,所以最大连续1的个数是 3.
*/
package array;
public class q_485 {
public int findMaxConsecutiveOnes(int[] nums) {
int local = 0;
int global = 0;
for (int i : nums){
global = Math.max(global , local = i == 0 ? 0 : local + 1);
}
return global;
}
}
| mit |
TomiTakussaari/phaas | src/test/java/com/github/tomitakussaari/phaas/user/UsersFromEnvironmentStringCreator.java | 2279 | package com.github.tomitakussaari.phaas.user;
import com.github.tomitakussaari.phaas.model.PasswordEncodingAlgorithm;
import com.github.tomitakussaari.phaas.user.UsersFromEnvironment.UserData;
import com.github.tomitakussaari.phaas.user.dao.UserConfigurationDTO;
import com.github.tomitakussaari.phaas.user.dao.UserConfigurationRepository;
import com.github.tomitakussaari.phaas.user.dao.UserDTO;
import com.github.tomitakussaari.phaas.user.dao.UserRepository;
import com.github.tomitakussaari.phaas.util.CryptoHelper;
import com.github.tomitakussaari.phaas.util.PepperSource;
import org.mockito.Mockito;
import java.util.Collections;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.when;
public class UsersFromEnvironmentStringCreator {
private static final UserConfigurationRepository userConfigurationRepository = Mockito.mock(UserConfigurationRepository.class);
private static final UserRepository userRepository = Mockito.mock(UserRepository.class);
/**
* Can be used to print out json configuration for initializing phaas user database
*/
public static void main(String... args) {
String sharedSecret = "secret";
String password = "my-password";
UsersService usersService = new UsersService(userConfigurationRepository, userRepository, new CryptoHelper(new PepperSource("secret-pepper")));
final UserData userData = new UserData();
when(userRepository.save(any(UserDTO.class))).then(invocationOnMock -> {
userData.setUserDTO((UserDTO) invocationOnMock.getArguments()[0]);
return invocationOnMock.getArguments()[0];
});
when(userConfigurationRepository.save(any(UserConfigurationDTO.class))).then(invocationOnMock -> {
UserConfigurationDTO userConfigurationDTO = (UserConfigurationDTO) invocationOnMock.getArguments()[0];
userData.setUserConfigurationDTOs(new UserConfigurationDTO[]{userConfigurationDTO});
return userConfigurationDTO;
});
usersService.createUser("testing-user", PasswordEncodingAlgorithm.ARGON2, Collections.singletonList(UsersService.ROLE.USER), password, sharedSecret);
System.out.println(UserData.serialize(Collections.singletonList(userData)));
}
}
| mit |
rchain/Rholang | src/main/java/coop/rchain/syntax/rholang/Absyn/PPtPar.java | 831 | package coop.rchain.syntax.rholang.Absyn; // Java Package generated by the BNF Converter.
public class PPtPar extends PPattern {
public final PPattern ppattern_1, ppattern_2;
public PPtPar(PPattern p1, PPattern p2) { ppattern_1 = p1; ppattern_2 = p2; }
public <R,A> R accept(coop.rchain.syntax.rholang.Absyn.PPattern.Visitor<R,A> v, A arg) { return v.visit(this, arg); }
public boolean equals(Object o) {
if (this == o) return true;
if (o instanceof coop.rchain.syntax.rholang.Absyn.PPtPar) {
coop.rchain.syntax.rholang.Absyn.PPtPar x = (coop.rchain.syntax.rholang.Absyn.PPtPar)o;
return this.ppattern_1.equals(x.ppattern_1) && this.ppattern_2.equals(x.ppattern_2);
}
return false;
}
public int hashCode() {
return 37*(this.ppattern_1.hashCode())+this.ppattern_2.hashCode();
}
}
| mit |
DaanSander/Omega-Engine | src/main/java/com/daansander/engine/component/Button.java | 244 | package com.daansander.engine.component;
import java.util.HashSet;
/**
* Created by Daan on 8-10-2015.
*/
public abstract class Button implements Component {
protected HashSet<ListenerComponent> listenerComponents = new HashSet<>();
}
| mit |
hzmdream/dead_local | dl-base/src/main/java/dl/base/product/service/support/ProductTypeServiceImpl.java | 387 | package dl.base.product.service.support;
import org.springframework.stereotype.Service;
import dl.base.product.model.ProductTypeDO;
import dl.base.product.service.ProductTypeService;
import dl.common.service.BaseServiceImpl;
@Service(value="productTypeService")
public class ProductTypeServiceImpl extends BaseServiceImpl<ProductTypeDO> implements ProductTypeService {
}
| mit |
gardncl/elements-of-programming-interviews | binarytrees/src/main/java/LockingBinaryTree.java | 315 | public class LockingBinaryTree extends BinaryTree<Integer> {
/*
10.17
*/
public LockingBinaryTree(Integer data) {
super(data);
}
public boolean isLocked() {
return false;
}
public boolean lock() {
return false;
}
public void unlock() {
}
}
| mit |
theCubeMC/theCube | src/main/java/theCube/data/Article.java | 226 | package theCube.data;
public final class Article{
public final String header;
public final String text;
public Article(String header, String text) {
this.header = header;
this.text = text;
}
} | mit |
contentful/cma-cookies-demo | mobile/src/main/java/com/contentful/androidcookies/WearableService.java | 1534 | /*
* Copyright (C) 2014 Contentful GmbH
*
* 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.contentful.androidcookies;
import android.content.Intent;
import com.contentful.androidcookies.shared.Constants;
import com.google.android.gms.wearable.MessageEvent;
import com.google.android.gms.wearable.WearableListenerService;
/**
* WearableService.
*/
public class WearableService extends WearableListenerService {
@Override public void onMessageReceived(MessageEvent messageEvent) {
super.onMessageReceived(messageEvent);
String path = messageEvent.getPath();
if (Constants.PATH_CREATE_COOKIE.equals(path)) {
startService(new Intent(this, CookieService.class)
.setAction(CookieService.ACTION_CREATE_COOKIE)
.putExtra(CookieService.EXTRA_COOKIE, new String(messageEvent.getData())));
} else if (Constants.PATH_REQUEST_COOKIE.equals(path)) {
startService(new Intent(this, CookieService.class)
.setAction(CookieService.ACTION_REQUEST_COOKIE));
}
}
}
| mit |
selvasingh/azure-sdk-for-java | sdk/spring/azure-spring-data-gremlin/src/test/java/com/microsoft/spring/data/gremlin/repository/BookReferenceRepositoryIT.java | 7161 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.microsoft.spring.data.gremlin.repository;
import com.microsoft.spring.data.gremlin.common.GremlinEntityType;
import com.microsoft.spring.data.gremlin.common.TestRepositoryConfiguration;
import com.microsoft.spring.data.gremlin.common.domain.Book;
import com.microsoft.spring.data.gremlin.common.domain.BookReference;
import com.microsoft.spring.data.gremlin.common.repository.BookReferenceRepository;
import com.microsoft.spring.data.gremlin.common.repository.BookRepository;
import org.assertj.core.util.Lists;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.NonNull;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = TestRepositoryConfiguration.class)
public class BookReferenceRepositoryIT {
private static final Integer BOOK_ID_0 = 0;
private static final Integer BOOK_ID_1 = 1;
private static final Integer BOOK_ID_2 = 2;
private static final Integer BOOK_REFERENCE_ID_0 = 3;
private static final Integer BOOK_REFERENCE_ID_1 = 4;
private static final Integer NO_EXIST_ID = -1;
private static final String NAME_0 = "name-0";
private static final String NAME_1 = "name-1";
private static final String NAME_2 = "name-2";
private static final Double PRINCE_0 = 3.4;
private static final Double PRINCE_1 = 72.0;
private static final Double PRINCE_2 = 102.82;
private static final Book BOOK_0 = new Book(BOOK_ID_0, NAME_0, PRINCE_0);
private static final Book BOOK_1 = new Book(BOOK_ID_1, NAME_1, PRINCE_1);
private static final Book BOOK_2 = new Book(BOOK_ID_2, NAME_2, PRINCE_2);
private static final BookReference BOOK_REFERENCE_0 = new BookReference(BOOK_REFERENCE_ID_0, BOOK_ID_0, BOOK_ID_2);
private static final BookReference BOOK_REFERENCE_1 = new BookReference(BOOK_REFERENCE_ID_1, BOOK_ID_1, BOOK_ID_2);
private static final List<Book> BOOKS = Arrays.asList(BOOK_0, BOOK_1, BOOK_2);
private static final List<BookReference> BOOK_REFERENCES = Arrays.asList(BOOK_REFERENCE_0, BOOK_REFERENCE_1);
@Autowired
private BookReferenceRepository referenceRepository;
@Autowired
private BookRepository bookRepository;
@Before
public void setup() {
this.referenceRepository.deleteAll();
this.bookRepository.deleteAll();
}
private void assertDomainListEquals(@NonNull List<BookReference> found, @NonNull List<BookReference> expected) {
found.sort(Comparator.comparing(BookReference::getId));
expected.sort(Comparator.comparing(BookReference::getId));
Assert.assertEquals(found.size(), expected.size());
Assert.assertEquals(found, expected);
}
@Test
public void testDeleteAll() {
bookRepository.saveAll(BOOKS);
referenceRepository.saveAll(BOOK_REFERENCES);
Assert.assertTrue(referenceRepository.findAll().iterator().hasNext());
referenceRepository.deleteAll();
Assert.assertFalse(referenceRepository.findAll().iterator().hasNext());
}
@Test
public void testDeleteAllOnType() {
bookRepository.saveAll(BOOKS);
referenceRepository.saveAll(BOOK_REFERENCES);
Assert.assertTrue(referenceRepository.findAll().iterator().hasNext());
referenceRepository.deleteAll(GremlinEntityType.EDGE);
Assert.assertFalse(referenceRepository.findAll().iterator().hasNext());
}
@Test
public void testDeleteAllOnDomain() {
bookRepository.saveAll(BOOKS);
referenceRepository.saveAll(BOOK_REFERENCES);
Assert.assertTrue(referenceRepository.findAll().iterator().hasNext());
referenceRepository.deleteAll(BookReference.class);
Assert.assertFalse(referenceRepository.findAll().iterator().hasNext());
}
@Test
public void testSave() {
bookRepository.saveAll(BOOKS);
referenceRepository.save(BOOK_REFERENCE_0);
Assert.assertTrue(referenceRepository.findById(BOOK_REFERENCE_0.getId()).isPresent());
Assert.assertFalse(referenceRepository.findById(BOOK_REFERENCE_1.getId()).isPresent());
}
@Test
public void testSaveAll() {
bookRepository.saveAll(BOOKS);
referenceRepository.saveAll(BOOK_REFERENCES);
final List<BookReference> found = Lists.newArrayList(referenceRepository.findAll());
assertDomainListEquals(found, BOOK_REFERENCES);
}
@Test
public void testFindById() {
bookRepository.saveAll(BOOKS);
referenceRepository.saveAll(BOOK_REFERENCES);
Optional<BookReference> optional = referenceRepository.findById(BOOK_REFERENCE_0.getId());
Assert.assertTrue(optional.isPresent());
Assert.assertEquals(optional.get(), BOOK_REFERENCE_0);
optional = referenceRepository.findById(NO_EXIST_ID);
Assert.assertFalse(optional.isPresent());
}
@Test
public void testExistsById() {
bookRepository.saveAll(BOOKS);
referenceRepository.saveAll(BOOK_REFERENCES);
Assert.assertTrue(referenceRepository.existsById(BOOK_REFERENCE_0.getId()));
Assert.assertFalse(referenceRepository.existsById(NO_EXIST_ID));
}
@Test
public void testFindAllById() {
bookRepository.saveAll(BOOKS);
referenceRepository.saveAll(BOOK_REFERENCES);
final List<Integer> ids = Arrays.asList(BOOK_REFERENCE_0.getId(), BOOK_REFERENCE_1.getId());
final List<BookReference> found = Lists.newArrayList(referenceRepository.findAllById(ids));
assertDomainListEquals(found, BOOK_REFERENCES);
Assert.assertFalse(referenceRepository.findAllById(Collections.singleton(NO_EXIST_ID)).iterator().hasNext());
}
@Test
public void testCount() {
bookRepository.saveAll(BOOKS);
referenceRepository.saveAll(BOOK_REFERENCES);
Assert.assertEquals(referenceRepository.count(), BOOK_REFERENCES.size() + BOOKS.size());
referenceRepository.deleteAll();
Assert.assertEquals(referenceRepository.count(), 0);
}
@Test
public void testDeleteById() {
bookRepository.saveAll(BOOKS);
referenceRepository.saveAll(BOOK_REFERENCES);
Assert.assertTrue(referenceRepository.findById(BOOK_REFERENCE_0.getId()).isPresent());
referenceRepository.deleteById(BOOK_REFERENCE_0.getId());
Assert.assertFalse(referenceRepository.findById(BOOK_REFERENCE_0.getId()).isPresent());
}
@Test
public void testEdgeCount() {
bookRepository.saveAll(BOOKS);
referenceRepository.saveAll(BOOK_REFERENCES);
Assert.assertEquals(referenceRepository.edgeCount(), BOOK_REFERENCES.size());
}
}
| mit |
flyzsd/java-code-snippets | ibm.jdk8/src/javax/management/MBeanServerBuilder.java | 4702 | /*===========================================================================
* Licensed Materials - Property of IBM
* "Restricted Materials of IBM"
*
* IBM SDK, Java(tm) Technology Edition, v8
* (C) Copyright IBM Corp. 2002, 2007. All Rights Reserved
*
* US Government Users Restricted Rights - Use, duplication or disclosure
* restricted by GSA ADP Schedule Contract with IBM Corp.
*===========================================================================
*/
/*
* Copyright (c) 2002, 2007, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package javax.management;
import com.sun.jmx.mbeanserver.JmxMBeanServer;
/**
* <p>This class represents a builder that creates a default
* {@link javax.management.MBeanServer} implementation.
* The JMX {@link javax.management.MBeanServerFactory} allows
* applications to provide their custom MBeanServer
* implementation by providing a subclass of this class.</p>
*
* @see MBeanServer
* @see MBeanServerFactory
*
* @since 1.5
*/
public class MBeanServerBuilder {
/**
* Public default constructor.
**/
public MBeanServerBuilder() {
}
/**
* This method creates a new MBeanServerDelegate for a new MBeanServer.
* When creating a new MBeanServer the
* {@link javax.management.MBeanServerFactory} first calls this method
* in order to create a new MBeanServerDelegate.
* <br>Then it calls
* <code>newMBeanServer(defaultDomain,outer,delegate)</code>
* passing the <var>delegate</var> that should be used by the MBeanServer
* implementation.
* <p>Note that the passed <var>delegate</var> might not be directly the
* MBeanServerDelegate that was returned by this method. It could
* be, for instance, a new object wrapping the previously
* returned object.
*
* @return A new {@link javax.management.MBeanServerDelegate}.
**/
public MBeanServerDelegate newMBeanServerDelegate() {
return JmxMBeanServer.newMBeanServerDelegate();
}
/**
* This method creates a new MBeanServer implementation object.
* When creating a new MBeanServer the
* {@link javax.management.MBeanServerFactory} first calls
* <code>newMBeanServerDelegate()</code> in order to obtain a new
* {@link javax.management.MBeanServerDelegate} for the new
* MBeanServer. Then it calls
* <code>newMBeanServer(defaultDomain,outer,delegate)</code>
* passing the <var>delegate</var> that should be used by the MBeanServer
* implementation.
* <p>Note that the passed <var>delegate</var> might not be directly the
* MBeanServerDelegate that was returned by this implementation. It could
* be, for instance, a new object wrapping the previously
* returned delegate.
* <p>The <var>outer</var> parameter is a pointer to the MBeanServer that
* should be passed to the {@link javax.management.MBeanRegistration}
* interface when registering MBeans inside the MBeanServer.
* If <var>outer</var> is <code>null</code>, then the MBeanServer
* implementation must use its own <code>this</code> reference when
* invoking the {@link javax.management.MBeanRegistration} interface.
* <p>This makes it possible for a MBeanServer implementation to wrap
* another MBeanServer implementation, in order to implement, e.g,
* security checks, or to prevent access to the actual MBeanServer
* implementation by returning a pointer to a wrapping object.
*
* @param defaultDomain Default domain of the new MBeanServer.
* @param outer A pointer to the MBeanServer object that must be
* passed to the MBeans when invoking their
* {@link javax.management.MBeanRegistration} interface.
* @param delegate A pointer to the MBeanServerDelegate associated
* with the new MBeanServer. The new MBeanServer must register
* this MBean in its MBean repository.
*
* @return A new private implementation of an MBeanServer.
**/
public MBeanServer newMBeanServer(String defaultDomain,
MBeanServer outer,
MBeanServerDelegate delegate) {
// By default, MBeanServerInterceptors are disabled.
// Use com.sun.jmx.mbeanserver.MBeanServerBuilder to obtain
// MBeanServers on which MBeanServerInterceptors are enabled.
return JmxMBeanServer.newMBeanServer(defaultDomain,outer,delegate,
false);
}
}
| mit |
pmarques/SocketIO-Server | SocketIO-Netty/src/test/java/eu/k2c/socket/io/ci/usecases/UC03Handler.java | 2344 | /**
* Copyright (C) 2011 K2C @ Patrick Marques <patrickfmarques@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Except as contained in this notice, the name(s) of the above copyright holders
* shall not be used in advertising or otherwise to promote the sale, use or other
* dealings in this Software without prior written authorization.
*/
package eu.k2c.socket.io.ci.usecases;
import org.apache.log4j.Logger;
import eu.k2c.socket.io.ci.AbstractHandler;
import eu.k2c.socket.io.server.api.SocketIOOutbound;
import eu.k2c.socket.io.server.api.SocketIOSessionEventRegister;
import eu.k2c.socket.io.server.api.SocketIOSessionNSRegister;
import eu.k2c.socket.io.server.exceptions.SocketIOException;
public class UC03Handler extends AbstractHandler {
private static final Logger LOGGER = Logger.getLogger(UC03Handler.class);
// 'test sending messages'
SocketIOOutbound outbound;
@Override
public void onConnect(final SocketIOOutbound outbound, final SocketIOSessionEventRegister eventRegister,
final SocketIOSessionNSRegister NSRegister) {
this.outbound = outbound;
}
@Override
public void onMessage(final long messageID, final String endPoint, final String message) {
try {
outbound.sendMessage(message, null);
} catch (SocketIOException e) {
LOGGER.fatal(e);
}
}
}
| mit |
KaskMartin/I200_FUNZ | src/lib/Sprite.java | 2065 | package lib; /**
* Created by martin on 18.10.15.
* Algkood on laenatud siit: https://github.com/tutsplus/Introduction-to-JavaFX-for-Game-Development/blob/master/Sprite.java
* Kuid kogu klassi on veidike modifitseeritud
*
*/
import javafx.scene.image.Image;
import javafx.scene.canvas.GraphicsContext;
import javafx.geometry.Rectangle2D;
public class Sprite
{
private Image image;
protected double positionX;
protected double positionY;
protected double velocityX;
protected double velocityY;
protected double width;
protected double height;
public Sprite()
{
positionX = 0;
positionY = 0;
velocityX = 0;
velocityY = 0;
}
public void setImage(Image i)
{
image = i;
width = i.getWidth();
height = i.getHeight();
}
public void setImage(String filename)
{
Image i = new Image(filename);
setImage(i);
}
public void setPosition(double x, double y)
{
positionX = x;
positionY = y;
}
public double getPositionX (){
return this.positionX;
}
// public double getPositionY (){
// return this.positionY;
// }
public void setVelocity(double x, double y)
{
velocityX = x;
velocityY = y;
}
public void addVelocity(double x, double y)
{
velocityX += x;
velocityY += y;
}
public void update(double time)
{
positionX += velocityX * time;
positionY += velocityY * time;
}
public void render(GraphicsContext gc)
{
gc.drawImage( image, positionX, positionY );
}
public Rectangle2D getBoundary()
{
return new Rectangle2D(positionX,positionY,width,height);
}
public boolean intersects(Sprite s)
{
return s.getBoundary().intersects( this.getBoundary() );
}
public String toString()
{
return " Position: [" + positionX + "," + positionY + "]"
+ " Velocity: [" + velocityX + "," + velocityY + "]";
}
} | mit |
TormundTargers/Animal-Simulator | src/HuntingFactory.java | 1926 | import java.awt.Color;
import java.util.Random;
/**
* A class responsible for creating the initial population
* of actors in the simulation.
*
* @author Jamie Redding
* @version 20/02/2014
*/
public class HuntingFactory implements Factory
{
// The probability that a hunter will be created in any given grid position.
private static final double HUNTER_CREATION_PROBABILITY = 0.01;
// The probability that a deer will be created in any given grid position.
private static final double DEER_CREATION_PROBABILITY = 0.08;
/**
* Constructor for objects of class HuntingFactory
*/
public HuntingFactory()
{
}
/**
* Optionally create an actor.
* Whether an actor is created will depend upon probabilities
* of actor creation.
* @param row The row that the actor could be placed in
* @param col The column that the actor could be placed in
* @param field The field that the actor could be placed in
* @return A newly created Actor, or null if none is created.
*/
public Actor optionallyCreateActor(int row, int col, Field field)
{
Random rand = Randomizer.getRandom();
if(rand.nextDouble() <= HUNTER_CREATION_PROBABILITY) {
Location location = new Location(row, col);
Hunter hunter = new Hunter(field, location);
return hunter;
}
else if(rand.nextDouble() <= DEER_CREATION_PROBABILITY) {
Location location = new Location(row, col);
Deer deer = new Deer(true, field, location);
return deer;
}
return null;
}
/**
* Associate colors with the animal classes.
* @param view The simulatorview to set the colors of
*/
public void setupColors(SimulatorView view)
{
view.setColor(Deer.class, Color.green);
view.setColor(Hunter.class, Color.red);
}
}
| mit |
Mashashi/ringsms | src/pt/mashashi/ringsms/licensing/MyLicenseCheckerCallBack.java | 2381 | package pt.mashashi.ringsms.licensing;
import pt.mashashi.ringsms.MyLog;
import pt.mashashi.ringsms.threads.ThreadsActivity;
import com.google.android.vending.licensing.LicenseCheckerCallback;
import com.google.android.vending.licensing.Policy;
public class MyLicenseCheckerCallBack implements LicenseCheckerCallback {
private Object objNotify;
private Integer reason;
public MyLicenseCheckerCallBack(Object objNotify){
this.objNotify = objNotify;
reason = null;
}
// Policy.NOT_LICENSED
// In theory the policy can return Policy.NOT_LICENSED here as well.
@Override
public void allow(int reason) {
MyLog.d(ThreadsActivity.DEBUG_TAG, "Allow");
alertResult(Policy.LICENSED);
}
// Policy.LICENSED
// In theory the policy can return Policy.LICENSED here as well. Perhaps the call to the LVL took too long, for example.
@Override
public void dontAllow(int reason) {
MyLog.d(ThreadsActivity.DEBUG_TAG, "Dont Allow");
switch(reason){
case Policy.NOT_LICENSED:{
MyLog.d(ThreadsActivity.DEBUG_TAG, "Not Licensed");
alertResult(Policy.NOT_LICENSED);
break;
}
case Policy.RETRY:{
MyLog.d(ThreadsActivity.DEBUG_TAG, "Retry");
alertResult(Policy.RETRY);
break;
}
}
}
@SuppressWarnings("unused") private static final int ERROR_NOT_MARKET_MANAGED = 0x3;
@SuppressWarnings("unused") private static final int ERROR_SERVER_FAILURE = 0x4;
@SuppressWarnings("unused") private static final int ERROR_OVER_QUOTA = 0x5;
@SuppressWarnings("unused") private static final int ERROR_CONTACTING_SERVER = 0x101;
@SuppressWarnings("unused") private static final int ERROR_INVALID_PACKAGE_NAME = 0x102;
@SuppressWarnings("unused") private static final int ERROR_NON_MATCHING_UID = 0x103;
@Override
public void applicationError(int errorCode) {
MyLog.d(ThreadsActivity.DEBUG_TAG, "App error "+errorCode);
}
private void alertResult(int reason){
synchronized(objNotify){
this.reason = reason;
objNotify.notify();
}
}
public Integer getReason(){
return reason;
}
/*private void verificate(int reason){
switch(reason){
case Policy.NOT_LICENSED:{
MyLog.d(ThreadsActivity.DEBUG_TAG, "Not Licensed");
break;
}
case Policy.RETRY:{
MyLog.d(ThreadsActivity.DEBUG_TAG, "Retry");
break;
}
case Policy.LICENSED:{
MyLog.d(ThreadsActivity.DEBUG_TAG, "Licensed");
break;
}
}
}*/
} | mit |
izou7/izou7AndroidClient | Izouqi/src/com/izouqi/client/server/webservice/dto/CrowdfundingDto.java | 1073 | package com.izouqi.client.server.webservice.dto;
import java.util.Date;
import java.util.List;
public class CrowdfundingDto {
float totalAmount;
float currentAmount;
Date deadLine;
List<CrowdfundingDetailDto> detail;
String registrationInfo;
public float getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(float totalAmount) {
this.totalAmount = totalAmount;
}
public float getCurrentAmount() {
return currentAmount;
}
public void setCurrentAmount(float currentAmount) {
this.currentAmount = currentAmount;
}
public Date getDeadLine() {
return deadLine;
}
public void setDeadLine(Date deadLine) {
this.deadLine = deadLine;
}
public List<CrowdfundingDetailDto> getDetail() {
return detail;
}
public void setDetail(List<CrowdfundingDetailDto> detail) {
this.detail = detail;
}
public String getRegistrationInfo() {
return registrationInfo;
}
public void setRegistrationInfo(String registrationInfo) {
this.registrationInfo = registrationInfo;
}
}
| mit |
wipu/iwant | essential/iwant-api-model/src/main/java/org/fluentjava/iwant/api/model/SideEffect.java | 146 | package org.fluentjava.iwant.api.model;
public interface SideEffect {
String name();
void mutate(SideEffectContext ctx) throws Exception;
}
| mit |
zsoltk/GameOfLife | app/src/main/java/hu/supercluster/gameoflife/game/visualization/cell/AbstractCellColors.java | 659 | package hu.supercluster.gameoflife.game.visualization.cell;
import android.graphics.Color;
import android.graphics.Paint;
import java.util.HashMap;
import java.util.Map;
public class AbstractCellColors implements CellColors {
protected final Map<Integer, Paint> paintMap;
public AbstractCellColors() {
paintMap = new HashMap<>(2);
}
protected Paint createPaint(String color) {
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.parseColor(color));
return paint;
}
@Override
public Paint getPaint(int state) {
return paintMap.get(state);
}
}
| mit |
breadwallet/breadwallet-core | Java/crypto/src/main/java/com/breadwallet/crypto/blockchaindb/models/bdb/Transaction.java | 7580 | /*
* Created by Michael Carrara <michael.carrara@breadwallet.com> on 7/1/19.
* Copyright (c) 2019 Breadwinner AG. All right reserved.
*
* See the LICENSE file at the project root for license information.
* See the CONTRIBUTORS file at the project root for a list of contributors.
*/
package com.breadwallet.crypto.blockchaindb.models.bdb;
import android.support.annotation.Nullable;
import com.breadwallet.crypto.blockchaindb.models.Utilities;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Optional;
import com.google.common.primitives.UnsignedLong;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import static com.google.common.base.Preconditions.checkNotNull;
public class Transaction {
// creator
@JsonCreator
public static Transaction create(@JsonProperty("transaction_id") String transactionId,
@JsonProperty("identifier") String identifier,
@JsonProperty("hash") String hash,
@JsonProperty("blockchain_id") String blockchainId,
@JsonProperty("size") UnsignedLong size,
@JsonProperty("fee") Amount fee,
@JsonProperty("status") String status,
@JsonProperty("_embedded") @Nullable Embedded embedded,
@JsonProperty("first_seen") @Nullable Date firstSeen,
@JsonProperty("timestamp") @Nullable Date timestamp,
@JsonProperty("index") @Nullable UnsignedLong index,
@JsonProperty("block_hash") @Nullable String blockHash,
@JsonProperty("block_height") @Nullable UnsignedLong blockHeight,
@JsonProperty("acknowledgements") @Nullable UnsignedLong acknowledgements,
@JsonProperty("confirmations") @Nullable UnsignedLong confirmations,
@JsonProperty("raw") @Nullable String raw,
@JsonProperty("proof") @Nullable String proof) {
return new Transaction(
checkNotNull(transactionId),
checkNotNull(identifier),
checkNotNull(hash),
checkNotNull(blockchainId),
checkNotNull(size),
checkNotNull(fee),
checkNotNull(status),
embedded,
firstSeen,
timestamp,
index,
blockHash,
blockHeight,
acknowledgements,
confirmations,
raw,
proof
);
}
// fields
private final String transactionId;
private final String identifier;
private final String hash;
private final String blockchainId;
private final UnsignedLong size;
private final Amount fee;
private final String status;
private final @Nullable Embedded embedded;
private final @Nullable Date firstSeen;
private final @Nullable Date timestamp;
private final @Nullable UnsignedLong index;
private final @Nullable String blockHash;
private final @Nullable UnsignedLong blockHeight;
private final @Nullable UnsignedLong acknowledgements;
private final @Nullable UnsignedLong confirmations;
private final @Nullable String raw;
private final @Nullable String proof;
private Transaction(String transactionId,
String identifier,
String hash,
String blockchainId,
UnsignedLong size,
Amount fee,
String status,
@Nullable Embedded embedded,
@Nullable Date firstSeen,
@Nullable Date timestamp,
@Nullable UnsignedLong index,
@Nullable String blockHash,
@Nullable UnsignedLong blockHeight,
@Nullable UnsignedLong acknowledgements,
@Nullable UnsignedLong confirmations,
@Nullable String raw,
@Nullable String proof) {
this.transactionId = transactionId;
this.identifier = identifier;
this.hash = hash;
this.blockchainId = blockchainId;
this.size = size;
this.fee = fee;
this.status = status;
this.embedded = embedded;
this.firstSeen = firstSeen;
this.timestamp = timestamp;
this.index = index;
this.blockHash = blockHash;
this.blockHeight = blockHeight;
this.acknowledgements = acknowledgements;
this.confirmations = confirmations;
this.raw = raw;
this.proof = proof;
}
// getters
@JsonProperty("transaction_id")
public String getId() {
return transactionId;
}
@JsonProperty("identifier")
public String getIdentifier() {
return identifier;
}
@JsonProperty("hash")
public String getHash() {
return hash;
}
@JsonProperty("blockchain_id")
public String getBlockchainId() {
return blockchainId;
}
@JsonProperty("size")
public UnsignedLong getSize() {
return size;
}
@JsonProperty("fee")
public Amount getFee() {
return fee;
}
@JsonProperty("status")
public String getStatus() {
return status;
}
@JsonProperty("first_seen")
public Optional<Date> getFirstSeen() {
return Optional.fromNullable(firstSeen);
}
@JsonProperty("timestamp")
public Optional<Date> getTimestamp() {
return Optional.fromNullable(timestamp);
}
@JsonProperty("index")
public Optional<UnsignedLong> getIndex() {
return Optional.fromNullable(index);
}
@JsonProperty("block_hash")
public Optional<String> getBlockHash() {
return Optional.fromNullable(blockHash);
}
@JsonProperty("block_height")
public Optional<UnsignedLong> getBlockHeight() {
return Optional.fromNullable(blockHeight);
}
@JsonProperty("acknowledgements")
public Optional<UnsignedLong> getAcknowledgements() {
return Optional.fromNullable(acknowledgements);
}
@JsonProperty("confirmations")
public Optional<UnsignedLong> getConfirmations() {
return Optional.fromNullable(confirmations);
}
@JsonProperty("raw")
public Optional<String> getRawValue() {
return Optional.fromNullable(raw);
}
@JsonIgnore
public Optional<byte[]> getRaw() {
return Utilities.getOptionalBase64Bytes(raw);
}
@JsonProperty("proof")
public Optional<String> getProof() {
return Optional.fromNullable(proof);
}
@JsonProperty("_embedded")
public Optional<Embedded> getEmbedded() {
return Optional.fromNullable(embedded);
}
@JsonIgnore
public List<Transfer> getTransfers() {
return embedded == null ? Collections.emptyList() : embedded.transfers;
}
// internal details
public static class Embedded {
@JsonProperty
public List<Transfer> transfers;
}
}
| mit |
isudox/leetcode-solution | java-algorithm/src/main/java/com/leetcode/Problem91.java | 3274 | package com.leetcode;
/**
* 91. Decode Ways
* https://leetcode.com/problems/decode-ways/
*
* A message containing letters from A-Z can be encoded into numbers using the
* following mapping:
*
* 'A' -> "1"
* 'B' -> "2"
* ...
* 'Z' -> "26"
*
* To decode an encoded message, all the digits must be grouped then mapped back
* into letters using the reverse of the mapping above (there may be multiple
* ways). For example, "11106" can be mapped into:
*
* "AAJF" with the grouping (1 1 10 6)
* "KJF" with the grouping (11 10 6)
*
* Note that the grouping (1 11 06) is invalid because "06" cannot be mapped
* into 'F' since "6" is different from "06".
*
* Given a string s containing only digits, return the number of ways to decode
* it.
*
* The answer is guaranteed to fit in a 32-bit integer.
*
* Example 1:
*
* Input: s = "12"
* Output: 2
* Explanation: "12" could be decoded as "AB" (1 2) or "L" (12).
*
* Example 2:
*
* Input: s = "226"
* Output: 3
* Explanation: "226" could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2
* 2 6).
*
* Example 3:
*
* Input: s = "0"
* Output: 0
* Explanation: There is no character that is mapped to a number starting with
* 0.
* The only valid mappings with 0 are 'J' -> "10" and 'T' -> "20", neither of
* which start with 0.
* Hence, there are no valid ways to decode this since all digits need to be
* mapped.
*
* Example 4:
*
* Input: s = "06"
* Output: 0
* Explanation: "06" cannot be mapped to "F" because of the leading zero ("6" is
* different from "06").
*
* Constraints:
*
* 1 <= s.length <= 100
* s contains only digits and may contain leading zero(s).
*/
public class Problem91 {
public int numDecodings(String s) {
int n = s.length();
if (n == 0 || s.charAt(0) == '0') return 0;
if (n == 1) return 1;
int[] dp = new int[n];
dp[n - 1] = s.charAt(n - 1) == '0' ? 0 : 1;
if (s.charAt(n - 2) == '0') {
dp[n - 2] = 0;
} else if ((s.charAt(n - 2) - '0') * 10 + s.charAt(n - 1) - '0' <= 26) {
dp[n - 2] = dp[n - 1] + 1;
} else {
dp[n - 2] = dp[n - 1];
}
for (int i = n - 3; i >= 0; i--) {
if (s.charAt(i) == '0')
dp[i] = 0;
else if ((s.charAt(i) - '0') * 10 + s.charAt(i + 1) - '0' <= 26)
dp[i] = dp[i + 1] + dp[i + 2];
else
dp[i] = dp[i + 1];
}
return dp[0];
}
public int numDecodings2(String s) {
int n = s.length();
if (n == 0 || s.charAt(0) == '0') return 0;
if (n == 1) return 1;
int[] dp = new int[2];
if (s.charAt(n - 1) != '0') dp[1] = 1;
if (s.charAt(n - 2) != '0') {
dp[0] = (s.charAt(n - 2) - '0') * 10 + s.charAt(n - 1) - '0' <= 26 ? dp[1] + 1 : dp[1];
}
for (int i = n - 3; i >= 0; i--) {
if (s.charAt(i) == '0') {
dp[1] = dp[0];
dp[0] = 0;
} else if ((s.charAt(i) - '0') * 10 + s.charAt(i + 1) - '0' <= 26) {
dp[0] = dp[0] + dp[1];
dp[1] = dp[0] - dp[1];
} else {
dp[1] = dp[0];
}
}
return dp[0];
}
}
| mit |
farchanjo/webcron | src/main/java/br/eti/archanjo/webcron/entities/mysql/EnvironmentEntity.java | 1100 | package br.eti.archanjo.webcron.entities.mysql;
import lombok.*;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
/*
* Created by fabricio on 10/07/17.
*/
@Builder
@AllArgsConstructor(access = AccessLevel.PUBLIC)
@NoArgsConstructor(access = AccessLevel.PUBLIC)
@Getter
@Setter
@Table(name = "ENVS")
@Entity(name = "ENVS")
public class EnvironmentEntity implements Serializable {
private static final long serialVersionUID = -3651782794702121063L;
@GeneratedValue(strategy = GenerationType.AUTO)
@Id
@Column(name = "id")
private Long id;
@Column(name = "`key`", nullable = false)
private String key;
@Column(name = "`value`", nullable = false)
private String value;
@Column(name = "created", nullable = false)
private Date created;
@Column(name = "modified", nullable = false)
private Date modified;
@PrePersist
private void prePersist() {
created = new Date();
modified = new Date();
}
@PreUpdate
private void postUpdated() {
modified = new Date();
}
} | mit |
hazendaz/oshi | oshi-core/src/main/java/oshi/hardware/platform/mac/MacDisplay.java | 3882 | /*
* MIT License
*
* Copyright (c) 2019-2021 The OSHI Project Contributors: https://github.com/oshi/oshi/graphs/contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package oshi.hardware.platform.mac;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sun.jna.Pointer; // NOSONAR squid:S1191
import com.sun.jna.platform.mac.CoreFoundation.CFDataRef;
import com.sun.jna.platform.mac.CoreFoundation.CFStringRef;
import com.sun.jna.platform.mac.CoreFoundation.CFTypeRef;
import com.sun.jna.platform.mac.IOKit.IOIterator;
import com.sun.jna.platform.mac.IOKit.IORegistryEntry;
import com.sun.jna.platform.mac.IOKitUtil;
import oshi.annotation.concurrent.Immutable;
import oshi.hardware.Display;
import oshi.hardware.common.AbstractDisplay;
/**
* A Display
*/
@Immutable
final class MacDisplay extends AbstractDisplay {
private static final Logger LOG = LoggerFactory.getLogger(MacDisplay.class);
/**
* Constructor for MacDisplay.
*
* @param edid
* a byte array representing a display EDID
*/
MacDisplay(byte[] edid) {
super(edid);
LOG.debug("Initialized MacDisplay");
}
/**
* Gets Display Information
*
* @return An array of Display objects representing monitors, etc.
*/
public static List<Display> getDisplays() {
List<Display> displays = new ArrayList<>();
// Iterate IO Registry IODisplayConnect
IOIterator serviceIterator = IOKitUtil.getMatchingServices("IODisplayConnect");
if (serviceIterator != null) {
CFStringRef cfEdid = CFStringRef.createCFString("IODisplayEDID");
IORegistryEntry sdService = serviceIterator.next();
while (sdService != null) {
// Display properties are in a child entry
IORegistryEntry properties = sdService.getChildEntry("IOService");
if (properties != null) {
// look up the edid by key
CFTypeRef edidRaw = properties.createCFProperty(cfEdid);
if (edidRaw != null) {
CFDataRef edid = new CFDataRef(edidRaw.getPointer());
// Edid is a byte array of 128 bytes
int length = edid.getLength();
Pointer p = edid.getBytePtr();
displays.add(new MacDisplay(p.getByteArray(0, length)));
edid.release();
}
properties.release();
}
// iterate
sdService.release();
sdService = serviceIterator.next();
}
serviceIterator.release();
cfEdid.release();
}
return displays;
}
}
| mit |
yangra/SoftUni | JavaFundamentals/JavaOOPBasic/01.DefiningClassesExercise/src/_09Google/Main.java | 1956 | package _09Google;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
Map<String, Person> people = new HashMap<>();
while (true) {
String[] record = reader.readLine().split("\\s+");
if ("End".equalsIgnoreCase(record[0])) {
break;
}
people.putIfAbsent(record[0], new Person(record[0]));
Person person = people.get(record[0]);
switch (record[1]) {
case "company":
Person.Company company = person.new Company(record[2],record[3],Double.parseDouble(record[4]));
person.setCompany(company);
break;
case "pokemon":
Person.Pokemon pokemon = person.new Pokemon(record[2],record[3]);
person.getPokemons().add(pokemon);
break;
case "parents":
Person.Human parent = person.new Human(record[2], record[3]);
person.getParents().add(parent);
break;
case "children":
Person.Human child = person.new Human(record[2],record[3]);
person.getChildren().add(child);
break;
case "car":
Person.Car car = person.new Car(record[2], Integer.parseInt(record[3]));
person.setCar(car);
break;
default:
System.out.println("Invalid record!");
break;
}
}
String personName = reader.readLine();
System.out.println(people.get(personName));
}
}
| mit |
teacurran/wirelust-bitbucket-api | client/src/main/java/com/wirelust/bitbucket/client/representations/CommitList.java | 586 | package com.wirelust.bitbucket.client.representations;
import java.io.Serializable;
import java.util.List;
/**
* Date: 10-Oct-2015
*
* @author T. Curran
*/
public class CommitList extends PageableList implements Serializable {
private static final long serialVersionUID = 6410285719035915746L;
String next;
private List<Commit> values;
public String getNext() {
return next;
}
public void setNext(String next) {
this.next = next;
}
public List<Commit> getValues() {
return values;
}
public void setValues(List<Commit> values) {
this.values = values;
}
}
| mit |