hexsha stringlengths 40 40 | size int64 8 1.04M | content stringlengths 8 1.04M | avg_line_length float64 2.24 100 | max_line_length int64 4 1k | alphanum_fraction float64 0.25 0.97 |
|---|---|---|---|---|---|
895017868449681568b1a1bc8f1885fa677c5737 | 1,444 | package au.com.example.restful.persistence.dao.customer.entity;
import javax.persistence.*;
@Entity
@Table(name = "Customer")
public class CustomerEntity implements Cloneable {
private Long id;
private String firstName;
private String lastName;
public CustomerEntity() {
this(null, null, null);
}
public CustomerEntity(Long id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
@Id
@Column(name = "customer_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name = "first_name", nullable = false)
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@Column(name = "last_name", nullable = false)
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
// ====== Cloneable Override =========
@Override
public CustomerEntity clone() {
return new CustomerEntity(id, firstName, lastName);
}
// ====== Overrides ========
@Override
public String toString() {
return "CustomerEntity{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
'}';
}
}
| 21.235294 | 68 | 0.623961 |
34420af3c96c261728a3046e9a9c53f81c0495d4 | 530 | package concurrency.ch5;
public class StaticSingleton {
private static int i = 5;
private StaticSingleton() {
System.out.println("StaticSingleton is create");
}
private static class SingletonHolder {
private static StaticSingleton instance = new StaticSingleton();
}
public static StaticSingleton getInstance() {
return SingletonHolder.instance;
}
public static void main(String[] args) {
System.out.println("StaticSingleton.i = " + StaticSingleton.i);
}
}
| 24.090909 | 72 | 0.675472 |
1b352ed843ee8724c0bae38f24ee04ab31045ea5 | 1,603 | package actors;
import static org.junit.Assert.assertThat;
import org.hamcrest.CoreMatchers;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.fasterxml.jackson.databind.node.ObjectNode;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.testkit.javadsl.TestKit;
import service.TwitterMockServiceImpl;
/**
* This class is used to unit test the TweetUserProfileActor class.
*
* @author Ashwin Soorkeea
*
*/
public class TweetUserProfileActorTest {
static ActorSystem system;
/**
* Create an actor system for the unit tests.
*/
@BeforeClass
public static void setup() {
system = ActorSystem.create();
}
/**
* Destroys the actor system.
*/
@AfterClass
public static void teardown() {
TestKit.shutdownActorSystem(system);
system = null;
}
/**
* Validates the get user profile information by calling the {@code TweetUserProfileActor} by using the
* {@code RequestUserProfileMessage} and confirming that we have at least 1 response.
*/
@Test
public void testGetUserProfile() {
TestKit probe = new TestKit(system);
ActorRef testActor = probe.getTestActor();
ActorRef tweetUserProfileActor = system.actorOf(TweetUserProfileActor.props(testActor));
TweetUserProfileActor.RequestUserProfileMessage req = new TweetUserProfileActor.RequestUserProfileMessage(new TwitterMockServiceImpl(), null, "bank", null, null);
tweetUserProfileActor.tell(req, probe.getRef());
ObjectNode objectNode = probe.expectMsgClass(ObjectNode.class);
assertThat(objectNode.size(), CoreMatchers.is(1));
}
}
| 27.637931 | 164 | 0.761697 |
3d16d340847c52bbe7af35b0403da8dc32ac19b1 | 277 | package com.yuanzf.ioc.order;
import org.springframework.stereotype.Component;
/**
* @Author: yzf
* @Date: 2020/2/19 11:16
* @Desoription:
*/
//@Component
public class IocOrderBean {
@Override
public String toString(){
return "com.yuanzf.ioc.priority.IocBean";
}
}
| 15.388889 | 48 | 0.703971 |
227f382372f3d004f93974b4654d690acdc6b975 | 1,397 | package com.quasar.backend.modules.base.enums;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
@Slf4j
public class AuditResultTypeTypeHandler extends BaseTypeHandler<AuditResultType> {
@Override
public void setNonNullParameter(PreparedStatement preparedStatement, int i, AuditResultType auditResultType, JdbcType jdbcType) throws SQLException {
preparedStatement.setString(i, auditResultType.getVal());
}
@Override
public AuditResultType getNullableResult(ResultSet resultSet, String s) throws SQLException {
log.info("type-handler1:{}", resultSet.getString(s));
return AuditResultType.fromValue(resultSet.getString(s));
}
@Override
public AuditResultType getNullableResult(ResultSet resultSet, int i) throws SQLException {
log.info("type-handler2:{}", resultSet.getString(i));
return AuditResultType.fromValue(resultSet.getString(i));
}
@Override
public AuditResultType getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
log.info("type-handler3:{}", callableStatement.getString(i));
return AuditResultType.fromValue(callableStatement.getString(i));
}
}
| 37.756757 | 153 | 0.76378 |
649ad974b9fd684e8309a3ca6149999324d18dc2 | 13,003 | // ============================================================================
//
// Copyright (C) 2006-2021 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.cwm.compare.factory.comparisonlevel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.Path;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.talend.core.model.metadata.builder.connection.Connection;
import org.talend.core.model.metadata.builder.connection.DatabaseConnection;
import org.talend.core.model.metadata.builder.database.DqRepositoryViewService;
import org.talend.core.model.properties.ConnectionItem;
import org.talend.core.model.properties.Item;
import org.talend.core.model.repository.IRepositoryViewObject;
import org.talend.cwm.compare.DQStructureComparer;
import org.talend.cwm.compare.exception.ReloadCompareException;
import org.talend.cwm.compare.factory.IComparisonLevel;
import org.talend.cwm.compare.factory.IUIHandler;
import org.talend.cwm.db.connection.ConnectionUtils;
import org.talend.cwm.helper.ConnectionHelper;
import org.talend.cwm.helper.SwitchHelpers;
import org.talend.cwm.relational.TdColumn;
import org.talend.dq.helper.EObjectHelper;
import org.talend.dq.helper.resourcehelper.PrvResourceFileHelper;
import org.talend.dq.writer.EMFSharedResources;
import org.talend.resource.ResourceManager;
import org.talend.utils.sugars.TypedReturnCode;
import orgomg.cwm.foundation.softwaredeployment.Component;
import orgomg.cwm.objectmodel.core.ModelElement;
import orgomg.cwm.objectmodel.core.Package;
import orgomg.cwm.resource.relational.ColumnSet;
/**
*
* DOC mzhao class global comment. Compare two selected element in local structure.
*/
public class SelectedLocalComparison implements IComparisonLevel {
private static final int LEFT_RESOURCE = 0;
private static final int RIGHT_RESOURCE = 1;
private Object firstSelectedObj = null, secondSelectedObj = null;
private Connection firstSelectedDataProvider;
private Connection secondSelectedDataProvider;
private Connection tempFirstSelectedDataProvider;
private Connection tempSecondSelectedDataProvider;
private Map<String, Object> options;
public SelectedLocalComparison(Object firstSelectedObj, Object secondSelectedObj) {
this.firstSelectedObj = firstSelectedObj;
this.secondSelectedObj = secondSelectedObj;
options = new HashMap<String, Object>();
// options.put(MatchOptions.OPTION_IGNORE_XMI_ID, true);
}
@Override
public void popComparisonUI(IUIHandler uiHandler) throws ReloadCompareException {
// Judge selected elements types.
ModelElementAdapter meAdapter = new ModelElementAdapter();
firstSelectedDataProvider = meAdapter.getAdaptableProvider(firstSelectedObj);
if (firstSelectedDataProvider != null && firstSelectedDataProvider.eIsProxy()) {
firstSelectedDataProvider = (DatabaseConnection) EObjectHelper.resolveObject(firstSelectedDataProvider);
}
secondSelectedDataProvider = meAdapter.getAdaptableProvider(secondSelectedObj);
if (secondSelectedDataProvider != null && secondSelectedDataProvider.eIsProxy()) {
secondSelectedDataProvider = (DatabaseConnection) EObjectHelper.resolveObject(secondSelectedDataProvider);
}
if (firstSelectedDataProvider == null || secondSelectedDataProvider == null) {
return;
}
DQStructureComparer.deleteFirstResourceFile();
DQStructureComparer.deleteSecondResourceFile();
createTempConnectionFile();
// createCopyedProvider();
// MOD mzhao 2009-03-09 Set default dbname is first. (When compare local
// with distant structure, dbname need to
// displayed at left panel of compare editor,have not handled case when
// compared models both from local
// structure)
// DQStructureComparer.openDiffCompareEditor(getResource(LEFT_RESOURCE), getResource(RIGHT_RESOURCE), options,
// uiHandler,
// DQStructureComparer.getLocalDiffResourceFile(), firstSelectedDataProvider.getName(), firstSelectedObj, true);
}
@SuppressWarnings("deprecation")
protected void createTempConnectionFile() throws ReloadCompareException {
// First resource.
IFile selectedFile1 = PrvResourceFileHelper.getInstance().findCorrespondingFile(firstSelectedDataProvider);
if (selectedFile1 == null) {
selectedFile1 = ResourceManager.getRoot().getFile(
new Path(firstSelectedDataProvider.eResource().getURI().toPlatformString(false)));
}
IFile firstConnectionFile = DQStructureComparer.getFirstComparisonLocalFile();
IFile copyedFile1 = DQStructureComparer.copyedToDestinationFile(selectedFile1, firstConnectionFile);
TypedReturnCode<Connection> returnProvider = DqRepositoryViewService.readFromFile(copyedFile1);
if (!returnProvider.isOk()) {
throw new ReloadCompareException(returnProvider.getMessage());
}
tempFirstSelectedDataProvider = returnProvider.getObject();
// Second resource.
IFile selectedFile2 = PrvResourceFileHelper.getInstance().findCorrespondingFile(secondSelectedDataProvider);
if (selectedFile2 == null) {
selectedFile2 = ResourceManager.getRoot().getFile(
new Path(secondSelectedDataProvider.eResource().getURI().toPlatformString(false)));
}
IFile secondConnectionFile = DQStructureComparer.getSecondComparisonLocalFile();
IFile copyedFile2 = DQStructureComparer.copyedToDestinationFile(selectedFile2, secondConnectionFile);
TypedReturnCode<Connection> returnProvider2 = DqRepositoryViewService.readFromFile(copyedFile2);
if (!returnProvider2.isOk()) {
throw new ReloadCompareException(returnProvider2.getMessage());
}
tempSecondSelectedDataProvider = returnProvider2.getObject();
}
private Resource getResource(int pos) throws ReloadCompareException {
Connection tdProvider = null;
Object selectedObj = null;
switch (pos) {
case LEFT_RESOURCE:
selectedObj = firstSelectedObj;
tdProvider = tempFirstSelectedDataProvider;
break;
case RIGHT_RESOURCE:
selectedObj = secondSelectedObj;
tdProvider = tempSecondSelectedDataProvider;
break;
default:
break;
}
ModelElementAdapter meAdapter = new ModelElementAdapter();
Object rootElement = meAdapter.getListModelElements(selectedObj, tdProvider);
Resource leftResource = null;
if (rootElement instanceof Resource) {
leftResource = (Resource) rootElement;
} else {
// leftResource = tdProvider.eResource();
// leftResource.getContents().clear();
leftResource = ((ModelElement) rootElement).eResource();
leftResource.getContents().clear();
leftResource.getContents().add((ModelElement) rootElement);
}
EMFSharedResources.getInstance().saveResource(leftResource);
return leftResource;
}
/**
* DOC mzhao Interface that do instanceof converter to provider common object to client.
*
* FIXME the class should be made static.
*/
private class ModelElementAdapter {
public Connection getAdaptableProvider(Object element) {
Connection adaptedDataProvider = null;
if (element instanceof IFile) {
// IFile
adaptedDataProvider = PrvResourceFileHelper.getInstance().findProvider((IFile) element);
} else if (element instanceof IRepositoryViewObject) {
Item item = ((IRepositoryViewObject) element).getProperty().getItem();
if (item instanceof ConnectionItem) {
adaptedDataProvider = ((ConnectionItem) item).getConnection();
}
} else if (element instanceof Connection) {
adaptedDataProvider = ConnectionUtils.fillConnectionMetadataInformation((Connection) element);
} else {
Package package1 = SwitchHelpers.PACKAGE_SWITCH.doSwitch((ModelElement) element);
if (package1 != null) {
adaptedDataProvider = ConnectionHelper.getTdDataProvider(package1);
} else {
ColumnSet columnSet1 = SwitchHelpers.COLUMN_SET_SWITCH.doSwitch((ModelElement) element);
if (columnSet1 != null) {
adaptedDataProvider = ConnectionHelper.getDataProvider(columnSet1);
} else {
TdColumn column1 = SwitchHelpers.COLUMN_SWITCH.doSwitch((TdColumn) element);
if (column1 != null) {
adaptedDataProvider = ConnectionHelper.getTdDataProvider(column1);
}
}
}
}
return adaptedDataProvider;
}
public Object getListModelElements(Object element, Connection tdProvider) throws ReloadCompareException {
Object rootElement = null;
// List<ModelElement> meList = new ArrayList<ModelElement>();
if (element instanceof IFile) {
rootElement = tdProvider.eResource();
} else if (element instanceof IRepositoryViewObject) {
rootElement = tdProvider.eResource();
} else if (element instanceof Connection) {
Resource eResource = tdProvider.eResource();
EList<Package> contents = ((Connection) element).getDataPackage();// eResource().getContents();
eResource.getContents().clear();
List<EObject> objects = new ArrayList<EObject>();
for (EObject object : contents) {
if (!(object instanceof Connection || object instanceof Component)) {
objects.add(object);
}
}
eResource.getContents().addAll(objects);
rootElement = eResource;
} else {
Package package1 = SwitchHelpers.PACKAGE_SWITCH.doSwitch((ModelElement) element);
if (package1 != null) {
Package findMatchPackage = DQStructureComparer.findMatchedPackage((Package) element, tdProvider);
findMatchPackage.getDataManager().clear();
rootElement = findMatchPackage;
} else {
ColumnSet columnSet1 = SwitchHelpers.COLUMN_SET_SWITCH.doSwitch((ModelElement) element);
if (columnSet1 != null) {
ColumnSet findMatchedColumnSet = DQStructureComparer.findMatchedColumnSet(columnSet1, tdProvider);
rootElement = findMatchedColumnSet;
} else {
TdColumn column1 = SwitchHelpers.COLUMN_SWITCH.doSwitch((TdColumn) element);
if (column1 != null) {
TdColumn findMathedColumn = DQStructureComparer.findMatchedColumn(column1, tdProvider);
rootElement = findMathedColumn;
((TdColumn) rootElement).getTaggedValue().clear();
// ~MOD 2009-04-21 Clear primary key as well. If
// not clear, it
// will cause exception: not contained in
// a resource
((TdColumn) rootElement).getUniqueKey().clear();
// ~MOD 2009-04-21 Clear foreign key.
((TdColumn) rootElement).getKeyRelationship().clear();
}
}
}
}
return rootElement;
}
}
@Override
public Connection reloadCurrentLevelElement() throws ReloadCompareException {
// FIXME implement this method
return null;
}
}
| 45.785211 | 123 | 0.638545 |
886b59a3a46307c9a3a5ef0dc8b5b81aa526c08b | 1,701 | package com.example.newsapi.controller;
import com.example.newsapi.model.Article;
import com.example.newsapi.service.ArticleService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RequiredArgsConstructor
@RestController
@RequestMapping("/newsapi/v1/news")
public class ArticleController {
private final ArticleService articleService;
@GetMapping("/articles")
public List<Article> getAllArticles(){
return articleService.getAllArticles();
}
@GetMapping("/articles/authors")
public List<String> getAllAuthors(){
return articleService.getAllAuthors();
}
//api/v1/news/articles/author/{mane}
@GetMapping("/articles/author/{author}")
public ResponseEntity<?> getArticlesByAuthor(@PathVariable String author){
if(StringUtils.isBlank(author)){
return ResponseEntity.badRequest().body("Author is invalid");
}
List<Article> articlesByAuthor = articleService.getArticlesByAuthor(author);
if(CollectionUtils.isEmpty(articlesByAuthor)){
return new ResponseEntity<>("no articles found for the author :"+author,
HttpStatus.NOT_FOUND);
}
return ResponseEntity.ok(articlesByAuthor);
}
}
| 28.830508 | 87 | 0.738977 |
2278654c63a093e2aea03638b2dade169270d0e6 | 5,719 | package com.currencyconverter.view;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import com.currencyconverter.R;
import com.currencyconverter.database.DataSource;
import com.currencyconverter.model.Converter;
import com.currencyconverter.model.Currency;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.ListActivity;
import android.content.Intent;
public class MainActivity extends ListActivity {
private DataSource ds;
private ArrayAdapter<String> currencyPrefered;
private TextView primaryCurrency;
private EditText primaryCurrencyQuantity;
private Double quantity;
private Double primaryCurrencyDollarValue ;
private String primaryCurrencyName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
primaryCurrency = (TextView) findViewById(R.id.txt_primary);
primaryCurrencyQuantity = (EditText) findViewById(R.id.et_primary);
quantity = Double.parseDouble(primaryCurrencyQuantity.getText().toString());
//Inicializo la moneda de referencia: el dolar
primaryCurrencyDollarValue = 1.0;
primaryCurrencyName = "USD";
//Inicializo el manejador de base de datos
ds = new DataSource(this);
//Inicializo la lista de favoritos
refreshFavoriteList();
}
/*
* @name: changePrimaryCurrency
* @type: void
* @param: String selection
* @Description: Cambia la moneda de referencia para hacer los computos
*/
public void changePrimaryCurrency(String selection){
//Se retira de la lista de monedas general
currencyPrefered.remove(selection);
//Se extrae el nombre y el pais de la nueva moneda de referencia
String[] mySelection = selection.split(" ");
String name = mySelection[0];
String country = mySelection[2];
//Actualizo las variables globales
primaryCurrencyName = name;
//Se trae el valor en dolares de la nueva moneda de referencia
ds.open();
primaryCurrencyDollarValue = ds.getDollarValue(name);
ds.close();
//Se resetea el valor de quantity
quantity = 1.0;
primaryCurrencyQuantity.setText("1");
//se transforma la lista en base a la nueva moneda de referencia
refreshFavoriteList();
//Pongo el nombre de la nueva moneda de referencia
primaryCurrency.setText(name+" from "+country);
}
/*
* @name: calculate
* @type: void
* @param: view:View
* @Description: hace el calculo de cambio con una cantidad
* especificada por el usuario
*/
public void calculate(View view){
//actualizo el valor de quantity
quantity = Double.parseDouble(
primaryCurrencyQuantity.getText().toString());
//actualizo la lista de favoritos con las nuevas cantidades
refreshFavoriteList();
}
//Cambia a la activity que me permite adicionar monedas favoritas
public void addCurrency(View view){
Intent addIntent = new Intent(this, AddCurrencyActivity.class);
startActivity(addIntent);
finish();
}
//Para informar como se cierra el pad numérico
public void informNumericPad(View view){
Toast.makeText(this, "To exit numeric pad please click back button",
Toast.LENGTH_LONG).show();
}
//Para que "escuche" cuando el usuario quiere cambiar de moneda de referencia
@Override protected void onListItemClick(ListView listView,
View view, int position, long id) {
super.onListItemClick(listView, view, position, id);
Object o = getListAdapter().getItem(position);
changePrimaryCurrency(o.toString());
}
/*
* @name: refreshFavoriteList
* @type: void
* @param: no
* @Description: Actualiza la lista de monedas favoritas y sus valores
*/
private void refreshFavoriteList(){
DecimalFormat df = new DecimalFormat("#,###,###,###.#####");
List<Currency> currencies;
ds.open();
//Extraigo la lista de la base de datos y cierro la conexión
currencies = ds.getPreferedCurrency();
ds.close();
List<String> currenciesString = new ArrayList<String>();
for (Currency currency : currencies) {
//No hago nada si es la moneda de referencia
if (currency.getCurrencyName().equals(primaryCurrencyName)){
continue;
}
Converter converter = new Converter();
Double converted = 0.0;
try {
ds.open();
currency.setDollarValue(ds.getDollarValue
(currency.getCurrencyName()));
ds.close();
converted = converter.convert(quantity,
primaryCurrencyDollarValue, currency.getDollarValue());
} catch (Exception e) {
e.printStackTrace();
}
String currencyString =
currency.getCurrencyName()+
" from: "+currency.getCurrencyCountry()+
" Convertion: "+ df.format(converted);//Convertion to especifically currency
currenciesString.add(currencyString);
}
currencyPrefered =
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, currenciesString);
setListAdapter(currencyPrefered);
}
@Override
public void onBackPressed() {
finish();
}
} | 30.913514 | 98 | 0.659556 |
1a3ed0bcfa147d796aaf5bc12b384d8bdfbe0889 | 6,818 | package org.jabref.logic.cleanup;
import java.util.ArrayList;
import java.util.List;
import org.jabref.logic.formatter.Formatters;
import org.jabref.logic.formatter.IdentityFormatter;
import org.jabref.logic.formatter.bibtexfields.HtmlToLatexFormatter;
import org.jabref.logic.formatter.bibtexfields.HtmlToUnicodeFormatter;
import org.jabref.logic.formatter.bibtexfields.NormalizeDateFormatter;
import org.jabref.logic.formatter.bibtexfields.NormalizeMonthFormatter;
import org.jabref.logic.formatter.bibtexfields.NormalizePagesFormatter;
import org.jabref.logic.formatter.bibtexfields.OrdinalsToSuperscriptFormatter;
import org.jabref.logic.formatter.bibtexfields.UnicodeToLatexFormatter;
import org.jabref.logic.layout.format.LatexToUnicodeFormatter;
import org.jabref.logic.layout.format.ReplaceUnicodeLigaturesFormatter;
import org.jabref.model.cleanup.FieldFormatterCleanup;
import org.jabref.model.cleanup.FieldFormatterCleanups;
import org.jabref.model.cleanup.Formatter;
import org.jabref.model.entry.FieldName;
import org.jabref.model.strings.StringUtil;
public class Cleanups {
public static final FieldFormatterCleanups DEFAULT_SAVE_ACTIONS;
public static final FieldFormatterCleanups RECOMMEND_BIBTEX_ACTIONS;
public static final FieldFormatterCleanups RECOMMEND_BIBLATEX_ACTIONS;
static {
List<FieldFormatterCleanup> defaultFormatters = new ArrayList<>();
defaultFormatters.add(new FieldFormatterCleanup(FieldName.PAGES, new NormalizePagesFormatter()));
defaultFormatters.add(new FieldFormatterCleanup(FieldName.DATE, new NormalizeDateFormatter()));
defaultFormatters.add(new FieldFormatterCleanup(FieldName.MONTH, new NormalizeMonthFormatter()));
defaultFormatters.add(new FieldFormatterCleanup(FieldName.INTERNAL_ALL_TEXT_FIELDS_FIELD, new ReplaceUnicodeLigaturesFormatter()));
DEFAULT_SAVE_ACTIONS = new FieldFormatterCleanups(false, defaultFormatters);
List<FieldFormatterCleanup> recommendedBibTeXFormatters = new ArrayList<>();
recommendedBibTeXFormatters.addAll(defaultFormatters);
recommendedBibTeXFormatters.add(new FieldFormatterCleanup(FieldName.TITLE, new HtmlToLatexFormatter()));
recommendedBibTeXFormatters.add(new FieldFormatterCleanup(FieldName.TITLE, new UnicodeToLatexFormatter()));
recommendedBibTeXFormatters.add(new FieldFormatterCleanup(FieldName.BOOKTITLE, new UnicodeToLatexFormatter()));
recommendedBibTeXFormatters.add(new FieldFormatterCleanup(FieldName.JOURNAL, new UnicodeToLatexFormatter()));
recommendedBibTeXFormatters.add(new FieldFormatterCleanup(FieldName.AUTHOR, new UnicodeToLatexFormatter()));
recommendedBibTeXFormatters.add(new FieldFormatterCleanup(FieldName.EDITOR, new UnicodeToLatexFormatter()));
recommendedBibTeXFormatters.add(new FieldFormatterCleanup(FieldName.INTERNAL_ALL_TEXT_FIELDS_FIELD, new OrdinalsToSuperscriptFormatter()));
RECOMMEND_BIBTEX_ACTIONS = new FieldFormatterCleanups(false, recommendedBibTeXFormatters);
List<FieldFormatterCleanup> recommendedBiblatexFormatters = new ArrayList<>();
recommendedBiblatexFormatters.addAll(defaultFormatters);
recommendedBiblatexFormatters.add(new FieldFormatterCleanup(FieldName.TITLE, new HtmlToUnicodeFormatter()));
recommendedBiblatexFormatters.add(new FieldFormatterCleanup(FieldName.INTERNAL_ALL_TEXT_FIELDS_FIELD, new LatexToUnicodeFormatter()));
RECOMMEND_BIBLATEX_ACTIONS = new FieldFormatterCleanups(false, recommendedBiblatexFormatters);
}
private Cleanups() {
}
public static List<Formatter> getBuiltInFormatters() {
return Formatters.getAll();
}
public static List<FieldFormatterCleanup> parse(String formatterString) {
if ((formatterString == null) || formatterString.isEmpty()) {
// no save actions defined in the meta data
return new ArrayList<>();
}
List<FieldFormatterCleanup> actions = new ArrayList<>();
//read concrete actions
int startIndex = 0;
// first remove all newlines for easier parsing
String remainingString = formatterString;
remainingString = StringUtil.unifyLineBreaks(remainingString, "");
try {
while (startIndex < formatterString.length()) {
// read the field name
int currentIndex = remainingString.indexOf('[');
String fieldKey = remainingString.substring(0, currentIndex);
int endIndex = remainingString.indexOf(']');
startIndex += endIndex + 1;
//read each formatter
int tokenIndex = remainingString.indexOf(',');
do {
boolean doBreak = false;
if ((tokenIndex == -1) || (tokenIndex > endIndex)) {
tokenIndex = remainingString.indexOf(']');
doBreak = true;
}
String formatterKey = remainingString.substring(currentIndex + 1, tokenIndex);
actions.add(new FieldFormatterCleanup(fieldKey, getFormatterFromString(formatterKey)));
remainingString = remainingString.substring(tokenIndex + 1);
if (remainingString.startsWith("]") || doBreak) {
break;
}
tokenIndex = remainingString.indexOf(',');
currentIndex = -1;
} while (true);
}
} catch (StringIndexOutOfBoundsException ignore) {
// if this exception occurs, the remaining part of the save actions string is invalid.
// Thus we stop parsing and take what we have parsed until now
return actions;
}
return actions;
}
public static FieldFormatterCleanups parse(List<String> formatterMetaList) {
if ((formatterMetaList != null) && (formatterMetaList.size() >= 2)) {
boolean enablementStatus = FieldFormatterCleanups.ENABLED.equals(formatterMetaList.get(0));
String formatterString = formatterMetaList.get(1);
return new FieldFormatterCleanups(enablementStatus, parse(formatterString));
} else {
// return default actions
return DEFAULT_SAVE_ACTIONS;
}
}
private static Formatter getFormatterFromString(String formatterName) {
for (Formatter formatter : getBuiltInFormatters()) {
if (formatterName.equals(formatter.getKey())) {
return formatter;
}
}
return new IdentityFormatter();
}
}
| 50.132353 | 148 | 0.692578 |
5102b62526f43deb6f85de05d8c0d25865c0e31b | 1,622 | package com.nurseryapi.entity.user;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ForeignKey;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import com.nurseryapi.entity.EducationEntity;
import com.nurseryapi.entity.SchoolEntity;
import com.nurseryapi.entity.TopicEntity;
import lombok.Getter;
import lombok.Setter;
/**
*
* @author Hamza Aljazara
*
*/
@Entity(name = "TeacherUser")
@Table(name = "teacher_users")
@DiscriminatorValue("TEACHER")
@Setter
@Getter
public class TeacherUserEntity extends UserEntity {
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "school_id", nullable = false, foreignKey = @ForeignKey(name = "fk_teacher_user_school_id"))
private SchoolEntity school;
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "education_id", nullable = false, foreignKey = @ForeignKey(name = "fk_education_grade_id"))
private EducationEntity education;
@ManyToMany(cascade = CascadeType.ALL)
// // @formatter:off
@JoinTable(name = "teachers_topics",
joinColumns = @JoinColumn(name = "teacher_user_id"),
inverseJoinColumns = @JoinColumn(name = "topic_id"))
// @formatter:on
private List<TopicEntity> topics;
} | 31.192308 | 112 | 0.778668 |
71a56c0b50b4d1fc6c819b793e925692afa241a6 | 1,848 | package ru.job4j.homeworks.tasks;
//11.12.* Заполнить массив:
// а) двадцатью первыми натуральными числами, делящимися нацело
// на 13 или на 17 и находящимися в интервале, левая граница которого равна 300;
// б) тридцатью первыми простыми числами (простым называется натураль-ное число,
// большее 1, не имеющее других делителей, кроме единицы и са-мого себя).
public class Task1112 {
public int[] numberTakeAway(int bound, int arraySize, int firstDivider, int secondDivider) {
// bound = 300;
// arraySize = 20;
// firstDivider = 13;
// secondDivider = 17;
// для создания более универсальной программы все условия выведены в разряд переменных
int[] result = new int[arraySize];
for (int i = 0; i < result.length; i++) {
while (bound % firstDivider != 0 && bound % secondDivider != 0) {
bound++;
}
result[i] = bound;
bound++;
}
return result;
}
public int[] naturalNumbersArray(int bound, int arraySize) {
int[] result = new int[arraySize];
// bound = 2;
// arraySize = 30;
// для создания более универсальной программы все условия выведены в разряд переменных
for (int i = 0; i < result.length; i++) {
boolean isSimple = false;
while (!isSimple) {
isSimple = true;
for (int j = 2; j <= bound / 2; j++) {
if (bound % j == 0) {
isSimple = false;
break;
}
}
if (isSimple) {
result[i] = bound;
}
bound++;
}
}
return result;
}
}
| 36.235294 | 97 | 0.502165 |
38bdc7b6b8069008eafa13d75f904726462440a5 | 812 | /*
* 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 interviews.sirionLabs;
/**
*
* @author bharat
*/
public class Hi {
static class A {
static void hi () {
System.err.print("A");
}
}
class B {
void hi () {
System.err.print("B");
}
}
void hi () {
class C {
void hi () {
System.err.print("C");
}
}
Object o = new C() { void hi () {System.err.print("D");} };
((C)o).hi(); new C().hi(); new B().hi();
}
static public void main (String args[]) {
new Hi().hi();
A.hi();
}
}
//DCBA | 20.820513 | 79 | 0.46798 |
72a5e5d4d55ce42834b229ac3ea6d2f1fcea0f4b | 1,316 | // This is a generated file. Not intended for manual editing.
package com.dropbox.djinni.ideaplugin.psi;
import java.util.List;
import org.jetbrains.annotations.*;
import com.intellij.psi.PsiElement;
import com.dropbox.djinni.ideaplugin.psi.impl.DjinniPsiImplUtil.DjinniType;
import com.intellij.navigation.ItemPresentation;
public interface DjinniTypeDefinition extends DjinniNamedElement {
@Nullable
DjinniDerivingParamList getDerivingParamList();
@NotNull
List<DjinniEnumMember> getEnumMemberList();
@Nullable
DjinniEnumTypeVariant getEnumTypeVariant();
@NotNull
List<DjinniInterfaceMember> getInterfaceMemberList();
@Nullable
DjinniInterfaceTypeVariant getInterfaceTypeVariant();
@NotNull
List<DjinniRecordMember> getRecordMemberList();
@Nullable
DjinniRecordTypeVariant getRecordTypeVariant();
@NotNull
PsiElement getEq();
@NotNull
PsiElement getLeftBlockBrace();
@Nullable
PsiElement getLeftParamBrace();
@NotNull
PsiElement getRightBlockBrace();
@Nullable
PsiElement getRightParamBrace();
@NotNull
PsiElement getIdentifier();
String getTypeName();
@NotNull
DjinniType getDjinniType();
String getName();
PsiElement setName(String newName);
@Nullable
PsiElement getNameIdentifier();
ItemPresentation getPresentation();
}
| 19.939394 | 75 | 0.781915 |
42ddd689d1ba18b5143d72a915658012bd00e71c | 1,069 | package io.github.tesla.ops.policy.vo;
import java.io.Serializable;
import java.util.List;
import com.google.common.collect.Lists;
/**
* @ClassName GwPolicyParamVo
* @Description Policy param vo
* @Author zhouchao
* @Date 2018/12/10 21:30
* @Version 1.0
**/
public class GwPolicyParamVo implements Serializable {
private static final long serialVersionUID = -5334060107026490553L;
private RateLimitVo rateLimit = new RateLimitVo();
private QuotaVo quota = new QuotaVo();
private List<String> accessControls = Lists.newArrayList();
public List<String> getAccessControls() {
return accessControls;
}
public QuotaVo getQuota() {
return quota;
}
public RateLimitVo getRateLimit() {
return rateLimit;
}
public void setAccessControls(List<String> accessControls) {
this.accessControls = accessControls;
}
public void setQuota(QuotaVo quota) {
this.quota = quota;
}
public void setRateLimit(RateLimitVo rateLimit) {
this.rateLimit = rateLimit;
}
}
| 23.23913 | 71 | 0.689429 |
2dc16f358fd3aaeaa9ddaa3c73e2baf08c03bcc0 | 606 | package ru.stqa.pft.sandbox;
import org.testng.Assert;
import org.testng.annotations.Test;
public class EquationTests {
@Test
public void return0RootTest() {
Equation equation = new Equation(1, 1, 1);
Assert.assertEquals(equation.returnRoots(), 0);
}
@Test
public void return1RootTest() {
Equation equation = new Equation(0,0,0);
Assert.assertEquals(equation.returnRoots(), 1);
}
@Test
public void return2RootsTest() {
Equation equation = new Equation(1,5,2);
Assert.assertEquals(equation.returnRoots(), 2);
}
}
| 23.307692 | 56 | 0.643564 |
b491f739281b3a5f88bee16d496fa9acd4ef3d1a | 6,061 | package net.sf.javagimmicks.io;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.Arrays;
import java.util.List;
import java.util.zip.Adler32;
import java.util.zip.CheckedInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
* Provides utility methods for basic file handling.
*/
public class FileUtils
{
private FileUtils()
{}
/**
* Splits the path information of a given {@link File} and returns the
* resulting segments as a {@link List} of {@link String}s.
* <p>
* The following algorithm is used internally:
* <ul>
* <li>Convert the given {@link File} into the absolute form</li>
* <li>Convert it into a {@link URI} path (which is OS independent)</li>
* <li>Split the {@link URI} path using {@code /} as a separator</li>
* </ul>
*
* @param file
* the {@link File} for which to determine the path segments
* @return the {@link List} of path segments
*/
public static List<String> getPathSegments(final File file)
{
final List<String> segements = Arrays.asList(file.getAbsoluteFile().toURI().getPath().split("/"));
return segements.subList(1, segements.size());
}
/**
* Returns the {@link Adler32} checksum of the contents of a given
* {@link File}.
*
* @param file
* the {@link File} to calculate the checksum from
* @return the resulting checksum as {@code long} value
*/
public static long getChecksum(final File file)
{
if (file.isDirectory())
{
return 0L;
}
CheckedInputStream cis = null;
try
{
cis = new CheckedInputStream(
new FileInputStream(file), new Adler32());
final byte[] tempBuf = new byte[8192];
final Thread currentThread = Thread.currentThread();
while (cis.read(tempBuf) >= 0)
{
if (currentThread.isInterrupted())
{
return 0L;
}
}
return cis.getChecksum().getValue();
}
catch (final IOException e)
{
return 0L;
}
finally
{
if (cis != null)
{
try
{
cis.close();
}
catch (final IOException e)
{
}
}
}
}
/**
* Unzips a given ZIP file {@link InputStream} into a given target
* {@link File folder}.
* <p>
* The given target {@link File folder} must either exist (and must really be
* a directory) or is must be producible by the calling application.
*
* @param zipFile
* the ZIP file to unzip as {@link InputStream}
* @param targetFolder
* the target {@link File folder} where to unzip the files
* @throws IOException
* if any internal file operation fails
* @throws IllegalArgumentException
* if the given target {@link File folder} is not a directory
*/
public static void unzip(final InputStream zipFile, final File targetFolder) throws IOException,
IllegalArgumentException
{
if (targetFolder.exists())
{
if (!targetFolder.isDirectory())
{
throw new IllegalArgumentException(String.format(
"Given existing target folder '%1$s' is not a directory!", targetFolder));
}
}
else
{
if (!targetFolder.mkdirs())
{
throw new IOException(String.format(
"Could not create target folder '%1$s'!", targetFolder));
}
}
final ZipInputStream zis = new ZipInputStream(zipFile);
final byte[] buffer = new byte[8192];
try
{
for (ZipEntry entry = zis.getNextEntry(); entry != null; entry = zis.getNextEntry())
{
try
{
if (entry.isDirectory())
{
new File(targetFolder, entry.getName()).mkdirs();
}
else
{
final File targetFile = new File(targetFolder, entry.getName());
targetFile.getParentFile().mkdirs();
final FileOutputStream fos = new FileOutputStream(targetFile);
try
{
for (int len = zis.read(buffer); len > 0; len = zis.read(buffer))
{
fos.write(buffer, 0, len);
}
}
finally
{
fos.close();
}
}
}
finally
{
zis.closeEntry();
}
}
}
finally
{
zis.close();
}
}
/**
* Unzips a given ZIP {@link File} into a given target {@link File folder}.
* <p>
* The given target {@link File folder} must either exist (and must really be
* a directory) or is must be producible by the calling application.
*
* @param zipFile
* the ZIP {@link File} to unzip
* @param targetFolder
* the target {@link File folder} where to unzip the files
* @throws IOException
* if any internal file operation fails
* @throws IllegalArgumentException
* if the given ZIP {@link File} is not valid or the given target
* {@link File folder} is not a directory
*/
public static void unzip(final File zipFile, final File targetFolder) throws IOException, IllegalArgumentException
{
if (zipFile == null || !zipFile.exists() || !zipFile.isFile())
{
throw new IllegalArgumentException(String.format(
"Given ZIP file '%1$s' is null, does not exist or is not a file!", zipFile));
}
unzip(new FileInputStream(zipFile), targetFolder);
}
}
| 29.280193 | 117 | 0.546609 |
227cad538c5ce5dc22d6a1038dab5abd79a20b72 | 763 | package com.wpy.utils;
import com.wpy.bean.User;
import org.springframework.security.core.context.SecurityContextHolder;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by sang on 2017/12/20.
*/
public class Util {
public static User getCurrentUser() {
User user = null;
if (SecurityContextHolder.getContext().getAuthentication().getPrincipal() instanceof User) {
user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}
return user;
}
public static String format_yyyyMMddHHmmss(Date date) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String str = format.format(date);
return str;
}
}
| 26.310345 | 100 | 0.68152 |
86bd63afe3644098ec9646787392eb4adfb924e7 | 1,466 | package com.github.liuche51.easyTaskX.cluster.task.leader;
import com.github.liuche51.easyTaskX.cluster.NodeService;
import com.github.liuche51.easyTaskX.cluster.leader.BakLeaderService;
import com.github.liuche51.easyTaskX.cluster.task.TimerTask;
import com.github.liuche51.easyTaskX.dto.BaseNode;
import java.util.Date;
import java.util.concurrent.TimeUnit;
/**
* bakleader同步leader集群元数据BinLog任务,异步复制
* 1、每个bakleader都运行一个任务实例
*/
public class ClusterMetaBinLogSyncTask extends TimerTask {
//是否已经存在一个任务实例运行中
public static volatile boolean hasRuning = false;
/**
* 当前已经同步日志的位置号。默认0,表示未开始
*/
private long currentIndex = 0;
public long getCurrentIndex() {
return currentIndex;
}
public void setCurrentIndex(long currentIndex) {
this.currentIndex = currentIndex;
}
@Override
public void run() {
while (!isExit()) {
setLastRunTime(new Date());
try {
BaseNode leader = NodeService.CURRENT_NODE.getClusterLeader();
BakLeaderService.requestLeaderSyncClusterMetaData(leader, this);
} catch (Exception e) {
log.error("", e);
}
try {
if (new Date().getTime() - getLastRunTime().getTime() < 500)//防止频繁空转
TimeUnit.MILLISECONDS.sleep(500L);
} catch (InterruptedException e) {
log.error("", e);
}
}
}
}
| 29.32 | 84 | 0.633697 |
564935543a7b3d836f384ec38382e2bb14c3e2db | 2,801 | /*
* Copyright 2015-2018 Micro Focus or one of its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.cafdataprocessing.corepolicy.common.shared;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.joda.JodaModule;
import com.github.cafdataprocessing.corepolicy.common.*;
import com.github.cafdataprocessing.corepolicy.common.dto.DtoBase;
import com.github.cafdataprocessing.corepolicy.common.dto.conditions.Condition;
/**
*
*/
public class CorePolicyObjectMapper extends ObjectMapper {
public CorePolicyObjectMapper(){
super();
SimpleModule module = new SimpleModule("EnvironmentObjectMapperModule", new Version(0, 1, 0, ""));
// module.addDeserializer(Condition.class, new ConditionDeserializer(this));
module.addSerializer(Document.class, new DocumentSerializer());
module.addDeserializer(Document.class, new DocumentDeserializer());
// module.addDeserializer(PageOfResults.class, new PageOfResultsDeserializer());
module.addDeserializer(EnvironmentSnapshot.class, new EnvironmentSnapshotDeserializer());
module.addDeserializer(Condition.class, new AbstractConditionDeserializer());
module.addDeserializer(DtoBase.class, new DtoDeserializer());
module.addSerializer(DtoBase.class, new DtoSerializer());
module.addSerializer(EnvironmentSnapshot.class, new EnvironmentSnapshotSerializer());
super.registerModule(module);
super.registerModule(new JodaModule());
super.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
super.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
super.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true);
super.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING,true);
//super.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); //this was causing a unit test failure
super.disable(SerializationFeature.INDENT_OUTPUT);
}
}
| 51.87037 | 124 | 0.774009 |
8f88aa7911bfe8f34027d7422978554054c8a2ca | 4,634 | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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 ai.djl.nn.recurrent;
import ai.djl.Device;
import ai.djl.ndarray.NDArray;
import ai.djl.ndarray.NDList;
import ai.djl.ndarray.internal.NDArrayEx;
import ai.djl.ndarray.types.Shape;
import ai.djl.nn.Block;
import ai.djl.nn.Parameter;
import ai.djl.training.ParameterStore;
import ai.djl.util.PairList;
import ai.djl.util.Preconditions;
/**
* {@code RNN} is an implementation of recurrent neural networks which applies a single-gate
* recurrent layer to input. Two kinds of activation function are supported: ReLU and Tanh.
*
* <p>Current implementation refers the [paper](https://crl.ucsd.edu/~elman/Papers/fsit.pdf),
* Finding structure in time - Elman, 1988.
*
* <p>The RNN operator is formulated as below:
*
* <p>With ReLU activation function: \(h_t = relu(W_{ih} * x_t + b_{ih} + W_{hh} * h_{(t-1)} +
* b_{hh})\)
*
* <p>With Tanh activation function: \(h_t = \tanh(W_{ih} * x_t + b_{ih} + W_{hh} * h_{(t-1)} +
* b_{hh})\)
*/
public class RNN extends RecurrentBlock {
private Activation activation;
/**
* Creates a vanilla RNN block.
*
* @param builder the builder used to create the RNN block
*/
RNN(Builder builder) {
super(builder);
activation = builder.activation;
gates = 1;
}
/** {@inheritDoc} */
@Override
protected NDList forwardInternal(
ParameterStore parameterStore,
NDList inputs,
boolean training,
PairList<String, Object> params) {
NDArrayEx ex = inputs.head().getNDArrayInternal();
Device device = inputs.head().getDevice();
NDList rnnParams = new NDList();
for (Parameter parameter : parameters.values()) {
rnnParams.add(parameterStore.getValue(parameter, device, training));
}
NDArray input = inputs.head();
if (inputs.size() == 1) {
int batchIndex = batchFirst ? 0 : 1;
inputs.add(
input.getManager()
.zeros(
new Shape(
(long) numLayers * getNumDirections(),
input.size(batchIndex),
stateSize)));
}
NDList outputs =
ex.rnn(
input,
inputs.get(1),
rnnParams,
hasBiases,
numLayers,
activation,
dropRate,
training,
bidirectional,
batchFirst);
if (returnState) {
return outputs;
}
outputs.stream().skip(1).forEach(NDArray::close);
return new NDList(outputs.get(0));
}
/**
* Creates a builder to build a {@link RNN}.
*
* @return a new builder
*/
public static Builder builder() {
return new Builder();
}
/** The Builder to construct a {@link RNN} type of {@link Block}. */
public static final class Builder extends BaseBuilder<Builder> {
/** {@inheritDoc} */
@Override
protected Builder self() {
return this;
}
/**
* Sets the activation for the RNN - ReLu or Tanh.
*
* @param activation the activation
* @return this Builder
*/
public Builder setActivation(RNN.Activation activation) {
this.activation = activation;
return self();
}
/**
* Builds a {@link RNN} block.
*
* @return the {@link RNN} block
*/
public RNN build() {
Preconditions.checkArgument(
stateSize > 0 && numLayers > 0, "Must set stateSize and numLayers");
return new RNN(this);
}
}
/** An enum that enumerates the type of activation. */
public enum Activation {
RELU,
TANH
}
}
| 31.739726 | 120 | 0.553517 |
c03a3d6df35d5d8197377bcee7b7988fc0614784 | 1,488 | package com.k_int.refine.es_recon.commands;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONException;
import org.json.JSONWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.refine.commands.Command;
import com.k_int.gokb.module.GOKbModuleImpl;
import com.mashape.unirest.http.exceptions.UnirestException;
public class GetTypes extends Command {
final static Logger logger = LoggerFactory.getLogger("ESRecon-get-types");
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Type", "application/json");
// The writer.
JSONWriter writer = new JSONWriter(response.getWriter());
// Get the list of workspaces.
String[] types = GOKbModuleImpl.singleton.getESTypes();
// Open an object.
writer.object();
writer.key("types");
// Open the array.
writer.array();
// Write each value.
for (String type : types) {
writer.value(type);
}
// Close the array.
writer.endArray();
writer.endObject();
} catch (JSONException | UnirestException e) {
respondException(response, e);
}
}
} | 27.054545 | 77 | 0.677419 |
24b144a420bb28178e86b77058abb046401f9c89 | 885 | /*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH under
* one or more contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright ownership.
* Licensed under the Zeebe Community License 1.1. You may not use this file
* except in compliance with the Zeebe Community License 1.1.
*/
package io.camunda.zeebe.broker.clustering;
import io.atomix.cluster.ClusterMembershipService;
import io.atomix.cluster.messaging.ClusterCommunicationService;
import io.atomix.cluster.messaging.ClusterEventService;
import io.atomix.cluster.messaging.MessagingService;
public interface ClusterServices {
MessagingService getMessagingService();
ClusterMembershipService getMembershipService();
ClusterEventService getEventService();
ClusterCommunicationService getCommunicationService();
}
| 35.4 | 81 | 0.822599 |
7a6bf84823e3eab4a9c44df36f916fd3d1521e55 | 2,609 | /*
* Copyright (c) 2020 Network New Technologies Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.networknt.schema;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.TextNode;
public class PropertyNamesValidator extends BaseJsonValidator implements JsonValidator {
private static final Logger logger = LoggerFactory.getLogger(PropertyNamesValidator.class);
private final JsonSchema innerSchema;
public PropertyNamesValidator(String schemaPath, JsonNode schemaNode, JsonSchema parentSchema, ValidationContext validationContext) {
super(schemaPath, schemaNode, parentSchema, ValidatorTypeCode.PROPERTYNAMES, validationContext);
innerSchema = new JsonSchema(validationContext, schemaPath, parentSchema.getCurrentUri(), schemaNode, parentSchema);
}
public Set<ValidationMessage> validate(JsonNode node, JsonNode rootNode, String at) {
debug(logger, node, rootNode, at);
Set<ValidationMessage> errors = new LinkedHashSet<ValidationMessage>();
for (Iterator<String> it = node.fieldNames(); it.hasNext(); ) {
final String pname = it.next();
final TextNode pnameText = TextNode.valueOf(pname);
final Set<ValidationMessage> schemaErrors = innerSchema.validate(pnameText, node, at + "." + pname);
for (final ValidationMessage schemaError : schemaErrors) {
final String path = schemaError.getPath();
String msg = schemaError.getMessage();
if (msg.startsWith(path))
msg = msg.substring(path.length()).replaceFirst("^:\\s*", "");
errors.add(buildValidationMessage(schemaError.getPath(), msg));
}
}
return Collections.unmodifiableSet(errors);
}
@Override
public void preloadJsonSchema() {
innerSchema.initializeValidators();
}
}
| 41.412698 | 137 | 0.711384 |
edbcd1487ffebed20ac33b683d1e3f50e90db944 | 803 | package com.coolio.templates;
/**
* Response Template for User Creation.
*
* @author Aseem Savio
* @since v1.0
*
*/
public class UserCreationResponse {
private String username;
private String firstName;
private String lastName;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public String toString() {
return "UserCreationResponse [username=" + username + ", firstName=" + firstName + ", lastName=" + lastName
+ "]";
}
}
| 17.085106 | 109 | 0.69863 |
e6e27c11c3a1099357a7a3258511243bd29f47ec | 2,009 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.epic.canvascontrollibrary;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Gilgamesh
*/
public class CCLWordProcessorProps
{
public String CanvasID;
public String WindowID;
public String X;
public String Y;
public String Width;
public String Height;
public String HasMarkup;
public String Text;
public String TextColor;
public String TextHeight;
public String TextFontString;
public String LineSpacingInPixels;
public String WordSensitive;
public String WaterMarkText;
public String WaterMarkTextColor;
public String WaterMarkTextHeight;
public String WaterMarkTextFontString;
public String MaxChars;
public String HasShadow;
public String ShadowColor;
public String ShadowOffsetX;
public String ShadowOffsetY;
public String HasRoundedEdges;
public String EdgeRadius;
public String HasBgGradient;
public String BgGradientStartColor;
public String BgGradientEndColor;
public String HasBgImage;
public String BgImageUrl;
public String Margin;
public String HasBorder;
public String BorderColor;
public String BorderLineWidth;
public String UserInputText;
public String VScrollBarWindowID;
public String CaretPosIndex;
public String ShowCaret;
public String CaretColor;
public List<Object> LineBreakIndexes;
public String SelectedTextStartIndex;
public String SelectedTextEndIndex;
public String MouseDown;
public String WasSelecting;
public String AllowedCharsRegEx;
public String CaretTime;
CCLWordProcessorProps()
{
LineBreakIndexes = new ArrayList<Object>();
}
}
| 29.985075 | 55 | 0.661523 |
8759b79244a277766b7700c636e184810f1b68e1 | 751 | package com.star.sync.elasticsearch;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
/**
* Created with IntelliJ IDEA.
* User: hanjiafu
* Date: 18-4-19
* Time: 下午8:26
* Detail:
*/
@SpringBootApplication
public class app extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(
SpringApplicationBuilder application) {
return application.sources(app.class);
}
public static void main(String[] args) {
SpringApplication.run(app.class, args);
}
}
| 26.821429 | 73 | 0.76032 |
b385f553a9a311c8642c1f214f331332389d7f77 | 529 | package jp.ac.keio.bio.fun.xitosbml;
import jp.ac.keio.bio.fun.xitosbml.xitosbml.MainModelValidator;
// TODO: Auto-generated Javadoc
/**
* Spatial SBML Plugin for ImageJ.
*
* @author Kaito Ii <ii@fun.bio.keio.ac.jp>
* @author Akira Funahashi <funa@bio.keio.ac.jp>
* Date Created: Oct 1, 2015
*/
public class Spatial_Model_Validator extends Spatial_SBML {
/* (non-Javadoc)
* @see sbmlplugin.Spatial_SBML#run(java.lang.String)
*/
@Override
public void run(String arg) {
new MainModelValidator().run(arg);;
}
}
| 22.041667 | 63 | 0.714556 |
2fe530aeeb7ac7743de66f320b2693c4ee65c9b8 | 120 | package model.persistence;
import model.User;
public interface IUserPersistance {
User readUser(String username);
} | 13.333333 | 35 | 0.791667 |
bf1f04337a43676901f365e024badd0b406614c6 | 1,845 | // Hash Table; Backtracking
// Write a program to solve a Sudoku puzzle by filling the empty cells.
// A sudoku solution must satisfy all of the following rules:
// Each of the digits 1-9 must occur exactly once in each row.
// Each of the digits 1-9 must occur exactly once in each column.
// Each of the the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.
// Empty cells are indicated by the character '.'.
// A sudoku puzzle...
// ...and its solution numbers marked in red.
// Note:
// The given board contain only digits 1-9 and the character '.'.
// You may assume that the given Sudoku puzzle will have a single unique solution.
// The given board size is always 9x9.
class Solution {
public void solveSudoku(char[][] board) {
solve(board);
}
public boolean solve(char[][] board) {
for (int i=0; i<board.length; i++) {
for (int j=0; j<board[0].length; j++) {
if (board[i][j] == '.') {
for (char c = '1'; c <='9'; c++) {
if (isValid(board, i, j, c)) {
board[i][j] = c;
if (solve(board)) return true;
else board[i][j] = '.';
}
}
return false;
}
}
}
return true;
}
private boolean isValid(char[][] board, int row, int col, char c) {
for (int i = 0; i < 9; i++) {
if (board[i][col] != '.' && board[i][col] == c) return false;
if (board[row][i] != '.' && board[row][i] == c) return false;
if (board[3 * (row/3) + i/3][3 * (col/3) + i%3] != '.' && board[3 * (row/3) + i/3][3 * (col/3) + i%3] == c) return false;
}
return true;
}
} | 33.545455 | 133 | 0.500271 |
3b604f47bd56bec9390b6ae79ce073f068a2c1ce | 17,367 | /**********************************************************************
Copyright (c) 2003 Erik Bengtson and others. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Contributors:
2004 Andy Jefferson - removed MetaData requirement
2007 Andy Jefferson - revised to fit in with JPA requirements for table sequences
...
**********************************************************************/
package org.datanucleus.store.rdbms.valuegenerator;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.datanucleus.exceptions.NucleusUserException;
import org.datanucleus.store.rdbms.adapter.DatastoreAdapter;
import org.datanucleus.store.rdbms.identifier.DatastoreIdentifier;
import org.datanucleus.store.rdbms.table.DatastoreClass;
import org.datanucleus.store.StoreManager;
import org.datanucleus.store.connection.ManagedConnection;
import org.datanucleus.store.rdbms.RDBMSPropertyNames;
import org.datanucleus.store.rdbms.RDBMSStoreManager;
import org.datanucleus.store.valuegenerator.AbstractConnectedGenerator;
import org.datanucleus.store.valuegenerator.ValueGenerationBlock;
import org.datanucleus.store.valuegenerator.ValueGenerationException;
import org.datanucleus.store.valuegenerator.ValueGenerator;
import org.datanucleus.util.Localiser;
import org.datanucleus.util.NucleusLogger;
/**
* Identity generator for RDBMS databases that generates ids using a table in the database.
* This generator is coupled to core and can't be used in standalone mode.
* <P>
* The following properties define the name of the sequence being generated. If "sequence-name" is specified then it is
* used. Otherwise the name of the sequence will either be based on the table name or the class name (for what we are
* generating the ids).
* <UL>
* <LI><U>sequence-name</U> - Name for the sequence</LI>
* <LI><U>sequence-table-basis</U> - Basic for the sequence name (if "sequence-name" not provided). This can be "table" or "class".</LI>
* </UL>
*
* <p>
* The following properties define the table where the identities are generated.
* <UL>
* <LI><U>sequence-catalog-name</U> - the catalog name for the table (defaults to the default catalog)</LI>
* <LI><U>sequence-schema-name</U> - the schema name for the table (defaults to the default schema)</LI>
* <LI><U>sequence-table-name</U> - the table name for the table (defaults to SEQUENCE_TABLE)</LI>
* <LI><U>sequence-name-column-name</U> - the name for the column that represent sequence names</LI>
* <LI><U>sequence-nextval-column-name</U> - the name for the column that represent incrementing sequence values</LI>
* </UL>
*
* <p>
* The following properties control the initial value, and the number of ids that are cached (generated) in each call.
* <UL>
* <LI><U>key-initial-value</U> - start value (if we have no current value). If not specified and we have
* no current value then we do a "SELECT max(column-name) FROM table-name" for the column being incremented</LI>
* <LI><U>key-cache-size</U> - number of unique identifiers to cache (defaults to 5)</LI>
* </UL>
*
* <p>
* The following properties are used when finding the starting point for the identities generated.
* <UL>
* <li><U>table-name</U> - name of the table whose column we are generating the value for</li>
* <li><U>column-name</U> - name of the column that we are generating the value for</li>
* </UL>
* TODO Change structure to not override obtainGenerationBlock so we can follow the superclass process and commonise more code.
*/
public final class TableGenerator extends AbstractConnectedGenerator<Long>
{
/** Connection to the datastore. */
protected ManagedConnection connection;
/** Flag for whether we know that the repository exists. */
protected boolean repositoryExists = false;
/** Table where we store the identities for each table. */
private SequenceTable sequenceTable = null;
/** Name of the sequence that we are storing values under in the SequenceTable. */
private final String sequenceName;
/** Default name for the datastore table storing the sequence values. Defaults to SEQUENCE_TABLE */
public static final String DEFAULT_TABLE_NAME = "SEQUENCE_TABLE";
/** Default name for the column storing the name of the sequence. */
public static final String DEFAULT_SEQUENCE_COLUMN_NAME = "SEQUENCE_NAME";
/** Default name for the column storing the next value of the sequence. */
public static final String DEFAULT_NEXTVALUE_COLUMN_NAME = "NEXT_VAL";
/**
* Constructor.
* @param storeMgr StoreManager
* @param name Symbolic name for this generator
* @param props Properties defining the behaviour of this generator
*/
public TableGenerator(StoreManager storeMgr, String name, Properties props)
{
super(storeMgr, name, props);
allocationSize = 5;
initialValue = -1; // So we know if being set
if (properties != null)
{
if (properties.containsKey(ValueGenerator.PROPERTY_KEY_CACHE_SIZE))
{
try
{
allocationSize = Integer.parseInt(properties.getProperty(ValueGenerator.PROPERTY_KEY_CACHE_SIZE));
}
catch (Exception e)
{
throw new ValueGenerationException(Localiser.msg("Sequence040006",properties.get(ValueGenerator.PROPERTY_KEY_CACHE_SIZE)));
}
}
if (properties.containsKey(ValueGenerator.PROPERTY_KEY_INITIAL_VALUE))
{
try
{
initialValue = Integer.parseInt(properties.getProperty(ValueGenerator.PROPERTY_KEY_INITIAL_VALUE));
}
catch (NumberFormatException nfe)
{
// Not an integer so ignore it
}
}
if (properties.containsKey(ValueGenerator.PROPERTY_SEQUENCE_NAME))
{
// Specified sequence-name so use that
sequenceName = properties.getProperty(ValueGenerator.PROPERTY_SEQUENCE_NAME);
}
else if (properties.containsKey("sequence-table-basis") && properties.getProperty("sequence-table-basis").equalsIgnoreCase("table"))
{
// Use table name in the sequence table as the sequence name
sequenceName = properties.getProperty(ValueGenerator.PROPERTY_TABLE_NAME);
}
else
{
// Use root class name (for this inheritance tree) in the sequence table as the sequence name
sequenceName = properties.getProperty(ValueGenerator.PROPERTY_ROOT_CLASS_NAME);
}
}
else
{
// User hasn't provided any sequence name!!!
sequenceName = "SEQUENCENAME";
}
}
/**
* Accessor for the storage class for values generated with this generator.
* @return Storage class (in this case Long.class)
*/
public static Class getStorageClass()
{
return Long.class;
}
/**
* Convenience accessor for the table being used.
* @return The table
*/
public SequenceTable getTable()
{
return sequenceTable;
}
/**
* Method to reserve a block of "size" identities.
* @param size Block size
* @return The reserved block
*/
public ValueGenerationBlock<Long> reserveBlock(long size)
{
if (size < 1)
{
return null;
}
// search for an ID in the database
List<Long> oid = new ArrayList<>();
try
{
if (sequenceTable == null)
{
initialiseSequenceTable();
}
DatastoreIdentifier sourceTableIdentifier = null;
if (properties.containsKey(ValueGenerator.PROPERTY_TABLE_NAME))
{
sourceTableIdentifier = ((RDBMSStoreManager)storeMgr).getIdentifierFactory().newTableIdentifier(properties.getProperty(ValueGenerator.PROPERTY_TABLE_NAME));
// TODO Apply passed in catalog/schema to this identifier rather than the default for the factory
}
Long nextId = sequenceTable.getNextVal(sequenceName, connection, (int)size, sourceTableIdentifier, properties.getProperty(ValueGenerator.PROPERTY_COLUMN_NAME), initialValue);
for (int i=0; i<size; i++)
{
oid.add(nextId);
nextId = Long.valueOf(nextId.longValue()+1);
}
if (NucleusLogger.VALUEGENERATION.isDebugEnabled())
{
NucleusLogger.VALUEGENERATION.debug(Localiser.msg("040004", "" + size));
}
return new ValueGenerationBlock<>(oid);
}
catch (SQLException e)
{
throw new ValueGenerationException(Localiser.msg("061001",e.getMessage()));
}
}
/**
* Method to return if the repository already exists.
* @return Whether the repository exists
*/
protected boolean repositoryExists()
{
if (repositoryExists)
{
return true;
}
else if (storeMgr.getBooleanProperty(RDBMSPropertyNames.PROPERTY_RDBMS_OMIT_DATABASEMETADATA_GETCOLUMNS))
{
// Assumed to exist if ignoring DMD.getColumns()
repositoryExists = true;
return true;
}
try
{
if (sequenceTable == null)
{
initialiseSequenceTable();
}
sequenceTable.exists((Connection)connection.getConnection(), true);
repositoryExists = true;
return true;
}
catch (SQLException sqle)
{
throw new ValueGenerationException("Exception thrown calling table.exists() for " + sequenceTable, sqle);
}
}
/**
* Method to create the repository for ids to be stored.
* @return Whether it was created successfully.
*/
protected boolean createRepository()
{
RDBMSStoreManager srm = (RDBMSStoreManager) storeMgr;
if (!srm.getSchemaHandler().isAutoCreateTables())
{
throw new NucleusUserException(Localiser.msg("040011", sequenceTable));
}
try
{
if (sequenceTable == null)
{
initialiseSequenceTable();
}
sequenceTable.exists((Connection)connection.getConnection(), true);
repositoryExists = true;
return true;
}
catch (SQLException sqle)
{
throw new ValueGenerationException("Exception thrown calling table.exists() for " + sequenceTable, sqle);
}
}
/**
* Method to initialise the sequence table used for storing the sequence values.
*/
protected synchronized void initialiseSequenceTable()
{
// Set catalog/schema name (using properties, and if not specified using the values for the table)
String catalogName = properties.getProperty(ValueGenerator.PROPERTY_SEQUENCETABLE_CATALOG);
if (catalogName == null)
{
catalogName = properties.getProperty(ValueGenerator.PROPERTY_CATALOG_NAME);
}
String schemaName = properties.getProperty(ValueGenerator.PROPERTY_SEQUENCETABLE_SCHEMA);
if (schemaName == null)
{
schemaName = properties.getProperty(ValueGenerator.PROPERTY_SCHEMA_NAME);
}
String tableName = (properties.getProperty(ValueGenerator.PROPERTY_SEQUENCETABLE_TABLE) == null ? DEFAULT_TABLE_NAME : properties.getProperty(ValueGenerator.PROPERTY_SEQUENCETABLE_TABLE));
RDBMSStoreManager storeMgr = (RDBMSStoreManager)this.storeMgr;
DatastoreAdapter dba = storeMgr.getDatastoreAdapter();
DatastoreIdentifier identifier = storeMgr.getIdentifierFactory().newTableIdentifier(tableName);
if (dba.supportsOption(DatastoreAdapter.CATALOGS_IN_TABLE_DEFINITIONS) && catalogName != null)
{
identifier.setCatalogName(catalogName);
}
if (dba.supportsOption(DatastoreAdapter.SCHEMAS_IN_TABLE_DEFINITIONS) && schemaName != null)
{
identifier.setSchemaName(schemaName);
}
DatastoreClass table = storeMgr.getDatastoreClass(identifier);
if (table != null)
{
sequenceTable = (SequenceTable)table;
}
else
{
String sequenceNameColumnName = DEFAULT_SEQUENCE_COLUMN_NAME;
if (properties.containsKey(ValueGenerator.PROPERTY_SEQUENCETABLE_NAME_COLUMN))
{
sequenceNameColumnName = properties.getProperty(ValueGenerator.PROPERTY_SEQUENCETABLE_NAME_COLUMN);
}
String nextValColumnName = DEFAULT_NEXTVALUE_COLUMN_NAME;
if (properties.containsKey(ValueGenerator.PROPERTY_SEQUENCETABLE_NEXTVAL_COLUMN))
{
nextValColumnName = properties.getProperty(ValueGenerator.PROPERTY_SEQUENCETABLE_NEXTVAL_COLUMN);
}
sequenceTable = new SequenceTable(identifier, storeMgr, sequenceNameColumnName, nextValColumnName);
sequenceTable.initialize(storeMgr.getNucleusContext().getClassLoaderResolver(null));
}
}
/**
* Get a new ValueGenerationBlock with the specified number of ids.
* @param number The number of additional ids required
* @return the ValueGenerationBlock
*/
protected ValueGenerationBlock<Long> obtainGenerationBlock(int number)
{
ValueGenerationBlock<Long> block = null;
// Try getting the block
boolean repository_exists=true; // TODO Ultimately this can be removed when "repositoryExists()" is implemented
try
{
connection = connectionProvider.retrieveConnection();
if (!repositoryExists)
{
synchronized (this)
{
// Make sure the repository is present before proceeding
repositoryExists = repositoryExists();
if (!repositoryExists)
{
createRepository();
repositoryExists = true;
}
}
}
try
{
block = (number < 0) ? reserveBlock() : reserveBlock(number);
}
catch (ValueGenerationException vge)
{
NucleusLogger.VALUEGENERATION.info(Localiser.msg("040003", vge.getMessage()));
if (NucleusLogger.VALUEGENERATION.isDebugEnabled())
{
NucleusLogger.VALUEGENERATION.debug("Caught exception", vge);
}
// attempt to obtain the block of unique identifiers is invalid
repository_exists = false;
}
catch (RuntimeException ex)
{
NucleusLogger.VALUEGENERATION.info(Localiser.msg("040003", ex.getMessage()));
if (NucleusLogger.VALUEGENERATION.isDebugEnabled())
{
NucleusLogger.VALUEGENERATION.debug("Caught exception", ex);
}
// attempt to obtain the block of unique identifiers is invalid
repository_exists = false;
}
}
finally
{
if (connection != null)
{
connectionProvider.releaseConnection();
connection = null;
}
}
// If repository didn't exist, try creating it and then get block
if (!repository_exists)
{
try
{
connection = connectionProvider.retrieveConnection();
NucleusLogger.VALUEGENERATION.info(Localiser.msg("040005"));
if (!createRepository())
{
throw new ValueGenerationException(Localiser.msg("040002"));
}
block = (number < 0) ? reserveBlock() : reserveBlock(number);
}
finally
{
connectionProvider.releaseConnection();
connection = null;
}
}
return block;
}
} | 40.201389 | 197 | 0.612599 |
97e0c7abbfa1d3f7dfc31d62bb9519cb45994855 | 2,834 | package pagamento;
import dao.DaoFactoryPSQL;
import java.sql.*;
import java.util.Vector;
import paciente.*;
import tipoconsulta.*;
import consulta.*;
import convenio.*;
public class DaoPagamentoPSQL implements DaoPagamento
{
PreparedStatement ps=null;
ResultSet r=null;
public boolean buscarConvenio (Convenio conv,Paciente p)
{
try
{
ps =DaoFactoryPSQL.getConnection().prepareStatement("SELECT convenio.cnpj,convenio.instituicao,convenio.percentual" +
" FROM(convenio inner join paciente on paciente.codconvenio = convenio.cnpj)" +
"WHERE paciente.matricula='"+p.getMatricula()+"'");
r =ps.executeQuery();
if(r.next())
{
conv.setCnpj(r.getString("cnpj"));
conv.setInstituicao(r.getString("instituicao"));
conv.setPercentual(r.getInt("percentual"));
return true;
}
else
{
return false;
}
}
catch(Exception ex)
{
System.out.print(ex.getMessage());
return false;
}
}
public void salvarCartao(Cartao cart)
{
}
public boolean buscaPagamento(Consulta c,Paciente p,TipoConsulta tp)
{
try{
ps=DaoFactoryPSQL.getConnection().prepareStatement("select p.matricula,tp.valor from (paciente p inner join consulta "+
"c on p.matricula = c.codpaciente) inner join tipoconsulta tp on tp.codtipoconsulta=c.codtipoconsulta where c.hora='"+c.getHora()+"'");
r=ps.executeQuery();
if(r.next())
{
p.setMatricula(r.getInt("matricula"));
tp.setValor(r.getDouble("valor"));
return true;
}
else
{
return false;
}
}
catch(Exception e)
{
return false;
}
}
public Vector preencheReciboConsulta(Paciente p, Pagamento pag)
{
Vector v= new Vector();
try{
ps=DaoFactoryPSQL.getConnection().prepareStatement("select pac.nome,pg.datapag,pg.total,c.data from (consulta c inner join paciente pac on c.codpaciente=pac.matricula)inner join pagamento pg on c.codconsulta=pg.codconsulta where c.data='"+pag.getDataCons()+"' and c.hora='"+pag.getHora()+"' and pac.matricula='"+p.getMatricula()+"'");
r=ps.executeQuery();
if(r.next())
{
pag.setNome((r.getString("nome")));
pag.setData((r.getString("datapag")));
pag.setDatacons((r.getString("data")));
pag.setTotal((r.getInt("total")));
v.add(pag);
}
}
catch(Exception e)
{
System.out.println("ERRO no SQL:"+e.getMessage());
}
return v;
}
public void finalize()
{
try
{
ps.close();
}
catch(Exception e )
{
System.out.println("" +e);
}
}
} | 21.968992 | 339 | 0.58645 |
c26e58f21c977d85635982fc497a0334a12581bb | 13,208 | /*************************************************************************************
* Copyright (c) 2011, 2012, 2013 James Talbut.
* jim-emitters@spudsoft.co.uk
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* James Talbut - Initial implementation.
************************************************************************************/
package uk.co.spudsoft.birt.emitters.excel;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.extensions.XSSFCellBorder.BorderSide;
import org.eclipse.birt.report.engine.content.IStyle;
import org.eclipse.birt.report.engine.css.engine.CSSEngine;
import org.eclipse.birt.report.engine.css.engine.value.FloatValue;
import org.eclipse.birt.report.engine.css.engine.value.css.CSSConstants;
import org.w3c.dom.css.CSSValue;
import uk.co.spudsoft.birt.emitters.excel.framework.Logger;
/**
* StyleManager is a cache of POI CellStyles to enable POI CellStyles to be reused based upon their BIRT styles.
* @author Jim Talbut
*
*/
public class StyleManager {
/**
* StylePair maintains the relationship between a BIRT style and a POI style.
* @author Jim Talbut
*
*
private class StylePair {
public BirtStyle birtStyle;
public CellStyle poiStyle;
public StylePair(BirtStyle birtStyle, CellStyle poiStyle) {
this.birtStyle = birtStyle;
this.poiStyle = poiStyle;
}
}*/
private Workbook workbook;
private FontManager fm;
// private List<StylePair> styles = new ArrayList<StylePair>();
private Map< BirtStyle, CellStyle > styleMap = new HashMap< BirtStyle, CellStyle >();
private StyleManagerUtils smu;
private CSSEngine cssEngine;
@SuppressWarnings("unused")
private Logger log;
private Locale locale;
/**
* @param workbook
* The workbook for which styles are being tracked.
* @param styleStack
* A style stack, to allow cells to inherit properties from container elements.
* @param log
* Logger to be used during processing.
* @param smu
* Set of functions for carrying out conversions between BIRT and POI.
* @param cssEngine
* BIRT CSS Engine for creating BIRT styles.
*/
public StyleManager(Workbook workbook, Logger log, StyleManagerUtils smu, CSSEngine cssEngine, Locale locale) {
this.workbook = workbook;
this.fm = new FontManager(cssEngine, workbook, smu);
this.log = log;
this.smu = smu;
this.cssEngine = cssEngine;
this.locale = locale;
}
public FontManager getFontManager() {
return fm;
}
public CSSEngine getCssEngine() {
return cssEngine;
}
static int COMPARE_CSS_PROPERTIES[] = {
StylePropertyIndexes.STYLE_TEXT_ALIGN,
StylePropertyIndexes.STYLE_BACKGROUND_COLOR,
StylePropertyIndexes.STYLE_BORDER_TOP_STYLE,
StylePropertyIndexes.STYLE_BORDER_TOP_WIDTH,
StylePropertyIndexes.STYLE_BORDER_TOP_COLOR,
StylePropertyIndexes.STYLE_BORDER_LEFT_STYLE,
StylePropertyIndexes.STYLE_BORDER_LEFT_WIDTH,
StylePropertyIndexes.STYLE_BORDER_LEFT_COLOR,
StylePropertyIndexes.STYLE_BORDER_RIGHT_STYLE,
StylePropertyIndexes.STYLE_BORDER_RIGHT_WIDTH,
StylePropertyIndexes.STYLE_BORDER_RIGHT_COLOR,
StylePropertyIndexes.STYLE_BORDER_BOTTOM_STYLE,
StylePropertyIndexes.STYLE_BORDER_BOTTOM_WIDTH,
StylePropertyIndexes.STYLE_BORDER_BOTTOM_COLOR,
StylePropertyIndexes.STYLE_WHITE_SPACE,
StylePropertyIndexes.STYLE_VERTICAL_ALIGN,
};
/**
* Test whether two BIRT styles are equivalent, as far as the attributes understood by POI are concerned.
* <br/>
* Every attribute tested in this method must be used in the construction of the CellStyle in createStyle.
* @param style1
* The first BIRT style to be compared.
* @param style2
* The second BIRT style to be compared.
* @return
* true if style1 and style2 would produce identical CellStyles if passed to createStyle.
*
private boolean stylesEquivalent( BirtStyle style1, BirtStyle style2) {
// System.out.println( "style1: " + style1 );
// System.out.println( "style2: " + style2 );
for( int i = 0; i < COMPARE_CSS_PROPERTIES.length; ++i ) {
int prop = COMPARE_CSS_PROPERTIES[ i ];
CSSValue value1 = style1.getProperty( prop );
CSSValue value2 = style2.getProperty( prop );
if( ! StyleManagerUtils.objectsEqual( value1, value2 ) ) {
// System.out.println( "Differ on " + i + " because " + value1 + " != " + value2 );
return false;
}
}
if( ! StyleManagerUtils.objectsEqual( style1.getProperty( BirtStyle.TEXT_ROTATION ), style2.getProperty( BirtStyle.TEXT_ROTATION ) ) ) {
// System.out.println( "Differ on " + i + " because " + value1 + " != " + value2 );
return false;
}
// Number format
if( ! StyleManagerUtils.dataFormatsEquivalent( (DataFormatValue)style1.getProperty( StylePropertyIndexes.STYLE_DATA_FORMAT )
, (DataFormatValue)style2.getProperty( StylePropertyIndexes.STYLE_DATA_FORMAT ) ) ) {
// System.out.println( "Differ on DataFormat" );
return false;
}
// Font
if( !FontManager.fontsEquivalent( style1, style2 ) ) {
// System.out.println( "Differ on font" );
return false;
}
return true;
}*/
/**
* Create a new POI CellStyle based upon a BIRT style.
* @param birtStyle
* The BIRT style to base the CellStyle upon.
* @return
* The CellStyle whose attributes are described by the BIRT style.
*/
private CellStyle createStyle( BirtStyle birtStyle ) {
CellStyle poiStyle = workbook.createCellStyle();
// Font
Font font = fm.getFont(birtStyle);
if( font != null ) {
poiStyle.setFont(font);
}
// Alignment
poiStyle.setAlignment(smu.poiAlignmentFromBirtAlignment(birtStyle.getString( StylePropertyIndexes.STYLE_TEXT_ALIGN )));
// Background colour
smu.addBackgroundColourToStyle(workbook, poiStyle, birtStyle.getString( StylePropertyIndexes.STYLE_BACKGROUND_COLOR ));
// Top border
smu.applyBorderStyle(workbook, poiStyle, BorderSide.TOP, birtStyle.getProperty(StylePropertyIndexes.STYLE_BORDER_TOP_COLOR), birtStyle.getProperty(StylePropertyIndexes.STYLE_BORDER_TOP_STYLE), birtStyle.getProperty(StylePropertyIndexes.STYLE_BORDER_TOP_WIDTH));
// Left border
smu.applyBorderStyle(workbook, poiStyle, BorderSide.LEFT, birtStyle.getProperty(StylePropertyIndexes.STYLE_BORDER_LEFT_COLOR), birtStyle.getProperty(StylePropertyIndexes.STYLE_BORDER_LEFT_STYLE), birtStyle.getProperty(StylePropertyIndexes.STYLE_BORDER_LEFT_WIDTH));
// Right border
smu.applyBorderStyle(workbook, poiStyle, BorderSide.RIGHT, birtStyle.getProperty(StylePropertyIndexes.STYLE_BORDER_RIGHT_COLOR), birtStyle.getProperty(StylePropertyIndexes.STYLE_BORDER_RIGHT_STYLE), birtStyle.getProperty(StylePropertyIndexes.STYLE_BORDER_RIGHT_WIDTH));
// Bottom border
smu.applyBorderStyle(workbook, poiStyle, BorderSide.BOTTOM, birtStyle.getProperty(StylePropertyIndexes.STYLE_BORDER_BOTTOM_COLOR), birtStyle.getProperty(StylePropertyIndexes.STYLE_BORDER_BOTTOM_STYLE), birtStyle.getProperty(StylePropertyIndexes.STYLE_BORDER_BOTTOM_WIDTH));
// Number format
smu.applyNumberFormat(workbook, birtStyle, poiStyle, locale);
// Whitespace/wrap
if( CSSConstants.CSS_PRE_VALUE.equals( birtStyle.getString( StylePropertyIndexes.STYLE_WHITE_SPACE ) ) ) {
poiStyle.setWrapText( true );
}
// Vertical alignment
if( CSSConstants.CSS_TOP_VALUE.equals( birtStyle.getString( StylePropertyIndexes.STYLE_VERTICAL_ALIGN ) ) ) {
poiStyle.setVerticalAlignment( CellStyle.VERTICAL_TOP );
} else if ( CSSConstants.CSS_MIDDLE_VALUE.equals( birtStyle.getString( StylePropertyIndexes.STYLE_VERTICAL_ALIGN ) ) ) {
poiStyle.setVerticalAlignment( CellStyle.VERTICAL_CENTER );
} else if ( CSSConstants.CSS_BOTTOM_VALUE.equals( birtStyle.getString( StylePropertyIndexes.STYLE_VERTICAL_ALIGN ) ) ) {
poiStyle.setVerticalAlignment( CellStyle.VERTICAL_BOTTOM );
}
// Rotation
CSSValue rotation = birtStyle.getProperty( BirtStyle.TEXT_ROTATION );
if( rotation instanceof FloatValue ) {
poiStyle.setRotation( (short) ((FloatValue)rotation).getFloatValue() );
}
styleMap.put( birtStyle, poiStyle );
return poiStyle;
}
public CellStyle getStyle( BirtStyle birtStyle ) {
CellStyle poiStyle = styleMap.get(birtStyle);
if( poiStyle == null ) {
poiStyle = createStyle( birtStyle );
}
return poiStyle;
}
private BirtStyle birtStyleFromCellStyle( CellStyle source ) {
for( Entry< BirtStyle, CellStyle > stylePair : styleMap.entrySet() ) {
if( source.equals(stylePair.getValue()) ) {
return stylePair.getKey().clone();
}
}
return new BirtStyle(cssEngine);
}
/**
* Given a POI CellStyle, add border definitions to it and obtain a CellStyle (from the cache or newly created) based upon that.
* @param source
* The POI CellStyle to form the base style.
* @param borderStyleBottom
* The BIRT style of the bottom border.
* @param borderWidthBottom
* The BIRT with of the bottom border.
* @param borderColourBottom
* The BIRT colour of the bottom border.
* @param borderStyleLeft
* The BIRT style of the left border.
* @param borderWidthLeft
* The BIRT width of the left border.
* @param borderColourLeft
* The BIRT colour of the left border.
* @param borderStyleRight
* The BIRT width of the right border.
* @param borderWidthRight
* The BIRT colour of the right border.
* @param borderColourRight
* The BIRT style of the right border.
* @param borderStyleTop
* The BIRT style of the top border.
* @param borderWidthTop
* The BIRT width of the top border.
* @param borderColourTop
* The BIRT colour of the top border.
* @return
* A POI CellStyle equivalent to the source CellStyle with all the defined borders added to it.
*/
public CellStyle getStyleWithBorders( CellStyle source
, CSSValue borderStyleBottom, CSSValue borderWidthBottom, CSSValue borderColourBottom
, CSSValue borderStyleLeft, CSSValue borderWidthLeft, CSSValue borderColourLeft
, CSSValue borderStyleRight, CSSValue borderWidthRight, CSSValue borderColourRight
, CSSValue borderStyleTop, CSSValue borderWidthTop, CSSValue borderColourTop
) {
BirtStyle birtStyle = birtStyleFromCellStyle( source );
if( ( borderStyleBottom != null ) && ( borderWidthBottom != null ) && ( borderColourBottom != null ) ){
birtStyle.setProperty( StylePropertyIndexes.STYLE_BORDER_BOTTOM_STYLE, borderStyleBottom );
birtStyle.setProperty( StylePropertyIndexes.STYLE_BORDER_BOTTOM_WIDTH, borderWidthBottom );
birtStyle.setProperty( StylePropertyIndexes.STYLE_BORDER_BOTTOM_COLOR, borderColourBottom );
}
if( ( borderStyleLeft != null ) && ( borderWidthLeft != null ) && ( borderColourLeft != null ) ){
birtStyle.setProperty( StylePropertyIndexes.STYLE_BORDER_LEFT_STYLE, borderStyleLeft );
birtStyle.setProperty( StylePropertyIndexes.STYLE_BORDER_LEFT_WIDTH, borderWidthLeft );
birtStyle.setProperty( StylePropertyIndexes.STYLE_BORDER_LEFT_COLOR, borderColourLeft );
}
if( ( borderStyleRight != null ) && ( borderWidthRight != null ) && ( borderColourRight != null ) ){
birtStyle.setProperty( StylePropertyIndexes.STYLE_BORDER_RIGHT_STYLE, borderStyleRight );
birtStyle.setProperty( StylePropertyIndexes.STYLE_BORDER_RIGHT_WIDTH, borderWidthRight );
birtStyle.setProperty( StylePropertyIndexes.STYLE_BORDER_RIGHT_COLOR, borderColourRight );
}
if( ( borderStyleTop != null ) && ( borderWidthTop != null ) && ( borderColourTop != null ) ){
birtStyle.setProperty( StylePropertyIndexes.STYLE_BORDER_TOP_STYLE, borderStyleTop );
birtStyle.setProperty( StylePropertyIndexes.STYLE_BORDER_TOP_WIDTH, borderWidthTop );
birtStyle.setProperty( StylePropertyIndexes.STYLE_BORDER_TOP_COLOR, borderColourTop );
}
CellStyle newStyle = getStyle( birtStyle );
return newStyle;
}
/**
* Return a POI style created by combining a POI style with a BIRT style, where the BIRT style overrides the values in the POI style.
* @param source
* The POI style that represents the base style.
* @param birtExtraStyle
* The BIRT style to overlay on top of the POI style.
* @return
* A POI style representing the combination of source and birtExtraStyle.
*/
public CellStyle getStyleWithExtraStyle( CellStyle source, IStyle birtExtraStyle ) {
BirtStyle birtStyle = birtStyleFromCellStyle( source );
for(int i = 0; i < BirtStyle.NUMBER_OF_STYLES; ++i ) {
CSSValue value = birtExtraStyle.getProperty( i );
if( value != null ) {
birtStyle.setProperty( i , value );
}
}
CellStyle newStyle = getStyle( birtStyle );
return newStyle;
}
}
| 41.665615 | 276 | 0.729331 |
0a01f5f55824e3d7c323accae45986490ab7590b | 2,322 | /*
* 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 glm.vec._2.i;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
/**
*
* @author GBarbieri
*/
public class Vec2i extends FuncRelational {
public Vec2i() {
x = 0;
y = 0;
}
public Vec2i(int i) {
x = i;
y = i;
}
public Vec2i(Vec2i v) {
x = v.x;
y = v.y;
}
public Vec2i(int x, int y) {
this.x = x;
this.y = y;
}
public Vec2i set(Vec2i v) {
x = v.x;
y = v.y;
return this;
}
public Vec2i set(int x, int y) {
this.x = x;
this.y = y;
return this;
}
public int[] toIA_() {
return toIA_(new int[2]);
}
public int[] toIA_(int[] ia) {
ia[0] = x;
ia[1] = y;
return ia;
}
public IntBuffer toDib_() {
return toDib(ByteBuffer.allocateDirect(SIZE).order(ByteOrder.nativeOrder()).asIntBuffer());
}
public IntBuffer toDib(IntBuffer ib) {
return toDib(ib, 0);
}
public IntBuffer toDib(IntBuffer ib, int index) {
return ib
.put(index + 0, x)
.put(index + 1, y);
}
public ByteBuffer toDbb_() {
return toDbb(ByteBuffer.allocateDirect(SIZE).order(ByteOrder.nativeOrder()));
}
public ByteBuffer toDbb(ByteBuffer bb) {
return toDbb(bb, 0);
}
public ByteBuffer toDbb(ByteBuffer bb, int index) {
return bb
.putInt(index + 0 * Integer.BYTES, x)
.putInt(index + 1 * Integer.BYTES, y);
}
@Override
public String toString() {
return "(" + x + ", " + y + ")";
}
public void print() {
print("", true);
}
public void print(String title) {
print(title, true);
}
public void print(boolean outStream) {
print("", outStream);
}
public void print(String title, boolean outStream) {
String res = title + "\n(" + x + ", " + y + ")";
if (outStream) {
System.out.print(res);
} else {
System.err.print(res);
}
}
}
| 20.368421 | 99 | 0.516796 |
b4794c2f7ba8d95119362cd891ae10837f00593c | 1,190 | /*
* Copyright 2013 Commonwealth Computer Research, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package geomesa.utils.geotools;
import org.geotools.data.DataStore;
/**
* Utility class to help bridge the Java and Scala code for external consumers
* of the API.
*/
public class ShapefileIngest {
public static DataStore ingestShapefile(String shapefileName,
DataStore dataStore,
String featureName) {
// invoke the Scala code
return geomesa.utils.geotools.GeneralShapefileIngest$.MODULE$.shpToDataStore(
shapefileName, dataStore, featureName);
}
}
| 35 | 85 | 0.691597 |
6bcb75dbfbdf67286f7f18fd1ac83045612ce86a | 1,670 | package mcjty.rftoolscontrol.items.vectorartmodule;
import mcjty.rftools.api.screens.IClientScreenModule;
import mcjty.rftools.api.screens.IModuleRenderHelper;
import mcjty.rftools.api.screens.ModuleRenderInfo;
import mcjty.rftoolscontrol.blocks.vectorart.GfxOp;
import mcjty.rftoolscontrol.compat.rftoolssupport.ModuleDataVectorArt;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import java.util.List;
public class VectorArtClientScreenModule implements IClientScreenModule<ModuleDataVectorArt> {
@Override
public TransformMode getTransformMode() {
return TransformMode.TEXT;
}
@Override
public int getHeight() {
return 114;
}
@Override
public void render(IModuleRenderHelper renderHelper, FontRenderer fontRenderer, int currenty, ModuleDataVectorArt screenData, ModuleRenderInfo renderInfo) {
GlStateManager.disableLighting();
GlStateManager.enableDepth();
GlStateManager.depthMask(false);
if (screenData != null) {
List<GfxOp> ops = screenData.getSortedOperations();
if (ops != null) {
for (GfxOp op : ops) {
op.render();
}
}
}
}
@Override
public void mouseClick(World world, int x, int y, boolean clicked) {
}
@Override
public void setupFromNBT(NBTTagCompound tagCompound, int dim, BlockPos pos) {
}
@Override
public boolean needsServerData() {
return true;
}
}
| 28.793103 | 160 | 0.701796 |
1d540c3fcbd6a3336b144fe50be93142fa7413fe | 1,159 | /*
* Copyright (c) 2020-2021 Polyhedral Development
*
* The Terra API is licensed under the terms of the MIT License. For more details,
* reference the LICENSE file in the common/api directory.
*/
package com.dfsek.terra.api.config;
import com.dfsek.tectonic.api.exception.ConfigException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
public interface Loader {
Loader thenNames(Consumer<List<String>> consumer) throws ConfigException;
Loader thenEntries(Consumer<Set<Map.Entry<String, InputStream>>> consumer) throws ConfigException;
/**
* Get a single file from this Loader.
*
* @param singleFile File to get
*
* @return InputStream from file.
*/
InputStream get(String singleFile) throws IOException;
/**
* Open a subdirectory.
*
* @param directory Directory to open
* @param extension File extension
*/
Loader open(String directory, String extension);
/**
* Close all InputStreams opened.
*/
Loader close();
}
| 24.145833 | 102 | 0.684211 |
649b77a083828624c95cd084d603c104d8cec55c | 1,016 | package mage.cards.h;
import mage.abilities.effects.common.CreateTokenEffect;
import mage.abilities.effects.common.LearnEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.game.permanent.token.WitherbloomToken;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class HuntForSpecimens extends CardImpl {
public HuntForSpecimens(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.SORCERY}, "{1}{B}");
// Create a 1/1 black and green Pest creature token with "When this creature dies, you gain 1 life."
this.getSpellAbility().addEffect(new CreateTokenEffect(new WitherbloomToken()));
// Learn.
this.getSpellAbility().addEffect(new LearnEffect().concatBy("<br>"));
}
private HuntForSpecimens(final HuntForSpecimens card) {
super(card);
}
@Override
public HuntForSpecimens copy() {
return new HuntForSpecimens(this);
}
}
| 28.222222 | 108 | 0.714567 |
a4d4bb8be39dedd1557b6445109a585de1380fff | 4,108 | /**
* (C) Le Hong Phuong, phuonglh@gmail.com
* Vietnam National University, Hanoi, Vietnam.
*/
package vn.hus.nlp.graph.util;
import vn.hus.nlp.graph.AdjacencyListGraph;
import vn.hus.nlp.graph.AdjacencyMatrixGraph;
import vn.hus.nlp.graph.Edge;
import vn.hus.nlp.graph.IGraph;
import vn.hus.nlp.graph.IWeightedGraph;
/**
* @author Le Hong Phuong, phuonglh@gmail.com
* <p>
* Oct 21, 2007, 8:30:03 PM
* <p>
* An utility for processing graphs. This class provides methods for
* common access to graphs, for example, edges extraction.
*/
public class GraphUtilities {
/**
* Extract edges of a graph.
*
* @param graph
* a graph
* @return an array of edges of the graph.
*/
public static Edge[] getEdges(IGraph graph) {
Edge[] edges = new Edge[graph.getNumberOfEdges()];
int e = 0;
for (int u = 0; u < graph.getNumberOfVertices(); u++) {
// get all vertices adjacent to u
VertexIterator iterator = graph.vertexIterator(u);
while (iterator.hasNext()) {
int v = iterator.next();
// create an edge (u,v)
// we don't count for a loop edge of type (u,u)
if (graph.isDirected() || u < v) {
edges[e++] = new Edge(u, v);
}
}
}
return edges;
}
/**
* Extract edges of a weighted graph.
*
* @param graph
* a weighted graph
* @return an array of edges.
*/
public static Edge[] getWeightedEdges(IWeightedGraph graph) {
Edge[] edges = new Edge[graph.getNumberOfEdges()];
int e = 0;
for (int u = 0; u < graph.getNumberOfVertices(); u++) {
// get all edges adjacent to u
EdgeIterator iterator = graph.edgeIterator(u);
while (iterator.hasNext()) {
Edge edge = iterator.next();
if (graph.isDirected() || u < edge.getV()) {
edges[e++] = edge;
}
}
}
return edges;
}
/**
* Copy a graph.
*
* @param g
* a graph
* @param dense
* the returned graph is a dense one or not.
* @return a dense graph that is implemented by an adjacency matrix graph or
* a adjacency list graph.
* @see AdjacencyMatrixGraph
* @see AdjacencyListGraph
*/
public static IGraph copy(IGraph g, boolean dense) {
int n = g.getNumberOfVertices();
// create an appropriate graph
IGraph graph = null;
if (dense) {
graph = new AdjacencyMatrixGraph(n, g.isDirected());
} else {
graph = new AdjacencyListGraph(n, g.isDirected());
}
// fill its edges
for (int u = 0; u < n; u++) {
for (int v = 0; v < n; v++)
if (g.edge(u, v)) {
graph.insert(new Edge(u, v));
}
}
return graph;
}
/**
* Get the transitive closure of a graph.
*
* @param g a graph.
* @return the transitive closure of <code>g</code>.
*/
public static IGraph getTransitiveClosure(IGraph g) {
// copy the original graph
IGraph transitiveClosure = GraphUtilities.copy(g, true);
int n = g.getNumberOfVertices();
// add dummy loop edges
for (int u = 0; u < n; u++) {
transitiveClosure.insert(new Edge(u, u));
}
// the Warhall's algorithm to compute the transitive closure
for (int v = 0; v < n; v++)
for (int u = 0; u < n; u++)
if (transitiveClosure.edge(u, v)) {
for (int w = 0; w < n; w++)
if (transitiveClosure.edge(v, w))
transitiveClosure.insert(new Edge(u, w));
}
return transitiveClosure;
}
/**
* Checks the projectivity of a graph. A graph is projective
* if for all edges (u,v), forall k (u < k < v or v < k < u), there
* exists a path from u to k, that is (u,k) is an edge of the transitive
* closure of g.
* @param g a graph
* @return <code>true</code> or <code>false</code>
*/
public static boolean isProjective(IGraph g) {
// get the transitive closure of g
IGraph tcg = getTransitiveClosure(g);
Edge[] edges = GraphUtilities.getEdges(g);
for (Edge e : edges) {
int u = e.getU();
int v = e.getV();
for (int k = Math.min(u, v); k < Math.max(u, v); k++) {
if (!tcg.edge(u, k)) {
System.err.println("(u,k,v) = (" + u + "," + k + "," + v + ")");
return false;
}
}
}
return true;
}
}
| 26.849673 | 78 | 0.603944 |
4c27b839856704ef34b13d115c11f55d7798fc71 | 555 | package kl.gamestore.services;
import kl.gamestore.domain.dtos.order.OrderAddItemDto;
import kl.gamestore.domain.dtos.order.OrderRemoveItemDto;
import kl.gamestore.domain.entities.Order;
import java.util.List;
public interface OrderService {
String addItem(OrderAddItemDto title, String usersEmail);
String removeItem(OrderRemoveItemDto orderRemoveItemDto, String usersEmail);
List<Order> findAllByUserIdAndGameId(Long userId, Long gameId);
List<Order> findAllOrdersByUserId(Long userId);
String buyItems(String loggedInUser);
}
| 29.210526 | 80 | 0.803604 |
95cb5fe3e99c428fdc6d37b1d5ba608927610fc1 | 1,686 | package model;
import java.time.LocalDate;
public class cliente {
private int id;
private String nome;
private String sobrenome;
private String telefone;
private LocalDate dataDeNascimento;
private long cpf;
private String email;
private String endereco;
public cliente(String nome, String sobrenome, String telefone, LocalDate dataDeNascimento, long cpf, String email, String endereco){
this.nome = nome;
this.sobrenome = sobrenome;
this.telefone = telefone;
this.dataDeNascimento = dataDeNascimento;
this.cpf = cpf;
this.email = email;
this.endereco = endereco;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getNome() {
return this.nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getSobrenome() {
return this.sobrenome;
}
public void setSobrenome(String sobrenome) {
this.sobrenome = sobrenome;
}
public String getTelefone() {
return this.telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
public LocalDate getDataDeNascimento() {
return this.dataDeNascimento;
}
public void setDataDeNascimento(LocalDate dataDeNascimento) {
this.dataDeNascimento = dataDeNascimento;
}
public long getCpf() {
return this.cpf;
}
public void setCpf(long cpf) {
this.cpf = cpf;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getEndereco() {
return this.endereco;
}
public void setEndereco(String endereco) {
this.endereco = endereco;
}
}
| 18.94382 | 136 | 0.689798 |
06171dc48a32c8793e36663a682cc8c84e04f6b3 | 4,237 | package com.socatel.models;
import com.socatel.models.relationships.UserFeedbackVote;
import com.socatel.utils.enums.ByOrgEnum;
import com.socatel.utils.enums.VisibleEnum;
import com.socatel.utils.enums.VoteTypeEnum;
import javax.persistence.*;
import java.sql.Timestamp;
import java.util.Set;
@Entity
@Table(name = "so_feedback")
public class Feedback {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "feedback_id")
private int id;
@Column(name = "feedback_title")
private String title;
@Column(name = "feedback_description")
private String description;
@Column(name = "feedback_question")
private String question;
@Column(name = "feedback_visible")
@Enumerated(EnumType.ORDINAL)
private VisibleEnum visible;
@Column(name = "feedback_timestamp")
private Timestamp timestamp;
@Column(name = "feedback_by_org")
@Enumerated(EnumType.ORDINAL)
private ByOrgEnum byOrg;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "group_id")
private Group group;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "post_id")
private Post post;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "user_id")
private User user;
@OneToMany(mappedBy = "feedback", fetch = FetchType.LAZY)
private Set<UserFeedbackVote> usersLikes;
public Feedback() {
}
public Feedback(String title, String description, String question, ByOrgEnum byOrg, Group group, Post post, User user) {
this.title = title;
this.description = description;
this.question = question;
this.byOrg = byOrg;
this.group = group;
this.post = post;
this.user = user;
}
public boolean isByOrg() {
return byOrg.equals(ByOrgEnum.BY_ORG);
}
public boolean hasUpVoted(String username) {
if (usersLikes != null)
for (UserFeedbackVote vote : usersLikes)
if (vote.getVoteType().equals(VoteTypeEnum.UP_VOTED) && vote.getUser().getUsername().equals(username))
return true;
return false;
}
public boolean hasDownVoted(String username) {
if (usersLikes != null)
for (UserFeedbackVote vote : usersLikes)
if (vote.getVoteType().equals(VoteTypeEnum.DOWN_VOTED) && vote.getUser().getUsername().equals(username))
return true;
return false;
}
public boolean isVisible() {
return visible.equals(VisibleEnum.VISIBLE);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public VisibleEnum getVisible() {
return visible;
}
public void setVisible(VisibleEnum visible) {
this.visible = visible;
}
public ByOrgEnum getByOrg() {
return byOrg;
}
public void setByOrg(ByOrgEnum byOrg) {
this.byOrg = byOrg;
}
public Group getGroup() {
return group;
}
public void setGroup(Group group) {
this.group = group;
}
public Post getPost() {
return post;
}
public void setPost(Post post) {
this.post = post;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Timestamp getTimestamp() {
return timestamp;
}
public void setTimestamp(Timestamp timestamp) {
this.timestamp = timestamp;
}
public Set<UserFeedbackVote> getUsersLikes() {
return usersLikes;
}
public void setUsersLikes(Set<UserFeedbackVote> usersLikes) {
this.usersLikes = usersLikes;
}
}
| 23.28022 | 124 | 0.629691 |
b084f03c088b2d6d97fabb31b93b20a367546106 | 3,649 | /*
* 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 BD;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class BD {
String driver, url, login, password;
Connection conexion = null;
public BD() {
driver = "com.mysql.jdbc.Driver";
url = "jdbc:mysql://j21q532mu148i8ms.cbetxkdyhwsb.us-east-1.rds.amazonaws.com:3306/m6fl4gi1gtab1m7l";
login = "w4f1agseuwgbanl3";
password = "t1tpfcm1640win1k";
try {
Class.forName(driver).newInstance();
conexion = DriverManager.getConnection(url, login, password);
System.out.println("Conexion con Base de datos Ok....");
} catch (ClassNotFoundException | IllegalAccessException | InstantiationException | SQLException exc) {
System.out.println("Error al tratar de abrir la base de datos");
System.out.println(exc.getMessage());
}
}
// guardar registros en BD
public void AgregarInfo(int id,String nombre, String cedula, String placa) {
String estado = "1";
// String ComandoSQL = "INSERT INTO listado(nombre,cedula,placa,estado) VALUES ('" + nombre + "' , '" + cedula + "' ,'" + placa + "','" + estado + "' )";
String ComandoSQL = "CALL listadoAddOrEdit('"+id+"','" + nombre + "' , '" + cedula + "' ,'" + placa + "','" + estado + "' )";
try {
Statement stmt = conexion.createStatement();
stmt.executeUpdate(ComandoSQL);
System.out.println("Registro agregado!");
stmt.close();
} catch (java.sql.SQLException er) {
System.out.println("No se pudo realizar la operación.");
}
}
// traer lista de registros desde BD
public ArrayList<Registro> ListarRegistros() {
String id, nombre, cedula, placa, estado, fechaE, fechaS;
String ComandoSQL = "SELECT * FROM listado";
ArrayList<Registro> cts = new ArrayList<>();
try {
Statement stmt = conexion.createStatement();
ResultSet resultado = stmt.executeQuery(ComandoSQL);
while (resultado.next()) {
id = resultado.getString(5);
nombre = resultado.getString(1);
cedula = resultado.getString(2);
placa = resultado.getString(3);
estado = resultado.getString(4);
fechaE = resultado.getString(6);
fechaS = resultado.getString(7);
cts.add(new Registro(id, nombre, cedula, placa, estado, fechaE, fechaS));
}
stmt.close();
} catch (java.sql.SQLException er) {
System.out.println("No se pudo realizar la operación.");
}
return cts;
}
public void AgregarSalida(String id) {
System.out.println("dentro;"+id);
String ComandoSQL = "UPDATE `listado` SET `estado`=0 WHERE id="+id;
System.out.println("okis");
try {
Statement stmt = conexion.createStatement();
stmt.executeUpdate(ComandoSQL);
System.out.println("Salida registrada");
stmt.close();
} catch (java.sql.SQLException er) {
System.out.println("No se pudo realizar la operación.");
System.out.println(er.getMessage());
}
}
}
| 34.424528 | 161 | 0.595232 |
3cbace989f4f3976629e43ca93dd87427c29b626 | 2,591 | // package tutorial_1_server.testing;
package com.mycompany.app;
import com.google.guiceberry.GuiceBerryEnvMain;
import com.google.guiceberry.GuiceBerryModule;
import com.google.guiceberry.TestId;
import com.google.guiceberry.TestScoped;
import com.google.guiceberry.controllable.IcMaster;
import com.google.guiceberry.controllable.StaticMapInjectionController;
import com.google.guiceberry.controllable.TestIdServerModule;
import com.google.inject.AbstractModule;
import com.google.inject.Inject;
import com.google.inject.Key;
import com.google.inject.Module;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
// import tutorial_1_server.prod.PetStoreServer;
// import tutorial_1_server.prod.Pet;
// import tutorial_1_server.prod.Featured;
import com.mycompany.app.PetStoreServer;
import com.mycompany.app.Pet;
import com.mycompany.app.Featured;
public final class PetStoreEnv4InjectionController extends AbstractModule {
@Provides @Singleton
@PortNumber int getPortNumber() {
return FreePortFinder.findFreePort();
}
@Provides @TestScoped
WebDriver getWebDriver(@PortNumber int portNumber, TestId testId) {
WebDriver driver = new HtmlUnitDriver();
driver.get("http://localhost:" + portNumber);
driver.manage().addCookie(new Cookie(TestId.COOKIE_NAME, testId.toString()));
return driver;
}
@Provides
@Singleton
PetStoreServer buildPetStoreServer(@PortNumber int portNumber) {
PetStoreServer result = new PetStoreServer(portNumber) {
@Override
protected Module getPetStoreModule() {
// !!! HERE !!!
return icMaster.buildServerModule(
new TestIdServerModule(),
super.getPetStoreModule());
}
};
return result;
}
private IcMaster icMaster;
@Override
protected void configure() {
install(new GuiceBerryModule());
bind(GuiceBerryEnvMain.class).to(PetStoreServerStarter.class);
// !!!! HERE !!!!
icMaster = new IcMaster()
.thatControls(StaticMapInjectionController.strategy(),
Key.get(Pet.class, Featured.class));
install(icMaster.buildClientModule());
}
private static final class PetStoreServerStarter implements GuiceBerryEnvMain {
@Inject
private PetStoreServer petStoreServer;
public void run() {
// Starting a server should never be done in a @Provides method
// (or inside Provider's get).
petStoreServer.start();
}
}
}
| 30.482353 | 81 | 0.740641 |
f7a3fddd08433c0a620cbb9f20c88b519b41aada | 4,360 | /**
*
*/
package com.legrig.jenkinsci.plugins.GitBranchJobGenerator;
import hudson.Extension;
import hudson.model.AbstractDescribableImpl;
import hudson.model.Descriptor;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import jenkins.model.Jenkins;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.export.ExportedBean;
/**
* @author mlasevich
*
*/
@ExportedBean
public class BranchRule extends AbstractDescribableImpl<BranchRule> implements Serializable {
/**
*
*/
private static final long serialVersionUID = 5642698046334746381L;
private List<BranchMatchPattern> matchPatterns;
private String branchType;
private boolean create;
private String templateProject;
private String projectName;
private String projectDisplayName;
private String projectDescription;
private boolean enableOnCreate;
private boolean disableOnDelete;
private boolean runOnCreate;
private boolean injectEnvVariables;
/**
*
*/
@DataBoundConstructor
public BranchRule(
List<BranchMatchPattern> matchPatterns,
boolean create,
String branchType,
String templateProject,
String projectName, String projectDisplayName,
String projectDescription,
boolean enableOnCreate,
boolean disableOnDelete,
boolean runOnCreate,
boolean injectEnvVariables) {
this.create=create;
this.matchPatterns=matchPatterns;
this.branchType=branchType;
this.templateProject=templateProject;
this.projectName=projectName;
this.projectDisplayName=projectDisplayName;
this.projectDescription=projectDescription;
this.enableOnCreate=enableOnCreate;
this.disableOnDelete=disableOnDelete;
this.runOnCreate=runOnCreate;
this.injectEnvVariables=injectEnvVariables;
}
public List<BranchMatchPattern> getMatchPatterns() {
return matchPatterns;
}
public void setMatchPatterns(List<BranchMatchPattern> matchPatterns) {
this.matchPatterns = matchPatterns;
}
public String getBranchType() {
return branchType;
}
public void setBranchType(String branchType) {
this.branchType = branchType;
}
public boolean isCreate() {
return create;
}
public boolean getCreate() {
return create;
}
public void setCreate(boolean create) {
this.create = create;
}
public boolean isEnableOnCreate() {
return enableOnCreate;
}
public boolean getEnableOnCreate() {
return enableOnCreate;
}
public void setEnableOnCreate(boolean enableOnCreate) {
this.enableOnCreate = enableOnCreate;
}
public boolean isDisableOnDelete() {
return disableOnDelete;
}
public boolean getDisableOnDelete() {
return disableOnDelete;
}
public void setDisableOnDelete(boolean disableOnDelete) {
this.disableOnDelete = disableOnDelete;
}
public String getTemplateProject() {
return templateProject;
}
public void setTemplateProject(String templateProject) {
this.templateProject = templateProject;
}
public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public String getProjectDisplayName() {
return projectDisplayName;
}
public void setProjectDisplayName(String projectDisplayName) {
this.projectDisplayName = projectDisplayName;
}
public String getProjectDescription() {
return projectDescription;
}
public void setProjectDescription(String projectDescription) {
this.projectDescription = projectDescription;
}
public boolean isRunOnCreate() {
return runOnCreate;
}
public boolean getRunOnCreate() {
return runOnCreate;
}
public void setRunOnCreate(boolean runOnCreate) {
this.runOnCreate = runOnCreate;
}
public boolean isInjectEnvVariables() {
return injectEnvVariables;
}
public boolean getInjectEnvVariables() {
return injectEnvVariables;
}
public void setInjectEnvVariables(boolean injectEnvVariables) {
this.injectEnvVariables = injectEnvVariables;
}
@Extension
public static class DescriptorImpl extends Descriptor<BranchRule> {
@Override
public String getDisplayName() {
return "Branch Rule";
}
public Set<String> getTemplateProjects(){
GitBranchJobGeneratorBuilder.DescriptorImpl descriptor = Jenkins.getInstance().getDescriptorByType(GitBranchJobGeneratorBuilder.DescriptorImpl.class);
return descriptor.getTemplateProjects();
}
}
}
| 22.244898 | 153 | 0.775 |
7fa6b8f111055a8e39dc24304b06425a42236119 | 1,374 | package com.readlearncode.mapping._default.javatypes;
import org.junit.Test;
import javax.json.bind.JsonbBuilder;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import static org.assertj.core.api.Java6Assertions.assertThat;
/**
* Source code github.com/readlearncode
*
* @author Alex Theedom www.readlearncode.com
* @version 1.0
*/
public class JavaTypesTest {
@Test
public void givenJavaTypes_shouldSerialise() throws MalformedURLException, URISyntaxException {
/*
{
"atomicInteger": 10,
"bigDecimal": 10,
"bigInteger": 10,
"longAdder": 0,
"optionalDouble": 10,
"optionalInt": 10,
"optionalLong": 10,
"stringOptional": "Hello World",
"uri": "http://www.readlearncode.com",
"url": "http://www.readlearncode.com"
}
*/
String expectedJson = "{\"atomicInteger\":10,\"bigDecimal\":10,\"bigInteger\":10,\"longAdder\":0,\"optionalDouble\":10.0,\"optionalInt\":10,\"optionalLong\":10,\"stringOptional\":\"Hello World\",\"uri\":\"http://www.readlearncode.com\",\"url\":\"http://www.readlearncode.com\"}";
String actualJson = JsonbBuilder.create().toJson(new JavaTypes());
assertThat(actualJson).isEqualTo(expectedJson);
}
} | 31.953488 | 287 | 0.620815 |
e4962c4cb1c7143af4650d10cdafd141938b93d3 | 4,562 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.sql.planner.optimizations;
import com.facebook.presto.matching.Captures;
import com.facebook.presto.matching.Pattern;
import com.facebook.presto.metadata.Metadata;
import com.facebook.presto.spi.relation.RowExpression;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.sql.parser.SqlParser;
import com.facebook.presto.sql.planner.Symbol;
import com.facebook.presto.sql.planner.iterative.Rule;
import com.facebook.presto.sql.planner.iterative.Rule.Context;
import com.facebook.presto.sql.planner.plan.ValuesNode;
import com.facebook.presto.sql.relational.SqlToRowExpressionTranslator;
import com.facebook.presto.sql.tree.Expression;
import com.facebook.presto.sql.tree.NodeRef;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static com.facebook.presto.execution.warnings.WarningCollector.NOOP;
import static com.facebook.presto.sql.analyzer.ExpressionAnalyzer.getExpressionTypes;
import static com.facebook.presto.sql.planner.plan.Patterns.values;
import static com.facebook.presto.sql.relational.OriginalExpressionUtils.castToExpression;
import static com.facebook.presto.sql.relational.OriginalExpressionUtils.isExpression;
import static java.util.Objects.requireNonNull;
public class TranslateExpressions
{
private final Metadata metadata;
private final SqlParser sqlParser;
public TranslateExpressions(Metadata metadata, SqlParser sqlParser)
{
this.metadata = requireNonNull(metadata, "metadata is null");
this.sqlParser = requireNonNull(sqlParser, "sqlParseris null");
}
public Set<Rule<?>> rules()
{
// TODO: finish all other PlanNodes that have Expression
return ImmutableSet.of(
new ValuesExpressionTranslation());
}
private final class ValuesExpressionTranslation
implements Rule<ValuesNode>
{
@Override
public Pattern<ValuesNode> getPattern()
{
return values();
}
@Override
public Result apply(ValuesNode valuesNode, Captures captures, Context context)
{
boolean anyRewritten = false;
ImmutableList.Builder<List<RowExpression>> rows = ImmutableList.builder();
for (List<RowExpression> row : valuesNode.getRows()) {
ImmutableList.Builder<RowExpression> newRow = ImmutableList.builder();
for (RowExpression rowExpression : row) {
if (isExpression(rowExpression)) {
Expression expression = castToExpression(rowExpression);
RowExpression rewritten = toRowExpression(expression, context, ImmutableMap.of());
anyRewritten = true;
newRow.add(rewritten);
}
else {
newRow.add(rowExpression);
}
}
rows.add(newRow.build());
}
if (anyRewritten) {
return Result.ofPlanNode(new ValuesNode(valuesNode.getId(), valuesNode.getOutputSymbols(), rows.build()));
}
return Result.empty();
}
}
private RowExpression toRowExpression(Expression expression, Context context, Map<Symbol, Integer> sourceLayout)
{
Map<NodeRef<Expression>, Type> types = getExpressionTypes(
context.getSession(),
metadata,
sqlParser,
context.getSymbolAllocator().getTypes(),
ImmutableList.of(expression),
ImmutableList.of(),
NOOP,
false);
return SqlToRowExpressionTranslator.translate(expression, types, sourceLayout, metadata.getFunctionManager(), metadata.getTypeManager(), context.getSession(), false);
}
}
| 40.017544 | 174 | 0.681499 |
71a0249834001c9c18c5444d54fac5a491567e32 | 4,322 | package org.javaswift.joss.command.impl.container;
import mockit.Verifications;
import org.apache.http.client.methods.HttpRequestBase;
import org.javaswift.joss.command.impl.core.BaseCommandTest;
import org.javaswift.joss.exception.CommandException;
import org.javaswift.joss.exception.NotFoundException;
import org.javaswift.joss.instructions.ListInstructions;
import org.javaswift.joss.model.StoredObject;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;
public class ListObjectsCommandImplTest extends BaseCommandTest {
public static final ListInstructions listInstructions = new ListInstructions()
.setMarker(null)
.setLimit(10);
@Before
public void setup() throws IOException {
super.setup();
}
@Test
public void listObjects() throws IOException {
new ListObjectsCommandImpl(this.account, httpClient, defaultAccess, account.getContainer("containername"), listInstructions).call();
}
@Test
public void listObjectsWithNoneThere() throws IOException {
expectStatusCode(204);
new ListObjectsCommandImpl(this.account, httpClient, defaultAccess, account.getContainer("containername"), listInstructions).call();
}
@Test (expected = NotFoundException.class)
public void containerDoesNotExist() throws IOException {
checkForError(404, new ListObjectsCommandImpl(this.account, httpClient, defaultAccess, account.getContainer("containername"), listInstructions));
}
@Test (expected = CommandException.class)
public void unknownError() throws IOException {
checkForError(500, new ListObjectsCommandImpl(this.account, httpClient, defaultAccess, account.getContainer("containername"), listInstructions));
}
@Test
public void isSecure() throws IOException {
isSecure(new ListObjectsCommandImpl(this.account, httpClient, defaultAccess, account.getContainer("containername"), listInstructions));
}
@Test
public void queryParameters() throws IOException {
expectStatusCode(204);
new ListObjectsCommandImpl(this.account, httpClient, defaultAccess, account.getContainer("containerName"),
new ListInstructions().setMarker("dogs").setLimit(10)).call();
new Verifications() {{
List<HttpRequestBase> requests = new ArrayList<HttpRequestBase>();
httpClient.execute(withCapture(requests));
for (HttpRequestBase request : requests) {
String assertQueryParameters = "?marker=dogs&limit=10";
String uri = request.getURI().toString();
assertTrue(uri+" must contain "+assertQueryParameters, uri.contains(assertQueryParameters));
}
}};
}
@Test
public void setHeaderValues() throws IOException {
loadSampleJson("/sample-object-list.json");
expectStatusCode(204);
Collection<StoredObject> objects =
new ListObjectsCommandImpl(this.account, httpClient, defaultAccess, account.getContainer("containerName"), listInstructions).call();
assertEquals(4, objects.size());
StoredObject object = objects.iterator().next();
assertEquals("image/jpeg", object.getContentType());
assertEquals("c8fc5698c0b3ca145f2c98937cbd9ff2", object.getEtag());
assertTrue(object.getLastModified().contains("Wed, 05 Dec 2012"));
assertEquals(22979, object.getContentLength());
}
@Test
public void checkThatHeaderFieldsDoNotCostAnExtraCall() throws IOException {
loadSampleJson("/sample-object-list.json");
expectStatusCode(204);
Collection<StoredObject> objects =
new ListObjectsCommandImpl(this.account, httpClient, defaultAccess, account.getContainer("containerName"), listInstructions).call();
assertEquals(1, account.getNumberOfCalls());
StoredObject object = objects.iterator().next();
object.getContentType();
object.getContentLength();
object.getEtag();
object.getLastModified();
assertEquals(1, account.getNumberOfCalls());
}
}
| 41.557692 | 153 | 0.713327 |
24d6d73a3df1fa0fdca242ebbbb697a22a8efdf1 | 1,449 | /*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.picasso;
import android.graphics.Bitmap;
/**
* Represents an arbitrary listener for image loading.
* <p/>
* Objects implementing this class <strong>must</strong> have a working implementation of
* {@link #equals(Object)} and {@link #hashCode()} for proper storage internally. Instances of this
* interface will also be compared to determine if view recycling is occurring. It is recommended
* that you add this interface directly on to a custom view type when using in an adapter to ensure
* correct recycling behavior.
*/
public interface Target {
/**
* Callback when an image has been successfully loaded.
* <p/>
* <strong>Note:</strong> You must not recycle the bitmap.
*/
void onSuccess(Bitmap bitmap);
/** Callback indicating the image could not be successfully loaded. */
void onError();
}
| 36.225 | 99 | 0.730849 |
52e0d5925a0c371197c3e51ebe9712d18f988d56 | 1,416 | package com.groupname.game.entities.enemies;
import com.groupname.framework.io.Content;
import com.groupname.framework.math.Vector2D;
import com.groupname.game.entities.EnemySpriteType;
import com.groupname.game.entities.SpriteFactory;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
public class GuardEnemyTests {
@BeforeClass
public static void init() {
Content.setContentBaseFolder("/com/groupname/game/resources");
}
@Test(expected = NullPointerException.class)
public void constructorParameterCannotMeNull() {
new GuardEnemy(null, null);
}
@Test(expected = NullPointerException.class)
public void positionCannotBeNull() {
new GuardEnemy(new SpriteFactory().createEnemy(EnemySpriteType.BEE), new Vector2D(2,2)).setPosition(null);
}
@Test
public void setPositionWorks() {
GuardEnemy enemy = new GuardEnemy(new SpriteFactory().createEnemy(EnemySpriteType.BEE), new Vector2D(3,3));
enemy.setPosition(new Vector2D(1,2));
assertEquals((int)enemy.getPosition().getX(), (int)1);
assertEquals((int)enemy.getPosition().getY(), (int)2);
}
@Test(expected = NullPointerException.class)
public void drawNotNull() {
GuardEnemy enemy = new GuardEnemy(new SpriteFactory().createEnemy(EnemySpriteType.BEE), new Vector2D(3,3));
enemy.draw(null);
}
}
| 32.181818 | 115 | 0.714689 |
e53c0672e483fd9db665dcab4be151791eadb0d3 | 2,386 | // faster alternative to Matlab ppval
// @author Michael Kaess
package drake.systems.trajectories;
public class JavaPP {
double[] m_breaks;
double[][] m_coefs;
int m_order;
int m_dim1;
int m_dim2;
int m_cached_idx;
public JavaPP(double[] breaks, double[][] coefs, int order, int[] dims) {
m_breaks = breaks.clone();
m_coefs = new double[coefs.length][];
for (int i=0; i<coefs.length; i++) {
m_coefs[i] = coefs[i].clone();
}
m_order = order;
// dims can have one or two entries
m_dim1 = dims[0];
if (dims.length > 1)
m_dim2 = dims[1];
else
m_dim2 = 1;
m_cached_idx = -1;
}
// evaluate the PP at locate t
// to be optimized for multiple access to same PP, with temporal coherence
public double[][] eval(double t) {
double[][] r = new double[m_dim1][m_dim2];
// use cached index if possible
int idx;
if (m_cached_idx >= 0 && m_cached_idx < m_breaks.length // valid m_cached_idx?
&& t < m_breaks[m_cached_idx+1] // still in same interval?
&& ((m_cached_idx == 0 ) || (t >= m_breaks[m_cached_idx]))) { // left up to -infinity
idx = m_cached_idx;
} else {
// search for the correct interval
idx = java.util.Arrays.binarySearch(m_breaks, t);
if (idx==m_breaks.length) idx=m_breaks.length-1; // the last break does not matter
if (idx<0) idx = -idx-1;
idx = idx -1;
if (idx<0) idx=0;
// handle degenerate case of duplicate breaks consistently with Matlab
while (m_breaks[idx]==m_breaks[idx+1] && idx<m_breaks.length-2) idx++;
m_cached_idx = idx;
}
int base = idx*m_dim1*m_dim2;
for (int l=0; l<m_dim2; l++) {
for (int k=0; k<m_dim1; k++) {
r[k][l] = m_coefs[base+k+l*m_dim1][0];
}
}
double local = t - m_breaks[idx];
for (int i=2; i<=m_order; i++) {
for (int l=0; l<m_dim2; l++) {
for (int k=0; k<m_dim1; k++) {
r[k][l] = local*r[k][l] + m_coefs[base+k+l*m_dim1][i-1];
}
}
}
return r;
}
public void shiftTime(double offset) {
for (int i=0; i<m_breaks.length; i++) {
m_breaks[i] = m_breaks[i] + offset;
}
}
public void uminus() {
for(int i=0; i<m_order; i++) {
for (int j=0; j<m_dim1*m_dim2*(m_breaks.length-1); j++) {
m_coefs[j][i] = -m_coefs[j][i];
}
}
}
}
| 27.425287 | 93 | 0.571668 |
bfa26710294ae48f250ecaf929cd26799f328855 | 841 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package erp.mtrn.data;
/**
*
* @author Sergio Flores
*/
public class SDataDpsEntryCommissionsRow extends erp.lib.table.STableRow {
public SDataDpsEntryCommissionsRow(java.lang.Object data) {
moData = data;
prepareTableRow();
}
@Override
public void prepareTableRow() {
SDataDpsEntryCommissions commissions = (SDataDpsEntryCommissions) moData;
mvValues.clear();
mvValues.add(commissions.getPercentage());
mvValues.add(commissions.getValueUnitary());
mvValues.add(commissions.getValue());
mvValues.add(commissions.getCommissions());
mvValues.add(commissions.getCommissionsCy());
mvValues.add(commissions.getDbmsCommissionsType());
}
}
| 26.28125 | 81 | 0.686088 |
00ce9fb3dacc71cd95fbdf6cbd75502a60b05065 | 229 | package com.travel.dao;
import com.travel.domain.Seller;
/**
* @author Summerday
*/
public interface SellerDao {
/**
* 根据route的sid找到seller信息
* @param sid
* @return
*/
Seller findBySid(int sid);
}
| 13.470588 | 32 | 0.615721 |
ca750b4b31436f50fe6eeab63fe47623a7368649 | 764 | import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.Scanner;
public class ObjectMapperTest {
public static void main(final String... args) throws IOException {
ObjectMapper obm = new ObjectMapper();
Scanner sc = new Scanner(System.in);
Player player = new Player(sc.nextInt(), sc.next());
String responseBody = "";
try {
responseBody = obm.writeValueAsString(player);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
System.out.println(responseBody);
player = obm.readValue(responseBody, Player.class);
System.out.println(player);
}
} | 34.727273 | 70 | 0.66623 |
75ea361480c68e4546c3fb31e076568642d97447 | 14,352 | package st.domain.ggviario.secret.fragments;
import android.app.FragmentManager;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import st.domain.ggviario.secret.R;
import st.domain.ggviario.secret.dao.CreditsDao;
import st.domain.ggviario.secret.items.CreditCreateNewItemViewHolder;
import st.domain.ggviario.secret.items.CreditRegisterItemViewHolder;
import st.domain.ggviario.secret.model.Client;
import st.domain.ggviario.secret.model.CreditProduct;
import st.zudamue.support.android.adapter.ItemDataSet;
import st.zudamue.support.android.adapter.ItemViewHolder;
import st.zudamue.support.android.adapter.RecyclerViewAdapter;
import st.zudamue.support.android.fragment.BaseFragment;
import st.zudamue.support.android.fragment.CallbackFragmentManager;
import st.zudamue.support.android.fragment.DatePickerDialogSupport;
import st.zudamue.support.android.util.DateUtil;
/**
*
* Created by dchost on 15/02/17.
*/
public class CreditRegisterFragment extends BaseFragment {
private Context context;
private RecyclerViewAdapter adapter;
private float finalValueTotal;
private TextView tvCreditValueFinal;
private NumberFormat numberFormatter;
private DateFormat dateFormatter;
private Client client;
private Date dateFinisher;
private boolean dateChanged;
private CallbackFragmentManager.FragmentCallback done;
private TextView tvCreditDateFinisher;
private Calendar creditCalendar;
@Override
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
}
public CreditRegisterFragment setDone(CallbackFragmentManager.FragmentCallback done){
this.done = done;
return this;
}
@Override
public void onSaveInstanceState(Bundle out) {
super.onSaveInstanceState(out);
out.putLong( "credit-date", this.dateFinisher.getTime() );
out.putBoolean( "credit-date-change", this.dateChanged );
out.putParcelable( "client", this.client );
out.putFloat( "credit-value-total", this.finalValueTotal );
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout._credit_newcredit, container, false);
this.dateFormatter = new SimpleDateFormat( "dd 'de' MMMMM 'de' yyyy");
this.numberFormatter = NumberFormat.getCurrencyInstance( Locale.FRANCE );
this.numberFormatter.setMaximumFractionDigits( 2 );
this.numberFormatter.setMinimumFractionDigits( 2 );
this.numberFormatter.setMinimumIntegerDigits( 1 );
this.creditCalendar = Calendar.getInstance();
//date of credit
Bundle arguments = savedInstanceState;
//on init
if( arguments == null ) {
arguments = getArguments();
// Add more one month in the date finhisher
creditCalendar.add( Calendar.MONTH, 1 );
this.dateFinisher = creditCalendar.getTime();
this.dateChanged = false;
this.client = arguments.getParcelable( "client" );
this.finalValueTotal = 0.0f;
} else {
this.dateFinisher = new Date( arguments.getLong( "credit-date" ) );
this.dateChanged = arguments.getBoolean( "credit-date-change" );
this.client = arguments.getParcelable( "client" );
this.finalValueTotal = arguments.getFloat( "credit-value-total" );
this.creditCalendar.setTime( this.dateFinisher );
}
//credit value
this.tvCreditValueFinal = ( TextView) rootView.findViewById( R.id.tv_credit_value_final);
this.tvCreditValueFinal.setText( this.numberFormatter.format( this.finalValueTotal ) );
//credit date
this.tvCreditDateFinisher = ( TextView ) rootView.findViewById( R.id.tv_credit_date );
if( ! this.dateChanged )
this.tvCreditDateFinisher.setText( this.dateFormatter.format( dateFinisher ).concat( "(1 mês)" ) );
else
this.tvCreditDateFinisher.setText( this.dateFormatter.format( dateFinisher ) );
//change date
rootView.findViewById( R.id.bt_credit_change_date ).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openModalChangeDate();
}
});
//Prepare botom sheet
// View bottomSheet = rootView.findViewById(R.id.ll_bottom_sheet);
// BottomSheetBehavior behavior = BottomSheetBehavior.from(bottomSheet);
// behavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
// @Override
// public void onStateChanged(@NonNull View bottomSheet, int newState) {}
// @Override
// public void onSlide(@NonNull View bottomSheet, float slideOffset) {}
// });
//Prepare recycler vew item
RecyclerView recyclerView = (RecyclerView) rootView.findViewById(R.id.rv);
this.adapter = new RecyclerViewAdapter( this.context );
StaggeredGridLayoutManager sgl = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL );
recyclerView.setLayoutManager( sgl );
recyclerView.setAdapter( this.adapter );
this.populateData( );
return rootView;
}
private void openModalChangeDate() {
DatePickerDialog datePickerDialog = DatePickerDialog.newInstance(
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
creditCalendar.set( year, monthOfYear, dayOfMonth );
dateFinisher = creditCalendar.getTime();
dateChanged = true;
tvCreditDateFinisher.setText( dateFormatter.format( dateFinisher ) );
}
},
creditCalendar.get( Calendar.YEAR ),
creditCalendar.get( Calendar.MONTH ),
creditCalendar.get( Calendar.DAY_OF_MONTH )
);
final Date currentDate = Calendar.getInstance().getTime();
final Calendar calendar = Calendar.getInstance();
datePickerDialog.setMinDate( Calendar.getInstance() );
// datePickerDialog.setOnCheckSelection(new DatePickerDialogSupport.OnCheckSelection() {
// @Override
// public boolean isSelectable(int year, int month, int day) {
//// calendar.set( year, month, day );
//// Date date = calendar.getTime();
//// DateUtil dateUtil = new DateUtil( date );
//// return currentDate.before( date )
//// || dateUtil.isToday();
// return true;
// }
// });
// datePickerDialog.setSelectableDays(selectableDays);
datePickerDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
}
});
FragmentManager fragmanager = this.getActivity().getFragmentManager();
datePickerDialog.show( fragmanager, "credit-date-picker" );
}
/**
* Populate the data setItem using the addItem product date setItem
* this is dynamic populate
*/
private void populateData() {
final CallbackFragmentManager.FragmentCallback addCreditItemCallback = new CallbackFragmentManager.FragmentCallback() {
@Override
public void onCallback(Fragment fragment, Map<String, Object> objectsParam, Bundle extraParam, Map<String, Object> pushMap) {
CreditRegisterItemViewHolder.CreditProductItemDataSet item = ( CreditRegisterItemViewHolder.CreditProductItemDataSet ) objectsParam.get( "item" );
adapter.addItem( adapter.getItemCount() - 1, item );
finalValueTotal = finalValueTotal + item.getPriceQuantity();
tvCreditValueFinal.setText( numberFormatter.format( finalValueTotal ) );
}
};
final ItemViewHolder.ItemCallback onClickOperationAddItem = new ItemViewHolder.ItemCallback() {
@Override
public void onCallback( ItemViewHolder itemViewHolder, View view, ItemDataSet itemDataSet, int adapterPosition ) {
CreditRegisterBottomSheetFragment dialogTestFragment = new CreditRegisterBottomSheetFragment();
Bundle params = new Bundle();
params.putFloat( "old_price_quantity", 0.0f );
dialogTestFragment.setArguments( params );
dialogTestFragment.setActionCallback( addCreditItemCallback );
dialogTestFragment.show( getFragmentManager(), CreditRegisterBottomSheetFragment.class.getName() );
}
};
final ItemViewHolder.ItemCallback removeCallback = new ItemViewHolder.ItemCallback() {
@Override
public void onCallback(ItemViewHolder itemViewHolder, View view, ItemDataSet itemDataSet, int adapterPosition) {
CreditRegisterItemViewHolder.CreditProductItemDataSet creditItemDataSet = (CreditRegisterItemViewHolder.CreditProductItemDataSet) itemDataSet;
adapter.removeItem( adapterPosition );
finalValueTotal = finalValueTotal - creditItemDataSet.getOldPriceQuantity();
tvCreditValueFinal.setText( numberFormatter.format( finalValueTotal ) );
}
};
final ItemViewHolder.ItemCallback editCallback = new ItemViewHolder.ItemCallback() {
@Override
public void onCallback(ItemViewHolder itemViewHolder, View view, ItemDataSet itemDataSet, final int adapterPosition ) {
final CreditRegisterItemViewHolder.CreditProductItemDataSet item = (CreditRegisterItemViewHolder.CreditProductItemDataSet) itemDataSet;
CreditRegisterBottomSheetFragment dialogTestFragment = new CreditRegisterBottomSheetFragment();
Bundle params = new Bundle();
params.putParcelable( "item", item );
dialogTestFragment.setArguments( params );
dialogTestFragment.setActionCallback( new CallbackFragmentManager.FragmentCallback() {
@Override
public void onCallback(Fragment fragment, Map<String, Object> objectsParam, Bundle extraParam, Map<String, Object> pushMap) {
adapter.setItem( adapterPosition, (ItemDataSet) objectsParam.get( "item" ));
finalValueTotal = finalValueTotal + item.getPriceQuantity() - item.getOldPriceQuantity();
tvCreditValueFinal.setText( numberFormatter.format( finalValueTotal ) );
}
});
dialogTestFragment.show( getFragmentManager(), CreditRegisterBottomSheetFragment.class.getName() );
}
};
this.adapter.registerFactory(R.layout.credits_operaction_add, new RecyclerViewAdapter.ViewHolderFactory() {
@Override
public ItemViewHolder factory( View view ) {
CreditCreateNewItemViewHolder addCreditsProduct = new CreditCreateNewItemViewHolder( view );
addCreditsProduct.addProductCallback( onClickOperationAddItem );
return addCreditsProduct;
}
});
/**
* Add the credit credit item factory
*/
this.adapter.registerFactory(R.layout._credit_newcredit_item, new RecyclerViewAdapter.ViewHolderFactory() {
@Override
public ItemViewHolder factory(View view) {
return new CreditRegisterItemViewHolder( view )
.editCallback( editCallback )
.removeCallback( removeCallback )
;
}
});
ItemDataSet add = new CreditCreateNewItemViewHolder.AddCreditProductItemDataSet();
this.adapter.addItem( add );
}
public boolean done() {
if ( this.adapter.getItemCount() < 2 ) {
Toast.makeText( this.context, "Nenhum item adicionado (Adicionar pelo menos um item)", Toast.LENGTH_LONG).show();
return false;
}
this.regCredits();
return true;
}
private void regCredits() {
CreditsDao creditsDao = new CreditsDao( this.context );
creditsDao.registerCredit( this.client, this.dateFinisher, this.finalValueTotal, this.createListCreditsProduct());
}
private List<CreditProduct> createListCreditsProduct() {
List<CreditProduct> list = new LinkedList<>();
for( ItemDataSet itemDataSet: this.adapter ) {
if( itemDataSet instanceof CreditRegisterItemViewHolder.CreditProductItemDataSet ){
CreditRegisterItemViewHolder.CreditProductItemDataSet dataSet = ( CreditRegisterItemViewHolder.CreditProductItemDataSet ) itemDataSet;
CreditProduct creditProduct = new CreditProduct(
null,
dataSet.getSelectedProduct(),
dataSet.getQuantity(),
dataSet.getProductPrice().getPrice(),
dataSet.getSelectedMeasure(),
dataSet.getProductPrice().calcPrice( dataSet.getQuantity() )
);
list.add( creditProduct );
}
}
this.callback( this.done );
return list;
}
}
| 42.587537 | 162 | 0.662138 |
f9f9275d0777ea3ea936fe8f277ced4a99720cda | 766 | package piece;
import java.awt.Color;
import game.FieldSquare;
public class PieceShapeO extends PieceShape {
private static final Color COLOR = Color.PINK;
private static final FieldSquare[][][] SHAPES = {
{
{ FieldSquare.PIECE, FieldSquare.PIECE, FieldSquare.EMPTY, FieldSquare.EMPTY },
{ FieldSquare.PIECE, FieldSquare.PIECE, FieldSquare.EMPTY, FieldSquare.EMPTY },
{ FieldSquare.EMPTY, FieldSquare.EMPTY, FieldSquare.EMPTY, FieldSquare.EMPTY },
{ FieldSquare.EMPTY, FieldSquare.EMPTY, FieldSquare.EMPTY, FieldSquare.EMPTY }
}
};
public PieceShapeO() {
super();
}
@Override
public Color getColor() {
return PieceShapeO.COLOR;
}
@Override
protected FieldSquare[][][] getShapes() {
return PieceShapeO.SHAPES;
}
}
| 24.709677 | 84 | 0.71671 |
4ef7e06c119af25ce43e5440dc9099ddaab16974 | 1,475 | package samebutdifferent.trickortreat.effect;
import net.minecraft.core.particles.ParticleTypes;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.util.Mth;
import net.minecraft.world.effect.MobEffect;
import net.minecraft.world.effect.MobEffectCategory;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.phys.Vec3;
public class BouncyEffect extends MobEffect {
public BouncyEffect() {
super(MobEffectCategory.BENEFICIAL, 3140701);
}
@Override
public void applyEffectTick(LivingEntity entity, int amplifier) {
if (entity.isOnGround()) {
Vec3 movement = entity.getDeltaMovement();
entity.setDeltaMovement(movement.x, 1.5D, movement.z);
entity.hasImpulse = true;
entity.playSound(SoundEvents.SLIME_JUMP, 1.0F, 1.0F);
for(int j = 0; j < 8; ++j) {
float f = entity.level.random.nextFloat() * ((float)Math.PI * 2F);
float f1 = entity.level.random.nextFloat() * 0.5F + 0.5F;
float f2 = Mth.sin(f) * 0.5F * f1;
float f3 = Mth.cos(f) * 0.5F * f1;
entity.level.addParticle(ParticleTypes.ITEM_SLIME, entity.getX() + (double)f2, entity.getY(), entity.getZ() + (double)f3, 0.0D, 0.0D, 0.0D);
}
}
entity.fallDistance = 0.0F;
}
@Override
public boolean isDurationEffectTick(int pDuration, int pAmplifier) {
return true;
}
}
| 37.820513 | 156 | 0.642034 |
8d62b205c418ba375cc189c6c6121d5c3b177afd | 948 | import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
public class AbusingMap {
int solution(int k, int[] score) {
Map<Integer, Integer> map = new HashMap<>();
Boolean[] check = new Boolean[score.length];
Arrays.fill(check, true);
for (int i = 0; i < score.length; i++) {
if (i == 0) continue;
int diff = score[i - 1] = score[i];
map.put(diff, map.get(diff) + 1);
}
Map<Integer, Integer> abusingMap = map.entrySet().stream()
.filter(entry -> entry.getKey() >= k)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
for (int i = 0; i < score.length; i++) {
if (i == 0) continue;
int diff = score[i - 1] = score[i];
if (abusingMap.containsKey(diff)) {
check[i - 1] = false;
check[i] = false;
}
}
return (int) Arrays.stream(check).filter(it -> it).count();
}
} | 27.882353 | 75 | 0.581224 |
0f83b857d003a6e16c4bafa4b640889434b67032 | 956 | package tests;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import complex_numbers.Complex;
import complex_numbers.StatusComplex;
class AdditionTests {
@Test
void verify_add_with_complex_parameter() {
Complex n1 = new Complex(1, -1); // n1 = 1 - i
Complex n2 = new Complex(1, 1); // n2 = 1 + i
Complex n3 = new Complex(2, 0); // n3 = 2
Complex n4 = new Complex(-10, -5);// n5 = -10 - 5i
Complex resultNumber;
resultNumber = Complex.add(n1, n2);
assertEquals(new Complex(2, StatusComplex.ONLY_REAL).toString(), resultNumber.toString());
resultNumber = Complex.add(n2,n3);
assertEquals(new Complex(3,1).toString(), resultNumber.toString());
resultNumber = Complex.add(n3, n4);
assertEquals(new Complex(-8,-5).toString(), resultNumber.toString());
resultNumber = Complex.add(n4 , n4);
assertEquals(new Complex(-20,-10).toString(), resultNumber.toString());
}
}
| 26.555556 | 92 | 0.687238 |
92da454ad7f46a68aecbe293d06cc82143e73cfe | 1,164 | package org.nakedobjects.examples;
import org.nakedobjects.metamodel.spec.NakedObjectSpecification;
import org.nakedobjects.metamodel.spec.feature.NakedObjectAssociation;
import org.nakedobjects.runtime.context.NakedObjectsContext;
public class SpecificationExamples {
public void testSpecificationDetails() {
// @extract one
NakedObjectSpecification spec;
spec = NakedObjectsContext.getSpecificationLoader().loadSpecification(Location.class);
String screenName = spec.getSingularName();
// @extract-end
System.out.println(screenName);
// @extract two
NakedObjectAssociation[] associations = spec.getAssociations();
for (int i = 0; i < associations.length; i++) {
String name = associations[i].getName();
boolean mustEnter = associations[i].isMandatory();
// @skip
// @skip-end
// @ignore
System.out.println(name + " " + mustEnter);
// @ignore-end
}
// @extract-end
}
}
// Copyright (c) Naked Objects Group Ltd.
| 31.459459 | 95 | 0.610825 |
c6a7f0783be64948ae1befd5c261f06e82671748 | 1,250 | package com.bumptech.glide.h;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
// compiled from: LruCache.java
public class e<T, Y> {
private int a;
public final LinkedHashMap<T, Y> b;
public int c;
private final int d;
public e(int i) {
this.b = new LinkedHashMap(100, 0.75f, true);
this.c = 0;
this.d = i;
this.a = i;
}
public int a(Y y) {
return 1;
}
public void a(T t, Y y) {
}
public final Y b(T t) {
return this.b.get(t);
}
public final Y b(T t, Y y) {
if (a(y) >= this.a) {
a(t, y);
return null;
}
Y put = this.b.put(t, y);
if (y != null) {
this.c += a(y);
}
if (put != null) {
this.c -= a(put);
}
b(this.a);
return put;
}
public final void a() {
b(0);
}
public final void b(int i) {
while (this.c > i) {
Entry entry = (Entry) this.b.entrySet().iterator().next();
Object value = entry.getValue();
this.c -= a(value);
Object key = entry.getKey();
this.b.remove(key);
a(key, value);
}
}
}
| 20.16129 | 70 | 0.4536 |
60eea3e6c87d7393ba08f24c0c7b7b1cf842804a | 4,034 | //
// "This sample program is provided AS IS and may be used, executed, copied and modified without royalty payment by customer (a) for its own
// instruction and study, (b) in order to develop applications designed to run with an IBM WebSphere product, either for customer's own internal use
// or for redistribution by customer, as part of such an application, in customer's own products. "
//
// (C) COPYRIGHT International Business Machines Corp., 2005
// All Rights Reserved * Licensed Materials - Property of IBM
//
package com.ibm.icap.tradelite;
import com.ibm.icap.tradelite.util.*;
public class AccountProfileDataBean
implements java.io.Serializable
{
/* Accessor methods for persistent fields */
private String userID; /* userID */
private String password; /* password */
private String fullName; /* fullName */
private String address; /* address */
private String email; /* email */
private String creditCard; /* creditCard */
public AccountProfileDataBean(){ }
public AccountProfileDataBean(String userID,
String password,
String fullName,
String address,
String email,
String creditCard)
{
setUserID(userID);
setPassword(password);
setFullName(fullName);
setAddress(address);
setEmail(email);
setCreditCard(creditCard);
}
public static AccountProfileDataBean getRandomInstance() {
return new AccountProfileDataBean(
TradeConfig.rndUserID(), // userID
TradeConfig.rndUserID(), // password
TradeConfig.rndFullName(), // fullname
TradeConfig.rndAddress(), // address
TradeConfig.rndEmail(TradeConfig.rndUserID()), //email
TradeConfig.rndCreditCard() // creditCard
);
}
public String toString()
{
return "\n\tAccount Profile Data for userID:" + getUserID()
+ "\n\t\t password:" + getPassword()
+ "\n\t\t fullName:" + getFullName()
+ "\n\t\t address:" + getAddress()
+ "\n\t\t email:" + getEmail()
+ "\n\t\t creditCard:" + getCreditCard()
;
}
public String toHTML()
{
return "<BR>Account Profile Data for userID: <B>" + getUserID() + "</B>"
+ "<LI> password:" + getPassword() + "</LI>"
+ "<LI> fullName:" + getFullName() + "</LI>"
+ "<LI> address:" + getAddress() + "</LI>"
+ "<LI> email:" + getEmail() + "</LI>"
+ "<LI> creditCard:" + getCreditCard() + "</LI>"
;
}
public void print()
{
Log.log( this.toString() );
}
/**
* Gets the userID
* @return Returns a String
*/
public String getUserID() {
return userID;
}
/**
* Sets the userID
* @param userID The userID to set
*/
public void setUserID(String userID)
{
this.userID = userID;
}
/**
* Gets the password
* @return Returns a String
*/
public String getPassword() {
return password;
}
/**
* Sets the password
* @param password The password to set
*/
public void setPassword(String password)
{
this.password = password;
}
/**
* Gets the fullName
* @return Returns a String
*/
public String getFullName() {
return fullName;
}
/**
* Sets the fullName
* @param fullName The fullName to set
*/
public void setFullName(String fullName)
{
this.fullName = fullName;
}
/**
* Gets the address
* @return Returns a String
*/
public String getAddress() {
return address;
}
/**
* Sets the address
* @param address The address to set
*/
public void setAddress(String address)
{
this.address = address;
}
/**
* Gets the email
* @return Returns a String
*/
public String getEmail() {
return email;
}
/**
* Sets the email
* @param email The email to set
*/
public void setEmail(String email)
{
this.email = email;
}
/**
* Gets the creditCard
* @return Returns a String
*/
public String getCreditCard() {
return creditCard;
}
/**
* Sets the creditCard
* @param creditCard The creditCard to set
*/
public void setCreditCard(String creditCard)
{
this.creditCard = creditCard;
}
}
| 22.920455 | 149 | 0.642291 |
7f38a7f3efa12a8d52c91db67452d08ad94388f3 | 2,001 | package de.lukaskoerfer.simplepnml;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class FillTest {
private Fill fill;
@BeforeEach
void setup() {
fill = new Fill();
}
@Test
void setColor_nullValue_fails() {
assertThrows(IllegalArgumentException.class, () -> {
fill.setColor(null);
});
}
@Test
void setGradientColor_nullValue_fails() {
assertThrows(IllegalArgumentException.class, () -> {
fill.setGradientColor(null);
});
}
@Test
void setGradientRotation_nullValue_fails() {
assertThrows(IllegalArgumentException.class, () -> {
fill.setGradientRotation(null);
});
}
@Test
void setImage_nullValue_fails() {
assertThrows(IllegalArgumentException.class, () -> {
fill.setImage(null);
});
}
@Test
void collect_newInstance_containsOneElement() {
var elements = fill.collect();
assertEquals(1, elements.count());
}
@Test
void isDefault_newInstance_true() {
assertTrue(fill.isDefault());
}
@Test
void isDefault_colorNotEmpty_false() {
fill.setColor("red");
assertFalse(fill.isDefault());
}
@Test
void isDefault_gradientColorNotEmpty_false() {
fill.setGradientColor("green");
assertFalse(fill.isDefault());
}
@Test
void isDefault_gradientRotationNotNone_false() {
fill.setGradientRotation(GradientRotation.DIAGONAL);
assertFalse(fill.isDefault());
}
@Test
void isDefault_imageNotEmpty_false() {
fill.setImage("http://example.com/image.png");
assertFalse(fill.isDefault());
}
}
| 22.738636 | 60 | 0.641679 |
c8cefea061df2e7f3eb8291a5156ded73c3cc3bf | 314 | package com.cutter.point.blog.xo.mapper;
import com.cutter.point.blog.xo.entity.WebConfig;
import com.cutter.point.blog.base.mapper.SuperMapper;
/**
* <p>
* 网站配置表 Mapper 接口
* </p>
*
* @author xuzhixiang
* @since 2018年11月11日15:01:44
*/
public interface WebConfigMapper extends SuperMapper<WebConfig> {
}
| 18.470588 | 65 | 0.729299 |
7b550fa6e4a00fe557c88de8dbcc4ec992ced3e5 | 6,506 | /********************************************************************************************
*
* Logger.java
*
* Description:
*
* Created on Feb 8, 2006
* @author Douglas Pearson
*
* Developed by ThreePenny Software <a href="http://www.threepenny.net">www.threepenny.net</a>
********************************************************************************************/
package edu.umich.soar.logger;
import sml.* ;
import java.io.* ;
public class Logger implements Agent.xmlEventInterface
{
Kernel m_Kernel ;
FileWriter m_OutputFile ;
boolean m_IsLogging = false ;
public static final String kLineSeparator = System.getProperty("line.separator");
/////////////////////////////////////////////////////////////////
//
// This handler is called with parsed XML data from the execution trace.
// There's a lot of interesting stuff in here that could be logged.
// If you need to log things that don't appear in the trace, you can register
// for other events (like production firings) and log extra information.
//
// If you don't want to process the trace but just capture it consider
// listening for the smlPrintEventId.smlEVENT_PRINT event instead
// which sends the trace just as strings.
//
//////////////////////////////////////////////////////////////// /
public void xmlEventHandler(int eventID, Object data, Agent agent, ClientXML xml)
{
try
{
// Setting this flag to true will dump the entire XML trace into the log file
// That can be helpful if you'd like to process it later or you'd like to see what
// information is available.
boolean kLogRawXML = false ;
if (kLogRawXML)
{
String str = xml.GenerateXMLString(true) ;
m_OutputFile.write(str + kLineSeparator) ;
}
// This will always succeed. If this isn't really trace XML
// the methods checking on tag names etc. will just fail.
// This is a cast.
ClientTraceXML pRootXML = xml.ConvertToTraceXML() ;
// The root object is just a <trace> tag. The substance is in the children
// so we'll get the first child which should exist.
for (int i = 0 ; i < pRootXML.GetNumberChildren() ; i++)
{
ClientTraceXML childXML = new ClientTraceXML() ;
boolean ok = pRootXML.GetChild(childXML, i) ;
ClientTraceXML pTraceXML = childXML ;
if (!ok)
{
// In Java we must explicitly delete XML objects we create
// Otherwise, the underlying C++ object won't be reclaimed until the gc runs which
// may not happen before the app finishes, in which case it'll look like a memory leak even
// though technically that's not the case.
childXML.delete() ;
return ;
}
// To figure out the format of the XML you can either look at the ClientTraceXML class
// (which has methods grouped appropriately) or you can look at the XML output directly.
// It's designed to be readable, so looking at a few packets you should quickly get the hang
// of what's going on and what attributes are available to be read.
// Here are a couple of examples.
// Check if this is a new state
if (pTraceXML.IsTagState())
{
String count = pTraceXML.GetDecisionCycleCount() ;
String stateID = pTraceXML.GetStateID() ;
String impasseObject = pTraceXML.GetImpasseObject() ;
String impasseType = pTraceXML.GetImpasseType() ;
m_OutputFile.write("New state at decision " + count + " was " + stateID + " (" + impasseObject + " " + impasseType + ")" + kLineSeparator) ;
}
// Check if this is a new operator
if (pTraceXML.IsTagOperator())
{
String count = pTraceXML.GetDecisionCycleCount() ;
String operatorID = pTraceXML.GetOperatorID() ;
String operatorName = pTraceXML.GetOperatorName() ;
m_OutputFile.write("Operator at decision " + count + " was " + operatorID + " name " + operatorName + kLineSeparator) ;
}
// In Java we must explicitly delete XML objects we create
// Otherwise, the underlying C++ object won't be reclaimed until the gc runs which
// may not happen before the app finishes, in which case it'll look like a memory leak even
// though technically that's not the case.
childXML.delete() ;
}
// Flushing the file means we can look at it while it's still being formed
// at the cost of a small reduction in performance.
m_OutputFile.flush() ;
}
catch (IOException ex)
{
System.out.println(ex) ;
}
}
public String startLogging(String filename, boolean append)
{
try
{
m_OutputFile = new FileWriter(filename, append) ;
}
catch (IOException ex)
{
return "Failed to open log file " + filename + " with exception " + ex ;
}
// Connect to the kernel we wish to capture logging information from.
m_Kernel = Kernel.CreateRemoteConnection(true, null) ;
if (m_Kernel.HadError())
{
String error = m_Kernel.GetLastErrorDescription() ;
m_Kernel.delete() ;
m_Kernel = null ;
return error ;
}
// This logger just logs the first agent's output.
// It could easily be extended to log an agent whose name we pass in or to log
// all agents if that's what you need.
Agent pAgent = m_Kernel.GetAgentByIndex(0) ;
if (pAgent == null)
{
String error = "Connected to kernel, but there are no agents running" ;
m_Kernel.Shutdown() ;
m_Kernel.delete() ;
m_Kernel = null ;
return error ;
}
// Start listening for XML trace events.
pAgent.RegisterForXMLEvent(smlXMLEventId.smlEVENT_XML_TRACE_OUTPUT, this, null) ;
// We'll also explicitly set the watch level to level 1 here. This determines how much
// output is sent out to the event handler. This setting is for the agent, so if you change it in
// the debugger (e.g. to watch 0) it will affect what gets logged. This is a limitation in the kernel.
pAgent.ExecuteCommandLine("watch 1") ;
m_IsLogging = true ;
return null ;
}
public void stopLogging()
{
try
{
if (m_OutputFile != null)
{
m_OutputFile.close() ;
m_OutputFile = null ;
}
}
catch (IOException ex)
{
System.out.println(ex) ;
}
if (m_Kernel != null)
{
m_Kernel.Shutdown() ;
m_Kernel.delete() ;
m_Kernel = null ;
}
m_IsLogging = false ;
}
public boolean isLogging()
{
return m_IsLogging ;
}
}
| 32.049261 | 146 | 0.624193 |
446236c51e90b544ea99871e062948ebb0c6c5b3 | 994 | package pl.com.bottega.factory.demand.forecasting;
import lombok.AllArgsConstructor;
import pl.com.bottega.factory.demand.forecasting.ReviewRequired.ToReview;
import java.util.Collections;
import java.util.function.Function;
@AllArgsConstructor
public enum ReviewDecision {
IGNORE(r -> null),
PICK_PREVIOUS(ToReview::getPreviousDocumented),
MAKE_ADJUSTMENT_WEAK(ToReview::getAdjustment),
PICK_NEW(ToReview::getNewDocumented);
private final Function<ToReview, Demand> pick;
public AdjustDemand toAdjustment(ToReview review) {
if (this == IGNORE) {
throw new IllegalStateException("can't convert " + this + " to adjustment");
}
return new AdjustDemand(review.getRefNo(),
Collections.singletonMap(
review.getDate(),
Adjustment.weak(pick.apply(review))
)
);
}
public boolean requireAdjustment() {
return this != IGNORE;
}
}
| 29.235294 | 88 | 0.65996 |
3680a5f829a6beb56bd7efe7cafbcf4ece944214 | 5,447 | package com.voidaspect.jgol.game;
import com.voidaspect.jgol.grid.Grid;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.Duration;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
class ThreadSafeLifeTest {
private static final Logger log = LoggerFactory.getLogger(ThreadSafeLifeTest.class);
private ThreadSafeLife subject;
private AbstractLife delegate;
private Grid grid;
@BeforeEach
void setUp() {
grid = mock(Grid.class);
delegate = mock(AbstractLife.class);
when(delegate.grid()).thenReturn(grid);
subject = ThreadSafeLife.of(delegate);
}
@Test
void shouldFreezeAndUnfreeze() {
when(delegate.isFrozen()).thenReturn(false);
assertFalse(subject.isFrozen());
assertFalse(subject.isFrozen());
subject.freeze();
when(delegate.isFrozen()).thenReturn(true);
assertTrue(subject.isFrozen());
assertTrue(subject.isFrozen());
subject.freeze();
assertTrue(subject.isFrozen());
verify(delegate, times(1)).freeze();
subject.unfreeze();
when(delegate.isFrozen()).thenReturn(false);
assertFalse(subject.isFrozen());
assertFalse(subject.isFrozen());
subject.unfreeze();
assertFalse(subject.isFrozen());
verify(delegate, times(1)).unfreeze();
}
@Test
void shouldPreventDoubleProxyOfGame() {
var tSafeLife = ThreadSafeLife.of(delegate);
assertSame(grid, delegate.grid());
assertNotSame(delegate.grid(), tSafeLife.grid());
var doubleProxy = ThreadSafeLife.of(tSafeLife);
assertSame(tSafeLife, doubleProxy);
}
@RepeatedTest(3)
void shouldAllowParallelReadOfGrid() {
when(grid.get(0, 0)).thenReturn(true);
int maxThreads = getMaxThreads();
var executor = Executors.newFixedThreadPool(maxThreads);
assertTimeout(Duration.ofMillis(200), () -> {
var futures = Stream.generate(() -> executor.submit(() -> {
sleep(100);
return subject.grid().get(0, 0);
})).limit(maxThreads).collect(Collectors.toList());
for (var future : futures) {
assertDoesNotThrow(() -> assertTrue(future.get()));
}
});
executor.shutdown();
assertDoesNotThrow(() -> executor.awaitTermination(1, TimeUnit.SECONDS));
}
@RepeatedTest(3)
void shouldHandleWriteContention() {
when(grid.get(0, 0)).thenReturn(false).thenReturn(true);
int maxThreads = getMaxThreads();
var executor = Executors.newFixedThreadPool(maxThreads);
assertTimeout(Duration.ofMillis(200), () -> {
var futures = Stream.generate(() -> executor.submit(() -> {
sleep(100);
subject.grid().set(0, 0, true);
return subject.grid().get(0, 0);
})).limit(maxThreads).collect(Collectors.toList());
for (var future : futures) {
assertDoesNotThrow(() -> assertTrue(future.get()));
}
});
executor.shutdown();
assertDoesNotThrow(() -> executor.awaitTermination(1, TimeUnit.SECONDS));
}
@Test
void shouldWaitForProgressBeforeRead() {
when(delegate.isFrozen()).thenReturn(false);
when(grid.get(0, 0)).thenReturn(true);
doAnswer(invocation -> {
sleep(300);
when(grid.get(0, 0)).thenReturn(false);
return null;
}).when(delegate).nextGen(any());
int readers = Math.max(getMaxThreads() - 1, 1);
var executor = Executors.newFixedThreadPool(readers);
assertTimeout(Duration.ofMillis(500), () -> {
var futures = Stream.generate(() -> executor.submit(() -> {
sleep(100);
return subject.grid().get(0, 0);
})).limit(readers).collect(Collectors.toList());
subject.progress();
for (var future : futures) {
assertDoesNotThrow(() -> assertFalse(future.get()));
}
});
executor.shutdown();
assertDoesNotThrow(() -> executor.awaitTermination(1, TimeUnit.SECONDS));
}
private static int getMaxThreads() {
int maxThreads = Runtime.getRuntime().availableProcessors();
log.info("Max thread count for synchronization tests {}", maxThreads);
return maxThreads;
}
private static void sleep(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
log.error("sleep interrupted", e);
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
static class ThreadSafeGridTest extends LifeTest.LifeGridTest {
@Override
AbstractLife getGame() {
return ThreadSafeLife.of(super.getGame());
}
@Override
AbstractLife getGame(boolean[][] initial) {
return ThreadSafeLife.of(super.getGame(initial));
}
}
} | 30.430168 | 88 | 0.608041 |
768064ed7c1911411d1509c03bda48e58960474f | 1,483 | package edu.sdsc.mmtf.spark.datasets;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.RowFactory;
import org.rcsb.mmtf.api.StructureDataInterface;
import edu.sdsc.mmtf.spark.mappers.StructureToPolymerSequences;
import edu.sdsc.mmtf.spark.ml.JavaRDDToDataset;
/**
* Creates a dataset of polymer sequences using the full sequence
* used in the experiment (i.e., the "SEQRES" record in PDB files).
*
* <p>Example: get dataset of sequences of L-proteins
* <pre><code>
* pdb.flatMapToPair(new StructureToPolymerChains())
* .filter(new ContainsLProteinChain());
*
* Dataset<Row> protSeq = PolymerSequenceExtractor.getDataset(pdb);
* protSeq.show(10);
* </pre></code>
*
* @author Peter Rose
* @since 0.1.0
*
*/
public class PolymerSequenceExtractor {
/**
* Returns a dataset of polymer sequences contained in PDB entries
* using the full sequence used in the experiment
* (i.e., the "SEQRES" record in PDB files).
*
* @param structureRDD structure
* @return dataset with sequence information
*/
public static Dataset<Row> getDataset(JavaPairRDD<String, StructureDataInterface> structureRDD) {
JavaRDD<Row> rows = structureRDD
.flatMapToPair(new StructureToPolymerSequences())
.map(t -> RowFactory.create(t._1, t._2));
return JavaRDDToDataset.getDataset(rows, "structureChainId","sequence");
}
}
| 30.895833 | 98 | 0.742414 |
c947ed7f073449646183fa2c96eabf003e4a10b8 | 632 | package org.traccar.protocol;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import org.traccar.BaseProtocol;
import org.traccar.PipelineBuilder;
import org.traccar.TrackerServer;
public class RadarProtocol extends BaseProtocol {
public RadarProtocol() {
addServer(new TrackerServer(false, getName()) {
@Override
protected void addProtocolHandlers(PipelineBuilder pipeline) {
pipeline.addLast(new LengthFieldBasedFrameDecoder(1024, 12, 2, -14, 0));
pipeline.addLast(new RadarProtocolDecoder(RadarProtocol.this));
}
});
}
}
| 30.095238 | 88 | 0.69462 |
a382f30df6f2b3266e5084cc4b747de54d42c99d | 11,562 | class uurErkoX35lG {
}
class wHuc {
}
class t {
public dM4hwQwvkuLmQf[][][][][][] wlN2eKLotZk2;
public p2[][][] ARp1CCgB () {
int tBhVCG5kThI;
boolean lx8gIgyNv18I = wfwLdHELwWVzD0.kuI8cwU6xJ;
}
public static void qzhMyKbNP11t (String[] qYJsyvzdfvTXH) {
ZLeKnabKNyK Kp9Vh = -eC().N4PQW;
while ( !--null.g()) while ( new boolean[ false.PDI1ing]._nRi6) return;
}
public Ba6V[][] _xk_pSex () throws WuLU0kdo {
!!-new KNuyFnloc5()._lXOY9;
new void[ -false.x].gK();
if ( !--true._HZjS()) while ( false.HwzsllM38()) {
while ( ---false.WKXE) !false.rp;
}else !--!null.r3AhVQr7JrZgS;
while ( --426906.MqcSxv()) ;
return;
return new Kiiu5V()[ -null[ 0[ 285517498.zN_]]];
void wbMvRd06 = ( -new void[ -new void[ -new void[ new f3UG2lqy[ --rGZp2j()[ -new XBAaOVwkShG().Og3damMOV]][ new boolean[ --null.H61F4WKlBbw].WsCC()]].pkXbXS()].ZYcAE7T].ywuqYjkd).hZ4geiE_EDD9FJ = -!this.AoDCjUUcg();
{
int[] gkrHobQg;
{
{
void pn5Toq;
}
}
;
void[] AOrn4dgxY2qP5;
if ( -fO32YdUqquTFa().DLDpqM8wOWhaa) -!this[ -false.Ge()];
}
int[][][][] JOZ;
boolean q4QDvv = dY4bHOLKtcW().Ijq12 = -!-true.IMJSPaXIm();
}
public boolean hykldXW (void[][][][][][][] HIFaSqLuBXzAlo, boolean[][] xChx, S[] AIaufqPpM, int zH6yLIAlql7, NQhjHrbGAZ[][] NWZ, void[][][] qgAmvcqp) throws hIYgMN {
boolean[] My1IONEX = false.ld3pUkIp() = -!!--!-!!!!!new boolean[ this.u3g].Jn;
if ( !this.Ym()) {
return;
}else {
while ( null.TQHG) {
return;
}
}
{
T8l3z[] g89gA;
while ( !944141.qdwt) return;
}
;
boolean[][][][][] V0ALPdAp;
while ( ( !!!-!162.eqor7).RVUOqcK49x) if ( true[ -!!( eJSK9NZiqnD[ !!-qUCqb7().IY7v()])[ !( EK2d82kFatvBV.ZbysxdoRN)[ !Mhfr9[ !-4662.hKQcfG7uNIZfU]]]]) while ( K8Q5XvXSUjUzV().AKLmJpzcnCk5kY) -!Tac0t()[ -77.uRqDQo()];
int[][][] zpXmHvIx = ( !-false.Bcr8IrQ)[ 70047795.rV()];
;
return -!-UCKRWkPuHIDnV()[ 8827.IqlEDXwK];
{
;
--!true[ MR.KR];
void rSPJpYyn4mnw;
boolean AA2eRH9oAcro;
void[][] psEHLRAy;
{
;
}
void[][][] kE;
{
while ( new void[ null[ true[ -true._()]]][ biyLlAQWIPT8B.XbkyPPHZkZdfy]) while ( false.Esp_iEH) while ( !true[ -false[ false.LXkC5b2IJPHO8b()]]) while ( -new Ws27jyFi[ new M9l()[ CsR.RGH1LLQ]].Btf0MZj) if ( -( !!new jtUyMFl().G8BEG).evhDj31) ;
}
}
boolean nI04XbDcYtD = new pp5M()[ !!false.PNdVimLu()];
DR1dT8mq().qQutfB1w();
{
{
int amoEo;
}
int[] D;
;
return;
int DZUm;
boolean[] LNAK70pe;
if ( -!2023[ new XMxggT8s4e()[ !new Xk_QcuN0()[ true[ -!this[ this[ ( new p2X().Pz88P).kn53Ch2W1KTf]]]]]]) ;
while ( !new ac_bNLj_JUzZ[ -!-new int[ ( false.fLA_t())[ !new int[ --( -!-null[ ( true.ozb2FUrOHtmz)[ !this.bo]]).Eg].TdD2Fu]].PsfHIvkkKirUoS()].NMiCDDh6td()) !false.tkIU9();
LjcNW2Qxw IZtN0UBY;
}
p pGoRSFa9AL2A;
return;
while ( false[ --( new Yx().XcdYeYC).Dw7Ne]) {
void y;
}
}
public Cm7 Lv;
public boolean[] alyrnNa5tIB5BF;
public int[][] Ov3LiQsbtP33Vn () throws riZ4F {
void vU = !!OiIQe()[ -!pMaK().jrEFHX_2gF()];
;
boolean FaJwqK8tly_;
void[][][] vkM = !-327.t6x_WUjSQD();
if ( !true[ null.DnLbtACm()]) ;else if ( false.uJcekZFERN0v()) if ( !z9wHt8y[ !571003.nU0LscbB()]) return;
3[ null.A28B1()];
while ( null.zzDiHxs1EpR()) ---i.rgnPoNm3Gem1();
while ( --new i().WGSY1_b1JEj()) while ( !6110521.vrFJSb) -this.O5uSd;
int[][] CIyJ2cI = true.vr0sNl6o9ID;
GX9vqRSqKvInpD[] dXPQJu2vO3hlIO;
new h().bu_a2();
-tC.aVO();
if ( -new void[ !-!new kxrAtStj2li().unWFYktPlzUi1()][ !-new int[ pn8o1JUCjrMsm().DhuS][ !995946631.Rof3tPqn3m7iDb]]) ;
void[] kUL7DTCx_6nw = new CmkPJixzz().qCKme() = !-null.ELWSLk();
int[] y_CtAUiT78_ng;
}
public boolean aEFDLz9od (TMJWWF00[] Y, void[][][] Pxg0Cpn) {
rXaaTg0 D = null.tlEk3k();
ipt VABrJaIzzTOl;
return;
boolean ZOP7eRi;
int[] rcZUCEq5fLyF;
return -!-false.DNWP8Hv;
int hHuh = !qenoWoS[ ---!JaDoQNr1w().r5YlZ] = !true[ !new rdeymwkCAxKH7[ -this.xoIE5hVd0][ ----4156241.g()]];
while ( new msdV()[ MkeC3L68_s.UbBLKxdusq]) if ( -!!!-79[ !I()[ -false.at0DPy4e8]]) if ( null.UbsemagHGo_0()) return;
return !!!-qxAGqBPBsG().E9cp_1TLOB;
void[][] UGK;
{
while ( false.caxwVs6a58X) if ( -this.ZrFGpkXrKK()) ;
int uC;
return;
boolean GieIYfpvjzeHgK;
void O7JB;
}
}
public L3v FWc;
public int n1HCj3rVgwU;
}
class W {
public int FrPR8rkV;
public static void gZXJQe1fLTw (String[] tel7lg2QqjgVB) {
{
;
int VLSy5p7D_xD;
{
cU2jEZ0nW4[] CzU6kyo8aeBLI;
}
{
void[][][] BHLPqoLNQNro;
}
return;
boolean[] _ipmRlEK;
IDtkdpO[] FRE;
while ( GvGVpna4CL8()[ -null[ -!-!new P2ZwKVaf1zZ()[ !---!new RRoCqeJ().IqqM]]]) {
if ( null.aEaEu()) if ( PvBWRBxaUBpRFG.MW9t1Wc()) while ( true.KPomi) ;
}
iYGpDgo[] PERO54w3UIl1x;
;
null.p0O45gXiJ4e9Q;
return;
;
boolean[][][] m3JtteVwWYIjA;
}
while ( ( !true.FnU4VAD5du)[ --462686712.ZXKxlL()]) ;
void[][] rAqp = !!new iB().RMXwjMJ() = false.EF9AmI;
return;
while ( !!!new void[ CvJWpsUN().MG287X].dBYMnfZuj4EkqJ) if ( --!false.XXo9xxxYEYDV) if ( TzNrsX3C[ !--null.tLUSlY()]) ;
mM GW;
if ( rU3zN.doo563aaT3n()) while ( true.o04W3qry) return;else return;
;
return;
int[] bEj58X;
if ( !null[ -!vFEEwFwyVhZ[ !false.hjhGvg0]]) while ( !true[ !--new h[ ( true[ --78118564.V4dEhCYNOU]).KdzQgKd].cSRHFANd9KJ()]) ;
while ( -_().zAG2cQG) while ( !0[ !( !!!!99[ EB6BkiWs().vOkH0ea()])[ -16.GB8vg]]) return;
void[][] zNw5YtWz = -true.ph5e6XcGu6();
boolean[][][] tU4L3vO;
}
public A_c2FdUL9JeJlk[][] a89e9zsh4ZWbYh (boolean V9yBAOjbA) throws n1zAxYAP0SvD {
f[][][] VR;
boolean uB7h = !!!false[ ( ( null[ -( -null.vpHRn2P).XepHQ3xZ()]).cWCPtk3poX5iza()).P2];
{
boolean ltYP4J3s;
return;
return;
}
{
return;
boolean B;
_GoHICdfH.Ti3PMIPEaGs();
int RZ;
void[] Mr;
int[][] T;
sTRRl45PE8[] HMS;
return;
if ( ---new yv8IQsjSP().BHc) ;
}
void St = -!s.eW5nUJvZhFYr = new kG[ --!!-null[ true.epbUbyQzh()]].Z9zeltEPGqW1;
if ( -( -cAHlZ9yz9().gNV()).U9D) {
while ( qWgXP.jeiQOKhzk9C3qv) -ep8mM1fkCVvc()[ false.Agh6wrsov()];
}else ;
;
}
public int Bur7zlOKkfO_M;
public Og31XZYhxkEz[] GDaUUV () throws CS {
void[][][] v = ( drWTsVY0sRhOPr.yyxaEx371wpLkf).mzZ1IxHmm();
while ( 142559.S0Cxw9DAsAkhE()) if ( VrqF2cmAQ2g().BmDv()) false.fa7qgKeFMeUk();
return -!!!new Z9Zd6q()[ new SW[ 3153.we()][ --!etAes_6.f9gRiTK()]];
{
X1 mI0G5If;
while ( !new j9GErPGe().oJsGkn3HJXCK) while ( --hJA1Q7BsCWmK1.ME1vrAMU_wpT_) {
boolean nkE7pCERSOGA;
}
{
kV0pOZDUOotT[][] V0_;
}
}
return;
boolean A6p7fxzKk;
boolean[][] vuWELe = -!false.w7ov3MxodT();
{
while ( -evUXVa[ fODvtXZ()[ !true.IjdMceEZmk7W]]) {
{
while ( seu5gQ().dN0rh4euKn) ;
}
}
while ( ju2oiGDzKxFm().t()) if ( ( !new void[ !this[ ( dDetQpv6pVu2[ this.C]).bU9WywDb()]][ -null.q4HW()]).gi) {
if ( ( -!!!v9C4VKGGZLF0i.dOD9LNYYHx8Pv()).u7WWJd92()) if ( !!--( !!!this.fV1SRvKx_).EqF8H3()) return;
}
AKikd K1JH7j;
;
{
if ( -Vw.NKcs4cE) return;
}
{
-fjJcpc[ ScTS.mS0gsykh];
}
Pf Uw;
boolean O2;
int vtVYDTBl;
;
int[] dq;
void[] GLPX5r4F5Qr;
if ( false[ 29122[ false.ROfPA()]]) if ( true.WrswQEeoPd) while ( !( 96195023.xlUxcCm9G7)[ new vXV0YhS().Dc]) ;
return;
}
void r0lrwXIhV = 1987532.WEluIQd4_MB();
--!this.PWMD5d_WFyO4;
void[][][] XQbSlhmkxf5Fkl = false.iE();
void[] fm = this[ !new boolean[ !this.OJNGfiyo90qUDe()].GA2Ow2e] = new QtJY()[ !new uOkhzB1NIKHOHJ().wp];
unvc06uBAjhi[] qpdI7k = 544386.g1cZiE3;
}
public int SHXA8l3r;
public static void K92BMsXrqXVwry (String[] gr1Lmi_pSOenKI) {
return false.fsy0RXp9NIby;
boolean _1U = new MKZ1u7k9BV().CTF8DiUH = !new LNRe4o().Vl;
qjTFzHaw[][] D9pjACl7_y_MJ;
if ( -new int[ --!false[ ( !-!true.MNWQ).FJ]].FgBzeui_o5Z()) return;else while ( 860.nZ) return;
int ZBQv = new SVhy4uTPwA5PwI()[ !!this[ -!25.S3lnHt08Ei]] = !this.BpVv1vB76();
return -new boolean[ -!aT.lG_G()][ true[ M9ZvHB1IZJ.r9D]];
;
RnPG_4pltF2yK.depYUHRyza();
while ( 443344[ false[ false.e_d]]) {
return;
}
void PDeo_0fe;
ld5hIVxkQY[] WH3KDKHJ;
}
public dLocM[] yS0 (void[] LCkfW36w4HG6v, iFOv97zez dpwbR1pTt, wR_hanL[][][][] QuF) {
reC0Wtobks_p7S[] Y6sp38lwstvP9n = new int[ true.tg3VHl_WycvTjC].kosgnd_1Dc;
while ( --604677860.acSsh99Hwf3()) {
!-!new int[ G_iHTU_mKa.xhHqIMd()][ !oA5Wizctkc._t()];
}
Mos9HoQRxk1L[][][][][] Yqk = -false.R;
;
return;
AhFLOJabFrNd[][] KJjfgaJE = 1879.qA5ZygSq;
pN.rk;
int ucboeDRb = LcL0rdg94[ !null[ --pdRP().T1fNux()]] = -!wnK.wya;
if ( -!null.zgfqZqmANwCT5m()) return;else if ( false.mLqFoCxHI5WdA) return;
return --!!!-this.m6tk;
boolean AwDeJ3z;
!-5308470[ -this[ -MjX6KOLeMl().lykFjIqYVsy1]];
void l81tWAFDN9sj = -( VtwM7npWl.bGs)[ this.oZodkP()];
;
while ( null.RxWH) while ( --this.nib) if ( null.X) while ( new int[ null.o9oBh].CvLhcEd) if ( -this.Etvj1ymQdEB7w2()) while ( new D_4MmqegXQ().XHVCREM5tT3a4O) {
Tv[] pTECrmv9d;
}
{
void eNXWp6IPY;
boolean c;
int[][][][] YJlMY;
;
int[] HxmX;
Qf8n8rWd dqGPkU1_o3;
if ( !( true.r2AFDtj0_TPP()).nIEP8jY) ;
while ( ( !null.SxIgC()).DacXWV()) while ( --true.kz5anN()) {
while ( -( !747.gQeZGBQpv()).B1i()) ;
}
;
return;
pGwKxFEf[] LUiqRf;
}
void oXEkKYXITeZiL;
}
}
| 37.784314 | 260 | 0.493254 |
22d243a1bde2798cee3a6a1a6be57e5cc009d90d | 857 | package com;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
public class SendMessage {
public void InternetStatus(String room, String status) {
String host = null;
switch (room) {
case "618_1":
host = "192.168.14.27";
break;
case "618_2":
host = "192.168.14.27";
break;
case "621":
host = "192.168.14.27";
break;
}
try {
Socket socketLogin = new Socket(host, 25101);
try (PrintWriter put = new PrintWriter(socketLogin.getOutputStream())) {
put.println(status);
put.flush();
System.out.println("\n[PUT] " + status);
}
} catch (IOException e) {
}
}
}
| 25.969697 | 84 | 0.47958 |
d020c8e85f46debead1c46404d6e18eb508751a8 | 775 | package test.objects;
import cz.mg.vulkan.Vk;
import cz.mg.vulkan.VkDevice;
import cz.mg.vulkan.VkPhysicalDevice;
import static cz.mg.vulkan.Vk.*;
public class TextureImage extends Image {
public TextureImage(Vk vk, VkPhysicalDevice physicalDevice, VkDevice device, int width, int height, int mipLevelCount) {
this(vk, physicalDevice, device, width, height, mipLevelCount, VK_FORMAT_R8G8B8A8_UNORM);
}
public TextureImage(Vk vk, VkPhysicalDevice physicalDevice, VkDevice device, int width, int height, int mipLevelCount, int format) {
super(vk, physicalDevice, device, width, height, mipLevelCount, format, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
}
}
| 40.789474 | 206 | 0.781935 |
3c002d878fe38e1daf083b2e82d93d29ec3f4e83 | 79 | /**
* Service layer beans.
*/
package com.bcmc.xor.flare.client.api.service;
| 15.8 | 46 | 0.696203 |
183a8b407c140aff63a7503b08d073c15b42b24e | 1,664 | package com.hdl.myhttputilssimple.view;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.StateListDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.hdl.myhttputils.MyHttpUtils;
import com.hdl.myhttputils.bean.CommCallback;
import com.hdl.myhttputils.bean.StringCallBack;
import com.hdl.myhttputils.utils.FailedMsgUtils;
import com.hdl.myhttputilssimple.R;
import com.hdl.myhttputilssimple.bean.LoginBean;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private ProgressDialog mProgressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("加载中");
}
public void onGet(View view) {
startActivity(new Intent(this,IPQueryActivity.class));
}
public void onPost(View view) {
startActivity(new Intent(this,LoginActivity.class));
}
public void onDownLoad(View view) {
startActivity(new Intent(this,DownloadActivity.class));
}
public void onUpLoad(View view) {
startActivity(new Intent(this,UploadActivity.class));
}
public void onString(View view) {
startActivity(new Intent(this,UpperCaseActivity.class));
}
}
| 29.192982 | 68 | 0.75 |
10f517c88e354340edaf9f622aa438a9318b8ae1 | 7,628 | package com.my.judge_in_proxy;
import android.util.ArrayMap;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class MyOkHttp {
private static final MediaType mediaType = MediaType.get("application/json; charset=utf-8");
public static OkHttpClient client;
private MyOkHttp() {
client = new OkHttpClient
.Builder()
.connectTimeout(60 * 1000, TimeUnit.MILLISECONDS)
.readTimeout(5 * 60 * 1000, TimeUnit.MILLISECONDS)
.writeTimeout(5 * 60 * 1000, TimeUnit.MILLISECONDS)
.proxy(Proxy.NO_PROXY)//不使用代理,网络抓不到包
// .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("192.168.1.7", 8888)))
.build();
}
//单例
private static class HttpOkHttpInstance {
private final static MyOkHttp INSTANCE = new MyOkHttp();
}
public static MyOkHttp getInstance() {
return HttpOkHttpInstance.INSTANCE;
}
/**
* GET请求
*
* @param url 请求地址
* @param okHttpCallBack 请求回调
* @param clazz 返回结果的Class
* @param <T> 返回结果类型
*/
public <T> void requestGet(@NotNull String url, @NotNull final OkHttpCallBack<T> okHttpCallBack,
@NotNull final Class<T> clazz) {
Request request = new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
okHttpCallBack.requestFailure(e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
assert response.body() != null;
requestResult(response.body().string(), okHttpCallBack, clazz);
} else {
okHttpCallBack.requestFailure(response.message());
}
}
});
}
/**
* POST请求
*
* @param url 请求地址
* @param params 请求参数 Map<String,String> 格式
* @param okHttpCallBack 请求回调
* @param clazz 返回结果的class
* @param <T> 请求返回的类型
*/
public <T> void requestPost(@NotNull String url, @NotNull ArrayMap<String, Object> params, @NotNull final OkHttpCallBack<T> okHttpCallBack,
@NotNull final Class<T> clazz) {
//获取到参数 params 类型为Map<String,String>,转化为发网络请求所需的JSON字符串格式
JSONObject param_json = new JSONObject(params);
String json = param_json.toString();
RequestBody body = RequestBody.create(mediaType, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
okHttpCallBack.requestFailure(e.getMessage());
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
if (response.isSuccessful()) {
assert response.body() != null;
requestResult(response.body().string(), okHttpCallBack, clazz);
} else {
okHttpCallBack.requestFailure(response.message());
}
}
});
}
/**
* POST请求 raw text原生格式
*
* @param url 请求地址
* @param params 请求参数 String 格式
* @param okHttpCallBack 请求回调
* @param clazz 返回结果的class
* @param <T> 请求返回的类型
*/
public <T> void doPost(@NotNull String url, @NotNull String params, @NotNull final OkHttpCallBack<T> okHttpCallBack,
@NotNull final Class<T> clazz) {
final MediaType mediaType = MediaType.get("application/x-www-form-urlencoded;charset=UTF-8");
RequestBody body = RequestBody.create(mediaType, params);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
okHttpCallBack.requestFailure(e.getMessage());
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
if (response.isSuccessful()) {
assert response.body() != null;
requestResult(response.body().string(), okHttpCallBack, clazz);
} else {
okHttpCallBack.requestFailure(response.message());
}
}
});
}
/**
* POST提交Form-data表单
*
* @param url 请求地址
* @param params 请求参数 Map<String,String> 类型
* @param okHttpCallBack 请求回调
* @param clazz 返回结果的Class
* @param <T> 返回结果类型
*/
public <T> void submitFormdata(@NotNull String url, @NotNull ArrayMap<String, String> params, @NotNull final OkHttpCallBack<T> okHttpCallBack, @NotNull final Class<T> clazz) {
//把传进来的Map<String,String> 类型 prams 参数 拼接到RequestBody body里
FormBody.Builder builder = new FormBody.Builder();
for (ArrayMap.Entry<String, String> entity : params.entrySet()) {
builder.add(entity.getKey(), entity.getValue());
}
RequestBody body = builder.build();
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
okHttpCallBack.requestFailure(e.getMessage());
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
if (response.isSuccessful()) {
assert response.body() != null;
requestResult(response.body().string(), okHttpCallBack, clazz);
} else {
okHttpCallBack.requestFailure(response.message());
}
}
});
}
private <T> void requestResult(String result, OkHttpCallBack<T> callBack, @NotNull Class<T> clazz) {
if ("java.lang.String".equals(clazz.getName())) {
callBack.requestSuccess((T) result);
} else {
Gson gson = new GsonBuilder().create();
callBack.requestSuccess(gson.fromJson(result, clazz));
}
}
public interface OkHttpCallBack<T> {
/**
* 请求成功回调
*
* @param t 回调返回成功结果输出
*/
void requestSuccess(T t);
/**
* 请求失败回调
*
* @param message 回调返回失败消息
*/
void requestFailure(String message);
}
}
| 34.36036 | 179 | 0.562402 |
4f02f19902ff4bd91841e6fdcdd1635c8fcbd2fe | 7,577 | package io.jari.fingerprint;
import android.Manifest;
import android.content.pm.PackageManager;
import androidx.core.hardware.fingerprint.FingerprintManagerCompat;
import androidx.core.os.CancellationSignal;
import androidx.core.app.ActivityCompat;
import android.util.Log;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import java.util.HashMap;
import java.util.Map;
@SuppressWarnings("MissingPermission")
public class FingerprintModule extends ReactContextBaseJavaModule {
private static final String TAG = "FingerprintModule";
FingerprintManagerCompat fingerprintManager;
ReactApplicationContext reactContext;
CancellationSignal cancellationSignal;
boolean isCancelled = false;
final int FINGERPRINT_ACQUIRED_AUTH_FAILED = 999;
final int FINGERPRINT_ERROR_CANCELED = 5;
public FingerprintModule(ReactApplicationContext reactContext) {
super(reactContext);
this.reactContext = reactContext;
this.fingerprintManager = FingerprintManagerCompat.from(reactContext);
}
// Harcdoded from https://developer.android.com/reference/android/hardware/fingerprint/FingerprintManager.html#FINGERPRINT_ACQUIRED_GOOD
// So we don't depend on FingerprintManager directly
@Override
public Map<String, Object> getConstants() {
final Map<String, Object> constants = new HashMap<>();
constants.put("FINGERPRINT_ACQUIRED_GOOD", 0);
constants.put("FINGERPRINT_ACQUIRED_IMAGER_DIRTY", 3);
constants.put("FINGERPRINT_ACQUIRED_INSUFFICIENT", 2);
constants.put("FINGERPRINT_ACQUIRED_PARTIAL", 1);
constants.put("FINGERPRINT_ACQUIRED_TOO_FAST", 5);
constants.put("FINGERPRINT_ACQUIRED_TOO_SLOW", 4);
constants.put("FINGERPRINT_ACQUIRED_AUTH_FAILED", FINGERPRINT_ACQUIRED_AUTH_FAILED);
constants.put("FINGERPRINT_ERROR_CANCELED", FINGERPRINT_ERROR_CANCELED);
constants.put("FINGERPRINT_ERROR_HW_UNAVAILABLE", 1);
constants.put("FINGERPRINT_ERROR_LOCKOUT", 7);
constants.put("FINGERPRINT_ERROR_NO_SPACE", 4);
constants.put("FINGERPRINT_ERROR_TIMEOUT", 3);
constants.put("FINGERPRINT_ERROR_UNABLE_TO_PROCESS", 2);
return constants;
}
@ReactMethod
public void hasPermission(Promise promise) {
try {
promise.resolve(ActivityCompat.checkSelfPermission(reactContext, Manifest.permission.USE_FINGERPRINT) == PackageManager.PERMISSION_GRANTED);
} catch (Exception ex) {
promise.reject(ex);
}
}
@ReactMethod
public void hasEnrolledFingerprints(Promise promise) {
try {
promise.resolve(fingerprintManager.hasEnrolledFingerprints());
} catch (SecurityException secEx) {
Exception exception = new Exception("App does not have the proper permissions. (did you add USE_FINGERPRINT to your manifest?)\nMore info see https://github.com/jariz/react-native-fingerprint-android");
exception.initCause(secEx);
promise.reject(exception);
} catch (Exception ex) {
promise.reject(ex);
}
}
@ReactMethod
public void isHardwareDetected(Promise promise) {
try {
promise.resolve(fingerprintManager.isHardwareDetected());
} catch (SecurityException secEx) {
Exception exception = new Exception("App does not have the proper permissions. (did you add USE_FINGERPRINT to your manifest?)\nMore info see https://github.com/jariz/react-native-fingerprint-android");
exception.initCause(secEx);
promise.reject(exception);
} catch (Exception ex) {
promise.reject(ex);
}
}
@ReactMethod
public void authenticate(Promise promise) {
try {
isCancelled = false;
cancellationSignal = new CancellationSignal();
fingerprintManager.authenticate(null, 0, cancellationSignal, new AuthenticationCallback(promise), null);
} catch (SecurityException secEx) {
Exception exception = new Exception("App does not have the proper permissions. (did you add USE_FINGERPRINT to your manifest?)\nMore info see https://github.com/jariz/react-native-fingerprint-android");
exception.initCause(secEx);
promise.reject(exception);
} catch (Exception ex) {
promise.reject(ex);
}
}
@ReactMethod
public void isAuthenticationCanceled(Promise promise) {
promise.resolve(isCancelled);
}
@ReactMethod
public void cancelAuthentication(Promise promise) {
try {
if(!isCancelled) {
cancellationSignal.cancel();
isCancelled = true;
}
promise.resolve(null);
} catch(Exception e) {
promise.reject(e);
}
}
@Override
public String getName() {
return "FingerprintAndroid";
}
public class AuthenticationCallback extends FingerprintManagerCompat.AuthenticationCallback {
Promise promise;
public AuthenticationCallback(Promise promise) {
this.promise = promise;
}
@Override
public void onAuthenticationError(int errorCode, CharSequence errString) {
super.onAuthenticationError(errorCode, errString);
if(errorCode == FINGERPRINT_ERROR_CANCELED) {
isCancelled = true;
}
if(promise == null) {
Log.w(TAG, "Tried to reject the auth promise, but it was already resolved / rejected.");
return;
}
promise.reject(Integer.toString(errorCode), errString.toString());
promise = null;
}
@Override
public void onAuthenticationHelp(int helpCode, CharSequence helpString) {
super.onAuthenticationHelp(helpCode, helpString);
WritableNativeMap writableNativeMap = new WritableNativeMap();
writableNativeMap.putInt("code", helpCode);
writableNativeMap.putString("message", helpString.toString());
reactContext
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("fingerPrintAuthenticationHelp", writableNativeMap);
}
@Override
public void onAuthenticationSucceeded(FingerprintManagerCompat.AuthenticationResult result) {
super.onAuthenticationSucceeded(result);
if(promise == null) {
Log.w(TAG, "Tried to reject the auth promise, but it was already resolved / rejected.");
return;
}
promise.resolve(null);
promise = null;
}
@Override
public void onAuthenticationFailed() {
super.onAuthenticationFailed();
WritableNativeMap writableNativeMap = new WritableNativeMap();
writableNativeMap.putInt("code", FINGERPRINT_ACQUIRED_AUTH_FAILED);
writableNativeMap.putString("message", "Fingerprint was recognized as not valid.");
reactContext
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("fingerPrintAuthenticationHelp", writableNativeMap);
}
}
}
| 39.056701 | 214 | 0.67375 |
d6c1cec8278ec1da70ef1c43da0c1e8b9d428aa4 | 970 | package im.actor.sdk.controllers.fragment.settings;
import android.os.Bundle;
import im.actor.sdk.R;
import im.actor.sdk.controllers.Intents;
import im.actor.sdk.controllers.activity.BaseFragmentActivity;
public class EditAboutActivity extends BaseFragmentActivity {
public static final int TYPE_ME = 0;
public static final int TYPE_GROUP = 2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int type = getIntent().getIntExtra(Intents.EXTRA_EDIT_TYPE, 0);
int id = getIntent().getIntExtra(Intents.EXTRA_EDIT_ID, 0);
if (type == TYPE_ME) {
getSupportActionBar().setTitle(R.string.about_user_me);
} else if (type == TYPE_GROUP) {
getSupportActionBar().setTitle(R.string.about_group);
}
if (savedInstanceState == null) {
showFragment(EditAboutFragment.editAbout(type, id), false, false);
}
}
}
| 30.3125 | 78 | 0.68866 |
217da54019067c4bd3ac2cefe07fda0b9eaf270d | 817 | package frc.robot;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj2.command.button.*;
public class JoyButton extends Button {
private JoyDir joyDir;
private Joystick stick;
private int axis;
public enum JoyDir {
DOWN,UP;
}
/**
* Uses Joystick as a button input.
* @param joystick
* @param direction
* @param axis
*/
public JoyButton(Joystick joystick, JoyDir direction, int axis) {
joyDir = direction;
stick = joystick;
this.axis = axis;
}
public double getRawAxis() {
return stick.getRawAxis(axis);
}
@Override
public boolean get() {
switch(joyDir) {
case UP:
if(stick.getRawAxis(axis) <= -.1) {
return true;
}
break;
case DOWN:
if(stick.getRawAxis(axis) >= .1) {
return true;
}
break;
}
return false;
}
}
| 17.020833 | 66 | 0.648715 |
a0bdfcf369ca1325256aa6b22a4098c27a2a8463 | 1,510 | package com.googlecode.l10nmavenplugin.validators.property.format;
import static org.junit.Assert.*;
import java.util.Properties;
import org.junit.Before;
import org.junit.Test;
import com.googlecode.l10nmavenplugin.model.BundlePropertiesFile;
import com.googlecode.l10nmavenplugin.model.PropertiesFile;
import com.googlecode.l10nmavenplugin.model.Property;
import com.googlecode.l10nmavenplugin.model.PropertyImpl;
import com.googlecode.l10nmavenplugin.validators.AbstractL10nValidatorTest;
public class InnerResourcesFormattingValidatorTest extends AbstractL10nValidatorTest<Property> {
private static final String REGEX_DOLLAR_SIGN = "\\$\\{([A-Za-z0-9\\._]+)\\}";
private Properties properties = new Properties();
private PropertiesFile file = new BundlePropertiesFile("SomeFile.properties", properties);
@Override
@Before
public void setUp() {
super.setUp();
validator = new InnerResourcesFormattingValidator(logger, REGEX_DOLLAR_SIGN);
}
@Test
public void test() {
properties.setProperty("some.key", "some.value");
assertEquals(0, validator.validate(new PropertyImpl(KEY_OK, "Some value without inner keys", file), items));
assertEquals(0, validator.validate(new PropertyImpl(KEY_OK, "Some value with existing inner key ${some.key}",
file), items));
assertEquals(1, validator.validate(new PropertyImpl(KEY_KO,
"Some value with non existing inner key ${some.other.key}", file), items));
}
}
| 35.116279 | 114 | 0.745033 |
85b28f4a692241624c4e42569bedc8eaabf7769a | 784 | package com.academy.datastax.api;
import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan(basePackages= {"com.academy.datastax"})
@EnableAutoConfiguration( exclude = {
org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration.class,
org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration.class
} )
public class KillrVideoRestApi {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(KillrVideoRestApi.class);
app.setBannerMode(Banner.Mode.OFF);
app.run(args);
}
} | 37.333333 | 98 | 0.784439 |
e4dd3c13d375c3ce5412286da229ef13ba3d145f | 5,178 | /*
* Copyright 2015 AT&T
*
* 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.att.aro.core.commandline.impl;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.log4j.Logger;
import org.apache.log4j.LogManager;
import org.springframework.beans.factory.annotation.Autowired;
import com.att.aro.core.commandline.IExternalProcessRunner;
import com.att.aro.core.commandline.IProcessFactory;
import com.att.aro.core.commandline.pojo.ProcessWorker;
import com.att.aro.core.concurrent.IThreadExecutor;
import com.att.aro.core.util.Util;
public class ExternalProcessRunnerImpl implements IExternalProcessRunner {
IThreadExecutor threadExecuter;
ProcessWorker worker = null;
IProcessFactory procfactory;
private static final Logger LOG = LogManager.getLogger(ExternalProcessRunnerImpl.class.getName());
@Autowired
public void setProcessFactory(IProcessFactory factory){
this.procfactory = factory;
}
@Autowired
public void setThreadExecutor(IThreadExecutor threadExecuter) {
this.threadExecuter = threadExecuter;
}
public ExternalProcessRunnerImpl() {
}
public void setProcessWorker(ProcessWorker worker) {
this.worker = worker;
}
/**
* execute command in bash/CMD shell
*
* @param cmd
* @return stdout and stderr
*/
@Override
public String executeCmd(String cmd) {
String result = executeCmdRunner(cmd, false, "");
return result;
}
@Override
public String executeCmdRunner(String cmd, boolean earlyExit, String msg) {
ProcessBuilder pbldr = new ProcessBuilder().redirectErrorStream(true);
if (!Util.isWindowsOS()) {
pbldr.command(new String[] { "bash", "-c", cmd });
} else {
pbldr.command(new String[] { "CMD", "/C", cmd });
}
StringBuilder builder = new StringBuilder();
try {
Process proc = pbldr.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = null;
while (true) {
line = reader.readLine();
if (line == null) {
break;
}
if(earlyExit && line.trim().equals(msg)) {
LOG.debug("read a line:" + line);
builder.append(line);
break;
}
LOG.debug("read a line:" + line);
builder.append(line);
builder.append(System.getProperty("line.separator"));
}
} catch (IOException e) {
LOG.error("Error executing <" + cmd + "> IOException:" + e.getMessage());
}
return builder.toString();
}
@Override
public String runCmd(String[] command) throws IOException {
Process process = procfactory.create(command);
InputStream input = process.getInputStream();
try (ByteArrayOutputStream out = readInputStream(input)) {
if (input != null) {
input.close();
}
if (process != null) {
process.destroy();
}
String datastr = null;
if (out != null) {
datastr = out.toString();
}
return datastr;
}
}
ByteArrayOutputStream readInputStream(InputStream input) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int totalread = -1;
while ((totalread = input.read(data, 0, data.length)) != -1) {
out.write(data, 0, totalread);
}
return out;
}
@Override
public String runCmdWithTimeout(String[] command, long timeout) throws IOException {
Process process = procfactory.create(command);
if (worker == null) {
worker = new ProcessWorker(process, timeout);
}
threadExecuter.execute(worker);
InputStream input = process.getInputStream();
try (ByteArrayOutputStream out = readInputStream(input)) {
worker.setExit();
worker = null;
if (input != null) {
input.close();
}
if (process != null) {
process.destroy();
}
String datastr = null;
if (out != null) {
datastr = out.toString();
}
return datastr;
}
}
@Override
public String runGetString(String command) throws IOException {
ByteArrayOutputStream data = this.run(command);
String out = "";
if (data != null) {
out = data.toString();
data.close();
return out;
}
return null;
}
@Override
public ByteArrayOutputStream run(String command) throws IOException {
Process process = procfactory.create(command);
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream input = process.getInputStream();
byte[] data = new byte[1024];
int totalread = -1;
while ((totalread = input.read(data, 0, data.length)) != -1) {
out.write(data, 0, totalread);
}
if (input != null) {
input.close();
}
if (process != null) {
process.destroy();
}
return out;
}
}
| 25.89 | 99 | 0.69776 |
e2992a15d8b2c7b5a4e42d4580715d5b0945d01b | 898 | package com.dpgrandslam.stockdataservice.acceptance;
import com.dpgrandslam.stockdataservice.StockDataServiceApplication;
import io.cucumber.spring.CucumberContextConfiguration;
import org.junit.Ignore;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = StockDataServiceApplication.class)
@CucumberContextConfiguration
@ActiveProfiles({"local", "local-mock"})
@AutoConfigureMockMvc
@Ignore
public class BaseAcceptanceTestSteps {
@Autowired
protected MockMvc mockMvc;
}
| 33.259259 | 84 | 0.848552 |
d128e429cb23bf9352e97d745804da970b658214 | 1,701 | package jdbcUtils;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
/**
* jdbc连接工具类 v3
* @author Administrator
* @date 2018年4月3日
*/
public class jdbcUtil {
private static String driver = null;
private static String url = null;
private static String username = null;
private static String password = null;
/**
* 使用db.propertise配置文件加载数据库信息
* 使用Properties对象
*/
static {
try {
ClassLoader classloader = jdbcUtil.class.getClassLoader();
InputStream inps = classloader.getResourceAsStream("db.properties");
Properties pro = new Properties();
pro.load(inps);
driver = pro.getProperty("driver");
url = pro.getProperty("url");
username = pro.getProperty("username");
password = pro.getProperty("password");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获取连接
* @return
*/
public static Connection getConnection() {
Connection conn = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url,username,password);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
/**
* 释放资源
* @param conn
* @param pst
* @param rs
*/
public static void release(Connection conn, PreparedStatement pst, ResultSet rs) {
try {
if(rs != null) rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(pst != null) pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
| 21.807692 | 83 | 0.677837 |
880688ec70da912065249dda95ea9d1e1162e20b | 961 | package client.messages.commands.gm;
import client.MapleClient;
import client.messages.Command;
public class LevelCommand extends Command {
@Override
public void execute(MapleClient c, String[] splitted){
short maxLevel = 255;
short level = c.getPlayer().getLevel();
try {
level = Short.parseShort(splitted[0]);
} catch (NumberFormatException $Exception) { // out of range for short.
level = maxLevel;
}
if (level > maxLevel) { // in range of short, but out of range for max level.
level = maxLevel;
}
if (level != c.getPlayer().getLevel()) { // Only do this if target level is different from now.
c.getPlayer().setLevel(level);
c.getPlayer().levelUp();
if (c.getPlayer().getExp() < 0) {
c.getPlayer().gainExp(-c.getPlayer().getExp(), false, false, true);
}
}
}
}
| 32.033333 | 103 | 0.57128 |
4126973e1d5ed99e80502afcfb91cebf98bf30c1 | 3,240 | package com.truextend.firstProblem.controllers;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.truextend.firstProblem.entities.ClassEntity;
import com.truextend.firstProblem.services.ClassService;
import com.truextend.firstProblem.services.impl.ClassServiceImpl;
@RestController
@RequestMapping(path = "/class")
public class ClassController {
@Autowired
ClassService classService = new ClassServiceImpl();
@CrossOrigin
@GetMapping
public List<ClassEntity> findAll() {
return classService.findAll();
}
@CrossOrigin
@PostMapping
public ResponseEntity<ClassEntity> save(@Valid @RequestBody ClassEntity classEntity) {
return ResponseEntity.ok(classService.save(classEntity));
}
@SuppressWarnings("rawtypes")
@CrossOrigin
@PutMapping("/{sClassId}")
public ResponseEntity update(@PathVariable String sClassId,
@Valid @RequestBody ClassEntity classEntity) {
Optional<String> classId = Optional.ofNullable(sClassId);
if (classId.isEmpty()) {
return new ResponseEntity(HttpStatus.BAD_REQUEST);
} else {
Long lClassId = Long.parseLong(sClassId);
Optional<ClassEntity> foundClass = Optional.ofNullable(classService.findByLClassId(lClassId));
if (foundClass.isPresent()) {
classEntity.setLClassId(lClassId);
return ResponseEntity.ok(classService.save(classEntity));
} else {
return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
}
}
@SuppressWarnings("rawtypes")
@CrossOrigin
@DeleteMapping("/{sClassId}")
public ResponseEntity delete(@PathVariable String sClassId) {
Optional<String> classId = Optional.ofNullable(sClassId);
if (classId.isEmpty()) {
return new ResponseEntity(HttpStatus.BAD_REQUEST);
} else {
Long lClassId = Long.parseLong(sClassId);
Optional<ClassEntity> foundClass = Optional.ofNullable(classService.findByLClassId(lClassId));
if (foundClass.isPresent()) {
classService.deleteById(lClassId);
return new ResponseEntity(HttpStatus.OK);
} else {
return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
}
}
@CrossOrigin
@PostMapping(path = "/search")
public ResponseEntity<Set<ClassEntity>> filter(@Valid @RequestBody ClassEntity classEntity)
throws JsonProcessingException {
return ResponseEntity
.ok(classService.findByObjectFilter(classEntity.getSClassCode(), classEntity.getSClassTitle(),
classEntity.getSClassDescription(), classEntity.getClassFilteredStudents()));
}
}
| 34.105263 | 98 | 0.791975 |
f15eb2c9e46485f4b5037ce044e672d51144c487 | 1,637 | package io.github.pedroermarinho.comandalivreapi.domain.usecases.employeea_at_organization;
import io.github.pedroermarinho.comandalivreapi.domain.dtos.EmployeeAtOrganizationDTO;
import io.github.pedroermarinho.comandalivreapi.domain.repositories.EmployeeAtOrganizationRepository;
import io.github.pedroermarinho.comandalivreapi.domain.validation.NotNullValidation;
import io.github.pedroermarinho.comandalivreapi.domain.validation.Validation;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
@Service
public class StatusEmployeeAtOrganization {
private final EmployeeAtOrganizationRepository employeeAtOrganizationRepository;
public StatusEmployeeAtOrganization(EmployeeAtOrganizationRepository employeeAtOrganizationRepository) {
this.employeeAtOrganizationRepository = employeeAtOrganizationRepository;
}
@Transactional
public EmployeeAtOrganizationDTO disableEmployeeAtOrganization(UUID id) {
final List<Validation<UUID>> validations = Arrays.asList(new NotNullValidation<>());
validations.forEach(validation -> validation.validationThrow(id));
return employeeAtOrganizationRepository.disable(id);
}
@Transactional
public EmployeeAtOrganizationDTO enableEmployeeAtOrganization(UUID id) {
final List<Validation<UUID>> validations = Arrays.asList(new NotNullValidation<>());
validations.forEach(validation -> validation.validationThrow(id));
return employeeAtOrganizationRepository.enable(id);
}
}
| 39.926829 | 108 | 0.814905 |
760b585c159889e30d74636eab604af5854769e3 | 1,223 | package com.example.android.bluetoothlegatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import java.util.List;
import java.util.UUID;
import static java.lang.Thread.sleep;
/**
* Created by andre on 22/11/2017.
*/
public class classeBozza extends Thread{
Handler wHandler;
public classeBozza(Handler wHandler){
this.wHandler = wHandler;
}
private BluetoothLeService mBluetoothLeService;
/* EMG Service UUID */
public static UUID EMG_SERVICE = UUID.fromString("00001805-0000-1000-8000-00805f9b34fb");
/* Mandatory Current Value Information Characteristic */
public static UUID CURRENT_VALUE = UUID.fromString("00002a2b-0000-1000-8000-00805f9b34fb");
public void run() {
while (true){
Log.i("Thread acquisizione", "is running");
try {sleep(50);} catch (InterruptedException e) {e.printStackTrace();}
// Send the Message to the Main activity.
Message readMsg = wHandler.obtainMessage();
wHandler.sendMessage(readMsg);
}
}
}
| 27.177778 | 98 | 0.700736 |
0ad1eaeb963116a29717823d88a56e6557f163b3 | 4,687 | /*
* 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.arrow.flight;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.function.Consumer;
import org.apache.arrow.flight.FlightClient.Builder;
import org.apache.arrow.memory.BufferAllocator;
import org.apache.arrow.memory.RootAllocator;
import org.junit.Assert;
import org.junit.Test;
/**
* Tests for TLS in Flight.
*/
public class TestTls {
/**
* Test a basic request over TLS.
*/
@Test
public void connectTls() {
test((builder) -> {
try (final InputStream roots = new FileInputStream(FlightTestUtil.exampleTlsRootCert().toFile());
final FlightClient client = builder.trustedCertificates(roots).build()) {
final Iterator<Result> responses = client.doAction(new Action("hello-world"));
final byte[] response = responses.next().getBody();
Assert.assertEquals("Hello, world!", new String(response, StandardCharsets.UTF_8));
Assert.assertFalse(responses.hasNext());
} catch (InterruptedException | IOException e) {
throw new RuntimeException(e);
}
});
}
/**
* Make sure that connections are rejected when the root certificate isn't trusted.
*/
@Test
public void rejectInvalidCert() {
test((builder) -> {
try (final FlightClient client = builder.build()) {
final Iterator<Result> responses = client.doAction(new Action("hello-world"));
FlightTestUtil.assertCode(FlightStatusCode.UNAVAILABLE, () -> responses.next().getBody());
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
}
/**
* Make sure that connections are rejected when the hostname doesn't match.
*/
@Test
public void rejectHostname() {
test((builder) -> {
try (final InputStream roots = new FileInputStream(FlightTestUtil.exampleTlsRootCert().toFile());
final FlightClient client = builder.trustedCertificates(roots).overrideHostname("fakehostname")
.build()) {
final Iterator<Result> responses = client.doAction(new Action("hello-world"));
FlightTestUtil.assertCode(FlightStatusCode.UNAVAILABLE, () -> responses.next().getBody());
} catch (InterruptedException | IOException e) {
throw new RuntimeException(e);
}
});
}
void test(Consumer<Builder> testFn) {
final FlightTestUtil.CertKeyPair certKey = FlightTestUtil.exampleTlsCerts().get(0);
try (
BufferAllocator a = new RootAllocator(Long.MAX_VALUE);
Producer producer = new Producer();
FlightServer s =
FlightTestUtil.getStartedServer(
(location) -> {
try {
return FlightServer.builder(a, location, producer)
.useTls(certKey.cert, certKey.key)
.build();
} catch (IOException e) {
throw new RuntimeException(e);
}
})) {
final Builder builder = FlightClient.builder(a, Location.forGrpcTls(FlightTestUtil.LOCALHOST, s.getPort()));
testFn.accept(builder);
} catch (InterruptedException | IOException e) {
throw new RuntimeException(e);
}
}
static class Producer extends NoOpFlightProducer implements AutoCloseable {
@Override
public void doAction(CallContext context, Action action, StreamListener<Result> listener) {
if (action.getType().equals("hello-world")) {
listener.onNext(new Result("Hello, world!".getBytes(StandardCharsets.UTF_8)));
listener.onCompleted();
return;
}
listener
.onError(CallStatus.UNIMPLEMENTED.withDescription("Invalid action " + action.getType()).toRuntimeException());
}
@Override
public void close() {
}
}
}
| 36.053846 | 120 | 0.670792 |
9949f258108ceb9459b9e33f85fc74a36bc65bed | 1,107 | package com.braintreegateway.unittest;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import com.braintreegateway.PaginatedCollection;
import com.braintreegateway.PaginatedResult;
import com.braintreegateway.SimplePager;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class PaginatedCollectionTest {
@Test
public void testGetsSinglePageFullCollection() {
SimplePager pager = mock(SimplePager.class);
List<Integer> values = new ArrayList<Integer>();
values.add(1);
when(pager.getPage(1)).thenReturn(new PaginatedResult(1, 1, values));
PaginatedCollection<Integer> collection = new PaginatedCollection<Integer>(pager);
List<Integer> results = new ArrayList<Integer>();
for(Integer i : collection) {
results.add(i);
}
verify(pager, times(1)).getPage(1);
verify(pager, times(1)).getPage(any(int.class));
}
}
| 29.131579 | 90 | 0.718157 |
6b78fa4da35d1628cd587e9eeb3c959338156184 | 6,547 | /**
* Copyright 2014 Meruvian
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.meruvian.yama.webapi.config;
import org.apache.commons.lang3.RandomStringUtils;
import org.meruvian.yama.core.user.User;
import org.meruvian.yama.social.connection.SocialConnectionRepository;
import org.meruvian.yama.social.core.SocialConnectionService;
import org.meruvian.yama.social.core.SocialServiceLocator;
import org.meruvian.yama.social.core.SocialServiceRegistry;
import org.meruvian.yama.social.core.SocialUsersConnectionService;
import org.meruvian.yama.social.facebook.FacebookService;
import org.meruvian.yama.social.github.GithubService;
import org.meruvian.yama.social.google.GooglePlusService;
import org.meruvian.yama.social.linkedin.LinkedInService;
import org.meruvian.yama.social.mervid.MervidService;
import org.meruvian.yama.social.mervid.connect.MervidConnectionFactory;
import org.meruvian.yama.web.SessionCredentials;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.core.env.Environment;
import org.springframework.social.connect.ConnectionSignUp;
import org.springframework.social.facebook.connect.FacebookConnectionFactory;
import org.springframework.social.github.connect.GitHubConnectionFactory;
import org.springframework.social.google.connect.GoogleConnectionFactory;
import org.springframework.social.linkedin.connect.LinkedInConnectionFactory;
/**
* @author Dian Aditya
*
*/
@Configuration
public class SocialConfig implements EnvironmentAware {
private RelaxedPropertyResolver env;
@Bean
public SocialServiceLocator socialServiceLocator() {
SocialServiceRegistry registry = new SocialServiceRegistry();
registry.addSocialService(facebookService());
registry.addSocialService(googlePlusService());
registry.addSocialService(mervidService());
registry.addSocialService(linkedInService());
registry.addSocialService(githubService());
return registry;
}
@Bean
public SocialUsersConnectionService usersConnectionRepository(SocialServiceLocator locator,
SocialConnectionRepository repository, ConnectionSignUp connectionSignUp) {
SocialUsersConnectionService s = new SocialUsersConnectionService(locator, repository);
s.setConnectionSignUp(connectionSignUp);
return s;
}
@Bean
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public SocialConnectionService connectionRepository(SocialUsersConnectionService usersConnectionRepository) {
User user = SessionCredentials.getCurrentUser();
if (user == null) return null;
return usersConnectionRepository.createConnectionRepository(user.getId());
}
@Bean
public FacebookService facebookService() {
String appId = env.getProperty("facebook.appId");
String appSecret = env.getProperty("facebook.appSecret");
String redirectUri = env.getProperty("facebook.redirectUri");
String scope = env.getProperty("facebook.scope");
FacebookConnectionFactory factory = new FacebookConnectionFactory(appId, appSecret);
FacebookService facebookService = new FacebookService(factory);
facebookService.setRedirectUri(redirectUri);
facebookService.setScope(scope);
facebookService.setState(RandomStringUtils.randomAlphanumeric(20));
return facebookService;
}
@Bean
public GooglePlusService googlePlusService() {
String appId = env.getProperty("google.appId");
String appSecret = env.getProperty("google.appSecret");
String redirectUri = env.getProperty("google.redirectUri");
String scope = env.getProperty("google.scope");
GoogleConnectionFactory factory = new GoogleConnectionFactory(appId, appSecret);
GooglePlusService gPlusService = new GooglePlusService(factory);
gPlusService.setRedirectUri(redirectUri);
gPlusService.setScope(scope);
gPlusService.setState(RandomStringUtils.randomAlphanumeric(20));
return gPlusService;
}
@Bean
public MervidService mervidService() {
String appId = env.getProperty("mervid.appId");
String appSecret = env.getProperty("mervid.appSecret");
String redirectUri = env.getProperty("mervid.redirectUri");
String scope = env.getProperty("mervid.scope");
MervidConnectionFactory factory = new MervidConnectionFactory(appId, appSecret);
MervidService mervidService = new MervidService(factory);
mervidService.setRedirectUri(redirectUri);
mervidService.setScope(scope);
mervidService.setState(RandomStringUtils.randomAlphanumeric(20));
return mervidService;
}
@Bean
public LinkedInService linkedInService() {
String appId = env.getProperty("linkedin.appId");
String appSecret = env.getProperty("linkedin.appSecret");
String redirectUri = env.getProperty("linkedin.redirectUri");
String scope = env.getProperty("linkedin.scope");
LinkedInConnectionFactory factory = new LinkedInConnectionFactory(appId, appSecret);
LinkedInService linkedInService = new LinkedInService(factory);
linkedInService.setRedirectUri(redirectUri);
linkedInService.setScope(scope);
linkedInService.setState(RandomStringUtils.randomAlphanumeric(20));
return linkedInService;
}
@Bean
public GithubService githubService() {
String appId = env.getProperty("github.appId");
String appSecret = env.getProperty("github.appSecret");
String redirectUri = env.getProperty("github.redirectUri");
String scope = env.getProperty("github.scope");
GitHubConnectionFactory factory = new GitHubConnectionFactory(appId, appSecret);
GithubService githubService = new GithubService(factory);
githubService.setRedirectUri(redirectUri);
githubService.setState(RandomStringUtils.randomAlphanumeric(20));
return githubService;
}
@Override
public void setEnvironment(Environment env) {
this.env = new RelaxedPropertyResolver(env, "social.");
}
}
| 38.970238 | 110 | 0.803574 |
ef33f5cbf50916224831d865dccdebe3ac7e92cb | 1,244 | package com.dyvak.crm.controller;
import com.dyvak.crm.aspects.Benchmark;
import com.dyvak.crm.aspects.LoggedArgs;
import com.dyvak.crm.aspects.LoggedReturn;
import com.dyvak.crm.domain.User;
import com.dyvak.crm.security.UserRole;
import com.dyvak.crm.service.UserService;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api")
@AllArgsConstructor
public class UserController {
private UserService userService;
@LoggedArgs
@LoggedReturn
@Benchmark
@RequestMapping(path = "/user", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public @ResponseBody
long addNewUser(@RequestParam String email, @RequestParam String password) {
User user = User.builder()
.email(email)
.password(password)
.role(UserRole.USER)
.build();
userService.createUser(user);
return user.getId();
}
@LoggedArgs
@LoggedReturn
@Benchmark
@GetMapping(path = "/user/{id}")
public @ResponseBody
User getUserById(@PathVariable("id") long id) {
return userService.findById(id);
}
}
| 27.043478 | 80 | 0.69373 |
b09b3011b4079b3c3bee8cc445399e9d10fa8bd7 | 5,116 | /*
* Copyright 2018 Lake Zhang
*
* 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.smailnet.eamil;
import android.app.Activity;
import com.smailnet.eamil.Callback.GetSendCallback;
import com.smailnet.eamil.Utils.AddressUtil;
import java.io.UnsupportedEncodingException;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeUtility;
/**
* Email for Android是基于JavaMail封装的电子邮件库,简化在Android客户端中编写
* 发送电子邮件的的代码。把它集成到你的Android项目中,只需简单配置邮件服务器,即
* 可使用,所见即所得哦!
*
* @author 张观湖
* @author E-mail: zguanhu@foxmail.com
* @version 2.3
*/
public class EmailSendClient {
private String nickname;
private String subject;
private String text;
private Object content;
private Address[] to;
private Address[] cc;
private Address[] bcc;
private EmailConfig emailConfig;
public EmailSendClient(EmailConfig emailConfig){
this.emailConfig = emailConfig;
}
/**
* 设置收件人的邮箱地址(该方法将在2.3版本上弃用)
* @param to
* @return
*/
@Deprecated
public EmailSendClient setReceiver(String to){
this.to = AddressUtil.getInternetAddress(to);
return this;
}
/**
* 设置发件人的昵称
* @param nickname
* @return
*/
public EmailSendClient setNickname(String nickname){
try {
this.nickname = MimeUtility.encodeText(nickname);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return this;
}
/**
* 设置收件人的邮箱地址
* @param to
* @return
*/
public EmailSendClient setTo(String to){
this.to = AddressUtil.getInternetAddress(to);
return this;
}
/**
* 设置抄送人的邮箱地址
* @param cc
* @return
*/
public EmailSendClient setCc(String cc){
this.cc = AddressUtil.getInternetAddress(cc);
return this;
}
/**
* 设置密送人的邮箱地址
* @param bcc
* @return
*/
public EmailSendClient setBcc(String bcc){
this.bcc = AddressUtil.getInternetAddress(bcc);
return this;
}
/**
* 设置邮件标题
* @param subject
* @return
*/
public EmailSendClient setSubject(String subject){
this.subject = subject;
return this;
}
/**
* 设置邮件内容(纯文本)
* @param text
* @return
*/
public EmailSendClient setText(String text){
this.text = text;
return this;
}
/**
* 设置邮件内容(HTML)
* @param content
* @return
*/
public EmailSendClient setContent(Object content){
this.content = content;
return this;
}
/**
* 异步发送邮件,发送完毕回调并切回到主线程
* @param activity
* @param getSendCallback
* @return
*/
public void sendAsyn(final Activity activity, final GetSendCallback getSendCallback){
new Thread(new Runnable() {
@Override
public void run() {
try {
Operator.Core(emailConfig)
.setMessage(nickname, to, cc, bcc, subject, text, content)
.sendMail();
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
getSendCallback.sendSuccess();
}
});
} catch (final MessagingException e) {
e.printStackTrace();
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
getSendCallback.sendFailure(e.toString());
}
});
}
}
}).start();
}
/**
* 异步发送邮件,发送完毕回调不切回到主线程
* @param getSendCallback
* @return
*/
public void sendAsyn(final GetSendCallback getSendCallback){
new Thread(new Runnable() {
@Override
public void run() {
try {
Operator.Core(emailConfig)
.setMessage(nickname, to, cc, bcc, subject, text, content)
.sendMail();
getSendCallback.sendSuccess();
} catch (final MessagingException e) {
e.printStackTrace();
getSendCallback.sendFailure(e.toString());
}
}
}).start();
}
}
| 25.969543 | 89 | 0.56509 |
537bc5a63f500e28cb1ab7af14e23f2bbd61aff8 | 764 | package ru.hixon.springredisclustertestcontainers;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Optional;
class NumberServiceTests extends AbstractIntegrationTest {
@Autowired
private NumberService numberService;
@Test
void intTests() {
Assertions.assertTrue(numberService.get(42).isEmpty());
for (int i = 1; i < 100; i++) {
numberService.multiplyAndSave(i);
}
for (int i = 1; i < 100; i++) {
Optional<Integer> result = numberService.get(i);
Assertions.assertTrue(result.isPresent());
Assertions.assertEquals(2 * i, result.get());
}
}
}
| 25.466667 | 63 | 0.657068 |
cebc0136f8b5cad8ce7538692d93f2ef8d1bf059 | 794 | package br.sprintdev.model.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import br.sprintdev.model.dao.TaskDao;
import br.sprintdev.model.entity.Task;
@Service @Transactional(readOnly = false)
public class TaskServiceImpl implements TaskService {
@Autowired
private TaskDao dao;
@Override
public void create(Task task) {
dao.save(task);
}
@Override
public void update(Task task) {
dao.update(task);
}
@Override
public void delete(Long id) {
dao.delete(id);
}
@Override
public Task findById(Long id) {
return dao.findById(id);
}
@Override
public List<Task> findAll() {
return dao.findAll();
}
}
| 18.045455 | 64 | 0.751889 |
b060b49c13bb2fa2e0729eba90e337eaa62f6cb2 | 20,598 | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.zookeeper;
import com.google.common.base.Preconditions;
import com.google.common.collect.Sets;
import com.webank.ai.fate.register.annotions.RegisterService;
import com.webank.ai.fate.register.common.*;
import com.webank.ai.fate.register.interfaces.NotifyListener;
import com.webank.ai.fate.register.url.CollectionUtils;
import com.webank.ai.fate.register.url.URL;
import com.webank.ai.fate.register.url.UrlUtils;
import com.webank.ai.fate.register.utils.NetUtils;
import com.webank.ai.fate.register.utils.StringUtils;
import com.webank.ai.fate.register.utils.URLBuilder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import static com.webank.ai.fate.register.common.Constants.*;
import static org.apache.curator.utils.ZKPaths.PATH_SEPARATOR;
public class ZookeeperRegistry extends FailbackRegistry {
private static final Logger logger = LogManager.getLogger();
private final static int DEFAULT_ZOOKEEPER_PORT = 2181;
private final static String DEFAULT_ROOT = "FATE-SERVICES";
private final static String ROOT_KEY = "root";
public static ConcurrentMap<URL, ZookeeperRegistry> registeryMap = new ConcurrentHashMap();
private final String root;
private final ConcurrentMap<URL, ConcurrentMap<NotifyListener, ChildListener>> zkListeners = new ConcurrentHashMap<>();
;
private final ZookeeperClient zkClient;
Set<String> registedString = Sets.newHashSet();
String DYNAMIC_KEY = "dynamic";
Set<String> anyServices = new HashSet<String>();
private String environment;
private Set<String> dynamicEnvironments = new HashSet<String>();
private String project;
private int port;
public ZookeeperRegistry(URL url, ZookeeperTransporter zookeeperTransporter) {
super(url);
//
String group = url.getParameter(ROOT_KEY, DEFAULT_ROOT);
if (!group.startsWith(PATH_SEPARATOR)) {
group = PATH_SEPARATOR + group;
}
this.environment = url.getParameter(ENVIRONMENT_KEY, "online");
project = url.getParameter(PROJECT_KEY);
port = url.getParameter(SERVER_PORT) != null ? new Integer(url.getParameter(SERVER_PORT)) : 0;
this.root = group;
zkClient = zookeeperTransporter.connect(url);
zkClient.addStateListener(state -> {
if (state == StateListener.RECONNECTED) {
logger.error("state listenner reconnected");
try {
recover();
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
});
}
public static synchronized ZookeeperRegistry getRegistery(String url, String project, String environment, int port) {
if (url == null) {
return null;
}
URL registryUrl = URL.valueOf(url);
registryUrl = registryUrl.addParameter(Constants.ENVIRONMENT_KEY, environment);
registryUrl = registryUrl.addParameter(Constants.SERVER_PORT, port);
registryUrl = registryUrl.addParameter(Constants.PROJECT_KEY, project);
List<URL> backups = registryUrl.getBackupUrls();
if (registeryMap.get(registryUrl) == null) {
URL finalRegistryUrl = registryUrl;
registeryMap.computeIfAbsent(registryUrl, n -> {
CuratorZookeeperTransporter curatorZookeeperTransporter = new CuratorZookeeperTransporter();
ZookeeperRegistryFactory zookeeperRegistryFactory = new ZookeeperRegistryFactory();
zookeeperRegistryFactory.setZookeeperTransporter(curatorZookeeperTransporter);
ZookeeperRegistry zookeeperRegistry = (ZookeeperRegistry) zookeeperRegistryFactory.createRegistry(finalRegistryUrl);
return zookeeperRegistry;
});
}
return registeryMap.get(registryUrl);
}
@Override
public void doSubProject(String project) {
String path = root + Constants.PATH_SEPARATOR + project;
List<String> environments = zkClient.addChildListener(path, (parent, childrens) -> {
if (StringUtils.isNotEmpty(parent)) {
logger.info("fire environments changes {}", childrens);
subEnvironments(path, project, childrens);
}
});
logger.info("environments {}", environments);
if (environments == null) {
logger.info("environment is null,maybe zk is not started");
throw new RuntimeException("environment is null");
}
subEnvironments(path, project, environments);
}
private void subEnvironments(String path, String project, List<String> environments) {
if (environments != null) {
for (String environment : environments) {
String tempPath = path + Constants.PATH_SEPARATOR + environment;
List<String> services = zkClient.addChildListener(tempPath, (parent, childrens) -> {
if (StringUtils.isNotEmpty(parent)) {
logger.info("fire services changes {}", childrens);
subServices(project, environment, childrens);
}
});
subServices(project, environment, services);
}
}
}
private void subServices(String project, String environment, List<String> services) {
if (services != null) {
for (String service : services) {
String subString = project + Constants.PATH_SEPARATOR + environment + Constants.PATH_SEPARATOR + service;
logger.info("subServices sub {}", subString);
subscribe(URL.valueOf(subString), urls -> {
logger.info("change services urls =" + urls);
});
}
}
}
private String parseRegisterService(RegisterService registerService) {
String serviceName = registerService.serviceName();
String version = registerService.version();
String param = "?";
RouterModel routerModel = registerService.routerModel();
param = param + Constants.ROUTER_MODEL + "=" + routerModel.name();
param = param + "&";
param = param + Constants.TIMESTAMP_KEY + "=" + System.currentTimeMillis();
String key = serviceName;
boolean appendParam = false;
if (StringUtils.isNotEmpty(version)) {
param = param + "&" + Constants.VERSION + "=" + version;
}
if (this.getServieWeightMap().containsKey(serviceName + ".weight")) {
int weight = this.getServieWeightMap().get(serviceName + ".weight");
param = param + "&" + Constants.WEIGHT_KEY + "=" + weight;
}
key = key + param;
return key;
}
public synchronized void register(Set<RegisterService> sets) {
String hostAddress = NetUtils.getLocalIp();
Preconditions.checkArgument(port != 0);
Preconditions.checkArgument(StringUtils.isNotEmpty(environment));
Set<URL> registered = this.getRegistered();
for (RegisterService service : sets) {
URL serviceUrl = URL.valueOf("grpc://" + hostAddress + ":" + port + Constants.PATH_SEPARATOR + parseRegisterService(service));
if (service.useDynamicEnvironment()) {
if (CollectionUtils.isNotEmpty(dynamicEnvironments)) {
dynamicEnvironments.forEach(environment -> {
URL newServiceUrl = serviceUrl.setEnvironment(environment);
String serviceName = service.serviceName() + environment;
if (!registedString.contains(serviceName)) {
this.register(newServiceUrl);
this.registedString.add(serviceName);
} else {
logger.info("url {} is already registed,will not do anything ", newServiceUrl);
}
});
}
} else {
if (!registedString.contains(service.serviceName())) {
this.register(serviceUrl);
this.registedString.add(service.serviceName());
}
}
}
logger.info("registed urls {}", registered);
}
public void addDynamicEnvironment(String environment) {
dynamicEnvironments.add(environment);
}
@Override
public boolean isAvailable() {
return zkClient.isConnected();
}
@Override
public void destroy() {
super.destroy();
try {
zkClient.close();
} catch (Exception e) {
logger.warn("Failed to close zookeeper client " + getUrl() + ", cause: " + e.getMessage(), e);
}
}
@Override
public void doRegister(URL url) {
try {
String urlPath = toUrlPath(url);
logger.info("create urlpath {} ", urlPath);
zkClient.create(urlPath, true);
} catch (Throwable e) {
throw new RuntimeException("Failed to register " + url + " to zookeeper " + getUrl() + ", cause: " + e.getMessage(), e);
}
}
@Override
public void doUnregister(URL url) {
try {
zkClient.delete(toUrlPath(url));
} catch (Throwable e) {
throw new RuntimeException("Failed to unregister " + url + " to zookeeper " + getUrl() + ", cause: " + e.getMessage(), e);
}
}
@Override
public void doSubscribe(final URL url, final NotifyListener listener) {
try {
List<URL> urls = new ArrayList<>();
if (ANY_VALUE.equals(url.getEnvironment())) {
String root = toRootPath();
ConcurrentMap<NotifyListener, ChildListener> listeners = zkListeners.get(url);
if (listeners == null) {
zkListeners.putIfAbsent(url, new ConcurrentHashMap<>());
listeners = zkListeners.get(url);
}
ChildListener zkListener = listeners.get(listener);
if (zkListener == null) {
listeners.putIfAbsent(listener, (parentPath, currentChilds) -> {
if (parentPath.equals(Constants.PROVIDERS_CATEGORY)) {
for (String child : currentChilds) {
child = URL.decode(child);
if (!anyServices.contains(child)) {
anyServices.add(child);
subscribe(url.setPath(child).addParameters(INTERFACE_KEY, child,
Constants.CHECK_KEY, String.valueOf(false)), listener);
}
}
}
});
zkListener = listeners.get(listener);
}
String xx = root + "/" + url.getProject();
List<String> children = zkClient.addChildListener(xx, zkListener);
for (String environment : children) {
//URL childUrl = url.setEnvironment(environment);
//urls.add(childUrl);
xx = xx + "/" + environment;
List<String> interfaces = zkClient.addChildListener(xx, zkListener);
if (interfaces != null) {
for (String inter : interfaces) {
xx = xx + "/" + inter + "/" + Constants.PROVIDERS_CATEGORY;
List<String> services = zkClient.addChildListener(xx, zkListener);
if (services != null) {
urls.addAll(toUrlsWithEmpty(url, xx, services));
}
}
}
}
notify(url, listener, urls);
}
// if (ANY_VALUE.equals(url.getServiceInterface())) {
// String root = toRootPath();
// ConcurrentMap<NotifyListener, ChildListener> listeners = zkListeners.get(url);
// if (listeners == null) {
// zkListeners.putIfAbsent(url, new ConcurrentHashMap<>());
// listeners = zkListeners.get(url);
// }
// ChildListener zkListener = listeners.get(listener);
// if (zkListener == null) {
// listeners.putIfAbsent(listener, (parentPath, currentChilds) -> {
// for (String child : currentChilds) {
// child = URL.decode(child);
// if (!anyServices.contains(child)) {
// anyServices.add(child);
// subscribe(url.setPath(child).addParameters(INTERFACE_KEY, child,
// Constants.CHECK_KEY, String.valueOf(false)), listener);
// }
// }
// });
// zkListener = listeners.get(listener);
// }
// zkClient.create(root, false);
// List<String> services = zkClient.addChildListener(root, zkListener);
// if (CollectionUtils.isNotEmpty(services)) {
// for (String service : services) {
// service = URL.decode(service);
// anyServices.add(service);
// subscribe(url.setPath(service).addParameters(INTERFACE_KEY, service,
// Constants.CHECK_KEY, String.valueOf(false)), listener);
// }
// }
// }
else {
for (String path : toCategoriesPath(url)) {
ConcurrentMap<NotifyListener, ChildListener> listeners = zkListeners.get(url);
if (listeners == null) {
zkListeners.putIfAbsent(url, new ConcurrentHashMap<>());
listeners = zkListeners.get(url);
}
ChildListener zkListener = listeners.get(listener);
if (zkListener == null) {
listeners.putIfAbsent(listener, (parentPath, currentChilds) -> {
if (StringUtils.isNotEmpty(parentPath)) {
ZookeeperRegistry.this.notify(url, listener,
toUrlsWithEmpty(url, parentPath, currentChilds));
}
}
);
zkListener = listeners.get(listener);
}
zkClient.create(path, false);
List<String> children = zkClient.addChildListener(path, zkListener);
if (children != null) {
urls.addAll(toUrlsWithEmpty(url, path, children));
}
}
notify(url, listener, urls);
// }
}
} catch (Throwable e) {
throw new RuntimeException("Failed to subscribe " + url + " to zookeeper " + getUrl() + ", cause: " + e.getMessage(), e);
}
}
@Override
public void doUnsubscribe(URL url, NotifyListener listener) {
ConcurrentMap<NotifyListener, ChildListener> listeners = zkListeners.get(url);
if (listeners != null) {
ChildListener zkListener = listeners.get(listener);
if (zkListener != null) {
for (String path : toCategoriesPath(url)) {
zkClient.removeChildListener(path, zkListener);
}
}
}
}
@Override
public List<URL> lookup(URL url) {
if (url == null) {
throw new IllegalArgumentException("lookup url == null");
}
try {
List<String> providers = new ArrayList<>();
for (String path : toCategoriesPath(url)) {
List<String> children = zkClient.getChildren(path);
if (children != null) {
providers.addAll(children);
}
}
return toUrlsWithoutEmpty(url, providers);
} catch (Throwable e) {
throw new RuntimeException("Failed to lookup " + url + " from zookeeper " + getUrl() + ", cause: " + e.getMessage(), e);
}
}
private String toRootDir() {
if (root.equals(PATH_SEPARATOR)) {
return root;
}
return root + PATH_SEPARATOR;
}
private String toRootPath() {
return root;
}
private String toServicePath(URL url) {
String project = url.getProject() != null ? url.getProject() : this.project;
String environment = url.getEnvironment() != null ? url.getEnvironment() : this.environment;
String name = url.getServiceInterface();
if (ANY_VALUE.equals(name)) {
return toRootPath();
}
String result = toRootDir() + project + Constants.PATH_SEPARATOR + environment + Constants.PATH_SEPARATOR + URL.encode(name);
return result;
}
private String[] toCategoriesPath(URL url) {
String[] categories;
if (ANY_VALUE.equals(url.getParameter(CATEGORY_KEY))) {
categories = new String[]{PROVIDERS_CATEGORY, CONSUMERS_CATEGORY, ROUTERS_CATEGORY, CONFIGURATORS_CATEGORY};
} else {
categories = url.getParameter(CATEGORY_KEY, new String[]{DEFAULT_CATEGORY});
}
String[] paths = new String[categories.length];
for (int i = 0; i < categories.length; i++) {
paths[i] = toServicePath(url) + PATH_SEPARATOR + categories[i];
}
return paths;
}
private String toCategoryPath(URL url) {
String servicePath = toServicePath(url);
String category = url.getParameter(CATEGORY_KEY, DEFAULT_CATEGORY);
return servicePath + PATH_SEPARATOR + category;
}
private String toUrlPath(URL url) {
return toCategoryPath(url) + PATH_SEPARATOR + URL.encode(url.toFullString());
}
private List<URL> toUrlsWithoutEmpty(URL consumer, List<String> providers) {
List<URL> urls = new ArrayList<>();
if (CollectionUtils.isNotEmpty(providers)) {
for (String provider : providers) {
provider = URL.decode(provider);
if (provider.contains(PROTOCOL_SEPARATOR)) {
URL url;
// for jmx url
if (provider.startsWith(JMX_PROTOCOL_KEY)) {
url = URL.parseJMXServiceUrl(provider);
} else {
url = URL.valueOf(provider);
}
if (UrlUtils.isMatch(consumer, url)) {
urls.add(url);
}
}
}
}
return urls;
}
private List<URL> toUrlsWithEmpty(URL consumer, String path, List<String> providers) {
List<URL> urls = toUrlsWithoutEmpty(consumer, providers);
if (urls == null || urls.isEmpty()) {
int i = path.lastIndexOf(PATH_SEPARATOR);
String category = i < 0 ? path : path.substring(i + 1);
URL empty = URLBuilder.from(consumer)
.setProtocol(EMPTY_PROTOCOL)
.addParameter(CATEGORY_KEY, category)
.build();
urls.add(empty);
}
return urls;
}
}
| 38.645403 | 138 | 0.559181 |
6ef98cfa30de875422ec4036f3a04f56c3a69c11 | 2,344 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.syncope.sra.session;
import org.apache.syncope.sra.SessionConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.session.MapSession;
import org.springframework.session.ReactiveSessionRepository;
import reactor.core.publisher.Mono;
public class CacheManagerReactiveSessionRepository implements ReactiveSessionRepository<MapSession> {
@Autowired
private CacheManager cacheManager;
@Override
public Mono<MapSession> createSession() {
return Mono.just(new MapSession());
}
@Override
public Mono<Void> save(final MapSession session) {
return Mono.fromRunnable(() -> {
if (!session.getId().equals(session.getOriginalId())) {
cacheManager.getCache(SessionConfig.DEFAULT_CACHE).evictIfPresent(session.getOriginalId());
}
cacheManager.getCache(SessionConfig.DEFAULT_CACHE).put(session.getId(), session);
});
}
@Override
public Mono<MapSession> findById(final String id) {
return Mono.defer(() -> Mono.justOrEmpty(
cacheManager.getCache(SessionConfig.DEFAULT_CACHE).get(id, MapSession.class)).
map(MapSession::new).
switchIfEmpty(deleteById(id).then(Mono.empty())));
}
@Override
public Mono<Void> deleteById(final String id) {
return Mono.fromRunnable(() -> cacheManager.getCache(SessionConfig.DEFAULT_CACHE).evictIfPresent(id));
}
}
| 38.42623 | 110 | 0.720137 |
50e8635466ba1e0e3fa331fb413d876da4319235 | 511 | package it.cnr.istc.stlab.pss.harvester;
public class LocalDestination {
private String localPath;
public LocalDestination(String localPath) {
super();
this.localPath = localPath;
}
public String getLocalPath() {
return localPath;
}
public String getDownloadedFile() {
return localPath + "/downloaded.txt";
}
public String getResourcesImpossibleToDownload() {
return localPath + "/undownloadable.txt";
}
public String getUploadedFile() {
return localPath + "/uploaded.txt";
}
}
| 17.62069 | 51 | 0.726027 |
e8c3c198af2ea0415cf24de795442f8ae0d67456 | 89 | package org.zstack.sdk;
public enum MdevDeviceStatus {
Active,
Attached,
Reserved,
}
| 11.125 | 30 | 0.752809 |
9ea344f5167bb78dd17dd625e049584a84ac2041 | 2,315 | /*******************************************************************************
* Copyright 2014 IBM
*
* 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.ibm.hrl.proton.server.executorServices;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* <code>SimpleThreadFactory</code>.
*
*
*/
public class SimpleThreadFactory implements ThreadFactory
{
UncaughtExceptionHandler exceptionHandler;
private AtomicInteger threadNumber = new AtomicInteger(1);
private final static Logger logger = Logger.getLogger(SimpleThreadFactory.class.getName());
public SimpleThreadFactory()
{
exceptionHandler= new ProtonExceptionHandler(logger);
}
/* (non-Javadoc)
* @see java.util.concurrent.ThreadFactory#newThread(java.lang.Runnable)
*/
@Override
public Thread newThread(Runnable r)
{
Thread t = new Thread(r,""+threadNumber.getAndIncrement());
t.setUncaughtExceptionHandler(exceptionHandler);
return t;
}
private class ProtonExceptionHandler implements Thread.UncaughtExceptionHandler {
private Logger logger;
private ProtonExceptionHandler(Logger logger) {
this.logger = logger;
}
@Override
public void uncaughtException(Thread t, Throwable e) {
if (logger.isLoggable(Level.SEVERE)) {
logger.severe("Uncaught exception in thread: " + t + ",exception: "+e.getMessage());
}
e.printStackTrace();
}
}
}
| 30.866667 | 100 | 0.638013 |
26418d6308e7b7c719474d61cc64393e413bf3e0 | 434 | /*
* @test /nodynamiccopyright/
* @bug 7034511 7040883 7041019
* @summary Loophole in typesafety
* @compile/fail/ref=T7034511a.out -XDrawDiagnostics T7034511a.java
*/
class T7034511a {
interface A<T> {
void foo(T x);
}
interface B<T> extends A<T[]> { }
static abstract class C implements B<Integer> {
<T extends B<?>> void test(T x, String[] ss) {
x.foo(ss);
}
}
}
| 19.727273 | 67 | 0.582949 |
255a0da6e4dbae4a29034cb9c3f89832cbcc1828 | 1,135 | package com.egojit.cloud.common.base;
import com.egojit.cloud.common.utils.GuidUtils;
import org.apache.commons.lang3.StringUtils;
import javax.persistence.Id;
import java.util.Date;
import java.util.UUID;
/**
* 基础数据库对象,所有数据库对象必须继承
*
* @author 高露 QQ:408365330
* @date $date$
*/
public abstract class BaseDbEntity extends Entity {
/**
* id
*/
@Id
private String id;
/**
* 创建时间
*/
private Date createTime;
public BaseDbEntity() {
}
public BaseDbEntity(String id) {
this.setId(id);
}
/**
* 新增之前默认处理
*/
public void preInsert() {
if (StringUtils.isEmpty(this.getId())) {
this.setId(GuidUtils.guid());
}
//当前时间戳毫秒
this.createTime =new Date();
}
/**
* 新增之前默认处理
*/
public void preUpdate() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
}
| 15.985915 | 51 | 0.569163 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.